From f51c1806805aa23c962e1b988f8c763edbf0cb15 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:55:30 -0800 Subject: [PATCH 1/3] fix(server): a PR watch the agent owns keeps its thread working until the PR merges Since #33214 a watched thread leaves Working once the PR's checks finish. That is right when the agent hands the PR to the user, but wrong when the agent still owns it: it waits on a teammate's approval to merge, a merge queue, or the author's push after its own review. Codex threads have no other way to stay Working. watch_pull_request now takes an optional untilMerged. With true, the watch holds its thread until the PR merges or closes, or the agent unwatches it, whatever its checks say. false clears it, and watching again without it keeps the current value. The flag lives on the watch, survives reactor reads (including one that began before the agent set it) and projection rebuilds, and the hold is decided only in the shared pullRequestWatchTasks. The UI watch toggle does not set it. Fixes #36230. Thanks to @jawr, whose untilApproved diff in the issue mapped the plumbing this follows. Co-Authored-By: Claude Opus 5.5 --- .../src/mcp/toolkits/pullRequests/handlers.ts | 16 ++-- .../src/mcp/toolkits/pullRequests/tools.ts | 12 ++- .../src/orchestration-v2/Orchestrator.ts | 93 +++++++++++-------- .../PullRequestWatchReactor.ts | 3 +- .../src/orchestration-v2/pullRequestWatch.ts | 1 + .../src/orchestration-v2/runtimeLayer.test.ts | 67 +++++++++++++ .../src/provider/agentContextBudget.json | 2 +- .../pullRequest/PullRequestWatchService.ts | 3 + docs/user/source-control.md | 6 +- evals/mcp-tool-use/cases/pull-requests.ndjson | 2 + packages/contracts/src/orchestrationV2.ts | 2 + packages/contracts/src/threadPullRequest.ts | 2 + ...chestrationV2PendingBackgroundWork.test.ts | 13 +++ .../orchestrationV2PendingBackgroundWork.ts | 9 +- 14 files changed, 177 insertions(+), 54 deletions(-) diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index 884dd09a3dea4..28c322def57fb 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -199,18 +199,20 @@ const make = Effect.gen(function* () { // The domain service owns the registration span. const setWatching = Effect.fnUntraced(function* ( - input: PullRequestTargetInput, + input: PullRequestTargetInput & { readonly untilMerged?: boolean | undefined }, watching: boolean, ) { const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests"); const threadId = input.threadId ?? scope.thread?.threadId; if (threadId === undefined) return yield* new PullRequestThreadRequiredError(); - return yield* watches.setWatching({ threadId, target: input, watching }).pipe( - Effect.catchTags({ - PullRequestWatchThreadNotFoundError: (error) => - threadNotFound(engine, scope, error.threadId, error.message), - }), - ); + return yield* watches + .setWatching({ threadId, target: input, watching, untilMerged: input.untilMerged }) + .pipe( + Effect.catchTags({ + PullRequestWatchThreadNotFoundError: (error) => + threadNotFound(engine, scope, error.threadId, error.message), + }), + ); }); const locateAll = Effect.fn("PullRequestsToolkit.locateAll")(function* ( diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 376817db10079..918e3a6d201bc 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -324,10 +324,20 @@ const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", { .annotate(Tool.Idempotent, true) .annotate(Tool.OpenWorld, false); +const WatchPullRequestInput = Schema.Struct({ + ...PullRequestTargetInput.fields, + untilMerged: Schema.optional( + Schema.Boolean.annotate({ + description: + "Keep this thread working until the PR merges or closes, not just until its checks finish. Set it when you will act on the PR yourself, such as merging it after someone else approves; leave it off when handing the PR to the user.", + }), + ), +}); + const WatchPullRequestTool = Tool.make("watch_pull_request", { description: "Watch an open PR for this thread, linking it first if needed. T3 wakes you on failed checks, passed required checks, new comments or reviews, or conflicts. Handle old comments first. Only later ones wake you. After this call, end your turn. The watch stays on after each wake, so do not call this again on a wake. A wake is not a merge decision. Check readiness yourself.", - parameters: PullRequestTargetInput, + parameters: WatchPullRequestInput, success: WatchPullRequestResult, failure: PullRequestToolError, dependencies: watchDependencies, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 3dc32ee9863b2..5bf6c25e27322 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -892,11 +892,23 @@ function syncedPullRequestWatch( }, ): ThreadPullRequestWatch | undefined { if (command.watch === null) return undefined; + // Only the agent sets untilMerged, so a read in flight keeps what the watch has now. + const watch = withUntilMerged(command.watch, existing?.untilMerged === true); // A push cleared the answer while this read was in flight, so its answer is the old head's. if (command.checksPendingBefore === undefined || existing?.checksPending !== undefined) { - return command.watch; + return watch; } - return withoutChecksAnswer(command.watch); + return withoutChecksAnswer(watch); +} + +function withUntilMerged( + watch: ThreadPullRequestWatch, + untilMerged: boolean | undefined, +): ThreadPullRequestWatch { + if (untilMerged === undefined || untilMerged === (watch.untilMerged === true)) return watch; + if (untilMerged) return { ...watch, untilMerged: true }; + const { untilMerged: _off, ...rest } = watch; + return rest; } const withoutChecksAnswer = ({ @@ -5077,43 +5089,46 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : existing.watch : !command.watching ? undefined - : (existing.watch ?? { - startedAt, - headSha: null, - failedChecks: [], - passed: false, - passedChecks: [], - conflicting: false, - // Watching again must not repeat check or conflict news the last watch told. - ...(existing.endedWatch && { - headSha: existing.endedWatch.headSha, - failedChecks: existing.endedWatch.failedChecks, - passed: existing.endedWatch.passed, - passedChecks: existing.endedWatch.passedChecks, - conflicting: existing.endedWatch.conflicting, - rebaseRequired: existing.endedWatch.rebaseRequired, - }), - awaitingBaseline: existing.endedWatch - ? existing.endedWatch.awaitingBaseline - : "all", - ...(existing.endedWatch?.owedChecks !== undefined && { - owedChecks: existing.endedWatch.owedChecks, - }), - ...(existing.endedWatch?.awaitingApproval !== undefined && { - awaitingApproval: existing.endedWatch.awaitingApproval, - }), - ...(existing.endedWatch?.approvalAnnounced !== undefined && { - approvalAnnounced: existing.endedWatch.approvalAnnounced, - }), - // A finished-checks answer may be an older head's; a fresh read decides. - ...(existing.endedWatch?.checksPending === true && { checksPending: true }), - ...(existing.endedWatch?.checksAwaitedSince !== undefined && { - checksAwaitedSince: existing.endedWatch.checksAwaitedSince, - }), - remarksThrough: startedAt, - remarkIds: [], - wakes: 0, - }); + : withUntilMerged( + existing.watch ?? { + startedAt, + headSha: null, + failedChecks: [], + passed: false, + passedChecks: [], + conflicting: false, + // Watching again must not repeat check or conflict news the last watch told. + ...(existing.endedWatch && { + headSha: existing.endedWatch.headSha, + failedChecks: existing.endedWatch.failedChecks, + passed: existing.endedWatch.passed, + passedChecks: existing.endedWatch.passedChecks, + conflicting: existing.endedWatch.conflicting, + rebaseRequired: existing.endedWatch.rebaseRequired, + }), + awaitingBaseline: existing.endedWatch + ? existing.endedWatch.awaitingBaseline + : "all", + ...(existing.endedWatch?.owedChecks !== undefined && { + owedChecks: existing.endedWatch.owedChecks, + }), + ...(existing.endedWatch?.awaitingApproval !== undefined && { + awaitingApproval: existing.endedWatch.awaitingApproval, + }), + ...(existing.endedWatch?.approvalAnnounced !== undefined && { + approvalAnnounced: existing.endedWatch.approvalAnnounced, + }), + // A finished-checks answer may be an older head's; a fresh read decides. + ...(existing.endedWatch?.checksPending === true && { checksPending: true }), + ...(existing.endedWatch?.checksAwaitedSince !== undefined && { + checksAwaitedSince: existing.endedWatch.checksAwaitedSince, + }), + remarksThrough: startedAt, + remarkIds: [], + wakes: 0, + }, + command.untilMerged, + ); if (watch === existing.watch && links === linked) return thread; const final = command.type === "thread.pull-request-watch.sync" && watch === undefined diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index 8fdab0f30fee2..03ca9782249a3 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -229,7 +229,8 @@ function watchesEqual(left: ThreadPullRequestWatch, right: ThreadPullRequestWatc left.wakes === right.wakes && left.awaitingBaseline === right.awaitingBaseline && left.checksAwaitedSince === right.checksAwaitedSince && - left.checksPending === right.checksPending + left.checksPending === right.checksPending && + left.untilMerged === right.untilMerged ); } diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.ts b/apps/server/src/orchestration-v2/pullRequestWatch.ts index ad7ad80f72638..1bf19a7b18575 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.ts @@ -256,6 +256,7 @@ export function evaluatePullRequestWatch( }), checksAwaitedSince, checksPending, + ...(watch.untilMerged === true && { untilMerged: true as const }), }, exhausted: commentsOnly && wakes >= PULL_REQUEST_WATCH_WAKE_LIMIT, }; diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 29aac0d000cf4..e1cabbeffd3cd 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -4280,6 +4280,73 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect("keeps a watch's untilMerged across reads until the agent changes it", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const maintenance = yield* ProjectionReplay.ProjectionReplay; + const threadId = ThreadId.make("runtime-pull-request-watch-until-merged"); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("pr-watch-merged-create"), + threadId, + projectId: ProjectId.make("pr-watch-project"), + title: "Watch until merged", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + const key = { host: "github.com", repository: "pingdotgg/t3code", number: 7 }; + const watchOf = Effect.map( + orchestrator.getThreadShell(threadId), + (thread) => thread?.pullRequests?.[0]?.watch, + ); + const watch = (id: string, untilMerged?: boolean) => + orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make(id), + threadId, + ...key, + watching: true, + link: { url: "https://github.com/pingdotgg/t3code/pull/7", source: "agent" }, + ...(untilMerged !== undefined && { untilMerged }), + }); + + yield* watch("pr-watch-merged-start"); + assert.isUndefined((yield* watchOf)?.untilMerged); + + yield* watch("pr-watch-merged-on", true); + const started = yield* watchOf; + assert.equal(started?.untilMerged, true); + if (started === undefined) return; + + // A read that began before the agent set it must not drop it. + const { untilMerged: _read, ...readBefore } = started; + yield* orchestrator.dispatch({ + type: "thread.pull-request-watch.sync", + commandId: CommandId.make("pr-watch-merged-record"), + threadId, + ...key, + startedAt: started.startedAt, + watch: { ...readBefore, headSha: "abc123", checksPending: false }, + }); + assert.equal((yield* watchOf)?.untilMerged, true); + assert.equal((yield* watchOf)?.headSha, "abc123"); + + yield* watch("pr-watch-merged-again"); + assert.equal((yield* watchOf)?.untilMerged, true); + assert.isTrue((yield* maintenance.rebuild).valid); + assert.equal((yield* watchOf)?.untilMerged, true); + + yield* watch("pr-watch-merged-off", false); + assert.isUndefined((yield* watchOf)?.untilMerged); + assert.equal((yield* watchOf)?.headSha, "abc123"); + }), + ); + it.effect.each(["manual", "automatic"])("settling ends every pull request watch: %s", (mode) => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 6658b3beaea3b..ec5f1b9448e11 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6037, "codexAdditionalContextBytes": 7431, - "mcpToolListJsonBytes": 52145 + "mcpToolListJsonBytes": 52423 } diff --git a/apps/server/src/pullRequest/PullRequestWatchService.ts b/apps/server/src/pullRequest/PullRequestWatchService.ts index 6ed736075c018..a3ff3496ced79 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.ts @@ -69,6 +69,7 @@ export class PullRequestWatchService extends Context.Service< readonly threadId: ThreadId; readonly target: PullRequestTarget; readonly watching: boolean; + readonly untilMerged?: boolean | undefined; }) => Effect.Effect< ResolvedTarget & { readonly watching: boolean; readonly wasWatching: boolean }, | PullRequestWatchFailedError @@ -104,6 +105,7 @@ const make = Effect.gen(function* () { readonly threadId: ThreadId; readonly target: PullRequestTarget; readonly watching: boolean; + readonly untilMerged?: boolean | undefined; }) { const { watching } = input; const thread = yield* requireThread(input.threadId); @@ -158,6 +160,7 @@ const make = Effect.gen(function* () { number: target.number, watching, ...(watching ? { link: { url: target.url, source: "agent" as const } } : {}), + ...(watching && input.untilMerged !== undefined && { untilMerged: input.untilMerged }), }) .pipe( Effect.catchCause((cause) => diff --git a/docs/user/source-control.md b/docs/user/source-control.md index d419a6a55ca0b..73a2b95154d47 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -351,8 +351,10 @@ A watched thread counts as working while the pull request still has checks runni the **Working** section, including after the agent pushes a fix. Once every check has finished, including review bots that report as checks, the thread returns to your inbox: what happens next is up to a person. That includes a workflow waiting for a maintainer to approve it, which runs only -once someone does. The watch stays on and still wakes the agent on new comments, failed checks or -conflicts, and a watched thread never auto-settles. +once someone does. If you ask the agent to act on the pull request itself, such as merging it once +a teammate approves, the thread stays in **Working** until the pull request merges or closes. The +watch stays on and still wakes the agent on new comments, failed checks or conflicts, and a watched +thread never auto-settles. Cross-repository links use a project on the same host. Azure DevOps reviews require a project checked out from the matching organization and repository. diff --git a/evals/mcp-tool-use/cases/pull-requests.ndjson b/evals/mcp-tool-use/cases/pull-requests.ndjson index 2e14e45f7f250..b4edc838d1d69 100644 --- a/evals/mcp-tool-use/cases/pull-requests.ndjson +++ b/evals/mcp-tool-use/cases/pull-requests.ndjson @@ -37,3 +37,5 @@ {"id": "link-one-pr", "area": "pull-requests", "privacy": "commit-safe", "kind": "control", "pattern": "single link stays single", "experience": "Linking one named PR is ordinary work.", "setup": {"role": "top", "context": "No pull requests are linked to this thread.", "world": {"repo": "acme/app", "branch": "main"}}, "prompt": "link https://github.com/acme/app/pull/130 here", "expect": {"calls": [{"tool": "link_pull_request", "args": {"url": "~/pull/130"}}], "notCalls": ["link_pull_requests"]}, "maxSteps": 6, "source": {"thread": "Synthetic control for batch link"}} {"id": "schedule-one-time-date", "area": "pull-requests", "kind": "bad", "pattern": "one-off date scheduled as a daily task", "experience": "Theo asked whether a scheduled task can run at a specific date and time. schedule_task only had daily times, intervals, and webhooks, so a one-off request became a daily task.", "source": {"report": "maintainer request, 2026-10-31: scheduled tasks could not run at one date and time"}, "rule": "schedule: {type:'once',runAt} for one date and time", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"schedule_task": {"scheduledTaskId": "scheduled-task-4", "title": "Cut 2.0 release branch", "schedule": {"type": "once", "runAt": "2026-11-03T09:00:00.000Z"}, "enabled": true, "nextRunAt": "2026-11-03T09:00:00.000Z"}}}, "prompt": "On November 3rd at 9am UTC, start a new thread that cuts the 2.0 release branch from main in acme/app. Only that one time.", "expect": {"calls": [{"tool": "schedule_task", "args": {"schedule.type": "once", "schedule.runAt": "~11-03T09:00"}}], "notCalls": ["delegate_task", "run_scheduled_task_now"]}, "notes": "Mock result shape is an approximation."} {"id": "schedule-fresh-session-per-run", "area": "pull-requests", "kind": "guard", "pattern": "recurring task that should not accumulate context", "experience": "A recurring triage task kept one thread so the user could read its history, but each run carried every earlier run's context into the next.", "rule": "schedule_task `freshSession: true` keeps runs in one thread while each run starts a fresh session.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Today is Monday 2026-11-02, 10:00 local time.", "mocks": {"schedule_task": {"scheduledTaskId": "scheduled-task-7", "title": "Triage new issues", "enabled": true, "projectId": "project-1", "boundThreadId": null, "freshSession": true, "schedule": {"type": "fixed_time", "timeOfDay": "09:00"}, "nextRunAt": "2026-11-03T09:00:00-08:00", "lastRunStatus": "never"}}}, "prompt": "Every morning at 9, triage new issues in acme/app. Keep all the runs in one thread so I can scroll back, but each run should start clean without remembering the previous days.", "expect": {"calls": [{"tool": "schedule_task", "args": {"schedule.type": "fixed_time", "freshSession": true}}], "notCalls": ["delegate_task", "run_scheduled_task_now"]}, "source": {"request": "juliusmarminge (maintainer) request, 2026-11-03: automations in one thread with separate provider sessions"}, "notes": "schedule-one-off-tomorrow is the control: an ordinary schedule must not set freshSession."} +{"id": "babysit-merge-after-approval-until-merged", "area": "pull-requests", "kind": "bad", "pattern": "babysit until a teammate approves, then merge, without untilMerged", "experience": "Asked to babysit a PR and merge it once a teammate approved, the agent watched it without untilMerged, so the thread left Working as soon as checks passed while the agent still owned the merge.", "rule": "untilMerged: set it when you will act on the PR yourself, such as merging it after someone else approves", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "The HTML preview frame has no accessible name. Fix it and open a PR."}, {"role": "assistant", "text": "Opened [PR #124](https://github.com/acme/app/pull/124). The preview frame now has the title \"HTML preview\".", "toolCalls": [{"tool": "Bash", "input": {"command": "git push -u origin fix/html-preview-title && gh pr create --fill"}, "result": "https://github.com/acme/app/pull/124"}, {"tool": "link_pull_request", "input": {"url": "https://github.com/acme/app/pull/124"}, "result": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124", "alreadyLinked": false}}]}], "mocks": {"watch_pull_request": "default", "link_pull_request": "default"}, "world": {"branch": "fix/html-preview-title", "commits": [{"sha": "abc1234", "subject": "fix(web): HTML preview frame gets an accessible title"}], "diff": "diff --git a/apps/web/src/HtmlPreview.tsx b/apps/web/src/HtmlPreview.tsx\n--- a/apps/web/src/HtmlPreview.tsx\n+++ b/apps/web/src/HtmlPreview.tsx\n@@ -1,3 +1,3 @@\n export function HtmlPreview({ html }: { html: string }) {\n- return