This is an automated email from the ASF dual-hosted git repository.

klesh pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/devlake.git


The following commit(s) were added to refs/heads/main by this push:
     new 3dad8cd52 fix(azuredevops_go): restore on-premises connection 
compatibility (#9386)
3dad8cd52 is described below

commit 3dad8cd52efb21c99796bc44e55806062b85d251
Author: kerem <[email protected]>
AuthorDate: Sat Nov 14 10:07:23 2026 +0300

    fix(azuredevops_go): restore on-premises connection compatibility (#9386)
    
    * fix(azuredevops_go): restore on-premises connection compatibility
    
    * fix(azuredevops_go): enhance error handling for remote repository 
retrieval and improve test coverage
---
 backend/plugins/azuredevops_go/README.md           |  64 ++++++-
 .../azuredevops_go/api/azuredevops/client.go       |  48 ++++--
 .../api/azuredevops/client_onprem_test.go          | 171 ++++++++++++++++++-
 .../plugins/azuredevops_go/api/connection_api.go   |   4 +-
 .../plugins/azuredevops_go/api/remote_helper.go    |  12 +-
 .../azuredevops_go/api/remote_helper_test.go       |  50 ++++++
 backend/plugins/azuredevops_go/impl/impl.go        |   3 +
 .../plugins/azuredevops_go/models/api_version.go   | 153 +++++++++++++++++
 .../azuredevops_go/models/connection_test.go       | 186 +++++++++++++++++++++
 .../tasks/ci_cd_timeline_records_collector.go      |   1 -
 backend/plugins/azuredevops_go/tasks/shared.go     |   2 +-
 .../plugins/azuredevops_go/tasks/shared_test.go    |  21 +++
 .../components/connection-form/fields/username.tsx |   8 +-
 config-ui/src/plugins/register/azure/config.tsx    |  21 ++-
 .../register/azure/connection-fields/base-url.tsx  |  26 ++-
 .../azure/connection-fields/connection.test.tsx    | 133 +++++++++++++++
 16 files changed, 865 insertions(+), 38 deletions(-)

diff --git a/backend/plugins/azuredevops_go/README.md 
b/backend/plugins/azuredevops_go/README.md
index 1ea487025..11e909920 100644
--- a/backend/plugins/azuredevops_go/README.md
+++ b/backend/plugins/azuredevops_go/README.md
@@ -15,10 +15,9 @@ See the License for the specific language governing 
permissions and
 limitations under the License.
 -->
 
-# Azure Devops Python Plugin
+# Azure DevOps Go Plugin
 
-This is a revamped version of the Python Azure DevOps Plugin, originally 
located at `../../python/plugins/azuredevops`.
-The plugin is able to coexist with the Python version as both implementations 
come with their own `_raw` and `_tool` tables.
+This plugin can coexist with the Python Azure DevOps plugin at 
`../../python/plugins/azuredevops`; the two implementations use separate `_raw` 
and `_tool` tables.
 
 **Read access** to the following Azure DevOps Scopes is required:
 
@@ -27,4 +26,61 @@ The plugin is able to coexist with the Python version as 
both implementations co
 - Graph (collectAccounts task)
 - Release
 
-Access to Service Connections has been removed as they usually contain 
sensitive security information.
\ No newline at end of file
+Discovering external repositories also requires permission to read Service 
Connections.
+Cloud Graph account collection is skipped for on-premises connections.
+Source-provider repository HTTP errors are logged with their status and up to
+4 KiB of response detail. A failing service connection is skipped so 
repositories
+from other service connections can still be discovered.
+
+## Azure DevOps Server (On-Premises)
+
+Select **Azure DevOps Server (On-Premises)** and enter the full collection URL
+(for example, `https://your-server/tfs/DefaultCollection/`). Username is 
optional
+when authenticating with a PAT. Editing a connection preserves its server URL.
+
+The Go plugin automatically probes REST API versions **7.2, 7.1, 7.0, and 6.0**
+in descending order when initializing an API client, including during **Test
+Connection**. Only HTTP 400 with `VssVersionNotSupportedException` or
+`VssVersionOutOfRangeException` triggers a lower version; authentication,
+permission, and connectivity failures are reported.
+The selected version is reused for scope discovery and collection requests made
+by that client. It is detected again for new clients, so changing the endpoint
+or upgrading the server requires no manual version setting or database 
migration.
+Servers must support REST API 6.0 or later (Azure DevOps Server 2020 or newer).
+Cloud connections retain their existing API versions.
+
+### Endpoint compatibility
+
+The server API family and the resource's preview revision are separate. 
Requests
+use the following versions from the Microsoft REST reference:
+
+| Endpoint | 6.0 | 7.0 | 7.1 | 7.2 |
+| --- | --- | --- | --- | --- |
+| Projects | 6.0 | 7.0 | 7.1 | 7.2-preview.4 |
+| Git repositories, commits, pull request list | 6.0 | 7.0 | 7.1 | 
7.2-preview.2 |
+| Pull request commits | 6.0 | 7.0 | 7.1 | 7.2-preview.1 |
+| Builds | 6.0 | 7.0 | 7.1 | 7.2-preview.8 |
+| Build timeline | 6.0 | 7.0 | 7.1 | 7.2-preview.3 |
+| Service endpoints | 6.0-preview.4 | 7.0 | 7.1 | 7.2-preview.4 |
+| Source provider repositories | 6.0-preview.1 | 7.0 | 7.1 | 7.2-preview.1 |
+
+On-premises requests are relative to the collection URL, without a Cloud
+organization prefix. Previously saved organization-prefixed scope IDs are
+normalized to project-only parent IDs and empty organization IDs during
+on-premises discovery. Cloud scope IDs retain their organization prefix.
+External repository discovery follows the response body's `continuationToken`.
+The timeline API is not paginated; pull request commits use continuation 
tokens,
+not `$skip`.
+
+REST 6.0 and 7.0 do not support the pull request `minTime`, `maxTime`, or
+`queryTimeRangeType` search filters. Those parameters are omitted on these
+servers, and all pull request pages are collected instead. This preserves data
+collection but can take longer than the server-side date filtering used with
+7.1 and 7.2. Build date filters remain supported on all four versions.
+
+References: [6.0 service 
endpoints](https://learn.microsoft.com/en-us/rest/api/azure/devops/serviceendpoint/endpoints/get-service-endpoints?view=azure-devops-rest-6.0),
+[7.2 
projects](https://learn.microsoft.com/en-us/rest/api/azure/devops/core/projects/list?view=azure-devops-rest-7.2),
+[7.2 
builds](https://learn.microsoft.com/en-us/rest/api/azure/devops/build/builds/list?view=azure-devops-rest-7.2),
+[7.0 pull 
requests](https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull-requests/get-pull-requests?view=azure-devops-rest-7.0),
+[7.1 pull 
requests](https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pull-requests/get-pull-requests?view=azure-devops-rest-7.1),
+and [source provider 
pagination](https://learn.microsoft.com/en-us/rest/api/azure/devops/build/source-providers/list-repositories?view=azure-devops-rest-6.0).
\ No newline at end of file
diff --git a/backend/plugins/azuredevops_go/api/azuredevops/client.go 
b/backend/plugins/azuredevops_go/api/azuredevops/client.go
index 355f5b997..e090b2466 100644
--- a/backend/plugins/azuredevops_go/api/azuredevops/client.go
+++ b/backend/plugins/azuredevops_go/api/azuredevops/client.go
@@ -33,7 +33,7 @@ import (
        "github.com/apache/devlake/plugins/azuredevops_go/models"
 )
 
-const apiVersion = "7.1"
+const apiVersion = models.DefaultAPIVersion
 const maxPageSize = 100
 
 type Client struct {
@@ -164,8 +164,8 @@ func (c *Client) GetProjects(args GetProjectsArgs) 
([]Project, errors.Error) {
                query.Set("$skip", strconv.Itoa(skip))
 
                path := "_apis/projects"
-               if args.OrgId != "" {
-                       path = fmt.Sprintf("%s/_apis/projects", args.OrgId)
+               if args.OrgId != "" && (c.connection == nil || 
c.connection.Endpoint == "") {
+                       path = fmt.Sprintf("%s/_apis/projects", 
url.PathEscape(args.OrgId))
                }
                res, err := c.apiClient.Get(path, query, nil)
                if err != nil {
@@ -200,6 +200,13 @@ type GetRepositoriesArgs struct {
        ProjectId string
 }
 
+func (c *Client) projectPath(org, project string) string {
+       if org == "" || (c.connection != nil && c.connection.Endpoint != "") {
+               return url.PathEscape(project)
+       }
+       return url.PathEscape(org) + "/" + url.PathEscape(project)
+}
+
 func (c *Client) GetRepositories(args GetRepositoriesArgs) ([]Repository, 
errors.Error) {
        query := url.Values{}
        query.Set("api-version", apiVersion)
@@ -208,10 +215,7 @@ func (c *Client) GetRepositories(args GetRepositoriesArgs) 
([]Repository, errors
                Repos []Repository `json:"value"`
        }
 
-       path := fmt.Sprintf("%s/%s/_apis/git/repositories", args.OrgId, 
args.ProjectId)
-       if args.OrgId == "" {
-               path = fmt.Sprintf("%s/_apis/git/repositories", args.ProjectId)
-       }
+       path := fmt.Sprintf("%s/_apis/git/repositories", 
c.projectPath(args.OrgId, args.ProjectId))
        res, err := c.apiClient.Get(path, query, nil)
        if err != nil {
                return nil, err
@@ -244,7 +248,7 @@ func (c *Client) GetServiceEndpoints(args 
GetServiceEndpointsArgs) ([]ServiceEnd
        query := url.Values{}
        query.Set("api-version", apiVersion)
 
-       path := fmt.Sprintf("%s/%s/_apis/serviceendpoint/endpoints/", 
args.OrgId, args.ProjectId)
+       path := fmt.Sprintf("%s/_apis/serviceendpoint/endpoints/", 
c.projectPath(args.OrgId, args.ProjectId))
        res, err := c.apiClient.Get(path, query, nil)
        if err != nil {
                return nil, err
@@ -282,28 +286,44 @@ type GetRemoteRepositoriesArgs struct {
 func (c *Client) GetRemoteRepositories(args GetRemoteRepositoriesArgs) 
([]RemoteRepository, error) {
        query := url.Values{}
        query.Set("api-version", apiVersion)
+       query.Set("pageResults", "true")
        if args.ServiceEndpoint != "" {
                query.Set("serviceEndpointId", args.ServiceEndpoint)
        }
 
        var repos []RemoteRepository
-       var response struct {
-               Repository []RemoteRepository `json:"repositories"`
-       }
-
        for {
-               path := 
fmt.Sprintf("%s/%s/_apis/sourceProviders/%s/repositories/", args.OrgId, 
args.ProjectId, args.Provider)
+               var response struct {
+                       Repository        []RemoteRepository 
`json:"repositories"`
+                       ContinuationToken string             
`json:"continuationToken"`
+               }
+               path := 
fmt.Sprintf("%s/_apis/sourceProviders/%s/repositories/", 
c.projectPath(args.OrgId, args.ProjectId), url.PathEscape(args.Provider))
                res, err := c.apiClient.Get(path, query, nil)
                if err != nil {
                        return nil, errors.Internal.Wrap(err, "failed to read 
remote repositories")
                }
+               if res.StatusCode != http.StatusOK {
+                       body, readErr := io.ReadAll(io.LimitReader(res.Body, 
4096))
+                       res.Body.Close()
+                       message := fmt.Sprintf("failed to read remote 
repositories, upstream api call failed with (%v)", res.StatusCode)
+                       if detail := strings.TrimSpace(string(body)); detail != 
"" {
+                               message += ": " + detail
+                       }
+                       if readErr != nil {
+                               return nil, errors.Internal.Wrap(readErr, 
message)
+                       }
+                       return nil, errors.Internal.New(message)
+               }
                err = api.UnmarshalResponse(res, &response)
                if err != nil {
                        return nil, errors.Internal.Wrap(err, "failed to 
unmarshal remote repositories response")
                }
 
                repos = append(repos, response.Repository...)
-               contToken := res.Header.Get("X-Ms-Continuationtoken")
+               contToken := response.ContinuationToken
+               if contToken == "" {
+                       contToken = res.Header.Get("X-Ms-Continuationtoken")
+               }
                if contToken == "" {
                        return repos, nil
                }
diff --git 
a/backend/plugins/azuredevops_go/api/azuredevops/client_onprem_test.go 
b/backend/plugins/azuredevops_go/api/azuredevops/client_onprem_test.go
index 4753d19e4..9b689699e 100644
--- a/backend/plugins/azuredevops_go/api/azuredevops/client_onprem_test.go
+++ b/backend/plugins/azuredevops_go/api/azuredevops/client_onprem_test.go
@@ -18,11 +18,180 @@ limitations under the License.
 package azuredevops
 
 import (
+       "errors"
+       "fmt"
+       "io"
+       "net/http"
+       "net/http/httptest"
+       "strconv"
+       "strings"
+       "testing"
+
        "github.com/apache/devlake/helpers/pluginhelper/api"
        "github.com/apache/devlake/plugins/azuredevops_go/models"
-       "testing"
 )
 
+func TestOnPremisesScopeRequestsAcrossVersions(t *testing.T) {
+       for _, tc := range []struct {
+               version  string
+               projects string
+               repos    string
+               service  string
+               source   string
+       }{
+               {"6.0", "6.0", "6.0", "6.0-preview.4", "6.0-preview.1"},
+               {"7.0", "7.0", "7.0", "7.0", "7.0"},
+               {"7.1", "7.1", "7.1", "7.1", "7.1"},
+               {"7.2", "7.2-preview.4", "7.2-preview.2", "7.2-preview.4", 
"7.2-preview.1"},
+       } {
+               t.Run(tc.version, func(t *testing.T) {
+                       sourcePages := 0
+                       server := httptest.NewServer(http.HandlerFunc(func(w 
http.ResponseWriter, r *http.Request) {
+                               path := strings.TrimPrefix(r.URL.Path, 
"/tfs/DefaultCollection/")
+                               query := r.URL.Query()
+                               version := query.Get("api-version")
+                               if user, token, ok := r.BasicAuth(); !ok || 
user != "" || token != "test-token" {
+                                       t.Error("expected authenticated 
on-premises request")
+                               }
+                               if path == "_apis/projects" && 
query.Get("$top") == "1" && version != tc.projects {
+                                       w.WriteHeader(http.StatusBadRequest)
+                                       fmt.Fprint(w, 
`{"typeKey":"VssVersionNotSupportedException"}`)
+                                       return
+                               }
+                               switch path {
+                               case "_apis/projects":
+                                       if version != tc.projects {
+                                               t.Errorf("project API version = 
%s; want %s", version, tc.projects)
+                                       }
+                                       fmt.Fprint(w, 
`{"count":1,"value":[{"id":"project","name":"Project One"}]}`)
+                               case "Project One/_apis/git/repositories":
+                                       if version != tc.repos {
+                                               t.Errorf("repository API 
version = %s; want %s", version, tc.repos)
+                                       }
+                                       fmt.Fprint(w, 
`{"value":[{"id":"repo","name":"repo"}]}`)
+                               case "Project 
One/_apis/serviceendpoint/endpoints/":
+                                       if version != tc.service {
+                                               t.Errorf("service endpoint API 
version = %s; want %s", version, tc.service)
+                                       }
+                                       fmt.Fprint(w, 
`{"value":[{"id":"endpoint","type":"github"}]}`)
+                               case "Project 
One/_apis/sourceProviders/github/repositories/":
+                                       sourcePages++
+                                       if version != tc.source || 
query.Get("serviceEndpointId") != "endpoint" || query.Get("pageResults") != 
"true" {
+                                               t.Errorf("unexpected source 
provider query: %v", query)
+                                       }
+                                       if sourcePages == 1 {
+                                               if 
query.Get("continuationToken") != "" {
+                                                       t.Error("first page 
must not have a continuation token")
+                                               }
+                                               fmt.Fprint(w, 
`{"repositories":[{"id":"first"}],"continuationToken":"next-page"}`)
+                                       } else {
+                                               if sourcePages != 2 || 
query.Get("continuationToken") != "next-page" {
+                                                       t.Errorf("unexpected 
continuation request: page %d, query %v", sourcePages, query)
+                                                       
w.WriteHeader(http.StatusBadRequest)
+                                                       return
+                                               }
+                                               fmt.Fprint(w, 
`{"repositories":[{"id":"second"}]}`)
+                                       }
+                               default:
+                                       t.Errorf("unexpected on-premises URL: 
%s", r.URL)
+                                       w.WriteHeader(http.StatusNotFound)
+                               }
+                       }))
+                       defer server.Close()
+                       conn := &models.AzuredevopsConnection{AzuredevopsConn: 
models.AzuredevopsConn{
+                               Endpoint: server.URL + 
"/tfs/DefaultCollection", Organization: "cloud-org",
+                               AzuredevopsAccessToken: 
models.AzuredevopsAccessToken{Token: "test-token"},
+                       }}
+                       apiClient := &api.ApiClient{}
+                       apiClient.Setup(conn.GetEndpoint(), nil, 0)
+                       if err := conn.PrepareApiClient(apiClient); err != nil {
+                               t.Fatal(err)
+                       }
+                       apiClient.SetAuthFunction(conn.SetupAuthentication)
+                       client := NewClient(conn, apiClient, conn.GetEndpoint())
+                       projects, err := 
client.GetProjects(GetProjectsArgs{OrgId: "cloud-org"})
+                       if err != nil || len(projects) != 1 {
+                               t.Fatalf("projects = %v, error = %v", projects, 
err)
+                       }
+                       repos, err := 
client.GetRepositories(GetRepositoriesArgs{OrgId: "cloud-org", ProjectId: 
"Project One"})
+                       if err != nil || len(repos) != 1 {
+                               t.Fatalf("repositories = %v, error = %v", 
repos, err)
+                       }
+                       endpoints, err := 
client.GetServiceEndpoints(GetServiceEndpointsArgs{OrgId: "cloud-org", 
ProjectId: "Project One"})
+                       if err != nil || len(endpoints) != 1 {
+                               t.Fatalf("service endpoints = %v, error = %v", 
endpoints, err)
+                       }
+                       remote, remoteErr := 
client.GetRemoteRepositories(GetRemoteRepositoriesArgs{
+                               OrgId: "cloud-org", ProjectId: "Project One", 
Provider: "github", ServiceEndpoint: "endpoint",
+                       })
+                       if remoteErr != nil || len(remote) != 2 || sourcePages 
!= 2 {
+                               t.Fatalf("remote repositories = %v, pages = %d, 
error = %v", remote, sourcePages, remoteErr)
+                       }
+               })
+       }
+}
+
+func TestGetRemoteRepositoriesRejectsUpstreamError(t *testing.T) {
+       for _, tc := range []struct {
+               name           string
+               status         int
+               body           string
+               wantDetail     string
+               excludedDetail string
+               incomplete     bool
+       }{
+               {
+                       name: "JSON error", status: http.StatusBadRequest,
+                       body: `{"message":"API version not supported"}`, 
wantDetail: "API version not supported",
+               },
+               {
+                       name: "plain text error", status: http.StatusForbidden,
+                       body: "Missing repository read permission", wantDetail: 
"Missing repository read permission",
+               },
+               {
+                       name: "bounded error body", status: 
http.StatusBadGateway,
+                       body: strings.Repeat("x", 4096) + 
"discarded-error-tail", wantDetail: strings.Repeat("x", 4096),
+                       excludedDetail: "discarded-error-tail",
+               },
+               {
+                       name: "empty error body", status: 
http.StatusInternalServerError,
+               },
+               {
+                       name: "incomplete error body", status: 
http.StatusBadGateway,
+                       body: "Upstream response interrupted", wantDetail: 
"Upstream response interrupted", incomplete: true,
+               },
+       } {
+               t.Run(tc.name, func(t *testing.T) {
+                       server := httptest.NewServer(http.HandlerFunc(func(w 
http.ResponseWriter, r *http.Request) {
+                               if tc.incomplete {
+                                       w.Header().Set("Content-Length", 
strconv.Itoa(len(tc.body)+1))
+                               }
+                               w.WriteHeader(tc.status)
+                               fmt.Fprint(w, tc.body)
+                       }))
+                       defer server.Close()
+                       apiClient := &api.ApiClient{}
+                       apiClient.Setup(server.URL, nil, 0)
+                       client := NewClient(&models.AzuredevopsConnection{}, 
apiClient, server.URL)
+                       repos, err := 
client.GetRemoteRepositories(GetRemoteRepositoriesArgs{
+                               OrgId: "org", ProjectId: "project", Provider: 
"github",
+                       })
+                       if err == nil || len(repos) != 0 {
+                               t.Fatalf("expected upstream error, got 
repositories = %v, error = %v", repos, err)
+                       }
+                       if !strings.Contains(err.Error(), fmt.Sprintf("(%d)", 
tc.status)) || !strings.Contains(err.Error(), tc.wantDetail) {
+                               t.Errorf("error = %v; want HTTP %d and upstream 
detail %q", err, tc.status, tc.wantDetail)
+                       }
+                       if tc.excludedDetail != "" && 
strings.Contains(err.Error(), tc.excludedDetail) {
+                               t.Errorf("error includes response body beyond 
the 4 KiB limit: %v", err)
+                       }
+                       if tc.incomplete && !errors.Is(err, 
io.ErrUnexpectedEOF) {
+                               t.Errorf("error = %v; want wrapped response 
read failure", err)
+                       }
+               })
+       }
+}
+
 func TestGetUserProfile_OnPremises(t *testing.T) {
        conn := &models.AzuredevopsConnection{
                BaseConnection: api.BaseConnection{},
diff --git a/backend/plugins/azuredevops_go/api/connection_api.go 
b/backend/plugins/azuredevops_go/api/connection_api.go
index 4f1d70841..009300b1c 100644
--- a/backend/plugins/azuredevops_go/api/connection_api.go
+++ b/backend/plugins/azuredevops_go/api/connection_api.go
@@ -165,9 +165,7 @@ func testConnection(ctx context.Context, connection 
models.AzuredevopsConnection
                }
                _, err = vsc.GetProjects(args)
                if err != nil {
-                       // On-Premises Azure DevOps Server HTTP endpoints may 
use Windows NTLM Auth (which Git CLI succeeds with).
-                       // If GetProjects returns 401/Unauthorized, log a 
warning but allow connection test to succeed.
-                       basicRes.GetLogger().Warn(err, "GetProjects returned 
error for On-Premises connection, proceeding with connection setup")
+                       return nil, errors.BadInput.Wrap(err, "Failed to fetch 
projects from Azure DevOps Server")
                }
        } else {
                // Cloud: Azure DevOps Cloud test logic
diff --git a/backend/plugins/azuredevops_go/api/remote_helper.go 
b/backend/plugins/azuredevops_go/api/remote_helper.go
index 4b9ea78e2..b7d0016c1 100644
--- a/backend/plugins/azuredevops_go/api/remote_helper.go
+++ b/backend/plugins/azuredevops_go/api/remote_helper.go
@@ -60,6 +60,9 @@ func listAzuredevopsRemoteScopes(
 ) {
 
        org := connection.Organization
+       if connection.Endpoint != "" {
+               org = ""
+       }
        // Use the connection endpoint for On-Premises, or VSSPS for Cloud
        clientUrl := "https://app.vssps.visualstudio.com";
        if connection.Endpoint != "" {
@@ -77,9 +80,11 @@ func listAzuredevopsRemoteScopes(
        if len(id) > 1 {
                projectId = id[1]
        } else if connection.Endpoint != "" {
-               orgId = ""
                projectId = id[0]
        }
+       if connection.Endpoint != "" {
+               orgId = ""
+       }
 
        if projectId != "" {
                if remote, listErr := listRemoteRepos(vsc, orgId, projectId); 
listErr == nil {
@@ -260,7 +265,10 @@ func listRemoteRepos(
        _ = g.Wait()
 
        for _, v := range remoteRepos {
-               pID := orgId + idSeparator + projectId
+               pID := projectId
+               if orgId != "" {
+                       pID = orgId + idSeparator + projectId
+               }
                isFork, _ := strconv.ParseBool(v.Properties.IsFork)
                isPrivate, _ := strconv.ParseBool(v.Properties.IsPrivate)
 
diff --git a/backend/plugins/azuredevops_go/api/remote_helper_test.go 
b/backend/plugins/azuredevops_go/api/remote_helper_test.go
index 3385b1b39..202e9b0b0 100644
--- a/backend/plugins/azuredevops_go/api/remote_helper_test.go
+++ b/backend/plugins/azuredevops_go/api/remote_helper_test.go
@@ -92,3 +92,53 @@ func TestListRemoteReposSkipsFailingServiceConnection(t 
*testing.T) {
        }
        logger.AssertExpectations(t)
 }
+
+func TestScopeDiscoveryOrganizationIDs(t *testing.T) {
+       for _, tc := range []struct {
+               name           string
+               onPremises     bool
+               groupId        string
+               organizationId string
+               parentId       string
+       }{
+               {"on-premises project ID", true, "Project One", "", "Project 
One"},
+               {"on-premises legacy ID", true, "cloud-org/Project One", "", 
"Project One"},
+               {"Cloud ID", false, "cloud-org/Project One", "cloud-org", 
"cloud-org/Project One"},
+       } {
+               t.Run(tc.name, func(t *testing.T) {
+                       connection := 
&models.AzuredevopsConnection{AzuredevopsConn: models.AzuredevopsConn{
+                               Organization: "cloud-org",
+                       }}
+                       if tc.onPremises {
+                               connection.Endpoint = 
"https://ado.example.com/tfs/DefaultCollection/";
+                       }
+                       prefix := ""
+                       if tc.organizationId != "" {
+                               prefix = tc.organizationId + "/"
+                       }
+                       client := &fakeApiClient{responses: map[string]string{
+                               prefix + "_apis/projects":                      
           `{"count":1,"value":[{"id":"project","name":"Project One"}]}`,
+                               prefix + 
"Project%20One/_apis/git/repositories":           
`{"value":[{"id":"native","name":"native"}]}`,
+                               prefix + 
"Project%20One/_apis/serviceendpoint/endpoints/": 
`{"value":[{"id":"service","type":"github"}]}`,
+                               prefix + 
"Project%20One/_apis/sourceProviders/github/repositories/?service": 
`{"repositories":[
+                                       
{"id":"external","name":"external","fullName":"org/external","sourceProviderName":"github",
+                                        
"properties":{"connectedServiceId":"service","externalId":"external"}}
+                               ]}`,
+                       }}
+                       groups, _, err := 
listAzuredevopsRemoteScopes(connection, client, "", 
AzuredevopsRemotePagination{})
+                       assert.Nil(t, err)
+                       if assert.Len(t, groups, 1) {
+                               assert.Equal(t, tc.parentId, groups[0].Id)
+                       }
+                       repos, _, err := 
listAzuredevopsRemoteScopes(connection, client, tc.groupId, 
AzuredevopsRemotePagination{})
+                       assert.Nil(t, err)
+                       if assert.Len(t, repos, 2) {
+                               for _, repo := range repos {
+                                       assert.Equal(t, tc.parentId, 
*repo.ParentId)
+                                       assert.Equal(t, tc.organizationId, 
repo.Data.OrganizationId)
+                                       assert.Equal(t, "Project One", 
repo.Data.ProjectId)
+                               }
+                       }
+               })
+       }
+}
diff --git a/backend/plugins/azuredevops_go/impl/impl.go 
b/backend/plugins/azuredevops_go/impl/impl.go
index 0d1b862c8..1b625950d 100644
--- a/backend/plugins/azuredevops_go/impl/impl.go
+++ b/backend/plugins/azuredevops_go/impl/impl.go
@@ -126,6 +126,9 @@ func (p Azuredevops) PrepareTaskData(taskCtx 
plugin.TaskContext, options map[str
        if err != nil {
                return nil, errors.Default.Wrap(err, "failed to retrieve an 
Azure DevOps connection from the database using the provided connection ID")
        }
+       if connection.Endpoint != "" {
+               op.OrganizationId = ""
+       }
 
        apiClient, err := tasks.CreateApiClient(taskCtx, connection)
        if err != nil {
diff --git a/backend/plugins/azuredevops_go/models/api_version.go 
b/backend/plugins/azuredevops_go/models/api_version.go
new file mode 100644
index 000000000..57ba8b54d
--- /dev/null
+++ b/backend/plugins/azuredevops_go/models/api_version.go
@@ -0,0 +1,153 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements.  See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License.  You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package models
+
+import (
+       "encoding/json"
+       "fmt"
+       "net/http"
+       "net/url"
+       "strings"
+
+       "github.com/apache/devlake/core/errors"
+       "github.com/apache/devlake/core/plugin"
+)
+
+const DefaultAPIVersion = "7.1"
+
+var _ plugin.PrepareApiClient = (*AzuredevopsConn)(nil)
+
+// PrepareApiClient negotiates once per client so existing connections also 
adapt to server upgrades.
+func (conn *AzuredevopsConn) PrepareApiClient(client plugin.ApiClient) 
errors.Error {
+       version := DefaultAPIVersion
+       before := client.GetBeforeFunction()
+       if conn.Endpoint != "" {
+               // NewApiClientFromConnection installs authentication after 
preparation.
+               client.SetBeforeFunction(func(req *http.Request) errors.Error {
+                       if before != nil {
+                               if err := before(req); err != nil {
+                                       return err
+                               }
+                       }
+                       return conn.SetupAuthentication(req)
+               })
+               var err errors.Error
+               version, err = conn.detectAPIVersion(client)
+               client.SetBeforeFunction(before)
+               if err != nil {
+                       return err
+               }
+       }
+
+       setVersion := func(req *http.Request) errors.Error {
+               if before != nil {
+                       if err := before(req); err != nil {
+                               return err
+                       }
+               }
+               query := req.URL.Query()
+               if conn.Endpoint != "" {
+                       query.Set("api-version", apiVersionForPath(version, 
req.URL.Path))
+                       if (version == "6.0" || version == "7.0") && 
strings.HasSuffix(strings.TrimRight(strings.ToLower(req.URL.Path), "/"), 
"/pullrequests") {
+                               // These filters were introduced in 7.1. Older 
servers must scan all PR pages.
+                               query.Del("searchCriteria.minTime")
+                               query.Del("searchCriteria.maxTime")
+                               query.Del("searchCriteria.queryTimeRangeType")
+                       }
+                       req.URL.RawQuery = query.Encode()
+               } else if query.Get("api-version") == "" {
+                       query.Set("api-version", version)
+                       req.URL.RawQuery = query.Encode()
+               }
+               return nil
+       }
+       client.SetBeforeFunction(setVersion)
+       return nil
+}
+
+func (conn *AzuredevopsConn) detectAPIVersion(client plugin.ApiClient) 
(string, errors.Error) {
+       path := "_apis/projects"
+       for _, version := range []string{"7.2", "7.1", "7.0", "6.0"} {
+               res, err := client.Get(path, url.Values{"api-version": 
{apiVersionForPath(version, path)}, "$top": {"1"}}, nil)
+               if err != nil {
+                       return "", errors.Default.Wrap(err, "failed to detect 
Azure DevOps API version")
+               }
+               unsupported, err := checkAPIVersionResponse(res)
+               if err != nil {
+                       return "", err
+               }
+               if !unsupported {
+                       return version, nil
+               }
+       }
+       return "", errors.BadInput.New("Azure DevOps Server must support REST 
API version 6.0 or later")
+}
+
+// Preview revisions belong to individual REST resources, not the server as a 
whole.
+func apiVersionForPath(version, path string) string {
+       _, resource, _ := strings.Cut(strings.ToLower(path), "_apis/")
+       resource = strings.TrimRight(resource, "/")
+       if version == "6.0" {
+               switch {
+               case resource == "serviceendpoint/endpoints":
+                       return "6.0-preview.4"
+               case strings.HasPrefix(resource, "sourceproviders/") && 
strings.HasSuffix(resource, "/repositories"):
+                       return "6.0-preview.1"
+               }
+       }
+       if version == "7.2" {
+               switch {
+               case resource == "projects", resource == 
"serviceendpoint/endpoints":
+                       return "7.2-preview.4"
+               case strings.HasPrefix(resource, "git/repositories"):
+                       if strings.Contains(resource, "/pullrequests/") && 
strings.HasSuffix(resource, "/commits") {
+                               return "7.2-preview.1"
+                       }
+                       return "7.2-preview.2"
+               case resource == "build/builds":
+                       return "7.2-preview.8"
+               case strings.HasPrefix(resource, "build/builds/") && 
strings.HasSuffix(resource, "/timeline"):
+                       return "7.2-preview.3"
+               case strings.HasPrefix(resource, "sourceproviders/") && 
strings.HasSuffix(resource, "/repositories"):
+                       return "7.2-preview.1"
+               }
+       }
+       return version
+}
+
+func checkAPIVersionResponse(res *http.Response) (bool, errors.Error) {
+       defer res.Body.Close()
+       if res.StatusCode == http.StatusUnauthorized || res.StatusCode == 
http.StatusForbidden || res.StatusCode == http.StatusNonAuthoritativeInfo {
+               return false, errors.Unauthorized.New("Azure DevOps API version 
detection failed: check credentials and project read permissions")
+       }
+       var body struct {
+               Value   []json.RawMessage `json:"value"`
+               TypeKey string            `json:"typeKey"`
+       }
+       if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
+               return false, errors.BadInput.Wrap(err, fmt.Sprintf("Azure 
DevOps API version detection returned an invalid response (HTTP %d)", 
res.StatusCode))
+       }
+       if res.StatusCode == http.StatusOK && body.Value != nil {
+               return false, nil
+       }
+       if res.StatusCode == http.StatusBadRequest &&
+               (body.TypeKey == "VssVersionNotSupportedException" || 
body.TypeKey == "VssVersionOutOfRangeException") {
+               return true, nil
+       }
+       return false, errors.BadInput.New(fmt.Sprintf("Azure DevOps API version 
detection failed (HTTP %d, %s)", res.StatusCode, body.TypeKey))
+}
diff --git a/backend/plugins/azuredevops_go/models/connection_test.go 
b/backend/plugins/azuredevops_go/models/connection_test.go
index 10f265d11..817ab62c4 100644
--- a/backend/plugins/azuredevops_go/models/connection_test.go
+++ b/backend/plugins/azuredevops_go/models/connection_test.go
@@ -18,8 +18,16 @@ limitations under the License.
 package models
 
 import (
+       "fmt"
        "net/http"
+       "net/http/httptest"
+       "net/url"
+       "reflect"
+       "strings"
        "testing"
+
+       "github.com/apache/devlake/core/errors"
+       "github.com/apache/devlake/helpers/pluginhelper/api"
 )
 
 func TestGetEndpoint_CloudDefault(t *testing.T) {
@@ -142,3 +150,181 @@ func TestSanitize(t *testing.T) {
                t.Errorf("Sanitize() should preserve Username, got %q", 
sanitized.Username)
        }
 }
+
+func TestPrepareApiClientNegotiatesVersion(t *testing.T) {
+       operations := []struct {
+               path     string
+               versions [4]string // 7.2, 7.1, 7.0, 6.0
+               query    url.Values
+       }{
+               {"_apis/projects", [4]string{"7.2-preview.4", "7.1", "7.0", 
"6.0"}, url.Values{"$top": {"100"}, "$skip": {"100"}}},
+               {"project/_apis/git/repositories", [4]string{"7.2-preview.2", 
"7.1", "7.0", "6.0"}, nil},
+               {"project/_apis/git/repositories/repo/commits", 
[4]string{"7.2-preview.2", "7.1", "7.0", "6.0"}, url.Values{"$top": {"100"}, 
"$skip": {"200"}}},
+               {"project/_apis/build/builds", [4]string{"7.2-preview.8", 
"7.1", "7.0", "6.0"}, url.Values{
+                       "repositoryId": {"repo"}, "repositoryType": {"TfsGit"}, 
"$top": {"100"},
+                       "queryOrder": {"queueTimeDescending"}, "minTime": 
{"2026-01-01T00:00:00Z"}, "continuationToken": {"next"},
+               }},
+               {"project/_apis/build/builds/1/Timeline", 
[4]string{"7.2-preview.3", "7.1", "7.0", "6.0"}, nil},
+               {"project/_apis/git/repositories/repo/pullrequests", 
[4]string{"7.2-preview.2", "7.1", "7.0", "6.0"}, url.Values{
+                       "searchCriteria.status": {"all"}, "$skip": {"100"}, 
"$top": {"100"},
+                       "searchCriteria.queryTimeRangeType": {"created"}, 
"searchCriteria.minTime": {"2026-01-01T00:00:00Z"},
+                       "searchCriteria.maxTime": {"2026-02-01T00:00:00Z"},
+               }},
+               {"project/_apis/git/repositories/repo/pullRequests/1/commits", 
[4]string{"7.2-preview.1", "7.1", "7.0", "6.0"}, url.Values{"$top": {"100"}, 
"continuationToken": {"next"}}},
+               {"project/_apis/serviceendpoint/endpoints/", 
[4]string{"7.2-preview.4", "7.1", "7.0", "6.0-preview.4"}, nil},
+               {"project/_apis/sourceProviders/github/repositories/", 
[4]string{"7.2-preview.1", "7.1", "7.0", "6.0-preview.1"}, url.Values{
+                       "serviceEndpointId": {"endpoint"}, "pageResults": 
{"true"}, "continuationToken": {"next"},
+               }},
+       }
+       for i, version := range []string{"7.2", "7.1", "7.0", "6.0"} {
+               t.Run(version, func(t *testing.T) {
+                       var probes []string
+                       expectedQueries := make(map[string]url.Values)
+                       for _, operation := range operations {
+                               query := url.Values{"api-version": 
{operation.versions[i]}}
+                               for key, values := range operation.query {
+                                       query[key] = values
+                               }
+                               if i >= 2 && strings.HasSuffix(operation.path, 
"/pullrequests") {
+                                       query.Del("searchCriteria.minTime")
+                                       query.Del("searchCriteria.maxTime")
+                                       
query.Del("searchCriteria.queryTimeRangeType")
+                               }
+                               
expectedQueries["/tfs/DefaultCollection/"+operation.path] = query
+                       }
+                       server := httptest.NewServer(http.HandlerFunc(func(w 
http.ResponseWriter, r *http.Request) {
+                               user, token, ok := r.BasicAuth()
+                               if !ok || user != "" || token != "test-token" {
+                                       t.Error("version detection and 
subsequent requests must authenticate")
+                               }
+                               if r.Header.Get("X-Existing") != "preserved" {
+                                       t.Error("existing before-request hook 
was lost")
+                               }
+                               got := r.URL.Query().Get("api-version")
+                               if r.URL.Query().Get("$top") == "1" {
+                                       if r.URL.Path != 
"/tfs/DefaultCollection/_apis/projects" {
+                                               t.Errorf("unexpected probe 
path: %s", r.URL.Path)
+                                       }
+                                       probes = append(probes, got)
+                                       if got != operations[0].versions[i] {
+                                               
w.WriteHeader(http.StatusBadRequest)
+                                               if version == "6.0" {
+                                                       fmt.Fprint(w, 
`{"typeKey":"VssVersionOutOfRangeException"}`)
+                                               } else {
+                                                       fmt.Fprint(w, 
`{"typeKey":"VssVersionNotSupportedException"}`)
+                                               }
+                                               return
+                                       }
+                               } else if want, ok := 
expectedQueries[r.URL.Path]; !ok {
+                                       t.Errorf("unexpected request URL: %s", 
r.URL)
+                               } else if !reflect.DeepEqual(r.URL.Query(), 
want) {
+                                       t.Errorf("%s query = %v; want %v", 
r.URL.Path, r.URL.Query(), want)
+                               }
+                               fmt.Fprint(w, `{"count":0,"value":[]}`)
+                       }))
+                       defer server.Close()
+                       conn := AzuredevopsConn{
+                               Endpoint:               server.URL + 
"/tfs/DefaultCollection/",
+                               Organization:           
"cloud-only-organization",
+                               AzuredevopsAccessToken: 
AzuredevopsAccessToken{Token: "test-token"},
+                       }
+                       client := &api.ApiClient{}
+                       client.Setup(conn.GetEndpoint(), nil, 0)
+                       client.SetBeforeFunction(func(req *http.Request) 
errors.Error {
+                               req.Header.Set("X-Existing", "preserved")
+                               return nil
+                       })
+                       if err := conn.PrepareApiClient(client); err != nil {
+                               t.Fatal(err)
+                       }
+                       client.SetAuthFunction(conn.SetupAuthentication)
+                       for _, operation := range operations {
+                               res, err := 
client.Get(operation.path+"?api-version=7.1", operation.query, nil)
+                               if err != nil {
+                                       t.Fatal(err)
+                               }
+                               res.Body.Close()
+                       }
+                       want := []string{"7.2-preview.4", "7.1", "7.0", 
"6.0"}[:i+1]
+                       if !reflect.DeepEqual(probes, want) {
+                               t.Errorf("probes = %v; want %v", probes, want)
+                       }
+               })
+       }
+}
+
+func TestPrepareApiClientRejectsFailedDetection(t *testing.T) {
+       for _, tc := range []struct {
+               name     string
+               status   int
+               body     string
+               attempts int
+       }{
+               {"unauthorized", 401, `{"value":[]}`, 1},
+               {"forbidden", 403, `{"value":[]}`, 1},
+               {"login page", 203, `<html>Sign in</html>`, 1},
+               {"html success", 200, `<html>Sign in</html>`, 1},
+               {"wrong endpoint", 200, `{}`, 1},
+               {"not found", 404, 
`{"typeKey":"VssVersionNotSupportedException"}`, 1},
+               {"out of range not found", 404, 
`{"typeKey":"VssVersionOutOfRangeException"}`, 1},
+               {"unrelated bad request", 400, 
`{"typeKey":"ArgumentException"}`, 1},
+               {"server error", 500, 
`{"typeKey":"VssVersionNotSupportedException"}`, 1},
+               {"out of range server error", 500, 
`{"typeKey":"VssVersionOutOfRangeException"}`, 1},
+               {"unsupported server", 400, 
`{"typeKey":"VssVersionNotSupportedException"}`, 4},
+               {"out of range server", 400, 
`{"typeKey":"VssVersionOutOfRangeException"}`, 4},
+       } {
+               t.Run(tc.name, func(t *testing.T) {
+                       calls := 0
+                       server := httptest.NewServer(http.HandlerFunc(func(w 
http.ResponseWriter, r *http.Request) {
+                               calls++
+                               w.WriteHeader(tc.status)
+                               fmt.Fprint(w, tc.body)
+                       }))
+                       defer server.Close()
+                       conn := AzuredevopsConn{Endpoint: server.URL}
+                       client := &api.ApiClient{}
+                       client.Setup(conn.GetEndpoint(), nil, 0)
+                       if err := conn.PrepareApiClient(client); err == nil {
+                               t.Fatal("expected a detection error")
+                       }
+                       if calls != tc.attempts {
+                               t.Errorf("probe count = %d; want %d", calls, 
tc.attempts)
+                       }
+                       if client.GetBeforeFunction() != nil {
+                               t.Error("temporary authentication hook was not 
restored")
+                       }
+               })
+       }
+}
+
+func TestPrepareApiClientCloudPreservesPreviewVersion(t *testing.T) {
+       calls := 0
+       server := httptest.NewServer(http.HandlerFunc(func(w 
http.ResponseWriter, r *http.Request) {
+               calls++
+               want := DefaultAPIVersion
+               if r.URL.Path == "/_apis/graph/users" {
+                       want = "7.0-preview.1"
+               }
+               if got := r.URL.Query().Get("api-version"); got != want {
+                       t.Errorf("api-version = %q; want %q", got, want)
+               }
+               fmt.Fprint(w, `{"value":[]}`)
+       }))
+       defer server.Close()
+       conn := AzuredevopsConn{}
+       client := &api.ApiClient{}
+       client.Setup(server.URL, nil, 0)
+       if err := conn.PrepareApiClient(client); err != nil {
+               t.Fatal(err)
+       }
+       if calls != 0 {
+               t.Fatal("Cloud must not probe for a server version")
+       }
+       for _, path := range []string{"_apis/projects", 
"_apis/graph/users?api-version=7.0-preview.1"} {
+               res, err := client.Get(path, nil, nil)
+               if err != nil {
+                       t.Fatal(err)
+               }
+               res.Body.Close()
+       }
+}
diff --git 
a/backend/plugins/azuredevops_go/tasks/ci_cd_timeline_records_collector.go 
b/backend/plugins/azuredevops_go/tasks/ci_cd_timeline_records_collector.go
index 389d81a13..0fd4e4d38 100644
--- a/backend/plugins/azuredevops_go/tasks/ci_cd_timeline_records_collector.go
+++ b/backend/plugins/azuredevops_go/tasks/ci_cd_timeline_records_collector.go
@@ -66,7 +66,6 @@ func CollectRecords(taskCtx plugin.SubTaskContext) 
errors.Error {
                Input:              iterator,
                Incremental:        false,
                UrlTemplate:        "{{ if .Params.OrganizationId }}{{ 
.Params.OrganizationId }}/{{ end }}{{ .Params.ProjectId 
}}/_apis/build/builds/{{ .Input.AzuredevopsId }}/Timeline?api-version=7.1",
-               Query:              BuildPaginator(true),
                ResponseParser:     ParseRawMessageFromRecords,
                AfterResponse:      ignoreInvalidTimelineResponse, // Skip 
builds with missing/malformed timelines (e.g. YAML syntax errors)
        })
diff --git a/backend/plugins/azuredevops_go/tasks/shared.go 
b/backend/plugins/azuredevops_go/tasks/shared.go
index fa1f53e38..06e1d3cd4 100644
--- a/backend/plugins/azuredevops_go/tasks/shared.go
+++ b/backend/plugins/azuredevops_go/tasks/shared.go
@@ -93,7 +93,7 @@ func BuildPaginator(cursor bool) func(reqData 
*api.RequestData) (url.Values, err
                if cursor && reqData.CustomData != nil {
                        pag := reqData.CustomData.(CustomPageDate)
                        query.Set("continuationToken", pag.ContinuationToken)
-               } else {
+               } else if !cursor {
                        query.Set("$skip", fmt.Sprint(reqData.Pager.Skip))
                }
                query.Set("$top", fmt.Sprint(reqData.Pager.Size))
diff --git a/backend/plugins/azuredevops_go/tasks/shared_test.go 
b/backend/plugins/azuredevops_go/tasks/shared_test.go
index 312d91846..2f76773ff 100644
--- a/backend/plugins/azuredevops_go/tasks/shared_test.go
+++ b/backend/plugins/azuredevops_go/tasks/shared_test.go
@@ -21,6 +21,7 @@ import (
        "bytes"
        "io"
        "net/http"
+       "net/url"
        "testing"
 
        "github.com/apache/devlake/helpers/pluginhelper/api"
@@ -35,6 +36,26 @@ func makeResponse(statusCode int, body string) 
*http.Response {
        }
 }
 
+func TestBuildPaginatorCursorDoesNotSendOffset(t *testing.T) {
+       for _, tc := range []struct {
+               name   string
+               custom interface{}
+               want   url.Values
+       }{
+               {"first page", nil, url.Values{"$top": {"100"}}},
+               {"continuation", CustomPageDate{ContinuationToken: "next"}, 
url.Values{"$top": {"100"}, "continuationToken": {"next"}}},
+       } {
+               t.Run(tc.name, func(t *testing.T) {
+                       query, err := BuildPaginator(true)(&api.RequestData{
+                               Pager:      &api.Pager{Size: 100},
+                               CustomData: tc.custom,
+                       })
+                       assert.NoError(t, err)
+                       assert.Equal(t, tc.want, query)
+               })
+       }
+}
+
 func TestIgnoreInvalidTimelineResponse_404(t *testing.T) {
        res := makeResponse(http.StatusNotFound, "")
        err := ignoreInvalidTimelineResponse(res)
diff --git 
a/config-ui/src/plugins/components/connection-form/fields/username.tsx 
b/config-ui/src/plugins/components/connection-form/fields/username.tsx
index 9c294eadb..57ce2cd0c 100644
--- a/config-ui/src/plugins/components/connection-form/fields/username.tsx
+++ b/config-ui/src/plugins/components/connection-form/fields/username.tsx
@@ -22,6 +22,7 @@ import { Input } from 'antd';
 import { Block } from '@/components';
 
 interface Props {
+  required?: boolean;
   label?: string;
   subLabel?: string;
   placeholder?: string;
@@ -33,6 +34,7 @@ interface Props {
 }
 
 export const ConnectionUsername = ({
+  required = true,
   label,
   subLabel,
   placeholder,
@@ -46,15 +48,15 @@ export const ConnectionUsername = ({
   }, [initialValue]);
 
   useEffect(() => {
-    setError(value ? '' : 'username is required');
-  }, [value]);
+    setError(!required || value ? '' : 'username is required');
+  }, [value, required]);
 
   const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
     setValue(e.target.value);
   };
 
   return (
-    <Block title={label ?? 'Username'} description={subLabel ? subLabel : 
null} required>
+    <Block title={label ?? 'Username'} description={subLabel ? subLabel : 
null} required={required}>
       <Input
         style={{ width: 386 }}
         placeholder={placeholder ?? 'Your Username'}
diff --git a/config-ui/src/plugins/register/azure/config.tsx 
b/config-ui/src/plugins/register/azure/config.tsx
index 978a6af09..abb4b9141 100644
--- a/config-ui/src/plugins/register/azure/config.tsx
+++ b/config-ui/src/plugins/register/azure/config.tsx
@@ -88,11 +88,28 @@ export const AzureGoConfig: IPluginConfig = {
     initialValues: {},
     fields: [
       'name',
-      ({ values, setValues }: any) => (
-        <BaseURL key="base-url" value={values.endpoint} onChange={(val) => 
setValues({ endpoint: val })} />
+      ({
+        initialValues,
+        values,
+        setValues,
+        setErrors,
+      }: {
+        initialValues: { endpoint?: string };
+        values: { endpoint?: string };
+        setValues: (values: { endpoint: string }) => void;
+        setErrors: (errors: { endpoint: string }) => void;
+      }) => (
+        <BaseURL
+          key="base-url"
+          initialValue={initialValues.endpoint ?? ''}
+          value={values.endpoint}
+          onChange={(val) => setValues({ endpoint: val })}
+          setError={(error) => setErrors({ endpoint: error })}
+        />
       ),
       {
         key: 'username',
+        required: false,
         label: 'Username (Optional for On-Premises)',
         subLabel:
           'For On-Premises Azure DevOps Server, enter your Windows/Domain 
username if required (e.g. Administrator or domain\\user). Leave empty for 
Cloud.',
diff --git 
a/config-ui/src/plugins/register/azure/connection-fields/base-url.tsx 
b/config-ui/src/plugins/register/azure/connection-fields/base-url.tsx
index 28bd28ba6..2cbad529c 100644
--- a/config-ui/src/plugins/register/azure/connection-fields/base-url.tsx
+++ b/config-ui/src/plugins/register/azure/connection-fields/base-url.tsx
@@ -16,30 +16,42 @@
  *
  */
 
-import React, { useState } from 'react';
-import { Input, Radio } from 'antd';
+import { useEffect, useState } from 'react';
+import { Input, Radio, type RadioChangeEvent } from 'antd';
 import { Block } from '@/components';
 
 interface Props {
+  initialValue?: string;
   value?: string;
   onChange?: (value: string) => void;
+  setError?: (error: string) => void;
 }
 
-export const BaseURL = ({ value, onChange }: Props) => {
-  // Default to 'server' mode if an endpoint value already exists, 'cloud' 
otherwise
+export const BaseURL = ({ initialValue, value, onChange, setError }: Props) => 
{
   const [version, setVersion] = useState<'cloud' | 'server'>(value ? 'server' 
: 'cloud');
 
-  const handleVersionChange = (e: any) => {
+  useEffect(() => {
+    if (initialValue !== undefined) {
+      onChange?.(initialValue);
+      setVersion(initialValue ? 'server' : 'cloud');
+    }
+  }, [initialValue]);
+
+  useEffect(() => {
+    setError?.(version === 'server' && !value?.trim() ? 'endpoint is required' 
: '');
+  }, [version, value]);
+
+  const handleVersionChange = (e: RadioChangeEvent) => {
     const selectedVersion = e.target.value;
     setVersion(selectedVersion);
     if (selectedVersion === 'cloud') {
-      onChange?.(''); // Reset endpoint when switching to Cloud mode
+      onChange?.('');
     }
   };
 
   return (
     <Block title="Azure DevOps Version" required>
-      <Radio.Group value={version} onChange={handleVersionChange}>
+      <Radio.Group name="azure-devops-version" value={version} 
onChange={handleVersionChange}>
         <Radio value="cloud">Azure DevOps Cloud</Radio>
         <Radio value="server">Azure DevOps Server (On-Premises)</Radio>
       </Radio.Group>
diff --git 
a/config-ui/src/plugins/register/azure/connection-fields/connection.test.tsx 
b/config-ui/src/plugins/register/azure/connection-fields/connection.test.tsx
new file mode 100644
index 000000000..4e5c0ea62
--- /dev/null
+++ b/config-ui/src/plugins/register/azure/connection-fields/connection.test.tsx
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+import { useState, type ReactNode } from 'react';
+import '@testing-library/jest-dom/vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { Form } from '@/plugins/components/connection-form/fields';
+
+import { AzureGoConfig } from '../config';
+
+vi.mock('@/components', () => ({
+  Block: ({ title, children }: { title?: ReactNode; children?: ReactNode }) => 
(
+    <section>
+      {title}
+      {children}
+    </section>
+  ),
+  ExternalLink: ({ children }: { children?: ReactNode }) => 
<span>{children}</span>,
+}));
+
+const endpoint = 'https://ado.example.com/tfs/DefaultCollection/';
+const initialConnection = { name: 'Test', token: 'test-token', endpoint };
+
+function ConnectionFields({
+  initialValues,
+  fields = AzureGoConfig.connection.fields,
+}: {
+  initialValues: Record<string, string>;
+  fields?: typeof AzureGoConfig.connection.fields;
+}) {
+  const [values, setValues] = useState<Record<string, unknown>>({});
+  const [errors, setErrors] = useState<Record<string, string>>({});
+  return (
+    <>
+      <Form
+        type="update"
+        name="Azure DevOps Go"
+        fields={fields}
+        initialValues={initialValues}
+        values={values}
+        errors={errors}
+        setValues={setValues}
+        setErrors={setErrors}
+      />
+      <button disabled={Object.values(errors).some(Boolean)}>Save</button>
+      <output data-testid="values">{JSON.stringify(values)}</output>
+    </>
+  );
+}
+
+describe('Azure DevOps Go connection fields', () => {
+  it('allows an empty username for on-premises and Cloud connections', async 
() => {
+    const { rerender } = render(<ConnectionFields 
initialValues={initialConnection} />);
+    await waitFor(() => expect(screen.getByRole('button', { name: 'Save' 
})).not.toBeDisabled());
+    expect(screen.getByPlaceholderText('Your Username')).toHaveValue('');
+
+    rerender(<ConnectionFields initialValues={{ ...initialConnection, 
endpoint: '' }} />);
+    await waitFor(() => expect(screen.getByRole('radio', { name: 'Azure DevOps 
Cloud' })).toBeChecked());
+    expect(screen.getByRole('button', { name: 'Save' })).not.toBeDisabled();
+  });
+
+  it('restores a saved on-premises endpoint even when the connection loads 
after mount', async () => {
+    const { rerender } = render(<ConnectionFields initialValues={{}} />);
+    rerender(<ConnectionFields initialValues={initialConnection} />);
+
+    await waitFor(() => expect(screen.getByRole('radio', { name: 'Azure DevOps 
Server (On-Premises)' })).toBeChecked());
+    expect(screen.getByPlaceholderText('e.g., 
https://your-server/tfs/DefaultCollection/')).toHaveValue(endpoint);
+    expect(JSON.parse(screen.getByTestId('values').textContent ?? 
'{}').endpoint).toBe(endpoint);
+
+    const updatedEndpoint = 'https://other.example.com/tfs/Collection/';
+    fireEvent.change(screen.getByPlaceholderText('e.g., 
https://your-server/tfs/DefaultCollection/'), {
+      target: { value: updatedEndpoint },
+    });
+    fireEvent.change(screen.getByPlaceholderText('Your Username'), { target: { 
value: 'user' } });
+    expect(JSON.parse(screen.getByTestId('values').textContent ?? 
'{}').endpoint).toBe(updatedEndpoint);
+  });
+
+  it('clears the endpoint when switching to Cloud and requires a URL when 
switching back', async () => {
+    render(<ConnectionFields initialValues={initialConnection} />);
+    fireEvent.click(await screen.findByRole('radio', { name: 'Azure DevOps 
Cloud' }));
+    await waitFor(() => 
expect(JSON.parse(screen.getByTestId('values').textContent ?? 
'{}').endpoint).toBe(''));
+    fireEvent.click(screen.getByRole('radio', { name: 'Azure DevOps Server 
(On-Premises)' }));
+    await waitFor(() => expect(screen.getByRole('button', { name: 'Save' 
})).toBeDisabled());
+    fireEvent.change(screen.getByPlaceholderText('e.g., 
https://your-server/tfs/DefaultCollection/'), {
+      target: { value: endpoint },
+    });
+    await waitFor(() => expect(screen.getByRole('button', { name: 'Save' 
})).not.toBeDisabled());
+  });
+
+  it('preserves other field errors when endpoint validation changes', async () 
=> {
+    render(<ConnectionFields initialValues={initialConnection} />);
+    const save = screen.getByRole('button', { name: 'Save' });
+    await waitFor(() => expect(save).not.toBeDisabled());
+
+    fireEvent.change(screen.getByPlaceholderText('Your Connection Name'), { 
target: { value: '' } });
+    await waitFor(() => expect(save).toBeDisabled());
+    fireEvent.change(screen.getByPlaceholderText('e.g., 
https://your-server/tfs/DefaultCollection/'), {
+      target: { value: '' },
+    });
+    await waitFor(() => expect(save).toBeDisabled());
+    fireEvent.change(screen.getByPlaceholderText('e.g., 
https://your-server/tfs/DefaultCollection/'), {
+      target: { value: endpoint },
+    });
+    await waitFor(() => expect(save).toBeDisabled());
+
+    fireEvent.change(screen.getByPlaceholderText('Your Connection Name'), { 
target: { value: 'Test' } });
+    await waitFor(() => expect(save).not.toBeDisabled());
+  });
+
+  it('keeps username required by default for other connections', async () => {
+    render(<ConnectionFields initialValues={{}} fields={['username']} />);
+    await waitFor(() => expect(screen.getByRole('button', { name: 'Save' 
})).toBeDisabled());
+    fireEvent.change(screen.getByPlaceholderText('Your Username'), { target: { 
value: 'user' } });
+    await waitFor(() => expect(screen.getByRole('button', { name: 'Save' 
})).not.toBeDisabled());
+  });
+});

Reply via email to