@devries-cameron20 / t3code Mirror · read-only / commits / c4419dadd9
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

fix(server): threads stay in Working when Claude or OpenCode marks a background wait between turns (#38638)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Bilal Bakr committed Nov 19, 2026 at 23:47 UTC c4419dadd91249d9eeff4a26c1098517e71736f0
4 files changed +276 -13
apps/server/src/mcp/toolkits/core.test.ts
+40
@@ -1291,6 +1291,46 @@ it.effect.each(["t3_thread_interrupt", "t3_workflow_stop"])(
1291 ),
1292 );
1293
1294 +it.effect(
1295 + "t3_background_wait marks work from a turn Claude started before T3 started its run",
1296 + () =>
1297 + Effect.gen(function* () {
1298 + const server = yield* McpServer.McpServer;
1299 + const result = yield* server
1300 + .callTool({ name: "t3_background_wait", arguments: { taskIds: ["checks"] } })
1301 + .pipe(
1302 + Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
1303 + Effect.provideService(McpSchema.McpServerClient, client),
1304 + );
1305 + expect(result.structuredContent).toEqual({ matched: ["checks"], unmatched: [] });
1306 + }).pipe(
1307 + Effect.provide(
1308 + layerOrchestratorToolkit.pipe(
1309 + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
1310 + Layer.provide(NodeCrypto.layer),
1311 + Layer.provide(
1312 + Layer.mock(ThreadManagement.ThreadManagementService)({
1313 + getThreadShell: (id) =>
1314 + Effect.succeed(McpToolAccessTestkit.liveThreadShell(id, { activeRunId: null })),
1315 + awaitBackgroundTasks: ({ taskIds }) =>
1316 + Effect.succeed({ matched: taskIds, unmatched: [] }),
1317 + }),
1318 + ),
1319 + Layer.provide(ServerSettings.layerTest()),
1320 + Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
1321 + Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
1322 + Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
1323 + Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
1324 + Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
1325 + Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
1326 + Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
1327 + Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
1328 + Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
1329 + ),
1330 + ),
1331 + ),
1332 +);
1333 +
1334 it.effect("discovers workflow stop targets and requires orchestration capability", () => {
1335 const threadId = ThreadId.make("workflow-parent");
1336 const shell = McpToolAccessTestkit.liveThreadShell(threadId);
apps/server/src/mcp/toolkits/orchestrator/handlers.ts
+2 -1
@@ -61,7 +61,8 @@ const handlers = {
61 );
62 }),
63 ),
64 - t3_background_wait: McpToolAccess.actsAsCaller((input) =>
64 + // Claude can start a turn by itself before T3 starts its run, so a live-run check would refuse the mark.
65 + t3_background_wait: McpToolAccess.readsAsCaller((input) =>
66 Effect.gen(function* () {
67 const { scope, threads } = yield* readCaller();
68 const caller = yield* McpInvocationContext.requireThreadScope(scope, "t3_background_wait");
apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+145
@@ -2342,6 +2342,151 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2342 }),
2343 );
2344
2345 + it.effect.each(["running", "exited", "timeout", "held", "sync"] as const)(
2346 + "marks a shell OpenCode started on its own before T3 runs the wake, shell %s",
2347 + (shell) =>
2348 + Effect.gen(function* () {
2349 + const shellID = "sh_wake";
2350 + const tool = { sessionID: SESSION, assistantMessageID: "msg_wake", id: "call-wake-shell" };
2351 + const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
2352 + const shellReport = (state: string, extra: Record<string, unknown> = {}) =>
2353 + event("session.inbox.enqueued", {
2354 + inboxID: "msg_shell_report",
2355 + sessionID: SESSION,
2356 + item: {
2357 + type: "synthetic",
2358 + payload: {
2359 + text: `<shell id="${shellID}" state="${state}">done</shell>`,
2360 + description: "vp test",
2361 + metadata: { source: "shell", shellID, state, ...extra },
2362 + },
2363 + delivery: "steer",
2364 + },
2365 + });
2366 + const { runtime, thread } = yield* resumed([
2367 + ...backgroundLaunch(CHILD),
2368 + event("session.execution.succeeded", { sessionID: SESSION }),
2369 + event("session.execution.succeeded", { sessionID: CHILD }),
2370 + childReport("msg_report", "CHILD_OK"),
2371 + event("session.execution.started", { sessionID: SESSION }),
2372 + event("session.tool.input.started", { ...tool, name: "shell" }),
2373 + event("session.tool.called", {
2374 + ...tool,
2375 + name: "shell",
2376 + input: { command: "vp test", background: true },
2377 + executed: false,
2378 + }),
2379 + event(
2380 + "session.tool.success",
2381 + {
2382 + ...tool,
2383 + content: [{ type: "text", text: "Launched" }],
2384 + // A foreground shell's result already carries its exit.
2385 + metadata: shell === "sync" ? { shellID, exit: 0 } : { shellID },
2386 + executed: false,
2387 + },
2388 + undefined,
2389 + 2,
2390 + ),
2391 + event("shell.created", {
2392 + info: {
2393 + id: shellID,
2394 + status: "running",
2395 + command: "vp test",
2396 + cwd: WORK,
2397 + shell: "bash",
2398 + file: "/tmp/sh_wake.log",
2399 + metadata: { sessionID: SESSION },
2400 + time: { started: 1 },
2401 + },
2402 + }),
2403 + ...(shell === "held" ? [shellReport("completed")] : []),
2404 + event("session.execution.succeeded", { sessionID: SESSION }),
2405 + ...(shell === "exited"
2406 + ? [
2407 + event("shell.exited", { id: shellID, exit: 7, status: "exited" }),
2408 + shellReport("error"),
2409 + ]
2410 + : []),
2411 + ...(shell === "timeout"
2412 + ? [
2413 + event("shell.exited", { id: shellID, status: "timeout" }),
2414 + shellReport("completed", { timeout: true }),
2415 + ]
2416 + : []),
2417 + // Routed once the held execution ended, so its update proves the launch reached the adapter.
2418 + event("session.model.selected", {
2419 + sessionID: SESSION,
2420 + model: { providerID: "opencode", id: "big-pickle", variant: "thinking" },
2421 + }),
2422 + ...Array.from({ length: shell === "held" ? 2 : shell === "sync" ? 0 : 1 }, () => [
2423 + out("shell.output", "<any>"),
2424 + reply("shell.output", {
2425 + location: { directory: WORK },
2426 + data: { output: "", cursor: 0, size: 0, truncated: false },
2427 + }),
2428 + ]).flat(),
2429 + ]).pipe(
2430 + Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
2431 + offer: (request) =>
2432 + Effect.sync(() => {
2433 + offers.push(request);
2434 + }),
2435 + take: Effect.never,
2436 + }),
2437 + );
2438 + // One reader: the runtime's event queue hands each event to only one taker.
2439 + const launchSeen = yield* Deferred.make<void>();
2440 + const marked = yield* Deferred.make<boolean | undefined>();
2441 + const settled =
2442 + yield* Deferred.make<import("@t3tools/contracts").OrchestrationV2TurnItem>();
2443 + yield* runtime.events.pipe(
2444 + Stream.tap((e) =>
2445 + e.type === "turn_item.updated" &&
2446 + e.turnItem.type === "command_execution" &&
2447 + e.turnItem.status !== "running"
2448 + ? Deferred.succeed(settled, e.turnItem)
2449 + : e.type !== "provider_thread.updated"
2450 + ? Effect.void
2451 + : Effect.gen(function* () {
2452 + const variant =
2453 + e.providerThread.nativeMetadata?.modelSelection?.options?.[0]?.value;
2454 + if (variant === "thinking") yield* Deferred.succeed(launchSeen, undefined);
2455 + const listed = e.providerThread.pendingBackgroundTasks?.find(
2456 + (task) => task.taskId === shellID,
2457 + );
2458 + // The first roster that lists the shell must hold the thread already.
2459 + if (listed !== undefined) yield* Deferred.succeed(marked, listed.awaited);
2460 + }),
2461 + ),
2462 + Stream.runDrain,
2463 + Effect.forkScoped,
2464 + );
2465 + yield* runtime.startTurn(withLineage(thread));
2466 + yield* Deferred.await(launchSeen);
2467 + assert.deepEqual(
2468 + yield* runtime.awaitBackgroundTasks!({
2469 + providerThread: thread,
2470 + taskIds: [shellID],
2471 + awaited: true,
2472 + }),
2473 + { matched: shell === "running" ? [shellID] : [] },
2474 + );
2475 + if (shell === "sync") return;
2476 + yield* runtime.startTurn(continuationTurn(thread, offers[0]!));
2477 + if (shell === "running") return assert.isTrue(yield* Deferred.await(marked));
2478 + // A shell that ended before the wake ran never holds the thread.
2479 + assert.deepInclude(
2480 + yield* Deferred.await(settled),
2481 + shell === "exited"
2482 + ? { status: "failed", exitCode: 7 }
2483 + : { status: shell === "timeout" ? "failed" : "completed" },
2484 + );
2485 + const listed = yield* Deferred.poll(marked);
2486 + if (Option.isSome(listed)) assert.notStrictEqual(yield* listed.value, true);
2487 + }),
2488 + );
2489 +
2490 it.effect("clears the caller's pending work when a called session's held wake runs", () =>
2491 Effect.gen(function* () {
2492 const OTHER = "ses_other00000000000000000000";
packages/provider-opencode/src/server/v2/adapter.ts
+89 -12
@@ -313,6 +313,12 @@ interface Wake {
313 readonly after: string | undefined;
314 readonly first: string | undefined;
315 readonly children: Set<string>;
316 + readonly awaited: Set<string>;
317 + /** Held shell launches whose end report arrived first; the report already cleared their status. */
318 + readonly ended: Map<
319 + string,
320 + { readonly status: "completed" | "failed" | "interrupted"; readonly exit?: number }
321 + >;
322 }
323
324 interface OpenBlock {
@@ -1011,6 +1017,38 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
1017 }
1018 >();
1019
1020 + // A held wake routes its shell launches only when T3 starts its run, so marks wait on the wake.
1021 + const heldLaunch = (state: ThreadState, taskId: string) =>
1022 + sessionsOf(state)
1023 + .flatMap((session) => session.wakes)
1024 + .find((wake) =>
1025 + wake.events.some(
1026 + (event) =>
1027 + event.type === "session.tool.success" &&
1028 + stringField(event.data.metadata, "shellID") === taskId &&
1029 + event.data.metadata?.["exit"] === undefined &&
1030 + event.data.metadata?.["signal"] === undefined &&
1031 + event.data.metadata?.["timeout"] !== true,
1032 + ),
1033 + );
1034 + const wakeLaunchingShell = (state: ThreadState, taskId: string) => {
1035 + const wake = heldLaunch(state, taskId);
1036 + return wake === undefined ||
1037 + wake.ended.has(taskId) ||
1038 + (shellInfo.get(taskId)?.status ?? "running") !== "running" ||
1039 + // An end report held with the launch replays after it.
1040 + wake.events.some(
1041 + (event) =>
1042 + event.type === "session.inbox.enqueued" &&
1043 + event.data.item.type === "synthetic" &&
1044 + stringField(event.data.item.payload.metadata, "source") === "shell" &&
1045 + stringField(event.data.item.payload.metadata, "shellID") === taskId,
1046 + )
1047 + ? undefined
1048 + : wake;
1049 + };
1050 + let replaying: Wake | undefined;
1051 +
1052 const owesWork = (state: ThreadState) =>
1053 [...shells.values()].some((shell) => shell.state === state && shell.running) ||
1054 [...state.imageJobs.values()].some((job) => job.status === "running") ||
@@ -1966,7 +2004,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
2004 awaited:
2005 state.providerThread.pendingBackgroundTasks?.some(
2006 (task) => task.taskId === info.id && task.awaited === true,
1969 - ) === true,
2007 + ) === true || wakeLaunchingShell(state, info.id)?.awaited.has(info.id) === true,
2008 running: true,
2009 output: "",
2010 cursor: 0,
@@ -2863,25 +2901,30 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
2901 toolId: event.data.id,
2902 tool,
2903 command: stringField(tool.input, "command") ?? "Shell command",
2904 + ...(replaying?.awaited.has(shellId) === true ? { awaited: true } : {}),
2905 running: true,
2906 output: "",
2907 cursor: 0,
2908 });
2870 - yield* readShellOutput(shellId).pipe(Effect.ignore({ log: true }));
2909 const known = shellInfo.get(shellId);
2910 + const ended = replaying?.ended.get(shellId);
2911 const tracked = shells.get(shellId)!;
2873 - tracked.running = known === undefined || known.status === "running";
2912 + tracked.running =
2913 + ended === undefined && (known === undefined || known.status === "running");
2914 + yield* readShellOutput(shellId, !tracked.running).pipe(Effect.ignore({ log: true }));
2915 yield* emitShell(
2916 shellId,
2917 tracked.running
2918 ? "running"
2878 - : known?.status === "killed"
2879 - ? "interrupted"
2880 - : known?.exit === 0
2881 - ? "completed"
2882 - : "failed",
2883 - known?.exit,
2919 + : (ended?.status ??
2920 + (known?.status === "killed"
2921 + ? "interrupted"
2922 + : known?.exit === 0
2923 + ? "completed"
2924 + : "failed")),
2925 + ended?.exit ?? known?.exit,
2926 );
2927 + if (ended !== undefined) shells.delete(shellId);
2928 yield* syncRosterAncestors(state);
2929 return;
2930 }
@@ -3009,6 +3052,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3052 after: delivered.at(-1)?.inboxId,
3053 first: leading ?? delivered[0]?.inboxId,
3054 children: new Set(),
3055 + awaited: new Set(),
3056 + ended: new Map(),
3057 };
3058 state.wakes.push(wake);
3059 yield* Effect.logInfo("OpenCode started a turn on its own; asking for a continuation.", {
@@ -3119,6 +3164,27 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3164 outcome: reportOutcome(stringField(payload.metadata, "state")),
3165 },
3166 });
3167 + if (id !== undefined && shell === undefined) {
3168 + const outcome = reportOutcome(stringField(payload.metadata, "state"));
3169 + const known = shellInfo.get(id);
3170 + const exit = known?.exit;
3171 + // A known exit outranks the report, which says "completed" for a timeout.
3172 + heldLaunch(state, id)?.ended.set(id, {
3173 + status:
3174 + known !== undefined && known.status !== "running"
3175 + ? known.status === "killed"
3176 + ? "interrupted"
3177 + : exit === 0
3178 + ? "completed"
3179 + : "failed"
3180 + : outcome === "failed"
3181 + ? "failed"
3182 + : outcome === "cancelled"
3183 + ? "interrupted"
3184 + : "completed",
3185 + ...(exit === undefined ? {} : { exit }),
3186 + });
3187 + }
3188 if (id !== undefined && shell?.stopping !== true) {
3189 if (shell?.running === true && shell.state === state) {
3190 yield* readShellOutput(id, true).pipe(Effect.ignore({ log: true }));
@@ -4424,7 +4490,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
4490
4491 const replay = Effect.fnUntraced(function* (wake: Wake) {
4492 wake.dropped = true;
4427 - for (const event of wake.events) yield* route(event, sessionOfEvent(event), true);
4493 + replaying = wake;
4494 + yield* Effect.forEach(wake.events, (event) => route(event, sessionOfEvent(event), true), {
4495 + discard: true,
4496 + }).pipe(Effect.ensuring(Effect.sync(() => (replaying = undefined))));
4497 });
4498
4499 const discardWakes = (caller: ThreadState, wakes: ReadonlyArray<Wake>) => {
@@ -5153,11 +5222,19 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
5222 const sessions = sessionsOf(state);
5223 const matched = [...new Set(taskIds)].filter((taskId) => {
5224 const shell = shells.get(taskId);
5156 - return shell !== undefined && shell.running && sessions.includes(shell.state);
5225 + return shell === undefined
5226 + ? wakeLaunchingShell(state, taskId) !== undefined
5227 + : shell.running && sessions.includes(shell.state);
5228 });
5229 if (matched.length === 0) return { matched };
5230 for (const taskId of matched) {
5160 - const shell = shells.get(taskId)!;
5231 + const shell = shells.get(taskId);
5232 + if (shell === undefined) {
5233 + const held = wakeLaunchingShell(state, taskId)!.awaited;
5234 + if (awaited) held.add(taskId);
5235 + else held.delete(taskId);
5236 + continue;
5237 + }
5238 shell.awaited = awaited;
5239 yield* syncRosterAncestors(shell.state);
5240 }