Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 41 additions & 23 deletions apps/server/src/orchestration-v2/PullRequestWatchReactor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -399,26 +399,45 @@ export const make = Effect.gen(function* () {
),
);

const closed = (target: WatchTarget) =>
record(target, null, {
text: `Pull request #${target.link.number} (${target.link.url}) was closed, so T3 Code stopped watching it. Call watch_pull_request if it reopens.`,
notification: {
source: { kind: "monitor" },
outcome: "updated",
summary: `#${target.link.number}: closed, stopped watching`,
},
}).pipe(
// An agent still watching at a merge may have planned work for after it, and this wake is its
// only way back in. A refused wake (say the thread's provider was removed) ends the watch
// silently: pending-work derivation counts a live watch as awaited, so a stuck one would hold
// auto-settle forever.
const finished = (target: WatchTarget, state: "merged" | "closed") =>
record(
target,
null,
state === "merged"
? {
text: `Pull request #${target.link.number} (${target.link.url}) merged, so T3 Code stopped watching it. Do anything you planned for after the merge, such as checking the deploy, then end your turn.`,
notification: {
source: { kind: "monitor" },
outcome: "completed",
summary: `#${target.link.number}: merged, stopped watching`,
},
}
: {
text: `Pull request #${target.link.number} (${target.link.url}) was closed, so T3 Code stopped watching it. Call watch_pull_request if it reopens.`,
notification: {
source: { kind: "monitor" },
outcome: "updated",
summary: `#${target.link.number}: closed, stopped watching`,
},
},
).pipe(
Effect.tap(() => woke(target)),
Effect.tap(() => ended(target, "closed")),
Effect.catch(() => record(target, null)),
Effect.tap(() => ended(target, state)),
);

// Settled and subagent threads first: the orchestrator refuses wakes on them.
const endsWithoutRead = ({ thread, link }: WatchTarget): WatchEndReason | undefined =>
link.snapshot?.state === "merged"
? "merged"
: thread.settledOverride === "settled" || thread.settledAt !== null
? "settled"
: thread.lineage.relationshipToParent === "subagent"
? "subagent"
thread.settledOverride === "settled" || thread.settledAt !== null
? "settled"
: thread.lineage.relationshipToParent === "subagent"
? "subagent"
: link.snapshot?.state === "merged"
? "merged"
: undefined;

const eachTarget = <E>(
Expand Down Expand Up @@ -528,11 +547,8 @@ export const make = Effect.gen(function* () {
}
if (detail.state !== "open") {
lastReads.delete(group.key);
return yield* eachTarget(group, (target) =>
detail.state === "closed"
? closed(target)
: record(target, null).pipe(Effect.tap(() => ended(target, "merged"))),
);
const state = detail.state;
return yield* eachTarget(group, (target) => finished(target, state));
}

// Never advance the remark watermark past comments an incomplete read could have missed.
Expand Down Expand Up @@ -620,8 +636,10 @@ export const make = Effect.gen(function* () {
yield* Effect.forEach(
ending,
([target, reason]) =>
record(target, null).pipe(
Effect.tap(() => ended(target, reason)),
(reason === "merged"
? finished(target, "merged")
: record(target, null).pipe(Effect.tap(() => ended(target, reason)))
).pipe(
Effect.catchCause(
logFailure("pull request watch stop failed", {
threadId: target.thread.id,
Expand Down
117 changes: 117 additions & 0 deletions apps/server/src/orchestration-v2/runtimeLayer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3514,6 +3514,123 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
}),
);

// An agent that queues its PR and ends its turn planning post-merge work (check the deploy, open
// the next PR) only gets another turn from this wake. The sync reactor usually stores the merged
// snapshot before this reactor reads the host, so both paths must wake. A wake that can never be
// delivered must still end the watch, or the watch would hold auto-settle forever.
it.effect.each([
{ seenBy: "host read", deliverable: true },
{ seenBy: "link snapshot", deliverable: true },
{ seenBy: "link snapshot", deliverable: false },
] as const)(
"a merge wakes the agent once and ends the watch: $seenBy (deliverable: $deliverable)",
({ seenBy, deliverable }) =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const id = `${seenBy === "host read" ? "read" : "snapshot"}-${deliverable}`;
const threadId = ThreadId.make(`runtime-pull-request-watch-merged-${id}`);
const projectId = ProjectId.make(`pr-watch-merged-project-${id}`);
yield* seedProject({
projectId,
title: "Watch merged",
workspaceRoot: "/workspace/watch-merged",
defaultModelSelection: null,
createdAt: "2026-10-01T00:00:00.000Z",
});
yield* orchestrator.dispatch({
type: "thread.create",
createdBy: "user",
creationSource: "web",
commandId: CommandId.make(`pr-watch-merged-create-${id}`),
threadId,
projectId,
title: "Watch merged",
modelSelection: deliverable
? modelSelection
: { ...modelSelection, instanceId: ProviderInstanceId.make("removed_instance") },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
});
const key = { host: "github.com", repository: "pingdotgg/t3code", number: 21 };
yield* orchestrator.dispatch({
type: "thread.pull-request.watch",
commandId: CommandId.make(`pr-watch-merged-start-${id}`),
threadId,
...key,
watching: true,
link: { url: "https://github.com/pingdotgg/t3code/pull/21", source: "agent" },
});
if (seenBy === "link snapshot") {
yield* orchestrator.dispatch({
type: "thread.pull-request-link.sync",
commandId: CommandId.make(`pr-watch-merged-sync-${id}`),
threadId,
...key,
snapshot: {
state: "merged",
title: "Watched pull request",
headBranch: "feature",
baseBranch: "main",
isDraft: false,
updatedAt: null,
syncedAt: "2026-10-02T12:05:00.000Z",
mergedAt: "2026-10-02T12:05:00.000Z",
},
stack: null,
});
}
let reads = 0;
const reactor = yield* PullRequestWatchReactor.make.pipe(
Effect.provide(
Layer.mergeAll(
NodeServices.layer,
NodeCrypto.layer,
Layer.mock(PullRequestService.PullRequestService)({
watchFingerprint: () => Effect.succeed(null),
detail: () =>
Effect.sync(() => {
reads += 1;
return {
...watchedPullRequestDetail({
projectId,
number: 21,
at: "2026-10-02T12:00:00.000Z",
}),
state: "merged" as const,
mergedAt: "2026-10-02T12:05:00.000Z",
};
}),
activity: () =>
Effect.succeed({
comments: [],
commentCount: 0,
commentsTruncated: false,
reviewThreads: [],
commits: [],
}),
}),
),
),
);
const summaries = Effect.map(
orchestrator.getThreadRecords(threadId, ["messages"]),
({ messages }) => messages.flatMap((message) => message.notification?.summary ?? []),
);

yield* reactor.sweep;
yield* TestClock.adjust("10 minutes");
yield* reactor.sweep;

assert.isUndefined(
(yield* orchestrator.getThreadShell(threadId))?.pullRequests?.[0]?.watch,
);
assert.deepEqual(yield* summaries, deliverable ? ["#21: merged, stopped watching"] : []);
assert.equal(reads, seenBy === "host read" ? 1 : 0);
}),
);

it.effect("finishes owed checks once after pending sweeps, a restart, and a re-watch", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
Expand Down
7 changes: 5 additions & 2 deletions docs/user/source-control.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,8 +306,11 @@ the thread is active, the server checks the pull request every two minutes and w
check fails, the required checks pass, someone else comments or reviews, or the branch starts to
conflict. Threads in a project that watch the same pull request share one check. On GitHub, a check
first asks whether anything changed and reads the pull request only when it did, which keeps
watching inside GitHub's rate limit. Comments from your own account do not wake it. Watching ends
when the pull request merges or closes, after 10 wakes in a row that bring only comments, after 8
watching inside GitHub's rate limit. Comments from your own account do not wake it. When the pull
request merges or closes, the agent is woken one last time and the watch ends, so an agent that
planned work for after the merge, such as checking a deploy, gets to do it. Until that wake, the
merged pull request still holds the thread from auto-settling. Watching also ends after 10 wakes in a
row that bring only comments, after 8
failed reads in a row, or when you press Stop on the thread. A rate limit only pauses watching.
Settling or archiving a thread also ends all its watches. Unsettle the thread before starting a new
watch. Watching a pull request again does not repeat check or conflict news its last
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,7 @@ describe("derivePendingBackgroundWork kinds", () => {
link(5, { state: "closed" }),
];

// Merged (#4) and closed (#5) hold too: the watch reactor still owes the agent that wake.
it("keeps a settled run waiting on each visible watch, as an awaited monitor", () => {
const tasks = derivePendingBackgroundWork({
latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" },
Expand All @@ -410,6 +411,12 @@ describe("derivePendingBackgroundWork kinds", () => {
kind: "monitor",
awaited: true,
},
{
taskId: "pull-request-watch:github.com/acme/app#4",
description: "Watching pull request #4",
kind: "monitor",
awaited: true,
},
{
taskId: "pull-request-watch:github.com/acme/app#5",
description: "Watching pull request #5",
Expand All @@ -430,6 +437,7 @@ describe("derivePendingBackgroundWork kinds", () => {
}).map((task) => task.taskId),
).toEqual([
"pull-request-watch:github.com/acme/app#1",
"pull-request-watch:github.com/acme/app#4",
"pull-request-watch:github.com/acme/app#5",
]);
});
Expand Down
12 changes: 5 additions & 7 deletions packages/shared/src/orchestrationV2PendingBackgroundWork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,7 @@ type PendingBackgroundWorkRun = Pick<OrchestrationV2Run, "id" | "ordinal" | "sta
type PendingBackgroundWorkPullRequest = Pick<
ThreadPullRequestLink,
"host" | "repository" | "number" | "url" | "source" | "watch"
> & {
readonly snapshot: Pick<NonNullable<ThreadPullRequestLink["snapshot"]>, "state"> | null;
};
>;

type PendingBackgroundWorkProviderThread = Pick<
OrchestrationV2ProviderThread,
Expand Down Expand Up @@ -293,10 +291,10 @@ function pullRequestWatchTasks(
pullRequests: ReadonlyArray<PendingBackgroundWorkPullRequest> | undefined,
): Array<PendingBackgroundWorkTask> {
return (pullRequests ?? []).flatMap((link) =>
// The watch reactor ends a merged PR's watch without waking the agent, so it holds nothing.
link.watch === undefined ||
link.source === "stack-dismissed" ||
link.snapshot?.state === "merged"
// A merged or closed PR's watch holds until the watch reactor ends it with a wake. Settling
// first would detach the session, and the orchestrator refuses wakes on settled threads, so the
// agent would never hear about the merge it was waiting for.
link.watch === undefined || link.source === "stack-dismissed"
? []
: [
{
Expand Down
Loading