Skip to content

Commit 207f6a1

Browse files
t3dotggclaude
andauthored
fix(threads): threads watching a PR stay in Working instead of bouncing to the inbox (#16204)
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
1 parent f5eb250 commit 207f6a1

15 files changed

Lines changed: 357 additions & 10 deletions

File tree

‎apps/server/src/mcp/toolkits/pullRequests/tools.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,7 @@ const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", {
289289

290290
const WatchPullRequestTool = Tool.make("watch_pull_request", {
291291
description:
292-
"Have T3 Code watch an open pull request for this thread, linking it first if needed. T3 Code checks it every minute and wakes you with a message when a check fails, the required checks pass, someone else comments or reviews, or the branch starts to conflict with its base. Use this to monitor or babysit a pull request instead of polling, sleeping, or running a watcher. Only comments posted after this call wake you, so handle the existing ones first, then end your turn. A wake is news, not a merge decision: check readiness yourself before merging. Watching ends when the pull request merges or closes, when its thread settles, when T3 Code cannot read it for 15 minutes, when the user stops this thread, or when you call unwatch_pull_request. Unsettle the thread before starting a new watch.",
292+
"Have T3 Code watch an open pull request for this thread, linking it first if needed. T3 Code checks it every minute and wakes you with a message when a check fails, the required checks pass, someone else comments or reviews, or the branch starts to conflict with its base. Use this to monitor or babysit a pull request instead of polling, sleeping, or running a watcher. Only comments posted after this call wake you, so handle the existing ones first, then end your turn. A wake is news, not a merge decision: check readiness yourself before merging. While T3 Code watches, the thread stays in the user's Working list, not their inbox. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox. Watching ends when the pull request merges or closes, when its thread settles, when T3 Code cannot read it for 15 minutes, when the user stops this thread, or when you call unwatch_pull_request. Unsettle the thread before starting a new watch.",
293293
parameters: PullRequestTargetInput,
294294
success: WatchPullRequestResult,
295295
failure: PullRequestToolError,

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

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
RunId,
2222
ThreadId,
2323
TurnItemId,
24+
type ThreadPullRequestLink,
2425
} from "@t3tools/contracts";
2526
import * as DateTime from "effect/DateTime";
2627
import * as Effect from "effect/Effect";
@@ -4401,6 +4402,128 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
44014402
}),
44024403
);
44034404

4405+
it.effect("a pull request watch keeps a finished thread working until it ends", () =>
4406+
Effect.gen(function* () {
4407+
const store = yield* ProjectionStore.ProjectionStoreV2;
4408+
const threadId = ThreadId.make("thread:watched-pull-request");
4409+
const runId = RunId.make("run:watched-pull-request");
4410+
const at = DateTime.makeUnsafe("2026-10-05T12:00:00.000Z");
4411+
const thread = {
4412+
createdBy: "user" as const,
4413+
creationSource: "web" as const,
4414+
id: threadId,
4415+
projectId: ProjectId.make("project:watched-pull-request"),
4416+
title: "Babysit the PR",
4417+
providerInstanceId,
4418+
modelSelection,
4419+
runtimeMode: "full-access" as const,
4420+
interactionMode: "default" as const,
4421+
branch: null,
4422+
worktreePath: null,
4423+
activeProviderThreadId: null,
4424+
lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
4425+
forkedFrom: null,
4426+
createdAt: at,
4427+
updatedAt: at,
4428+
archivedAt: null,
4429+
settledOverride: null,
4430+
settledAt: null,
4431+
lastVisitedAt: null,
4432+
deletedAt: null,
4433+
};
4434+
yield* store.apply({
4435+
id: EventId.make("event:watched-pull-request:thread"),
4436+
type: "thread.created",
4437+
threadId,
4438+
occurredAt: at,
4439+
payload: thread,
4440+
});
4441+
yield* store.apply({
4442+
id: EventId.make("event:watched-pull-request:run"),
4443+
type: "run.created",
4444+
threadId,
4445+
runId,
4446+
driver,
4447+
providerInstanceId,
4448+
occurredAt: at,
4449+
payload: {
4450+
id: runId,
4451+
threadId,
4452+
ordinal: 1,
4453+
providerInstanceId,
4454+
modelSelection,
4455+
providerThreadId: null,
4456+
userMessageId: MessageId.make("message:watched-pull-request"),
4457+
rootNodeId: null,
4458+
activeAttemptId: null,
4459+
status: "completed",
4460+
requestedAt: at,
4461+
startedAt: at,
4462+
completedAt: at,
4463+
checkpointId: null,
4464+
contextHandoffId: null,
4465+
},
4466+
});
4467+
const link = {
4468+
host: "github.com",
4469+
repository: "pingdotgg/t3code",
4470+
number: 7,
4471+
url: "https://github.com/pingdotgg/t3code/pull/7",
4472+
source: "agent" as const,
4473+
linkedAt: DateTime.formatIso(at),
4474+
snapshot: null,
4475+
stack: null,
4476+
};
4477+
const syncPullRequests = (id: string, pullRequests: ReadonlyArray<ThreadPullRequestLink>) =>
4478+
store.apply({
4479+
id: EventId.make(`event:watched-pull-request:${id}`),
4480+
type: "thread.pull-request-synced",
4481+
threadId,
4482+
occurredAt: at,
4483+
payload: { ...thread, pullRequests },
4484+
});
4485+
const project = { title: "Project" };
4486+
const environmentId = EnvironmentId.make("environment:watched-pull-request");
4487+
const phase = Effect.gen(function* () {
4488+
const shell = yield* store.getThreadShell(threadId);
4489+
const listed = (yield* store.getShellSnapshot()).threads.find(
4490+
(candidate) => candidate.id === threadId,
4491+
);
4492+
assert.deepEqual(listed?.pendingBackgroundTasks, shell?.pendingBackgroundTasks);
4493+
return shell && projectThreadAwarenessV2({ environmentId, project, thread: shell })?.phase;
4494+
});
4495+
4496+
yield* syncPullRequests("watched", [
4497+
{
4498+
...link,
4499+
watch: {
4500+
startedAt: DateTime.formatIso(at),
4501+
headSha: null,
4502+
failedChecks: [],
4503+
passed: false,
4504+
passedChecks: [],
4505+
remarksThrough: DateTime.formatIso(at),
4506+
remarkIds: [],
4507+
conflicting: false,
4508+
wakes: 0,
4509+
},
4510+
},
4511+
]);
4512+
assert.deepEqual((yield* store.getThreadShell(threadId))?.pendingBackgroundTasks, [
4513+
{
4514+
taskId: "pull-request-watch:github.com/pingdotgg/t3code#7",
4515+
description: "Watching pull request #7",
4516+
kind: "monitor",
4517+
},
4518+
]);
4519+
assert.equal(yield* phase, "running");
4520+
4521+
yield* syncPullRequests("unwatched", [link]);
4522+
assert.deepEqual((yield* store.getThreadShell(threadId))?.pendingBackgroundTasks, []);
4523+
assert.equal(yield* phase, "completed");
4524+
}),
4525+
);
4526+
44044527
it.effect("dates a completion released by held background work at the release", () =>
44054528
Effect.gen(function* () {
44064529
const store = yield* ProjectionStore.ProjectionStoreV2;

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1346,6 +1346,7 @@ export function threadShellFromProjection(
13461346
turnItems: projection.turnItems,
13471347
activeProviderThreadId: projection.thread.activeProviderThreadId,
13481348
runs: projection.runs,
1349+
pullRequests: projection.thread.pullRequests,
13491350
});
13501351
return {
13511352
createdBy: projection.thread.createdBy,
@@ -5220,6 +5221,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
52205221
turnItems: pendingTurnItemsByThreadId.get(thread.id) ?? [],
52215222
activeProviderThreadId: thread.activeProviderThreadId,
52225223
hasActiveRun: false,
5224+
pullRequests: thread.pullRequests,
52235225
}),
52245226
} satisfies ProjectionSettlementCandidate;
52255227
}),
@@ -5338,6 +5340,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
53385340
turnItems: pendingTurnItemsByThreadId.get(thread.id) ?? [],
53395341
activeProviderThreadId: thread.activeProviderThreadId,
53405342
hasActiveRun: row.active_run_id !== null,
5343+
pullRequests: thread.pullRequests,
53415344
}),
53425345
];
53435346
return {

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

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -193,10 +193,13 @@ export const make = Effect.gen(function* () {
193193
const check = Effect.fn("PullRequestWatchReactor.check")(function* (target: WatchTarget) {
194194
const { thread, link, watch } = target;
195195
const pullRequest = identityOf(link);
196-
// A merged pull request cannot reopen, so its watch ends without a host read, even on a
197-
// settled thread. A closed one can, so the host decides below.
196+
// A merged pull request cannot reopen, so its watch ends without a host read. A closed one
197+
// can, so the host decides below. Settling ends watches; one left from before that rule
198+
// ends here, so the thread does not show as working while settled.
198199
if (link.snapshot?.state === "merged") return yield* record(target, null);
199-
if (thread.settledOverride === "settled" || thread.settledAt !== null) return;
200+
if (thread.settledOverride === "settled" || thread.settledAt !== null) {
201+
return yield* record(target, null);
202+
}
200203

201204
const reference = { projectId: thread.projectId, ...pullRequest };
202205
const read = yield* Effect.exit(

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ export function pullRequestWatchMessage(input: {
197197
"",
198198
exhausted
199199
? `T3 Code stopped watching after ${PULL_REQUEST_WATCH_WAKE_LIMIT} comment-only updates in a row. Call watch_pull_request to watch it again.`
200-
: "Look into each item and act on it as your task requires. T3 Code keeps watching and wakes you on the next change, so end your turn when you are done. Call unwatch_pull_request when you no longer need updates.",
200+
: "Look into each item and act on it as your task requires. T3 Code keeps watching and wakes you on the next change, so end your turn when you are done. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox.",
201201
].join("\n");
202202
const failed = changes.some(
203203
(change) => change.kind === "checks-failed" || change.kind === "conflicting",

‎apps/server/src/provider/RuntimeInstructions.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
const PULL_REQUEST_LINKING_INSTRUCTIONS = `<pull_request_linking>
2-
When the t3-code MCP server exposes link_pull_request, you must use it to register every pull request you create or work on for this thread. Call link_pull_request with the full PR URL immediately after creating a PR or starting work on an existing PR. For a stack, call it for every layer, not just the current branch or the top PR. This applies when creating or updating PRs through gh, gh stack, another CLI, or the host API: those operations do not register the PRs with this thread. Linking an already-linked PR is safe. Before finishing PR work, call list_thread_pull_requests and link any PR from your work that is missing. Do not link unrelated PRs mentioned only as background. If a linking call fails, report that failure instead of claiming the PR is linked. When asked to monitor, watch, or babysit a PR and watch_pull_request is available, call it and end your turn: T3 Code wakes you when checks finish, someone else comments, or the branch conflicts, so do not poll or run your own watcher.
2+
When the t3-code MCP server exposes link_pull_request, you must use it to register every pull request you create or work on for this thread. Call link_pull_request with the full PR URL immediately after creating a PR or starting work on an existing PR. For a stack, call it for every layer, not just the current branch or the top PR. This applies when creating or updating PRs through gh, gh stack, another CLI, or the host API: those operations do not register the PRs with this thread. Linking an already-linked PR is safe. Before finishing PR work, call list_thread_pull_requests and link any PR from your work that is missing. Do not link unrelated PRs mentioned only as background. If a linking call fails, report that failure instead of claiming the PR is linked. When asked to monitor, watch, or babysit a PR and watch_pull_request is available, call it and end your turn: T3 Code wakes you when checks finish, someone else comments, or the branch conflicts, so do not poll or run your own watcher. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox.
33
</pull_request_linking>`;
44

55
/**

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3561,6 +3561,7 @@ export default function ChatView(props: ChatViewProps) {
35613561
turnItems: serverProjection.turnItems,
35623562
activeProviderThreadId: serverProjection.thread.activeProviderThreadId,
35633563
runs: serverProjection.runs,
3564+
pullRequests: serverProjection.thread.pullRequests,
35643565
}),
35653566
];
35663567
}, [serverProjection]);

‎docs/user/source-control.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,10 @@ after 10 wakes in a row that bring only comments, when the server cannot read th
200200
Unsettle the thread before starting a new watch. To start or stop it yourself, use the row menu in
201201
the **Linked pull requests** panel.
202202

203+
A watched thread counts as working between wakes, so it stays in the **Working** section and does
204+
not auto-settle. Agents stop watching when they hand the work back to you, and the thread then
205+
returns to your inbox.
206+
203207
Cross-repository links use a project on the same host. Azure DevOps reviews require a project checked
204208
out from the matching organization and repository.
205209

‎packages/client-runtime/src/operations/commands.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,60 @@ describe("V2 environment commands", () => {
502502
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
503503
);
504504

505+
it.effect("Stop with no run left ends the thread's pull request watches", () =>
506+
Effect.gen(function* () {
507+
const link = {
508+
host: "github.com",
509+
repository: "pingdotgg/t3code",
510+
url: "https://github.com/pingdotgg/t3code/pull/7",
511+
source: "agent" as const,
512+
linkedAt: "2026-10-05T00:00:00.000Z",
513+
snapshot: null,
514+
stack: null,
515+
};
516+
const watch = {
517+
startedAt: "2026-10-05T00:00:00.000Z",
518+
headSha: null,
519+
failedChecks: [],
520+
passed: false,
521+
passedChecks: [],
522+
remarksThrough: "2026-10-05T00:00:00.000Z",
523+
remarkIds: [],
524+
conflicting: false,
525+
wakes: 0,
526+
};
527+
const projection: OrchestrationV2ThreadProjection = {
528+
...v2Projection,
529+
thread: {
530+
...v2Projection.thread,
531+
pullRequests: [
532+
{ ...link, number: 7, watch },
533+
{ ...link, number: 8 },
534+
{ ...link, number: 9, source: "stack-dismissed", watch },
535+
],
536+
},
537+
};
538+
const commands: OrchestrationV2Command[] = [];
539+
const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
540+
541+
yield* interruptThreadTurn({ threadId: v2ThreadId }).pipe(
542+
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
543+
);
544+
545+
expect(commands).toEqual([
546+
{
547+
type: "thread.pull-request.watch",
548+
commandId: expect.any(String),
549+
threadId: v2ThreadId,
550+
host: "github.com",
551+
repository: "pingdotgg/t3code",
552+
number: 7,
553+
watching: false,
554+
},
555+
]);
556+
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
557+
);
558+
505559
it.effect.each([
506560
"waiting",
507561
"completed",

‎packages/client-runtime/src/operations/commands.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
} from "@t3tools/contracts";
2929
import { modelSelectionCommandType } from "@t3tools/shared/model";
3030
import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
31+
import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
3132
import * as Crypto from "effect/Crypto";
3233
import * as Effect from "effect/Effect";
3334

@@ -771,6 +772,11 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(
771772
});
772773
});
773774

775+
/**
776+
* Stop for the thread's latest work: interrupts the active run, or the settled run whose
777+
* background work still runs. With no run to stop, it ends the thread's pull request
778+
* watches, the only background work that has no run.
779+
*/
774780
export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThreadTurn")(function* (
775781
input: InterruptThreadTurnInput,
776782
) {
@@ -798,6 +804,22 @@ export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThrea
798804
runId = latestRun?.id;
799805
}
800806
}
807+
if (runId === undefined) {
808+
let result = { sequence: 0 };
809+
for (const link of visibleThreadPullRequests(projection.thread.pullRequests ?? [])) {
810+
if (link.watch === undefined) continue;
811+
result = yield* dispatch({
812+
type: "thread.pull-request.watch",
813+
commandId: yield* allocateCommandId(result.sequence === 0 ? input : {}),
814+
threadId: input.threadId,
815+
host: link.host,
816+
repository: link.repository,
817+
number: link.number,
818+
watching: false,
819+
});
820+
}
821+
return result;
822+
}
801823
}
802824
if (runId === undefined) return { sequence: 0 };
803825
return yield* dispatch({

0 commit comments

Comments
 (0)