Skip to content

Commit cbc471a

Browse files
fix(threads): Working holds only background work the agent waits on
A thread left Working while the agent was still waiting on a background command (tests, a CI wait), and stayed stuck in Working while a dev-server watchdog Monitor ran. Both came from deciding "the agent will come back" by task kind: commands never held and monitors always did, but either can be a wait or a process left running. Agents now mark the background work they will resume from with the t3_background_wait MCP tool. Marked tasks hold the thread in Working, block completion alerts, auto-settle and snooze wake, and wake the agent after a restart. Unmarked commands and monitors do neither. Subagents and PR watches hold as before. Claude implements the mark on its roster entries, so it ends with the task and resets with the process, and its system prompt says when to call the tool, since Claude Code defers MCP tools behind ToolSearch. Other providers report the tool as unsupported.
1 parent 7c83530 commit cbc471a

32 files changed

Lines changed: 675 additions & 83 deletions

‎apps/mobile/src/features/threads/threadListV2.test.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,9 @@ describe("resolveThreadListV2Status", () => {
163163
makeThread({
164164
id: ThreadId.make("t"),
165165
title: "t",
166-
pendingBackgroundTasks: [{ taskId: "bg-1", description: "Watch build", kind: "monitor" }],
166+
pendingBackgroundTasks: [
167+
{ taskId: "bg-1", description: "Watch build", kind: "monitor", awaited: true },
168+
],
167169
runtime: {
168170
status: "idle",
169171
activeRunId: null,
@@ -178,19 +180,20 @@ describe("resolveThreadListV2Status", () => {
178180
});
179181

180182
it.each([
181-
{ kind: "command", status: "ready" },
182-
{ kind: "monitor", status: "waiting" },
183+
{ roster: "dev server", task: { kind: "command" }, status: "ready" },
184+
{ roster: "dev server watchdog", task: { kind: "monitor" }, status: "ready" },
185+
{ roster: "awaited command", task: { kind: "command", awaited: true }, status: "waiting" },
183186
] as const)(
184-
"presents an unseen completion with a $kind roster as $status",
185-
({ kind, status }) => {
187+
"presents an unseen completion with a $roster roster as $status",
188+
({ task, status }) => {
186189
const thread = presentThreadShell(
187190
environmentId,
188191
makeRawThreadShell({
189192
latestRunId: RunId.make("run-background-completion"),
190193
status: "completed",
191194
latestRunCompletedAt: DateTime.makeUnsafe(NOW),
192195
lastVisitedAt: DateTime.makeUnsafe("2026-06-01T23:59:00.000Z"),
193-
pendingBackgroundTasks: [{ taskId: "background-work", kind }],
196+
pendingBackgroundTasks: [{ taskId: "background-work", ...task }],
194197
}),
195198
);
196199

‎apps/server/src/mcp/toolkits/orchestrator/handlers.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,27 @@ const handlers = {
5757
);
5858
}),
5959
),
60+
t3_background_wait: McpToolAccess.actsAsCaller((input) =>
61+
Effect.gen(function* () {
62+
const { scope, threads } = yield* readCaller();
63+
const caller = yield* McpInvocationContext.requireThreadScope(scope, "t3_background_wait");
64+
return yield* threads
65+
.awaitBackgroundTasks({
66+
threadId: caller.thread.threadId,
67+
taskIds: input.taskIds,
68+
awaited: input.waiting ?? true,
69+
})
70+
.pipe(
71+
Effect.mapError(
72+
(cause) =>
73+
new OrchestratorMcpFailure({
74+
code: cause.reason === "unsupported" ? "invalid_request" : "orchestration_error",
75+
message: cause.message,
76+
}),
77+
),
78+
);
79+
}),
80+
),
6081
schedule_task: McpToolAccess.startsThreads(
6182
() => ({}),
6283
(input) =>

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
OrchestratorMcpThreadWaitResult,
3131
ThreadMetadataMcpUpdateInput,
3232
ThreadMetadataMcpUpdateResult,
33+
TrimmedNonEmptyString,
3334
} from "@t3tools/contracts";
3435
import { Tool, Toolkit } from "effect/ai";
3536
import * as Schema from "effect/Schema";
@@ -114,6 +115,25 @@ const WorkflowStopTool = Tool.make("t3_workflow_stop", {
114115
.annotate(Tool.Title, "Stop a workflow")
115116
.annotate(Tool.Destructive, true);
116117

118+
const BackgroundWaitTool = Tool.make("t3_background_wait", {
119+
description:
120+
"Keep this thread in the user's Working list while you wait on your own background work. After starting a background command or Monitor whose result you will act on when you are woken, call this with its task ID (the ID shown when it started) before ending your turn. Until that task ends, the thread stays in Working and the user is not told it finished. Unmarked background commands and monitors, such as dev servers and their watchdogs, never keep the thread in Working, so do not mark those. Pass waiting=false to stop waiting without stopping the task. IDs that are not running come back in unmatched and change nothing. Only Claude threads support this.",
121+
parameters: Schema.Struct({
122+
taskIds: Schema.Array(TrimmedNonEmptyString).check(
123+
Schema.isMinLength(1),
124+
Schema.isMaxLength(20),
125+
),
126+
waiting: Schema.optional(Schema.Boolean),
127+
}),
128+
success: Schema.Struct({
129+
matched: Schema.Array(Schema.String),
130+
unmatched: Schema.Array(Schema.String),
131+
}),
132+
failure: OrchestratorMcpFailure,
133+
failureMode: "return",
134+
dependencies,
135+
}).annotate(Tool.Title, "Wait on background work");
136+
117137
export const ScheduleTaskTool = Tool.make("schedule_task", {
118138
description:
119139
"Create persistent work in the app scheduler that runs even when no turn is active. Pass schedule as a STRUCTURED OBJECT, never JSON text. Timers: {type:'interval', everyMs:3600000} is hourly; {type:'fixed_time', timeOfDay:'09:00', weekdays:[1,2,3,4,5]} is weekday mornings; report the returned nextRunAt. Webhooks: {type:'webhook'} runs once per request to a generated URL. The run sees the request ONLY through prompt placeholders: {{body.path}} (e.g. {{body.action}}, {{body.release.tag_name}}), {{headers.name}}, {{query.name}}, {{body}}, or {{request}} (method, headers with credentials redacted, and body). Each value arrives framed as untrusted request data, and $skill, @file or /command mentions inside it do not act; without a signature, anyone with the URL can trigger a run. For a sender that signs requests, first call request_secret so the user enters the secret privately (never ask for it in chat or invent one), then set signature with the returned secretRef, e.g. GitHub: {type:'webhook', signature:{header:'x-hub-signature-256', encoding:'hex', prefix:'sha256=', secretRef}}. The result's webhookUrl is the public URL to give the user; if it is absent, this environment has no T3 Connect managed tunnel, so tell the user to enable T3 Connect remote access rather than sharing a path. Omit projectId for this thread's project. In this thread's project, runs post into THIS thread by default (bindToCurrentThread=true), which suits an orchestrator that sees every trigger, delegates work, and can dedupe against what is in flight; use false only when the user wants a fresh top-level thread per run. Elsewhere each run launches a fresh thread. Provider, model, and runtime settings inherit from this thread, or from the project default when there is no calling thread.",
@@ -277,6 +297,7 @@ export const OrchestratorToolkit = Toolkit.make(
277297
TaskStatusTool,
278298
TaskCancelTool,
279299
WorkflowStopTool,
300+
BackgroundWaitTool,
280301
ScheduleTaskTool,
281302
ListScheduledTasksTool,
282303
UpdateScheduledTaskTool,

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -794,6 +794,7 @@ describe("ClaudeAdapterV2 native protocol logging", () => {
794794
assert.equal(systemPrompt.type, "preset");
795795
assert.equal(systemPrompt.preset, "claude_code");
796796
assert.include(systemPrompt.append ?? "", "Use `delegate_task`");
797+
assert.include(systemPrompt.append ?? "", "call `t3_background_wait`");
797798
const logged = ClaudeAdapterV2.loggedClaudeQueryOptions(options);
798799
assert.equal(logged.hasMcpServers, true);
799800
assert.notInclude(JSON.stringify(logged), "secret-claude-token");
@@ -6215,6 +6216,111 @@ describe("ClaudeAdapterV2 background wake turns", () => {
62156216
),
62166217
);
62176218

6219+
it.effect("holds only the background tasks the agent marks awaited, until they end", () =>
6220+
Effect.scoped(
6221+
Effect.gen(function* () {
6222+
const harness = yield* makeWakeHarness;
6223+
const now = yield* DateTime.now;
6224+
const awaitBackgroundTasks = harness.runtime.awaitBackgroundTasks;
6225+
if (awaitBackgroundTasks === undefined) {
6226+
throw new Error("Claude adapter runtime must expose awaitBackgroundTasks.");
6227+
}
6228+
const roster = (tasks: ReadonlyArray<string>, uuid: string) =>
6229+
claudeSdkFrame({
6230+
type: "system",
6231+
subtype: "background_tasks_changed",
6232+
tasks: tasks.map((taskId) => ({
6233+
task_id: taskId,
6234+
task_type: "local_bash",
6235+
description: taskId,
6236+
})),
6237+
uuid,
6238+
session_id: WAKE_NATIVE_SESSION,
6239+
});
6240+
const latestTasks = () =>
6241+
providerThreadRosterEvents(harness.events).at(-1)?.providerThread
6242+
.pendingBackgroundTasks ?? [];
6243+
6244+
yield* harness.runtime.startTurn(
6245+
makeClaudeTestTurnInput({
6246+
threadId: harness.threadId,
6247+
providerThread: harness.providerThread,
6248+
now,
6249+
attemptId: RunAttemptId.make("attempt-claude-awaited-roster"),
6250+
text: "Run the tests in the background and the dev server.",
6251+
attachments: [],
6252+
}),
6253+
);
6254+
yield* Queue.offer(
6255+
harness.sdkMessages,
6256+
roster([WAKE_TASK_ID, "dev-server"], "00000000-0000-4000-8000-000000000301"),
6257+
);
6258+
yield* awaitUntil(() => latestTasks().length === 2, "roster with both tasks");
6259+
6260+
const marked = yield* awaitBackgroundTasks({
6261+
providerThread: harness.providerThread,
6262+
taskIds: [WAKE_TASK_ID, "already-finished"],
6263+
awaited: true,
6264+
});
6265+
assert.deepStrictEqual(marked.matched, [WAKE_TASK_ID]);
6266+
yield* Queue.offer(harness.sdkMessages, turnOneResult);
6267+
yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal");
6268+
assert.deepStrictEqual(
6269+
latestTasks().map((task) => [task.taskId, task.awaited === true]),
6270+
[
6271+
[WAKE_TASK_ID, true],
6272+
["dev-server", false],
6273+
],
6274+
);
6275+
6276+
// A replacing level rebuilds every entry; the mark must survive it.
6277+
yield* Queue.offer(
6278+
harness.sdkMessages,
6279+
roster(["dev-server", WAKE_TASK_ID], "00000000-0000-4000-8000-000000000302"),
6280+
);
6281+
yield* awaitUntil(() => latestTasks()[0]?.taskId === "dev-server", "reordered roster");
6282+
assert.isTrue(latestTasks().some((task) => task.taskId === WAKE_TASK_ID && task.awaited));
6283+
6284+
// Once the task leaves the roster, a reused id starts unmarked.
6285+
yield* Queue.offer(
6286+
harness.sdkMessages,
6287+
roster(["dev-server"], "00000000-0000-4000-8000-000000000303"),
6288+
);
6289+
yield* awaitUntil(() => latestTasks().length === 1, "awaited task ended");
6290+
yield* Queue.offer(
6291+
harness.sdkMessages,
6292+
roster(["dev-server", WAKE_TASK_ID], "00000000-0000-4000-8000-000000000304"),
6293+
);
6294+
yield* awaitUntil(() => latestTasks().length === 2, "id reused");
6295+
assert.isFalse(latestTasks().some((task) => task.awaited === true));
6296+
6297+
yield* awaitBackgroundTasks({
6298+
providerThread: harness.providerThread,
6299+
taskIds: ["dev-server"],
6300+
awaited: true,
6301+
});
6302+
yield* awaitUntil(
6303+
() => latestTasks().some((task) => task.taskId === "dev-server" && task.awaited),
6304+
"dev server marked",
6305+
);
6306+
const released = yield* awaitBackgroundTasks({
6307+
providerThread: harness.providerThread,
6308+
taskIds: ["dev-server"],
6309+
awaited: false,
6310+
});
6311+
assert.deepStrictEqual(released.matched, ["dev-server"]);
6312+
yield* awaitUntil(
6313+
() => !latestTasks().some((task) => task.awaited === true),
6314+
"dev server released",
6315+
);
6316+
}).pipe(
6317+
Effect.provide(
6318+
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
6319+
),
6320+
),
6321+
),
6322+
);
6323+
62186324
it.effect("keeps a running Claude monitor typed after many newer monitors end", () =>
62196325
Effect.scoped(
62206326
Effect.gen(function* () {

0 commit comments

Comments
 (0)