Skip to content

Commit f36ea27

Browse files
fix(azure-devops): az repos pr create links the new pull request to the thread
An agent that opened a pull request with `az repos pr create` left its thread without a link: the Azure DevOps definition named no create command, and the reactor only reads a URL on a line of its own, while `az` prints the pull request as JSON with its REST address. The definition now names the create command and reads the web URL out of that JSON. Every `az repos pr` subcommand prints an existing pull request in the same form, so one beside the create (`show`, `list`, `update`) leaves nothing linked. Printed URLs are now counted against each host's own create commands, so an Azure create cannot vouch for a second GitHub URL. Fixes #31166 Co-Authored-By: Claude Fable 5.2 <[email protected]>
1 parent 9efd960 commit f36ea27

8 files changed

Lines changed: 225 additions & 106 deletions

File tree

‎apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1962,6 +1962,28 @@ describe("PullRequestSyncReactor", () => {
19621962
}),
19631963
);
19641964

1965+
// What `az repos pr` prints for one pull request: indented JSON whose `url` is the REST
1966+
// address, with every attribute the response left unset as null.
1967+
const azurePullRequestJson = (pullRequestId: number) =>
1968+
JSON.stringify(
1969+
{
1970+
closedDate: null,
1971+
createdBy: { displayName: "Sam Example", uniqueName: "[email protected]" },
1972+
pullRequestId,
1973+
repository: {
1974+
name: "repository",
1975+
project: { name: "project", state: "wellFormed", url: null },
1976+
url: "https://dev.azure.com/organization/a7573007/_apis/git/repositories/3411ebc1",
1977+
webUrl: null,
1978+
},
1979+
status: "active",
1980+
title: "Fix the thing",
1981+
url: `https://dev.azure.com/organization/a7573007/_apis/git/repositories/3411ebc1/pullRequests/${pullRequestId}`,
1982+
},
1983+
null,
1984+
2,
1985+
);
1986+
19651987
it.effect.each([
19661988
{
19671989
name: "a plain create",
@@ -2089,6 +2111,26 @@ describe("PullRequestSyncReactor", () => {
20892111
output: "https://github.com/owner/repository/pull/120",
20902112
linked: [],
20912113
},
2114+
{
2115+
name: "an Azure DevOps pull request after a push",
2116+
input: 'git push -u origin feature 2>&1 && az repos pr create --title "Fix the thing"',
2117+
output: `To https://dev.azure.com/organization/project/_git/repository\n * [new branch] feature -> feature\n${azurePullRequestJson(42)}\n`,
2118+
linked: [42],
2119+
},
2120+
{
2121+
name: "an existing Azure DevOps pull request shown beside a create that printed nothing",
2122+
input: 'az repos pr show --id "$PR_ID" && az repos pr create --title test --output none',
2123+
output: azurePullRequestJson(42),
2124+
linked: [],
2125+
},
2126+
{
2127+
name: "an existing GitHub pull request printed beside GitHub and Azure DevOps creates",
2128+
input:
2129+
"gh pr view --json url --jq .url && az repos pr create --title test --output none && gh pr create --fill",
2130+
output:
2131+
"https://github.com/owner/repository/pull/120\nhttps://github.com/owner/repository/pull/124\n",
2132+
linked: [],
2133+
},
20922134
])("links what the command created: $name", ({ input, output, linked }) =>
20932135
Effect.gen(function* () {
20942136
yield* TestClock.setTime(Date.parse(NOW));

‎apps/server/src/orchestration-v2/PullRequestSyncReactor.ts‎

Lines changed: 37 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -57,19 +57,19 @@ const isChangeRequestCloseCommand = (command: string) =>
5757
// A create command anywhere else, as in `echo "gh pr create"`, is text, not a command that runs.
5858
const COMMAND_START =
5959
"(?:^|[;&|({`\\n]|\\b(?:do|then|else)\\s)\\s*(?:(?:\\w+=\\S*|env|time|nohup|timeout\\s+\\S+)\\s+)*";
60-
const CREATE_COMMANDS = sourceControlDefinitions.definitions.flatMap(
61-
({ kind, changeRequestCreateCommand: command }) =>
62-
command === undefined
63-
? []
64-
: // The subcommand must end its shell word: `gh pr create#x` runs another one.
65-
[
66-
{
67-
kind,
68-
command,
69-
run: new RegExp(`${COMMAND_START}${command.source}(?=$|[\\s;&|)])`, "gu"),
70-
},
71-
],
72-
);
60+
const CREATE_COMMANDS = sourceControlDefinitions.definitions.flatMap((definition) => {
61+
const command = definition.changeRequestCreateCommand;
62+
return command === undefined
63+
? []
64+
: // The subcommand must end its shell word: `gh pr create#x` runs another one.
65+
[
66+
{
67+
definition,
68+
command,
69+
run: new RegExp(`${COMMAND_START}${command.source}(?=$|[\\s;&|)])`, "gu"),
70+
},
71+
];
72+
});
7373
const createCommandCount = (code: string) =>
7474
CREATE_COMMANDS.reduce((count, { run }) => count + [...code.matchAll(run)].length, 0);
7575
// A push, directly or through a stack tool, that can start checks on a linked pull request.
@@ -144,17 +144,15 @@ const isPushCommand = (input: string) => PUSH_COMMAND.test(shellCode(shellScript
144144
type CommandExecution = Extract<OrchestrationV2TurnItem, { readonly type: "command_execution" }>;
145145

146146
/**
147-
* The change requests a shell command opened: URLs on lines of their own in the output of a
148-
* command that runs a host's create command. One the command also names, as `gh pr view 12`
149-
* does, existed before it ran. More URLs than create commands means something else printed
150-
* some, such as `gh pr list`, so none are taken.
147+
* The change requests a shell command opened: the URLs its host's create command printed. One the
148+
* command also names, as `gh pr view 12` does, existed before it ran. More of a host's URLs than
149+
* its creates means something else printed some, such as `gh pr list`, so none of them are taken.
151150
*/
152151
export function changeRequestsCreatedBy(input: string, output: string) {
153152
if (!CREATE_COMMANDS.some(({ command }) => command.test(input))) return [];
154153
const script = shellScript(input);
155154
const code = shellCode(script);
156-
const creates = createCommandCount(code);
157-
if (creates === 0) return [];
155+
if (createCommandCount(code) === 0) return [];
158156
const otherCommands = code
159157
.split(COMMAND_SEPARATOR)
160158
.filter((part) => createCommandCount(part) === 0)
@@ -163,22 +161,26 @@ export function changeRequestsCreatedBy(input: string, output: string) {
163161
const otherScript = shellSegments(script)
164162
.filter((segment) => createCommandCount(shellCode(segment)) === 0)
165163
.join("\n");
166-
const creators = new Set(
167-
CREATE_COMMANDS.filter(({ run }) => code.match(run) !== null).map(({ kind }) => kind),
168-
);
169-
const created = new Map<string, ThreadPullRequestKey & { readonly url: string }>();
170-
for (const [, url = ""] of output.matchAll(URL_LINE)) {
171-
const parsed = sourceControlDefinitions.parseChangeRequestUrl(url);
172-
// Only the host whose create command ran can have printed a new change request.
173-
if (parsed === null || !creators.has(parsed.definition.kind)) continue;
174-
const { link } = parsed;
175-
const named = new RegExp(`(?:^|(?<=[\\s#/=("']))${link.number}(?=$|[\\s);&|/"'])`, "u");
176-
// Quoted text in the other commands counts, as in `printf '.../pull/12'`.
177-
if (named.test(otherScript)) continue;
178-
const key = normalizeThreadPullRequestKey(link);
179-
created.set(threadPullRequestKeyOf(key), { ...key, url });
180-
}
181-
return created.size > creates ? [] : [...created.values()];
164+
const urlLines = Array.from(output.matchAll(URL_LINE), ([, url = ""]) => url);
165+
return CREATE_COMMANDS.flatMap(({ definition, run }) => {
166+
const creates = [...code.matchAll(run)].length;
167+
if (creates === 0 || definition.changeRequestPrintCommand?.test(otherCommands) === true) {
168+
return [];
169+
}
170+
const created = new Map<string, ThreadPullRequestKey & { readonly url: string }>();
171+
for (const url of definition.changeRequestCreateOutputUrls?.(output) ?? urlLines) {
172+
const parsed = sourceControlDefinitions.parseChangeRequestUrl(url);
173+
// Only the host whose create command ran can have printed a new change request.
174+
if (parsed === null || parsed.definition.kind !== definition.kind) continue;
175+
const { link } = parsed;
176+
const named = new RegExp(`(?:^|(?<=[\\s#/=("']))${link.number}(?=$|[\\s);&|/"'])`, "u");
177+
// Quoted text in the other commands counts, as in `printf '.../pull/12'`.
178+
if (named.test(otherScript)) continue;
179+
const key = normalizeThreadPullRequestKey(link);
180+
created.set(threadPullRequestKeyOf(key), { ...key, url });
181+
}
182+
return created.size > creates ? [] : [...created.values()];
183+
});
182184
}
183185

184186
const isPullRequestProviderError = Schema.is(PullRequestProviderError);

‎docs/user/source-control.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -308,8 +308,8 @@ and their marks follow the same rules as on web and desktop.
308308
A thread can hold several pull requests, including reviews from another repository on the same host.
309309
Use **Link pull request** in the command palette or **Linked pull requests** panel, or right-click a
310310
pull request link in the conversation. Creating a pull request from Git actions links it automatically,
311-
and so does an agent creating one with `gh pr create` or `glab mr create`. Agents can link other
312-
pull requests with the `link_pull_request` tool.
311+
and so does an agent creating one with `gh pr create`, `glab mr create`, or `az repos pr create`.
312+
Agents can link other pull requests with the `link_pull_request` tool.
313313

314314
Use **Link pull request to thread** in the command palette to keep a pull request with the thread. From a review
315315
on the Pull requests page, **Link to thread** lets you search for an active thread. The review header

‎packages/source-control-azure-devops/src/server/azureDevOpsPullRequestJson.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import type {
1616
import { TrimmedNonEmptyString } from "@t3tools/contracts";
1717
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
1818

19-
import { azureDevOpsPullRequestWebUrl } from "./azureDevOpsPullRequests.ts";
19+
import { azureDevOpsPullRequestWebUrl } from "../shared/pullRequestUrls.ts";
2020

2121
// CLI fields vary by command; unknown enum values must not fail the payload.
2222
const RawIdentitySchema = Schema.Struct({

‎packages/source-control-azure-devops/src/server/azureDevOpsPullRequests.ts‎

Lines changed: 2 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import * as Schema from "effect/Schema";
1111
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
1212
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
1313

14+
import { azureDevOpsPullRequestWebUrl } from "../shared/pullRequestUrls.ts";
15+
1416
export interface NormalizedAzureDevOpsPullRequestRecord {
1517
readonly number: number;
1618
readonly title: string;
@@ -75,72 +77,6 @@ function normalizeAzureDevOpsPullRequestState(status: string): "open" | "closed"
7577
}
7678
}
7779

78-
function encodeAzureDevOpsPathSegment(segment: string): string {
79-
return encodeURIComponent(segment);
80-
}
81-
82-
function azureDevOpsOrganizationBaseFromRestApiUrl(
83-
value: string | null | undefined,
84-
): string | null {
85-
const rawUrl = trimOptionalString(value);
86-
if (!rawUrl) {
87-
return null;
88-
}
89-
90-
try {
91-
const url = new URL(rawUrl);
92-
const hostname = url.hostname.toLowerCase();
93-
const pathSegments = url.pathname.split("/").filter((segment) => segment.length > 0);
94-
const isAzureRestUrl = pathSegments.some((segment) => segment.toLowerCase() === "_apis");
95-
if (!isAzureRestUrl) {
96-
return null;
97-
}
98-
99-
if (hostname === "dev.azure.com") {
100-
const organization = pathSegments[0];
101-
return organization ? `${url.origin}/${organization}` : null;
102-
}
103-
104-
if (hostname.endsWith(".visualstudio.com")) {
105-
return url.origin;
106-
}
107-
108-
return null;
109-
} catch {
110-
return null;
111-
}
112-
}
113-
114-
export function azureDevOpsPullRequestWebUrl(input: {
115-
readonly pullRequestId: number;
116-
readonly webLink?: string | null | undefined;
117-
readonly repositoryWebUrl?: string | null | undefined;
118-
readonly restApiUrl?: string | null | undefined;
119-
readonly projectName?: string | null | undefined;
120-
readonly repositoryName?: string | null | undefined;
121-
}): string {
122-
const webLink = trimOptionalString(input.webLink);
123-
if (webLink) {
124-
return webLink;
125-
}
126-
127-
const repositoryWebUrl = trimOptionalString(input.repositoryWebUrl);
128-
if (repositoryWebUrl) {
129-
return `${repositoryWebUrl.replace(/\/+$/, "")}/pullrequest/${input.pullRequestId}`;
130-
}
131-
132-
const organizationBase = azureDevOpsOrganizationBaseFromRestApiUrl(input.restApiUrl);
133-
const projectName = trimOptionalString(input.projectName);
134-
const repositoryName = trimOptionalString(input.repositoryName);
135-
if (organizationBase && projectName && repositoryName) {
136-
const encodedProjectName = encodeAzureDevOpsPathSegment(projectName);
137-
const encodedRepositoryName = encodeAzureDevOpsPathSegment(repositoryName);
138-
return `${organizationBase}/${encodedProjectName}/_git/${encodedRepositoryName}/pullrequest/${input.pullRequestId}`;
139-
}
140-
141-
return trimOptionalString(input.restApiUrl) ?? "";
142-
}
143-
14480
function normalizeAzureDevOpsPullRequestUrl(
14581
raw: Schema.Schema.Type<typeof AzureDevOpsPullRequestSchema>,
14682
): string {

‎packages/source-control-azure-devops/src/shared/definition.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
remoteWebOrigin,
1010
} from "@t3tools/source-control-core/shared/definition";
1111
import { icon } from "./icon.ts";
12+
import { azureDevOpsPrintedPullRequestUrls } from "./pullRequestUrls.ts";
1213

1314
// Azure DevOps Server runs on any hostname; its `_git` route identifies it.
1415
const CHANGE_REQUEST_PATH = /^\/((?:[^/]+\/)*_git\/[^/]+)\/pullrequest\/(\d+)(?:\/|$)/u;
@@ -116,6 +117,11 @@ export const definition = defineSourceControl({
116117
// Completing or abandoning is a status change, the same `update` this package runs.
117118
changeRequestCloseCommand:
118119
/\baz\s+repos\s+pr\s+update\b[^;&|]*--status[\s=]+["']?(?:completed|abandoned)\b/u,
120+
changeRequestCreateCommand: /\baz\s+repos\s+pr\s+create\b/u,
121+
// `az` prints the pull request as JSON, with its REST address and no web URL.
122+
changeRequestCreateOutputUrls: azureDevOpsPrintedPullRequestUrls,
123+
// Every `az repos pr` subcommand prints pull requests that way, as a raw REST call can.
124+
changeRequestPrintCommand: /\baz\s+(?:repos\s+pr|devops\s+invoke|rest)\b/u,
119125
authorProfileUrl: () => null,
120126
hardLineBreaks: true,
121127
reviewSummaryRequired: () => false,
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
import * as Result from "effect/Result";
2+
import * as Schema from "effect/Schema";
3+
import { PositiveInt } from "@t3tools/contracts";
4+
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
5+
6+
function trimOptionalString(value: string | null | undefined): string | null {
7+
const trimmed = value?.trim() ?? "";
8+
return trimmed.length > 0 ? trimmed : null;
9+
}
10+
11+
function encodeAzureDevOpsPathSegment(segment: string): string {
12+
return encodeURIComponent(segment);
13+
}
14+
15+
function azureDevOpsOrganizationBaseFromRestApiUrl(
16+
value: string | null | undefined,
17+
): string | null {
18+
const rawUrl = trimOptionalString(value);
19+
if (!rawUrl) {
20+
return null;
21+
}
22+
23+
try {
24+
const url = new URL(rawUrl);
25+
const hostname = url.hostname.toLowerCase();
26+
const pathSegments = url.pathname.split("/").filter((segment) => segment.length > 0);
27+
const isAzureRestUrl = pathSegments.some((segment) => segment.toLowerCase() === "_apis");
28+
if (!isAzureRestUrl) {
29+
return null;
30+
}
31+
32+
if (hostname === "dev.azure.com") {
33+
const organization = pathSegments[0];
34+
return organization ? `${url.origin}/${organization}` : null;
35+
}
36+
37+
if (hostname.endsWith(".visualstudio.com")) {
38+
return url.origin;
39+
}
40+
41+
return null;
42+
} catch {
43+
return null;
44+
}
45+
}
46+
47+
export function azureDevOpsPullRequestWebUrl(input: {
48+
readonly pullRequestId: number;
49+
readonly webLink?: string | null | undefined;
50+
readonly repositoryWebUrl?: string | null | undefined;
51+
readonly restApiUrl?: string | null | undefined;
52+
readonly projectName?: string | null | undefined;
53+
readonly repositoryName?: string | null | undefined;
54+
}): string {
55+
const webLink = trimOptionalString(input.webLink);
56+
if (webLink) {
57+
return webLink;
58+
}
59+
60+
const repositoryWebUrl = trimOptionalString(input.repositoryWebUrl);
61+
if (repositoryWebUrl) {
62+
return `${repositoryWebUrl.replace(/\/+$/, "")}/pullrequest/${input.pullRequestId}`;
63+
}
64+
65+
const organizationBase = azureDevOpsOrganizationBaseFromRestApiUrl(input.restApiUrl);
66+
const projectName = trimOptionalString(input.projectName);
67+
const repositoryName = trimOptionalString(input.repositoryName);
68+
if (organizationBase && projectName && repositoryName) {
69+
const encodedProjectName = encodeAzureDevOpsPathSegment(projectName);
70+
const encodedRepositoryName = encodeAzureDevOpsPathSegment(repositoryName);
71+
return `${organizationBase}/${encodedProjectName}/_git/${encodedRepositoryName}/pullrequest/${input.pullRequestId}`;
72+
}
73+
74+
return trimOptionalString(input.restApiUrl) ?? "";
75+
}
76+
77+
const OptionalString = Schema.optional(Schema.NullOr(Schema.String));
78+
79+
// `az` prints every attribute the response left unset as null.
80+
const decodePrintedPullRequest = decodeJsonResult(
81+
Schema.Struct({
82+
pullRequestId: PositiveInt,
83+
url: OptionalString,
84+
repository: Schema.optional(
85+
Schema.NullOr(
86+
Schema.Struct({
87+
name: OptionalString,
88+
webUrl: OptionalString,
89+
project: Schema.optional(Schema.NullOr(Schema.Struct({ name: OptionalString }))),
90+
}),
91+
),
92+
),
93+
}),
94+
);
95+
96+
/**
97+
* The web URLs of the pull requests `az repos pr` printed one at a time in its default indented
98+
* JSON, where only a whole object's braces sit unindented on lines of their own. Other output may
99+
* surround them; a listed pull request sits indented inside an array and is not read.
100+
*/
101+
export function azureDevOpsPrintedPullRequestUrls(output: string): ReadonlyArray<string> {
102+
const urls: Array<string> = [];
103+
const lines = output.split("\n").map((line) => line.trimEnd());
104+
let start = -1;
105+
for (const [index, line] of lines.entries()) {
106+
if (line === "{") start = index;
107+
if (line !== "}" || start === -1) continue;
108+
const decoded = decodePrintedPullRequest(lines.slice(start, index + 1).join("\n"));
109+
start = -1;
110+
if (Result.isFailure(decoded)) continue;
111+
const { pullRequestId, repository, url } = decoded.success;
112+
urls.push(
113+
azureDevOpsPullRequestWebUrl({
114+
pullRequestId,
115+
repositoryWebUrl: repository?.webUrl,
116+
restApiUrl: url,
117+
projectName: repository?.project?.name,
118+
repositoryName: repository?.name,
119+
}),
120+
);
121+
}
122+
return urls;
123+
}

0 commit comments

Comments
 (0)