Skip to content

Commit 4e1f681

Browse files
donjor-agent[bot]donjor
authored andcommitted
fix(server): an ended PR watch cancels its queued wakes (#1628)
## Problem A PR watch wake queued behind a busy turn still ran after its watch ended. The agent then got a turn about a pull request it had unwatched, or one that had merged. ## Change When a mutation ends a watch, the orchestrator cancels that pull request's queued wakes. | Ends a watch | Cancels | | --- | --- | | `thread.pull-request.unlink` | queued wakes for that PR | | `thread.pull-request.watch`, `watching: false` | same | | `thread.pull-request-watch.sync` to `null` | same; its own last wake survives | - **Match:** wake id prefix `pr-watch:<host/repo#N>:` - **Other PRs:** their wakes stay queued ## Scope and approval Closes #1627 ## Verification | Command | Result | | --- | --- | | `vp test run` on the new `.fork.test.ts` | 1 passed | | Same test, `Orchestrator.ts` change reverted | fails: `checks-7` still queued | | Watch tests (`-t "watch"`) | 6 passed | | Server `tsc --noEmit` | exit 0 | | `vp run fork:ci` | exit 0 | | `git merge-tree` against `upstream/main` | clean | ### Recordings Dev web build, this branch. Prompt: watch `RSI-Software/infra#97`, run a 90s foreground wait, unwatch, reply "done". **Before** (`hyprws` at `73e0f4cbe4c`): a stale `#97` wake starts a second turn after "done". https://github.com/user-attachments/assets/8bb14b04-a2cd-4703-9991-820a37529587 **After** (`33d1b2c1ea7`): the thread ends at "done". https://github.com/user-attachments/assets/88b280ad-47e1-40bd-86e3-687db4549ea5 <details> <summary>Cut tables and run events</summary> | Span | Before real | After real | Clip | | --- | --- | --- | --- | | take start | 2s | 3s | cut | | send | 4s | 4s | 1x | | watch, wait, unwatch | 98s | 101s | 25x | | "done" and what follows | 11s | 13s | 1x | | idle tail | 178s | 38s | cut | The queued wake has no on-screen marker, so the dev database shows it: | Run | Before | After | | --- | --- | --- | | wake queued | +36s | +56s | | unwatch | +95s | +110s | | wake run | started +106s, completed | cancelled +110s | | runs after "done" | 1 | 0 | </details> Model: Claude Opus 5.5 in Claude Code, inside T3 Code. ## Fork trailers Squashes: - fdc56d2 fix(server): an ended PR watch cancels its queued wakes (#1628) (#1628) - 31fd05b fixup! fix(server): an ended PR watch cancels its queued wakes (#1628) (#1628) - 277b116 fix(server): an ended PR watch cancels its queued wakes (#1628) (#1628) - 0ee7c5c fixup! fix(server): an ended PR watch cancels its queued wakes (#1628) (#1628) Fork-Domain: upstream-fixes Fork-Tier: bugfix Fork-Upstreamable: yes Co-authored-by: donjor <[email protected]>
1 parent 1f6543e commit 4e1f681

4 files changed

Lines changed: 221 additions & 2 deletions

File tree

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
import { assert, it } from "@effect/vitest";
2+
import {
3+
CommandId,
4+
MessageId,
5+
ProjectId,
6+
ProviderDriverKind,
7+
ProviderInstanceId,
8+
ThreadId,
9+
} from "@t3tools/contracts";
10+
import * as Effect from "effect/Effect";
11+
12+
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
13+
import * as Orchestrator from "./Orchestrator.ts";
14+
import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
15+
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
16+
import { pullRequestWatchWakePrefix } from "./pullRequestWatch.ts";
17+
import { makeOrchestratorV2ReplayLayerWithRegistry } from "./testkit/ProviderReplayHarness.ts";
18+
19+
// Fork: a pull request watch wake queued behind a busy turn is cancelled when its watch ends,
20+
// so the agent is not woken about a pull request it stopped watching or that merged meanwhile.
21+
22+
const driver = ProviderDriverKind.make("codex");
23+
const instanceId = ProviderInstanceId.make("codex");
24+
const modelSelection = { instanceId, model: "test-model" };
25+
const adapter: ProviderAdapterV2Shape = {
26+
instanceId,
27+
driver,
28+
getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
29+
planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
30+
openSession: () => Effect.die("watch wake tests start no session"),
31+
};
32+
const layer = makeOrchestratorV2ReplayLayerWithRegistry(
33+
{ name: "pull-request-watch-wakes-fork" },
34+
ProviderAdapterRegistry.makeLayer([adapter]),
35+
{ runEffectWorker: false },
36+
);
37+
38+
const threadId = ThreadId.make("pr-watch-wakes");
39+
const repository = { host: "github.com", repository: "rsi-software/t3code-hyprws" };
40+
41+
it.layer(layer)("pull request watch wakes (fork)", (it) => {
42+
it.effect("cancels the queued wakes of a watch that ends, and keeps its last wake", () =>
43+
Effect.gen(function* () {
44+
const orchestrator = yield* Orchestrator.OrchestratorV2;
45+
yield* orchestrator.dispatch({
46+
type: "thread.create",
47+
commandId: CommandId.make("pr-watch-wakes-create"),
48+
threadId,
49+
projectId: ProjectId.make("pr-watch-wakes-project"),
50+
title: "Watch wakes",
51+
modelSelection,
52+
runtimeMode: "full-access",
53+
interactionMode: "default",
54+
branch: null,
55+
worktreePath: null,
56+
createdBy: "user",
57+
creationSource: "web",
58+
});
59+
for (const number of [7, 8, 9]) {
60+
yield* orchestrator.dispatch({
61+
type: "thread.pull-request.watch",
62+
commandId: CommandId.make(`pr-watch-wakes-start-${number}`),
63+
threadId,
64+
...repository,
65+
number,
66+
watching: true,
67+
link: {
68+
url: `https://github.com/rsi-software/t3code-hyprws/pull/${number}`,
69+
source: "agent",
70+
},
71+
});
72+
}
73+
// The agent is busy, so every wake below queues behind this turn.
74+
yield* orchestrator.dispatch({
75+
type: "message.dispatch",
76+
commandId: CommandId.make("pr-watch-wakes-busy"),
77+
threadId,
78+
messageId: MessageId.make("pr-watch-wakes-busy"),
79+
text: "Busy",
80+
attachments: [],
81+
modelSelection,
82+
dispatchMode: { type: "start_immediately" },
83+
createdBy: "user",
84+
creationSource: "web",
85+
});
86+
87+
const linkOf = (number: number) =>
88+
Effect.map(orchestrator.getThreadShell(threadId), (thread) =>
89+
thread?.pullRequests?.find((link) => link.number === number),
90+
);
91+
const sync = (number: number, ending: boolean, wake: string | null) =>
92+
Effect.gen(function* () {
93+
const link = yield* linkOf(number);
94+
if (link?.watch === undefined) return yield* Effect.die(`#${number} is not watched`);
95+
yield* orchestrator.dispatch({
96+
type: "thread.pull-request-watch.sync",
97+
commandId: CommandId.make(`pr-watch-wakes-sync-${number}-${wake ?? "end"}`),
98+
threadId,
99+
...repository,
100+
number,
101+
startedAt: link.watch.startedAt,
102+
watch: ending ? null : { ...link.watch, wakes: link.watch.wakes + 1 },
103+
...(wake === null
104+
? {}
105+
: {
106+
wake: {
107+
messageId: MessageId.make(`${pullRequestWatchWakePrefix(link)}${wake}`),
108+
text: `Update on #${number}`,
109+
notification: {
110+
source: { kind: "monitor" },
111+
outcome: "updated",
112+
summary: `#${number}: checks passed`,
113+
},
114+
},
115+
}),
116+
});
117+
});
118+
const queued = Effect.map(orchestrator.getThreadProjection(threadId), (projection) =>
119+
projection.runs
120+
.filter((run) => run.status === "queued")
121+
.map((run) => run.userMessageId.split(":").at(-1))
122+
.toSorted(),
123+
);
124+
125+
yield* sync(7, false, "checks-7");
126+
yield* sync(8, false, "checks-8");
127+
yield* sync(9, false, "checks-9");
128+
assert.deepEqual(yield* queued, ["checks-7", "checks-8", "checks-9"]);
129+
130+
// #7 merged: the watch ends with no wake of its own.
131+
yield* sync(7, true, null);
132+
assert.deepEqual(yield* queued, ["checks-8", "checks-9"]);
133+
134+
// The agent stops watching #8.
135+
yield* orchestrator.dispatch({
136+
type: "thread.pull-request.watch",
137+
commandId: CommandId.make("pr-watch-wakes-stop-8"),
138+
threadId,
139+
...repository,
140+
number: 8,
141+
watching: false,
142+
});
143+
assert.deepEqual(yield* queued, ["checks-9"]);
144+
145+
// #9 gives up with a last wake: that one stays, the stale one before it goes.
146+
yield* sync(9, true, "stopped-9");
147+
assert.deepEqual(yield* queued, ["stopped-9"]);
148+
}),
149+
);
150+
});

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

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,7 @@ import {
166166
ThreadForkServiceV2,
167167
} from "./ThreadForkService.ts";
168168
import { planThreadDeletion } from "./ThreadDeletion.ts";
169+
import { pullRequestWatchWakePrefix } from "./pullRequestWatch.ts";
169170
import { dispatchThreadIssueCommandFork } from "./ThreadIssues.fork.ts"; // fork-hook: github-issues/orchestrator-issues-import
170171
import { recordCheckoutRecoveryFork } from "./checkoutMove.fork.ts"; // fork-hook: zmux-estate/decider-recovery-record-import
171172
import {
@@ -2829,6 +2830,48 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
28292830
return decided.success;
28302831
});
28312832

2833+
// A wake queued behind a busy turn would report on a watch that has since ended, often on a
2834+
// pull request that merged meanwhile. A watch's own last wake is queued after this runs.
2835+
const cancelEndedWatchWakes = Effect.fn("orchestrationV2.dispatch.cancelEndedWatchWakes")(
2836+
function* (
2837+
command: OrchestrationV2ServerCommand,
2838+
thread: OrchestrationV2AppThread,
2839+
updatedThread: OrchestrationV2AppThread,
2840+
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
2841+
) {
2842+
const next = threadPullRequestsOf(updatedThread);
2843+
const prefixes = threadPullRequestsOf(thread)
2844+
.filter(
2845+
(link) =>
2846+
link.watch !== undefined &&
2847+
next.find((candidate) => threadPullRequestKeysEqual(candidate, link))?.watch ===
2848+
undefined,
2849+
)
2850+
.map(pullRequestWatchWakePrefix);
2851+
if (prefixes.length === 0) return;
2852+
const { runs } = yield* projectionStore
2853+
.getThreadRecords(thread.id, ["runs"])
2854+
.pipe(mapDispatchError(command));
2855+
for (const run of runs) {
2856+
if (
2857+
run.status !== "queued" ||
2858+
!prefixes.some((prefix) => run.userMessageId.startsWith(prefix))
2859+
) {
2860+
continue;
2861+
}
2862+
yield* dispatchQueuedRunCancel(
2863+
{
2864+
type: "queued-run.cancel",
2865+
commandId: command.commandId,
2866+
threadId: thread.id,
2867+
runId: run.id,
2868+
},
2869+
events,
2870+
);
2871+
}
2872+
},
2873+
);
2874+
28322875
const dispatchThreadMutation = Effect.fn("orchestrationV2.dispatch.threadMutation")(function* (
28332876
command: Extract<
28342877
OrchestrationV2ServerCommand,
@@ -3728,6 +3771,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
37283771
occurredAt: now,
37293772
payload: link,
37303773
});
3774+
yield* cancelEndedWatchWakes(command, thread, updatedThread, events); // fork-hook: upstream-fixes/pr-watch-sync-wake-cancel
37313775
return;
37323776
}
37333777
const eventType = (() => {
@@ -3807,6 +3851,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
38073851
]);
38083852
}
38093853

3854+
if (
3855+
command.type === "thread.pull-request.unlink" ||
3856+
command.type === "thread.pull-request.watch"
3857+
) {
3858+
yield* cancelEndedWatchWakes(command, thread, updatedThread, events);
3859+
}
3860+
38103861
if (command.type === "thread.archive") {
38113862
const projection = yield* loadProjectionForCommand(
38123863
command,

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

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,11 @@ import * as PullRequestService from "../pullRequest/PullRequestService.ts";
3434
import { forkParked } from "../serverActivation.ts";
3535
import * as Orchestrator from "./Orchestrator.ts";
3636
import * as ProjectionStore from "./ProjectionStore.ts";
37-
import { evaluatePullRequestWatch, pullRequestWatchMessage } from "./pullRequestWatch.ts";
37+
import {
38+
evaluatePullRequestWatch,
39+
pullRequestWatchMessage,
40+
pullRequestWatchWakePrefix,
41+
} from "./pullRequestWatch.ts";
3842

3943
/** Checks take minutes; faster sweeps waste the account's shared host quota. */
4044
const SWEEP_MINUTES = 2;
@@ -274,7 +278,12 @@ export const make = Effect.gen(function* () {
274278
...(endedWatch === undefined ? {} : { endedWatch }),
275279
...(wake === undefined
276280
? {}
277-
: { wake: { ...wake, messageId: MessageId.make(`message:pr-watch:${uuid}`) } }),
281+
: {
282+
wake: {
283+
...wake,
284+
messageId: MessageId.make(`${pullRequestWatchWakePrefix(target.link)}${uuid}`),
285+
},
286+
}),
278287
});
279288
});
280289

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ import type {
33
PullRequestCheck,
44
PullRequestComment,
55
PullRequestDetail,
6+
ThreadPullRequestLink,
67
ThreadPullRequestWatch,
78
} from "@t3tools/contracts";
89
import * as DateTime from "effect/DateTime";
10+
import { threadPullRequestKeyOf } from "../sourceControl/threadPullRequests.ts";
911

1012
/** Bounds consecutive comment-only wakes to stop bot reply loops; check, conflict, or push news resets it. */
1113
export const PULL_REQUEST_WATCH_WAKE_LIMIT = 10;
@@ -214,6 +216,13 @@ const SUMMARY: Record<PullRequestWatchChange["kind"], string> = {
214216
conflicting: "merge conflict",
215217
};
216218

219+
/**
220+
* Starts the message id of every wake for a pull request, so the wakes still queued behind a
221+
* busy turn can be found when its watch ends.
222+
*/
223+
export const pullRequestWatchWakePrefix = (link: ThreadPullRequestLink) =>
224+
`message:pr-watch:${threadPullRequestKeyOf(link)}:`;
225+
217226
export function pullRequestWatchMessage(input: {
218227
readonly number: number;
219228
readonly url: string;

0 commit comments

Comments
 (0)