Skip to content

Commit a0f1bb8

Browse files
fix(server): watched PRs wake the agent when they merge
A watched PR's merge ended the watch without telling the agent, so it could keep saying it was still watching a merged PR. A merge or close now wakes the agent once, naming the merge commit and, where the host reports it, who merged, and then ends the watch. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c4ce7b0 commit a0f1bb8

20 files changed

Lines changed: 416 additions & 60 deletions

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

Lines changed: 17 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
type OrchestrationV2Notification,
55
type PullRequestActivity,
66
type PullRequestComment,
7+
type PullRequestDetail,
78
type PullRequestRef,
89
type PullRequestThreadCommentsResult,
910
type ThreadPullRequestLink,
@@ -38,6 +39,7 @@ import * as ProjectionStore from "./ProjectionStore.ts";
3839
import {
3940
evaluatePullRequestWatch,
4041
PULL_REQUEST_WATCH_NO_CHECKS_MS,
42+
pullRequestWatchEndMessage,
4143
pullRequestWatchMessage,
4244
} from "./pullRequestWatch.ts";
4345

@@ -399,27 +401,23 @@ export const make = Effect.gen(function* () {
399401
),
400402
);
401403

402-
const closed = (target: WatchTarget) =>
403-
record(target, null, {
404-
text: `Pull request #${target.link.number} (${target.link.url}) was closed, so T3 Code stopped watching it. Call watch_pull_request if it reopens.`,
405-
notification: {
406-
source: { kind: "monitor" },
407-
outcome: "updated",
408-
summary: `#${target.link.number}: closed, stopped watching`,
409-
},
410-
}).pipe(
404+
const finished = (target: WatchTarget, detail: PullRequestDetail) =>
405+
record(
406+
target,
407+
null,
408+
pullRequestWatchEndMessage({ number: target.link.number, url: target.link.url, detail }),
409+
).pipe(
411410
Effect.tap(() => woke(target)),
412-
Effect.tap(() => ended(target, "closed")),
411+
Effect.tap(() => ended(target, detail.state === "merged" ? "merged" : "closed")),
413412
);
414413

415-
const endsWithoutRead = ({ thread, link }: WatchTarget): WatchEndReason | undefined =>
416-
link.snapshot?.state === "merged"
417-
? "merged"
418-
: thread.settledOverride === "settled" || thread.settledAt !== null
419-
? "settled"
420-
: thread.lineage.relationshipToParent === "subagent"
421-
? "subagent"
422-
: undefined;
414+
// A merged snapshot still gets one read, so the wake can name the merge commit.
415+
const endsWithoutRead = ({ thread }: WatchTarget): WatchEndReason | undefined =>
416+
thread.settledOverride === "settled" || thread.settledAt !== null
417+
? "settled"
418+
: thread.lineage.relationshipToParent === "subagent"
419+
? "subagent"
420+
: undefined;
423421

424422
const eachTarget = <E>(
425423
group: WatchGroup,
@@ -528,11 +526,7 @@ export const make = Effect.gen(function* () {
528526
}
529527
if (detail.state !== "open") {
530528
lastReads.delete(group.key);
531-
return yield* eachTarget(group, (target) =>
532-
detail.state === "closed"
533-
? closed(target)
534-
: record(target, null).pipe(Effect.tap(() => ended(target, "merged"))),
535-
);
529+
return yield* eachTarget(group, (target) => finished(target, detail));
536530
}
537531

538532
// Never advance the remark watermark past comments an incomplete read could have missed.

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

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { assert, describe, it } from "@effect/vitest";
88
import {
99
PULL_REQUEST_WATCH_WAKE_LIMIT,
1010
evaluatePullRequestWatch as evaluate,
11+
pullRequestWatchEndMessage,
1112
pullRequestWatchMessage,
1213
} from "./pullRequestWatch.ts";
1314

@@ -436,3 +437,42 @@ describe("evaluatePullRequestWatch", () => {
436437
assert.isTrue(anHourLater(watch(), silent).every((kinds) => kinds.length === 0));
437438
});
438439
});
440+
441+
describe("pullRequestWatchEndMessage", () => {
442+
const url = "https://git.cafe/pingdotgg/t3code/pull/7";
443+
const end = (overrides: Partial<Parameters<typeof pullRequestWatchEndMessage>[0]["detail"]>) =>
444+
pullRequestWatchEndMessage({
445+
number: 7,
446+
url,
447+
detail: { state: "merged", baseBranch: "main", ...overrides },
448+
});
449+
const mergeCommitSha = "3b2f958603a51d8c42c4ede02eee7b8cb310b2d9";
450+
451+
it("says how the pull request ended, with the merge commit and merger the host reports", () => {
452+
const merged = end({
453+
mergeCommitSha,
454+
mergedBy: { login: "juliusmarminge", name: null, avatarUrl: null },
455+
});
456+
assert.equal(
457+
merged.text,
458+
`Pull request #7 (${url}) was merged into main by juliusmarminge as 3b2f958, so T3 Code stopped watching it.`,
459+
);
460+
assert.deepEqual(merged.notification, {
461+
source: { kind: "monitor" },
462+
outcome: "completed",
463+
summary: "#7: merged, stopped watching",
464+
});
465+
// GitCafe reports a merge made on GitHub without who made it.
466+
assert.equal(
467+
end({ mergeCommitSha }).text,
468+
`Pull request #7 (${url}) was merged into main as 3b2f958, so T3 Code stopped watching it.`,
469+
);
470+
471+
const closed = end({ state: "closed" });
472+
assert.equal(
473+
closed.text,
474+
`Pull request #7 (${url}) was closed without merging, so T3 Code stopped watching it. If it is reopened, call watch_pull_request to watch it again.`,
475+
);
476+
assert.equal(closed.notification.summary, "#7: closed, stopped watching");
477+
});
478+
});

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

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,33 @@ const SUMMARY: Record<PullRequestWatchChange["kind"], string> = {
221221
conflicting: "merge conflict",
222222
};
223223

224+
export function pullRequestWatchEndMessage(input: {
225+
readonly number: number;
226+
readonly url: string;
227+
readonly detail: Pick<PullRequestDetail, "state" | "baseBranch" | "mergeCommitSha" | "mergedBy">;
228+
}): { readonly text: string; readonly notification: OrchestrationV2Notification } {
229+
const { detail } = input;
230+
const merged = detail.state === "merged";
231+
const how = merged
232+
? [
233+
`was merged into ${detail.baseBranch}`,
234+
detail.mergedBy ? ` by ${detail.mergedBy.login}` : "",
235+
detail.mergeCommitSha ? ` as ${detail.mergeCommitSha.slice(0, 7)}` : "",
236+
].join("")
237+
: "was closed without merging";
238+
return {
239+
text: [
240+
`Pull request #${input.number} (${input.url}) ${how}, so T3 Code stopped watching it.`,
241+
...(merged ? [] : ["If it is reopened, call watch_pull_request to watch it again."]),
242+
].join(" "),
243+
notification: {
244+
source: { kind: "monitor" },
245+
outcome: merged ? "completed" : "updated",
246+
summary: `#${input.number}: ${merged ? "merged" : "closed"}, stopped watching`,
247+
},
248+
};
249+
}
250+
224251
export function pullRequestWatchMessage(input: {
225252
readonly number: number;
226253
readonly url: string;

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

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3416,6 +3416,202 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
34163416
}),
34173417
);
34183418

3419+
// regression: watched #26248 merged and its agent kept saying it was still watching
3420+
it.effect("wakes once when a watched pull request merges, naming the merge commit", () =>
3421+
Effect.gen(function* () {
3422+
const orchestrator = yield* Orchestrator.OrchestratorV2;
3423+
const threadId = ThreadId.make("runtime-pull-request-watch-merged");
3424+
const projectId = ProjectId.make("pr-watch-merged-project");
3425+
yield* seedProject({
3426+
projectId,
3427+
title: "Watch merged",
3428+
workspaceRoot: "/workspace/watch-merged",
3429+
defaultModelSelection: null,
3430+
createdAt: "2026-10-01T00:00:00.000Z",
3431+
});
3432+
yield* orchestrator.dispatch({
3433+
type: "thread.create",
3434+
createdBy: "user",
3435+
creationSource: "web",
3436+
commandId: CommandId.make("pr-watch-merged-create"),
3437+
threadId,
3438+
projectId,
3439+
title: "Watch merged",
3440+
modelSelection,
3441+
runtimeMode: "full-access",
3442+
interactionMode: "default",
3443+
branch: null,
3444+
worktreePath: null,
3445+
});
3446+
yield* orchestrator.dispatch({
3447+
type: "thread.pull-request.watch",
3448+
commandId: CommandId.make("pr-watch-merged-start"),
3449+
threadId,
3450+
host: "github.com",
3451+
repository: "pingdotgg/t3code",
3452+
number: 15,
3453+
watching: true,
3454+
link: { url: "https://github.com/pingdotgg/t3code/pull/15", source: "agent" },
3455+
});
3456+
const reactor = yield* PullRequestWatchReactor.make.pipe(
3457+
Effect.provide(
3458+
Layer.mergeAll(
3459+
NodeServices.layer,
3460+
NodeCrypto.layer,
3461+
Layer.mock(PullRequestService.PullRequestService)({
3462+
detail: () =>
3463+
Effect.succeed({
3464+
...watchedPullRequestDetail({
3465+
projectId,
3466+
number: 15,
3467+
at: "2026-10-02T12:00:00.000Z",
3468+
}),
3469+
state: "merged" as const,
3470+
mergedAt: "2026-10-02T12:00:00.000Z",
3471+
mergeCommitSha: "3b2f958603a51d8c42c4ede02eee7b8cb310b2d9",
3472+
mergedBy: { login: "juliusmarminge", name: null, avatarUrl: null },
3473+
}),
3474+
activity: () =>
3475+
Effect.succeed({
3476+
comments: [],
3477+
commentCount: 0,
3478+
commentsTruncated: false,
3479+
reviewThreads: [],
3480+
commits: [],
3481+
}),
3482+
}),
3483+
),
3484+
),
3485+
);
3486+
yield* reactor.sweep;
3487+
yield* TestClock.adjust("10 minutes");
3488+
yield* reactor.sweep;
3489+
3490+
assert.isUndefined((yield* orchestrator.getThreadShell(threadId))?.pullRequests?.[0]?.watch);
3491+
const wakes = (yield* orchestrator.getThreadRecords(threadId, ["messages"])).messages.filter(
3492+
(message) => message.notification != null,
3493+
);
3494+
assert.deepEqual(
3495+
wakes.map((message) => message.notification?.summary),
3496+
["#15: merged, stopped watching"],
3497+
);
3498+
assert.include(wakes[0]!.text, "merged into main by juliusmarminge as 3b2f958");
3499+
}),
3500+
);
3501+
3502+
it.effect("a pull request closed, reopened, and then merged wakes once for each end", () =>
3503+
Effect.gen(function* () {
3504+
const orchestrator = yield* Orchestrator.OrchestratorV2;
3505+
const threadId = ThreadId.make("runtime-pull-request-watch-reopened");
3506+
const projectId = ProjectId.make("pr-watch-reopened-project");
3507+
yield* seedProject({
3508+
projectId,
3509+
title: "Watch reopened",
3510+
workspaceRoot: "/workspace/watch-reopened",
3511+
defaultModelSelection: null,
3512+
createdAt: "2026-10-01T00:00:00.000Z",
3513+
});
3514+
yield* orchestrator.dispatch({
3515+
type: "thread.create",
3516+
createdBy: "user",
3517+
creationSource: "web",
3518+
commandId: CommandId.make("pr-watch-reopened-create"),
3519+
threadId,
3520+
projectId,
3521+
title: "Watch reopened",
3522+
modelSelection,
3523+
runtimeMode: "full-access",
3524+
interactionMode: "default",
3525+
branch: null,
3526+
worktreePath: null,
3527+
});
3528+
const key = { host: "github.com", repository: "pingdotgg/t3code", number: 16 };
3529+
const watch = (id: string) =>
3530+
orchestrator.dispatch({
3531+
type: "thread.pull-request.watch",
3532+
commandId: CommandId.make(`pr-watch-reopened-${id}`),
3533+
threadId,
3534+
...key,
3535+
watching: true,
3536+
link: { url: "https://github.com/pingdotgg/t3code/pull/16", source: "agent" },
3537+
});
3538+
yield* watch("start");
3539+
3540+
let state: PullRequestDetail["state"] = "closed";
3541+
const host = Layer.mergeAll(
3542+
NodeServices.layer,
3543+
NodeCrypto.layer,
3544+
Layer.mock(PullRequestService.PullRequestService)({
3545+
detail: () =>
3546+
Effect.sync(() => ({
3547+
...watchedPullRequestDetail({
3548+
projectId,
3549+
number: 16,
3550+
at: "2026-10-02T12:00:00.000Z",
3551+
}),
3552+
state,
3553+
checks: [{ name: "lint", status: "pending" as const, description: null, url: null }],
3554+
})),
3555+
activity: () =>
3556+
Effect.succeed({
3557+
comments: [],
3558+
commentCount: 0,
3559+
commentsTruncated: false,
3560+
reviewThreads: [],
3561+
commits: [],
3562+
}),
3563+
}),
3564+
);
3565+
const summaries = Effect.map(
3566+
orchestrator.getThreadRecords(threadId, ["messages"]),
3567+
({ messages }) => messages.flatMap((message) => message.notification?.summary ?? []),
3568+
);
3569+
const watching = Effect.map(
3570+
orchestrator.getThreadShell(threadId),
3571+
(thread) => thread?.pullRequests?.[0]?.watch !== undefined,
3572+
);
3573+
const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host));
3574+
yield* reactor.sweep;
3575+
assert.deepEqual(yield* summaries, ["#16: closed, stopped watching"]);
3576+
assert.isFalse(yield* watching);
3577+
3578+
// Reopening does not restart the watch; the agent was told to watch again.
3579+
state = "open";
3580+
yield* watch("again");
3581+
yield* TestClock.adjust("10 minutes");
3582+
yield* reactor.sweep;
3583+
assert.isTrue(yield* watching);
3584+
assert.deepEqual(yield* summaries, ["#16: closed, stopped watching"]);
3585+
3586+
// The link's own sync can see the merge before the watch reads it.
3587+
state = "merged";
3588+
yield* orchestrator.dispatch({
3589+
type: "thread.pull-request-link.sync",
3590+
commandId: CommandId.make("pr-watch-reopened-synced"),
3591+
threadId,
3592+
...key,
3593+
snapshot: {
3594+
state: "merged",
3595+
title: "Watched pull request",
3596+
headBranch: "feature",
3597+
baseBranch: "main",
3598+
isDraft: false,
3599+
updatedAt: null,
3600+
syncedAt: "2026-10-02T12:30:00.000Z",
3601+
mergedAt: "2026-10-02T12:30:00.000Z",
3602+
},
3603+
stack: null,
3604+
});
3605+
yield* TestClock.adjust("10 minutes");
3606+
yield* reactor.sweep;
3607+
assert.deepEqual(yield* summaries, [
3608+
"#16: closed, stopped watching",
3609+
"#16: merged, stopped watching",
3610+
]);
3611+
assert.isFalse(yield* watching);
3612+
}),
3613+
);
3614+
34193615
it.effect("wakes once for a state it reported, across a restart and a new watch", () =>
34203616
Effect.gen(function* () {
34213617
const orchestrator = yield* Orchestrator.OrchestratorV2;

‎apps/server/src/pullRequest/PullRequestService.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1833,6 +1833,10 @@ export const make = Effect.gen(function* () {
18331833
updatedAt: changeRequest.updatedAt,
18341834
observedAt,
18351835
mergedAt: changeRequest.mergedAt,
1836+
...(changeRequest.mergeCommitSha
1837+
? { mergeCommitSha: changeRequest.mergeCommitSha }
1838+
: {}),
1839+
...(changeRequest.mergedBy ? { mergedBy: changeRequest.mergedBy } : {}),
18361840
closedAt: changeRequest.closedAt,
18371841
reviewers: changeRequest.reviewers,
18381842
labels: changeRequest.labels,

‎docs/user/source-control.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -306,8 +306,9 @@ the thread is active, the server checks the pull request every two minutes and w
306306
check fails, the required checks pass, someone else comments or reviews, or the branch starts to
307307
conflict. Threads in a project that watch the same pull request share one check. On GitHub, a check
308308
first asks whether anything changed and reads the pull request only when it did, which keeps
309-
watching inside GitHub's rate limit. Comments from your own account do not wake it. Watching ends
310-
when the pull request merges or closes, after 10 wakes in a row that bring only comments, after 8
309+
watching inside GitHub's rate limit. Comments from your own account do not wake it. When the pull
310+
request merges or closes, the agent is woken once and watching ends; a reopened pull request needs a
311+
new watch. Watching also ends after 10 wakes in a row that bring only comments, after 8
311312
failed reads in a row, or when you press Stop on the thread. A rate limit only pauses watching.
312313
Settling or archiving a thread also ends all its watches. Unsettle the thread before starting a new
313314
watch. Watching a pull request again does not repeat check or conflict news its last

‎packages/contracts/src/pullRequest.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -622,6 +622,8 @@ export const PullRequestDetail = Schema.Struct({
622622
updatedAt: IsoDateTime,
623623
observedAt: Schema.optional(Schema.Finite),
624624
mergedAt: Schema.NullOr(IsoDateTime),
625+
mergeCommitSha: Schema.optional(TrimmedNonEmptyString),
626+
mergedBy: Schema.optional(PullRequestActor),
625627
closedAt: Schema.NullOr(IsoDateTime),
626628
reviewers: Schema.Array(PullRequestActor),
627629
labels: Schema.Array(PullRequestLabel),

‎packages/shared/src/orchestrationV2PendingBackgroundWork.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,7 @@ function pullRequestWatchTasks(
293293
pullRequests: ReadonlyArray<PendingBackgroundWorkPullRequest> | undefined,
294294
): Array<PendingBackgroundWorkTask> {
295295
return (pullRequests ?? []).flatMap((link) =>
296-
// The watch reactor ends a merged PR's watch without waking the agent, so it holds nothing.
296+
// A merged PR's watch ends at the next sweep, whose wake starts its own run, so it holds nothing.
297297
link.watch === undefined ||
298298
link.source === "stack-dismissed" ||
299299
link.snapshot?.state === "merged"

0 commit comments

Comments
 (0)