The best way to control Claude Code, Codex and more from any computer or phone
fix(server): a watched PR stops holding its thread once its checks finish (#33214)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 12, 2026 at 17:39 UTC
36254ab82eb5e8415f6f3ea12a6dedacc1d0ae8b
15 files changed
+499
-30
apps/server/src/orchestration-v2/Orchestrator.ts
+56
-1
@@ -631,6 +631,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {
631
case "thread.pull-request-link.sync":
632
case "thread.pull-request.watch":
633
case "thread.pull-request-watch.sync":
634
+ case "thread.pull-request-watch.checks-reopen":
635
case "thread.pull-request.sync":
636
case "thread.title.regeneration.complete":
637
case "thread.project.adopt-folder":
@@ -782,6 +783,26 @@ function withPullRequestWatch(
783
return ended === undefined ? rest : { ...rest, endedWatch: ended };
784
}
785
786
+function syncedPullRequestWatch(
787
+ existing: ThreadPullRequestWatch | undefined,
788
+ command: {
789
+ readonly watch: ThreadPullRequestWatch | null;
790
+ readonly checksPendingBefore?: boolean | undefined;
791
+ },
792
+): ThreadPullRequestWatch | undefined {
793
+ if (command.watch === null) return undefined;
794
+ // A push cleared the answer while this read was in flight, so its answer is the old head's.
795
+ if (command.checksPendingBefore === undefined || existing?.checksPending !== undefined) {
796
+ return command.watch;
797
+ }
798
+ return withoutChecksAnswer(command.watch);
799
+}
800
+
801
+const withoutChecksAnswer = ({
802
+ checksPending: _answer,
803
+ ...watch
804
+}: ThreadPullRequestWatch): ThreadPullRequestWatch => watch;
805
+
806
function legacyPullRequestLink(
807
thread: OrchestrationV2AppThread,
808
linked: ThreadLinkedPullRequest,
@@ -3871,6 +3892,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
3892
| "thread.pull-request-link.sync"
3893
| "thread.pull-request.watch"
3894
| "thread.pull-request-watch.sync"
3895
+ | "thread.pull-request-watch.checks-reopen"
3896
| "thread.pull-request.sync"
3897
| "thread.title.regeneration.complete"
3898
| "thread.runtime-mode.set"
@@ -4688,6 +4710,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4710
updatedAt: command.type === "thread.pull-request-link.sync" ? thread.updatedAt : now,
4711
};
4712
}
4713
+ case "thread.pull-request-watch.checks-reopen": {
4714
+ const linked = threadPullRequestsOf(thread);
4715
+ if (!linked.some((link) => link.watch?.checksPending !== undefined)) return thread;
4716
+ return {
4717
+ ...thread,
4718
+ pullRequests: linked.map((link) =>
4719
+ link.watch?.checksPending === undefined
4720
+ ? link
4721
+ : { ...link, watch: withoutChecksAnswer(link.watch) },
4722
+ ),
4723
+ };
4724
+ }
4725
case "thread.pull-request.watch":
4726
case "thread.pull-request-watch.sync": {
4727
const key = normalizeThreadPullRequestKey(command);
@@ -4724,7 +4758,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4758
const watch =
4759
command.type === "thread.pull-request-watch.sync"
4760
? existing.watch?.startedAt === command.startedAt
4727
- ? (command.watch ?? undefined)
4761
+ ? syncedPullRequestWatch(existing.watch, command)
4762
: existing.watch
4763
: !command.watching
4764
? undefined
@@ -4755,6 +4789,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4789
...(existing.endedWatch?.approvalAnnounced !== undefined && {
4790
approvalAnnounced: existing.endedWatch.approvalAnnounced,
4791
}),
4792
+ // A finished-checks answer may be an older head's; a fresh read decides.
4793
+ ...(existing.endedWatch?.checksPending === true && { checksPending: true }),
4794
...(existing.endedWatch?.checksAwaitedSince !== undefined && {
4795
checksAwaitedSince: existing.endedWatch.checksAwaitedSince,
4796
}),
@@ -4842,6 +4878,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4878
};
4879
}
4880
})();
4881
+ if (command.type === "thread.pull-request-watch.checks-reopen") {
4882
+ if (updatedThread === thread) return;
4883
+ yield* emit(
4884
+ events,
4885
+ command,
4886
+ )({
4887
+ type: "thread.pull-request-synced",
4888
+ threadId: command.threadId,
4889
+ providerInstanceId: updatedThread.providerInstanceId,
4890
+ occurredAt: now,
4891
+ payload: updatedThread,
4892
+ });
4893
+ return;
4894
+ }
4895
if (
4896
command.type === "thread.pull-request-link.sync" ||
4897
command.type === "thread.pull-request-watch.sync"
@@ -14500,6 +14550,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14550
case "provider.switch":
14551
yield* dispatchThreadMutation(command, events, effects);
14552
break;
14553
+ case "thread.pull-request-watch.checks-reopen":
14554
+ yield* dispatchThreadMutation(command, events, effects);
14555
+ break;
14556
case "thread.pull-request-watch.sync":
14557
yield* dispatchPullRequestWatchSync(command, events, effects);
14558
break;
@@ -14857,6 +14910,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14910
planned.events.length > 0 ||
14911
isUnobservedAcknowledgement(command) ||
14912
command.type === "thread.background-work.settle" ||
14913
+ // A read can answer a watch again before a push's reopen lands; nothing is left to clear.
14914
+ command.type === "thread.pull-request-watch.checks-reopen" ||
14915
command.type === "thread.interrupt.unresponsive" ||
14916
command.type === "thread.stop" ||
14917
command.type === "subagent.stop" ||
apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts
+62
@@ -12,6 +12,7 @@ import {
12
ThreadId,
13
TurnItemId,
14
type OrchestrationV2Command as OrchestrationCommand,
15
+ type OrchestrationV2InternalCommand,
16
type OrchestrationV2DomainEvent,
17
type OrchestrationV2Run,
18
type OrchestrationProjectShell,
@@ -51,6 +52,10 @@ type SyncCommand = Extract<
52
{ readonly type: "thread.pull-request-link.sync" }
53
>;
54
type LinkCommand = Extract<OrchestrationCommand, { readonly type: "thread.pull-request.link" }>;
55
+type ChecksReopenCommand = Extract<
56
+ OrchestrationV2InternalCommand,
57
+ { readonly type: "thread.pull-request-watch.checks-reopen" }
58
+>;
59
60
const testCrypto = SecureRandom.make((size) => new Uint8Array(size).fill(1));
61
@@ -189,6 +194,7 @@ const makeHarness = Effect.fn("makePullRequestSyncHarness")(function* (options:
194
const shellSnapshotReads = yield* Ref.make(0);
195
const syncCommands = yield* Ref.make<ReadonlyArray<SyncCommand>>([]);
196
const linkCommands = yield* Ref.make<ReadonlyArray<LinkCommand>>([]);
197
+ const reopenCommands = yield* Queue.unbounded<ChecksReopenCommand>();
198
const summaryCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
199
const stackCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
200
const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
@@ -223,6 +229,11 @@ const makeHarness = Effect.fn("makePullRequestSyncHarness")(function* (options:
229
Effect.as({ sequence: 1, storedEvents: [] }),
230
);
231
}
232
+ if (command.type === "thread.pull-request-watch.checks-reopen") {
233
+ return Queue.offer(reopenCommands, command).pipe(
234
+ Effect.as({ sequence: 1, storedEvents: [] }),
235
+ );
236
+ }
237
return Effect.die(new Error(`Unexpected command: ${command.type}`));
238
};
239
@@ -284,6 +295,7 @@ const makeHarness = Effect.fn("makePullRequestSyncHarness")(function* (options:
295
shellSnapshotReads,
296
syncCommands,
297
linkCommands,
298
+ reopenCommands,
299
summaryCalls,
300
stackCalls,
301
domainEvents,
@@ -1880,6 +1892,56 @@ describe("PullRequestSyncReactor", () => {
1892
),
1893
);
1894
1895
+ it.effect("reopens a watch's checks when its thread's agent pushes", () =>
1896
+ Effect.scoped(
1897
+ Effect.gen(function* () {
1898
+ yield* TestClock.setTime(Date.parse(NOW));
1899
+ const watch = {
1900
+ startedAt: NOW,
1901
+ headSha: "aaaaaaaaaa",
1902
+ failedChecks: [],
1903
+ passed: true,
1904
+ passedChecks: ["test"],
1905
+ remarksThrough: NOW,
1906
+ remarkIds: [],
1907
+ conflicting: false,
1908
+ wakes: 0,
1909
+ };
1910
+ const fixture = yield* makeHarness({
1911
+ snapshot: makeSnapshot([
1912
+ makeThread("agent", {
1913
+ pullRequests: [
1914
+ makeLink(7, { state: "open" }, { watch: { ...watch, checksPending: false } }),
1915
+ ],
1916
+ }),
1917
+ makeThread("unread", {
1918
+ pullRequests: [makeLink(8, { state: "open" }, { watch })],
1919
+ }),
1920
+ ]),
1921
+ });
1922
+
1923
+ yield* Effect.gen(function* () {
1924
+ yield* startAndSweep(fixture);
1925
+ const agent = ThreadId.make("agent");
1926
+ yield* Queue.offerAll(fixture.domainEvents, [
1927
+ commandRan(agent, "git status && echo 'then git push'", undefined, "status"),
1928
+ // A watch that has not read its checks yet has no answer to forget.
1929
+ commandRan(ThreadId.make("unread"), "git push", undefined, "unread-push"),
1930
+ commandRan(agent, "cd app && git -C . push --force-with-lease", undefined, "push"),
1931
+ commandRan(agent, '/bin/zsh -lc "gh stack submit --auto"', undefined, "stack"),
1932
+ ]);
1933
+ for (const item of ["push", "stack"]) {
1934
+ const command = yield* Queue.take(fixture.reopenCommands);
1935
+ assert.deepStrictEqual(
1936
+ [command.threadId, command.commandId],
1937
+ [agent, `server:pr-push-checks:agent:item:agent:${item}`],
1938
+ );
1939
+ }
1940
+ }).pipe(Effect.provide(fixture.layer));
1941
+ }),
1942
+ ),
1943
+ );
1944
+
1945
it.effect("reads open links again when the run ends, after `merge --auto` left them open", () =>
1946
Effect.scoped(
1947
Effect.gen(function* () {
apps/server/src/orchestration-v2/PullRequestSyncReactor.ts
+37
-1
@@ -72,6 +72,11 @@ const CREATE_COMMANDS = sourceControlDefinitions.definitions.flatMap(
72
);
73
const createCommandCount = (code: string) =>
74
CREATE_COMMANDS.reduce((count, { run }) => count + [...code.matchAll(run)].length, 0);
75
+// A push, directly or through a stack tool, that can start checks on a linked pull request.
76
+const PUSH_COMMAND = new RegExp(
77
+ `${COMMAND_START}(?:git(?:\\s+-[cC]\\s+\\S+)*\\s+push|gh\\s+stack\\s+(?:push|submit)|cafe\\s+stack\\s+submit|jj\\s+git\\s+push)(?=$|[\\s;&|)])`,
78
+ "u",
79
+);
80
81
// Codex runs each command as `/bin/zsh -lc <script>`, quoting the script in pieces such as
82
// `"a "'`b`'" c"`.
@@ -134,6 +139,8 @@ function shellSegments(script: string): ReadonlyArray<string> {
139
const shellCode = (script: string) =>
140
script.replace(HEREDOC_BODY, "<<").replace(QUOTED_OR_COMMENT, "''");
141
142
+const isPushCommand = (input: string) => PUSH_COMMAND.test(shellCode(shellScript(input)));
143
+
144
type CommandExecution = Extract<OrchestrationV2TurnItem, { readonly type: "command_execution" }>;
145
146
/**
@@ -757,6 +764,32 @@ export const make = Effect.gen(function* () {
764
},
765
);
766
767
+ // A push can start new checks, so the thread's watches forget whether checks were running and
768
+ // hold the thread until they read the pull request again. The run is still going, so the
769
+ // thread never shows as done in between.
770
+ const reopenWatchedChecks = Effect.fn("PullRequestSyncReactor.reopenWatchedChecks")(
771
+ function* (threadId: ThreadId, item: CommandExecution) {
772
+ if (isOrchestrationV2WorkActive(item.status) || !isPushCommand(item.input)) return;
773
+ const threads = yield* projections.getThreadsWithPullRequests(threadId);
774
+ const answered = threads.some((thread) =>
775
+ (thread.pullRequests ?? []).some((link) => link.watch?.checksPending !== undefined),
776
+ );
777
+ if (!answered) return;
778
+ yield* engine.dispatch({
779
+ type: "thread.pull-request-watch.checks-reopen",
780
+ // Stable per command, so a repeated settlement clears an answer read since only once.
781
+ commandId: CommandId.make(`server:pr-push-checks:${threadId}:${item.id}`),
782
+ threadId,
783
+ });
784
+ },
785
+ (effect, threadId) =>
786
+ effect.pipe(
787
+ Effect.catchCause(
788
+ logSkipped("reopening a watch's checks after a push failed", { threadId }),
789
+ ),
790
+ ),
791
+ );
792
+
793
const start: PullRequestSyncReactor["Service"]["start"] = Effect.fn(
794
"PullRequestSyncReactor.start",
795
)(function* () {
@@ -787,7 +820,10 @@ export const make = Effect.gen(function* () {
820
case "turn-item.updated": {
821
const item = event.payload;
822
if (item.type !== "command_execution") return Effect.void;
790
- const linked = linkCreatedChangeRequests(event.threadId, item);
823
+ const linked = Effect.andThen(
824
+ linkCreatedChangeRequests(event.threadId, item),
825
+ reopenWatchedChecks(event.threadId, item),
826
+ );
827
if (!isChangeRequestCloseCommand(item.input)) return linked;
828
const ended = closeCommands.get(event.threadId) ?? new Set<string>();
829
closeCommands.set(event.threadId, ended);
apps/server/src/orchestration-v2/PullRequestWatchReactor.ts
+14
-4
@@ -165,11 +165,13 @@ function planRead(
165
if (last === undefined || group.targets.some((target) => !last.watches.has(watchKey(target)))) {
166
return { detail: true, activity: true };
167
}
168
- // Nothing on the host changes when the no-checks deadline passes, so it alone prompts a read.
168
+ // Nothing on the host changes when the no-checks deadline passes, or when a push to another
169
+ // branch clears a watch's answer, so either alone prompts a read.
170
const checksDue = group.targets.some(
171
({ watch }) =>
171
- watch.checksAwaitedSince != null &&
172
- now - Date.parse(watch.checksAwaitedSince) >= PULL_REQUEST_WATCH_NO_CHECKS_MS,
172
+ watch.checksPending === undefined ||
173
+ (watch.checksAwaitedSince != null &&
174
+ now - Date.parse(watch.checksAwaitedSince) >= PULL_REQUEST_WATCH_NO_CHECKS_MS),
175
);
176
if (fingerprint === null) {
177
const read =
@@ -189,6 +191,10 @@ function planRead(
191
};
192
}
193
194
+// Lets the orchestrator tell that a push cleared the answer while this read was in flight.
195
+const checksPendingBeforeOf = ({ watch }: WatchTarget) =>
196
+ watch.checksPending === undefined ? {} : { checksPendingBefore: watch.checksPending };
197
+
198
function watchesEqual(left: ThreadPullRequestWatch, right: ThreadPullRequestWatch): boolean {
199
return (
200
left.startedAt === right.startedAt &&
@@ -205,7 +211,8 @@ function watchesEqual(left: ThreadPullRequestWatch, right: ThreadPullRequestWatc
211
left.mergeQueueRemovalId === right.mergeQueueRemovalId &&
212
left.wakes === right.wakes &&
213
left.awaitingBaseline === right.awaitingBaseline &&
208
- left.checksAwaitedSince === right.checksAwaitedSince
214
+ left.checksAwaitedSince === right.checksAwaitedSince &&
215
+ left.checksPending === right.checksPending
216
);
217
}
218
@@ -314,6 +321,7 @@ export const make = Effect.gen(function* () {
321
...identityOf(target.link),
322
startedAt: target.watch.startedAt,
323
watch: next,
324
+ ...checksPendingBeforeOf(target),
325
...(endedWatch === undefined ? {} : { endedWatch }),
326
...(wake === undefined
327
? {}
@@ -455,11 +463,13 @@ export const make = Effect.gen(function* () {
463
...identityOf(first.target.link),
464
startedAt: first.target.watch.startedAt,
465
watch: first.next,
466
+ ...checksPendingBeforeOf(first.target),
467
...(first.endedWatch === undefined ? {} : { endedWatch: first.endedWatch }),
468
others: rest.map((item) => ({
469
...identityOf(item.target.link),
470
startedAt: item.target.watch.startedAt,
471
watch: item.next,
472
+ ...checksPendingBeforeOf(item.target),
473
...(item.endedWatch === undefined ? {} : { endedWatch: item.endedWatch }),
474
...(item.wake.includesRemarks === true ? { includesRemarks: true } : {}),
475
})),
apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
+11
@@ -147,6 +147,17 @@ describe("isAutoSettlementCandidate", () => {
147
NOW_MS,
148
),
149
).toBe(true);
150
+ // A pull request watch whose checks finished holds nothing, yet still keeps the thread.
151
+ expect(
152
+ ThreadSettlementService.isAutoSettlementCandidate(
153
+ shell({
154
+ pendingBackgroundTasks: [
155
+ { taskId: "pull-request-watch:github.com/acme/app#1", kind: "monitor" },
156
+ ],
157
+ }),
158
+ NOW_MS,
159
+ ),
160
+ ).toBe(false);
161
});
162
163
it("never settles, or keeps snoozed, a thread whose guest is waiting on the owner", () => {
apps/server/src/orchestration-v2/ThreadSettlementService.ts
+5
-1
@@ -1,5 +1,6 @@
1
import {
2
backgroundWorkHoldsCompletion,
3
+ isPullRequestWatchTask,
4
turnItemUpdateCanEndBackgroundWork,
5
} from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
6
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
@@ -154,7 +155,10 @@ export function isAutoSettlementCandidate(
155
// A guest is waiting on the owner; settling would hide the Request.
156
if ((thread.pendingGuestMessageCount ?? 0) > 0) return false;
157
if (thread.activityRunStatus != null) return false;
157
- if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) return false;
158
+ const pendingTasks = thread.pendingBackgroundTasks ?? [];
159
+ if (backgroundWorkHoldsCompletion(pendingTasks)) return false;
160
+ // Settling ends a watch, which would silently drop a reviewer's later comments.
161
+ if (pendingTasks.some(isPullRequestWatchTask)) return false;
162
if (threadHasQueuedTurnStart(thread, nowMs)) return false;
163
// Interrupted runs must keep the same snooze protection the sidebar shows.
164
return !isSnoozed(thread, nowMs);
apps/server/src/orchestration-v2/pullRequestWatch.test.ts
+58
@@ -217,6 +217,7 @@ describe("evaluatePullRequestWatch", () => {
217
);
218
assert.deepEqual(empty.changes, []);
219
assert.isUndefined(empty.next.awaitingBaseline);
220
+ assert.isTrue(empty.next.checksPending);
221
assert.deepEqual(
222
evaluatePullRequestWatch(empty.next, detail({ checks: [check("test", status)] }), noRemarks)
223
.changes,
@@ -862,4 +863,61 @@ describe("evaluatePullRequestWatch", () => {
863
const silent = detail({ capabilities: capabilities(false), checks: [] });
864
assert.isTrue(anHourLater(watch(), silent).every((kinds) => kinds.length === 0));
865
});
866
+
867
+ it("counts checks as pending until every one, a review bot's included, has finished", () => {
868
+ const pending = (checks: ReadonlyArray<PullRequestCheck>, from = watch()) =>
869
+ evaluatePullRequestWatch(from, detail({ checks }), noRemarks).next.checksPending;
870
+ const ci = { ...check("test", "success"), required: true };
871
+ assert.isTrue(pending([ci, check("CodeRabbit", "pending")]));
872
+ assert.isFalse(pending([ci, check("CodeRabbit", "success")]));
873
+ assert.isFalse(pending([ci, check("CodeRabbit", "failure")]));
874
+ assert.isFalse(pending([ci, check("deploy", "action-required")]));
875
+ // A failed read keeps the last answer, as does one with only an unreadable approval check.
876
+ assert.isFalse(pending([], watch({ headSha: "aaaaaaaaaa", checksPending: false })));
877
+ const unreadable = { ...check("approvals", "action-required"), placeholder: true };
878
+ assert.isTrue(pending([unreadable], watch({ headSha: "aaaaaaaaaa", checksPending: true })));
879
+ });
880
+
881
+ it("waits a while for a new head's checks on every host", () => {
882
+ const pushed = (checksAlwaysReport: boolean) =>
883
+ evaluatePullRequestWatch(
884
+ watch({ headSha: "aaaaaaaaaa", checksPending: false }),
885
+ detail({
886
+ headSha: "bbbbbbbbbb",
887
+ capabilities: capabilities(checksAlwaysReport),
888
+ checks: [],
889
+ }),
890
+ noRemarks,
891
+ ).next.checksPending;
892
+ assert.isTrue(pushed(true));
893
+ assert.isTrue(pushed(false));
894
+
895
+ // Once the no-checks window passes, the watch stops waiting for them.
896
+ for (const checksAlwaysReport of [true, false]) {
897
+ let current = watch({ headSha: "aaaaaaaaaa" });
898
+ for (const minute of [0, 20]) {
899
+ current = evaluate(
900
+ current,
901
+ detail({
902
+ headSha: "bbbbbbbbbb",
903
+ capabilities: capabilities(checksAlwaysReport),
904
+ checks: [],
905
+ }),
906
+ noRemarks,
907
+ minute * 60_000,
908
+ ).next;
909
+ }
910
+ assert.isFalse(current.checksPending);
911
+ }
912
+
913
+ // A watch with no answer waits on an empty list only while the no-checks clock runs.
914
+ const unanswered = (checksAwaitedSince: string | null) =>
915
+ evaluatePullRequestWatch(
916
+ watch({ headSha: "bbbbbbbbbb", checksAwaitedSince }),
917
+ detail({ headSha: "bbbbbbbbbb", checks: [] }),
918
+ noRemarks,
919
+ ).next.checksPending;
920
+ assert.isFalse(unanswered(null));
921
+ assert.isTrue(unanswered(STARTED));
922
+ });
923
});
apps/server/src/orchestration-v2/pullRequestWatch.ts
+21
-14
@@ -64,12 +64,17 @@ export function evaluatePullRequestWatch(
64
let owedChecks = headMoved ? [] : (watch.owedChecks ?? []);
65
let awaitingApproval = headMoved ? [] : (watch.awaitingApproval ?? []);
66
let approvalAnnounced = headMoved ? false : (watch.approvalAnnounced ?? false);
67
+ // A watch with no answer (saved before the field, or since a push) waits only while the clock
68
+ // below runs.
69
+ let checksPending = headMoved ? false : (watch.checksPending ?? watch.checksAwaitedSince != null);
70
// An unavailable approval read cannot establish success or that no checks exist.
71
const unread = detail.checks.some((check) => check.placeholder === true);
72
const checks = detail.checks.filter((check) => check.placeholder !== true);
73
const failed = checks.filter(isFailedCheck);
74
const awaiting = checks.filter((check) => check.status === "action-required");
75
if (checks.length > 0) {
76
+ // A run awaiting approval waits on a person, like a review, so only running checks count.
77
+ checksPending = checks.some((check) => check.status === "pending");
78
const newlyFailed = failed.filter((check) => !failedChecks.includes(check.name));
79
if (!checksBaseline && newlyFailed.length > 0) {
80
changes.push({ kind: "checks-failed", failed: newlyFailed });
@@ -152,22 +157,23 @@ export function evaluatePullRequestWatch(
157
passedChecks = passedNow ? gateNames : [];
158
}
159
155
- // Only a head never read with checks waits for them: an empty read after checks were seen is
156
- // the failed read above. A watch saved before this field may have seen pending checks on its
157
- // head, so its clock starts only at the next push. Where a host's empty list can mean the
158
- // repository runs no checks at all, nothing waits.
159
- let checksAwaitedSince = watch.checksAwaitedSince;
160
- if (detail.capabilities.checksAlwaysReport === true) {
161
- const awaitedBefore =
162
- headMoved || watch.awaitingBaseline === "all"
163
- ? DateTime.formatIso(DateTime.makeUnsafe(now))
164
- : (watch.checksAwaitedSince ?? null);
165
- checksAwaitedSince = checks.length > 0 ? null : awaitedBefore;
166
- const awaitedMs = checksAwaitedSince === null ? 0 : now - Date.parse(checksAwaitedSince);
167
- if (!unread && awaitedMs >= PULL_REQUEST_WATCH_NO_CHECKS_MS) {
160
+ // Only a head never read with checks waits for them; a legacy watch's clock starts at its next
161
+ // push. CI can register late on any host, so every host waits, but running out of time is news
162
+ // only where a host always reports checks: elsewhere an empty list can mean there are none.
163
+ const awaitedBefore =
164
+ headMoved || watch.awaitingBaseline === "all"
165
+ ? DateTime.formatIso(DateTime.makeUnsafe(now))
166
+ : (watch.checksAwaitedSince ?? null);
167
+ let checksAwaitedSince = checks.length > 0 ? null : awaitedBefore;
168
+ const awaitedMs = checksAwaitedSince === null ? 0 : now - Date.parse(checksAwaitedSince);
169
+ if (!unread && awaitedMs >= PULL_REQUEST_WATCH_NO_CHECKS_MS) {
170
+ if (detail.capabilities.checksAlwaysReport === true) {
171
changes.push({ kind: "no-checks", minutes: Math.round(awaitedMs / 60_000) });
169
- checksAwaitedSince = null;
172
}
173
+ checksAwaitedSince = null;
174
+ checksPending = false;
175
+ } else if (checksAwaitedSince !== null) {
176
+ checksPending = true;
177
}
178
179
const own = (detail.viewer ?? detail.author?.login)?.toLowerCase();
@@ -241,6 +247,7 @@ export function evaluatePullRequestWatch(
247
awaitingBaseline: "checks" as const,
248
}),
249
checksAwaitedSince,
250
+ checksPending,
251
},
252
exhausted: commentsOnly && wakes >= PULL_REQUEST_WATCH_WAKE_LIMIT,
253
};
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+154
-1
@@ -25,6 +25,7 @@ import {
25
type OrchestrationV2ShellSnapshot,
26
type OrchestrationV2RuntimeRequest,
27
ProjectId,
28
+ type PullRequestCheck,
29
type PullRequestDetail,
30
type PullRequestComment,
31
PullRequestOperationError,
@@ -4265,6 +4266,153 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
4266
}),
4267
);
4268
4269
+ it.effect(
4270
+ "records when a watched PR's checks finish, unless a push cleared that during the read",
4271
+ () =>
4272
+ Effect.gen(function* () {
4273
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
4274
+ const threadId = ThreadId.make("runtime-pull-request-watch-quiet");
4275
+ const projectId = ProjectId.make("pr-watch-quiet-project");
4276
+ yield* seedProject({
4277
+ projectId,
4278
+ title: "Watch quiet",
4279
+ workspaceRoot: "/workspace/watch-quiet",
4280
+ defaultModelSelection: null,
4281
+ createdAt: "2026-10-01T00:00:00.000Z",
4282
+ });
4283
+ yield* orchestrator.dispatch({
4284
+ type: "thread.create",
4285
+ createdBy: "user",
4286
+ creationSource: "web",
4287
+ commandId: CommandId.make("pr-watch-quiet-create"),
4288
+ threadId,
4289
+ projectId,
4290
+ title: "Watch quiet",
4291
+ modelSelection,
4292
+ runtimeMode: "full-access",
4293
+ interactionMode: "default",
4294
+ branch: null,
4295
+ worktreePath: null,
4296
+ });
4297
+ // Two watches, as with a stack, so news on both wakes the thread once for both.
4298
+ for (const number of [17, 18]) {
4299
+ yield* orchestrator.dispatch({
4300
+ type: "thread.pull-request.watch",
4301
+ commandId: CommandId.make(`pr-watch-quiet-start-${number}`),
4302
+ threadId,
4303
+ host: "github.com",
4304
+ repository: "pingdotgg/t3code",
4305
+ number,
4306
+ watching: true,
4307
+ link: { url: `https://github.com/pingdotgg/t3code/pull/${number}`, source: "agent" },
4308
+ });
4309
+ }
4310
+
4311
+ let e2e: PullRequestCheck["status"] = "pending";
4312
+ let comments: ReadonlyArray<PullRequestComment> = [];
4313
+ let gate: {
4314
+ readonly started: Deferred.Deferred<void>;
4315
+ readonly release: Deferred.Deferred<void>;
4316
+ } | null = null;
4317
+ const host = Layer.mergeAll(
4318
+ NodeServices.layer,
4319
+ NodeCrypto.layer,
4320
+ Layer.mock(PullRequestService.PullRequestService)({
4321
+ detail: (input) =>
4322
+ Effect.gen(function* () {
4323
+ if (gate !== null) {
4324
+ yield* Deferred.succeed(gate.started, undefined);
4325
+ yield* Deferred.await(gate.release);
4326
+ }
4327
+ return {
4328
+ ...watchedPullRequestDetail({
4329
+ projectId,
4330
+ number: input.number,
4331
+ at: "2026-10-02T12:00:00.000Z",
4332
+ }),
4333
+ checks: [
4334
+ { name: "test", status: "failure" as const, description: null, url: null },
4335
+ { name: "e2e", status: e2e, description: null, url: null },
4336
+ ],
4337
+ };
4338
+ }),
4339
+ activity: () =>
4340
+ Effect.sync(() => ({
4341
+ comments,
4342
+ commentCount: comments.length,
4343
+ commentsTruncated: false,
4344
+ reviewThreads: [],
4345
+ commits: [],
4346
+ })),
4347
+ }),
4348
+ );
4349
+ const summaries = Effect.map(
4350
+ orchestrator.getThreadRecords(threadId, ["messages"]),
4351
+ ({ messages }) => messages.flatMap((message) => message.notification?.summary ?? []),
4352
+ );
4353
+ const checksPending = Effect.map(orchestrator.getThreadShell(threadId), (thread) => {
4354
+ const answers = (thread?.pullRequests ?? []).map((link) => link.watch?.checksPending);
4355
+ assert.lengthOf(answers, 2);
4356
+ assert.strictEqual(answers[0], answers[1]);
4357
+ return answers[0];
4358
+ });
4359
+
4360
+ const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host));
4361
+ yield* reactor.sweep;
4362
+ assert.deepEqual(yield* summaries, []);
4363
+ assert.isTrue(yield* checksPending);
4364
+ const reopen = (id: string) =>
4365
+ orchestrator.dispatch({
4366
+ type: "thread.pull-request-watch.checks-reopen",
4367
+ commandId: CommandId.make(`pr-watch-quiet-${id}`),
4368
+ threadId,
4369
+ });
4370
+ // A push forgets a running answer too, so a read begun before it cannot settle it.
4371
+ yield* reopen("push-pending");
4372
+ assert.isUndefined(yield* checksPending);
4373
+
4374
+ e2e = "success";
4375
+ yield* TestClock.adjust("10 minutes");
4376
+ yield* reactor.sweep;
4377
+ assert.deepEqual(yield* summaries, []);
4378
+ assert.isFalse(yield* checksPending);
4379
+
4380
+ // A push clears the answer while a read with news is in flight. That read's answer is the
4381
+ // old head's, so the answer stays cleared while its news still wakes the agent.
4382
+ const started = yield* Deferred.make<void>();
4383
+ const release = yield* Deferred.make<void>();
4384
+ gate = { started, release };
4385
+ comments = [
4386
+ {
4387
+ id: "comment-1",
4388
+ kind: "issue-comment",
4389
+ author: { login: "reviewer", name: null, avatarUrl: null },
4390
+ body: "Looks good once CI passes.",
4391
+ createdAt: "2999-01-01T00:00:00.000Z",
4392
+ url: null,
4393
+ path: null,
4394
+ reviewState: null,
4395
+ },
4396
+ ];
4397
+ yield* TestClock.adjust("10 minutes");
4398
+ const inFlight = yield* reactor.sweep.pipe(Effect.forkChild({ startImmediately: true }));
4399
+ yield* Deferred.await(started);
4400
+ yield* reopen("push");
4401
+ // Another push before the watch read again finds nothing to clear, which is fine.
4402
+ yield* reopen("push-again");
4403
+ gate = null;
4404
+ yield* Deferred.succeed(release, undefined);
4405
+ yield* Fiber.join(inFlight);
4406
+ assert.lengthOf(yield* summaries, 1);
4407
+ assert.isUndefined(yield* checksPending);
4408
+
4409
+ // The next sweep reads it again though nothing on the host changed.
4410
+ yield* TestClock.adjust("2 minutes");
4411
+ yield* reactor.sweep;
4412
+ assert.isFalse(yield* checksPending);
4413
+ }),
4414
+ );
4415
+
4416
it.effect.each(["pending", "action-required"] as const)("recovers %s watches", (initialStatus) =>
4417
Effect.gen(function* () {
4418
const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -4363,9 +4511,14 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
4511
yield* worker.drain();
4512
assert.deepEqual(yield* summaries, []);
4513
4366
- // A new watch on the same pull request knows what the last one told.
4514
+ // A new watch on the same pull request knows what the last one told, and that its checks
4515
+ // were still running. A finished answer may be an older head's, so it reads again.
4516
yield* watch(false, "stop");
4517
yield* watch(true, "again");
4518
+ assert.strictEqual(
4519
+ (yield* orchestrator.getThreadShell(threadId))?.pullRequests?.[0]?.watch?.checksPending,
4520
+ approval ? undefined : true,
4521
+ );
4522
yield* restarted.sweep;
4523
yield* worker.drain();
4524
assert.deepEqual(yield* summaries, []);
docs/user/source-control.md
+6
-3
@@ -340,9 +340,12 @@ watch already reported; unlinking the pull request clears that. Subagents cannot
340
it yourself, use the row menu in the **Linked pull requests** panel. In the thread details card, a
341
watched pull request shows an eye; click it to stop watching.
342
343
-A watched thread counts as working between wakes, so it stays in the **Working** section and does
344
-not auto-settle. Agents stop watching when they hand the work back to you, and the thread then
345
-returns to your inbox.
343
+A watched thread counts as working while the pull request still has checks running, so it stays in
344
+the **Working** section, including after the agent pushes a fix. Once every check has finished,
345
+including review bots that report as checks, the thread returns to your inbox: what happens next is
346
+up to a person. That includes a workflow waiting for a maintainer to approve it, which runs only
347
+once someone does. The watch stays on and still wakes the agent on new comments, failed checks or
348
+conflicts, and a watched thread never auto-settles.
349
350
Cross-repository links use a project on the same host. Azure DevOps reviews require a project checked
351
out from the matching organization and repository.
docs/user/thread-sidebar.md
+1
-1
@@ -134,7 +134,7 @@ open.
134
135
Threads that are working or waiting on work they will resume from move into a collapsed
136
**Working** section below the active list.
137
-That includes subagents, watched pull requests, and background commands or monitors the agent
137
+That includes subagents, watched pull requests with checks still running, and background commands or monitors the agent
138
says it is waiting on. A dev server or other process an agent leaves running does not keep a thread
139
there. A thread returns to the top of the active list when it finishes, fails, or needs an approval or
140
answer. The Working section lists the thread you last sent work to first. Pinned threads stay in
packages/contracts/src/orchestrationV2.ts
+15
@@ -3535,6 +3535,15 @@ const OrchestrationV2InternalCommand = Schema.Union([
3535
threadId: ThreadId,
3536
projectId: ProjectId,
3537
}),
3538
+ /**
3539
+ * After a push, the thread's watches forget whether their checks were running, since the push
3540
+ * can start new ones. Applied to the watches as they are then, so no earlier read overwrites them.
3541
+ */
3542
+ Schema.Struct({
3543
+ type: Schema.Literal("thread.pull-request-watch.checks-reopen"),
3544
+ commandId: CommandId,
3545
+ threadId: ThreadId,
3546
+ }),
3547
Schema.Struct({
3548
type: Schema.Literal("thread.pull-request-watch.sync"),
3549
commandId: CommandId,
@@ -3542,6 +3551,11 @@ const OrchestrationV2InternalCommand = Schema.Union([
3551
...ThreadPullRequestKey.fields,
3552
startedAt: IsoDateTime,
3553
watch: Schema.NullOr(ThreadPullRequestWatch),
3554
+ /**
3555
+ * The watch's `checksPending` when this read started. A push that clears it during the read
3556
+ * makes the read's answer describe the old head, so the cleared answer stays.
3557
+ */
3558
+ checksPendingBefore: Schema.optional(Schema.Boolean),
3559
/** With `watch: null`, the state the ended watch keeps instead of its last saved one. */
3560
endedWatch: Schema.optional(ThreadPullRequestWatch),
3561
/** More watches of this thread recorded together, which `wake` also reports on. */
@@ -3551,6 +3565,7 @@ const OrchestrationV2InternalCommand = Schema.Union([
3565
...ThreadPullRequestKey.fields,
3566
startedAt: IsoDateTime,
3567
watch: Schema.NullOr(ThreadPullRequestWatch),
3568
+ checksPendingBefore: Schema.optional(Schema.Boolean),
3569
endedWatch: Schema.optional(ThreadPullRequestWatch),
3570
includesRemarks: Schema.optional(Schema.Boolean),
3571
}),
packages/contracts/src/threadPullRequest.ts
+5
@@ -111,6 +111,11 @@ export const ThreadPullRequestWatch = Schema.Struct({
111
* none did. Null once either happened; absent on watches saved before it existed.
112
*/
113
checksAwaitedSince: Schema.optional(Schema.NullOr(IsoDateTime)),
114
+ /**
115
+ * Whether the host was still running checks on the head at the last read. Only then does the
116
+ * watch keep its thread waiting; absent on watches not read since it existed.
117
+ */
118
+ checksPending: Schema.optional(Schema.Boolean),
119
});
120
export type ThreadPullRequestWatch = typeof ThreadPullRequestWatch.Type;
121
packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts
+39
@@ -3,6 +3,7 @@ import { ProviderInstanceId, ProviderThreadId } from "@t3tools/contracts";
3
import {
4
backgroundWorkHoldsCompletion,
5
derivePendingBackgroundWork,
6
+ monitorHoldsWakeCompletion,
7
} from "./orchestrationV2PendingBackgroundWork.ts";
8
9
describe("backgroundWorkHoldsCompletion", () => {
@@ -434,6 +435,44 @@ describe("derivePendingBackgroundWork kinds", () => {
435
]);
436
});
437
438
+ it("stops a watch whose checks all finished from holding the thread, while still listing it", () => {
439
+ const tasks = derivePendingBackgroundWork({
440
+ latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" },
441
+ providerThreads: [],
442
+ turnItems: [],
443
+ pullRequests: [{ ...link(1, {}), watch: { ...watch, passed: true, checksPending: false } }],
444
+ });
445
+ expect(tasks).toEqual([
446
+ {
447
+ taskId: "pull-request-watch:github.com/acme/app#1",
448
+ description: "Watching pull request #1",
449
+ kind: "monitor",
450
+ },
451
+ ]);
452
+ expect(backgroundWorkHoldsCompletion(tasks)).toBe(false);
453
+ // Unlike a monitor that wakes per line, it lets a comment wake's run complete too.
454
+ expect(
455
+ monitorHoldsWakeCompletion({
456
+ latestRunBackgroundWake: true,
457
+ pendingBackgroundTasks: tasks,
458
+ }),
459
+ ).toBe(false);
460
+ expect(
461
+ monitorHoldsWakeCompletion({
462
+ latestRunBackgroundWake: true,
463
+ pendingBackgroundTasks: [...tasks, { taskId: "tail", kind: "monitor" }],
464
+ }),
465
+ ).toBe(true);
466
+
467
+ const running = derivePendingBackgroundWork({
468
+ latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" },
469
+ providerThreads: [],
470
+ turnItems: [],
471
+ pullRequests: [{ ...link(1, {}), watch: { ...watch, checksPending: true } }],
472
+ });
473
+ expect(backgroundWorkHoldsCompletion(running)).toBe(true);
474
+ });
475
+
476
it("lists no watch while a run is active", () => {
477
expect(
478
derivePendingBackgroundWork({
packages/shared/src/orchestrationV2PendingBackgroundWork.ts
+15
-4
@@ -108,13 +108,23 @@ function backgroundWorkKindHoldsCompletion(kind: PendingBackgroundWorkTask["kind
108
}
109
}
110
111
-/** A monitor wakes the agent once per line, so a progress wake run's completion waits for the monitor to end. */
111
+const PULL_REQUEST_WATCH_TASK_ID = "pull-request-watch:";
112
+
113
+export const isPullRequestWatchTask = (task: Pick<PendingBackgroundWorkTask, "taskId">) =>
114
+ task.taskId.startsWith(PULL_REQUEST_WATCH_TASK_ID);
115
+
116
+/**
117
+ * A monitor wakes the agent once per line, so a progress wake run's completion waits for the
118
+ * monitor to end. A pull request watch wakes only on news and holds while its checks run.
119
+ */
120
export function monitorHoldsWakeCompletion(
121
thread: Pick<OrchestrationV2ThreadShell, "latestRunBackgroundWake" | "pendingBackgroundTasks">,
122
): boolean {
123
return (
124
thread.latestRunBackgroundWake === true &&
117
- (thread.pendingBackgroundTasks ?? []).some((task) => task.kind === "monitor")
125
+ (thread.pendingBackgroundTasks ?? []).some(
126
+ (task) => task.kind === "monitor" && !isPullRequestWatchTask(task),
127
+ )
128
);
129
}
130
@@ -313,10 +323,11 @@ function pullRequestWatchTasks(
323
{
324
// Links store their normalized identity, and this id only has to be unique within the
325
// thread, so it reads those fields instead of parsing the URL.
316
- taskId: `pull-request-watch:${link.host.toLowerCase()}/${link.repository.toLowerCase()}#${link.number}`,
326
+ taskId: `${PULL_REQUEST_WATCH_TASK_ID}${link.host.toLowerCase()}/${link.repository.toLowerCase()}#${link.number}`,
327
description: `Watching pull request #${link.number}`,
328
kind: "monitor" as const,
319
- awaited: true as const,
329
+ // Once every check finished, a person moves the PR next: the watch stays on but holds nothing.
330
+ ...(link.watch.checksPending === false ? {} : { awaited: true as const }),
331
},
332
],
333
);