The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 19:45 UTC
fix(server): a pass that changes several watched pull requests wakes their thread once (#35109)
Julius Marminge committed
Nov 12, 2026 at 02:59 UTC
1de3c3c68c4b886c52ddee49cdb32c4e3150d39b
5 files changed
+481
-78
apps/server/src/orchestration-v2/Orchestrator.ts
+149
-45
@@ -34,6 +34,7 @@ import {
34
OrchestrationV2Command,
35
type OrchestrationV2InternalCommand,
36
type OrchestrationV2LimitRecoveryUpdate,
37
+ type OrchestrationV2Notification,
38
type OrchestrationV2ServerCommand,
39
type ThreadPullRequestLink,
40
type ThreadPullRequestWatch,
@@ -80,6 +81,7 @@ import {
81
import * as KeyedLock from "@t3tools/shared/KeyedLock";
82
import { modelSelectionsEqual } from "@t3tools/shared/model";
83
import { modelSwitchSince } from "./modelSwitch.ts";
84
+import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts";
85
import { recordThreadOpen } from "@t3tools/shared/paletteSearch";
86
import {
87
backgroundWorkHoldsCompletion,
@@ -964,14 +966,21 @@ function pullRequestSnapshotEndsWatch(
966
);
967
}
968
967
-function isStalePullRequestWatchWake(
969
+type MonitorPullRequestStamp = NonNullable<
970
+ Extract<OrchestrationV2Notification["source"], { readonly kind: "monitor" }>["pullRequest"]
971
+>;
972
+
973
+function monitorPullRequestStamps(
974
+ source: OrchestrationV2Notification["source"] | undefined,
975
+): ReadonlyArray<MonitorPullRequestStamp> {
976
+ if (source?.kind !== "monitor" || source.pullRequest === undefined) return [];
977
+ return [source.pullRequest, ...(source.otherPullRequests ?? [])];
978
+}
979
+
980
+function isStalePullRequestWatchStamp(
981
projection: Pick<OrchestrationV2ThreadProjection, "thread" | "messages">,
969
- run: OrchestrationV2Run,
982
+ stamp: MonitorPullRequestStamp,
983
): boolean {
971
- const source = projection.messages.find((message) => message.id === run.userMessageId)
972
- ?.notification?.source;
973
- if (source?.kind !== "monitor" || source.pullRequest === undefined) return false;
974
- const stamp = source.pullRequest;
984
const link = threadPullRequestsOf(projection.thread).find(
985
(candidate) =>
986
candidate.source !== "stack-dismissed" && threadPullRequestKeysEqual(candidate, stamp),
@@ -984,15 +993,14 @@ function isStalePullRequestWatchWake(
993
}
994
if (link.watch === undefined) {
995
// A watch the server ended with a final notice still owes the wakes it queued before it.
987
- const endedWithNotice = projection.messages.some((message) => {
988
- const ending = message.notification?.source;
989
- return (
990
- ending?.kind === "monitor" &&
991
- ending.pullRequest?.watchEnded === true &&
992
- ending.pullRequest.watchStartedAt === stamp.watchStartedAt &&
993
- threadPullRequestKeysEqual(ending.pullRequest, stamp)
994
- );
995
- });
996
+ const endedWithNotice = projection.messages.some((message) =>
997
+ monitorPullRequestStamps(message.notification?.source).some(
998
+ (ending) =>
999
+ ending.watchEnded === true &&
1000
+ ending.watchStartedAt === stamp.watchStartedAt &&
1001
+ threadPullRequestKeysEqual(ending, stamp),
1002
+ ),
1003
+ );
1004
return (
1005
!endedWithNotice ||
1006
link.endedWatch?.startedAt !== stamp.watchStartedAt ||
@@ -1006,6 +1014,58 @@ function isStalePullRequestWatchWake(
1014
);
1015
}
1016
1017
+function isStalePullRequestWatchWake(
1018
+ projection: Pick<OrchestrationV2ThreadProjection, "thread" | "messages">,
1019
+ run: OrchestrationV2Run,
1020
+): boolean {
1021
+ const stamps = monitorPullRequestStamps(
1022
+ projection.messages.find((message) => message.id === run.userMessageId)?.notification?.source,
1023
+ );
1024
+ return (
1025
+ stamps.length > 0 && stamps.every((stamp) => isStalePullRequestWatchStamp(projection, stamp))
1026
+ );
1027
+}
1028
+
1029
+/**
1030
+ * A queued wake covering several pull requests, rebuilt from the ones still current, or
1031
+ * undefined when it needs no change.
1032
+ */
1033
+function currentPullRequestWatchWake(
1034
+ projection: Pick<OrchestrationV2ThreadProjection, "thread" | "messages">,
1035
+ run: OrchestrationV2Run,
1036
+): OrchestrationV2ConversationMessage | undefined {
1037
+ const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
1038
+ const stamps = monitorPullRequestStamps(message?.notification?.source);
1039
+ if (message === undefined || stamps.length < 2) return undefined;
1040
+ const current = stamps.filter((stamp) => !isStalePullRequestWatchStamp(projection, stamp));
1041
+ const [first, ...rest] = current;
1042
+ if (first === undefined || rest.length === stamps.length - 1) return undefined;
1043
+ const sections = current.flatMap(({ section }) => (section === undefined ? [] : [section]));
1044
+ if (sections.length !== current.length) return undefined;
1045
+ const wake = combinePullRequestWatchWakes(
1046
+ sections.map(({ text, outcome, summary }) => ({
1047
+ text,
1048
+ notification: { source: { kind: "monitor" }, outcome, summary },
1049
+ })) as [PullRequestWatchWake, ...Array<PullRequestWatchWake>],
1050
+ );
1051
+ return {
1052
+ ...message,
1053
+ text: wake.text,
1054
+ notification: {
1055
+ ...wake.notification,
1056
+ source: {
1057
+ kind: "monitor",
1058
+ pullRequest: rest.length === 0 ? withoutSection(first) : first,
1059
+ ...(rest.length === 0 ? {} : { otherPullRequests: rest }),
1060
+ },
1061
+ },
1062
+ };
1063
+}
1064
+
1065
+function withoutSection({ section: _, ...stamp }: MonitorPullRequestStamp) {
1066
+ return stamp;
1067
+}
1068
+
1069
function queuedRunCancellationEvents(
1070
projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "attempts">,
1071
run: OrchestrationV2Run,
@@ -2117,6 +2177,28 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2177
projection = yield* readCommandProjection(threadId);
2178
storedQueuedRun = nextQueuedRun(projection);
2179
}
2180
+ // A wake that outlived some of its pull requests tells only the current ones.
2181
+ const currentWake =
2182
+ storedQueuedRun === undefined
2183
+ ? undefined
2184
+ : currentPullRequestWatchWake(projection, storedQueuedRun);
2185
+ if (storedQueuedRun !== undefined && currentWake !== undefined) {
2186
+ const now = yield* DateTime.now;
2187
+ yield* writeSystemEvents([
2188
+ {
2189
+ type: "message.updated",
2190
+ threadId,
2191
+ runId: storedQueuedRun.id,
2192
+ ...(storedQueuedRun.rootNodeId === null ? {} : { nodeId: storedQueuedRun.rootNodeId }),
2193
+ providerInstanceId: storedQueuedRun.providerInstanceId,
2194
+ occurredAt: now,
2195
+ payload: { ...currentWake, updatedAt: now },
2196
+ },
2197
+ ]);
2198
+ const runId = storedQueuedRun.id;
2199
+ projection = yield* readCommandProjection(threadId);
2200
+ storedQueuedRun = projection.runs.find((run) => run.id === runId);
2201
+ }
2202
if (storedQueuedRun === undefined) {
2203
return;
2204
}
@@ -3554,57 +3636,79 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
3636
(cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
3637
),
3638
);
3557
- const key = normalizeThreadPullRequestKey(command);
3558
- const link = threadPullRequestsOf(thread).find(
3559
- (candidate) =>
3560
- candidate.source !== "stack-dismissed" && threadPullRequestKeysEqual(candidate, key),
3561
- );
3639
+ const { others = [], wake, ...primary } = command;
3640
+ const entries = [
3641
+ { ...primary, includesRemarks: wake?.includesRemarks },
3642
+ ...others.map((other) => ({
3643
+ type: primary.type,
3644
+ commandId: primary.commandId,
3645
+ threadId: primary.threadId,
3646
+ ...other,
3647
+ })),
3648
+ ].map((entry) => {
3649
+ const key = normalizeThreadPullRequestKey(entry);
3650
+ const link = threadPullRequestsOf(thread).find(
3651
+ (candidate) =>
3652
+ candidate.source !== "stack-dismissed" && threadPullRequestKeysEqual(candidate, key),
3653
+ );
3654
+ return { entry, key, link };
3655
+ });
3656
const inactive =
3657
thread.archivedAt !== null ||
3658
thread.settledOverride === "settled" ||
3659
thread.settledAt !== null ||
3660
isProviderNativeSubagentThread(thread);
3567
- if (link?.watch?.startedAt !== command.startedAt || (command.wake && inactive)) {
3661
+ // An idle thread dispatches immediately, bypassing queued-wake validation.
3662
+ const outdated = entries.map(
3663
+ ({ entry, link }) =>
3664
+ wake?.notification.source.kind === "monitor" &&
3665
+ entry.watch !== null &&
3666
+ pullRequestSnapshotEndsWatch(link?.snapshot ?? null, entry.startedAt),
3667
+ );
3668
+ if (
3669
+ entries.some(({ entry, link }) => link?.watch?.startedAt !== entry.startedAt) ||
3670
+ (wake && inactive) ||
3671
+ // One wake cannot drop the news of just some of its pull requests; the sender splits it.
3672
+ (entries.length > 1 && outdated.some(Boolean))
3673
+ ) {
3674
return yield* new OrchestratorDispatchError({
3675
commandId: command.commandId,
3676
commandType: command.type,
3677
cause: "The pull request watch ended or its thread settled while it was read.",
3678
});
3679
}
3574
- yield* dispatchThreadMutation(command, events, effects);
3575
- if (command.wake === undefined) return;
3576
- // An idle thread dispatches immediately, bypassing queued-wake validation.
3577
- if (
3578
- command.wake.notification.source.kind === "monitor" &&
3579
- command.watch !== null &&
3580
- pullRequestSnapshotEndsWatch(link.snapshot, command.startedAt)
3581
- ) {
3582
- return;
3583
- }
3680
+ for (const { entry } of entries) {
3681
+ const { includesRemarks: _, ...mutation } = entry;
3682
+ yield* dispatchThreadMutation(mutation, events, effects);
3683
+ }
3684
+ if (wake === undefined || outdated[0]) return;
3685
+ const { sections, ...wakeMessage } = wake;
3686
+ const stamps = entries.map(({ entry, key }, index) => ({
3687
+ ...key,
3688
+ watchStartedAt: entry.startedAt,
3689
+ headSha: entry.includesRemarks === true ? null : (entry.watch?.headSha ?? null),
3690
+ ...(entry.watch === null ? { watchEnded: true } : {}),
3691
+ ...(entries.length > 1 && sections?.[index] !== undefined
3692
+ ? { section: sections[index] }
3693
+ : {}),
3694
+ }));
3695
yield* dispatchMessage(
3696
{
3697
type: "message.dispatch",
3698
commandId: command.commandId,
3699
threadId: command.threadId,
3589
- messageId: command.wake.messageId,
3590
- text: command.wake.text,
3700
+ messageId: wakeMessage.messageId,
3701
+ text: wakeMessage.text,
3702
notification: {
3592
- ...command.wake.notification,
3703
+ ...wakeMessage.notification,
3704
source:
3594
- command.wake.notification.source.kind === "monitor"
3705
+ wake.notification.source.kind === "monitor"
3706
? {
3707
kind: "monitor",
3597
- pullRequest: {
3598
- ...key,
3599
- watchStartedAt: command.startedAt,
3600
- headSha:
3601
- command.wake.includesRemarks === true
3602
- ? null
3603
- : (command.watch?.headSha ?? null),
3604
- ...(command.watch === null ? { watchEnded: true } : {}),
3605
- },
3708
+ pullRequest: stamps[0]!,
3709
+ ...(stamps.length > 1 ? { otherPullRequests: stamps.slice(1) } : {}),
3710
}
3607
- : command.wake.notification.source,
3711
+ : wake.notification.source,
3712
},
3713
attachments: [],
3714
dispatchMode: { type: "queue_after_active" },
apps/server/src/orchestration-v2/PullRequestWatchReactor.ts
+125
-22
@@ -38,6 +38,7 @@ import { forkParked } from "../serverActivation.ts";
38
import * as Orchestrator from "./Orchestrator.ts";
39
import * as ProjectionStore from "./ProjectionStore.ts";
40
import {
41
+ combinePullRequestWatchWakes,
42
evaluatePullRequestWatch,
43
PULL_REQUEST_WATCH_NO_CHECKS_MS,
44
pullRequestWatchMessage,
@@ -98,6 +99,22 @@ interface ReadPlan {
99
readonly activity: boolean;
100
}
101
102
+interface Wake {
103
+ readonly text: string;
104
+ readonly notification: OrchestrationV2Notification;
105
+ readonly includesRemarks?: boolean;
106
+}
107
+
108
+/** A wake a pass holds back so each thread gets one for everything the pass found. */
109
+interface HeldWake {
110
+ readonly groupKey: string;
111
+ readonly target: WatchTarget;
112
+ readonly next: ThreadPullRequestWatch | null;
113
+ readonly endedWatch?: ThreadPullRequestWatch;
114
+ readonly wake: Wake;
115
+ readonly reason?: WatchEndReason;
116
+}
117
+
118
const watchKey = ({ thread, watch }: WatchTarget) => `${thread.id} ${watch.startedAt}`;
119
120
type WatchEndReason =
@@ -284,11 +301,7 @@ export const make = Effect.gen(function* () {
301
const record = Effect.fn("PullRequestWatchReactor.record")(function* (
302
target: WatchTarget,
303
next: ThreadPullRequestWatch | null,
287
- wake?: {
288
- readonly text: string;
289
- readonly notification: OrchestrationV2Notification;
290
- readonly includesRemarks?: boolean;
291
- },
304
+ wake?: Wake,
305
endedWatch?: ThreadPullRequestWatch,
306
) {
307
const uuid = yield* random.uuidV4();
@@ -411,18 +424,102 @@ export const make = Effect.gen(function* () {
424
),
425
);
426
414
- const closed = (target: WatchTarget) =>
415
- record(target, null, {
416
- text: `Pull request #${target.link.number} (${target.link.url}) was closed, so T3 Code stopped watching it. Call watch_pull_request if it reopens.`,
417
- notification: {
418
- source: { kind: "monitor" },
419
- outcome: "updated",
420
- summary: `#${target.link.number}: closed, stopped watching`,
427
+ /** Wakes the current pass found, sent by `sendHeld` once every read of the pass is done. */
428
+ let held: Array<HeldWake> = [];
429
+ const hold = (wake: HeldWake) => Effect.sync(() => void held.push(wake));
430
+
431
+ const sendOne = (item: HeldWake) =>
432
+ record(item.target, item.next, item.wake, item.endedWatch).pipe(
433
+ Effect.tap(() => woke(item.target)),
434
+ Effect.tap(() => (item.reason === undefined ? Effect.void : ended(item.target, item.reason))),
435
+ Effect.catchCause((cause) => {
436
+ lastReads.delete(item.groupKey);
437
+ return logFailure("pull request watch update failed", {
438
+ threadId: item.target.thread.id,
439
+ pullRequest: item.groupKey,
440
+ })(cause);
441
+ }),
442
+ );
443
+
444
+ const sendTogether = Effect.fn("PullRequestWatchReactor.sendTogether")(function* (
445
+ items: readonly [HeldWake, ...ReadonlyArray<HeldWake>],
446
+ ) {
447
+ const [first, ...rest] = items;
448
+ const uuid = yield* random.uuidV4();
449
+ yield* engine.dispatch({
450
+ type: "thread.pull-request-watch.sync",
451
+ commandId: CommandId.make(`server:pr-watch:${first.target.thread.id}:${uuid}`),
452
+ threadId: first.target.thread.id,
453
+ ...identityOf(first.target.link),
454
+ startedAt: first.target.watch.startedAt,
455
+ watch: first.next,
456
+ ...(first.endedWatch === undefined ? {} : { endedWatch: first.endedWatch }),
457
+ others: rest.map((item) => ({
458
+ ...identityOf(item.target.link),
459
+ startedAt: item.target.watch.startedAt,
460
+ watch: item.next,
461
+ ...(item.endedWatch === undefined ? {} : { endedWatch: item.endedWatch }),
462
+ ...(item.wake.includesRemarks === true ? { includesRemarks: true } : {}),
463
+ })),
464
+ wake: {
465
+ ...combinePullRequestWatchWakes([first.wake, ...rest.map((item) => item.wake)]),
466
+ ...(first.wake.includesRemarks === true ? { includesRemarks: true } : {}),
467
+ sections: items.map(({ wake }) => ({
468
+ text: wake.text,
469
+ outcome: wake.notification.outcome,
470
+ summary: wake.notification.summary,
471
+ })),
472
+ messageId: MessageId.make(`message:pr-watch:${uuid}`),
473
},
422
- }).pipe(
423
- Effect.tap(() => woke(target)),
424
- Effect.tap(() => ended(target, "closed")),
474
+ });
475
+ yield* Effect.forEach(
476
+ items,
477
+ (item) =>
478
+ woke(item.target).pipe(
479
+ Effect.andThen(item.reason === undefined ? Effect.void : ended(item.target, item.reason)),
480
+ ),
481
+ { discard: true },
482
);
483
+ });
484
+
485
+ const sendHeld = Effect.suspend(() => {
486
+ const byThread = new Map<string, Array<HeldWake>>();
487
+ for (const item of held) {
488
+ byThread.set(item.target.thread.id, [...(byThread.get(item.target.thread.id) ?? []), item]);
489
+ }
490
+ held = [];
491
+ return Effect.forEach(
492
+ byThread.values(),
493
+ ([first, ...rest]) =>
494
+ rest.length === 0
495
+ ? sendOne(first!)
496
+ : // A watch that ended or moved during the pass fails the whole command; each then
497
+ // goes on its own, as the orchestrator decides for it alone.
498
+ sendTogether([first!, ...rest]).pipe(
499
+ Effect.catchCauseIf(
500
+ (cause) => !Cause.hasInterruptsOnly(cause),
501
+ () => Effect.forEach([first!, ...rest], sendOne, { discard: true }),
502
+ ),
503
+ ),
504
+ { discard: true },
505
+ );
506
+ });
507
+
508
+ const closed = (groupKey: string, target: WatchTarget) =>
509
+ hold({
510
+ groupKey,
511
+ target,
512
+ next: null,
513
+ wake: {
514
+ text: `Pull request #${target.link.number} (${target.link.url}) was closed, so T3 Code stopped watching it. Call watch_pull_request if it reopens.`,
515
+ notification: {
516
+ source: { kind: "monitor" },
517
+ outcome: "updated",
518
+ summary: `#${target.link.number}: closed, stopped watching`,
519
+ },
520
+ },
521
+ reason: "closed",
522
+ });
523
524
const endsWithoutRead = ({ thread, link }: WatchTarget): WatchEndReason | undefined =>
525
link.snapshot?.state === "merged"
@@ -545,7 +642,7 @@ export const make = Effect.gen(function* () {
642
lastReads.delete(group.key);
643
return yield* eachTarget(group, (target) =>
644
detail.state === "closed"
548
- ? closed(target)
645
+ ? closed(group.key, target)
646
: record(target, null).pipe(Effect.tap(() => ended(target, "merged"))),
647
);
648
}
@@ -588,13 +685,17 @@ export const make = Effect.gen(function* () {
685
includesRemarks: report.changes.some((change) => change.kind === "remarks"),
686
};
687
// An ending watch keeps what this pass saw, so watching again starts from it.
591
- return (
688
+ return hold(
689
report.exhausted
593
- ? record(target, null, wake, report.next)
594
- : record(target, report.next, wake)
595
- ).pipe(
596
- Effect.tap(() => woke(target)),
597
- Effect.tap(() => (report.exhausted ? ended(target, "comment-limit") : Effect.void)),
690
+ ? {
691
+ groupKey: group.key,
692
+ target,
693
+ next: null,
694
+ endedWatch: report.next,
695
+ wake,
696
+ reason: "comment-limit",
697
+ }
698
+ : { groupKey: group.key, target, next: report.next, wake },
699
);
700
}
701
return watchesEqual(report.next, target.watch) ? Effect.void : record(target, report.next);
@@ -604,6 +705,7 @@ export const make = Effect.gen(function* () {
705
/** Every watch, or with `changed`, only that pull request's after its host reported a change. */
706
// The sweep and change reads each name their own span.
707
const pass = Effect.fnUntraced(function* (changed: string | undefined) {
708
+ held = [];
709
const threads = yield* projections.getThreadsWithPullRequests();
710
const targets = threads.flatMap((thread) =>
711
visibleThreadPullRequests(thread.pullRequests ?? []).flatMap((link) =>
@@ -697,6 +799,7 @@ export const make = Effect.gen(function* () {
799
),
800
{ concurrency: "unbounded", discard: true },
801
);
802
+ yield* sendHeld;
803
}, passes.withPermit);
804
805
const sweep = pass(undefined).pipe(
apps/server/src/orchestration-v2/pullRequestWatch.ts
+38
-1
@@ -279,6 +279,43 @@ const SUMMARY: Record<PullRequestWatchChange["kind"], string> = {
279
conflicting: "merge conflict",
280
};
281
282
+const WATCHING_CLOSING =
283
+ "Look into each item and act on it as your task requires. This PR stays linked and watched, so do not link, watch, or list it again. End your turn when you are done, and T3 Code wakes you on the next change. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox.";
284
+const WATCHING_CLOSING_PLURAL =
285
+ "Look into each item and act on it as your task requires. Each PR T3 Code still watches stays linked and watched, so do not link, watch, or list them again. End your turn when you are done, and T3 Code wakes you on the next change. When you hand the work back to the user, call unwatch_pull_request for each first so the thread returns to their inbox.";
286
+
287
+export interface PullRequestWatchWake {
288
+ readonly text: string;
289
+ readonly notification: OrchestrationV2Notification;
290
+}
291
+
292
+/** One wake for news on several pull requests, with the closing instructions said once. */
293
+export function combinePullRequestWatchWakes(
294
+ wakes: readonly [PullRequestWatchWake, ...ReadonlyArray<PullRequestWatchWake>],
295
+): PullRequestWatchWake {
296
+ if (wakes.length === 1) return wakes[0];
297
+ const closing = `\n\n${WATCHING_CLOSING}`;
298
+ const watching = wakes.some((wake) => wake.text.endsWith(closing));
299
+ const outcomes = wakes.map((wake) => wake.notification.outcome);
300
+ return {
301
+ text: [
302
+ ...wakes.map((wake) =>
303
+ wake.text.endsWith(closing) ? wake.text.slice(0, -closing.length) : wake.text,
304
+ ),
305
+ ...(watching ? [WATCHING_CLOSING_PLURAL] : []),
306
+ ].join("\n\n"),
307
+ notification: {
308
+ source: { kind: "monitor" },
309
+ outcome: outcomes.includes("failed")
310
+ ? "failed"
311
+ : outcomes.every((outcome) => outcome === "completed")
312
+ ? "completed"
313
+ : "updated",
314
+ summary: wakes.map((wake) => wake.notification.summary).join("; "),
315
+ },
316
+ };
317
+}
318
+
319
export function pullRequestWatchMessage(input: {
320
readonly number: number;
321
readonly url: string;
@@ -297,7 +334,7 @@ export function pullRequestWatchMessage(input: {
334
"",
335
exhausted
336
? `T3 Code stopped watching after ${PULL_REQUEST_WATCH_WAKE_LIMIT} comment-only updates in a row. Call watch_pull_request to watch it again.`
300
- : "Look into each item and act on it as your task requires. This PR stays linked and watched, so do not link, watch, or list it again. End your turn when you are done, and T3 Code wakes you on the next change. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox.",
337
+ : WATCHING_CLOSING,
338
].join("\n");
339
const failed = changes.some(
340
(change) => change.kind === "checks-failed" || change.kind === "conflicting",
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+129
@@ -4094,6 +4094,135 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
4094
}),
4095
);
4096
4097
+ it.effect.each([
4098
+ ["an idle", false],
4099
+ ["a busy", true],
4100
+ ] as const)(
4101
+ "wakes %s thread once for a pass that changed several of its pull requests",
4102
+ ([, busy]) =>
4103
+ Effect.gen(function* () {
4104
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
4105
+ const threadId = ThreadId.make(`runtime-pull-request-watch-pass-${busy}`);
4106
+ const projectId = ProjectId.make(`pr-watch-pass-project-${busy}`);
4107
+ yield* seedProject({
4108
+ projectId,
4109
+ title: "Watch pass",
4110
+ workspaceRoot: "/workspace/watch-pass",
4111
+ defaultModelSelection: null,
4112
+ createdAt: "2026-10-01T00:00:00.000Z",
4113
+ });
4114
+ yield* orchestrator.dispatch({
4115
+ type: "thread.create",
4116
+ createdBy: "user",
4117
+ creationSource: "web",
4118
+ commandId: CommandId.make(`pr-watch-pass-create-${busy}`),
4119
+ threadId,
4120
+ projectId,
4121
+ title: "Watch pass",
4122
+ modelSelection,
4123
+ runtimeMode: "full-access",
4124
+ interactionMode: "default",
4125
+ branch: null,
4126
+ worktreePath: null,
4127
+ });
4128
+ const numbers = [12, 13, 14];
4129
+ for (const number of numbers) {
4130
+ yield* orchestrator.dispatch({
4131
+ type: "thread.pull-request.watch",
4132
+ commandId: CommandId.make(`pr-watch-pass-start-${busy}-${number}`),
4133
+ threadId,
4134
+ host: "github.com",
4135
+ repository: "pingdotgg/t3code",
4136
+ number,
4137
+ watching: true,
4138
+ link: { url: `https://github.com/pingdotgg/t3code/pull/${number}`, source: "agent" },
4139
+ });
4140
+ }
4141
+ if (busy) {
4142
+ yield* orchestrator.dispatch({
4143
+ type: "message.dispatch",
4144
+ createdBy: "user",
4145
+ creationSource: "web",
4146
+ commandId: CommandId.make("pr-watch-pass-busy"),
4147
+ threadId,
4148
+ messageId: MessageId.make("pr-watch-pass-busy"),
4149
+ text: "Keep this run active.",
4150
+ attachments: [],
4151
+ modelSelection,
4152
+ dispatchMode: { type: "start_immediately" },
4153
+ });
4154
+ }
4155
+ const host = Layer.mergeAll(
4156
+ NodeServices.layer,
4157
+ NodeCrypto.layer,
4158
+ Layer.mock(PullRequestService.PullRequestService)({
4159
+ detail: (input) =>
4160
+ Effect.succeed({
4161
+ ...watchedPullRequestDetail({
4162
+ projectId,
4163
+ number: input.number,
4164
+ at: "2026-10-02T12:00:00.000Z",
4165
+ }),
4166
+ headSha: `head${input.number}`,
4167
+ checks: [
4168
+ { name: "test", status: "failure", description: null, url: null, required: true },
4169
+ ],
4170
+ }),
4171
+ activity: () =>
4172
+ Effect.succeed({
4173
+ comments: [],
4174
+ commentCount: 0,
4175
+ commentsTruncated: false,
4176
+ reviewThreads: [],
4177
+ commits: [],
4178
+ }),
4179
+ }),
4180
+ );
4181
+
4182
+ const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host));
4183
+ yield* reactor.sweep;
4184
+ const { messages } = yield* orchestrator.getThreadRecords(threadId, ["messages"]);
4185
+ const wakes = messages.filter((message) => message.notification !== undefined);
4186
+ const stamps = wakes.map(({ notification }) =>
4187
+ notification?.source.kind === "monitor"
4188
+ ? [notification.source.pullRequest, ...(notification.source.otherPullRequests ?? [])]
4189
+ .map((stamp) => stamp?.number)
4190
+ .toSorted()
4191
+ : [],
4192
+ );
4193
+ assert.deepEqual(stamps, [numbers]);
4194
+ for (const number of numbers) assert.include(wakes[0]!.text, `#${number}`);
4195
+ if (!busy) return;
4196
+
4197
+ // A pull request unwatched while the wake waited leaves it; the others still start.
4198
+ yield* orchestrator.dispatch({
4199
+ type: "thread.pull-request.watch",
4200
+ commandId: CommandId.make("pr-watch-pass-stop-12"),
4201
+ threadId,
4202
+ host: "github.com",
4203
+ repository: "pingdotgg/t3code",
4204
+ number: 12,
4205
+ watching: false,
4206
+ });
4207
+ const active = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
4208
+ yield* orchestrator.dispatch({
4209
+ type: "run.interrupt",
4210
+ commandId: CommandId.make("pr-watch-pass-interrupt"),
4211
+ threadId,
4212
+ runId: active.id,
4213
+ });
4214
+ yield* orchestrator.resumeQueuedRuns;
4215
+ const after = yield* orchestrator.getThreadProjection(threadId);
4216
+ const woken = after.messages.find((message) => message.id === wakes[0]!.id)!;
4217
+ assert.notInclude(woken.text, "#12");
4218
+ for (const number of [13, 14]) assert.include(woken.text, `#${number}`);
4219
+ assert.notEqual(
4220
+ after.runs.find((run) => run.userMessageId === woken.id)?.status,
4221
+ "cancelled",
4222
+ );
4223
+ }),
4224
+ );
4225
+
4226
it.effect.each(["pending", "action-required"] as const)("recovers %s watches", (initialStatus) =>
4227
Effect.gen(function* () {
4228
const orchestrator = yield* Orchestrator.OrchestratorV2;
packages/contracts/src/orchestrationV2.ts
+40
-10
@@ -1260,6 +1260,28 @@ const SubagentNotificationSource = Schema.Struct({
1260
childThreadId: Schema.optional(ThreadId),
1261
});
1262
const CommandNotificationSource = Schema.Struct({ kind: Schema.Literal("command") });
1263
+const OrchestrationV2NotificationOutcome = Schema.Literals([
1264
+ "completed",
1265
+ "failed",
1266
+ "cancelled",
1267
+ "updated",
1268
+ "unknown",
1269
+]);
1270
+/** One pull request's part of a wake, which stands alone once the others are outdated. */
1271
+const PullRequestWakeSection = Schema.Struct({
1272
+ text: Schema.String,
1273
+ outcome: OrchestrationV2NotificationOutcome,
1274
+ summary: TrimmedNonEmptyString,
1275
+});
1276
+const MonitorPullRequestStamp = Schema.Struct({
1277
+ ...ThreadPullRequestKey.fields,
1278
+ watchStartedAt: IsoDateTime,
1279
+ /** Null when the wake is not about one head, so a newer push does not outdate it. */
1280
+ headSha: Schema.NullOr(TrimmedNonEmptyString),
1281
+ watchEnded: Schema.optional(Schema.Boolean),
1282
+ /** Set on a wake covering several pull requests. */
1283
+ section: Schema.optional(PullRequestWakeSection),
1284
+});
1285
1286
/** Encode legacy background_command/background_task shapes first so older clients accept command/subagent sources. */
1287
export const OrchestrationV2NotificationSource = kindUnionWithFallback(
@@ -1292,15 +1314,9 @@ export const OrchestrationV2NotificationSource = kindUnionWithFallback(
1314
CommandNotificationSource,
1315
Schema.Struct({
1316
kind: Schema.Literal("monitor"),
1295
- pullRequest: Schema.optional(
1296
- Schema.Struct({
1297
- ...ThreadPullRequestKey.fields,
1298
- watchStartedAt: IsoDateTime,
1299
- /** Null when the wake is not about one head, so a newer push does not outdate it. */
1300
- headSha: Schema.NullOr(TrimmedNonEmptyString),
1301
- watchEnded: Schema.optional(Schema.Boolean),
1302
- }),
1303
- ),
1317
+ pullRequest: Schema.optional(MonitorPullRequestStamp),
1318
+ /** The other pull requests one wake covers; outdated ones leave it before it starts. */
1319
+ otherPullRequests: Schema.optional(Schema.Array(MonitorPullRequestStamp)),
1320
}),
1321
Schema.Struct({ kind: Schema.Literal("background_task") }),
1322
Schema.Struct({ kind: Schema.Literal("system") }),
@@ -1312,7 +1328,7 @@ export type OrchestrationV2NotificationSource = typeof OrchestrationV2Notificati
1328
1329
export const OrchestrationV2Notification = Schema.Struct({
1330
source: OrchestrationV2NotificationSource,
1315
- outcome: Schema.Literals(["completed", "failed", "cancelled", "updated", "unknown"]),
1331
+ outcome: OrchestrationV2NotificationOutcome,
1332
summary: TrimmedNonEmptyString,
1333
detail: Schema.optional(Schema.String),
1334
});
@@ -3482,6 +3498,18 @@ const OrchestrationV2InternalCommand = Schema.Union([
3498
watch: Schema.NullOr(ThreadPullRequestWatch),
3499
/** With `watch: null`, the state the ended watch keeps instead of its last saved one. */
3500
endedWatch: Schema.optional(ThreadPullRequestWatch),
3501
+ /** More watches of this thread recorded together, which `wake` also reports on. */
3502
+ others: Schema.optional(
3503
+ Schema.Array(
3504
+ Schema.Struct({
3505
+ ...ThreadPullRequestKey.fields,
3506
+ startedAt: IsoDateTime,
3507
+ watch: Schema.NullOr(ThreadPullRequestWatch),
3508
+ endedWatch: Schema.optional(ThreadPullRequestWatch),
3509
+ includesRemarks: Schema.optional(Schema.Boolean),
3510
+ }),
3511
+ ),
3512
+ ),
3513
wake: Schema.optional(
3514
Schema.Struct({
3515
messageId: MessageId,
@@ -3489,6 +3517,8 @@ const OrchestrationV2InternalCommand = Schema.Union([
3517
notification: OrchestrationV2Notification,
3518
/** Comments stay worth reading after a push, so the wake outlives a newer head. */
3519
includesRemarks: Schema.optional(Schema.Boolean),
3520
+ /** With `others`, each pull request's own part, in the same order. */
3521
+ sections: Schema.optional(Schema.Array(PullRequestWakeSection)),
3522
}),
3523
),
3524
}),