The best way to control Claude Code, Codex and more from any computer or phone
feat(server): link pull requests agents create from the shell (#24813)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 25, 2026 at 02:45 UTC
dca46e2b2424757e15bbf0a1138518755ea5b72b
6 files changed
+376
-10
apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts
+211
-3
@@ -332,17 +332,22 @@ function runUpdated(
332
};
333
}
334
335
-function commandRan(threadId: ThreadId, input: string): OrchestrationV2DomainEvent {
335
+function commandRan(
336
+ threadId: ThreadId,
337
+ input: string,
338
+ output?: string,
339
+ name = "command",
340
+): OrchestrationV2DomainEvent {
341
const runId = RunId.make(`run:${threadId}:1`);
342
const at = DateTime.makeUnsafe(NOW);
343
return {
344
type: "turn-item.updated",
340
- id: EventId.make(`event:${threadId}:command`),
345
+ id: EventId.make(`event:${threadId}:${name}`),
346
threadId,
347
runId,
348
occurredAt: at,
349
payload: {
345
- id: TurnItemId.make(`item:${threadId}:command`),
350
+ id: TurnItemId.make(`item:${threadId}:${name}`),
351
threadId,
352
runId,
353
nodeId: null,
@@ -358,6 +363,7 @@ function commandRan(threadId: ThreadId, input: string): OrchestrationV2DomainEve
363
updatedAt: at,
364
type: "command_execution",
365
input,
366
+ ...(output === undefined ? {} : { output }),
367
},
368
};
369
}
@@ -466,6 +472,29 @@ const requestAndApply = Effect.fn("requestPullRequestSyncHarness")(function* (
472
yield* applyRecordedSyncs(fixture);
473
});
474
475
+/** A thread with an open pull request whose merge command marks the end of earlier events. */
476
+const MERGING_THREAD = ThreadId.make("merging");
477
+
478
+/** The link commands `events` dispatch, read once the reactor has handled them all. */
479
+const linksFrom = Effect.fn("linksFrom")(function* (
480
+ fixture: Harness,
481
+ reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"],
482
+ events: ReadonlyArray<OrchestrationV2DomainEvent>,
483
+) {
484
+ yield* Ref.set(fixture.linkCommands, []);
485
+ yield* Queue.offerAll(fixture.domainEvents, [
486
+ ...events,
487
+ commandRan(MERGING_THREAD, "gh pr merge 7", undefined, "merge"),
488
+ ]);
489
+ yield* Queue.take(fixture.snapshotReads);
490
+ yield* Queue.take(fixture.snapshotReads);
491
+ yield* reactor.drain;
492
+ return yield* Ref.get(fixture.linkCommands);
493
+});
494
+
495
+const mergingSnapshot = () =>
496
+ makeSnapshot([makeThread(MERGING_THREAD, { pullRequests: [makeLink(7, { state: "open" })] })]);
497
+
498
describe("PullRequestSyncReactor", () => {
499
it.effect("retries a failed stack read after the summary becomes terminal", () =>
500
Effect.scoped(
@@ -1480,4 +1509,183 @@ describe("PullRequestSyncReactor", () => {
1509
}),
1510
),
1511
);
1512
+
1513
+ it.effect.each([
1514
+ {
1515
+ name: "a plain create",
1516
+ input:
1517
+ 'gh pr create --base main --head feature --title "fix: 7 things" --body-file /tmp/body.md',
1518
+ output: "https://github.com/owner/repository/pull/124\n",
1519
+ linked: [124],
1520
+ },
1521
+ {
1522
+ name: "a Codex shell wrapper after a push",
1523
+ input: '/bin/zsh -lc "git push -u origin feature 2>&1 | tail -2 && gh pr create --fill"',
1524
+ output: [
1525
+ "remote: Create a pull request for 'feature' on GitHub by visiting:",
1526
+ "remote: https://github.com/owner/repository/pull/new/feature",
1527
+ "https://github.com/owner/repository/pull/124",
1528
+ ].join("\n"),
1529
+ linked: [124],
1530
+ },
1531
+ {
1532
+ name: "a Codex script quoted in pieces around a heredoc",
1533
+ input:
1534
+ "/bin/zsh -lc \"cat > /tmp/body.md <<'EOF'\nSet the \"'`hidden`'\" flag.\nEOF\ngh pr create --fill --body-file /tmp/body.md\"",
1535
+ output: "https://github.com/owner/repository/pull/62\n",
1536
+ linked: [62],
1537
+ },
1538
+ {
1539
+ name: "an older pull request read in the same command",
1540
+ input: "gh pr view 120 --json url --jq .url && gh pr create --fill",
1541
+ output:
1542
+ "https://github.com/owner/repository/pull/120\nhttps://github.com/owner/repository/pull/124",
1543
+ linked: [124],
1544
+ },
1545
+ {
1546
+ name: "both layers of a stack",
1547
+ input: "gh pr create --base main --head a --fill && gh pr create --base a --head b --fill",
1548
+ output:
1549
+ "https://github.com/owner/repository/pull/124\nhttps://github.com/owner/repository/pull/125",
1550
+ linked: [124, 125],
1551
+ },
1552
+ {
1553
+ name: "the first pull request of a new repository",
1554
+ input: "cargo test 2>&1 | tail -1 && timeout 60 gh pr create -R owner/repository --fill",
1555
+ output: "test result: ok\nhttps://github.com/owner/repository/pull/1",
1556
+ linked: [1],
1557
+ },
1558
+ {
1559
+ name: "a GitLab merge request",
1560
+ input: "glab mr create --fill --yes",
1561
+ output:
1562
+ "!3 Fix the thing (feature)\n https://gitlab.com/owner/repository/-/merge_requests/3\n",
1563
+ linked: [3],
1564
+ },
1565
+ {
1566
+ name: "a new pull request whose number appears in the create command",
1567
+ input: "timeout 60 gh pr create --fill",
1568
+ output: "https://github.com/owner/repository/pull/60",
1569
+ linked: [60],
1570
+ },
1571
+ {
1572
+ name: "a create subcommand that does not end its shell word",
1573
+ input: "gh pr create#typo; gh pr view --json url --jq .url",
1574
+ output: "https://github.com/owner/repository/pull/124",
1575
+ linked: [],
1576
+ },
1577
+ {
1578
+ name: "a create after an empty heredoc",
1579
+ input: "cat > /tmp/notes.md <<'EOF'\nEOF\ngh pr create --fill",
1580
+ output: "https://github.com/owner/repository/pull/124",
1581
+ linked: [124],
1582
+ },
1583
+ {
1584
+ name: "a read with no create",
1585
+ input: "gh pr view 124 --json url --jq .url",
1586
+ output: "https://github.com/owner/repository/pull/124",
1587
+ linked: [],
1588
+ },
1589
+ {
1590
+ name: "a create command quoted in another program's query",
1591
+ input: `sqlite3 audit.db "select output from items where input like '%gh pr create%'"`,
1592
+ output: "https://github.com/owner/repository/pull/124",
1593
+ linked: [],
1594
+ },
1595
+ {
1596
+ name: "a create command with a separator inside quotes",
1597
+ input: "echo 'example: gh pr create; gh pr create --fill' && gh pr view --json url --jq .url",
1598
+ output: "https://github.com/owner/repository/pull/124",
1599
+ linked: [],
1600
+ },
1601
+ {
1602
+ name: "more URLs than create commands",
1603
+ input: "gh pr view --json url --jq .url && gh pr create --fill",
1604
+ output:
1605
+ "https://github.com/owner/repository/pull/120\nhttps://github.com/owner/repository/pull/124",
1606
+ linked: [],
1607
+ },
1608
+ {
1609
+ name: "a create command only in heredoc text",
1610
+ input:
1611
+ "cat > notes.md <<'EOF'\nOpen it with gh pr create.\nEOF\ngh pr list --json url --jq '.[].url'",
1612
+ output: "https://github.com/owner/repository/pull/124",
1613
+ linked: [],
1614
+ },
1615
+ {
1616
+ name: "a create command after a comment that starts at a separator",
1617
+ input: "gh pr view --json url --jq .url;# note; gh pr create --fill",
1618
+ output: "https://github.com/owner/repository/pull/124",
1619
+ linked: [],
1620
+ },
1621
+ {
1622
+ name: "a create beside a command that lists other pull requests",
1623
+ input: "gh pr list --json url --jq '.[].url' && gh pr create --fill > /dev/null",
1624
+ output: "https://github.com/owner/repository/pull/120",
1625
+ linked: [],
1626
+ },
1627
+ {
1628
+ name: "another host's URL beside a create command",
1629
+ input: "gh pr create --fill",
1630
+ output: "https://gitlab.com/owner/repository/-/merge_requests/3",
1631
+ linked: [],
1632
+ },
1633
+ {
1634
+ name: "an existing pull request quoted in another command",
1635
+ input:
1636
+ "printf '%s\\n' 'https://github.com/owner/repository/pull/120'; gh pr create --fill > /dev/null",
1637
+ output: "https://github.com/owner/repository/pull/120",
1638
+ linked: [],
1639
+ },
1640
+ ])("links what the command created: $name", ({ input, output, linked }) =>
1641
+ Effect.scoped(
1642
+ Effect.gen(function* () {
1643
+ yield* TestClock.setTime(Date.parse(NOW));
1644
+ const fixture = yield* makeHarness({ snapshot: mergingSnapshot() });
1645
+
1646
+ yield* Effect.gen(function* () {
1647
+ const reactor = yield* startAndSweep(fixture);
1648
+ const child = ThreadId.make("delegated-child");
1649
+ const links = yield* linksFrom(fixture, reactor, [commandRan(child, input, output)]);
1650
+
1651
+ assert.deepStrictEqual(
1652
+ links.map((command) => [command.threadId, command.number, command.source]),
1653
+ linked.map((number) => [child, number, "created"]),
1654
+ );
1655
+ }).pipe(Effect.provide(fixture.layer));
1656
+ }),
1657
+ ),
1658
+ );
1659
+
1660
+ it.effect("links a created pull request once its command settles, with one command id", () =>
1661
+ Effect.scoped(
1662
+ Effect.gen(function* () {
1663
+ yield* TestClock.setTime(Date.parse(NOW));
1664
+ const fixture = yield* makeHarness({ snapshot: mergingSnapshot() });
1665
+
1666
+ yield* Effect.gen(function* () {
1667
+ const reactor = yield* startAndSweep(fixture);
1668
+ const settled = commandRan(
1669
+ ThreadId.make("agent"),
1670
+ "gh pr create --fill",
1671
+ "https://github.com/owner/repository/pull/124",
1672
+ );
1673
+ assert.strictEqual(settled.type, "turn-item.updated");
1674
+ if (settled.type !== "turn-item.updated") return;
1675
+
1676
+ const links = yield* linksFrom(fixture, reactor, [
1677
+ { ...settled, payload: { ...settled.payload, status: "running" } },
1678
+ settled,
1679
+ settled,
1680
+ ]);
1681
+
1682
+ assert.deepStrictEqual(
1683
+ links.map((command) => command.number),
1684
+ [124, 124],
1685
+ );
1686
+ assert.strictEqual(links[0]!.commandId, links[1]!.commandId);
1687
+ }).pipe(Effect.provide(fixture.layer));
1688
+ }),
1689
+ ),
1690
+ );
1691
});
apps/server/src/orchestration-v2/PullRequestSyncReactor.ts
+155
-5
@@ -1,6 +1,7 @@
1
import {
2
CommandId,
3
isOrchestrationV2WorkActive,
4
+ type OrchestrationV2TurnItem,
5
type PullRequestSummary,
6
type ThreadId,
7
type ThreadPullRequestKey,
@@ -49,6 +50,127 @@ const isChangeRequestCloseCommand = (command: string) =>
50
(definition) => definition.changeRequestCloseCommand?.test(command) === true,
51
);
52
53
+// Where a shell starts a command, past `NAME=value` assignments and wrappers like `timeout 60`.
54
+// A create command anywhere else, as in `echo "gh pr create"`, is text, not a command that runs.
55
+const COMMAND_START =
56
+ "(?:^|[;&|({`\\n]|\\b(?:do|then|else)\\s)\\s*(?:(?:\\w+=\\S*|env|time|nohup|timeout\\s+\\S+)\\s+)*";
57
+const CREATE_COMMANDS = sourceControlDefinitions.definitions.flatMap(
58
+ ({ kind, changeRequestCreateCommand: command }) =>
59
+ command === undefined
60
+ ? []
61
+ : // The subcommand must end its shell word: `gh pr create#x` runs another one.
62
+ [
63
+ {
64
+ kind,
65
+ command,
66
+ run: new RegExp(`${COMMAND_START}${command.source}(?=$|[\\s;&|)])`, "gu"),
67
+ },
68
+ ],
69
+);
70
+const createCommandCount = (code: string) =>
71
+ CREATE_COMMANDS.reduce((count, { run }) => count + [...code.matchAll(run)].length, 0);
72
+
73
+// Codex runs each command as `/bin/zsh -lc <script>`, quoting the script in pieces such as
74
+// `"a "'`b`'" c"`.
75
+const SHELL_WRAPPER = /^\s*(?:\S*\/)?(?:ba|z|da|k)?sh\s+-l?c\s+(?=["'])([\s\S]*)$/u;
76
+const SHELL_WORD_PIECE = /"((?:\\[\s\S]|[^"\\])*)"|'([^']*)'|\\([\s\S])|(\S)/gu;
77
+// Heredoc bodies, quoted strings and comments are text a command carries, not commands it runs.
78
+const HEREDOC_BODY =
79
+ /<<-?[ \t]*(['"]?)(\w+)\1[^\n]*\n(?:(?:[\s\S]*?\n)?[ \t]*\2[ \t]*(?=\n|$)|[\s\S]*$)/gu;
80
+const QUOTED_OR_COMMENT = /'[^']*'|"(?:\\[\s\S]|[^"\\])*"|(?<=^|[\s;&|(])#[^\n]*/gmu;
81
+const COMMAND_SEPARATOR = /&&|\|\||[;|\n]/u;
82
+// Commands that print other change requests' URLs, so output beside them proves nothing.
83
+const LISTS_CHANGE_REQUESTS =
84
+ /\b(?:gh\s+(?:pr\s+(?:list|status)|search\s+prs|api)|glab\s+(?:mr\s+list|api))\b/u;
85
+const URL_LINE = /^[ \t]*(https?:\/\/\S+)[ \t]*$/gmu;
86
+
87
+/** The script a shell input runs, unwrapped from Codex's `sh -lc`. */
88
+function shellScript(input: string): string {
89
+ const [, wrapped] = SHELL_WRAPPER.exec(input) ?? [];
90
+ return wrapped === undefined
91
+ ? input
92
+ : Array.from(
93
+ wrapped.matchAll(SHELL_WORD_PIECE),
94
+ ([, double, single, escaped, bare]) =>
95
+ double?.replace(/\\(["\\$`])/gu, "$1") ?? single ?? escaped ?? bare,
96
+ ).join("");
97
+}
98
+
99
+/** A script split at command separators that sit outside quotes. */
100
+function shellSegments(script: string): ReadonlyArray<string> {
101
+ const segments: Array<string> = [];
102
+ let current = "";
103
+ let quote: string | null = null;
104
+ for (let index = 0; index < script.length; index++) {
105
+ const char = script[index] ?? "";
106
+ if (quote !== null) {
107
+ current += char;
108
+ if (char === "\\" && quote === '"') current += script[++index] ?? "";
109
+ else if (char === quote) quote = null;
110
+ continue;
111
+ }
112
+ if (char === "'" || char === '"') quote = char;
113
+ if (char === "\\") {
114
+ current += char + (script[++index] ?? "");
115
+ continue;
116
+ }
117
+ const pair = script.slice(index, index + 2);
118
+ if (pair === "&&" || pair === "||" || char === ";" || char === "|" || char === "\n") {
119
+ segments.push(current);
120
+ current = "";
121
+ if (pair === "&&" || pair === "||") index++;
122
+ continue;
123
+ }
124
+ current += char;
125
+ }
126
+ segments.push(current);
127
+ return segments;
128
+}
129
+
130
+/** The commands a script runs, without the text it carries. */
131
+const shellCode = (script: string) =>
132
+ script.replace(HEREDOC_BODY, "<<").replace(QUOTED_OR_COMMENT, "''");
133
+
134
+type CommandExecution = Extract<OrchestrationV2TurnItem, { readonly type: "command_execution" }>;
135
+
136
+/**
137
+ * The change requests a shell command opened: URLs on lines of their own in the output of a
138
+ * command that runs a host's create command. One the command also names, as `gh pr view 12`
139
+ * does, existed before it ran. More URLs than create commands means something else printed
140
+ * some, such as `gh pr list`, so none are taken.
141
+ */
142
+function changeRequestsCreatedBy(input: string, output: string) {
143
+ if (!CREATE_COMMANDS.some(({ command }) => command.test(input))) return [];
144
+ const script = shellScript(input);
145
+ const code = shellCode(script);
146
+ const creates = createCommandCount(code);
147
+ if (creates === 0) return [];
148
+ const otherCommands = code
149
+ .split(COMMAND_SEPARATOR)
150
+ .filter((part) => createCommandCount(part) === 0)
151
+ .join("\n");
152
+ if (LISTS_CHANGE_REQUESTS.test(otherCommands)) return [];
153
+ const otherScript = shellSegments(script)
154
+ .filter((segment) => createCommandCount(shellCode(segment)) === 0)
155
+ .join("\n");
156
+ const creators = new Set(
157
+ CREATE_COMMANDS.filter(({ run }) => code.match(run) !== null).map(({ kind }) => kind),
158
+ );
159
+ const created = new Map<string, ThreadPullRequestKey & { readonly url: string }>();
160
+ for (const [, url = ""] of output.matchAll(URL_LINE)) {
161
+ const parsed = sourceControlDefinitions.parseChangeRequestUrl(url);
162
+ // Only the host whose create command ran can have printed a new change request.
163
+ if (parsed === null || !creators.has(parsed.definition.kind)) continue;
164
+ const { link } = parsed;
165
+ const named = new RegExp(`(?:^|(?<=[\\s#/=("']))${link.number}(?=$|[\\s);&|/"'])`, "u");
166
+ // Quoted text in the other commands counts, as in `printf '.../pull/12'`.
167
+ if (named.test(otherScript)) continue;
168
+ const key = normalizeThreadPullRequestKey(link);
169
+ created.set(threadPullRequestKeyOf(key), { ...key, url });
170
+ }
171
+ return created.size > creates ? [] : [...created.values()];
172
+}
173
+
174
const isPullRequestProviderError = Schema.is(PullRequestProviderError);
175
176
type SnapshotFields = Omit<ThreadPullRequestSnapshot, "syncedAt">;
@@ -500,6 +622,34 @@ export const make = Effect.gen(function* () {
622
Effect.catchCause(logSkipped("pull request refresh after run skipped", { threadId })),
623
);
624
625
+ // An agent that opens a pull request from a shell gets it linked as link_pull_request would.
626
+ const linkCreatedChangeRequests = Effect.fn("PullRequestSyncReactor.linkCreatedChangeRequests")(
627
+ function* (threadId: ThreadId, item: CommandExecution) {
628
+ if (isOrchestrationV2WorkActive(item.status)) return;
629
+ yield* Effect.forEach(
630
+ changeRequestsCreatedBy(item.input, item.output ?? ""),
631
+ (created) =>
632
+ engine
633
+ .dispatch({
634
+ type: "thread.pull-request.link",
635
+ // Stable per command, so a repeated settlement cannot relink one the user unlinked.
636
+ commandId: CommandId.make(
637
+ `server:pr-created-link:${threadId}:${item.id}:${threadPullRequestKeyOf(created)}`,
638
+ ),
639
+ threadId,
640
+ ...created,
641
+ source: "created",
642
+ })
643
+ .pipe(
644
+ Effect.catchCause(
645
+ logSkipped("linking a pull request a command created failed", { threadId }),
646
+ ),
647
+ ),
648
+ { discard: true },
649
+ );
650
+ },
651
+ );
652
+
653
const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
654
"PullRequestSyncReactor.start",
655
)(function* () {
@@ -532,14 +682,14 @@ export const make = Effect.gen(function* () {
682
// ends. Read again when the run ends, since `merge --auto` returns before it merges.
683
case "turn-item.updated": {
684
const item = event.payload;
535
- if (item.type !== "command_execution" || !isChangeRequestCloseCommand(item.input)) {
536
- return Effect.void;
537
- }
685
+ if (item.type !== "command_execution") return Effect.void;
686
+ const linked = linkCreatedChangeRequests(event.threadId, item);
687
+ if (!isChangeRequestCloseCommand(item.input)) return linked;
688
const ended = closeCommands.get(event.threadId) ?? new Set<string>();
689
closeCommands.set(event.threadId, ended);
540
- if (isOrchestrationV2WorkActive(item.status) || ended.has(item.id)) return Effect.void;
690
+ if (isOrchestrationV2WorkActive(item.status) || ended.has(item.id)) return linked;
691
ended.add(item.id);
542
- return refreshOpenLinks(event.threadId);
692
+ return Effect.andThen(linked, refreshOpenLinks(event.threadId));
693
}
694
case "run.updated":
695
return isTerminalRunStatus(event.payload.status) && closeCommands.delete(event.threadId)
docs/user/source-control.md
+3
-2
@@ -266,8 +266,9 @@ and their marks follow the same rules as on web and desktop.
266
267
A thread can hold several pull requests, including reviews from another repository on the same host.
268
Use **Link pull request** in the command palette or **Linked pull requests** panel, or right-click a
269
-pull request link in the conversation. Creating a pull request from Git actions links it automatically.
270
-Agents can link their pull requests with the `link_pull_request` tool.
269
+pull request link in the conversation. Creating a pull request from Git actions links it automatically,
270
+and so does an agent creating one with `gh pr create` or `glab mr create`. Agents can link other
271
+pull requests with the `link_pull_request` tool.
272
273
Use **Link this PR** in a branch-detected badge's tooltip to keep it with the thread. From a review
274
on the Pull Requests page, **Link to thread** lets you search for an active thread. The review header
packages/source-control-core/src/shared/definition.ts
+5
@@ -234,6 +234,11 @@ export interface SourceControlDefinition {
234
* sends T3 no notification of its own. Absent for a host with no such CLI.
235
*/
236
readonly changeRequestCloseCommand?: RegExp;
237
+ /**
238
+ * Matches a shell command that opens a change request with this host's CLI and prints its URL
239
+ * on a line of its own. Absent for a host with no such CLI.
240
+ */
241
+ readonly changeRequestCreateCommand?: RegExp;
242
readonly authorProfileUrl: (login: string, repositoryUrl: string) => string | null;
243
/**
244
* The references this host's own renderer links in plain text, such as `#12` or a commit SHA,
packages/source-control-github/src/shared/definition.ts
+1
@@ -105,6 +105,7 @@ export const definition = defineSourceControl({
105
] as const),
106
checkoutCommand: ({ number }) => `gh pr checkout ${number}`,
107
changeRequestCloseCommand: /\bgh\s+(?:pr\s+(?:merge|close)|stack\s+merge)\b/u,
108
+ changeRequestCreateCommand: /\bgh\s+pr\s+create\b/u,
109
authorProfileUrl: (login, repositoryUrl) =>
110
login.endsWith("[bot]")
111
? null
packages/source-control-gitlab/src/shared/definition.ts
+1
@@ -53,6 +53,7 @@ export const definition = defineSourceControl({
53
] as const),
54
checkoutCommand: ({ number }) => `glab mr checkout ${number}`,
55
changeRequestCloseCommand: /\bglab\s+mr\s+(?:merge|close)\b/u,
56
+ changeRequestCreateCommand: /\bglab\s+mr\s+create\b/u,
57
authorProfileUrl: () => null,
58
reviewSummaryRequired: () => false,
59
checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,