Skip to content
TypeScript

fix(server): expose turns blocked only on T3 thread waits (#21499)

Julius Marmingefb1486901f7d
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
index 92bb99e4de1..cbc0ee419ea 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
@@ -22,10 +22,12 @@ import {
ProviderThreadId,
ThreadId,
type OrchestrationV2ProviderThread,
+ type OrchestrationV2TurnItem,
type ProviderOptionDescriptor,
} from "@t3tools/contracts";
import { GrokSettings } from "@t3tools/provider-grok/settings";
import * as HostProcess from "@t3tools/shared/HostProcess";
+import { deriveBlockedOnThreadWait } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
@@ -913,6 +915,139 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
+ it.effect.each(["agent_message_chunk", "agent_thought_chunk"] as const)(
+ "keeps named ACP %s open while deriving thread wait execution state",
+ (sessionUpdate) =>
+ Effect.gen(function* () {
+ type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
+ let handler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
+ const instanceId = ProviderInstanceId.make("acp-named-stream-wait");
+ const path = yield* Path.Path;
+ const adapter = yield* makeAcpAdapterV2({
+ instanceId,
+ selfInvocation: yield* resolveSelfInvocation(),
+ flavor: {
+ driver: ACP_TEST_DRIVER,
+ capabilities: AcpProviderCapabilitiesV2,
+ makeRuntime: makeMockRuntime({
+ childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner,
+ mockAgentPath: yield* path.fromFileUrl(
+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
+ ),
+ wrapRuntime: (runtime) => ({
+ ...runtime,
+ handleSessionUpdate: (next) =>
+ Effect.sync(() => {
+ handler = next;
+ }).pipe(Effect.andThen(runtime.handleSessionUpdate(next))),
+ prompt: () =>
+ Effect.gen(function* () {
+ assert.isDefined(handler);
+ const updates = [
+ {
+ sessionUpdate,
+ messageId: "named-stream",
+ content: { type: "text", text: "Waiting for the child result" },
+ },
+ {
+ sessionUpdate: "tool_call",
+ toolCallId: "wait",
+ title: "Wait for the child",
+ status: "in_progress",
+ rawInput: {
+ server: "t3-code",
+ tool: "t3_thread_wait",
+ arguments: { threadId: "child" },
+ },
+ _meta: { is_mcp_tool_call: true },
+ },
+ {
+ sessionUpdate: "tool_call",
+ toolCallId: "command",
+ kind: "execute",
+ title: "Run command",
+ status: "in_progress",
+ rawInput: { command: "pwd" },
+ },
+ {
+ sessionUpdate: "tool_call_update",
+ toolCallId: "command",
+ status: "completed",
+ },
+ {
+ sessionUpdate: "tool_call_update",
+ toolCallId: "wait",
+ status: "completed",
+ },
+ ] satisfies Array<EffectAcpSchema.SessionUpdate>;
+ for (const update of updates)
+ yield* handler!({ sessionId: "mock-session-1", update });
+ return { stopReason: "end_turn" as const };
+ }),
+ }),
+ }),
+ },
+ });
+ const threadId = ThreadId.make("thread-acp-named-stream-wait");
+ const modelSelection = { instanceId, model: "default" };
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ cwd: process.cwd(),
+ });
+ const runtime = yield* adapter.openSession({
+ threadId,
+ providerSessionId: ProviderSessionId.make("session-acp-named-stream-wait"),
+ modelSelection,
+ runtimePolicy,
+ });
+ const providerThread = yield* runtime.ensureThread({
+ threadId,
+ modelSelection,
+ runtimePolicy,
+ });
+ const input = makeTurnInput({
+ threadId,
+ providerThread,
+ instanceId,
+ runtimePolicy,
+ now: yield* DateTime.now,
+ });
+ yield* runtime.startTurn(input);
+ const events = yield* runtime.events.pipe(
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
+ Stream.runCollect,
+ );
+ const retained = new Map<string, OrchestrationV2TurnItem>();
+ const states: Array<boolean> = [];
+ for (const event of events) {
+ if (event.type !== "turn_item.updated") continue;
+ const item = event.turnItem;
+ retained.set(item.id, item);
+ if (item.type !== "dynamic_tool" && item.type !== "command_execution") continue;
+ const streams = [...retained.values()].filter(
+ (entry) => entry.type === "assistant_message" || entry.type === "reasoning",
+ );
+ assert.deepEqual(
+ streams.map((entry) => [entry.type, entry.status]),
+ [
+ [
+ sessionUpdate === "agent_message_chunk" ? "assistant_message" : "reasoning",
+ "running",
+ ],
+ ],
+ );
+ states.push(
+ deriveBlockedOnThreadWait({
+ activeRun: { id: input.runId, status: "running" },
+ turnItems: [...retained.values()],
+ }),
+ );
+ }
+ assert.deepEqual(states, [true, false, true, false]);
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
+ );
+
it.effect("starts a new replay message after ACP v2 plan boundaries", () =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
index 2c6c62446bc..a7212a95a57 100644
--- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
@@ -3333,6 +3333,50 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
+ it.effect("keeps thread-scoped T3 waits as dynamic tools through their lifecycle", () =>
+ Effect.gen(function* () {
+ const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-wait" };
+ const name = "t3-code-web_delegate_task";
+ const input = { task: "Review", mode: "wait" };
+ const { runtime, thread } = yield* resumed([
+ out("session.prompt", { sessionID: SESSION, text: "<any>" }),
+ promptAccepted,
+ event("session.tool.input.started", { ...tool, name }),
+ event("session.tool.called", { ...tool, name, input, executed: true }),
+ event("session.tool.success", {
+ ...tool,
+ content: [{ type: "text", text: "Reviewed" }],
+ metadata: {},
+ executed: true,
+ }),
+ event("session.execution.succeeded", { sessionID: SESSION }),
+ ]);
+ const events = yield* runtime.events.pipe(
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
+ Stream.runCollect,
+ Effect.forkScoped,
+ );
+ yield* runtime.startTurn(turnInput(thread));
+ const items = (yield* Fiber.join(events)).flatMap((event) =>
+ event.type === "turn_item.updated" &&
+ event.turnItem.nativeItemRef?.nativeId?.endsWith(tool.id)
+ ? [event.turnItem]
+ : [],
+ );
+ assert.deepEqual(
+ items.map((item) => item.type),
+ ["dynamic_tool", "dynamic_tool", "dynamic_tool"],
+ );
+ assert.deepEqual(
+ items.map((item) => item.status),
+ ["running", "running", "completed"],
+ );
+ const last = items.at(-1);
+ assert.equal(last?.type === "dynamic_tool" ? last.toolName : null, name);
+ assert.deepEqual(last?.type === "dynamic_tool" ? last.input : null, input);
+ }).pipe(Effect.scoped),
+ );
+
it.effect(
"registers T3's MCP server for the thread alone and removes it when the thread unloads",
() =>
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
index 35581cde540..32c83629c66 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
@@ -9,6 +9,7 @@ import {
MessageId,
type ModelSelection,
type OrchestrationV2ProviderThread,
+ type OrchestrationV2TurnItem,
type OrchestrationV2ThreadShellSnapshot,
NodeId,
PlanId,
@@ -185,6 +186,194 @@ const addRolledBackRecoveryCandidate = Effect.fn("addRolledBackRecoveryCandidate
return threadId;
});
+it.effect.each([
+ ["memory", ProjectionStore.layerMemory],
+ ["SQL", layerTest],
+] as const)("%s shells flag only an active turn blocked solely on T3 thread waits", ([, layer]) =>
+ Effect.gen(function* () {
+ const store = yield* ProjectionStore.ProjectionStoreV2;
+ const threadId = yield* addRolledBackRecoveryCandidate("thread-wait");
+ const initial = yield* store.getThreadProjection(threadId);
+ const at = initial.updatedAt;
+ const previousCommand = initial.turnItems.find((item) => item.type === "command_execution")!;
+ const itemBase = {
+ ...previousCommand,
+ providerThreadId: previousCommand.providerThreadId ?? null,
+ providerTurnId: previousCommand.providerTurnId ?? null,
+ nativeItemRef: previousCommand.nativeItemRef ?? null,
+ parentItemId: previousCommand.parentItemId ?? null,
+ };
+ yield* store.apply({
+ id: EventId.make("event:thread-wait:previous-completed"),
+ type: "run.updated",
+ threadId,
+ occurredAt: at,
+ payload: { ...initial.runs[0]!, status: "completed", completedAt: at },
+ });
+ const run = {
+ ...initial.runs[0]!,
+ id: RunId.make("run:thread-wait:active"),
+ ordinal: 2,
+ status: "running" as const,
+ completedAt: null,
+ };
+ yield* store.apply({
+ id: EventId.make("event:thread-wait:active"),
+ type: "run.created",
+ threadId,
+ occurredAt: at,
+ payload: run,
+ });
+ let sequence = 0;
+ const updateItem = (payload: OrchestrationV2TurnItem) =>
+ store.apply({
+ id: EventId.make(`event:thread-wait:item:${sequence++}`),
+ type: "turn-item.updated",
+ threadId,
+ runId: payload.runId ?? undefined,
+ driver,
+ occurredAt: at,
+ payload,
+ });
+ const assertBlocked = Effect.fnUntraced(function* (expected: boolean) {
+ const listed = (yield* store.getShellSnapshot()).threads.find((row) => row.id === threadId);
+ for (const shell of [yield* store.getThreadShell(threadId), listed]) {
+ assert.equal(shell?.activeRunId, run.id);
+ assert.equal(shell?.status, "running");
+ assert.equal(shell?.blockedOnThreadWait ?? false, expected);
+ }
+ });
+ const wait = {
+ ...itemBase,
+ id: TurnItemId.make("item:thread-wait:active"),
+ runId: run.id,
+ type: "dynamic_tool" as const,
+ toolName: "mcp__t3_code__t3_thread_wait",
+ input: { threadId: "child-thread" },
+ status: "running" as const,
+ };
+
+ yield* updateItem({
+ ...wait,
+ id: TurnItemId.make("item:thread-wait:stale"),
+ runId: initial.runs[0]!.id,
+ });
+ yield* assertBlocked(false);
+ const foreign = {
+ ...wait,
+ id: TurnItemId.make("item:thread-wait:foreign"),
+ toolName: "weather.t3_thread_wait",
+ };
+ yield* updateItem(foreign);
+ yield* assertBlocked(false);
+ yield* updateItem({ ...foreign, status: "completed", completedAt: at });
+ yield* updateItem({ ...wait, status: "pending", startedAt: null });
+ yield* assertBlocked(false);
+ yield* updateItem(wait);
+ yield* assertBlocked(true);
+
+ yield* updateItem({
+ ...wait,
+ id: TurnItemId.make("item:thread-wait:plan"),
+ type: "todo_list",
+ planId: PlanId.make("plan:thread-wait"),
+ steps: [{ id: "review", text: "Review the child result", status: "running" }],
+ });
+ yield* assertBlocked(true);
+ yield* updateItem({
+ ...wait,
+ id: TurnItemId.make("item:thread-wait:proposed-plan"),
+ type: "proposed_plan",
+ planId: PlanId.make("plan:thread-wait:proposed"),
+ markdown: "Review the child result",
+ streaming: true,
+ });
+ yield* updateItem({
+ ...wait,
+ id: TurnItemId.make("item:thread-wait:named-message"),
+ nativeItemRef: { driver, nativeId: "named-message", strength: "weak" },
+ type: "assistant_message",
+ messageId: MessageId.make("message:thread-wait:named"),
+ text: "Waiting for the child result",
+ streaming: true,
+ });
+ yield* updateItem({
+ ...wait,
+ id: TurnItemId.make("item:thread-wait:named-thought"),
+ nativeItemRef: { driver, nativeId: "named-thought", strength: "weak" },
+ type: "reasoning",
+ text: "I need the child result",
+ streaming: true,
+ });
+ yield* assertBlocked(true);
+
+ const command = {
+ ...itemBase,
+ id: TurnItemId.make("item:thread-wait:concurrent"),
+ runId: run.id,
+ };
+ yield* updateItem(command);
+ yield* assertBlocked(false);
+ yield* updateItem({ ...wait, status: "waiting" });
+ yield* assertBlocked(false);
+ yield* updateItem({ ...command, status: "completed", completedAt: at });
+ yield* assertBlocked(true);
+ const fileChange = {
+ ...command,
+ id: TurnItemId.make("item:thread-wait:concurrent-edit"),
+ type: "file_change" as const,
+ fileName: "example.ts",
+ };
+ yield* updateItem(fileChange);
+ yield* assertBlocked(false);
+ yield* updateItem({ ...fileChange, status: "completed", completedAt: at });
+ yield* assertBlocked(true);
+ const compaction = {
+ ...command,
+ id: TurnItemId.make("item:thread-wait:compaction"),
+ type: "compaction" as const,
+ driver,
+ };
+ yield* updateItem(compaction);
+ yield* assertBlocked(false);
+ yield* updateItem({ ...compaction, status: "completed", completedAt: at });
+ yield* assertBlocked(true);
+ yield* updateItem({ ...wait, status: "completed", completedAt: at });
+ yield* assertBlocked(false);
+
+ const delegation = {
+ ...wait,
+ id: TurnItemId.make("item:thread-wait:delegation"),
+ toolName: "t3-code-thread_opencode2-adapter_delegate_task",
+ input: { task: "Review", mode: "async" },
+ };
+ yield* updateItem(delegation);
+ yield* assertBlocked(false);
+ yield* updateItem({ ...delegation, status: "completed", completedAt: at });
+ const blockingDelegation = {
+ ...delegation,
+ id: TurnItemId.make("item:thread-wait:blocking-delegation"),
+ input: { task: "Review", mode: "wait" },
+ };
+ yield* updateItem({
+ ...command,
+ id: TurnItemId.make("item:thread-wait:child"),
+ type: "subagent",
+ subagentId: NodeId.make("node:thread-wait:child"),
+ origin: "app_owned",
+ driver,
+ providerInstanceId,
+ childThreadId: ThreadId.make("child-thread"),
+ prompt: "Review",
+ result: null,
+ });
+ yield* updateItem(blockingDelegation);
+ yield* assertBlocked(true);
+ yield* updateItem({ ...blockingDelegation, status: "completed", completedAt: at });
+ yield* assertBlocked(false);
+ }).pipe(Effect.provide(layer)),
+);
+
it.effect.each([
["memory", ProjectionStore.layerMemory],
["SQL", layerTest],
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index 8448ff8268e..b349ff667f5 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -72,7 +72,10 @@ import {
createOrchestrationV2TurnItemVisibility,
isOrchestrationV2SupersededInterrupt,
} from "@t3tools/shared/orchestrationV2Timeline";
-import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
+import {
+ deriveBlockedOnThreadWait,
+ derivePendingBackgroundWork,
+} from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -1056,6 +1059,7 @@ type ShellThreadRow = {
readonly latest_run_started_at: string | null;
readonly latest_run_completed_at: string | null;
readonly active_run_id: string | null;
+ readonly active_run_status: string | null;
readonly activity_run_status: string | null;
readonly activity_run_started_at: string | null;
readonly last_error: string | null;
@@ -1595,6 +1599,7 @@ export function threadShellFromProjection(
latestRunStartedAt: latestRun?.startedAt ?? null,
latestRunCompletedAt: latestRun?.completedAt ?? null,
activeRunId: activeRun?.id ?? null,
+ blockedOnThreadWait: deriveBlockedOnThreadWait({ activeRun, turnItems: projection.turnItems }),
activityRunStatus: activityRun?.status ?? null,
activityRunStartedAt:
activityRun === null ? null : orchestrationV2RunWorkStartedAt(activityRun),
@@ -1693,6 +1698,7 @@ type ShellThreadState = {
readonly latestRunStartedAt: DateTime.Utc | null;
readonly latestRunCompletedAt: DateTime.Utc | null;
readonly activeRunId: RunId | null;
+ readonly blockedOnThreadWait: boolean;
readonly activityRunStatus: ShellActivityRunStatus | null;
readonly activityRunStartedAt: DateTime.Utc | null;
readonly lastError: string | null;
@@ -1845,6 +1851,7 @@ function shellFromState(input: {
latestRunStartedAt: input.state.latestRunStartedAt,
latestRunCompletedAt: input.state.latestRunCompletedAt,
activeRunId: input.state.activeRunId,
+ blockedOnThreadWait: input.state.blockedOnThreadWait,
activityRunStatus: input.state.activityRunStatus,
activityRunStartedAt: input.state.activityRunStartedAt,
status: input.state.latestRunStatus,
@@ -5565,14 +5572,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
presented.requested_at AS latest_run_requested_at,
json_extract(presented.payload_json, '$.startedAt') AS latest_run_started_at,
presented.completed_at AS latest_run_completed_at,
- (
- SELECT r.run_id
- FROM orchestration_v2_projection_runs r
- WHERE r.thread_id = t.thread_id
- AND r.status IN ('preparing', 'starting', 'running')
- ORDER BY r.ordinal DESC, r.run_id DESC
- LIMIT 1
- ) AS active_run_id,
+ active.run_id AS active_run_id,
+ active.status AS active_run_status,
(
SELECT r.status
FROM orchestration_v2_projection_runs r
@@ -5697,6 +5698,14 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
AND i.run_id IS NULL
) AS runless_item_count
FROM orchestration_v2_projection_threads t
+ LEFT JOIN orchestration_v2_projection_runs active ON active.run_id = (
+ SELECT r.run_id
+ FROM orchestration_v2_projection_runs r
+ WHERE r.thread_id = t.thread_id
+ AND r.status IN ('preparing', 'starting', 'running')
+ ORDER BY r.ordinal DESC, r.run_id DESC
+ LIMIT 1
+ )
-- The newest run not waiting in a held queue, matching latestUnheldRun.
LEFT JOIN orchestration_v2_projection_runs presented ON presented.run_id = (
SELECT candidate.run_id
@@ -5780,34 +5789,34 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
WHERE thread_id IN ${sql.in(threadIds)}
`;
- const selectShellPendingTurnItemRows = (threadIds?: ReadonlyArray<ThreadId>) =>
- threadIds === undefined
- ? sql<ShellPendingTurnItemRow>`
- SELECT i.thread_id, i.payload_json, p.provider_instance_id AS owning_provider_instance_id
- FROM orchestration_v2_projection_turn_items i
- LEFT JOIN orchestration_v2_projection_provider_threads p
- ON p.provider_thread_id = i.provider_thread_id
- LEFT JOIN orchestration_v2_projection_runs r
- ON r.run_id = i.run_id
- WHERE i.type IN ('command_execution', 'dynamic_tool', 'subagent')
- AND i.status NOT IN ('completed', 'interrupted', 'failed', 'cancelled')
- -- A rolled-back run's items are abandoned, not pending. Without
- -- this the shell reports Waiting for work no one will finish,
- -- matching the item_count query's exclusion above.
- AND (i.run_id IS NULL OR r.status <> 'rolled_back')
- `
- : sql<ShellPendingTurnItemRow>`
- SELECT i.thread_id, i.payload_json, p.provider_instance_id AS owning_provider_instance_id
- FROM orchestration_v2_projection_turn_items i
- LEFT JOIN orchestration_v2_projection_provider_threads p
- ON p.provider_thread_id = i.provider_thread_id
- LEFT JOIN orchestration_v2_projection_runs r
- ON r.run_id = i.run_id
- WHERE i.type IN ('command_execution', 'dynamic_tool', 'subagent')
- AND i.status NOT IN ('completed', 'interrupted', 'failed', 'cancelled')
- AND (i.run_id IS NULL OR r.status <> 'rolled_back')
- AND i.thread_id IN ${sql.in(threadIds)}
- `;
+ const selectShellPendingTurnItemRows = (
+ threadIds?: ReadonlyArray<ThreadId>,
+ activeRunIds: ReadonlyArray<string> = [],
+ ) => sql<ShellPendingTurnItemRow>`
+ SELECT i.thread_id, i.payload_json, p.provider_instance_id AS owning_provider_instance_id
+ FROM orchestration_v2_projection_turn_items i
+ LEFT JOIN orchestration_v2_projection_provider_threads p
+ ON p.provider_thread_id = i.provider_thread_id
+ LEFT JOIN orchestration_v2_projection_runs r
+ ON r.run_id = i.run_id
+ WHERE i.type IN ('command_execution', 'dynamic_tool', 'subagent')
+ AND i.status NOT IN ('completed', 'interrupted', 'failed', 'cancelled')
+ AND (i.run_id IS NULL OR r.status <> 'rolled_back')
+ ${threadIds === undefined ? sql`` : sql`AND i.thread_id IN ${sql.in(threadIds)}`}
+ ${
+ activeRunIds.length === 0
+ ? sql``
+ : sql`
+ -- Preserve the pending-item partial index; read other work only from running runs.
+ UNION ALL
+ SELECT i.thread_id, i.payload_json, NULL AS owning_provider_instance_id
+ FROM orchestration_v2_projection_turn_items i
+ WHERE i.run_id IN ${sql.in(activeRunIds)}
+ AND i.type IN ('file_change', 'file_search', 'web_search', 'compaction')
+ AND i.status IN ('running', 'waiting')
+ `
+ }
+ `;
const runMapsByThreadId = (input: {
readonly runRows: ReadonlyArray<ShellRunRow>;
@@ -6137,6 +6146,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
latestRunStartedAt,
latestRunCompletedAt,
activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id),
+ blockedOnThreadWait: deriveBlockedOnThreadWait({
+ activeRun:
+ row.active_run_id === null || row.active_run_status !== "running"
+ ? null
+ : { id: RunId.make(row.active_run_id), status: "running" },
+ turnItems: pendingTurnItemsByThreadId.get(thread.id) ?? [],
+ }),
activityRunStartedAt:
row.activity_run_started_at === null
? null
@@ -6223,7 +6239,16 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
AND aggregate_kind = 'thread'
`,
readForThreadIds(selectShellProviderThreadRows),
- readForThreadIds(selectShellPendingTurnItemRows),
+ readForThreadIds((ids) =>
+ selectShellPendingTurnItemRows(
+ ids,
+ threadRows.flatMap((row) =>
+ row.active_run_id !== null && row.active_run_status === "running"
+ ? [row.active_run_id]
+ : [],
+ ),
+ ),
+ ),
]);
return {
targetThreadIds,
@@ -6329,7 +6354,14 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
? Effect.succeed([] as ReadonlyArray<ShellRunItemCountRow>)
: selectShellRunItemCounts(forkSourceIds),
selectShellProviderThreadRows(threadIds),
- selectShellPendingTurnItemRows(threadIds),
+ selectShellPendingTurnItemRows(
+ threadIds,
+ [...rowsByThreadId.values()].flatMap((row) =>
+ row.active_run_id !== null && row.active_run_status === "running"
+ ? [row.active_run_id]
+ : [],
+ ),
+ ),
]);
const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
runRows,
diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts
index 6a957dc2ba8..60c05ab7ede 100644
--- a/packages/contracts/src/orchestrationV2.ts
+++ b/packages/contracts/src/orchestrationV2.ts
@@ -1826,6 +1826,7 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
activityRunStatus: Schema.optional(
Schema.NullOr(Schema.Literals(["preparing", "starting", "running", "waiting"])),
),
+ blockedOnThreadWait: Schema.optional(Schema.Boolean),
status: OrchestrationV2ShellThreadStatus,
lastError: Schema.optional(Schema.NullOr(Schema.String)),
lastErrorClass: Schema.optional(Schema.NullOr(OrchestrationV2ProviderFailureClass)),
diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts
index be87e4a4819..8aecb9f92df 100644
--- a/packages/provider-cursor/src/server/adapter.test.ts
+++ b/packages/provider-cursor/src/server/adapter.test.ts
@@ -830,11 +830,7 @@ describe("CursorAdapterV2", () => {
name: "weather",
kind: "integration",
});
- assert.deepEqual(item.input, {
- providerIdentifier: "weather",
- toolName: "get_weather",
- args: { city: "Berlin" },
- });
+ assert.deepEqual(item.input, { city: "Berlin" });
}
const fileSearchItems = events.flatMap((event) =>
event.type === "turn_item.updated" &&
diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts
index b69ba4449b8..765ec16fdec 100644
--- a/packages/provider-cursor/src/server/adapter.ts
+++ b/packages/provider-cursor/src/server/adapter.ts
@@ -1321,7 +1321,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
})
: {}),
toolName: cursorToolName(toolCall),
- input: toolCall.args,
+ input: toolCall.type === "mcp" ? (toolCall.args.args ?? {}) : toolCall.args,
...(cursorToolOutput(toolCall) === undefined
? {}
: { output: cursorToolOutput(toolCall) }),
diff --git a/packages/provider-opencode/src/server/toolItems.ts b/packages/provider-opencode/src/server/toolItems.ts
index c222c223bf8..a0f7e2c6bfe 100644
--- a/packages/provider-opencode/src/server/toolItems.ts
+++ b/packages/provider-opencode/src/server/toolItems.ts
@@ -1,4 +1,5 @@
import type { OrchestrationV2TurnItem } from "@t3tools/contracts";
+import { resolveT3McpToolId } from "@t3tools/shared/t3McpToolPresentation";
import { formatReadToolLabel, formatSearchToolLabel } from "@t3tools/shared/toolActivity";
// Search results stay on the timeline wire, so keep their text a preview.
@@ -12,6 +13,7 @@ type ToolItemBase = Omit<
export function openCodeToolProjectionKind(
toolName: string,
): "command_execution" | "file_change" | "file_search" | "web_search" | "dynamic_tool" {
+ if (resolveT3McpToolId(toolName) !== null) return "dynamic_tool";
const normalized = toolName.toLowerCase();
if (normalized === "todowrite") {
return "dynamic_tool";
diff --git a/packages/shared/src/orchestrationV2PendingBackgroundWork.ts b/packages/shared/src/orchestrationV2PendingBackgroundWork.ts
index 15453ae0185..8073bcccd0b 100644
--- a/packages/shared/src/orchestrationV2PendingBackgroundWork.ts
+++ b/packages/shared/src/orchestrationV2PendingBackgroundWork.ts
@@ -7,7 +7,9 @@ import type {
ThreadPullRequestLink,
} from "@t3tools/contracts";
import { isOrchestrationV2WorkActive } from "@t3tools/contracts";
+import * as Predicate from "effect/Predicate";
+import { resolveT3McpToolId } from "./t3McpToolPresentation.ts";
import { threadPullRequestKeyOf } from "./threadPullRequests.ts";
const BACKGROUND_TURN_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
@@ -16,6 +18,15 @@ const BACKGROUND_TURN_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
"subagent",
]);
+// Plans and text streams can stay open across tool calls without executing work.
+const EXECUTION_TURN_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
+ ...BACKGROUND_TURN_ITEM_TYPES,
+ "file_change",
+ "file_search",
+ "web_search",
+ "compaction",
+]);
+
const TERMINAL_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
"cancelled",
"completed",
@@ -48,6 +59,39 @@ export function turnItemUpdateCanEndBackgroundWork(
return BACKGROUND_TURN_ITEM_TYPES.has(item.type) && !isOrchestrationV2WorkActive(item.status);
}
+export function deriveBlockedOnThreadWait(input: {
+ readonly activeRun: Pick<OrchestrationV2Run, "id" | "status"> | null;
+ readonly turnItems: ReadonlyArray<OrchestrationV2TurnItem>;
+}): boolean {
+ if (input.activeRun?.status !== "running") return false;
+ let hasWait = false;
+ for (const item of input.turnItems) {
+ if (
+ item.runId !== input.activeRun.id ||
+ !EXECUTION_TURN_ITEM_TYPES.has(item.type) ||
+ (item.status !== "running" && item.status !== "waiting") ||
+ // App-owned rows track the child, including the child a blocking delegate is waiting for.
+ (item.type === "subagent" && item.origin === "app_owned")
+ ) {
+ continue;
+ }
+ if (item.type !== "dynamic_tool") return false;
+ const tool = resolveT3McpToolId(item.toolName);
+ if (
+ tool !== "t3_thread_wait" &&
+ !(
+ tool === "delegate_task" &&
+ Predicate.isObject(item.input) &&
+ Reflect.get(item.input, "mode") === "wait"
+ )
+ ) {
+ return false;
+ }
+ hasWait = true;
+ }
+ return hasWait;
+}
+
export function backgroundWorkHoldsCompletion(
tasks: ReadonlyArray<Pick<PendingBackgroundWorkTask, "kind">>,
): boolean {