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, 23:30 UTC
fix(server): drop stale queued pull-request watch wakes (#21239)
Co-authored-by: Sinan Turna <189102964+Sinan53x@users.noreply.github.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Sinan Turna committed
Nov 11, 2026 at 14:25 UTC
0af2d21647416e3092347d4be82af6cfa6fa6b2d
4 files changed
+520
-65
apps/server/src/orchestration-v2/Orchestrator.ts
+140
-56
@@ -940,6 +940,106 @@ function usageLimitHoldsQueue(
940
return resetAt != null && Date.parse(resetAt) > DateTime.toEpochMillis(now);
941
}
942
943
+function pullRequestSnapshotEndsWatch(
944
+ snapshot: ThreadPullRequestLink["snapshot"],
945
+ watchStartedAt: ThreadPullRequestWatch["startedAt"],
946
+): boolean {
947
+ return (
948
+ snapshot?.state === "merged" ||
949
+ // A restarted watch can see a closed snapshot from before the PR reopened.
950
+ (snapshot?.state === "closed" &&
951
+ DateTime.isGreaterThanOrEqualTo(
952
+ DateTime.makeUnsafe(snapshot.syncedAt),
953
+ DateTime.makeUnsafe(watchStartedAt),
954
+ ))
955
+ );
956
+}
957
+
958
+function isStalePullRequestWatchWake(
959
+ projection: Pick<OrchestrationV2ThreadProjection, "thread" | "messages">,
960
+ run: OrchestrationV2Run,
961
+): boolean {
962
+ const source = projection.messages.find((message) => message.id === run.userMessageId)
963
+ ?.notification?.source;
964
+ if (source?.kind !== "monitor" || source.pullRequest === undefined) return false;
965
+ const stamp = source.pullRequest;
966
+ const link = threadPullRequestsOf(projection.thread).find(
967
+ (candidate) =>
968
+ candidate.source !== "stack-dismissed" && threadPullRequestKeysEqual(candidate, stamp),
969
+ );
970
+ if (link === undefined) return true;
971
+ if (stamp.watchEnded === true) {
972
+ // The final notice outlives its watch, but a replacement watch supersedes it.
973
+ const latestWatch = link.watch ?? link.endedWatch;
974
+ return latestWatch?.startedAt !== stamp.watchStartedAt;
975
+ }
976
+ if (link.watch === undefined) {
977
+ // A watch the server ended with a final notice still owes the wakes it queued before it.
978
+ const endedWithNotice = projection.messages.some((message) => {
979
+ const ending = message.notification?.source;
980
+ return (
981
+ ending?.kind === "monitor" &&
982
+ ending.pullRequest?.watchEnded === true &&
983
+ ending.pullRequest.watchStartedAt === stamp.watchStartedAt &&
984
+ threadPullRequestKeysEqual(ending.pullRequest, stamp)
985
+ );
986
+ });
987
+ return (
988
+ !endedWithNotice ||
989
+ link.endedWatch?.startedAt !== stamp.watchStartedAt ||
990
+ pullRequestSnapshotEndsWatch(link.snapshot, stamp.watchStartedAt)
991
+ );
992
+ }
993
+ return (
994
+ link.watch.startedAt !== stamp.watchStartedAt ||
995
+ (stamp.headSha !== null && link.watch.headSha !== stamp.headSha) ||
996
+ pullRequestSnapshotEndsWatch(link.snapshot, link.watch.startedAt)
997
+ );
998
+}
999
+
1000
+function queuedRunCancellationEvents(
1001
+ projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "attempts">,
1002
+ run: OrchestrationV2Run,
1003
+ now: DateTime.Utc,
1004
+): ReadonlyArray<Omit<OrchestrationV2DomainEvent, "id">> {
1005
+ const rootNode = projection.nodes.find((node) => node.id === run.rootNodeId);
1006
+ const attempt = projection.attempts.find((candidate) => candidate.id === run.activeAttemptId);
1007
+ const events: Array<Omit<OrchestrationV2DomainEvent, "id">> = [
1008
+ {
1009
+ type: "run.updated",
1010
+ threadId: run.threadId,
1011
+ runId: run.id,
1012
+ ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }),
1013
+ providerInstanceId: run.providerInstanceId,
1014
+ occurredAt: now,
1015
+ payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now },
1016
+ },
1017
+ ];
1018
+ if (attempt !== undefined && rootNode !== undefined) {
1019
+ events.push({
1020
+ type: "run-attempt.updated",
1021
+ threadId: run.threadId,
1022
+ runId: run.id,
1023
+ nodeId: rootNode.id,
1024
+ providerInstanceId: run.providerInstanceId,
1025
+ occurredAt: now,
1026
+ payload: { ...attempt, status: "cancelled", completedAt: now },
1027
+ });
1028
+ }
1029
+ if (rootNode !== undefined) {
1030
+ events.push({
1031
+ type: "node.updated",
1032
+ threadId: run.threadId,
1033
+ runId: run.id,
1034
+ nodeId: rootNode.id,
1035
+ providerInstanceId: run.providerInstanceId,
1036
+ occurredAt: now,
1037
+ payload: { ...rootNode, status: "cancelled", completedAt: now },
1038
+ });
1039
+ }
1040
+ return events;
1041
+}
1042
+
1043
function latestStableRun(
1044
projection: Pick<OrchestrationV2ThreadProjection, "runs">,
1045
): OrchestrationV2Run | null {
@@ -1769,60 +1869,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1869
readonly run: OrchestrationV2Run;
1870
readonly now: DateTime.Utc;
1871
}) {
1772
- const rootNode =
1773
- input.run.rootNodeId === null
1774
- ? undefined
1775
- : input.projection.nodes.find((candidate) => candidate.id === input.run.rootNodeId);
1776
- const attempt =
1777
- input.run.activeAttemptId === null
1778
- ? undefined
1779
- : input.projection.attempts.find(
1780
- (candidate) => candidate.id === input.run.activeAttemptId,
1781
- );
1872
const emitEvent = emit(input.events, input.command);
1783
- yield* emitEvent({
1784
- type: "run.updated",
1785
- threadId: input.run.threadId,
1786
- runId: input.run.id,
1787
- ...(input.run.rootNodeId === null ? {} : { nodeId: input.run.rootNodeId }),
1788
- providerInstanceId: input.run.providerInstanceId,
1789
- occurredAt: input.now,
1790
- payload: {
1791
- ...input.run,
1792
- status: "cancelled",
1793
- queuePosition: null,
1794
- completedAt: input.now,
1795
- },
1796
- });
1797
- if (attempt !== undefined && rootNode !== undefined) {
1798
- yield* emitEvent({
1799
- type: "run-attempt.updated",
1800
- threadId: input.run.threadId,
1801
- runId: input.run.id,
1802
- nodeId: rootNode.id,
1803
- providerInstanceId: input.run.providerInstanceId,
1804
- occurredAt: input.now,
1805
- payload: {
1806
- ...attempt,
1807
- status: "cancelled",
1808
- completedAt: input.now,
1809
- },
1810
- });
1811
- }
1812
- if (rootNode !== undefined) {
1813
- yield* emitEvent({
1814
- type: "node.updated",
1815
- threadId: input.run.threadId,
1816
- runId: input.run.id,
1817
- nodeId: rootNode.id,
1818
- providerInstanceId: input.run.providerInstanceId,
1819
- occurredAt: input.now,
1820
- payload: {
1821
- ...rootNode,
1822
- status: "cancelled",
1823
- completedAt: input.now,
1824
- },
1825
- });
1873
+ for (const event of queuedRunCancellationEvents(input.projection, input.run, input.now)) {
1874
+ yield* emitEvent(event);
1875
}
1876
},
1877
);
@@ -1949,7 +1998,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1998
},
1999
) {
2000
if (!(yield* projectionStore.canStartQueuedRun(threadId))) return;
1952
- const projection = yield* readCommandProjection(threadId);
2001
+ let projection = yield* readCommandProjection(threadId);
2002
if (
2003
projection.thread.archivedAt !== null ||
2004
projection.thread.deletedAt !== null ||
@@ -1958,12 +2007,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2007
return;
2008
}
2009
1961
- const storedQueuedRun =
2010
+ let storedQueuedRun =
2011
options?.queuedRunId === undefined
2012
? nextQueuedRun(projection)
2013
: projection.runs.find(
2014
(run) => run.id === options.queuedRunId && run.status === "queued",
2015
);
2016
+ while (
2017
+ storedQueuedRun !== undefined &&
2018
+ isStalePullRequestWatchWake(projection, storedQueuedRun)
2019
+ ) {
2020
+ yield* writeSystemEvents(
2021
+ queuedRunCancellationEvents(projection, storedQueuedRun, yield* DateTime.now),
2022
+ );
2023
+ projection = yield* readCommandProjection(threadId);
2024
+ storedQueuedRun = nextQueuedRun(projection);
2025
+ }
2026
if (storedQueuedRun === undefined) {
2027
return;
2028
}
@@ -3417,6 +3476,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
3476
}
3477
yield* dispatchThreadMutation(command, events, effects);
3478
if (command.wake === undefined) return;
3479
+ // An idle thread dispatches immediately, bypassing queued-wake validation.
3480
+ if (
3481
+ command.wake.notification.source.kind === "monitor" &&
3482
+ command.watch !== null &&
3483
+ pullRequestSnapshotEndsWatch(link.snapshot, command.startedAt)
3484
+ ) {
3485
+ return;
3486
+ }
3487
yield* dispatchMessage(
3488
{
3489
type: "message.dispatch",
@@ -3424,7 +3491,24 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
3491
threadId: command.threadId,
3492
messageId: command.wake.messageId,
3493
text: command.wake.text,
3427
- notification: command.wake.notification,
3494
+ notification: {
3495
+ ...command.wake.notification,
3496
+ source:
3497
+ command.wake.notification.source.kind === "monitor"
3498
+ ? {
3499
+ kind: "monitor",
3500
+ pullRequest: {
3501
+ ...key,
3502
+ watchStartedAt: command.startedAt,
3503
+ headSha:
3504
+ command.wake.includesRemarks === true
3505
+ ? null
3506
+ : (command.watch?.headSha ?? null),
3507
+ ...(command.watch === null ? { watchEnded: true } : {}),
3508
+ },
3509
+ }
3510
+ : command.wake.notification.source,
3511
+ },
3512
attachments: [],
3513
dispatchMode: { type: "queue_after_active" },
3514
createdBy: "agent",
apps/server/src/orchestration-v2/PullRequestWatchReactor.ts
+15
-8
@@ -284,7 +284,11 @@ export const make = Effect.gen(function* () {
284
const record = Effect.fn("PullRequestWatchReactor.record")(function* (
285
target: WatchTarget,
286
next: ThreadPullRequestWatch | null,
287
- wake?: { readonly text: string; readonly notification: OrchestrationV2Notification },
287
+ wake?: {
288
+ readonly text: string;
289
+ readonly notification: OrchestrationV2Notification;
290
+ readonly includesRemarks?: boolean;
291
+ },
292
endedWatch?: ThreadPullRequestWatch,
293
) {
294
const uuid = yield* random.uuidV4();
@@ -570,13 +574,16 @@ export const make = Effect.gen(function* () {
574
yield* eachTarget(group, (target) => {
575
const report = evaluatePullRequestWatch(target.watch, detail, remarks, now);
576
if (report.changes.length > 0) {
573
- const wake = pullRequestWatchMessage({
574
- number: target.link.number,
575
- url: target.link.url,
576
- baseBranch: detail.baseBranch,
577
- headSha: report.next.headSha,
578
- report,
579
- });
577
+ const wake = {
578
+ ...pullRequestWatchMessage({
579
+ number: target.link.number,
580
+ url: target.link.url,
581
+ baseBranch: detail.baseBranch,
582
+ headSha: report.next.headSha,
583
+ report,
584
+ }),
585
+ includesRemarks: report.changes.some((change) => change.kind === "remarks"),
586
+ };
587
// An ending watch keeps what this pass saw, so watching again starts from it.
588
return (
589
report.exhausted
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+351
@@ -4502,6 +4502,357 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
4502
}),
4503
);
4504
4505
+ const createWatchedThread = Effect.fnUntraced(function* (name: string, reopened = false) {
4506
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
4507
+ const threadId = ThreadId.make(`pr-wake-${name}`);
4508
+ yield* orchestrator.dispatch({
4509
+ type: "thread.create",
4510
+ createdBy: "user",
4511
+ creationSource: "web",
4512
+ commandId: CommandId.make(`${threadId}-create`),
4513
+ threadId,
4514
+ projectId: ProjectId.make(`${threadId}-project`),
4515
+ title: "Watch wake",
4516
+ modelSelection,
4517
+ runtimeMode: "full-access",
4518
+ interactionMode: "default",
4519
+ branch: null,
4520
+ worktreePath: process.cwd(),
4521
+ });
4522
+ const key = { host: "github.com", repository: "pingdotgg/t3code", number: 7 };
4523
+ yield* orchestrator.dispatch({
4524
+ type: "thread.pull-request.watch",
4525
+ commandId: CommandId.make(`${threadId}-watch`),
4526
+ threadId,
4527
+ ...key,
4528
+ watching: true,
4529
+ link: { url: "https://github.com/pingdotgg/t3code/pull/7", source: "agent" },
4530
+ });
4531
+ let watch = (yield* orchestrator.getThreadShell(threadId))?.pullRequests?.[0]?.watch;
4532
+ assert.isDefined(watch);
4533
+ const snapshotSyncedAt = reopened
4534
+ ? DateTime.formatIso(yield* DateTime.now)
4535
+ : "2026-10-02T12:00:00.000Z";
4536
+ if (reopened) {
4537
+ yield* orchestrator.dispatch({
4538
+ type: "thread.pull-request-watch.sync",
4539
+ commandId: CommandId.make(`${threadId}-end-watch`),
4540
+ threadId,
4541
+ ...key,
4542
+ startedAt: watch.startedAt,
4543
+ watch: null,
4544
+ });
4545
+ yield* TestClock.adjust("1 millis");
4546
+ yield* orchestrator.dispatch({
4547
+ type: "thread.pull-request.watch",
4548
+ commandId: CommandId.make(`${threadId}-rewatch`),
4549
+ threadId,
4550
+ ...key,
4551
+ watching: true,
4552
+ });
4553
+ watch = (yield* orchestrator.getThreadShell(threadId))?.pullRequests?.[0]?.watch;
4554
+ assert.isDefined(watch);
4555
+ }
4556
+ return { threadId, key, watch, snapshotSyncedAt };
4557
+ });
4558
+
4559
+ it.effect.each([
4560
+ "unwatch",
4561
+ "unlink",
4562
+ "new watch",
4563
+ "merged",
4564
+ "closed",
4565
+ "newer head",
4566
+ "comments then newer head",
4567
+ "comment limit",
4568
+ "still watching",
4569
+ "closed notice",
4570
+ "closed notice unlinked and relinked",
4571
+ "reopened",
4572
+ ] as const)("revalidates a queued pull-request wake before promotion: %s", (mode) =>
4573
+ Effect.gen(function* () {
4574
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
4575
+ const eventSink = yield* EventSink.EventSinkV2;
4576
+ const { threadId, key, watch, snapshotSyncedAt } = yield* createWatchedThread(
4577
+ `queued-${mode}`,
4578
+ mode === "reopened",
4579
+ );
4580
+ const finalNotice =
4581
+ mode === "closed notice" || mode === "closed notice unlinked and relinked";
4582
+ const deliverable =
4583
+ mode === "still watching" ||
4584
+ mode === "closed notice" ||
4585
+ mode === "reopened" ||
4586
+ mode === "comments then newer head" ||
4587
+ mode === "comment limit";
4588
+ yield* orchestrator.dispatch({
4589
+ type: "message.dispatch",
4590
+ createdBy: "user",
4591
+ creationSource: "web",
4592
+ commandId: CommandId.make(`${threadId}-active`),
4593
+ threadId,
4594
+ messageId: MessageId.make(`${threadId}-active`),
4595
+ text: "Active work",
4596
+ attachments: [],
4597
+ modelSelection,
4598
+ dispatchMode: { type: "start_immediately" },
4599
+ });
4600
+ const wakeMessageId = MessageId.make(`${threadId}-wake`);
4601
+ const recordedWatch = { ...watch, headSha: "abc123", wakes: 1 };
4602
+ yield* orchestrator.dispatch({
4603
+ type: "thread.pull-request-watch.sync",
4604
+ commandId: CommandId.make(`${threadId}-wake`),
4605
+ threadId,
4606
+ ...key,
4607
+ startedAt: watch.startedAt,
4608
+ watch: finalNotice ? null : recordedWatch,
4609
+ wake: {
4610
+ messageId: wakeMessageId,
4611
+ text: finalNotice ? "Closed, stopped watching" : "Checks failed",
4612
+ notification: {
4613
+ source: { kind: "monitor" },
4614
+ outcome: "updated",
4615
+ summary: finalNotice ? "#7: closed, stopped watching" : "#7: checks failed",
4616
+ },
4617
+ ...(mode === "comments then newer head" || mode === "comment limit"
4618
+ ? { includesRemarks: true }
4619
+ : {}),
4620
+ },
4621
+ });
4622
+ const userMessageId = MessageId.make(`${threadId}-user`);
4623
+ yield* orchestrator.dispatch({
4624
+ type: "message.dispatch",
4625
+ createdBy: "user",
4626
+ creationSource: "web",
4627
+ commandId: CommandId.make(`${threadId}-user`),
4628
+ threadId,
4629
+ messageId: userMessageId,
4630
+ text: "User follow-up",
4631
+ attachments: [],
4632
+ modelSelection,
4633
+ dispatchMode: { type: "queue_after_active" },
4634
+ });
4635
+ const before = yield* orchestrator.getThreadProjection(threadId);
4636
+ const activeRun = before.runs.find((run) => run.status === "starting");
4637
+ const wakeRun = before.runs.find((run) => run.userMessageId === wakeMessageId);
4638
+ const userRun = before.runs.find((run) => run.userMessageId === userMessageId);
4639
+ assert.isDefined(activeRun);
4640
+ assert.isDefined(wakeRun);
4641
+ assert.isDefined(userRun);
4642
+ assert.equal(wakeRun.status, "queued");
4643
+ assert.equal(userRun.status, "queued");
4644
+
4645
+ if (mode === "unwatch" || mode === "new watch") {
4646
+ yield* orchestrator.dispatch({
4647
+ type: "thread.pull-request.watch",
4648
+ commandId: CommandId.make(`${threadId}-unwatch`),
4649
+ threadId,
4650
+ ...key,
4651
+ watching: false,
4652
+ });
4653
+ if (mode === "new watch") {
4654
+ yield* TestClock.adjust("1 millis");
4655
+ yield* orchestrator.dispatch({
4656
+ type: "thread.pull-request.watch",
4657
+ commandId: CommandId.make(`${threadId}-rewatch`),
4658
+ threadId,
4659
+ ...key,
4660
+ watching: true,
4661
+ });
4662
+ const restarted = (yield* orchestrator.getThreadShell(threadId))?.pullRequests?.[0]
4663
+ ?.watch;
4664
+ assert.isDefined(restarted);
4665
+ assert.notEqual(restarted.startedAt, watch.startedAt);
4666
+ yield* orchestrator.dispatch({
4667
+ type: "thread.pull-request-watch.sync",
4668
+ commandId: CommandId.make(`${threadId}-same-head`),
4669
+ threadId,
4670
+ ...key,
4671
+ startedAt: restarted.startedAt,
4672
+ watch: { ...restarted, headSha: recordedWatch.headSha },
4673
+ });
4674
+ }
4675
+ } else if (mode === "unlink" || mode === "closed notice unlinked and relinked") {
4676
+ yield* orchestrator.dispatch({
4677
+ type: "thread.pull-request.unlink",
4678
+ commandId: CommandId.make(`${threadId}-unlink`),
4679
+ threadId,
4680
+ ...key,
4681
+ });
4682
+ if (mode === "closed notice unlinked and relinked") {
4683
+ yield* orchestrator.dispatch({
4684
+ type: "thread.pull-request.link",
4685
+ commandId: CommandId.make(`${threadId}-relink`),
4686
+ threadId,
4687
+ ...key,
4688
+ url: "https://github.com/pingdotgg/t3code/pull/7",
4689
+ source: "manual",
4690
+ });
4691
+ }
4692
+ } else if (
4693
+ mode === "merged" ||
4694
+ mode === "closed" ||
4695
+ mode === "closed notice" ||
4696
+ mode === "reopened"
4697
+ ) {
4698
+ yield* orchestrator.dispatch({
4699
+ type: "thread.pull-request-link.sync",
4700
+ commandId: CommandId.make(`${threadId}-snapshot`),
4701
+ threadId,
4702
+ ...key,
4703
+ snapshot: {
4704
+ state: mode === "merged" ? "merged" : "closed",
4705
+ title: "Watched pull request",
4706
+ headBranch: "feature",
4707
+ baseBranch: "main",
4708
+ isDraft: false,
4709
+ updatedAt: null,
4710
+ // A delayed sync can still report the closure from before this watch restarted.
4711
+ syncedAt: snapshotSyncedAt,
4712
+ },
4713
+ stack: null,
4714
+ });
4715
+ } else if (mode === "comment limit") {
4716
+ yield* orchestrator.dispatch({
4717
+ type: "thread.pull-request-watch.sync",
4718
+ commandId: CommandId.make(`${threadId}-exhausted`),
4719
+ threadId,
4720
+ ...key,
4721
+ startedAt: watch.startedAt,
4722
+ watch: null,
4723
+ endedWatch: recordedWatch,
4724
+ wake: {
4725
+ messageId: MessageId.make(`${threadId}-exhausted`),
4726
+ text: "New comments, stopped watching",
4727
+ notification: {
4728
+ source: { kind: "monitor" },
4729
+ outcome: "updated",
4730
+ summary: "#7: new comments, stopped watching",
4731
+ },
4732
+ includesRemarks: true,
4733
+ },
4734
+ });
4735
+ } else if (mode === "newer head" || mode === "comments then newer head") {
4736
+ yield* orchestrator.dispatch({
4737
+ type: "thread.pull-request-watch.sync",
4738
+ commandId: CommandId.make(`${threadId}-advance`),
4739
+ threadId,
4740
+ ...key,
4741
+ startedAt: watch.startedAt,
4742
+ watch: { ...recordedWatch, headSha: "def456" },
4743
+ });
4744
+ }
4745
+
4746
+ const afterSequence = yield* orchestrator.getThreadEventSequence(threadId);
4747
+ const completedAt = yield* DateTime.now;
4748
+ yield* eventSink.write({
4749
+ events: [
4750
+ {
4751
+ id: EventId.make(`${threadId}-completed`),
4752
+ type: "run.updated",
4753
+ threadId,
4754
+ runId: activeRun.id,
4755
+ ...(activeRun.rootNodeId === null ? {} : { nodeId: activeRun.rootNodeId }),
4756
+ providerInstanceId: activeRun.providerInstanceId,
4757
+ occurredAt: completedAt,
4758
+ payload: { ...activeRun, status: "completed", completedAt },
4759
+ },
4760
+ ],
4761
+ });
4762
+ yield* eventSink.stream({ threadId, afterSequence }).pipe(
4763
+ Stream.filter(
4764
+ (stored) =>
4765
+ stored.event.type === "run.updated" && stored.event.payload.status === "starting",
4766
+ ),
4767
+ Stream.take(1),
4768
+ Stream.runDrain,
4769
+ );
4770
+ const after = yield* orchestrator.getThreadProjection(threadId);
4771
+ assert.equal(
4772
+ after.runs.find((run) => run.id === wakeRun.id)?.status,
4773
+ deliverable ? "starting" : "cancelled",
4774
+ );
4775
+ assert.equal(
4776
+ after.runs.find((run) => run.id === userRun.id)?.status,
4777
+ deliverable ? "queued" : "starting",
4778
+ );
4779
+ if (!deliverable) {
4780
+ assert.equal(
4781
+ after.attempts.find((attempt) => attempt.id === wakeRun.activeAttemptId)?.status,
4782
+ "cancelled",
4783
+ );
4784
+ assert.equal(
4785
+ after.nodes.find((node) => node.id === wakeRun.rootNodeId)?.status,
4786
+ "cancelled",
4787
+ );
4788
+ assert.isFalse(after.turnItems.some((item) => item.runId === wakeRun.id));
4789
+ }
4790
+ assert.deepEqual(
4791
+ after.messages
4792
+ .filter((message) => message.id === wakeMessageId)
4793
+ .map((message) => message.notification?.summary),
4794
+ [finalNotice ? "#7: closed, stopped watching" : "#7: checks failed"],
4795
+ );
4796
+ }),
4797
+ );
4798
+
4799
+ it.effect.each(["open", "merged", "closed", "closed notice", "reopened"] as const)(
4800
+ "revalidates a pull-request wake before idle dispatch: %s",
4801
+ (mode) =>
4802
+ Effect.gen(function* () {
4803
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
4804
+ const { threadId, key, watch, snapshotSyncedAt } = yield* createWatchedThread(
4805
+ `idle-${mode}`,
4806
+ mode === "reopened",
4807
+ );
4808
+ yield* orchestrator.dispatch({
4809
+ type: "thread.pull-request-link.sync",
4810
+ commandId: CommandId.make(`${threadId}-snapshot`),
4811
+ threadId,
4812
+ ...key,
4813
+ snapshot: {
4814
+ state: mode === "closed notice" || mode === "reopened" ? "closed" : mode,
4815
+ title: "Watched pull request",
4816
+ headBranch: "feature",
4817
+ baseBranch: "main",
4818
+ isDraft: false,
4819
+ updatedAt: null,
4820
+ syncedAt: snapshotSyncedAt,
4821
+ },
4822
+ stack: null,
4823
+ });
4824
+ const wakeMessageId = MessageId.make(`${threadId}-wake`);
4825
+ yield* orchestrator.dispatch({
4826
+ type: "thread.pull-request-watch.sync",
4827
+ commandId: CommandId.make(`${threadId}-wake`),
4828
+ threadId,
4829
+ ...key,
4830
+ startedAt: watch.startedAt,
4831
+ watch: mode === "closed notice" ? null : { ...watch, headSha: "abc123", wakes: 1 },
4832
+ wake: {
4833
+ messageId: wakeMessageId,
4834
+ text: mode === "closed notice" ? "Closed, stopped watching" : "Checks failed",
4835
+ notification: {
4836
+ source: { kind: "monitor" },
4837
+ outcome: "updated",
4838
+ summary:
4839
+ mode === "closed notice" ? "#7: closed, stopped watching" : "#7: checks failed",
4840
+ },
4841
+ },
4842
+ });
4843
+ const after = yield* orchestrator.getThreadProjection(threadId);
4844
+ const deliverable = mode === "open" || mode === "closed notice" || mode === "reopened";
4845
+ assert.deepEqual(
4846
+ after.runs.map((run) => [run.userMessageId, run.status]),
4847
+ deliverable ? [[wakeMessageId, "starting"]] : [],
4848
+ );
4849
+ assert.deepEqual(
4850
+ after.messages.map((message) => message.id),
4851
+ deliverable ? [wakeMessageId] : [],
4852
+ );
4853
+ }),
4854
+ );
4855
+
4856
it.effect("reads each watched PR as soon as its own fingerprint lands", () =>
4857
Effect.gen(function* () {
4858
const orchestrator = yield* Orchestrator.OrchestratorV2;
packages/contracts/src/orchestrationV2.ts
+14
-1
@@ -1294,7 +1294,18 @@ export const OrchestrationV2NotificationSource = kindUnionWithFallback(
1294
Schema.Struct({ kind: Schema.Literal("background_command").transform("command") }),
1295
SubagentNotificationSource,
1296
CommandNotificationSource,
1297
- Schema.Struct({ kind: Schema.Literal("monitor") }),
1297
+ Schema.Struct({
1298
+ kind: Schema.Literal("monitor"),
1299
+ pullRequest: Schema.optional(
1300
+ Schema.Struct({
1301
+ ...ThreadPullRequestKey.fields,
1302
+ watchStartedAt: IsoDateTime,
1303
+ /** Null when the wake is not about one head, so a newer push does not outdate it. */
1304
+ headSha: Schema.NullOr(TrimmedNonEmptyString),
1305
+ watchEnded: Schema.optional(Schema.Boolean),
1306
+ }),
1307
+ ),
1308
+ }),
1309
Schema.Struct({ kind: Schema.Literal("background_task") }),
1310
Schema.Struct({ kind: Schema.Literal("system") }),
1311
],
@@ -3466,6 +3477,8 @@ const OrchestrationV2InternalCommand = Schema.Union([
3477
messageId: MessageId,
3478
text: Schema.String,
3479
notification: OrchestrationV2Notification,
3480
+ /** Comments stay worth reading after a push, so the wake outlives a newer head. */
3481
+ includesRemarks: Schema.optional(Schema.Boolean),
3482
}),
3483
),
3484
}),