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 22, 23:15 UTC
fix(server): expose turns blocked only on T3 thread waits (#21499)
Julius Marminge committed
Oct 19, 2026 at 21:07 UTC
fb1486901f7d07e9e394b6061323d07967405f4f
9 files changed
+488
-45
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+135
@@ -22,10 +22,12 @@ import {
22
ProviderThreadId,
23
ThreadId,
24
type OrchestrationV2ProviderThread,
25
+ type OrchestrationV2TurnItem,
26
type ProviderOptionDescriptor,
27
} from "@t3tools/contracts";
28
import { GrokSettings } from "@t3tools/provider-grok/settings";
29
import * as HostProcess from "@t3tools/shared/HostProcess";
30
+import { deriveBlockedOnThreadWait } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
31
import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
32
import * as DateTime from "effect/DateTime";
33
import * as Deferred from "effect/Deferred";
@@ -913,6 +915,139 @@ describe("AcpAdapterV2", () => {
915
}).pipe(Effect.provide(layerTest), Effect.scoped),
916
);
917
918
+ it.effect.each(["agent_message_chunk", "agent_thought_chunk"] as const)(
919
+ "keeps named ACP %s open while deriving thread wait execution state",
920
+ (sessionUpdate) =>
921
+ Effect.gen(function* () {
922
+ type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
923
+ let handler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
924
+ const instanceId = ProviderInstanceId.make("acp-named-stream-wait");
925
+ const path = yield* Path.Path;
926
+ const adapter = yield* makeAcpAdapterV2({
927
+ instanceId,
928
+ selfInvocation: yield* resolveSelfInvocation(),
929
+ flavor: {
930
+ driver: ACP_TEST_DRIVER,
931
+ capabilities: AcpProviderCapabilitiesV2,
932
+ makeRuntime: makeMockRuntime({
933
+ childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
934
+ mockAgentPath: yield* path.fromFileUrl(
935
+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
936
+ ),
937
+ wrapRuntime: (runtime) => ({
938
+ ...runtime,
939
+ handleSessionUpdate: (next) =>
940
+ Effect.sync(() => {
941
+ handler = next;
942
+ }).pipe(Effect.andThen(runtime.handleSessionUpdate(next))),
943
+ prompt: () =>
944
+ Effect.gen(function* () {
945
+ assert.isDefined(handler);
946
+ const updates = [
947
+ {
948
+ sessionUpdate,
949
+ messageId: "named-stream",
950
+ content: { type: "text", text: "Waiting for the child result" },
951
+ },
952
+ {
953
+ sessionUpdate: "tool_call",
954
+ toolCallId: "wait",
955
+ title: "Wait for the child",
956
+ status: "in_progress",
957
+ rawInput: {
958
+ server: "t3-code",
959
+ tool: "t3_thread_wait",
960
+ arguments: { threadId: "child" },
961
+ },
962
+ _meta: { is_mcp_tool_call: true },
963
+ },
964
+ {
965
+ sessionUpdate: "tool_call",
966
+ toolCallId: "command",
967
+ kind: "execute",
968
+ title: "Run command",
969
+ status: "in_progress",
970
+ rawInput: { command: "pwd" },
971
+ },
972
+ {
973
+ sessionUpdate: "tool_call_update",
974
+ toolCallId: "command",
975
+ status: "completed",
976
+ },
977
+ {
978
+ sessionUpdate: "tool_call_update",
979
+ toolCallId: "wait",
980
+ status: "completed",
981
+ },
982
+ ] satisfies Array<EffectAcpSchema.SessionUpdate>;
983
+ for (const update of updates)
984
+ yield* handler!({ sessionId: "mock-session-1", update });
985
+ return { stopReason: "end_turn" as const };
986
+ }),
987
+ }),
988
+ }),
989
+ },
990
+ });
991
+ const threadId = ThreadId.make("thread-acp-named-stream-wait");
992
+ const modelSelection = { instanceId, model: "default" };
993
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
994
+ runtimeMode: "full-access",
995
+ interactionMode: "default",
996
+ cwd: process.cwd(),
997
+ });
998
+ const runtime = yield* adapter.openSession({
999
+ threadId,
1000
+ providerSessionId: ProviderSessionId.make("session-acp-named-stream-wait"),
1001
+ modelSelection,
1002
+ runtimePolicy,
1003
+ });
1004
+ const providerThread = yield* runtime.ensureThread({
1005
+ threadId,
1006
+ modelSelection,
1007
+ runtimePolicy,
1008
+ });
1009
+ const input = makeTurnInput({
1010
+ threadId,
1011
+ providerThread,
1012
+ instanceId,
1013
+ runtimePolicy,
1014
+ now: yield* DateTime.now,
1015
+ });
1016
+ yield* runtime.startTurn(input);
1017
+ const events = yield* runtime.events.pipe(
1018
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
1019
+ Stream.runCollect,
1020
+ );
1021
+ const retained = new Map<string, OrchestrationV2TurnItem>();
1022
+ const states: Array<boolean> = [];
1023
+ for (const event of events) {
1024
+ if (event.type !== "turn_item.updated") continue;
1025
+ const item = event.turnItem;
1026
+ retained.set(item.id, item);
1027
+ if (item.type !== "dynamic_tool" && item.type !== "command_execution") continue;
1028
+ const streams = [...retained.values()].filter(
1029
+ (entry) => entry.type === "assistant_message" || entry.type === "reasoning",
1030
+ );
1031
+ assert.deepEqual(
1032
+ streams.map((entry) => [entry.type, entry.status]),
1033
+ [
1034
+ [
1035
+ sessionUpdate === "agent_message_chunk" ? "assistant_message" : "reasoning",
1036
+ "running",
1037
+ ],
1038
+ ],
1039
+ );
1040
+ states.push(
1041
+ deriveBlockedOnThreadWait({
1042
+ activeRun: { id: input.runId, status: "running" },
1043
+ turnItems: [...retained.values()],
1044
+ }),
1045
+ );
1046
+ }
1047
+ assert.deepEqual(states, [true, false, true, false]);
1048
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
1049
+ );
1050
+
1051
it.effect("starts a new replay message after ACP v2 plan boundaries", () =>
1052
Effect.gen(function* () {
1053
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+44
@@ -3333,6 +3333,50 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3333
}).pipe(Effect.scoped),
3334
);
3335
3336
+ it.effect("keeps thread-scoped T3 waits as dynamic tools through their lifecycle", () =>
3337
+ Effect.gen(function* () {
3338
+ const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-wait" };
3339
+ const name = "t3-code-web_delegate_task";
3340
+ const input = { task: "Review", mode: "wait" };
3341
+ const { runtime, thread } = yield* resumed([
3342
+ out("session.prompt", { sessionID: SESSION, text: "<any>" }),
3343
+ promptAccepted,
3344
+ event("session.tool.input.started", { ...tool, name }),
3345
+ event("session.tool.called", { ...tool, name, input, executed: true }),
3346
+ event("session.tool.success", {
3347
+ ...tool,
3348
+ content: [{ type: "text", text: "Reviewed" }],
3349
+ metadata: {},
3350
+ executed: true,
3351
+ }),
3352
+ event("session.execution.succeeded", { sessionID: SESSION }),
3353
+ ]);
3354
+ const events = yield* runtime.events.pipe(
3355
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
3356
+ Stream.runCollect,
3357
+ Effect.forkScoped,
3358
+ );
3359
+ yield* runtime.startTurn(turnInput(thread));
3360
+ const items = (yield* Fiber.join(events)).flatMap((event) =>
3361
+ event.type === "turn_item.updated" &&
3362
+ event.turnItem.nativeItemRef?.nativeId?.endsWith(tool.id)
3363
+ ? [event.turnItem]
3364
+ : [],
3365
+ );
3366
+ assert.deepEqual(
3367
+ items.map((item) => item.type),
3368
+ ["dynamic_tool", "dynamic_tool", "dynamic_tool"],
3369
+ );
3370
+ assert.deepEqual(
3371
+ items.map((item) => item.status),
3372
+ ["running", "running", "completed"],
3373
+ );
3374
+ const last = items.at(-1);
3375
+ assert.equal(last?.type === "dynamic_tool" ? last.toolName : null, name);
3376
+ assert.deepEqual(last?.type === "dynamic_tool" ? last.input : null, input);
3377
+ }).pipe(Effect.scoped),
3378
+ );
3379
+
3380
it.effect(
3381
"registers T3's MCP server for the thread alone and removes it when the thread unloads",
3382
() =>
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+189
@@ -9,6 +9,7 @@ import {
9
MessageId,
10
type ModelSelection,
11
type OrchestrationV2ProviderThread,
12
+ type OrchestrationV2TurnItem,
13
type OrchestrationV2ThreadShellSnapshot,
14
NodeId,
15
PlanId,
@@ -185,6 +186,194 @@ const addRolledBackRecoveryCandidate = Effect.fn("addRolledBackRecoveryCandidate
186
return threadId;
187
});
188
189
+it.effect.each([
190
+ ["memory", ProjectionStore.layerMemory],
191
+ ["SQL", layerTest],
192
+] as const)("%s shells flag only an active turn blocked solely on T3 thread waits", ([, layer]) =>
193
+ Effect.gen(function* () {
194
+ const store = yield* ProjectionStore.ProjectionStoreV2;
195
+ const threadId = yield* addRolledBackRecoveryCandidate("thread-wait");
196
+ const initial = yield* store.getThreadProjection(threadId);
197
+ const at = initial.updatedAt;
198
+ const previousCommand = initial.turnItems.find((item) => item.type === "command_execution")!;
199
+ const itemBase = {
200
+ ...previousCommand,
201
+ providerThreadId: previousCommand.providerThreadId ?? null,
202
+ providerTurnId: previousCommand.providerTurnId ?? null,
203
+ nativeItemRef: previousCommand.nativeItemRef ?? null,
204
+ parentItemId: previousCommand.parentItemId ?? null,
205
+ };
206
+ yield* store.apply({
207
+ id: EventId.make("event:thread-wait:previous-completed"),
208
+ type: "run.updated",
209
+ threadId,
210
+ occurredAt: at,
211
+ payload: { ...initial.runs[0]!, status: "completed", completedAt: at },
212
+ });
213
+ const run = {
214
+ ...initial.runs[0]!,
215
+ id: RunId.make("run:thread-wait:active"),
216
+ ordinal: 2,
217
+ status: "running" as const,
218
+ completedAt: null,
219
+ };
220
+ yield* store.apply({
221
+ id: EventId.make("event:thread-wait:active"),
222
+ type: "run.created",
223
+ threadId,
224
+ occurredAt: at,
225
+ payload: run,
226
+ });
227
+ let sequence = 0;
228
+ const updateItem = (payload: OrchestrationV2TurnItem) =>
229
+ store.apply({
230
+ id: EventId.make(`event:thread-wait:item:${sequence++}`),
231
+ type: "turn-item.updated",
232
+ threadId,
233
+ runId: payload.runId ?? undefined,
234
+ driver,
235
+ occurredAt: at,
236
+ payload,
237
+ });
238
+ const assertBlocked = Effect.fnUntraced(function* (expected: boolean) {
239
+ const listed = (yield* store.getShellSnapshot()).threads.find((row) => row.id === threadId);
240
+ for (const shell of [yield* store.getThreadShell(threadId), listed]) {
241
+ assert.equal(shell?.activeRunId, run.id);
242
+ assert.equal(shell?.status, "running");
243
+ assert.equal(shell?.blockedOnThreadWait ?? false, expected);
244
+ }
245
+ });
246
+ const wait = {
247
+ ...itemBase,
248
+ id: TurnItemId.make("item:thread-wait:active"),
249
+ runId: run.id,
250
+ type: "dynamic_tool" as const,
251
+ toolName: "mcp__t3_code__t3_thread_wait",
252
+ input: { threadId: "child-thread" },
253
+ status: "running" as const,
254
+ };
255
+
256
+ yield* updateItem({
257
+ ...wait,
258
+ id: TurnItemId.make("item:thread-wait:stale"),
259
+ runId: initial.runs[0]!.id,
260
+ });
261
+ yield* assertBlocked(false);
262
+ const foreign = {
263
+ ...wait,
264
+ id: TurnItemId.make("item:thread-wait:foreign"),
265
+ toolName: "weather.t3_thread_wait",
266
+ };
267
+ yield* updateItem(foreign);
268
+ yield* assertBlocked(false);
269
+ yield* updateItem({ ...foreign, status: "completed", completedAt: at });
270
+ yield* updateItem({ ...wait, status: "pending", startedAt: null });
271
+ yield* assertBlocked(false);
272
+ yield* updateItem(wait);
273
+ yield* assertBlocked(true);
274
+
275
+ yield* updateItem({
276
+ ...wait,
277
+ id: TurnItemId.make("item:thread-wait:plan"),
278
+ type: "todo_list",
279
+ planId: PlanId.make("plan:thread-wait"),
280
+ steps: [{ id: "review", text: "Review the child result", status: "running" }],
281
+ });
282
+ yield* assertBlocked(true);
283
+ yield* updateItem({
284
+ ...wait,
285
+ id: TurnItemId.make("item:thread-wait:proposed-plan"),
286
+ type: "proposed_plan",
287
+ planId: PlanId.make("plan:thread-wait:proposed"),
288
+ markdown: "Review the child result",
289
+ streaming: true,
290
+ });
291
+ yield* updateItem({
292
+ ...wait,
293
+ id: TurnItemId.make("item:thread-wait:named-message"),
294
+ nativeItemRef: { driver, nativeId: "named-message", strength: "weak" },
295
+ type: "assistant_message",
296
+ messageId: MessageId.make("message:thread-wait:named"),
297
+ text: "Waiting for the child result",
298
+ streaming: true,
299
+ });
300
+ yield* updateItem({
301
+ ...wait,
302
+ id: TurnItemId.make("item:thread-wait:named-thought"),
303
+ nativeItemRef: { driver, nativeId: "named-thought", strength: "weak" },
304
+ type: "reasoning",
305
+ text: "I need the child result",
306
+ streaming: true,
307
+ });
308
+ yield* assertBlocked(true);
309
+
310
+ const command = {
311
+ ...itemBase,
312
+ id: TurnItemId.make("item:thread-wait:concurrent"),
313
+ runId: run.id,
314
+ };
315
+ yield* updateItem(command);
316
+ yield* assertBlocked(false);
317
+ yield* updateItem({ ...wait, status: "waiting" });
318
+ yield* assertBlocked(false);
319
+ yield* updateItem({ ...command, status: "completed", completedAt: at });
320
+ yield* assertBlocked(true);
321
+ const fileChange = {
322
+ ...command,
323
+ id: TurnItemId.make("item:thread-wait:concurrent-edit"),
324
+ type: "file_change" as const,
325
+ fileName: "example.ts",
326
+ };
327
+ yield* updateItem(fileChange);
328
+ yield* assertBlocked(false);
329
+ yield* updateItem({ ...fileChange, status: "completed", completedAt: at });
330
+ yield* assertBlocked(true);
331
+ const compaction = {
332
+ ...command,
333
+ id: TurnItemId.make("item:thread-wait:compaction"),
334
+ type: "compaction" as const,
335
+ driver,
336
+ };
337
+ yield* updateItem(compaction);
338
+ yield* assertBlocked(false);
339
+ yield* updateItem({ ...compaction, status: "completed", completedAt: at });
340
+ yield* assertBlocked(true);
341
+ yield* updateItem({ ...wait, status: "completed", completedAt: at });
342
+ yield* assertBlocked(false);
343
+
344
+ const delegation = {
345
+ ...wait,
346
+ id: TurnItemId.make("item:thread-wait:delegation"),
347
+ toolName: "t3-code-thread_opencode2-adapter_delegate_task",
348
+ input: { task: "Review", mode: "async" },
349
+ };
350
+ yield* updateItem(delegation);
351
+ yield* assertBlocked(false);
352
+ yield* updateItem({ ...delegation, status: "completed", completedAt: at });
353
+ const blockingDelegation = {
354
+ ...delegation,
355
+ id: TurnItemId.make("item:thread-wait:blocking-delegation"),
356
+ input: { task: "Review", mode: "wait" },
357
+ };
358
+ yield* updateItem({
359
+ ...command,
360
+ id: TurnItemId.make("item:thread-wait:child"),
361
+ type: "subagent",
362
+ subagentId: NodeId.make("node:thread-wait:child"),
363
+ origin: "app_owned",
364
+ driver,
365
+ providerInstanceId,
366
+ childThreadId: ThreadId.make("child-thread"),
367
+ prompt: "Review",
368
+ result: null,
369
+ });
370
+ yield* updateItem(blockingDelegation);
371
+ yield* assertBlocked(true);
372
+ yield* updateItem({ ...blockingDelegation, status: "completed", completedAt: at });
373
+ yield* assertBlocked(false);
374
+ }).pipe(Effect.provide(layer)),
375
+);
376
+
377
it.effect.each([
378
["memory", ProjectionStore.layerMemory],
379
["SQL", layerTest],
apps/server/src/orchestration-v2/ProjectionStore.ts
+71
-39
@@ -72,7 +72,10 @@ import {
72
createOrchestrationV2TurnItemVisibility,
73
isOrchestrationV2SupersededInterrupt,
74
} from "@t3tools/shared/orchestrationV2Timeline";
75
-import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
75
+import {
76
+ deriveBlockedOnThreadWait,
77
+ derivePendingBackgroundWork,
78
+} from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
79
import * as Context from "effect/Context";
80
import * as DateTime from "effect/DateTime";
81
import * as Effect from "effect/Effect";
@@ -1056,6 +1059,7 @@ type ShellThreadRow = {
1059
readonly latest_run_started_at: string | null;
1060
readonly latest_run_completed_at: string | null;
1061
readonly active_run_id: string | null;
1062
+ readonly active_run_status: string | null;
1063
readonly activity_run_status: string | null;
1064
readonly activity_run_started_at: string | null;
1065
readonly last_error: string | null;
@@ -1595,6 +1599,7 @@ export function threadShellFromProjection(
1599
latestRunStartedAt: latestRun?.startedAt ?? null,
1600
latestRunCompletedAt: latestRun?.completedAt ?? null,
1601
activeRunId: activeRun?.id ?? null,
1602
+ blockedOnThreadWait: deriveBlockedOnThreadWait({ activeRun, turnItems: projection.turnItems }),
1603
activityRunStatus: activityRun?.status ?? null,
1604
activityRunStartedAt:
1605
activityRun === null ? null : orchestrationV2RunWorkStartedAt(activityRun),
@@ -1693,6 +1698,7 @@ type ShellThreadState = {
1698
readonly latestRunStartedAt: DateTime.Utc | null;
1699
readonly latestRunCompletedAt: DateTime.Utc | null;
1700
readonly activeRunId: RunId | null;
1701
+ readonly blockedOnThreadWait: boolean;
1702
readonly activityRunStatus: ShellActivityRunStatus | null;
1703
readonly activityRunStartedAt: DateTime.Utc | null;
1704
readonly lastError: string | null;
@@ -1845,6 +1851,7 @@ function shellFromState(input: {
1851
latestRunStartedAt: input.state.latestRunStartedAt,
1852
latestRunCompletedAt: input.state.latestRunCompletedAt,
1853
activeRunId: input.state.activeRunId,
1854
+ blockedOnThreadWait: input.state.blockedOnThreadWait,
1855
activityRunStatus: input.state.activityRunStatus,
1856
activityRunStartedAt: input.state.activityRunStartedAt,
1857
status: input.state.latestRunStatus,
@@ -5565,14 +5572,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5572
presented.requested_at AS latest_run_requested_at,
5573
json_extract(presented.payload_json, '$.startedAt') AS latest_run_started_at,
5574
presented.completed_at AS latest_run_completed_at,
5568
- (
5569
- SELECT r.run_id
5570
- FROM orchestration_v2_projection_runs r
5571
- WHERE r.thread_id = t.thread_id
5572
- AND r.status IN ('preparing', 'starting', 'running')
5573
- ORDER BY r.ordinal DESC, r.run_id DESC
5574
- LIMIT 1
5575
- ) AS active_run_id,
5575
+ active.run_id AS active_run_id,
5576
+ active.status AS active_run_status,
5577
(
5578
SELECT r.status
5579
FROM orchestration_v2_projection_runs r
@@ -5697,6 +5698,14 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5698
AND i.run_id IS NULL
5699
) AS runless_item_count
5700
FROM orchestration_v2_projection_threads t
5701
+ LEFT JOIN orchestration_v2_projection_runs active ON active.run_id = (
5702
+ SELECT r.run_id
5703
+ FROM orchestration_v2_projection_runs r
5704
+ WHERE r.thread_id = t.thread_id
5705
+ AND r.status IN ('preparing', 'starting', 'running')
5706
+ ORDER BY r.ordinal DESC, r.run_id DESC
5707
+ LIMIT 1
5708
+ )
5709
-- The newest run not waiting in a held queue, matching latestUnheldRun.
5710
LEFT JOIN orchestration_v2_projection_runs presented ON presented.run_id = (
5711
SELECT candidate.run_id
@@ -5780,34 +5789,34 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5789
WHERE thread_id IN ${sql.in(threadIds)}
5790
`;
5791
5783
- const selectShellPendingTurnItemRows = (threadIds?: ReadonlyArray<ThreadId>) =>
5784
- threadIds === undefined
5785
- ? sql<ShellPendingTurnItemRow>`
5786
- SELECT i.thread_id, i.payload_json, p.provider_instance_id AS owning_provider_instance_id
5787
- FROM orchestration_v2_projection_turn_items i
5788
- LEFT JOIN orchestration_v2_projection_provider_threads p
5789
- ON p.provider_thread_id = i.provider_thread_id
5790
- LEFT JOIN orchestration_v2_projection_runs r
5791
- ON r.run_id = i.run_id
5792
- WHERE i.type IN ('command_execution', 'dynamic_tool', 'subagent')
5793
- AND i.status NOT IN ('completed', 'interrupted', 'failed', 'cancelled')
5794
- -- A rolled-back run's items are abandoned, not pending. Without
5795
- -- this the shell reports Waiting for work no one will finish,
5796
- -- matching the item_count query's exclusion above.
5797
- AND (i.run_id IS NULL OR r.status <> 'rolled_back')
5798
- `
5799
- : sql<ShellPendingTurnItemRow>`
5800
- SELECT i.thread_id, i.payload_json, p.provider_instance_id AS owning_provider_instance_id
5801
- FROM orchestration_v2_projection_turn_items i
5802
- LEFT JOIN orchestration_v2_projection_provider_threads p
5803
- ON p.provider_thread_id = i.provider_thread_id
5804
- LEFT JOIN orchestration_v2_projection_runs r
5805
- ON r.run_id = i.run_id
5806
- WHERE i.type IN ('command_execution', 'dynamic_tool', 'subagent')
5807
- AND i.status NOT IN ('completed', 'interrupted', 'failed', 'cancelled')
5808
- AND (i.run_id IS NULL OR r.status <> 'rolled_back')
5809
- AND i.thread_id IN ${sql.in(threadIds)}
5810
- `;
5792
+ const selectShellPendingTurnItemRows = (
5793
+ threadIds?: ReadonlyArray<ThreadId>,
5794
+ activeRunIds: ReadonlyArray<string> = [],
5795
+ ) => sql<ShellPendingTurnItemRow>`
5796
+ SELECT i.thread_id, i.payload_json, p.provider_instance_id AS owning_provider_instance_id
5797
+ FROM orchestration_v2_projection_turn_items i
5798
+ LEFT JOIN orchestration_v2_projection_provider_threads p
5799
+ ON p.provider_thread_id = i.provider_thread_id
5800
+ LEFT JOIN orchestration_v2_projection_runs r
5801
+ ON r.run_id = i.run_id
5802
+ WHERE i.type IN ('command_execution', 'dynamic_tool', 'subagent')
5803
+ AND i.status NOT IN ('completed', 'interrupted', 'failed', 'cancelled')
5804
+ AND (i.run_id IS NULL OR r.status <> 'rolled_back')
5805
+ ${threadIds === undefined ? sql`` : sql`AND i.thread_id IN ${sql.in(threadIds)}`}
5806
+ ${
5807
+ activeRunIds.length === 0
5808
+ ? sql``
5809
+ : sql`
5810
+ -- Preserve the pending-item partial index; read other work only from running runs.
5811
+ UNION ALL
5812
+ SELECT i.thread_id, i.payload_json, NULL AS owning_provider_instance_id
5813
+ FROM orchestration_v2_projection_turn_items i
5814
+ WHERE i.run_id IN ${sql.in(activeRunIds)}
5815
+ AND i.type IN ('file_change', 'file_search', 'web_search', 'compaction')
5816
+ AND i.status IN ('running', 'waiting')
5817
+ `
5818
+ }
5819
+ `;
5820
5821
const runMapsByThreadId = (input: {
5822
readonly runRows: ReadonlyArray<ShellRunRow>;
@@ -6137,6 +6146,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6146
latestRunStartedAt,
6147
latestRunCompletedAt,
6148
activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id),
6149
+ blockedOnThreadWait: deriveBlockedOnThreadWait({
6150
+ activeRun:
6151
+ row.active_run_id === null || row.active_run_status !== "running"
6152
+ ? null
6153
+ : { id: RunId.make(row.active_run_id), status: "running" },
6154
+ turnItems: pendingTurnItemsByThreadId.get(thread.id) ?? [],
6155
+ }),
6156
activityRunStartedAt:
6157
row.activity_run_started_at === null
6158
? null
@@ -6223,7 +6239,16 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6239
AND aggregate_kind = 'thread'
6240
`,
6241
readForThreadIds(selectShellProviderThreadRows),
6226
- readForThreadIds(selectShellPendingTurnItemRows),
6242
+ readForThreadIds((ids) =>
6243
+ selectShellPendingTurnItemRows(
6244
+ ids,
6245
+ threadRows.flatMap((row) =>
6246
+ row.active_run_id !== null && row.active_run_status === "running"
6247
+ ? [row.active_run_id]
6248
+ : [],
6249
+ ),
6250
+ ),
6251
+ ),
6252
]);
6253
return {
6254
targetThreadIds,
@@ -6329,7 +6354,14 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6354
? Effect.succeed([] as ReadonlyArray<ShellRunItemCountRow>)
6355
: selectShellRunItemCounts(forkSourceIds),
6356
selectShellProviderThreadRows(threadIds),
6332
- selectShellPendingTurnItemRows(threadIds),
6357
+ selectShellPendingTurnItemRows(
6358
+ threadIds,
6359
+ [...rowsByThreadId.values()].flatMap((row) =>
6360
+ row.active_run_id !== null && row.active_run_status === "running"
6361
+ ? [row.active_run_id]
6362
+ : [],
6363
+ ),
6364
+ ),
6365
]);
6366
const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
6367
runRows,
packages/contracts/src/orchestrationV2.ts
+1
@@ -1826,6 +1826,7 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
1826
activityRunStatus: Schema.optional(
1827
Schema.NullOr(Schema.Literals(["preparing", "starting", "running", "waiting"])),
1828
),
1829
+ blockedOnThreadWait: Schema.optional(Schema.Boolean),
1830
status: OrchestrationV2ShellThreadStatus,
1831
lastError: Schema.optional(Schema.NullOr(Schema.String)),
1832
lastErrorClass: Schema.optional(Schema.NullOr(OrchestrationV2ProviderFailureClass)),
packages/provider-cursor/src/server/adapter.test.ts
+1
-5
@@ -830,11 +830,7 @@ describe("CursorAdapterV2", () => {
830
name: "weather",
831
kind: "integration",
832
});
833
- assert.deepEqual(item.input, {
834
- providerIdentifier: "weather",
835
- toolName: "get_weather",
836
- args: { city: "Berlin" },
837
- });
833
+ assert.deepEqual(item.input, { city: "Berlin" });
834
}
835
const fileSearchItems = events.flatMap((event) =>
836
event.type === "turn_item.updated" &&
packages/provider-cursor/src/server/adapter.ts
+1
-1
@@ -1321,7 +1321,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
1321
})
1322
: {}),
1323
toolName: cursorToolName(toolCall),
1324
- input: toolCall.args,
1324
+ input: toolCall.type === "mcp" ? (toolCall.args.args ?? {}) : toolCall.args,
1325
...(cursorToolOutput(toolCall) === undefined
1326
? {}
1327
: { output: cursorToolOutput(toolCall) }),
packages/provider-opencode/src/server/toolItems.ts
+2
@@ -1,4 +1,5 @@
1
import type { OrchestrationV2TurnItem } from "@t3tools/contracts";
2
+import { resolveT3McpToolId } from "@t3tools/shared/t3McpToolPresentation";
3
import { formatReadToolLabel, formatSearchToolLabel } from "@t3tools/shared/toolActivity";
4
5
// Search results stay on the timeline wire, so keep their text a preview.
@@ -12,6 +13,7 @@ type ToolItemBase = Omit<
13
export function openCodeToolProjectionKind(
14
toolName: string,
15
): "command_execution" | "file_change" | "file_search" | "web_search" | "dynamic_tool" {
16
+ if (resolveT3McpToolId(toolName) !== null) return "dynamic_tool";
17
const normalized = toolName.toLowerCase();
18
if (normalized === "todowrite") {
19
return "dynamic_tool";
packages/shared/src/orchestrationV2PendingBackgroundWork.ts
+44
@@ -7,7 +7,9 @@ import type {
7
ThreadPullRequestLink,
8
} from "@t3tools/contracts";
9
import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
10
+import * as Predicate from "effect/Predicate";
11
12
+import { resolveT3McpToolId } from "./t3McpToolPresentation.ts";
13
import { threadPullRequestKeyOf } from "./threadPullRequests.ts";
14
15
const BACKGROUND_TURN_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
@@ -16,6 +18,15 @@ const BACKGROUND_TURN_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
18
"subagent",
19
]);
20
21
+// Plans and text streams can stay open across tool calls without executing work.
22
+const EXECUTION_TURN_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
23
+ ...BACKGROUND_TURN_ITEM_TYPES,
24
+ "file_change",
25
+ "file_search",
26
+ "web_search",
27
+ "compaction",
28
+]);
29
+
30
const TERMINAL_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
31
"cancelled",
32
"completed",
@@ -48,6 +59,39 @@ export function turnItemUpdateCanEndBackgroundWork(
59
return BACKGROUND_TURN_ITEM_TYPES.has(item.type) && !isOrchestrationV2WorkActive(item.status);
60
}
61
62
+export function deriveBlockedOnThreadWait(input: {
63
+ readonly activeRun: Pick<OrchestrationV2Run, "id" | "status"> | null;
64
+ readonly turnItems: ReadonlyArray<OrchestrationV2TurnItem>;
65
+}): boolean {
66
+ if (input.activeRun?.status !== "running") return false;
67
+ let hasWait = false;
68
+ for (const item of input.turnItems) {
69
+ if (
70
+ item.runId !== input.activeRun.id ||
71
+ !EXECUTION_TURN_ITEM_TYPES.has(item.type) ||
72
+ (item.status !== "running" && item.status !== "waiting") ||
73
+ // App-owned rows track the child, including the child a blocking delegate is waiting for.
74
+ (item.type === "subagent" && item.origin === "app_owned")
75
+ ) {
76
+ continue;
77
+ }
78
+ if (item.type !== "dynamic_tool") return false;
79
+ const tool = resolveT3McpToolId(item.toolName);
80
+ if (
81
+ tool !== "t3_thread_wait" &&
82
+ !(
83
+ tool === "delegate_task" &&
84
+ Predicate.isObject(item.input) &&
85
+ Reflect.get(item.input, "mode") === "wait"
86
+ )
87
+ ) {
88
+ return false;
89
+ }
90
+ hasWait = true;
91
+ }
92
+ return hasWait;
93
+}
94
+
95
export function backgroundWorkHoldsCompletion(
96
tasks: ReadonlyArray<Pick<PendingBackgroundWorkTask, "kind">>,
97
): boolean {