feat(orchestrator): Surface waiting background work (#4378)

This commit is contained in:
Mike Olson authored and Julius Marminge committed 2026-08-15 16:51:19 +02:00
1 parent b5cada5e89
commit 18a91d6822
65 files changed
+12414 -640

No files matched your search

@@ -60,6 +60,8 @@ const STATUS_LABEL_BY_STATUS: Partial<
approval: { label: "Approval", className: "text-amber-700 dark:text-amber-300" },
input: { label: "Input", className: "text-indigo-600 dark:text-indigo-300" },
working: { label: "Working", className: "text-sky-600 dark:text-sky-400" },
// Colorless like the web sidebar: parked on background work, not "act now".
waiting: { label: "Waiting", className: "text-foreground-tertiary" },
failed: { label: "Failed", className: "text-red-700 dark:text-red-300" },
};
@@ -127,6 +127,26 @@ describe("resolveThreadListV2Status", () => {
expect(resolveThreadListV2Status(thread)).toBe("approval");
});
it("reports waiting when presentation parks runtime idle for background tasks", () => {
expect(
resolveThreadListV2Status(
makeThread({
id: ThreadId.make("t"),
title: "t",
pendingBackgroundTasks: [{ taskId: "bg-1", description: "Run Codex review" }],
runtime: {
status: "idle",
activeRunId: null,
providerInstanceId: ProviderInstanceId.make("codex"),
providerName: "Codex",
lastError: null,
updatedAt: NOW,
},
}),
),
).toBe("waiting");
});
it("resolves ready for quiescent threads", () => {
expect(resolveThreadListV2Status(makeThread({ id: ThreadId.make("t"), title: "t" }))).toBe(
"ready",
@@ -20,11 +20,13 @@ export { snoozeWakeLabel };
* Thread List v2 model, ported from the web sidebar v2
* (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
*
* Four visual states, three colors: color is reserved for "act now"
* (approval), "in motion" (working), and "broken" (failed). Ready is the
* unlabeled resting state.
* Six visual states. Color distinguishes approval, input, active work, and
* failures. Ready is the unlabeled resting state; waiting (runtime status "idle") is the agent
* parked on open background tasks, grey like working rather than a false Done.
* The orchestrator v2 presentation bridge parks runtime at idle when the
* post-settlement background roster is nonempty.
*/
export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "ready";
export type ThreadListV2Status = "approval" | "input" | "working" | "waiting" | "failed" | "ready";
export type ThreadListV2SwipeAction = "archive" | "settle" | "unsettle" | "snooze" | "unsnooze";
export function resolveThreadListV2SnoozeMenuSelection(input: {
@@ -158,6 +160,9 @@ export function resolveThreadListV2Status(
) {
return "working";
}
if (thread.runtime?.status === "idle") {
return "waiting";
}
if (thread.runtime?.status === "failed") {
return "failed";
}
@@ -3,6 +3,7 @@ import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
import {
deriveThreadActivityRun,
deriveThreadRuntime,
threadRuntimeHasInterruptibleRun,
} from "@t3tools/client-runtime/state/thread-execution";
import { useCallback, useEffect, useMemo } from "react";
@@ -150,7 +151,9 @@ export function useThreadComposerState() {
}, [selectedThreadActivityRun, selectedThreadSessionActivity, selectedThreadShell]);
const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime);
const interruptibleRunId = selectedThreadRuntime?.activeRunId ?? null;
const interruptibleRunId = threadRuntimeHasInterruptibleRun(selectedThreadRuntime)
? (selectedThreadRuntime?.activeRunId ?? null)
: null;
const onSendMessage = useCallback(async () => {
if (!selectedThreadShell) {
@@ -0,0 +1,307 @@
import {
EnvironmentId,
NodeId,
type OrchestrationV2ThreadProjection,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
RunId,
ThreadId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { expect, it } from "vite-plus/test";
import { ProviderRegistry } from "../provider/Services/ProviderRegistry.ts";
import { ScheduledTaskService } from "../scheduledTasks/ScheduledTaskService.ts";
import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts";
import type * as McpInvocationContext from "./McpInvocationContext.ts";
import {
layer as orchestratorMcpServiceLayer,
OrchestratorMcpService,
} from "./OrchestratorMcpService.ts";
const environmentId = EnvironmentId.make("environment-mcp-orchestrator-detail");
const projectId = ProjectId.make("project-mcp-orchestrator-detail");
const parentThreadId = ThreadId.make("thread-mcp-orchestrator-parent");
const childThreadId = ThreadId.make("thread-mcp-orchestrator-child");
const activeRunId = RunId.make("run-mcp-active");
const cancelledRunId = RunId.make("run-mcp-cancelled");
const childRunId = RunId.make("run-mcp-child");
const taskId = NodeId.make("node-mcp-task-1");
const now = DateTime.makeUnsafe("2026-08-04T12:00:00.000Z");
const codexDriver = ProviderDriverKind.make("codex");
// Distinct from driver kind so a regression that re-derives from driver fails.
const customCodexInstanceId = ProviderInstanceId.make("codex-custom-workspace");
const parentInstanceId = ProviderInstanceId.make("codex");
const makeScope = (): McpInvocationContext.McpInvocationScope => ({
environmentId,
threadId: parentThreadId,
providerSessionId: "provider-session-mcp-orchestrator-detail",
providerInstanceId: parentInstanceId,
capabilities: new Set(["orchestration"]),
issuedAt: 1,
});
function baseThread(input: {
readonly threadId: ThreadId;
readonly title: string;
readonly instanceId: ProviderInstanceId;
readonly model: string;
}) {
return {
id: input.threadId,
projectId,
title: input.title,
createdBy: "user" as const,
creationSource: "mcp" as const,
modelSelection: {
instanceId: input.instanceId,
model: input.model,
},
runtimeMode: "full-access" as const,
interactionMode: "default" as const,
branch: null,
worktreePath: null,
lineage: {
parentThreadId: null,
relationshipToParent: null,
rootThreadId: input.threadId,
},
archivedAt: null,
deletedAt: null,
providerInstanceId: input.instanceId,
createdAt: now,
updatedAt: now,
};
}
function makeRun(input: {
readonly id: RunId;
readonly ordinal: number;
readonly status: "running" | "waiting" | "cancelled" | "queued" | "completed";
readonly instanceId?: ProviderInstanceId;
}) {
return {
id: input.id,
ordinal: input.ordinal,
status: input.status,
modelSelection: {
instanceId: input.instanceId ?? parentInstanceId,
model: "gpt-5.4",
},
providerInstanceId: input.instanceId ?? parentInstanceId,
requestedAt: now,
startedAt: input.status === "cancelled" || input.status === "queued" ? null : now,
completedAt: input.status === "cancelled" || input.status === "completed" ? now : null,
};
}
it("readThread prefers activity-run status over a newer cancelled queued run", async () => {
const projection = {
thread: baseThread({
threadId: parentThreadId,
title: "Parent",
instanceId: parentInstanceId,
model: "gpt-5.4",
}),
runs: [
makeRun({ id: activeRunId, ordinal: 1, status: "running" }),
makeRun({ id: cancelledRunId, ordinal: 2, status: "cancelled" }),
],
visibleTurnItems: [],
runtimeRequests: [],
messages: [],
contextTransfers: [],
subagents: [],
updatedAt: now,
} as unknown as OrchestrationV2ThreadProjection;
const layer = orchestratorMcpServiceLayer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.mock(ThreadManagementService)({
getThreadProjection: (threadId) =>
threadId === parentThreadId
? Effect.succeed(projection)
: Effect.die(`unexpected thread ${threadId}`),
} satisfies Partial<ThreadManagementService["Service"]>),
Layer.mock(ProviderRegistry)({
getProviders: Effect.succeed([]),
} satisfies Partial<ProviderRegistry["Service"]>),
Layer.mock(ScheduledTaskService)({
list: () => Effect.succeed({ tasks: [] }),
} satisfies Partial<ScheduledTaskService["Service"]>),
NodeCrypto.layer,
),
),
);
await Effect.gen(function* () {
const service = yield* OrchestratorMcpService;
const result = yield* service.readThread(makeScope(), { threadId: parentThreadId });
expect(result.thread.status).toBe("running");
expect(result.thread.latestRunId).toBe(cancelledRunId);
expect(result.thread.activeRunId).toBe(activeRunId);
}).pipe(Effect.provide(layer), Effect.runPromise);
});
it("readThread prefers waiting activity status over a newer cancelled queued run", async () => {
const projection = {
thread: baseThread({
threadId: parentThreadId,
title: "Parent waiting",
instanceId: parentInstanceId,
model: "gpt-5.4",
}),
runs: [
makeRun({ id: activeRunId, ordinal: 1, status: "waiting" }),
makeRun({ id: cancelledRunId, ordinal: 2, status: "cancelled" }),
],
visibleTurnItems: [],
runtimeRequests: [],
messages: [],
contextTransfers: [],
subagents: [],
updatedAt: now,
} as unknown as OrchestrationV2ThreadProjection;
const layer = orchestratorMcpServiceLayer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.mock(ThreadManagementService)({
getThreadProjection: (threadId) =>
threadId === parentThreadId
? Effect.succeed(projection)
: Effect.die(`unexpected thread ${threadId}`),
} satisfies Partial<ThreadManagementService["Service"]>),
Layer.mock(ProviderRegistry)({
getProviders: Effect.succeed([]),
} satisfies Partial<ProviderRegistry["Service"]>),
Layer.mock(ScheduledTaskService)({
list: () => Effect.succeed({ tasks: [] }),
} satisfies Partial<ScheduledTaskService["Service"]>),
NodeCrypto.layer,
),
),
);
await Effect.gen(function* () {
const service = yield* OrchestratorMcpService;
const result = yield* service.readThread(makeScope(), { threadId: parentThreadId });
expect(result.thread.status).toBe("waiting");
expect(result.thread.activeRunId).toBe(activeRunId);
}).pipe(Effect.provide(layer), Effect.runPromise);
});
it("taskStatus returns task.providerInstanceId rather than the driver kind", async () => {
const parentProjection = {
thread: baseThread({
threadId: parentThreadId,
title: "Parent",
instanceId: parentInstanceId,
model: "gpt-5.4",
}),
runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })],
visibleTurnItems: [],
runtimeRequests: [],
messages: [],
contextTransfers: [],
subagents: [
{
id: taskId,
threadId: parentThreadId,
runId: activeRunId,
parentNodeId: NodeId.make("node-parent"),
origin: "app_owned",
createdBy: "agent",
driver: codexDriver,
providerInstanceId: customCodexInstanceId,
providerThreadId: null,
childThreadId,
nativeTaskRef: null,
prompt: "Inspect the custom instance.",
title: null,
model: "gpt-5.4",
status: "running",
result: null,
startedAt: now,
completedAt: null,
updatedAt: now,
},
],
updatedAt: now,
} as unknown as OrchestrationV2ThreadProjection;
const childProjection = {
thread: {
...baseThread({
threadId: childThreadId,
title: "Child",
instanceId: customCodexInstanceId,
model: "gpt-5.4",
}),
lineage: {
parentThreadId,
relationshipToParent: "subagent",
rootThreadId: parentThreadId,
},
createdBy: "agent",
},
runs: [
makeRun({
id: childRunId,
ordinal: 1,
status: "running",
instanceId: customCodexInstanceId,
}),
],
visibleTurnItems: [],
runtimeRequests: [],
messages: [],
contextTransfers: [
{
type: "subagent_spawn",
sourceThreadId: parentThreadId,
targetThreadId: childThreadId,
targetRunId: childRunId,
},
],
subagents: [],
updatedAt: now,
} as unknown as OrchestrationV2ThreadProjection;
const layer = orchestratorMcpServiceLayer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.mock(ThreadManagementService)({
getThreadProjection: (threadId) => {
if (threadId === parentThreadId) return Effect.succeed(parentProjection);
if (threadId === childThreadId) return Effect.succeed(childProjection);
return Effect.die(`unexpected thread ${threadId}`);
},
} satisfies Partial<ThreadManagementService["Service"]>),
Layer.mock(ProviderRegistry)({
getProviders: Effect.succeed([]),
} satisfies Partial<ProviderRegistry["Service"]>),
Layer.mock(ScheduledTaskService)({
list: () => Effect.succeed({ tasks: [] }),
} satisfies Partial<ScheduledTaskService["Service"]>),
NodeCrypto.layer,
),
),
);
await Effect.gen(function* () {
const service = yield* OrchestratorMcpService;
const result = yield* service.taskStatus(makeScope(), taskId);
expect(result.providerInstanceId).toBe(customCodexInstanceId);
expect(result.providerInstanceId).not.toBe(ProviderInstanceId.make(String(codexDriver)));
expect(result.status).toBe("running");
expect(result.taskId).toBe(taskId);
expect(result.childThreadId).toBe(childThreadId);
}).pipe(Effect.provide(layer), Effect.runPromise);
});
@@ -43,7 +43,6 @@ import {
type OrchestratorMcpThreadWaitInput,
type OrchestratorMcpThreadWaitResult,
type ProviderInteractionMode,
ProviderInstanceId,
type ProviderOptionDescriptor,
type ProviderOptionSelection,
type RuntimeMode,
@@ -512,7 +511,7 @@ function listItemFromShell(shell: OrchestrationV2ThreadShell): OrchestratorMcpTh
title: shell.title,
createdBy: shell.createdBy,
creationSource: shell.creationSource,
status: shell.status,
status: shell.activityRunStatus ?? shell.status,
latestRunId: shell.latestRunId,
providerInstanceId: shell.modelSelection.instanceId,
model: shell.modelSelection.model,
@@ -535,7 +534,7 @@ function threadDetail(projection: OrchestrationV2ThreadProjection): Orchestrator
title: projection.thread.title,
createdBy: projection.thread.createdBy,
creationSource: projection.thread.creationSource,
status: latest?.status ?? "idle",
status: active?.status ?? latest?.status ?? "idle",
latestRunId: latest?.id ?? null,
activeRunId: active?.id ?? null,
providerInstanceId: projection.thread.modelSelection.instanceId,
@@ -876,7 +875,7 @@ const make = Effect.gen(function* () {
childRunId: childRun?.id ?? null,
childNodeId: task.id,
status,
providerInstanceId: ProviderInstanceId.make(task.driver),
providerInstanceId: task.providerInstanceId,
model: task.model,
summary: derivedResult,
resultContextTransferId: resultTransfer?.id ?? null,
@@ -1488,7 +1487,10 @@ const make = Effect.gen(function* () {
const statuses = input.statuses === undefined ? null : new Set(input.statuses);
const titleContains = input.titleContains?.toLocaleLowerCase();
const filtered = projectThreads
.filter((thread) => statuses === null || statuses.has(thread.status))
.filter(
(thread) =>
statuses === null || statuses.has(thread.activityRunStatus ?? thread.status),
)
.filter(
(thread) =>
titleContains === undefined ||
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -8,6 +8,7 @@ import {
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { vi } from "vite-plus/test";
@@ -20,14 +21,19 @@ import {
} from "./ClaudeAdapterV2.ts";
import {
CLAUDE_AGENT_SDK_REPLAY_PROTOCOL,
ClaudeReplayIncompleteError,
ClaudeReplayRuntimeExitError,
ClaudeReplayUnexpectedOutboundError,
makeReplayQueryRunner,
recordInterruptedClaudeQuery,
recordMessagesUntilTurnResultAndFinalize,
} from "./ClaudeAdapterV2.testkit.ts";
import { makeProviderReplayGate } from "../testkit/ProviderReplayGate.testkit.ts";
const isClaudeAgentSdkQueryRunnerError = Schema.is(ClaudeAgentSdkQueryRunnerError);
const isClaudeReplayIncompleteError = Schema.is(ClaudeReplayIncompleteError);
const isClaudeReplayRuntimeExitError = Schema.is(ClaudeReplayRuntimeExitError);
const isClaudeReplayUnexpectedOutboundError = Schema.is(ClaudeReplayUnexpectedOutboundError);
const claudeSdkMock = vi.hoisted(() => {
const close = vi.fn();
@@ -63,7 +69,284 @@ vi.mock("@anthropic-ai/claude-agent-sdk", () => ({
query: claudeSdkMock.query,
}));
function makeGatedReplaySession() {
const options = {
model: "claude-sonnet-4-6",
tools: [],
permissionMode: "default",
sessionId: "session-replay-gate",
} satisfies ClaudeAgentSdkQueryOptions;
const label = "background_tasks_changed:empty";
const replayGate = makeProviderReplayGate([label]);
const runner = makeReplayQueryRunner(
{
provider: CLAUDE_PROVIDER,
protocol: CLAUDE_AGENT_SDK_REPLAY_PROTOCOL,
version: "test",
scenario: "labeled-inbound-replay-gate",
entries: [
{
type: "expect_outbound",
frame: {
type: "query.open",
options,
},
},
{
type: "emit_inbound",
label,
frame: {
type: "system",
subtype: "background_tasks_changed",
tasks: [],
uuid: "replay-gate-message",
session_id: options.sessionId,
},
},
{
type: "runtime_exit",
status: "success",
},
],
},
{ replayGate },
);
const session = runner.open({
options,
threadId: ThreadId.make("thread-replay-gate"),
providerSessionId: ProviderSessionId.make("provider-session-replay-gate"),
});
return { label, replayGate, runner, session };
}
const yieldToReplayStream = Effect.promise(
() =>
new Promise<void>((resolve) => {
setImmediate(resolve);
}),
);
describe("ClaudeAdapterV2 replay testkit", () => {
it.effect("holds a labeled inbound frame until its replay gate is released", () =>
Effect.gen(function* () {
const { label, replayGate, runner, session } = makeGatedReplaySession();
const streamFiber = yield* Stream.runDrain(session.messages).pipe(Effect.forkChild);
yield* yieldToReplayStream;
assert.isTrue(replayGate.hasReached(label));
assert.isUndefined(streamFiber.pollUnsafe());
assert.isTrue(replayGate.release(label));
yield* Fiber.join(streamFiber);
runner.assertComplete();
}),
);
it.effect("releases a replay gate when its stream consumer is interrupted", () =>
Effect.gen(function* () {
const { label, replayGate, session } = makeGatedReplaySession();
const streamFiber = yield* Stream.runDrain(session.messages).pipe(Effect.forkChild);
yield* yieldToReplayStream;
assert.isTrue(replayGate.hasReached(label));
yield* Fiber.interrupt(streamFiber);
assert.isFalse(replayGate.release(label));
}),
);
it.effect("interrupts a delayed inbound frame without emitting or advancing it", () =>
Effect.gen(function* () {
const options = {
model: "claude-sonnet-4-6",
tools: [],
permissionMode: "default",
sessionId: "session-replay-delayed-interrupt",
} satisfies ClaudeAgentSdkQueryOptions;
const label = "delayed-inbound";
const replayGate = makeProviderReplayGate([label]);
const runner = makeReplayQueryRunner(
{
provider: CLAUDE_PROVIDER,
protocol: CLAUDE_AGENT_SDK_REPLAY_PROTOCOL,
version: "test",
scenario: "delayed-inbound-interruption",
entries: [
{
type: "expect_outbound",
frame: {
type: "query.open",
options,
},
},
{
type: "emit_inbound",
label,
afterMs: 30_000,
frame: {
type: "assistant",
message: { content: [] },
parent_tool_use_id: null,
session_id: options.sessionId,
uuid: "delayed-inbound-message",
},
},
{
type: "runtime_exit",
status: "success",
},
],
},
{ replayGate },
);
const session = runner.open({
options,
threadId: ThreadId.make("thread-replay-delayed-interrupt"),
providerSessionId: ProviderSessionId.make("provider-session-replay-delayed-interrupt"),
});
const emittedMessages: Array<unknown> = [];
const streamFiber = yield* session.messages.pipe(
Stream.tap((message) => Effect.sync(() => emittedMessages.push(message))),
Stream.runDrain,
Effect.forkChild,
);
yield* yieldToReplayStream;
assert.isTrue(replayGate.hasReached(label));
assert.isTrue(replayGate.release(label));
yield* yieldToReplayStream;
yield* Fiber.interrupt(streamFiber);
assert.deepEqual(emittedMessages, []);
const incomplete = assert.throws(() => runner.assertComplete());
assert.isTrue(isClaudeReplayIncompleteError(incomplete));
if (isClaudeReplayIncompleteError(incomplete)) {
assert.equal(incomplete.cursor, 1);
assert.equal(incomplete.remaining, 2);
}
}),
);
it.effect("wakes a gated replay stream when an outbound frame mismatches", () =>
Effect.gen(function* () {
const { label, replayGate, session } = makeGatedReplaySession();
const emittedMessages: Array<unknown> = [];
const streamFiber = yield* session.messages.pipe(
Stream.tap((message) => Effect.sync(() => emittedMessages.push(message))),
Stream.runDrain,
Effect.exit,
Effect.forkChild,
);
yield* yieldToReplayStream;
assert.isTrue(replayGate.hasReached(label));
const offerExit = yield* Effect.exit(
session.offer(makeClaudeUserMessage({ text: "unexpected gated prompt" })),
);
assert.isTrue(Exit.isFailure(offerExit));
const streamExit = yield* Fiber.join(streamFiber);
assert.isTrue(Exit.isFailure(streamExit));
if (Exit.isFailure(streamExit)) {
const error = Cause.squash(streamExit.cause);
assert.isTrue(isClaudeAgentSdkQueryRunnerError(error));
if (isClaudeAgentSdkQueryRunnerError(error)) {
assert.isTrue(isClaudeReplayUnexpectedOutboundError(error.cause));
}
}
assert.deepEqual(emittedMessages, []);
}),
);
it.effect("surfaces an outbound mismatch during a delay without inbound callbacks", () =>
Effect.gen(function* () {
const stableOptions = {
model: "claude-sonnet-4-6",
tools: [],
permissionMode: "default",
sessionId: "session-replay-gated-permission",
} satisfies ClaudeAgentSdkQueryOptions;
const canUseTool = vi.fn<NonNullable<ClaudeAgentSdkQueryOptions["canUseTool"]>>(
async (_toolName, input, options) => ({
behavior: "allow",
updatedInput: input,
toolUseID: options.toolUseID,
}),
);
const label = "permission_request";
const replayGate = makeProviderReplayGate([label]);
const runner = makeReplayQueryRunner(
{
provider: CLAUDE_PROVIDER,
protocol: CLAUDE_AGENT_SDK_REPLAY_PROTOCOL,
version: "test",
scenario: "gated-permission-stops-after-failure",
entries: [
{
type: "expect_outbound",
frame: {
type: "query.open",
options: stableOptions,
},
},
{
type: "emit_inbound",
label,
afterMs: 30_000,
frame: {
type: "permission.request",
toolName: "Read",
input: { file_path: "/workspace/gated.ts" },
options: { toolUseID: "tool-use-gated" },
},
},
{
type: "runtime_exit",
status: "success",
},
],
},
{ replayGate },
);
const session = runner.open({
options: { ...stableOptions, canUseTool },
threadId: ThreadId.make("thread-replay-gated-permission"),
providerSessionId: ProviderSessionId.make("provider-session-replay-gated-permission"),
});
const emittedMessages: Array<unknown> = [];
const streamFiber = yield* session.messages.pipe(
Stream.tap((message) => Effect.sync(() => emittedMessages.push(message))),
Stream.runDrain,
Effect.exit,
Effect.forkChild,
);
yield* yieldToReplayStream;
assert.isTrue(replayGate.hasReached(label));
assert.isTrue(replayGate.release(label));
yield* yieldToReplayStream;
const offerExit = yield* Effect.exit(
session.offer(makeClaudeUserMessage({ text: "unexpected gated prompt" })),
);
assert.isTrue(Exit.isFailure(offerExit));
const streamExit = yield* Fiber.join(streamFiber);
assert.isTrue(Exit.isFailure(streamExit));
if (Exit.isFailure(streamExit)) {
const error = Cause.squash(streamExit.cause);
assert.isTrue(isClaudeAgentSdkQueryRunnerError(error));
if (isClaudeAgentSdkQueryRunnerError(error)) {
assert.isTrue(isClaudeReplayUnexpectedOutboundError(error.cause));
}
}
assert.deepEqual(emittedMessages, []);
assert.equal(canUseTool.mock.calls.length, 0);
}),
);
it.effect("wakes a replay stream waiting on an outbound frame when that frame mismatches", () =>
Effect.gen(function* () {
const options = {
@@ -118,6 +401,146 @@ describe("ClaudeAdapterV2 replay testkit", () => {
}),
);
it.effect("interrupts a replay stream waiting on its next outbound frame", () =>
Effect.gen(function* () {
const options = {
model: "claude-sonnet-4-6",
tools: [],
permissionMode: "default",
sessionId: "session-replay-outbound-interrupt",
} satisfies ClaudeAgentSdkQueryOptions;
const runner = makeReplayQueryRunner({
provider: CLAUDE_PROVIDER,
protocol: CLAUDE_AGENT_SDK_REPLAY_PROTOCOL,
version: "test",
scenario: "outbound-wait-interruption",
entries: [
{
type: "expect_outbound",
frame: {
type: "query.open",
options,
},
},
{
type: "expect_outbound",
frame: {
type: "prompt.offer",
message: makeClaudeUserMessage({ text: "next prompt" }),
},
},
],
});
const session = runner.open({
options,
threadId: ThreadId.make("thread-replay-outbound-interrupt"),
providerSessionId: ProviderSessionId.make("provider-session-replay-outbound-interrupt"),
});
const streamFiber = yield* Stream.runDrain(session.messages).pipe(Effect.forkChild);
yield* yieldToReplayStream;
assert.isUndefined(streamFiber.pollUnsafe());
yield* Fiber.interrupt(streamFiber);
const incomplete = assert.throws(() => runner.assertComplete());
assert.isTrue(isClaudeReplayIncompleteError(incomplete));
if (isClaudeReplayIncompleteError(incomplete)) {
assert.equal(incomplete.cursor, 1);
assert.equal(incomplete.remaining, 1);
}
}),
);
it.effect("aborts a pending permission callback when replay fails", () =>
Effect.gen(function* () {
const stableOptions = {
model: "claude-sonnet-4-6",
tools: [],
permissionMode: "default",
sessionId: "session-replay-permission-abort",
} satisfies ClaudeAgentSdkQueryOptions;
let callbackSignal: AbortSignal | undefined;
let notifyCallbackStarted = () => {};
const callbackStarted = new Promise<void>((resolve) => {
notifyCallbackStarted = resolve;
});
const canUseTool = vi.fn<NonNullable<ClaudeAgentSdkQueryOptions["canUseTool"]>>(
async (_toolName, _input, options) => {
callbackSignal = options.signal;
notifyCallbackStarted();
await new Promise<never>((_resolve, reject) => {
const rejectOnAbort = () => reject(new Error("permission callback aborted"));
options.signal.addEventListener("abort", rejectOnAbort, { once: true });
if (options.signal.aborted) {
rejectOnAbort();
}
});
return {
behavior: "allow",
updatedInput: _input,
toolUseID: options.toolUseID,
};
},
);
const runner = makeReplayQueryRunner({
provider: CLAUDE_PROVIDER,
protocol: CLAUDE_AGENT_SDK_REPLAY_PROTOCOL,
version: "test",
scenario: "pending-permission-aborts-on-replay-failure",
entries: [
{
type: "expect_outbound",
frame: {
type: "query.open",
options: stableOptions,
},
},
{
type: "emit_inbound",
frame: {
type: "permission.request",
toolName: "Read",
input: { file_path: "/workspace/pending.ts" },
options: { toolUseID: "tool-use-pending" },
},
},
{
type: "runtime_exit",
status: "success",
},
],
});
const session = runner.open({
options: { ...stableOptions, canUseTool },
threadId: ThreadId.make("thread-replay-permission-abort"),
providerSessionId: ProviderSessionId.make("provider-session-replay-permission-abort"),
});
const streamFiber = yield* Stream.runDrain(session.messages).pipe(
Effect.exit,
Effect.forkChild,
);
yield* Effect.promise(() => callbackStarted);
const offerExit = yield* Effect.exit(
session.offer(makeClaudeUserMessage({ text: "unexpected prompt" })),
);
assert.isTrue(Exit.isFailure(offerExit));
const streamExit = yield* Fiber.join(streamFiber);
assert.isTrue(Exit.isFailure(streamExit));
if (Exit.isFailure(streamExit)) {
const error = Cause.squash(streamExit.cause);
assert.isTrue(isClaudeAgentSdkQueryRunnerError(error));
if (isClaudeAgentSdkQueryRunnerError(error)) {
assert.isTrue(isClaudeReplayUnexpectedOutboundError(error.cause));
}
}
assert.equal(canUseTool.mock.calls.length, 1);
assert.isTrue(callbackSignal?.aborted);
}),
);
it.effect("keeps permission callbacks scoped to the query that opened the stream", () =>
Effect.gen(function* () {
const firstCanUseTool = vi.fn<NonNullable<ClaudeAgentSdkQueryOptions["canUseTool"]>>(
@@ -14,8 +14,10 @@ import {
type ProviderApprovalDecision,
type ProviderReplayTranscript,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
@@ -44,6 +46,7 @@ import {
makeReplayServerConfig,
type OrchestratorV2ProviderReplayHarness,
} from "../testkit/ProviderReplayHarness.ts";
import type { ProviderReplayGate } from "../testkit/ProviderReplayGate.testkit.ts";
export const CLAUDE_AGENT_SDK_REPLAY_PROTOCOL = "claude-agent-sdk.query" as const;
@@ -333,11 +336,11 @@ function makeClaudePermissionResponseFrame(
function permissionRequestOptionsFromFrame(
frame: ClaudePermissionRequestFrame,
signal: AbortSignal,
): Parameters<CanUseTool>[2] {
const abortController = new AbortController();
const options = frame.options;
return {
signal: abortController.signal,
signal,
...(options.suggestions === undefined ? {} : { suggestions: options.suggestions }),
...(options.blockedPath === undefined ? {} : { blockedPath: options.blockedPath }),
...(options.decisionReason === undefined ? {} : { decisionReason: options.decisionReason }),
@@ -363,6 +366,35 @@ function makeCursorSignal(): {
return { promise, resolve };
}
function waitForCursorAdvance(promise: Promise<void>, signal: AbortSignal): Promise<void> {
if (signal.aborted) {
return Promise.resolve();
}
return new Promise<void>((resolve) => {
let waiting = true;
const finish = () => {
if (!waiting) {
return;
}
waiting = false;
signal.removeEventListener("abort", finish);
resolve();
};
signal.addEventListener("abort", finish, { once: true });
void promise.then(finish);
if (signal.aborted) {
finish();
}
});
}
async function waitForReplayDelay(afterMs: number, signal: AbortSignal): Promise<void> {
const exit = await Effect.runPromiseExit(Effect.sleep(Duration.millis(afterMs)), { signal });
if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) {
throw Cause.squash(exit.cause);
}
}
function stableClaudeQueryOptions(options: ClaudeAgentSdkQueryOptions): ClaudeAgentSdkQueryOptions {
const stable = {
model: options.model,
@@ -417,17 +449,33 @@ function makeClaudeSessionForkFrame(
export function makeReplayQueryRunner(
transcript: ClaudeAgentSdkReplayTranscript,
replayOptions: { readonly replayGate?: ProviderReplayGate } = {},
): ClaudeQueryRunner {
let cursor = 0;
let failure: ClaudeAgentSdkReplayError | null = null;
let cursorAdvanced = makeCursorSignal();
const iteratorAbortControllers = new Set<AbortController>();
const abortReplayIterators = () => {
for (const abortController of iteratorAbortControllers) {
abortController.abort();
}
};
const fail = (error: ClaudeAgentSdkReplayError): never => {
failure = error;
abortReplayIterators();
replayOptions.replayGate?.releaseAll();
cursorAdvanced.resolve();
throw error;
};
const throwIfFailed = () => {
if (failure !== null) {
throw failure;
}
};
const advance = () => {
cursor += 1;
const signal = cursorAdvanced;
@@ -437,11 +485,10 @@ export function makeReplayQueryRunner(
async function* replayMessages(
options: ClaudeAgentSdkQueryOptions,
signal: AbortSignal,
): AsyncGenerator<SDKMessage, void> {
while (true) {
if (failure !== null) {
throw failure;
}
throwIfFailed();
const entry = transcript.entries[cursor];
if (entry === undefined) {
@@ -449,6 +496,20 @@ export function makeReplayQueryRunner(
}
if (entry.type === "emit_inbound") {
if (replayOptions.replayGate !== undefined) {
await replayOptions.replayGate.beforeEmit(entry.label, signal);
throwIfFailed();
if (signal.aborted) {
return;
}
}
if (entry.afterMs !== undefined && entry.afterMs > 0) {
await waitForReplayDelay(entry.afterMs, signal);
throwIfFailed();
if (signal.aborted) {
return;
}
}
if (isClaudePermissionRequestFrame(entry.frame)) {
const request = entry.frame;
const invokeCanUseTool = options.canUseTool;
@@ -459,15 +520,27 @@ export function makeReplayQueryRunner(
expectedType: "permission.request",
actual: request,
});
failure = error;
throw error;
return fail(error);
}
advance();
const result = await invokeCanUseTool(
request.toolName,
request.input,
permissionRequestOptionsFromFrame(request),
);
let result: PermissionResult | null;
try {
result = await invokeCanUseTool(
request.toolName,
request.input,
permissionRequestOptionsFromFrame(request, signal),
);
} catch (cause) {
throwIfFailed();
if (signal.aborted) {
return;
}
throw cause;
}
throwIfFailed();
if (signal.aborted) {
return;
}
if (result === null) {
const error = new ClaudeReplayUnexpectedOutboundError({
scenario: transcript.scenario,
@@ -475,8 +548,7 @@ export function makeReplayQueryRunner(
expectedType: "permission.response",
actual: null,
});
failure = error;
throw error;
return fail(error);
}
assertNextOutboundFrame(makeClaudePermissionResponseFrame(result));
continue;
@@ -502,13 +574,49 @@ export function makeReplayQueryRunner(
}
if (entry.type === "expect_outbound") {
const signal = cursorAdvanced;
await signal.promise;
await waitForCursorAdvance(cursorAdvanced.promise, signal);
throwIfFailed();
if (signal.aborted) {
return;
}
continue;
}
}
}
const replayMessagesWithGateCleanup = (
options: ClaudeAgentSdkQueryOptions,
): AsyncIterable<SDKMessage> => ({
[Symbol.asyncIterator]: () => {
const abortController = new AbortController();
iteratorAbortControllers.add(abortController);
const iterator = replayMessages(options, abortController.signal);
return {
next: async () => {
try {
const result = await iterator.next();
if (result.done) {
iteratorAbortControllers.delete(abortController);
}
return result;
} catch (cause) {
iteratorAbortControllers.delete(abortController);
throw cause;
}
},
return: async () => {
abortController.abort();
replayOptions.replayGate?.releaseAll();
try {
return await iterator.return();
} finally {
iteratorAbortControllers.delete(abortController);
}
},
};
},
});
const assertNextOutboundFrame = (actual: ClaudeOutboundFrame) => {
if (failure !== null) {
throw failure;
@@ -602,7 +710,7 @@ export function makeReplayQueryRunner(
open: (input) => {
assertNextOutboundFrame(makeClaudeQueryOpenFrame(input));
return {
messages: Stream.fromAsyncIterable(replayMessages(input.options), (cause) =>
messages: Stream.fromAsyncIterable(replayMessagesWithGateCleanup(input.options), (cause) =>
replayQueryRunnerError(transcript, cause),
),
offer: (message) =>
@@ -631,6 +739,7 @@ export function makeReplayQueryRunner(
throw failure;
}
if (cursor !== transcript.entries.length) {
replayOptions.replayGate?.releaseAll();
throw new ClaudeReplayIncompleteError({
scenario: transcript.scenario,
cursor,
@@ -680,8 +789,11 @@ function replayQueryRunnerError(
}
const makeClaudeAgentSdkReplayQueryRunner = Effect.fn("ClaudeAgentSdkReplayQueryRunner.layer")(
function* (transcript: ClaudeAgentSdkReplayTranscript) {
const queryRunner = makeReplayQueryRunner(transcript);
function* (
transcript: ClaudeAgentSdkReplayTranscript,
options: { readonly replayGate?: ProviderReplayGate } = {},
) {
const queryRunner = makeReplayQueryRunner(transcript, options);
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
queryRunner.assertComplete();
@@ -710,14 +822,19 @@ const makeClaudeAgentSdkReplayQueryRunner = Effect.fn("ClaudeAgentSdkReplayQuery
export function makeClaudeAgentSdkReplayQueryRunnerLayer(
transcript: ClaudeAgentSdkReplayTranscript,
options: { readonly replayGate?: ProviderReplayGate } = {},
): Layer.Layer<ClaudeAgentSdkQueryRunner> {
return Layer.effect(ClaudeAgentSdkQueryRunner, makeClaudeAgentSdkReplayQueryRunner(transcript));
return Layer.effect(
ClaudeAgentSdkQueryRunner,
makeClaudeAgentSdkReplayQueryRunner(transcript, options),
);
}
export function makeClaudeAgentSdkReplayLayer(
transcript: ClaudeAgentSdkReplayTranscript,
options: { readonly replayGate?: ProviderReplayGate } = {},
): Layer.Layer<ClaudeAgentSdkQueryRunner> {
const queryRunner = makeReplayQueryRunner(transcript);
const queryRunner = makeReplayQueryRunner(transcript, options);
return Layer.effect(
ClaudeAgentSdkQueryRunner,
Effect.gen(function* () {
@@ -750,6 +867,7 @@ export function makeClaudeAgentSdkReplayLayer(
export function makeClaudeProviderAdapterRegistryReplayLayer(
transcript: ClaudeAgentSdkReplayTranscript,
options: { readonly replayGate?: ProviderReplayGate } = {},
) {
const serverConfigLayer = Layer.effect(
ServerConfig,
@@ -765,7 +883,7 @@ export function makeClaudeProviderAdapterRegistryReplayLayer(
}).pipe(
Layer.provide(
Layer.mergeAll(
makeClaudeAgentSdkReplayLayer(transcript),
makeClaudeAgentSdkReplayLayer(transcript, options),
idAllocatorLayer,
NodeServices.layer,
serverConfigLayer,
@@ -2432,6 +2550,6 @@ export const ClaudeOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarnes
}),
),
),
makeProviderAdapterRegistryLayer: (transcript) =>
makeClaudeProviderAdapterRegistryReplayLayer(transcript),
makeProviderAdapterRegistryLayer: (transcript, options) =>
makeClaudeProviderAdapterRegistryReplayLayer(transcript, options),
};
@@ -28,6 +28,7 @@ import {
type OrchestrationV2ExecutionNode,
type OrchestrationV2ProviderCapabilities,
type OrchestrationV2ProviderFailure,
type OrchestrationV2PendingBackgroundTask,
type OrchestrationV2ProviderRetry,
type OrchestrationV2ProviderSession,
type OrchestrationV2ProviderThread,
@@ -1399,6 +1400,15 @@ function commandInputFromClaudeTool(toolName: string, input: ClaudeNativeToolInp
);
}
// Opaque non-subagent background work admitted onto the Waiting roster.
// Subagents project through the normal subagent lifecycle and must not be
// double-counted when background_tasks_changed includes them.
const CLAUDE_OPAQUE_BACKGROUND_TASK_TYPES = new Set(["local_bash"]);
function isClaudeOpaqueBackgroundTaskType(taskType: string | null | undefined): boolean {
return typeof taskType === "string" && CLAUDE_OPAQUE_BACKGROUND_TASK_TYPES.has(taskType);
}
function claudeTaskTypeFromSdkMessage(message: SDKMessage): string | null {
if (typeof message !== "object" || message === null) {
return null;
@@ -1408,7 +1418,45 @@ function claudeTaskTypeFromSdkMessage(message: SDKMessage): string | null {
}
function isClaudeNonSubagentTask(message: SDKMessage): boolean {
return claudeTaskTypeFromSdkMessage(message) === "local_bash";
return isClaudeOpaqueBackgroundTaskType(claudeTaskTypeFromSdkMessage(message));
}
function isClaudeBackgroundTasksChangedMessage(message: SDKMessage): boolean {
return (
message.type === "system" &&
// Undeclared SDK subtype: full roster snapshot of live background tasks.
(message.subtype as string) === "background_tasks_changed"
);
}
function claudePendingBackgroundTasksFromRoster(
roster: ReadonlyMap<string, OrchestrationV2PendingBackgroundTask>,
): ReadonlyArray<OrchestrationV2PendingBackgroundTask> {
return Array.from(roster.values());
}
function parseClaudeBackgroundTaskEntry(
entry: unknown,
): OrchestrationV2PendingBackgroundTask | null {
if (entry === null || typeof entry !== "object") {
return null;
}
const taskId = Reflect.get(entry, "task_id");
if (typeof taskId !== "string" || taskId.length === 0) {
return null;
}
const taskType = Reflect.get(entry, "task_type");
// Mirror the incremental path: only opaque non-subagent types currently
// supported for Waiting. Subagent/agent entries stay on the subagent path.
if (!isClaudeOpaqueBackgroundTaskType(typeof taskType === "string" ? taskType : null)) {
return null;
}
const description = Reflect.get(entry, "description");
return {
taskId,
...(typeof description === "string" && description.trim().length > 0 ? { description } : {}),
taskType,
};
}
function fileNameFromClaudeTool(toolName: string, input: ClaudeNativeToolInput): string {
@@ -2039,7 +2087,32 @@ export function makeClaudeAdapterV2(
{ readonly threadId: ThreadId; readonly providerThreadId: ProviderThreadId }
>(),
);
const pendingBackgroundTaskIds = yield* Ref.make(new Set<string>());
// Authoritative + incremental background-task roster for post-settle
// Waiting UI. Outer key is native Claude session id so concurrent
// provider threads on one runtime cannot share or clear each other.
const pendingBackgroundTasksByNativeThread = yield* Ref.make(
new Map<string, Map<string, OrchestrationV2PendingBackgroundTask>>(),
);
// Wake eligibility is separate from the Waiting roster. It survives
// empty background_tasks_changed levels (SDK: empty level can precede
// task_notification) and is consumed when the first idle notification
// is buffered/offered so duplicates cannot re-buffer. A short-lived
// replay tombstone then covers continuation drain classification so
// local_bash is never projected as a subagent; the tombstone is
// cleared after that drained notification is processed. Both sets
// clear on CLI process open/replacement and failed/interrupted turns.
const wakeEligibleBackgroundTasksByNativeThread = yield* Ref.make(
new Map<string, Set<string>>(),
);
const opaqueBackgroundTaskReplayTombstonesByNativeThread = yield* Ref.make(
new Map<string, Set<string>>(),
);
// Last known provider-thread payload per native session, used to emit
// roster-only provider_thread.updated events between turns without
// resurrecting an active status after root settlement.
const lastProviderThreadByNativeThread = yield* Ref.make(
new Map<string, OrchestrationV2ProviderThread>(),
);
// Subagent registry that survives turn settle: a background subagent
// (Agent with run_in_background) can complete after the root turn
// ended, and its task_notification must both count as wake evidence
@@ -2059,6 +2132,359 @@ export function makeClaudeAdapterV2(
const emitProviderEvent = (event: ProviderAdapterV2Event) =>
Queue.offer(events, event).pipe(Effect.asVoid);
const rememberProviderThread = (providerThread: OrchestrationV2ProviderThread) =>
Effect.gen(function* () {
const nativeThreadId = providerThread.nativeThreadRef?.nativeId;
if (nativeThreadId === undefined || nativeThreadId === null) {
return;
}
yield* Ref.update(lastProviderThreadByNativeThread, (current) =>
new Map(current).set(nativeThreadId, providerThread),
);
});
const rosterForNativeThread = (
all: ReadonlyMap<string, Map<string, OrchestrationV2PendingBackgroundTask>>,
nativeThreadId: string,
): Map<string, OrchestrationV2PendingBackgroundTask> =>
all.get(nativeThreadId) ?? new Map<string, OrchestrationV2PendingBackgroundTask>();
const hasPendingBackgroundTaskOnNativeThread = (nativeThreadId: string, taskId: string) =>
Ref.get(pendingBackgroundTasksByNativeThread).pipe(
Effect.map((all) => rosterForNativeThread(all, nativeThreadId).has(taskId)),
);
const taskIdSetForNativeThread = (
all: ReadonlyMap<string, Set<string>>,
nativeThreadId: string,
): Set<string> => all.get(nativeThreadId) ?? new Set<string>();
const addTaskIdsToNativeThreadSet = (
ref: Ref.Ref<Map<string, Set<string>>>,
nativeThreadId: string,
taskIds: ReadonlyArray<string>,
) =>
Ref.update(ref, (current) => {
if (taskIds.length === 0) {
return current;
}
const next = new Set(taskIdSetForNativeThread(current, nativeThreadId));
let changed = false;
for (const taskId of taskIds) {
if (!next.has(taskId)) {
next.add(taskId);
changed = true;
}
}
return changed ? new Map(current).set(nativeThreadId, next) : current;
});
const clearTaskIdFromNativeThreadSet = (
ref: Ref.Ref<Map<string, Set<string>>>,
nativeThreadId: string,
taskId: string,
) =>
Ref.update(ref, (current) => {
const existing = taskIdSetForNativeThread(current, nativeThreadId);
if (!existing.has(taskId)) {
return current;
}
const next = new Set(existing);
next.delete(taskId);
const updated = new Map(current);
if (next.size === 0) {
updated.delete(nativeThreadId);
} else {
updated.set(nativeThreadId, next);
}
return updated;
});
const clearNativeThreadTaskIdSet = (
ref: Ref.Ref<Map<string, Set<string>>>,
nativeThreadId: string,
) =>
Ref.update(ref, (current) => {
if (!current.has(nativeThreadId)) {
return current;
}
const updated = new Map(current);
updated.delete(nativeThreadId);
return updated;
});
// First-notification wake offering only: not the Waiting roster and
// not the post-buffer replay tombstone.
const isWakeEligibleOpaqueBackgroundTaskOnNativeThread = (
nativeThreadId: string,
taskId: string,
) =>
Ref.get(wakeEligibleBackgroundTasksByNativeThread).pipe(
Effect.map((all) => taskIdSetForNativeThread(all, nativeThreadId).has(taskId)),
);
const hasOpaqueBackgroundTaskReplayTombstoneOnNativeThread = (
nativeThreadId: string,
taskId: string,
) =>
Ref.get(opaqueBackgroundTaskReplayTombstonesByNativeThread).pipe(
Effect.map((all) => taskIdSetForNativeThread(all, nativeThreadId).has(taskId)),
);
// Classify a task_notification as opaque local_bash (not a subagent):
// live roster, still-eligible first notification, or short-lived
// replay tombstone left after the idle notification was buffered.
const isKnownOpaqueBackgroundTaskOnNativeThread = (
nativeThreadId: string,
taskId: string,
) =>
Effect.gen(function* () {
if (yield* hasPendingBackgroundTaskOnNativeThread(nativeThreadId, taskId)) {
return true;
}
if (yield* isWakeEligibleOpaqueBackgroundTaskOnNativeThread(nativeThreadId, taskId)) {
return true;
}
return yield* hasOpaqueBackgroundTaskReplayTombstoneOnNativeThread(
nativeThreadId,
taskId,
);
});
// Admit onto wake eligibility only. Replay tombstones are created when
// the first idle notification is buffered, not at task start.
const markWakeEligibleOpaqueBackgroundTasks = (
nativeThreadId: string,
taskIds: ReadonlyArray<string>,
) =>
addTaskIdsToNativeThreadSet(
wakeEligibleBackgroundTasksByNativeThread,
nativeThreadId,
taskIds,
);
// After the first idle opaque notification is buffered/offered: stop
// further wake buffering for this task id, but keep a replay tombstone
// until the continuation drain classifies the buffered notification.
const consumeWakeEligibilityForBufferedNotification = (
nativeThreadId: string,
taskId: string,
) =>
Effect.gen(function* () {
yield* clearTaskIdFromNativeThreadSet(
wakeEligibleBackgroundTasksByNativeThread,
nativeThreadId,
taskId,
);
yield* addTaskIdsToNativeThreadSet(
opaqueBackgroundTaskReplayTombstonesByNativeThread,
nativeThreadId,
[taskId],
);
});
const clearOpaqueBackgroundTaskReplayTombstone = (nativeThreadId: string, taskId: string) =>
clearTaskIdFromNativeThreadSet(
opaqueBackgroundTaskReplayTombstonesByNativeThread,
nativeThreadId,
taskId,
);
const emitProviderThreadRoster = Effect.fnUntraced(function* (input: {
readonly nativeThreadId: string;
readonly providerThread: OrchestrationV2ProviderThread;
readonly status?: OrchestrationV2ProviderThread["status"];
}) {
const roster = rosterForNativeThread(
yield* Ref.get(pendingBackgroundTasksByNativeThread),
input.nativeThreadId,
);
const now = yield* DateTime.now;
const providerThread: OrchestrationV2ProviderThread = {
...input.providerThread,
providerSessionId: session.id,
...(input.status === undefined ? {} : { status: input.status }),
pendingBackgroundTasks: claudePendingBackgroundTasksFromRoster(roster),
updatedAt: now,
};
yield* rememberProviderThread(providerThread);
yield* emitProviderEvent({
type: "provider_thread.updated",
driver: CLAUDE_PROVIDER,
providerThread,
});
});
const replacePendingBackgroundTasks = (
nativeThreadId: string,
tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,
) =>
Effect.gen(function* () {
yield* Ref.update(pendingBackgroundTasksByNativeThread, (current) => {
const updated = new Map(current);
if (tasks.length === 0) {
updated.delete(nativeThreadId);
} else {
updated.set(
nativeThreadId,
new Map(tasks.map((task) => [task.taskId, task] as const)),
);
}
return updated;
});
// Empty level must not drop wake eligibility: notification may
// still be in flight. Non-empty level admits new task ids to
// wake eligibility only (replay tombstones are edge-created).
if (tasks.length > 0) {
yield* markWakeEligibleOpaqueBackgroundTasks(
nativeThreadId,
tasks.map((task) => task.taskId),
);
}
});
const upsertPendingBackgroundTask = (
nativeThreadId: string,
task: OrchestrationV2PendingBackgroundTask,
) =>
Effect.gen(function* () {
yield* Ref.update(pendingBackgroundTasksByNativeThread, (current) => {
const roster = new Map(rosterForNativeThread(current, nativeThreadId));
roster.set(task.taskId, task);
return new Map(current).set(nativeThreadId, roster);
});
yield* markWakeEligibleOpaqueBackgroundTasks(nativeThreadId, [task.taskId]);
});
const clearPendingBackgroundTask = (nativeThreadId: string, taskId: string) =>
Ref.modify(pendingBackgroundTasksByNativeThread, (current) => {
const roster = rosterForNativeThread(current, nativeThreadId);
if (!roster.has(taskId)) {
return [false, current] as const;
}
const nextRoster = new Map(roster);
nextRoster.delete(taskId);
const updated = new Map(current);
if (nextRoster.size === 0) {
updated.delete(nativeThreadId);
} else {
updated.set(nativeThreadId, nextRoster);
}
return [true, updated] as const;
});
const clearPendingBackgroundTasksForNativeThread = (nativeThreadId: string) =>
Ref.update(pendingBackgroundTasksByNativeThread, (current) => {
if (!current.has(nativeThreadId)) {
return current;
}
const updated = new Map(current);
updated.delete(nativeThreadId);
return updated;
});
// Drop idle wake traffic for a dead native process so it cannot pin
// session-wide pending work after sibling query replacement.
const clearWakeStateForNativeThread = (nativeThreadId: string) =>
Effect.gen(function* () {
yield* Ref.update(wakeBuffers, (current) => {
if (!current.has(nativeThreadId)) {
return current;
}
const updated = new Map(current);
updated.delete(nativeThreadId);
return updated;
});
yield* Ref.update(requestedContinuations, (current) => {
if (!current.has(nativeThreadId)) {
return current;
}
const updated = new Set(current);
updated.delete(nativeThreadId);
return updated;
});
});
// Process-scoped level: SDK emits nothing at CLI start, so both the
// Waiting roster and wake eligibility reset when a live query opens
// or is replaced for this native thread. Opaque replay tombstones that
// already covered buffered task_notification frames are restored so a
// model/policy query replacement still classifies those local_bash
// completions on continuation drain. Buffer membership alone must not
// invent opaque classification: session-registered subagent
// notifications share the same buffer.
const resetBackgroundTaskStateForNativeThreadProcess = Effect.fnUntraced(function* (
nativeThreadId: string,
options?: {
// openQuery during startTurn: activeTurn is not installed yet, but
// ProviderTurnStartService already marked the provider thread active.
readonly status?: OrchestrationV2ProviderThread["status"];
},
) {
const hadRoster =
rosterForNativeThread(
yield* Ref.get(pendingBackgroundTasksByNativeThread),
nativeThreadId,
).size > 0;
const remembered = (yield* Ref.get(lastProviderThreadByNativeThread)).get(nativeThreadId);
const hadPersistedRoster = (remembered?.pendingBackgroundTasks?.length ?? 0) > 0;
const priorOpaqueTombstones = taskIdSetForNativeThread(
yield* Ref.get(opaqueBackgroundTaskReplayTombstonesByNativeThread),
nativeThreadId,
);
const bufferedTaskNotificationIds = new Set<string>();
const buffered = (yield* Ref.get(wakeBuffers)).get(nativeThreadId);
if (buffered !== undefined) {
for (const message of buffered.messages) {
if (message.type === "system" && message.subtype === "task_notification") {
bufferedTaskNotificationIds.add(message.task_id);
}
}
}
const preservedOpaqueTombstones = [...priorOpaqueTombstones].filter((taskId) =>
bufferedTaskNotificationIds.has(taskId),
);
yield* clearPendingBackgroundTasksForNativeThread(nativeThreadId);
yield* clearNativeThreadTaskIdSet(
wakeEligibleBackgroundTasksByNativeThread,
nativeThreadId,
);
yield* clearNativeThreadTaskIdSet(
opaqueBackgroundTaskReplayTombstonesByNativeThread,
nativeThreadId,
);
if (preservedOpaqueTombstones.length > 0) {
yield* addTaskIdsToNativeThreadSet(
opaqueBackgroundTaskReplayTombstonesByNativeThread,
nativeThreadId,
preservedOpaqueTombstones,
);
}
if (!hadRoster && !hadPersistedRoster) {
return;
}
if (remembered === undefined) {
return;
}
// Prefer an explicit starting-turn status so a successful openQuery
// replacement clear cannot emit idle over an already-active thread.
// Otherwise: between turns never resurrect active from process reset;
// with a live activeTurn context, upgrade idle → active.
const activeContext = yield* Ref.get(activeTurn);
const status =
options?.status ??
(activeContext === null
? ("idle" as const)
: remembered.status === "idle"
? ("active" as const)
: remembered.status);
yield* emitProviderThreadRoster({
nativeThreadId,
providerThread: remembered,
status,
});
});
const resolveItemOrdinal = Effect.fnUntraced(function* (
context: ActiveClaudeTurnContext,
nativeItemId: string,
@@ -2946,26 +3372,55 @@ export function makeClaudeAdapterV2(
completedAt: input.completedAt,
}),
}),
...(input.status === "completed" &&
input.context.input.providerThread.nativeConversationHeadRef !== null
? [
emitProviderEvent({
type: "provider_thread.updated" as const,
driver: CLAUDE_PROVIDER,
providerThread: {
...input.context.input.providerThread,
providerSessionId: session.id,
nativeConversationHeadRef: null,
status: "active" as const,
firstRunOrdinal:
input.context.input.providerThread.firstRunOrdinal ??
input.context.input.runOrdinal,
lastRunOrdinal: input.context.input.runOrdinal,
updatedAt: input.completedAt,
},
}),
]
: []),
// Surface this native thread's roster before the root turn
// terminals so writeFinalRunEvents preserves it. Failed or
// interrupted turns drop only this thread's roster so sibling
// native threads keep their Waiting state.
Effect.gen(function* () {
const nativeThreadId =
input.context.input.providerThread.nativeThreadRef?.nativeId ?? null;
if (nativeThreadId !== null) {
if (input.status !== "completed") {
yield* clearPendingBackgroundTasksForNativeThread(nativeThreadId);
yield* clearNativeThreadTaskIdSet(
wakeEligibleBackgroundTasksByNativeThread,
nativeThreadId,
);
yield* clearNativeThreadTaskIdSet(
opaqueBackgroundTaskReplayTombstonesByNativeThread,
nativeThreadId,
);
}
}
const roster =
nativeThreadId === null
? new Map<string, OrchestrationV2PendingBackgroundTask>()
: rosterForNativeThread(
yield* Ref.get(pendingBackgroundTasksByNativeThread),
nativeThreadId,
);
const clearConversationHead =
input.status === "completed" &&
input.context.input.providerThread.nativeConversationHeadRef !== null;
const providerThread: OrchestrationV2ProviderThread = {
...input.context.input.providerThread,
providerSessionId: session.id,
...(clearConversationHead ? { nativeConversationHeadRef: null } : {}),
firstRunOrdinal:
input.context.input.providerThread.firstRunOrdinal ??
input.context.input.runOrdinal,
lastRunOrdinal: input.context.input.runOrdinal,
pendingBackgroundTasks: claudePendingBackgroundTasksFromRoster(roster),
status: input.status === "completed" ? "active" : "idle",
updatedAt: input.completedAt,
};
yield* rememberProviderThread(providerThread);
yield* emitProviderEvent({
type: "provider_thread.updated" as const,
driver: CLAUDE_PROVIDER,
providerThread,
});
}),
emitProviderEvent(terminalEvent),
],
{ concurrency: 1 },
@@ -3060,16 +3515,6 @@ export function makeClaudeAdapterV2(
}
});
const clearPendingBackgroundTask = (taskId: string) =>
Ref.modify(pendingBackgroundTaskIds, (current) => {
if (!current.has(taskId)) {
return [false, current] as const;
}
const updated = new Set(current);
updated.delete(taskId);
return [true, updated] as const;
});
const bufferWakeMessage = Effect.fnUntraced(function* (wakeInput: {
readonly nativeThreadId: string;
readonly message: SDKMessage;
@@ -3078,13 +3523,17 @@ export function makeClaudeAdapterV2(
const isNotification =
message.type === "system" && message.subtype === "task_notification";
// Only notifications for tracked tasks count as wake evidence: a
// pending local_bash background task, or a session-registered
// subagent that is still running (Agent with run_in_background
// settling after the root turn). A stray notification for an
// unknown task is dropped as before instead of triggering a
// spurious continuation.
// wake-eligible local_bash task (eligibility set, not the Waiting
// roster), or a session-registered subagent that is still running
// (Agent with run_in_background settling after the root turn). A
// stray notification for an unknown task is dropped as before
// instead of triggering a spurious continuation.
const isPendingTaskNotification =
isNotification && (yield* Ref.get(pendingBackgroundTaskIds)).has(message.task_id);
isNotification &&
(yield* isWakeEligibleOpaqueBackgroundTaskOnNativeThread(
wakeInput.nativeThreadId,
message.task_id,
));
const isPendingSubagentNotification =
isNotification &&
!isPendingTaskNotification &&
@@ -3148,12 +3597,31 @@ export function makeClaudeAdapterV2(
});
return updated;
});
// Request a continuation run once per wake, when the wake turn has
// either announced the finished task or fully settled. Earlier
// messages only buffer; the continuation turn drains them.
// First idle opaque notification: consume wake eligibility so a
// duplicate cannot re-buffer, and leave a short-lived replay
// tombstone for continuation-drain classification.
if (isPendingTaskNotification) {
yield* consumeWakeEligibilityForBufferedNotification(
wakeInput.nativeThreadId,
message.task_id,
);
}
// A terminal task notification can clear the Waiting roster without
// Claude dequeuing it into a native model turn. Buffer it for replay,
// but do not open an opaque-task continuation until native user,
// assistant, or result output proves that Claude actually began the
// wake turn. Subagent notifications retain their existing immediate
// offer because their projected lifecycle owns the continuation.
const buffered = (yield* Ref.get(wakeBuffers)).get(wakeInput.nativeThreadId);
const hasBufferedNotification =
buffered?.messages.some(
(entry) => entry.type === "system" && entry.subtype === "task_notification",
) ?? false;
const isNativeOpaqueWakeFrame =
hasBufferedNotification && (message.type === "assistant" || message.type === "user");
if (
!isPendingTaskNotification &&
!isPendingSubagentNotification &&
!isNativeOpaqueWakeFrame &&
message.type !== "result"
) {
return;
@@ -3192,6 +3660,90 @@ export function makeClaudeAdapterV2(
});
});
const applyBackgroundTaskRosterMessage = Effect.fnUntraced(function* (input: {
readonly nativeThreadId: string;
readonly message: SDKMessage;
readonly activeContext: ActiveClaudeTurnContext | null;
}) {
const message = input.message;
let rosterChanged = false;
if (isClaudeBackgroundTasksChangedMessage(message)) {
const roster = Reflect.get(message, "tasks");
if (!Array.isArray(roster)) {
return false;
}
const nextTasks: OrchestrationV2PendingBackgroundTask[] = [];
for (const entry of roster) {
const task = parseClaudeBackgroundTaskEntry(entry);
if (task !== null) {
nextTasks.push(task);
}
}
yield* replacePendingBackgroundTasks(input.nativeThreadId, nextTasks);
rosterChanged = true;
} else if (message.type === "system" && message.subtype === "task_started") {
// Incremental fallback when background_tasks_changed is absent.
// Subagent tasks project as subagent turn items; only non-subagent
// background work (e.g. local_bash) lives on the provider-thread roster.
if (!isClaudeNonSubagentTask(message)) {
return false;
}
const description =
typeof message.description === "string" && message.description.trim().length > 0
? message.description
: undefined;
const taskType = claudeTaskTypeFromSdkMessage(message) ?? undefined;
yield* upsertPendingBackgroundTask(input.nativeThreadId, {
taskId: message.task_id,
...(description === undefined ? {} : { description }),
...(taskType === undefined ? {} : { taskType }),
});
rosterChanged = true;
} else if (message.type === "system" && message.subtype === "task_notification") {
const removed = yield* clearPendingBackgroundTask(
input.nativeThreadId,
message.task_id,
);
// Waiting roster clears on the notification edge. Wake eligibility
// is consumed when the first idle notification is buffered; clear
// here too for same-turn active notifications that never entered
// the idle buffer path. Replay tombstones are not cleared here.
yield* clearTaskIdFromNativeThreadSet(
wakeEligibleBackgroundTasksByNativeThread,
input.nativeThreadId,
message.task_id,
);
rosterChanged = removed;
}
if (!rosterChanged) {
return false;
}
const baseThread =
input.activeContext?.input.providerThread ??
(yield* Ref.get(lastProviderThreadByNativeThread)).get(input.nativeThreadId);
if (baseThread === undefined) {
return true;
}
// Between turns, never resurrect active status from a late empty
// roster update. During an active turn, preserve the thread status.
const status =
input.activeContext === null
? ("idle" as const)
: baseThread.status === "idle"
? ("active" as const)
: baseThread.status;
yield* emitProviderThreadRoster({
nativeThreadId: input.nativeThreadId,
providerThread: baseThread,
status,
});
return true;
});
const handleSdkMessage = Effect.fnUntraced(function* (input: {
readonly query: ClaudeAgentSdkQuerySession;
readonly message: SDKMessage;
@@ -3204,7 +3756,23 @@ export function makeClaudeAdapterV2(
const message = input.message;
const context = yield* Ref.get(activeTurn);
if (context === null) {
yield* bufferWakeMessage({ nativeThreadId: liveQuery.nativeThreadId, message });
// task_notification must buffer wake evidence while still tracked
// on the roster; clearing first would drop the wake pin.
if (message.type === "system" && message.subtype === "task_notification") {
yield* bufferWakeMessage({ nativeThreadId: liveQuery.nativeThreadId, message });
yield* applyBackgroundTaskRosterMessage({
nativeThreadId: liveQuery.nativeThreadId,
message,
activeContext: null,
});
} else {
yield* applyBackgroundTaskRosterMessage({
nativeThreadId: liveQuery.nativeThreadId,
message,
activeContext: null,
});
yield* bufferWakeMessage({ nativeThreadId: liveQuery.nativeThreadId, message });
}
return;
}
@@ -3257,12 +3825,23 @@ export function makeClaudeAdapterV2(
return;
}
if (isClaudeBackgroundTasksChangedMessage(message)) {
yield* applyBackgroundTaskRosterMessage({
nativeThreadId: liveQuery.nativeThreadId,
message,
activeContext: context,
});
return;
}
if (message.type === "system" && message.subtype === "task_started") {
if (isClaudeNonSubagentTask(message)) {
context.ignoredTaskIds.add(message.task_id);
yield* Ref.update(pendingBackgroundTaskIds, (current) =>
new Set(current).add(message.task_id),
);
yield* applyBackgroundTaskRosterMessage({
nativeThreadId: liveQuery.nativeThreadId,
message,
activeContext: context,
});
} else {
yield* updateClaudeSubagentNode({
context,
@@ -3278,7 +3857,8 @@ export function makeClaudeAdapterV2(
if (message.type === "system" && message.subtype === "task_progress") {
const progress = message.description.trim();
const isBackgroundTask = (yield* Ref.get(pendingBackgroundTaskIds)).has(
const isBackgroundTask = yield* hasPendingBackgroundTaskOnNativeThread(
liveQuery.nativeThreadId,
message.task_id,
);
if (
@@ -3297,9 +3877,19 @@ export function makeClaudeAdapterV2(
}
if (message.type === "system" && message.subtype === "task_notification") {
// A wake-replay turn has empty ignoredTaskIds, so the session-level
// background registry is the durable ignore signal across turns.
const wasBackgroundTask = yield* clearPendingBackgroundTask(message.task_id);
// A wake-replay turn has empty ignoredTaskIds, so opaque-task
// tracking (live roster, wake eligibility, or the short-lived
// post-buffer replay tombstone) classifies local_bash before any
// subagent handling.
const wasBackgroundTask = yield* isKnownOpaqueBackgroundTaskOnNativeThread(
liveQuery.nativeThreadId,
message.task_id,
);
yield* applyBackgroundTaskRosterMessage({
nativeThreadId: liveQuery.nativeThreadId,
message,
activeContext: context,
});
if (!wasBackgroundTask && !context.ignoredTaskIds.has(message.task_id)) {
yield* updateClaudeSubagentNode({
context,
@@ -3314,6 +3904,14 @@ export function makeClaudeAdapterV2(
: "failed",
});
}
// Replay tombstone only needs to outlive buffering until this
// drained/live classification runs; drop it so it cannot leak.
if (wasBackgroundTask) {
yield* clearOpaqueBackgroundTaskReplayTombstone(
liveQuery.nativeThreadId,
message.task_id,
);
}
}
for (const toolUse of claudeToolUseBlocksFromAssistantMessage(message)) {
@@ -3609,8 +4207,20 @@ export function makeClaudeAdapterV2(
return existing;
}
// openQuery owns one live process. Closing it for another native
// thread kills that sibling's CLI; it can never emit a roster clear,
// so drop its process-scoped Waiting/wake state immediately. Closing
// for the same native thread leaves a non-authoritative roster until
// the replacement open succeeds or fails below.
const closedExistingNativeThreadId = existing !== null ? existing.nativeThreadId : null;
if (existing !== null) {
yield* existing.query.close.pipe(Effect.ignore);
if (existing.nativeThreadId !== nativeThreadId) {
yield* clearWakeStateForNativeThread(existing.nativeThreadId);
yield* resetBackgroundTaskStateForNativeThreadProcess(existing.nativeThreadId, {
status: "idle",
});
}
}
const openedWithResume = (yield* Ref.get(openedNativeThreads)).has(nativeThreadId);
@@ -3622,26 +4232,45 @@ export function makeClaudeAdapterV2(
const hasPersistedProviderTurn = turnInput.providerTurnOrdinal > 1;
const shouldResume =
resumeSessionAt !== undefined || openedWithResume || hasPersistedProviderTurn;
const querySession = yield* queryRunner.open({
threadId: turnInput.threadId,
providerSessionId: input.providerSessionId,
options: makeClaudeQueryOptions({
modelSelection: turnInput.modelSelection,
nativeThreadId,
resume: shouldResume,
...(resumeSessionAt === undefined ? {} : { resumeSessionAt }),
cwd: turnInput.runtimePolicy.cwd,
settings: adapterOptions.settings,
environment: adapterOptions.environment,
tools: queryPolicy.tools ?? CLAUDE_CODE_PRESET_TOOLS,
...mcpOverrides,
permissionMode: queryPolicy.permissionMode,
...(queryPolicy.allowDangerouslySkipPermissions === undefined
? {}
: { allowDangerouslySkipPermissions: queryPolicy.allowDangerouslySkipPermissions }),
...(shouldInstallClaudePermissionCallback(queryPolicy) ? { canUseTool } : {}),
}),
});
const querySession = yield* queryRunner
.open({
threadId: turnInput.threadId,
providerSessionId: input.providerSessionId,
options: makeClaudeQueryOptions({
modelSelection: turnInput.modelSelection,
nativeThreadId,
resume: shouldResume,
...(resumeSessionAt === undefined ? {} : { resumeSessionAt }),
cwd: turnInput.runtimePolicy.cwd,
settings: adapterOptions.settings,
environment: adapterOptions.environment,
tools: queryPolicy.tools ?? CLAUDE_CODE_PRESET_TOOLS,
...mcpOverrides,
permissionMode: queryPolicy.permissionMode,
...(queryPolicy.allowDangerouslySkipPermissions === undefined
? {}
: {
allowDangerouslySkipPermissions: queryPolicy.allowDangerouslySkipPermissions,
}),
...(shouldInstallClaudePermissionCallback(queryPolicy) ? { canUseTool } : {}),
}),
})
.pipe(
Effect.tapError(() =>
// Same-native-thread replacement: the old process is already
// dead, so its process-scoped roster is not authoritative.
// First-ever failed open (no prior live query) must not invent
// native-session reset events.
closedExistingNativeThreadId === nativeThreadId
? Effect.gen(function* () {
yield* clearWakeStateForNativeThread(nativeThreadId);
yield* resetBackgroundTaskStateForNativeThreadProcess(nativeThreadId, {
status: "idle",
});
})
: Effect.void,
),
);
// Marked only after a successful open: a failed create must not
// leave the runtime believing the native session exists, or the
// retry would resume a session that was never created.
@@ -3653,6 +4282,16 @@ export function makeClaudeAdapterV2(
updated.add(nativeThreadId);
return updated;
});
// Level is per CLI process: reset Waiting roster and wake
// eligibility whenever this native thread's process starts or is
// replaced. Membership repopulates on the next snapshot/edge.
// openQuery only runs from startTurn after ProviderTurnStartService
// marked the provider thread active, and before activeTurn is set.
// Buffered local_bash task_notification classification is preserved
// across this reset (see resetBackgroundTaskStateForNativeThreadProcess).
yield* resetBackgroundTaskStateForNativeThreadProcess(nativeThreadId, {
status: "active",
});
const closed = yield* Deferred.make<void, never>();
const context: ClaudeLiveQueryContext = {
nativeThreadId,
@@ -3708,6 +4347,7 @@ export function makeClaudeAdapterV2(
});
return updated;
});
yield* rememberProviderThread(turnInput.providerThread);
const context: ActiveClaudeTurnContext = {
input: turnInput,
nativeTurnId,
@@ -3786,6 +4426,16 @@ export function makeClaudeAdapterV2(
// replaying it before the rest would drop them back into the wake
// buffer and request another continuation.
const resultMessages = drained.filter((entry) => entry.type === "result");
const opaqueReplayTombstones = taskIdSetForNativeThread(
yield* Ref.get(opaqueBackgroundTaskReplayTombstonesByNativeThread),
nativeThreadId,
);
const hasOpaqueTaskNotification = drained.some(
(entry) =>
entry.type === "system" &&
entry.subtype === "task_notification" &&
opaqueReplayTombstones.has(entry.task_id),
);
for (const entry of drained) {
if (entry.type !== "result") {
yield* handleSdkMessage({ query: querySession.query, message: entry });
@@ -3794,6 +4444,14 @@ export function makeClaudeAdapterV2(
const lastResult = resultMessages.at(-1);
if (lastResult !== undefined) {
yield* handleSdkMessage({ query: querySession.query, message: lastResult });
return;
}
const hasNativeWakeFrame = drained.some(
(entry) => entry.type === "user" || entry.type === "assistant",
);
if (hasOpaqueTaskNotification && !hasNativeWakeFrame) {
const completedAt = yield* DateTime.now;
yield* finalizeActiveTurn({ context, status: "completed", completedAt });
}
},
(effect, turnInput) =>
@@ -3966,8 +4624,11 @@ export function makeClaudeAdapterV2(
providerSession: session,
events: Stream.fromEffectRepeat(Queue.take(events)),
hasPendingBackgroundWork: Effect.gen(function* () {
if ((yield* Ref.get(pendingBackgroundTaskIds)).size > 0) {
return true;
// Session capability: any native thread with pending work pins idle.
for (const roster of (yield* Ref.get(pendingBackgroundTasksByNativeThread)).values()) {
if (roster.size > 0) {
return true;
}
}
for (const subagent of (yield* Ref.get(sessionSubagentsByTaskId)).values()) {
if (subagent.task.status === "running") {
@@ -3976,12 +4637,34 @@ export function makeClaudeAdapterV2(
}
const buffers = yield* Ref.get(wakeBuffers);
for (const entry of buffers.values()) {
if (entry.messages.length > 0) {
if (
entry.messages.some(
(message) =>
message.type === "user" ||
message.type === "assistant" ||
message.type === "result",
)
) {
return true;
}
}
return false;
}),
hasPendingBackgroundWorkForThread: (providerThread) =>
Effect.gen(function* () {
const nativeThreadId = providerThread.nativeThreadRef?.nativeId;
if (nativeThreadId === undefined || nativeThreadId === null) {
return false;
}
// Root-run stop gate: only this native thread's roster. Session
// subagents and wake buffers stay on the session-wide probe.
return (
rosterForNativeThread(
yield* Ref.get(pendingBackgroundTasksByNativeThread),
nativeThreadId,
).size > 0
);
}),
ensureThread: Effect.fn("ClaudeAdapterV2.ensureThread")(
function* (threadInput: ProviderAdapterV2EnsureThreadInput) {
const createdAt = yield* DateTime.now;
@@ -15,6 +15,7 @@ import { ProviderAdapterOpenSessionError } from "../ProviderAdapter.ts";
import { ProviderAdapterDriverCreateError } from "../ProviderAdapterDriver.ts";
import { makeDriverLayer as makeProviderAdapterRegistryDriverLayer } from "../ProviderAdapterRegistry.ts";
import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts";
import type { ProviderReplayGate } from "../testkit/ProviderReplayGate.testkit.ts";
import {
CODEX_DEFAULT_INSTANCE_ID,
CODEX_DRIVER_KIND,
@@ -205,13 +206,29 @@ export const CodexOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness
}),
),
),
makeProviderAdapterRegistryLayer: (transcript) => {
makeProviderAdapterRegistryLayer: (
transcript,
options: { readonly replayGate?: ProviderReplayGate } = {},
) => {
return Layer.effectContext(
CodexReplay.makeReplayDriver(transcript).pipe(
Effect.flatMap((driver) =>
Layer.build(makeCodexProviderAdapterRegistryReplayLayer({ transcript, driver })),
),
),
Effect.gen(function* () {
const replayGate = options.replayGate;
if (replayGate !== undefined) {
yield* Effect.addFinalizer(() => Effect.sync(() => replayGate.releaseAll()));
}
const driver = yield* CodexReplay.makeReplayDriver(
transcript,
replayGate === undefined
? {}
: {
beforeEmitInbound: (entry) =>
Effect.promise((signal) => replayGate.beforeEmit(entry.label, signal)),
},
);
return yield* Layer.build(
makeCodexProviderAdapterRegistryReplayLayer({ transcript, driver }),
);
}),
);
},
};
@@ -13,6 +13,7 @@ import {
acpRootTurnIsIdle,
acpRootTurnSettleDebounceMs,
acpRootTurnShouldRearmRecoveryTimers,
acpSubagentStatusBlocksTurnSettlement,
acpSupportsImagePrompts,
} from "./AcpAdapterV2.ts";
import {
@@ -159,6 +160,20 @@ describe("acpRootTurn recovery timer re-arm", () => {
});
});
describe("acpSubagentStatusBlocksTurnSettlement", () => {
it("blocks settlement for pending and running subagents", () => {
assert.isTrue(acpSubagentStatusBlocksTurnSettlement("pending"));
assert.isTrue(acpSubagentStatusBlocksTurnSettlement("running"));
});
it("does not block settlement for terminal subagents", () => {
assert.isFalse(acpSubagentStatusBlocksTurnSettlement("cancelled"));
assert.isFalse(acpSubagentStatusBlocksTurnSettlement("completed"));
assert.isFalse(acpSubagentStatusBlocksTurnSettlement("failed"));
assert.isFalse(acpSubagentStatusBlocksTurnSettlement("interrupted"));
});
});
describe("acpRootTurnIsIdle", () => {
const quiet = {
finalized: false,
@@ -168,7 +183,7 @@ describe("acpRootTurnIsIdle", () => {
hasRunningTool: false,
hasPendingRuntimeRequest: false,
hasToolHistory: false,
hasRunningSubagent: false,
hasActiveSubagent: false,
hasOutput: true,
} as const;
@@ -185,7 +200,7 @@ describe("acpRootTurnIsIdle", () => {
});
it("is false while a native subagent task is still running", () => {
assert.isFalse(acpRootTurnIsIdle({ ...quiet, hasRunningSubagent: true }));
assert.isFalse(acpRootTurnIsIdle({ ...quiet, hasActiveSubagent: true }));
});
it("is false when only reasoning or tools have streamed", () => {
@@ -3,6 +3,7 @@ import {
type OrchestrationV2Run,
OrchestrationV2DomainEvent,
OrchestrationV2StoredEvent,
ProviderThreadId,
RunAttemptId,
RunId,
ThreadId,
@@ -99,6 +100,26 @@ export interface EventSinkV2Shape {
},
EventSinkV2Error
>;
/**
* Atomically commit only when the provider thread is still owned by the
* expected run attempt and ordinal. Used for late post-terminal
* provider_thread updates so a completed or superseded attempt cannot clobber
* a newer attempt that already claimed the thread.
*/
readonly writeIfProviderThreadOwner: (input: {
readonly commandId?: CommandId;
readonly providerThreadId: ProviderThreadId;
readonly runId: RunId;
readonly activeAttemptId: RunAttemptId;
readonly expectedLastRunOrdinal: number;
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
}) => Effect.Effect<
{
readonly committed: boolean;
readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
},
EventSinkV2Error
>;
readonly commitCommand: (input: {
readonly commandId: CommandId;
readonly threadId: ThreadId;
@@ -299,6 +320,62 @@ const baseLayer: Layer.Layer<
},
);
const writeIfProviderThreadOwnerEffect = Effect.fn(
"orchestrationV2.EventSink.writeIfProviderThreadOwner",
)(function* (input: Parameters<EventSinkV2Shape["writeIfProviderThreadOwner"]>[0]) {
yield* Effect.annotateCurrentSpan({
"orchestration_v2.command_id": input.commandId ?? null,
"orchestration_v2.event_count": input.events.length,
"orchestration_v2.provider_thread_id": input.providerThreadId,
"orchestration_v2.run_id": input.runId,
"orchestration_v2.active_attempt_id": input.activeAttemptId,
"orchestration_v2.expected_last_run_ordinal": input.expectedLastRunOrdinal,
});
const result = yield* sql.withTransaction(
Effect.gen(function* () {
const rows = yield* sql<{
readonly active_attempt_id: string | null;
readonly last_run_ordinal: number | null;
}>`
SELECT
json_extract(r.payload_json, '$.activeAttemptId') AS active_attempt_id,
p.last_run_ordinal
FROM orchestration_v2_projection_provider_threads p
JOIN orchestration_v2_projection_runs r
ON r.run_id = ${input.runId}
AND r.thread_id = p.thread_id
WHERE p.provider_thread_id = ${input.providerThreadId}
LIMIT 1
`;
const current = rows[0];
if (
current === undefined ||
current.active_attempt_id !== input.activeAttemptId ||
current.last_run_ordinal !== input.expectedLastRunOrdinal
) {
return {
committed: false as const,
storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
};
}
const normalized = yield* normalizeEvents(input.events);
const storedEvents = yield* eventStore.append({
...(input.commandId === undefined ? {} : { commandId: input.commandId }),
events: normalized,
});
yield* applyStoredEvents(storedEvents);
return { committed: true as const, storedEvents };
}),
);
if (result.committed) {
yield* eventStore.publishCommitted(result.storedEvents);
yield* PubSub.publishAll(liveEvents, result.storedEvents);
}
return result;
});
const existingCommandResult = (commandId: CommandId) =>
Effect.gen(function* () {
const existing = yield* commandReceipts.getByCommandId(commandId);
@@ -497,6 +574,17 @@ const baseLayer: Layer.Layer<
}),
),
),
writeIfProviderThreadOwner: (input) =>
writeIfProviderThreadOwnerEffect(input).pipe(
Effect.mapError(
(cause) =>
new EventSinkWriteError({
eventCount: input.events.length,
...(input.commandId === undefined ? {} : { commandId: input.commandId }),
cause,
}),
),
),
commitCommand: (input) =>
commitCommandEffect(input).pipe(
Effect.mapError(
@@ -867,6 +867,229 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
}),
);
it.effect("guards post-terminal provider-thread writes by attempt and run ordinal", () =>
Effect.gen(function* () {
const eventSink = yield* EventSinkV2;
const projectionStore = yield* ProjectionStoreV2;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread:foundation-provider-thread-owner");
const runId = RunId.make("run:foundation-provider-thread-owner");
const attemptId = RunAttemptId.make("attempt:foundation-provider-thread-owner");
const replacementAttemptId = RunAttemptId.make(
"attempt:foundation-provider-thread-owner:replacement",
);
const rootNodeId = NodeId.make("node:foundation-provider-thread-owner");
const providerThreadId = ProviderThreadId.make(
"provider-thread:foundation-provider-thread-owner",
);
const thread = makeThread(threadId, now);
const run: OrchestrationV2Run = {
id: runId,
threadId,
ordinal: 1,
providerInstanceId,
modelSelection,
providerThreadId,
userMessageId: MessageId.make("message:foundation-provider-thread-owner"),
rootNodeId,
activeAttemptId: attemptId,
status: "completed",
queuePosition: null,
requestedAt: now,
startedAt: now,
completedAt: now,
checkpointId: null,
contextHandoffId: null,
};
const baseProviderThread = {
id: providerThreadId,
driver: providerDriver,
providerInstanceId,
providerSessionId: null,
appThreadId: threadId,
ownerNodeId: null,
nativeThreadRef: null,
nativeConversationHeadRef: null,
status: "idle" as const,
firstRunOrdinal: 1,
lastRunOrdinal: 1,
handoffIds: [] as const,
forkedFrom: null,
pendingBackgroundTasks: [
{ taskId: "bg-owner", description: "sleep 20", taskType: "local_bash" },
],
createdAt: now,
updatedAt: now,
};
yield* eventSink.write({
events: [
threadCreatedEvent({
id: "event:foundation-provider-thread-owner:thread",
thread,
now,
}),
{
id: EventId.make("event:foundation-provider-thread-owner:run"),
type: "run.created",
threadId,
runId,
nodeId: rootNodeId,
providerInstanceId,
occurredAt: now,
payload: run,
},
{
id: EventId.make("event:foundation-provider-thread-owner:provider-thread"),
type: "provider-thread.updated",
threadId,
driver: providerDriver,
providerInstanceId,
occurredAt: now,
payload: baseProviderThread,
},
],
});
const ownedClear = yield* eventSink.writeIfProviderThreadOwner({
providerThreadId,
runId,
activeAttemptId: attemptId,
expectedLastRunOrdinal: 1,
events: [
{
id: EventId.make("event:foundation-provider-thread-owner:clear"),
type: "provider-thread.updated",
threadId,
driver: providerDriver,
providerInstanceId,
occurredAt: now,
payload: {
...baseProviderThread,
pendingBackgroundTasks: [],
updatedAt: now,
},
},
],
});
assert.isTrue(ownedClear.committed);
assert.equal(ownedClear.storedEvents.length, 1);
const afterReplacement = yield* DateTime.now;
yield* eventSink.write({
events: [
{
id: EventId.make("event:foundation-provider-thread-owner:replacement-attempt"),
type: "run.updated",
threadId,
runId,
nodeId: rootNodeId,
providerInstanceId,
occurredAt: afterReplacement,
payload: {
...run,
activeAttemptId: replacementAttemptId,
status: "running",
},
},
],
});
const supersededAttemptWrite = yield* eventSink.writeIfProviderThreadOwner({
providerThreadId,
runId,
activeAttemptId: attemptId,
expectedLastRunOrdinal: 1,
events: [
{
id: EventId.make("event:foundation-provider-thread-owner:superseded-attempt"),
type: "provider-thread.updated",
threadId,
driver: providerDriver,
providerInstanceId,
occurredAt: afterReplacement,
payload: {
...baseProviderThread,
status: "active",
pendingBackgroundTasks: [
{
taskId: "bg-superseded",
description: "should not land",
taskType: "local_bash",
},
],
updatedAt: afterReplacement,
},
},
],
});
assert.isFalse(supersededAttemptWrite.committed);
assert.deepEqual(supersededAttemptWrite.storedEvents, []);
yield* eventSink.write({
events: [
{
id: EventId.make("event:foundation-provider-thread-owner:replacement-completed"),
type: "run.updated",
threadId,
runId,
nodeId: rootNodeId,
providerInstanceId,
occurredAt: afterReplacement,
payload: {
...run,
activeAttemptId: replacementAttemptId,
},
},
{
id: EventId.make("event:foundation-provider-thread-owner:newer-run"),
type: "provider-thread.updated",
threadId,
driver: providerDriver,
providerInstanceId,
occurredAt: afterReplacement,
payload: {
...baseProviderThread,
lastRunOrdinal: 2,
status: "active",
pendingBackgroundTasks: [],
updatedAt: afterReplacement,
},
},
],
});
const staleOrdinalWrite = yield* eventSink.writeIfProviderThreadOwner({
providerThreadId,
runId,
activeAttemptId: replacementAttemptId,
expectedLastRunOrdinal: 1,
events: [
{
id: EventId.make("event:foundation-provider-thread-owner:stale-ordinal"),
type: "provider-thread.updated",
threadId,
driver: providerDriver,
providerInstanceId,
occurredAt: afterReplacement,
payload: baseProviderThread,
},
],
});
assert.isFalse(staleOrdinalWrite.committed);
assert.deepEqual(staleOrdinalWrite.storedEvents, []);
const projection = yield* projectionStore.getThreadProjection(threadId);
const providerThread = projection.providerThreads.find(
(candidate) => candidate.id === providerThreadId,
);
assert.isDefined(providerThread);
assert.equal(providerThread?.lastRunOrdinal, 2);
assert.equal(providerThread?.status, "active");
assert.deepEqual(providerThread?.pendingBackgroundTasks ?? [], []);
}),
);
it.effect("interrupts a running process-bound effect when it is cancelled", () =>
Effect.gen(function* () {
const outbox = yield* EffectOutboxV2;
@@ -818,6 +818,9 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
const assistantMessageId = MessageId.make("message:projection-rollback-prune:assistant");
const userTurnItemId = TurnItemId.make("turn-item:projection-rollback-prune:user");
const assistantTurnItemId = TurnItemId.make("turn-item:projection-rollback-prune:assistant");
const backgroundTurnItemId = TurnItemId.make(
"turn-item:projection-rollback-prune:background",
);
yield* projectionStore.apply({
id: EventId.make("event:projection-rollback-prune:thread-created"),
@@ -1103,6 +1106,33 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
streaming: false,
},
});
yield* projectionStore.apply({
id: EventId.make("event:projection-rollback-prune:background-item"),
type: "turn-item.updated",
threadId,
runId,
nodeId: rootNodeId,
driver,
occurredAt: now,
payload: {
id: backgroundTurnItemId,
threadId,
runId,
nodeId: rootNodeId,
providerThreadId,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 300,
status: "running",
title: "rolled back background command",
startedAt: now,
completedAt: null,
updatedAt: now,
type: "command_execution",
input: "sleep 60",
},
});
yield* projectionStore.apply({
id: EventId.make("event:projection-rollback-prune:run-rolled-back"),
type: "run.updated",
@@ -1171,8 +1201,16 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
);
assert.lengthOf(projection.providerTurns, 1);
assert.lengthOf(projection.messages, 2);
assert.lengthOf(projection.turnItems, 2);
assert.lengthOf(projection.turnItems, 3);
assert.lengthOf(projection.visibleTurnItems, 0);
// A rolled-back run's background item is abandoned, not pending. The
// shell must not report it as Waiting, or the sidebar shows Waiting for
// work nothing will ever finish.
const shell = yield* projectionStore.getShellSnapshot();
const rolledBackShellThread = shell.threads.find((entry) => entry.id === threadId);
assert.isDefined(rolledBackShellThread);
assert.deepEqual(rolledBackShellThread?.pendingBackgroundTasks ?? [], []);
}),
);
@@ -36,6 +36,7 @@ import {
isOrchestrationV2SupersededInterrupt,
isOrchestrationV2TurnItemVisible,
} from "@t3tools/shared/orchestrationV2Timeline";
import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -441,6 +442,7 @@ type ShellThreadRow = {
readonly latest_run_started_at: string | null;
readonly latest_run_completed_at: string | null;
readonly active_run_id: string | null;
readonly activity_run_status: string | null;
readonly last_error: string | null;
readonly pending_request_payload_json: string | null;
readonly latest_message_payload_json: string | null;
@@ -817,6 +819,10 @@ export function threadShellFromProjection(
projection.runs
.filter(isInterruptibleRunForShell)
.toSorted((left, right) => right.ordinal - left.ordinal)[0] ?? null;
const activityRun =
projection.runs
.filter(isActivityRunForShell)
.toSorted((left, right) => right.ordinal - left.ordinal)[0] ?? null;
const pendingRuntimeRequest =
projection.runtimeRequests
.filter((request) => request.status === "pending")
@@ -843,6 +849,13 @@ export function threadShellFromProjection(
(left, right) =>
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
)[0] ?? null;
const pendingBackgroundTasks = derivePendingBackgroundWork({
latestRun,
providerThreads: projection.providerThreads,
turnItems: projection.turnItems,
activeProviderThreadId: projection.thread.activeProviderThreadId,
runs: projection.runs,
});
return {
createdBy: projection.thread.createdBy,
creationSource: projection.thread.creationSource,
@@ -866,6 +879,7 @@ export function threadShellFromProjection(
latestRunStartedAt: latestRun?.startedAt ?? null,
latestRunCompletedAt: latestRun?.completedAt ?? null,
activeRunId: activeRun?.id ?? null,
activityRunStatus: activityRun?.status ?? null,
status: latestRun?.status ?? "idle",
lastError: providerSession?.lastError ?? null,
pendingRuntimeRequest:
@@ -889,6 +903,7 @@ export function threadShellFromProjection(
hasActionableProposedPlan: projection.plans.some(
(plan) => plan.kind === "proposed_plan" && plan.status === "active",
),
pendingBackgroundTasks: [...pendingBackgroundTasks],
itemCount: activeLocalTurnItems(projection).length,
visibleItemCount: projection.visibleTurnItems.length,
createdAt: projection.thread.createdAt,
@@ -909,6 +924,16 @@ function isInterruptibleRunForShell(run: OrchestrationV2ThreadProjection["runs"]
return run.status === "preparing" || run.status === "starting" || run.status === "running";
}
type ShellActivityRunStatus = "preparing" | "running" | "starting" | "waiting";
function isActivityRunForShell(
run: OrchestrationV2ThreadProjection["runs"][number],
): run is OrchestrationV2ThreadProjection["runs"][number] & {
readonly status: ShellActivityRunStatus;
} {
return isInterruptibleRunForShell(run) || run.status === "waiting";
}
type ShellThreadState = {
readonly thread: OrchestrationV2ThreadProjection["thread"];
readonly latestRunId: RunId | null;
@@ -917,11 +942,13 @@ type ShellThreadState = {
readonly latestRunStartedAt: DateTime.Utc | null;
readonly latestRunCompletedAt: DateTime.Utc | null;
readonly activeRunId: RunId | null;
readonly activityRunStatus: ShellActivityRunStatus | null;
readonly lastError: string | null;
readonly pendingRuntimeRequest: OrchestrationV2ThreadProjection["runtimeRequests"][number] | null;
readonly latestVisibleMessage: OrchestrationV2ConversationMessage | null;
readonly latestUserMessageAt: DateTime.Utc | null;
readonly hasActionableProposedPlan: boolean;
readonly pendingBackgroundTasks: OrchestrationV2ThreadShell["pendingBackgroundTasks"];
readonly itemCount: number;
readonly runlessItemCount: number;
readonly updatedAt: OrchestrationV2ThreadProjection["updatedAt"];
@@ -1038,6 +1065,7 @@ function shellFromState(input: {
latestRunStartedAt: input.state.latestRunStartedAt,
latestRunCompletedAt: input.state.latestRunCompletedAt,
activeRunId: input.state.activeRunId,
activityRunStatus: input.state.activityRunStatus,
status: input.state.latestRunStatus,
lastError: input.state.lastError,
pendingRuntimeRequest:
@@ -1059,6 +1087,7 @@ function shellFromState(input: {
},
latestUserMessageAt: input.state.latestUserMessageAt,
hasActionableProposedPlan: input.state.hasActionableProposedPlan,
pendingBackgroundTasks: input.state.pendingBackgroundTasks,
itemCount: input.state.itemCount,
visibleItemCount: input.visibleItemCount,
createdAt: input.state.thread.createdAt,
@@ -2242,6 +2271,14 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
ORDER BY r.ordinal DESC, r.run_id DESC
LIMIT 1
) AS active_run_id,
(
SELECT r.status
FROM orchestration_v2_projection_runs r
WHERE r.thread_id = t.thread_id
AND r.status IN ('preparing', 'starting', 'running', 'waiting')
ORDER BY r.ordinal DESC, r.run_id DESC
LIMIT 1
) AS activity_run_status,
(
SELECT json_extract(session.payload_json, '$.lastError')
FROM orchestration_v2_projection_provider_sessions session
@@ -2329,6 +2366,44 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
GROUP BY thread_id, run_id
`;
const selectShellProviderThreadRows = (threadIds?: ReadonlyArray<ThreadId>) =>
threadIds === undefined
? sql<PayloadRow & { readonly thread_id: string }>`
SELECT thread_id, payload_json
FROM orchestration_v2_projection_provider_threads
WHERE thread_id IS NOT NULL
`
: sql<PayloadRow & { readonly thread_id: string }>`
SELECT thread_id, payload_json
FROM orchestration_v2_projection_provider_threads
WHERE thread_id IN ${sql.in(threadIds)}
`;
const selectShellPendingTurnItemRows = (threadIds?: ReadonlyArray<ThreadId>) =>
threadIds === undefined
? sql<PayloadRow & { readonly thread_id: string }>`
SELECT i.thread_id, i.payload_json
FROM orchestration_v2_projection_turn_items i
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<PayloadRow & { readonly thread_id: string }>`
SELECT i.thread_id, i.payload_json
FROM orchestration_v2_projection_turn_items i
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 runMapsByThreadId = (input: {
readonly runRows: ReadonlyArray<ShellRunRow>;
readonly itemCountRows: ReadonlyArray<ShellRunItemCountRow>;
@@ -2352,13 +2427,60 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
return { runOrdinalsByThreadId, itemCountsByThreadId };
};
const pendingBackgroundDataByThreadId = (input: {
readonly providerThreadRows: ReadonlyArray<PayloadRow & { readonly thread_id: string }>;
readonly pendingTurnItemRows: ReadonlyArray<PayloadRow & { readonly thread_id: string }>;
}) =>
Effect.gen(function* () {
const providerThreadsByThreadId = new Map<
ThreadId,
Array<OrchestrationV2ThreadProjection["providerThreads"][number]>
>();
for (const row of input.providerThreadRows) {
const providerThread = yield* decodeProviderThreadPayload(row.payload_json);
const threadId =
row.thread_id.length > 0 ? ThreadId.make(row.thread_id) : providerThread.appThreadId;
if (threadId === null) {
continue;
}
const existing = providerThreadsByThreadId.get(threadId) ?? [];
existing.push(providerThread);
providerThreadsByThreadId.set(threadId, existing);
}
const pendingTurnItemsByThreadId = new Map<ThreadId, Array<OrchestrationV2TurnItem>>();
for (const row of input.pendingTurnItemRows) {
const turnItem = yield* decodeTurnItemPayload(row.payload_json);
const threadId = ThreadId.make(row.thread_id);
const existing = pendingTurnItemsByThreadId.get(threadId) ?? [];
existing.push(turnItem);
pendingTurnItemsByThreadId.set(threadId, existing);
}
return { providerThreadsByThreadId, pendingTurnItemsByThreadId };
});
const shellThreadStateFromRow = (input: {
readonly row: ShellThreadRow;
readonly runOrdinalsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;
readonly itemCountsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;
readonly providerThreadsByThreadId: ReadonlyMap<
ThreadId,
ReadonlyArray<OrchestrationV2ThreadProjection["providerThreads"][number]>
>;
readonly pendingTurnItemsByThreadId: ReadonlyMap<
ThreadId,
ReadonlyArray<OrchestrationV2TurnItem>
>;
}) =>
Effect.gen(function* () {
const { row, runOrdinalsByThreadId, itemCountsByThreadId } = input;
const {
row,
runOrdinalsByThreadId,
itemCountsByThreadId,
providerThreadsByThreadId,
pendingTurnItemsByThreadId,
} = input;
const thread = yield* decodeThreadPayload(row.payload_json);
const pendingRuntimeRequest =
row.pending_request_payload_json === null
@@ -2368,10 +2490,28 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
row.latest_message_payload_json === null
? null
: yield* decodeMessagePayload(row.latest_message_payload_json);
const latestRunId = row.latest_run_id === null ? null : RunId.make(row.latest_run_id);
const latestRunStatus = shellStatusFromStoredRunStatus(row.latest_run_status);
const pendingBackgroundTasks = [
...derivePendingBackgroundWork({
latestRun:
latestRunId === null || latestRunStatus === "idle"
? null
: {
id: latestRunId,
ordinal: 0,
status: latestRunStatus,
},
providerThreads: providerThreadsByThreadId.get(thread.id) ?? [],
turnItems: pendingTurnItemsByThreadId.get(thread.id) ?? [],
activeProviderThreadId: thread.activeProviderThreadId,
hasActiveRun: row.active_run_id !== null,
}),
];
return {
thread,
latestRunId: row.latest_run_id === null ? null : RunId.make(row.latest_run_id),
latestRunStatus: shellStatusFromStoredRunStatus(row.latest_run_status),
latestRunId,
latestRunStatus,
latestRunRequestedAt:
row.latest_run_requested_at === null
? null
@@ -2385,6 +2525,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
? null
: DateTime.makeUnsafe(row.latest_run_completed_at),
activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id),
activityRunStatus:
row.activity_run_status === "preparing" ||
row.activity_run_status === "starting" ||
row.activity_run_status === "running" ||
row.activity_run_status === "waiting"
? row.activity_run_status
: null,
lastError: row.last_error,
pendingRuntimeRequest,
latestVisibleMessage,
@@ -2393,6 +2540,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
? null
: DateTime.makeUnsafe(row.latest_user_message_at),
hasActionableProposedPlan: row.has_actionable_proposed_plan === 1,
pendingBackgroundTasks,
itemCount: row.item_count,
runlessItemCount: row.runless_item_count,
updatedAt: thread.updatedAt,
@@ -2405,7 +2553,14 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
sql
.withTransaction(
Effect.gen(function* () {
const [threadRows, runRows, itemCountRows, sequenceRows] = yield* Effect.all([
const [
threadRows,
runRows,
itemCountRows,
sequenceRows,
providerThreadRows,
pendingTurnItemRows,
] = yield* Effect.all([
selectShellThreadRows(),
selectShellRunRows(),
selectShellRunItemCounts(),
@@ -2415,15 +2570,24 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
WHERE application_event_version = 2
AND aggregate_kind = 'thread'
`,
selectShellProviderThreadRows(),
selectShellPendingTurnItemRows(),
]);
const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
runRows,
itemCountRows,
});
const { providerThreadsByThreadId, pendingTurnItemsByThreadId } =
yield* pendingBackgroundDataByThreadId({ providerThreadRows, pendingTurnItemRows });
const states = yield* Effect.forEach(threadRows, (row) =>
shellThreadStateFromRow({ row, runOrdinalsByThreadId, itemCountsByThreadId }),
shellThreadStateFromRow({
row,
runOrdinalsByThreadId,
itemCountsByThreadId,
providerThreadsByThreadId,
pendingTurnItemsByThreadId,
}),
);
const statesByThreadId = new Map(states.map((state) => [state.thread.id, state]));
@@ -2484,17 +2648,28 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
}
const threadIds = [...rowsByThreadId.keys()];
const [runRows, itemCountRows] = yield* Effect.all([
selectShellRunRows(threadIds),
selectShellRunItemCounts(threadIds),
]);
const [runRows, itemCountRows, providerThreadRows, pendingTurnItemRows] =
yield* Effect.all([
selectShellRunRows(threadIds),
selectShellRunItemCounts(threadIds),
selectShellProviderThreadRows(threadIds),
selectShellPendingTurnItemRows(threadIds),
]);
const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
runRows,
itemCountRows,
});
const { providerThreadsByThreadId, pendingTurnItemsByThreadId } =
yield* pendingBackgroundDataByThreadId({ providerThreadRows, pendingTurnItemRows });
const states = yield* Effect.forEach([...rowsByThreadId.values()], (row) =>
shellThreadStateFromRow({ row, runOrdinalsByThreadId, itemCountsByThreadId }),
shellThreadStateFromRow({
row,
runOrdinalsByThreadId,
itemCountsByThreadId,
providerThreadsByThreadId,
pendingTurnItemsByThreadId,
}),
);
const statesByThreadId = new Map(states.map((state) => [state.thread.id, state]));
const state = statesByThreadId.get(threadId);
@@ -485,6 +485,15 @@ export interface ProviderAdapterV2SessionRuntime {
* here so the session manager defers idle release while it is pending.
*/
readonly hasPendingBackgroundWork?: Effect.Effect<boolean>;
/**
* Per-provider-thread pending work for root-run ingestion stop gates. When
* present, RunExecutionService uses only this probe (never the session-wide
* hasPendingBackgroundWork) so sibling native threads cannot pin an
* unrelated root subscription open.
*/
readonly hasPendingBackgroundWorkForThread?: (
providerThread: OrchestrationV2ProviderThread,
) => Effect.Effect<boolean>;
readonly ensureThread: (
input: ProviderAdapterV2EnsureThreadInput,
) => Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapterV2Error>;
@@ -588,6 +588,25 @@ describe("ProviderContinuationService", () => {
});
});
it.effect("queues a continuation behind an active user run", () => {
return Effect.gen(function* () {
const dispatched = yield* Queue.unbounded<unknown>();
yield* Effect.gen(function* () {
const requests = yield* ProviderContinuationRequests;
yield* requests.offer(request());
const command = yield* Queue.take(dispatched);
assert.deepEqual((command as { readonly dispatchMode?: unknown }).dispatchMode, {
type: "queue_after_active",
});
}).pipe(
Effect.provide(
testLayer({ dispatched, getThreadProjection: () => Effect.succeed(projection) }),
),
Effect.scoped,
);
});
});
it.effect("drops a request invalidated before dispatch", () => {
return Effect.gen(function* () {
const dispatched = yield* Queue.unbounded<unknown>();
@@ -6,8 +6,13 @@ import {
type OrchestrationV2AppThread,
type OrchestrationV2DomainEvent,
type OrchestrationV2ProviderThread,
type OrchestrationV2Run,
type OrchestrationV2TurnItem,
ProviderDriverKind,
ProviderInstanceId,
RunAttemptId,
RunId,
TurnItemId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -28,6 +33,12 @@ import {
layer as providerEventIngestorLayer,
} from "./ProviderEventIngestor.ts";
import { makeProviderFailure } from "./ProviderFailure.ts";
import {
makeProviderEventRoutingState,
type ProviderEventRouteIdentity,
routeProviderEvent,
selectInheritedBackgroundTurnItems,
} from "./RunExecutionService.ts";
const TestDatabaseLayer = SqlitePersistenceMemory;
const TestStoresLayer = Layer.merge(eventStoreLayer, projectionStoreLayer).pipe(
@@ -233,6 +244,263 @@ layer("ProviderEventIngestorV2", (it) => {
}),
);
it.effect("persists an interrupted run's inherited terminal through the live run router", () =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const eventSink = yield* EventSinkV2;
const projectionStore = yield* ProjectionStoreV2;
const ingestor = yield* ProviderEventIngestorV2;
const idAllocator = yield* IdAllocatorV2;
const threadEvent = yield* threadCreatedEvent(now);
const priorRunId = RunId.make("run:provider-event-inherited:prior");
const currentRunId = RunId.make("run:provider-event-inherited:current");
const itemId = TurnItemId.make("turn-item:provider-event-inherited");
const providerSessionId = yield* idAllocator.allocate.providerSession({
providerInstanceId: modelSelection.instanceId,
threadId: threadEvent.threadId,
});
const providerThreadId = idAllocator.derive.providerThread({
driver: CODEX_DRIVER,
nativeThreadId: "native-thread-inherited",
});
const providerTurnId = idAllocator.derive.providerTurn({
driver: CODEX_DRIVER,
nativeTurnId: "native-turn-inherited",
});
const runningItem = {
id: itemId,
threadId: threadEvent.threadId,
runId: priorRunId,
nodeId: NodeId.make("node:provider-event-inherited"),
providerThreadId,
providerTurnId,
nativeItemRef: null,
parentItemId: null,
ordinal: 101,
status: "running",
title: "Inherited background command",
startedAt: now,
completedAt: null,
updatedAt: now,
type: "command_execution",
input: "sleep 60",
} satisfies OrchestrationV2TurnItem;
const terminalItem = {
...runningItem,
status: "completed" as const,
completedAt: now,
updatedAt: now,
};
yield* eventSink.write({ events: [threadEvent] });
yield* ingestor.ingestNormalized({
providerSessionId,
providerInstanceId: modelSelection.instanceId,
threadId: threadEvent.threadId,
runId: priorRunId,
event: { type: "turn_item.updated", driver: CODEX_DRIVER, turnItem: runningItem },
});
const identity: ProviderEventRouteIdentity = {
threadId: threadEvent.threadId,
runId: currentRunId,
attemptId: RunAttemptId.make("attempt:provider-event-inherited:current"),
providerThreadId,
};
const inheritedBackgroundTurnItems = selectInheritedBackgroundTurnItems({
threadId: threadEvent.threadId,
currentProviderThreadId: providerThreadId,
currentRunOrdinal: 2,
runs: [
{
id: priorRunId,
threadId: threadEvent.threadId,
ordinal: 1,
status: "interrupted",
} as OrchestrationV2Run,
{
id: currentRunId,
threadId: threadEvent.threadId,
ordinal: 2,
status: "running",
} as OrchestrationV2Run,
],
turnItems: [runningItem],
});
const routeState = makeProviderEventRoutingState({
identity,
inheritedBackgroundTurnItems,
providerTurnId: null,
});
const terminalEvent = {
type: "turn_item.updated",
driver: CODEX_DRIVER,
turnItem: terminalItem,
} as const;
const [accepted] = routeProviderEvent(terminalEvent, identity, routeState);
assert.isTrue(accepted);
const stored = yield* ingestor.ingestNormalized({
providerSessionId,
providerInstanceId: modelSelection.instanceId,
threadId: threadEvent.threadId,
runId: currentRunId,
event: terminalEvent,
});
const projection = yield* projectionStore.getThreadProjection(threadEvent.threadId);
const persisted = projection.turnItems.find((item) => item.id === itemId);
assert.equal(stored.length, 1);
assert.equal(stored[0]?.event.type, "turn-item.updated");
assert.equal(persisted?.runId, priorRunId);
assert.equal(persisted?.threadId, threadEvent.threadId);
assert.equal(persisted?.status, "completed");
}),
);
it.effect("persists a completed run's late background terminal exactly once", () =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const eventSink = yield* EventSinkV2;
const eventStore = yield* EventStoreV2;
const ingestor = yield* ProviderEventIngestorV2;
const idAllocator = yield* IdAllocatorV2;
const threadEvent = yield* threadCreatedEvent(now);
const priorRunId = RunId.make("run:provider-event-completed:prior");
const currentRunId = RunId.make("run:provider-event-completed:current");
const itemId = TurnItemId.make("turn-item:provider-event-completed");
const providerSessionId = yield* idAllocator.allocate.providerSession({
providerInstanceId: modelSelection.instanceId,
threadId: threadEvent.threadId,
});
const providerThreadId = idAllocator.derive.providerThread({
driver: CODEX_DRIVER,
nativeThreadId: "native-thread-completed",
});
const providerTurnId = idAllocator.derive.providerTurn({
driver: CODEX_DRIVER,
nativeTurnId: "native-turn-completed",
});
const runningItem = {
id: itemId,
threadId: threadEvent.threadId,
runId: priorRunId,
nodeId: NodeId.make("node:provider-event-completed"),
providerThreadId,
providerTurnId,
nativeItemRef: null,
parentItemId: null,
ordinal: 101,
status: "running",
title: "Completed run background command",
startedAt: now,
completedAt: null,
updatedAt: now,
type: "command_execution",
input: "sleep 60",
} satisfies OrchestrationV2TurnItem;
const terminalEvent = {
type: "turn_item.updated",
driver: CODEX_DRIVER,
turnItem: {
...runningItem,
status: "completed" as const,
completedAt: now,
updatedAt: now,
},
} as const;
yield* eventSink.write({ events: [threadEvent] });
yield* ingestor.ingestNormalized({
providerSessionId,
providerInstanceId: modelSelection.instanceId,
threadId: threadEvent.threadId,
runId: priorRunId,
event: { type: "turn_item.updated", driver: CODEX_DRIVER, turnItem: runningItem },
});
const priorIdentity: ProviderEventRouteIdentity = {
threadId: threadEvent.threadId,
runId: priorRunId,
attemptId: RunAttemptId.make("attempt:provider-event-completed:prior"),
providerThreadId,
};
const currentIdentity: ProviderEventRouteIdentity = {
threadId: threadEvent.threadId,
runId: currentRunId,
attemptId: RunAttemptId.make("attempt:provider-event-completed:current"),
providerThreadId,
};
const inheritedBackgroundTurnItems = selectInheritedBackgroundTurnItems({
threadId: threadEvent.threadId,
currentProviderThreadId: providerThreadId,
currentRunOrdinal: 2,
runs: [
{
id: priorRunId,
threadId: threadEvent.threadId,
ordinal: 1,
status: "completed",
} as OrchestrationV2Run,
{
id: currentRunId,
threadId: threadEvent.threadId,
ordinal: 2,
status: "running",
} as OrchestrationV2Run,
],
turnItems: [runningItem],
});
const routers = [
{
identity: priorIdentity,
state: makeProviderEventRoutingState({
identity: priorIdentity,
providerTurnId: providerTurnId,
}),
},
{
identity: currentIdentity,
state: makeProviderEventRoutingState({
identity: currentIdentity,
inheritedBackgroundTurnItems,
providerTurnId: null,
}),
},
];
const acceptedRouters = routers.filter(
({ identity, state }) => routeProviderEvent(terminalEvent, identity, state)[0],
);
yield* Effect.forEach(
acceptedRouters,
({ identity }) =>
ingestor.ingestNormalized({
providerSessionId,
providerInstanceId: modelSelection.instanceId,
threadId: threadEvent.threadId,
runId: identity.runId,
event: terminalEvent,
}),
{ concurrency: 1 },
);
const storedEvents = yield* eventStore
.read({ threadId: threadEvent.threadId })
.pipe(Stream.runCollect);
const storedTerminals = Array.from(storedEvents).filter(
(stored) =>
stored.event.type === "turn-item.updated" &&
stored.event.payload.id === itemId &&
stored.event.payload.status === "completed",
);
assert.equal(storedTerminals.length, 1);
assert.equal(acceptedRouters.length, 1);
assert.equal(acceptedRouters[0]?.identity.runId, priorRunId);
}),
);
it.effect("persists a failed provider terminal as one expected error item", () =>
Effect.gen(function* () {
const now = yield* DateTime.now;
@@ -6,6 +6,7 @@ import {
type OrchestrationV2Run,
ProviderInstanceId,
ProviderSessionId,
ProviderThreadId,
RawEventId,
RunAttemptId,
RunId,
@@ -81,6 +82,16 @@ export interface ProviderEventIngestorV2Shape {
readonly activeAttemptId: RunAttemptId;
readonly expectedStatus: OrchestrationV2Run["status"];
};
/**
* Atomically reject provider-thread snapshots from an attempt that no
* longer owns the run or from a run that no longer owns the thread.
*/
readonly writeIfProviderThreadOwner?: {
readonly providerThreadId: ProviderThreadId;
readonly runId: RunId;
readonly activeAttemptId: RunAttemptId;
readonly expectedLastRunOrdinal: number;
};
},
) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, ProviderEventIngestorV2Error>;
}
@@ -283,6 +294,16 @@ export const layer: Layer.Layer<ProviderEventIngestorV2, never, EventSinkV2 | Id
eventCount: events.length,
cause,
});
if (input.writeIfProviderThreadOwner !== undefined) {
const ownerResult = yield* eventSink
.writeIfProviderThreadOwner({
...(input.commandId === undefined ? {} : { commandId: input.commandId }),
...input.writeIfProviderThreadOwner,
events,
})
.pipe(Effect.mapError(mapWriteError));
return ownerResult.storedEvents;
}
if (input.writeIfRunCurrent === undefined) {
return yield* eventSink
.write({
@@ -0,0 +1,84 @@
import {
ProviderInstanceId,
RunId,
ThreadId,
TurnItemId,
type OrchestrationV2ThreadProjection,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { expect, it } from "vite-plus/test";
import * as EffectWorker from "./EffectWorker.ts";
import * as EffectOutbox from "./EffectOutbox.ts";
import * as EventSink from "./EventSink.ts";
import * as IdAllocator from "./IdAllocator.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts";
it("uses the thread provider for stale background work without provider threads", async () => {
const threadId = ThreadId.make("thread_recovery_background_no_provider_threads");
const runId = RunId.make("run_recovery_background_no_provider_threads");
const itemId = TurnItemId.make("turn_item_recovery_background_no_provider_threads");
const providerInstanceId = ProviderInstanceId.make("codex");
let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
null;
const projection = {
thread: { id: threadId, providerInstanceId },
runtimeRequests: [],
providerSessions: [],
providerThreads: [],
providerTurns: [],
runs: [{ id: runId, status: "completed", providerInstanceId }],
attempts: [],
nodes: [],
subagents: [],
messages: [],
turnItems: [
{
id: itemId,
runId: null,
nodeId: null,
providerThreadId: null,
type: "command_execution",
status: "running",
},
],
} as unknown as OrchestrationV2ThreadProjection;
const layer = ProviderRuntimeRecovery.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.mock(ProjectionStore.ProjectionStoreV2)({
getShellSnapshot: () =>
Effect.succeed({
schemaVersion: 2,
snapshotSequence: 0,
threads: [{ id: threadId }],
archivedThreads: [],
} as never),
getThreadProjection: () => Effect.succeed(projection),
}),
Layer.mock(EventSink.EventSinkV2)({
commitCommand: (input) => {
committedInput = input;
return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
},
}),
IdAllocator.layer,
Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
Layer.mock(EffectOutbox.EffectOutboxV2)({
reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
}),
),
),
);
await Effect.gen(function* () {
yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
const event = committedInput?.events.find(
(candidate) => candidate.type === "turn-item.updated",
);
expect(event?.providerInstanceId).toBe(providerInstanceId);
expect(event?.type === "turn-item.updated" ? event.payload.status : null).toBe("cancelled");
}).pipe(Effect.provide(layer), Effect.runPromise);
});
@@ -192,57 +192,114 @@ it.effect("uses the same reconciliation path to cancel runtime requests during s
}).pipe(Effect.provide(layer));
});
it.effect("preserves a waiting run while its replay-safe checkpoint capture is unsettled", () => {
const threadId = ThreadId.make("thread_waiting_checkpoint");
const runId = RunId.make("run_waiting_checkpoint");
const committed = vi.fn(() => Effect.succeed({ committed: true } as never));
const projection = {
thread: { id: threadId },
runtimeRequests: [],
providerSessions: [],
providerThreads: [],
runs: [{ id: runId, status: "waiting" }],
} as unknown as OrchestrationV2ThreadProjection;
const layer = ProviderRuntimeRecovery.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.mock(ProjectionStore.ProjectionStoreV2)({
getShellSnapshot: () =>
Effect.succeed({
schemaVersion: 2,
snapshotSequence: 0,
threads: [{ id: threadId }],
archivedThreads: [],
} as never),
getThreadProjection: () => Effect.succeed(projection),
}),
Layer.mock(EventSink.EventSinkV2)({ commitCommand: committed }),
IdAllocator.layer,
Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
Layer.mock(EffectOutbox.EffectOutboxV2)({
listByCommandId: () =>
Effect.succeed([
{
request: { type: "checkpoint.capture", runId },
status: "running",
},
] as never),
cancelUnsettled: () => Effect.succeed([]),
signalCancellations: () => Effect.void,
reconcileAfterProcessLoss: Effect.succeed({ requeued: 1, cancelled: 0 }),
}),
it.effect(
"preserves a replayable waiting run while cancelling its process-bound background work",
() => {
const threadId = ThreadId.make("thread_waiting_checkpoint");
const runId = RunId.make("run_waiting_checkpoint");
const providerThreadId = ProviderThreadId.make("provider_thread_waiting_checkpoint");
const providerInstanceId = ProviderInstanceId.make("claude");
const backgroundItemId = TurnItemId.make("turn_item_waiting_checkpoint");
let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
null;
const projection = {
thread: { id: threadId },
runtimeRequests: [],
providerSessions: [],
providerThreads: [
{
id: providerThreadId,
driver: ProviderDriverKind.make("claude"),
providerInstanceId,
status: "idle",
pendingBackgroundTasks: [
{ taskId: String(backgroundItemId), description: "Finish background task" },
],
},
],
runs: [{ id: runId, status: "waiting", providerInstanceId }],
attempts: [],
nodes: [],
subagents: [],
messages: [],
turnItems: [
{
id: backgroundItemId,
runId,
nodeId: null,
providerThreadId,
type: "command_execution",
status: "running",
},
],
} as unknown as OrchestrationV2ThreadProjection;
const layer = ProviderRuntimeRecovery.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.mock(ProjectionStore.ProjectionStoreV2)({
getShellSnapshot: () =>
Effect.succeed({
schemaVersion: 2,
snapshotSequence: 0,
threads: [{ id: threadId }],
archivedThreads: [],
} as never),
getThreadProjection: () => Effect.succeed(projection),
}),
Layer.mock(EventSink.EventSinkV2)({
commitCommand: (input) => {
committedInput = input;
return Effect.succeed({
committed: true,
cancelledEffectCount: 0,
} as never);
},
}),
IdAllocator.layer,
Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
Layer.mock(EffectOutbox.EffectOutboxV2)({
listByCommandId: () =>
Effect.succeed([
{
request: { type: "checkpoint.capture", runId },
status: "running",
},
] as never),
reconcileAfterProcessLoss: Effect.succeed({ requeued: 1, cancelled: 0 }),
}),
),
),
),
);
);
return Effect.gen(function* () {
const summary =
yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
assert.equal(summary.terminalizedRuns, 0);
assert.equal(summary.requeuedEffects, 1);
assert.equal(committed.mock.calls.length, 0);
}).pipe(Effect.provide(layer));
});
return Effect.gen(function* () {
const summary =
yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
assert.equal(summary.terminalizedRuns, 0);
assert.equal(summary.requeuedEffects, 1);
const command = committedInput;
assert.isNotNull(command);
if (command === null) return;
assert.isFalse(command.events.some((event) => event.type === "run.updated"));
assert.isTrue(
command.events.some(
(event) =>
event.type === "turn-item.updated" &&
event.payload.id === backgroundItemId &&
event.payload.status === "cancelled",
),
);
assert.isTrue(
command.events.some(
(event) =>
event.type === "provider-thread.updated" &&
event.payload.id === providerThreadId &&
event.payload.pendingBackgroundTasks?.length === 0,
),
);
}).pipe(Effect.provide(layer));
},
);
it.effect("cancels a stale waiting run when no checkpoint capture can finish it", () => {
const threadId = ThreadId.make("thread_stale_waiting");
@@ -524,3 +581,368 @@ it.effect(
}).pipe(Effect.provide(layer));
},
);
it.effect(
"clears persisted pendingBackgroundTasks and terminalizes stale background items on settled runs",
() => {
const threadId = ThreadId.make("thread_recovery_background");
const settledRunId = RunId.make("run_recovery_background_settled");
const activeRunId = RunId.make("run_recovery_background_active");
const activeAttemptId = RunAttemptId.make("attempt_recovery_background_active");
const activeRootNodeId = NodeId.make("node_recovery_background_active");
const idleProviderThreadId = ProviderThreadId.make("provider_thread_recovery_background_idle");
const activeProviderThreadId = ProviderThreadId.make(
"provider_thread_recovery_background_active",
);
const secondaryProviderThreadId = ProviderThreadId.make(
"provider_thread_recovery_background_secondary",
);
const providerSessionId = ProviderSessionId.make("provider_session_recovery_background");
const settledStaleItemId = TurnItemId.make("turn_item_recovery_background_stale");
const activeRunItemId = TurnItemId.make("turn_item_recovery_background_active");
const nullRunCommandItemId = TurnItemId.make("turn_item_recovery_background_null_run");
const nullRunSubagentItemId = TurnItemId.make("turn_item_recovery_background_null_subagent");
const claudeInstanceId = ProviderInstanceId.make("claude");
const secondaryInstanceId = ProviderInstanceId.make("claude-secondary");
const subagentInstanceId = ProviderInstanceId.make("claude-subagent");
let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
null;
const projection = {
thread: { id: threadId },
runtimeRequests: [],
providerSessions: [
{
id: providerSessionId,
driver: ProviderDriverKind.make("claude"),
providerInstanceId: claudeInstanceId,
status: "ready",
},
],
providerThreads: [
{
id: idleProviderThreadId,
driver: ProviderDriverKind.make("claude"),
// Index-0 is intentionally a different instance so misattribution
// to providerThreads[0] fails the assertions below.
providerInstanceId: claudeInstanceId,
status: "idle",
pendingBackgroundTasks: [{ taskId: "bg-settled", description: "sleep 30" }],
},
{
id: activeProviderThreadId,
driver: ProviderDriverKind.make("claude"),
providerInstanceId: claudeInstanceId,
status: "active",
pendingBackgroundTasks: [{ taskId: "bg-active", description: "npm test" }],
},
{
id: secondaryProviderThreadId,
driver: ProviderDriverKind.make("claude"),
providerInstanceId: secondaryInstanceId,
status: "idle",
pendingBackgroundTasks: [],
},
],
providerTurns: [],
runs: [
{
id: settledRunId,
status: "completed",
providerInstanceId: claudeInstanceId,
},
{
id: activeRunId,
status: "running",
providerInstanceId: claudeInstanceId,
},
],
attempts: [
{
id: activeAttemptId,
runId: activeRunId,
rootNodeId: activeRootNodeId,
status: "running",
},
],
nodes: [{ id: activeRootNodeId, runId: activeRunId, status: "running" }],
subagents: [],
messages: [],
turnItems: [
{
id: settledStaleItemId,
runId: settledRunId,
nodeId: null,
providerThreadId: idleProviderThreadId,
type: "command_execution",
status: "running",
},
{
id: activeRunItemId,
runId: activeRunId,
nodeId: activeRootNodeId,
providerThreadId: activeProviderThreadId,
type: "dynamic_tool",
status: "running",
},
{
// Missing run: must attribute via providerThreadId, not index 0.
id: nullRunCommandItemId,
runId: null,
nodeId: null,
providerThreadId: secondaryProviderThreadId,
type: "command_execution",
status: "running",
},
{
// Missing run with a real matching provider thread whose instance
// differs from the subagent's own: own providerInstanceId must win.
id: nullRunSubagentItemId,
runId: null,
nodeId: null,
providerThreadId: secondaryProviderThreadId,
type: "subagent",
status: "running",
providerInstanceId: subagentInstanceId,
},
],
} as unknown as OrchestrationV2ThreadProjection;
const layer = ProviderRuntimeRecovery.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.mock(ProjectionStore.ProjectionStoreV2)({
getShellSnapshot: () =>
Effect.succeed({
schemaVersion: 2,
snapshotSequence: 0,
threads: [{ id: threadId }],
archivedThreads: [],
} as never),
getThreadProjection: () => Effect.succeed(projection),
}),
Layer.mock(EventSink.EventSinkV2)({
commitCommand: (input) => {
committedInput = input;
return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
},
}),
IdAllocator.layer,
Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
Layer.mock(EffectOutbox.EffectOutboxV2)({
listByCommandId: () => Effect.succeed([]),
reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
}),
),
),
);
return Effect.gen(function* () {
const summary =
yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
assert.equal(summary.terminalizedRuns, 1);
const events = committedInput?.events ?? [];
const turnItemCancels = events.filter(
(event) => event.type === "turn-item.updated" && event.payload.status === "cancelled",
);
// Active-run item + settled-run stale + null-run command + null-run subagent.
assert.equal(turnItemCancels.length, 4);
assert.deepEqual(
turnItemCancels
.map((event) => event.type === "turn-item.updated" && event.payload.id)
.sort(),
[activeRunItemId, nullRunCommandItemId, nullRunSubagentItemId, settledStaleItemId].sort(),
);
const cancelById = (id: TurnItemId) =>
turnItemCancels.find(
(event) => event.type === "turn-item.updated" && event.payload.id === id,
);
assert.equal(cancelById(nullRunCommandItemId)?.providerInstanceId, secondaryInstanceId);
// Subagent own instance wins over the matching thread's secondary instance.
assert.notEqual(subagentInstanceId, secondaryInstanceId);
assert.equal(cancelById(nullRunSubagentItemId)?.providerInstanceId, subagentInstanceId);
// Settled-run item still prefers the run's provider instance when present.
assert.equal(cancelById(settledStaleItemId)?.providerInstanceId, claudeInstanceId);
const providerThreadEvents = events.filter(
(event) => event.type === "provider-thread.updated",
);
// Only threads with active status or nonempty rosters are rewritten.
assert.equal(providerThreadEvents.length, 2);
for (const event of providerThreadEvents) {
if (event.type !== "provider-thread.updated") continue;
assert.deepEqual(event.payload.pendingBackgroundTasks ?? [], []);
}
const idleThreadEvent = providerThreadEvents.find(
(event) =>
event.type === "provider-thread.updated" && event.payload.id === idleProviderThreadId,
);
assert.equal(
idleThreadEvent?.type === "provider-thread.updated" ? idleThreadEvent.payload.status : null,
"idle",
);
const activeThreadEvent = providerThreadEvents.find(
(event) =>
event.type === "provider-thread.updated" && event.payload.id === activeProviderThreadId,
);
assert.equal(
activeThreadEvent?.type === "provider-thread.updated"
? activeThreadEvent.payload.status
: null,
"idle",
);
}).pipe(Effect.provide(layer));
},
);
it.effect(
"terminalizes the linked subagent and node for a stale subagent item on a settled run",
() => {
const threadId = ThreadId.make("thread_recovery_subagent");
const settledRunId = RunId.make("run_recovery_subagent_settled");
const providerThreadId = ProviderThreadId.make("provider_thread_recovery_subagent");
const staleSubagentNodeId = NodeId.make("node_recovery_subagent_stale");
const doneSubagentNodeId = NodeId.make("node_recovery_subagent_done");
const staleItemId = TurnItemId.make("turn_item_recovery_subagent_stale");
const doneItemId = TurnItemId.make("turn_item_recovery_subagent_done");
const claudeInstanceId = ProviderInstanceId.make("claude");
let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
null;
const projection = {
thread: { id: threadId },
runtimeRequests: [],
providerSessions: [],
providerThreads: [
{
id: providerThreadId,
driver: ProviderDriverKind.make("claude"),
providerInstanceId: claudeInstanceId,
status: "idle",
pendingBackgroundTasks: [],
},
],
providerTurns: [],
// Settled run: the stale-item loop owns it, not the nonterminal loop.
runs: [{ id: settledRunId, status: "completed", providerInstanceId: claudeInstanceId }],
attempts: [],
nodes: [
{ id: staleSubagentNodeId, runId: settledRunId, status: "running" },
{ id: doneSubagentNodeId, runId: settledRunId, status: "completed" },
],
subagents: [
{
id: staleSubagentNodeId,
runId: settledRunId,
driver: ProviderDriverKind.make("claude"),
providerInstanceId: claudeInstanceId,
status: "running",
},
{
// Already finished with a real result: must never be overwritten.
id: doneSubagentNodeId,
runId: settledRunId,
driver: ProviderDriverKind.make("claude"),
providerInstanceId: claudeInstanceId,
status: "completed",
result: "done",
},
],
messages: [],
turnItems: [
{
id: staleItemId,
runId: settledRunId,
nodeId: staleSubagentNodeId,
providerThreadId,
type: "subagent",
status: "running",
subagentId: staleSubagentNodeId,
providerInstanceId: claudeInstanceId,
},
{
id: doneItemId,
runId: settledRunId,
nodeId: doneSubagentNodeId,
providerThreadId,
type: "subagent",
status: "completed",
subagentId: doneSubagentNodeId,
providerInstanceId: claudeInstanceId,
},
],
} as unknown as OrchestrationV2ThreadProjection;
const layer = ProviderRuntimeRecovery.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.mock(ProjectionStore.ProjectionStoreV2)({
getShellSnapshot: () =>
Effect.succeed({
schemaVersion: 2,
snapshotSequence: 0,
threads: [{ id: threadId }],
archivedThreads: [],
} as never),
getThreadProjection: () => Effect.succeed(projection),
}),
Layer.mock(EventSink.EventSinkV2)({
commitCommand: (input) => {
committedInput = input;
return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
},
}),
IdAllocator.layer,
Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.succeed(false) }),
Layer.mock(EffectOutbox.EffectOutboxV2)({
listByCommandId: () => Effect.succeed([]),
reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
}),
),
),
);
return Effect.gen(function* () {
yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
const events = committedInput?.events ?? [];
// Only the nonterminal subagent item is cancelled.
const turnItemCancels = events.filter(
(event) => event.type === "turn-item.updated" && event.payload.status === "cancelled",
);
assert.equal(turnItemCancels.length, 1);
// The linked subagent entity is terminalized alongside its turn item.
const subagentCancels = events.filter((event) => event.type === "subagent.updated");
assert.equal(subagentCancels.length, 1);
const subagentCancel = subagentCancels[0];
assert.equal(
subagentCancel?.type === "subagent.updated" ? subagentCancel.payload.id : null,
staleSubagentNodeId,
);
assert.equal(
subagentCancel?.type === "subagent.updated" ? subagentCancel.payload.status : null,
"cancelled",
);
// So is its execution node, which no live process can terminalize.
const nodeCancels = events.filter((event) => event.type === "node.updated");
assert.equal(nodeCancels.length, 1);
const nodeCancel = nodeCancels[0];
assert.equal(
nodeCancel?.type === "node.updated" ? nodeCancel.payload.id : null,
staleSubagentNodeId,
);
// The already-completed subagent and node are left untouched.
assert.isFalse(
events.some(
(event) => event.type === "subagent.updated" && event.payload.id === doneSubagentNodeId,
),
);
assert.isFalse(
events.some(
(event) => event.type === "node.updated" && event.payload.id === doneSubagentNodeId,
),
);
}).pipe(Effect.provide(layer));
},
);
@@ -69,6 +69,58 @@ function nonterminalRuns(projection: OrchestrationV2ThreadProjection) {
});
}
function isBackgroundCapableTurnItemType(type: string): boolean {
return type === "command_execution" || type === "dynamic_tool" || type === "subagent";
}
function isNonterminalTurnItemStatus(status: string): boolean {
return status === "pending" || status === "running" || status === "waiting";
}
function isNonterminalSubagentStatus(status: string): boolean {
return status === "pending" || status === "running" || status === "waiting";
}
function isNonterminalNodeStatus(status: string): boolean {
return status === "pending" || status === "running" || status === "waiting";
}
function providerThreadHasPendingBackgroundTasks(
providerThread: OrchestrationV2ThreadProjection["providerThreads"][number],
): boolean {
return (providerThread.pendingBackgroundTasks?.length ?? 0) > 0;
}
/**
* Resolve providerInstanceId for a stale background-capable turn item whose
* run is missing/null (or not found). Prefer an existing run, then a subagent
* item's own instance id, then the item's provider thread, then a last-resort
* first provider thread, then the thread's selected provider.
*/
function resolveStaleBackgroundItemProviderInstanceId(
item: OrchestrationV2ThreadProjection["turnItems"][number],
projection: OrchestrationV2ThreadProjection,
): OrchestrationV2ThreadProjection["thread"]["providerInstanceId"] {
if (item.runId !== null) {
const run = projection.runs.find((candidate) => candidate.id === item.runId);
if (run !== undefined) {
return run.providerInstanceId;
}
}
if (item.type === "subagent") {
return item.providerInstanceId;
}
if (item.providerThreadId !== null && item.providerThreadId !== undefined) {
const providerThread = projection.providerThreads.find(
(candidate) => candidate.id === item.providerThreadId,
);
if (providerThread !== undefined) {
return providerThread.providerInstanceId;
}
}
return projection.providerThreads[0]?.providerInstanceId ?? projection.thread.providerInstanceId;
}
export const make = Effect.gen(function* () {
const projections = yield* ProjectionStore.ProjectionStoreV2;
const eventSink = yield* EventSink.EventSinkV2;
@@ -253,9 +305,82 @@ export const make = Effect.gen(function* () {
});
}
}
for (const providerThread of projection.providerThreads.filter(
(candidate) => candidate.status === "active",
)) {
// Process loss also orphans background-capable turn items on already-
// settled runs (e.g. post-settle Waiting work). Skip items already
// cancelled above for recovered nonterminal runs to avoid duplicate
// cancellation events.
const recoveredNonterminalRunIds = new Set(runs.map((run) => run.id));
for (const item of projection.turnItems ?? []) {
if (item.runId !== null && recoveredNonterminalRunIds.has(item.runId)) {
continue;
}
if (!isBackgroundCapableTurnItemType(item.type)) {
continue;
}
if (!isNonterminalTurnItemStatus(item.status)) {
continue;
}
const providerInstanceId = resolveStaleBackgroundItemProviderInstanceId(item, projection);
events.push({
id: yield* allocateEventId(),
type: "turn-item.updated",
threadId: projection.thread.id,
...(item.runId === null ? {} : { runId: item.runId }),
...(item.nodeId === null || item.nodeId === undefined ? {} : { nodeId: item.nodeId }),
providerInstanceId,
occurredAt: now,
payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
});
if (item.type !== "subagent") {
continue;
}
// Cancelling only the turn item would leave the linked subagent entity
// and its execution node non-terminal forever, since the dead provider
// process can no longer emit their terminal events. Match the exact
// linked ids so a subagent that already finished is never overwritten.
const staleSubagent = projection.subagents.find(
(candidate) =>
candidate.id === item.subagentId && isNonterminalSubagentStatus(candidate.status),
);
if (staleSubagent !== undefined) {
events.push({
id: yield* allocateEventId(),
type: "subagent.updated",
threadId: projection.thread.id,
...(item.runId === null ? {} : { runId: item.runId }),
nodeId: staleSubagent.id,
driver: staleSubagent.driver,
providerInstanceId: staleSubagent.providerInstanceId,
occurredAt: now,
payload: { ...staleSubagent, status: "cancelled", completedAt: now, updatedAt: now },
});
}
const staleSubagentNode = projection.nodes.find(
(candidate) =>
candidate.id === item.subagentId && isNonterminalNodeStatus(candidate.status),
);
if (staleSubagentNode !== undefined) {
events.push({
id: yield* allocateEventId(),
type: "node.updated",
threadId: projection.thread.id,
...(item.runId === null ? {} : { runId: item.runId }),
nodeId: staleSubagentNode.id,
providerInstanceId,
occurredAt: now,
payload: { ...staleSubagentNode, status: "cancelled", completedAt: now },
});
}
}
// All provider processes are gone on startup/shutdown: clear any
// persisted Waiting roster (including idle threads from settled roots)
// and idle active threads without resurrecting active status.
for (const providerThread of projection.providerThreads ?? []) {
const needsIdle = providerThread.status === "active";
const needsRosterClear = providerThreadHasPendingBackgroundTasks(providerThread);
if (!needsIdle && !needsRosterClear) {
continue;
}
events.push({
id: yield* allocateEventId(),
type: "provider-thread.updated",
@@ -263,7 +388,12 @@ export const make = Effect.gen(function* () {
driver: providerThread.driver,
providerInstanceId: providerThread.providerInstanceId,
occurredAt: now,
payload: { ...providerThread, status: "idle", updatedAt: now },
payload: {
...providerThread,
status: needsIdle ? "idle" : providerThread.status,
pendingBackgroundTasks: [],
updatedAt: now,
},
});
}
for (const session of projection.providerSessions.filter(
@@ -0,0 +1,103 @@
import { expect, it, vi } from "vite-plus/test";
import {
CheckpointScopeId,
MessageId,
NodeId,
ProviderSessionId,
ProviderThreadId,
RunAttemptId,
RunId,
ThreadId,
type OrchestrationV2ThreadProjection,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ContextHandoffService from "./ContextHandoffService.ts";
import * as EventSink from "./EventSink.ts";
import * as IdAllocator from "./IdAllocator.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
import * as ProviderSessionManager from "./ProviderSessionManager.ts";
import * as ProviderTurnStart from "./ProviderTurnStartService.ts";
import * as RunExecutionService from "./RunExecutionService.ts";
import * as RuntimePolicy from "./RuntimePolicy.ts";
it("does not commit running state when inherited background routing cannot be read", async () => {
const threadId = ThreadId.make("thread_provider_turn_start_projection_failure");
const runId = RunId.make("run_provider_turn_start_projection_failure");
const attemptId = RunAttemptId.make("attempt_provider_turn_start_projection_failure");
const rootNodeId = NodeId.make("node_provider_turn_start_projection_failure");
const providerThreadId = ProviderThreadId.make(
"provider_thread_provider_turn_start_projection_failure",
);
const providerSessionId = ProviderSessionId.make(
"provider_session_provider_turn_start_projection_failure",
);
const messageId = MessageId.make("message_provider_turn_start_projection_failure");
const checkpointScopeId = CheckpointScopeId.make(
"checkpoint_scope_provider_turn_start_projection_failure",
);
const projection = {
thread: { id: threadId },
runs: [
{
id: runId,
status: "starting",
rootNodeId,
activeAttemptId: attemptId,
providerThreadId,
userMessageId: messageId,
ordinal: 2,
},
],
nodes: [{ id: rootNodeId, checkpointScopeId }],
attempts: [{ id: attemptId }],
providerThreads: [{ id: providerThreadId, providerSessionId }],
messages: [{ id: messageId }],
checkpointScopes: [{ id: checkpointScopeId }],
contextHandoffs: [],
contextTransfers: [],
turnItems: [],
} as unknown as OrchestrationV2ThreadProjection;
let projectionReadCount = 0;
const writeIfRunCurrent = vi.fn(() =>
Effect.succeed({ committed: true, storedEvents: [] } as never),
);
const startRootRun = vi.fn(() => Effect.void);
const layer = ProviderTurnStart.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}),
Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }),
IdAllocator.layer,
Layer.mock(ProjectionStore.ProjectionStoreV2)({
getThreadProjection: () => {
projectionReadCount += 1;
return projectionReadCount === 1
? Effect.succeed(projection)
: Effect.fail(
new ProjectionStore.ProjectionStoreReadError({
threadId,
cause: "simulated inherited-background projection failure",
}),
);
},
}),
Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}),
Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }),
Layer.mock(RuntimePolicy.RuntimePolicyV2)({}),
),
),
);
await Effect.gen(function* () {
const error = yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2)
.start({ threadId, runId })
.pipe(Effect.flip);
expect(error._tag).toBe("ProviderTurnStartError");
expect(projectionReadCount).toBe(2);
expect(writeIfRunCurrent).not.toHaveBeenCalled();
expect(startRootRun).not.toHaveBeenCalled();
}).pipe(Effect.provide(layer), Effect.runPromise);
});
@@ -22,7 +22,11 @@ import {
import { IdAllocatorV2 } from "./IdAllocator.ts";
import { ProjectionStoreV2 } from "./ProjectionStore.ts";
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
import { canRouteRelatedSubagent, RunExecutionServiceV2 } from "./RunExecutionService.ts";
import {
canRouteRelatedSubagent,
RunExecutionServiceV2,
selectInheritedBackgroundTurnItems,
} from "./RunExecutionService.ts";
import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
export class ProviderTurnStartError extends Schema.TaggedErrorClass<ProviderTurnStartError>()(
@@ -124,6 +128,19 @@ export const layer: Layer.Layer<
cause: `Run ${runId} is missing its execution projection state.`,
});
}
const selectInheritedBackgroundItems = (
current: typeof projection,
): ReturnType<typeof selectInheritedBackgroundTurnItems> =>
selectInheritedBackgroundTurnItems({
threadId: current.thread.id,
currentProviderThreadId: providerThread.id,
currentRunOrdinal: run.ordinal,
runs: current.runs,
turnItems: current.turnItems,
});
const inheritedBackgroundTurnItems = yield* projectionStore
.getThreadProjection(projection.thread.id)
.pipe(Effect.map(selectInheritedBackgroundItems));
const providerSessionId = providerThread.providerSessionId;
const isCurrentAttemptInStatus = (
expectedStatus: OrchestrationV2Run["status"],
@@ -417,6 +434,11 @@ export const layer: Layer.Layer<
providerThread: runningProviderThread,
attempt: runningAttempt,
attemptId: attempt.id,
loadInheritedBackgroundTurnItems: () =>
projectionStore.getThreadProjection(projection.thread.id).pipe(
Effect.map(selectInheritedBackgroundItems),
Effect.catchCause(() => Effect.succeed(inheritedBackgroundTurnItems)),
),
relatedThreadIds: routableSubagents.flatMap((subagent) =>
subagent.childThreadId === null ? [] : [subagent.childThreadId],
),
File diff suppressed because it is too large. Load diff
@@ -53,6 +53,7 @@ export interface ProviderEventRoutingState {
readonly ownedThreadIds: ReadonlySet<ThreadId>;
readonly ownedProviderThreadIds: ReadonlySet<ProviderThreadId>;
readonly ownedProviderTurnIds: ReadonlySet<ProviderTurnId>;
readonly inheritedBackgroundTurnItems: ReadonlyMap<TurnItemId, OrchestrationV2Run["id"]>;
readonly rootProviderTurnId: ProviderTurnId | null;
}
@@ -63,6 +64,11 @@ export interface ProviderEventRouteIdentity {
readonly providerThreadId: ProviderThreadId;
}
export interface InheritedBackgroundTurnItemRoute {
readonly id: TurnItemId;
readonly runId: OrchestrationV2Run["id"];
}
type ProviderTerminalEvent = Extract<ProviderAdapterV2Event, { readonly type: "turn.terminal" }>;
function isTerminalProviderTurnStatus(status: OrchestrationV2ProviderTurn["status"]): boolean {
@@ -102,6 +108,46 @@ function isTerminalTurnItemStatus(status: OrchestrationV2TurnItem["status"]): bo
);
}
function isSettledRunEligibleForInheritedBackground(status: OrchestrationV2Run["status"]): boolean {
return status === "interrupted" || status === "failed" || status === "cancelled";
}
/**
* Transfer delivery permission for exact live background items whose original
* run no longer has a subscriber. Provider sessions are runtime containers and
* can host multiple provider threads, so the durable provider-thread lineage is
* the discriminator. Completed, rolled-back, and already-terminal items remain
* excluded.
*/
export function selectInheritedBackgroundTurnItems(input: {
readonly threadId: ThreadId;
readonly currentProviderThreadId: ProviderThreadId;
readonly currentRunOrdinal: number;
readonly runs: ReadonlyArray<OrchestrationV2Run>;
readonly turnItems: ReadonlyArray<OrchestrationV2TurnItem>;
}): ReadonlyArray<InheritedBackgroundTurnItemRoute> {
const settledPriorRunIds = new Set(
input.runs
.filter(
(run) =>
run.threadId === input.threadId &&
run.ordinal < input.currentRunOrdinal &&
isSettledRunEligibleForInheritedBackground(run.status),
)
.map((run) => run.id),
);
return input.turnItems.flatMap((turnItem) =>
turnItem.threadId === input.threadId &&
turnItem.providerThreadId === input.currentProviderThreadId &&
turnItem.runId !== null &&
settledPriorRunIds.has(turnItem.runId) &&
backgroundCapableTurnItemTypes.has(turnItem.type) &&
!isTerminalTurnItemStatus(turnItem.status)
? [{ id: turnItem.id, runId: turnItem.runId }]
: [],
);
}
type SubagentTurnItem = Extract<OrchestrationV2TurnItem, { readonly type: "subagent" }>;
type OpenRunOwnedSubagentProjection = {
@@ -274,6 +320,7 @@ export function finalProviderThreadStatus(
export function makeProviderEventRoutingState(input: {
readonly identity: ProviderEventRouteIdentity;
readonly inheritedBackgroundTurnItems?: ReadonlyArray<InheritedBackgroundTurnItemRoute>;
readonly providerTurnId: ProviderTurnId | null;
readonly relatedThreadIds?: ReadonlyArray<ThreadId>;
readonly relatedProviderThreadIds?: ReadonlyArray<ProviderThreadId>;
@@ -286,6 +333,9 @@ export function makeProviderEventRoutingState(input: {
]),
ownedProviderTurnIds:
input.providerTurnId === null ? new Set() : new Set([input.providerTurnId]),
inheritedBackgroundTurnItems: new Map(
(input.inheritedBackgroundTurnItems ?? []).map((item) => [item.id, item.runId]),
),
rootProviderTurnId: input.providerTurnId,
};
}
@@ -363,8 +413,28 @@ export function routeProviderEvent(
return [ownsRun(event.subagent.runId) || ownsChildThread(event.subagent.threadId), state];
case "message.updated":
return [ownsRun(event.message.runId) || ownsChildThread(event.message.threadId), state];
case "turn_item.updated":
return [ownsRun(event.turnItem.runId) || ownsChildThread(event.turnItem.threadId), state];
case "turn_item.updated": {
if (ownsRun(event.turnItem.runId) || ownsChildThread(event.turnItem.threadId)) {
return [true, state];
}
const inheritedRunId = state.inheritedBackgroundTurnItems.get(event.turnItem.id);
// Preserve the item's original ownership while allowing the one live run
// to deliver an exact carryover identity selected from the projection.
const isInheritedBackgroundItem =
event.turnItem.threadId === input.threadId &&
event.turnItem.runId !== null &&
event.turnItem.runId === inheritedRunId &&
backgroundCapableTurnItemTypes.has(event.turnItem.type);
if (!isInheritedBackgroundItem) {
return [false, state];
}
if (!isTerminalTurnItemStatus(event.turnItem.status)) {
return [true, state];
}
const inheritedBackgroundTurnItems = new Map(state.inheritedBackgroundTurnItems);
inheritedBackgroundTurnItems.delete(event.turnItem.id);
return [true, { ...state, inheritedBackgroundTurnItems }];
}
case "plan.updated":
return [ownsRun(event.plan.runId) || ownsChildThread(event.plan.threadId), state];
case "runtime_request.updated":
@@ -428,6 +498,10 @@ export interface RunExecutionServiceV2StartRootRunInput {
readonly attempt: OrchestrationV2RunAttempt;
readonly attemptId: RunAttemptId;
readonly providerTurnOrdinal: number;
readonly loadInheritedBackgroundTurnItems?: () => Effect.Effect<
ReadonlyArray<InheritedBackgroundTurnItemRoute>,
unknown
>;
readonly relatedThreadIds?: ReadonlyArray<ThreadId>;
readonly relatedProviderThreadIds?: ReadonlyArray<ProviderThreadId>;
readonly shouldStartProviderTurn?: () => Effect.Effect<boolean, never>;
@@ -765,9 +839,30 @@ export const layer: Layer.Layer<
attemptId: input.attempt.id,
providerThreadId: input.providerThread.id,
};
const eventSubscription =
input.session.subscribeEvents === undefined
? { events: input.session.events, close: Effect.void }
: yield* input.session.subscribeEvents;
const inheritedBackgroundTurnItems = yield* (
input.loadInheritedBackgroundTurnItems?.() ?? Effect.succeed([])
).pipe(
Effect.onError(() => eventSubscription.close),
Effect.mapError(
(cause) =>
new RunExecutionStartError({
commandId: input.commandId,
runId: input.run.id,
cause,
}),
),
);
const inheritedBackgroundTurnItemsById = new Map(
inheritedBackgroundTurnItems.map((item) => [item.id, item.runId]),
);
const eventRouting = yield* Ref.make<ProviderEventRoutingState>(
makeProviderEventRoutingState({
identity: routeIdentity,
inheritedBackgroundTurnItems,
providerTurnId: input.attempt.providerTurnId,
...(input.relatedThreadIds === undefined
? {}
@@ -779,11 +874,12 @@ export const layer: Layer.Layer<
);
const rootTerminalSeen = yield* Ref.make(false);
const rootRunFinalized = yield* Ref.make(false);
const providerThreadOwnerLost = yield* Ref.make(false);
const activeChildProviderTurns = yield* Ref.make<ReadonlySet<ProviderTurnId>>(new Set());
const activeChildSubagents = yield* Ref.make<ReadonlySet<NodeId>>(new Set());
const activeBackgroundTurnItems = yield* Ref.make<
ReadonlySet<OrchestrationV2TurnItem["id"]>
>(new Set());
>(new Set(inheritedBackgroundTurnItemsById.keys()));
const openRunOwnedSubagents = yield* Ref.make(emptyOpenRunOwnedSubagentProjection());
const finalizeRootRun = (terminal: ProviderTerminalEvent) =>
Effect.gen(function* () {
@@ -895,9 +991,15 @@ export const layer: Layer.Layer<
const belongsToOwnedChildThread =
event.turnItem.threadId !== input.run.threadId &&
routing.ownedThreadIds.has(event.turnItem.threadId);
const belongsToInheritedBackgroundItem =
event.turnItem.threadId === input.run.threadId &&
event.turnItem.runId !== null &&
inheritedBackgroundTurnItemsById.get(event.turnItem.id) === event.turnItem.runId;
if (
backgroundCapableTurnItemTypes.has(event.turnItem.type) &&
(belongsToRootRun || belongsToOwnedChildThread)
(belongsToRootRun ||
belongsToOwnedChildThread ||
belongsToInheritedBackgroundItem)
) {
yield* Ref.update(activeBackgroundTurnItems, (current) => {
const next = new Set(current);
@@ -940,6 +1042,7 @@ export const layer: Layer.Layer<
return false;
}
const terminal = yield* Ref.get(terminalEvent);
// Non-completed terminals drop background tracking immediately.
if (terminal !== null && terminal.status !== "completed") {
return true;
}
@@ -956,16 +1059,40 @@ export const layer: Layer.Layer<
// non-terminal, so their late completion events reach the
// projection (stuck-spinner fix). Only for completed runs:
// interrupted/failed turns intentionally drop background tracking
// rather than pinning the stream open. Assumes adapters emit an
// item's non-terminal event before the root terminal; an item
// first seen after the terminal is not pinned.
// rather than pinning the stream open. Newly owned items depend on
// adapters emitting a non-terminal event before the root terminal.
// Exact inherited items are seeded from their selected durable rows.
//
// Owner loss (a newer run claimed lastRunOrdinal) must not close
// this stream while these sets are non-empty: turn_item.updated
// writes are not ownership-gated, so late completions still land.
const backgroundItems = yield* Ref.get(activeBackgroundTurnItems);
return backgroundItems.size === 0;
if (backgroundItems.size > 0) {
return false;
}
// Owner loss means do not hold the stream open solely for the
// roster probe; once background sets are empty, release.
if (yield* Ref.get(providerThreadOwnerLost)) {
return true;
}
// Claude background Bash has no turn-item projection. Keep the
// stream open while this root's provider thread still reports
// pending roster work so late empty updates can clear Waiting.
// Use only the thread-scoped probe: session-wide pending work
// (siblings, wake buffers, session subagents) must not pin this
// root subscription. Session idle release still uses
// hasPendingBackgroundWork via ProviderSessionManager.
const latestProviderThreadSnapshot = yield* Ref.get(latestProviderThread);
if (input.session.hasPendingBackgroundWorkForThread !== undefined) {
const hasPendingWork = yield* input.session
.hasPendingBackgroundWorkForThread(latestProviderThreadSnapshot)
.pipe(Effect.catchCause(() => Effect.succeed(false)));
if (hasPendingWork) {
return false;
}
}
return true;
});
const eventSubscription =
input.session.subscribeEvents === undefined
? { events: input.session.events, close: Effect.void }
: yield* input.session.subscribeEvents;
const providerEventFiber = yield* eventSubscription.events.pipe(
Stream.filterEffect((event) =>
Ref.modify(eventRouting, (state) => routeProviderEvent(event, routeIdentity, state)),
@@ -975,6 +1102,15 @@ export const layer: Layer.Layer<
let storedEventCount = 0;
const shouldDeliver = shouldDeliverProviderEvent(event, assistantStreamingEnabled);
if (shouldDeliver) {
// Root provider_thread.updated always uses an ownership gate:
// pre-terminal writeIfRunCurrent (attempt still running), or
// post-terminal writeIfProviderThreadOwner so late roster
// clears still land while this attempt owns the run and this
// run owns lastRunOrdinal.
const rootTerminalAlreadySeen = yield* Ref.get(rootTerminalSeen);
const isRootProviderThreadUpdate =
event.type === "provider_thread.updated" &&
event.providerThread.id === input.providerThread.id;
const storedEvents = yield* providerEventIngestor.ingestNormalized({
providerSessionId: input.providerSessionId,
providerInstanceId: input.run.providerInstanceId,
@@ -982,18 +1118,35 @@ export const layer: Layer.Layer<
runId: input.run.id,
nodeId: input.rootNode.id,
event,
...(event.type === "provider_thread.updated" &&
event.providerThread.id === input.providerThread.id
? {
writeIfRunCurrent: {
runId: input.run.id,
activeAttemptId: input.attempt.id,
expectedStatus: "running" as const,
},
}
...(isRootProviderThreadUpdate
? rootTerminalAlreadySeen
? {
writeIfProviderThreadOwner: {
providerThreadId: input.providerThread.id,
runId: input.run.id,
activeAttemptId: input.attempt.id,
expectedLastRunOrdinal: input.run.ordinal,
},
}
: {
writeIfRunCurrent: {
runId: input.run.id,
activeAttemptId: input.attempt.id,
expectedStatus: "running" as const,
},
}
: {}),
});
storedEventCount = storedEvents.length;
if (
isRootProviderThreadUpdate &&
rootTerminalAlreadySeen &&
storedEventCount === 0
) {
// Ownership lost (or thread row missing). Stop pinning the
// stream on this run's background probe.
yield* Ref.set(providerThreadOwnerLost, true);
}
}
if (event.type === "provider_thread.updated") {
if (event.providerThread.id === input.providerThread.id && storedEventCount > 0) {
@@ -29,44 +29,56 @@ type ProtocolReplayEntry = Extract<
{ readonly type: "expect_outbound" | "emit_inbound" }
>;
const CODEX_REPLAY_FIXTURES = ORCHESTRATOR_REPLAY_FIXTURES.flatMap((fixture) =>
interface CodexReplayFixtureRegistration {
readonly registrationScenario: string;
readonly recordedScenario: string;
readonly transcriptFile: URL;
}
const CODEX_REPLAY_FIXTURE_REGISTRATIONS = ORCHESTRATOR_REPLAY_FIXTURES.flatMap((fixture) =>
fixture.providers
.filter((provider) => provider.driver === "codex")
.map((provider) => ({
scenario: fixture.name,
registrationScenario: fixture.name,
recordedScenario: provider.recordedScenario ?? fixture.name,
transcriptFile: provider.transcriptFile,
})),
).concat([
{
scenario: "provider_thread_resume",
registrationScenario: "provider_thread_resume",
recordedScenario: "provider_thread_resume",
transcriptFile: new URL(
"./fixtures/provider_thread_resume/codex_transcript.ndjson",
import.meta.url,
),
},
{
scenario: "thread_fork_native_continue",
registrationScenario: "thread_fork_native_continue",
recordedScenario: "thread_fork_native_continue",
transcriptFile: new URL(
"./fixtures/thread_fork_native_continue/codex_transcript.ndjson",
import.meta.url,
),
},
{
scenario: "thread_fork_native_siblings",
registrationScenario: "thread_fork_native_siblings",
recordedScenario: "thread_fork_native_siblings",
transcriptFile: new URL(
"./fixtures/thread_fork_native_siblings/codex_transcript.ndjson",
import.meta.url,
),
},
{
scenario: "thread_merge_back_continue",
registrationScenario: "thread_merge_back_continue",
recordedScenario: "thread_merge_back_continue",
transcriptFile: new URL(
"./fixtures/thread_merge_back_continue/codex_transcript.ndjson",
import.meta.url,
),
},
{
scenario: "thread_merge_back_siblings",
registrationScenario: "thread_merge_back_siblings",
recordedScenario: "thread_merge_back_siblings",
transcriptFile: new URL(
"./fixtures/thread_merge_back_siblings/codex_transcript.ndjson",
import.meta.url,
@@ -74,6 +86,25 @@ const CODEX_REPLAY_FIXTURES = ORCHESTRATOR_REPLAY_FIXTURES.flatMap((fixture) =>
},
]);
function uniqueCanonicalTranscripts(
registrations: ReadonlyArray<CodexReplayFixtureRegistration>,
): ReadonlyArray<CodexReplayFixtureRegistration> {
const canonicalTranscripts = new Map<string, CodexReplayFixtureRegistration>();
for (const registration of registrations) {
const canonicalUrl = registration.transcriptFile.href;
const existing = canonicalTranscripts.get(canonicalUrl);
if (existing !== undefined && existing.recordedScenario !== registration.recordedScenario) {
throw new Error(
`Codex replay transcript ${canonicalUrl} has conflicting recorded scenarios ${existing.recordedScenario} (${existing.registrationScenario}) and ${registration.recordedScenario} (${registration.registrationScenario}).`,
);
}
canonicalTranscripts.set(canonicalUrl, existing ?? registration);
}
return Array.from(canonicalTranscripts.values());
}
const CODEX_REPLAY_TRANSCRIPTS = uniqueCanonicalTranscripts(CODEX_REPLAY_FIXTURE_REGISTRATIONS);
const scenarioExpectations = {
simple: {
outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
@@ -641,23 +672,25 @@ function assertSiblingMergeBackSemantics(transcript: ProviderReplayTranscript) {
}
describe("Codex replay fixtures", () => {
it.effect("loads every current Codex fixture as a codex app-server replay transcript", () =>
it.effect("loads each canonical Codex fixture as an app-server replay transcript", () =>
Effect.gen(function* () {
for (const fixture of CODEX_REPLAY_FIXTURES) {
for (const fixture of CODEX_REPLAY_TRANSCRIPTS) {
const transcript = yield* readTranscript(fixture.transcriptFile);
const codexTranscript = yield* decodeCodexTranscript(transcript);
const first = transcript.entries[0];
assert.equal(codexTranscript.provider, "codex");
assert.equal(codexTranscript.protocol, "codex.app-server");
assert.equal(codexTranscript.scenario, fixture.scenario);
assert.equal(codexTranscript.scenario, fixture.recordedScenario);
assert.deepEqual(codexTranscript.entries.at(-1), {
type: "runtime_exit",
status: "success",
});
assert.equal(first?.type, "expect_outbound");
if (first?.type !== "expect_outbound") {
throw new Error(`Expected ${fixture.scenario} to start with initialize outbound frame.`);
throw new Error(
`Expected ${fixture.recordedScenario} to start with initialize outbound frame.`,
);
}
assert.equal(first.label, "initialize");
@@ -671,16 +704,32 @@ describe("Codex replay fixtures", () => {
}),
);
it.effect("covers the expected replay suite exactly", () =>
Effect.gen(function* () {
const transcripts = yield* Effect.forEach(CODEX_REPLAY_FIXTURES, (fixture) =>
readTranscript(fixture.transcriptFile),
);
it("covers the expected replay suite exactly", () => {
assert.deepEqual(
CODEX_REPLAY_TRANSCRIPTS.map((fixture) => fixture.recordedScenario).toSorted(),
Object.keys(scenarioExpectations).toSorted(),
);
});
assert.deepEqual(
transcripts.map((transcript) => transcript.scenario).toSorted(),
Object.keys(scenarioExpectations).toSorted(),
);
}),
);
it("rejects conflicting recorded scenarios for one canonical transcript", () => {
const transcriptFile = new URL(
"./fixtures/queued_turn/codex_transcript.ndjson",
import.meta.url,
);
assert.throws(() =>
uniqueCanonicalTranscripts([
{
registrationScenario: "queued_turn",
recordedScenario: "queued_turn",
transcriptFile,
},
{
registrationScenario: "conflicting_alias",
recordedScenario: "different_recording",
transcriptFile,
},
]),
);
});
});
@@ -51,6 +51,192 @@ describe("orchestrator replay fixture contract", () => {
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime),
);
it.effect(
"keeps consecutive queue_message inputs queued without an intermediate idle barrier",
() =>
Effect.gen(function* () {
const materialized = yield* materializeFixtureInput({
scenario: "consecutive-queue-message-ordering",
fixtureInput: {
steps: [
{ type: "message", text: "active run" },
{ type: "queue_message", text: "queued run 1" },
{ type: "queue_message", text: "queued run 2" },
],
},
driver: ProviderDriverKind.make("codex"),
modelSelection: CODEX_MODEL_SELECTION,
});
const queueCommands = materialized.commands.filter(
(command) =>
command.type === "message.dispatch" &&
(command.text === "queued run 1" || command.text === "queued run 2"),
);
assert.lengthOf(queueCommands, 2);
for (const command of queueCommands) {
assert.deepInclude(command, {
dispatchMode: { type: "queue_after_active" },
});
}
const firstQueueDispatchIndex = materialized.steps.findIndex(
(step) =>
step.type === "dispatch" &&
step.command.type === "message.dispatch" &&
step.command.text === "queued run 1",
);
const secondQueueDispatchIndex = materialized.steps.findIndex(
(step) =>
step.type === "dispatch" &&
step.command.type === "message.dispatch" &&
step.command.text === "queued run 2",
);
assert.isAtLeast(firstQueueDispatchIndex, 0);
assert.isAbove(secondQueueDispatchIndex, firstQueueDispatchIndex);
const betweenQueueSteps = materialized.steps.slice(
firstQueueDispatchIndex + 1,
secondQueueDispatchIndex,
);
assert.isFalse(
betweenQueueSteps.some(
(step) => step.type === "await" || step.type === "await_thread_idle",
),
"consecutive queue_message steps must not await the active run or thread idle between queues",
);
const afterSecondQueue = materialized.steps.slice(secondQueueDispatchIndex + 1);
const barrierAwaitIndex = afterSecondQueue.findIndex((step) => step.type === "await");
const barrierIdleIndex = afterSecondQueue.findIndex(
(step) => step.type === "await_thread_idle",
);
assert.isAtLeast(
barrierAwaitIndex,
0,
"the final queue_message still inserts the post-queue await barrier",
);
assert.deepEqual(afterSecondQueue[barrierAwaitIndex], {
type: "await",
key: "run:1",
});
assert.isAbove(
barrierIdleIndex,
barrierAwaitIndex,
"the final queue_message still inserts await_thread_idle after its await",
);
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime),
);
it.effect(
"does not await thread idle between steer/restart and answer_next_user_input_request",
() =>
Effect.gen(function* () {
for (const steeringType of ["steer", "restart"] as const) {
const answers = { "question-0": "answer" };
const materialized = yield* materializeFixtureInput({
scenario: `${steeringType}-then-answer-user-input-ordering`,
fixtureInput: {
steps: [
{ type: "message", text: "active run" },
{
type: steeringType,
text: `${steeringType} active run`,
targetRunIndex: 1,
},
{
type: "answer_next_user_input_request",
answers,
},
],
},
driver: ProviderDriverKind.make("codex"),
modelSelection: CODEX_MODEL_SELECTION,
});
const steeringDispatchIndex = materialized.steps.findIndex(
(step) =>
step.type === "dispatch" &&
step.command.type === "message.dispatch" &&
step.command.text === `${steeringType} active run`,
);
const answerStepIndex = materialized.steps.findIndex(
(step) =>
step.type === "respond_to_next_runtime_request" &&
step.answers !== undefined &&
Object.keys(step.answers).includes("question-0"),
);
assert.isAtLeast(steeringDispatchIndex, 0, `${steeringType} dispatch must materialize`);
assert.isAbove(
answerStepIndex,
steeringDispatchIndex,
`${steeringType} answer must follow the steering dispatch`,
);
const betweenSteps = materialized.steps.slice(steeringDispatchIndex + 1, answerStepIndex);
assert.isFalse(
betweenSteps.some((step) => step.type === "await" || step.type === "await_thread_idle"),
`${steeringType} followed by answer_next_user_input_request must not await idle before answering`,
);
}
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime),
);
it.effect("keeps the active dispatch barrier through queued-run replacement", () =>
Effect.gen(function* () {
const materialized = yield* materializeFixtureInput({
scenario: "queued-run-replacement-ordering",
fixtureInput: {
steps: [
{ type: "message", text: "active run" },
{ type: "queue_message", text: "queued run" },
{ type: "cancel_queued_run", targetRunIndex: 2 },
{ type: "queue_message", text: "replacement queued run" },
],
},
driver: ProviderDriverKind.make("codex"),
modelSelection: CODEX_MODEL_SELECTION,
});
const replacementQueueDispatchIndex = materialized.steps.findIndex(
(step) =>
step.type === "dispatch" &&
step.command.type === "message.dispatch" &&
step.command.text === "replacement queued run",
);
assert.isAtLeast(replacementQueueDispatchIndex, 0);
const afterReplacementQueue = materialized.steps.slice(replacementQueueDispatchIndex + 1);
const barrierAwait = afterReplacementQueue.find((step) => step.type === "await");
assert.deepEqual(barrierAwait, {
type: "await",
key: "run:1",
});
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime),
);
it.effect("materializes fixture run-status waits against derived run IDs", () =>
Effect.gen(function* () {
const idAllocator = yield* IdAllocatorV2;
const materialized = yield* materializeFixtureInput({
scenario: "await-fixture-run-status",
fixtureInput: {
steps: [{ type: "await_run_status", targetRunIndex: 1, status: "running" }],
},
driver: ProviderDriverKind.make("codex"),
modelSelection: CODEX_MODEL_SELECTION,
});
const threadId = materialized.projectionThreadIds[0];
assert.isDefined(threadId);
const runStatusWait = materialized.steps.find((step) => step.type === "await_run_status");
assert.deepEqual(runStatusWait, {
type: "await_run_status",
threadId,
runId: idAllocator.derive.run({ threadId, ordinal: 1 }),
status: "running",
});
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime),
);
it.effect("keeps message ordinals separate from app run ordinals after steering", () =>
Effect.gen(function* () {
const idAllocator = yield* IdAllocatorV2;
@@ -112,6 +298,14 @@ describe("orchestrator replay fixture contract", () => {
for (const provider of fixture.providers) {
const transcript = yield* readTranscript(provider.transcriptFile);
const replayGateLabels = fixture
.buildInput()
.steps.flatMap((step) =>
step.type === "release_replay_gate" ||
step.type === "release_replay_gate_after_waiting"
? [step.label]
: [],
);
const materialized = yield* materializeFixtureInput({
scenario: fixture.name,
fixtureInput: fixture.buildInput(),
@@ -120,7 +314,7 @@ describe("orchestrator replay fixture contract", () => {
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime);
const firstCommand = materialized.commands[0];
assert.equal(transcript.scenario, fixture.name);
assert.equal(transcript.scenario, provider.recordedScenario ?? fixture.name);
if (provider.driver === "acpRegistry") {
assert.include(
["acpRegistry", "grok"],
@@ -140,14 +334,39 @@ describe("orchestrator replay fixture contract", () => {
throw new Error(`${fixture.name}/${provider.driver} must start with thread.create`);
}
assert.equal(firstCommand.threadId, materialized.projectionThreadIds[0]);
// advance_clock only moves the test clock; every other input step
// dispatches a command.
// These fixture steps coordinate the test runtime; every other
// input step dispatches a command.
const commandProducingSteps = fixture
.buildInput()
.steps.filter((step) => step.type !== "advance_clock");
.steps.filter(
(step) =>
step.type !== "advance_clock" &&
step.type !== "await_run_status" &&
step.type !== "capture_shell_snapshot" &&
step.type !== "release_replay_gate" &&
step.type !== "release_replay_gate_after_waiting",
);
assert.equal(materialized.commands.length, commandProducingSteps.length + 1);
assert.isAtLeast(materialized.steps.length, materialized.commands.length);
assert.equal(typeof provider.assertOutput, "function");
for (const label of replayGateLabels) {
assert.isTrue(
transcript.entries.some(
(entry) => entry.type === "emit_inbound" && entry.label === label,
),
`${fixture.name}/${provider.driver} replay gate ${label} must label an inbound frame`,
);
}
if (provider.transcriptEntriesThroughLabel !== undefined) {
assert.isTrue(
transcript.entries.some(
(entry) =>
entry.type === "emit_inbound" &&
entry.label === provider.transcriptEntriesThroughLabel,
),
`${fixture.name}/${provider.driver} transcript slice must name an inbound frame`,
);
}
assertUnique(
materialized.commands.map((command) => command.commandId),
@@ -39,6 +39,25 @@ function normalizeTestError(cause: unknown): Error {
return cause instanceof Error ? cause : new Error(String(cause));
}
function transcriptEntriesThroughLabel(
transcript: ProviderReplayTranscript,
label: string | undefined,
): ProviderReplayTranscript {
if (label === undefined) {
return transcript;
}
const entryIndex = transcript.entries.findIndex(
(entry) => entry.type === "emit_inbound" && entry.label === label,
);
if (entryIndex === -1) {
throw new Error(`${transcript.scenario} is missing inbound transcript label ${label}.`);
}
return {
...transcript,
entries: transcript.entries.slice(0, entryIndex + 1),
};
}
function isStreamingAssistantEvent(event: OrchestrationV2DomainEvent): boolean {
switch (event.type) {
case "node.updated":
@@ -63,11 +82,15 @@ const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* <
readonly enableAssistantStreaming?: boolean;
}) {
const rawTranscript = yield* readTranscript(input.driver.transcriptFile);
const replayTranscript = transcriptEntriesThroughLabel(
rawTranscript,
input.driver.transcriptEntriesThroughLabel,
);
const workspace = yield* checkpointWorkspace(input.fixtureName);
const transcript = yield* input.harness.decodeTranscript(
input.driver.driver === "codex"
? materializeReplayTranscriptWorkspace(rawTranscript, workspace)
: rawTranscript,
? materializeReplayTranscriptWorkspace(replayTranscript, workspace)
: replayTranscript,
);
const materialized = yield* materializeFixtureInput({
scenario: input.fixtureName,
@@ -21,6 +21,7 @@ import * as Stream from "effect/Stream";
import { TestClock } from "effect/testing";
import { OrchestratorV2, type OrchestratorV2Error } from "../Orchestrator.ts";
import type { ProviderReplayGate } from "./ProviderReplayGate.testkit.ts";
export type OrchestratorV2ScenarioStep =
| {
@@ -61,6 +62,20 @@ export type OrchestratorV2ScenarioStep =
readonly runId: OrchestrationV2Run["id"];
readonly itemType: OrchestrationV2TurnItem["type"];
}
| {
readonly type: "release_replay_gate_after_waiting";
readonly label: string;
readonly threadId: ThreadId;
readonly runId: OrchestrationV2Run["id"];
}
| {
readonly type: "release_replay_gate";
readonly label: string;
}
| {
readonly type: "capture_shell_snapshot";
readonly key: string;
}
| {
readonly type: "respond_to_next_runtime_request";
readonly threadId: ThreadId;
@@ -81,6 +96,7 @@ export interface OrchestratorV2ScenarioResult {
readonly domainEvents: ReadonlyArray<OrchestrationV2DomainEvent>;
readonly projections: ReadonlyMap<ThreadId, OrchestrationV2ThreadProjection>;
readonly shellSnapshot: OrchestrationV2ThreadShellSnapshot;
readonly capturedShellSnapshots: ReadonlyMap<string, OrchestrationV2ThreadShellSnapshot>;
}
export class OrchestratorV2ScenarioStepError extends Schema.TaggedErrorClass<OrchestratorV2ScenarioStepError>()(
@@ -204,6 +220,9 @@ function collectProjectionThreadIds(scenario: OrchestratorV2Scenario): ReadonlyA
export function runOrchestratorV2Scenario(
scenario: OrchestratorV2Scenario,
options: {
readonly replayGate?: ProviderReplayGate;
} = {},
): Effect.Effect<
OrchestratorV2ScenarioResult,
OrchestratorV2Error | OrchestratorV2ScenarioStepError,
@@ -224,6 +243,7 @@ export function runOrchestratorV2Scenario(
string,
Fiber.Fiber<ReadonlyArray<OrchestrationV2StoredEvent>, OrchestratorV2Error>
>();
const capturedShellSnapshots = new Map<string, OrchestrationV2ThreadShellSnapshot>();
let anonymousBackgroundDispatchIndex = 0;
const awaitDispatch = (key: string) =>
@@ -384,6 +404,100 @@ export function runOrchestratorV2Scenario(
);
});
const releaseReplayGateAfterWaiting = (
label: string,
threadId: ThreadId,
runId: OrchestrationV2Run["id"],
attemptsRemaining = SCENARIO_WAIT_ATTEMPTS,
): Effect.Effect<void, OrchestratorV2Error | OrchestratorV2ScenarioStepError, never> =>
Effect.gen(function* () {
const projection = yield* orchestrator.getThreadProjection(threadId);
const run = projection.runs.find((candidate) => candidate.id === runId);
const providerThread = projection.providerThreads.find(
(candidate) => candidate.id === run?.providerThreadId,
);
const pendingTaskCount = providerThread?.pendingBackgroundTasks?.length ?? 0;
const gateReached = options.replayGate?.hasReached(label) ?? false;
if (
gateReached &&
run?.status === "completed" &&
providerThread !== undefined &&
pendingTaskCount > 0
) {
options.replayGate?.release(label);
yield* waitForProviderBackgroundTasksCleared(threadId, providerThread.id);
return;
}
if (attemptsRemaining <= 0) {
options.replayGate?.release(label);
return yield* new OrchestratorV2ScenarioStepError({
scenario: scenario.name,
step: `release_replay_gate_after_waiting:${label}:reached=${gateReached}:run=${run?.status ?? "missing"}:providerThread=${run?.providerThreadId ?? "missing"}:pending=${pendingTaskCount}`,
});
}
yield* yieldToRuntime;
return yield* releaseReplayGateAfterWaiting(
label,
threadId,
runId,
attemptsRemaining - 1,
);
});
const waitForProviderBackgroundTasksCleared = (
threadId: ThreadId,
providerThreadId: NonNullable<OrchestrationV2Run["providerThreadId"]>,
attemptsRemaining = SCENARIO_WAIT_ATTEMPTS,
): Effect.Effect<void, OrchestratorV2Error | OrchestratorV2ScenarioStepError, never> =>
Effect.gen(function* () {
const projection = yield* orchestrator.getThreadProjection(threadId);
const providerThread = projection.providerThreads.find(
(candidate) => candidate.id === providerThreadId,
);
const hasPendingTasks = (providerThread?.pendingBackgroundTasks?.length ?? 0) > 0;
if (!hasPendingTasks && providerThread?.status === "idle") {
return;
}
if (attemptsRemaining <= 0) {
const providerState = projection.providerThreads
.map(
(candidate) =>
`${candidate.id}:${candidate.status}:pending=${candidate.pendingBackgroundTasks?.length ?? 0}`,
)
.join(",");
return yield* new OrchestratorV2ScenarioStepError({
scenario: scenario.name,
step: `await_provider_background_tasks_cleared:${threadId}:target=${providerThreadId}:providers=${providerState}`,
});
}
yield* yieldToRuntime;
return yield* waitForProviderBackgroundTasksCleared(
threadId,
providerThreadId,
attemptsRemaining - 1,
);
});
const releaseReplayGate = (
label: string,
attemptsRemaining = SCENARIO_WAIT_ATTEMPTS,
): Effect.Effect<void, OrchestratorV2ScenarioStepError> =>
Effect.gen(function* () {
if (options.replayGate?.hasReached(label) ?? false) {
options.replayGate?.release(label);
return;
}
if (attemptsRemaining <= 0) {
options.replayGate?.release(label);
return yield* new OrchestratorV2ScenarioStepError({
scenario: scenario.name,
step: `release_replay_gate:${label}:reached=false`,
});
}
yield* yieldToRuntime;
return yield* releaseReplayGate(label, attemptsRemaining - 1);
});
for (const step of scenarioSteps(scenario)) {
switch (step.type) {
case "dispatch": {
@@ -427,6 +541,15 @@ export function runOrchestratorV2Scenario(
case "await_run_turn_item":
yield* waitForRunTurnItem(step.threadId, step.runId, step.itemType);
break;
case "release_replay_gate_after_waiting":
yield* releaseReplayGateAfterWaiting(step.label, step.threadId, step.runId);
break;
case "release_replay_gate":
yield* releaseReplayGate(step.label);
break;
case "capture_shell_snapshot":
capturedShellSnapshots.set(step.key, yield* orchestrator.getShellSnapshot());
break;
case "respond_to_next_runtime_request": {
const request = yield* waitForPendingRuntimeRequest(step.threadId);
const result = yield* orchestrator.dispatch({
@@ -468,6 +591,7 @@ export function runOrchestratorV2Scenario(
domainEvents: storedEvents.map((stored) => stored.event),
projections,
shellSnapshot,
capturedShellSnapshots,
};
}),
);
@@ -0,0 +1,17 @@
import { describe, expect, it } from "vite-plus/test";
import { makeProviderReplayGate } from "./ProviderReplayGate.testkit.ts";
describe("ProviderReplayGate", () => {
it("stops waiting when the replay consumer is interrupted", async () => {
const label = "held-frame";
const gate = makeProviderReplayGate([label]);
const controller = new AbortController();
const waiting = gate.beforeEmit(label, controller.signal);
expect(gate.hasReached(label)).toBe(true);
controller.abort();
await waiting;
expect(gate.release(label)).toBe(true);
});
});
@@ -0,0 +1,78 @@
export interface ProviderReplayGate {
readonly beforeEmit: (label: string | undefined, signal?: AbortSignal) => Promise<void>;
readonly hasReached: (label: string) => boolean;
readonly release: (label: string) => boolean;
readonly releaseAll: () => void;
}
interface GateState {
reached: boolean;
released: boolean;
readonly promise: Promise<void>;
readonly resolve: () => void;
}
export function makeProviderReplayGate(labels: ReadonlyArray<string>): ProviderReplayGate {
const states = new Map<string, GateState>();
for (const label of labels) {
if (states.has(label)) {
throw new Error(`Duplicate provider replay gate label ${label}.`);
}
let resolve = () => {};
const promise = new Promise<void>((resume) => {
resolve = resume;
});
states.set(label, {
reached: false,
released: false,
promise,
resolve,
});
}
return {
beforeEmit: (label, signal) => {
if (label === undefined) {
return Promise.resolve();
}
const state = states.get(label);
if (state === undefined) {
return Promise.resolve();
}
state.reached = true;
if (signal === undefined) {
return state.promise;
}
if (signal.aborted) {
return Promise.resolve();
}
return new Promise<void>((resolve) => {
const stopWaiting = () => resolve();
signal.addEventListener("abort", stopWaiting, { once: true });
void state.promise.then(() => {
signal.removeEventListener("abort", stopWaiting);
resolve();
});
});
},
hasReached: (label) => states.get(label)?.reached ?? false,
release: (label) => {
const state = states.get(label);
if (state === undefined || state.released) {
return false;
}
state.released = true;
state.resolve();
return true;
},
releaseAll: () => {
for (const state of states.values()) {
if (state.released) {
continue;
}
state.released = true;
state.resolve();
}
},
};
}
@@ -57,6 +57,7 @@ import {
type OrchestratorV2Scenario,
type OrchestratorV2ScenarioResult,
} from "./OrchestratorScenario.ts";
import { makeProviderReplayGate, type ProviderReplayGate } from "./ProviderReplayGate.testkit.ts";
export function makeReplayServerConfig(
scenario: string,
@@ -156,6 +157,7 @@ export interface OrchestratorV2ProviderReplayHarness<
) => Effect.Effect<Transcript, Error>;
readonly makeProviderAdapterRegistryLayer: (
transcript: Transcript,
options?: { readonly replayGate?: ProviderReplayGate },
) => Layer.Layer<ProviderAdapterRegistryV2, Error>;
}
@@ -183,9 +185,19 @@ export function runOrchestratorV2ProviderReplayScenario<
| SqlError,
never
> {
const layer = makeOrchestratorV2ProviderReplayLayer(scenario, harness, options);
const replayGate = makeProviderReplayGate(
scenario.steps?.flatMap((step) =>
step.type === "release_replay_gate" || step.type === "release_replay_gate_after_waiting"
? [step.label]
: [],
) ?? [],
);
const layer = makeOrchestratorV2ProviderReplayLayer(scenario, harness, {
...options,
replayGate,
});
return runOrchestratorV2Scenario(scenario).pipe(Effect.provide(layer));
return runOrchestratorV2Scenario(scenario, { replayGate }).pipe(Effect.provide(layer));
}
export function makeOrchestratorV2ProviderReplayLayer<
@@ -201,9 +213,13 @@ export function makeOrchestratorV2ProviderReplayLayer<
>;
readonly enableAssistantStreaming?: boolean;
readonly runEffectWorker?: boolean;
readonly replayGate?: ProviderReplayGate;
} = {},
): Layer.Layer<OrchestratorV2, Error | MigrationError | PlatformError.PlatformError | SqlError> {
const registryLayer = harness.makeProviderAdapterRegistryLayer(scenario.transcript);
const registryLayer = harness.makeProviderAdapterRegistryLayer(
scenario.transcript,
options.replayGate === undefined ? {} : { replayGate: options.replayGate },
);
return makeOrchestratorV2ReplayLayerWithRegistry(scenario, registryLayer, options);
}
@@ -0,0 +1,13 @@
{"type":"transcript_start","provider":"claudeAgent","protocol":"claude-agent-sdk.query","version":"0.2.111","scenario":"claude_background_task_after_root","metadata":{"prompts":["Live-test post-settle background Bash wake. Do exactly this in order, with no extra steps.\n\n1) Run this exact command using the Bash tool with run_in_background set to true:\n sleep 25 && echo L2_BG_DONE\n2) Immediately after starting it, reply with a short message containing exactly L2_STARTED and stop.\n3) Do NOT poll TaskOutput. Do NOT wait for the task. Do not spawn subagents or monitors.\n4) If its completion is reported later, acknowledge it once by replying with exactly L2_WAKE: L2_BG_DONE and stop.\n\nThe point is that your first turn ends while the command is still running."],"model":"claude-sonnet-4-6","nativeSessionId":"ec24a006-617b-4324-b516-57a7afff15a4","queryMode":"streaming","tools":"claude_code","permissionMode":"bypassPermissions","timingCompression":"25-second background gap controlled by the replay scenario gate","generatedBy":"manual-replay-from-thread-ec24a006 (ctm-catchup-l2-20260729, captured 2026-07-30T00:35:14Z)"}}
{"type":"expect_outbound","label":"query.open","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"sessionId":"ec24a006-617b-4324-b516-57a7afff15a4"}}}
{"type":"expect_outbound","label":"prompt.offer:1","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Live-test post-settle background Bash wake. Do exactly this in order, with no extra steps.\n\n1) Run this exact command using the Bash tool with run_in_background set to true:\n sleep 25 && echo L2_BG_DONE\n2) Immediately after starting it, reply with a short message containing exactly L2_STARTED and stop.\n3) Do NOT poll TaskOutput. Do NOT wait for the task. Do not spawn subagents or monitors.\n4) If its completion is reported later, acknowledge it once by replying with exactly L2_WAKE: L2_BG_DONE and stop.\n\nThe point is that your first turn ends while the command is still running."},"parent_tool_use_id":null}}}
{"type":"emit_inbound","label":"system:init","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.219","cwd":"/tmp/claude-replay-claude_background_task_after_root","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"fdd8c2b3-f443-405c-996d-1a5ac798e100","session_id":"ec24a006-617b-4324-b516-57a7afff15a4"}}
{"type":"emit_inbound","label":"assistant:background-bash","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_011CdXJcN9jaK2KDf7LcqkDx","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01DAnwwvVvLM1cTfzrm6kkor","name":"Bash","input":{"command":"sleep 25 && echo L2_BG_DONE","run_in_background":true},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":89,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"ec24a006-617b-4324-b516-57a7afff15a4","uuid":"6e8e602b-da0f-409d-92a4-8a912b9c7ca9"}}
{"type":"emit_inbound","label":"task_started:local_bash","frame":{"type":"system","subtype":"task_started","task_id":"bc9gkn8ei","tool_use_id":"toolu_01DAnwwvVvLM1cTfzrm6kkor","description":"sleep 25 && echo L2_BG_DONE","task_type":"local_bash","uuid":"ed0f530b-93fe-4f94-a385-367b440a04ba","session_id":"ec24a006-617b-4324-b516-57a7afff15a4"}}
{"type":"emit_inbound","label":"background_tasks_changed:pending","frame":{"type":"system","subtype":"background_tasks_changed","tasks":[{"task_id":"bc9gkn8ei","description":"sleep 25 && echo L2_BG_DONE","task_type":"local_bash"}],"uuid":"7d3cb8ba-6736-4b30-a748-c511cfa61803","session_id":"ec24a006-617b-4324-b516-57a7afff15a4"}}
{"type":"emit_inbound","label":"user:background-bash-ack","frame":{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01DAnwwvVvLM1cTfzrm6kkor","type":"tool_result","content":"Command running in background with ID: bc9gkn8ei. Output is being written to: /tmp/claude-replay-claude_background_task_after_root/tasks/bc9gkn8ei.output. You will be notified when it completes. To check interim output, use Read on that file path.","is_error":false}]},"parent_tool_use_id":null,"session_id":"ec24a006-617b-4324-b516-57a7afff15a4","uuid":"7e95842b-dec4-4be5-9b20-9738697edf62","timestamp":"2026-07-30T00:35:18.555Z","tool_use_result":{"stdout":"","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false,"backgroundTaskId":"bc9gkn8ei"}}}
{"type":"emit_inbound","label":"assistant:root-final","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_011CdXJcdoKdTMfN4depYTKM","type":"message","role":"assistant","content":[{"type":"text","text":"L2_STARTED"}],"stop_reason":"end_turn","stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":9,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"ec24a006-617b-4324-b516-57a7afff15a4","uuid":"12ddebd6-6f2d-4223-be97-56ed454f7d15"}}
{"type":"emit_inbound","label":"result:root","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":7125,"duration_api_ms":6500,"num_turns":2,"result":"L2_STARTED","stop_reason":"end_turn","session_id":"ec24a006-617b-4324-b516-57a7afff15a4","total_cost_usd":0.001,"usage":{"input_tokens":2,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":9,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":2,"output_tokens":9,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":2,"outputTokens":9,"cacheReadInputTokens":0,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.001,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"633b885b-240f-4f44-bfe1-d554088b2dfd"}}
{"type":"emit_inbound","label":"background_tasks_changed:empty","frame":{"type":"system","subtype":"background_tasks_changed","tasks":[],"uuid":"3464e6d2-1a25-4e37-82de-d305440ed44b","session_id":"ec24a006-617b-4324-b516-57a7afff15a4"}}
{"type":"emit_inbound","label":"task_notification:local_bash","frame":{"type":"system","subtype":"task_notification","task_id":"bc9gkn8ei","tool_use_id":"toolu_01DAnwwvVvLM1cTfzrm6kkor","status":"completed","output_file":"/tmp/claude-replay-claude_background_task_after_root/tasks/bc9gkn8ei.output","summary":"Background command \"sleep 25 && echo L2_BG_DONE\" completed (exit code 0)","uuid":"0a8bc186-10a1-421c-a319-e3c7db9cb4a6","session_id":"ec24a006-617b-4324-b516-57a7afff15a4"}}
{"type":"runtime_exit","status":"success"}
@@ -0,0 +1,26 @@
import type { OrchestratorFixtureInput } from "../shared.ts";
export const CLAUDE_BACKGROUND_TASK_AFTER_ROOT_PROMPT = [
"Live-test post-settle background Bash wake. Do exactly this in order, with no extra steps.",
"",
"1) Run this exact command using the Bash tool with run_in_background set to true:",
" sleep 25 && echo L2_BG_DONE",
"2) Immediately after starting it, reply with a short message containing exactly L2_STARTED and stop.",
"3) Do NOT poll TaskOutput. Do NOT wait for the task. Do not spawn subagents or monitors.",
"4) If its completion is reported later, acknowledge it once by replying with exactly L2_WAKE: L2_BG_DONE and stop.",
"",
"The point is that your first turn ends while the command is still running.",
].join("\n");
export function claudeBackgroundTaskAfterRootInput(): OrchestratorFixtureInput {
return {
steps: [
{ type: "message", text: CLAUDE_BACKGROUND_TASK_AFTER_ROOT_PROMPT },
{
type: "release_replay_gate_after_waiting",
label: "background_tasks_changed:empty",
targetRunIndex: 1,
},
],
};
}
@@ -0,0 +1,96 @@
import { assert } from "@effect/vitest";
import type { ProviderReplayTranscript } from "@t3tools/contracts";
import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
import {
assertBaseProjection,
assertSemanticProjectionIntegrity,
assertUserMessagesInclude,
projectionFor,
} from "../shared.ts";
import { CLAUDE_BACKGROUND_TASK_AFTER_ROOT_PROMPT } from "./input.ts";
const BACKGROUND_TASK_ID = "bc9gkn8ei";
export function assertClaudeBackgroundTaskAfterRootOutput(
result: OrchestratorV2ScenarioResult,
transcript: ProviderReplayTranscript,
) {
assertBaseProjection({
result,
transcript,
runCount: 1,
runStatuses: ["completed"],
});
const projection = projectionFor(result, transcript.scenario);
assertSemanticProjectionIntegrity(projection);
assertUserMessagesInclude(projection, [CLAUDE_BACKGROUND_TASK_AFTER_ROOT_PROMPT]);
const rootRun = projection.runs[0];
assert.isDefined(rootRun);
const pendingRosterIndex = result.domainEvents.findIndex(
(event) =>
event.type === "provider-thread.updated" &&
event.payload.pendingBackgroundTasks?.some((task) => task.taskId === BACKGROUND_TASK_ID),
);
const waitingRunIndex = result.domainEvents.findIndex(
(event) =>
event.type === "run.updated" &&
event.runId === rootRun.id &&
event.payload.status === "waiting",
);
const waitingRootNodeIndex = result.domainEvents.findIndex(
(event) =>
event.type === "node.updated" &&
event.payload.runId === rootRun.id &&
event.payload.kind === "root_turn" &&
event.payload.status === "waiting",
);
const idleRosterIndex = result.domainEvents.findIndex(
(event, index) =>
index > waitingRunIndex &&
event.type === "provider-thread.updated" &&
event.payload.status === "idle" &&
(event.payload.pendingBackgroundTasks?.length ?? 0) === 0,
);
assert.isAtLeast(pendingRosterIndex, 0, "replay must project the live background task roster");
assert.isAbove(
waitingRunIndex,
pendingRosterIndex,
"checkpoint-waiting root run must retain the background roster",
);
assert.isAbove(
waitingRootNodeIndex,
pendingRosterIndex,
"checkpoint-waiting root node must retain the background roster",
);
assert.isAbove(
idleRosterIndex,
waitingRunIndex,
"late background completion must clear the roster and return the provider thread to idle",
);
assert.equal(rootRun.status, "completed");
const rootNode = projection.nodes.find(
(node) => node.runId === rootRun.id && node.kind === "root_turn",
);
assert.isDefined(rootNode);
assert.equal(rootNode.status, "completed");
assert.lengthOf(projection.providerThreads, 1);
assert.equal(projection.providerThreads[0]?.status, "idle");
assert.deepEqual(projection.providerThreads[0]?.pendingBackgroundTasks ?? [], []);
assert.lengthOf(projection.subagents, 0);
const assistantTexts = projection.turnItems.flatMap((item) =>
item.type === "assistant_message" ? [item.text] : [],
);
assert.deepEqual(assistantTexts, ["L2_STARTED"]);
const shell = result.shellSnapshot.threads.find((thread) => thread.id === projection.thread.id);
assert.isDefined(shell);
assert.equal(shell.activeRunId, null);
assert.equal(shell.status, "completed");
assert.deepEqual(shell.pendingBackgroundTasks ?? [], []);
}
@@ -1,5 +1,7 @@
import { ProviderDriverKind } from "@t3tools/contracts";
import { claudeBackgroundTaskAfterRootInput } from "./claude_background_task_after_root/input.ts";
import { assertClaudeBackgroundTaskAfterRootOutput } from "./claude_background_task_after_root/output.ts";
import { claudeIdleResumeInput } from "./claude_idle_resume/input.ts";
import { assertClaudeIdleResumeOutput } from "./claude_idle_resume/output.ts";
import { claudeLocalBashTaskInput } from "./claude_local_bash_task/input.ts";
@@ -24,6 +26,8 @@ import { planQuestionsInput } from "./plan_questions/input.ts";
import { assertProposedPlanOutput } from "./proposed_plan/codex_output.ts";
import { assertProposedPlanCursorOutput } from "./proposed_plan/cursor_output.ts";
import { proposedPlanInput } from "./proposed_plan/input.ts";
import { assertQueuedCancelledWhileActiveOutput } from "./queued_cancelled_while_active/codex_output.ts";
import { queuedCancelledWhileActiveInput } from "./queued_cancelled_while_active/input.ts";
import { assertQueuedTurnOutput } from "./queued_turn/codex_output.ts";
import { queuedTurnInput } from "./queued_turn/input.ts";
import { assertSimpleClaudeOutput } from "./simple/claude_output.ts";
@@ -83,7 +87,22 @@ import {
WORKSPACE_NEVER_POLICY,
} from "./shared.ts";
export const ORCHESTRATOR_REPLAY_FIXTURES = [
export const ORCHESTRATOR_REPLAY_FIXTURES: ReadonlyArray<OrchestratorReplayFixture> = [
{
name: "claude_background_task_after_root",
buildInput: claudeBackgroundTaskAfterRootInput,
providers: [
{
driver: ProviderDriverKind.make("claudeAgent"),
transcriptFile: new URL(
"./claude_background_task_after_root/claude_transcript.ndjson",
import.meta.url,
),
modelSelection: CLAUDE_MODEL_SELECTION,
assertOutput: assertClaudeBackgroundTaskAfterRootOutput,
},
],
},
{
name: "claude_local_bash_task",
buildInput: claudeLocalBashTaskInput,
@@ -457,6 +476,20 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
},
],
},
{
name: "queued_cancelled_while_active",
buildInput: queuedCancelledWhileActiveInput,
providers: [
{
driver: ProviderDriverKind.make("codex"),
transcriptFile: new URL("./queued_turn/codex_transcript.ndjson", import.meta.url),
recordedScenario: "queued_turn",
transcriptEntriesThroughLabel: "turn/completed",
modelSelection: CODEX_MODEL_SELECTION,
assertOutput: assertQueuedCancelledWhileActiveOutput,
},
],
},
{
name: "queued_turn",
buildInput: queuedTurnInput,
@@ -737,7 +770,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
},
],
},
] satisfies ReadonlyArray<OrchestratorReplayFixture>;
];
// TODO(claude-v2/approvals-denied): add denied write fixtures after the live query runner records
// Claude denial callback responses. Cross-reference
@@ -0,0 +1,42 @@
import { assert } from "@effect/vitest";
import type { ProviderReplayTranscript } from "@t3tools/contracts";
import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
import { assertBaseProjection, projectionFor } from "../shared.ts";
import { ACTIVE_RUN_SHELL_SNAPSHOT_KEY } from "./input.ts";
export function assertQueuedCancelledWhileActiveOutput(
result: OrchestratorV2ScenarioResult,
transcript: ProviderReplayTranscript,
) {
assertBaseProjection({
result,
transcript,
runCount: 2,
runStatuses: ["completed", "cancelled"],
providerTurnCountAtLeast: 1,
});
const projection = projectionFor(result, transcript.scenario);
const activeRun = projection.runs[0];
const cancelledRun = projection.runs[1];
assert.isDefined(activeRun);
assert.isDefined(cancelledRun);
assert.isNull(cancelledRun.startedAt);
const cancelledMessage = projection.messages.find(
(message) => message.id === cancelledRun.userMessageId,
);
assert.isDefined(cancelledMessage);
assert.equal(cancelledMessage.createdBy, "agent");
assert.equal(cancelledMessage.creationSource, "server");
const capturedShell = result.capturedShellSnapshots
.get(ACTIVE_RUN_SHELL_SNAPSHOT_KEY)
?.threads.find((thread) => thread.id === projection.thread.id);
assert.isDefined(capturedShell);
assert.equal(capturedShell.latestRunId, cancelledRun.id);
assert.equal(capturedShell.status, "cancelled");
assert.equal(capturedShell.activeRunId, activeRun.id);
assert.equal(capturedShell.activityRunStatus, "running");
assert.deepEqual(capturedShell.pendingBackgroundTasks, []);
}
@@ -0,0 +1,25 @@
import {
MULTI_TURN_FIRST_PROMPT,
MULTI_TURN_SECOND_PROMPT,
type OrchestratorFixtureInput,
} from "../shared.ts";
export const ACTIVE_RUN_SHELL_SNAPSHOT_KEY = "active-run-over-cancelled-latest";
export function queuedCancelledWhileActiveInput(): OrchestratorFixtureInput {
return {
steps: [
{ type: "message", text: MULTI_TURN_FIRST_PROMPT },
{
type: "queue_message",
text: MULTI_TURN_SECOND_PROMPT,
createdBy: "agent",
creationSource: "server",
},
{ type: "cancel_queued_run", targetRunIndex: 2 },
{ type: "await_run_status", targetRunIndex: 1, status: "running" },
{ type: "capture_shell_snapshot", key: ACTIVE_RUN_SHELL_SNAPSHOT_KEY },
{ type: "release_replay_gate", label: "turn/completed" },
],
};
}
@@ -162,6 +162,31 @@ export type OrchestratorFixtureInputStep =
readonly type: "queue_message";
readonly text: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly createdBy?: Extract<
OrchestrationV2Command,
{ readonly type: "message.dispatch" }
>["createdBy"];
readonly creationSource?: Extract<
OrchestrationV2Command,
{ readonly type: "message.dispatch" }
>["creationSource"];
}
| {
readonly type: "cancel_queued_run";
readonly targetRunIndex: number;
}
| {
readonly type: "await_run_status";
readonly targetRunIndex: number;
readonly status: OrchestrationV2RunStatus;
}
| {
readonly type: "capture_shell_snapshot";
readonly key: string;
}
| {
readonly type: "release_replay_gate";
readonly label: string;
}
| {
readonly type: "steer";
@@ -180,6 +205,11 @@ export type OrchestratorFixtureInputStep =
readonly targetRunIndex: number;
readonly waitForTurnItemType?: OrchestrationV2TurnItem["type"];
}
| {
readonly type: "release_replay_gate_after_waiting";
readonly label: string;
readonly targetRunIndex: number;
}
| {
readonly type: "approve_next_runtime_request";
readonly decision?: Extract<
@@ -213,6 +243,8 @@ export interface OrchestratorFixtureInput {
export interface ProviderOrchestratorReplayVariant {
readonly driver: ProviderDriverKind;
readonly transcriptFile: URL;
readonly recordedScenario?: string;
readonly transcriptEntriesThroughLabel?: string;
readonly modelSelection: ModelSelection;
readonly runtimePolicyOverride?: RuntimePolicyV2Override;
readonly assertOutput: (
@@ -348,6 +380,14 @@ export function dispatchMessageCommand(input: {
readonly messageId: MessageId;
readonly text: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly createdBy?: Extract<
OrchestrationV2Command,
{ readonly type: "message.dispatch" }
>["createdBy"];
readonly creationSource?: Extract<
OrchestrationV2Command,
{ readonly type: "message.dispatch" }
>["creationSource"];
readonly dispatchMode?: Extract<
OrchestrationV2Command,
{ readonly type: "message.dispatch" }
@@ -355,8 +395,8 @@ export function dispatchMessageCommand(input: {
}): OrchestrationV2Command {
return {
type: "message.dispatch",
createdBy: "user",
creationSource: "web",
createdBy: input.createdBy ?? "user",
creationSource: input.creationSource ?? "web",
commandId: input.commandId,
threadId: input.ids.threadId,
messageId: input.messageId,
@@ -436,7 +476,9 @@ export function materializeFixtureInput(input: {
(nextStep !== undefined &&
((nextStep.type === "interrupt" && nextStep.targetRunIndex === runIndex) ||
nextStep.type === "queue_message" ||
(nextStep.type === "restart" && nextStep.targetRunIndex === runIndex))) ||
(nextStep.type === "restart" && nextStep.targetRunIndex === runIndex) ||
(nextStep.type === "release_replay_gate_after_waiting" &&
nextStep.targetRunIndex === runIndex))) ||
nextStep?.type === "approve_next_runtime_request" ||
nextStep?.type === "answer_next_user_input_request";
const key = `run:${runIndex}`;
@@ -470,9 +512,10 @@ export function materializeFixtureInput(input: {
}
}
break;
case "queue_message":
case "queue_message": {
messageIndex += 1;
runIndex += 1;
const nextStep = input.fixtureInput.steps[stepIndex + 1];
pushDispatch(
dispatchMessageCommand({
commandId: yield* idAllocator.allocate.command({
@@ -486,12 +529,48 @@ export function materializeFixtureInput(input: {
ordinal: messageIndex,
}),
text: step.text,
...(step.createdBy === undefined ? {} : { createdBy: step.createdBy }),
...(step.creationSource === undefined ? {} : { creationSource: step.creationSource }),
...(step.attachments === undefined ? {} : { attachments: step.attachments }),
dispatchMode: { type: "queue_after_active" },
}),
);
steps.push({ type: "await", key: `run:${runIndex - 1}` });
steps.push({ type: "await_thread_idle", threadId: ids.threadId });
const shouldSkipQueueBarrier =
nextStep?.type === "queue_message" ||
(nextStep?.type === "cancel_queued_run" && nextStep.targetRunIndex === runIndex);
if (!shouldSkipQueueBarrier) {
const queueBarrierKey =
Array.from(activeRunDispatchKeys).at(-1) ?? `run:${runIndex - 1}`;
activeRunDispatchKeys.delete(queueBarrierKey);
steps.push({ type: "await", key: queueBarrierKey });
steps.push({ type: "await_thread_idle", threadId: ids.threadId });
}
break;
}
case "cancel_queued_run":
pushDispatch({
type: "queued-run.cancel",
commandId: yield* idAllocator.allocate.command({
fixtureName: input.scenario,
commandName: `cancel-queued-run-${step.targetRunIndex}`,
}),
threadId: ids.threadId,
runId: runIdFor(step.targetRunIndex),
});
break;
case "await_run_status":
steps.push({
type: "await_run_status",
threadId: ids.threadId,
runId: runIdFor(step.targetRunIndex),
status: step.status,
});
break;
case "capture_shell_snapshot":
steps.push({ type: "capture_shell_snapshot", key: step.key });
break;
case "release_replay_gate":
steps.push({ type: "release_replay_gate", label: step.label });
break;
case "answer_next_user_input_request":
pushDispatch(
@@ -572,11 +651,17 @@ export function materializeFixtureInput(input: {
},
}),
);
if (input.fixtureInput.steps[stepIndex + 1]?.type !== "approve_next_runtime_request") {
if (activeRunDispatchKeys.delete(`run:${step.targetRunIndex}`)) {
steps.push({ type: "await", key: `run:${step.targetRunIndex}` });
{
const nextStepType = input.fixtureInput.steps[stepIndex + 1]?.type;
if (
nextStepType !== "approve_next_runtime_request" &&
nextStepType !== "answer_next_user_input_request"
) {
if (activeRunDispatchKeys.delete(`run:${step.targetRunIndex}`)) {
steps.push({ type: "await", key: `run:${step.targetRunIndex}` });
}
steps.push({ type: "await_thread_idle", threadId: ids.threadId });
}
steps.push({ type: "await_thread_idle", threadId: ids.threadId });
}
break;
case "restart":
@@ -606,11 +691,17 @@ export function materializeFixtureInput(input: {
},
}),
);
if (input.fixtureInput.steps[stepIndex + 1]?.type !== "approve_next_runtime_request") {
if (activeRunDispatchKeys.delete(`run:${step.targetRunIndex}`)) {
steps.push({ type: "await", key: `run:${step.targetRunIndex}` });
{
const nextStepType = input.fixtureInput.steps[stepIndex + 1]?.type;
if (
nextStepType !== "approve_next_runtime_request" &&
nextStepType !== "answer_next_user_input_request"
) {
if (activeRunDispatchKeys.delete(`run:${step.targetRunIndex}`)) {
steps.push({ type: "await", key: `run:${step.targetRunIndex}` });
}
steps.push({ type: "await_thread_idle", threadId: ids.threadId });
}
steps.push({ type: "await_thread_idle", threadId: ids.threadId });
}
break;
case "interrupt":
@@ -645,6 +736,14 @@ export function materializeFixtureInput(input: {
steps.push({ type: "advance_clock", duration: "1 millis" });
steps.push({ type: "await_thread_idle", threadId: ids.threadId });
break;
case "release_replay_gate_after_waiting":
steps.push({
type: "release_replay_gate_after_waiting",
label: step.label,
threadId: ids.threadId,
runId: runIdFor(step.targetRunIndex),
});
break;
case "advance_clock":
steps.push({ type: "advance_clock", duration: step.duration });
break;
@@ -194,6 +194,7 @@ export function describeThreadShellForAwareness(
return {
found: true,
status: shell.status,
activityRunStatus: shell.activityRunStatus ?? null,
activeRunId: shell.activeRunId ?? null,
latestRunId: shell.latestRunId ?? null,
pendingRuntimeRequestKind: shell.pendingRuntimeRequest?.kind ?? null,
+22
View File
@@ -48,6 +48,7 @@ import {
resolvePromptInjectedEffort,
} from "@t3tools/shared/model";
import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList";
import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { truncate } from "@t3tools/shared/String";
import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
@@ -2351,6 +2352,26 @@ function ChatViewContent(props: ChatViewProps) {
threadError,
});
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
const pendingBackgroundTasks = useMemo(() => {
if (serverProjection === null || serverProjection === undefined) {
return [];
}
const latestRun =
serverProjection.runs.length === 0
? null
: serverProjection.runs.reduce((latest, candidate) =>
candidate.ordinal > latest.ordinal ? candidate : latest,
);
return [
...derivePendingBackgroundWork({
latestRun,
providerThreads: serverProjection.providerThreads,
turnItems: serverProjection.turnItems,
activeProviderThreadId: serverProjection.thread.activeProviderThreadId,
runs: serverProjection.runs,
}),
];
}, [serverProjection]);
const activeWorkStartedAt = deriveActiveWorkStartedAt(
activeActivityRun,
activeRuntime,
@@ -6327,6 +6348,7 @@ function ChatViewContent(props: ChatViewProps) {
isWorking={isWorking}
activeTurnInProgress={isWorking || !latestRunSettled}
activeTurnStartedAt={activeWorkStartedAt}
pendingBackgroundTasks={pendingBackgroundTasks}
listRef={legendListRef}
timelineEntries={timelineEntries}
latestRun={activeActivityRun}
+106 -17
View File
@@ -21,10 +21,13 @@ import {
resolveSidebarStageBadgeLabel,
resolveThreadRowClassName,
resolveSidebarThreadStatus,
resolveSidebarV2Status,
resolveSidebarV2TopStatus,
resolveThreadStatusPill,
resolveWorkingStartedAt,
searchSidebarThreadsByTitle,
formatWorkingDurationLabel,
shouldShowSidebarV2Duration,
shouldNavigateAfterProjectRemoval,
shouldClearThreadSelectionOnMouseDown,
sortLogicalProjectsForSidebar,
@@ -38,7 +41,7 @@ import {
sortSettledThreadsForSidebarV2,
sortThreadsForSidebarV2,
sortScopedProjectsForSidebar,
shouldCreateNewThreadInCurrentProject,
sortProjectsForSidebar,
THREAD_JUMP_HINT_SHOW_DELAY_MS,
} from "./Sidebar.logic";
import { EnvironmentId, ProjectId, ProviderInstanceId, RunId, ThreadId } from "@t3tools/contracts";
@@ -500,21 +503,6 @@ describe("isTrailingDoubleClick", () => {
});
});
describe("shouldCreateNewThreadInCurrentProject", () => {
it("creates directly on shift+click in a multi-project setup", () => {
expect(shouldCreateNewThreadInCurrentProject(true, 2)).toBe(true);
});
it("opens the picker on a plain click in a multi-project setup", () => {
expect(shouldCreateNewThreadInCurrentProject(false, 2)).toBe(false);
});
it("creates directly on any click with a single project", () => {
expect(shouldCreateNewThreadInCurrentProject(false, 1)).toBe(true);
expect(shouldCreateNewThreadInCurrentProject(true, 1)).toBe(true);
});
});
describe("orderItemsByPreferredIds", () => {
it("keeps preferred ids first, skips stale ids, and preserves the relative order of remaining items", () => {
const ordered = orderItemsByPreferredIds({
@@ -735,6 +723,8 @@ describe("isContextMenuPointerDown", () => {
describe("resolveSidebarThreadStatus", () => {
const session = {
threadId: ThreadId.make("thread-1"),
describe("resolveSidebarV2Status", () => {
const runtime = {
status: "running" as const,
activeRunId: null,
providerInstanceId: ProviderInstanceId.make("codex"),
@@ -747,6 +737,8 @@ describe("resolveSidebarThreadStatus", () => {
it("prioritizes approval over a running session", () => {
expect(resolveSidebarThreadStatus({ ...idle, hasPendingApprovals: true, session })).toBe(
it("prioritizes approval over a running runtime", () => {
expect(resolveSidebarV2Status({ ...idle, hasPendingApprovals: true, runtime })).toBe(
"approval",
);
});
@@ -755,6 +747,8 @@ describe("resolveSidebarThreadStatus", () => {
expect(resolveSidebarThreadStatus({ ...idle, hasPendingUserInput: true, session })).toBe(
"input",
);
it("prioritizes awaiting input over a running runtime, below approval", () => {
expect(resolveSidebarV2Status({ ...idle, hasPendingUserInput: true, runtime })).toBe("input");
expect(
resolveSidebarThreadStatus({
...idle,
@@ -767,6 +761,8 @@ describe("resolveSidebarThreadStatus", () => {
it("reports working for running and starting sessions", () => {
expect(resolveSidebarThreadStatus({ ...idle, session })).toBe("working");
it("reports working for running and starting runtimes", () => {
expect(resolveSidebarV2Status({ ...idle, runtime })).toBe("working");
expect(
resolveSidebarThreadStatus({
...idle,
@@ -793,11 +789,24 @@ describe("resolveSidebarThreadStatus", () => {
...idle,
runtime: { ...runtime, status: "idle" as const, lastError: "persisted" },
}),
).toBe("ready");
).toBe("waiting");
});
it("defaults to ready with no session", () => {
expect(resolveSidebarThreadStatus({ ...idle, session: null })).toBe("ready");
it("defaults to ready with no runtime", () => {
expect(resolveSidebarV2Status(idle)).toBe("ready");
});
it("keeps a waiting runtime visible ahead of unread and woke presentation", () => {
expect(resolveSidebarV2TopStatus({ status: "waiting", isUnread: true, isWoke: true })).toBe(
"waiting",
);
});
it("keeps Waiting static while Working shows elapsed duration", () => {
expect(shouldShowSidebarV2Duration("waiting")).toBe(false);
expect(shouldShowSidebarV2Duration("working")).toBe(true);
});
});
@@ -1159,6 +1168,54 @@ describe("resolveThreadStatusPill", () => {
).toMatchObject({ label: "Working", pulse: true });
});
it("shows waiting for an idle thread with pending background tasks", () => {
expect(
resolveThreadStatusPill({
thread: {
...baseThread,
pendingBackgroundTasks: [{ taskId: "bg-1", description: "sleep 20" }],
runtime: {
...baseThread.runtime,
status: "idle",
activeRunId: null,
},
},
}),
).toMatchObject({
label: "Waiting",
colorClass: "text-sidebar-muted-foreground",
dotClass: "bg-sidebar-muted-foreground",
pulse: false,
});
});
it("keeps an active turn working when background tasks are also present", () => {
expect(
resolveThreadStatusPill({
thread: {
...baseThread,
pendingBackgroundTasks: [{ taskId: "bg-1", description: "sleep 20" }],
},
}),
).toMatchObject({ label: "Working", pulse: true });
});
it("does not show waiting after the background task roster clears", () => {
expect(
resolveThreadStatusPill({
thread: {
...baseThread,
pendingBackgroundTasks: [],
runtime: {
...baseThread.runtime,
status: "idle",
activeRunId: null,
},
},
}),
).toBeNull();
});
it("shows plan ready when a settled plan turn has a proposed plan ready for follow-up", () => {
expect(
resolveThreadStatusPill({
@@ -1281,6 +1338,38 @@ describe("resolveProjectStatusIndicator", () => {
]),
).toMatchObject({ label: "Plan Ready", dotClass: "bg-violet-500" });
});
it("ranks waiting below active work and above plan-ready", () => {
const waiting = {
label: "Waiting" as const,
colorClass: "text-sidebar-muted-foreground",
dotClass: "bg-sidebar-muted-foreground",
pulse: false,
};
expect(
resolveProjectStatusIndicator([
waiting,
{
label: "Working",
colorClass: "text-sky-600",
dotClass: "bg-sky-500",
pulse: true,
},
]),
).toMatchObject({ label: "Working" });
expect(
resolveProjectStatusIndicator([
{
label: "Plan Ready",
colorClass: "text-violet-600",
dotClass: "bg-violet-500",
pulse: false,
},
waiting,
]),
).toMatchObject({ label: "Waiting" });
});
});
describe("getVisibleThreadsForProject", () => {
+64 -57
View File
@@ -148,27 +148,24 @@ export function buildBulkTitleRegenerationContextMenuItem(input: {
export interface ThreadStatusPill {
label:
| "Working"
| "Monitoring"
| "Connecting"
| "Completed"
| "Pending Approval"
| "Awaiting Input"
| "Waiting"
| "Plan Ready";
colorClass: string;
dotClass: string;
pulse: boolean;
}
// Rollup order mirrors the per-thread resolver exactly: attention states,
// then active work, then the actionable plan prompt, then passive
// monitoring. A Monitoring sibling must never hide a Plan Ready thread.
const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
"Pending Approval": 6,
"Awaiting Input": 5,
Working: 4,
Connecting: 4,
"Plan Ready": 3,
Monitoring: 2,
"Pending Approval": 5,
"Awaiting Input": 4,
Working: 3,
Connecting: 3,
Waiting: 2.5,
"Plan Ready": 2,
Completed: 1,
};
@@ -178,16 +175,11 @@ type ThreadStatusInput = Pick<
| "hasPendingApprovals"
| "hasPendingUserInput"
| "interactionMode"
<<<<<<< HEAD
| "latestTurn"
| "session"
| "backgroundLiveness"
=======
| "latestRun"
| "runtime"
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
> & {
lastVisitedAt?: string | null | undefined;
pendingBackgroundTasks?: SidebarThreadSummary["pendingBackgroundTasks"] | undefined;
};
export interface ThreadJumpHintVisibilityController {
@@ -505,9 +497,14 @@ export function resolveThreadRowClassName(input: {
// ── Sidebar thread status model ─────────────────────────────────────
// Five visual states, three colors: color is reserved for "act now"
// ── Sidebar v2 status model ─────────────────────────────────────────
// Six visual states, three colors: color is reserved for "act now"
// (approval), "in motion" (working), and "broken" (failed). Ready is the
// unlabeled resting state — the agent stopped and is waiting on the user,
// whether it finished, asked a question, or proposed a plan.
// whether it finished, asked a question, or proposed a plan. Waiting
// (runtime status "idle") is the agent stopped with background tasks still
// open: not the user's turn yet, so it renders grey like working, not as a
// false Done.
// Unread completion is tracked separately: it describes whether a ready
// thread needs attention, not what the thread is currently doing.
export type SidebarThreadStatus =
@@ -517,14 +514,11 @@ export type SidebarThreadStatus =
| "monitoring"
| "failed"
| "ready";
export type SidebarV2Status = "approval" | "input" | "working" | "waiting" | "failed" | "ready";
type SidebarThreadStatusInput = Pick<
SidebarThreadSummary,
<<<<<<< HEAD
"hasPendingApprovals" | "hasPendingUserInput" | "session" | "backgroundLiveness"
=======
"hasPendingApprovals" | "hasPendingUserInput" | "runtime"
>>>>>>> 0c15987295 (fix: reconcile rebase with latest main)
>;
export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
@@ -540,24 +534,52 @@ export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): Si
) {
return "working";
}
<<<<<<< HEAD
// A failed session outranks lingering background liveness: the user must
// see the failure, not a stale Working (review finding).
if (thread.session?.status === "error") {
=======
if (thread.runtime?.status === "idle") {
return "waiting";
}
if (thread.runtime?.status === "failed") {
>>>>>>> 0c15987295 (fix: reconcile rebase with latest main)
return "failed";
}
// Background work outlives the turn: fleets read as working; monitoring
// only when watch loops are the sole live work.
if (thread.backgroundLiveness === "working") {
return "ready";
}
export type SidebarV2TopStatusKind =
| "approval"
| "done"
| "failed"
| "input"
| "waiting"
| "woke"
| "working";
export function resolveSidebarV2TopStatus(input: {
readonly status: SidebarV2Status;
readonly isUnread: boolean;
readonly isWoke: boolean;
}): SidebarV2TopStatusKind | null {
if (input.status === "working") {
return "working";
}
if (thread.backgroundLiveness === "monitoring") {
return "monitoring";
if (input.status === "waiting") {
return "waiting";
}
return "ready";
if (input.status === "approval") {
return "approval";
}
if (input.status === "input") {
return "input";
}
if (input.status === "failed") {
return "failed";
}
if (input.isWoke) {
return "woke";
}
return input.isUnread ? "done" : null;
}
export function shouldShowSidebarV2Duration(status: SidebarV2Status): boolean {
return status === "working";
}
/** NaN-safe Date.parse for sort comparators: a malformed timestamp must not
@@ -742,8 +764,15 @@ export function resolveThreadStatusPill(input: {
};
}
// An actionable plan prompt outranks lingering background work: it needs
// the user's decision, while liveness merely reports (review finding).
if ((thread.pendingBackgroundTasks?.length ?? 0) > 0) {
return {
label: "Waiting",
colorClass: "text-sidebar-muted-foreground",
dotClass: "bg-sidebar-muted-foreground",
pulse: false,
};
}
const hasPlanReadyPrompt =
!thread.hasPendingUserInput &&
thread.interactionMode === "plan" &&
@@ -758,28 +787,6 @@ export function resolveThreadStatusPill(input: {
};
}
// The turn can settle while native background work runs on. Subagent and
// workflow fleets read as plain Working; Monitoring is reserved for watch
// loops (a parent agent babysitting a PR, tailing checks) with no other
// live work. Same recede treatment as Working per inbox-zero.
if (thread.backgroundLiveness === "working") {
return {
label: "Working",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
if (thread.backgroundLiveness === "monitoring") {
return {
label: "Monitoring",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: false,
};
}
if (hasUnseenCompletion(thread)) {
return {
label: "Completed",
+43 -40
View File
@@ -118,9 +118,11 @@ import {
resolveAdjacentThreadId,
resolveSettledTimestamp,
resolveSidebarV2Status,
resolveSidebarV2TopStatus,
resolveThreadLastVisitedAt,
resolveWorkingStartedAt,
searchSidebarThreadsByTitle,
shouldShowSidebarV2Duration,
shouldNavigateAfterProjectRemoval,
sortSidebarV2ProjectGroups,
sortSettledThreadsForSidebarV2,
@@ -175,6 +177,44 @@ const PROJECT_GROUPING_MODE_LABELS: Record<SidebarProjectGroupingMode, string> =
repository_path: "Group by repository path",
separate: "Keep separate",
};
const SIDEBAR_V2_TOP_STATUS = {
approval: {
label: "Approval",
icon: null,
className: "text-amber-700 dark:text-amber-300",
},
done: {
label: "Done",
icon: "done",
className: "text-emerald-700 dark:text-emerald-300",
},
failed: {
label: "Failed",
icon: null,
className: "text-red-700 dark:text-red-300",
},
input: {
label: "Input",
icon: null,
className: "text-indigo-600 dark:text-indigo-300",
},
waiting: {
label: "Waiting",
icon: null,
className: "text-muted-foreground",
},
woke: {
label: "Woke",
icon: "woke",
className: "text-amber-700 dark:text-amber-300",
},
working: {
label: "Working",
icon: "working",
className:
"animate-sidebar-working-text text-sky-600 motion-reduce:animate-none dark:text-sky-400",
},
} as const;
function compactSidebarTimeLabel(label: string): string {
if (label === "just now") return "now";
@@ -491,45 +531,8 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
// Status hues follow the system-wide convention set by sidebar v1 and the
// mobile Live Activity/widgets (amber approval, indigo input, sky working)
// so a thread reads the same color everywhere it surfaces.
const topStatus =
status === "working"
? {
label: "Working",
icon: "working" as const,
className:
"animate-sidebar-working-text text-sky-600 motion-reduce:animate-none dark:text-sky-400",
}
: status === "approval"
? {
label: "Approval",
icon: null,
className: "text-amber-700 dark:text-amber-300",
}
: status === "input"
? {
label: "Input",
icon: null,
className: "text-indigo-600 dark:text-indigo-300",
}
: status === "failed"
? {
label: "Failed",
icon: null,
className: "text-red-700 dark:text-red-300",
}
: isWoke
? {
label: "Woke",
icon: "woke" as const,
className: "text-amber-700 dark:text-amber-300",
}
: isUnread
? {
label: "Done",
icon: "done" as const,
className: "text-emerald-700 dark:text-emerald-300",
}
: null;
const topStatusKind = resolveSidebarV2TopStatus({ status, isUnread, isWoke });
const topStatus = topStatusKind === null ? null : SIDEBAR_V2_TOP_STATUS[topStatusKind];
const gitCwd = thread.worktreePath ?? props.projectCwd;
const gitStatus = useEnvironmentQuery(
@@ -987,7 +990,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
wrapper around the ticking duration would make
screen readers announce every second. */}
<span role="status">{topStatus.label}</span>
{status === "working" ? (
{shouldShowSidebarV2Duration(status) ? (
<span aria-hidden>
<WorkingDuration startedAt={resolveWorkingStartedAt(thread)} />
</span>
@@ -1432,3 +1432,66 @@ describe("computeStableMessagesTimelineRows", () => {
expect(reordered.result).toEqual([initial.result[1], initial.result[0]]);
});
});
describe("deriveMessagesTimelineRows waiting-background", () => {
it("renders the waiting-background row instead of Working for a parked waiting runtime", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [],
isWorking: false,
activeTurnStartedAt: null,
pendingBackgroundTasks: [{ taskId: "bg-1", description: "Run Codex review" }],
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
expect(rows).toEqual([
{
kind: "waiting-background",
id: "waiting-background-row",
createdAt: null,
description: "Run Codex review",
taskCount: 1,
label: "Waiting on background task: Run Codex review",
},
]);
});
it("suppresses a stale waiting roster while an active running turn is Working", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [],
isWorking: true,
activeTurnStartedAt: "2026-01-01T00:00:00Z",
pendingBackgroundTasks: [{ taskId: "bg-1", description: "Run Codex review" }],
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
expect(rows.some((row) => row.kind === "waiting-background")).toBe(false);
expect(rows.some((row) => row.kind === "working")).toBe(true);
});
it("includes task count for multiple background tasks", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [],
isWorking: false,
activeTurnStartedAt: null,
pendingBackgroundTasks: [
{ taskId: "bg-1", description: "first" },
{ taskId: "bg-2", description: "second" },
],
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
expect(rows).toEqual([
{
kind: "waiting-background",
id: "waiting-background-row",
createdAt: null,
description: "first",
taskCount: 2,
label: "Waiting on 2 background tasks: first, …",
},
]);
});
});
@@ -3,7 +3,6 @@ import {
formatDuration,
timelineEntryIsPersistentResourceCard,
type TimelineEntry,
type TurnPlanEntry,
type WorkLogEntry,
} from "../../session-logic";
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
@@ -14,6 +13,7 @@ import {
type RunId,
} from "@t3tools/contracts";
import type { ThreadRunSummary } from "@t3tools/client-runtime/state/shell";
import { formatPendingBackgroundWorkLabel } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
import {
resolveT3McpToolPresentation,
type T3McpToolPresentation,
@@ -28,37 +28,11 @@ export const TIMELINE_MINIMAP_PERSISTENT_GUTTER = 48;
export interface TimelineEndState {
readonly isAtEnd?: boolean;
readonly contentLength?: number;
readonly scroll?: number;
readonly scrollLength?: number;
readonly isNearEnd?: boolean;
}
/**
* Follow re-arm band above the hard bottom. Strict on purpose: LegendList's
* isNearEnd fires within half a viewport, which re-armed live-follow while the
* user was reading history and yanked them back down on the next stream chunk.
* A small pixel band (instead of the 1px isAtEnd epsilon alone) keeps re-arming
* reliable while streaming content is still growing under the viewport.
*/
export const TIMELINE_FOLLOW_REARM_THRESHOLD_PX = 40;
export function resolveTimelineIsAtEnd(
state: TimelineEndState | undefined,
endInset = 0,
): boolean | undefined {
if (!state) {
return undefined;
}
if (state.isAtEnd) {
return true;
}
const { contentLength, scroll, scrollLength } = state;
if (contentLength === undefined || scroll === undefined || scrollLength === undefined) {
return state.isAtEnd;
}
// contentLength includes the end inset (composer overlay), so subtract it to
// measure the distance to the real content bottom.
return contentLength - scroll - scrollLength - endInset <= TIMELINE_FOLLOW_REARM_THRESHOLD_PX;
export function resolveTimelineIsAtEnd(state: TimelineEndState | undefined): boolean | undefined {
return state?.isNearEnd ?? state?.isAtEnd;
}
export function shouldPreserveAssistantLineBreaks(text: string): boolean {
@@ -222,13 +196,15 @@ export type MessagesTimelineRow =
createdAt: string;
proposedPlan: ProposedPlan;
}
| { kind: "working"; id: string; createdAt: string | null }
| {
kind: "turn-plan";
kind: "waiting-background";
id: string;
createdAt: string;
turnPlan: TurnPlanEntry;
}
| { kind: "working"; id: string; createdAt: string | null };
createdAt: string | null;
description: string | null;
taskCount: number;
label: string;
};
export interface StableMessagesTimelineRowsState {
byId: Map<string, MessagesTimelineRow>;
@@ -474,13 +450,6 @@ function deriveTurnFolds(input: {
if (entry.id !== group.terminalEntry?.id && !timelineEntryIsPersistentResourceCard(entry)) {
hiddenEntryIds.add(entry.id);
}
// Agent-spawn CTA rows never fold: workflows outlive their launching
// turn (dynamic spawns, background execution), and folding the CTA
// when the turn settles makes a still-running fleet invisible.
if (entry.kind === "work" && entry.entry.agentSpawn !== undefined) {
continue;
}
hiddenEntryIds.add(entry.id);
}
if (hiddenEntryIds.size === 0) {
continue;
@@ -533,6 +502,10 @@ export function deriveMessagesTimelineRows(input: {
expandedAttemptIds?: ReadonlySet<RunAttemptId>;
isWorking: boolean;
activeTurnStartedAt: string | null;
pendingBackgroundTasks?: ReadonlyArray<{
readonly taskId: string;
readonly description?: string | undefined;
}> | null;
turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
}): MessagesTimelineRow[] {
@@ -633,69 +606,12 @@ export function deriveMessagesTimelineRows(input: {
groupedEntries.push(nextEntry.entry);
cursor += 1;
}
<<<<<<< HEAD
const visibleGroupedEntries = groupedEntries.filter(
(entry) => !workEntryIndicatesToolNeutralStatus(entry),
);
if (visibleGroupedEntries.length > 0) {
if (visibleGroupedEntries.length <= MAX_VISIBLE_WORK_LOG_ENTRIES) {
nextRows.push({
kind: "work",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
groupedEntries: visibleGroupedEntries,
});
} else {
const groupId = `work-group:${timelineEntry.id}`;
const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
// Agent-spawn CTA rows are always visible: a running fleet must
// never hide behind a "+N tool calls" toggle. Selection is by
// membership (spawn OR recent-tail), preserving the group's
// chronological order in both collapsed and expanded states
// (review finding: concatenating two filtered lists moved a
// mid-group spawn row above earlier tool rows).
const overflowCandidates = visibleGroupedEntries.filter(
(entry) => entry.agentSpawn === undefined,
);
const hiddenEntries = overflowCandidates.slice(0, -MAX_VISIBLE_WORK_LOG_ENTRIES);
const hiddenIds = new Set(hiddenEntries.map((entry) => entry.id));
const visibleEntries = visibleGroupedEntries.filter(
(entry) => entry.agentSpawn !== undefined || !hiddenIds.has(entry.id),
);
const renderedEntries = expanded ? visibleGroupedEntries : visibleEntries;
for (const workEntry of renderedEntries) {
nextRows.push({
kind: "work",
id: workEntry.id,
createdAt: workEntry.createdAt,
groupedEntries: [workEntry],
});
}
if (hiddenEntries.length > 0) {
nextRows.push({
kind: "work-toggle",
id: `work-toggle:${timelineEntry.id}`,
createdAt: timelineEntry.createdAt,
groupId,
hiddenCount: hiddenEntries.length,
expanded,
onlyToolEntries: visibleGroupedEntries.every((entry) =>
workLogEntryIsToolLike(entry),
),
});
}
}
}
=======
nextRows.push({
kind: "work",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
groupedEntries,
});
>>>>>>> 0c15987295 (fix: reconcile rebase with latest main)
index = cursor - 1;
continue;
}
@@ -765,6 +681,20 @@ export function deriveMessagesTimelineRows(input: {
id: "working-indicator-row",
createdAt: input.activeTurnStartedAt,
});
} else if (input.pendingBackgroundTasks && input.pendingBackgroundTasks.length > 0) {
// Root run settled but finite provider background work remains. Show Waiting
// instead of looking fully idle until the roster drains.
const firstTask = input.pendingBackgroundTasks[0];
nextRows.push({
kind: "waiting-background",
id: "waiting-background-row",
createdAt: input.activeTurnStartedAt,
description: firstTask?.description ?? null,
taskCount: input.pendingBackgroundTasks.length,
label:
formatPendingBackgroundWorkLabel(input.pendingBackgroundTasks) ??
"Waiting on a background task",
});
}
return nextRows;
@@ -798,6 +728,16 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
case "working":
return a.createdAt === (b as typeof a).createdAt;
case "waiting-background": {
const bw = b as typeof a;
return (
a.createdAt === bw.createdAt &&
a.description === bw.description &&
a.taskCount === bw.taskCount &&
a.label === bw.label
);
}
case "turn-fold": {
const bf = b as typeof a;
return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded;
@@ -189,6 +189,10 @@ interface MessagesTimelineProps {
isWorking: boolean;
activeTurnInProgress: boolean;
activeTurnStartedAt: string | null;
pendingBackgroundTasks?: ReadonlyArray<{
readonly taskId: string;
readonly description?: string | undefined;
}> | null;
listRef: React.RefObject<LegendListRef | null>;
timelineEntries: ReadonlyArray<TimelineEntry>;
latestRun: TimelineLatestRun | null;
@@ -238,6 +242,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
isWorking,
activeTurnInProgress,
activeTurnStartedAt,
pendingBackgroundTasks = null,
listRef,
timelineEntries,
latestRun,
@@ -336,6 +341,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
expandedAttemptIds,
isWorking,
activeTurnStartedAt,
pendingBackgroundTasks,
turnDiffSummaryByAssistantMessageId,
revertTurnCountByUserMessageId,
}),
@@ -346,6 +352,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
expandedAttemptIds,
isWorking,
activeTurnStartedAt,
pendingBackgroundTasks,
turnDiffSummaryByAssistantMessageId,
revertTurnCountByUserMessageId,
],
@@ -944,6 +951,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
{row.kind === "proposed-plan" ? <ProposedPlanTimelineRow row={row} /> : null}
{row.kind === "event" ? <V2EventTimelineRow row={row} /> : null}
{row.kind === "working" ? <WorkingTimelineRow row={row} /> : null}
{row.kind === "waiting-background" ? <WaitingBackgroundTimelineRow row={row} /> : null}
</div>
);
});
@@ -1599,6 +1607,25 @@ function WorkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "workin
);
}
function WaitingBackgroundTimelineRow({
row,
}: {
row: Extract<TimelineRow, { kind: "waiting-background" }>;
}) {
return (
<div className="py-0.5 pl-1.5">
<div className="flex items-center gap-2 pt-1 text-[11px] text-muted-foreground/70 tabular-nums">
<span className="inline-flex items-center gap-[3px]">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-status-pulse" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-status-pulse [animation-delay:200ms]" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-status-pulse [animation-delay:400ms]" />
</span>
<span className="line-clamp-2 min-w-0 flex-1 break-words">{row.label}</span>
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// Self-ticking labels — update their own text nodes so elapsed-time display
// does not create a React commit every second while a response is streaming.
@@ -107,6 +107,147 @@ describe("V2 client presentation", () => {
});
});
it("parks presented runtime at idle when a settled shell has pending background tasks", () => {
const runId = RunId.make("run-completed");
const shell = presentThreadShell(environmentId, {
...v2ThreadShell,
latestRunId: runId,
activeRunId: null,
status: "completed",
pendingBackgroundTasks: [{ taskId: "bg-1", description: "sleep 20" }],
});
expect(shell.latestRun).toMatchObject({ runId, status: "completed" });
expect(shell.runtime).toMatchObject({
status: "idle",
activeRunId: null,
});
expect(shell.pendingBackgroundTasks).toEqual([{ taskId: "bg-1", description: "sleep 20" }]);
});
it("keeps terminal runtime completed when there are no pending background tasks", () => {
const runId = RunId.make("run-completed");
const shell = presentThreadShell(environmentId, {
...v2ThreadShell,
latestRunId: runId,
activeRunId: null,
status: "completed",
pendingBackgroundTasks: [],
});
expect(shell.latestRun).toMatchObject({ runId, status: "completed" });
expect(shell.runtime).toMatchObject({
status: "completed",
activeRunId: null,
});
});
it("keeps runtime running when there is no background roster", () => {
const runId = RunId.make("run-running");
const shell = presentThreadShell(environmentId, {
...v2ThreadShell,
latestRunId: runId,
activeRunId: runId,
status: "running",
pendingBackgroundTasks: [],
});
expect(shell.latestRun).toMatchObject({ runId, status: "running" });
expect(shell.runtime).toMatchObject({
status: "running",
activeRunId: runId,
});
});
it("keeps an older active run visible over a newer cancelled run", () => {
const activeRunId = RunId.make("run-active");
const cancelledRunId = RunId.make("run-cancelled");
const shell = presentThreadShell(environmentId, {
...v2ThreadShell,
latestRunId: cancelledRunId,
latestRunStartedAt: null,
latestRunCompletedAt: DateTime.makeUnsafe("2026-06-20T01:05:00.000Z"),
activeRunId,
activityRunStatus: "running",
status: "cancelled",
pendingBackgroundTasks: [],
});
expect(shell.latestRun).toMatchObject({ runId: cancelledRunId, status: "cancelled" });
expect(shell.runtime).toMatchObject({
status: "running",
activeRunId,
});
});
it("keeps an older waiting run visible over a newer cancelled run", () => {
const shell = presentThreadShell(environmentId, {
...v2ThreadShell,
latestRunId: RunId.make("run-cancelled"),
activeRunId: null,
activityRunStatus: "waiting",
status: "cancelled",
pendingBackgroundTasks: [],
});
expect(shell.runtime).toMatchObject({ status: "waiting", activeRunId: null });
});
it("keeps a post-settlement background roster ahead of activity status", () => {
const activeRunId = RunId.make("run-active");
const shell = presentThreadShell(environmentId, {
...v2ThreadShell,
latestRunId: RunId.make("run-cancelled"),
activeRunId,
activityRunStatus: "running",
status: "cancelled",
pendingBackgroundTasks: [{ taskId: "bg-activity", description: "background work" }],
});
expect(shell.runtime).toMatchObject({ status: "idle", activeRunId });
});
it("parks runtime idle over stale shell running when the roster is nonempty", () => {
const runId = RunId.make("run-stale-running");
const shell = presentThreadShell(environmentId, {
...v2ThreadShell,
latestRunId: runId,
activeRunId: runId,
// Stale: server already projected a post-settlement roster, but shell
// status still says running (packaged orchestrator-v2 bug).
status: "running",
pendingBackgroundTasks: [{ taskId: "bg-1", description: "sleep 20" }],
});
expect(shell.latestRun).toMatchObject({ runId, status: "running" });
expect(shell.runtime).toMatchObject({
status: "idle",
activeRunId: runId,
});
expect(shell.pendingBackgroundTasks).toEqual([{ taskId: "bg-1", description: "sleep 20" }]);
});
it("parks runtime idle over stale checkpoint waiting when the roster is nonempty", () => {
const runId = RunId.make("run-stale-waiting");
const shell = presentThreadShell(environmentId, {
...v2ThreadShell,
latestRunId: runId,
activeRunId: runId,
// Stale: checkpoint-oriented waiting masks post-settlement background work.
status: "waiting",
pendingBackgroundTasks: [{ taskId: "bg-2", description: "background bash" }],
});
expect(shell.latestRun).toMatchObject({ runId, status: "waiting" });
expect(shell.runtime).toMatchObject({
status: "idle",
activeRunId: runId,
});
expect(shell.pendingBackgroundTasks).toEqual([
{ taskId: "bg-2", description: "background bash" },
]);
});
it("derives execution summaries without wrapping or copying the projection", () => {
const runId = RunId.make("run-1");
const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
@@ -163,6 +304,67 @@ describe("V2 client presentation", () => {
});
});
it("parks waiting runtime for a post-settlement roster without hiding active running work", () => {
const runId = RunId.make("run-background-presentation");
const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
const run = {
id: runId,
threadId: v2Projection.thread.id,
ordinal: 1,
providerInstanceId: v2Projection.thread.providerInstanceId,
modelSelection: v2Projection.thread.modelSelection,
providerThreadId: null,
userMessageId: MessageId.make("message-background-presentation"),
rootNodeId: null,
activeAttemptId: null,
status: "waiting" as const,
requestedAt: now,
startedAt: now,
completedAt: null,
checkpointId: null,
contextHandoffId: null,
};
const backgroundItem = {
id: TurnItemId.make("item-background-command"),
threadId: v2Projection.thread.id,
runId,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 0,
status: "running" as const,
title: "Background command",
startedAt: now,
completedAt: null,
updatedAt: now,
type: "command_execution" as const,
input: "sleep 20",
};
expect(
deriveThreadRuntime({
...v2Projection,
runs: [run],
turnItems: [backgroundItem],
}),
).toMatchObject({
status: "idle",
activeRunId: null,
});
expect(
deriveThreadRuntime({
...v2Projection,
runs: [{ ...run, status: "running" as const }],
turnItems: [backgroundItem],
}),
).toMatchObject({
status: "running",
activeRunId: runId,
});
});
it("joins pending request entities to their native turn-item display data", () => {
const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
const requestId = RuntimeRequestId.make("request-approval");
+12 -1
View File
@@ -86,6 +86,9 @@ export interface EnvironmentThreadShell {
readonly hasPendingApprovals: boolean;
readonly hasPendingUserInput: boolean;
readonly hasActionableProposedPlan: boolean;
readonly pendingBackgroundTasks: ReadonlyArray<
NonNullable<OrchestrationV2ThreadShell["pendingBackgroundTasks"]>[number]
>;
readonly itemCount: number;
readonly visibleItemCount: number;
readonly createdAt: string;
@@ -126,10 +129,17 @@ function terminalRunStatus(status: OrchestrationV2RunStatus): boolean {
);
}
// Park runtime at idle when the post-settlement background roster is nonempty
// so #4415 waiting-presentation Waiting (session.idle) can consume CTM runtime.
// The server suppresses the roster while an interruptible activity run exists,
// so a remaining roster is stronger than checkpoint-oriented waiting.
// latestRun keeps the latest run's status for history presentation.
function shellRuntime(thread: OrchestrationV2ThreadShell): ThreadRuntimeSummary | null {
if (thread.latestRunId === null && thread.activeProviderThreadId === null) return null;
const hasPendingBackgroundTasks = (thread.pendingBackgroundTasks?.length ?? 0) > 0;
const status = hasPendingBackgroundTasks ? "idle" : (thread.activityRunStatus ?? thread.status);
return {
status: thread.status,
status,
activeRunId: thread.activeRunId,
providerInstanceId: thread.providerInstanceId,
providerName: null,
@@ -189,6 +199,7 @@ export function presentThreadShell(
thread.pendingRuntimeRequest.kind !== "auth_refresh",
hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input",
hasActionableProposedPlan: thread.hasActionableProposedPlan,
pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
itemCount: thread.itemCount,
visibleItemCount: thread.visibleItemCount,
createdAt: iso(thread.createdAt),
@@ -85,4 +85,30 @@ describe("thread execution presentation", () => {
});
expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
});
it("does not expose a stale active run after the runtime parks at idle", () => {
const runtime = {
status: "idle" as const,
activeRunId: RunId.make("run-stale"),
providerInstanceId: v2Projection.thread.providerInstanceId,
providerName: null,
lastError: null,
updatedAt: DateTime.formatIso(now),
};
expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(false);
});
it.each(["preparing", "starting"] as const)("keeps an active %s run interruptible", (status) => {
const runtime = {
status,
activeRunId: RunId.make(`run-${status}`),
providerInstanceId: v2Projection.thread.providerInstanceId,
providerName: null,
lastError: null,
updatedAt: DateTime.formatIso(now),
};
expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(true);
});
});
@@ -1,7 +1,12 @@
import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts";
import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
import * as DateTime from "effect/DateTime";
import type { ThreadRunSummary, ThreadRuntimeSummary } from "./models.ts";
import {
threadRuntimeIsActive,
type ThreadRunSummary,
type ThreadRuntimeSummary,
} from "./models.ts";
const ACTIVITY_RUN_STATUSES = new Set(["preparing", "starting", "running", "waiting"]);
const INTERRUPTIBLE_RUN_STATUSES = new Set(["preparing", "starting", "running"]);
@@ -62,6 +67,7 @@ export function deriveThreadRuntime(
projection: OrchestrationV2ThreadProjection,
): ThreadRuntimeSummary | null {
const latestRun = deriveLatestThreadRun(projection);
const latestRunProjection = latestMatchingRun(projection, () => true);
const activityRun = deriveThreadActivityRun(projection);
const providerSession = projection.providerSessions.findLast(
(session) => session.providerInstanceId === projection.thread.providerInstanceId,
@@ -69,11 +75,16 @@ export function deriveThreadRuntime(
if (latestRun === null && projection.thread.activeProviderThreadId === null) return null;
const activeRunId =
latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status))?.id ?? null;
const hasPendingBackgroundTasks =
derivePendingBackgroundWork({
latestRun: latestRunProjection,
providerThreads: projection.providerThreads,
turnItems: projection.turnItems,
activeProviderThreadId: projection.thread.activeProviderThreadId,
runs: projection.runs,
}).length > 0;
return {
// Queueing creates a newer run, but does not replace the provider work
// already in flight. Present the executing run's status until it reaches
// a terminal state so clients do not flash from "running" to "queued".
status: activityRun?.status ?? "idle",
status: hasPendingBackgroundTasks ? "idle" : (activityRun?.status ?? "idle"),
activeRunId,
providerInstanceId: projection.thread.providerInstanceId,
providerName: providerSession?.driver ?? null,
@@ -85,5 +96,9 @@ export function deriveThreadRuntime(
export function threadRuntimeHasInterruptibleRun(
runtime: ThreadRuntimeSummary | null | undefined,
): boolean {
return runtime?.activeRunId !== null && runtime?.activeRunId !== undefined;
return (
threadRuntimeIsActive(runtime) &&
runtime?.activeRunId !== null &&
runtime?.activeRunId !== undefined
);
}
@@ -12,6 +12,32 @@ import {
} from "./threadRelationships.ts";
describe("thread relationships", () => {
it("keeps an older activity run visible over a newer cancelled run", () => {
const parent = ThreadId.make("thread-parent");
const child = ThreadId.make("thread-child");
const graph = deriveThreadRelationshipGraph({
threads: [
{
id: child,
title: "Active child",
activityRunStatus: "running",
status: "cancelled",
forkedFrom: { type: "run", threadId: parent, runId: "run-parent" },
lineage: {
rootThreadId: parent,
parentThreadId: parent,
relationshipToParent: "subagent",
},
},
] as never,
projection: null,
});
expect(graph.edges).toEqual([
expect.objectContaining({ targetThreadId: child, status: "running" }),
]);
});
it("keeps missing parents and cycles navigable without recursive traversal", () => {
const root = ThreadId.make("thread-root");
const child = ThreadId.make("thread-child");
@@ -84,7 +84,7 @@ export function deriveThreadRelationshipGraph(input: {
sourceThreadId: parentThreadId,
targetThreadId: thread.id,
kind: thread.lineage.relationshipToParent === "subagent" ? "subagent" : "fork",
status: thread.status,
status: thread.activityRunStatus ?? thread.status,
});
}
@@ -24,9 +24,12 @@ import {
OrchestrationV2CheckpointScope,
OrchestrationV2Command,
OrchestrationV2DomainEvent,
OrchestrationV2ProviderThread,
OrchestrationV2ProviderThreadJson,
OrchestrationV2ShellSnapshot,
OrchestrationV2Subagent,
OrchestrationV2ThreadProjection,
OrchestrationV2ThreadShell,
OrchestrationV2TurnItem,
} from "./orchestrationV2.ts";
@@ -51,6 +54,11 @@ const decodeOrchestrationV2Subagent = Schema.decodeUnknownSync(OrchestrationV2Su
const decodeOrchestrationV2ThreadProjection = Schema.decodeUnknownSync(
OrchestrationV2ThreadProjection,
);
const decodeOrchestrationV2ProviderThreadJson = Schema.decodeUnknownSync(
OrchestrationV2ProviderThreadJson,
);
const decodeOrchestrationV2ProviderThread = Schema.decodeUnknownSync(OrchestrationV2ProviderThread);
const decodeOrchestrationV2ThreadShell = Schema.decodeUnknownSync(OrchestrationV2ThreadShell);
describe("orchestration V2 contracts", () => {
it("lets legacy snapshot decoders ignore enrichment metadata", () => {
@@ -673,4 +681,92 @@ describe("orchestration V2 contracts", () => {
expect(CheckpointRef.make("git-ref-1")).toBe("git-ref-1");
expect(ContextTransferId.make("context-transfer-1")).toBe("context-transfer-1");
});
it("decodes historical provider-thread JSON without pendingBackgroundTasks as empty roster", () => {
const providerThread = decodeOrchestrationV2ProviderThreadJson({
id: "provider-thread-1",
driver: "claude",
providerInstanceId: "claudeAgent",
providerSessionId: "provider-session-1",
appThreadId: "thread-1",
ownerNodeId: null,
nativeThreadRef: {
driver: "claude",
nativeId: "native-session-1",
strength: "strong",
},
nativeConversationHeadRef: null,
status: "idle",
firstRunOrdinal: 1,
lastRunOrdinal: 1,
handoffIds: [],
forkedFrom: null,
createdAt: "2026-04-20T00:00:00.000Z",
updatedAt: "2026-04-20T00:00:00.000Z",
});
expect(providerThread.pendingBackgroundTasks).toEqual([]);
const runtimeThread = decodeOrchestrationV2ProviderThread({
id: "provider-thread-2",
driver: "claude",
providerInstanceId: "claudeAgent",
providerSessionId: null,
appThreadId: "thread-2",
ownerNodeId: null,
nativeThreadRef: null,
nativeConversationHeadRef: null,
status: "idle",
firstRunOrdinal: null,
lastRunOrdinal: null,
handoffIds: [],
forkedFrom: null,
createdAt: now,
updatedAt: now,
});
expect(runtimeThread.pendingBackgroundTasks).toEqual([]);
});
it("decodes historical thread shell JSON without pendingBackgroundTasks as empty roster", () => {
const shell = decodeOrchestrationV2ThreadShell({
createdBy: "user",
creationSource: "web",
id: "thread-1",
projectId: "project-1",
title: "Thread",
providerInstanceId: "claudeAgent",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
lineage: {
parentThreadId: null,
relationshipToParent: null,
rootThreadId: "thread-1",
},
forkedFrom: null,
activeProviderThreadId: "provider-thread-1",
latestRunId: "run-1",
activeRunId: null,
status: "completed",
pendingRuntimeRequest: null,
latestVisibleMessage: null,
latestUserMessageAt: null,
hasActionableProposedPlan: false,
itemCount: 0,
visibleItemCount: 0,
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
});
expect(shell.pendingBackgroundTasks).toEqual([]);
});
});
+24
View File
@@ -557,6 +557,18 @@ export const OrchestrationV2ProviderSessionDetached = Schema.Struct({
export type OrchestrationV2ProviderSessionDetached =
typeof OrchestrationV2ProviderSessionDetached.Type;
/**
* Provider-owned background work that can outlive the root turn (for example a
* Claude background Bash task). Associated with the provider thread so shared
* runtimes cannot make an unrelated app thread look busy.
*/
export const OrchestrationV2PendingBackgroundTask = Schema.Struct({
taskId: TrimmedNonEmptyString,
description: Schema.optional(TrimmedNonEmptyString),
taskType: Schema.optional(TrimmedNonEmptyString),
});
export type OrchestrationV2PendingBackgroundTask = typeof OrchestrationV2PendingBackgroundTask.Type;
export const OrchestrationV2ProviderThread = Schema.Struct({
id: ProviderThreadId,
driver: ProviderDriverKind,
@@ -577,6 +589,10 @@ export const OrchestrationV2ProviderThread = Schema.Struct({
checkpointId: Schema.optional(CheckpointId),
}),
),
// Optional Type so adapters can omit empty rosters; historical JSON decodes to [].
pendingBackgroundTasks: Schema.optional(Schema.Array(OrchestrationV2PendingBackgroundTask)).pipe(
Schema.withDecodingDefault(Effect.succeed([])),
),
createdAt: Schema.DateTimeUtc,
updatedAt: Schema.DateTimeUtc,
});
@@ -1260,12 +1276,20 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
latestRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
latestRunCompletedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
activeRunId: Schema.NullOr(RunId),
activityRunStatus: Schema.optional(
Schema.NullOr(Schema.Literals(["preparing", "starting", "running", "waiting"])),
),
status: OrchestrationV2ShellThreadStatus,
lastError: Schema.optional(Schema.NullOr(Schema.String)),
pendingRuntimeRequest: Schema.NullOr(OrchestrationV2PendingRuntimeRequestSummary),
latestVisibleMessage: Schema.NullOr(OrchestrationV2LatestVisibleMessageSummary),
latestUserMessageAt: Schema.NullOr(Schema.DateTimeUtc),
hasActionableProposedPlan: Schema.Boolean,
// Normalized post-settlement background work for sidebar Waiting pills.
// Empty when the latest root run is still active or no pending work remains.
pendingBackgroundTasks: Schema.optional(Schema.Array(OrchestrationV2PendingBackgroundTask)).pipe(
Schema.withDecodingDefault(Effect.succeed([])),
),
itemCount: NonNegativeInt,
visibleItemCount: NonNegativeInt,
createdAt: Schema.DateTimeUtc,
+12 -2
View File
@@ -144,10 +144,12 @@ export interface CodexAppServerReplayState {
export interface CodexAppServerReplayDriver {
readonly transcript: CodexAppServerReplayTranscript;
readonly state: Ref.Ref<CodexAppServerReplayState>;
readonly beforeEmitInbound?: (
entry: Extract<CodexAppServerReplayEntry, { readonly type: "emit_inbound" }>,
) => Effect.Effect<void>;
}
const encoder = new TextEncoder();
const decoder = new TextDecoder();
function stableStringify(value: unknown): string {
if (Array.isArray(value)) {
@@ -334,10 +336,14 @@ export function layerReplay(
}
export const makeReplayDriver = Effect.fn("effect-codex-app-server/replay.makeReplayDriver")(
function* (transcript: CodexAppServerReplayTranscript) {
function* (
transcript: CodexAppServerReplayTranscript,
options: Pick<CodexAppServerReplayDriver, "beforeEmitInbound"> = {},
) {
return {
transcript,
state: yield* Ref.make<CodexAppServerReplayState>({ cursor: 0, failure: null }),
...options,
} satisfies CodexAppServerReplayDriver;
},
);
@@ -368,6 +374,7 @@ const makeReplayClientWithState = Effect.fn(
const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
const state = driver.state;
const outboundRemainder = yield* Ref.make("");
const decoder = new TextDecoder();
const failReplay = (error: CodexAppServerReplayError) =>
Ref.update(state, (current) => ({
@@ -388,6 +395,9 @@ const makeReplayClientWithState = Effect.fn(
}
if (entry.type === "emit_inbound") {
if (driver.beforeEmitInbound !== undefined) {
yield* driver.beforeEmitInbound(entry);
}
if (entry.afterMs !== undefined && entry.afterMs > 0) {
yield* Effect.sleep(Duration.millis(entry.afterMs));
}
+4
View File
@@ -115,6 +115,10 @@
"types": "./src/orchestrationV2Timeline.ts",
"import": "./src/orchestrationV2Timeline.ts"
},
"./orchestrationV2PendingBackgroundWork": {
"types": "./src/orchestrationV2PendingBackgroundWork.ts",
"import": "./src/orchestrationV2PendingBackgroundWork.ts"
},
"./remote": {
"types": "./src/remote.ts",
"import": "./src/remote.ts"
+13 -1
View File
@@ -20,7 +20,9 @@ const project = {
describe("projectThreadAwarenessV2", () => {
const updatedAt = DateTime.makeUnsafe(NOW);
const v2Thread = (
overrides: Partial<Pick<OrchestrationV2ThreadShell, "status" | "pendingRuntimeRequest">> = {},
overrides: Partial<
Pick<OrchestrationV2ThreadShell, "activityRunStatus" | "status" | "pendingRuntimeRequest">
> = {},
) => ({
id: "thread-2" as ThreadId,
title: "Integrate orchestration",
@@ -41,6 +43,16 @@ describe("projectThreadAwarenessV2", () => {
).toMatchObject({ phase: "running", headline: "Agent is working" });
});
it("keeps an older activity run visible over a newer cancelled run", () => {
expect(
projectThreadAwarenessV2({
environmentId: "env-1" as EnvironmentId,
project,
thread: v2Thread({ status: "cancelled", activityRunStatus: "running" }),
}),
).toMatchObject({ phase: "running", headline: "Agent is working" });
});
it("prioritizes V2 user-input requests", () => {
expect(
projectThreadAwarenessV2({
+8 -2
View File
@@ -40,7 +40,13 @@ export interface ProjectThreadAwarenessV2Input {
readonly project: Pick<Project, "title">;
readonly thread: Pick<
OrchestrationV2ThreadShell,
"id" | "title" | "modelSelection" | "status" | "pendingRuntimeRequest" | "updatedAt"
| "activityRunStatus"
| "id"
| "modelSelection"
| "pendingRuntimeRequest"
| "status"
| "title"
| "updatedAt"
>;
}
@@ -85,7 +91,7 @@ function resolveThreadAwarenessPhaseV2(
) {
return "waiting_for_approval";
}
switch (thread.status) {
switch (thread.activityRunStatus ?? thread.status) {
case "preparing":
case "starting":
return "starting";
@@ -0,0 +1,432 @@
import { describe, expect, it } from "vite-plus/test";
import {
derivePendingBackgroundWork,
formatPendingBackgroundWorkLabel,
} from "./orchestrationV2PendingBackgroundWork.ts";
describe("derivePendingBackgroundWork", () => {
it("returns empty while the latest run is not settled", () => {
const tasks = derivePendingBackgroundWork({
latestRun: { id: "run-1" as never, ordinal: 1, status: "running" },
providerThreads: [
{
id: "pt-1" as never,
pendingBackgroundTasks: [{ taskId: "bg-1", description: "sleep 20" }],
},
],
turnItems: [
{
id: "item-1" as never,
type: "command_execution",
status: "running",
title: "npm test",
nativeItemRef: null,
input: "npm test",
},
],
});
expect(tasks).toEqual([]);
});
it("returns pending work when the latest run is waiting (post-success, pre-checkpoint)", () => {
const tasks = derivePendingBackgroundWork({
latestRun: { id: "run-1" as never, ordinal: 1, status: "waiting" },
providerThreads: [{ id: "pt-1" as never }],
turnItems: [
{
id: "item-1" as never,
type: "command_execution",
status: "running",
title: "npm test",
nativeItemRef: { nativeId: "cmd-1" },
input: "npm test",
},
],
});
expect(tasks).toEqual([
{ taskId: "cmd-1", description: "npm test", taskType: "command_execution" },
]);
});
it("still returns empty when the latest run is running even with background items", () => {
const tasks = derivePendingBackgroundWork({
latestRun: { id: "run-1" as never, ordinal: 1, status: "running" },
providerThreads: [
{
id: "pt-1" as never,
pendingBackgroundTasks: [{ taskId: "bg-1", description: "sleep 20" }],
},
],
turnItems: [
{
id: "item-1" as never,
type: "subagent",
status: "running",
title: "review",
nativeItemRef: { nativeId: "sub-1" },
prompt: "review",
},
],
});
expect(tasks).toEqual([]);
});
it("excludes rolled_back items when the latest run is waiting", () => {
const tasks = derivePendingBackgroundWork({
latestRun: { id: "run-2" as never, ordinal: 2, status: "waiting" },
providerThreads: [{ id: "pt-1" as never }],
runs: [
{ id: "run-1" as never, ordinal: 1, status: "rolled_back" },
{ id: "run-2" as never, ordinal: 2, status: "waiting" },
],
turnItems: [
{
id: "item-old" as never,
type: "command_execution",
status: "running",
title: "from rolled-back run",
runId: "run-1",
nativeItemRef: { nativeId: "cmd-old" },
input: "sleep 99",
},
{
id: "item-new" as never,
type: "command_execution",
status: "running",
title: "still pending",
runId: "run-2",
nativeItemRef: { nativeId: "cmd-new" },
input: "npm test",
},
],
});
expect(tasks).toEqual([
{ taskId: "cmd-new", description: "still pending", taskType: "command_execution" },
]);
});
it("returns the provider-thread roster after settlement", () => {
const tasks = derivePendingBackgroundWork({
latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" },
providerThreads: [
{
id: "pt-1" as never,
pendingBackgroundTasks: [
{ taskId: "bg-1", description: "Run Codex review", taskType: "local_bash" },
],
},
],
turnItems: [],
activeProviderThreadId: "pt-1",
});
expect(tasks).toEqual([
{ taskId: "bg-1", description: "Run Codex review", taskType: "local_bash" },
]);
});
it("includes nonterminal turn items and excludes completed ones", () => {
const tasks = derivePendingBackgroundWork({
latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" },
providerThreads: [{ id: "pt-1" as never }],
turnItems: [
{
id: "item-1" as never,
type: "command_execution",
status: "running",
title: "npm test",
nativeItemRef: { nativeId: "cmd-1" },
input: "npm test",
},
{
id: "item-2" as never,
type: "command_execution",
status: "completed",
title: "done",
nativeItemRef: { nativeId: "cmd-2" },
input: "echo done",
},
],
});
expect(tasks).toEqual([
{ taskId: "cmd-1", description: "npm test", taskType: "command_execution" },
]);
});
it("trims normalized background-work descriptions", () => {
const base = {
latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" as const },
providerThreads: [
{
id: "pt-1" as never,
pendingBackgroundTasks: [
{
taskId: "native-task",
description: " native background work ",
},
],
},
],
};
expect(
derivePendingBackgroundWork({
...base,
turnItems: [
{
id: "item-command" as never,
type: "command_execution",
status: "running",
title: " npm test ",
nativeItemRef: null,
},
{
id: "item-tool" as never,
type: "dynamic_tool",
status: "running",
title: null,
nativeItemRef: null,
toolName: " browser.search ",
} as never,
],
}),
).toEqual([
{
taskId: "native-task",
description: "native background work",
},
{
taskId: "item-command",
description: "npm test",
taskType: "command_execution",
},
{
taskId: "item-tool",
description: "browser.search",
taskType: "dynamic_tool",
},
]);
});
it("dedupes roster entries against turn items by native task id", () => {
const tasks = derivePendingBackgroundWork({
latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" },
providerThreads: [
{
id: "pt-1" as never,
pendingBackgroundTasks: [{ taskId: "task-9", description: "Agent review" }],
},
],
turnItems: [
{
id: "item-sub" as never,
type: "subagent",
status: "running",
title: "Agent review",
nativeItemRef: { nativeId: "task-9" },
prompt: "review the plan",
},
],
});
expect(tasks).toEqual([{ taskId: "task-9", description: "Agent review" }]);
});
it("excludes Grok persistent monitors", () => {
const tasks = derivePendingBackgroundWork({
latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" },
providerThreads: [{ id: "pt-1" as never }],
turnItems: [
{
id: "item-1" as never,
type: "dynamic_tool",
status: "running",
title: "monitor logs",
nativeItemRef: { nativeId: "mon-1" },
input: { persistent: true, command: "tail -f" },
},
{
id: "item-2" as never,
type: "dynamic_tool",
status: "running",
title: "finite monitor",
nativeItemRef: { nativeId: "mon-2" },
input: { persistent: false, command: "sleep 5" },
},
],
});
expect(tasks).toEqual([
{ taskId: "mon-2", description: "finite monitor", taskType: "dynamic_tool" },
]);
});
it("returns multiple tasks with stable ordering from insertion", () => {
const tasks = derivePendingBackgroundWork({
latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" },
providerThreads: [
{
id: "pt-1" as never,
pendingBackgroundTasks: [
{ taskId: "bg-1", description: "first" },
{ taskId: "bg-2", description: "second" },
],
},
],
turnItems: [
{
id: "item-1" as never,
type: "command_execution",
status: "running",
title: "third",
nativeItemRef: { nativeId: "cmd-3" },
input: "third",
},
],
});
expect(tasks.map((task) => task.taskId)).toEqual(["bg-1", "bg-2", "cmd-3"]);
});
it("excludes turn items owned by a rolled_back run", () => {
const tasks = derivePendingBackgroundWork({
latestRun: { id: "run-1" as never, ordinal: 1, status: "rolled_back" },
providerThreads: [{ id: "pt-1" as never }],
runs: [{ id: "run-1" as never, ordinal: 1, status: "rolled_back" }],
turnItems: [
{
id: "item-1" as never,
type: "command_execution",
status: "running",
title: "abandoned",
runId: "run-1",
nativeItemRef: { nativeId: "cmd-1" },
input: "sleep 99",
},
],
});
expect(tasks).toEqual([]);
});
it("returns empty when the latest run is rolled_back even with a nonempty roster", () => {
const tasks = derivePendingBackgroundWork({
latestRun: { id: "run-1" as never, ordinal: 1, status: "rolled_back" },
providerThreads: [
{
id: "pt-1" as never,
pendingBackgroundTasks: [{ taskId: "bg-1", description: "sleep 20" }],
},
],
turnItems: [
{
id: "item-1" as never,
type: "command_execution",
status: "running",
title: "abandoned",
runId: "run-1",
nativeItemRef: { nativeId: "cmd-1" },
input: "sleep 99",
},
],
});
expect(tasks).toEqual([]);
});
it("excludes an older rolled_back nonterminal item when the latest run is completed", () => {
const tasks = derivePendingBackgroundWork({
latestRun: { id: "run-2" as never, ordinal: 2, status: "completed" },
providerThreads: [{ id: "pt-1" as never }],
runs: [
{ id: "run-1" as never, ordinal: 1, status: "rolled_back" },
{ id: "run-2" as never, ordinal: 2, status: "completed" },
],
turnItems: [
{
id: "item-old" as never,
type: "command_execution",
status: "running",
title: "from rolled-back run",
runId: "run-1",
nativeItemRef: { nativeId: "cmd-old" },
input: "sleep 99",
},
{
id: "item-new" as never,
type: "command_execution",
status: "running",
title: "still pending",
runId: "run-2",
nativeItemRef: { nativeId: "cmd-new" },
input: "npm test",
},
],
});
expect(tasks).toEqual([
{ taskId: "cmd-new", description: "still pending", taskType: "command_execution" },
]);
});
it("does not reclassify an older active run as background work", () => {
const tasks = derivePendingBackgroundWork({
latestRun: { id: "run-2" as never, ordinal: 2, status: "cancelled" },
providerThreads: [
{
id: "pt-1" as never,
pendingBackgroundTasks: [{ taskId: "provider-task" }],
},
],
runs: [
{ id: "run-1" as never, ordinal: 1, status: "running" },
{ id: "run-2" as never, ordinal: 2, status: "cancelled" },
],
turnItems: [
{
id: "item-active" as never,
type: "command_execution",
status: "running",
title: "foreground work",
runId: "run-1",
nativeItemRef: { nativeId: "cmd-active" },
input: "vp check",
},
],
});
expect(tasks).toEqual([]);
});
it("includes items with a null run id even when runs list has rolled_back rows", () => {
const tasks = derivePendingBackgroundWork({
latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" },
providerThreads: [{ id: "pt-1" as never }],
runs: [{ id: "run-1" as never, ordinal: 1, status: "rolled_back" }],
turnItems: [
{
id: "item-null-run" as never,
type: "command_execution",
status: "running",
title: "orphan item",
runId: null,
nativeItemRef: { nativeId: "cmd-null" },
input: "echo orphan",
},
],
});
expect(tasks).toEqual([
{ taskId: "cmd-null", description: "orphan item", taskType: "command_execution" },
]);
});
});
describe("formatPendingBackgroundWorkLabel", () => {
it("formats single and multi-task labels", () => {
expect(formatPendingBackgroundWorkLabel([])).toBeNull();
expect(formatPendingBackgroundWorkLabel([{ taskId: "a" }])).toBe(
"Waiting on a background task",
);
expect(
formatPendingBackgroundWorkLabel([{ taskId: "a", description: "Run Codex review" }]),
).toBe("Waiting on background task: Run Codex review");
expect(
formatPendingBackgroundWorkLabel([
{ taskId: "a", description: "first" },
{ taskId: "b", description: "second" },
]),
).toBe("Waiting on 2 background tasks: first, …");
});
});
@@ -0,0 +1,238 @@
import type {
OrchestrationV2PendingBackgroundTask,
OrchestrationV2ProviderThread,
OrchestrationV2Run,
OrchestrationV2TurnItem,
} from "@t3tools/contracts";
const BACKGROUND_TURN_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
"command_execution",
"dynamic_tool",
"subagent",
]);
const TERMINAL_TURN_ITEM_STATUSES = new Set<OrchestrationV2TurnItem["status"]>([
"completed",
"interrupted",
"failed",
"cancelled",
]);
/**
* True terminal run statuses (includes `rolled_back`). Retained as the
* canonical terminal set for this module; do not widen or reuse it as the
* background-wait gate — that gate intentionally excludes `rolled_back`.
*/
const TERMINAL_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
"cancelled",
"completed",
"failed",
"interrupted",
"rolled_back",
]);
/**
* Run statuses that allow a pending-background roster to surface.
* Includes `waiting`: a successful turn persists as waiting until checkpoint
* capture flips it to completed, and waiting is only set from completed.
* Excludes `rolled_back`: the provider-thread roster is not run-tied, so a
* rolled-back latest run must fail the gate entirely (not only item filter).
* Built explicitly rather than spreading or deleting from TERMINAL_RUN_STATUSES.
*/
const SETTLED_FOR_BACKGROUND_WAIT_RUN_STATUSES = new Set<OrchestrationV2Run["status"]>([
"cancelled",
"completed",
"failed",
"interrupted",
"waiting",
]);
// Keep TERMINAL_RUN_STATUSES referenced so the true-terminal set stays defined
// next to the background-wait subset (rolled_back is terminal, not wait-settled).
void TERMINAL_RUN_STATUSES;
export type PendingBackgroundWorkTask = OrchestrationV2PendingBackgroundTask;
type PendingBackgroundWorkRun = Pick<OrchestrationV2Run, "id" | "ordinal" | "status">;
type PendingBackgroundWorkProviderThread = Pick<
OrchestrationV2ProviderThread,
"id" | "pendingBackgroundTasks"
>;
type PendingBackgroundWorkTurnItem = {
readonly id: OrchestrationV2TurnItem["id"] | string;
readonly type: OrchestrationV2TurnItem["type"];
readonly status: OrchestrationV2TurnItem["status"];
readonly title: string | null;
/** When present and the run is rolled_back, the item is abandoned, not pending. */
readonly runId?: OrchestrationV2Run["id"] | string | null;
readonly nativeItemRef?: {
readonly nativeId: string | null;
} | null;
readonly input?: unknown;
readonly prompt?: string | undefined;
};
function isTerminalTurnItemStatus(status: OrchestrationV2TurnItem["status"]): boolean {
return TERMINAL_TURN_ITEM_STATUSES.has(status);
}
function isLatestRunSettledForBackgroundWait(
latestRun: PendingBackgroundWorkRun | null | undefined,
): boolean {
if (latestRun === undefined || latestRun === null) {
return false;
}
return SETTLED_FOR_BACKGROUND_WAIT_RUN_STATUSES.has(latestRun.status);
}
function isPersistentDynamicToolInput(input: unknown): boolean {
if (input === null || typeof input !== "object" || Array.isArray(input)) {
return false;
}
return Reflect.get(input, "persistent") === true;
}
function descriptionFromTurnItem(item: PendingBackgroundWorkTurnItem): string | undefined {
if (typeof item.title === "string" && item.title.trim().length > 0) {
return item.title.trim();
}
if (item.type === "command_execution" && typeof item.input === "string") {
const command = item.input.trim();
return command.length > 0 ? command : undefined;
}
if (item.type === "dynamic_tool") {
const toolName = Reflect.get(item, "toolName");
if (typeof toolName === "string" && toolName.trim().length > 0) {
return toolName.trim();
}
}
if (item.type === "subagent" && typeof item.prompt === "string") {
const prompt = item.prompt.trim();
return prompt.length > 0 ? prompt : undefined;
}
return undefined;
}
function nativeTaskIdFromTurnItem(item: PendingBackgroundWorkTurnItem): string {
const nativeId = item.nativeItemRef?.nativeId;
if (typeof nativeId === "string" && nativeId.length > 0) {
return nativeId;
}
return String(item.id);
}
/**
* Derive one normalized pending-background-work list for post-settlement UI.
*
* Sources:
* - Provider-thread roster (Claude SDK background tasks)
* - Nonterminal command_execution / dynamic_tool / subagent turn items
*
* Gated on latest root run settlement. Dedupes by native task ID. Excludes
* the roster while any interruptible foreground run remains active. Excludes
* Grok persistent monitors (`dynamic_tool` input with `persistent: true`).
* Excludes turn items whose run resolves to `rolled_back` (abandoned work);
* items with a null or absent run id stay eligible (matches SQL shell path).
* Does not consult subagent entities (those double-count turn items).
*/
export function derivePendingBackgroundWork(input: {
readonly latestRun: PendingBackgroundWorkRun | null | undefined;
readonly providerThreads: ReadonlyArray<PendingBackgroundWorkProviderThread>;
readonly turnItems: ReadonlyArray<PendingBackgroundWorkTurnItem>;
readonly activeProviderThreadId?: string | null;
readonly hasActiveRun?: boolean;
/**
* Run rows used to exclude items owned by rolled_back runs. Optional for
* callers that already filtered (SQL shell path); in-memory callers should
* pass projection runs so policy cannot drift.
*/
readonly runs?: ReadonlyArray<PendingBackgroundWorkRun>;
}): ReadonlyArray<PendingBackgroundWorkTask> {
const hasActiveRun =
input.hasActiveRun ??
input.runs?.some(
(run) => run.status === "preparing" || run.status === "starting" || run.status === "running",
) ??
false;
if (hasActiveRun) {
return [];
}
if (!isLatestRunSettledForBackgroundWait(input.latestRun)) {
return [];
}
const byTaskId = new Map<string, PendingBackgroundWorkTask>();
const rolledBackRunIds = new Set(
(input.runs ?? []).filter((run) => run.status === "rolled_back").map((run) => String(run.id)),
);
const providerThreads =
input.activeProviderThreadId === undefined || input.activeProviderThreadId === null
? input.providerThreads
: input.providerThreads.filter((thread) => thread.id === input.activeProviderThreadId);
for (const providerThread of providerThreads) {
for (const task of providerThread.pendingBackgroundTasks ?? []) {
if (task.taskId.length === 0 || byTaskId.has(task.taskId)) {
continue;
}
const description = task.description?.trim();
byTaskId.set(task.taskId, {
taskId: task.taskId,
...(description === undefined || description.length === 0 ? {} : { description }),
...(task.taskType === undefined ? {} : { taskType: task.taskType }),
});
}
}
for (const item of input.turnItems) {
if (!BACKGROUND_TURN_ITEM_TYPES.has(item.type)) {
continue;
}
if (isTerminalTurnItemStatus(item.status)) {
continue;
}
if (item.type === "dynamic_tool" && isPersistentDynamicToolInput(item.input)) {
continue;
}
// Null/absent run id stays eligible; only known rolled_back runs drop.
const itemRunId = item.runId;
if (itemRunId !== undefined && itemRunId !== null && rolledBackRunIds.has(String(itemRunId))) {
continue;
}
const taskId = nativeTaskIdFromTurnItem(item);
if (byTaskId.has(taskId)) {
continue;
}
const description = descriptionFromTurnItem(item);
byTaskId.set(taskId, {
taskId,
...(description === undefined ? {} : { description }),
taskType: item.type,
});
}
return Array.from(byTaskId.values());
}
export function formatPendingBackgroundWorkLabel(
tasks: ReadonlyArray<PendingBackgroundWorkTask>,
): string | null {
if (tasks.length === 0) {
return null;
}
const firstDescription = tasks[0]?.description?.trim();
if (tasks.length === 1) {
return firstDescription && firstDescription.length > 0
? `Waiting on background task: ${firstDescription}`
: "Waiting on a background task";
}
if (firstDescription && firstDescription.length > 0) {
return `Waiting on ${tasks.length} background tasks: ${firstDescription}, …`;
}
return `Waiting on ${tasks.length} background tasks`;
}