Skip to content

Commit b976b00

Browse files
fix(server): an agent's own merge or close ends its watch without a wake
The merge wake also fired when the thread's own agent had just merged the pull request with its host's CLI, costing a turn to tell it what it already knew. The watch reactor now follows the thread's merge and close commands: a pull request that ends while one runs, or since one ended after the last read that found it open, ends its watch quietly, and the command's end reads the thread's watches at once. A merge that lands later, as with `--auto`, still wakes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 564c710 commit b976b00

5 files changed

Lines changed: 240 additions & 10 deletions

File tree

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

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,10 @@ import {
1616
threadPullRequestKeysEqual,
1717
visibleThreadPullRequests,
1818
} from "../sourceControl/threadPullRequests.ts";
19-
import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
19+
import {
20+
isChangeRequestCloseCommand,
21+
sourceControlDefinitions,
22+
} from "../sourceControl/sourceControlDefinitions.ts";
2023
import * as Cause from "effect/Cause";
2124
import * as Clock from "effect/Clock";
2225
import * as Context from "effect/Context";
@@ -48,11 +51,6 @@ const QUIET_SYNC_INTERVAL_MS = 5 * 60 * 1_000;
4851
// does merged ones. A reader that sees it open, or a requested refresh, still reads it at once.
4952
const CLOSED_FINAL_AFTER_MS = 24 * 60 * 60 * 1_000;
5053

51-
const isChangeRequestCloseCommand = (command: string) =>
52-
sourceControlDefinitions.definitions.some(
53-
(definition) => definition.changeRequestCloseCommand?.test(command) === true,
54-
);
55-
5654
// Where a shell starts a command, past `NAME=value` assignments and wrappers like `timeout 60`.
5755
// A create command anywhere else, as in `echo "gh pr create"`, is text, not a command that runs.
5856
const COMMAND_START =

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

Lines changed: 92 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import {
22
CommandId,
3+
isOrchestrationV2WorkActive,
34
MessageId,
45
type OrchestrationV2Notification,
56
type PullRequestActivity,
@@ -8,8 +9,10 @@ import {
89
type PullRequestRef,
910
type PullRequestThreadCommentsResult,
1011
type ThreadPullRequestLink,
12+
type ThreadId,
1113
type ThreadPullRequestWatch,
1214
} from "@t3tools/contracts";
15+
import { isChangeRequestCloseCommand } from "../sourceControl/sourceControlDefinitions.ts";
1316
import {
1417
normalizeThreadPullRequestKey,
1518
threadPullRequestKeyOf,
@@ -38,6 +41,7 @@ import * as PullRequestService from "../pullRequest/PullRequestService.ts";
3841
import { forkParked } from "../serverActivation.ts";
3942
import * as Orchestrator from "./Orchestrator.ts";
4043
import * as ProjectionStore from "./ProjectionStore.ts";
44+
import { isTerminalRunStatus } from "./ThreadManagementService.ts";
4145
import {
4246
combinePullRequestWatchWakes,
4347
evaluatePullRequestWatch,
@@ -287,6 +291,22 @@ export const make = Effect.gen(function* () {
287291
// A pass reads watches and records new ones, so passes must not overlap.
288292
const passes = Semaphore.makeUnsafe(1);
289293
const lastReads = new Map<string, LastRead>();
294+
/** When each group's last read that found its pull request open began. */
295+
const openAt = new Map<string, number>();
296+
/** The merge and close commands each thread's agent ran with its host's CLI. */
297+
const agentEnds = new Map<
298+
ThreadId,
299+
{ readonly running: Set<string>; readonly finished: Set<string>; endedAt: number }
300+
>();
301+
// The agent needs no wake for its own merge or close. Only a command that ran since a read last
302+
// found the pull request open can have ended it; a merge that lands later, as with `--auto`, is news.
303+
const endedByAgent = (target: WatchTarget, openSince: number | undefined) => {
304+
const ends = agentEnds.get(target.thread.id);
305+
return (
306+
ends !== undefined &&
307+
(ends.running.size > 0 || ends.endedAt > (openSince ?? Date.parse(target.watch.startedAt)))
308+
);
309+
};
290310
const threadTails = new Map<
291311
string,
292312
{
@@ -650,8 +670,16 @@ export const make = Effect.gen(function* () {
650670
}
651671
if (detail.state !== "open") {
652672
lastReads.delete(group.key);
653-
return yield* eachTarget(group, (target) => finished(group.key, target, detail));
673+
const openSince = openAt.get(group.key);
674+
openAt.delete(group.key);
675+
const reason = detail.state === "merged" ? "merged" : "closed";
676+
return yield* eachTarget(group, (target) =>
677+
endedByAgent(target, openSince)
678+
? record(target, null).pipe(Effect.tap(() => ended(target, reason)))
679+
: finished(group.key, target, detail),
680+
);
654681
}
682+
openAt.set(group.key, now);
655683

656684
// Never advance the remark watermark past comments an incomplete read could have missed.
657685
const remarks = Option.isSome(activity)
@@ -749,9 +777,12 @@ export const make = Effect.gen(function* () {
749777
}));
750778
if (changed === undefined) {
751779
currentGroups = groups;
752-
for (const cache of [readFailures, lastReads, threadTails]) {
780+
for (const cache of [readFailures, lastReads, threadTails, openAt]) {
753781
for (const key of cache.keys()) if (!byPullRequest.has(key)) cache.delete(key);
754782
}
783+
const watching = new Set(targets.map((target) => target.thread.id));
784+
for (const threadId of agentEnds.keys())
785+
if (!watching.has(threadId)) agentEnds.delete(threadId);
755786
}
756787
yield* Effect.forEach(
757788
ending,
@@ -821,9 +852,68 @@ export const make = Effect.gen(function* () {
821852
Effect.withSpan("PullRequestWatchReactor.readOnChange"),
822853
);
823854

855+
const readThreadWatches = (threadId: ThreadId) =>
856+
projections.getThreadsWithPullRequests(threadId).pipe(
857+
Effect.flatMap((threads) =>
858+
Effect.forEach(
859+
new Set(
860+
threads.flatMap((thread) =>
861+
visibleThreadPullRequests(thread.pullRequests ?? [])
862+
.filter((link) => link.watch !== undefined)
863+
.map(threadPullRequestKeyOf),
864+
),
865+
),
866+
readOnChange,
867+
{ discard: true },
868+
),
869+
),
870+
Effect.catchCause(logFailure("pull request watch read after a merge failed", { threadId })),
871+
);
872+
824873
const start: PullRequestWatchReactor["Service"]["start"] = Effect.fn(
825874
"PullRequestWatchReactor.start",
826875
)(function* () {
876+
// Reading a thread's watches once its agent's merge or close ends lets them end at once, and
877+
// without a wake, rather than at the next sweep.
878+
const agentReads = yield* FiberMap.make<ThreadId>();
879+
const commandEnded = Effect.fn("PullRequestWatchReactor.commandEnded")(function* (
880+
threadId: ThreadId,
881+
) {
882+
const ends = agentEnds.get(threadId);
883+
if (ends !== undefined) ends.endedAt = yield* Clock.currentTimeMillis;
884+
yield* FiberMap.run(agentReads, threadId)(readThreadWatches(threadId));
885+
});
886+
yield* forkParked(
887+
Stream.runForEach(engine.streamDomainEvents, (event) => {
888+
if (event.type === "run.updated") {
889+
const ends = agentEnds.get(event.threadId);
890+
// A run can stop before its command reports that it ended.
891+
if (ends === undefined || ends.running.size === 0) return Effect.void;
892+
if (!isTerminalRunStatus(event.payload.status)) return Effect.void;
893+
ends.running.clear();
894+
return commandEnded(event.threadId);
895+
}
896+
if (event.type !== "turn-item.updated") return Effect.void;
897+
const item = event.payload;
898+
if (item.type !== "command_execution" || !isChangeRequestCloseCommand(item.input)) {
899+
return Effect.void;
900+
}
901+
const ends = agentEnds.get(event.threadId) ?? {
902+
running: new Set<string>(),
903+
finished: new Set<string>(),
904+
endedAt: 0,
905+
};
906+
agentEnds.set(event.threadId, ends);
907+
if (ends.finished.has(item.id)) return Effect.void;
908+
if (isOrchestrationV2WorkActive(item.status)) {
909+
ends.running.add(item.id);
910+
return Effect.void;
911+
}
912+
ends.running.delete(item.id);
913+
ends.finished.add(item.id);
914+
return commandEnded(event.threadId);
915+
}).pipe(Effect.catchCause(logFailure("pull request watch command stream failed", {}))),
916+
);
827917
// One feed per pull request: the host keeps one subscription per pull request and account.
828918
const feeds = yield* FiberMap.make<string>();
829919
const follow = Effect.gen(function* () {

‎apps/server/src/orchestration-v2/runtimeLayer.test.ts‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
RuntimeRequestId,
2222
TurnItemId,
2323
type ModelSelection,
24+
type OrchestrationV2DomainEvent,
2425
type OrchestrationV2Run,
2526
type OrchestrationV2ShellSnapshot,
2627
type OrchestrationV2RuntimeRequest,
@@ -4035,6 +4036,141 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
40354036
}),
40364037
);
40374038

4039+
it.effect("ends a watch without a wake when the thread's own agent merged it", () =>
4040+
Effect.gen(function* () {
4041+
const orchestrator = yield* Orchestrator.OrchestratorV2;
4042+
const threadId = ThreadId.make("runtime-pull-request-watch-own-merge");
4043+
const projectId = ProjectId.make("pr-watch-own-merge-project");
4044+
yield* seedProject({
4045+
projectId,
4046+
title: "Watch own merge",
4047+
workspaceRoot: "/workspace/watch-own-merge",
4048+
defaultModelSelection: null,
4049+
createdAt: "2026-10-01T00:00:00.000Z",
4050+
});
4051+
yield* orchestrator.dispatch({
4052+
type: "thread.create",
4053+
createdBy: "user",
4054+
creationSource: "web",
4055+
commandId: CommandId.make("pr-watch-own-merge-create"),
4056+
threadId,
4057+
projectId,
4058+
title: "Watch own merge",
4059+
modelSelection,
4060+
runtimeMode: "full-access",
4061+
interactionMode: "default",
4062+
branch: null,
4063+
worktreePath: null,
4064+
});
4065+
for (const number of [19, 20]) {
4066+
yield* orchestrator.dispatch({
4067+
type: "thread.pull-request.watch",
4068+
commandId: CommandId.make(`pr-watch-own-merge-start-${number}`),
4069+
threadId,
4070+
host: "github.com",
4071+
repository: "pingdotgg/t3code",
4072+
number,
4073+
watching: true,
4074+
link: { url: `https://github.com/pingdotgg/t3code/pull/${number}`, source: "agent" },
4075+
});
4076+
}
4077+
4078+
const states = new Map<number, PullRequestDetail["state"]>([
4079+
[19, "open"],
4080+
[20, "open"],
4081+
]);
4082+
let fingerprints = 0;
4083+
const detailReads = yield* Queue.unbounded<number>();
4084+
const agentEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
4085+
const host = Layer.mergeAll(
4086+
NodeServices.layer,
4087+
NodeCrypto.layer,
4088+
Layer.mock(PullRequestService.PullRequestService)({
4089+
detail: (input) =>
4090+
Queue.offer(detailReads, input.number).pipe(
4091+
Effect.as({
4092+
...watchedPullRequestDetail({
4093+
projectId,
4094+
number: input.number,
4095+
at: "2026-10-02T12:00:00.000Z",
4096+
}),
4097+
state: states.get(input.number)!,
4098+
}),
4099+
),
4100+
activity: () =>
4101+
Effect.succeed({
4102+
comments: [],
4103+
commentCount: 0,
4104+
commentsTruncated: false,
4105+
reviewThreads: [],
4106+
commits: [],
4107+
}),
4108+
// A fresh fingerprint every time, so every pass reads the detail.
4109+
watchFingerprint: () =>
4110+
Effect.sync(() => ({ status: String(++fingerprints), remarks: "" })),
4111+
invalidate: () => Effect.void,
4112+
changes: () => Stream.never,
4113+
}),
4114+
Layer.succeed(Orchestrator.OrchestratorV2, {
4115+
...orchestrator,
4116+
streamDomainEvents: Stream.fromQueue(agentEvents),
4117+
}),
4118+
);
4119+
const runId = RunId.make(`run:${threadId}:1`);
4120+
const command = (status: "running" | "completed") =>
4121+
Effect.map(DateTime.now, (at): OrchestrationV2DomainEvent => ({
4122+
type: "turn-item.updated",
4123+
id: EventId.make(`event:${threadId}:merge-${status}`),
4124+
threadId,
4125+
runId,
4126+
occurredAt: at,
4127+
payload: {
4128+
id: TurnItemId.make(`item:${threadId}:merge`),
4129+
threadId,
4130+
runId,
4131+
nodeId: null,
4132+
providerThreadId: null,
4133+
providerTurnId: null,
4134+
nativeItemRef: null,
4135+
parentItemId: null,
4136+
ordinal: 1,
4137+
status,
4138+
title: null,
4139+
startedAt: at,
4140+
completedAt: status === "completed" ? at : null,
4141+
updatedAt: at,
4142+
type: "command_execution",
4143+
input: "gh pr merge 19 --squash",
4144+
},
4145+
}));
4146+
const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host));
4147+
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
4148+
yield* reactor.start();
4149+
// The first sweep finds both open.
4150+
yield* Queue.take(detailReads);
4151+
yield* Queue.take(detailReads);
4152+
4153+
yield* Queue.offer(agentEvents, yield* command("running"));
4154+
states.set(19, "merged");
4155+
yield* TestClock.adjust("1 second");
4156+
// The command's end reads the thread's watches, so #19 ends before any sweep.
4157+
yield* Queue.offer(agentEvents, yield* command("completed"));
4158+
yield* Queue.take(detailReads);
4159+
yield* Queue.take(detailReads);
4160+
4161+
// That read found #20 open, so someone else merging it later is news.
4162+
states.set(20, "merged");
4163+
yield* reactor.sweep;
4164+
yield* worker.drain();
4165+
const thread = yield* orchestrator.getThreadShell(threadId);
4166+
assert.isTrue(thread?.pullRequests?.every((link) => link.watch === undefined));
4167+
const wakes = (yield* orchestrator.getThreadRecords(threadId, ["messages"])).messages.flatMap(
4168+
(message) => message.notification?.summary ?? [],
4169+
);
4170+
assert.deepEqual(wakes, ["#20: merged, stopped watching"]);
4171+
}),
4172+
);
4173+
40384174
it.effect("a pull request closed, reopened, and then merged wakes once for each end", () =>
40394175
Effect.gen(function* () {
40404176
const orchestrator = yield* Orchestrator.OrchestratorV2;

‎apps/server/src/sourceControl/sourceControlDefinitions.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,9 @@ export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [
1919
] as const;
2020

2121
export const sourceControlDefinitions = builtInSourceControlDefinitions;
22+
23+
/** A host CLI command that merges or closes a change request, such as `gh pr merge`. */
24+
export const isChangeRequestCloseCommand = (command: string) =>
25+
sourceControlDefinitions.definitions.some(
26+
(definition) => definition.changeRequestCloseCommand?.test(command) === true,
27+
);

‎docs/user/source-control.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -332,8 +332,8 @@ conflict. On github.com it also wakes the agent, with GitHub's reason, when the
332332
the pull request without merging it. Threads in a project that watch the same pull request share one check. On GitHub, a check
333333
first asks whether anything changed and reads the pull request only when it did, which keeps
334334
watching inside GitHub's rate limit. Comments from your own account do not wake it. When the pull
335-
request merges or closes, the agent is woken once and watching ends; a reopened pull request needs a
336-
new watch. Watching also ends after 10 wakes in a row that bring only comments, after 8
335+
request merges or closes, watching ends, and the agent is woken once unless it merged or closed the
336+
pull request itself with the host's CLI. A reopened pull request needs a new watch. Watching also ends after 10 wakes in a row that bring only comments, after 8
337337
failed reads in a row, or when you press Stop on the thread. A rate limit only pauses watching.
338338
Settling or archiving a thread also ends all its watches. Unsettle the thread before starting a new
339339
watch. Watching a pull request again does not repeat check or conflict news its last

0 commit comments

Comments
 (0)