,
+ remoteCheckOf(declaration) as RemoteCheck | undefined,
+ forwarded,
+ );
+
const fullAccessRequired =
"Changing projects or environment settings needs a live full-access/default calling thread or a full-access client.";
@@ -387,6 +422,9 @@ const routed = Effect.fn("McpToolAccess.routed")(function* , never>
+ | undefined;
if (remote === undefined)
return yield* Effect.die(
`${name} takes a linked environment, but it acts as its calling thread, which is here.`,
@@ -402,7 +440,11 @@ const routed = Effect.fn("McpToolAccess.routed")(function* )(params);
if (Option.isNone(forwarding)) return yield* linksUnavailable;
- return yield* forwarding.value.call(scope, tool, target, { ...params, environmentId });
+ const result = yield* forwarding.value.call(scope, tool, target, {
+ ...params,
+ environmentId,
+ });
+ return forwarded === undefined ? result : yield* forwarded(params, target, result);
});
}
return handlers as Toolkit.HandlersFrom;
diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts
index e0bb1aa96e2f3..5f5cae7563621 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.test.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts
@@ -35,6 +35,7 @@ import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
+import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
@@ -3812,6 +3813,55 @@ describe("OrchestratorMcpService thread lookup", () => {
}),
);
+ it.effect("records the linked environment's thread that sent a message", () =>
+ Effect.gen(function* () {
+ const target = liveThreadShell(ThreadId.make("thread:target"));
+ const sender = {
+ environmentId: EnvironmentId.make("environment:a"),
+ threadId: ThreadId.make("thread:orc"),
+ title: "orc lead",
+ };
+ const linked = (senderThread?: typeof sender): McpInvocationScope => ({
+ ...client,
+ client: {
+ sessionId: "link-a",
+ label: "A",
+ access: "full-access",
+ linked: true,
+ ...(senderThread === undefined ? {} : { senderThread }),
+ },
+ });
+ const sendAs = (scope: McpInvocationScope) =>
+ Effect.gen(function* () {
+ const inputs: Array = [];
+ const sent = yield* Ref.make(0);
+ yield* Effect.gen(function* () {
+ const mcp = yield* OrchestratorMcpService.OrchestratorMcpService;
+ yield* mcp.sendToThread(scope, { threadId: target.id, message: "hello" });
+ }).pipe(
+ Effect.provide(
+ service([target], sent, {
+ getProjectThreadRecords: () => Effect.succeed(idleThreadProjection(target)),
+ sendToThread: (input) => {
+ inputs.push(input);
+ return Effect.succeed({
+ run: { id: RunId.make("run:sent"), status: "running" },
+ delivery: "started",
+ } as never);
+ },
+ }),
+ ),
+ );
+ return inputs[0];
+ });
+
+ const fromLink = yield* sendAs(linked(sender));
+ assert.deepStrictEqual(fromLink?.linkedSender, sender);
+ assert.isUndefined(fromLink?.senderThreadId);
+ assert.isUndefined((yield* sendAs(linked()))?.linkedSender);
+ }),
+ );
+
it.effect("refuses waiting without orchestration capability before reading the target", () =>
Effect.gen(function* () {
const sent = yield* Ref.make(0);
@@ -3886,6 +3936,13 @@ describe("OrchestratorMcpService thread list", () => {
shell("thread:a-snoozed", "project:a", true),
shell("thread:a-awake", "project:a", false),
shell("thread:b-snoozed", "project:b", true),
+ {
+ ...shell("thread:a-awaiting-command", "project:a", false),
+ activityRunStatus: null,
+ pendingBackgroundTasks: [
+ { taskId: "sleep-600", kind: "command" as const, awaited: true as const },
+ ],
+ },
];
const service = layerOrchestratorService.pipe(
Layer.provide(
@@ -3905,7 +3962,21 @@ describe("OrchestratorMcpService thread list", () => {
Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
list: () => Effect.succeed([]),
}),
- Layer.mock(ProjectService.ProjectService)({}),
+ Layer.mock(ProjectService.ProjectService)({
+ getById: (id) =>
+ shells.some((thread) => thread.projectId === id)
+ ? Effect.succeedSome({
+ id,
+ title: id,
+ workspaceRoot: `/projects/${id}`,
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: "2026-10-18T00:00:00.000Z",
+ updatedAt: "2026-10-18T00:00:00.000Z",
+ deletedAt: null,
+ })
+ : Effect.succeedNone,
+ }),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
@@ -3932,6 +4003,34 @@ describe("OrchestratorMcpService thread list", () => {
}).pipe(Effect.provide(service)),
);
+ it.effect("refuses a projectId that names no project", () =>
+ Effect.gen(function* () {
+ const mcp = yield* OrchestratorMcpService.OrchestratorMcpService;
+ const listed = yield* mcp
+ .listThreads(client, { projectId: ProjectId.make("project:missing") })
+ .pipe(Effect.result);
+ if (Result.isSuccess(listed)) {
+ assert.fail(`listed threads for a missing project: ${JSON.stringify(listed.success)}`);
+ }
+ assert.equal(listed.failure.code, "invalid_request");
+ assert.include(listed.failure.message, "not found");
+ }).pipe(Effect.provide(service)),
+ );
+
+ it.effect("counts a thread holding awaited background work as live in the status filter", () =>
+ Effect.gen(function* () {
+ const mcp = yield* OrchestratorMcpService.OrchestratorMcpService;
+ const listed = yield* mcp.listThreads(client, {
+ projectId: ProjectId.make("project:a"),
+ statuses: ["preparing", "queued", "starting", "running", "waiting"],
+ });
+ assert.deepStrictEqual(
+ listed.threads.map((thread) => thread.threadId),
+ ["thread:a-awaiting-command"],
+ );
+ }).pipe(Effect.provide(service)),
+ );
+
it.effect("points a caller outside any thread at allProjects when it omits projectId", () =>
Effect.gen(function* () {
const mcp = yield* OrchestratorMcpService.OrchestratorMcpService;
diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts
index 960253adc3982..844930371fa4f 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.ts
@@ -68,6 +68,7 @@ import {
SECRET_REQUEST_UNSAVED_NOTE,
} from "@t3tools/contracts";
import { getProviderOptionCurrentValue, withLegacyUltracodeEffort } from "@t3tools/shared/model";
+import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
import { formatThreadLink } from "@t3tools/shared/threadLinks";
import {
@@ -814,6 +815,14 @@ function threadPullRequests(
}));
}
+// Awaited background work keeps a thread live after its turn ends, as auto-settle and the sidebar treat it.
+function listedThreadStatus(shell: OrchestrationV2ThreadShell) {
+ if (shell.activityRunStatus != null) return shell.activityRunStatus;
+ return backgroundWorkHoldsCompletion(shell.pendingBackgroundTasks ?? [])
+ ? "waiting"
+ : shell.status;
+}
+
function listItemFromShell(
scope: McpInvocationScope,
shell: OrchestrationV2ThreadShell,
@@ -826,7 +835,7 @@ function listItemFromShell(
link: threadLinkFor(scope, shell.id, shell.title),
createdBy: shell.createdBy,
creationSource: shell.creationSource,
- status: shell.activityRunStatus ?? shell.status,
+ status: listedThreadStatus(shell),
latestRunId: shell.latestRunId,
providerInstanceId: shell.modelSelection.instanceId,
model: shell.modelSelection.model,
@@ -2960,6 +2969,9 @@ const make = Effect.gen(function* () {
input.projectId,
"Pass projectId, or allProjects: true for every project. This MCP client is not running inside a T3 thread.",
);
+ if (!input.allProjects && input.projectId !== undefined) {
+ yield* requireProject(input.projectId);
+ }
const projectThreads = yield* threadManagement
.listProjectThreads({
projectId: projectId ?? undefined,
@@ -2978,9 +2990,7 @@ const make = Effect.gen(function* () {
: new Set(input.statuses);
const titleContains = input.titleContains?.toLocaleLowerCase();
const filtered = projectThreads
- .filter(
- (thread) => statuses === null || statuses.has(thread.activityRunStatus ?? thread.status),
- )
+ .filter((thread) => statuses === null || statuses.has(listedThreadStatus(thread)))
.filter(
(thread) =>
input.settled === undefined || threadSettlement(thread).settled === input.settled,
@@ -3137,6 +3147,10 @@ const make = Effect.gen(function* () {
}),
threadId: input.threadId,
...(parent === undefined ? {} : { senderThreadId: parent.thread.id }),
+ // A linked environment's agent has no thread here; the link names it.
+ ...(parent === undefined && scope.client?.senderThread !== undefined
+ ? { linkedSender: scope.client.senderThread }
+ : {}),
messageId,
text: input.message,
attachments: [],
diff --git a/apps/server/src/mcp/linkOrigin.test.ts b/apps/server/src/mcp/linkOrigin.test.ts
index b8e3b3d2cadb1..928fda0dd72f8 100644
--- a/apps/server/src/mcp/linkOrigin.test.ts
+++ b/apps/server/src/mcp/linkOrigin.test.ts
@@ -16,6 +16,7 @@ import {
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
import { McpSchema, McpServer } from "effect/ai";
import * as ServerConfig from "../config.ts";
@@ -133,7 +134,21 @@ const layerTools = Layer.mergeAll(
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
Layer.provide(
Layer.mock(ProjectService.ProjectService)({
- getById: () => Effect.succeedNone,
+ getById: (id) =>
+ Effect.succeed(
+ id === projectId
+ ? Option.some({
+ id,
+ title: "t3code",
+ workspaceRoot: "/p/t3code",
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: "2026-10-18T00:00:00.000Z",
+ updatedAt: "2026-10-18T00:00:00.000Z",
+ deletedAt: null,
+ })
+ : Option.none(),
+ ),
create: (input) =>
Effect.succeed({
id: input.projectId,
diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts
index 2c3d4026a71fe..f0575c91001ea 100644
--- a/apps/server/src/mcp/toolkits/core.test.ts
+++ b/apps/server/src/mcp/toolkits/core.test.ts
@@ -1100,7 +1100,21 @@ it.effect(
Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
- Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
+ Layer.provide(
+ Layer.mock(ProjectService.ProjectService)({
+ getById: (projectId) =>
+ Effect.succeedSome({
+ id: projectId,
+ title: "MCP test",
+ workspaceRoot: "/repo",
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: "2026-10-18T00:00:00.000Z",
+ updatedAt: "2026-10-18T00:00:00.000Z",
+ deletedAt: null,
+ }),
+ }),
+ ),
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
diff --git a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts
index 3db297bc0d303..1f4ee4a57a6f5 100644
--- a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts
+++ b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
import * as PeerLinkRequests from "../../../peer/PeerLinkRequests.ts";
import * as PeerLinks from "../../../peer/PeerLinks.ts";
+import * as RemoteDelegation from "../../../peer/RemoteDelegation.ts";
import { readCaller } from "../../threadAccess.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as McpToolAccess from "../../McpToolAccess.ts";
@@ -168,13 +169,22 @@ const handlers = {
return yield* service.update(scope, input);
}),
),
- t3_thread_send: McpToolAccess.writesThreads(
- (input) => [input.threadId],
- (input) =>
+ t3_thread_send: McpToolAccess.afterForwarding(
+ McpToolAccess.writesThreads(
+ (input) => [input.threadId],
+ (input) =>
+ Effect.gen(function* () {
+ const scope = yield* McpInvocationContext.McpInvocationContext;
+ const service = yield* OrchestratorMcpService.OrchestratorMcpService;
+ return yield* service.sendToThread(scope, input);
+ }),
+ ),
+ // There the thread's parent is here, so only this side can make a follow-up a task.
+ (input, environmentId, sent) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext.McpInvocationContext;
- const service = yield* OrchestratorMcpService.OrchestratorMcpService;
- return yield* service.sendToThread(scope, input);
+ const remote = yield* RemoteDelegation.RemoteDelegation;
+ return yield* remote.followUp(scope, environmentId, input, sent);
}),
),
t3_thread_wait: McpToolAccess.reads((input) =>
diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts
index d1c916f2caefb..38d8fb4e0ada5 100644
--- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts
+++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts
@@ -46,6 +46,7 @@ import * as ThreadManagementService from "../../../orchestration-v2/ThreadManage
import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
import * as PeerLinkRequests from "../../../peer/PeerLinkRequests.ts";
import * as PeerLinks from "../../../peer/PeerLinks.ts";
+import * as RemoteDelegation from "../../../peer/RemoteDelegation.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as OrchestratorMcpService from "../../OrchestratorMcpService.ts";
import * as ThreadMetadataMcpService from "../../ThreadMetadataMcpService.ts";
@@ -63,6 +64,8 @@ const linkingDependencies = [
PeerLinkRequests.PeerLinkRequests,
PeerLinks.PeerLinks,
];
+/** A send there may record a follow-up to a remote task. */
+const sendDependencies = [...dependencies, RemoteDelegation.RemoteDelegation];
const threadMetadataDependencies = [
McpInvocationContext.McpInvocationContext,
ThreadManagementService.ThreadManagementService,
@@ -279,7 +282,7 @@ const ThreadSendTool = Tool.make("t3_thread_send", {
success: OrchestratorMcpThreadSendResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
- dependencies,
+ dependencies: sendDependencies,
})
.annotate(Tool.Title, "Send to a T3 thread")
.annotate(Tool.Destructive, true)
diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts
index 6266e31abece0..b2ba460d0c8b7 100644
--- a/apps/server/src/mcp/toolkits/project/handlers.test.ts
+++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts
@@ -642,6 +642,40 @@ it.effect("a launch into a new worktree creates nothing when its branch collides
}),
);
+it.effect("a launch into an unknown project says the project was not found", () =>
+ Effect.gen(function* () {
+ const launched: Array = [];
+ const { modelSelection, dependencies } = clientLaunchHarness({
+ runtimeModeCeiling: "auto",
+ launched,
+ });
+ const toolkit = yield* ProjectToolkit.pipe(
+ Effect.provide(
+ McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)),
+ ),
+ );
+ for (const workspaceStrategy of [
+ undefined,
+ { type: "worktree", baseRef: "main", startFromOrigin: false } as const,
+ ]) {
+ const result = yield* toolkit
+ .handle("t3_thread_launch", {
+ title: "Fix",
+ message: "Fix the bug",
+ projectId: ProjectId.make("current"),
+ modelSelection,
+ ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
+ })
+ .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies));
+ expect(result.at(-1)?.result).toMatchObject({
+ code: "invalid_request",
+ message: "The project was not found.",
+ });
+ }
+ expect(launched).toHaveLength(0);
+ }),
+);
+
it.effect("a retried worktree launch replays after its base ref is gone", () =>
Effect.gen(function* () {
const launched: Array = [];
diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts
index 2c60c7fb8676b..2ad7161cb630b 100644
--- a/apps/server/src/mcp/toolkits/project/handlers.ts
+++ b/apps/server/src/mcp/toolkits/project/handlers.ts
@@ -151,11 +151,6 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
),
)).projectId
: yield* resolveProjectId(context, input.projectId);
- const readProject = Project.ProjectService.pipe(
- Effect.flatMap((projects) => projects.getById(projectId)),
- Effect.mapError(unavailable),
- Effect.map(Option.getOrUndefined),
- );
// A retry of an accepted launch replays it: it keeps the model it started
// with and skips the checks only a new launch needs, which the project
// may no longer pass, such as a base branch deleted since.
@@ -166,15 +161,26 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
const launchedModel =
launched === null || launched.deletedAt !== null ? undefined : launched.modelSelection;
const replaying = launchedModel !== undefined;
- if (!replaying && input.workspaceStrategy?.type === "existing_worktree") {
- const project = yield* readProject;
- if (project === undefined)
- return yield* new OrchestratorMcpFailure({
- code: "invalid_request",
- message: "The project was not found.",
- });
+ const project = replaying
+ ? undefined
+ : yield* Project.ProjectService.pipe(
+ Effect.flatMap((projects) => projects.getById(projectId)),
+ Effect.mapError(unavailable),
+ Effect.flatMap(
+ Option.match({
+ onNone: () =>
+ Effect.fail(
+ new OrchestratorMcpFailure({
+ code: "invalid_request",
+ message: "The project was not found.",
+ }),
+ ),
+ onSome: Effect.succeed,
+ }),
+ ),
+ );
+ if (project !== undefined && input.workspaceStrategy?.type === "existing_worktree")
yield* assertProjectWorktree(project.workspaceRoot, input.workspaceStrategy.worktreePath);
- }
if (!replaying && input.modelSelection !== undefined) {
const { instanceId, model } = input.modelSelection;
const providers = yield* (yield* ProviderRegistry.ProviderRegistry).getProviders;
@@ -201,15 +207,12 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
// project's effective defaults, as the composer does. Its mode stays
// within the ceiling it was approved with.
const projectDefaults =
- caller === undefined && !replaying
+ caller === undefined && project !== undefined
? yield* ServerSettings.ServerSettingsService.pipe(
Effect.flatMap((settings) => settings.getSettings),
Effect.mapError(unavailable),
- Effect.flatMap((settings) =>
- Effect.map(
- readProject,
- (project) => resolveProjectSettings(settings, projectId, project).settings,
- ),
+ Effect.map(
+ (settings) => resolveProjectSettings(settings, projectId, project).settings,
),
)
: undefined;
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
index 05bed3c120263..fb51465629018 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
@@ -4708,7 +4708,25 @@ describe("AcpAdapterV2", () => {
kind: "other",
granted: false,
},
- ] as const)("$label", ({ kind, granted }) =>
+ {
+ label: "grants an explicit execute approval",
+ kind: "execute",
+ requestKind: "execute",
+ granted: true,
+ },
+ {
+ label: "does not grant execution to an approved mode switch",
+ kind: "execute",
+ requestKind: "switch_mode",
+ granted: false,
+ },
+ {
+ label: "does not grant execution to an approved explicit other tool",
+ kind: "other",
+ requestKind: "other",
+ granted: false,
+ },
+ ] as const)("$label", ({ kind, granted, ...testCase }) =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const path = yield* Path.Path;
@@ -4795,7 +4813,10 @@ describe("AcpAdapterV2", () => {
const permissionFiber = yield* requestPermission(
{
sessionId: "mock-session-1",
- toolCall: { toolCallId: "tracked-tool-call" },
+ toolCall: {
+ toolCallId: "tracked-tool-call",
+ ...("requestKind" in testCase ? { kind: testCase.requestKind } : {}),
+ },
options: [{ optionId: "allow-once", name: "Allow once", kind: "allow_once" }],
},
{ requestId: "id-only-permission-request", method: "session/request_permission" },
@@ -4837,8 +4858,12 @@ describe("AcpAdapterV2", () => {
{ requestId: "id-only-permission-terminal", method: "terminal/create" },
).pipe(Effect.exit);
assert.deepEqual(
- { prompt: approval.prompt, terminalCreated: Exit.isSuccess(terminalExit) },
- { prompt: "git status", terminalCreated: granted },
+ {
+ prompt: approval.prompt,
+ requestKind: approval.requestKind,
+ terminalCreated: Exit.isSuccess(terminalExit),
+ },
+ { prompt: "git status", requestKind: "command", terminalCreated: granted },
);
yield* runtime.interruptTurn({ providerThread, providerTurnId });
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index d702b795b9d1e..8b3c39af568e4 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -3375,7 +3375,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
const makeWakeHarnessWithOptions = (options?: {
readonly close?: (sdkMessages: Queue.Queue) => Effect.Effect;
- readonly interrupt?: Effect.Effect;
+ readonly interrupt?: Effect.Effect;
readonly setPermissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["setPermissionMode"];
readonly applyFlagSettings?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["applyFlagSettings"];
readonly stopTask?: (
@@ -11001,7 +11001,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
);
it.effect(
- "uses task_started as an incremental roster fallback and clears on empty snapshot",
+ "uses task_started as an incremental roster fallback and clears internal work on empty snapshot",
() =>
Effect.scoped(
Effect.gen(function* () {
@@ -11119,13 +11119,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
- yield* Queue.offer(harness.sdkMessages, emptyRoster);
- yield* harness.until(() =>
- providerThreadRosterEvents(harness.events).some(
- (event) =>
- event.providerThread.status === "idle" &&
- (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0,
- ),
+ yield* harness.offerAndWait(emptyRoster);
+ assert.include(
+ (
+ providerThreadRosterEvents(harness.events).at(-1)?.providerThread
+ .pendingBackgroundTasks ?? []
+ ).map((task) => task.taskId),
+ WAKE_TASK_ID,
);
assert.isFalse(yield* harness.hasPendingBackgroundWork);
}).pipe(
@@ -11203,9 +11203,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
["dev-server", false],
],
);
- yield* Queue.offer(harness.sdkMessages, turnOneResult);
- yield* Queue.take(harness.terminalReceipts);
-
// A replacing level rebuilds every entry; the mark must survive it.
yield* Queue.offer(
harness.sdkMessages,
@@ -11219,10 +11216,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
],
);
- // Once the task leaves the roster, a reused id starts unmarked.
+ // Once the task ends, a reused id starts unmarked.
yield* Queue.offer(
harness.sdkMessages,
- roster(["dev-server"], "00000000-0000-4000-8000-000000000303"),
+ claudeSdkFrame({ ...wakeNotification, uuid: "00000000-0000-4000-8000-000000000303" }),
);
yield* nextRoster((tasks) => tasks.length === 1);
yield* Queue.offer(
@@ -11259,6 +11256,8 @@ describe("ClaudeAdapterV2 background wake turns", () => {
[WAKE_TASK_ID, false],
],
);
+ yield* Queue.offer(harness.sdkMessages, turnOneResult);
+ yield* Queue.take(harness.terminalReceipts);
}).pipe(
Effect.provide(
Layer.mergeAll(
@@ -12205,6 +12204,79 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
+ it.effect.each([
+ { teardown: "before Stop" as const },
+ { teardown: "during Stop's interrupt write" as const },
+ ])("Stop with session teardown $teardown does not fail on the closed CLI", ({ teardown }) =>
+ Effect.gen(function* () {
+ const sessionScope = yield* Scope.make();
+ let queryClosed = false;
+ const harness = yield* makeWakeHarnessWithOptions({
+ close: (sdkMessages) =>
+ Effect.sync(() => {
+ queryClosed = true;
+ }).pipe(Effect.andThen(Queue.shutdown(sdkMessages))),
+ interrupt: Effect.suspend(() =>
+ teardown === "before Stop" ? Effect.void : Scope.close(sessionScope, Exit.void),
+ ).pipe(
+ Effect.andThen(
+ Effect.suspend(() =>
+ queryClosed
+ ? Effect.fail(
+ new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
+ method: "interrupt",
+ cause: new Error("ProcessTransport is not ready for writing"),
+ }),
+ )
+ : Effect.void,
+ ),
+ ),
+ ),
+ }).pipe(Scope.provide(sessionScope));
+ const now = yield* DateTime.now;
+ const attemptId = RunAttemptId.make("attempt-claude-closed-scope-stop");
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId,
+ text: "Hand this thread off to a worktree.",
+ attachments: [],
+ }),
+ );
+ // A workspace handoff detaches the session, closing its scope while the turn streams.
+ if (teardown === "before Stop") {
+ yield* Scope.close(sessionScope, Exit.void);
+ assert.isTrue(queryClosed);
+ }
+
+ const interrupted = yield* Effect.exit(
+ harness.runtime.interruptTurn({
+ providerThread: harness.providerThread,
+ providerTurnId: idAllocator.derive.providerTurn({
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
+ nativeTurnId: `turn:${attemptId}`,
+ }),
+ requestRuntimeRestart: true,
+ }),
+ );
+
+ assert.isTrue(Exit.isSuccess(interrupted), String(interrupted));
+ assert.isTrue(queryClosed);
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ );
+
it.effect("a settled Stop leaves a turn that replaced the closing process alone", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -13940,150 +14012,1089 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
- it.effect.each([true, false])(
- "carries a rejected wake rate limit into the continuation failure (event=%s)",
- (standaloneEvent) =>
- Effect.scoped(
- Effect.gen(function* () {
- const harness = yield* makeWakeHarness;
- const now = yield* DateTime.now;
- const resetsAt = 1790298600;
+ it.effect("offers a later wake after an earlier wake's continuation dispatch failed", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const SECOND_TASK_ID = "b2ndwake";
+ const SECOND_TOOL_USE_ID = "toolu_second_wake";
+ const SECOND_SUMMARY = 'Background command "Second sleep" completed (exit code 0)';
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make("attempt-claude-wake-limit-1"),
- text: "Run the build in the background.",
- attachments: [],
- }),
- );
- yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
- yield* Queue.offer(harness.sdkMessages, turnOneResult);
- yield* Queue.take(harness.terminalReceipts);
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-dispatch-failed-1"),
+ text: "Run two builds in the background.",
+ attachments: [],
+ }),
+ );
+ yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
+ yield* Queue.offer(
+ harness.sdkMessages,
+ claudeSdkFrame({
+ ...wakeTaskStarted,
+ task_id: SECOND_TASK_ID,
+ tool_use_id: SECOND_TOOL_USE_ID,
+ description: "Second sleep",
+ uuid: "00000000-0000-4000-8000-000000000121",
+ }),
+ );
+ yield* Queue.offer(harness.sdkMessages, turnOneResult);
+ yield* harness.awaitTerminal(1);
- yield* Queue.offer(harness.sdkMessages, wakeNotification);
- if (standaloneEvent) {
- yield* harness.offerAndWait(
- claudeSdkFrame({
- type: "rate_limit_event",
- rate_limit_info: {
- status: "rejected",
- rateLimitType: "five_hour",
- resetsAt,
- overageStatus: "rejected",
- },
- uuid: "00000000-0000-4000-8000-000000000630",
- session_id: WAKE_NATIVE_SESSION,
- }),
- );
- }
- assert.lengthOf(harness.continuationRequests, 0);
- yield* harness.offerAndWait(
- makeAssistantErrorFrame({
- uuid: "00000000-0000-4000-8000-000000000631",
- error: "rate_limit",
- apiErrorParams: {
- rate_limit_info: {
- status: "rejected",
- rateLimitType: "five_hour",
- // A conflicting embedded time must not replace the event for this window.
- resetsAt: standaloneEvent ? resetsAt + 3_600 : resetsAt,
- },
- },
- }),
- );
- assert.lengthOf(harness.continuationRequests, 1);
- yield* harness.offerAndWait(
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000000632",
- result: "You've hit your session limit · resets 11:10am (Australia/Sydney)",
- isError: true,
- apiErrorStatus: 429,
- terminalReason: "api_error",
- origin: { kind: "task-notification" },
- }),
- );
- assert.lengthOf(harness.continuationRequests, 1);
+ yield* harness.offerAndWait(wakeNotification);
+ yield* harness.offerAndWait(wakeTurnInit);
+ assert.lengthOf(harness.continuationRequests, 1);
+ yield* harness.offerAndWait(wakeAssistant);
+ yield* harness.offerAndWait(wakeResult);
- // An empty session-task lifecycle result arriving before T3 opens the
- // wake run must not replace the root's terminal usage-limit result.
- yield* harness.offerAndWait(wakeTurnInit);
- yield* harness.offerAndWait(
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000000633",
- result: "",
- numTurns: 0,
- origin: { kind: "task-notification" },
- terminalReason: null,
- }),
- );
+ // A failed dispatch never attaches the wake turn; clearIfCurrent is the only release.
+ const failed = harness.continuationRequests[0]!;
+ assert.isDefined(failed.clearIfCurrent);
+ yield* failed.clearIfCurrent!();
+ yield* harness.until(
+ () =>
+ !(
+ providerThreadRosterEvents(harness.events).at(-1)?.providerThread
+ .pendingBackgroundTasks ?? []
+ ).some((task) => task.taskId === WAKE_TASK_ID),
+ );
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make("attempt-claude-wake-limit-2"),
- text: "Background task completed.",
- attachments: [],
- providerTurnOrdinal: 2,
- messageCreatedBy: "agent",
- messageCreationSource: "provider",
- }),
- );
- const terminal = yield* Queue.take(harness.terminalReceipts);
- assert.equal(terminal?.status, "failed");
- if (terminal === undefined || terminal.status !== "failed") return;
- assert.equal(terminal.failure.class, "usage_limit");
- assert.equal(terminal.failure.resetAt, "2026-09-25T01:10:00.000Z");
- if (standaloneEvent) {
- const pause = yield* Queue.take(harness.systemNoticeReceipts);
- assert.equal(pause.turnItem.type, "system_notice");
- if (pause.turnItem.type !== "system_notice") return;
- assert.include(pause.turnItem.message, "This turn is paused until the 5-hour limit");
- }
- }).pipe(
- Effect.provide(
- Layer.mergeAll(
- IdAllocator.layer,
- McpProviderSessions.layer,
- NodeServices.layer,
- NodeCrypto.layer,
- ),
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ ...wakeNotification,
+ task_id: SECOND_TASK_ID,
+ tool_use_id: SECOND_TOOL_USE_ID,
+ output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`,
+ summary: SECOND_SUMMARY,
+ uuid: "00000000-0000-4000-8000-000000000123",
+ }),
+ );
+ yield* harness.offerAndWait(
+ claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000124" }),
+ );
+ assert.lengthOf(harness.continuationRequests, 2);
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
),
),
),
+ ),
);
- it.effect(
- "dates a buffered wake gateway limit from its arrival, not the continuation replay",
- () =>
- Effect.scoped(
- Effect.gen(function* () {
- const harness = yield* makeWakeHarness;
- const now = yield* DateTime.now;
+ it.effect("keeps a newer wake's output when a stale continuation request is cleared", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const SECOND_TASK_ID = "b2ndwake";
+ const SECOND_TOOL_USE_ID = "toolu_second_wake";
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make("attempt-claude-wake-gateway-1"),
- text: "Run the build in the background.",
- attachments: [],
- }),
- );
- yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
- yield* Queue.offer(harness.sdkMessages, turnOneResult);
- yield* Queue.take(harness.terminalReceipts);
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-stale-clear-1"),
+ text: "Run two builds in the background.",
+ attachments: [],
+ }),
+ );
+ yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
+ yield* Queue.offer(
+ harness.sdkMessages,
+ claudeSdkFrame({
+ ...wakeTaskStarted,
+ task_id: SECOND_TASK_ID,
+ tool_use_id: SECOND_TOOL_USE_ID,
+ description: "Second sleep",
+ uuid: "00000000-0000-4000-8000-000000000131",
+ }),
+ );
+ yield* Queue.offer(harness.sdkMessages, turnOneResult);
+ yield* harness.awaitTerminal(1);
- yield* Queue.offer(harness.sdkMessages, wakeNotification);
- yield* harness.offerAndWait(
- makeAssistantErrorFrame({
- uuid: "00000000-0000-4000-8000-000000000634",
- error: "server_error",
+ yield* harness.offerAndWait(wakeNotification);
+ yield* harness.offerAndWait(wakeTurnInit);
+ assert.lengthOf(harness.continuationRequests, 1);
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-stale-clear-2"),
+ text: "Background task completed.",
+ attachments: [],
+ providerTurnOrdinal: 2,
+ messageCreatedBy: "agent",
+ messageCreationSource: "provider",
+ }),
+ );
+ yield* harness.offerAndWait(wakeAssistant);
+ yield* harness.offerAndWait(wakeResult);
+ yield* harness.awaitTerminal(2);
+
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ ...wakeNotification,
+ task_id: SECOND_TASK_ID,
+ tool_use_id: SECOND_TOOL_USE_ID,
+ output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`,
+ uuid: "00000000-0000-4000-8000-000000000133",
+ }),
+ );
+ yield* harness.offerAndWait(
+ claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000134" }),
+ );
+ assert.lengthOf(harness.continuationRequests, 2);
+
+ yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!();
+ yield* harness.offerAndWait(
+ makeAssistantTextFrame({
+ uuid: "00000000-0000-4000-8000-000000000135",
+ text: "Second build done.",
+ }),
+ );
+ yield* harness.offerAndWait(
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000136",
+ result: "Second build done.",
+ origin: { kind: "task-notification" },
+ }),
+ );
+ assert.lengthOf(harness.continuationRequests, 2);
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-stale-clear-3"),
+ text: "Background task completed.",
+ attachments: [],
+ providerTurnOrdinal: 3,
+ messageCreatedBy: "agent",
+ messageCreationSource: "provider",
+ }),
+ );
+ yield* harness.awaitTerminal(3);
+ assert.isTrue(
+ harness.events.some(
+ (event) =>
+ event.type === "turn_item.updated" &&
+ event.turnItem.type === "assistant_message" &&
+ event.turnItem.text === "Second build done.",
+ ),
+ "clearing the first wake's request must not discard the second wake's output",
+ );
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ ),
+ );
+
+ it.effect("offers the next wake when a cancelled wake's release arrives after it opened", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const SECOND_TASK_ID = "b2ndwake";
+ const SECOND_TOOL_USE_ID = "toolu_second_wake";
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
+
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-late-release"),
+ text: "Run two builds in the background.",
+ attachments: [],
+ }),
+ );
+ yield* harness.offerAndWait(wakeTaskStarted);
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ ...wakeTaskStarted,
+ task_id: SECOND_TASK_ID,
+ tool_use_id: SECOND_TOOL_USE_ID,
+ uuid: "00000000-0000-4000-8000-000000000141",
+ }),
+ );
+ yield* harness.offerAndWait(turnOneResult);
+ yield* harness.awaitTerminal(1);
+
+ yield* harness.offerAndWait(wakeNotification);
+ yield* harness.offerAndWait(wakeTurnInit);
+ yield* harness.offerAndWait(wakeAssistant);
+ yield* harness.offerAndWait(wakeResult);
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ ...wakeNotification,
+ task_id: SECOND_TASK_ID,
+ tool_use_id: SECOND_TOOL_USE_ID,
+ uuid: "00000000-0000-4000-8000-000000000142",
+ }),
+ );
+ yield* harness.offerAndWait(
+ claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000143" }),
+ );
+ assert.lengthOf(harness.continuationRequests, 1);
+
+ yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!();
+ yield* harness.offerAndWait(
+ claudeSdkFrame({ ...wakeAssistant, uuid: "00000000-0000-4000-8000-000000000144" }),
+ );
+ yield* harness.offerAndWait(
+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000145", result: "Done." }),
+ );
+ assert.lengthOf(
+ harness.continuationRequests,
+ 2,
+ "the wake that opened before the cancelled wake's release must get its own continuation",
+ );
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ ),
+ );
+
+ it.effect("does not offer a wake again when it is cancelled before its first root frame", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
+
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-early-cancel"),
+ text: "Start an agent in the background.",
+ attachments: [],
+ }),
+ );
+ yield* harness.offerAndWait(
+ claudeSdkFrame({ ...wakeTaskStarted, task_type: "local_agent" }),
+ );
+ yield* harness.offerAndWait(turnOneResult);
+ yield* harness.awaitTerminal(1);
+
+ yield* harness.offerAndWait(wakeNotification);
+ assert.lengthOf(harness.continuationRequests, 1);
+ yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!();
+ yield* harness.offerAndWait(wakeTurnInit);
+ yield* harness.offerAndWait(wakeAssistant);
+ yield* harness.offerAndWait(wakeResult);
+ assert.lengthOf(
+ harness.continuationRequests,
+ 1,
+ "the cancelled wake must not be offered again",
+ );
+
+ yield* harness.offerAndWait(
+ claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000146" }),
+ );
+ assert.lengthOf(harness.continuationRequests, 2, "the next wake must be offered");
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ ),
+ );
+
+ it.effect("offers a later task's wake when a cancelled wake never opens", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const SECOND_TASK_ID = "b2ndwake";
+ const SECOND_TOOL_USE_ID = "toolu_second_wake";
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
+
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-never-opens"),
+ text: "Start an agent and a build in the background.",
+ attachments: [],
+ }),
+ );
+ yield* harness.offerAndWait(
+ claudeSdkFrame({ ...wakeTaskStarted, task_type: "local_agent" }),
+ );
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ ...wakeTaskStarted,
+ task_id: SECOND_TASK_ID,
+ tool_use_id: SECOND_TOOL_USE_ID,
+ uuid: "00000000-0000-4000-8000-000000000151",
+ }),
+ );
+ yield* harness.offerAndWait(turnOneResult);
+ yield* harness.awaitTerminal(1);
+
+ // Claude never opens a wake for the agent's notification.
+ yield* harness.offerAndWait(wakeNotification);
+ assert.lengthOf(harness.continuationRequests, 1);
+ yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!();
+
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ ...wakeNotification,
+ task_id: SECOND_TASK_ID,
+ tool_use_id: SECOND_TOOL_USE_ID,
+ output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`,
+ uuid: "00000000-0000-4000-8000-000000000152",
+ }),
+ );
+ yield* harness.offerAndWait(
+ claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000153" }),
+ );
+ yield* harness.offerAndWait(
+ makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000154", text: "Built." }),
+ );
+ yield* harness.offerAndWait(
+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000155", result: "Built." }),
+ );
+ assert.lengthOf(
+ harness.continuationRequests,
+ 2,
+ "the build's wake must get its own continuation",
+ );
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ ),
+ );
+
+ it.effect.each([
+ { ending: "notification", cancelled: "after its result" },
+ { ending: "tool result", cancelled: "after its result" },
+ { ending: "tool result", cancelled: "while the subagent ran" },
+ ] as const)(
+ "does not replay a subagent that finished inside a cancelled wake (ended by $ending, cancelled $cancelled)",
+ ({ ending, cancelled }) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const SECOND_TASK_ID = "b2ndwake";
+ const SECOND_TOOL_USE_ID = "toolu_second_wake";
+ const SUBAGENT_TASK_ID = "fg-agent";
+ const SUBAGENT_TOOL_USE_ID = "toolu-fg-agent";
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
+
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-finished-subagent"),
+ text: "Run two builds in the background.",
+ attachments: [],
+ }),
+ );
+ yield* harness.offerAndWait(wakeTaskStarted);
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ ...wakeTaskStarted,
+ task_id: SECOND_TASK_ID,
+ tool_use_id: SECOND_TOOL_USE_ID,
+ uuid: "00000000-0000-4000-8000-000000000161",
+ }),
+ );
+ yield* harness.offerAndWait(turnOneResult);
+ yield* harness.awaitTerminal(1);
+
+ // The first wake runs a subagent to completion before its result.
+ yield* harness.offerAndWait(wakeNotification);
+ yield* harness.offerAndWait(wakeTurnInit);
+ assert.lengthOf(harness.continuationRequests, 1);
+ yield* harness.offerAndWait(wakeAssistant);
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ type: "system",
+ subtype: "task_started",
+ task_id: SUBAGENT_TASK_ID,
+ tool_use_id: SUBAGENT_TOOL_USE_ID,
+ description: "Inspect build output",
+ subagent_type: "general-purpose",
+ task_type: "local_agent",
+ prompt: "Inspect the build output.",
+ uuid: "00000000-0000-4000-8000-000000000162",
+ session_id: WAKE_NATIVE_SESSION,
+ }),
+ );
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ ...makeAssistantTextFrame({
+ uuid: "00000000-0000-4000-8000-000000000168",
+ text: "Reading the build log.",
+ }),
+ parent_tool_use_id: SUBAGENT_TOOL_USE_ID,
+ }),
+ );
+ if (cancelled === "while the subagent ran") {
+ yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!();
+ }
+ yield* harness.offerAndWait(
+ ending === "notification"
+ ? claudeSdkFrame({
+ type: "system",
+ subtype: "task_notification",
+ task_id: SUBAGENT_TASK_ID,
+ tool_use_id: SUBAGENT_TOOL_USE_ID,
+ status: "completed",
+ output_file: "/tmp/fg-agent.output",
+ summary: "Inspected",
+ uuid: "00000000-0000-4000-8000-000000000163",
+ session_id: WAKE_NATIVE_SESSION,
+ })
+ : claudeSdkFrame({
+ type: "user",
+ uuid: "00000000-0000-4000-8000-000000000163",
+ session_id: WAKE_NATIVE_SESSION,
+ parent_tool_use_id: null,
+ message: {
+ role: "user",
+ content: [
+ {
+ type: "tool_result",
+ tool_use_id: SUBAGENT_TOOL_USE_ID,
+ content: "Inspected",
+ },
+ ],
+ },
+ }),
+ );
+ yield* harness.offerAndWait(wakeResult);
+ if (cancelled === "after its result") {
+ yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!();
+ }
+
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ ...wakeNotification,
+ task_id: SECOND_TASK_ID,
+ tool_use_id: SECOND_TOOL_USE_ID,
+ output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`,
+ uuid: "00000000-0000-4000-8000-000000000164",
+ }),
+ );
+ yield* harness.offerAndWait(
+ claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000165" }),
+ );
+ assert.lengthOf(harness.continuationRequests, 2);
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-finished-subagent-2"),
+ text: "Background task completed.",
+ attachments: [],
+ providerTurnOrdinal: 2,
+ messageCreatedBy: "agent",
+ messageCreationSource: "provider",
+ }),
+ );
+ yield* harness.offerAndWait(
+ makeAssistantTextFrame({
+ uuid: "00000000-0000-4000-8000-000000000166",
+ text: "Second build done.",
+ }),
+ );
+ yield* harness.offerAndWait(
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000167",
+ result: "Second build done.",
+ origin: { kind: "task-notification" },
+ }),
+ );
+ yield* harness.awaitTerminal(2);
+
+ const subagentStatuses = harness.events.flatMap((event) =>
+ event.type === "subagent.updated" &&
+ event.subagent.nativeTaskRef?.nativeId === SUBAGENT_TASK_ID
+ ? [event.subagent.status]
+ : [],
+ );
+ assert.notInclude(
+ subagentStatuses,
+ "running",
+ "a subagent that finished in the cancelled wake must not be replayed as running",
+ );
+ assert.isFalse(yield* harness.hasPendingBackgroundWork);
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ ),
+ );
+
+ it.effect("offers a cancelled wake once when an empty lifecycle result precedes its turn", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const SECOND_TASK_ID = "b2ndwake";
+ const SECOND_TOOL_USE_ID = "toolu_second_wake";
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
+
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-empty-lifecycle"),
+ text: "Run two builds in the background.",
+ attachments: [],
+ }),
+ );
+ yield* harness.offerAndWait(wakeTaskStarted);
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ ...wakeTaskStarted,
+ task_id: SECOND_TASK_ID,
+ tool_use_id: SECOND_TOOL_USE_ID,
+ uuid: "00000000-0000-4000-8000-000000000171",
+ }),
+ );
+ yield* harness.offerAndWait(turnOneResult);
+ yield* harness.awaitTerminal(1);
+
+ yield* harness.offerAndWait(wakeNotification);
+ yield* harness.offerAndWait(wakeTurnInit);
+ assert.lengthOf(harness.continuationRequests, 1);
+ yield* harness.offerAndWait(
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000172",
+ result: "",
+ numTurns: 0,
+ origin: { kind: "task-notification" },
+ terminalReason: null,
+ }),
+ );
+ yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!();
+ yield* harness.offerAndWait(
+ claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000173" }),
+ );
+ yield* harness.offerAndWait(wakeAssistant);
+ yield* harness.offerAndWait(wakeResult);
+ assert.lengthOf(
+ harness.continuationRequests,
+ 1,
+ "the cancelled wake must not be offered again",
+ );
+
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ ...wakeNotification,
+ task_id: SECOND_TASK_ID,
+ tool_use_id: SECOND_TOOL_USE_ID,
+ output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`,
+ uuid: "00000000-0000-4000-8000-000000000174",
+ }),
+ );
+ yield* harness.offerAndWait(
+ claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000175" }),
+ );
+ assert.lengthOf(harness.continuationRequests, 2, "the next wake must be offered");
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ ),
+ );
+
+ it.effect("does not offer a cancelled wake again for its trailing empty lifecycle result", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
+
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-trailing-lifecycle"),
+ text: "Run a build in the background.",
+ attachments: [],
+ }),
+ );
+ yield* harness.offerAndWait(wakeTaskStarted);
+ yield* harness.offerAndWait(turnOneResult);
+ yield* harness.awaitTerminal(1);
+
+ yield* harness.offerAndWait(wakeNotification);
+ yield* harness.offerAndWait(wakeTurnInit);
+ yield* harness.offerAndWait(wakeAssistant);
+ yield* harness.offerAndWait(wakeResult);
+ yield* harness.offerAndWait(
+ claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000176" }),
+ );
+ yield* harness.offerAndWait(
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000177",
+ result: "",
+ numTurns: 0,
+ origin: { kind: "task-notification" },
+ terminalReason: null,
+ }),
+ );
+ assert.lengthOf(harness.continuationRequests, 1);
+ yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!();
+ assert.lengthOf(
+ harness.continuationRequests,
+ 1,
+ "a lifecycle result after the cancelled wake must not open another continuation",
+ );
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ ),
+ );
+
+ it.effect.each([
+ "before the cancelled wake's result",
+ "after the cancelled wake's result",
+ ] as const)(
+ "offers a subagent's wake that arrives behind a cancelled wake (notified %s)",
+ (notified) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const SUBAGENT_TASK_ID = "bg-agent";
+ const SUBAGENT_TOOL_USE_ID = "toolu-bg-agent";
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
+
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-later-subagent"),
+ text: "Run a build and an agent in the background.",
+ attachments: [],
+ }),
+ );
+ yield* harness.offerAndWait(wakeTaskStarted);
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ ...wakeTaskStarted,
+ task_id: SUBAGENT_TASK_ID,
+ tool_use_id: SUBAGENT_TOOL_USE_ID,
+ task_type: "local_agent",
+ uuid: "00000000-0000-4000-8000-000000000181",
+ }),
+ );
+ yield* harness.offerAndWait(turnOneResult);
+ yield* harness.awaitTerminal(1);
+
+ const subagentNotification = claudeSdkFrame({
+ ...wakeNotification,
+ task_id: SUBAGENT_TASK_ID,
+ tool_use_id: SUBAGENT_TOOL_USE_ID,
+ output_file: `/tmp/claude-replay/tasks/${SUBAGENT_TASK_ID}.output`,
+ summary: "Agent finished",
+ uuid: "00000000-0000-4000-8000-000000000182",
+ });
+ yield* harness.offerAndWait(wakeNotification);
+ yield* harness.offerAndWait(wakeTurnInit);
+ yield* harness.offerAndWait(wakeAssistant);
+ assert.lengthOf(harness.continuationRequests, 1);
+ if (notified === "before the cancelled wake's result") {
+ yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!();
+ yield* harness.offerAndWait(subagentNotification);
+ yield* harness.offerAndWait(wakeResult);
+ } else {
+ yield* harness.offerAndWait(wakeResult);
+ yield* harness.offerAndWait(subagentNotification);
+ yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!();
+ }
+ assert.lengthOf(
+ harness.continuationRequests,
+ 2,
+ "the subagent's wake must get its own continuation",
+ );
+ assert.equal(harness.continuationRequests[1]?.detail, "Agent finished");
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ ),
+ );
+
+ it.effect.each(["none", "before", "after", "sibling"] as const)(
+ "keeps an exited background command on the roster until its wake run starts (empty level %s notification)",
+ (emptyLevel) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
+ const secondTaskId = "second-owed-wake";
+ const taskIds = emptyLevel === "sibling" ? [WAKE_TASK_ID, secondTaskId] : [WAKE_TASK_ID];
+ const wakeAttemptId = RunAttemptId.make("attempt-claude-wake-roster-2");
+ const emptyRoster = claudeSdkFrame({
+ type: "system",
+ subtype: "background_tasks_changed",
+ tasks: [],
+ uuid: "00000000-0000-4000-8000-000000000204",
+ session_id: WAKE_NATIVE_SESSION,
+ });
+
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-roster-1"),
+ text: "Run the build in the background.",
+ attachments: [],
+ }),
+ );
+ yield* harness.offerAndWait(wakeTaskStarted);
+ if (emptyLevel === "sibling")
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ ...wakeTaskStarted,
+ task_id: secondTaskId,
+ tool_use_id: "toolu_second_owed_wake",
+ uuid: "00000000-0000-4000-8000-000000000205",
+ }),
+ );
+ const awaitBackgroundTasks = harness.runtime.awaitBackgroundTasks;
+ assert.isDefined(awaitBackgroundTasks);
+ yield* awaitBackgroundTasks!({
+ providerThread: harness.providerThread,
+ taskIds,
+ awaited: true,
+ });
+ yield* Queue.offer(harness.sdkMessages, turnOneResult);
+ yield* harness.awaitTerminal(1);
+ const afterFirstTurn = harness.events.length;
+ if (emptyLevel === "before" || emptyLevel === "sibling")
+ yield* harness.offerAndWait(emptyRoster);
+ yield* harness.offerAndWait(wakeNotification);
+ if (emptyLevel === "after") yield* harness.offerAndWait(emptyRoster);
+ // Query replacement reads the internal roster, which the exit already cleared.
+ assert.isFalse(yield* harness.hasPendingBackgroundWork);
+ yield* harness.offerAndWait(wakeTurnInit);
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: wakeAttemptId,
+ text: "Background task completed.",
+ attachments: [],
+ providerTurnOrdinal: 2,
+ messageCreatedBy: "agent",
+ messageCreationSource: "provider",
+ }),
+ );
+ yield* harness.offerAndWait(wakeAssistant);
+ yield* harness.offerAndWait(wakeResult);
+ yield* harness.awaitTerminal(2);
+
+ const wakeStart = harness.events.findIndex(
+ (event) =>
+ event.type === "provider_turn.updated" &&
+ event.providerTurn.runAttemptId === wakeAttemptId,
+ );
+ assert.isAbove(wakeStart, -1);
+ const rosters = harness.events.flatMap((event, index) =>
+ event.type === "provider_thread.updated" &&
+ event.providerThread.id === harness.providerThread.id &&
+ index >= afterFirstTurn
+ ? [
+ {
+ beforeWake: index < wakeStart,
+ pendingWork: event.pendingBackgroundWork === true,
+ taskIds: (event.providerThread.pendingBackgroundTasks ?? []).map((task) => [
+ task.taskId,
+ task.awaited === true,
+ ]),
+ },
+ ]
+ : [],
+ );
+ assert.deepEqual(
+ rosters.filter((roster) => roster.beforeWake).map((roster) => roster.taskIds),
+ rosters
+ .filter((roster) => roster.beforeWake)
+ .map(() => taskIds.map((id) => [id, true])),
+ );
+ assert.isTrue(
+ rosters.filter((roster) => roster.beforeWake).every((roster) => roster.pendingWork),
+ );
+ assert.deepEqual(
+ rosters.at(-1)?.taskIds,
+ emptyLevel === "sibling" ? [[secondTaskId, true]] : [],
+ );
+ if (emptyLevel === "sibling") {
+ assert.isTrue(rosters.at(-1)?.pendingWork);
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ ...wakeNotification,
+ task_id: secondTaskId,
+ tool_use_id: "toolu_second_owed_wake",
+ uuid: "00000000-0000-4000-8000-000000000206",
+ }),
+ );
+ yield* harness.offerAndWait(
+ claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000207" }),
+ );
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-owed-sibling-3"),
+ text: "Second command completed.",
+ attachments: [],
+ providerTurnOrdinal: 3,
+ messageCreatedBy: "agent",
+ messageCreationSource: "provider",
+ }),
+ );
+ yield* harness.offerAndWait(
+ makeAssistantTextFrame({
+ uuid: "00000000-0000-4000-8000-000000000208",
+ text: "Second command finished.",
+ }),
+ );
+ yield* harness.offerAndWait(
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000209",
+ result: "Second command finished.",
+ origin: { kind: "task-notification" },
+ }),
+ );
+ yield* harness.awaitTerminal(3);
+ assert.deepEqual(
+ providerThreadRosterEvents(harness.events).at(-1)?.providerThread
+ .pendingBackgroundTasks,
+ [],
+ );
+ }
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ ),
+ );
+
+ it.effect.each([true, false])(
+ "carries a rejected wake rate limit into the continuation failure (event=%s)",
+ (standaloneEvent) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
+ const resetsAt = 1790298600;
+
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-limit-1"),
+ text: "Run the build in the background.",
+ attachments: [],
+ }),
+ );
+ yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
+ yield* Queue.offer(harness.sdkMessages, turnOneResult);
+ yield* Queue.take(harness.terminalReceipts);
+
+ yield* Queue.offer(harness.sdkMessages, wakeNotification);
+ if (standaloneEvent) {
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ type: "rate_limit_event",
+ rate_limit_info: {
+ status: "rejected",
+ rateLimitType: "five_hour",
+ resetsAt,
+ overageStatus: "rejected",
+ },
+ uuid: "00000000-0000-4000-8000-000000000630",
+ session_id: WAKE_NATIVE_SESSION,
+ }),
+ );
+ }
+ assert.lengthOf(harness.continuationRequests, 0);
+ yield* harness.offerAndWait(
+ makeAssistantErrorFrame({
+ uuid: "00000000-0000-4000-8000-000000000631",
+ error: "rate_limit",
+ apiErrorParams: {
+ rate_limit_info: {
+ status: "rejected",
+ rateLimitType: "five_hour",
+ // A conflicting embedded time must not replace the event for this window.
+ resetsAt: standaloneEvent ? resetsAt + 3_600 : resetsAt,
+ },
+ },
+ }),
+ );
+ assert.lengthOf(harness.continuationRequests, 1);
+ yield* harness.offerAndWait(
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000632",
+ result: "You've hit your session limit · resets 11:10am (Australia/Sydney)",
+ isError: true,
+ apiErrorStatus: 429,
+ terminalReason: "api_error",
+ origin: { kind: "task-notification" },
+ }),
+ );
+ assert.lengthOf(harness.continuationRequests, 1);
+
+ // An empty session-task lifecycle result arriving before T3 opens the
+ // wake run must not replace the root's terminal usage-limit result.
+ yield* harness.offerAndWait(wakeTurnInit);
+ yield* harness.offerAndWait(
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000633",
+ result: "",
+ numTurns: 0,
+ origin: { kind: "task-notification" },
+ terminalReason: null,
+ }),
+ );
+
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-limit-2"),
+ text: "Background task completed.",
+ attachments: [],
+ providerTurnOrdinal: 2,
+ messageCreatedBy: "agent",
+ messageCreationSource: "provider",
+ }),
+ );
+ const terminal = yield* Queue.take(harness.terminalReceipts);
+ assert.equal(terminal?.status, "failed");
+ if (terminal === undefined || terminal.status !== "failed") return;
+ assert.equal(terminal.failure.class, "usage_limit");
+ assert.equal(terminal.failure.resetAt, "2026-09-25T01:10:00.000Z");
+ if (standaloneEvent) {
+ const pause = yield* Queue.take(harness.systemNoticeReceipts);
+ assert.equal(pause.turnItem.type, "system_notice");
+ if (pause.turnItem.type !== "system_notice") return;
+ assert.include(pause.turnItem.message, "This turn is paused until the 5-hour limit");
+ }
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ ),
+ );
+
+ it.effect(
+ "dates a buffered wake gateway limit from its arrival, not the continuation replay",
+ () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
+
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-gateway-1"),
+ text: "Run the build in the background.",
+ attachments: [],
+ }),
+ );
+ yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
+ yield* Queue.offer(harness.sdkMessages, turnOneResult);
+ yield* Queue.take(harness.terminalReceipts);
+
+ yield* Queue.offer(harness.sdkMessages, wakeNotification);
+ yield* harness.offerAndWait(
+ makeAssistantErrorFrame({
+ uuid: "00000000-0000-4000-8000-000000000634",
+ error: "server_error",
}),
);
assert.lengthOf(harness.continuationRequests, 1);
@@ -14358,6 +15369,96 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
+ it.effect.each(["before", "after"] as const)(
+ "offers a later wake when a wake a user turn absorbed is cancelled %s that turn ends",
+ (cancelled) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const SECOND_TASK_ID = "b2ndwake";
+ const SECOND_TOOL_USE_ID = "toolu_second_wake";
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
+
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-cancel-1"),
+ text: "Run two builds in the background.",
+ attachments: [],
+ }),
+ );
+ yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
+ yield* Queue.offer(
+ harness.sdkMessages,
+ claudeSdkFrame({
+ ...wakeTaskStarted,
+ task_id: SECOND_TASK_ID,
+ tool_use_id: SECOND_TOOL_USE_ID,
+ uuid: "00000000-0000-4000-8000-000000000191",
+ }),
+ );
+ yield* Queue.offer(harness.sdkMessages, wakeNotification);
+ yield* Queue.offer(harness.sdkMessages, turnOneResult);
+ yield* harness.awaitTerminal(1);
+ yield* harness.offerAndWait(wakeTurnInit);
+ yield* harness.offerAndWait(wakeAssistant);
+ yield* harness.awaitContinuation(1);
+
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-cancel-2"),
+ text: "Any update on the pull request?",
+ attachments: [],
+ providerTurnOrdinal: 2,
+ }),
+ );
+ yield* harness.until(() => harness.offeredMessages.length === 2);
+ if (cancelled === "before") {
+ yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!();
+ }
+ yield* Queue.offer(
+ harness.sdkMessages,
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000192",
+ result: "Checks passed and the pull request is up to date.",
+ }),
+ );
+ yield* harness.awaitTerminal(2);
+ if (cancelled === "after") {
+ yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!();
+ }
+
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ ...wakeNotification,
+ task_id: SECOND_TASK_ID,
+ tool_use_id: SECOND_TOOL_USE_ID,
+ output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`,
+ uuid: "00000000-0000-4000-8000-000000000193",
+ }),
+ );
+ yield* harness.offerAndWait(
+ claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000194" }),
+ );
+ assert.lengthOf(harness.continuationRequests, 2, "the later wake must be offered");
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ ),
+ );
+
it.effect("ignores a zero-turn task-notification origin result during a normal user turn", () =>
Effect.scoped(
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index a02dcb3bcbdf1..29556cf6ee531 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -146,6 +146,7 @@ import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
+import * as Schedule from "effect/Schedule";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -178,6 +179,7 @@ import {
} from "../../claudeModelOptions.ts";
import * as ServerConfig from "../../config.ts";
import * as PortScanner from "../../preview/PortScanner.ts";
+import * as ProcessRunner from "../../processRunner.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe";
@@ -364,6 +366,7 @@ export const CLAUDE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CLAUDE_PROV
const CLAUDE_SCRIPT_EXTENSIONS = [".js", ".mjs", ".tsx", ".ts", ".jsx"];
// The SDK has no control-request deadline; the CLI waits up to 30 s per MCP server.
const CLAUDE_MCP_REGISTRATION_TIMEOUT = "90 seconds";
+const CLAUDE_BOOT_TIMEOUT = "5 minutes";
// Claude can consume a subagent result before the launching turn ends, leaving
// its notification with no native wake turn to answer the continuation.
const CLAUDE_WAKE_TURN_START_DEADLINE = "2 minutes";
@@ -380,6 +383,8 @@ const CLAUDE_STOP_CONFIRM_TIMEOUT_MS = 10_000;
const CLAUDE_STDERR_TAIL_LENGTH = 2_048;
// The process group is killed on exit, so its stderr closes promptly.
const CLAUDE_STDERR_DRAIN_TIMEOUT = Duration.seconds(1);
+// How often the CLI's process tree is recorded when no agent scope will stop what it leaves.
+const CLAUDE_DESCENDANT_POLL = "1 second";
// Claude Code's refusal of bypassPermissions as root, which it explains only on stderr.
const CLAUDE_ROOT_REFUSAL =
"--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";
@@ -399,7 +404,7 @@ export function spawnClaudeProcessGroup(
onExit?: () => void,
onStderr: (text: string) => void = () => {},
onStderrClose: () => void = () => {},
-): ClaudeSpawnedProcess {
+): ClaudeSpawnedProcess & Pick {
const child = NodeChildProcess.spawn(
"/bin/sh",
["-c", CLAUDE_GROUP_WATCH_SCRIPT, "t3-claude", options.command, ...options.args],
@@ -420,7 +425,60 @@ export function spawnClaudeProcessGroup(
onExit?.();
});
// Node's typings make stdin and stdout nullable once stdio has a fourth entry; both are pipes.
- return child as ClaudeSpawnedProcess;
+ return child as ClaudeSpawnedProcess & Pick;
+}
+
+interface ClaudeProcessRow {
+ readonly pid: number;
+ readonly ppid: number;
+ readonly pgid: number;
+ readonly started: string;
+}
+
+/** Parses `ps -A -o pid=,ppid=,pgid=,lstart=`; pid plus start time tells a process from a reused pid. */
+function parseClaudeProcessTable(table: string): ReadonlyArray {
+ return table.split("\n").flatMap((line) => {
+ const [pid, ppid, pgid, ...started] = line.trim().split(/\s+/);
+ const row = {
+ pid: Number(pid),
+ ppid: Number(ppid),
+ pgid: Number(pgid),
+ started: started.join(" "),
+ };
+ return Number.isSafeInteger(row.pid) &&
+ Number.isSafeInteger(row.ppid) &&
+ Number.isSafeInteger(row.pgid) &&
+ row.started
+ ? [row]
+ : [];
+ });
+}
+
+// A job leading its own group takes the processes it started since with it.
+function killClaudeDescendant(row: ClaudeProcessRow) {
+ try {
+ if (row.pgid === row.pid) signalProcessGroup(row.pid, "SIGKILL");
+ else process.kill(row.pid, "SIGKILL");
+ } catch {}
+}
+
+function claudeDescendants(
+ rows: ReadonlyArray,
+ rootPids: ReadonlyArray,
+): ReadonlyArray {
+ const children = Map.groupBy(rows, (row) => row.ppid);
+ const found: Array = [];
+ const seen = new Set(rootPids);
+ const pending = [...rootPids];
+ for (let parent = pending.pop(); parent !== undefined; parent = pending.pop()) {
+ for (const child of children.get(parent) ?? []) {
+ if (seen.has(child.pid)) continue;
+ seen.add(child.pid);
+ found.push(child);
+ pending.push(child.pid);
+ }
+ }
+ return found;
}
export const ClaudeProviderCapabilitiesV2 = {
@@ -640,10 +698,12 @@ export class ClaudeCodeRootRefusalError extends Schema.TaggedError()(
"ClaudeMcpRegistrationTimeoutError",
- {},
+ { phase: Schema.Literals(["initialize", "setMcpServers"]) },
) {
override get message(): string {
- return "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.";
+ return this.phase === "initialize"
+ ? "Claude timed out while starting up. Retry the turn; if it keeps failing, check Claude and the server logs."
+ : "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.";
}
}
@@ -1213,6 +1273,41 @@ export const layerQueryRunner: Layer.Layer<
const runFork = Effect.runForkWith(yield* Effect.context());
const hostEnvironment = yield* HostProcess.Environment;
const portDiscovery = yield* PortScanner.PortDiscovery;
+ const processRunner = yield* ProcessRunner.make();
+ const readProcessTable = processRunner
+ .run({ command: "ps", args: ["-A", "-o", "pid=,ppid=,pgid=,lstart="], timeout: "5 seconds" })
+ .pipe(
+ Effect.map((result) => (result.code === 0 ? parseClaudeProcessTable(result.stdout) : [])),
+ Effect.orElseSucceed(() => []),
+ );
+ // Without an agent scope, a job that left the CLI's group escapes the group kill and is
+ // re-parented once the CLI exits. So the CLI's tree is recorded while it runs, and what is
+ // still the same process (pid and start time) is stopped after it exits.
+ const trackDescendants = (cliPid: number) => {
+ const tracked = new Map();
+ const identity = (row: ClaudeProcessRow) => `${row.pid} ${row.started}`;
+ // After exit the CLI's pid may belong to an unrelated process, so only tracked jobs are roots.
+ const refresh = Effect.fn("ClaudeAgentSdkQueryRunner.trackDescendants")(function* (
+ cliRunning: boolean,
+ ) {
+ const rows = yield* readProcessTable;
+ const running = new Set(rows.map(identity));
+ const roots = [
+ ...(cliRunning ? [cliPid] : []),
+ ...[...tracked.values()].flatMap((row) => (running.has(identity(row)) ? [row.pid] : [])),
+ ];
+ for (const row of claudeDescendants(rows, roots)) tracked.set(identity(row), row);
+ return running;
+ });
+ const stop = refresh(false).pipe(
+ Effect.map((running) => {
+ for (const row of tracked.values()) {
+ if (running.has(identity(row))) killClaudeDescendant(row);
+ }
+ }),
+ );
+ return { refresh: refresh(true).pipe(Effect.asVoid), stop };
+ };
return ClaudeAgentSdkQueryRunner.of({
allocateSessionId: random.uuidV4(),
@@ -1277,6 +1372,7 @@ export const layerQueryRunner: Layer.Layer<
if (answered) return;
stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH);
};
+ let refreshDescendants: Effect.Effect = Effect.void;
const spawnProcess =
options.spawnClaudeCodeProcess ??
((spawnOptions: ClaudeSpawnOptions) => {
@@ -1284,7 +1380,23 @@ export const layerQueryRunner: Layer.Layer<
// Node can report "exit" before it has read the stderr the CLI wrote.
let stderrDone = () => {};
stderrClosed = new Promise((resolve) => (stderrDone = resolve));
- return spawnClaudeProcessGroup(spawnOptions, stopScope, appendStderr, stderrDone);
+ const child = spawnClaudeProcessGroup(
+ spawnOptions,
+ stopScope,
+ appendStderr,
+ stderrDone,
+ );
+ if (unit === undefined && child.pid !== undefined) {
+ const tracker = trackDescendants(child.pid);
+ const polling = runFork(
+ tracker.refresh.pipe(Effect.repeat(Schedule.spaced(CLAUDE_DESCENDANT_POLL))),
+ );
+ child.once("exit", () =>
+ runFork(Fiber.interrupt(polling).pipe(Effect.andThen(tracker.stop))),
+ );
+ refreshDescendants = tracker.refresh;
+ }
+ return child;
}
const child = NodeChildProcess.spawn(spawnOptions.command, spawnOptions.args, {
cwd: spawnOptions.cwd,
@@ -1332,6 +1444,31 @@ export const layerQueryRunner: Layer.Layer<
restore(
Effect.gen(function* () {
if (mcpServers !== undefined) {
+ const timedOut = (phase: ClaudeMcpRegistrationTimeoutError["phase"]) => () =>
+ Effect.logWarning("orchestration-v2.claude-mcp-registration-timeout", {
+ threadId: input.threadId,
+ providerSessionId: input.providerSessionId,
+ phase,
+ }).pipe(
+ Effect.andThen(
+ Effect.fail(
+ queryRunnerError(
+ new ClaudeMcpRegistrationTimeoutError({ phase }),
+ phase,
+ ),
+ ),
+ ),
+ );
+ // The SDK leaves query() boot unbounded, and it takes about a minute on a host
+ // with CPUs 12x oversubscribed, so it gets its own, longer deadline.
+ yield* Effect.promise(() =>
+ queryRuntime.initializationResult().catch(() => undefined),
+ ).pipe(
+ Effect.timeoutOrElse({
+ duration: CLAUDE_BOOT_TIMEOUT,
+ orElse: timedOut("initialize"),
+ }),
+ );
// Errors and mcp_status can echo headers; log only server names.
const failed = yield* Effect.tryPromise({
try: () => queryRuntime.setMcpServers(mcpServers),
@@ -1341,20 +1478,7 @@ export const layerQueryRunner: Layer.Layer<
Effect.orElseSucceed(() => Object.keys(mcpServers)),
Effect.timeoutOrElse({
duration: CLAUDE_MCP_REGISTRATION_TIMEOUT,
- orElse: () =>
- Effect.logWarning("orchestration-v2.claude-mcp-registration-timeout", {
- threadId: input.threadId,
- providerSessionId: input.providerSessionId,
- }).pipe(
- Effect.andThen(
- Effect.fail(
- queryRunnerError(
- new ClaudeMcpRegistrationTimeoutError(),
- "setMcpServers",
- ),
- ),
- ),
- ),
+ orElse: timedOut("setMcpServers"),
}),
);
if (failed.length > 0) {
@@ -1579,7 +1703,9 @@ export const layerQueryRunner: Layer.Layer<
}),
),
),
- close: Queue.shutdown(promptQueue).pipe(
+ // A job started since the last poll is recorded before the CLI is told to exit.
+ close: Effect.suspend(() => (processExited ? Effect.void : refreshDescendants)).pipe(
+ Effect.andThen(Queue.shutdown(promptQueue)),
Effect.andThen(closeClaudeQuery(queryRuntime)),
Effect.tap(() =>
logProtocolEvent({
@@ -3511,6 +3637,45 @@ function isClaudeSubagentAsyncLaunchAck(output: ClaudeNativeToolOutput): boolean
return claudeSubagentResultText(output).startsWith("Async agent launched successfully.");
}
+// Background Agent launches ACK immediately and workflow launches return run handles; only task_notification settles those.
+function claudeToolResultSettlesSubagent(
+ toolResult: ClaudeToolResultContentBlock,
+ output: ClaudeNativeToolOutput,
+): boolean {
+ return (
+ isClaudeToolResultError(toolResult) ||
+ (parseClaudeWorkflowRunHandles(claudeNativeToolOutputValue(output)) === undefined &&
+ !isClaudeSubagentAsyncLaunchAck(output))
+ );
+}
+
+function claudeSettledSubagentToolUseIds(messages: ReadonlyArray): ReadonlySet {
+ return new Set(
+ messages.flatMap((entry) =>
+ entry.type === "user" && entry.parent_tool_use_id == null
+ ? claudeToolResultEntriesFromMessage(entry).flatMap(({ toolResult, output }) =>
+ claudeToolResultSettlesSubagent(toolResult, output) ? [toolResult.tool_use_id] : [],
+ )
+ : [],
+ ),
+ );
+}
+
+function claudeWakeBufferDetail(messages: ReadonlyArray): string | null {
+ return (
+ messages
+ .flatMap((entry) =>
+ entry.type === "system" &&
+ entry.subtype === "task_notification" &&
+ typeof entry.summary === "string" &&
+ entry.summary.length > 0
+ ? [entry.summary]
+ : [],
+ )
+ .at(-1) ?? null
+ );
+}
+
const WEB_FETCH_SNIPPET_MAX_CHARS = 8_000;
function webSearchPatternsFromClaudeTool(input: {
@@ -4137,6 +4302,18 @@ function isClaudeTaskNotificationOriginResult(message: SDKMessage): message is S
return message.type === "result" && message.origin?.kind === "task-notification";
}
+// A session-task lifecycle result: it can precede a wake's real turn and ends no turn.
+function isClaudeEmptyTaskNotificationSuccess(message: SDKMessage): boolean {
+ return (
+ isClaudeTaskNotificationOriginResult(message) &&
+ message.subtype === "success" &&
+ !message.is_error &&
+ message.num_turns === 0 &&
+ message.result.length === 0 &&
+ terminalStatusFromResult(message) === "completed"
+ );
+}
+
// The CLI throttles unchanged rate_limit_event frames, but repeats this
// undeclared payload on each blocked assistant response.
const isClaudeBlockedAssistantRateLimit = Schema.is(
@@ -5593,7 +5770,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
return { kind: "command", label, outcome };
}
});
- const requestedContinuations = yield* Ref.make(new Set());
+ // `end` is the offered wake's last frame once known: its result, or the last frame a user turn absorbed.
+ // A retired latch belongs to a cancelled wake that has not ended; its root frames are dropped until it does.
+ // Claude may never open an "unopened" one, so a later task's notification releases it instead.
+ const requestedContinuations = yield* Ref.make(
+ new Map<
+ string,
+ {
+ readonly token: symbol;
+ readonly end: SDKMessage | undefined;
+ readonly retired: "unopened" | "opened" | null;
+ }
+ >(),
+ );
const absorbedWakes = yield* Ref.make(new Set());
const heldProposedPlansByToolUseId = new Map();
const runtimeContext = yield* Effect.context();
@@ -5878,6 +6067,24 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
taskId,
);
+ // Untraced with roster emission: this runs for each streamed roster update.
+ const owedWakeTasksForNativeThread = Effect.fnUntraced(function* (nativeThreadId: string) {
+ const previous = (yield* Ref.get(lastProviderThreadByNativeThread)).get(nativeThreadId);
+ const roster = rosterForNativeThread(
+ yield* Ref.get(pendingBackgroundTasksByNativeThread),
+ nativeThreadId,
+ );
+ const tasks: OrchestrationV2PendingBackgroundTask[] = [];
+ for (const task of previous?.pendingBackgroundTasks ?? []) {
+ if (
+ !roster.has(task.taskId) &&
+ (yield* isKnownOpaqueBackgroundTaskOnNativeThread(nativeThreadId, task.taskId))
+ )
+ tasks.push(task);
+ }
+ return tasks;
+ });
+
const emitProviderThreadRoster = Effect.fnUntraced(function* (input: {
readonly nativeThreadId: string;
readonly providerThread: OrchestrationV2ProviderThread;
@@ -5891,16 +6098,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
yield* Ref.get(awaitedBackgroundTasksByNativeThread),
input.nativeThreadId,
);
+ const owedWakeTasks = yield* owedWakeTasksForNativeThread(input.nativeThreadId);
const now = yield* DateTime.now;
const providerThread: OrchestrationV2ProviderThread = {
...input.providerThread,
providerSessionId: session.id,
...(input.status === undefined ? {} : { status: input.status }),
- pendingBackgroundTasks: publishedPendingBackgroundTasks(
- input.nativeThreadId,
- roster,
- awaitedTaskIds,
- ),
+ pendingBackgroundTasks: [
+ ...publishedPendingBackgroundTasks(input.nativeThreadId, roster, awaitedTaskIds),
+ ...owedWakeTasks,
+ ],
...(goalsByNativeThread.has(input.nativeThreadId)
? { goal: goalsByNativeThread.get(input.nativeThreadId) ?? null }
: {}),
@@ -5911,6 +6118,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
type: "provider_thread.updated",
driver: CLAUDE_PROVIDER,
providerThread,
+ pendingBackgroundWork: owedWakeTasks.length > 0,
});
});
@@ -6079,20 +6287,41 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
if (!current.has(nativeThreadId)) {
return current;
}
- const updated = new Set(current);
+ const updated = new Map(current);
updated.delete(nativeThreadId);
return updated;
});
yield* forgetAbsorbedWake(nativeThreadId);
});
+ const releaseContinuationLatch = (nativeThreadId: string) =>
+ Ref.update(requestedContinuations, (current) => {
+ if (!current.has(nativeThreadId)) return current;
+ const updated = new Map(current);
+ updated.delete(nativeThreadId);
+ return updated;
+ });
+
// Claude runs one root turn at a time, so a user turn's result also ends a wake turn it
// folded in. The continuation replays that wake's buffered frames but gets no result of its own.
const markAbsorbedWake = Effect.fnUntraced(function* (nativeThreadId: string) {
+ const latch = (yield* Ref.get(requestedContinuations)).get(nativeThreadId);
+ if (latch !== undefined && latch.retired !== null) {
+ yield* releaseContinuationLatch(nativeThreadId);
+ return;
+ }
const messages = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? [];
const lastResult = messages.findLastIndex((entry) => entry.type === "result");
if (!messages.slice(lastResult + 1).some(isClaudeRootTurnFrame)) return;
yield* Ref.update(absorbedWakes, (current) => new Set(current).add(nativeThreadId));
+ if (latch !== undefined && latch.end === undefined) {
+ yield* Ref.update(requestedContinuations, (current) =>
+ new Map(current).set(nativeThreadId, {
+ ...latch,
+ end: messages.findLast(isClaudeRootTurnFrame),
+ }),
+ );
+ }
});
// The SDK emits no initial roster; reset roster and wake eligibility when opening a live query.
@@ -8482,6 +8711,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
yield* Ref.get(awaitedBackgroundTasksByNativeThread),
nativeThreadId,
);
+ const owedWakeTasks =
+ nativeThreadId === null
+ ? []
+ : yield* owedWakeTasksForNativeThread(nativeThreadId);
// A stopped turn that wrote to the transcript moved past the pinned head.
const clearConversationHead =
(input.status === "completed" || input.context.nativeMessageCursor !== null) &&
@@ -8520,11 +8753,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
input.context.input.providerThread.firstRunOrdinal ??
input.context.input.runOrdinal,
lastRunOrdinal: input.context.input.runOrdinal,
- pendingBackgroundTasks: publishedPendingBackgroundTasks(
- nativeThreadId,
- roster,
- awaitedTaskIds,
- ),
+ pendingBackgroundTasks: [
+ ...publishedPendingBackgroundTasks(nativeThreadId, roster, awaitedTaskIds),
+ ...owedWakeTasks,
+ ],
status: input.status === "completed" ? "active" : "idle",
updatedAt: input.completedAt,
};
@@ -8533,6 +8765,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
type: "provider_thread.updated" as const,
driver: CLAUDE_PROVIDER,
providerThread,
+ pendingBackgroundWork: owedWakeTasks.length > 0,
});
}),
emitProviderEvent(terminalEvent),
@@ -8861,6 +9094,34 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
if (!isWakeEvidence) {
return;
}
+ const retired = (yield* Ref.get(requestedContinuations)).get(
+ wakeInput.nativeThreadId,
+ )?.retired;
+ if (
+ retired === "unopened" &&
+ (isPendingTaskNotification || isPendingSubagentNotification)
+ ) {
+ yield* releaseContinuationLatch(wakeInput.nativeThreadId);
+ } else if (
+ retired != null &&
+ (isClaudeRootTurnFrame(message) ||
+ message.type === "result" ||
+ message.type === "rate_limit_event")
+ ) {
+ if (isClaudeEmptyTaskNotificationSuccess(message)) {
+ yield* setRetiredLatch(wakeInput.nativeThreadId, "unopened");
+ } else if (message.type === "result") {
+ yield* releaseContinuationLatch(wakeInput.nativeThreadId);
+ yield* offerBufferedWake(wakeInput.nativeThreadId);
+ } else if (isClaudeRootTurnFrame(message)) {
+ yield* setRetiredLatch(wakeInput.nativeThreadId, "opened");
+ yield* dropSettledSubagents(
+ wakeInput.nativeThreadId,
+ claudeSettledSubagentToolUseIds([message]),
+ );
+ }
+ return;
+ }
const notificationSummary =
isNotification && typeof message.summary === "string" && message.summary.length > 0
? message.summary
@@ -8911,6 +9172,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
message.task_id,
);
}
+ if (message.type === "result" && !isClaudeEmptyTaskNotificationSuccess(message)) {
+ yield* Ref.update(requestedContinuations, (current) => {
+ const latch = current.get(wakeInput.nativeThreadId);
+ if (latch === undefined || latch.end !== undefined) return current;
+ return new Map(current).set(wakeInput.nativeThreadId, { ...latch, end: message });
+ });
+ }
// Open continuations only after root init, user, assistant, or result frames prove a wake began.
// Background child frames can stream while the root is idle.
const buffered = (yield* Ref.get(wakeBuffers)).get(wakeInput.nativeThreadId);
@@ -8930,28 +9198,38 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
) {
return;
}
- const route = (yield* Ref.get(lastTurnRouteByNativeThread)).get(wakeInput.nativeThreadId);
+ yield* offerWakeContinuation(wakeInput.nativeThreadId);
+ });
+
+ const offerWakeContinuation = Effect.fnUntraced(function* (nativeThreadId: string) {
+ const route = (yield* Ref.get(lastTurnRouteByNativeThread)).get(nativeThreadId);
if (route === undefined) {
yield* Effect.logWarning("orchestration-v2.claude-wake-turn-unroutable", {
providerSessionId: input.providerSessionId,
- nativeThreadId: wakeInput.nativeThreadId,
+ nativeThreadId,
});
return;
}
+ const buffered = (yield* Ref.get(wakeBuffers)).get(nativeThreadId);
+ const token = Symbol(nativeThreadId);
const shouldOffer = yield* Ref.modify(requestedContinuations, (current) => {
- if (current.has(wakeInput.nativeThreadId)) {
+ if (current.has(nativeThreadId)) {
return [false, current] as const;
}
- const updated = new Set(current);
- updated.add(wakeInput.nativeThreadId);
+ const updated = new Map(current);
+ updated.set(nativeThreadId, {
+ token,
+ end: buffered?.messages.find(
+ (entry) => entry.type === "result" && !isClaudeEmptyTaskNotificationSuccess(entry),
+ ),
+ retired: null,
+ });
return [true, updated] as const;
});
if (!shouldOffer) {
return;
}
- const detail =
- (yield* Ref.get(wakeBuffers)).get(wakeInput.nativeThreadId)?.detail ?? null;
- const reports = yield* takeWakeReports(wakeInput.nativeThreadId);
+ const reports = yield* takeWakeReports(nativeThreadId);
const notification = backgroundWorkNotification(
[...(reports?.values() ?? [])].map((entry) => entry.report),
);
@@ -8960,13 +9238,169 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
threadId: route.threadId,
providerThreadId: route.providerThreadId,
});
+ // A process reset can clear and re-latch this thread; a stale request must not retire the newer wake.
+ const retire = (): Effect.Effect =>
+ sdkMessageLock.withPermits(1)(retireOfferedWake(nativeThreadId, token));
yield* continuationRequests.offer({
threadId: route.threadId,
providerThreadId: route.providerThreadId,
driver: CLAUDE_PROVIDER,
- detail,
+ detail: buffered?.detail ?? null,
...(notification === null ? {} : { notification }),
+ clearIfCurrent: retire,
+ onRunEndedWithoutStarting: retire,
+ });
+ });
+
+ // Drops what the unstarted continuation would have shown. Starts of subagents still running stay
+ // because later child frames and notifications resolve their owner from them.
+ const retireOfferedWake = Effect.fnUntraced(function* (
+ nativeThreadId: string,
+ token: symbol,
+ ) {
+ const latch = (yield* Ref.get(requestedContinuations)).get(nativeThreadId);
+ if (latch?.token !== token) return;
+ const buffered = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages;
+ const messages = buffered ?? [];
+ const endIndex =
+ latch.end === undefined ? messages.length - 1 : messages.indexOf(latch.end);
+ const retired = messages.slice(0, endIndex + 1);
+ const later = messages.slice(endIndex + 1);
+ const retiredTaskIds = new Set(
+ retired.flatMap((entry) =>
+ entry.type === "system" && entry.subtype === "task_notification"
+ ? [entry.task_id]
+ : [],
+ ),
+ );
+ const settledToolUseIds = claudeSettledSubagentToolUseIds(retired);
+ const kept = [
+ ...retired.filter(
+ (entry) =>
+ entry.type === "system" &&
+ entry.subtype === "task_started" &&
+ !retiredTaskIds.has(entry.task_id) &&
+ (entry.tool_use_id === undefined || !settledToolUseIds.has(entry.tool_use_id)),
+ ),
+ ...later,
+ ];
+ if (!(yield* replaceWakeBuffer(nativeThreadId, buffered, kept, retiredTaskIds))) return;
+ for (const taskId of retiredTaskIds) {
+ yield* clearPendingBackgroundTask(nativeThreadId, taskId);
+ yield* clearTaskIdFromNativeThreadSet(
+ wakeEligibleBackgroundTasksByNativeThread,
+ nativeThreadId,
+ taskId,
+ );
+ yield* clearOpaqueBackgroundTaskReplayTombstone(nativeThreadId, taskId);
+ }
+ yield* endClaudeMonitorTasks((taskId) => retiredTaskIds.has(taskId));
+ const providerThread = (yield* Ref.get(lastProviderThreadByNativeThread)).get(
+ nativeThreadId,
+ );
+ if (providerThread !== undefined)
+ yield* emitProviderThreadRoster({ nativeThreadId, providerThread });
+ if (latch.end === undefined) {
+ // A lifecycle result closes the root frames before it without opening the wake's turn.
+ const sinceLifecycleResult = retired.slice(
+ retired.findLastIndex(isClaudeEmptyTaskNotificationSuccess) + 1,
+ );
+ yield* setRetiredLatch(
+ nativeThreadId,
+ sinceLifecycleResult.some(isClaudeRootTurnFrame) ? "opened" : "unopened",
+ );
+ return;
+ }
+ yield* releaseContinuationLatch(nativeThreadId);
+ yield* forgetAbsorbedWake(nativeThreadId);
+ yield* offerBufferedWake(nativeThreadId);
+ });
+
+ const setRetiredLatch = (nativeThreadId: string, retired: "unopened" | "opened") =>
+ Ref.update(requestedContinuations, (current) => {
+ const latch = current.get(nativeThreadId);
+ return latch === undefined || latch.retired === retired
+ ? current
+ : new Map(current).set(nativeThreadId, { ...latch, retired });
});
+
+ // Compare-and-set: a process reset clears the buffer without the SDK message lock, and must not be undone.
+ const replaceWakeBuffer = Effect.fnUntraced(function* (
+ nativeThreadId: string,
+ expected: ReadonlyArray | undefined,
+ messages: ReadonlyArray,
+ droppedTaskIds: ReadonlySet,
+ ) {
+ const replaced = yield* Ref.modify(wakeBuffers, (current) => {
+ if (current.get(nativeThreadId)?.messages !== expected)
+ return [false, current] as const;
+ const updated = new Map(current);
+ if (messages.length === 0) updated.delete(nativeThreadId);
+ else
+ updated.set(nativeThreadId, { messages, detail: claudeWakeBufferDetail(messages) });
+ return [true, updated] as const;
+ });
+ if (!replaced) return false;
+ yield* Ref.update(wakeReportsByNativeThread, ({ userTurns, reports }) => {
+ const threadReports = reports.get(nativeThreadId);
+ if (threadReports === undefined) return { userTurns, reports };
+ const remaining = new Map(
+ [...threadReports].filter(([taskId]) => !droppedTaskIds.has(taskId)),
+ );
+ const updatedReports = new Map(reports);
+ if (remaining.size === 0) updatedReports.delete(nativeThreadId);
+ else updatedReports.set(nativeThreadId, remaining);
+ return { userTurns, reports: updatedReports };
+ });
+ return true;
+ });
+
+ // A retired wake's dropped tool results still settle the subagents it kept for later frames.
+ const dropSettledSubagents = Effect.fnUntraced(function* (
+ nativeThreadId: string,
+ settledToolUseIds: ReadonlySet,
+ ) {
+ if (settledToolUseIds.size === 0) return;
+ const buffered = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages;
+ const messages = buffered ?? [];
+ const settledTaskIds = new Set(
+ messages.flatMap((entry) =>
+ entry.type === "system" &&
+ entry.subtype === "task_started" &&
+ entry.tool_use_id !== undefined &&
+ settledToolUseIds.has(entry.tool_use_id)
+ ? [entry.task_id]
+ : [],
+ ),
+ );
+ const kept = messages.filter((entry) => {
+ const parentToolUseId = parentToolUseIdFromSdkMessage(entry);
+ return (
+ (parentToolUseId === null || !settledToolUseIds.has(parentToolUseId)) &&
+ !(entry.type === "system" && "task_id" in entry && settledTaskIds.has(entry.task_id))
+ );
+ });
+ if (kept.length === messages.length) return;
+ yield* replaceWakeBuffer(nativeThreadId, buffered, kept, settledTaskIds);
+ });
+
+ // After a retired wake releases its latch, a wake buffered behind it has had no offer of its own.
+ const offerBufferedWake = Effect.fnUntraced(function* (nativeThreadId: string) {
+ const messages = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? [];
+ const reports = (yield* Ref.get(wakeReportsByNativeThread)).reports.get(nativeThreadId);
+ // A lifecycle result ends no turn, and closes the root frames before it.
+ const hasWake =
+ messages
+ .slice(messages.findLastIndex(isClaudeEmptyTaskNotificationSuccess) + 1)
+ .some(isClaudeRootTurnFrame) ||
+ messages.some(
+ (entry) =>
+ (entry.type === "result" && !isClaudeEmptyTaskNotificationSuccess(entry)) ||
+ (entry.type === "system" &&
+ entry.subtype === "task_notification" &&
+ reports?.get(entry.task_id)?.report.kind === "subagent"),
+ );
+ if (hasWake) yield* offerWakeContinuation(nativeThreadId);
});
// Untraced like the roster message handling: it runs for every streamed roster change.
@@ -8986,7 +9420,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
: baseThread.status === "idle"
? ("active" as const)
: baseThread.status;
- yield* emitProviderThreadRoster({ nativeThreadId, providerThread: baseThread, status });
+ yield* emitProviderThreadRoster({
+ nativeThreadId,
+ providerThread: baseThread,
+ status,
+ });
});
const applyBackgroundTaskRosterMessage = Effect.fnUntraced(function* (input: {
@@ -10130,13 +10568,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
subagent !== undefined &&
findToolCall(context, toolResult.tool_use_id) === undefined
) {
- // Background Agent launches ACK immediately; only task_notification settles them.
- if (
- !isClaudeToolResultError(toolResult) &&
- (runHandles !== undefined || isClaudeSubagentAsyncLaunchAck(output))
- ) {
- continue;
- }
+ if (!claudeToolResultSettlesSubagent(toolResult, output)) continue;
const result = claudeSubagentResultText(output);
yield* updateClaudeSubagentNode({
context,
@@ -11598,7 +12030,24 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
});
return updated;
});
- yield* rememberProviderThread(turnInput.providerThread);
+ // A queued turn's snapshot can predate another task's exit.
+ const owedWakeTasks = yield* owedWakeTasksForNativeThread(nativeThreadId);
+ yield* rememberProviderThread(
+ owedWakeTasks.length === 0
+ ? turnInput.providerThread
+ : {
+ ...turnInput.providerThread,
+ pendingBackgroundTasks: [
+ ...(turnInput.providerThread.pendingBackgroundTasks ?? []),
+ ...owedWakeTasks.filter(
+ (task) =>
+ !(turnInput.providerThread.pendingBackgroundTasks ?? []).some(
+ (current) => current.taskId === task.taskId,
+ ),
+ ),
+ ],
+ },
+ );
if (!goalsByNativeThread.has(nativeThreadId)) {
goalsByNativeThread.set(nativeThreadId, turnInput.providerThread.goal ?? null);
}
@@ -11788,7 +12237,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
yield* attachTurn;
const drained = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? [];
yield* Ref.update(requestedContinuations, (current) => {
- const updated = new Set(current);
+ const updated = new Map(current);
updated.delete(nativeThreadId);
return updated;
});
@@ -11812,15 +12261,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
.some((entry) => isClaudeTurnStartMessage(entry));
// The CLI can append empty task successes after a failure. Filter
// those for replay without changing the raw-tail successor guard.
- const isEmptyTaskNotificationSuccess = (entry: SDKMessage) =>
- isClaudeTaskNotificationOriginResult(entry) &&
- entry.subtype === "success" &&
- !entry.is_error &&
- entry.num_turns === 0 &&
- entry.result.length === 0 &&
- terminalStatusFromResult(entry) === "completed";
const replayResultIndex = drained.findLastIndex(
- (entry) => entry.type === "result" && !isEmptyTaskNotificationSuccess(entry),
+ (entry) =>
+ entry.type === "result" && !isClaudeEmptyTaskNotificationSuccess(entry),
);
const lastResult =
drained[replayResultIndex === -1 ? lastResultIndex : replayResultIndex];
@@ -11953,8 +12396,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
next.add(turnInput.providerTurnId);
return next;
});
- yield* existing.query.interrupt.pipe(Effect.timeoutOption("10 seconds"));
- yield* existing.query.close.pipe(Effect.ignore);
+ if (!(yield* Deferred.isDone(existing.closed))) {
+ yield* existing.query.interrupt.pipe(
+ Effect.timeoutOption("10 seconds"),
+ // Teardown can close the CLI between the check and the write.
+ Effect.catch((error) =>
+ Deferred.isDone(existing.closed).pipe(
+ Effect.flatMap((closed) => (closed ? Effect.void : Effect.fail(error))),
+ ),
+ ),
+ );
+ yield* existing.query.close.pipe(Effect.ignore);
+ }
const closed = yield* Deferred.await(existing.closed).pipe(
Effect.timeoutOption(CLAUDE_STOP_CONFIRM_TIMEOUT_MS),
);
@@ -12197,6 +12650,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
const closeSession = Effect.fnUntraced(function* () {
const existing = yield* Ref.get(queryContext);
if (existing !== null) {
+ // Marked first so a concurrent Stop skips or tolerates writes to the closing CLI;
+ // the scope interrupts the stream fiber, so it may never mark its query closed.
+ yield* Deferred.succeed(existing.closed, undefined);
yield* existing.query.close.pipe(Effect.ignore);
}
yield* Effect.yieldNow;
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
index fd72aceaa5905..4716ec06175a6 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
@@ -254,6 +254,7 @@ it.effect("reopens a stalled MCP registration before delivering the resumed prom
if (typeof prompt === "string") throw new Error("Expected streaming input");
prompts.push(prompt);
return {
+ initializationResult: async () => ({}),
setMcpServers: prompts.length === 1 ? firstRegistration : secondRegistration,
close: prompts.length === 1 ? firstClose : secondClose,
[Symbol.asyncDispose]: async () => {
@@ -360,6 +361,7 @@ it.effect.each([true, false])("only retries after confirmed process exit: %s", (
cleanupProgress.resolve("retry");
}
return {
+ initializationResult: async () => ({}),
setMcpServers: () => {
registrationStarted.resolve();
return first
@@ -410,6 +412,7 @@ it.effect("stops retrying MCP registration after two timeouts and reports the ca
const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => {
const started = querySpy.mock.calls.length === 1 ? firstRegistration : secondRegistration;
return {
+ initializationResult: async () => ({}),
setMcpServers: () => {
started.resolve();
return new Promise(() => {});
@@ -450,6 +453,7 @@ it.effect("cancels a stalled registration without retrying or retaining its prom
const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
() =>
({
+ initializationResult: async () => ({}),
setMcpServers: () => {
registrationStarted.resolve();
return new Promise(() => {});
@@ -480,6 +484,7 @@ it.effect("does not reuse a fresh session ID after MCP registration times out",
const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
() =>
({
+ initializationResult: async () => ({}),
setMcpServers: () => {
registrationStarted.resolve();
return new Promise(() => {});
@@ -507,6 +512,55 @@ it.effect("does not reuse a fresh session ID after MCP registration times out",
),
);
+it.effect.each([
+ ["opens after a slow CLI boot", "120 seconds", true],
+ ["times out a CLI that never boots", "5 minutes", false],
+] as const)("%s", ([, bootWait, boots]) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const waiting = Promise.withResolvers();
+ const booted = Promise.withResolvers();
+ const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
+ () =>
+ ({
+ initializationResult: () => {
+ waiting.resolve();
+ return booted.promise;
+ },
+ // The CLI answers control requests only after it has booted.
+ setMcpServers: async () => {
+ waiting.resolve();
+ await booted.promise;
+ return { added: ["t3-code"], removed: [], errors: {} };
+ },
+ close: vi.fn(),
+ [Symbol.asyncDispose]: async () => {},
+ }) as unknown as ClaudeSdk.Query,
+ );
+ yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
+ const runner = yield* ClaudeAgentSdkQueryRunner;
+ const { resume, ...options } = resumedMcpQueryInput.options;
+ const opening = yield* runner
+ .open({ ...resumedMcpQueryInput, options: { ...options, sessionId: resume } })
+ .pipe(Effect.result, Effect.forkChild);
+ yield* Effect.promise(() => waiting.promise);
+ yield* TestClock.adjust(bootWait);
+ if (boots) booted.resolve();
+ const result = yield* Fiber.join(opening);
+
+ assert.equal(result._tag, boots ? "Success" : "Failure");
+ if (result._tag === "Success") yield* result.success.close;
+ else
+ assert.equal(
+ makeProviderFailure({
+ cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure },
+ }).message,
+ "Claude timed out while starting up. Retry the turn; if it keeps failing, check Claude and the server logs.",
+ );
+ }).pipe(Effect.provide(realQueryRunner)),
+ ),
+);
+
function fakeClaudeCli(script: string): string {
const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-claude-cli-"));
const cli = NodePath.join(dir, "claude");
@@ -579,6 +633,69 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro
}),
);
+ // The default AgentScope is what macOS gets: no systemd scope to catch a job outside the CLI's group.
+ it.effect("stops a job the CLI started in its own process group when the session closes", () =>
+ Effect.gen(function* () {
+ const cli = fakeClaudeCli(
+ [
+ 'dir=$(dirname "$0")',
+ `perl -e 'setpgrp(0, 0); exec @ARGV' sleep 600 > "$dir/alive" &`,
+ 'echo $! > "$dir/leftover.pid"',
+ "cat > /dev/null",
+ ].join("\n"),
+ );
+ const dir = NodePath.dirname(cli);
+ NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]);
+ yield* Effect.addFinalizer(() =>
+ Effect.sync(() => {
+ try {
+ process.kill(Number(NodeFS.readFileSync(NodePath.join(dir, "leftover.pid"), "utf8")));
+ } catch {}
+ NodeFS.rmSync(dir, { recursive: true, force: true });
+ }),
+ );
+ const alive = NodeFS.createReadStream(NodePath.join(dir, "alive"));
+ const leftoverStarted = new Promise((resolve) => alive.once("open", () => resolve()));
+ const leftoverStopped = new Promise((resolve) => alive.once("close", () => resolve()));
+ alive.resume();
+
+ const session = yield* openFakeCli(cli).pipe(Effect.provide(realQueryRunner));
+ yield* Effect.promise(() => leftoverStarted);
+ yield* session.close;
+ yield* Effect.promise(() => leftoverStopped);
+ }),
+ );
+
+ // Live clock: the job is found by polling while the CLI runs, and the CLI exits on its own.
+ it.live("stops a job the CLI started in its own process group when the CLI exits", () =>
+ Effect.gen(function* () {
+ const cli = fakeClaudeCli(
+ [
+ 'dir=$(dirname "$0")',
+ `perl -e 'setpgrp(0, 0); exec @ARGV' sleep 600 > "$dir/alive" &`,
+ 'echo $! > "$dir/leftover.pid"',
+ "sleep 3",
+ ].join("\n"),
+ );
+ const dir = NodePath.dirname(cli);
+ NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]);
+ yield* Effect.addFinalizer(() =>
+ Effect.sync(() => {
+ try {
+ process.kill(Number(NodeFS.readFileSync(NodePath.join(dir, "leftover.pid"), "utf8")));
+ } catch {}
+ NodeFS.rmSync(dir, { recursive: true, force: true });
+ }),
+ );
+ const alive = NodeFS.createReadStream(NodePath.join(dir, "alive"));
+ const leftoverStopped = new Promise((resolve) => alive.once("close", () => resolve()));
+ alive.resume();
+
+ yield* openFakeCli(cli).pipe(Effect.provide(realQueryRunner));
+ yield* Effect.promise(() => leftoverStopped);
+ }),
+ );
+
const rootRefusal =
"--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
index f48b2b9d5e445..17e10e9c1d695 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
@@ -2266,6 +2266,74 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
+ it.effect("records the model Codex reports on the root provider turn", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const nativeThreadId = "reported-model-thread";
+ const nativeTurnId = "reported-model-turn";
+ const transcript = makeCodexReplayTranscript({
+ scenario: "codex-reported-model",
+ entries: [
+ ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "say hi" }),
+ {
+ type: "emit_inbound",
+ label: "rerouted",
+ frame: {
+ method: "model/rerouted",
+ params: {
+ threadId: nativeThreadId,
+ turnId: nativeTurnId,
+ fromModel: "gpt-6-astra",
+ toModel: "gpt-5.6-sol",
+ reason: "highRiskCyberActivity",
+ },
+ },
+ },
+ {
+ type: "emit_inbound",
+ label: "complete",
+ frame: {
+ method: "turn/completed",
+ params: {
+ threadId: nativeThreadId,
+ turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
+ },
+ },
+ },
+ ],
+ });
+ const harness = yield* makeCodexReplayHarness(transcript);
+ yield* harness.runtime.startTurn(
+ makeCodexTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make("reported-model-attempt"),
+ text: "say hi",
+ }),
+ );
+ yield* harness.firstTerminal;
+ const completed = harness.events.find(
+ (event) =>
+ event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
+ );
+ assert.equal(completed?.type, "provider_turn.updated");
+ if (completed?.type !== "provider_turn.updated") return;
+ assert.deepEqual(completed.providerTurn.turnTokenUsage?.models, ["gpt-5.6-sol"]);
+ assert.equal(completed.providerTurn.model, "gpt-5.6-sol");
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ ),
+ );
+
it.effect("stops asking for commands the user allowed for the session", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -3197,6 +3265,109 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
+ // regression: #33747 Codex refuses thread/resume until an unsubscribed thread finishes closing
+ it.effect.each([
+ { name: "waits for thread/closed after a closing error", closedFirst: false },
+ { name: "retries at once when the thread already closed", closedFirst: true },
+ ])("$name", ({ name, closedFirst }) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const nativeThreadId = "closing-thread";
+ const params = {
+ threadId: nativeThreadId,
+ excludeTurns: true,
+ cwd: CODEX_TEST_RUNTIME_POLICY.cwd,
+ model: CODEX_TEST_MODEL_SELECTION.model,
+ config: CodexAdapterV2.CODEX_THREAD_CONFIG,
+ };
+ const closed: CodexReplay.CodexAppServerReplayEntry = {
+ type: "emit_inbound",
+ label: "thread closed",
+ frame: { method: "thread/closed", params: { threadId: nativeThreadId } },
+ };
+ const closingError: CodexReplay.CodexAppServerReplayEntry = {
+ type: "emit_inbound",
+ label: "resume closing error",
+ frame: {
+ id: 4,
+ error: {
+ code: -32600,
+ message: `thread ${nativeThreadId} is closing; retry thread/resume after the thread is closed`,
+ },
+ },
+ };
+ const harness = yield* makeCodexReplayHarness(
+ makeCodexReplayTranscript({
+ scenario: name,
+ entries: [
+ ...codexReplayPreamble({
+ nativeThreadId,
+ nativeTurnId: "unused-turn",
+ prompt: "unused-prompt",
+ }).slice(0, 5),
+ {
+ type: "expect_outbound",
+ label: "unsubscribe",
+ frame: {
+ id: 3,
+ method: "thread/unsubscribe",
+ params: { threadId: nativeThreadId },
+ },
+ },
+ {
+ type: "emit_inbound",
+ label: "unsubscribe result",
+ frame: { id: 3, result: { status: "unsubscribed" } },
+ },
+ {
+ type: "expect_outbound",
+ label: "resume closing thread",
+ frame: { id: 4, method: "thread/resume", params },
+ },
+ ...(closedFirst ? [closed, closingError] : [closingError, closed]),
+ {
+ type: "expect_outbound",
+ label: "retry identical resume",
+ frame: { id: 5, method: "thread/resume", params },
+ },
+ {
+ type: "emit_inbound",
+ label: "retry result",
+ frame: {
+ id: 5,
+ result: {
+ thread: {
+ id: nativeThreadId,
+ updatedAt: 1782622450,
+ turns: [{ type: "unknown-history-item" }],
+ },
+ },
+ },
+ },
+ ],
+ }),
+ );
+ yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread });
+ const resumed = yield* harness.runtime.resumeThread({
+ providerThread: harness.providerThread,
+ modelSelection: CODEX_TEST_MODEL_SELECTION,
+ runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
+ });
+ assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId);
+ assert.equal(resumed.status, "idle");
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ ),
+ );
+
it.effect.each([
"recover",
"completion-only",
@@ -4772,6 +4943,52 @@ describe("CodexAdapterV2 post-settle continuation", () => {
],
});
+ it.effect("marks a root command it wakes the agent for once the command finishes", () =>
+ Effect.gen(function* () {
+ const harness = yield* makeCodexReplayHarness({
+ ...backgroundExecTranscript,
+ entries: backgroundExecTranscript.entries.map((entry) =>
+ entry.type === "emit_inbound" && entry.label === "item/completed/command-late"
+ ? { ...entry, afterMs: 0 }
+ : entry,
+ ),
+ });
+ yield* harness.runtime.startTurn(
+ makeCodexTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make("attempt-command-completion-wake"),
+ text: BG_PROMPT,
+ }),
+ );
+ const commands = () =>
+ harness.events.flatMap((event) =>
+ event.type === "turn_item.updated" && event.turnItem.type === "command_execution"
+ ? [[event.turnItem.status, event.turnItem.completionWake]]
+ : [],
+ );
+ yield* harness.until(
+ () => harness.continuationRequests.length === 1 && commands().length === 2,
+ );
+ // Restart recovery reads this to keep the wake the restart cut.
+ assert.deepEqual(commands(), [
+ ["running", "always"],
+ ["completed", "always"],
+ ]);
+ }).pipe(
+ Effect.scoped,
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ );
+
it.effect("wakes with well-formed text when the cuts split an emoji", () =>
Effect.scoped(
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
index da632592e8424..60d1449656a40 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
@@ -1962,6 +1962,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
const pendingRuntimeRequests = yield* Ref.make(
new Map(),
);
+ /** Completed by thread/closed after this connection unsubscribes from the native thread. */
+ const threadClosings = new Map>();
/** Codex acceptForSession covers only the exact command or patch, not future commands. */
const sessionApprovals = new Map<
string,
@@ -3789,6 +3791,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
...(item.exitCode === null || item.exitCode === undefined
? {}
: { exitCode: item.exitCode }),
+ // Matches the continuation offered when it completes after the turn.
+ ...(context.subagent === null && continuationRequests !== undefined
+ ? { completionWake: "always" as const }
+ : {}),
};
return { node, turnItem };
});
@@ -4994,6 +5000,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
// their command items, while the shared provider session stays alive.
yield* client.handleServerNotification("thread/closed", (payload) =>
Effect.gen(function* () {
+ const closing = threadClosings.get(payload.threadId);
+ threadClosings.delete(payload.threadId);
+ if (closing !== undefined) yield* Deferred.succeed(closing, undefined);
const completedAt = yield* DateTime.now;
for (const context of (yield* Ref.get(settledTurns)).values()) {
if (context.providerThread.nativeThreadRef?.nativeId !== payload.threadId) continue;
@@ -6447,6 +6456,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
nativeThreadId != null &&
(goalsByNativeThread.get(nativeThreadId)?.status === "active" ||
(activation !== undefined && !activation.stopped));
+ const executedModel = reportedTurnModel(nativeThreadId ?? "", input.nativeTurnId);
const completedTurn: OrchestrationV2ProviderTurn = {
id: input.context.providerTurnId,
providerThreadId: input.context.providerThread.id,
@@ -6469,11 +6479,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
),
input.nativeTurnId,
input.status === "completed",
- reportedTurnModel(
- input.context.providerThread.nativeThreadRef?.nativeId ?? "",
- input.nativeTurnId,
- ),
+ executedModel,
),
+ ...(executedModel === undefined ? {} : { model: executedModel }),
};
if (!holdsForGoal) {
yield* emitProviderEvent({
@@ -7075,7 +7083,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
);
});
- // Codex refuses to resume a session archived elsewhere until it is unarchived.
+ // Codex refuses to resume a session archived elsewhere until it is unarchived, and
+ // one it is still unloading after thread/unsubscribe until it emits thread/closed.
const resumeNativeThread = Effect.fn("CodexAdapterV2.resumeNativeThread")(function* (
threadId: string,
params: Record,
@@ -7083,12 +7092,22 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
const resume = client.raw.request("thread/resume", { threadId, ...params });
return yield* resume.pipe(
Effect.catchTags({
- CodexAppServerRequestError: (cause) =>
- /\bsession \S+ is archived\b|\bcodex unarchive\b/i.test(cause.errorMessage)
- ? client.raw
- .request("thread/unarchive", { threadId })
- .pipe(Effect.andThen(resume))
- : Effect.fail(cause),
+ CodexAppServerRequestError: (cause) => {
+ if (/\bsession \S+ is archived\b|\bcodex unarchive\b/i.test(cause.errorMessage)) {
+ return client.raw
+ .request("thread/unarchive", { threadId })
+ .pipe(Effect.andThen(resume));
+ }
+ if (/\bthread \S+ is closing\b/i.test(cause.errorMessage)) {
+ const closing = threadClosings.get(threadId);
+ return (
+ closing === undefined
+ ? Effect.void
+ : Deferred.await(closing).pipe(Effect.timeoutOption("10 seconds"))
+ ).pipe(Effect.andThen(resume));
+ }
+ return Effect.fail(cause);
+ },
}),
);
});
@@ -7631,6 +7650,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
function* (unloadInput) {
const nativeThreadId = yield* getNativeThreadId(unloadInput.providerThread);
sessionApprovals.delete(nativeThreadId);
+ // A resume may already wait on the pending entry; replacing it would strand that wait.
+ if (!threadClosings.has(nativeThreadId)) {
+ threadClosings.set(nativeThreadId, yield* Deferred.make());
+ }
yield* client.request("thread/unsubscribe", { threadId: nativeThreadId });
},
(effect, unloadInput) =>
diff --git a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts
index 7310cc7c81ea0..183e2fab66922 100644
--- a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts
@@ -1,5 +1,5 @@
import * as HostProcess from "@t3tools/shared/HostProcess";
-import type { InteractionUpdate, RunResult } from "@cursor/sdk";
+import type { InteractionUpdate, RunResult, SteerAckOutcome } from "@cursor/sdk";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
ProviderReplayEntry,
@@ -213,6 +213,7 @@ function replayRunnerError(
export function makeCursorAgentSdkReplayRunner(
transcript: CursorAgentSdkReplayTranscript,
): CursorAgentSdk.CursorAgentSdkRunner["Service"] {
+ const steerAcks = new Map>();
let cursor = 0;
let failure: CursorAgentSdkReplayError | null = null;
let cursorAdvanced = makeSignal();
@@ -306,16 +307,19 @@ export function makeCursorAgentSdkReplayRunner(
);
}
if (entry.type === "expect_outbound") {
- const expectedCancel = {
- type: "run.cancel",
- runId,
- };
- if (!sameFrame(entry.frame, expectedCancel)) {
+ const type =
+ typeof entry.frame === "object" && entry.frame !== null
+ ? Reflect.get(entry.frame, "type")
+ : undefined;
+ if (
+ (type !== "run.cancel" && type !== "run.steer") ||
+ Reflect.get(entry.frame as object, "runId") !== runId
+ ) {
return yield* recordFailure(
new CursorReplayFrameMismatchError({
scenario: transcript.scenario,
cursor,
- expected: expectedCancel,
+ expected: { type: "run.cancel | run.steer", runId },
actual: entry.frame,
}),
);
@@ -378,6 +382,23 @@ export function makeCursorAgentSdkReplayRunner(
yield* Effect.yieldNow;
continue;
}
+ if (frame.type === "run.steered") {
+ const ack = steerAcks.get(frame.runId);
+ if (ack === undefined || frame.runId !== runId) {
+ return yield* recordFailure(
+ new CursorReplayFrameMismatchError({
+ scenario: transcript.scenario,
+ cursor,
+ expected: { runId },
+ actual: frame,
+ }),
+ );
+ }
+ advance();
+ steerAcks.delete(runId);
+ yield* Deferred.succeed(ack, frame.outcome);
+ continue;
+ }
if (frame.type === "run.completed") {
if (frame.result.id !== runId) {
return yield* recordFailure(
@@ -433,6 +454,16 @@ export function makeCursorAgentSdkReplayRunner(
replayRunnerError(transcript, cause, "replay.run.wait"),
),
),
+ steer: Effect.fn("CursorReplay.steer")(function* (text) {
+ const ack = yield* Deferred.make();
+ steerAcks.set(started.runId, ack);
+ yield* Effect.try({
+ try: () =>
+ assertOutbound({ type: "run.steer", runId: started.runId, text }),
+ catch: (cause) => replayRunnerError(transcript, cause, "replay.run.steer"),
+ });
+ return yield* Deferred.await(ack);
+ }),
cancel: Effect.try({
try: () =>
assertOutbound({
@@ -663,6 +694,7 @@ interface CursorReplayRecordingInput {
readonly apiKey?: string;
readonly interruptAfterToolStart?: boolean;
readonly interruptAfterRunStartPromptIndex?: number;
+ readonly steerAfterRunStartPromptIndex?: number;
readonly restartBeforePromptIndex?: number;
}
@@ -809,6 +841,11 @@ export const recordCursorAgentSdkReplayTranscript = Effect.fn(
prompt: string,
index: number,
) {
+ if (
+ input.steerAfterRunStartPromptIndex !== undefined &&
+ index === input.steerAfterRunStartPromptIndex + 1
+ )
+ return;
const interruptAfterRunStart = input.interruptAfterRunStartPromptIndex === index;
const firstUpdate = yield* Deferred.make();
const toolStarted = yield* Deferred.make();
@@ -831,6 +868,15 @@ export const recordCursorAgentSdkReplayTranscript = Effect.fn(
});
sent = true;
const waiting = yield* run.wait.pipe(Effect.forkChild({ startImmediately: true }));
+ if (input.steerAfterRunStartPromptIndex === index) {
+ yield* awaitSignal(firstUpdate, "Cursor SDK activity before steering");
+ const steerText = input.prompts[index + 1];
+ if (run.steer === undefined || steerText === undefined)
+ return yield* invalid("Steering requires a following prompt and Run.steer.");
+ const outcome = yield* run.steer(steerText);
+ if (outcome !== "complete_delivered")
+ return yield* invalid("The running turn did not accept the steer.");
+ }
if (interruptAfterRunStart) {
yield* awaitSignal(firstUpdate, "Cursor SDK run activity before interrupt");
yield* run.cancel;
diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
index 160bcc6f32699..6767a6a9ad315 100644
--- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
@@ -5672,6 +5672,78 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
+ // regression: #24549 a Stop whose interrupted event never arrives blocked the next fork
+ it.effect("forks a stopped session whose interrupted event never arrived", () =>
+ Effect.gen(function* () {
+ const FORK = "ses_f1484db83ffeLGtrRCFimo1H0e";
+ const { runtime, thread } = yield* resumed([
+ out("session.prompt", { sessionID: SESSION, text: "" }),
+ promptAccepted,
+ event("session.execution.started", { sessionID: SESSION }),
+ out("session.interrupt", { sessionID: SESSION }),
+ reply("session.interrupt", { interrupted: true }),
+ out("session.active"),
+ reply("session.active", { data: {} }),
+ out("session.fork", { sessionID: SESSION }),
+ replyData("session.fork", sessionInfo({ id: FORK })),
+ out("session.update", { sessionID: FORK, permissions: "" }),
+ reply("session.update", null),
+ out("session.active"),
+ reply("session.active", { data: {} }),
+ out("session.prompt", { sessionID: SESSION, text: "" }),
+ promptAccepted,
+ event("session.execution.interrupted", { sessionID: SESSION }),
+ event("session.execution.started", { sessionID: SESSION }),
+ event("session.execution.failed", {
+ sessionID: SESSION,
+ error: { type: "provider", message: "second turn failed" },
+ }),
+ ]);
+ const ended = yield* terminals(runtime, 2);
+ yield* runtime.startTurn(turnInput(thread));
+ yield* runtime.interruptTurn({
+ providerThread: thread,
+ providerTurnId: yield* providerTurnId,
+ });
+ const forked = yield* runtime.forkThread({
+ sourceProviderThread: thread,
+ targetThreadId: ThreadId.make("thread:opencode2-adapter:fork"),
+ });
+ assert.equal(forked.nativeThreadRef?.nativeId, FORK);
+ // The lost end arriving late must not finish the source's next turn.
+ yield* runtime.startTurn(secondTurn(thread));
+ const [first, second] = yield* Fiber.join(ended);
+ assert.equal(first?.status, "interrupted");
+ assert.equal(second?.failure?.message, "second turn failed");
+ }).pipe(Effect.scoped),
+ );
+
+ it.effect("refuses to fork a stopped session OpenCode still runs", () =>
+ Effect.gen(function* () {
+ const { runtime, thread } = yield* resumed([
+ out("session.prompt", { sessionID: SESSION, text: "" }),
+ promptAccepted,
+ event("session.execution.started", { sessionID: SESSION }),
+ out("session.interrupt", { sessionID: SESSION }),
+ reply("session.interrupt", { interrupted: true }),
+ out("session.active"),
+ reply("session.active", { data: { [SESSION]: { type: "running" } } }),
+ ]);
+ yield* runtime.startTurn(turnInput(thread));
+ yield* runtime.interruptTurn({
+ providerThread: thread,
+ providerTurnId: yield* providerTurnId,
+ });
+ const refused = yield* runtime
+ .forkThread({
+ sourceProviderThread: thread,
+ targetThreadId: ThreadId.make("thread:opencode2-adapter:fork"),
+ })
+ .pipe(Effect.flip);
+ assert.equal(refused._tag, "ProviderAdapterProtocolError");
+ }).pipe(Effect.scoped),
+ );
+
it.effect("moves a fork into its target thread's worktree before the first prompt", () =>
Effect.gen(function* () {
const FORK = "ses_f1484db83ffeLGtrRCFimo1H0e";
@@ -5701,7 +5773,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
- const continued = (after: ReadonlyArray) =>
+ const continued = (after: ReadonlyArray, external?: string) =>
Effect.gen(function* () {
const offers: Array = [];
const offered = yield* Deferred.make();
@@ -5709,6 +5781,15 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
...backgroundLaunch(CHILD),
event("session.execution.succeeded", { sessionID: SESSION }),
event("session.execution.succeeded", { sessionID: CHILD }),
+ ...(external === undefined
+ ? []
+ : [
+ event("session.inbox.enqueued", {
+ inboxID: external,
+ sessionID: SESSION,
+ item: { type: "user", payload: { text: "qwe!", files: [] }, delivery: "steer" },
+ }),
+ ]),
event("session.inbox.enqueued", {
inboxID: "msg_report",
sessionID: SESSION,
@@ -5728,6 +5809,9 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
},
}),
event("session.execution.started", { sessionID: SESSION }),
+ ...(external === undefined
+ ? []
+ : [event("session.inbox.delivered", { sessionID: SESSION, inboxID: external })]),
event("session.inbox.delivered", { sessionID: SESSION, inboxID: "msg_report" }),
event("session.text.ended", {
sessionID: SESSION,
@@ -5813,6 +5897,59 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
+ it.effect(
+ "reverts OpenCode at another client's prompt queued before a continuation's report",
+ () =>
+ Effect.gen(function* () {
+ const { runtime, thread, first, second } = yield* continued(
+ [
+ out("message.list", ""),
+ reply("message.list", {
+ data: [
+ {
+ id: "msg_report",
+ time: { created: 3 },
+ text: CONTINUED_REPORT,
+ type: "synthetic",
+ },
+ { id: "msg_external", time: { created: 2 }, text: "qwe!", type: "user" },
+ { id: CONTINUED_PROMPT, time: { created: 1 }, text: "hi", type: "user" },
+ ],
+ cursor: {},
+ }),
+ out("session.revert.stage", {
+ sessionID: SESSION,
+ messageID: "msg_external",
+ files: false,
+ }),
+ replyData("session.revert.stage", { messageID: "msg_external", files: [] }),
+ out("session.revert.commit", { sessionID: SESSION }),
+ reply("session.revert.commit", null),
+ out("message.list", ""),
+ reply("message.list", {
+ data: [{ id: CONTINUED_PROMPT, time: { created: 1 }, text: "hi", type: "user" }],
+ cursor: {},
+ }),
+ ],
+ "msg_external",
+ );
+ const snapshot = yield* runtime.rollbackThread({
+ providerThread: thread,
+ target: {
+ type: "provider_turn",
+ checkpointId: CheckpointId.make("checkpoint:first"),
+ appRunOrdinal: 1,
+ providerTurn: first,
+ },
+ providerThreadTurns: [first, second],
+ });
+ assert.deepEqual(
+ snapshot.providerTurns.map((turn) => turn.id),
+ [first.id],
+ );
+ }).pipe(Effect.scoped),
+ );
+
it.effect("keeps a subagent a stopped background reply started off the next turn", () =>
Effect.gen(function* () {
const CHILD_B = "ses_f1485c529ffeBBBBBBBBBBBBBB";
@@ -6190,6 +6327,346 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped, Effect.provide(IdAllocator.layer)),
);
+ it.effect(
+ "reverts a report's continuation at its report after a Stop dropped another client's prompt",
+ () =>
+ Effect.gen(function* () {
+ const kept = `msg_t3_turn_${SESSION}:attempt:opencode2-adapter`;
+ const offers: Array = [];
+ const reportOffered = yield* Deferred.make();
+ const { runtime, thread } = yield* resumed([
+ event("session.inbox.enqueued", {
+ inboxID: "msg_stale",
+ sessionID: SESSION,
+ item: { type: "user", payload: { text: "qwe!", files: [] }, delivery: "steer" },
+ }),
+ event("session.execution.started", { sessionID: SESSION }),
+ event("session.inbox.delivered", { sessionID: SESSION, inboxID: "msg_stale" }),
+ event("session.execution.succeeded", { sessionID: SESSION }),
+ event("session.model.selected", {
+ sessionID: SESSION,
+ model: { id: "buffered", providerID: "opencode" },
+ }),
+ out("session.switchModel", { sessionID: SESSION, model: "" }),
+ reply("session.switchModel", null),
+ ...backgroundLaunch(CHILD),
+ event("session.execution.succeeded", { sessionID: SESSION }),
+ event("session.execution.succeeded", { sessionID: CHILD }),
+ event("session.inbox.enqueued", {
+ inboxID: "msg_report",
+ sessionID: SESSION,
+ item: {
+ type: "synthetic",
+ payload: {
+ text: CONTINUED_REPORT,
+ description: "Sleep",
+ metadata: {
+ source: "subagent",
+ childID: CHILD,
+ agent: "General",
+ state: "completed",
+ },
+ },
+ delivery: "steer",
+ },
+ }),
+ event("session.execution.started", { sessionID: SESSION }),
+ event("session.inbox.delivered", { sessionID: SESSION, inboxID: "msg_report" }),
+ event("session.execution.succeeded", { sessionID: SESSION }),
+ out("message.list", ""),
+ reply("message.list", {
+ data: [
+ { id: "msg_report", time: { created: 3 }, text: CONTINUED_REPORT, type: "synthetic" },
+ { id: kept, time: { created: 2 }, text: "hi", type: "user" },
+ { id: "msg_stale", time: { created: 1 }, text: "qwe!", type: "user" },
+ ],
+ cursor: {},
+ }),
+ out("session.revert.stage", {
+ sessionID: SESSION,
+ messageID: "msg_report",
+ files: false,
+ }),
+ replyData("session.revert.stage", { messageID: "msg_report", files: [] }),
+ out("session.revert.commit", { sessionID: SESSION }),
+ reply("session.revert.commit", null),
+ out("message.list", ""),
+ reply("message.list", {
+ data: [
+ { id: kept, time: { created: 2 }, text: "hi", type: "user" },
+ { id: "msg_stale", time: { created: 1 }, text: "qwe!", type: "user" },
+ ],
+ cursor: {},
+ }),
+ ]).pipe(
+ Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
+ offer: (request) =>
+ Effect.sync(() => void offers.push(request)).pipe(
+ Effect.andThen(() =>
+ offers.length === 2 ? Deferred.succeed(reportOffered, undefined) : Effect.void,
+ ),
+ Effect.asVoid,
+ ),
+ take: Effect.never,
+ }),
+ );
+ const turns: Array = [];
+ const buffered = yield* Deferred.make();
+ const bothEnded = yield* Deferred.make();
+ yield* runtime.events.pipe(
+ Stream.tap((event) =>
+ Effect.gen(function* () {
+ if (
+ event.type === "provider_thread.updated" &&
+ event.providerThread.nativeMetadata?.modelSelection?.model === "opencode/buffered"
+ ) {
+ yield* Deferred.succeed(buffered, undefined);
+ }
+ if (
+ event.type === "provider_turn.updated" &&
+ event.providerTurn.status !== "running"
+ ) {
+ turns.push(event.providerTurn);
+ if (turns.length === 2) yield* Deferred.succeed(bothEnded, undefined);
+ }
+ }),
+ ),
+ Stream.runDrain,
+ Effect.forkScoped,
+ );
+ yield* Deferred.await(buffered);
+ yield* runtime.interruptTurn({
+ providerThread: thread,
+ providerTurnId: yield* providerTurnId,
+ requestRuntimeRestart: true,
+ });
+ yield* runtime.startTurn(withLineage(thread));
+ yield* Deferred.await(reportOffered);
+ yield* runtime.startTurn(continuationTurn(thread, offers[1]!));
+ yield* Deferred.await(bothEnded);
+ const [first, continuation] = turns;
+ const snapshot = yield* runtime.rollbackThread({
+ providerThread: thread,
+ target: {
+ type: "provider_turn",
+ checkpointId: CheckpointId.make("checkpoint:first"),
+ appRunOrdinal: 1,
+ providerTurn: first!,
+ },
+ providerThreadTurns: [first!, continuation!],
+ });
+ assert.deepEqual(
+ snapshot.providerTurns.map((turn) => turn.id),
+ [first!.id],
+ );
+ }).pipe(Effect.scoped),
+ );
+
+ it.effect(
+ "reverts a report's continuation at its report after a reconnect lost another client's prompt start",
+ () =>
+ Effect.gen(function* () {
+ const kept = `msg_t3_turn_${SESSION}:attempt:opencode2-adapter`;
+ const offered =
+ yield* Deferred.make();
+ const { runtime, thread } = yield* resumed([
+ event("session.inbox.enqueued", {
+ inboxID: "msg_stale",
+ sessionID: SESSION,
+ item: { type: "user", payload: { text: "qwe!", files: [] }, delivery: "steer" },
+ }),
+ { type: "runtime_exit", status: "success" } as const,
+ out("event.subscribe"),
+ event("session.model.selected", {
+ sessionID: SESSION,
+ model: { id: "buffered", providerID: "opencode" },
+ }),
+ out("session.switchModel", { sessionID: SESSION, model: "" }),
+ reply("session.switchModel", null),
+ ...backgroundLaunch(CHILD),
+ event("session.execution.succeeded", { sessionID: SESSION }),
+ event("session.execution.succeeded", { sessionID: CHILD }),
+ event("session.inbox.enqueued", {
+ inboxID: "msg_report",
+ sessionID: SESSION,
+ item: {
+ type: "synthetic",
+ payload: {
+ text: CONTINUED_REPORT,
+ description: "Sleep",
+ metadata: {
+ source: "subagent",
+ childID: CHILD,
+ agent: "General",
+ state: "completed",
+ },
+ },
+ delivery: "steer",
+ },
+ }),
+ event("session.execution.started", { sessionID: SESSION }),
+ event("session.inbox.delivered", { sessionID: SESSION, inboxID: "msg_report" }),
+ event("session.execution.succeeded", { sessionID: SESSION }),
+ out("message.list", ""),
+ reply("message.list", {
+ data: [
+ { id: "msg_report", time: { created: 3 }, text: CONTINUED_REPORT, type: "synthetic" },
+ { id: kept, time: { created: 2 }, text: "hi", type: "user" },
+ { id: "msg_stale", time: { created: 1 }, text: "qwe!", type: "user" },
+ ],
+ cursor: {},
+ }),
+ out("session.revert.stage", {
+ sessionID: SESSION,
+ messageID: "msg_report",
+ files: false,
+ }),
+ replyData("session.revert.stage", { messageID: "msg_report", files: [] }),
+ out("session.revert.commit", { sessionID: SESSION }),
+ reply("session.revert.commit", null),
+ out("message.list", ""),
+ reply("message.list", {
+ data: [
+ { id: kept, time: { created: 2 }, text: "hi", type: "user" },
+ { id: "msg_stale", time: { created: 1 }, text: "qwe!", type: "user" },
+ ],
+ cursor: {},
+ }),
+ ]).pipe(
+ Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
+ offer: (request) => Deferred.succeed(offered, request).pipe(Effect.asVoid),
+ take: Effect.never,
+ }),
+ );
+ const turns: Array = [];
+ const reconnected = yield* Deferred.make();
+ const bothEnded = yield* Deferred.make();
+ yield* runtime.events.pipe(
+ Stream.tap((event) =>
+ Effect.gen(function* () {
+ if (
+ event.type === "provider_thread.updated" &&
+ event.providerThread.nativeMetadata?.modelSelection?.model === "opencode/buffered"
+ ) {
+ yield* Deferred.succeed(reconnected, undefined);
+ }
+ if (
+ event.type === "provider_turn.updated" &&
+ event.providerTurn.status !== "running"
+ ) {
+ turns.push(event.providerTurn);
+ if (turns.length === 2) yield* Deferred.succeed(bothEnded, undefined);
+ }
+ }),
+ ),
+ Stream.runDrain,
+ Effect.forkScoped,
+ );
+ yield* Deferred.await(reconnected);
+ yield* runtime.startTurn(withLineage(thread));
+ yield* runtime.startTurn(continuationTurn(thread, yield* Deferred.await(offered)));
+ yield* Deferred.await(bothEnded);
+ const [first, continuation] = turns;
+ const snapshot = yield* runtime.rollbackThread({
+ providerThread: thread,
+ target: {
+ type: "provider_turn",
+ checkpointId: CheckpointId.make("checkpoint:first"),
+ appRunOrdinal: 1,
+ providerTurn: first!,
+ },
+ providerThreadTurns: [first!, continuation!],
+ });
+ assert.deepEqual(
+ snapshot.providerTurns.map((turn) => turn.id),
+ [first!.id],
+ );
+ }).pipe(Effect.scoped),
+ );
+
+ it.effect("shows a second prompt another client sent while its continuation was pending", () =>
+ Effect.gen(function* () {
+ const offers: Array = [];
+ const prompt = (inboxID: string, text: string) =>
+ event("session.inbox.enqueued", {
+ inboxID,
+ sessionID: SESSION,
+ item: { type: "user", payload: { text, files: [] }, delivery: "steer" },
+ });
+ // T3's own prompt can be admitted after a failed submit ended its turn.
+ const late = `msg_t3_turn_${SESSION}:attempt:late`;
+ const { runtime, thread } = yield* resumed([
+ prompt(late, "mine"),
+ prompt("msg_external_a", "first?"),
+ event("session.execution.started", { sessionID: SESSION }),
+ event("session.inbox.delivered", { sessionID: SESSION, inboxID: late }),
+ event("session.inbox.delivered", { sessionID: SESSION, inboxID: "msg_external_a" }),
+ prompt("msg_external_b", "second?"),
+ event("session.inbox.delivered", { sessionID: SESSION, inboxID: "msg_external_b" }),
+ event("session.text.ended", {
+ sessionID: SESSION,
+ assistantMessageID: "msg_external_reply",
+ ordinal: 0,
+ text: "Both!",
+ }),
+ event("session.execution.succeeded", { sessionID: SESSION }),
+ // Handled only after the wake above has buffered everything before it.
+ event("session.model.selected", {
+ sessionID: SESSION,
+ model: { id: "buffered", providerID: "opencode" },
+ }),
+ ]).pipe(
+ Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
+ offer: (request) => Effect.sync(() => void offers.push(request)),
+ take: Effect.never,
+ }),
+ );
+ const collected: Array = [];
+ const buffered = yield* Deferred.make();
+ const ended = yield* Deferred.make();
+ yield* runtime.events.pipe(
+ Stream.tap((event) =>
+ Effect.gen(function* () {
+ collected.push(event);
+ if (
+ event.type === "provider_thread.updated" &&
+ event.providerThread.nativeMetadata?.modelSelection?.model === "opencode/buffered"
+ ) {
+ yield* Deferred.succeed(buffered, undefined);
+ }
+ if (event.type === "turn.terminal") yield* Deferred.succeed(ended, undefined);
+ }),
+ ),
+ Stream.runDrain,
+ Effect.forkScoped,
+ );
+ yield* Deferred.await(buffered);
+ yield* runtime.startTurn(continuationTurn(thread, offers[0]!));
+ yield* Deferred.await(ended);
+ assert.deepEqual(
+ collected.flatMap((event) =>
+ event.type === "turn_item.updated" &&
+ (event.turnItem.type === "user_message" || event.turnItem.type === "assistant_message")
+ ? [`${event.turnItem.type}: ${event.turnItem.text}`]
+ : [],
+ ),
+ ["user_message: first?", "user_message: second?", "assistant_message: Both!"],
+ );
+ assert.deepEqual(
+ [
+ ...new Set(
+ collected.flatMap((event) =>
+ event.type === "message.updated"
+ ? [`${event.message.role}: ${event.message.text}`]
+ : [],
+ ),
+ ),
+ ],
+ ["user: first?", "user: second?", "assistant: Both!"],
+ );
+ }).pipe(Effect.scoped),
+ );
+
it.effect("shows a question asked while OpenCode wakes for a background reply", () =>
Effect.gen(function* () {
const OTHER = "ses_other00000000000000000000";
diff --git a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts
index 9700757eb8bbe..fc27392eda0db 100644
--- a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts
+++ b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts
@@ -15,6 +15,7 @@ import {
type OrchestrationV2DomainEvent,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
+import * as Deferred from "effect/Deferred";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -36,6 +37,7 @@ import * as EffectWorker from "./EffectWorker.ts";
import * as EventSink from "./EventSink.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
+import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
import * as Orchestrator from "./Orchestrator.ts";
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
@@ -610,3 +612,291 @@ it.effect("applies an effort change to the running Claude query without waiting
),
),
);
+
+const backgroundTaskStarted = (taskId: string) =>
+ frame({
+ type: "system",
+ subtype: "task_started",
+ task_id: taskId,
+ tool_use_id: `tool-${taskId}`,
+ description: "Background build",
+ is_backgrounded: true,
+ task_type: "local_bash",
+ uuid: `started-${taskId}`,
+ session_id: sessionId,
+ });
+
+const backgroundTaskNotification = (taskId: string) =>
+ frame({
+ type: "system",
+ subtype: "task_notification",
+ task_id: taskId,
+ tool_use_id: `tool-${taskId}`,
+ status: "completed",
+ output_file: `/tmp/claude-replay/tasks/${taskId}.output`,
+ summary: `Background build ${taskId} completed`,
+ uuid: `notification-${taskId}`,
+ session_id: sessionId,
+ });
+
+const wakeAssistant = (uuid: string) =>
+ frame({
+ type: "assistant",
+ uuid,
+ session_id: sessionId,
+ parent_tool_use_id: null,
+ message: {
+ id: `msg-${uuid}`,
+ role: "assistant",
+ type: "message",
+ model: modelSelection.model,
+ content: [{ type: "text", text: `Background build finished (${uuid}).` }],
+ stop_reason: null,
+ stop_sequence: null,
+ usage: { input_tokens: 1, output_tokens: 1 },
+ },
+ });
+
+it.effect("offers a continuation for a later wake after a queued continuation is cancelled", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const cwd = yield* checkpointWorkspace("claude-cancelled-continuation");
+ const sdkMessages = yield* Queue.unbounded();
+ const processed = new WeakMap>();
+ const offerAndWait = Effect.fnUntraced(function* (message: SDKMessage) {
+ const done = yield* Deferred.make();
+ processed.set(message, done);
+ yield* Queue.offer(sdkMessages, message);
+ yield* Deferred.await(done);
+ });
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const random = yield* SecureRandom.SecureRandom;
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
+ const continuations: ProviderContinuationRequests.ProviderContinuationRequest[] = [];
+ const services =
+ yield* Effect.context<
+ Effect.Services>
+ >();
+ const registry = ProviderAdapterRegistry.layerFromAdaptersEffect(
+ Effect.gen(function* () {
+ const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
+ const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
+ instanceId: modelSelection.instanceId,
+ settings,
+ environment: {},
+ attachmentsDir: cwd,
+ fileSystem,
+ path,
+ random,
+ idAllocator,
+ continuationRequests: {
+ offer: (request) =>
+ Effect.sync(() => continuations.push(request)).pipe(
+ Effect.andThen(requests.offer(request)),
+ ),
+ },
+ queryRunner: {
+ allocateSessionId: Effect.succeed(sessionId),
+ open: () =>
+ Effect.succeed({
+ // Resolve each frame's Deferred once the adapter pulls the next one.
+ messages: Stream.fromQueue(sdkMessages).pipe(
+ Stream.flatMap((message) =>
+ Stream.make(message).pipe(
+ Stream.concat(
+ Stream.fromEffect(
+ Effect.suspend(() => {
+ const done = processed.get(message);
+ return done === undefined
+ ? Effect.void
+ : Deferred.succeed(done, undefined);
+ }),
+ ).pipe(Stream.drain),
+ ),
+ ),
+ ),
+ ),
+ offer: () => Effect.void,
+ setModel: () => Effect.void,
+ applyFlagSettings: () => Effect.void,
+ setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
+ mcpServerStatus: Effect.succeed([]),
+ readMcpResource: () => Effect.die("unexpected MCP resource read"),
+ callMcpTool: () => Effect.die("unexpected MCP tool call"),
+ listPermissionRules: Effect.die("unexpected permission rules read"),
+ stopTask: () => Effect.void,
+ interrupt: Effect.void,
+ close: Effect.void,
+ }),
+ forkSession: () => Effect.die("unused"),
+ subagentLaunchToolUseId: () => Effect.succeed(null),
+ assertComplete: Effect.void,
+ },
+ }).pipe(Effect.provideContext(services));
+ return [adapter];
+ }),
+ );
+ yield* Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
+ const threadId = ThreadId.make("thread:cancelled-continuation");
+ const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
+ orchestrator.streamDomainEvents.pipe(
+ Stream.filter(predicate),
+ Stream.take(1),
+ Stream.runDrain,
+ Effect.forkScoped,
+ );
+ const runUpdated = (messageId: string, status: string) =>
+ watch(
+ (event) =>
+ event.type === "run.updated" &&
+ event.payload.userMessageId === messageId &&
+ event.payload.status === status,
+ );
+ // A user turn that leaves a background task running when it ends.
+ const userTurnWithBackgroundTask = Effect.fnUntraced(function* (
+ id: string,
+ taskId: string,
+ ) {
+ const running = yield* runUpdated(id, "running");
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make(id),
+ threadId,
+ messageId: MessageId.make(id),
+ text: "Run the build in the background.",
+ attachments: [],
+ dispatchMode: { type: "start_immediately" },
+ createdBy: "user",
+ creationSource: "web",
+ });
+ yield* worker.drain();
+ yield* Fiber.join(running);
+ const waiting = yield* runUpdated(id, "waiting");
+ yield* Queue.offer(sdkMessages, backgroundTaskStarted(taskId));
+ yield* Queue.offer(sdkMessages, result(`result-${id}`, false));
+ yield* Fiber.join(waiting);
+ });
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make("create"),
+ threadId,
+ projectId: ProjectId.make("project:cancelled-continuation"),
+ title: "Cancelled continuation",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: cwd,
+ createdBy: "user",
+ creationSource: "web",
+ });
+
+ // The first run is still finalizing when its background task wakes Claude.
+ yield* userTurnWithBackgroundTask("first", "build-1");
+ const queued = yield* watch(
+ (event) => event.type === "run.created" && event.payload.status === "queued",
+ );
+ yield* offerAndWait(backgroundTaskNotification("build-1"));
+ yield* offerAndWait(wakeAssistant("wake-1"));
+ yield* Fiber.join(queued);
+ assert.lengthOf(continuations, 1);
+ const continuationRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
+ (run) => run.status === "queued",
+ );
+ assert.ok(continuationRun !== undefined);
+ yield* orchestrator.dispatch({
+ type: "queued-run.cancel",
+ commandId: CommandId.make("cancel"),
+ threadId,
+ runId: continuationRun.id,
+ });
+ yield* offerAndWait(result("wake-1-result", false));
+ yield* worker.drain();
+ yield* orchestrator.resumeQueuedRuns;
+ yield* worker.drain();
+ const idle = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(idle.runs.find((run) => run.id === continuationRun.id)?.status, "cancelled");
+ assert.isFalse(idle.runs.some((run) => run.status === "queued"));
+
+ yield* userTurnWithBackgroundTask("second", "build-2");
+ yield* worker.drain();
+ // The second user run has completed, so this continuation starts without queueing.
+ const isContinuationRun = (
+ event: OrchestrationV2DomainEvent,
+ type: string,
+ status: string,
+ ) =>
+ (event.type === "run.created" || event.type === "run.updated") &&
+ event.type === type &&
+ event.payload.status === status &&
+ event.payload.userMessageId !== MessageId.make("first") &&
+ event.payload.userMessageId !== MessageId.make("second");
+ const secondCreated = yield* watch((event) =>
+ isContinuationRun(event, "run.created", "starting"),
+ );
+ const secondRunning = yield* watch((event) =>
+ isContinuationRun(event, "run.updated", "running"),
+ );
+ yield* offerAndWait(backgroundTaskNotification("build-2"));
+ yield* offerAndWait(wakeAssistant("wake-2"));
+ assert.lengthOf(
+ continuations,
+ 2,
+ "the wake after a cancelled queued continuation must offer a new continuation",
+ );
+ yield* Fiber.join(secondCreated);
+ yield* worker.drain();
+ yield* Fiber.join(secondRunning);
+ const secondContinuation = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
+ (run) => run.status === "running",
+ );
+ assert.ok(secondContinuation !== undefined);
+ const secondWaiting = yield* watch(
+ (event) =>
+ event.type === "run.updated" &&
+ event.payload.id === secondContinuation.id &&
+ event.payload.status === "waiting",
+ );
+ yield* offerAndWait(result("wake-2-result", false));
+ yield* Fiber.join(secondWaiting);
+ yield* worker.drain();
+ const settled = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(
+ settled.runs.find((run) => run.id === secondContinuation.id)?.status,
+ "completed",
+ );
+ assert.deepEqual(
+ settled.turnItems.flatMap((item) =>
+ item.runId === secondContinuation.id && item.type === "assistant_message"
+ ? [item.text]
+ : [],
+ ),
+ ["Background build finished (wake-2)."],
+ "the continuation must carry only its own wake's output",
+ );
+ assert.lengthOf(continuations, 2, "two wakes must offer exactly two continuations");
+ }).pipe(
+ Effect.provide(
+ ProviderReplayHarness.layerWithRegistry(
+ { name: "claude-cancelled-continuation" },
+ registry,
+ { runEffectWorker: false, runContinuationWorker: true },
+ ),
+ ),
+ );
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ IdAllocator.layer,
+ McpProviderSessions.layer,
+ NodeServices.layer,
+ NodeCrypto.layer,
+ ),
+ ),
+ ),
+ ),
+);
diff --git a/apps/server/src/orchestration-v2/CommandPolicy.test.ts b/apps/server/src/orchestration-v2/CommandPolicy.test.ts
index 8ed4de3e9dea0..85babb8a869bf 100644
--- a/apps/server/src/orchestration-v2/CommandPolicy.test.ts
+++ b/apps/server/src/orchestration-v2/CommandPolicy.test.ts
@@ -247,6 +247,19 @@ it.each(["/compact", " /LOGOUT "])("queues a steer sent while %s runs", (text) =
const layer = it.layer(CommandPolicy.layer);
layer("CommandPolicyV2", (it) => {
+ it.effect("steers a live Cursor turn in place", () =>
+ Effect.gen(function* () {
+ const policy = yield* CommandPolicy.CommandPolicyV2;
+ const result = yield* policy.decideSteeringExecution({
+ commandId,
+ threadId,
+ providerInstanceId: ProviderInstanceId.make("cursor"),
+ capabilities: CursorProviderCapabilitiesV2,
+ });
+ assert.equal(result, "active_steering");
+ }),
+ );
+
it.effect("falls back to portable context when Cursor cannot fork natively", () =>
Effect.gen(function* () {
const policy = yield* CommandPolicy.CommandPolicyV2;
diff --git a/apps/server/src/orchestration-v2/CommandPolicy.ts b/apps/server/src/orchestration-v2/CommandPolicy.ts
index 02f329e536feb..cd56460369bd6 100644
--- a/apps/server/src/orchestration-v2/CommandPolicy.ts
+++ b/apps/server/src/orchestration-v2/CommandPolicy.ts
@@ -10,6 +10,7 @@ import {
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
+import { latestExecutedRun } from "@t3tools/shared/orchestrationV2ThreadError";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -125,6 +126,15 @@ export function isActiveRun(run: OrchestrationV2Run): boolean {
);
}
+/** The run a follow-up to a finished child binds to: the latest active one, else the last that ran. */
+export function followUpOwnerRun(
+ runs: ReadonlyArray,
+): OrchestrationV2Run | null {
+ return (
+ runs.filter(isActiveRun).toSorted((a, b) => b.ordinal - a.ordinal)[0] ?? latestExecutedRun(runs)
+ );
+}
+
function providerTurnCapabilities(
projection: OrchestrationV2ThreadProjection,
run: OrchestrationV2Run,
diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
index 9b3b38ec4b607..5facb16bf26eb 100644
--- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
+++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
@@ -1,3 +1,6 @@
+import * as Exit from "effect/Exit";
+import * as EffectOutbox from "./EffectOutbox.ts";
+import * as EffectWorker from "./EffectWorker.ts";
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
@@ -118,6 +121,7 @@ const layerTest = Layer.mergeAll(
RuntimeLayer.layer,
RuntimeLayer.layerEventSink,
ThreadCommandExecutor.layer,
+ EffectOutbox.layer,
).pipe(
Layer.provideMerge(RuntimeLayer.layerProjectService),
Layer.provide(
@@ -143,6 +147,7 @@ const layerTest = Layer.mergeAll(
repositoryIdentityResolved: false,
}),
invalidate: () => Effect.void,
+ refreshRepositoryIdentity: () => Effect.void,
subscribeChanges: Effect.never,
}),
),
@@ -2427,138 +2432,344 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))(
}),
);
- it.effect("delivers the run a background command's wake starts after the original result", () =>
+ it.effect("checkpoint retry releases a pending sibling after its wake offer failed", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
- const eventSink = yield* EventSink.EventSinkV2;
+ const sink = yield* EventSink.EventSinkV2;
+ const outbox = yield* EffectOutbox.EffectOutboxV2;
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
const now = yield* DateTime.now;
- const parentThreadId = ThreadId.make("thread:background-wake-parent");
- const projectId = ProjectId.make("project:background-wake");
- const parentRunId = RunId.make("run:background-wake-parent");
- const rootNodeId = NodeId.make("node:background-wake-parent");
+ const threadId = ThreadId.make("thread:checkpoint-own-delivery");
+ const originRunId = RunId.make("run:checkpoint-own-delivery:origin");
+ const firstId = NodeId.make("node:checkpoint-own-delivery:first");
+ const siblingId = NodeId.make("node:checkpoint-own-delivery:sibling");
yield* seedParentWithTerminalTask({
- threadId: parentThreadId,
- projectId,
- runId: parentRunId,
- rootNodeId,
- taskId: NodeId.make("node:background-wake-seed"),
- deliveryState: "acknowledged",
- now,
- });
- const child = yield* seedRestartCancelledChild({
- parentThreadId,
- projectId,
- parentRunId,
- rootNodeId,
- name: "background-wake-child",
- completionWake: "always",
- continuationPending: false,
- runStatus: "completed",
+ threadId,
+ projectId: ProjectId.make("project:checkpoint-own-delivery"),
+ runId: originRunId,
+ rootNodeId: NodeId.make("node:checkpoint-own-delivery:root"),
+ taskId: firstId,
+ deliveryState: "claimed",
+ deliveryTaskIds: [firstId],
+ parentRunStatus: "completed",
now,
});
- yield* orchestrator.recoverDelegatedTasks;
- let firstWake = yield* requests.take;
- while (firstWake.threadId !== parentThreadId) firstWake = yield* requests.take;
- yield* orchestrator.dispatch({
- type: "delegated_task.completion-delivery.acknowledge",
- commandId: CommandId.make("command:background-wake-ack"),
- parentThreadId,
- taskId: child.taskId,
- observedByRunId: parentRunId,
- });
- const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.find(
- (run) => run.id === parentRunId,
- )!;
- yield* eventSink.write({
- commandId: reconcileCommandId("background-wake-parent-finished"),
- events: [
- {
- id: EventId.make("event:background-wake-parent-finished"),
- type: "run.updated",
- threadId: parentThreadId,
- runId: parentRunId,
- occurredAt: now,
- payload: { ...parentRun, status: "completed", completedAt: now },
- },
- ],
- });
-
- // The shape ProviderContinuationService dispatches when the provider
- // reports a background command (wire kind `background_command`) ended.
- const wakeMessageId = MessageId.make("message:background-wake");
+ const original = yield* orchestrator.getThreadProjection(threadId);
+ const first = original.subagents.find((task) => task.id === firstId)!;
+ const delivery = original.runs.find((run) => run.id === originRunId)!.delegatedCompletion!
+ .delivery!;
yield* orchestrator.dispatch({
type: "message.dispatch",
createdBy: "agent",
- creationSource: "provider",
- commandId: CommandId.make("command:background-wake"),
- threadId: child.childThreadId,
- messageId: wakeMessageId,
- text: "Background activity updated",
- notification: {
- source: { kind: "command" },
- outcome: "completed",
- summary: 'Command "sleep 60" finished',
- },
+ creationSource: "server",
+ commandId: reconcileCommandId("checkpoint-own-delivery-wake"),
+ threadId,
+ messageId: delivery.messageId,
+ text: "First result",
attachments: [],
dispatchMode: { type: "queue_after_active" },
+ delegatedCompletion: {
+ parentRunId: originRunId,
+ generation: delivery.generation,
+ taskIds: delivery.taskIds,
+ },
});
- const run = (yield* orchestrator.getThreadProjection(child.childThreadId)).runs.find(
- (row) => row.userMessageId === wakeMessageId,
+ const started = yield* orchestrator.getThreadProjection(threadId);
+ const run = started.runs.find(
+ (candidate) => candidate.userMessageId === delivery.messageId,
)!;
- assert.isDefined(run.delegatedTaskId);
- yield* eventSink.write({
- commandId: reconcileCommandId("background-wake-finished"),
+ const scopeId = started.nodes.find(
+ (node) => node.id === run.rootNodeId,
+ )!.checkpointScopeId!;
+ yield* outbox.cancelUnsettled({
+ threadId,
+ effectTypes: ["provider-turn.start"],
+ reason: "The delivery turn already completed.",
+ });
+ const commandId = reconcileCommandId("checkpoint-own-delivery-finished");
+ yield* sink.writeWithEffects({
+ commandId,
events: [
{
- id: EventId.make("event:background-wake-result"),
- type: "message.updated",
- threadId: child.childThreadId,
- runId: run.id,
+ id: EventId.make("event:checkpoint-own-delivery:sibling"),
+ type: "subagent.updated",
+ threadId,
+ runId: originRunId,
+ nodeId: siblingId,
occurredAt: now,
payload: {
- id: MessageId.make("message:background-wake-result"),
- threadId: child.childThreadId,
- runId: run.id,
- nodeId: null,
- role: "assistant",
- text: "The background command finished cleanly.",
- attachments: [],
- streaming: false,
- createdBy: "agent",
- creationSource: "server",
- createdAt: now,
- updatedAt: now,
+ ...first,
+ id: siblingId,
+ completionDelivery: { state: "pending", observedByRunId: null },
},
},
{
- id: EventId.make("event:background-wake-finished"),
+ id: EventId.make("event:checkpoint-own-delivery:finished"),
type: "run.updated",
- threadId: child.childThreadId,
+ threadId,
runId: run.id,
occurredAt: now,
- payload: { ...run, status: "completed", startedAt: now, completedAt: now },
+ payload: {
+ ...run,
+ status: "completed",
+ startedAt: now,
+ completedAt: now,
+ checkpointId: CheckpointId.make("checkpoint:own-delivery"),
+ },
+ },
+ ],
+ effects: [
+ {
+ id: "effect:checkpoint-own-delivery",
+ commandId,
+ threadId,
+ request: { type: "checkpoint.capture", runId: run.id, scopeId },
},
],
});
- yield* orchestrator.recoverDelegatedTasks;
- const followup = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find(
- (task) => task.id === run.delegatedTaskId,
- )!;
- assert.equal(followup.status, "completed");
- assert.equal(followup.result, "The background command finished cleanly.");
- assert.equal(followup.completionDelivery?.state, "claimed");
+ using offer = vi
+ .spyOn(requests, "offer")
+ .mockImplementationOnce(() => Effect.die("successor wake offer failed"));
+ const firstAttempt = yield* Effect.exit(
+ orchestrator.recoverDelegatedTask(threadId, { completedRunId: run.id }),
+ );
+ assert.isTrue(Exit.isFailure(firstAttempt));
+ const reserved = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
+ (candidate) => candidate.id === originRunId,
+ )!.delegatedCompletion!.delivery!;
+ assert.deepEqual(reserved.taskIds, [siblingId]);
+ yield* worker.drain();
+ assert.lengthOf(offer.mock.calls, 2);
+ const completed = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(
+ completed.subagents.find((task) => task.id === firstId)?.completionDelivery?.state,
+ "delivered",
+ );
+ assert.equal(
+ completed.subagents.find((task) => task.id === siblingId)?.completionDelivery?.state,
+ "claimed",
+ );
+ assert.deepEqual(
+ completed.runs.find((candidate) => candidate.id === originRunId)?.delegatedCompletion
+ ?.delivery?.taskIds,
+ [siblingId],
+ );
let wake = yield* requests.take;
- while (
- wake.threadId !== parentThreadId ||
- wake.delegatedCompletion?.messageId === firstWake.delegatedCompletion?.messageId
- ) {
- wake = yield* requests.take;
- }
- assert.equal(wake.delegatedCompletion?.parentRunId, parentRunId);
+ while (wake.threadId !== threadId) wake = yield* requests.take;
+ assert.equal(wake.delegatedCompletion?.generation, delivery.generation + 1);
}),
);
+ it.effect.each(["live", "checkpoint-retry", "checkpoint-offer-retry"] as const)(
+ "delivers the run a background command's wake starts after the original result (%s)",
+ (delivery) =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const eventSink = yield* EventSink.EventSinkV2;
+ const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
+ const now = yield* DateTime.now;
+ const parentThreadId = ThreadId.make(`thread:background-wake-parent-${delivery}`);
+ const projectId = ProjectId.make(`project:background-wake-${delivery}`);
+ const parentRunId = RunId.make(`run:background-wake-parent-${delivery}`);
+ const rootNodeId = NodeId.make(`node:background-wake-parent-${delivery}`);
+ yield* seedParentWithTerminalTask({
+ threadId: parentThreadId,
+ projectId,
+ runId: parentRunId,
+ rootNodeId,
+ taskId: NodeId.make(`node:background-wake-seed-${delivery}`),
+ deliveryState: "acknowledged",
+ now,
+ });
+ const child = yield* seedRestartCancelledChild({
+ parentThreadId,
+ projectId,
+ parentRunId,
+ rootNodeId,
+ name: `background-wake-child-${delivery}`,
+ completionWake: "always",
+ continuationPending: false,
+ runStatus: "completed",
+ now,
+ });
+ yield* orchestrator.recoverDelegatedTasks;
+ let firstWake = yield* requests.take;
+ while (firstWake.threadId !== parentThreadId) firstWake = yield* requests.take;
+ yield* orchestrator.dispatch({
+ type: "delegated_task.completion-delivery.acknowledge",
+ commandId: CommandId.make(`command:background-wake-ack-${delivery}`),
+ parentThreadId,
+ taskId: child.taskId,
+ observedByRunId: parentRunId,
+ });
+ const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.find(
+ (run) => run.id === parentRunId,
+ )!;
+ yield* eventSink.write({
+ commandId: reconcileCommandId(`background-wake-parent-finished-${delivery}`),
+ events: [
+ {
+ id: EventId.make(`event:background-wake-parent-finished-${delivery}`),
+ type: "run.updated",
+ threadId: parentThreadId,
+ runId: parentRunId,
+ occurredAt: now,
+ payload: { ...parentRun, status: "completed", completedAt: now },
+ },
+ ],
+ });
+
+ // The shape ProviderContinuationService dispatches when the provider
+ // reports a background command (wire kind `background_command`) ended.
+ const wakeMessageId = MessageId.make(`message:background-wake-${delivery}`);
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ createdBy: "agent",
+ creationSource: "provider",
+ commandId:
+ delivery === "live"
+ ? CommandId.make(`command:background-wake-${delivery}`)
+ : reconcileCommandId(`background-wake-${delivery}`),
+ threadId: child.childThreadId,
+ messageId: wakeMessageId,
+ text: "Background activity updated",
+ notification: {
+ source: { kind: "command" },
+ outcome: "completed",
+ summary: 'Command "sleep 60" finished',
+ },
+ attachments: [],
+ dispatchMode: { type: "queue_after_active" },
+ });
+ const childProjection = yield* orchestrator.getThreadProjection(child.childThreadId);
+ const run = childProjection.runs.find((row) => row.userMessageId === wakeMessageId)!;
+ const scopeId = childProjection.nodes.find(
+ (node) => node.id === run.rootNodeId,
+ )!.checkpointScopeId!;
+ const commandId =
+ delivery === "live"
+ ? CommandId.make(`command:background-wake-finished-${delivery}`)
+ : reconcileCommandId(`background-wake-finished-${delivery}`);
+ if (delivery !== "live") {
+ const outbox = yield* EffectOutbox.EffectOutboxV2;
+ yield* outbox.cancelUnsettled({
+ threadId: child.childThreadId,
+ effectTypes: ["provider-turn.start"],
+ reason: "The turn already finished before its checkpoint retry.",
+ });
+ }
+ const afterSequence = yield* eventSink.latestSequence();
+ assert.isDefined(run.delegatedTaskId);
+ yield* eventSink.writeWithEffects({
+ commandId,
+ effects:
+ delivery === "live"
+ ? []
+ : [
+ {
+ id: `effect:background-wake-checkpoint-retry-${delivery}`,
+ commandId,
+ threadId: child.childThreadId,
+ request: { type: "checkpoint.capture", runId: run.id, scopeId },
+ },
+ ],
+ events: [
+ {
+ id: EventId.make(`event:background-wake-result-${delivery}`),
+ type: "message.updated",
+ threadId: child.childThreadId,
+ runId: run.id,
+ occurredAt: now,
+ payload: {
+ id: MessageId.make(`message:background-wake-result-${delivery}`),
+ threadId: child.childThreadId,
+ runId: run.id,
+ nodeId: null,
+ role: "assistant",
+ text: "The background command finished cleanly.",
+ attachments: [],
+ streaming: false,
+ createdBy: "agent",
+ creationSource: "server",
+ createdAt: now,
+ updatedAt: now,
+ },
+ },
+ {
+ id: EventId.make(`event:background-wake-finished-${delivery}`),
+ type: "run.updated",
+ threadId: child.childThreadId,
+ runId: run.id,
+ occurredAt: now,
+ payload: {
+ ...run,
+ status: "completed",
+ startedAt: now,
+ completedAt: now,
+ checkpointId:
+ delivery === "live"
+ ? null
+ : CheckpointId.make(`checkpoint:background-wake-${delivery}`),
+ },
+ },
+ ],
+ });
+ if (delivery !== "live") {
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
+ if (delivery === "checkpoint-offer-retry") {
+ using offer = vi
+ .spyOn(requests, "offer")
+ .mockImplementationOnce(() => Effect.die("wake offer failed"));
+ const first = yield* Effect.exit(
+ orchestrator.recoverDelegatedTask(child.childThreadId),
+ );
+ assert.isTrue(Exit.isFailure(first));
+ const committed = (yield* orchestrator.getThreadProjection(
+ parentThreadId,
+ )).subagents.find((task) => task.id === run.delegatedTaskId)!;
+ assert.equal(committed.result, "The background command finished cleanly.");
+ yield* worker.drain();
+ assert.lengthOf(offer.mock.calls, 2);
+ } else {
+ yield* worker.drain();
+ }
+ } else {
+ yield* eventSink.stream({ afterSequence, eventType: "subagent.updated" }).pipe(
+ Stream.filter(
+ (stored) =>
+ stored.event.type === "subagent.updated" &&
+ stored.event.payload.id === run.delegatedTaskId &&
+ stored.event.payload.status === "completed",
+ ),
+ Stream.take(1),
+ Stream.runDrain,
+ );
+ }
+ const completed = yield* orchestrator.getThreadProjection(parentThreadId);
+ const followup = completed.subagents.find((task) => task.id === run.delegatedTaskId)!;
+ assert.lengthOf(
+ completed.contextTransfers.filter(
+ (transfer) =>
+ transfer.type === "subagent_result" &&
+ transfer.sourceThreadId === child.childThreadId,
+ ),
+ 2,
+ );
+ assert.equal(followup.status, "completed");
+ assert.equal(followup.result, "The background command finished cleanly.");
+ assert.equal(followup.completionDelivery?.state, "claimed");
+ let wake = yield* requests.take;
+ while (
+ wake.threadId !== parentThreadId ||
+ wake.delegatedCompletion?.messageId === firstWake.delegatedCompletion?.messageId
+ ) {
+ wake = yield* requests.take;
+ }
+ assert.equal(wake.delegatedCompletion?.parentRunId, parentRunId);
+ }),
+ );
+
// The child's follow-up run sends `t3_thread_send` to its own thread before it ends.
const startSelfQueuedFollowup = (name: string) =>
Effect.gen(function* () {
@@ -3670,7 +3881,9 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => {
assert.isTrue(yield* orchestrator.delegatedTaskResultPending(recut.childThreadId));
assert.isTrue(yield* orchestrator.delegatedTaskResultPending(resumed.childThreadId));
assert.isFalse(yield* orchestrator.delegatedTaskResultPending(stopped.childThreadId));
- yield* orchestrator.recoverDelegatedTask(recut.childThreadId, recut.childRunId);
+ yield* orchestrator.recoverDelegatedTask(recut.childThreadId, {
+ sourceRunId: recut.childRunId,
+ });
const replayed = yield* orchestrator.getThreadProjection(threadId);
assert.equal(replayed.subagents.find((row) => row.id === recut.taskId)?.status, "running");
yield* eventSink.write({
diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts
index 58aa3ea97489c..eb1209158cc74 100644
--- a/apps/server/src/orchestration-v2/EffectOutbox.ts
+++ b/apps/server/src/orchestration-v2/EffectOutbox.ts
@@ -5,6 +5,7 @@ import {
MessageId,
ModelSelection,
NodeId,
+ NonNegativeInt,
ProviderSessionId,
RunAttemptId,
ProviderApprovalDecision,
@@ -65,6 +66,7 @@ export const OrchestrationEffectRequestV2 = Schema.Union([
providerTurnId: ProviderTurnId,
messageId: MessageId,
modelSelection: Schema.optional(ModelSelection),
+ steerFollowUpAfterRunOrdinal: Schema.optional(NonNegativeInt),
}),
Schema.Struct({
type: Schema.Literal("provider-turn.restart"),
diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts
index 0013735f3b4f3..dfb47bd7b3744 100644
--- a/apps/server/src/orchestration-v2/EffectWorker.ts
+++ b/apps/server/src/orchestration-v2/EffectWorker.ts
@@ -29,6 +29,8 @@ import * as ThreadManagementService from "./ThreadManagementService.ts";
import * as ServerSettings from "../serverSettings.ts";
import { continueRestartedRun } from "./RestartContinuation.ts";
+const isProviderTurnControlError = Schema.is(ProviderTurnControlService.ProviderTurnControlError);
+
export class OrchestrationEffectExecutionError extends Schema.TaggedError()(
"OrchestrationEffectExecutionError",
{
@@ -106,7 +108,7 @@ export const layerExecutor: Layer.Layer<
Effect.tapError(() =>
willRetry
? Effect.void
- : threads.recoverDelegatedTask(effect.threadId, sourceRunId),
+ : threads.recoverDelegatedTask(effect.threadId, { sourceRunId }),
),
Effect.mapError(
(cause) =>
@@ -284,8 +286,8 @@ export const layerExecutor: Layer.Layer<
Effect.catch((error) =>
Effect.gen(function* () {
if (
- !("turnCompleted" in error) ||
- !error.turnCompleted ||
+ !isProviderTurnControlError(error) ||
+ (!error.turnCompleted && !error.steerDeclined) ||
effect.request.type !== "provider-turn.steer"
) {
return yield* error;
@@ -302,7 +304,8 @@ export const layerExecutor: Layer.Layer<
// Notifications must be queued messages.
const queued =
message.delegatedCompletion !== undefined ||
- message.notification !== undefined;
+ message.notification !== undefined ||
+ error.steerDeclined === true;
// Reuse message ids and receipts so retries cannot duplicate messages or follow-ups.
yield* threads
.dispatch({
@@ -310,12 +313,22 @@ export const layerExecutor: Layer.Layer<
commandId: CommandId.make(`command:steer-follow-up:${effect.id}`),
threadId: effect.threadId,
messageId: message.id,
+ ...(error.steerDeclined ? { steerFollowUpOfRunId: run.id } : {}),
+ ...(error.steerDeclined &&
+ effect.request.steerFollowUpAfterRunOrdinal !== undefined
+ ? {
+ steerFollowUpAfterRunOrdinal:
+ effect.request.steerFollowUpAfterRunOrdinal,
+ }
+ : {}),
text: message.text,
...(message.context ? { context: message.context } : {}),
attachments: message.attachments,
- ...(message.delegatedCompletion === undefined
- ? {}
- : { modelSelection: run.modelSelection }),
+ ...(error.steerDeclined && effect.request.modelSelection !== undefined
+ ? { modelSelection: effect.request.modelSelection }
+ : message.delegatedCompletion === undefined
+ ? {}
+ : { modelSelection: run.modelSelection }),
dispatchMode: {
type: queued ? "queue_after_active" : "start_immediately",
},
@@ -333,6 +346,9 @@ export const layerExecutor: Layer.Layer<
...(message.senderThreadId === undefined
? {}
: { senderThreadId: message.senderThreadId }),
+ ...(message.linkedSender === undefined
+ ? {}
+ : { linkedSender: message.linkedSender }),
})
.pipe(
// A disabled instance cannot retry this completed turn; its result stands.
@@ -506,6 +522,12 @@ export const layerExecutor: Layer.Layer<
scopeId: effect.request.scopeId,
})
.pipe(
+ // Completion bookkeeping must survive a missed live run update, including capture retries.
+ Effect.andThen(
+ threads.recoverDelegatedTask(effect.threadId, {
+ completedRunId: effect.request.runId,
+ }),
+ ),
Effect.mapError(
(cause) =>
new OrchestrationEffectExecutionError({
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index aedae5508b58a..39d0595d02a46 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -8,6 +8,7 @@ import type {
import {
latestExecutedRun,
latestRootProviderFailure,
+ orchestrationV2WorktreePending,
runRanAfter,
usageLimitBlockedRun,
} from "@t3tools/shared/orchestrationV2ThreadError";
@@ -62,7 +63,6 @@ import {
latestProviderTurnForAttempt,
parseGoalCommand,
orchestrationV2RunWorkStartedAt,
- orchestrationV2WorktreePending,
ProviderInstanceId,
ProviderInteractionMode,
isRuntimeModeAbove,
@@ -107,6 +107,7 @@ import {
import { CheckpointServiceV2 } from "./CheckpointService.ts";
import {
CommandPolicyV2,
+ followUpOwnerRun,
goalCommandStopsActiveRun,
isActiveRun,
isNativeMaintenanceCommand,
@@ -382,7 +383,10 @@ export interface OrchestratorV2DispatchResult {
export interface OrchestratorV2Shape {
readonly resumeQueuedRuns: Effect.Effect;
readonly recoverDelegatedTasks: Effect.Effect;
- readonly recoverDelegatedTask: (threadId: ThreadId, sourceRunId: RunId) => Effect.Effect;
+ readonly recoverDelegatedTask: (
+ threadId: ThreadId,
+ options?: { readonly sourceRunId?: RunId; readonly completedRunId?: RunId },
+ ) => Effect.Effect;
/** Commits cancellation with the child's Stop after descendants accept stopping. */
readonly cancelDelegatedTask: (input: {
readonly parentThreadId: ThreadId;
@@ -2640,6 +2644,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
...(queuedMessage.senderThreadId === undefined
? {}
: { senderThreadId: queuedMessage.senderThreadId }),
+ ...(queuedMessage.linkedSender === undefined
+ ? {}
+ : { linkedSender: queuedMessage.linkedSender }),
...(queuedMessage.idleCompaction === undefined
? {}
: { idleCompaction: queuedMessage.idleCompaction }),
@@ -5457,6 +5464,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
readonly creationSource: OrchestrationV2ConversationMessage["creationSource"];
readonly scheduledTaskId?: OrchestrationV2ConversationMessage["scheduledTaskId"];
readonly senderThreadId?: OrchestrationV2ConversationMessage["senderThreadId"];
+ readonly linkedSender?: OrchestrationV2ConversationMessage["linkedSender"];
readonly idleCompaction?: OrchestrationV2ConversationMessage["idleCompaction"];
readonly delegatedCompletion?: OrchestrationV2ConversationMessage["delegatedCompletion"];
readonly notification?: OrchestrationV2ConversationMessage["notification"];
@@ -5601,6 +5609,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {}
: { scheduledTaskId: input.scheduledTaskId }),
...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
+ ...(input.linkedSender === undefined ? {} : { linkedSender: input.linkedSender }),
...(input.idleCompaction === undefined ? {} : { idleCompaction: input.idleCompaction }),
id: input.messageId,
threadId: input.command.threadId,
@@ -5621,6 +5630,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {}
: { scheduledTaskId: input.scheduledTaskId }),
...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
+ ...(input.linkedSender === undefined ? {} : { linkedSender: input.linkedSender }),
...(input.idleCompaction === undefined ? {} : { idleCompaction: input.idleCompaction }),
id: idAllocator.derive.userTurnItem({ messageId: input.messageId }),
threadId: input.command.threadId,
@@ -5737,6 +5747,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
providerTurnId: providerTurn.id,
messageId: input.messageId,
...(steerCarriesSelection ? { modelSelection: input.modelSelection } : {}),
+ steerFollowUpAfterRunOrdinal: Math.max(
+ 0,
+ ...input.projection.runs.map((run) => run.ordinal),
+ ),
},
} satisfies PendingOrchestrationEffectV2,
]);
@@ -6170,6 +6184,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
effects: Ref.Ref>,
) {
let projection = yield* getProjectionWithPendingEvents(command.threadId, events);
+ if (command.steerFollowUpOfRunId !== undefined) {
+ const source = projection.runs.find((run) => run.id === command.steerFollowUpOfRunId);
+ if (
+ source === undefined ||
+ command.dispatchMode.type !== "queue_after_active" ||
+ !projection.messages.some(
+ (message) => message.id === command.messageId && message.runId === source.id,
+ ) ||
+ projection.thread.archivedAt !== null ||
+ projection.thread.deletedAt !== null ||
+ (yield* stopReachedRun(command, command.threadId, source.id))
+ ) {
+ yield* emit(
+ events,
+ command,
+ )({
+ type: "thread.metadata-updated",
+ threadId: command.threadId,
+ occurredAt: yield* DateTime.now,
+ payload: projection.thread,
+ });
+ return;
+ }
+ }
if (
(yield* isStaleQuestionWake(projection, command.messageId, command.notification)) ||
(command.cacheExpiryCompactionOfProviderTurnId !== undefined &&
@@ -6770,6 +6808,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {}
: { scheduledTaskId: command.scheduledTaskId }),
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
+ ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
forceRestart: dispatchMode.type === "restart_active",
});
@@ -6818,6 +6857,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
// Provider failure or usage limits re-hold the queue.
const worktreeSetupUnresolved = worktreeSetupPending(projection);
const sentByUserFromClient =
+ command.steerFollowUpOfRunId === undefined &&
command.createdBy === "user" &&
(command.creationSource === "web" || command.creationSource === "mobile") &&
command.scheduledTaskId === undefined;
@@ -6949,6 +6989,35 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
command.createdBy === "agent" &&
command.creationSource === "provider" &&
!(yield* stopReachedRun(command, command.threadId, activeRun.id));
+ let steerFollowUpQueuePosition: number | undefined;
+ if (
+ command.steerFollowUpOfRunId !== undefined &&
+ command.steerFollowUpAfterRunOrdinal !== undefined
+ ) {
+ const afterRunOrdinal = command.steerFollowUpAfterRunOrdinal;
+ const steerOrdinal =
+ projection.turnItems.find(
+ (item) => item.type === "user_message" && item.messageId === command.messageId,
+ )?.ordinal ?? -1;
+ // Earlier declined steers have newer runs but retain their original turn-item ordinals.
+ const earlierSteerMessageIds = new Set(
+ projection.turnItems.flatMap((item) =>
+ item.type === "user_message" && item.ordinal < steerOrdinal ? [item.messageId] : [],
+ ),
+ );
+ steerFollowUpQueuePosition =
+ Math.max(
+ 0,
+ ...projection.runs
+ .filter(
+ (candidate) =>
+ candidate.status === "queued" &&
+ (candidate.ordinal <= afterRunOrdinal ||
+ earlierSteerMessageIds.has(candidate.userMessageId)),
+ )
+ .map((candidate) => candidate.queuePosition ?? candidate.ordinal),
+ ) + 1;
+ }
const run: OrchestrationV2Run = {
id: runId,
threadId: command.threadId,
@@ -6971,12 +7040,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
queuePosition:
queuedRunStop !== undefined
? 1
- : Math.max(
+ : (steerFollowUpQueuePosition ??
+ Math.max(
0,
...projection.runs
.filter((candidate) => candidate.status === "queued")
.map((candidate) => candidate.queuePosition ?? candidate.ordinal),
- ) + 1,
+ ) + 1),
requestedAt: now,
startedAt: null,
completedAt: null,
@@ -7029,6 +7099,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {}
: { scheduledTaskId: command.scheduledTaskId }),
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
+ ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
id: command.messageId,
threadId: command.threadId,
@@ -7063,6 +7134,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
occurredAt: now,
payload: run,
});
+ if (steerFollowUpQueuePosition !== undefined) {
+ for (const queued of projection.runs) {
+ if (
+ queued.status !== "queued" ||
+ (queued.queuePosition ?? queued.ordinal) < steerFollowUpQueuePosition
+ )
+ continue;
+ yield* emitEvent({
+ type: "run.updated",
+ threadId: command.threadId,
+ runId: queued.id,
+ providerInstanceId: queued.providerInstanceId,
+ occurredAt: now,
+ payload: { ...queued, queuePosition: (queued.queuePosition ?? queued.ordinal) + 1 },
+ });
+ }
+ }
yield* completeSourcePlan(now);
yield* emitEvent({
type: "run-attempt.created",
@@ -7419,6 +7507,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {}
: { scheduledTaskId: command.scheduledTaskId }),
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
+ ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
id: command.messageId,
threadId: command.threadId,
@@ -7441,6 +7530,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {}
: { scheduledTaskId: command.scheduledTaskId }),
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
+ ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
threadId: command.threadId,
@@ -8204,6 +8294,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {}
: { scheduledTaskId: command.scheduledTaskId }),
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
+ ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
id: command.messageId,
threadId: command.threadId,
@@ -8226,6 +8317,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
? {}
: { scheduledTaskId: command.scheduledTaskId }),
...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }),
+ ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }),
...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }),
id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
threadId: command.threadId,
@@ -8968,9 +9060,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
task.id === (child.forkedFrom?.type === "node" ? child.forkedFrom.nodeId : undefined),
);
if (original === undefined || original.result === null) return;
- const owner =
- parent.runs.filter(isActiveRun).toSorted((a, b) => b.ordinal - a.ordinal)[0] ??
- latestExecutedRun(parent.runs);
+ const owner = followUpOwnerRun(parent.runs);
if (owner === null || owner.rootNodeId === null) return;
const now = message.createdAt;
const adapter = yield* providerAdapters.get(run.providerInstanceId);
@@ -9088,7 +9178,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
events: Ref.Ref>,
) {
const parentProjection = yield* projectionStore
- .getThreadRecords(command.parentThreadId, ["runs", "providerTurns", "attempts"])
+ .getThreadRecords(command.parentThreadId, ["runs", "providerTurns", "attempts", "subagents"])
.pipe(
Effect.mapError(
(cause) => new OrchestratorProjectionError({ threadId: command.parentThreadId, cause }),
@@ -9097,7 +9187,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
const parentRun = parentProjection.runs.find(
(candidate) => candidate.id === command.parentRunId,
);
- if (parentRun === undefined || !isActiveRun(parentRun) || parentRun.rootNodeId === null) {
+ // A follow-up to a finished task there binds as one to a child here does.
+ const followsUp = parentProjection.subagents.some(
+ (task) =>
+ task.result !== null &&
+ task.remoteChild?.environmentId === command.remoteChild.environmentId &&
+ task.remoteChild.threadId === command.remoteChild.threadId,
+ );
+ if (
+ parentRun === undefined ||
+ (followsUp
+ ? parentRun.id !== followUpOwnerRun(parentProjection.runs)?.id
+ : !isActiveRun(parentRun)) ||
+ parentRun.rootNodeId === null
+ ) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
@@ -10690,6 +10793,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
...(queuedMessage.senderThreadId === undefined
? {}
: { senderThreadId: queuedMessage.senderThreadId }),
+ ...(queuedMessage.linkedSender === undefined
+ ? {}
+ : { linkedSender: queuedMessage.linkedSender }),
...(queuedMessage.idleCompaction === undefined
? {}
: { idleCompaction: queuedMessage.idleCompaction }),
@@ -15058,23 +15164,48 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
);
const recoverDelegatedTask = Effect.fn("Orchestrator.recoverDelegatedTask")(
- function* (threadId: ThreadId, sourceRunId: RunId) {
+ function* (
+ threadId: ThreadId,
+ options?: { readonly sourceRunId?: RunId; readonly completedRunId?: RunId },
+ ) {
+ const completedRunId = options?.completedRunId;
+ if (completedRunId !== undefined) {
+ yield* threadDispatch.withLock(
+ threadId,
+ Effect.gen(function* () {
+ const message = yield* projectionStore.getRunMessage(threadId, completedRunId);
+ if (message?.delegatedCompletion === undefined) return;
+ // A prior attempt may have committed the next generation before offering its wake.
+ yield* offerDelegatedCompletionDelivery(
+ threadId,
+ message.delegatedCompletion.parentRunId,
+ );
+ yield* finalizeDelegatedCompletionDelivery(threadId, completedRunId);
+ }),
+ );
+ }
+ const sourceRunId = options?.sourceRunId;
const parentThreadId = yield* appOwnedSubagentParentThreadId(threadId);
if (parentThreadId === undefined) return;
+ if (
+ sourceRunId === undefined &&
+ !(yield* projectionStore.hasPendingDelegatedCompletion(threadId))
+ )
+ return;
yield* threadDispatch.withLock(
parentThreadId,
- finalizeAppOwnedSubagent(threadId, { settledContinuationOf: sourceRunId }),
+ offerDelegatedCompletionDeliveries(parentThreadId).pipe(
+ Effect.andThen(
+ finalizeAppOwnedSubagent(
+ threadId,
+ sourceRunId === undefined ? undefined : { settledContinuationOf: sourceRunId },
+ ),
+ ),
+ ),
);
},
- (effect, threadId, _sourceRunId) =>
- effect.pipe(
- Effect.catchCause((cause) =>
- Effect.logWarning("Failed to recover delegated task after restart", {
- childThreadId: threadId,
- cause,
- }),
- ),
- ),
+ (effect, threadId, _options) =>
+ effect.pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))),
);
const cancelDelegatedTask: OrchestratorV2Shape["cancelDelegatedTask"] = Effect.fn(
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
index 63b9485e59511..7678430840e1b 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
@@ -2929,6 +2929,16 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
const now = yield* DateTime.now;
const nowIso = DateTime.formatIso(now);
const threadId = ThreadId.make("thread:bounded-sql-history");
+ // The raw SQL edits below stand in for committed writes, which always append a thread event.
+ let revision = 0;
+ const historyPage = (...args: Parameters) =>
+ sql`INSERT INTO orchestration_events (
+ event_id, aggregate_kind, stream_id, stream_version, event_type,
+ occurred_at, actor_kind, payload_json, metadata_json, application_event_version
+ ) VALUES (
+ ${`event:bounded-sql-history:revision:${++revision}`}, 'thread', ${threadId}, ${revision},
+ 'turn-item.updated', ${nowIso}, 'user', '{}', '{}', 2
+ )`.pipe(Effect.andThen(projectionStore.getThreadHistoryPage(...args)));
yield* projectionStore.apply({
id: EventId.make("event:bounded-sql-history:thread"),
type: "thread.created",
@@ -3152,7 +3162,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
sourceItemId: TurnItemId.make("turn-item:bounded-sql-history:71"),
position: 70,
});
- const bytePage = yield* projectionStore.getThreadHistoryPage(threadId, byteCursor);
+ const bytePage = yield* historyPage(threadId, byteCursor);
assert.isAbove(bytePage.items.length, 0);
assert.isBelow(bytePage.items.length, 70);
assert.isAtMost(
@@ -3163,7 +3173,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
let byteNext = bytePage.nextCursor;
for (let pages = 0; byteNext !== null; pages += 1) {
assert.isBelow(pages, 70);
- const page = yield* projectionStore.getThreadHistoryPage(threadId, byteNext);
+ const page = yield* historyPage(threadId, byteNext);
assert.isAbove(page.items.length, 0);
byteIds.unshift(...page.items.map((row) => String(row.sourceItemId)));
byteNext = page.nextCursor;
@@ -3269,7 +3279,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
'$.attachments', json('[]'))
WHERE thread_id = ${threadId} AND ordinal BETWEEN 600 AND 624
`;
- const targetedPage = yield* projectionStore.getThreadHistoryPage(
+ const targetedPage = yield* historyPage(
threadId,
encodeThreadHistoryCursor({
snapshotSequence: 0,
@@ -3299,7 +3309,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
'$.type', CASE ordinal WHEN 500 THEN 'run_interrupt_request' ELSE 'run_interrupt_result' END)
WHERE thread_id = ${threadId} AND ordinal IN (500, 580)
`;
- const interruptPage = yield* projectionStore.getThreadHistoryPage(
+ const interruptPage = yield* historyPage(
threadId,
encodeThreadHistoryCursor({
snapshotSequence: 0,
@@ -3446,7 +3456,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
let workCursor: string | null = anchor.item.deferredWork!.cursor;
for (let pages = 0; workCursor !== null; pages += 1) {
assert.isBelow(pages, 20);
- const page: OrchestrationV2ThreadHistoryPage = yield* projectionStore.getThreadHistoryPage(
+ const page: OrchestrationV2ThreadHistoryPage = yield* historyPage(
threadId,
workCursor,
anchor.sourceItemId,
@@ -3475,7 +3485,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
window.projection.visibleTurnItems.find((row) => row.item.deferredWork)?.item.ordinal,
3,
);
- const page = yield* projectionStore.getThreadHistoryPage(
+ const page = yield* historyPage(
threadId,
encodeThreadHistoryCursor({
snapshotSequence: 0,
@@ -3532,14 +3542,13 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
const loaded = new Set();
for (let pages = 0; cursor !== null; pages += 1) {
assert.isBelow(pages, 20);
- const page: OrchestrationV2ThreadHistoryPage =
- yield* projectionStore.getThreadHistoryPage(
- threadId,
- cursor,
- oldWork!.sourceItemId,
- false,
- "work",
- );
+ const page: OrchestrationV2ThreadHistoryPage = yield* historyPage(
+ threadId,
+ cursor,
+ oldWork!.sourceItemId,
+ false,
+ "work",
+ );
for (const row of page.items) loaded.add(row.sourceItemId);
cursor = page.nextCursor;
}
@@ -4470,6 +4479,276 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
}),
);
+ it.effect("pages a whole thread without re-reading its full timeline for every page", () =>
+ Effect.gen(function* () {
+ const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
+ const sql = yield* SqlClient.SqlClient;
+ const now = yield* DateTime.now;
+ const nowIso = DateTime.formatIso(now);
+ const threadId = ThreadId.make("thread:paged-scrollback");
+ const runId = RunId.make("run:paged-scrollback");
+ const itemCount = 600;
+ yield* projectionStore.apply({
+ id: EventId.make("event:paged-scrollback:thread"),
+ type: "thread.created",
+ threadId,
+ occurredAt: now,
+ payload: {
+ createdBy: "user",
+ creationSource: "web",
+ id: threadId,
+ projectId: ProjectId.make("project:paged-scrollback"),
+ title: "Paged scrollback",
+ providerInstanceId,
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ activeProviderThreadId: null,
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
+ forkedFrom: null,
+ createdAt: now,
+ updatedAt: now,
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ lastVisitedAt: null,
+ deletedAt: null,
+ },
+ });
+ yield* sql`
+ INSERT INTO orchestration_v2_projection_runs (
+ run_id, thread_id, ordinal, provider, provider_thread_id, status,
+ requested_at, completed_at, payload_json
+ ) VALUES (
+ ${runId}, ${threadId}, 1, 'codex', NULL, 'completed', ${nowIso}, ${nowIso},
+ ${encodeUnknownJsonString({
+ id: runId,
+ threadId,
+ ordinal: 1,
+ providerInstanceId,
+ modelSelection,
+ providerThreadId: null,
+ userMessageId: "message:paged-scrollback",
+ rootNodeId: "node:paged-scrollback",
+ activeAttemptId: null,
+ status: "completed",
+ requestedAt: nowIso,
+ startedAt: nowIso,
+ completedAt: nowIso,
+ checkpointId: null,
+ contextHandoffId: null,
+ })}
+ )
+ `;
+ for (let ordinal = 0; ordinal < itemCount; ordinal += 1) {
+ const id = `turn-item:paged-scrollback:${ordinal}`;
+ const message = ordinal % 9 === 0;
+ yield* sql`
+ INSERT INTO orchestration_v2_projection_turn_items (
+ turn_item_id, thread_id, run_id, node_id, provider_thread_id, provider_turn_id,
+ parent_item_id, ordinal, type, status, updated_at, payload_json
+ ) VALUES (
+ ${id}, ${threadId}, ${runId}, NULL, NULL, NULL, NULL, ${ordinal},
+ ${message ? "user_message" : "command_execution"}, 'completed', ${nowIso},
+ ${encodeUnknownJsonString({
+ id,
+ threadId,
+ runId,
+ nodeId: null,
+ providerThreadId: null,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal,
+ status: "completed",
+ title: `item ${ordinal}`,
+ startedAt: nowIso,
+ completedAt: nowIso,
+ updatedAt: nowIso,
+ ...(message
+ ? {
+ type: "user_message",
+ createdBy: "user",
+ creationSource: "web",
+ messageId: `message:paged-scrollback:${ordinal}`,
+ inputIntent: "turn_start",
+ text: `Turn ${ordinal}`,
+ attachments: [],
+ }
+ : { type: "command_execution", input: "echo", output: "ok", exitCode: 0 }),
+ })}
+ )
+ `;
+ }
+ // An unbounded read of every turn item in the thread costs O(thread) per page, so a full
+ // scrollback that repeats it on each page is quadratic in thread length.
+ const wholeThreadReads = (statements: ReadonlyArray) =>
+ statements.filter(
+ (statement) =>
+ /FROM orchestration_v2_projection_turn_items(\s+AS item)?\s+WHERE (item\.)?thread_id = \?\s*(ORDER BY|$)/.test(
+ statement,
+ ) && !/\bLIMIT\b/.test(statement),
+ ).length;
+ const snapshot = yield* projectionStore.getThreadSnapshot(threadId);
+
+ const history = traceSqlStatements();
+ let cursor: string | null = encodeThreadHistoryCursor({
+ snapshotSequence: snapshot.snapshotSequence,
+ sourceThreadId: threadId,
+ sourceItemId: "absent",
+ position: itemCount,
+ });
+ const historyIds: Array = [];
+ let historyPages = 0;
+ while (cursor !== null) {
+ const page: OrchestrationV2ThreadHistoryPage = yield* projectionStore
+ .getThreadHistoryPage(threadId, cursor)
+ .pipe(Effect.withTracer(history.tracer));
+ historyIds.push(...page.items.map((row) => String(row.sourceItemId)));
+ historyPages += 1;
+ cursor = page.hasMoreHistory ? page.nextCursor : null;
+ }
+ assert.strictEqual(new Set(historyIds).size, itemCount);
+ assert.isAtLeast(historyPages, 4);
+
+ const timeline = traceSqlStatements();
+ const timelineIds: Array = [];
+ let afterPosition = -1;
+ let timelinePages = 0;
+ for (let hasMore = true; hasMore;) {
+ const page = yield* projectionStore
+ .getTimelinePage(threadId, { view: "activity", afterPosition, limit: 100 })
+ .pipe(Effect.withTracer(timeline.tracer));
+ timelineIds.push(...page.items.map((row) => String(row.sourceItemId)));
+ afterPosition = page.items.at(-1)?.position ?? afterPosition;
+ timelinePages += 1;
+ hasMore = page.hasMore;
+ }
+ assert.strictEqual(new Set(timelineIds).size, itemCount);
+ assert.isAtLeast(timelinePages, 4);
+
+ assert.isAtMost(
+ wholeThreadReads(history.statements),
+ 1,
+ `getThreadHistoryPage read the whole thread on each of ${historyPages} pages`,
+ );
+ assert.isAtMost(
+ wholeThreadReads(timeline.statements),
+ 1,
+ `getTimelinePage read the whole thread on each of ${timelinePages} pages`,
+ );
+
+ // A write to the thread a fork inherits from must reach the fork's next page.
+ const forkThreadId = ThreadId.make("thread:paged-scrollback:fork");
+ yield* projectionStore.apply({
+ id: EventId.make("event:paged-scrollback:fork"),
+ type: "thread.created",
+ threadId: forkThreadId,
+ occurredAt: now,
+ payload: {
+ createdBy: "user",
+ creationSource: "web",
+ id: forkThreadId,
+ projectId: ProjectId.make("project:paged-scrollback"),
+ title: "Paged scrollback fork",
+ providerInstanceId,
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ activeProviderThreadId: null,
+ lineage: {
+ parentThreadId: threadId,
+ relationshipToParent: "fork",
+ rootThreadId: threadId,
+ },
+ forkedFrom: { type: "run", threadId, runId },
+ createdAt: now,
+ updatedAt: now,
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ lastVisitedAt: null,
+ deletedAt: null,
+ },
+ });
+ const forkPage = () =>
+ projectionStore.getTimelinePage(forkThreadId, { view: "activity", limit: 1 });
+ const forkTotal = (yield* forkPage()).totalItems;
+ assert.strictEqual((yield* forkPage()).totalItems, forkTotal);
+ yield* projectionStore.apply({
+ id: EventId.make("event:paged-scrollback:late-item"),
+ type: "turn-item.updated",
+ threadId,
+ runId,
+ driver,
+ occurredAt: now,
+ payload: {
+ id: TurnItemId.make("turn-item:paged-scrollback:late"),
+ threadId,
+ runId,
+ nodeId: null,
+ providerThreadId: null,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: itemCount,
+ status: "completed",
+ title: "late",
+ startedAt: now,
+ completedAt: now,
+ updatedAt: now,
+ type: "command_execution",
+ input: "echo",
+ },
+ });
+ assert.strictEqual((yield* forkPage()).totalItems, forkTotal + 1);
+
+ // Another store instance's write reaches this one only through the committed thread event.
+ const directId = "turn-item:paged-scrollback:direct";
+ yield* sql`
+ INSERT INTO orchestration_v2_projection_turn_items (
+ turn_item_id, thread_id, run_id, node_id, provider_thread_id, provider_turn_id,
+ parent_item_id, ordinal, type, status, updated_at, payload_json
+ ) VALUES (
+ ${directId}, ${threadId}, ${runId}, NULL, NULL, NULL, NULL, ${itemCount + 1},
+ 'command_execution', 'completed', ${nowIso},
+ ${encodeUnknownJsonString({
+ id: directId,
+ threadId,
+ runId,
+ nodeId: null,
+ providerThreadId: null,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: itemCount + 1,
+ status: "completed",
+ title: "direct",
+ startedAt: nowIso,
+ completedAt: nowIso,
+ updatedAt: nowIso,
+ type: "command_execution",
+ input: "echo",
+ })}
+ )
+ `;
+ yield* sql`
+ INSERT INTO orchestration_events (
+ event_id, aggregate_kind, stream_id, stream_version, event_type,
+ occurred_at, actor_kind, payload_json, metadata_json, application_event_version
+ ) VALUES (
+ 'event:paged-scrollback:direct', 'thread', ${threadId}, 1,
+ 'turn-item.updated', ${nowIso}, 'user', '{}', '{}', 2
+ )
+ `;
+ assert.strictEqual((yield* forkPage()).totalItems, forkTotal + 2);
+ }),
+ );
+
it.effect("scopes actionable provider state to the requested bounded thread", () =>
Effect.gen(function* () {
const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
@@ -4781,6 +5060,8 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
number: 42,
url: "https://github.com/acme/project/pull/42",
})})) WHERE thread_id = ${readThreadId}`;
+ const [latest] = yield* sql<{ readonly sequence: number }>`
+ SELECT COALESCE(MAX(sequence), 0) AS sequence FROM orchestration_events`;
const trace = traceSqlStatements();
const discovery = yield* projectionStore
.getPullRequestSnapshot({})
@@ -4791,7 +5072,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
.filter((id) => id === readThreadId || id === laterThreadId),
[readThreadId],
);
- assert.strictEqual(discovery.snapshotSequence, 0);
+ assert.strictEqual(discovery.snapshotSequence, latest?.sequence);
assert.strictEqual(trace.queryTransactions.length, 2);
assert.isNotNull(trace.queryTransactions[0]);
assert.strictEqual(new Set(trace.queryTransactions).size, 1);
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index f5df388b39c14..0986f957abe25 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -567,6 +567,9 @@ export interface ProjectionStoreV2Shape {
readonly listAppOwnedChildThreadIds: (
threadId: ThreadId,
) => Effect.Effect, ProjectionStoreV2Error>;
+ readonly hasPendingDelegatedCompletion: (
+ childThreadId: ThreadId,
+ ) => Effect.Effect;
readonly getNextTurnItemOrdinal: (
threadId: ThreadId,
) => Effect.Effect;
@@ -2158,10 +2161,50 @@ export const layer: Layer.Layer =
END
`;
+ type TimelineIndexItem = Pick<
+ OrchestrationV2TurnItem,
+ "id" | "threadId" | "runId" | "nodeId" | "parentItemId" | "type" | "status" | "ordinal"
+ > & {
+ readonly inputIntent?: Extract<
+ OrchestrationV2TurnItem,
+ { type: "user_message" }
+ >["inputIntent"];
+ readonly createdBy?: "user" | "agent" | "system";
+ readonly messageId?: MessageId;
+ readonly runStatus?: string | undefined;
+ readonly attemptId?: string | null;
+ readonly attemptStatus?: string | null;
+ readonly persistentOutput?: boolean;
+ readonly deferredWork?: OrchestrationV2TurnItem["deferredWork"];
+ };
+ type TimelineIndexRow = {
+ readonly sourceThreadId: ThreadId;
+ readonly sourceItemId: TurnItemId;
+ readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
+ readonly item: TimelineIndexItem;
+ readonly synthetic?: OrchestrationV2TurnItem;
+ };
+ type TimelineIndex = {
+ readonly records: ProjectionRecords<"runs" | "attempts">;
+ /** The thread and every fork source the index read. */
+ readonly threadIds: ReadonlyArray;
+ readonly local: ReadonlyArray;
+ readonly visible: ReadonlyArray;
+ };
+ // Least recently used first; a few cover clients scrolling side by side without pinning every thread.
+ const TIMELINE_INDEX_CACHE_LIMIT = 8;
+ const timelineIndexes = new Map<
+ string,
+ { readonly sequence: number; readonly index: TimelineIndex }
+ >();
+
const apply: ProjectionStoreV2Shape["apply"] =
/* This helper runs for individual orchestration events; the enclosing operation owns the span. */
Effect.fnUntraced(
function* (event) {
+ for (const [key, cached] of timelineIndexes) {
+ if (cached.index.threadIds.includes(event.threadId)) timelineIndexes.delete(key);
+ }
switch (event.type) {
case "thread.pull-request-link-updated": {
const thread = yield* getThread(event.threadId);
@@ -5946,6 +5989,20 @@ export const layer: Layer.Layer