Skip to content
TypeScript

test(server): prune low-value tests in orchestration-v2 (second pass) (#22599)

Julius Marminge32d8f8f0d0e3
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
index d52e0559507..fa4b0883c07 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
@@ -72,13 +72,10 @@ import { makeTurnInput } from "./AcpAdapterV2.testkit.ts";
import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
import {
AcpProviderCapabilitiesV2,
- acpProviderItemNativeId,
acpScopedNativeId,
- acpCarryoverTerminalShouldClearContinuation,
acpPostSettleContinuationOfferEvidence,
acpPostSettleWakeEvidence,
acpToolCallDiffPatch,
- acpTurnStartShouldPreserveContinuation,
makeAcpAdapterV2,
type AcpAdapterV2ExtensionContext,
type AcpAdapterV2Flavor,
@@ -133,63 +130,6 @@ describe("acpToolCallDiffPatch", () => {
].join("\n"),
);
});
-
- it("drops the patch for a rewrite too large to diff cheaply", () => {
- const lines = (prefix: string) =>
- Array.from({ length: 2_000 }, (_, index) => `${prefix} ${index}`).join("\n");
- assert.isUndefined(
- acpToolCallDiffPatch([
- { type: "diff", path: "/repo/big.ts", oldText: lines("old"), newText: lines("new") },
- ]),
- );
- });
-});
-
-describe("ACP continuation ownership", () => {
- it("preserves a continuation offered during non-buffered carryover handling", () => {
- assert.isFalse(
- acpCarryoverTerminalShouldClearContinuation({
- continuationOffered: true,
- wakeBufferLength: 0,
- }),
- );
- assert.isFalse(
- acpCarryoverTerminalShouldClearContinuation({
- continuationOffered: false,
- wakeBufferLength: 1,
- }),
- );
- assert.isTrue(
- acpCarryoverTerminalShouldClearContinuation({
- continuationOffered: false,
- wakeBufferLength: 0,
- }),
- );
- });
-
- it("preserves only user-raced offers that still own buffered wake traffic", () => {
- assert.isTrue(
- acpTurnStartShouldPreserveContinuation({
- continuationRequested: true,
- isContinuationTurn: false,
- wakeBufferLength: 1,
- }),
- );
- assert.isFalse(
- acpTurnStartShouldPreserveContinuation({
- continuationRequested: true,
- isContinuationTurn: false,
- wakeBufferLength: 0,
- }),
- );
- assert.isFalse(
- acpTurnStartShouldPreserveContinuation({
- continuationRequested: true,
- isContinuationTurn: true,
- wakeBufferLength: 1,
- }),
- );
- });
});
function makeMockRuntime(input: {
@@ -487,6 +427,7 @@ describe("AcpAdapterV2", () => {
],
}));
+ // regression: #20417 Droid AskUser answers were sent as a cancel
it.live.each([
{
scenario: "preserves selected IDs and encodes custom answers",
@@ -531,19 +472,6 @@ describe("AcpAdapterV2", () => {
answers: { name: "Ada" },
result: { action: "accept", content: { name: "Ada" } },
},
- {
- scenario: "falls back when the companion field is missing",
- schema: {
- type: "object",
- properties: { question_1: droidChoice },
- required: ["question_1"],
- },
- questions: [
- { id: "question_1", header: "Format", question: "Which reply format?", options: [] },
- ],
- answers: { question_1: "Markdown" },
- result: { action: "accept", content: { question_1: "Markdown" } },
- },
])("Droid elicitation $scenario", ({ schema, questions, answers, result, withAttachments }) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -719,7 +647,7 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
- it.live.each(["failed", "recovered", "completed", "cancelled"] as const)(
+ it.live.each(["failed", "recovered", "cancelled"] as const)(
"projects Mistral retry notices and their %s outcome",
(outcome) =>
Effect.gen(function* () {
@@ -806,18 +734,6 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
- it("preserves legacy ids and scopes v2 ids by provider instance", () => {
- const instanceId = ProviderInstanceId.make("acp-identity-test");
- assert.equal(
- acpProviderItemNativeId({ instanceId, itemIdentityVersion: undefined, nativeId: "item-1" }),
- "item-1",
- );
- assert.equal(
- acpProviderItemNativeId({ instanceId, itemIdentityVersion: 2, nativeId: "item-1" }),
- acpScopedNativeId(instanceId, "item-1"),
- );
- });
-
it.live("refreshes ACP prompt instructions when the interaction mode changes", () =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -1080,7 +996,8 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
- it.effect.each(["agent_message_chunk", "agent_thought_chunk"] as const)(
+ // regression: #21499 turns blocked only on T3 thread waits must show as waiting
+ it.effect.each(["agent_message_chunk"] as const)(
"keeps named ACP %s open while deriving thread wait execution state",
(sessionUpdate) =>
Effect.gen(function* () {
@@ -3162,158 +3079,6 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
- it.effect("keeps the original ACP session usable when a staged replacement terminates", () =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const path = yield* Path.Path;
- const selfInvocation = yield* resolveSelfInvocation();
- const mockAgentPath = yield* path.fromFileUrl(
- new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
- );
- let runtimeOrdinal = 0;
- const makeBaseRuntime = makeMockRuntime({
- childProcessSpawner,
- mockAgentPath,
- });
- const makeRuntime: AcpAdapterV2Flavor["makeRuntime"] = (runtimeInput) =>
- Effect.gen(function* () {
- const currentOrdinal = runtimeOrdinal + 1;
- runtimeOrdinal = currentOrdinal;
- const currentRuntime = yield* makeBaseRuntime(runtimeInput);
- if (currentOrdinal === 1) return currentRuntime;
- return {
- ...currentRuntime,
- start: () =>
- currentRuntime.start().pipe(
- Effect.tap(() =>
- runtimeInput.onTermination(
- new EffectAcpErrors.AcpTransportError({
- detail: "Forced staged rollback replacement termination",
- cause: "test",
- }),
- ),
- ),
- ),
- };
- });
- const instanceId = ProviderInstanceId.make("acp-test-rollback-failure-compensation");
- const adapter = yield* makeAcpAdapterV2({
- instanceId,
- flavor: {
- driver: ACP_TEST_DRIVER,
- capabilities: AcpProviderCapabilitiesV2,
- makeRuntime,
- },
- selfInvocation,
- });
- const threadId = ThreadId.make("thread-acp-rollback-failure-compensation");
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd: process.cwd(),
- });
- const modelSelection = { instanceId, model: "default" } as const;
- const runtime = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make(
- "provider-session-acp-rollback-failure-compensation",
- ),
- modelSelection,
- runtimePolicy,
- });
- const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
- yield* runtime.events.pipe(
- Stream.runForEach((event) => Queue.offer(events, event)),
- Effect.forkScoped,
- );
- const providerThread = yield* runtime.ensureThread({
- threadId,
- modelSelection,
- runtimePolicy,
- });
-
- const rollback = yield* runtime
- .rollbackThread({
- providerThread,
- providerThreadTurns: [],
- target: {
- type: "thread_start",
- checkpointId: CheckpointId.make("checkpoint-acp-rollback-failure-compensation"),
- appRunOrdinal: 0,
- },
- })
- .pipe(Effect.result);
- assert.equal(rollback._tag, "Failure");
-
- yield* runtime.startTurn(
- makeTurnInput({
- threadId,
- providerThread,
- instanceId,
- runtimePolicy,
- now: yield* DateTime.now,
- }),
- );
- const providerTurnId = idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(
- instanceId,
- `${providerThread.nativeThreadRef?.nativeId}:turn:1`,
- ),
- });
- while (true) {
- const event = yield* Queue.take(events);
- if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) {
- assert.equal(event.status, "completed");
- break;
- }
- }
- }).pipe(Effect.provide(layerTest), Effect.scoped),
- );
-
- it.effect("closes an idle ACP session exactly once through the transition permit", () =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const path = yield* Path.Path;
- const selfInvocation = yield* resolveSelfInvocation();
- const mockAgentPath = yield* path.fromFileUrl(
- new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
- );
- const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
- const instanceId = ProviderInstanceId.make("acp-test");
- const adapter = yield* makeAcpAdapterV2({
- instanceId,
- flavor: {
- driver: ACP_TEST_DRIVER,
- capabilities: AcpProviderCapabilitiesV2,
- makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, protocolEvents }),
- },
- selfInvocation,
- });
- const threadId = ThreadId.make("thread-acp-idle-finalizer");
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd: process.cwd(),
- });
- const modelSelection = { instanceId, model: "default" } as const;
- const sessionScope = yield* Scope.make();
- yield* adapter
- .openSession({
- threadId,
- providerSessionId: ProviderSessionId.make("provider-session-acp-idle-finalizer"),
- modelSelection,
- runtimePolicy,
- })
- .pipe(Effect.provideService(Scope.Scope, sessionScope));
- yield* pollProtocolMethods(protocolEvents);
- yield* Scope.close(sessionScope, Exit.void);
- const finalizerMethods = yield* pollProtocolMethods(protocolEvents);
- assert.equal(finalizerMethods.filter((method) => method === "session/close").length, 1);
- }).pipe(Effect.provide(layerTest)),
- );
-
it.effect("keeps an agent's empty-valued default choice selectable", () =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -4009,408 +3774,96 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
- it.live("rejects delayed native response registration when normal close wins the permit", () =>
+ it.live("treats a second hard Stop as success when the turn is already gone", () =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
const path = yield* Path.Path;
const selfInvocation = yield* resolveSelfInvocation();
const mockAgentPath = yield* path.fromFileUrl(
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
);
- const registrationStarted = yield* Deferred.make<void>();
- const releaseRegistration = yield* Deferred.make<void>();
- const transportClosed = yield* Deferred.make<void>();
- const releaseTransportClose = yield* Deferred.make<void>();
- const responseLifecycle: Array<string> = [];
- const instanceId = ProviderInstanceId.make("acp-test-close-wins-registration");
+ const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
+ const instanceId = ProviderInstanceId.make("acp-test");
const adapter = yield* makeAcpAdapterV2({
instanceId,
flavor: {
driver: ACP_TEST_DRIVER,
capabilities: AcpProviderCapabilitiesV2,
+ interruptPromptOnCancel: false,
+ restartRuntimeAfterInterrupt: true,
+ terminateRuntimeProcessGroupOnInterrupt: true,
makeRuntime: makeMockRuntime({
childProcessSpawner,
mockAgentPath,
- environment: { T3_ACP_EMIT_TOOL_CALLS: "1" },
+ ownDetachedProcessGroup: true,
+ environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" },
+ protocolEvents,
}),
},
selfInvocation,
- testHooks: {
- afterNativeResponseTransportClosed: () =>
- Deferred.succeed(transportClosed, undefined).pipe(
- Effect.andThen(Deferred.await(releaseTransportClose)),
- ),
- beforeNativeResponseAdmissionCheck: () =>
- Deferred.succeed(registrationStarted, undefined).pipe(
- Effect.andThen(Deferred.await(releaseRegistration)),
- ),
- onNativeResponseLifecycle: (event) =>
- Effect.sync(() => {
- responseLifecycle.push(event.type);
- }),
- },
});
- const threadId = ThreadId.make("thread-acp-close-wins-registration");
+ const threadId = ThreadId.make("thread-acp-double-stop");
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "approval-required",
+ runtimeMode: "full-access",
interactionMode: "default",
cwd: process.cwd(),
});
const modelSelection = { instanceId, model: "default" } as const;
- const sessionScope = yield* Scope.make();
- const runtime = yield* adapter
- .openSession({
- threadId,
- providerSessionId: ProviderSessionId.make("provider-session-acp-close-wins-registration"),
- modelSelection,
- runtimePolicy,
- })
- .pipe(Effect.provideService(Scope.Scope, sessionScope));
+ const runtime = yield* adapter.openSession({
+ threadId,
+ providerSessionId: ProviderSessionId.make("provider-session-acp-double-stop"),
+ modelSelection,
+ runtimePolicy,
+ });
+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
+ yield* runtime.events.pipe(
+ Stream.runForEach((event) => Queue.offer(events, event)),
+ Effect.forkScoped,
+ );
const providerThread = yield* runtime.ensureThread({
threadId,
modelSelection,
runtimePolicy,
});
- yield* runtime.startTurn(
- makeTurnInput({
- threadId,
+ const now = yield* DateTime.now;
+ yield* runtime
+ .startTurn(makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }))
+ .pipe(Effect.forkScoped);
+ yield* Stream.fromQueue(protocolEvents).pipe(
+ Stream.filter(
+ (event) =>
+ event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt",
+ ),
+ Stream.runHead,
+ );
+ const providerTurnId = idAllocator.derive.providerTurn({
+ driver: ACP_TEST_DRIVER,
+ nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
+ });
+ yield* runtime.interruptTurn({
+ providerThread,
+ providerTurnId,
+ requestRuntimeRestart: true,
+ });
+ const second = yield* Effect.exit(
+ runtime.interruptTurn({
providerThread,
- instanceId,
- runtimePolicy,
- now: yield* DateTime.now,
+ providerTurnId,
+ requestRuntimeRestart: true,
}),
);
- const pending = Option.getOrThrow(
- yield* runtime.events.pipe(
- Stream.filter(
- (event) =>
- event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
- ),
- Stream.runHead,
- ),
- );
- if (pending.type !== "runtime_request.updated") {
- return yield* Effect.die("Expected a pending permission request");
+ assert.isTrue(Exit.isSuccess(second), "duplicate hard Stop must be idempotent");
+ let terminal: string | null = null;
+ while (terminal === null) {
+ const event = yield* Queue.take(events);
+ if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) {
+ terminal = event.status;
+ }
}
- const responseFiber = yield* runtime
- .respondToRuntimeRequest({ requestId: pending.runtimeRequest.id, decision: "accept" })
- .pipe(Effect.exit, Effect.forkScoped);
- yield* Deferred.await(registrationStarted);
-
- const closeFiber = yield* Scope.close(sessionScope, Exit.void).pipe(Effect.forkScoped);
- yield* Deferred.await(transportClosed);
- yield* Deferred.succeed(releaseRegistration, undefined);
- while (!responseLifecycle.includes("admission_rejected")) {
- yield* Effect.yieldNow;
- }
- const responseExit = yield* Fiber.join(responseFiber);
- if (Exit.isSuccess(responseExit)) {
- assert.fail("normal close must reject a response delayed before transport registration");
- }
- assert.include(Cause.pretty(responseExit.cause), "ACP session transport closed");
- assert.equal(responseLifecycle.filter((event) => event === "registered").length, 1);
- assert.equal(responseLifecycle.filter((event) => event === "removed").length, 1);
- assert.equal(responseLifecycle.filter((event) => event === "admission_rejected").length, 1);
- yield* Deferred.succeed(releaseTransportClose, undefined);
- yield* Fiber.join(closeFiber);
- }).pipe(Effect.provide(layerTest), Effect.scoped),
- );
-
- it.live("waits for immediate allow and deny permission responses before hard teardown", () =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const path = yield* Path.Path;
- const selfInvocation = yield* resolveSelfInvocation();
- const mockAgentPath = yield* path.fromFileUrl(
- new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
- );
-
- for (const [name, sandboxPolicy] of [
- ["allow", undefined],
- ["deny", { type: "readOnly" } as const],
- ] as const) {
- yield* Effect.gen(function* () {
- const responseEnqueued = yield* Deferred.make<void>();
- const releaseResponseAcknowledgement = yield* Deferred.make<void>();
- const instanceId = ProviderInstanceId.make(`acp-test-${name}`);
- const adapter = yield* makeAcpAdapterV2({
- instanceId,
- flavor: {
- driver: ACP_TEST_DRIVER,
- capabilities: AcpProviderCapabilitiesV2,
- restartRuntimeAfterInterrupt: true,
- terminateRuntimeProcessGroupOnInterrupt: true,
- makeRuntime: makeMockRuntime({
- childProcessSpawner,
- mockAgentPath,
- environment: { T3_ACP_EMIT_TOOL_CALLS: "1" },
- ownDetachedProcessGroup: true,
- processGroupPlatform: "win32",
- windowsProcessTreeTerminator: (pid) =>
- Effect.sync(() => {
- process.kill(pid, "SIGTERM");
- }),
- wrapOutgoingResponse: (onOutgoingResponse) => (requestId) =>
- Deferred.succeed(responseEnqueued, undefined).pipe(
- Effect.andThen(Deferred.await(releaseResponseAcknowledgement)),
- Effect.andThen(onOutgoingResponse(requestId)),
- ),
- }),
- },
- selfInvocation,
- });
- const threadId = ThreadId.make(`thread-acp-immediate-permission-${name}`);
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- approvalPolicy: "never",
- cwd: process.cwd(),
- ...(sandboxPolicy === undefined ? {} : { sandboxPolicy }),
- });
- const modelSelection = { instanceId, model: "default" } as const;
- const runtime = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make(
- `provider-session-acp-immediate-permission-${name}`,
- ),
- modelSelection,
- runtimePolicy,
- });
- const providerThread = yield* runtime.ensureThread({
- threadId,
- modelSelection,
- runtimePolicy,
- });
- const turnFiber = yield* runtime
- .startTurn(
- makeTurnInput({
- threadId,
- providerThread,
- instanceId,
- runtimePolicy,
- now: yield* DateTime.now,
- }),
- )
- .pipe(Effect.forkDetach);
- yield* Deferred.await(responseEnqueued);
- const interruptFiber = yield* runtime
- .interruptTurn({
- providerThread,
- providerTurnId: idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
- }),
- requestRuntimeRestart: true,
- })
- .pipe(Effect.forkScoped);
- yield* Effect.yieldNow;
- assert.isUndefined(interruptFiber.pollUnsafe());
-
- yield* Deferred.succeed(releaseResponseAcknowledgement, undefined);
- yield* Fiber.join(interruptFiber);
- yield* Fiber.interrupt(turnFiber).pipe(Effect.forkDetach);
- }).pipe(Effect.scoped);
- }
- }).pipe(Effect.provide(layerTest), Effect.scoped),
- );
-
- it.live("rejects an elicitation response when hard teardown wins admission", () =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const path = yield* Path.Path;
- const selfInvocation = yield* resolveSelfInvocation();
- const mockAgentPath = yield* path.fromFileUrl(
- new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
- );
- const teardownStarted = yield* Deferred.make<void>();
- const releaseTeardown = yield* Deferred.make<void>();
- const instanceId = ProviderInstanceId.make("acp-test");
- const adapter = yield* makeAcpAdapterV2({
- instanceId,
- flavor: {
- driver: ACP_TEST_DRIVER,
- capabilities: AcpProviderCapabilitiesV2,
- restartRuntimeAfterInterrupt: true,
- terminateRuntimeProcessGroupOnInterrupt: true,
- makeRuntime: makeMockRuntime({
- childProcessSpawner,
- mockAgentPath,
- environment: { T3_ACP_EMIT_ELICITATION: "1" },
- ownDetachedProcessGroup: true,
- processGroupPlatform: "win32",
- windowsProcessTreeTerminator: (pid) =>
- Deferred.succeed(teardownStarted, undefined).pipe(
- Effect.andThen(Deferred.await(releaseTeardown)),
- Effect.andThen(
- Effect.sync(() => {
- process.kill(pid, "SIGTERM");
- }),
- ),
- ),
- }),
- },
- selfInvocation,
- });
- const threadId = ThreadId.make("thread-acp-teardown-wins-elicitation");
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "approval-required",
- interactionMode: "default",
- cwd: process.cwd(),
- });
- const modelSelection = { instanceId, model: "default" } as const;
- const runtime = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make("provider-session-acp-teardown-wins-elicitation"),
- modelSelection,
- runtimePolicy,
- });
- const providerThread = yield* runtime.ensureThread({
- threadId,
- modelSelection,
- runtimePolicy,
- });
- yield* runtime.startTurn(
- makeTurnInput({
- threadId,
- providerThread,
- instanceId,
- runtimePolicy,
- now: yield* DateTime.now,
- }),
- );
- const pending = Option.getOrThrow(
- yield* runtime.events.pipe(
- Stream.filter(
- (event) =>
- event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
- ),
- Stream.runHead,
- ),
- );
- if (
- pending.type !== "runtime_request.updated" ||
- pending.runtimeRequest.providerTurnId === null
- ) {
- return yield* Effect.die("Expected a pending elicitation request");
- }
- const interruptFiber = yield* runtime
- .interruptTurn({
- providerThread,
- providerTurnId: pending.runtimeRequest.providerTurnId,
- requestRuntimeRestart: true,
- })
- .pipe(Effect.forkScoped);
- yield* Deferred.await(teardownStarted);
- const responseFiber = yield* runtime
- .respondToRuntimeRequest({
- requestId: pending.runtimeRequest.id,
- answers: { approved: ["true"] },
- })
- .pipe(Effect.exit, Effect.forkScoped);
- yield* Effect.yieldNow;
- assert.isUndefined(responseFiber.pollUnsafe());
-
- yield* Deferred.succeed(releaseTeardown, undefined);
- yield* Fiber.join(interruptFiber);
- const responseExit = yield* Fiber.join(responseFiber);
- if (Exit.isSuccess(responseExit)) {
- assert.fail("teardown winning admission must reject the elicitation response");
- }
- assert.include(Cause.pretty(responseExit.cause), "No pending ACP runtime request");
- }).pipe(Effect.provide(layerTest), Effect.scoped),
- );
-
- it.live("treats a second hard Stop as success when the turn is already gone", () =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const path = yield* Path.Path;
- const selfInvocation = yield* resolveSelfInvocation();
- const mockAgentPath = yield* path.fromFileUrl(
- new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
- );
- const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
- const instanceId = ProviderInstanceId.make("acp-test");
- const adapter = yield* makeAcpAdapterV2({
- instanceId,
- flavor: {
- driver: ACP_TEST_DRIVER,
- capabilities: AcpProviderCapabilitiesV2,
- interruptPromptOnCancel: false,
- restartRuntimeAfterInterrupt: true,
- terminateRuntimeProcessGroupOnInterrupt: true,
- makeRuntime: makeMockRuntime({
- childProcessSpawner,
- mockAgentPath,
- ownDetachedProcessGroup: true,
- environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" },
- protocolEvents,
- }),
- },
- selfInvocation,
- });
- const threadId = ThreadId.make("thread-acp-double-stop");
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd: process.cwd(),
- });
- const modelSelection = { instanceId, model: "default" } as const;
- const runtime = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make("provider-session-acp-double-stop"),
- modelSelection,
- runtimePolicy,
- });
- const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
- yield* runtime.events.pipe(
- Stream.runForEach((event) => Queue.offer(events, event)),
- Effect.forkScoped,
- );
- const providerThread = yield* runtime.ensureThread({
- threadId,
- modelSelection,
- runtimePolicy,
- });
- const now = yield* DateTime.now;
- yield* runtime
- .startTurn(makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }))
- .pipe(Effect.forkScoped);
- yield* Stream.fromQueue(protocolEvents).pipe(
- Stream.filter(
- (event) =>
- event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt",
- ),
- Stream.runHead,
- );
- const providerTurnId = idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
- });
- yield* runtime.interruptTurn({
- providerThread,
- providerTurnId,
- requestRuntimeRestart: true,
- });
- const second = yield* Effect.exit(
- runtime.interruptTurn({
- providerThread,
- providerTurnId,
- requestRuntimeRestart: true,
- }),
- );
- assert.isTrue(Exit.isSuccess(second), "duplicate hard Stop must be idempotent");
- let terminal: string | null = null;
- while (terminal === null) {
- const event = yield* Queue.take(events);
- if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) {
- terminal = event.status;
- }
- }
- assert.equal(terminal, "interrupted");
- }).pipe(Effect.provide(layerTest), Effect.scoped),
- );
+ assert.equal(terminal, "interrupted");
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
+ );
it.effect("finalizes a settled turn held open for background work when interrupted", () =>
Effect.gen(function* () {
@@ -4638,230 +4091,6 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
- it.effect("handles a child terminal after carryover rehydrate", () =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const path = yield* Path.Path;
- const selfInvocation = yield* resolveSelfInvocation();
- const mockAgentPath = yield* path.fromFileUrl(
- new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
- );
- const secondPromptWireReturned = yield* Deferred.make<void>();
- const releaseSecondPromptCompletion = yield* Deferred.make<void>();
- const instanceId = ProviderInstanceId.make("acp-test");
- const childSessionId = "mock-child-session-active-carryover";
- let promptCount = 0;
- let subagentPhase: "spawn" | "complete" = "spawn";
- type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
- let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
- const promptSettled = yield* Deferred.make<void>();
- const adapter = yield* makeAcpAdapterV2({
- testHooks: {
- afterPromptSettledWithBackgroundWork: () =>
- Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid),
- },
- instanceId,
- flavor: {
- driver: ACP_TEST_DRIVER,
- capabilities: AcpProviderCapabilitiesV2,
- deferFinalizeForBackgroundWork: true,
- enablePostSettleContinuation: true,
- extractSubagentUpdate: (toolCall) =>
- toolCall.toolCallId !== "tool-call-generic-1"
- ? undefined
- : subagentPhase === "spawn"
- ? {
- nativeTaskId: "task-generic-1",
- prompt: "background subagent",
- title: "background subagent",
- model: null,
- status: "running",
- childSessionId,
- result: null,
- }
- : {
- nativeTaskId: "task-generic-1",
- prompt: "",
- title: null,
- model: null,
- status: "completed",
- childSessionId,
- result: "SUB_DONE",
- },
- makeRuntime: makeMockRuntime({
- childProcessSpawner,
- mockAgentPath,
- environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" },
- wrapRuntime: (runtime) => ({
- ...runtime,
- handleSessionUpdate: (handler) =>
- Effect.sync(() => {
- sessionUpdateHandler = handler;
- }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
- prompt: (payload) =>
- Effect.gen(function* () {
- const currentPrompt = ++promptCount;
- const result = yield* runtime.prompt(payload);
- if (currentPrompt === 2) {
- yield* Deferred.succeed(secondPromptWireReturned, undefined);
- yield* Deferred.await(releaseSecondPromptCompletion);
- }
- return result;
- }),
- }),
- }),
- },
- selfInvocation,
- continuationRequests: { offer: () => Effect.void },
- });
- const threadId = ThreadId.make("thread-acp-active-carryover-pending-pin");
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd: process.cwd(),
- });
- const modelSelection = { instanceId, model: "default" } as const;
- const runtime = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make(
- "provider-session-acp-active-carryover-pending-pin",
- ),
- modelSelection,
- runtimePolicy,
- });
- if (runtime.hasPendingBackgroundWork === undefined) {
- return yield* Effect.die(
- "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.",
- );
- }
- const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
- const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
- yield* runtime.events.pipe(
- Stream.runForEach((event) => Queue.offer(events, event)),
- Effect.forkScoped,
- );
- const providerThread = yield* runtime.ensureThread({
- threadId,
- modelSelection,
- runtimePolicy,
- });
- const now = yield* DateTime.now;
- yield* runtime.startTurn(
- makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }),
- );
- yield* Deferred.await(promptSettled);
-
- const firstProviderTurnId = idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
- });
- yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId });
-
- let firstTerminalStatus: string | null = null;
- while (firstTerminalStatus === null) {
- const event = yield* Queue.take(events);
- if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) {
- firstTerminalStatus = event.status;
- }
- }
- assert.equal(firstTerminalStatus, "interrupted");
- assert.isTrue(yield* hasPendingBackgroundWork);
- assert.isDefined(sessionUpdateHandler, "session update handler must be wired");
-
- const secondNow = yield* DateTime.now;
- const secondTurnFiber = yield* runtime
- .startTurn(
- makeTurnInput({
- threadId,
- providerThread,
- instanceId,
- runtimePolicy,
- now: secondNow,
- ordinal: 2,
- }),
- )
- .pipe(Effect.forkScoped);
- yield* Deferred.await(secondPromptWireReturned);
- assert.isTrue(
- yield* hasPendingBackgroundWork,
- "rehydrated live subagent must pin from activeTurn",
- );
- while (Option.isSome(yield* Queue.poll(events))) {}
-
- subagentPhase = "complete";
- yield* sessionUpdateHandler!({
- sessionId: childSessionId,
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: "tool-call-generic-1",
- title: "background subagent",
- kind: "other",
- status: "completed",
- rawOutput: { content: "SUB_DONE" },
- },
- });
- yield* sessionUpdateHandler!({
- sessionId: childSessionId,
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: "tool-call-generic-1",
- title: "background subagent",
- kind: "other",
- status: "completed",
- rawOutput: { content: "SUB_DONE" },
- },
- });
- subagentPhase = "spawn";
- yield* sessionUpdateHandler!({
- sessionId: childSessionId,
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: "tool-call-generic-1",
- title: "background subagent",
- kind: "other",
- status: "in_progress",
- rawOutput: {},
- },
- });
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
- assert.isFalse(
- yield* hasPendingBackgroundWork,
- "active-turn pin must clear after the child-session terminal is projected",
- );
- let completedSubagentUpdates = 0;
- let resurrectedSubagentUpdates = 0;
- let normalChildToolUpdates = 0;
- let polled = yield* Queue.poll(events);
- while (Option.isSome(polled)) {
- const event = polled.value;
- if (event.type === "turn_item.updated") {
- if (event.turnItem.type === "subagent") {
- if (event.turnItem.status === "completed") {
- completedSubagentUpdates += 1;
- }
- if (
- event.turnItem.status === "running" &&
- event.turnItem.nativeItemRef?.nativeId === "task-generic-1"
- ) {
- resurrectedSubagentUpdates += 1;
- }
- } else if (event.turnItem.nativeItemRef?.nativeId === "tool-call-generic-1") {
- normalChildToolUpdates += 1;
- }
- }
- polled = yield* Queue.poll(events);
- }
- assert.equal(completedSubagentUpdates, 1);
- assert.equal(resurrectedSubagentUpdates, 0);
- assert.equal(normalChildToolUpdates, 0);
-
- yield* Deferred.succeed(releaseSecondPromptCompletion, undefined);
- yield* Fiber.join(secondTurnFiber);
- }).pipe(Effect.provide(layerTest), Effect.scoped),
- );
-
it.effect(
"projects a child terminal in the completed-root finalization window exactly once",
() =>
@@ -5075,357 +4304,6 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
- it.effect(
- "defers an interrupted pending-spawn carryover terminal until the next observable attach",
- () =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const path = yield* Path.Path;
- const selfInvocation = yield* resolveSelfInvocation();
- const mockAgentPath = yield* path.fromFileUrl(
- new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
- );
- const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
- const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
- [];
- const promptSettled = yield* Deferred.make<void>();
- const instanceId = ProviderInstanceId.make("acp-test");
- const childSessionId = "mock-child-session-post-settle";
- let subagentPhase: "spawn" | "complete" = "spawn";
- type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
- let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
- const adapter = yield* makeAcpAdapterV2({
- testHooks: {
- afterPromptSettledWithBackgroundWork: () =>
- Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid),
- },
- instanceId,
- flavor: {
- driver: ACP_TEST_DRIVER,
- capabilities: AcpProviderCapabilitiesV2,
- deferFinalizeForBackgroundWork: true,
- enablePostSettleContinuation: true,
- extractSubagentUpdate: (toolCall) =>
- toolCall.toolCallId !== "tool-call-generic-1"
- ? undefined
- : subagentPhase === "spawn"
- ? {
- nativeTaskId: "task-generic-1",
- prompt: "background subagent",
- title: "background subagent",
- model: null,
- status: "pending",
- childSessionId,
- result: null,
- }
- : {
- nativeTaskId: "task-generic-1",
- prompt: "",
- title: null,
- model: null,
- status: "completed",
- childSessionId,
- result: "SUB_DONE",
- },
- makeRuntime: makeMockRuntime({
- childProcessSpawner,
- mockAgentPath,
- environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" },
- protocolEvents,
- wrapRuntime: (runtime) => ({
- ...runtime,
- handleSessionUpdate: (handler) =>
- Effect.sync(() => {
- sessionUpdateHandler = handler;
- }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
- }),
- }),
- },
- selfInvocation,
- continuationRequests: {
- offer: (request) =>
- Effect.sync(() => {
- continuationRequests.push(request);
- }),
- },
- });
- const threadId = ThreadId.make("thread-acp-carryover-child-session-post-settle");
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd: process.cwd(),
- });
- const modelSelection = { instanceId, model: "default" } as const;
- const runtime = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make(
- "provider-session-acp-carryover-child-session-post-settle",
- ),
- modelSelection,
- runtimePolicy,
- });
- if (runtime.hasPendingBackgroundWork === undefined) {
- return yield* Effect.die(
- "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.",
- );
- }
- const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
- const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
- yield* runtime.events.pipe(
- Stream.runForEach((event) => Queue.offer(events, event)),
- Effect.forkScoped,
- );
- const providerThread = yield* runtime.ensureThread({
- threadId,
- modelSelection,
- runtimePolicy,
- });
- const now = yield* DateTime.now;
- yield* runtime.startTurn(
- makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }),
- );
- yield* Deferred.await(promptSettled);
-
- const firstProviderTurnId = idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
- });
- yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId });
-
- let firstTerminalStatus: string | null = null;
- while (firstTerminalStatus === null) {
- const event = yield* Queue.take(events);
- if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) {
- firstTerminalStatus = event.status;
- }
- }
- assert.equal(firstTerminalStatus, "interrupted");
- assert.isTrue(
- yield* hasPendingBackgroundWork,
- "carryover live subagent must pin hasPendingBackgroundWork after root settle",
- );
- assert.isDefined(sessionUpdateHandler, "session update handler must be wired");
-
- subagentPhase = "complete";
- yield* sessionUpdateHandler!({
- sessionId: childSessionId,
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: "tool-call-generic-1",
- title: "background subagent",
- kind: "other",
- status: "completed",
- rawOutput: { content: "SUB_DONE" },
- },
- });
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
- let completedBeforeAttach = 0;
- let polled = yield* Queue.poll(events);
- while (Option.isSome(polled)) {
- const event = polled.value;
- if (
- event.type === "turn_item.updated" &&
- event.turnItem.type === "subagent" &&
- event.turnItem.status === "completed"
- ) {
- completedBeforeAttach += 1;
- }
- polled = yield* Queue.poll(events);
- }
- assert.equal(
- completedBeforeAttach,
- 0,
- "closed interrupted subscription must not be treated as projected",
- );
- assert.isTrue(
- yield* hasPendingBackgroundWork,
- "terminal carryover must stay pinned until an attach can project it",
- );
- assert.lengthOf(
- continuationRequests,
- 0,
- "child-session completion must not open a root continuation",
- );
-
- const attachNow = yield* DateTime.now;
- yield* runtime.startTurn(
- makeTurnInput({
- threadId,
- providerThread,
- instanceId,
- runtimePolicy,
- now: attachNow,
- ordinal: 2,
- messageCreatedBy: "agent",
- messageCreationSource: "provider",
- messageText: "Attach deferred completion.",
- }),
- );
- const attachProviderTurnId = idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"),
- });
- let attachTerminal: string | null = null;
- let completedAfterAttach = 0;
- while (attachTerminal === null) {
- const event = yield* Queue.take(events);
- if (
- event.type === "turn_item.updated" &&
- event.turnItem.type === "subagent" &&
- event.turnItem.status === "completed"
- ) {
- completedAfterAttach += 1;
- }
- if (event.type === "turn.terminal" && event.providerTurnId === attachProviderTurnId) {
- attachTerminal = event.status;
- }
- }
- assert.equal(attachTerminal, "completed");
- assert.equal(completedAfterAttach, 1);
- assert.isFalse(yield* hasPendingBackgroundWork);
- }).pipe(Effect.provide(layerTest), Effect.scoped),
- );
-
- it.effect("finishes a settled root's carryover subagent from its structured end", () =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const path = yield* Path.Path;
- const selfInvocation = yield* resolveSelfInvocation();
- const mockAgentPath = yield* path.fromFileUrl(
- new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
- );
- const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
- const instanceId = ProviderInstanceId.make("acp-test");
- const childSessionId = "019f44a6-4820-7402-925d-bc862ee711dd";
- let finishSubagent: AcpAdapterV2ExtensionContext["finishSubagent"] | undefined;
- const adapter = yield* makeAcpAdapterV2({
- instanceId,
- flavor: {
- driver: ACP_TEST_DRIVER,
- capabilities: AcpProviderCapabilitiesV2,
- enablePostSettleContinuation: true,
- extractSubagentUpdate: (toolCall) =>
- toolCall.toolCallId !== "tool-call-generic-1"
- ? undefined
- : {
- nativeTaskId: "task-generic-1",
- prompt: "background subagent",
- title: "background subagent",
- model: null,
- status: "running",
- childSessionId,
- result: null,
- },
- registerExtensions: (context) =>
- Effect.sync(() => {
- finishSubagent = context.finishSubagent;
- }),
- makeRuntime: makeMockRuntime({
- childProcessSpawner,
- mockAgentPath,
- environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" },
- protocolEvents,
- }),
- },
- selfInvocation,
- continuationRequests: { offer: () => Effect.void },
- });
- const threadId = ThreadId.make("thread-acp-carryover-subagent-finished");
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd: process.cwd(),
- });
- const modelSelection = { instanceId, model: "default" } as const;
- const runtime = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make("provider-session-acp-carryover-finished"),
- modelSelection,
- runtimePolicy,
- });
- if (runtime.hasPendingBackgroundWork === undefined) {
- return yield* Effect.die("post-settle continuation must expose hasPendingBackgroundWork");
- }
- const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
- const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
- yield* runtime.events.pipe(
- Stream.runForEach((event) => Queue.offer(events, event)),
- Effect.forkScoped,
- );
- const providerThread = yield* runtime.ensureThread({
- threadId,
- modelSelection,
- runtimePolicy,
- });
- yield* runtime.startTurn(
- makeTurnInput({
- threadId,
- providerThread,
- instanceId,
- runtimePolicy,
- now: yield* DateTime.now,
- }),
- );
- const providerTurnId = idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
- });
- let rootStatus: string | null = null;
- while (rootStatus === null) {
- const event = yield* Queue.take(events);
- if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) {
- rootStatus = event.status;
- }
- }
- assert.equal(rootStatus, "completed");
- assert.isTrue(yield* hasPendingBackgroundWork);
- assert.isDefined(finishSubagent);
- const subagentStatuses = Effect.gen(function* () {
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
- const statuses: Array<[string, string | null]> = [];
- let polled = yield* Queue.poll(events);
- while (Option.isSome(polled)) {
- const event = polled.value;
- if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") {
- statuses.push([event.turnItem.status, event.turnItem.result]);
- }
- polled = yield* Queue.poll(events);
- }
- return statuses;
- });
- yield* subagentStatuses;
-
- yield* finishSubagent!({
- sessionId: "some-other-session",
- childSessionId,
- status: "completed",
- result: "WRONG_PARENT",
- });
- assert.deepEqual(yield* subagentStatuses, [], "non-root notices must be dropped");
- assert.isTrue(yield* hasPendingBackgroundWork);
-
- yield* finishSubagent!({
- sessionId: "mock-session-1",
- childSessionId,
- status: "failed",
- result: "tool crashed",
- });
- assert.deepEqual(
- yield* subagentStatuses,
- [["failed", "tool crashed"]],
- "the completed root still owns the run, so the carryover end projects at once",
- );
- assert.isFalse(
- yield* hasPendingBackgroundWork,
- "a finished carryover subagent stops pinning",
- );
- }).pipe(Effect.provide(layerTest), Effect.scoped),
- );
-
it.effect("projects completed-root carryover eagerly and drain cannot resurrect it", () =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -5647,572 +4525,29 @@ describe("AcpAdapterV2", () => {
}
if (
event.type === "turn_item.updated" &&
- event.turnItem.runId === continuationInput.runId
- ) {
- replayedTurnItems += 1;
- }
- polled = yield* Queue.poll(events);
- }
- assert.equal(replayedLineages, 0, "buffered spawn ACK must not create a second lineage");
- assert.equal(
- replayedSubagentUpdates,
- 0,
- "buffered spawn ACK must not re-open the terminal subagent",
- );
- assert.equal(
- replayedTurnItems,
- 0,
- "buffered spawn ACK must not create a continuation-owned turn item",
- );
- assert.isFalse(yield* hasPendingBackgroundWork);
- }).pipe(Effect.provide(layerTest), Effect.scoped),
- );
-
- it.effect(
- "user attach flushes a deferred terminal but leaves wake traffic for its continuation",
- () =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const path = yield* Path.Path;
- const selfInvocation = yield* resolveSelfInvocation();
- const mockAgentPath = yield* path.fromFileUrl(
- new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
- );
- const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
- [];
- const bufferedAssistantText = "BUFFERED_WAKE_AFTER_USER_ATTACH";
- const instanceId = ProviderInstanceId.make("acp-test");
- let subagentPhase: "spawn" | "complete" = "spawn";
- type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
- let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
- const promptSettled = yield* Deferred.make<void>();
- const adapter = yield* makeAcpAdapterV2({
- testHooks: {
- afterPromptSettledWithBackgroundWork: () =>
- Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid),
- },
- instanceId,
- flavor: {
- driver: ACP_TEST_DRIVER,
- capabilities: AcpProviderCapabilitiesV2,
- deferFinalizeForBackgroundWork: true,
- enablePostSettleContinuation: true,
- extractSubagentUpdate: (toolCall) =>
- toolCall.toolCallId !== "tool-call-generic-1"
- ? undefined
- : subagentPhase === "spawn"
- ? {
- nativeTaskId: "task-generic-1",
- prompt: "background subagent",
- title: "background subagent",
- model: null,
- status: "running",
- childSessionId: null,
- result: null,
- }
- : {
- nativeTaskId: "task-generic-1",
- prompt: "",
- title: null,
- model: null,
- status: "completed",
- childSessionId: null,
- result: "SUB_DONE",
- },
- makeRuntime: makeMockRuntime({
- childProcessSpawner,
- mockAgentPath,
- environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" },
- wrapRuntime: (runtime) => ({
- ...runtime,
- handleSessionUpdate: (handler) =>
- Effect.sync(() => {
- sessionUpdateHandler = handler;
- }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
- }),
- }),
- },
- selfInvocation,
- continuationRequests: {
- offer: (request) =>
- Effect.sync(() => {
- continuationRequests.push(request);
- }),
- },
- });
- const threadId = ThreadId.make("thread-acp-carryover-root-session-continuation");
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd: process.cwd(),
- });
- const modelSelection = { instanceId, model: "default" } as const;
- const runtime = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make(
- "provider-session-acp-carryover-root-session-continuation",
- ),
- modelSelection,
- runtimePolicy,
- });
- if (runtime.hasPendingBackgroundWork === undefined) {
- return yield* Effect.die(
- "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.",
- );
- }
- const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
- const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
- yield* runtime.events.pipe(
- Stream.runForEach((event) => Queue.offer(events, event)),
- Effect.forkScoped,
- );
- const providerThread = yield* runtime.ensureThread({
- threadId,
- modelSelection,
- runtimePolicy,
- });
- const now = yield* DateTime.now;
- yield* runtime.startTurn(
- makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }),
- );
- yield* Deferred.await(promptSettled);
-
- const firstProviderTurnId = idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
- });
- yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId });
-
- let firstTerminalStatus: string | null = null;
- while (firstTerminalStatus === null) {
- const event = yield* Queue.take(events);
- if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) {
- firstTerminalStatus = event.status;
- }
- }
- assert.equal(firstTerminalStatus, "interrupted");
- assert.isTrue(
- yield* hasPendingBackgroundWork,
- "carryover live subagent must pin hasPendingBackgroundWork after root settle",
- );
- assert.isDefined(sessionUpdateHandler, "session update handler must be wired");
-
- subagentPhase = "complete";
- yield* sessionUpdateHandler!({
- sessionId: "mock-session-1",
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: "tool-call-generic-1",
- title: "background subagent",
- kind: "other",
- status: "completed",
- rawOutput: { content: "SUB_DONE" },
- },
- });
- yield* sessionUpdateHandler!({
- sessionId: "mock-session-1",
- update: {
- sessionUpdate: "agent_message_chunk",
- content: { type: "text", text: bufferedAssistantText },
- },
- });
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
-
- let completedBeforeDrain = 0;
- let polled = yield* Queue.poll(events);
- while (Option.isSome(polled)) {
- const event = polled.value;
- if (
- event.type === "turn_item.updated" &&
- event.turnItem.type === "subagent" &&
- event.turnItem.status === "completed"
- ) {
- completedBeforeDrain += 1;
- }
- polled = yield* Queue.poll(events);
- }
- assert.equal(
- completedBeforeDrain,
- 0,
- "interrupted root-session terminal must wait for an observable attach",
- );
- assert.lengthOf(
- continuationRequests,
- 1,
- "root-session post-settle subagent terminal must offer a continuation",
- );
- assert.isTrue(
- yield* hasPendingBackgroundWork,
- "interrupted unprojected terminal must pin hasPendingBackgroundWork until attach",
- );
-
- const userTurnNow = yield* DateTime.now;
- yield* runtime.startTurn(
- makeTurnInput({
- threadId,
- providerThread,
- instanceId,
- runtimePolicy,
- now: userTurnNow,
- ordinal: 2,
- messageText: "What finished while the prior turn was settling?",
- }),
- );
- yield* TestClock.adjust("3 seconds");
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
-
- const userProviderTurnId = idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"),
- });
- let userTurnTerminal: string | null = null;
- let completedSubagentTurnItems = 0;
- let bufferedTextSeenInUserTurn = false;
- while (userTurnTerminal === null) {
- const event = yield* Queue.take(events);
- if (
- event.type === "turn_item.updated" &&
- event.turnItem.type === "subagent" &&
- event.turnItem.status === "completed"
- ) {
- completedSubagentTurnItems += 1;
- }
- if (
- event.type === "message.updated" &&
- event.message.role === "assistant" &&
- event.message.text.includes(bufferedAssistantText)
- ) {
- bufferedTextSeenInUserTurn = true;
- }
- if (event.type === "turn.terminal" && event.providerTurnId === userProviderTurnId) {
- userTurnTerminal = event.status;
- }
- }
- assert.equal(userTurnTerminal, "completed");
- assert.equal(
- completedSubagentTurnItems,
- 1,
- "user attach must project the deferred terminal subagent turn item once",
- );
- assert.isFalse(bufferedTextSeenInUserTurn, "user attach must not drain wake traffic");
- assert.isTrue(
- yield* hasPendingBackgroundWork,
- "wake traffic must remain pinned for the already-dispatched continuation",
- );
-
- const continuationNow = yield* DateTime.now;
- yield* runtime.startTurn(
- makeTurnInput({
- threadId,
- providerThread,
- instanceId,
- runtimePolicy,
- now: continuationNow,
- ordinal: 3,
- messageCreatedBy: "agent",
- messageCreationSource: "provider",
- messageText: "Background task completed.",
- }),
- );
- yield* TestClock.adjust("3 seconds");
- const continuationProviderTurnId = idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:3"),
- });
- let continuationTerminal: string | null = null;
- let bufferedTextSeenInContinuation = false;
- while (continuationTerminal === null) {
- const event = yield* Queue.take(events);
- if (
- event.type === "message.updated" &&
- event.message.role === "assistant" &&
- event.message.text.includes(bufferedAssistantText)
- ) {
- bufferedTextSeenInContinuation = true;
- }
- if (
- event.type === "turn.terminal" &&
- event.providerTurnId === continuationProviderTurnId
- ) {
- continuationTerminal = event.status;
- }
- }
- assert.equal(continuationTerminal, "completed");
- assert.isTrue(
- bufferedTextSeenInContinuation,
- "queued continuation must drain the wake content after the user run",
- );
- assert.isFalse(yield* hasPendingBackgroundWork);
- }).pipe(Effect.provide(layerTest), Effect.scoped),
- );
-
- it.effect(
- "preserves wakeBuffer when a child-session completes while a continuation is pending",
- () =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const path = yield* Path.Path;
- const selfInvocation = yield* resolveSelfInvocation();
- const mockAgentPath = yield* path.fromFileUrl(
- new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
- );
- const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
- [];
- const instanceId = ProviderInstanceId.make("acp-test");
- const childSessionId = "mock-child-session-pending-continuation";
- const bufferedAssistantText = "POST_SETTLE_BUFFERED_ASSISTANT_TEXT";
- let subagentPhase: "spawn" | "complete" = "spawn";
- type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
- let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
- const promptSettled = yield* Deferred.make<void>();
- const adapter = yield* makeAcpAdapterV2({
- testHooks: {
- afterPromptSettledWithBackgroundWork: () =>
- Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid),
- },
- instanceId,
- flavor: {
- driver: ACP_TEST_DRIVER,
- capabilities: AcpProviderCapabilitiesV2,
- deferFinalizeForBackgroundWork: true,
- enablePostSettleContinuation: true,
- extractSubagentUpdate: (toolCall) =>
- toolCall.toolCallId !== "tool-call-generic-1"
- ? undefined
- : subagentPhase === "spawn"
- ? {
- nativeTaskId: "task-generic-1",
- prompt: "background subagent",
- title: "background subagent",
- model: null,
- status: "running",
- childSessionId,
- result: null,
- }
- : {
- nativeTaskId: "task-generic-1",
- prompt: "",
- title: null,
- model: null,
- status: "completed",
- childSessionId,
- result: "SUB_DONE",
- },
- makeRuntime: makeMockRuntime({
- childProcessSpawner,
- mockAgentPath,
- environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" },
- wrapRuntime: (runtime) => ({
- ...runtime,
- handleSessionUpdate: (handler) =>
- Effect.sync(() => {
- sessionUpdateHandler = handler;
- }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
- }),
- }),
- },
- selfInvocation,
- continuationRequests: {
- offer: (request) =>
- Effect.sync(() => {
- continuationRequests.push(request);
- }),
- },
- });
- const threadId = ThreadId.make("thread-acp-carryover-child-pending-continuation");
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd: process.cwd(),
- });
- const modelSelection = { instanceId, model: "default" } as const;
- const runtime = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make(
- "provider-session-acp-carryover-child-pending-continuation",
- ),
- modelSelection,
- runtimePolicy,
- });
- if (runtime.hasPendingBackgroundWork === undefined) {
- return yield* Effect.die(
- "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.",
- );
- }
- const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
- const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
- yield* runtime.events.pipe(
- Stream.runForEach((event) => Queue.offer(events, event)),
- Effect.forkScoped,
- );
- const providerThread = yield* runtime.ensureThread({
- threadId,
- modelSelection,
- runtimePolicy,
- });
- const now = yield* DateTime.now;
- yield* runtime.startTurn(
- makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }),
- );
- yield* Deferred.await(promptSettled);
-
- const firstProviderTurnId = idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
- });
- yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId });
-
- let firstTerminalStatus: string | null = null;
- while (firstTerminalStatus === null) {
- const event = yield* Queue.take(events);
- if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) {
- firstTerminalStatus = event.status;
- }
- }
- assert.equal(firstTerminalStatus, "interrupted");
- assert.isTrue(
- yield* hasPendingBackgroundWork,
- "carryover live subagent must pin hasPendingBackgroundWork after root settle",
- );
- assert.isDefined(sessionUpdateHandler, "session update handler must be wired");
-
- subagentPhase = "complete";
- yield* sessionUpdateHandler!({
- sessionId: "mock-session-1",
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: "tool-call-generic-1",
- title: "background subagent",
- kind: "other",
- status: "completed",
- rawOutput: { content: "SUB_DONE" },
- },
- });
- yield* sessionUpdateHandler!({
- sessionId: "mock-session-1",
- update: {
- sessionUpdate: "agent_message_chunk",
- content: { type: "text", text: bufferedAssistantText },
- },
- });
- assert.lengthOf(
- continuationRequests,
- 1,
- "root-session terminal must offer a continuation before child completion",
- );
- assert.isTrue(
- yield* hasPendingBackgroundWork,
- "pending continuation must keep hasPendingBackgroundWork pinned",
- );
-
- yield* sessionUpdateHandler!({
- sessionId: childSessionId,
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: "tool-call-generic-1",
- title: "background subagent",
- kind: "other",
- status: "completed",
- rawOutput: { content: "SUB_DONE" },
- },
- });
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
-
- let completedBeforeDrain = 0;
- let polled = yield* Queue.poll(events);
- while (Option.isSome(polled)) {
- const event = polled.value;
- if (
- event.type === "turn_item.updated" &&
- event.turnItem.type === "subagent" &&
- event.turnItem.status === "completed"
- ) {
- completedBeforeDrain += 1;
- }
- polled = yield* Queue.poll(events);
- }
- assert.equal(
- completedBeforeDrain,
- 0,
- "interrupted child-session terminal must wait for the continuation attach",
- );
- assert.isTrue(
- yield* hasPendingBackgroundWork,
- "child-session must not clear the pin while wakeBuffer still has delivery",
- );
-
- const continuationNow = yield* DateTime.now;
- yield* runtime.startTurn(
- makeTurnInput({
- threadId,
- providerThread,
- instanceId,
- runtimePolicy,
- now: continuationNow,
- ordinal: 2,
- messageCreatedBy: "agent",
- messageCreationSource: "provider",
- messageText: "Background task completed.",
- }),
- );
- yield* TestClock.adjust("3 seconds");
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
-
- const continuationProviderTurnId = idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"),
- });
- let continuationTerminal: string | null = null;
- let completedSubagentTurnItems = 0;
- let bufferedTextSeen = false;
- while (continuationTerminal === null) {
- const event = yield* Queue.take(events);
- if (
- event.type === "turn_item.updated" &&
- event.turnItem.type === "subagent" &&
- event.turnItem.status === "completed"
- ) {
- completedSubagentTurnItems += 1;
- }
- if (
- event.type === "message.updated" &&
- event.message.role === "assistant" &&
- event.message.text.includes(bufferedAssistantText)
- ) {
- bufferedTextSeen = true;
- }
- if (
- event.type === "turn.terminal" &&
- event.providerTurnId === continuationProviderTurnId
- ) {
- continuationTerminal = event.status;
- }
+ event.turnItem.runId === continuationInput.runId
+ ) {
+ replayedTurnItems += 1;
}
- assert.equal(continuationTerminal, "completed");
- assert.isTrue(
- bufferedTextSeen,
- "continuation drain must project buffered post-settle assistant text (buffer not wiped)",
- );
- assert.equal(
- completedSubagentTurnItems,
- 1,
- "continuation drain must project the terminal subagent turn item once",
- );
- assert.isFalse(
- yield* hasPendingBackgroundWork,
- "pin must clear after the continuation drains, not when the child session completed",
- );
- }).pipe(Effect.provide(layerTest), Effect.scoped),
+ polled = yield* Queue.poll(events);
+ }
+ assert.equal(replayedLineages, 0, "buffered spawn ACK must not create a second lineage");
+ assert.equal(
+ replayedSubagentUpdates,
+ 0,
+ "buffered spawn ACK must not re-open the terminal subagent",
+ );
+ assert.equal(
+ replayedTurnItems,
+ 0,
+ "buffered spawn ACK must not create a continuation-owned turn item",
+ );
+ assert.isFalse(yield* hasPendingBackgroundWork);
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
);
it.effect(
- "projects once when root-session then child-session complete the same carryover subagent",
+ "user attach flushes a deferred terminal but leaves wake traffic for its continuation",
() =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -6224,8 +4559,8 @@ describe("AcpAdapterV2", () => {
);
const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
[];
+ const bufferedAssistantText = "BUFFERED_WAKE_AFTER_USER_ATTACH";
const instanceId = ProviderInstanceId.make("acp-test");
- const childSessionId = "mock-child-session-root-then-child";
let subagentPhase: "spawn" | "complete" = "spawn";
type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
@@ -6251,7 +4586,7 @@ describe("AcpAdapterV2", () => {
title: "background subagent",
model: null,
status: "running",
- childSessionId,
+ childSessionId: null,
result: null,
}
: {
@@ -6260,7 +4595,7 @@ describe("AcpAdapterV2", () => {
title: null,
model: null,
status: "completed",
- childSessionId,
+ childSessionId: null,
result: "SUB_DONE",
},
makeRuntime: makeMockRuntime({
@@ -6284,7 +4619,7 @@ describe("AcpAdapterV2", () => {
}),
},
});
- const threadId = ThreadId.make("thread-acp-carryover-root-then-child");
+ const threadId = ThreadId.make("thread-acp-carryover-root-session-continuation");
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
@@ -6294,7 +4629,7 @@ describe("AcpAdapterV2", () => {
const runtime = yield* adapter.openSession({
threadId,
providerSessionId: ProviderSessionId.make(
- "provider-session-acp-carryover-root-then-child",
+ "provider-session-acp-carryover-root-session-continuation",
),
modelSelection,
runtimePolicy,
@@ -6353,21 +4688,11 @@ describe("AcpAdapterV2", () => {
rawOutput: { content: "SUB_DONE" },
},
});
- assert.lengthOf(
- continuationRequests,
- 1,
- "root-session terminal must still offer a continuation",
- );
-
yield* sessionUpdateHandler!({
- sessionId: childSessionId,
+ sessionId: "mock-session-1",
update: {
- sessionUpdate: "tool_call_update",
- toolCallId: "tool-call-generic-1",
- title: "background subagent",
- kind: "other",
- status: "completed",
- rawOutput: { content: "SUB_DONE" },
+ sessionUpdate: "agent_message_chunk",
+ content: { type: "text", text: bufferedAssistantText },
},
});
yield* Effect.yieldNow;
@@ -6389,34 +4714,42 @@ describe("AcpAdapterV2", () => {
assert.equal(
completedBeforeDrain,
0,
- "interrupted root-then-child completion must defer to the continuation attach",
+ "interrupted root-session terminal must wait for an observable attach",
+ );
+ assert.lengthOf(
+ continuationRequests,
+ 1,
+ "root-session post-settle subagent terminal must offer a continuation",
+ );
+ assert.isTrue(
+ yield* hasPendingBackgroundWork,
+ "interrupted unprojected terminal must pin hasPendingBackgroundWork until attach",
);
- const continuationNow = yield* DateTime.now;
+ const userTurnNow = yield* DateTime.now;
yield* runtime.startTurn(
makeTurnInput({
threadId,
providerThread,
instanceId,
runtimePolicy,
- now: continuationNow,
+ now: userTurnNow,
ordinal: 2,
- messageCreatedBy: "agent",
- messageCreationSource: "provider",
- messageText: "Background task completed.",
+ messageText: "What finished while the prior turn was settling?",
}),
);
yield* TestClock.adjust("3 seconds");
yield* Effect.yieldNow;
yield* Effect.yieldNow;
- const continuationProviderTurnId = idAllocator.derive.providerTurn({
+ const userProviderTurnId = idAllocator.derive.providerTurn({
driver: ACP_TEST_DRIVER,
nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"),
});
- let continuationTerminal: string | null = null;
+ let userTurnTerminal: string | null = null;
let completedSubagentTurnItems = 0;
- while (continuationTerminal === null) {
+ let bufferedTextSeenInUserTurn = false;
+ while (userTurnTerminal === null) {
const event = yield* Queue.take(events);
if (
event.type === "turn_item.updated" &&
@@ -6426,22 +4759,71 @@ describe("AcpAdapterV2", () => {
completedSubagentTurnItems += 1;
}
if (
- event.type === "turn.terminal" &&
- event.providerTurnId === continuationProviderTurnId
+ event.type === "message.updated" &&
+ event.message.role === "assistant" &&
+ event.message.text.includes(bufferedAssistantText)
) {
- continuationTerminal = event.status;
+ bufferedTextSeenInUserTurn = true;
+ }
+ if (event.type === "turn.terminal" && event.providerTurnId === userProviderTurnId) {
+ userTurnTerminal = event.status;
}
}
- assert.equal(continuationTerminal, "completed");
+ assert.equal(userTurnTerminal, "completed");
assert.equal(
completedSubagentTurnItems,
1,
- "root-then-child completion must project the terminal subagent turn item exactly once",
+ "user attach must project the deferred terminal subagent turn item once",
);
- assert.isFalse(
+ assert.isFalse(bufferedTextSeenInUserTurn, "user attach must not drain wake traffic");
+ assert.isTrue(
yield* hasPendingBackgroundWork,
- "hasPendingBackgroundWork must end false after the continuation drains",
+ "wake traffic must remain pinned for the already-dispatched continuation",
+ );
+
+ const continuationNow = yield* DateTime.now;
+ yield* runtime.startTurn(
+ makeTurnInput({
+ threadId,
+ providerThread,
+ instanceId,
+ runtimePolicy,
+ now: continuationNow,
+ ordinal: 3,
+ messageCreatedBy: "agent",
+ messageCreationSource: "provider",
+ messageText: "Background task completed.",
+ }),
+ );
+ yield* TestClock.adjust("3 seconds");
+ const continuationProviderTurnId = idAllocator.derive.providerTurn({
+ driver: ACP_TEST_DRIVER,
+ nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:3"),
+ });
+ let continuationTerminal: string | null = null;
+ let bufferedTextSeenInContinuation = false;
+ while (continuationTerminal === null) {
+ const event = yield* Queue.take(events);
+ if (
+ event.type === "message.updated" &&
+ event.message.role === "assistant" &&
+ event.message.text.includes(bufferedAssistantText)
+ ) {
+ bufferedTextSeenInContinuation = true;
+ }
+ if (
+ event.type === "turn.terminal" &&
+ event.providerTurnId === continuationProviderTurnId
+ ) {
+ continuationTerminal = event.status;
+ }
+ }
+ assert.equal(continuationTerminal, "completed");
+ assert.isTrue(
+ bufferedTextSeenInContinuation,
+ "queued continuation must drain the wake content after the user run",
);
+ assert.isFalse(yield* hasPendingBackgroundWork);
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
@@ -6842,138 +5224,21 @@ describe("AcpAdapterV2", () => {
toolCall.toolCallId === "tool-call-monitor-1" ? "task-monitor-1" : undefined,
extractBackgroundTaskCompletion: (toolCall) =>
toolCall.toolCallId === "tool-call-fetch-1"
- ? [
- {
- taskId: "task-monitor-1",
- status: toolCall.status === "completed" ? "completed" : "running",
- appendOutput: toolCall.status === "completed" ? "MONITOR_LISTING_TOKEN" : "",
- },
- ]
- : [],
- makeRuntime: makeMockRuntime({
- childProcessSpawner,
- mockAgentPath,
- environment: {
- T3_ACP_EMIT_IN_TURN_TASKOUTPUT_THEN_LATE_DUPLICATE: "1",
- },
- protocolEvents,
- }),
- },
- selfInvocation,
- continuationRequests: {
- offer: (request) =>
- Effect.sync(() => {
- continuationRequests.push(request);
- }),
- },
- });
- const threadId = ThreadId.make("thread-acp-already-handled-wake-pin");
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd: process.cwd(),
- });
- const modelSelection = { instanceId, model: "default" } as const;
- const runtime = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make(
- "provider-session-acp-already-handled-wake-pin",
- ),
- modelSelection,
- runtimePolicy,
- });
- if (runtime.hasPendingBackgroundWork === undefined) {
- return yield* Effect.die(
- "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.",
- );
- }
- const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
- const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
- yield* runtime.events.pipe(
- Stream.runForEach((event) => Queue.offer(events, event)),
- Effect.forkScoped,
- );
- const providerThread = yield* runtime.ensureThread({
- threadId,
- modelSelection,
- runtimePolicy,
- });
- const now = yield* DateTime.now;
- yield* runtime.startTurn(
- makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }),
- );
- const providerTurnId = idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
- });
-
- let terminalStatus: string | null = null;
- while (terminalStatus === null) {
- const event = yield* Queue.take(events);
- if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) {
- terminalStatus = event.status;
- }
- }
- assert.equal(terminalStatus, "completed");
-
- yield* Stream.fromQueue(protocolEvents).pipe(
- Stream.filter(
- (event) =>
- event.direction === "incoming" &&
- event.stage === "raw" &&
- typeof event.payload === "string" &&
- event.payload.includes("MONITOR_LISTING_TOKEN_LATE"),
- ),
- Stream.runHead,
- );
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
-
- assert.lengthOf(
- continuationRequests,
- 0,
- "already-handled late TaskOutput must not open a continuation run",
- );
- assert.isFalse(
- yield* hasPendingBackgroundWork,
- "wake buffer must not stay non-empty and pin idle release after an already-handled re-report",
- );
- }).pipe(Effect.provide(layerTest), Effect.scoped),
- );
-
- it.effect(
- "keeps a dispatched continuation offer sticky until a turn starts or the worker drops it",
- () =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const path = yield* Path.Path;
- const selfInvocation = yield* resolveSelfInvocation();
- const mockAgentPath = yield* path.fromFileUrl(
- new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
- );
- const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
- [];
- type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
- let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
- const instanceId = ProviderInstanceId.make("acp-test");
- const adapter = yield* makeAcpAdapterV2({
- instanceId,
- flavor: {
- driver: ACP_TEST_DRIVER,
- capabilities: AcpProviderCapabilitiesV2,
- enablePostSettleContinuation: true,
+ ? [
+ {
+ taskId: "task-monitor-1",
+ status: toolCall.status === "completed" ? "completed" : "running",
+ appendOutput: toolCall.status === "completed" ? "MONITOR_LISTING_TOKEN" : "",
+ },
+ ]
+ : [],
makeRuntime: makeMockRuntime({
childProcessSpawner,
mockAgentPath,
- wrapRuntime: (runtime) => ({
- ...runtime,
- handleSessionUpdate: (handler) =>
- Effect.sync(() => {
- sessionUpdateHandler = handler;
- }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
- }),
+ environment: {
+ T3_ACP_EMIT_IN_TURN_TASKOUTPUT_THEN_LATE_DUPLICATE: "1",
+ },
+ protocolEvents,
}),
},
selfInvocation,
@@ -6984,7 +5249,7 @@ describe("AcpAdapterV2", () => {
}),
},
});
- const threadId = ThreadId.make("thread-acp-sticky-continuation-dispatch");
+ const threadId = ThreadId.make("thread-acp-already-handled-wake-pin");
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
@@ -6994,11 +5259,17 @@ describe("AcpAdapterV2", () => {
const runtime = yield* adapter.openSession({
threadId,
providerSessionId: ProviderSessionId.make(
- "provider-session-acp-sticky-continuation-dispatch",
+ "provider-session-acp-already-handled-wake-pin",
),
modelSelection,
runtimePolicy,
});
+ if (runtime.hasPendingBackgroundWork === undefined) {
+ return yield* Effect.die(
+ "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.",
+ );
+ }
+ const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
yield* runtime.events.pipe(
Stream.runForEach((event) => Queue.offer(events, event)),
@@ -7017,6 +5288,7 @@ describe("AcpAdapterV2", () => {
driver: ACP_TEST_DRIVER,
nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
});
+
let terminalStatus: string | null = null;
while (terminalStatus === null) {
const event = yield* Queue.take(events);
@@ -7025,37 +5297,30 @@ describe("AcpAdapterV2", () => {
}
}
assert.equal(terminalStatus, "completed");
- assert.isDefined(sessionUpdateHandler, "session update handler must be wired");
- const lateTool = (toolCallId: string) =>
- sessionUpdateHandler!({
- sessionId: "mock-session-1",
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId,
- title: "Late tool result",
- kind: "other",
- status: "completed",
- rawOutput: { output: toolCallId },
- },
- });
- yield* lateTool("first-late-result");
- assert.lengthOf(continuationRequests, 1);
- const first = continuationRequests[0]!;
- assert.isDefined(first.dispatchIfCurrent);
- assert.isTrue(Option.isSome(yield* first.dispatchIfCurrent!(Effect.void)));
+ yield* Stream.fromQueue(protocolEvents).pipe(
+ Stream.filter(
+ (event) =>
+ event.direction === "incoming" &&
+ event.stage === "raw" &&
+ typeof event.payload === "string" &&
+ event.payload.includes("MONITOR_LISTING_TOKEN_LATE"),
+ ),
+ Stream.runHead,
+ );
+ yield* Effect.yieldNow;
+ yield* Effect.yieldNow;
+ yield* Effect.yieldNow;
- yield* lateTool("second-frame-before-dispatched-turn-starts");
assert.lengthOf(
continuationRequests,
- 1,
- "late frames must not enqueue duplicate continuations during dispatch-to-start",
+ 0,
+ "already-handled late TaskOutput must not open a continuation run",
+ );
+ assert.isFalse(
+ yield* hasPendingBackgroundWork,
+ "wake buffer must not stay non-empty and pin idle release after an already-handled re-report",
);
-
- assert.isDefined(first.clearIfCurrent);
- yield* first.clearIfCurrent!();
- yield* lateTool("new-result-after-worker-drop");
- assert.lengthOf(continuationRequests, 2);
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
@@ -7456,219 +5721,14 @@ describe("AcpAdapterV2", () => {
: [],
}),
"mutation-only end-notice must not count as post-settle wake evidence",
- );
- yield* sessionUpdateHandler!(bEndNotice);
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
- assert.lengthOf(
- continuationRequests,
- 1,
- "exactly one continuation when the last running task ends post-finalize with kept midTurn marks",
- );
- }).pipe(Effect.provide(layerTest), Effect.scoped),
- );
-
- it.effect(
- "staggered pre-settle completion does not keep midTurn marks when the turn is interrupted",
- () =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const path = yield* Path.Path;
- const selfInvocation = yield* resolveSelfInvocation();
- const mockAgentPath = yield* path.fromFileUrl(
- new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
- );
- const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
- const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
- [];
- type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
- let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
- const promptGate = yield* Deferred.make<EffectAcpSchema.PromptResponse>();
- const capturedMutation: {
- current:
- | ((mutation: {
- readonly sessionId: string;
- readonly taskId: string;
- readonly status: "running" | "completed" | "failed";
- }) => Effect.Effect<void>)
- | null;
- } = { current: null };
- const instanceId = ProviderInstanceId.make("acp-test");
- const adapter = yield* makeAcpAdapterV2({
- instanceId,
- flavor: {
- driver: ACP_TEST_DRIVER,
- capabilities: AcpProviderCapabilitiesV2,
- deferFinalizeForBackgroundWork: true,
- enablePostSettleContinuation: true,
- extractBackgroundTaskId: (toolCall) => {
- if (toolCall.toolCallId === "tool-call-monitor-a") return "task-monitor-a";
- if (toolCall.toolCallId === "tool-call-monitor-b") return "task-monitor-b";
- return undefined;
- },
- extractBackgroundToolMutation: (text) => {
- if (text.includes('Monitor "task-monitor-a" ended')) {
- return [{ taskId: "task-monitor-a", status: "completed", appendOutput: "" }];
- }
- if (text.includes('Monitor "task-monitor-b" ended')) {
- return [{ taskId: "task-monitor-b", status: "completed", appendOutput: "" }];
- }
- return [];
- },
- registerExtensions: (context) =>
- Effect.sync(() => {
- capturedMutation.current = context.applyBackgroundTaskMutation;
- }),
- makeRuntime: makeMockRuntime({
- childProcessSpawner,
- mockAgentPath,
- environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" },
- protocolEvents,
- wrapRuntime: (runtime) => ({
- ...runtime,
- handleSessionUpdate: (handler) =>
- Effect.sync(() => {
- sessionUpdateHandler = handler;
- }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
- prompt: () => Deferred.await(promptGate),
- }),
- }),
- },
- selfInvocation,
- continuationRequests: {
- offer: (request) =>
- Effect.sync(() => {
- continuationRequests.push(request);
- }),
- },
- });
- const threadId = ThreadId.make("thread-acp-staggered-midturn-clear-on-interrupt");
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd: process.cwd(),
- });
- const modelSelection = { instanceId, model: "default" } as const;
- const runtime = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make(
- "provider-session-acp-staggered-midturn-clear-on-interrupt",
- ),
- modelSelection,
- runtimePolicy,
- });
- const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
- yield* runtime.events.pipe(
- Stream.runForEach((event) => Queue.offer(events, event)),
- Effect.forkScoped,
- );
- const providerThread = yield* runtime.ensureThread({
- threadId,
- modelSelection,
- runtimePolicy,
- });
- const now = yield* DateTime.now;
- yield* runtime
- .startTurn(
- makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }),
- )
- .pipe(Effect.forkScoped);
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
- assert.isDefined(sessionUpdateHandler);
- const applyMutation = capturedMutation.current;
- if (applyMutation === null) {
- return yield* Effect.die("registerExtensions must capture applyBackgroundTaskMutation");
- }
-
- for (const [toolCallId, title] of [
- ["tool-call-monitor-a", "Monitor: staggered interrupt A"],
- ["tool-call-monitor-b", "Monitor: staggered interrupt B"],
- ] as const) {
- yield* sessionUpdateHandler!({
- sessionId: "mock-session-1",
- update: {
- sessionUpdate: "tool_call",
- toolCallId,
- title,
- kind: "execute",
- status: "pending",
- rawInput: {},
- },
- });
- yield* sessionUpdateHandler!({
- sessionId: "mock-session-1",
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId,
- status: "in_progress",
- },
- });
- }
- yield* applyMutation({
- sessionId: "mock-session-1",
- taskId: "task-monitor-a",
- status: "running",
- });
- yield* applyMutation({
- sessionId: "mock-session-1",
- taskId: "task-monitor-b",
- status: "running",
- });
- yield* applyMutation({
- sessionId: "mock-session-1",
- taskId: "task-monitor-a",
- status: "completed",
- });
- assert.lengthOf(continuationRequests, 0);
-
- yield* Deferred.succeed(promptGate, { stopReason: "end_turn" });
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
- assert.lengthOf(
- continuationRequests,
- 0,
- "settle must hold for deferred background tools; no mid-hold offer",
- );
-
- const providerTurnId = idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
- });
- yield* runtime.interruptTurn({ providerThread, providerTurnId });
-
- let terminalStatus: string | null = null;
- while (terminalStatus === null) {
- const event = yield* Queue.take(events);
- if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) {
- terminalStatus = event.status;
- }
- }
- assert.equal(terminalStatus, "interrupted");
- assert.lengthOf(
- continuationRequests,
- 0,
- "interrupted finalize must not offer a continuation",
- );
-
- yield* sessionUpdateHandler!({
- sessionId: "mock-session-1",
- update: {
- sessionUpdate: "user_message_chunk",
- content: {
- type: "text",
- text: 'Monitor "task-monitor-b" ended: [monitor ended: exit 0]',
- },
- },
- });
+ );
+ yield* sessionUpdateHandler!(bEndNotice);
yield* Effect.yieldNow;
yield* Effect.yieldNow;
assert.lengthOf(
continuationRequests,
- 0,
- "interrupted turns must clear midTurn marks; B ending post-finalize must not offer",
+ 1,
+ "exactly one continuation when the last running task ends post-finalize with kept midTurn marks",
);
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
@@ -8153,351 +6213,36 @@ describe("AcpAdapterV2", () => {
update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } },
});
- yield* endCommand("task-a", "sleep a");
- yield* agentText("A_DONE");
- assert.lengthOf(continuationRequests, 1);
- assert.equal(continuationRequests[0]?.notification?.summary, 'Command "sleep a" finished');
- yield* endCommand("task-b", "sleep b");
- assert.lengthOf(continuationRequests, 1);
-
- yield* runtime.startTurn(
- makeTurnInput({
- threadId,
- providerThread,
- instanceId,
- runtimePolicy,
- now: yield* DateTime.now,
- ordinal: 2,
- messageCreatedBy: "agent",
- messageCreationSource: "provider",
- messageText: "Background task completed.",
- }),
- );
- yield* TestClock.adjust("3 seconds");
- assert.equal(yield* awaitTerminal(2), "completed");
-
- yield* agentText("B_DONE");
- assert.lengthOf(continuationRequests, 2);
- assert.deepEqual(continuationRequests[1]?.notification, {
- source: { kind: "command" },
- outcome: "completed",
- summary: 'Command "sleep b" finished',
- });
- }).pipe(Effect.provide(layerTest), Effect.scoped),
- );
-
- it.effect("mid-turn completed mutation defers offer until finalize only when unhandled", () =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const path = yield* Path.Path;
- const selfInvocation = yield* resolveSelfInvocation();
- const mockAgentPath = yield* path.fromFileUrl(
- new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
- );
- const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
- const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
- [];
- type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
- let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
- const promptGates: Array<Deferred.Deferred<EffectAcpSchema.PromptResponse, never>> = [];
- const capturedMutation: {
- current:
- | ((mutation: {
- readonly sessionId: string;
- readonly taskId: string;
- readonly status: "running" | "completed" | "failed";
- }) => Effect.Effect<void>)
- | null;
- } = { current: null };
- const instanceId = ProviderInstanceId.make("acp-test");
- const adapter = yield* makeAcpAdapterV2({
- instanceId,
- flavor: {
- driver: ACP_TEST_DRIVER,
- capabilities: AcpProviderCapabilitiesV2,
- enablePostSettleContinuation: true,
- extractBackgroundTaskId: (toolCall) =>
- toolCall.toolCallId === "tool-call-monitor-unhandled"
- ? "task-monitor-unhandled"
- : toolCall.toolCallId === "tool-call-monitor-handled"
- ? "task-monitor-handled"
- : undefined,
- extractBackgroundTaskCompletion: (toolCall) =>
- toolCall.toolCallId === "tool-call-fetch-handled"
- ? [
- {
- taskId: "task-monitor-handled",
- status: toolCall.status === "completed" ? "completed" : "running",
- appendOutput: toolCall.status === "completed" ? "HANDLED_LISTING" : "",
- },
- ]
- : [],
- registerExtensions: (context) =>
- Effect.sync(() => {
- capturedMutation.current = context.applyBackgroundTaskMutation;
- }),
- makeRuntime: makeMockRuntime({
- childProcessSpawner,
- mockAgentPath,
- environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" },
- protocolEvents,
- wrapRuntime: (runtime) => ({
- ...runtime,
- handleSessionUpdate: (handler) =>
- Effect.sync(() => {
- sessionUpdateHandler = handler;
- }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
- prompt: () =>
- Effect.gen(function* () {
- const gate = yield* Deferred.make<EffectAcpSchema.PromptResponse>();
- promptGates.push(gate);
- return yield* Deferred.await(gate);
- }),
- }),
- }),
- },
- selfInvocation,
- continuationRequests: {
- offer: (request) =>
- Effect.sync(() => {
- continuationRequests.push(request);
- }),
- },
- });
- const threadId = ThreadId.make("thread-acp-mid-turn-dirty-wake-buffer");
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd: process.cwd(),
- });
- const modelSelection = { instanceId, model: "default" } as const;
- const runtime = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make(
- "provider-session-acp-mid-turn-dirty-wake-buffer",
- ),
- modelSelection,
- runtimePolicy,
- });
- if (runtime.hasPendingBackgroundWork === undefined) {
- return yield* Effect.die(
- "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.",
- );
- }
- const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
- const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
- yield* runtime.events.pipe(
- Stream.runForEach((event) => Queue.offer(events, event)),
- Effect.forkScoped,
- );
- const providerThread = yield* runtime.ensureThread({
- threadId,
- modelSelection,
- runtimePolicy,
- });
- const now = yield* DateTime.now;
- yield* runtime
- .startTurn(
- makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }),
- )
- .pipe(Effect.forkScoped);
- while (promptGates.length < 1) {
- yield* Effect.yieldNow;
- }
- yield* Deferred.succeed(promptGates[0]!, { stopReason: "end_turn" });
- const firstProviderTurnId = idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
- });
- let firstTerminal: string | null = null;
- while (firstTerminal === null) {
- const event = yield* Queue.take(events);
- if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) {
- firstTerminal = event.status;
- }
- }
- assert.equal(firstTerminal, "completed");
- assert.isDefined(sessionUpdateHandler);
- yield* sessionUpdateHandler!({
- sessionId: "mock-session-1",
- update: {
- sessionUpdate: "agent_thought_chunk",
- content: { type: "text", text: "stale wake residue from prior turn" },
- },
- });
- assert.isTrue(yield* hasPendingBackgroundWork, "thought residue must dirty the wake buffer");
- assert.lengthOf(continuationRequests, 0);
-
- yield* runtime
- .startTurn(
- makeTurnInput({
- threadId,
- providerThread,
- instanceId,
- runtimePolicy,
- now: yield* DateTime.now,
- ordinal: 2,
- }),
- )
- .pipe(Effect.forkScoped);
- while (promptGates.length < 2) {
- yield* Effect.yieldNow;
- }
- assert.isFalse(
- yield* hasPendingBackgroundWork,
- "user-turn start must drop prior-turn wake residue",
- );
- const applyMutation = capturedMutation.current;
- if (applyMutation === null || sessionUpdateHandler === undefined) {
- return yield* Effect.die("extensions and session handler must be wired for turn 2");
- }
-
- yield* sessionUpdateHandler({
- sessionId: "mock-session-1",
- update: {
- sessionUpdate: "tool_call",
- toolCallId: "tool-call-monitor-unhandled",
- title: "Monitor: unhandled",
- kind: "execute",
- status: "pending",
- rawInput: {},
- },
- });
- yield* sessionUpdateHandler({
- sessionId: "mock-session-1",
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: "tool-call-monitor-unhandled",
- status: "in_progress",
- },
- });
- yield* applyMutation({
- sessionId: "mock-session-1",
- taskId: "task-monitor-unhandled",
- status: "running",
- });
- yield* applyMutation({
- sessionId: "mock-session-1",
- taskId: "task-monitor-unhandled",
- status: "completed",
- });
- assert.lengthOf(
- continuationRequests,
- 0,
- "mid-turn completed mutation must not offer while the root turn is active",
- );
-
- yield* Deferred.succeed(promptGates[1]!, { stopReason: "end_turn" });
- const secondProviderTurnId = idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"),
- });
- let secondTerminal: string | null = null;
- while (secondTerminal === null) {
- const event = yield* Queue.take(events);
- if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) {
- secondTerminal = event.status;
- }
- }
- assert.equal(secondTerminal, "completed");
- assert.lengthOf(
- continuationRequests,
- 1,
- "post-finalize must offer when mid-turn completion was never handled in-turn",
- );
-
- const firstOffer = continuationRequests[0]!;
- if (firstOffer.clearIfCurrent !== undefined) {
- yield* firstOffer.clearIfCurrent();
- }
- continuationRequests.length = 0;
- yield* runtime
- .startTurn(
- makeTurnInput({
- threadId,
- providerThread,
- instanceId,
- runtimePolicy,
- now: yield* DateTime.now,
- ordinal: 3,
- }),
- )
- .pipe(Effect.forkScoped);
- while (promptGates.length < 3) {
- yield* Effect.yieldNow;
- }
- if (sessionUpdateHandler === undefined || capturedMutation.current === null) {
- return yield* Effect.die("handler must remain wired for turn 3");
- }
- yield* sessionUpdateHandler({
- sessionId: "mock-session-1",
- update: {
- sessionUpdate: "tool_call",
- toolCallId: "tool-call-monitor-handled",
- title: "Monitor: handled",
- kind: "execute",
- status: "pending",
- rawInput: {},
- },
- });
- yield* sessionUpdateHandler({
- sessionId: "mock-session-1",
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: "tool-call-monitor-handled",
- status: "in_progress",
- },
- });
- yield* capturedMutation.current({
- sessionId: "mock-session-1",
- taskId: "task-monitor-handled",
- status: "running",
- });
- yield* sessionUpdateHandler({
- sessionId: "mock-session-1",
- update: {
- sessionUpdate: "tool_call",
- toolCallId: "tool-call-fetch-handled",
- title: "get_command_or_subagent_output",
- kind: "other",
- status: "pending",
- rawInput: {},
- },
- });
- yield* sessionUpdateHandler({
- sessionId: "mock-session-1",
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: "tool-call-fetch-handled",
- status: "completed",
- rawOutput: { output: "HANDLED_LISTING" },
- },
- });
- yield* capturedMutation.current({
- sessionId: "mock-session-1",
- taskId: "task-monitor-handled",
- status: "completed",
- });
- assert.lengthOf(continuationRequests, 0, "handled mid-turn completion must not offer");
- yield* Deferred.succeed(promptGates[2]!, { stopReason: "end_turn" });
- const thirdProviderTurnId = idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:3"),
- });
- let thirdTerminal: string | null = null;
- while (thirdTerminal === null) {
- const event = yield* Queue.take(events);
- if (event.type === "turn.terminal" && event.providerTurnId === thirdProviderTurnId) {
- thirdTerminal = event.status;
- }
- }
- assert.equal(thirdTerminal, "completed");
- assert.lengthOf(
- continuationRequests,
- 0,
- "post-finalize must not offer when the mid-turn completion was handled in-turn",
+ yield* endCommand("task-a", "sleep a");
+ yield* agentText("A_DONE");
+ assert.lengthOf(continuationRequests, 1);
+ assert.equal(continuationRequests[0]?.notification?.summary, 'Command "sleep a" finished');
+ yield* endCommand("task-b", "sleep b");
+ assert.lengthOf(continuationRequests, 1);
+
+ yield* runtime.startTurn(
+ makeTurnInput({
+ threadId,
+ providerThread,
+ instanceId,
+ runtimePolicy,
+ now: yield* DateTime.now,
+ ordinal: 2,
+ messageCreatedBy: "agent",
+ messageCreationSource: "provider",
+ messageText: "Background task completed.",
+ }),
);
+ yield* TestClock.adjust("3 seconds");
+ assert.equal(yield* awaitTerminal(2), "completed");
+
+ yield* agentText("B_DONE");
+ assert.lengthOf(continuationRequests, 2);
+ assert.deepEqual(continuationRequests[1]?.notification, {
+ source: { kind: "command" },
+ outcome: "completed",
+ summary: 'Command "sleep b" finished',
+ });
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
@@ -8912,249 +6657,6 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
- it.live("keeps stale deferred cleanup inert while replacement requests remain live", () =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const path = yield* Path.Path;
- const selfInvocation = yield* resolveSelfInvocation();
- const mockAgentPath = yield* path.fromFileUrl(
- new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
- );
- const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
- const instanceId = ProviderInstanceId.make("acp-test");
- const adapter = yield* makeAcpAdapterV2({
- instanceId,
- flavor: {
- driver: ACP_TEST_DRIVER,
- capabilities: AcpProviderCapabilitiesV2,
- restartRuntimeAfterInterrupt: true,
- terminateRuntimeProcessGroupOnInterrupt: true,
- makeRuntime: makeMockRuntime({
- childProcessSpawner,
- mockAgentPath,
- ownDetachedProcessGroup: true,
- processGroupPlatform: "win32",
- windowsProcessTreeTerminator: () => Effect.void,
- environment: { T3_ACP_EMIT_TOOL_CALLS: "1" },
- protocolEvents,
- }),
- },
- selfInvocation,
- });
- const threadId = ThreadId.make("thread-acp-stale-deferred-cleanup");
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "approval-required",
- interactionMode: "default",
- cwd: process.cwd(),
- });
- const modelSelection = { instanceId, model: "default" } as const;
- const runtime = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make("provider-session-acp-stale-deferred-cleanup"),
- modelSelection,
- runtimePolicy,
- });
- const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
- yield* runtime.events.pipe(
- Stream.runForEach((event) => Queue.offer(events, event)),
- Effect.forkScoped,
- );
- const providerThread = yield* runtime.ensureThread({
- threadId,
- modelSelection,
- runtimePolicy,
- });
- const now = yield* DateTime.now;
- yield* runtime.startTurn(
- makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }),
- );
- const oldPending = yield* Queue.take(events).pipe(
- Effect.repeat({
- until: (event) =>
- event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
- }),
- );
- if (
- oldPending.type !== "runtime_request.updated" ||
- oldPending.runtimeRequest.providerTurnId === null
- ) {
- return yield* Effect.die("Expected the old runtime permission request");
- }
- yield* runtime.interruptTurn({
- providerThread,
- providerTurnId: oldPending.runtimeRequest.providerTurnId,
- requestRuntimeRestart: true,
- });
- const staleResponse = yield* runtime
- .respondToRuntimeRequest({
- requestId: oldPending.runtimeRequest.id,
- decision: "accept",
- })
- .pipe(Effect.exit);
- if (Exit.isSuccess(staleResponse)) {
- assert.fail("teardown must synchronously remove the old pending request");
- }
- while (Option.isSome(yield* Queue.poll(events))) {}
-
- yield* runtime.startTurn(
- makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }),
- );
- let replacementPending: ProviderAdapter.ProviderAdapterV2Event | undefined;
- while (replacementPending === undefined) {
- const event = yield* Queue.take(events);
- if (event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending") {
- replacementPending = event;
- }
- }
- if (replacementPending.type !== "runtime_request.updated") {
- return yield* Effect.die("Expected the replacement runtime permission request");
- }
- assert.notEqual(replacementPending.runtimeRequest.id, oldPending.runtimeRequest.id);
- yield* runtime.respondToRuntimeRequest({
- requestId: replacementPending.runtimeRequest.id,
- decision: "accept",
- });
- let replacementTerminal = false;
- while (!replacementTerminal) {
- const event = yield* Queue.take(events);
- if (
- event.type === "runtime_request.updated" &&
- event.runtimeRequest.id === oldPending.runtimeRequest.id
- ) {
- assert.fail("stale deferred cleanup must not emit into generation 2");
- }
- replacementTerminal = event.type === "turn.terminal";
- }
- }).pipe(Effect.provide(layerTest), Effect.scoped),
- );
-
- it.live("resolves owner cancellation and concurrent resume waiters after hard teardown", () =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const path = yield* Path.Path;
- const selfInvocation = yield* resolveSelfInvocation();
- const mockAgentPath = yield* path.fromFileUrl(
- new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
- );
- const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
- const teardownStarted = yield* Deferred.make<void>();
- const releaseTeardown = yield* Deferred.make<void>();
- let runtimeOrdinalSeen = 0;
- const instanceId = ProviderInstanceId.make("acp-test");
- const adapter = yield* makeAcpAdapterV2({
- instanceId,
- flavor: {
- driver: ACP_TEST_DRIVER,
- capabilities: AcpProviderCapabilitiesV2,
- interruptPromptOnCancel: true,
- restartRuntimeAfterInterrupt: true,
- terminateRuntimeProcessGroupOnInterrupt: true,
- makeRuntime: makeMockRuntime({
- childProcessSpawner,
- mockAgentPath,
- ownDetachedProcessGroup: true,
- processGroupPlatform: "win32",
- windowsProcessTreeTerminator: () =>
- Deferred.succeed(teardownStarted, undefined).pipe(
- Effect.andThen(Deferred.await(releaseTeardown)),
- ),
- environment: (runtimeOrdinal) => {
- runtimeOrdinalSeen = runtimeOrdinal;
- return runtimeOrdinal === 1 ? { T3_ACP_HANG_PROMPT_FOREVER: "1" } : {};
- },
- protocolEvents,
- }),
- },
- selfInvocation,
- });
- const threadId = ThreadId.make("thread-acp-concurrent-resume-teardown");
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd: process.cwd(),
- });
- const modelSelection = { instanceId, model: "default" } as const;
- const runtime = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make(
- "provider-session-acp-concurrent-resume-teardown",
- ),
- modelSelection,
- runtimePolicy,
- });
- const providerThread = yield* runtime.ensureThread({
- threadId,
- modelSelection,
- runtimePolicy,
- });
- const now = yield* DateTime.now;
- yield* runtime
- .startTurn(
- makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }),
- )
- .pipe(Effect.forkScoped);
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
- yield* pollProtocolMethods(protocolEvents);
- const providerTurnId = idAllocator.derive.providerTurn({
- driver: ACP_TEST_DRIVER,
- nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
- });
- const interruptFiber = yield* runtime
- .interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true })
- .pipe(Effect.forkScoped);
- yield* Deferred.await(teardownStarted);
- const resumeFiber = yield* runtime
- .resumeThread({ providerThread, modelSelection, runtimePolicy })
- .pipe(Effect.forkScoped);
- const secondResumeFiber = yield* runtime
- .resumeThread({ providerThread, modelSelection, runtimePolicy })
- .pipe(Effect.forkScoped);
- const snapshotProviderThread = {
- ...providerThread,
- nativeThreadRef: {
- ...providerThread.nativeThreadRef!,
- nativeId: "mock-session-snapshot",
- },
- };
- const snapshotFiber = yield* runtime
- .readThreadSnapshot({ providerThread: snapshotProviderThread })
- .pipe(Effect.forkScoped);
- const forkFiber = yield* runtime
- .forkThread({
- sourceProviderThread: providerThread,
- targetThreadId: ThreadId.make("thread-acp-concurrent-fork-after-teardown"),
- })
- .pipe(Effect.forkScoped);
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
- assert.isUndefined(resumeFiber.pollUnsafe());
- assert.isUndefined(secondResumeFiber.pollUnsafe());
- assert.isUndefined(snapshotFiber.pollUnsafe());
- assert.isUndefined(forkFiber.pollUnsafe());
- assert.equal(runtimeOrdinalSeen, 1);
- const methodsDuringTeardown = yield* pollProtocolMethods(protocolEvents);
- assert.notInclude(methodsDuringTeardown, "session/resume");
- assert.notInclude(methodsDuringTeardown, "session/fork");
- const cancelInterruptOwner = yield* Fiber.interrupt(interruptFiber).pipe(Effect.forkScoped);
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
- assert.isUndefined(cancelInterruptOwner.pollUnsafe());
- yield* Deferred.succeed(releaseTeardown, undefined);
- yield* Fiber.join(cancelInterruptOwner);
- yield* Fiber.join(resumeFiber);
- yield* Fiber.join(secondResumeFiber);
- yield* Fiber.join(snapshotFiber);
- yield* Fiber.join(forkFiber);
- assert.equal(runtimeOrdinalSeen, 2);
- const methodsAfterRestart = yield* pollProtocolMethods(protocolEvents);
- assert.equal(methodsAfterRestart.filter((method) => method === "session/resume").length, 2);
- assert.equal(methodsAfterRestart.filter((method) => method === "session/fork").length, 1);
- }).pipe(Effect.provide(layerTest), Effect.scoped),
- );
-
it.effect(
"direct Stop on a deferred subagent hold terminalizes the subagent and does not carry it forward",
() =>
@@ -9305,96 +6807,9 @@ describe("AcpAdapterV2", () => {
);
});
-describe("acpPostSettleWakeEvidence", () => {
- const sessionId = "session-wake";
-
- it("rejects monitor end chatter and background mutations", () => {
- assert.isFalse(
- acpPostSettleWakeEvidence({
- sessionId,
- update: {
- sessionUpdate: "agent_message_chunk",
- content: {
- type: "text",
- text: 'Monitor "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" ended',
- },
- },
- }),
- );
- assert.isFalse(
- acpPostSettleWakeEvidence(
- {
- sessionId,
- update: {
- sessionUpdate: "user_message_chunk",
- content: { type: "text", text: "task-1 completed" },
- },
- },
- {
- extractBackgroundToolMutation: () => [
- {
- taskId: "task-1",
- status: "completed",
- appendOutput: "",
- },
- ],
- },
- ),
- );
- });
-});
-
describe("acpPostSettleContinuationOfferEvidence", () => {
const sessionId = "session-wake-offer";
- it("buffers in-progress tool updates without offering", () => {
- assert.isTrue(
- acpPostSettleWakeEvidence({
- sessionId,
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: "call-1",
- title: "run_terminal_command",
- status: "in_progress",
- kind: "other",
- content: [],
- locations: [],
- rawInput: {},
- },
- }),
- );
- assert.isFalse(
- acpPostSettleContinuationOfferEvidence({
- sessionId,
- update: {
- sessionUpdate: "tool_call_update",
- toolCallId: "call-1",
- title: "run_terminal_command",
- status: "in_progress",
- kind: "other",
- content: [],
- locations: [],
- rawInput: {},
- },
- }),
- );
- assert.isFalse(
- acpPostSettleContinuationOfferEvidence({
- sessionId,
- update: {
- sessionUpdate: "tool_call",
- toolCallId: "call-1",
- title: "run_terminal_command",
- status: "pending",
- kind: "other",
- content: [],
- locations: [],
- rawInput: {},
- },
- }),
- );
- });
-
it("does not offer on a normalized monitor start ACK despite raw completed status", () => {
const monitorStartAck = {
sessionId,
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
index 5fec3ecdd41..0ec6920620d 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
@@ -757,6 +757,7 @@ describe("AcpRegistryAdapterV2", () => {
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
+ // regression: #19519 models come from session model state, not a hardcoded list
it.effect("leaves unadvertised model IDs alone in both model selection protocols", () =>
Effect.gen(function* () {
const { configurations } = yield* openWithStoredPicks({
@@ -898,73 +899,7 @@ describe("AcpRegistryAdapterV2", () => {
);
});
- it.effect("offers client terminals to Devin only and client fs to no registry agent", () =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const path = yield* Path.Path;
- const mockAgentPath = yield* path.fromFileUrl(
- new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
- );
- const advertisedCapabilities = Effect.fn("advertisedCapabilities")(function* (
- agentId: string,
- ) {
- let clientCapabilities: unknown;
- const instanceId = ProviderInstanceId.make(`acp-registry-capabilities-${agentId}`);
- const adapter = yield* makeAcpRegistryAdapterV2({
- selfInvocation: yield* resolveSelfInvocation(),
- instanceId,
- settings: yield* decodeAcpRegistryAdapterSettings({ agentId, authMethodId: "test" }),
- environment: {},
- makeRuntime: (input) =>
- Effect.gen(function* () {
- clientCapabilities = input.clientCapabilities;
- const { processEnvironment: _processEnvironment, ...runtimeInput } = input;
- const context = yield* Layer.build(
- AcpSessionRuntime.layer({
- ...runtimeInput,
- spawn: {
- command: process.execPath,
- args: [mockAgentPath],
- cwd: input.cwd,
- env: { T3_ACP_SESSION_LIFECYCLE: "1" },
- },
- authMethodId: "test",
- }).pipe(
- Layer.provide(
- Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
- ),
- ),
- );
- return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
- Effect.provide(context),
- );
- }),
- }).pipe(Effect.provide(layerInjectedRuntimeCatalog));
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd: process.cwd(),
- });
- yield* adapter.openSession({
- threadId: ThreadId.make(`thread-acp-registry-capabilities-${agentId}`),
- providerSessionId: ProviderSessionId.make(`provider-session-capabilities-${agentId}`),
- modelSelection: { instanceId, model: "default" },
- runtimePolicy,
- });
- return clientCapabilities;
- });
-
- assert.deepInclude(yield* advertisedCapabilities("devin"), {
- fs: { readTextFile: false, writeTextFile: false },
- terminal: true,
- });
- assert.deepInclude(yield* advertisedCapabilities("gemini"), {
- fs: { readTextFile: false, writeTextFile: false },
- terminal: false,
- });
- }).pipe(Effect.provide(layerTest), Effect.scoped),
- );
-
+ // regression: #21618 Claude Agent needs ACP v2 for native background lifecycle
it.effect("launches Claude Agent on ACP v2 unless its instance environment decides", () =>
Effect.gen(function* () {
const launchSwitch = Effect.fn("launchSwitch")(function* (
diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
index 6eac3f9e40f..58871bfdd3a 100644
--- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
@@ -377,111 +377,6 @@ describe("AntigravityAdapterV2 workspace changes", () => {
);
});
-describe("AntigravityAdapterV2 client file system under restrictive policies", () => {
- it.effect("serves in-workspace reads and writes and still refuses outside paths", () =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const fileSystem = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const crypto = yield* Crypto.Crypto;
- const mockAgentPath = yield* path.fromFileUrl(
- new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
- );
- type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
- const policies = [
- {
- name: "read-only sandbox",
- policy: {
- runtimeMode: "full-access",
- approvalPolicy: "never",
- sandboxPolicy: { type: "readOnly" },
- },
- },
- { name: "approval-required", policy: { runtimeMode: "approval-required" } },
- ] as const;
- for (const { name, policy } of policies) {
- let readTextFile: Parameters<RuntimeService["handleReadTextFile"]>[0] | undefined;
- let writeTextFile: Parameters<RuntimeService["handleWriteTextFile"]>[0] | undefined;
- const instanceId = ProviderInstanceId.make(`antigravity-restrictive-${policy.runtimeMode}`);
- const adapter = yield* makeAntigravityAdapterV2({
- instanceId,
- selfInvocation: yield* resolveSelfInvocation(),
- makeRuntime: (input) =>
- makeAntigravityAcpRuntime({
- ...input,
- childProcessSpawner,
- spawn: {
- command: process.execPath,
- args: [mockAgentPath],
- cwd: input.cwd,
- env: { T3_ACP_ANTIGRAVITY: "1" },
- },
- }).pipe(
- Effect.provideService(Crypto.Crypto, crypto),
- Effect.map((runtime): RuntimeService => ({
- ...runtime,
- handleReadTextFile: (handler) =>
- Effect.sync(() => {
- readTextFile = handler;
- }).pipe(Effect.andThen(runtime.handleReadTextFile(handler))),
- handleWriteTextFile: (handler) =>
- Effect.sync(() => {
- writeTextFile = handler;
- }).pipe(Effect.andThen(runtime.handleWriteTextFile(handler))),
- })),
- ),
- withProcess: (_stop, task) => task,
- defaultModel: Effect.succeed(undefined),
- });
- const workspace = yield* fileSystem.makeTempDirectoryScoped({
- prefix: "t3-ag-restrictive-",
- });
- const outside = yield* fileSystem.makeTempDirectoryScoped({
- prefix: "t3-ag-restrictive-outside-",
- });
- yield* fileSystem.writeFileString(path.join(workspace, "existing.ts"), "existing");
- const threadId = ThreadId.make(`thread-antigravity-restrictive-${policy.runtimeMode}`);
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- ...policy,
- interactionMode: "default",
- cwd: workspace,
- });
- const modelSelection = { instanceId, model: "gemini-test-low" } as const;
- const session = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make(
- `provider-session-antigravity-restrictive-${policy.runtimeMode}`,
- ),
- modelSelection,
- runtimePolicy,
- });
- yield* session.ensureThread({ threadId, modelSelection, runtimePolicy });
- if (readTextFile === undefined || writeTextFile === undefined) {
- return yield* Effect.die("Antigravity sessions must serve client file requests");
- }
- const context = (method: string) => ({ requestId: `test-${method}`, method });
- const read = yield* readTextFile(
- { sessionId: "mock-session-1", path: path.join(workspace, "existing.ts") },
- context("fs/read_text_file"),
- );
- assert.equal(read.content, "existing", name);
- const written = path.join(workspace, "src", "edited.ts");
- yield* writeTextFile(
- { sessionId: "mock-session-1", path: written, content: "edited" },
- context("fs/write_text_file"),
- );
- assert.equal(yield* fileSystem.readFileString(written), "edited", name);
- const outsideWrite = yield* writeTextFile(
- { sessionId: "mock-session-1", path: path.join(outside, "x.ts"), content: "x" },
- context("fs/write_text_file"),
- ).pipe(Effect.exit);
- assert.isTrue(Exit.isFailure(outsideWrite), name);
- assert.isFalse(yield* fileSystem.exists(path.join(outside, "x.ts")), name);
- }
- }).pipe(Effect.provide(layerSession), Effect.scoped),
- );
-});
-
describe("AntigravityAdapterV2 html_render pages", () => {
it.effect("shows the page html_render published when the agent reports only a summary", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index 8f88a661fb9..c7f23fb3c89 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -49,7 +49,6 @@ import {
ThreadId,
} from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
-import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
@@ -316,29 +315,6 @@ describe("ClaudeAdapterV2 runtime query policy", () => {
});
});
- it("maps canonical read-only on-request policy to Claude default with callbacks", () => {
- const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
- ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd: "/workspace",
- approvalPolicy: "on-request",
- sandboxPolicy: {
- type: "readOnly",
- access: { type: "fullAccess" },
- networkAccess: false,
- },
- }),
- );
-
- assert.deepEqual(queryPolicy, {
- permissionMode: "default",
- tools: ClaudeAdapterV2.CLAUDE_READ_ONLY_ALLOWED_TOOLS,
- allowedTools: ClaudeAdapterV2.CLAUDE_READ_ONLY_ALLOWED_TOOLS,
- installPermissionCallback: true,
- });
- });
-
it("does not auto-allow reads for canonical restricted read-only never policy", () => {
const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
@@ -422,45 +398,6 @@ describe("ClaudeAdapterV2 runtime query policy", () => {
installPermissionCallback: true,
});
});
-
- it("honors never approvals for approval-required workspace-write policy", () => {
- const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
- ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "approval-required",
- interactionMode: "default",
- cwd: "/workspace",
- approvalPolicy: "never",
- sandboxPolicy: {
- type: "workspaceWrite",
- },
- }),
- );
-
- assert.deepEqual(queryPolicy, {
- permissionMode: "dontAsk",
- installPermissionCallback: false,
- });
- });
-
- it("honors never approvals for externally sandboxed policy", () => {
- const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
- ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "approval-required",
- interactionMode: "default",
- cwd: "/workspace",
- approvalPolicy: "never",
- sandboxPolicy: {
- type: "externalSandbox",
- },
- }),
- );
-
- assert.deepEqual(queryPolicy, {
- permissionMode: "bypassPermissions",
- allowDangerouslySkipPermissions: true,
- installPermissionCallback: false,
- });
- });
});
describe("ClaudeAdapterV2 MCP query overrides", () => {
@@ -507,37 +444,6 @@ describe("ClaudeAdapterV2 MCP query overrides", () => {
assert.isFalse(overrides.allowedTools?.includes(ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_WILDCARD));
});
- it("keys live-query reuse on the MCP-derived pre-approvals", () => {
- const threadId = ThreadId.make("thread-claude-mcp-query-key");
- const mcpSession = mcpSessionFor(threadId);
- const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
- ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd: "/workspace",
- approvalPolicy: "on-request",
- sandboxPolicy: {
- type: "readOnly",
- access: { type: "fullAccess" },
- networkAccess: false,
- },
- }),
- );
-
- const readOnlyKey = ClaudeAdapterV2.claudeEffectiveQueryPolicyKey(
- queryPolicy,
- ClaudeAdapterV2.claudeMcpQueryOverrides({ mcpSession, readOnlySandbox: true }),
- );
- const fullAccessKey = ClaudeAdapterV2.claudeEffectiveQueryPolicyKey(
- queryPolicy,
- ClaudeAdapterV2.claudeMcpQueryOverrides({ mcpSession, readOnlySandbox: false }),
- );
- const detachedKey = ClaudeAdapterV2.claudeEffectiveQueryPolicyKey(queryPolicy, {});
-
- assert.notEqual(readOnlyKey, fullAccessKey);
- assert.notEqual(fullAccessKey, detachedKey);
- });
-
it("invalidates live-query reuse when MCP credentials rotate", () => {
const threadId = ThreadId.make("thread-claude-mcp-credential-rotation");
const mcpSession = mcpSessionFor(threadId);
@@ -641,50 +547,6 @@ describe("ClaudeAdapterV2 native protocol logging", () => {
assert.equal(logged.hasMcpServers, true);
assert.notInclude(JSON.stringify(logged), "secret-claude-token");
});
-
- it("logs query options without leaking environment values or callback functions", () => {
- const options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions = {
- model: "claude-sonnet-4-6",
- tools: {
- type: "preset",
- preset: "claude_code",
- },
- permissionMode: "default",
- sessionId: "native-thread-1",
- cwd: "/workspace",
- env: {
- ANTHROPIC_API_KEY: "secret",
- },
- extraArgs: {
- "append-system-prompt": "secret launch prompt",
- },
- canUseTool: (_toolName, input, callbackOptions) =>
- Promise.resolve({
- behavior: "allow",
- updatedInput: input,
- toolUseID: callbackOptions.toolUseID,
- decisionClassification: "user_temporary",
- }),
- };
-
- assert.deepEqual(ClaudeAdapterV2.loggedClaudeQueryOptions(options), {
- model: "claude-sonnet-4-6",
- tools: {
- type: "preset",
- preset: "claude_code",
- },
- permissionMode: "default",
- sessionId: "native-thread-1",
- cwd: "/workspace",
- hasCanUseTool: true,
- hasEnvironment: true,
- hasExtraArgs: true,
- });
- assert.notInclude(
- JSON.stringify(ClaudeAdapterV2.loggedClaudeQueryOptions(options)),
- "secret launch prompt",
- );
- });
});
describe("ClaudeAdapterV2 context usage", () => {
@@ -705,6 +567,7 @@ describe("ClaudeAdapterV2 context usage", () => {
});
describe("ClaudeAdapterV2 session permissions", () => {
+ // regression: #15892 an explicit user refusal must stay user_reject, not a tool failure
it("keeps explicit user refusals classified as user_reject", () => {
const result = ClaudeAdapterV2.permissionResultFromDecision({
toolName: "Bash",
@@ -986,6 +849,7 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {
),
);
+ // regression: #20413 malformed append-system-prompt launch args fail before a query opens
it.effect.each([
[
"--append-system-prompt-file missing.md",
@@ -1630,95 +1494,6 @@ describe("ClaudeAdapterV2 attachments", () => {
),
),
);
-
- it.effect("rejects unsupported image types before opening a provider query", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const fileSystem = yield* FileSystem.FileSystem;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
- prefix: "t3-claude-v2-unsupported-attachment-",
- });
- let openCount = 0;
- const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
- instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
- settings: DEFAULT_CLAUDE_SETTINGS,
- environment: {},
- attachmentsDir,
- fileSystem,
- path: yield* Path.Path,
- crypto: yield* Crypto.Crypto,
- idAllocator,
- queryRunner: {
- allocateSessionId: Effect.succeed("native-thread-claude-unsupported-attachment"),
- open: () =>
- Effect.sync(() => {
- openCount += 1;
- return {
- messages: Stream.never,
- offer: () => Effect.void,
- setModel: () => Effect.void,
- applyFlagSettings: () => Effect.void,
- setPermissionMode: () => Effect.void,
- backgroundTasks: () => Effect.succeed(false),
- stopTask: () => Effect.void,
- interrupt: Effect.void,
- close: Effect.void,
- };
- }),
- forkSession: () => Effect.die("unused forkSession"),
- subagentLaunchToolUseId: () => Effect.succeed(null),
- assertComplete: Effect.void,
- },
- });
- const threadId = ThreadId.make("thread-claude-unsupported-attachment");
- const runtime = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make(
- "provider-session-claude-unsupported-attachment",
- ),
- modelSelection: CLAUDE_TEST_MODEL_SELECTION,
- runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
- });
- const providerThread = yield* runtime.ensureThread({
- threadId,
- modelSelection: CLAUDE_TEST_MODEL_SELECTION,
- runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
- });
- const attachment = ChatImageAttachment.make({
- type: "image",
- id: ChatAttachmentId.make(
- "thread-claude-unsupported-12345678-1234-1234-1234-123456789abc",
- ),
- name: "diagram.svg",
- mimeType: "image/svg+xml",
- sizeBytes: 4,
- });
- const now = yield* DateTime.now;
-
- const error = yield* runtime
- .startTurn(
- makeClaudeTestTurnInput({
- threadId,
- providerThread,
- now,
- attemptId: RunAttemptId.make("attempt-claude-unsupported-attachment"),
- text: "Inspect this image.",
- attachments: [attachment],
- }),
- )
- .pipe(Effect.flip);
-
- assert.equal(error._tag, "ProviderAdapterTurnStartError");
- assert.include(String(error.cause), "Unsupported Claude image attachment type");
- assert.equal(openCount, 0);
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
});
describe("ClaudeAdapterV2 native fork", () => {
@@ -2864,6 +2639,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
+ // regression: #21806 bypass policy reads the custom home and project, never ambient ~/.claude
it.effect(
"combines a normalized custom home with project policy without reading the ambient user tier",
() =>
@@ -2912,6 +2688,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
+ // regression: #21806 only a missing custom settings file is benign; bad policy fails
it.effect(
"distinguishes missing custom settings from unreadable, malformed, or unresolved policy",
() =>
@@ -3220,6 +2997,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
+ // regression: #15475 MCP title arriving after the tool starts must survive to completion
it.effect.each([
{ isError: false, title: "Check weather" },
{ isError: true, title: "Check weather" },
@@ -3545,6 +3323,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
+ // regression: #15892 non-execution metadata is carried through, not guessed from result text
it.effect.each(["cancelled", "denied", "permission_denied", undefined])(
"preserves native tool non-execution metadata %s without inferring a denial from text",
(kind) =>
@@ -4869,70 +4648,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
- it.effect("surfaces a Claude safety model fallback without failing the turn", () =>
- 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("claude-safety-fallback-attempt"),
- text: "Continue the audit",
- attachments: [],
- }),
- );
- const notice = "Safeguards flagged this message. Switched to Opus 4.8.";
- const uuid = "00000000-0000-4000-8000-000000000301";
- yield* Queue.offer(
- harness.sdkMessages,
- claudeSdkFrame({
- type: "system",
- subtype: "model_refusal_fallback",
- trigger: "refusal",
- direction: "retry",
- original_model: "claude-fable-5",
- fallback_model: "claude-opus-4-8",
- request_id: "request-safety-fallback",
- api_refusal_category: "cyber",
- api_refusal_explanation: null,
- content: notice,
- session_id: WAKE_NATIVE_SESSION,
- uuid,
- }),
- );
- yield* Queue.offer(
- harness.sdkMessages,
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000000302",
- result: "Audit complete.",
- }),
- );
- yield* Queue.take(harness.terminalReceipts);
- const notices = harness.events.flatMap((event) =>
- event.type === "turn_item.updated" && event.turnItem.type === "system_notice"
- ? [event.turnItem]
- : [],
- );
- assert.lengthOf(notices, 1);
- assert.equal(notices[0]?.message, notice);
- assert.equal(notices[0]?.status, "completed");
- assert.equal(notices[0]?.nativeItemRef?.nativeId, uuid);
- assert.equal(harness.terminalEvents()[0]?.status, "completed");
- assert.isFalse(
- harness.events.some(
- (event) => event.type === "turn_item.updated" && event.turnItem.type === "error",
- ),
- );
- }).pipe(
- Effect.scoped,
- Effect.provide(
- Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
- ),
- ),
- );
-
it.effect("shows a hook-dropped Claude prompt once and skips info-level lines", () =>
Effect.gen(function* () {
const harness = yield* makeWakeHarness;
@@ -6194,6 +5909,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
+ // regression: #14964 structured task output attaches to exactly one tool result
it.effect("does not associate structured task output with multiple tool results", () =>
Effect.gen(function* () {
const harness = yield* makeTaskToolHarness;
@@ -6287,125 +6003,56 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
- it.effect("carries exhausted retry progress into the terminal provider error", () =>
- 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-api-retry-exhausted"),
- text: "Open github.com.",
- attachments: [],
- }),
- );
- yield* Queue.offer(
- harness.sdkMessages,
- claudeSdkFrame({
- type: "system",
- subtype: "api_retry",
- attempt: 10,
- max_retries: 10,
- retry_delay_ms: 38_010,
- error_status: 529,
- error: "overloaded",
- uuid: "00000000-0000-4000-8000-000000000203",
- session_id: WAKE_NATIVE_SESSION,
- }),
- );
- yield* Queue.offer(
- harness.sdkMessages,
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000000204",
- result: "Claude is temporarily overloaded.",
- isError: true,
- apiErrorStatus: 529,
- }),
- );
- yield* harness.awaitTerminal(1);
-
- const terminal = harness.terminalEvents()[0];
- assert.equal(terminal?.status, "failed");
- if (terminal?.status !== "failed") return;
- assert.deepEqual(terminal.retry, {
- attempt: 10,
- maxAttempts: 10,
- retryDelayMs: 38_010,
- });
- assert.isDefined(terminal.retryStartedAt);
- assert.equal(terminal.failure.code, "api_error_529");
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
- it.effect.each([
- "api_error",
- "malformed_tool_use_exhausted",
- "budget_exhausted",
- "structured_output_retry_exhausted",
- "tool_deferred_unavailable",
- "turn_setup_failed",
- "blocking_limit",
- "rapid_refill_breaker",
- "prompt_too_long",
- "image_error",
- "model_error",
- "overloaded_status",
- ] as const)("fails a success-shaped Claude result with %s", (terminalReason) =>
- 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-structured-terminal-failure"),
- text: "Complete the task.",
- attachments: [],
- }),
- );
- yield* Queue.offer(
- harness.sdkMessages,
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000000205",
- result: "Provider failure details.",
- isError: false,
- ...(terminalReason === "overloaded_status"
- ? { apiErrorStatus: 529 }
- : { terminalReason }),
- }),
- );
- const terminal = yield* Queue.take(harness.terminalReceipts);
- assert.equal(terminal.status, "failed");
- if (terminal.status !== "failed") return;
- assert.isNotEmpty(terminal.failure.message);
- assert.equal(terminal.failure.class, "provider_error");
- assert.isFalse(
- harness.events.some(
- (event) =>
- event.type === "message.updated" &&
- event.message.text === "Provider failure details.",
+ it.effect.each(["api_error", "overloaded_status"] as const)(
+ "fails a success-shaped Claude result with %s",
+ (terminalReason) =>
+ 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-structured-terminal-failure"),
+ text: "Complete the task.",
+ attachments: [],
+ }),
+ );
+ yield* Queue.offer(
+ harness.sdkMessages,
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000205",
+ result: "Provider failure details.",
+ isError: false,
+ ...(terminalReason === "overloaded_status"
+ ? { apiErrorStatus: 529 }
+ : { terminalReason }),
+ }),
+ );
+ const terminal = yield* Queue.take(harness.terminalReceipts);
+ assert.equal(terminal.status, "failed");
+ if (terminal.status !== "failed") return;
+ assert.isNotEmpty(terminal.failure.message);
+ assert.equal(terminal.failure.class, "provider_error");
+ assert.isFalse(
+ harness.events.some(
+ (event) =>
+ event.type === "message.updated" &&
+ event.message.text === "Provider failure details.",
+ ),
+ );
+ assert.equal(
+ terminal.failure.code,
+ terminalReason === "overloaded_status" ? "api_error_529" : terminalReason,
+ );
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
- );
- assert.equal(
- terminal.failure.code,
- terminalReason === "overloaded_status" ? "api_error_529" : terminalReason,
- );
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
- ),
);
// Frames follow #19832: a full context window ends the turn with
@@ -7605,101 +7252,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
- it.effect("drops a zero-turn task-notification result while awaiting a prompt echo", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const harness = yield* makeWakeHarness;
- const now = yield* DateTime.now;
- const firstAttempt = RunAttemptId.make("attempt-claude-echo-debris-1");
- const secondAttempt = RunAttemptId.make("attempt-claude-echo-debris-2");
- const stamp = (frame: SDKMessage, promptIndex: number) =>
- claudeSdkFrame({
- ...frame,
- user_message_uuid: harness.promptUuid(promptIndex),
- });
-
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: firstAttempt,
- text: "First.",
- attachments: [],
- }),
- );
- yield* Queue.offer(
- harness.sdkMessages,
- stamp(
- makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000760", text: "One." }),
- 0,
- ),
- );
- yield* Queue.offer(
- harness.sdkMessages,
- stamp(
- makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000761", result: "One." }),
- 0,
- ),
- );
- yield* harness.awaitTerminal(1);
-
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: secondAttempt,
- text: "Second.",
- attachments: [],
- providerTurnOrdinal: 2,
- }),
- );
- yield* Queue.offer(
- harness.sdkMessages,
- makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000764", text: "Stale." }),
- );
- yield* Queue.offer(harness.sdkMessages, staleTaskNotificationResult);
- yield* Queue.offer(
- harness.sdkMessages,
- stamp(
- makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000762", text: "Two." }),
- 1,
- ),
- );
- yield* Queue.offer(
- harness.sdkMessages,
- stamp(
- makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000763", result: "Two." }),
- 1,
- ),
- );
- yield* harness.awaitTerminal(2);
- assert.equal(harness.terminalEvents()[1]?.status, "completed");
- assert.lengthOf(harness.continuationRequests, 0);
- assert.deepEqual(
- harness.events.flatMap((event) =>
- event.type === "message.updated" && event.message.role === "assistant"
- ? [event.message.text]
- : [],
- ),
- ["One.", "Stale.", "Two."],
- );
- assert.isFalse(
- harness.events.some(
- (event) =>
- event.type === "message.updated" &&
- event.message.text === STALE_TASK_NOTIFICATION_RESULT_TEXT,
- ),
- );
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
it.effect("releases output held for a prompt echo when the stream ends", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -7816,6 +7368,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
+ // regression: #16897 a prompt whose uuid the session already holds must not hang or end early
it.effect("keeps a started prompt running until its result", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -8177,72 +7730,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
- it.effect("terminalizes an agent server wake from a positive task-notification result", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const harness = yield* makeWakeHarness;
- const now = yield* DateTime.now;
- const wakeText = "The background command completed.";
-
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make("attempt-claude-agent-server-wake"),
- text: "Background task completed.",
- attachments: [],
- messageCreatedBy: "agent",
- messageCreationSource: "server",
- }),
- );
- yield* Queue.offer(
- harness.sdkMessages,
- makeAssistantTextFrame({
- uuid: "00000000-0000-4000-8000-00000000010b",
- text: wakeText,
- }),
- );
- yield* Queue.offer(
- harness.sdkMessages,
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-00000000010c",
- result: wakeText,
- numTurns: 154,
- origin: { kind: "task-notification" },
- }),
- );
- yield* harness.awaitTerminal(1);
- assert.equal(harness.terminalEvents()[0]?.status, "completed");
-
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make("attempt-claude-agent-server-next"),
- text: "What finished?",
- attachments: [],
- providerTurnOrdinal: 2,
- }),
- );
- yield* Queue.offer(
- harness.sdkMessages,
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-00000000010d",
- result: "The background command finished.",
- }),
- );
- yield* harness.awaitTerminal(2);
- assert.equal(harness.terminalEvents()[1]?.status, "completed");
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
it.effect("ignores a zero-turn task-notification origin result during a normal user turn", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -8655,375 +8142,118 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
- it.effect("a subagent re-run in the foreground does not join a later wake", () =>
+ it.effect("streams a background subagent's work while the root turn is idle", () =>
Effect.scoped(
Effect.gen(function* () {
+ const TASK_ID = "task-live-idle";
+ const TOOL_USE_ID = "toolu-live-idle";
+ const STRADDLING_BASH = "toolu-live-straddling-bash";
+ const IDLE_BASH = "toolu-live-idle-bash";
const harness = yield* makeWakeHarness;
const now = yield* DateTime.now;
- const taskId = "task-foreground-rerun";
- const toolUseId = "toolu_foreground_rerun";
- const userTurn = (attempt: string, providerTurnOrdinal: number) =>
- harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make(attempt),
- text: "Go on.",
- attachments: [],
- providerTurnOrdinal,
- }),
+ const latestToolItem = (nativeId: string) =>
+ harness.events.findLast(
+ (event) =>
+ event.type === "turn_item.updated" &&
+ event.turnItem.nativeItemRef?.nativeId === nativeId,
);
- const result = (uuid: string) => makeResultFrame({ uuid, result: "Done." });
- const ended = (uuid: string) =>
- makeSubagentNotificationFrame({ taskId, toolUseId, summary: "AUDITED", uuid });
-
- yield* userTurn("attempt-rerun-1", 1);
- yield* Queue.offer(
- harness.sdkMessages,
- makeSubagentTaskStartedFrame({
- taskId,
- toolUseId,
- uuid: "00000000-0000-4000-8000-000000000901",
- }),
- );
- yield* Queue.offer(harness.sdkMessages, result("00000000-0000-4000-8000-000000000902"));
- yield* harness.awaitTerminal(1);
- yield* Queue.offer(harness.sdkMessages, ended("00000000-0000-4000-8000-000000000903"));
- yield* harness.awaitContinuation(1);
- yield* Queue.offer(harness.sdkMessages, result("00000000-0000-4000-8000-000000000904"));
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
- attemptId: RunAttemptId.make("attempt-rerun-2"),
- text: "Background task completed.",
+ attemptId: RunAttemptId.make("attempt-claude-live-idle-1"),
+ text: "Audit in the background.",
attachments: [],
- providerTurnOrdinal: 2,
- messageCreatedBy: "agent",
- messageCreationSource: "provider",
}),
);
- yield* harness.awaitTerminal(2);
-
- yield* userTurn("attempt-rerun-3", 3);
- yield* Queue.offer(
- harness.sdkMessages,
- claudeSdkFrame({
- ...makeSubagentTaskStartedFrame({
- taskId,
- toolUseId,
- uuid: "00000000-0000-4000-8000-000000000905",
- }),
- is_backgrounded: false,
+ for (const frame of [
+ makeSubagentTaskStartedFrame({
+ taskId: TASK_ID,
+ toolUseId: TOOL_USE_ID,
+ uuid: "00000000-0000-4000-8000-000000000951",
}),
- );
- yield* Queue.offer(harness.sdkMessages, ended("00000000-0000-4000-8000-000000000906"));
- yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
- yield* Queue.offer(harness.sdkMessages, result("00000000-0000-4000-8000-000000000907"));
- yield* harness.awaitTerminal(3);
-
- yield* Queue.offer(harness.sdkMessages, wakeNotification);
- yield* Queue.offer(harness.sdkMessages, wakeAssistant);
- yield* harness.awaitContinuation(2);
- assert.equal(
- harness.continuationRequests[1]?.notification?.summary,
- `Command "${WAKE_TASK_DESCRIPTION}" finished`,
- );
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
- it.effect("a turn that fails to start does not expire a queued wake's report", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const harness = yield* makeWakeHarness;
- const now = yield* DateTime.now;
- const userTurn = (
- attempt: string,
- providerTurnOrdinal: number,
- attachments: ProviderAdapter.ProviderAdapterV2TurnInput["message"]["attachments"] = [],
- ) =>
- harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make(attempt),
- text: "Go on.",
- attachments,
- providerTurnOrdinal,
- }),
- );
-
- yield* userTurn("attempt-failed-start-1", 1);
- yield* harness.offerAndWait(wakeTaskStarted);
- yield* harness.offerAndWait(turnOneResult);
- yield* Queue.take(harness.terminalReceipts);
- yield* harness.offerAndWait(wakeNotification);
- assert.isFalse(yield* harness.hasPendingBackgroundWork);
-
- const missing = ChatImageAttachment.make({
- type: "image",
- id: ChatAttachmentId.make("thread-claude-wake-12345678-1234-1234-1234-123456789abc"),
- name: "gone.png",
- mimeType: "image/png",
- sizeBytes: 4,
- });
- const failed = yield* userTurn("attempt-failed-start-2", 2, [missing]).pipe(Effect.flip);
- assert.equal(
- makeProviderFailure({ cause: failed }).message,
- "The provider could not start this turn: an attachment could not be read. Retry the turn; if it keeps failing, check the provider setup and server logs.",
- );
-
- yield* userTurn("attempt-failed-start-3", 2);
- yield* harness.offerAndWait(
- makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000911", result: "Answered." }),
- );
- yield* Queue.take(harness.terminalReceipts);
-
- yield* harness.offerAndWait(wakeAssistant);
- const continuation = yield* Queue.take(harness.continuationReceipts);
- assert.equal(
- continuation.notification?.summary,
- `Command "${WAKE_TASK_DESCRIPTION}" finished`,
- );
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
- it.effect("keeps a subagent a queued wake turn launches with its continuation", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const TASK_ID = "a-wake-launched-subagent";
- const TOOL_USE_ID = "toolu_01WakeLaunchedAgent";
- const harness = yield* makeWakeHarness;
- const now = yield* DateTime.now;
- const firstAttempt = RunAttemptId.make("attempt-claude-wake-subagent-1");
- const userAttempt = RunAttemptId.make("attempt-claude-wake-subagent-2");
- const continuationAttempt = RunAttemptId.make("attempt-claude-wake-subagent-3");
- const runOf = (attemptId: RunAttemptId) => RunId.make(`run-${attemptId}`);
- const stamp = (frame: SDKMessage, promptIndex: number) =>
- claudeSdkFrame({
- ...frame,
- user_message_uuid: harness.promptUuid(promptIndex),
- });
-
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: firstAttempt,
- text: "Run the build in the background.",
- attachments: [],
+ ...makeSubagentAssistantFrames({
+ parentToolUseId: TOOL_USE_ID,
+ uuid: "00000000-0000-4000-8000-000000000952",
+ bashToolUseId: STRADDLING_BASH,
}),
- );
- yield* Queue.offer(harness.sdkMessages, stamp(wakeTaskStarted, 0));
- yield* Queue.offer(
- harness.sdkMessages,
- stamp(
- makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000770", result: "STARTED" }),
- 0,
- ),
- );
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000953",
+ result: "Auditing in the background.",
+ }),
+ ]) {
+ yield* Queue.offer(harness.sdkMessages, frame);
+ }
yield* harness.awaitTerminal(1);
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: userAttempt,
- text: "Reply with exactly: USER_REPLY",
- attachments: [],
- providerTurnOrdinal: 2,
- }),
- );
- const wakeFrames = [
- wakeNotification,
- claudeSdkFrame({
- type: "assistant",
- message: {
- model: "claude-sonnet-4-6",
- id: "msg_wake_agent",
- type: "message",
- role: "assistant",
- content: [
- {
- type: "tool_use",
- id: TOOL_USE_ID,
- name: "Agent",
- input: { description: "Audit recent commits", prompt: "Audit them." },
- },
- ],
- },
- parent_tool_use_id: null,
- uuid: "00000000-0000-4000-8000-000000000771",
- session_id: WAKE_NATIVE_SESSION,
- }),
- makeSubagentTaskStartedFrame({
- taskId: TASK_ID,
- toolUseId: TOOL_USE_ID,
- uuid: "00000000-0000-4000-8000-000000000772",
+ for (const frame of [
+ makeSubagentToolResultFrame({
+ parentToolUseId: TOOL_USE_ID,
+ uuid: "00000000-0000-4000-8000-000000000954",
+ toolUseId: STRADDLING_BASH,
}),
...makeSubagentAssistantFrames({
parentToolUseId: TOOL_USE_ID,
- uuid: "00000000-0000-4000-8000-000000000773",
- text: "AUDIT_DONE",
- }),
- makeSubagentNotificationFrame({
- taskId: TASK_ID,
- toolUseId: TOOL_USE_ID,
- summary: "AUDIT_DONE",
- uuid: "00000000-0000-4000-8000-000000000774",
+ uuid: "00000000-0000-4000-8000-000000000955",
+ text: "Still auditing.",
+ bashToolUseId: IDLE_BASH,
}),
claudeSdkFrame({
- type: "user",
- message: {
- role: "user",
- content: [{ type: "tool_result", tool_use_id: TOOL_USE_ID, content: "AUDIT_DONE" }],
- },
- parent_tool_use_id: null,
- uuid: "00000000-0000-4000-8000-000000000775",
+ type: "system",
+ subtype: "task_progress",
+ task_id: TASK_ID,
+ description: "Reading the last commits",
+ uuid: "00000000-0000-4000-8000-000000000956",
session_id: WAKE_NATIVE_SESSION,
}),
- wakeResult,
- stamp(
- makeAssistantTextFrame({
- uuid: "00000000-0000-4000-8000-000000000776",
- text: "USER_REPLY",
- }),
- 1,
- ),
- stamp(
- makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000777", result: "USER_REPLY" }),
- 1,
- ),
- ];
- for (const frame of wakeFrames) {
+ ]) {
yield* Queue.offer(harness.sdkMessages, frame);
}
- yield* harness.awaitTerminal(2);
-
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: continuationAttempt,
- text: "Background task completed.",
- attachments: [],
- providerTurnOrdinal: 3,
- messageCreatedBy: "agent",
- messageCreationSource: "provider",
- }),
- );
- yield* harness.awaitTerminal(3);
-
- const subagentRuns = harness.events.flatMap((event) =>
- event.type === "subagent.updated" && event.subagent.nativeTaskRef?.nativeId === TASK_ID
- ? [event.subagent.runId]
- : [],
- );
- assert.isNotEmpty(subagentRuns);
- assert.isTrue(subagentRuns.every((runId) => runId === runOf(continuationAttempt)));
- const finalSubagent = harness.events.findLast(
- (event) =>
- event.type === "subagent.updated" && event.subagent.nativeTaskRef?.nativeId === TASK_ID,
+ yield* harness.until(() => {
+ const event = latestToolItem(IDLE_BASH);
+ return event?.type === "turn_item.updated" && event.turnItem.status === "running";
+ });
+ yield* harness.until(() =>
+ harness.events.some(
+ (event) =>
+ event.type === "subagent.updated" &&
+ event.subagent.progress === "Reading the last commits",
+ ),
);
+ const routing = subagentRouting(harness.events, [STRADDLING_BASH, IDLE_BASH]);
+ assert.deepEqual(routing.assistantTexts(routing.childThreadId), ["Still auditing."]);
+ const straddling = latestToolItem(STRADDLING_BASH);
+ const straddlingItem =
+ straddling?.type === "turn_item.updated" ? straddling.turnItem : undefined;
+ assert.equal(straddlingItem?.status, "completed");
assert.equal(
- finalSubagent?.type === "subagent.updated" && finalSubagent.subagent.status,
- "completed",
- );
- const userRunItems = harness.events.flatMap((event) =>
- event.type === "turn_item.updated" && event.turnItem.runId === runOf(userAttempt)
- ? [event.turnItem.type]
- : [],
- );
- assert.deepEqual([...new Set(userRunItems)], ["assistant_message"]);
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
- it.effect("routes a subagent that starts while the root turn is idle", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const TASK_ID = "task-idle-subagent";
- const TOOL_USE_ID = "toolu-idle-subagent";
- const FINAL_REPORT = "Idle auditor done.";
- 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-idle-subagent-1"),
- text: "Wait for background work.",
- attachments: [],
- }),
- );
- yield* Queue.offer(
- harness.sdkMessages,
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000000331",
- result: "Waiting in the background.",
- }),
+ straddlingItem?.type === "command_execution" ? straddlingItem.input : undefined,
+ "git log -5",
);
- yield* harness.awaitTerminal(1);
+ assert.equal(harness.continuationRequests.length, 0);
- const idleFrames = [
- makeSubagentTaskStartedFrame({
- taskId: TASK_ID,
- toolUseId: TOOL_USE_ID,
- uuid: "00000000-0000-4000-8000-000000000332",
- }),
- ...makeSubagentAssistantFrames({
- parentToolUseId: TOOL_USE_ID,
- uuid: "00000000-0000-4000-8000-000000000333",
- text: "Idle auditor working.",
- bashToolUseId: "toolu-idle-bash",
- }),
+ for (const frame of [
makeSubagentToolResultFrame({
parentToolUseId: TOOL_USE_ID,
- uuid: "00000000-0000-4000-8000-000000000334",
- toolUseId: "toolu-idle-bash",
- }),
- ...makeSubagentAssistantFrames({
- parentToolUseId: TOOL_USE_ID,
- uuid: "00000000-0000-4000-8000-000000000335",
- text: FINAL_REPORT,
+ uuid: "00000000-0000-4000-8000-000000000957",
+ toolUseId: IDLE_BASH,
}),
makeSubagentNotificationFrame({
taskId: TASK_ID,
toolUseId: TOOL_USE_ID,
- summary: FINAL_REPORT,
- uuid: "00000000-0000-4000-8000-000000000336",
+ summary: "Still auditing.",
+ uuid: "00000000-0000-4000-8000-000000000958",
}),
- ];
- for (const frame of idleFrames) {
+ ]) {
yield* Queue.offer(harness.sdkMessages, frame);
}
yield* harness.awaitContinuation(1);
yield* Queue.offer(
harness.sdkMessages,
makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000000337",
- result: "The idle auditor finished.",
+ uuid: "00000000-0000-4000-8000-000000000959",
+ result: "The auditor finished.",
}),
);
yield* harness.runtime.startTurn(
@@ -9031,7 +8261,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
- attemptId: RunAttemptId.make("attempt-claude-idle-subagent-2"),
+ attemptId: RunAttemptId.make("attempt-claude-live-idle-2"),
text: "Background task completed.",
attachments: [],
providerTurnOrdinal: 2,
@@ -9041,179 +8271,23 @@ describe("ClaudeAdapterV2 background wake turns", () => {
);
yield* harness.awaitTerminal(2);
- const routing = subagentRouting(harness.events, ["toolu-idle-bash"]);
- assert.isDefined(routing.childThreadId);
- assert.deepEqual(
- [...(routing.toolThreadIds.get("toolu-idle-bash") ?? [])],
- [routing.childThreadId],
- );
- assert.deepEqual(routing.assistantTexts(routing.childThreadId), [
- "Idle auditor working.",
- FINAL_REPORT,
- ]);
- assert.deepEqual(routing.assistantTexts(harness.threadId), [
- "Waiting in the background.",
- "The idle auditor finished.",
+ const finalRouting = subagentRouting(harness.events, [STRADDLING_BASH, IDLE_BASH]);
+ assert.deepEqual(finalRouting.assistantTexts(finalRouting.childThreadId), [
+ "Still auditing.",
]);
- const finalSubagent = harness.events.findLast((event) => event.type === "subagent.updated");
- assert.equal(
- finalSubagent?.type === "subagent.updated" && finalSubagent.subagent.status,
- "completed",
- );
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
- it.effect("streams a background subagent's work while the root turn is idle", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const TASK_ID = "task-live-idle";
- const TOOL_USE_ID = "toolu-live-idle";
- const STRADDLING_BASH = "toolu-live-straddling-bash";
- const IDLE_BASH = "toolu-live-idle-bash";
- const harness = yield* makeWakeHarness;
- const now = yield* DateTime.now;
- const latestToolItem = (nativeId: string) =>
- harness.events.findLast(
- (event) =>
- event.type === "turn_item.updated" &&
- event.turnItem.nativeItemRef?.nativeId === nativeId,
- );
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make("attempt-claude-live-idle-1"),
- text: "Audit in the background.",
- attachments: [],
- }),
- );
- for (const frame of [
- makeSubagentTaskStartedFrame({
- taskId: TASK_ID,
- toolUseId: TOOL_USE_ID,
- uuid: "00000000-0000-4000-8000-000000000951",
- }),
- ...makeSubagentAssistantFrames({
- parentToolUseId: TOOL_USE_ID,
- uuid: "00000000-0000-4000-8000-000000000952",
- bashToolUseId: STRADDLING_BASH,
- }),
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000000953",
- result: "Auditing in the background.",
- }),
- ]) {
- yield* Queue.offer(harness.sdkMessages, frame);
- }
- yield* harness.awaitTerminal(1);
-
- for (const frame of [
- makeSubagentToolResultFrame({
- parentToolUseId: TOOL_USE_ID,
- uuid: "00000000-0000-4000-8000-000000000954",
- toolUseId: STRADDLING_BASH,
- }),
- ...makeSubagentAssistantFrames({
- parentToolUseId: TOOL_USE_ID,
- uuid: "00000000-0000-4000-8000-000000000955",
- text: "Still auditing.",
- bashToolUseId: IDLE_BASH,
- }),
- claudeSdkFrame({
- type: "system",
- subtype: "task_progress",
- task_id: TASK_ID,
- description: "Reading the last commits",
- uuid: "00000000-0000-4000-8000-000000000956",
- session_id: WAKE_NATIVE_SESSION,
- }),
- ]) {
- yield* Queue.offer(harness.sdkMessages, frame);
- }
- yield* harness.until(() => {
- const event = latestToolItem(IDLE_BASH);
- return event?.type === "turn_item.updated" && event.turnItem.status === "running";
- });
- yield* harness.until(() =>
- harness.events.some(
- (event) =>
- event.type === "subagent.updated" &&
- event.subagent.progress === "Reading the last commits",
- ),
- );
- const routing = subagentRouting(harness.events, [STRADDLING_BASH, IDLE_BASH]);
- assert.deepEqual(routing.assistantTexts(routing.childThreadId), ["Still auditing."]);
- const straddling = latestToolItem(STRADDLING_BASH);
- const straddlingItem =
- straddling?.type === "turn_item.updated" ? straddling.turnItem : undefined;
- assert.equal(straddlingItem?.status, "completed");
- assert.equal(
- straddlingItem?.type === "command_execution" ? straddlingItem.input : undefined,
- "git log -5",
- );
- assert.equal(harness.continuationRequests.length, 0);
-
- for (const frame of [
- makeSubagentToolResultFrame({
- parentToolUseId: TOOL_USE_ID,
- uuid: "00000000-0000-4000-8000-000000000957",
- toolUseId: IDLE_BASH,
- }),
- makeSubagentNotificationFrame({
- taskId: TASK_ID,
- toolUseId: TOOL_USE_ID,
- summary: "Still auditing.",
- uuid: "00000000-0000-4000-8000-000000000958",
- }),
- ]) {
- yield* Queue.offer(harness.sdkMessages, frame);
- }
- yield* harness.awaitContinuation(1);
- yield* Queue.offer(
- harness.sdkMessages,
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000000959",
- result: "The auditor finished.",
- }),
- );
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make("attempt-claude-live-idle-2"),
- text: "Background task completed.",
- attachments: [],
- providerTurnOrdinal: 2,
- messageCreatedBy: "agent",
- messageCreationSource: "provider",
- }),
- );
- yield* harness.awaitTerminal(2);
-
- const finalRouting = subagentRouting(harness.events, [STRADDLING_BASH, IDLE_BASH]);
- assert.deepEqual(finalRouting.assistantTexts(finalRouting.childThreadId), [
- "Still auditing.",
- ]);
- for (const nativeId of [STRADDLING_BASH, IDLE_BASH]) {
- assert.deepEqual(
- [...(finalRouting.toolThreadIds.get(nativeId) ?? [])],
- [finalRouting.childThreadId],
- );
- const statuses = harness.events.flatMap((event) =>
- event.type === "turn_item.updated" &&
- event.turnItem.nativeItemRef?.nativeId === nativeId
- ? [`${event.turnItem.type}:${event.turnItem.status}`]
- : [],
- );
- assert.deepEqual(statuses, ["command_execution:running", "command_execution:completed"]);
- }
+ for (const nativeId of [STRADDLING_BASH, IDLE_BASH]) {
+ assert.deepEqual(
+ [...(finalRouting.toolThreadIds.get(nativeId) ?? [])],
+ [finalRouting.childThreadId],
+ );
+ const statuses = harness.events.flatMap((event) =>
+ event.type === "turn_item.updated" &&
+ event.turnItem.nativeItemRef?.nativeId === nativeId
+ ? [`${event.turnItem.type}:${event.turnItem.status}`]
+ : [],
+ );
+ assert.deepEqual(statuses, ["command_execution:running", "command_execution:completed"]);
+ }
const finalSubagent = harness.events.findLast((event) => event.type === "subagent.updated");
assert.equal(
finalSubagent?.type === "subagent.updated" && finalSubagent.subagent.status,
@@ -10094,71 +9168,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
- it.effect("does not resolve a newer API retry when replaying a held subagent frame", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const TOOL_USE_ID = "toolu-retry-subagent";
- 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-retry-subagent"),
- text: "Run an auditor.",
- attachments: [],
- }),
- );
- const frames = [
- ...makeSubagentAssistantFrames({
- parentToolUseId: TOOL_USE_ID,
- uuid: "00000000-0000-4000-8000-000000000351",
- text: "Held before registration.",
- }),
- claudeSdkFrame({
- type: "system",
- subtype: "api_retry",
- attempt: 2,
- max_retries: 10,
- retry_delay_ms: 1_500,
- error_status: 529,
- error: "overloaded",
- uuid: "00000000-0000-4000-8000-000000000352",
- session_id: WAKE_NATIVE_SESSION,
- }),
- makeSubagentTaskStartedFrame({
- taskId: "task-retry-subagent",
- toolUseId: TOOL_USE_ID,
- uuid: "00000000-0000-4000-8000-000000000353",
- }),
- ];
- for (const frame of frames) {
- yield* Queue.offer(harness.sdkMessages, frame);
- }
- const childTexts = () => {
- const routing = subagentRouting(harness.events, []);
- return routing.childThreadId === undefined
- ? []
- : routing.assistantTexts(routing.childThreadId);
- };
- yield* harness.until(() => childTexts().length === 1);
- const retryStatuses = harness.events.flatMap((event) =>
- event.type === "turn_item.updated" &&
- event.turnItem.type === "error" &&
- event.turnItem.retry !== undefined
- ? [event.turnItem.status]
- : [],
- );
- assert.deepEqual(retryStatuses, ["running"]);
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
it.effect("holds subagent frames that precede task_started and shows its result once", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -11696,253 +10705,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
- it.effect(
- "does not opaque-misclassify a buffered subagent notification across model/policy query replacement",
- () =>
- Effect.scoped(
- Effect.gen(function* () {
- const changes = yield* makeChangeSignal;
- const SUBAGENT_TASK_ID = "task-buffer-replace-subagent";
- const SUBAGENT_TOOL_USE_ID = "toolu-buffer-replace-subagent";
- const SUBAGENT_SUMMARY = "SUB_BUFFER_REPLACE_DONE";
- const subagentTaskStarted = claudeSdkFrame({
- type: "system",
- subtype: "task_started",
- task_id: SUBAGENT_TASK_ID,
- tool_use_id: SUBAGENT_TOOL_USE_ID,
- description: "Background research",
- subagent_type: "general-purpose",
- task_type: "local_agent",
- prompt: "Research then return SUB_BUFFER_REPLACE_DONE.",
- uuid: "00000000-0000-4000-8000-000000000801",
- session_id: WAKE_NATIVE_SESSION,
- });
- const subagentNotification = claudeSdkFrame({
- type: "system",
- subtype: "task_notification",
- task_id: SUBAGENT_TASK_ID,
- tool_use_id: SUBAGENT_TOOL_USE_ID,
- status: "completed",
- output_file: "/tmp/task-buffer-replace-subagent.output",
- summary: SUBAGENT_SUMMARY,
- uuid: "00000000-0000-4000-8000-000000000802",
- session_id: WAKE_NATIVE_SESSION,
- });
- const subagentAsyncAck = claudeSdkFrame({
- type: "user",
- message: {
- role: "user",
- content: [
- {
- type: "tool_result",
- tool_use_id: SUBAGENT_TOOL_USE_ID,
- content: [{ type: "text", text: "Async agent launched successfully." }],
- },
- ],
- },
- parent_tool_use_id: null,
- uuid: "00000000-0000-4000-8000-000000000803",
- session_id: WAKE_NATIVE_SESSION,
- tool_use_result: {
- isAsync: true,
- status: "async_launched",
- agentId: SUBAGENT_TASK_ID,
- prompt: "Research then return SUB_BUFFER_REPLACE_DONE.",
- },
- });
-
- const fileSystem = yield* FileSystem.FileSystem;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
- prefix: "t3-claude-v2-subagent-buffer-replace-",
- });
- const processQueues: Array<Queue.Queue<SDKMessage>> = [];
- const events: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
- const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
- [];
- const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
- instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
- settings: DEFAULT_CLAUDE_SETTINGS,
- environment: {},
- attachmentsDir,
- fileSystem,
- path: yield* Path.Path,
- crypto: yield* Crypto.Crypto,
- idAllocator,
- continuationRequests: {
- offer: (request) =>
- Effect.sync(() => {
- continuationRequests.push(request);
- }).pipe(Effect.andThen(changes.notify)),
- },
- queryRunner: {
- allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION),
- open: () =>
- Effect.gen(function* () {
- const sdkMessages = yield* Queue.unbounded<SDKMessage>();
- processQueues.push(sdkMessages);
- return {
- messages: Stream.fromQueue(sdkMessages),
- offer: () => Effect.void,
- setModel: () => Effect.void,
- applyFlagSettings: () => Effect.void,
- setPermissionMode: () => Effect.void,
- backgroundTasks: () => Effect.succeed(false),
- stopTask: () => Effect.void,
- interrupt: Effect.void,
- close: Queue.shutdown(sdkMessages),
- };
- }),
- forkSession: () => Effect.die("unused forkSession"),
- subagentLaunchToolUseId: () => Effect.succeed(null),
- assertComplete: Effect.void,
- },
- });
- const threadId = ThreadId.make("thread-claude-subagent-buffer-replace");
- const runtime = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make(
- "provider-session-claude-subagent-buffer-replace",
- ),
- modelSelection: CLAUDE_TEST_MODEL_SELECTION,
- runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
- });
- const providerThread = yield* runtime.ensureThread({
- threadId,
- modelSelection: CLAUDE_TEST_MODEL_SELECTION,
- runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
- });
- yield* runtime.events.pipe(
- Stream.runForEach((event) =>
- Effect.sync(() => {
- events.push(event);
- }).pipe(Effect.andThen(changes.notify)),
- ),
- Effect.forkScoped,
- );
- if (runtime.hasPendingBackgroundWork === undefined) {
- return yield* Effect.die(
- "Claude adapter runtime must expose hasPendingBackgroundWork.",
- );
- }
- const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
- const subagentEvents = () =>
- events.filter(
- (
- event,
- ): event is Extract<
- ProviderAdapter.ProviderAdapterV2Event,
- { type: "subagent.updated" }
- > => event.type === "subagent.updated",
- );
- const now = yield* DateTime.now;
-
- yield* runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId,
- providerThread,
- now,
- attemptId: RunAttemptId.make("attempt-claude-subagent-buffer-replace-a"),
- text: "Spawn a background subagent and stop.",
- attachments: [],
- }),
- );
- assert.equal(processQueues.length, 1);
- const firstProcess = processQueues[0]!;
- yield* Queue.offer(firstProcess, subagentTaskStarted);
- yield* changes.until(() => subagentEvents().length >= 1);
- assert.equal(subagentEvents()[0]?.subagent.status, "running");
- yield* Queue.offer(firstProcess, subagentAsyncAck);
- yield* Queue.offer(
- firstProcess,
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000000804",
- result: "Spawned the subagent in the background.",
- }),
- );
- yield* changes.until(() => events.some((event) => event.type === "turn.terminal"));
- assert.isTrue(yield* hasPendingBackgroundWork);
-
- yield* Queue.offer(firstProcess, subagentNotification);
- yield* changes.until(() => continuationRequests.length === 1);
- assert.equal(continuationRequests[0]?.detail, SUBAGENT_SUMMARY);
-
- const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION;
- yield* runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId,
- providerThread: { ...providerThread, status: "active" },
- now,
- attemptId: RunAttemptId.make("attempt-claude-subagent-buffer-replace-user"),
- text: "Switch model while the subagent completes.",
- attachments: [],
- providerTurnOrdinal: 2,
- modelSelection: alternateModel,
- }),
- );
- assert.equal(processQueues.length, 2);
- const secondProcess = processQueues[1]!;
- yield* Queue.offer(
- secondProcess,
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000000805",
- result: "User turn finished after model switch.",
- }),
- );
- yield* changes.until(
- () => events.filter((event) => event.type === "turn.terminal").length === 2,
- );
- assert.isFalse(yield* hasPendingBackgroundWork);
- assert.equal(subagentEvents().at(-1)?.subagent.status, "completed");
- assert.lengthOf(continuationRequests, 1);
-
- yield* Queue.offer(
- secondProcess,
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000000806",
- result: "The subagent finished with SUB_BUFFER_REPLACE_DONE.",
- }),
- );
- yield* runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId,
- providerThread: { ...providerThread, status: "active" },
- now,
- attemptId: RunAttemptId.make("attempt-claude-subagent-buffer-replace-cont"),
- text: "Background task completed.",
- attachments: [],
- providerTurnOrdinal: 3,
- modelSelection: alternateModel,
- messageCreatedBy: "agent",
- messageCreationSource: "provider",
- }),
- );
- yield* changes.until(
- () => events.filter((event) => event.type === "turn.terminal").length === 3,
- );
-
- const finalSubagent = subagentEvents().at(-1)?.subagent;
- assert.equal(finalSubagent?.status, "completed");
- assert.equal(finalSubagent?.result, SUBAGENT_SUMMARY);
- assert.equal(finalSubagent?.runId, subagentEvents()[0]?.subagent.runId);
- const subagentNodeEvents = events.filter(
- (
- event,
- ): event is Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "node.updated" }> =>
- event.type === "node.updated" &&
- event.node.kind === "subagent" &&
- event.node.nativeItemRef?.nativeId === SUBAGENT_TASK_ID,
- );
- assert.equal(subagentNodeEvents.at(-1)?.node.status, "completed");
- assert.isFalse(yield* hasPendingBackgroundWork);
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
it.effect("refuses a thinking change that would kill a running background subagent", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -12109,6 +10871,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
+ // regression: #20413 an unreadable append file must not tear down the running process
it.effect("keeps the live process when its replacement cannot read the append file", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -12368,228 +11131,27 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
- it.effect(
- "clears buffered wake and continuation state when same-native-thread replacement open fails",
- () =>
- Effect.scoped(
- Effect.gen(function* () {
- const changes = yield* makeChangeSignal;
- const fileSystem = yield* FileSystem.FileSystem;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
- prefix: "t3-claude-v2-replace-open-fail-wake-",
- });
- let openCount = 0;
- const processQueues: Array<Queue.Queue<SDKMessage>> = [];
- const events: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
- const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
- [];
- const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
- instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
- settings: DEFAULT_CLAUDE_SETTINGS,
- environment: {},
- attachmentsDir,
- fileSystem,
- path: yield* Path.Path,
- crypto: yield* Crypto.Crypto,
- idAllocator,
- continuationRequests: {
- offer: (request) =>
- Effect.sync(() => {
- continuationRequests.push(request);
- }).pipe(Effect.andThen(changes.notify)),
- },
- queryRunner: {
- allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION),
- open: () => {
- openCount += 1;
- if (openCount === 2) {
- return Effect.fail(
- new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
- method: "open",
- cause: "forced replacement open failure",
- }),
- );
- }
- return Effect.gen(function* () {
- const sdkMessages = yield* Queue.unbounded<SDKMessage>();
- processQueues.push(sdkMessages);
- return {
- messages: Stream.fromQueue(sdkMessages),
- offer: () => Effect.void,
- setModel: () => Effect.void,
- applyFlagSettings: () => Effect.void,
- setPermissionMode: () => Effect.void,
- backgroundTasks: () => Effect.succeed(false),
- stopTask: () => Effect.void,
- interrupt: Effect.void,
- close: Queue.shutdown(sdkMessages),
- };
- });
- },
- forkSession: () => Effect.die("unused forkSession"),
- subagentLaunchToolUseId: () => Effect.succeed(null),
- assertComplete: Effect.void,
- },
- });
- const threadId = ThreadId.make("thread-claude-replace-open-fail-wake");
- const runtime = yield* adapter.openSession({
- threadId,
- providerSessionId: ProviderSessionId.make(
- "provider-session-claude-replace-open-fail-wake",
- ),
- modelSelection: CLAUDE_TEST_MODEL_SELECTION,
- runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
- });
- const providerThread = yield* runtime.ensureThread({
- threadId,
- modelSelection: CLAUDE_TEST_MODEL_SELECTION,
- runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
- });
- yield* runtime.events.pipe(
- Stream.runForEach((event) =>
- Effect.sync(() => {
- events.push(event);
- }).pipe(Effect.andThen(changes.notify)),
- ),
- Effect.forkScoped,
- );
- if (runtime.hasPendingBackgroundWork === undefined) {
- return yield* Effect.die(
- "Claude adapter runtime must expose hasPendingBackgroundWork.",
- );
- }
- const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
- const now = yield* DateTime.now;
-
- yield* runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId,
- providerThread,
- now,
- attemptId: RunAttemptId.make("attempt-claude-replace-open-fail-wake-a"),
- text: "Run the build in the background.",
- attachments: [],
- }),
- );
- yield* Queue.offer(processQueues[0]!, wakeTaskStarted);
- yield* Queue.offer(processQueues[0]!, turnOneResult);
- yield* changes.until(
- () => events.filter((event) => event.type === "turn.terminal").length === 1,
- );
- yield* Queue.offer(processQueues[0]!, wakeNotification);
- yield* Queue.offer(processQueues[0]!, wakeAssistant);
- yield* changes.until(() => continuationRequests.length === 1);
- assert.isTrue(yield* hasPendingBackgroundWork);
-
- const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION;
- const failedStart = yield* runtime
- .startTurn(
- makeClaudeTestTurnInput({
- threadId,
- providerThread: { ...providerThread, status: "active" },
- now,
- attemptId: RunAttemptId.make("attempt-claude-replace-open-fail-wake-b"),
- text: "Replace process but fail open.",
- attachments: [],
- providerTurnOrdinal: 2,
- modelSelection: alternateModel,
- }),
- )
- .pipe(Effect.exit);
- assert.isTrue(Exit.isFailure(failedStart));
- assert.isFalse(yield* hasPendingBackgroundWork);
-
- yield* runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId,
- providerThread: { ...providerThread, status: "active" },
- now,
- attemptId: RunAttemptId.make("attempt-claude-replace-open-fail-wake-c"),
- text: "Retry after the failed replacement.",
- attachments: [],
- providerTurnOrdinal: 2,
- modelSelection: alternateModel,
- }),
- );
- const retryProcess = processQueues[1]!;
- const retryTaskId = "task-wake-build-after-retry";
- yield* Queue.offer(
- retryProcess,
- claudeSdkFrame({
- type: "system",
- subtype: "task_started",
- task_id: retryTaskId,
- tool_use_id: "toolu-wake-build-after-retry",
- description: "npm run build after retry",
- is_backgrounded: true,
- task_type: "local_bash",
- uuid: "00000000-0000-4000-8000-000000000901",
- session_id: WAKE_NATIVE_SESSION,
- }),
- );
- yield* Queue.offer(
- retryProcess,
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000000902",
- result: "Kicked off the retry build in the background.",
- }),
- );
- yield* changes.until(
- () => events.filter((event) => event.type === "turn.terminal").length === 2,
- );
- yield* Queue.offer(
- retryProcess,
- claudeSdkFrame({
- type: "system",
- subtype: "task_notification",
- task_id: retryTaskId,
- tool_use_id: "toolu-wake-build-after-retry",
- status: "completed",
- output_file: "/tmp/task-wake-build-after-retry.log",
- summary: "Retry build completed successfully",
- uuid: "00000000-0000-4000-8000-000000000903",
- session_id: WAKE_NATIVE_SESSION,
- }),
- );
- yield* Queue.offer(
- retryProcess,
- makeAssistantTextFrame({
- uuid: "00000000-0000-4000-8000-000000000904",
- text: "The retry build has finished.",
- }),
- );
- yield* changes.until(() => continuationRequests.length === 2);
- assert.equal(continuationRequests[1]?.detail, "Retry build completed successfully");
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
- const WORKFLOW_TASK_ID = "task-workflow-run";
- const WORKFLOW_TOOL_USE_ID = "toolu-workflow-run";
- const makeWorkflowHarnessWithOptions = (
- options?: Parameters<typeof makeWakeHarnessWithOptions>[0],
- ) =>
- Effect.gen(function* () {
- const fileSystem = yield* FileSystem.FileSystem;
- const configDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-wf-" });
- const transcriptDir = NodePath.join(configDir, "projects", "workflow");
- yield* fileSystem.makeDirectory(transcriptDir, { recursive: true });
- yield* fileSystem.writeFileString(
- NodePath.join(transcriptDir, "agent-a1.jsonl"),
- `{"type":"assistant","uuid":"wf-line-1-${options?.nativeSessionId ?? "default"}","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_a1","content":[{"type":"text","text":"A1 from the transcript"}]}}\n`,
- );
- const harness = yield* makeWakeHarnessWithOptions({
- ...options,
- environment: { ...options?.environment, CLAUDE_CONFIG_DIR: configDir },
- });
- return { ...harness, transcriptDir };
- });
- const makeWorkflowHarness = makeWorkflowHarnessWithOptions();
+ const WORKFLOW_TASK_ID = "task-workflow-run";
+ const WORKFLOW_TOOL_USE_ID = "toolu-workflow-run";
+ const makeWorkflowHarnessWithOptions = (
+ options?: Parameters<typeof makeWakeHarnessWithOptions>[0],
+ ) =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const configDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-wf-" });
+ const transcriptDir = NodePath.join(configDir, "projects", "workflow");
+ yield* fileSystem.makeDirectory(transcriptDir, { recursive: true });
+ yield* fileSystem.writeFileString(
+ NodePath.join(transcriptDir, "agent-a1.jsonl"),
+ `{"type":"assistant","uuid":"wf-line-1-${options?.nativeSessionId ?? "default"}","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_a1","content":[{"type":"text","text":"A1 from the transcript"}]}}\n`,
+ );
+ const harness = yield* makeWakeHarnessWithOptions({
+ ...options,
+ environment: { ...options?.environment, CLAUDE_CONFIG_DIR: configDir },
+ });
+ return { ...harness, transcriptDir };
+ });
+ const makeWorkflowHarness = makeWorkflowHarnessWithOptions();
const workflowToolUse = claudeSdkFrame({
type: "assistant",
@@ -12934,75 +11496,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
- it.effect("scopes workflow member artifacts to the provider thread", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const memberArtifacts: Array<Array<string>> = [];
- const memberThreads: Array<ThreadId | null | undefined> = [];
- for (const nativeSessionId of ["workflow-session-a", "workflow-session-b"]) {
- const harness = yield* makeWorkflowHarnessWithOptions({ nativeSessionId });
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now: yield* DateTime.now,
- attemptId: RunAttemptId.make(`attempt-${nativeSessionId}`),
- text: "Run the workflow.",
- attachments: [],
- }),
- );
- for (const frame of [
- workflowToolUse,
- workflowTaskStarted,
- workflowLaunchAck(harness.transcriptDir),
- workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001203", state: "done" }),
- ]) {
- yield* harness.offerAndWait(claudeSdkFrame({ ...frame, session_id: nativeSessionId }));
- }
- yield* Queue.offer(
- harness.sdkMessages,
- claudeSdkFrame({
- ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001204", result: "Done." }),
- session_id: nativeSessionId,
- }),
- );
- yield* Queue.take(harness.terminalReceipts);
- const member = workflowMemberEvents(harness.events, 1).at(-1)?.subagent;
- assert.isDefined(member);
- memberThreads.push(member?.childThreadId);
- const ids = harness.events.flatMap<string>((event) => {
- if (event.type === "subagent.updated" && event.subagent.id === member?.id)
- return [event.subagent.id];
- if (event.type === "node.updated" && event.node.threadId === member?.childThreadId)
- return [event.node.id];
- if (
- event.type === "message.updated" &&
- event.message.threadId === member?.childThreadId
- )
- return [event.message.id];
- if (
- event.type === "turn_item.updated" &&
- event.turnItem.threadId === member?.childThreadId
- )
- return [event.turnItem.id];
- return [];
- });
- assert.isAtLeast(new Set(ids).size, 6);
- memberArtifacts.push(ids);
- }
- assert.notEqual(memberThreads[0], memberThreads[1]);
- assert.deepEqual(
- memberArtifacts[0]?.filter((id) => memberArtifacts[1]?.includes(id)),
- [],
- );
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
it.effect("stops only a live workflow task and waits for its stopped notification", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -13328,626 +11821,132 @@ describe("ClaudeAdapterV2 background wake turns", () => {
assert.deepEqual(excerpt.subagent.completedAt, completedAt);
const finishedRoot = harness.events.findLast(
(event) => event.type === "node.updated" && event.node.threadId === firstThreadId,
- );
- assert.deepEqual(
- finishedRoot?.type === "node.updated" ? finishedRoot.node.completedAt : undefined,
- completedAt,
- );
-
- yield* harness.offerAndWait(
- workflowNotification({ uuid: "00000000-0000-4000-8000-000000001008", status: "stopped" }),
- );
- yield* Queue.offer(
- harness.sdkMessages,
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000001006",
- result: "Launched the workflow.",
- }),
- );
- yield* Queue.take(harness.terminalReceipts);
- const stopped = workflowMemberEvents(harness.events, 2).at(-1)?.subagent;
- assert.equal(stopped?.status, "cancelled");
- assert.isNull(stopped?.startedAt);
- const stoppedRoot = harness.events.findLast(
- (event) => event.type === "node.updated" && event.node.threadId === second?.childThreadId,
- );
- assert.equal(
- stoppedRoot?.type === "node.updated" ? stoppedRoot.node.status : null,
- "cancelled",
- );
- assert.isNull(
- stoppedRoot?.type === "node.updated" ? stoppedRoot.node.startedAt : undefined,
- );
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
- it.effect("projects workflow member threads after resuming a restarted session", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const harness = yield* makeWorkflowHarnessWithOptions({
- subagentLaunchToolUseId: WORKFLOW_TOOL_USE_ID,
- });
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now: yield* DateTime.now,
- attemptId: RunAttemptId.make("attempt-claude-workflow-resume"),
- text: "Continue the workflow.",
- attachments: [],
- }),
- );
- yield* harness.offerAndWait(
- claudeSdkFrame({
- ...workflowToolUse,
- message: {
- model: "claude-sonnet-4-6",
- content: [
- { type: "tool_use", id: "toolu-resume-workflow", name: "SendMessage", input: {} },
- ],
- },
- }),
- );
- yield* harness.offerAndWait(
- claudeSdkFrame({
- ...workflowTaskStarted,
- tool_use_id: "toolu-resume-workflow",
- prompt: "Continue the workflow.",
- }),
- );
- yield* harness.offerAndWait(workflowLaunchAck(harness.transcriptDir));
- yield* harness.offerAndWait(
- workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001040", state: "start" }),
- );
- yield* harness.offerAndWait(
- makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001041", result: "Resumed." }),
- );
- yield* Queue.take(harness.terminalReceipts);
- const member = workflowMemberEvents(harness.events, 1).at(-1)?.subagent;
- const coordinator = workflowCoordinatorEvents(harness.events).at(-1)?.subagent;
- assert.isDefined(member);
- assert.equal(member?.status, "running");
- assert.isTrue(
- harness.events.some(
- (event) =>
- event.type === "app_thread.created" && event.appThread.id === member?.childThreadId,
- ),
- );
- assert.deepEqual(
- threadMessages(harness.events, member?.childThreadId).map((event) => event.message.text),
- ["Reply with exactly: A1", "A1 from the transcript"],
- );
- assert.isDefined(coordinator?.childThreadId);
- const recoveredThreads = harness.events.filter(
- (event) =>
- event.type === "app_thread.created" &&
- event.appThread.id === coordinator?.childThreadId,
- );
- assert.lengthOf(recoveredThreads, 1);
- const recovered = recoveredThreads[0];
- assert.equal(recovered?.type, "app_thread.created");
- if (recovered?.type !== "app_thread.created") throw new Error("Expected recovered thread");
- assert.isTrue(recovered.createOnly);
- assert.deepEqual(recovered.appThread.lineage, {
- parentThreadId: harness.threadId,
- relationshipToParent: "subagent",
- rootThreadId: harness.threadId,
- });
- assert.equal(recovered.appThread.createdBy, "agent");
- assert.equal(recovered.appThread.creationSource, "provider");
- assert.isBelow(
- harness.events.indexOf(recovered),
- harness.events.findIndex(
- (event) =>
- event.type === "subagent.updated" &&
- event.subagent.childThreadId === coordinator?.childThreadId,
- ),
- );
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
- it.effect("does not republish a workflow roster on progress-only frames", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const harness = yield* makeWorkflowHarness;
- const now = yield* DateTime.now;
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make("attempt-claude-workflow-progress-only"),
- text: "Run the alpha workflow.",
- attachments: [],
- }),
- );
- yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001120" });
- const coordinatorCount = () => workflowCoordinatorEvents(harness.events).length;
- const offerProgressOnly = (index: number) =>
- Queue.offer(
- harness.sdkMessages,
- claudeSdkFrame({
- type: "system",
- subtype: "task_progress",
- task_id: WORKFLOW_TASK_ID,
- tool_use_id: WORKFLOW_TOOL_USE_ID,
- description: "Member is working",
- uuid: `00000000-0000-4000-8000-${String(1200 + index).padStart(12, "0")}`,
- session_id: WAKE_NATIVE_SESSION,
- }),
- );
-
- const inTurnCount = coordinatorCount();
- for (let index = 0; index < 5; index++) yield* offerProgressOnly(index);
- yield* Queue.offer(
- harness.sdkMessages,
- workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001121", state: "start" }),
- );
- yield* harness.until(() => coordinatorCount() > inTurnCount);
- assert.equal(coordinatorCount(), inTurnCount + 1);
-
- yield* Queue.offer(
- harness.sdkMessages,
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000001122",
- result: "Launched the workflow.",
- }),
- );
- yield* Queue.take(harness.terminalReceipts);
-
- const betweenTurnCount = coordinatorCount();
- for (let index = 5; index < 10; index++) yield* offerProgressOnly(index);
- yield* Queue.offer(
- harness.sdkMessages,
- workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001123", state: "done" }),
- );
- yield* harness.until(() => coordinatorCount() > betweenTurnCount);
- assert.equal(coordinatorCount(), betweenTurnCount + 1);
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
- it.effect("keeps resumed workflow tools open after stale interrupted cleanup", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const clock = yield* Clock.Clock;
- const cleanupPaused = yield* Deferred.make<void>();
- const releaseCleanup = yield* Deferred.make<void>();
- let readsUntilPause = 0;
- yield* Effect.gen(function* () {
- const harness = yield* makeWorkflowHarnessWithOptions({
- close: Queue.shutdown,
- freshQueueOnReopen: true,
- });
- const oldAttempt = RunAttemptId.make("attempt-workflow-stale-cleanup-old");
- const oldBash = "toolu-workflow-stale-cleanup-old-bash";
- const newBash = "toolu-workflow-stale-cleanup-new-bash";
- const resumeTool = "toolu-workflow-stale-cleanup-resume";
- const toolUpdates = (nativeId: string) =>
- harness.events.flatMap((event) =>
- event.type === "turn_item.updated" &&
- event.turnItem.type === "command_execution" &&
- event.turnItem.nativeItemRef?.nativeId === nativeId
- ? [event.turnItem]
- : [],
- );
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now: yield* DateTime.now,
- attemptId: oldAttempt,
- text: "Run the workflow.",
- attachments: [],
- }),
- );
- yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001150" });
- for (const frame of makeSubagentAssistantFrames({
- parentToolUseId: WORKFLOW_TOOL_USE_ID,
- uuid: "00000000-0000-4000-8000-000000001151",
- bashToolUseId: oldBash,
- })) {
- yield* harness.offerAndWait(frame);
- }
- yield* harness.until(() => toolUpdates(oldBash).length === 1);
- readsUntilPause = 2;
- const stop = yield* harness.runtime
- .interruptTurn({
- providerThread: harness.providerThread,
- providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
- driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
- nativeTurnId: `turn:${oldAttempt}`,
- }),
- })
- .pipe(Effect.forkScoped);
- yield* Deferred.await(cleanupPaused);
- yield* TestClock.adjust("10 seconds");
- yield* Fiber.join(stop);
- yield* Queue.take(harness.terminalReceipts);
- const oldToolCount = toolUpdates(oldBash).length;
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now: yield* DateTime.now,
- attemptId: RunAttemptId.make("attempt-workflow-stale-cleanup-new"),
- text: "Resume the workflow.",
- attachments: [],
- providerTurnOrdinal: 2,
- }),
- );
- const resumedQueue = harness.processQueues[1]!;
- yield* Queue.offer(
- resumedQueue,
- claudeSdkFrame({
- ...workflowTaskStarted,
- tool_use_id: resumeTool,
- prompt: "Resume the workflow.",
- uuid: "00000000-0000-4000-8000-000000001152",
- }),
- );
- for (const frame of makeSubagentAssistantFrames({
- parentToolUseId: resumeTool,
- uuid: "00000000-0000-4000-8000-000000001153",
- bashToolUseId: newBash,
- })) {
- yield* Queue.offer(resumedQueue, frame);
- }
- yield* harness.until(() => toolUpdates(newBash).length === 1);
- yield* Deferred.succeed(releaseCleanup, undefined);
- yield* Queue.take(harness.terminalReceipts);
- assert.lengthOf(toolUpdates(oldBash), oldToolCount);
- assert.deepEqual(
- toolUpdates(newBash).map((item) => item.status),
- ["running"],
- );
- yield* Queue.offer(
- resumedQueue,
- makeSubagentToolResultFrame({
- parentToolUseId: resumeTool,
- uuid: "00000000-0000-4000-8000-000000001154",
- toolUseId: newBash,
- }),
- );
- yield* harness.until(() => toolUpdates(newBash).at(-1)?.status === "completed");
- assert.equal(toolUpdates(newBash).at(-1)?.output, "ok");
- }).pipe(
- Effect.provideService(Clock.Clock, {
- ...clock,
- currentTimeMillis: Effect.gen(function* () {
- if (readsUntilPause > 0 && --readsUntilPause === 0) {
- yield* Deferred.succeed(cleanupPaused, undefined);
- yield* Deferred.await(releaseCleanup);
- }
- return yield* clock.currentTimeMillis;
- }),
- }),
- );
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
- it.effect.each(["root result", "query close"] as const)(
- "keeps a waiting continuation inactive until replay can handle %s",
- (arrival) =>
- Effect.scoped(
- Effect.gen(function* () {
- const digestStarted = yield* Deferred.make<void>();
- const releaseDigest = yield* Deferred.make<void>();
- const closeStarted = yield* Deferred.make<void>();
- let pauseDigest = false;
- yield* Effect.gen(function* () {
- const harness = yield* makeWorkflowHarnessWithOptions({
- freshQueueOnReopen: true,
- close: (messages) =>
- Deferred.succeed(closeStarted, undefined).pipe(
- Effect.andThen(Queue.shutdown(messages)),
- ),
- });
- const start = (attemptId: string, ordinal: number, continuation: boolean) =>
- harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now: DateTime.makeUnsafe(0),
- attemptId: RunAttemptId.make(attemptId),
- providerTurnOrdinal: ordinal,
- text: "Continue working.",
- attachments: [],
- ...(continuation
- ? { messageCreatedBy: "agent", messageCreationSource: "provider" }
- : {}),
- }),
- );
- yield* start("attempt-workflow-waiting-launch", 1, false);
- yield* launchWorkflow({
- harness,
- snapshotUuid: "00000000-0000-4000-8000-000000003200",
- });
- const fileSystem = yield* FileSystem.FileSystem;
- const liveTranscriptDir = NodePath.join(harness.transcriptDir, "live");
- yield* fileSystem.makeDirectory(liveTranscriptDir);
- yield* fileSystem.writeFileString(
- NodePath.join(liveTranscriptDir, "agent-a1.jsonl"),
- '{"type":"assistant","uuid":"wf-line-2","message":{"role":"assistant","stop_reason":"end_turn","content":[{"type":"text","text":"Live member answer"}]}}\n',
- );
- const liveTaskId = "task-workflow-live-while-waiting";
- const liveToolUseId = "toolu-workflow-live-while-waiting";
- yield* harness.offerAndWait(
- claudeSdkFrame({
- type: "assistant",
- message: {
- model: "claude-sonnet-4-6",
- content: [{ type: "tool_use", id: liveToolUseId, name: "Workflow", input: {} }],
- },
- parent_tool_use_id: null,
- session_id: WAKE_NATIVE_SESSION,
- uuid: "00000000-0000-4000-8000-000000003201",
- }),
- );
- yield* harness.offerAndWait(
- claudeSdkFrame({
- ...workflowTaskStarted,
- task_id: liveTaskId,
- tool_use_id: liveToolUseId,
- uuid: "00000000-0000-4000-8000-000000003202",
- }),
- );
- yield* harness.offerAndWait(
- claudeSdkFrame({
- type: "user",
- message: {
- role: "user",
- content: [
- { type: "tool_result", tool_use_id: liveToolUseId, content: "Launched." },
- ],
- },
- tool_use_result: {
- taskType: "local_workflow",
- runId: "wf_live_while_waiting",
- transcriptDir: liveTranscriptDir,
- },
- parent_tool_use_id: null,
- session_id: WAKE_NATIVE_SESSION,
- uuid: "00000000-0000-4000-8000-000000003203",
- }),
- );
- const liveProgress = (state: "start" | "done", uuid: string) =>
- claudeSdkFrame({
- ...workflowSnapshot({ state, uuid }),
- task_id: liveTaskId,
- tool_use_id: liveToolUseId,
- });
- yield* harness.offerAndWait(
- liveProgress("start", "00000000-0000-4000-8000-000000003204"),
- );
- yield* harness.offerAndWait(
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000003205",
- result: "Launched both workflows.",
- }),
- );
- yield* Queue.take(harness.terminalReceipts);
- yield* harness.offerAndWait(
- workflowNotification({
- uuid: "00000000-0000-4000-8000-000000003206",
- status: "completed",
- }),
- );
- yield* Queue.take(harness.continuationReceipts);
- yield* harness.offerAndWait(wakeTurnInit);
- pauseDigest = true;
- const progress = yield* harness
- .offerAndWait(liveProgress("done", "00000000-0000-4000-8000-000000003207"))
- .pipe(Effect.forkScoped);
- yield* Deferred.await(digestStarted);
- const replay = yield* start("attempt-workflow-waiting-replay", 2, true).pipe(
- Effect.forkScoped({ startImmediately: true }),
- );
- if (arrival === "query close") {
- const stop = yield* harness.runtime
- .interruptTurn({
- providerThread: harness.providerThread,
- providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
- driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
- nativeTurnId: "turn:attempt-workflow-waiting-replay",
- }),
- requestRuntimeRestart: true,
- })
- .pipe(Effect.forkScoped);
- yield* Deferred.await(closeStarted);
- yield* Deferred.succeed(releaseDigest, undefined);
- yield* Fiber.join(progress);
- yield* Fiber.join(stop);
- assert.isTrue(Exit.isFailure(yield* Fiber.await(replay)));
- } else {
- const offered = yield* Deferred.make<void>();
- const result = yield* harness
- .offerAndWait(wakeResult, offered)
- .pipe(Effect.forkScoped);
- yield* Deferred.await(offered);
- yield* Deferred.succeed(releaseDigest, undefined);
- yield* Fiber.join(progress);
- yield* Fiber.join(replay);
- yield* Fiber.join(result);
- yield* Queue.take(harness.terminalReceipts);
- assert.lengthOf(harness.continuationRequests, 1);
- }
- yield* start("attempt-workflow-waiting-next-user", 3, false);
- }).pipe(
- Effect.provideService(WorkflowAgentTranscriptReadObserver, () =>
- Effect.gen(function* () {
- if (pauseDigest) {
- pauseDigest = false;
- yield* Deferred.succeed(digestStarted, undefined);
- yield* Deferred.await(releaseDigest);
- }
- }),
- ),
- );
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
+ );
+ assert.deepEqual(
+ finishedRoot?.type === "node.updated" ? finishedRoot.node.completedAt : undefined,
+ completedAt,
+ );
+
+ yield* harness.offerAndWait(
+ workflowNotification({ uuid: "00000000-0000-4000-8000-000000001008", status: "stopped" }),
+ );
+ yield* Queue.offer(
+ harness.sdkMessages,
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000001006",
+ result: "Launched the workflow.",
+ }),
+ );
+ yield* Queue.take(harness.terminalReceipts);
+ const stopped = workflowMemberEvents(harness.events, 2).at(-1)?.subagent;
+ assert.equal(stopped?.status, "cancelled");
+ assert.isNull(stopped?.startedAt);
+ const stoppedRoot = harness.events.findLast(
+ (event) => event.type === "node.updated" && event.node.threadId === second?.childThreadId,
+ );
+ assert.equal(
+ stoppedRoot?.type === "node.updated" ? stoppedRoot.node.status : null,
+ "cancelled",
+ );
+ assert.isNull(
+ stoppedRoot?.type === "node.updated" ? stoppedRoot.node.startedAt : undefined,
+ );
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
+ ),
);
- it.effect.each(["registry", "transcript"] as const)(
- "does not replay stale idle progress over a completed workflow after awaiting %s",
- (boundary) =>
- Effect.scoped(
- Effect.gen(function* () {
- const clock = yield* Clock.Clock;
- const progressRead = yield* Deferred.make<void>();
- const releaseProgress = yield* Deferred.make<void>();
- let pauseNextRead = false;
- yield* Effect.gen(function* () {
- const harness = yield* makeWorkflowHarness;
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now: yield* DateTime.now,
- attemptId: RunAttemptId.make("attempt-claude-idle-race-launch"),
- text: "Run the workflow.",
- attachments: [],
- }),
- );
- yield* launchWorkflow({
- harness,
- snapshotUuid: "00000000-0000-4000-8000-000000001060",
- });
- yield* harness.offerAndWait(
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000001061",
- result: "Launched.",
- }),
- );
- yield* Queue.take(harness.terminalReceipts);
- yield* harness.offerAndWait(
- workflowNotification({
- uuid: "00000000-0000-4000-8000-000000001062",
- status: "completed",
- }),
- );
- if (boundary === "registry") {
- yield* harness.offerAndWait(
- makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001063", result: "Done." }),
- );
- }
- const continuationInput = makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now: yield* DateTime.now,
- attemptId: RunAttemptId.make("attempt-claude-idle-race-continuation"),
- text: "Continue.",
- attachments: [],
- providerTurnOrdinal: 2,
- messageCreatedBy: "agent",
- messageCreationSource: "provider",
- });
- pauseNextRead = true;
- const progress = yield* harness
- .offerAndWait(
- workflowSnapshot({
- uuid: "00000000-0000-4000-8000-000000001064",
- state: boundary === "transcript" ? "done" : "start",
- secondState: "start",
- }),
- )
- .pipe(Effect.forkScoped);
- yield* Deferred.await(progressRead);
- const continuation = yield* harness.runtime
- .startTurn(continuationInput)
- .pipe(Effect.forkScoped);
- yield* Deferred.succeed(releaseProgress, undefined);
- yield* Fiber.join(progress);
- yield* Fiber.join(continuation);
- if (boundary === "registry") {
- yield* Queue.take(harness.terminalReceipts);
- } else {
- const lastMemberId = workflowMemberEvents(harness.events, 2)[0]?.subagent.id;
- while (true) {
- const event = yield* Queue.take(harness.subagentReceipts);
- if (event.subagent.id === lastMemberId && event.subagent.status === "completed")
- break;
- }
- }
- if (boundary === "transcript") {
- yield* harness.offerAndWait(
- makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001065", result: "Done." }),
- );
- yield* Queue.take(harness.terminalReceipts);
- }
- assert.isFalse(yield* harness.hasPendingBackgroundWork);
- assert.equal(
- workflowCoordinatorEvents(harness.events).at(-1)?.subagent.status,
- "completed",
- );
- const member = workflowMemberEvents(harness.events, 2).at(-1)?.subagent;
- assert.equal(member?.status, "completed");
- const root = harness.events.findLast(
- (event) =>
- event.type === "node.updated" && event.node.threadId === member?.childThreadId,
- );
- assert.equal(root?.type === "node.updated" ? root.node.status : null, "completed");
- const item = harness.events.findLast(
- (event) =>
- event.type === "turn_item.updated" &&
- event.turnItem.type === "subagent" &&
- event.turnItem.nativeItemRef?.nativeId === WORKFLOW_TASK_ID,
- );
- assert.equal(
- item?.type === "turn_item.updated" ? item.turnItem.status : null,
- "completed",
- );
- }).pipe(
- Effect.provideService(Clock.Clock, {
- ...clock,
- currentTimeMillis: Effect.gen(function* () {
- if (boundary === "registry" && pauseNextRead) {
- pauseNextRead = false;
- yield* Deferred.succeed(progressRead, undefined);
- yield* Deferred.await(releaseProgress);
- }
- return yield* clock.currentTimeMillis;
- }),
- }),
- Effect.provideService(WorkflowAgentTranscriptReadObserver, () =>
- Effect.gen(function* () {
- if (boundary === "transcript" && pauseNextRead) {
- pauseNextRead = false;
- yield* Deferred.succeed(progressRead, undefined);
- yield* Deferred.await(releaseProgress);
- }
- }),
- ),
- );
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ it.effect("projects workflow member threads after resuming a restarted session", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const harness = yield* makeWorkflowHarnessWithOptions({
+ subagentLaunchToolUseId: WORKFLOW_TOOL_USE_ID,
+ });
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make("attempt-claude-workflow-resume"),
+ text: "Continue the workflow.",
+ attachments: [],
+ }),
+ );
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ ...workflowToolUse,
+ message: {
+ model: "claude-sonnet-4-6",
+ content: [
+ { type: "tool_use", id: "toolu-resume-workflow", name: "SendMessage", input: {} },
+ ],
+ },
+ }),
+ );
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ ...workflowTaskStarted,
+ tool_use_id: "toolu-resume-workflow",
+ prompt: "Continue the workflow.",
+ }),
+ );
+ yield* harness.offerAndWait(workflowLaunchAck(harness.transcriptDir));
+ yield* harness.offerAndWait(
+ workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001040", state: "start" }),
+ );
+ yield* harness.offerAndWait(
+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001041", result: "Resumed." }),
+ );
+ yield* Queue.take(harness.terminalReceipts);
+ const member = workflowMemberEvents(harness.events, 1).at(-1)?.subagent;
+ const coordinator = workflowCoordinatorEvents(harness.events).at(-1)?.subagent;
+ assert.isDefined(member);
+ assert.equal(member?.status, "running");
+ assert.isTrue(
+ harness.events.some(
+ (event) =>
+ event.type === "app_thread.created" && event.appThread.id === member?.childThreadId,
+ ),
+ );
+ assert.deepEqual(
+ threadMessages(harness.events, member?.childThreadId).map((event) => event.message.text),
+ ["Reply with exactly: A1", "A1 from the transcript"],
+ );
+ assert.isDefined(coordinator?.childThreadId);
+ const recoveredThreads = harness.events.filter(
+ (event) =>
+ event.type === "app_thread.created" &&
+ event.appThread.id === coordinator?.childThreadId,
+ );
+ assert.lengthOf(recoveredThreads, 1);
+ const recovered = recoveredThreads[0];
+ assert.equal(recovered?.type, "app_thread.created");
+ if (recovered?.type !== "app_thread.created") throw new Error("Expected recovered thread");
+ assert.isTrue(recovered.createOnly);
+ assert.deepEqual(recovered.appThread.lineage, {
+ parentThreadId: harness.threadId,
+ relationshipToParent: "subagent",
+ rootThreadId: harness.threadId,
+ });
+ assert.equal(recovered.appThread.createdBy, "agent");
+ assert.equal(recovered.appThread.creationSource, "provider");
+ assert.isBelow(
+ harness.events.indexOf(recovered),
+ harness.events.findIndex(
+ (event) =>
+ event.type === "subagent.updated" &&
+ event.subagent.childThreadId === coordinator?.childThreadId,
),
+ );
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
),
),
+ ),
);
it.effect.each([
@@ -14404,68 +12403,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
- it.effect("reads a transcript that appears after a terminal workflow notification", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const harness = yield* makeWorkflowHarness;
- const now = yield* DateTime.now;
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make("attempt-claude-workflow-late-terminal-answer"),
- text: "Run the alpha workflow.",
- attachments: [],
- }),
- );
- yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001030" });
- const secondThreadId = workflowMemberEvents(harness.events, 2)[0]?.subagent.childThreadId;
- yield* Queue.offer(
- harness.sdkMessages,
- workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001031", state: "done" }),
- );
- yield* harness.until(() => threadMessages(harness.events, secondThreadId).length === 2);
- const notification = workflowNotification({
- uuid: "00000000-0000-4000-8000-000000001032",
- status: "completed",
- });
- yield* Queue.offer(harness.sdkMessages, notification);
- yield* harness.until(() =>
- harness.events.some(
- (event) =>
- event.type === "turn_item.updated" &&
- event.turnItem.type === "subagent" &&
- event.turnItem.nativeItemRef?.nativeId === WORKFLOW_TASK_ID &&
- event.turnItem.status === "completed",
- ),
- );
- NodeFS.writeFileSync(
- NodePath.join(harness.transcriptDir, "agent-a2.jsonl"),
- '{"type":"assistant","uuid":"wf-line-3","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_late","content":[{"type":"text","text":"A2 final answer"}]}}\n',
- );
- yield* Queue.offer(
- harness.sdkMessages,
- claudeSdkFrame({ ...notification, uuid: "00000000-0000-4000-8000-000000001033" }),
- );
- yield* harness.until(
- () =>
- threadMessages(harness.events, secondThreadId).at(-1)?.message.text ===
- "A2 final answer",
- );
- yield* Queue.offer(
- harness.sdkMessages,
- makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001034", result: "Done." }),
- );
- yield* Queue.take(harness.terminalReceipts);
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
it.effect("answers settled workflow members from a transcript, or the snapshot excerpt", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -15124,45 +13061,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
- it.effect("keeps a goal active when a hook stops the turn before the goal passes", () =>
- Effect.gen(function* () {
- const harness = yield* makeWakeHarness;
- const condition = "the deploy succeeds";
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now: yield* DateTime.now,
- attemptId: RunAttemptId.make("goal-hook-stop-attempt"),
- text: `/goal ${condition}`,
- attachments: [],
- }),
- );
- for (const frame of [
- syntheticFrame("goal-hook-set", `Goal set: ${condition}`),
- makeAssistantTextFrame({ uuid: "goal-hook-work", text: "Deploying." }),
- makeResultFrame({
- uuid: "goal-hook-result",
- result: "Deploying.",
- terminalReason: "hook_stopped",
- }),
- ]) {
- yield* Queue.offer(harness.sdkMessages, frame);
- }
- yield* Queue.take(harness.terminalReceipts);
- assert.deepEqual(goalStatuses(harness.events).at(-1), {
- objective: condition,
- status: "active",
- checks: 0,
- });
- }).pipe(
- Effect.scoped,
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- );
-
it.effect(
"defers goal completion until an ambient subagent finishes and Claude checks again",
() =>
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
index 03cac0da552..bc69f75d37e 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
@@ -29,8 +29,6 @@ import {
TurnItemId,
} from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
-import * as HostProcess from "@t3tools/shared/HostProcess";
-import { SpawnExecutableResolution } from "@t3tools/shared/shell";
import * as CodexClient from "effect-codex-app-server/client";
import * as CodexReplay from "effect-codex-app-server/replay";
import type * as CodexSchema from "effect-codex-app-server/schema";
@@ -44,7 +42,6 @@ import { MCP_APP_OUTPUT_KEY, readMcpAppReference } from "@t3tools/shared/mcpApp"
import { resolveAttachmentPathById } from "../../attachmentStore.ts";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
-import * as PlatformError from "effect/PlatformError";
import * as PubSub from "effect/PubSub";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
@@ -66,7 +63,6 @@ import * as CodexAdapterV2 from "./CodexAdapterV2.ts";
import { makeReplayServerConfig, withCodexReplayChildMetadata } from "./CodexAdapterV2.testkit.ts";
import * as CodexAdapterV2Testkit from "./CodexAdapterV2.testkit.ts";
-const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
const replayTranscriptJson = Schema.fromJsonString(CodexReplay.CodexAppServerReplayTranscript);
const encodeReplayTranscriptJson = Schema.encodeEffect(replayTranscriptJson);
const decodeReplayTranscriptJson = Schema.decodeUnknownEffect(replayTranscriptJson);
@@ -135,77 +131,6 @@ describe("CodexAdapterV2 assistant message streaming", () => {
assert.equal((yield* Ref.get(updates)).length, 2);
}),
);
-
- it.effect("retains buffered text until completion updates are emitted", () =>
- Effect.gen(function* () {
- const updates = yield* Ref.make<ReadonlyArray<ProviderTextDeltaUpdate>>([]);
- const failNext = yield* Ref.make(true);
- const coalescer = yield* makeProviderTextDeltaCoalescer({
- flushIntervalMs: 50,
- emit: (update) =>
- Ref.getAndSet(failNext, false).pipe(
- Effect.flatMap((shouldFail) =>
- shouldFail
- ? Effect.die("projection unavailable")
- : Ref.update(updates, (current) => [...current, update]),
- ),
- ),
- });
-
- yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: "turn final" });
- const failedFlush = yield* coalescer.flushTurn("turn-1").pipe(Effect.exit);
- assert.equal(failedFlush._tag, "Failure");
- yield* coalescer.flushTurn("turn-1");
-
- yield* coalescer.append({ turnId: "turn-1", itemId: "message-2", delta: "item final" });
- yield* Ref.set(failNext, true);
- const failedComplete = yield* coalescer
- .complete({ turnId: "turn-1", itemId: "message-2" })
- .pipe(Effect.exit);
- assert.equal(failedComplete._tag, "Failure");
- const completedText = yield* coalescer.complete({
- turnId: "turn-1",
- itemId: "message-2",
- });
-
- assert.equal(completedText, "item final");
- assert.deepEqual(yield* Ref.get(updates), [
- { turnId: "turn-1", itemId: "message-1", text: "turn final", completed: true },
- { turnId: "turn-1", itemId: "message-2", text: "item final", completed: true },
- ]);
- }),
- );
-
- it.effect("treats explicit empty final text as authoritative over buffered deltas", () =>
- Effect.gen(function* () {
- const updates = yield* Ref.make<ReadonlyArray<ProviderTextDeltaUpdate>>([]);
- const coalescer = yield* makeProviderTextDeltaCoalescer({
- flushIntervalMs: 50,
- emit: (update) => Ref.update(updates, (current) => [...current, update]),
- });
-
- yield* coalescer.append({
- turnId: "turn-1",
- itemId: "message-1",
- delta: "stale buffered text",
- });
- const completedText = yield* coalescer.complete({
- turnId: "turn-1",
- itemId: "message-1",
- finalText: "",
- });
-
- assert.equal(completedText, "");
- assert.deepEqual(yield* Ref.get(updates), [
- {
- turnId: "turn-1",
- itemId: "message-1",
- text: "",
- completed: true,
- },
- ]);
- }),
- );
});
describe("CodexAdapterV2 runtime policy", () => {
@@ -248,31 +173,6 @@ describe("CodexAdapterV2 runtime policy", () => {
}),
);
- it.effect("preserves explicit Codex turn policy overrides", () =>
- Effect.gen(function* () {
- const params = yield* CodexAdapterV2.buildCodexTurnStartParams({
- nativeThreadId: "native-override",
- codexInput: [{ type: "text", text: "test" }],
- runtimePolicy: {
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd: null,
- approvalPolicy: "on-request",
- sandboxPolicy: {
- type: "readOnly",
- },
- },
- modelSelection: {
- instanceId: ProviderInstanceId.make("codex"),
- model: "gpt-5.4",
- },
- });
-
- assert.equal(params.approvalPolicy, "on-request");
- assert.equal(params.sandboxPolicy?.type, "readOnly");
- }),
- );
-
it.effect("sends MCP app model context as untrusted Codex context", () =>
Effect.gen(function* () {
const policy = { runtimeMode: "full-access", interactionMode: "default", cwd: null } as const;
@@ -305,91 +205,6 @@ describe("CodexAdapterV2 runtime policy", () => {
);
});
-describe("CodexAdapterV2 process spawning", () => {
- it.effect("resolves Windows command shims through the shared spawn policy", () =>
- Effect.gen(function* () {
- const command = yield* CodexAdapterV2.makeCodexAppServerSpawnCommand({
- command: "codex",
- args: ["app-server", "argument with spaces"],
- cwd: "C:\\workspace",
- env: { CUSTOM: "1" },
- extendEnv: true,
- });
-
- assert.isTrue(ChildProcess.isStandardCommand(command));
- if (!ChildProcess.isStandardCommand(command)) {
- return;
- }
- assert.equal(
- command.command,
- '^"C:\\npm\\codex.cmd^" ^"app-server^" ^"argument^ with^ spaces^"',
- );
- assert.deepEqual(command.args, []);
- assert.equal(command.options.shell, true);
- assert.equal(command.options.cwd, "C:\\workspace");
- assert.deepEqual(command.options.env, { CUSTOM: "1" });
- assert.equal(command.options.extendEnv, true);
- }).pipe(
- Effect.provideService(HostProcess.Platform, "win32"),
- Effect.provideService(HostProcess.Environment, {
- PATH: "C:\\Windows\\System32",
- HOST_ONLY: "1",
- }),
- Effect.provideService(SpawnExecutableResolution, (_command, _platform, environment) => {
- assert.equal(environment.HOST_ONLY, "1");
- assert.equal(environment.CUSTOM, "1");
- return "C:\\npm\\codex.cmd";
- }),
- ),
- );
-
- it.effect("launches the app-server with the configured launch arguments", () =>
- Effect.gen(function* () {
- const spawnedArgs: Array<ReadonlyArray<string>> = [];
- const spawner = ChildProcessSpawner.make((command) => {
- if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args);
- return Effect.fail(
- PlatformError.systemError({ _tag: "NotFound", module: "ChildProcess", method: "spawn" }),
- );
- });
- const factory = yield* CodexAdapterV2.CodexAppServerClientFactory.pipe(
- Effect.provide(CodexAdapterV2.layerAppServerClientFactory),
- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
- Effect.provideService(
- ProviderEventLoggers.ProviderEventLoggers,
- ProviderEventLoggers.NoOpProviderEventLoggers,
- ),
- );
- const open = (environment: NodeJS.ProcessEnv) =>
- factory
- .open({
- instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID,
- threadId: ThreadId.make("thread-launch-args"),
- providerSessionId: ProviderSessionId.make("provider-session-launch-args"),
- runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
- runtimeMode: "full-access",
- interactionMode: "default",
- cwd: "/workspace",
- }),
- settings: {
- ...DEFAULT_CODEX_SETTINGS,
- launchArgs: " --strict-config -c model_reasoning_summary=detailed ",
- },
- environment,
- })
- .pipe(Effect.scoped, Effect.exit);
-
- yield* open({});
- yield* open({ T3CODE_CODEX_LAUNCH_ARGS: " --enable env-feature " });
-
- assert.deepEqual(spawnedArgs, [
- ["app-server", "--strict-config", "-c", "model_reasoning_summary=detailed"],
- ["app-server", "--enable", "env-feature"],
- ]);
- }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
- );
-});
-
describe("CodexAdapterV2 native protocol logging", () => {
it.effect("logs decoded app-server frames once with credentials redacted", () =>
Effect.gen(function* () {
@@ -459,51 +274,6 @@ describe("CodexAdapterV2 native protocol logging", () => {
});
}),
);
-
- it.effect("retains redacted failures when large payloads are summarized", () =>
- Effect.gen(function* () {
- const writes: Array<unknown> = [];
- const protocolLogger = CodexAdapterV2.makeCodexAppServerProtocolLogger({
- nativeEventLogger: {
- filePath: "/tmp/events.log",
- write: (event) =>
- Effect.sync(() => {
- writes.push(event);
- }),
- close: () => Effect.void,
- },
- threadId: ThreadId.make("thread-1"),
- providerSessionId: ProviderSessionId.make("provider-session-1"),
- });
- assert.exists(protocolLogger);
- if (protocolLogger === undefined) return;
-
- yield* protocolLogger({
- direction: "incoming",
- stage: "decoded",
- payload: {
- method: "error",
- params: {
- threadId: "native-thread",
- turnId: "native-turn",
- error: {
- code: "unauthorized",
- message: '{"message":"Unauthorized","Authorization":"Bearer secret-token"}',
- },
- history: "x".repeat(128 * 1_024),
- },
- },
- });
-
- const serialized = encodeUnknownJson(writes);
- assert.equal(writes.length, 1);
- assert.isBelow(serialized.length, 2_048);
- assert.notInclude(serialized, "secret-token");
- assert.include(serialized, "[REDACTED]");
- assert.nestedPropertyVal(writes[0], "event.payload.params.error.code", "unauthorized");
- assert.nestedPropertyVal(writes[0], "event.payload.params.turnId", "native-turn");
- }),
- );
});
describe("CodexAdapterV2 rollback mapping", () => {
@@ -655,38 +425,6 @@ describe("CodexAdapterV2 fork boundary", () => {
assert.deepEqual(boundary, { lastTurnId: undefined, rollbackTurnCount: 1 });
}),
);
-
- it.effect("forks at head without a boundary when no provider turn is selected", () =>
- Effect.gen(function* () {
- const now = yield* DateTime.now;
-
- const boundary = yield* CodexAdapterV2.resolveCodexForkBoundary({
- sourceProviderThread: makeProviderThread(now),
- targetThreadId: ThreadId.make("thread-codex-fork-target"),
- });
-
- assert.deepEqual(boundary, { lastTurnId: undefined, rollbackTurnCount: 0 });
- }),
- );
-
- it.effect("fails with a typed error when the selected source turn is missing", () =>
- Effect.gen(function* () {
- const now = yield* DateTime.now;
- const firstTurn = makeProviderTurn("provider-turn-first", 1, "native-turn-first", now);
-
- const error = yield* Effect.flip(
- CodexAdapterV2.resolveCodexForkBoundary({
- sourceProviderThread: makeProviderThread(now),
- sourceProviderTurns: [firstTurn],
- providerTurnId: ProviderTurnId.make("provider-turn-missing"),
- targetThreadId: ThreadId.make("thread-codex-fork-target"),
- }),
- );
-
- assert.instanceOf(error, ProviderAdapter.ProviderAdapterForkThreadError);
- assert.include(String(error.cause), "provider-turn-missing");
- }),
- );
});
const DEFAULT_CODEX_SETTINGS = Schema.decodeSync(CodexSettings)({});
@@ -1042,6 +780,7 @@ describe("CodexAdapterV2 session initialize", () => {
),
);
+ // regression: #16260 one-shot initializers raced; a failed handshake must be retried
it.effect("retries initialize after a failed handshake", () =>
Effect.gen(function* () {
const preamble = replayPreamble("initialize-retry");
@@ -1424,6 +1163,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
+ // regression: #15839 launch-arg MCP servers survive the thread's t3-code server
it.effect("replays historical and dotted MCP config while enforcing other thread config", () =>
Effect.gen(function* () {
const recordedServer = {
@@ -1490,47 +1230,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
}).pipe(Effect.scoped),
);
- it.effect("unsubscribes from the native thread when it is unloaded", () =>
- Effect.gen(function* () {
- const nativeThreadId = "unload-thread";
- const preamble = codexReplayPreamble({
- nativeThreadId,
- nativeTurnId: "unused",
- prompt: "unused",
- });
- const transcript = makeCodexReplayTranscript({
- scenario: "unload-thread",
- entries: [
- ...preamble.slice(0, 5),
- {
- type: "expect_outbound",
- label: "thread/unsubscribe",
- frame: { id: 3, method: "thread/unsubscribe", params: { threadId: nativeThreadId } },
- },
- {
- type: "emit_inbound",
- label: "thread/unsubscribe",
- frame: { id: 3, result: { status: "unsubscribed" } },
- },
- ],
- });
- const requests: Array<string> = [];
- const harness = yield* makeCodexReplayHarness(
- transcript,
- () => Effect.void,
- (method) => Effect.sync(() => requests.push(method)),
- );
- assert.isDefined(harness.runtime.unloadThread);
- yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread });
- assert.deepEqual(requests, ["initialize", "thread/start", "thread/unsubscribe"]);
- }).pipe(
- Effect.scoped,
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- );
-
it.effect("waits for native start before interrupting an acknowledged queued turn", () =>
Effect.gen(function* () {
const nativeThreadId = "early-stop-thread";
@@ -1630,93 +1329,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
- it.effect("settles Stop when a queued native turn fails before starting", () =>
- Effect.gen(function* () {
- const nativeThreadId = "early-stop-thread";
- const nativeTurnId = "early-stop-turn";
- const prompt = "Run a command.";
- const preamble = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt });
- const transcript = makeCodexReplayTranscript({
- scenario: "early-stop-failed-before-native-start",
- entries: [
- ...preamble.slice(0, -2),
- {
- type: "emit_inbound",
- label: "turn/start/queued",
- frame: {
- id: 3,
- result: {
- turn: {
- ...makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }),
- startedAt: null,
- },
- },
- },
- },
- {
- type: "emit_inbound",
- label: "turn/failed",
- afterMs: 1000,
- frame: {
- method: "turn/completed",
- params: {
- threadId: nativeThreadId,
- turn: {
- ...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }),
- startedAt: null,
- error: {
- message: "Failed before native start",
- codexErrorInfo: null,
- additionalDetails: null,
- },
- },
- },
- },
- },
- ],
- });
- let interruptSent = false;
- const harness = yield* makeCodexReplayHarness(
- transcript,
- () => Effect.void,
- (method) =>
- Effect.sync(() => {
- if (method === "turn/interrupt") interruptSent = true;
- }),
- );
- yield* harness.runtime.startTurn(
- makeCodexTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now: yield* DateTime.now,
- attemptId: RunAttemptId.make("early-stop-attempt"),
- text: prompt,
- }),
- );
- const providerTurnId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
- driver: CodexAdapterV2.CODEX_DRIVER_KIND,
- nativeTurnId,
- });
- const interrupt = yield* harness.runtime
- .interruptTurn({ providerThread: harness.providerThread, providerTurnId })
- .pipe(Effect.forkScoped);
- yield* TestClock.adjust("500 millis");
- assert.isFalse(interruptSent, "Stop must not reach Codex before native turn/started");
- yield* TestClock.adjust("500 millis");
- yield* Fiber.join(interrupt);
- yield* harness.firstTerminal;
- assert.equal(harness.terminalEvents()[0]?.status, "failed");
- assert.lengthOf(harness.terminalEvents(), 1);
- assert.isFalse(interruptSent, "A terminal native turn must not receive turn/interrupt");
- assert.isFalse(yield* harness.hasPendingBackgroundWork);
- }).pipe(
- Effect.scoped,
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- );
-
const assistantMessages = (events: ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>) =>
events.filter(
(
@@ -2439,49 +2051,18 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
+ // regression: #15389 archived native Codex sessions resume via thread/unarchive
it.effect.each(
(
[
["recovers archived-session errors", "session saved-thread is archived", 0, ""],
- [
- "recovers unarchive hints",
- "Run `codex unarchive saved-thread` to unarchive it first.",
- 0,
- "",
- ],
["preserves missing-thread errors", "thread not found", 3, "thread not found"],
- ["preserves missing-rollout errors", "no rollout found", 3, "no rollout found"],
- ["preserves authentication errors", "authentication failed", 3, "authentication failed"],
- [
- "preserves archived-workspace errors",
- "workspace is archived",
- 3,
- "workspace is archived",
- ],
- [
- "preserves unrelated archive-path errors",
- "permission denied reading archived_sessions/saved-thread",
- 3,
- "permission denied reading archived_sessions/saved-thread",
- ],
[
"propagates unarchive missing-thread errors",
"session saved-thread is archived",
4,
"thread not found",
],
- [
- "propagates unarchive archived errors",
- "session saved-thread is archived",
- 4,
- "session saved-thread is archived",
- ],
- [
- "propagates retry missing-thread errors",
- "session saved-thread is archived",
- 5,
- "thread not found",
- ],
[
"does not retry archived errors twice",
"session saved-thread is archived",
@@ -2750,109 +2331,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
- it.effect("stamps Codex items with their own start time, not the turn's", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const scenario = "codex-item-start-times";
- const nativeThreadId = `native-${scenario}-thread`;
- const nativeTurnId = `native-${scenario}-turn`;
- const commandLifecycle = (id: string, startedAtMs: number) =>
- (["started", "completed"] as const).map((phase) => ({
- type: "emit_inbound" as const,
- label: `item/${phase}/${id}`,
- frame: {
- method: `item/${phase}`,
- params: {
- threadId: nativeThreadId,
- turnId: nativeTurnId,
- ...(phase === "started" ? { startedAtMs } : { completedAtMs: startedAtMs + 10 }),
- item: {
- type: "commandExecution",
- id,
- command: "pwd",
- cwd: "/workspace",
- processId: "42",
- source: "unifiedExecStartup",
- status: phase === "started" ? "inProgress" : "completed",
- commandActions: [{ type: "unknown", command: "pwd" }],
- aggregatedOutput: phase === "started" ? null : "/workspace\n",
- exitCode: phase === "started" ? null : 0,
- durationMs: phase === "started" ? null : 10,
- },
- },
- },
- }));
- const transcript = makeCodexReplayTranscript({
- scenario,
- entries: [
- ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Run two commands." }),
- ...commandLifecycle("first-command", 1782622445000),
- ...commandLifecycle("second-command", 1782622505000),
- ...(["started", "completed"] as const).map((phase) => ({
- type: "emit_inbound" as const,
- label: `item/${phase}/compaction`,
- frame: {
- method: `item/${phase}`,
- params: {
- threadId: nativeThreadId,
- turnId: nativeTurnId,
- ...(phase === "started"
- ? { startedAtMs: 1782622565000 }
- : { completedAtMs: 1782622575000 }),
- item: { type: "contextCompaction", id: "compaction" },
- },
- },
- })),
- {
- type: "emit_inbound",
- label: "turn/completed",
- 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("attempt-codex-item-start-times"),
- text: "Run two commands.",
- }),
- );
- yield* harness.awaitTerminal(1);
-
- const startedAtByItem = harness.events.flatMap((event) =>
- event.type === "turn_item.updated" &&
- (event.turnItem.type === "command_execution" || event.turnItem.type === "compaction")
- ? [[event.turnItem.nativeItemRef?.nativeId, event.turnItem.startedAt] as const]
- : [],
- );
- assert.deepEqual(
- startedAtByItem.map(([id, startedAt]) => [id, startedAt?.epochMilliseconds]),
- [
- ["first-command", 1782622445000],
- ["first-command", 1782622445000],
- ["second-command", 1782622505000],
- ["second-command", 1782622505000],
- ["compaction", 1782622565000],
- ["compaction", 1782622565000],
- ],
- );
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
it.effect.each(["completed", "interrupted"] as const)(
"retains Codex reasoning parts when the turn is %s",
(terminalStatus) =>
@@ -3154,39 +2632,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
- it.effect("keeps a later non-empty final answer after an initial empty final answer", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const transcript = finalAnswerTranscript("codex-empty-then-non-empty-final", [
- { id: "answer-empty", text: "" },
- { id: "answer-non-empty", text: "CODEX_RECOVERY_OK" },
- ]);
- const harness = yield* makeCodexReplayHarness(transcript);
- const now = yield* DateTime.now;
-
- yield* harness.runtime.startTurn(
- makeCodexTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make("attempt-codex-empty-then-non-empty-final"),
- text: "Reply with the requested recovery marker.",
- }),
- );
- yield* harness.awaitTerminal(1);
-
- assert.deepEqual(
- assistantMessages(harness.events).map((event) => event.message.text),
- ["", "CODEX_RECOVERY_OK"],
- );
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
const BG_SCENARIO = "codex-bg-exec-wake";
const BG_NATIVE_THREAD = "native-codex-bg-thread";
const BG_NATIVE_TURN = "native-codex-bg-turn";
@@ -4320,93 +3765,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
- const childInterruptResponseIndex = interruptSubagentCommandTranscript.entries.findIndex(
- (entry) => entry.type === "emit_inbound" && entry.label === "turn/interrupt/child",
- );
- const rootInterruptResponseIndex = interruptSubagentCommandTranscript.entries.findIndex(
- (entry) => entry.type === "emit_inbound" && entry.label === "turn/interrupt/root",
- );
- const interruptSubagentRequestFailureTranscript = makeCodexReplayTranscript({
- scenario: "codex-interrupt-subagent-request-failure",
- entries: [
- ...interruptSubagentCommandTranscript.entries.slice(0, rootInterruptResponseIndex + 1),
- {
- type: "emit_inbound",
- label: "turn/completed/root-before-child-interrupt-failure",
- frame: {
- method: "turn/completed",
- params: {
- threadId: INTERRUPT_NATIVE_THREAD,
- turn: makeCodexReplayTurn({ id: INTERRUPT_NATIVE_TURN, status: "interrupted" }),
- },
- },
- },
- ...interruptSubagentCommandTranscript.entries.slice(
- rootInterruptResponseIndex + 1,
- childInterruptResponseIndex,
- ),
- {
- type: "emit_inbound",
- label: "turn/interrupt/child",
- frame: {
- id: 5,
- error: { code: -32_000, message: "child interrupt request failed" },
- },
- },
- { type: "runtime_exit", status: "success" },
- ],
- });
-
- it.effect("terminalizes descendants before the root when an interrupt request fails", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const harness = yield* makeCodexReplayHarness(interruptSubagentRequestFailureTranscript);
- const now = yield* DateTime.now;
-
- yield* harness.runtime.startTurn(
- makeCodexTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make("attempt-codex-interrupt-subagent-request-failure"),
- text: INTERRUPT_PROMPT,
- }),
- );
- yield* harness.until(() =>
- harness.events.some(
- (event) =>
- event.type === "turn_item.updated" &&
- event.turnItem.type === "command_execution" &&
- event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_COMMAND_ITEM &&
- event.turnItem.status === "running",
- ),
- );
- const providerTurnId = harness.events.find(
- (
- event,
- ): event is Extract<
- ProviderAdapter.ProviderAdapterV2Event,
- { type: "provider_turn.updated" }
- > => event.type === "provider_turn.updated" && event.threadId === harness.threadId,
- )?.providerTurn.id;
- assert.isDefined(providerTurnId);
-
- const interruptExit = yield* harness.runtime
- .interruptTurn({ providerThread: harness.providerThread, providerTurnId })
- .pipe(Effect.exit);
-
- assert.equal(interruptExit._tag, "Failure");
- yield* harness.awaitTerminal(1);
- assertChildProviderTerminalBeforeRoot(harness.events, harness.threadId);
- assert.isFalse(yield* harness.hasPendingBackgroundWork);
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
const rootCompletionIndex = interruptSubagentCommandTranscript.entries.findIndex(
(entry) => entry.type === "emit_inbound" && entry.label === "turn/completed/root",
);
@@ -4518,115 +3876,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
- const interruptTerminationFailureTranscript = makeCodexReplayTranscript({
- scenario: "codex-interrupt-termination-failure",
- entries: [
- ...interruptMidCommandTranscript.entries
- .filter(
- (entry) => entry.type === "runtime_exit" || entry.label !== "item/completed/command-late",
- )
- .map((entry) =>
- entry.type === "emit_inbound" &&
- entry.label === "thread/backgroundTerminals/list/after-false"
- ? {
- ...entry,
- frame: {
- id: 6,
- result: {
- data: [{ processId: "57680" }],
- nextCursor: null,
- },
- },
- }
- : entry,
- ),
- {
- type: "expect_outbound",
- label: "thread/backgroundTerminals/terminate/one-retry",
- frame: {
- id: 8,
- method: "thread/backgroundTerminals/terminate",
- params: { threadId: INTERRUPT_NATIVE_THREAD, processId: "57680" },
- },
- },
- {
- type: "emit_inbound",
- label: "thread/backgroundTerminals/terminate/one-retry",
- frame: { id: 8, result: { terminated: false } },
- },
- {
- type: "expect_outbound",
- label: "thread/backgroundTerminals/list/after-false-retry",
- frame: {
- id: 9,
- method: "thread/backgroundTerminals/list",
- params: { threadId: INTERRUPT_NATIVE_THREAD },
- },
- },
- {
- type: "emit_inbound",
- label: "thread/backgroundTerminals/list/after-false-retry",
- frame: {
- id: 9,
- result: { data: [{ processId: "57680" }], nextCursor: null },
- },
- },
- { type: "runtime_exit", status: "success" },
- ],
- });
-
- it.effect("attempts every terminal and cleans up tracking when termination fails", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const harness = yield* makeCodexReplayHarness(interruptTerminationFailureTranscript);
- const now = yield* DateTime.now;
-
- yield* harness.runtime.startTurn(
- makeCodexTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make("attempt-codex-interrupt-termination-failure"),
- text: INTERRUPT_PROMPT,
- }),
- );
- yield* harness.until(() =>
- harness.events.some(
- (event) =>
- event.type === "turn_item.updated" &&
- event.turnItem.type === "command_execution" &&
- event.turnItem.status === "running",
- ),
- );
- const providerTurnId = harness.events.find(
- (
- event,
- ): event is Extract<
- ProviderAdapter.ProviderAdapterV2Event,
- { type: "provider_turn.updated" }
- > => event.type === "provider_turn.updated",
- )?.providerTurn.id;
- assert.isDefined(providerTurnId);
-
- const interruptExit = yield* harness.runtime
- .interruptTurn({
- providerThread: harness.providerThread,
- providerTurnId,
- })
- .pipe(Effect.exit);
-
- assert.equal(interruptExit._tag, "Failure");
- yield* harness.awaitTerminal(1);
- assert.equal(harness.terminalEvents()[0]?.status, "interrupted");
- assert.isFalse(yield* harness.hasPendingBackgroundWork);
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
it.effect.each([
{
name: "usage",
@@ -4634,31 +3883,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
notification: false,
expectedClass: "usage_limit",
},
- { name: "rate", code: "rateLimitExceeded", notification: false, expectedClass: "usage_limit" },
- {
- name: "ordinary",
- code: "contextWindowExceeded",
- notification: false,
- expectedClass: "provider_error",
- },
- {
- name: "notification",
- code: "usageLimitExceeded",
- notification: true,
- expectedClass: "usage_limit",
- },
{
name: "replacement",
code: "usageLimitExceeded",
notification: true,
expectedClass: "provider_error",
},
- {
- name: "known-reset",
- code: "usageLimitExceeded",
- notification: false,
- expectedClass: "usage_limit",
- },
{
name: "late-reset",
code: "usageLimitExceeded",
@@ -4717,9 +3947,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
scenario: `codex-limit-${scenario.name}`,
entries: [
...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }),
- ...(scenario.name === "known-reset" || scenario.name === "deferred-reset"
- ? [snapshot]
- : []),
+ ...(scenario.name === "deferred-reset" ? [snapshot] : []),
...(scenario.name === "deferred-reset"
? [
{
@@ -4859,8 +4087,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
if (terminal?.status !== "failed") return;
assert.equal(terminal.failure.class, scenario.expectedClass);
assert.equal(terminal.threadDisposition, "reusable");
- if (scenario.name === "known-reset" || scenario.name === "deferred-reset")
- assert.equal(terminal.failure.resetAt, resetAt);
+ if (scenario.name === "deferred-reset") assert.equal(terminal.failure.resetAt, resetAt);
if (scenario.name === "matching-details")
assert.equal(terminal.failure.message, "Detailed provider allowance explanation.");
if (scenario.name === "late-reset") {
@@ -4882,6 +4109,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
+ // regression: #17501 Codex 429 retry exhaustion classifies as a usage limit
it.effect.each([
{
notificationStatus: 500,
@@ -5664,7 +4892,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
],
});
- it.effect.each(["thread/settings/updated", "model/rerouted"] as const)(
+ it.effect.each(["model/rerouted"] as const)(
"keeps %s child metadata when an older lookup finishes later",
(method) =>
Effect.scoped(
@@ -5676,29 +4904,13 @@ describe("CodexAdapterV2 post-settle continuation", () => {
type: "emit_inbound",
frame: {
method,
- params:
- method === "model/rerouted"
- ? {
- threadId: RESUME_CHILD_THREAD,
- turnId: RESUME_CHILD_TURN_1,
- fromModel: "gpt-6-astra",
- toModel: model,
- reason: "highRiskCyberActivity",
- }
- : {
- threadId: RESUME_CHILD_THREAD,
- threadSettings: {
- model,
- effort: "low",
- serviceTier: "ultrafast",
- modelProvider: "openai",
- cwd: "/workspace",
- approvalPolicy: "never",
- approvalsReviewer: "auto_review",
- collaborationMode: { mode: "default", settings: { model } },
- sandboxPolicy: { type: "dangerFullAccess" },
- },
- },
+ params: {
+ threadId: RESUME_CHILD_THREAD,
+ turnId: RESUME_CHILD_TURN_1,
+ fromModel: "gpt-6-astra",
+ toModel: model,
+ reason: "highRiskCyberActivity",
+ },
},
};
const initialSettings: CodexReplay.CodexAppServerReplayEntry = {
@@ -5828,98 +5040,8 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
- it.effect("rejects duplicate child starts across parent runs", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const firstDone = yield* Deferred.make<void>();
- const resumed = yield* Deferred.make<void>();
- const secondTurn = "native-parent-resume-turn";
- const secondPrompt = "Resume the child.";
- const entries = [...resumeSubagentTranscript.entries];
- const resumeIndex = entries.findIndex(
- (e) => e.type === "emit_inbound" && e.label === `turn/started/${RESUME_CHILD_TURN_2}`,
- );
- const suffix = entries.splice(resumeIndex);
- for (const entry of codexReplayPreamble({
- nativeThreadId: RESUME_NATIVE_THREAD,
- nativeTurnId: secondTurn,
- prompt: secondPrompt,
- }).slice(-3)) {
- entries.push(
- entry.type === "expect_outbound" || entry.type === "emit_inbound"
- ? {
- ...entry,
- frame:
- Predicate.isObject(entry.frame) && "id" in entry.frame
- ? { ...entry.frame, id: 4 }
- : entry.frame,
- }
- : entry,
- );
- }
- entries.push(childTurnStarted(RESUME_CHILD_TURN_1));
- entries.push(...suffix);
- const harness = yield* makeCodexReplayHarness(
- makeCodexReplayTranscript({
- scenario: "codex-cross-run-resume",
- entries,
- }),
- (event) =>
- event.type === "turn.terminal"
- ? Deferred.succeed(firstDone, undefined)
- : event.type === "subagent.updated" && event.subagent.runId === "run-cross-run-second"
- ? Deferred.succeed(resumed, undefined)
- : Effect.void,
- );
- const now = yield* DateTime.now;
- yield* harness.runtime.startTurn(
- makeCodexTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make("cross-run-first"),
- text: RESUME_PROMPT,
- }),
- );
- yield* TestClock.adjust("100 millis");
- yield* Deferred.await(firstDone);
- yield* harness.runtime.startTurn({
- ...makeCodexTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make("cross-run-second"),
- text: secondPrompt,
- }),
- runOrdinal: 2,
- providerTurnOrdinal: 2,
- });
- yield* TestClock.adjust("30 seconds");
- yield* Deferred.await(resumed);
- const row = harness
- .subagentUpdates()
- .find((e) => e.subagent.runId === "run-cross-run-second")?.subagent;
- assert.equal(row?.status, "running");
- assert.equal(row?.parentNodeId, "node-cross-run-second");
- assert.isNull(row?.completedAt);
- assert.isNotNull(row?.startedAt);
- assert.equal(DateTime.toEpochMillis(row!.startedAt!), 1782622470000);
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- ),
- );
-
it.effect.each([
- ["pendingInit", "pending"],
- ["running", "running"],
- ["interrupted", "interrupted"],
["shutdown", "cancelled"],
- ["notFound", "failed"],
- ["errored", "failed"],
- ["completed", "completed"],
["activity-completed", "completed"],
["late-activity-completed", "completed"],
["stale-running", "completed"],
@@ -6528,55 +5650,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
- it.effect("settles /goal pause with a reply instead of a native turn", () =>
- Effect.gen(function* () {
- const transcript = makeCodexReplayTranscript({
- scenario: "goal-pause",
- entries: [
- ...sessionStart,
- ...request(
- 3,
- "thread/goal/get",
- { threadId: nativeThreadId },
- { goal: codexGoal("active", 10) },
- ),
- ...request(
- 4,
- "thread/goal/set",
- { threadId: nativeThreadId, status: "paused" },
- { goal: codexGoal("paused", 10) },
- ),
- ],
- });
- const harness = yield* makeCodexReplayHarness(transcript);
- yield* harness.runtime.startTurn(yield* goalTurnInput(harness, "/goal pause"));
- yield* harness.firstTerminal;
-
- assert.deepEqual(
- harness.terminalEvents().map((event) => event.status),
- ["completed"],
- );
- const turns = harness.events.flatMap((event) =>
- event.type === "provider_turn.updated" ? [event.providerTurn] : [],
- );
- assert.isTrue(turns.every((turn) => turn.nativeTurnRef === null));
- assert.include(
- harness.events.flatMap((event) =>
- event.type === "message.updated" && event.message.role === "assistant"
- ? [event.message.text]
- : [],
- ),
- "Goal paused. Send /goal resume to continue.",
- );
- assert.equal(providerGoals(harness.events).at(-1), "paused");
- }).pipe(
- Effect.scoped,
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- );
-
it.effect("settles a run held for the next goal turn when Stop arrives in between", () =>
Effect.gen(function* () {
const prompt = "Keep going";
@@ -6750,305 +5823,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
- it.effect("stops a held goal run's background command when Stop arrives between turns", () =>
- Effect.gen(function* () {
- const prompt = "Start the server";
- const command = "node server.js";
- const commandItem = (status: "inProgress" | "completed") => ({
- type: "commandExecution",
- id: "goal-bg-command",
- command,
- cwd: "/workspace",
- processId: "4242",
- source: "unifiedExecStartup",
- status,
- commandActions: [{ type: "unknown", command }],
- aggregatedOutput: null,
- exitCode: null,
- durationMs: null,
- });
- const transcript = makeCodexReplayTranscript({
- scenario: "goal-stop-held-background",
- entries: [
- ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "goal-turn", prompt }),
- notification("command started", "item/started", {
- item: commandItem("inProgress"),
- threadId: nativeThreadId,
- turnId: "goal-turn",
- startedAtMs: 1782622440500,
- }),
- notification("goal active", "thread/goal/updated", {
- threadId: nativeThreadId,
- turnId: "goal-turn",
- goal: codexGoal("active", 10),
- }),
- notification("turn done", "turn/completed", {
- threadId: nativeThreadId,
- turn: makeCodexReplayTurn({ id: "goal-turn", status: "completed" }),
- }),
- notification("goal accounted", "thread/goal/updated", {
- threadId: nativeThreadId,
- turnId: null,
- goal: codexGoal("active", 11),
- }),
- ...request(
- 4,
- "thread/goal/set",
- { threadId: nativeThreadId, status: "paused" },
- { goal: codexGoal("paused", 11) },
- ),
- ...request(
- 5,
- "thread/backgroundTerminals/terminate",
- { threadId: nativeThreadId, processId: "4242" },
- { terminated: true },
- ),
- ],
- });
- const harness = yield* makeCodexReplayHarness(transcript);
- yield* harness.runtime.startTurn(
- makeCodexTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now: yield* DateTime.now,
- attemptId: RunAttemptId.make("goal-held-background-attempt"),
- text: prompt,
- }),
- );
- yield* harness.until(() =>
- harness.events.some(
- (event) =>
- event.type === "provider_thread.updated" &&
- event.providerThread.goal?.tokensUsed === 11,
- ),
- );
- yield* harness.runtime.interruptTurn({
- providerThread: harness.providerThread,
- providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
- driver: CodexAdapterV2.CODEX_DRIVER_KIND,
- nativeTurnId: "goal-turn",
- }),
- requestRuntimeRestart: true,
- });
- yield* harness.firstTerminal;
- assert.deepEqual(
- harness.terminalEvents().map((event) => event.status),
- ["interrupted"],
- );
- yield* harness.until(() =>
- harness.events.some(
- (event) =>
- event.type === "turn_item.updated" &&
- event.turnItem.type === "command_execution" &&
- event.turnItem.status === "interrupted",
- ),
- );
- }).pipe(
- Effect.scoped,
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- );
-
- it.effect("moves Stop to a continuation Codex starts while the goal pause is in flight", () =>
- Effect.gen(function* () {
- const prompt = "Keep going";
- const transcript = makeCodexReplayTranscript({
- scenario: "goal-stop-races-continuation",
- entries: [
- ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "goal-turn-a", prompt }),
- notification("goal active", "thread/goal/updated", {
- threadId: nativeThreadId,
- turnId: "goal-turn-a",
- goal: codexGoal("active", 10),
- }),
- {
- type: "expect_outbound",
- label: "thread/goal/set",
- frame: {
- id: 4,
- method: "thread/goal/set",
- params: { threadId: nativeThreadId, status: "paused" },
- },
- },
- notification("first turn done", "turn/completed", {
- threadId: nativeThreadId,
- turn: makeCodexReplayTurn({ id: "goal-turn-a", status: "completed" }),
- }),
- notification("continuation", "turn/started", {
- threadId: nativeThreadId,
- turn: makeCodexReplayTurn({ id: "goal-turn-b", status: "inProgress" }),
- }),
- {
- type: "emit_inbound",
- label: "thread/goal/set",
- frame: { id: 4, result: { goal: codexGoal("paused", 11) } },
- },
- ...request(
- 5,
- "turn/interrupt",
- { threadId: nativeThreadId, turnId: "goal-turn-b" },
- {},
- ),
- notification("continuation interrupted", "turn/completed", {
- threadId: nativeThreadId,
- turn: makeCodexReplayTurn({ id: "goal-turn-b", status: "interrupted" }),
- }),
- ],
- });
- const harness = yield* makeCodexReplayHarness(transcript);
- yield* harness.runtime.startTurn(
- makeCodexTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now: yield* DateTime.now,
- attemptId: RunAttemptId.make("goal-stop-race-attempt"),
- text: prompt,
- }),
- );
- yield* harness.until(() =>
- harness.events.some(
- (event) =>
- event.type === "provider_thread.updated" &&
- event.providerThread.goal?.status === "active",
- ),
- );
- yield* harness.runtime.interruptTurn({
- providerThread: harness.providerThread,
- providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
- driver: CodexAdapterV2.CODEX_DRIVER_KIND,
- nativeTurnId: "goal-turn-a",
- }),
- requestRuntimeRestart: true,
- });
- yield* harness.firstTerminal;
- assert.deepEqual(
- harness.terminalEvents().map((event) => event.status),
- ["interrupted"],
- );
- }).pipe(
- Effect.scoped,
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- );
-
- it.effect("stops an earlier goal turn's subagent when the run settles during the pause", () =>
- Effect.gen(function* () {
- const prompt = "Delegate the audit";
- const childThreadId = "goal-race-child-thread";
- const childTurnId = "goal-race-child-turn";
- const transcript = makeCodexReplayTranscript({
- scenario: "goal-stop-run-settles-during-pause",
- entries: [
- ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "goal-turn-a", prompt }),
- notification("subagent started", "item/completed", {
- item: {
- type: "subAgentActivity",
- id: "goal-race-subagent-call",
- kind: "started",
- agentThreadId: childThreadId,
- agentPath: "/root/audit",
- },
- threadId: nativeThreadId,
- turnId: "goal-turn-a",
- completedAtMs: 1782622441000,
- }),
- notification("child turn", "turn/started", {
- threadId: childThreadId,
- turn: makeCodexReplayTurn({ id: childTurnId, status: "inProgress" }),
- }),
- notification("goal active", "thread/goal/updated", {
- threadId: nativeThreadId,
- turnId: "goal-turn-a",
- goal: codexGoal("active", 10),
- }),
- notification("first turn done", "turn/completed", {
- threadId: nativeThreadId,
- turn: makeCodexReplayTurn({ id: "goal-turn-a", status: "completed" }),
- }),
- notification("continuation", "turn/started", {
- threadId: nativeThreadId,
- turn: makeCodexReplayTurn({ id: "goal-turn-b", status: "inProgress" }),
- }),
- notification("goal accounted", "thread/goal/updated", {
- threadId: nativeThreadId,
- turnId: "goal-turn-b",
- goal: codexGoal("active", 11),
- }),
- {
- type: "expect_outbound",
- label: "thread/goal/set",
- frame: {
- id: 4,
- method: "thread/goal/set",
- params: { threadId: nativeThreadId, status: "paused" },
- },
- },
- notification("goal paused", "thread/goal/updated", {
- threadId: nativeThreadId,
- turnId: "goal-turn-b",
- goal: codexGoal("paused", 11),
- }),
- notification("continuation done", "turn/completed", {
- threadId: nativeThreadId,
- turn: makeCodexReplayTurn({ id: "goal-turn-b", status: "completed" }),
- }),
- {
- type: "emit_inbound",
- label: "thread/goal/set",
- frame: { id: 4, result: { goal: codexGoal("paused", 11) } },
- },
- ...request(5, "turn/interrupt", { threadId: childThreadId, turnId: childTurnId }, {}),
- notification("child interrupted", "turn/completed", {
- threadId: childThreadId,
- turn: makeCodexReplayTurn({ id: childTurnId, status: "interrupted" }),
- }),
- ],
- });
- const harness = yield* makeCodexReplayHarness(transcript);
- yield* harness.runtime.startTurn(
- makeCodexTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now: yield* DateTime.now,
- attemptId: RunAttemptId.make("goal-settles-during-pause-attempt"),
- text: prompt,
- }),
- );
- yield* harness.until(() =>
- harness.events.some(
- (event) =>
- event.type === "provider_thread.updated" &&
- event.providerThread.goal?.tokensUsed === 11,
- ),
- );
- yield* harness.runtime.interruptTurn({
- providerThread: harness.providerThread,
- providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
- driver: CodexAdapterV2.CODEX_DRIVER_KIND,
- nativeTurnId: "goal-turn-b",
- }),
- requestRuntimeRestart: true,
- });
- yield* harness.until(() =>
- harness.events.some(
- (event) =>
- event.type === "provider_turn.updated" &&
- event.providerTurn.nativeTurnRef?.nativeId === childTurnId &&
- event.providerTurn.status === "interrupted",
- ),
- );
- }).pipe(
- Effect.scoped,
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
- ),
- ),
- );
-
it.effect("pauses an active goal before Stop interrupts its turn", () =>
Effect.gen(function* () {
const prompt = "Keep going";
diff --git a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts
index dc24430a485..d2c23e185ba 100644
--- a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts
@@ -166,20 +166,6 @@ describe("GrokAdapterV2 capabilities", () => {
});
describe("ACP permission policy", () => {
- it("honors explicit on-request approval over full-access runtime mode", () => {
- assert.equal(
- acpPermissionDisposition(
- runtimePolicy({
- runtimeMode: "full-access",
- approvalPolicy: "on-request",
- sandboxPolicy: { type: "readOnly" },
- }),
- permissionRequest("execute"),
- ),
- "ask",
- );
- });
-
it("rejects mutating escalation under a non-interactive read-only policy", () => {
const policy = runtimePolicy({
runtimeMode: "full-access",
@@ -372,25 +358,6 @@ describe("Grok launch permission mode", () => {
]);
}),
);
-
- it.effect("launches asking when an explicit approval or sandbox policy governs the thread", () =>
- Effect.gen(function* () {
- const asking = [["--permission-mode", "default", "agent", "stdio"]];
- assert.deepEqual(
- yield* launchArgs(
- policy("full-access", {
- approvalPolicy: "never",
- sandboxPolicy: { type: "workspaceWrite", writableRoots: [], networkAccess: false },
- }),
- ),
- asking,
- );
- assert.deepEqual(
- yield* launchArgs(policy("full-access", { approvalPolicy: "on-request" })),
- asking,
- );
- }),
- );
});
describe("Grok native questions", () => {
diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
index cca0883dc2b..a068a08c5e2 100644
--- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
@@ -486,6 +486,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
+ // regression: #18315 OpenCode Go quota stops were not shown as usage limits
it.effect.each([
["provider.quota", "usage_limit"],
["provider.rate-limit", "usage_limit"],
@@ -721,90 +722,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
- it.effect("keeps tracking a background subagent whose Stop did not reach it", () =>
- Effect.gen(function* () {
- const { runtime, thread } = yield* resumed([
- ...backgroundLaunch(CHILD),
- out("session.interrupt", { sessionID: CHILD }),
- reply("session.interrupt", {
- status: 500,
- body: { _tag: "UnknownError", message: "interrupt failed" },
- }),
- out("session.interrupt", { sessionID: SESSION }),
- reply("session.interrupt", { interrupted: true }),
- event("session.execution.interrupted", { sessionID: SESSION }),
- ]);
- const watch = yield* watchBackgroundTurn(runtime);
- yield* runtime.startTurn(withLineage(thread));
- yield* watch.attached;
- yield* runtime.interruptTurn({
- providerThread: thread,
- providerTurnId: yield* providerTurnId,
- requestRuntimeRestart: true,
- });
- assert.equal((yield* watch.terminal)?.status, "interrupted");
- assert.isTrue(yield* runtime.hasPendingBackgroundWork!);
- assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
- }).pipe(Effect.scoped),
- );
-
- it.effect("stops a background subagent announced before its call named it", () =>
- Effect.gen(function* () {
- const call = "call-background";
- const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: call };
- const { runtime, thread } = yield* resumed([
- out("session.prompt", { sessionID: SESSION, text: "<any>" }),
- promptAccepted,
- event("session.execution.started", { sessionID: SESSION }),
- event("session.tool.input.started", { ...tool, name: "subagent" }),
- event("session.tool.called", {
- ...tool,
- name: "subagent",
- input: { description: "Sleep", prompt: "sleep", background: true },
- executed: false,
- }),
- event("session.created", childCreated(CHILD)),
- event("session.text.ended", {
- sessionID: SESSION,
- assistantMessageID: "msg_assistant",
- ordinal: 0,
- text: "Launched.",
- }),
- out("session.interrupt", { sessionID: CHILD }),
- reply("session.interrupt", { interrupted: true }),
- out("session.interrupt", { sessionID: SESSION }),
- reply("session.interrupt", { interrupted: true }),
- event("session.execution.interrupted", { sessionID: SESSION }),
- ]);
- const announced = yield* Deferred.make<void>();
- const terminal = yield* runtime.events.pipe(
- Stream.tap((event) =>
- event.type === "turn_item.updated" && event.turnItem.type === "assistant_message"
- ? Deferred.succeed(announced, undefined)
- : Effect.void,
- ),
- Stream.filter(
- (
- event,
- ): event is Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }> =>
- event.type === "turn.terminal",
- ),
- Stream.runHead,
- Effect.map(Option.getOrUndefined),
- Effect.forkScoped,
- );
- yield* runtime.startTurn(withLineage(thread));
- yield* Deferred.await(announced);
- yield* runtime.interruptTurn({
- providerThread: thread,
- providerTurnId: yield* providerTurnId,
- requestRuntimeRestart: true,
- });
- assert.equal((yield* Fiber.join(terminal))?.status, "interrupted");
- assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
- }).pipe(Effect.scoped),
- );
-
it.effect("gives a background subagent the rules of a mode changed while it runs", () =>
Effect.gen(function* () {
const { runtime, thread } = yield* resumed([
@@ -1033,6 +950,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
+ // regression: #21979 a failed background subagent pinned its thread as busy
it.effect("settles the background call a foreground call joined to a failed child", () =>
Effect.gen(function* () {
const again = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-again" };
@@ -1122,152 +1040,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
- it.effect("leaves no background work pending once a reconnect finds its subagent gone", () =>
- Effect.gen(function* () {
- const { runtime, thread } = yield* resumed([
- ...backgroundLaunch(CHILD),
- event("session.execution.started", { sessionID: CHILD }),
- event("session.execution.succeeded", { sessionID: SESSION }),
- { type: "runtime_exit", status: "success" } as const,
- out("event.subscribe"),
- out("session.active"),
- replyData("session.active", {}),
- ]);
- const settled = yield* Deferred.make<string | null>();
- yield* runtime.events.pipe(
- Stream.tap((event) =>
- event.type === "subagent.updated" && event.subagent.status === "interrupted"
- ? Deferred.succeed(settled, event.subagent.result)
- : Effect.void,
- ),
- Stream.runDrain,
- Effect.forkScoped,
- );
- yield* runtime.startTurn(withLineage(thread));
- assert.include((yield* Deferred.await(settled)) ?? "", "lost its connection to OpenCode");
- assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
- assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
- }).pipe(Effect.scoped),
- );
-
- it.effect("stops a nested background subagent's report on its own parent's session", () =>
- Effect.gen(function* () {
- const MIDDLE = "ses_middle0000000000000000000";
- const GRANDCHILD = "ses_grandchild00000000000000";
- const tool = (session: string, id: string) => ({
- sessionID: session,
- assistantMessageID: `msg_assistant_${id}`,
- id,
- });
- const report = {
- inboxID: "msg_nested_report",
- sessionID: MIDDLE,
- item: {
- type: "synthetic",
- payload: {
- text: `<subagent sessionID="${GRANDCHILD}" state="cancelled" description="Deep">\n</subagent>`,
- description: "Deep",
- metadata: {
- source: "subagent",
- childID: GRANDCHILD,
- agent: "General",
- state: "cancelled",
- },
- },
- delivery: "steer",
- },
- };
- const offered = yield* Deferred.make<void>();
- const { runtime, thread } = yield* resumed([
- out("session.prompt", { sessionID: SESSION, text: "<any>" }),
- promptAccepted,
- event("session.execution.started", { sessionID: SESSION }),
- event("session.tool.input.started", { ...tool(SESSION, "call-middle"), name: "subagent" }),
- event("session.tool.called", {
- ...tool(SESSION, "call-middle"),
- name: "subagent",
- input: { description: "Middle", prompt: "delegate", background: true },
- executed: false,
- }),
- event("session.created", { ...childCreated(MIDDLE), title: "Middle" }),
- event("session.tool.progress", {
- ...tool(SESSION, "call-middle"),
- metadata: { sessionID: MIDDLE, status: "running" },
- }),
- event("session.execution.started", { sessionID: MIDDLE }),
- event("session.tool.input.started", { ...tool(MIDDLE, "call-deep"), name: "subagent" }),
- event("session.tool.called", {
- ...tool(MIDDLE, "call-deep"),
- name: "subagent",
- input: { description: "Deep", prompt: "sleep", background: true },
- executed: false,
- }),
- event("session.created", {
- ...childCreated(GRANDCHILD),
- parentID: MIDDLE,
- title: "Deep",
- }),
- event("session.tool.progress", {
- ...tool(MIDDLE, "call-deep"),
- metadata: { sessionID: GRANDCHILD, status: "running" },
- }),
- event("session.text.ended", {
- sessionID: SESSION,
- assistantMessageID: "msg_assistant_root",
- ordinal: 0,
- text: "Launched.",
- }),
- out("session.interrupt", { sessionID: MIDDLE }),
- reply("session.interrupt", { interrupted: true }),
- out("session.interrupt", { sessionID: GRANDCHILD }),
- reply("session.interrupt", { interrupted: true }),
- out("session.interrupt", { sessionID: SESSION }),
- reply("session.interrupt", { interrupted: true }),
- event("session.execution.interrupted", { sessionID: SESSION }),
- event("session.execution.interrupted", { sessionID: MIDDLE }),
- event("session.inbox.enqueued", report),
- event("session.execution.started", { sessionID: MIDDLE }),
- out("session.interrupt", { sessionID: MIDDLE }),
- reply("session.interrupt", { interrupted: true }),
- event("session.execution.interrupted", { sessionID: MIDDLE }),
- event("session.execution.started", { sessionID: SESSION }),
- ]).pipe(
- Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
- offer: () => Deferred.succeed(offered, undefined).pipe(Effect.asVoid),
- take: Effect.never,
- }),
- );
- const launched = yield* Deferred.make<void>();
- const middleTurns: Array<string> = [];
- yield* runtime.events.pipe(
- Stream.tap((event) =>
- Effect.gen(function* () {
- if (
- event.type === "provider_turn.updated" &&
- event.providerTurn.nativeTurnRef?.nativeId?.startsWith(`${MIDDLE}:turn:`) === true
- ) {
- middleTurns.push(event.providerTurn.nativeTurnRef.nativeId);
- }
- if (event.type === "turn_item.updated" && event.turnItem.type === "assistant_message") {
- yield* Deferred.succeed(launched, undefined);
- }
- }),
- ),
- Stream.runDrain,
- Effect.forkScoped,
- );
- yield* runtime.startTurn(withLineage(thread));
- yield* Deferred.await(launched);
- yield* runtime.interruptTurn({
- providerThread: thread,
- providerTurnId: yield* providerTurnId,
- requestRuntimeRestart: true,
- });
- yield* Deferred.await(offered);
- assert.deepEqual([...new Set(middleTurns)], [`${MIDDLE}:turn:1`]);
- }).pipe(Effect.scoped),
- );
-
const MIDDLE = "ses_middle0000000000000000000";
const DEEP = "ses_grandchild00000000000000";
const toolOf = (session: string, id: string) => ({
@@ -1409,58 +1181,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
- it.effect("keeps a reused subagent's background subagent tracked and stops it", () =>
- Effect.gen(function* () {
- const again = "call-middle-again";
- const { runtime, thread } = yield* resumed([
- ...nestedLaunch,
- out("session.update", { sessionID: DEEP, permissions: "<any>" }),
- reply("session.update", null),
- out("session.prompt", { sessionID: SESSION, text: "<any>" }),
- promptAccepted,
- event("session.execution.started", { sessionID: SESSION }),
- event("session.tool.input.started", { ...toolOf(SESSION, again), name: "subagent" }),
- event("session.tool.called", {
- ...toolOf(SESSION, again),
- name: "subagent",
- input: { description: "Middle", prompt: "again", sessionID: MIDDLE },
- executed: false,
- }),
- event("session.tool.progress", {
- ...toolOf(SESSION, again),
- metadata: { sessionID: MIDDLE, status: "running" },
- }),
- out("session.update", { sessionID: MIDDLE, permissions: "<any>" }),
- reply("session.update", null),
- event("session.execution.started", { sessionID: MIDDLE }),
- event("session.execution.succeeded", { sessionID: MIDDLE }),
- event("session.tool.success", {
- ...toolOf(SESSION, again),
- content: [{ type: "text", text: `<subagent sessionID="${MIDDLE}" state="completed">` }],
- metadata: { sessionID: MIDDLE, status: "completed", truncated: false },
- executed: false,
- }),
- event("session.execution.succeeded", { sessionID: SESSION }),
- out("session.interrupt", { sessionID: DEEP }),
- reply("session.interrupt", { interrupted: true }),
- ]);
- const watch = yield* watchNested(runtime);
- yield* runtime.startTurn(withLineage(thread));
- yield* watch.until(() => watch.terminals.length === 1);
- yield* runtime.startTurn({ ...secondTurn(thread), appThread: withLineage(thread).appThread });
- yield* watch.until(() => watch.terminals.length === 2);
- assert.deepEqual(watch.terminals, ["completed", "completed"]);
- assert.equal(watch.deep.at(-1), "running");
- assert.isTrue(yield* runtime.hasPendingBackgroundWork!);
- yield* runtime.interruptTurn({
- providerThread: thread,
- providerTurnId: yield* providerTurnId,
- requestRuntimeRestart: true,
- });
- yield* watch.until(() => watch.deep.at(-1) === "interrupted");
- }).pipe(Effect.scoped),
- );
-
it.effect("stops the turn a foreground subagent runs to answer its background subagent", () =>
Effect.gen(function* () {
const { runtime, thread } = yield* resumed([
@@ -1578,6 +1298,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
);
+ // regression: #14744 continuations hung after a reconnect took a Stop's end
it.effect("still checks the server when a failed prompt's execution starts late", () =>
Effect.gen(function* () {
const offered = yield* Deferred.make<void>();
@@ -1608,26 +1329,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
);
- it.effect("prompts again without a check after the server refused a prompt", () =>
- Effect.gen(function* () {
- const { runtime, thread } = yield* resumed([
- out("session.prompt", { sessionID: SESSION, text: "<any>" }),
- reply("session.prompt", {
- status: 400,
- body: { _tag: "InvalidRequestError", message: "bad prompt" },
- }),
- out("session.prompt", { sessionID: SESSION, text: "<any>" }),
- promptAccepted,
- event("session.execution.succeeded", { sessionID: SESSION }),
- ]);
- const ended = yield* terminals(runtime, 2);
- yield* runtime.startTurn(turnInput(thread)).pipe(Effect.ignore);
- yield* runtime.startTurn(secondTurn(thread));
- const [first, second] = yield* Fiber.join(ended);
- assert.deepEqual([first?.status, second?.status], ["failed", "completed"]);
- }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
- );
-
it.effect("ends a background reply's continuation after a lost stream took a Stop's end", () =>
Effect.gen(function* () {
const offered =
@@ -1845,29 +1546,11 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
);
}).pipe(Effect.scoped, Effect.provide(TestClock.layer()));
+ // regression: #14744 continuations hung after a reconnect took a Stop's end
it.effect("ends a background reply's continuation after a prompt failed unclearly", () =>
replyAfterUnclearFailure(false),
);
- it.effect("does not report a Stop the server says did nothing", () =>
- Effect.gen(function* () {
- const { runtime, thread } = yield* resumed([
- out("session.prompt", { sessionID: SESSION, text: "<any>" }),
- promptAccepted,
- out("session.interrupt", { sessionID: SESSION }),
- reply("session.interrupt", { interrupted: false }),
- ]);
- yield* runtime.startTurn(turnInput(thread));
- const failed = yield* runtime
- .interruptTurn({
- providerThread: thread,
- providerTurnId: yield* providerTurnId,
- })
- .pipe(Effect.flip);
- assert.equal(failed._tag, "ProviderAdapterProtocolError");
- }).pipe(Effect.scoped),
- );
-
it.effect("reports a turn as completed when its Stop request failed", () =>
Effect.gen(function* () {
const { runtime, thread } = yield* resumed([
@@ -1961,21 +1644,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
- it.effect("refuses a model slug that is not provider/model before creating a session", () =>
- Effect.gen(function* () {
- const runtime = yield* openCode2ReplayRuntime([...opening]);
- const created = yield* runtime
- .ensureThread({
- threadId,
- modelSelection: { instanceId, model: "big-pickle" },
- runtimePolicy: policy(),
- })
- .pipe(Effect.flip);
- assert.equal(created._tag, "ProviderAdapterProtocolError");
- assert.include(created.message, "OpenCode model 'big-pickle' must use provider/model format");
- }).pipe(Effect.scoped),
- );
-
it.effect("stops the requests a session still waits on when a restarted T3 loads it", () =>
Effect.gen(function* () {
const runtime = yield* openCode2ReplayRuntimeWithInstructions(
@@ -2173,106 +1841,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
- const subagentAsks = (child: string): ReadonlyArray<ProviderReplayEntry> => {
- const call = "call-subagent";
- const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: call };
- return [
- out("session.prompt", { sessionID: SESSION, text: "<any>" }),
- promptAccepted,
- event("session.execution.started", { sessionID: SESSION }),
- event("session.tool.input.started", { ...tool, name: "subagent" }),
- event("session.tool.called", {
- ...tool,
- name: "subagent",
- input: { description: "Echo", prompt: "echo" },
- executed: false,
- }),
- event("session.created", { ...childCreated(child), title: "Echo" }),
- event("session.tool.progress", {
- ...tool,
- metadata: { sessionID: child, status: "running" },
- }),
- event("session.execution.started", { sessionID: child }),
- event("permission.asked", { ...shellAsk.data, sessionID: child }),
- ];
- };
-
- it.effect("keeps a subagent's 'allow this session' in the subagent's own rules", () =>
- Effect.gen(function* () {
- const { runtime, thread } = yield* resumed(
- [
- ...subagentAsks(CHILD),
- out("session.update", {
- sessionID: CHILD,
- permissions: [
- ...supervisedRules.slice(0, 3),
- { action: "shell", resource: "echo *", effect: "allow" },
- ...mcpRules,
- ],
- }),
- reply("session.update", null),
- out("permission.reply", {
- sessionID: CHILD,
- requestID: shellAsk.data.id,
- decision: "once",
- }),
- reply("permission.reply", null),
- event("session.execution.succeeded", { sessionID: CHILD }),
- event("session.execution.succeeded", { sessionID: SESSION }),
- ],
- { supervised: true },
- );
- const requested = yield* requestOf(runtime).pipe(Effect.forkScoped);
- const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
- yield* runtime.startTurn({
- ...withLineage(thread),
- runtimePolicy: policy("approval-required"),
- });
- const request = yield* Fiber.join(requested);
- yield* runtime.respondToRuntimeRequest({
- requestId: request!.id,
- decision: "acceptForSession",
- });
- assert.equal((yield* Fiber.join(terminal))?.status, "completed");
- }).pipe(Effect.scoped),
- );
-
- it.effect("ends only the subagent's turn when it declines the subagent's form", () =>
- Effect.gen(function* () {
- const linkForm = {
- id: "frm_0eb79ab35001fkvFECSh3wYNVD",
- sessionID: CHILD,
- title: "MCP authorization",
- metadata: { kind: "mcp" },
- fields: [{ key: "authorization", type: "external", url: "https://example.com/authorize" }],
- };
- const { runtime, thread } = yield* resumed([
- ...subagentAsks(CHILD).slice(0, -1),
- event("form.created", { form: linkForm }),
- out("session.form.cancel", { sessionID: CHILD, formID: linkForm.id }),
- reply("session.form.cancel", null),
- event("session.execution.interrupted", { sessionID: CHILD }),
- event("session.tool.failed", {
- sessionID: SESSION,
- assistantMessageID: "msg_assistant",
- id: "call-subagent",
- error: { type: "unknown", message: `Subagent cancelled (sessionID: ${CHILD})` },
- executed: true,
- }),
- event("session.text.ended", {
- sessionID: SESSION,
- assistantMessageID: "msg_assistant_after",
- ordinal: 0,
- text: "The subagent could not finish.",
- }),
- event("session.execution.succeeded", { sessionID: SESSION }),
- ]);
- const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
- yield* runtime.startTurn(withLineage(thread));
- assert.equal((yield* Fiber.join(terminal))?.status, "completed");
- }).pipe(Effect.scoped),
- );
-
it.effect("keeps 'allow this session' in the session's rules, not OpenCode's saved grants", () =>
Effect.gen(function* () {
const { runtime, thread } = yield* resumed(
@@ -2537,90 +2105,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
- it.effect(
- "backfills and ends a subagent's turn whose execution ended while the stream was down",
- () =>
- Effect.gen(function* () {
- const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-sub" };
- const SUB_PROMPT = "msg_0f73f91e0002lgRNb7FtMzcoQu";
- const { runtime, thread } = yield* resumed([
- out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
- promptAccepted,
- event("session.execution.started", { sessionID: SESSION }),
- event("session.tool.input.started", { ...tool, name: "subagent" }),
- event("session.tool.called", {
- ...tool,
- name: "subagent",
- input: { description: "Sleep", prompt: "sleep" },
- executed: false,
- }),
- event("session.created", childCreated(CHILD)),
- event("session.tool.progress", {
- ...tool,
- metadata: { sessionID: CHILD, status: "running" },
- }),
- event("session.inbox.enqueued", {
- inboxID: SUB_PROMPT,
- sessionID: CHILD,
- item: { type: "user", payload: { text: "sleep" }, delivery: "steer" },
- }),
- event("session.execution.started", { sessionID: CHILD }),
- { type: "runtime_exit", status: "success" } as const,
- out("event.subscribe"),
- out("session.active"),
- replyData("session.active", { [SESSION]: { type: "running" } }),
- out("message.list", { sessionID: CHILD, order: "desc", limit: "50" }),
- reply("message.list", {
- data: [
- { id: "msg_idle_sub", time: { created: 4 }, type: "idle", outcome: "succeeded" },
- {
- id: "msg_assistant_sub",
- time: { created: 3 },
- type: "assistant",
- agent: "general",
- model: { id: "big-pickle", providerID: "opencode", variant: "default" },
- content: [{ type: "text", text: "Slept while the stream was down." }],
- finish: "stop",
- },
- { id: SUB_PROMPT, time: { created: 2 }, text: "sleep", type: "user" },
- ],
- cursor: {},
- }),
- out("message.list", { sessionID: SESSION, order: "desc", limit: "50" }),
- reply("message.list", {
- data: [{ id: PROMPT_ID, time: { created: 1 }, text: "hi", type: "user" }],
- cursor: {},
- }),
- ...openRequests([]),
- event("session.execution.succeeded", { sessionID: SESSION }),
- ]);
- const events = yield* runtime.events.pipe(
- Stream.takeUntil((event) => event.type === "turn.terminal"),
- Stream.runCollect,
- Effect.forkScoped,
- );
- yield* runtime.startTurn(withLineage(thread));
- const collected = yield* Fiber.join(events);
- const childTurn = collected.findLast(
- (event) =>
- event.type === "provider_turn.updated" &&
- event.providerTurn.nativeTurnRef?.nativeId === `${CHILD}:turn:1`,
- );
- assert.isTrue(
- collected.some(
- (event) =>
- event.type === "turn_item.updated" &&
- event.turnItem.type === "assistant_message" &&
- event.turnItem.text === "Slept while the stream was down.",
- ),
- );
- assert.equal(
- childTurn?.type === "provider_turn.updated" ? childTurn.providerTurn.status : undefined,
- "completed",
- );
- }).pipe(Effect.scoped),
- );
-
it.effect("keeps a turn still running after a reconnect open for its next events", () =>
Effect.gen(function* () {
const { runtime, thread } = yield* resumed([
@@ -2756,47 +2240,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
- it.effect(
- "registers T3's MCP server for the thread alone and removes it when the thread unloads",
- () =>
- Effect.gen(function* () {
- const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
- yield* mcpSessions.set({
- environmentId: EnvironmentId.make("environment:opencode2-adapter"),
- threadId,
- providerSessionId: "mcp:opencode2-adapter",
- providerInstanceId: instanceId,
- endpoint: "http://127.0.0.1:3773/mcp",
- authorizationHeader: "Bearer thread-credential",
- browserToolsAvailable: false,
- });
- yield* Effect.addFinalizer(() => mcpSessions.clear(threadId));
- const server = "t3-code-thread_opencode2-adapter";
- const { runtime, thread } = yield* resumed([
- out("mcp.add", {
- server,
- "location[directory]": WORK,
- config: {
- type: "remote",
- url: "http://127.0.0.1:3773/mcp",
- headers: { Authorization: "Bearer thread-credential" },
- oauth: false,
- },
- }),
- reply("mcp.add", null),
- out("session.prompt", { sessionID: SESSION, text: "<any>" }),
- promptAccepted,
- event("session.execution.succeeded", { sessionID: SESSION }),
- out("mcp.remove", { server, "location[directory]": WORK }),
- reply("mcp.remove", null),
- ]);
- const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
- yield* runtime.startTurn(turnInput(thread));
- assert.equal((yield* Fiber.join(terminal))?.status, "completed");
- yield* runtime.unloadThread!({ providerThread: thread });
- }).pipe(Effect.scoped),
- );
-
it.effect("re-registers T3 MCP each turn and drops its instructions when adding fails", () =>
Effect.gen(function* () {
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
@@ -2912,6 +2355,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
+ // regression: #16142 OpenCode 2 threads were missing T3 Code's MCP tools
it.effect("names each thread's MCP server within OpenCode's limits, one name per thread", () =>
Effect.gen(function* () {
const project = "thread:project:ce04e4e2-6c29-4ff0-a1d7-b089dd63e258";
@@ -3373,10 +2817,10 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
+ // regression: #15672 OpenCode 2 provider retries ran silently instead of showing
it.effect.each([
{ name: "restores retry pending at reconnect", pending: true, streamed: false },
{ name: "settles retry recovered during drop", pending: false, streamed: false },
- { name: "keeps retry pending when only streamed at reconnect", pending: true, streamed: true },
])("$name", ({ pending, streamed }) =>
Effect.gen(function* () {
const gate = makeProviderReplayGate(["finish"]);
@@ -3819,6 +3263,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped, Effect.provide(IdAllocator.layer)),
);
+ // regression: #16775 unchanged session status updates were rewritten on every event
it.effect("reports the shared session's status only when it changes", () =>
Effect.gen(function* () {
const OTHER = "ses_f148ca2deffeOtherSession000";
@@ -3885,7 +3330,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
it.effect.each([
["refuses a rollback while a timed-out Stop's run is still going", true],
- ["rolls back once a timed-out Stop's run has left the server", false],
] as const)("%s", ([, running]) =>
Effect.gen(function* () {
const prompt = `msg_t3_turn_${SESSION}:attempt:opencode2-adapter`;
@@ -4164,7 +3608,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
);
it.effect.each([
- ["refuses to roll back a session not loaded yet while the server runs it", true],
[
"keeps the recorded turns before the target when rolling back a session not loaded yet",
false,
@@ -4270,23 +3713,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
- it.effect("asks the server before forking a session this runtime has not loaded", () =>
- Effect.gen(function* () {
- const runtime = yield* openCode2ReplayRuntime([
- ...opening,
- out("session.active"),
- reply("session.active", { data: { [SESSION]: { type: "running" } } }),
- ]);
- const refused = yield* runtime
- .forkThread({
- sourceProviderThread: providerThread(yield* DateTime.now),
- 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";
@@ -4414,35 +3840,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
- it.effect("rolls back before a continuation's report, so its answer leaves the history", () =>
- Effect.gen(function* () {
- const { runtime, thread, first, second } = yield* continued([
- out("message.list", "<any>"),
- reply("message.list", continuedHistory),
- 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", "<any>"),
- reply("message.list", { data: [continuedHistory.data[1]], cursor: {} }),
- ]);
- 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";
@@ -4630,6 +4027,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}).pipe(Effect.scoped),
);
+ // regression: #14752 continuations replayed background replies that were not theirs
it.effect("ends a continuation while a skipped reply's subagent does not answer its Stop", () =>
Effect.gen(function* () {
const CHILD_B = "ses_f1485c529ffeBBBBBBBBBBBBBB";
diff --git a/apps/server/src/orchestration-v2/Adapters/claudeWorkflowProgress.test.ts b/apps/server/src/orchestration-v2/Adapters/claudeWorkflowProgress.test.ts
index d93049b90dd..baea36ca738 100644
--- a/apps/server/src/orchestration-v2/Adapters/claudeWorkflowProgress.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/claudeWorkflowProgress.test.ts
@@ -2,14 +2,6 @@ import { describe, expect, it } from "vite-plus/test";
import { mergeClaudeWorkflowProgress } from "./claudeWorkflowProgress.ts";
-const startFrame = {
- type: "system",
- subtype: "task_started",
- task_id: "w1",
- task_type: "local_workflow",
- workflow_name: "probe-wf",
-};
-
const snapshotFrame = (
entries: ReadonlyArray<Record<string, unknown>>,
usage?: Record<string, number>,
@@ -35,21 +27,6 @@ const agent = (overrides: Record<string, unknown>) => ({
});
describe("mergeClaudeWorkflowProgress", () => {
- it("leaves an ordinary subagent's frames alone", () => {
- expect(
- mergeClaudeWorkflowProgress({
- previous: undefined,
- message: {
- type: "system",
- subtype: "task_progress",
- task_id: "t1",
- description: "reading files",
- usage: { total_tokens: 500, tool_uses: 2, duration_ms: 90 },
- },
- }),
- ).toBeUndefined();
- });
-
it("maps provider agent states and per-member metrics", () => {
const workflow = mergeClaudeWorkflowProgress({
previous: undefined,
@@ -128,18 +105,6 @@ describe("mergeClaudeWorkflowProgress", () => {
expect(second?.totalTokens).toBe(250);
});
- it("keeps a phase the plan reached at runtime even if a later frame omits it", () => {
- const first = mergeClaudeWorkflowProgress({
- previous: undefined,
- message: snapshotFrame([phase(1, "Alpha"), phase(2, "Beta"), phase(3, "Gamma")]),
- });
- const second = mergeClaudeWorkflowProgress({
- previous: first,
- message: snapshotFrame([phase(1, "Alpha")]),
- });
- expect(second?.phases.map((entry) => entry.title)).toEqual(["Alpha", "Beta", "Gamma"]);
- });
-
it("keeps other members and phase links when a sparse frame starts a new attempt", () => {
const first = mergeClaudeWorkflowProgress({
previous: undefined,
@@ -214,62 +179,6 @@ describe("mergeClaudeWorkflowProgress", () => {
expect(second?.agents).toEqual(first?.agents);
});
- it("retains member fields omitted by a later frame in the same attempt", () => {
- const first = mergeClaudeWorkflowProgress({
- previous: undefined,
- message: snapshotFrame([agent({ attempt: 2, promptPreview: "Current prompt", tokens: 100 })]),
- });
- const second = mergeClaudeWorkflowProgress({
- previous: first,
- message: snapshotFrame([agent({ state: "done", resultPreview: "Current result" })]),
- });
- expect(second?.agents[0]).toMatchObject({
- state: "completed",
- attempt: 2,
- prompt: "Current prompt",
- result: "Current result",
- totalTokens: 100,
- });
- });
-
- it("keeps existing run handles when a later acknowledgement supplies only a script path", () => {
- const first = mergeClaudeWorkflowProgress({
- previous: undefined,
- runHandles: { runId: "wf_abc", transcriptDir: "/workflows/wf_abc" },
- message: startFrame,
- });
- const second = mergeClaudeWorkflowProgress({
- previous: first,
- runHandles: { scriptPath: "/scripts/workflow.js" },
- message: startFrame,
- });
- expect(second?.runHandles).toEqual({
- runId: "wf_abc",
- transcriptDir: "/workflows/wf_abc",
- scriptPath: "/scripts/workflow.js",
- });
- });
-
- it("drops timestamps outside the DateTime range", () => {
- const workflow = mergeClaudeWorkflowProgress({
- previous: undefined,
- message: snapshotFrame([
- agent({
- state: "done",
- lastProgressAt: 8_640_000_000_000_001,
- startedAt: 8_640_000_000_000_001,
- queuedAt: Number.MAX_SAFE_INTEGER,
- }),
- agent({ index: 2, startedAt: 8_640_000_000_000_000, queuedAt: 0 }),
- ]),
- });
- expect(workflow?.agents[0]).not.toHaveProperty("startedAt");
- expect(workflow?.agents[0]).not.toHaveProperty("queuedAt");
- expect(workflow?.agents[0]).not.toHaveProperty("completedAt");
- expect(workflow?.agents[1]?.startedAt).toBe(8_640_000_000_000_000);
- expect(workflow?.agents[1]?.queuedAt).toBe(0);
- });
-
it("drops malformed entries instead of failing the frame", () => {
const workflow = mergeClaudeWorkflowProgress({
previous: undefined,
diff --git a/apps/server/src/orchestration-v2/AttachmentClaims.test.ts b/apps/server/src/orchestration-v2/AttachmentClaims.test.ts
index a84fd8c0f60..324ff6b1fb8 100644
--- a/apps/server/src/orchestration-v2/AttachmentClaims.test.ts
+++ b/apps/server/src/orchestration-v2/AttachmentClaims.test.ts
@@ -17,11 +17,7 @@ import {
parseThreadSegmentFromAttachmentId,
} from "../attachmentStore.ts";
import * as ServerConfig from "../config.ts";
-import {
- attachmentIsPendingUpload,
- claimPendingAttachments,
- releaseClaimedAttachments,
-} from "./AttachmentClaims.ts";
+import { attachmentIsPendingUpload, claimPendingAttachments } from "./AttachmentClaims.ts";
const layerTest = Layer.mergeAll(NodeServices.layer).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-attachment-claims-" })),
@@ -104,40 +100,6 @@ describe("AttachmentClaims", () => {
}).pipe(Effect.provide(layerTest)),
);
- it.effect("passes already-claimed attachments through untouched", () =>
- Effect.gen(function* () {
- const stored: ChatAttachment = {
- type: "image",
- id: ChatAttachmentId.make("thread-claims-2-00000000-0000-4000-8000-000000000001"),
- name: "existing.png",
- mimeType: "image/png",
- sizeBytes: 4,
- };
- const claimed = yield* claimPendingAttachments({
- threadId: "thread-claims-2",
- attachments: [stored],
- });
- expect(claimed.attachments[0]).toBe(stored);
- expect(claimed.claimedPaths).toHaveLength(0);
- }).pipe(Effect.provide(layerTest)),
- );
-
- it.effect("rejects a pending ref whose staged file is missing", () =>
- Effect.gen(function* () {
- const missing: ChatAttachment = {
- type: "image",
- id: ChatAttachmentId.make(createPendingAttachmentId()!),
- name: "gone.png",
- mimeType: "image/png",
- sizeBytes: 4,
- };
- const result = yield* Effect.exit(
- claimPendingAttachments({ threadId: "thread-claims-3", attachments: [missing] }),
- );
- expect(result._tag).toBe("Failure");
- }).pipe(Effect.provide(layerTest)),
- );
-
it.effect("rejects a size mismatch and cleans up earlier claims from the batch", () =>
Effect.gen(function* () {
const good = yield* stagePendingUpload({
@@ -250,22 +212,4 @@ describe("AttachmentClaims", () => {
).toHaveLength(1);
}).pipe(Effect.provide(layerTest)),
);
-
- it.effect("releaseClaimedAttachments removes claimed copies best-effort", () =>
- Effect.gen(function* () {
- const pending = yield* stagePendingUpload({
- name: "release.png",
- bytes: new Uint8Array([9, 9]),
- mimeType: "image/png",
- });
- const claimed = yield* claimPendingAttachments({
- threadId: "thread-claims-5",
- attachments: [pending],
- });
- expect(NodeFS.existsSync(claimed.claimedPaths[0]!)).toBe(true);
- yield* releaseClaimedAttachments(claimed.claimedPaths);
- expect(NodeFS.existsSync(claimed.claimedPaths[0]!)).toBe(false);
- yield* releaseClaimedAttachments(claimed.claimedPaths);
- }).pipe(Effect.provide(layerTest)),
- );
});
diff --git a/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts b/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts
index 76c090fca88..e59ad3da7cd 100644
--- a/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts
+++ b/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts
@@ -47,12 +47,7 @@ const stopEarlierBackgroundWork = ({
readonly stopWithQueue?: "thread.stop" | "run.interrupt";
readonly olderStart?: boolean;
readonly workflowMember?: boolean;
- readonly stalledRun?:
- | "missing-session"
- | "missing-session-terminal"
- | "returned-interrupt"
- | "returned-interrupt-terminal"
- | "superseded-attempt";
+ readonly stalledRun?: "missing-session-terminal" | "returned-interrupt" | "superseded-attempt";
}) =>
Effect.scoped(
Effect.gen(function* () {
@@ -235,7 +230,7 @@ const stopEarlierBackgroundWork = ({
const run = before.runs[0]!;
const node = before.nodes.find((candidate) => candidate.id === run.rootNodeId)!;
const attempt = before.attempts[0]!;
- if (stalledRun === "missing-session" || stalledRun === "missing-session-terminal") {
+ if (stalledRun === "missing-session-terminal") {
const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
const failed = yield* watch(
(event) => event.type === "run.updated" && event.payload.status === "failed",
@@ -1017,12 +1012,7 @@ it.effect.each(["thread.stop", "run.interrupt"] as const)(
(stopType) => stopEarlierBackgroundWork({ stopWithQueue: stopType, olderStart: true }),
);
-it.effect.each([
- "missing-session",
- "missing-session-terminal",
- "returned-interrupt",
- "returned-interrupt-terminal",
- "superseded-attempt",
-] as const)("Stop recovers a stalled run after %s without changing a newer attempt", (stalledRun) =>
- stopEarlierBackgroundWork({ stalledRun }),
+it.effect.each(["missing-session-terminal", "returned-interrupt", "superseded-attempt"] as const)(
+ "Stop recovers a stalled run after %s without changing a newer attempt",
+ (stalledRun) => stopEarlierBackgroundWork({ stalledRun }),
);
diff --git a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts
index 640d5ce2b94..dfbcd7aa227 100644
--- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts
+++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts
@@ -14,7 +14,6 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
-import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
import * as ServerConfig from "../config.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
@@ -32,14 +31,8 @@ import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
it.effect.each([
"nested",
"ancestor",
- "archived-nested",
- ...(symlinksSupported ? (["aliased-nested"] as const) : []),
- "project",
"provider",
- "scope",
"sibling",
- "stopped-provider",
- "errored-provider",
"shared-provider",
"conversation",
] as const)("preserves overlapping workspace files, owner=%s", (owner) =>
@@ -54,8 +47,6 @@ it.effect.each([
yield* fs.makeDirectory(sibling);
const otherFile = path.join(nested, "other-thread.txt");
yield* fs.writeFileString(otherFile, "other thread's uncommitted work");
- const alias = path.join(parent, "alias");
- if (owner === "aliased-nested") yield* fs.symlink(nested, alias);
const threadId = ThreadId.make("restore-current");
const otherId = ThreadId.make("restore-other");
const projectId = ProjectId.make("restore-project");
@@ -75,15 +66,11 @@ it.effect.each([
projectId,
deletedAt: null,
worktreePath:
- owner === "project"
- ? null
- : owner === "ancestor" || owner === "conversation"
- ? parent
- : owner === "nested" || owner === "archived-nested"
- ? nested
- : owner === "aliased-nested"
- ? alias
- : sibling,
+ owner === "ancestor" || owner === "conversation"
+ ? parent
+ : owner === "nested"
+ ? nested
+ : sibling,
};
const projection = {
thread: {
@@ -123,42 +110,34 @@ it.effect.each([
Effect.succeed({
schemaVersion: 1,
snapshotSequence: 0,
- threads: owner === "archived-nested" ? [] : ([otherThread] as never),
- archivedThreads: owner === "archived-nested" ? ([otherThread] as never) : [],
+ threads: [otherThread] as never,
+ archivedThreads: [],
}),
getCheckpointContext: () =>
Effect.succeed({
runs: [],
checkpoints: [],
- checkpointScopes: owner === "scope" ? ([{ cwd: nested }] as never) : [],
+ checkpointScopes: [],
}),
getThreadProviderContext: () =>
Effect.succeed({
thread: otherThread as never,
providerThreads: [],
- providerSessions: [
- "provider",
- "stopped-provider",
- "errored-provider",
- "shared-provider",
- ].includes(owner)
- ? ([
- {
- cwd: owner === "shared-provider" ? cwd : nested,
- status:
- owner === "provider" || owner === "shared-provider"
- ? "running"
- : owner === "errored-provider"
- ? "error"
- : "stopped",
- capabilities: {
- sessions: {
- supportsMultipleProviderThreadsPerSession: owner === "shared-provider",
+ providerSessions:
+ owner === "provider" || owner === "shared-provider"
+ ? ([
+ {
+ cwd: owner === "shared-provider" ? cwd : nested,
+ status: "running",
+ capabilities: {
+ sessions: {
+ supportsMultipleProviderThreadsPerSession:
+ owner === "shared-provider",
+ },
},
},
- },
- ] as never)
- : [],
+ ] as never)
+ : [],
}),
}),
Layer.mock(CheckpointServiceV2)({
@@ -187,9 +166,7 @@ it.effect.each([
Effect.provide(layerTest),
);
const restoreFiles = owner !== "conversation";
- const rejected = !["sibling", "stopped-provider", "shared-provider", "conversation"].includes(
- owner,
- );
+ const rejected = !["sibling", "shared-provider", "conversation"].includes(owner);
if (rejected) {
const error = yield* service
.execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles })
diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts
index 85db65f5e86..149c82452b6 100644
--- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts
+++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts
@@ -170,162 +170,8 @@ it.effect.each(["initial", "waiting"])(
},
);
-it.effect("rejects a rollback when another provider thread became active", () => {
- const threadId = ThreadId.make("thread:rollback-inactive-provider-thread");
- const requestedProviderThreadId = ProviderThreadId.make(
- "provider-thread:rollback-inactive-provider-thread:requested",
- );
- const activeProviderThreadId = ProviderThreadId.make(
- "provider-thread:rollback-inactive-provider-thread:active",
- );
- const providerSessionId = ProviderSessionId.make(
- "provider-session:rollback-inactive-provider-thread",
- );
- const checkpointId = CheckpointId.make("checkpoint:rollback-inactive-provider-thread");
- const scopeId = CheckpointScopeId.make("checkpoint-scope:rollback-inactive-provider-thread");
- const providerInstanceId = ProviderInstanceId.make("provider_rollback_inactive_provider_thread");
- const restore = vi.fn(() => Effect.die("checkpoint restore must not run"));
- const open = vi.fn(() => Effect.die("provider session open must not run"));
- const resolveRuntimePolicy = vi.fn(() => Effect.die("runtime policy resolution must not run"));
- const projection = {
- thread: {
- worktreePath: null,
- activeProviderThreadId,
- modelSelection: { instanceId: providerInstanceId, model: "test-model" },
- },
- providerThread: {
- id: requestedProviderThreadId,
- providerSessionId,
- providerInstanceId,
- },
- checkpoint: { id: checkpointId, scopeId, status: "ready" },
- scope: { id: scopeId, cwd: process.cwd() },
- } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
- const layerTest = layerCheckpointRollbackService.pipe(
- Layer.provide(
- Layer.mergeAll(
- ThreadCommandExecutor.layer,
- Layer.mock(CheckpointService.CheckpointServiceV2)({ restore }),
- Layer.mock(EventSink.EventSinkV2)({}),
- IdAllocator.layer,
- Layer.mock(ProjectionStore.ProjectionStoreV2)({
- getThread: () => Effect.succeed(projection.thread),
- getCheckpointRollbackContext: () => Effect.succeed(projection),
- getShellSnapshot: () =>
- Effect.succeed({
- schemaVersion: 1,
- snapshotSequence: 0,
- threads: [],
- archivedThreads: [],
- }),
- }),
- Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open }),
- Layer.mock(RuntimePolicy.RuntimePolicyV2)({ resolve: resolveRuntimePolicy }),
- ),
- ),
- );
-
- return Effect.gen(function* () {
- const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2;
- const error = yield* service
- .execute({
- threadId,
- providerThreadId: requestedProviderThreadId,
- checkpointId,
- scopeId,
- })
- .pipe(Effect.flip);
-
- assert.equal(error.reason, "active-provider-changed");
- assert.equal(
- error.message,
- `Active provider changed before rollback target ${checkpointId} could execute on thread ${threadId}.`,
- );
- assert.equal(error.cause, undefined);
- assert.equal(resolveRuntimePolicy.mock.calls.length, 0);
- assert.equal(open.mock.calls.length, 0);
- assert.equal(restore.mock.calls.length, 0);
- }).pipe(Effect.provide(layerTest));
-});
-
-it.effect("rejects an unavailable rollback target before opening a session", () => {
- const threadId = ThreadId.make("thread:rollback-provider-turn-unavailable");
- const providerThreadId = ProviderThreadId.make(
- "provider-thread:rollback-provider-turn-unavailable",
- );
- const providerSessionId = ProviderSessionId.make(
- "provider-session:rollback-provider-turn-unavailable",
- );
- const checkpointId = CheckpointId.make("checkpoint:rollback-provider-turn-unavailable");
- const scopeId = CheckpointScopeId.make("checkpoint-scope:rollback-provider-turn-unavailable");
- const providerInstanceId = ProviderInstanceId.make("provider_rollback_provider_turn_unavailable");
- const restore = vi.fn(() => Effect.die("checkpoint restore must not run"));
- const open = vi.fn(() => Effect.die("provider session open must not run"));
- const projection = {
- thread: {
- worktreePath: "/tmp/missing-invalid-rollback-worktree",
- branch: "feature/rollback",
- activeProviderThreadId: providerThreadId,
- modelSelection: { instanceId: providerInstanceId, model: "test-model" },
- },
- providerThread: { id: providerThreadId, providerSessionId, providerInstanceId },
- providerSession: undefined,
- checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: 1 },
- scope: { id: scopeId, cwd: process.cwd() },
- runsToRollback: [],
- targetAttempt: undefined,
- rolledBackAttemptIds: [],
- staleCheckpoints: [],
- providerTurns: [],
- } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
- const layerTest = layerCheckpointRollbackService.pipe(
- Layer.provide(
- Layer.mergeAll(
- ThreadCommandExecutor.layer,
- Layer.mock(CheckpointService.CheckpointServiceV2)({ restore }),
- Layer.mock(EventSink.EventSinkV2)({}),
- IdAllocator.layer,
- Layer.mock(ProjectionStore.ProjectionStoreV2)({
- getThread: () => Effect.succeed(projection.thread),
- getCheckpointRollbackContext: () => Effect.succeed(projection),
- getShellSnapshot: () =>
- Effect.succeed({
- schemaVersion: 1,
- snapshotSequence: 0,
- threads: [],
- archivedThreads: [],
- }),
- }),
- Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
- open,
- }),
- Layer.mock(RuntimePolicy.RuntimePolicyV2)({
- resolve: () => Effect.succeed({} as never),
- }),
- ),
- ),
- );
-
- return Effect.gen(function* () {
- const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2;
- const error = yield* service
- .execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles: false })
- .pipe(Effect.flip);
- assert.equal(open.mock.calls.length, 0);
- assert.equal(error.reason, "provider-turn-unavailable");
- assert.equal(
- error.message,
- `Provider turn for rollback target ${checkpointId} is unavailable on provider thread ${providerThreadId}.`,
- );
- assert.equal(error.cause, undefined);
- assert.equal(restore.mock.calls.length, 0);
- }).pipe(Effect.provide(layerTest));
-});
-
it.effect.each([
- { order: "normal", restoreFiles: true },
{ order: "cleanup-first", restoreFiles: true },
- { order: "cleanup-first", restoreFiles: false },
{ order: "rollback-first", restoreFiles: true },
// A path the server would not have made is left missing, not recreated.
{ order: "cleanup-first", restoreFiles: false, unmanaged: true },
@@ -495,9 +341,7 @@ it.effect.each([
calls,
order === "cleanup-first"
? ["cleanup", "prune", "create", ...rollbackCalls]
- : order === "rollback-first"
- ? [...rollbackCalls, "cleanup"]
- : rollbackCalls,
+ : [...rollbackCalls, "cleanup"],
);
}).pipe(Effect.provide(testLayer));
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
diff --git a/apps/server/src/orchestration-v2/CheckpointService.test.ts b/apps/server/src/orchestration-v2/CheckpointService.test.ts
index 7c0c83b6a72..39643ff38cf 100644
--- a/apps/server/src/orchestration-v2/CheckpointService.test.ts
+++ b/apps/server/src/orchestration-v2/CheckpointService.test.ts
@@ -1,5 +1,5 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
-import { assert, it, vi } from "@effect/vitest";
+import { assert, it } from "@effect/vitest";
import {
CheckpointScopeId,
NodeId,
@@ -12,99 +12,12 @@ import {
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
-import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
import * as CheckpointService from "./CheckpointService.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
-it.effect.each([false, true, "interrupt"] as const)(
- "materializes baseline, lookup fails=%s",
- (lookupFails) => {
- const scope: OrchestrationV2CheckpointScope = {
- id: CheckpointScopeId.make("checkpoint-scope:materialize-baseline"),
- threadId: ThreadId.make("thread:materialize-baseline"),
- runId: RunId.make("run:materialize-baseline:3"),
- nodeId: NodeId.make("node:materialize-baseline:3"),
- parentScopeId: null,
- providerThreadId: ProviderThreadId.make("provider-thread:materialize-baseline"),
- kind: "root_run",
- ordinalWithinParent: 0,
- advancesAppRunCount: true,
- cwd: "/repo",
- createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"),
- };
- const hasCheckpointRef = vi.fn((_input: CheckpointStore.RestoreCheckpointInput) =>
- lookupFails === "interrupt"
- ? Effect.interrupt
- : lookupFails
- ? Effect.fail(
- new VcsProcessTimeoutError({
- operation: "test.ref",
- command: "git",
- cwd: "/repo",
- timeoutMs: 30000,
- }),
- )
- : Effect.succeed(true),
- );
- const layerTest = CheckpointService.layer.pipe(
- Layer.provide(
- Layer.mergeAll(
- IdAllocator.layer,
- Layer.mock(CheckpointStore.CheckpointStore)({
- isGitRepository: () => Effect.succeed(true),
- hasCheckpointRef,
- captureCheckpoint: () => Effect.void,
- }),
- ),
- ),
- Layer.provideMerge(NodeCrypto.layer),
- );
-
- return Effect.gen(function* () {
- const checkpoints = yield* CheckpointService.CheckpointServiceV2;
- if (lookupFails === "interrupt") {
- const exit = yield* Effect.exit(
- checkpoints.materializeBaselineCheckpoint({ scope, ordinalWithinScope: 2 }),
- );
- assert.isTrue(Exit.hasInterrupts(exit));
- const captureExit = yield* Effect.exit(
- checkpoints.capture({
- scope,
- ordinalWithinScope: 1,
- runId: scope.runId!,
- nodeId: scope.nodeId!,
- appRunOrdinal: 1,
- capturedAt: scope.createdAt,
- }),
- );
- assert.isTrue(Exit.hasInterrupts(captureExit));
- return;
- }
- const baseline = yield* checkpoints.materializeBaselineCheckpoint({
- scope,
- ordinalWithinScope: 2,
- });
-
- assert.equal(baseline.ordinalWithinScope, 2);
- assert.equal(
- baseline.ref,
- yield* CheckpointService.checkpointRefForScopeOrdinal({
- scopeId: scope.id,
- ordinalWithinScope: 2,
- }),
- );
- assert.equal(baseline.status, lookupFails ? "missing" : "ready");
- assert.deepEqual(hasCheckpointRef.mock.calls[0]?.[0], {
- cwd: scope.cwd,
- checkpointRef: baseline.ref,
- });
- }).pipe(Effect.provide(layerTest));
- },
-);
-
it.effect(
"skips unsupported baseline and turn checkpoints without swallowing capture failures",
() =>
diff --git a/apps/server/src/orchestration-v2/CommandPolicy.test.ts b/apps/server/src/orchestration-v2/CommandPolicy.test.ts
index a2f7cb8f703..1bf294641a0 100644
--- a/apps/server/src/orchestration-v2/CommandPolicy.test.ts
+++ b/apps/server/src/orchestration-v2/CommandPolicy.test.ts
@@ -200,222 +200,6 @@ it.each(["/compact", " /LOGOUT "])("queues a steer sent while %s runs", (text) =
const layer = it.layer(CommandPolicy.layer);
layer("CommandPolicyV2", (it) => {
- it.effect("reports the actually missing capability across the steering matrix", () =>
- Effect.gen(function* () {
- const policy = yield* CommandPolicy.CommandPolicyV2;
- const providerInstanceId = ProviderInstanceId.make("codex");
- const fallbackDetail =
- "providerInstanceId cannot steer active turns directly or by interrupt-and-restart";
- const forcedRestartDetail =
- "providerInstanceId cannot satisfy a required interrupt-and-restart";
-
- const cases: ReadonlyArray<{
- readonly forceRestart: boolean;
- readonly supportsActiveSteering: boolean;
- readonly supportsInterrupt: boolean;
- readonly supportsSteeringByInterruptRestart: boolean;
- readonly expected:
- | { readonly type: "policy"; readonly value: CommandPolicy.SteeringExecutionPolicyV2 }
- | {
- readonly type: "error";
- readonly capability: CommandPolicy.CommandPolicyCapability;
- readonly detail: string;
- };
- }> = [
- {
- forceRestart: false,
- supportsActiveSteering: true,
- supportsInterrupt: false,
- supportsSteeringByInterruptRestart: false,
- expected: { type: "policy", value: "active_steering" },
- },
- {
- forceRestart: false,
- supportsActiveSteering: true,
- supportsInterrupt: false,
- supportsSteeringByInterruptRestart: true,
- expected: { type: "policy", value: "active_steering" },
- },
- {
- forceRestart: false,
- supportsActiveSteering: true,
- supportsInterrupt: true,
- supportsSteeringByInterruptRestart: false,
- expected: { type: "policy", value: "active_steering" },
- },
- {
- forceRestart: false,
- supportsActiveSteering: true,
- supportsInterrupt: true,
- supportsSteeringByInterruptRestart: true,
- expected: { type: "policy", value: "active_steering" },
- },
- {
- forceRestart: false,
- supportsActiveSteering: false,
- supportsInterrupt: true,
- supportsSteeringByInterruptRestart: true,
- expected: { type: "policy", value: "interrupt_restart" },
- },
- {
- forceRestart: false,
- supportsActiveSteering: false,
- supportsInterrupt: true,
- supportsSteeringByInterruptRestart: false,
- expected: {
- type: "error",
- capability: "interrupt_restart_steering",
- detail: fallbackDetail,
- },
- },
- {
- forceRestart: false,
- supportsActiveSteering: false,
- supportsInterrupt: false,
- supportsSteeringByInterruptRestart: true,
- expected: { type: "error", capability: "active_steering", detail: fallbackDetail },
- },
- {
- forceRestart: false,
- supportsActiveSteering: false,
- supportsInterrupt: false,
- supportsSteeringByInterruptRestart: false,
- expected: { type: "error", capability: "active_steering", detail: fallbackDetail },
- },
- {
- forceRestart: true,
- supportsActiveSteering: true,
- supportsInterrupt: true,
- supportsSteeringByInterruptRestart: true,
- expected: { type: "policy", value: "interrupt_restart" },
- },
- {
- forceRestart: true,
- supportsActiveSteering: false,
- supportsInterrupt: true,
- supportsSteeringByInterruptRestart: true,
- expected: { type: "policy", value: "interrupt_restart" },
- },
- {
- forceRestart: true,
- supportsActiveSteering: true,
- supportsInterrupt: true,
- supportsSteeringByInterruptRestart: false,
- expected: {
- type: "error",
- capability: "interrupt_restart_steering",
- detail: forcedRestartDetail,
- },
- },
- {
- forceRestart: true,
- supportsActiveSteering: false,
- supportsInterrupt: true,
- supportsSteeringByInterruptRestart: false,
- expected: {
- type: "error",
- capability: "interrupt_restart_steering",
- detail: forcedRestartDetail,
- },
- },
- {
- forceRestart: true,
- supportsActiveSteering: true,
- supportsInterrupt: false,
- supportsSteeringByInterruptRestart: true,
- expected: {
- type: "error",
- capability: "interrupt_restart_steering",
- detail: forcedRestartDetail,
- },
- },
- {
- forceRestart: true,
- supportsActiveSteering: false,
- supportsInterrupt: false,
- supportsSteeringByInterruptRestart: true,
- expected: {
- type: "error",
- capability: "interrupt_restart_steering",
- detail: forcedRestartDetail,
- },
- },
- {
- forceRestart: true,
- supportsActiveSteering: true,
- supportsInterrupt: false,
- supportsSteeringByInterruptRestart: false,
- expected: {
- type: "error",
- capability: "interrupt_restart_steering",
- detail: forcedRestartDetail,
- },
- },
- {
- forceRestart: true,
- supportsActiveSteering: false,
- supportsInterrupt: false,
- supportsSteeringByInterruptRestart: false,
- expected: {
- type: "error",
- capability: "interrupt_restart_steering",
- detail: forcedRestartDetail,
- },
- },
- ];
-
- for (const entry of cases) {
- const decision = policy.decideSteeringExecution({
- commandId,
- threadId,
- providerInstanceId,
- forceRestart: entry.forceRestart,
- capabilities: capabilities((current) => ({
- ...current,
- turns: {
- ...current.turns,
- supportsActiveSteering: entry.supportsActiveSteering,
- supportsInterrupt: entry.supportsInterrupt,
- supportsSteeringByInterruptRestart: entry.supportsSteeringByInterruptRestart,
- },
- })),
- });
-
- if (entry.expected.type === "policy") {
- assert.equal(yield* decision, entry.expected.value);
- continue;
- }
-
- const error = yield* decision.pipe(Effect.flip);
- assert.instanceOf(error, CommandPolicy.CommandPolicyCapabilityUnsupportedError);
- assert.equal(error.commandId, commandId);
- assert.equal(error.threadId, threadId);
- assert.equal(error.providerInstanceId, providerInstanceId);
- assert.equal(error.capability, entry.expected.capability);
- assert.equal(error.detail, entry.expected.detail);
- }
- }),
- );
-
- it.effect("uses a native fork when the provider supports the requested source point", () =>
- Effect.gen(function* () {
- const policy = yield* CommandPolicy.CommandPolicyV2;
-
- const result = yield* policy.decideForkExecution({
- commandId,
- threadId,
- providerInstanceId: ProviderInstanceId.make("codex"),
- capabilities: CodexProviderCapabilitiesV2,
- sameProvider: true,
- hasStrongNativeSource: true,
- sourceRunStatus: "completed",
- fromSpecificTurn: true,
- });
-
- assert.equal(result, "native_fork");
- }),
- );
-
it.effect("falls back to portable context when Cursor cannot fork natively", () =>
Effect.gen(function* () {
const policy = yield* CommandPolicy.CommandPolicyV2;
@@ -434,36 +218,4 @@ layer("CommandPolicyV2", (it) => {
assert.equal(result, "portable_context");
}),
);
-
- it.effect("returns a typed error when neither native nor portable fork is available", () =>
- Effect.gen(function* () {
- const policy = yield* CommandPolicy.CommandPolicyV2;
-
- const error = yield* policy
- .decideForkExecution({
- commandId,
- threadId,
- providerInstanceId: ProviderInstanceId.make("cursor"),
- capabilities: capabilities((current) => ({
- ...current,
- threads: {
- ...current.threads,
- canForkThread: false,
- },
- context: {
- ...current.context,
- canConsumeHandoffSummaries: false,
- },
- })),
- sameProvider: true,
- hasStrongNativeSource: true,
- sourceRunStatus: "completed",
- fromSpecificTurn: true,
- })
- .pipe(Effect.flip);
-
- assert.instanceOf(error, CommandPolicy.CommandPolicyCapabilityUnsupportedError);
- assert.equal(error.capability, "context_handoff");
- }),
- );
});
diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.ts
index 6aa7a79499c..671d7902fb4 100644
--- a/apps/server/src/orchestration-v2/EffectWorker.test.ts
+++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts
@@ -475,81 +475,6 @@ it.effect("terminalizes a process-bound claim when success settlement fails", ()
}),
);
-it.effect("keeps a process-bound executor failure retryable when retry settlement fails", () =>
- Effect.gen(function* () {
- const now = DateTime.formatIso(yield* DateTime.now);
- const effectId = "effect:worker-process-bound-retry-settlement-failure";
- const workerId = "worker-process-bound-retry-settlement-failure";
- const claimedEffect: EffectOutbox.OrchestrationEffectV2 = {
- id: effectId,
- commandId: CommandId.make("command:worker-process-bound-retry-settlement-failure"),
- threadId: ThreadId.make("thread:worker-process-bound-retry-settlement-failure"),
- request: {
- type: "provider-turn.start",
- runId: RunId.make("run:worker-process-bound-retry-settlement-failure"),
- },
- status: "running",
- attemptCount: 1,
- availableAt: now,
- leaseOwner: workerId,
- leaseExpiresAt: now,
- createdAt: now,
- updatedAt: now,
- completedAt: null,
- lastError: null,
- };
- const retryAttempts = yield* Ref.make(0);
- const terminalizations = yield* Ref.make(0);
- const layerOutbox = Layer.mock(EffectOutbox.EffectOutboxV2)({
- claimNext: () => Effect.succeed(Option.some(claimedEffect)),
- get: () => Effect.succeed(Option.some(claimedEffect)),
- awaitCancellation: () => Effect.never,
- clearCancellation: () => Effect.void,
- retry: () =>
- Ref.updateAndGet(retryAttempts, (count) => count + 1).pipe(
- Effect.flatMap((attempt) =>
- attempt === 1
- ? Effect.fail(
- new EffectOutbox.EffectOutboxError({
- operation: "retry",
- effectId,
- cause: "simulated retry settlement failure",
- }),
- )
- : Effect.succeed(true),
- ),
- ),
- fail: () => Ref.update(terminalizations, (count) => count + 1).pipe(Effect.as(true)),
- });
- const layerExecutor = Layer.succeed(
- EffectWorker.OrchestrationEffectExecutorV2,
- EffectWorker.OrchestrationEffectExecutorV2.of({
- execute: () =>
- Effect.fail(
- new EffectWorker.OrchestrationEffectExecutionError({
- effectId,
- effectType: claimedEffect.request.type,
- cause: "simulated provider execution failure",
- }),
- ),
- }),
- );
- const layerWorker = EffectWorker.layerWithOptions({ workerId }).pipe(
- Layer.provide(Layer.merge(layerOutbox, layerExecutor)),
- );
-
- const exit = yield* EffectWorker.OrchestrationEffectWorkerV2.pipe(
- Effect.flatMap((worker) => worker.runOnce),
- Effect.provide(layerWorker),
- Effect.exit,
- );
-
- assert.isTrue(Exit.isFailure(exit));
- assert.equal(yield* Ref.get(retryAttempts), 2);
- assert.equal(yield* Ref.get(terminalizations), 0);
- }),
-);
-
it.effect("settles a delegated child once its restart continuation fails for good", () =>
Effect.gen(function* () {
const timestamp = DateTime.formatIso(yield* DateTime.now);
diff --git a/apps/server/src/orchestration-v2/LiveStreamBudget.test.ts b/apps/server/src/orchestration-v2/LiveStreamBudget.test.ts
index d3980d946af..be612837c6e 100644
--- a/apps/server/src/orchestration-v2/LiveStreamBudget.test.ts
+++ b/apps/server/src/orchestration-v2/LiveStreamBudget.test.ts
@@ -8,7 +8,6 @@ import * as Stream from "effect/Stream";
import { describe, expect } from "vite-plus/test";
import {
- bufferLiveStream,
bufferLatestLiveStream,
makeLiveStreamBudget,
replayAndBufferLiveEvents,
@@ -133,42 +132,6 @@ describe("replayAndBufferLiveEvents", () => {
),
);
- it.effect.each(["items", "bytes"] as const)(
- "counts an unacknowledged replay batch toward the live %s limit",
- (limit) =>
- Effect.scoped(
- Effect.gen(function* () {
- const pubsub = yield* PubSub.unbounded<Event>();
- const subscribed = yield* Deferred.make<PubSub.Subscription<Event>>();
- const replayed = { sequence: 1, text: "replay" };
- const live = { sequence: 2, text: "live" };
- const pull = yield* Stream.toPull(
- replayAndBufferLiveEvents(
- {
- subscribe: PubSub.subscribe(pubsub).pipe(
- Effect.tap((subscription) => Deferred.succeed(subscribed, subscription)),
- ),
- latestSequence: Effect.succeed(1),
- replay: () => Stream.succeed(replayed),
- },
- limit === "items"
- ? { maxItems: 1 }
- : {
- maxSerializedBytes: 40,
- },
- ),
- );
- expect(yield* pull).toEqual([replayed]);
- yield* PubSub.publish(pubsub, live);
- yield* (yield* Deferred.await(subscribed)).shutdownHook.await;
- expect(yield* PubSub.size(pubsub)).toBe(0);
- const result = yield* pull.pipe(Effect.result);
- expect(result._tag).toBe("Failure");
- if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
- }),
- ),
- );
-
it.effect("lets a fast reader replay a database page larger than both buffer limits", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -229,57 +192,4 @@ describe("replayAndBufferLiveEvents", () => {
}),
),
);
-
- it.effect(
- "caps raw and projected stages while projection and client acknowledgement are blocked",
- () =>
- Effect.scoped(
- Effect.gen(function* () {
- const pubsub = yield* PubSub.unbounded<Event>();
- const subscribed = yield* Deferred.make<PubSub.Subscription<Event>>();
- const projectionStarted = yield* Deferred.make<void>();
- const projectionClosed = yield* Deferred.make<void>();
- const releaseProjection = yield* Deferred.make<void>();
- const source = replayAndBufferLiveEvents(
- {
- subscribe: PubSub.subscribe(pubsub).pipe(
- Effect.tap((subscription) => Deferred.succeed(subscribed, subscription)),
- ),
- latestSequence: Effect.succeed(0),
- replay: () => Stream.empty,
- },
- { maxItems: 2 },
- ).pipe(
- Stream.mapEffect((event) =>
- event.sequence === 3
- ? Deferred.succeed(projectionStarted, undefined).pipe(
- Effect.andThen(Deferred.await(releaseProjection)),
- Effect.as(event),
- )
- : Effect.succeed(event),
- ),
- Stream.ensuring(Deferred.succeed(projectionClosed, undefined)),
- );
- const pull = yield* Stream.toPull(bufferLiveStream(source, { maxItems: 2 }));
- const firstPull = yield* pull.pipe(Effect.forkScoped);
- const subscription = yield* Deferred.await(subscribed);
- yield* PubSub.publish(pubsub, { sequence: 1, text: "awaiting ACK" });
- expect(yield* Fiber.join(firstPull)).toEqual([{ sequence: 1, text: "awaiting ACK" }]);
- yield* PubSub.publish(pubsub, { sequence: 2, text: "projected tail" });
- yield* PubSub.publish(pubsub, { sequence: 3, text: "projecting" });
- yield* Deferred.await(projectionStarted);
- yield* PubSub.publishAll(pubsub, [
- { sequence: 4, text: "raw tail" },
- { sequence: 5, text: "overflow" },
- ]);
- yield* subscription.shutdownHook.await;
- expect(yield* PubSub.size(pubsub)).toBe(0);
- yield* Deferred.succeed(releaseProjection, undefined);
- yield* Deferred.await(projectionClosed);
- const result = yield* pull.pipe(Effect.result);
- expect(result._tag).toBe("Failure");
- if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
- }),
- ),
- );
});
diff --git a/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts b/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts
index 27380086828..187c25935a0 100644
--- a/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts
+++ b/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts
@@ -112,19 +112,6 @@ const agentList = (directory: string) => ({
],
});
-const noOpenRequests: ReadonlyArray<ProviderReplayEntry> = [
- out("permission.list", { sessionID: SESSION }),
- reply("permission.list", { data: [] }),
- out("session.form.list", { sessionID: SESSION }),
- reply("session.form.list", { data: [] }),
-];
-const supervisedRules = (name: string) => [
- { action: "shell", resource: "*", effect: "ask" },
- { action: "edit", resource: "*", effect: "ask" },
- { action: "external_directory", resource: "*", effect: "ask" },
- ...BUILD_PATHS,
- ...mcpRules(name),
-];
const autoEditRules = (name: string) => [
{ action: "shell", resource: "*", effect: "ask" },
{ action: "edit", resource: "*", effect: "allow" },
@@ -180,16 +167,6 @@ const answeredPrompt = (text: string): ReadonlyArray<ProviderReplayEntry> => [
event("session.execution.succeeded", { sessionID: SESSION }),
];
-const directoryModels = (directory: string): ReadonlyArray<ProviderReplayEntry> => [
- out("model.list", { "location[directory]": directory }),
- reply("model.list", {
- location: { directory },
- data: [
- catalogModel("big-pickle", "Big Pickle"),
- catalogModel("mimo-v2.6-flash-free", "MiMo V2.6 Flash Free"),
- ],
- }),
-];
/** A `/api/model` entry as 2.0.18 lists it; a known window means no re-read after a turn. */
const catalogModel = (id: string, name: string) => ({
id,
@@ -375,88 +352,6 @@ describe("OpenCode 2 through the orchestrator", () => {
}).pipe(Effect.scoped),
);
- it.effect("gives a session made with older rules T3's rules before its next prompt", () =>
- Effect.gen(function* () {
- const name = "opencode2-resume-rules";
- const before = yield* checkpointWorkspace(`${name}-before`);
- const after = yield* checkpointWorkspace(`${name}-after`);
- const thread = threadCommands({ name, worktreePath: before });
- const projection = yield* runScenario({
- name,
- threadId: thread.threadId,
- entries: [
- ...createdSession(before, name),
- ...instructionsWritten,
- ...answeredPrompt("FIRST"),
- ...directoryModels(after),
-
- out("session.get", { sessionID: SESSION }),
- reply(
- "session.get",
- sessionInfo(
- before,
- [
- { action: "*", resource: "*", effect: "allow" },
- { action: "subagent", resource: "*", effect: "deny" },
- ],
- name,
- ),
- ),
- ...noOpenRequests,
- out("session.update", { sessionID: SESSION, permissions: t3Rules(name) }),
- reply("session.update", null),
- out("session.move", { sessionID: SESSION, directory: after }),
- reply("session.move", null),
- ...instructionsWritten,
- ...answeredPrompt("SECOND"),
- ],
- commands: [
- thread.create,
- thread.message("first"),
- {
- type: "thread.metadata.update",
- commandId: thread.command("worktree"),
- threadId: thread.threadId,
- worktreePath: after,
- },
- thread.message("second"),
- ],
- });
- assert.deepEqual(
- projection.runs.map((run) => run.status),
- ["completed", "completed"],
- );
- }).pipe(Effect.scoped),
- );
-
- it.effect(
- "creates a Supervised thread's session with rules that ask before shell and edits",
- () =>
- Effect.gen(function* () {
- const name = "opencode2-supervised-rules";
- const cwd = yield* checkpointWorkspace(name);
- const thread = threadCommands({
- name,
- worktreePath: cwd,
- runtimeMode: "approval-required",
- });
- const projection = yield* runScenario({
- name,
- threadId: thread.threadId,
- entries: [
- ...createdSession(cwd, name, supervisedRules(name), true),
- ...instructionsWritten,
- ...answeredPrompt("FIRST"),
- ],
- commands: [thread.create, thread.message("first")],
- });
- assert.deepEqual(
- projection.runs.map((run) => run.status),
- ["completed"],
- );
- }).pipe(Effect.scoped),
- );
-
it.effect("rewrites the session's rules when the thread's mode changes between turns", () =>
Effect.gen(function* () {
const name = "opencode2-mode-change";
diff --git a/apps/server/src/orchestration-v2/ProjectCommands.test.ts b/apps/server/src/orchestration-v2/ProjectCommands.test.ts
index 49cd0024341..608c8b0ddad 100644
--- a/apps/server/src/orchestration-v2/ProjectCommands.test.ts
+++ b/apps/server/src/orchestration-v2/ProjectCommands.test.ts
@@ -45,22 +45,6 @@ const plan = (command: ProjectCommand, state: Partial<ProjectCommandState> = {})
now,
});
-const update = (
- fields: Omit<
- Extract<ProjectCommand, { type: "project.meta.update" }>,
- "type" | "commandId" | "projectId"
- >,
-) =>
- plan(
- {
- type: "project.meta.update",
- commandId: CommandId.make("cmd-update"),
- projectId,
- ...fields,
- },
- { project: row() },
- );
-
const payloadOf = (result: ReturnType<typeof plan>) => {
assert.isTrue(Result.isSuccess(result));
return Result.getOrThrow(result).payload as Record<string, unknown>;
@@ -72,29 +56,6 @@ const failureOf = (result: ReturnType<typeof plan>) => {
};
describe("planProjectCommand", () => {
- it("carries every edited field and omits the rest", () => {
- const scripts = [script("lint")];
- const payload = payloadOf(
- update({
- scripts,
- defaultThreadEnvMode: "worktree",
- autoPull: true,
- faviconPath: "brand/icon.svg",
- projectIcon: { kind: "lucide", name: "alarm-clock", color: "violet" },
- }),
- );
- assert.deepInclude(payload, {
- scripts,
- defaultThreadEnvMode: "worktree",
- autoPull: true,
- faviconPath: "brand/icon.svg",
- projectIcon: { kind: "lucide", name: "alarm-clock", color: "violet" },
- });
- const renamed = payloadOf(update({ title: "Renamed" }));
- assert.isFalse("defaultThreadEnvMode" in renamed);
- assert.isNull(payloadOf(update({ defaultThreadEnvMode: null })).defaultThreadEnvMode);
- });
-
it("keeps legacy scripts editable and removable while rejecting new invalid ones", () => {
const legacy = script("install-javascript-dependencies");
const withLegacy = (scripts: ReadonlyArray<ProjectScript>) =>
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
index a8761dc8abe..83f33269f39 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
@@ -1106,6 +1106,7 @@ const assertProjectScopedShells = Effect.fn("assertProjectScopedShells")(functio
});
it.layer(layerTest)("ProjectionStoreV2", (it) => {
+ // regression: #21969 keep corrupt plan JSON in the typed read error
it.effect("returns a typed read error for malformed stored plan JSON", () =>
Effect.gen(function* () {
const store = yield* ProjectionStore.ProjectionStoreV2;
@@ -2275,6 +2276,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
}),
);
+ // regression: #17141 shell snapshot decoding blocked other database reads
it.effect("reads the shell snapshot first and decodes it in a separate step", () =>
Effect.gen(function* () {
const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index ba10d09b804..89731e10f2a 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -680,7 +680,7 @@ function upsertById<T extends { readonly id: string }>(items: ReadonlyArray<T>,
return updated;
}
-export function upsertProviderTurn(
+function upsertProviderTurn(
turns: ReadonlyArray<OrchestrationV2ProviderTurn>,
next: OrchestrationV2ProviderTurn,
): Array<OrchestrationV2ProviderTurn> {
diff --git a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts
index 9cfdac9dfc6..b9ce054de8f 100644
--- a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts
@@ -121,31 +121,6 @@ const trackedCreate = <A, E, R>(
return yield* effect;
});
-it.effect("closes a partially-created adapter scope immediately on typed failure", () =>
- Effect.gen(function* () {
- const releases = yield* Ref.make(0);
- const createError = new ProviderAdapterDriverCreateError({
- driver: lifecycleDriver,
- instanceId: lifecycleInstanceId,
- detail: "expected test failure",
- });
-
- yield* Effect.scoped(
- Effect.gen(function* () {
- const exit = yield* ProviderAdapterRegistry.makeRegistryFromConfigMap({
- drivers: [makeLifecycleDriver(trackedCreate(releases, Effect.fail(createError)))],
- configMap: lifecycleConfigMap,
- }).pipe(Effect.exit);
-
- assert.isTrue(Exit.isFailure(exit));
- assert.strictEqual(yield* Ref.get(releases), 1);
- }),
- );
-
- assert.strictEqual(yield* Ref.get(releases), 1);
- }),
-);
-
it.effect("closes a partially-created adapter scope immediately on interruption", () =>
Effect.gen(function* () {
const releases = yield* Ref.make(0);
diff --git a/apps/server/src/orchestration-v2/ProviderContinuationService.test.ts b/apps/server/src/orchestration-v2/ProviderContinuationService.test.ts
index a6101db498c..6e2abc0c1d6 100644
--- a/apps/server/src/orchestration-v2/ProviderContinuationService.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderContinuationService.test.ts
@@ -11,7 +11,6 @@ import {
type OrchestrationV2Notification,
} from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
-import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
@@ -157,31 +156,6 @@ describe("ProviderContinuationService", () => {
}),
);
- it.effect("marks an adapter-buffered wake with the provider creation source", () => {
- return Effect.gen(function* () {
- const dispatched = yield* Queue.unbounded<unknown>();
- yield* Effect.gen(function* () {
- const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
- yield* requests.offer(request());
- const command = (yield* Queue.take(dispatched)) as {
- readonly creationSource: string;
- readonly notification: OrchestrationV2Notification;
- };
- assert.equal(command.creationSource, "provider");
- assert.deepEqual(command.notification, {
- source: { kind: "background_task" },
- outcome: "updated",
- summary: "Background activity updated",
- });
- }).pipe(
- Effect.provide(
- layerTest({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
- ),
- Effect.scoped,
- );
- });
- });
-
it.effect("delivers a message_text wake as a real prompt, not a buffered wake", () => {
return Effect.gen(function* () {
const dispatched = yield* Queue.unbounded<unknown>();
@@ -530,47 +504,6 @@ describe("ProviderContinuationService", () => {
});
});
- it.effect("drops archived and deleted delegated completions during recovery", () => {
- return Effect.gen(function* () {
- for (const barrier of ["archivedAt", "deletedAt"] as const) {
- const dispatched = yield* Queue.unbounded<unknown>();
- yield* Effect.gen(function* () {
- const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
- yield* requests.offer({
- threadId,
- providerThreadId,
- driver,
- detail: null,
- delivery: "message_text",
- delegatedCompletion: {
- parentRunId,
- generation: 1,
- messageId: delegatedMessageId,
- },
- });
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
- assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
- }).pipe(
- Effect.provide(
- layerTest({
- dispatched,
- getThreadRecords: () =>
- Effect.succeed({
- ...delegatedProjection(),
- thread: {
- ...projection.thread,
- [barrier]: DateTime.makeUnsafe("2026-08-03T00:00:00.000Z"),
- },
- } as unknown as OrchestrationV2ThreadProjection),
- }),
- ),
- Effect.scoped,
- );
- }
- });
- });
-
it.effect("dispatches a current request exactly once", () => {
return Effect.gen(function* () {
const dispatched = yield* Queue.unbounded<unknown>();
@@ -589,27 +522,6 @@ describe("ProviderContinuationService", () => {
});
});
- it.effect("drops a request invalidated before dispatch", () => {
- return Effect.gen(function* () {
- const dispatched = yield* Queue.unbounded<unknown>();
- yield* Effect.gen(function* () {
- const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
- const guard = yield* makeGuard();
- const dispatchIfCurrent = yield* guard.capture;
- yield* guard.invalidate;
- yield* requests.offer(request(dispatchIfCurrent));
- yield* Effect.yieldNow;
- yield* Effect.yieldNow;
- assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
- }).pipe(
- Effect.provide(
- layerTest({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
- ),
- Effect.scoped,
- );
- });
- });
-
it.effect("drops a request invalidated while projection is blocked", () => {
return Effect.gen(function* () {
const dispatched = yield* Queue.unbounded<unknown>();
diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts
index f2da22c17b9..849cedded92 100644
--- a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts
@@ -963,7 +963,7 @@ layer("ProviderEventIngestorV2", (it) => {
}),
);
- it.effect.each(["completed", "interrupted", "failed", "cancelled", "control"] as const)(
+ it.effect.each(["interrupted", "control"] as const)(
"dismisses only native questions when a provider turn ends with %s",
(terminal) =>
Effect.gen(function* () {
@@ -1777,20 +1777,15 @@ layer("ProviderEventIngestorV2", (it) => {
}),
);
- it.effect.each(["explicit", "detached", "unchanged", "legacy"])(
+ // regression: #20079 the renamed-branch correction must not rewrite a child that needs none
+ it.effect.each(["explicit", "detached"])(
"preserves a native child's branch when the checkout needs no correction: %s",
(scenario) =>
Effect.gen(function* () {
const { worktreePath, command } = yield* makeSharedWorktree;
const git = yield* GitVcsDriver.GitVcsDriver;
- const branch =
- scenario === "explicit"
- ? "child-feature"
- : scenario === "legacy"
- ? "t3-abcd1234"
- : "t3/abcd1234";
- if (scenario === "explicit" || scenario === "legacy")
- yield* command(worktreePath, ["branch", "-m", branch]);
+ const branch = scenario === "explicit" ? "child-feature" : "t3/abcd1234";
+ if (scenario === "explicit") yield* command(worktreePath, ["branch", "-m", branch]);
if (scenario === "detached") yield* command(worktreePath, ["checkout", "--detach"]);
const now = yield* DateTime.now;
const sink = yield* EventSink.EventSinkV2;
diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts
index 87333d4dc91..d0a97adb106 100644
--- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts
@@ -131,67 +131,6 @@ it.effect("preserves async questions across startup and shutdown", () => {
}).pipe(Effect.provide(layer));
});
-it.effect("uses the same reconciliation path to cancel runtime requests during shutdown", () => {
- const threadId = ThreadId.make("thread_shutdown_requests");
- let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
- null;
- const projection = {
- thread: { id: threadId },
- runtimeRequests: [
- {
- id: RuntimeRequestId.make("request_shutdown"),
- nodeId: NodeId.make("node_shutdown"),
- status: "pending",
- responseCapability: { type: "live" },
- },
- ],
- providerSessions: [],
- providerThreads: [],
- runs: [],
- nodes: [],
- } as unknown as OrchestrationV2ThreadProjection;
- const layer = ProviderRuntimeRecovery.layer.pipe(
- Layer.provide(ServerSettings.layerTest()),
- Layer.provide(
- Layer.mergeAll(
- Layer.mock(ProjectionStore.ProjectionStoreV2)({
- getRecoveryThreadIds: () => Effect.succeed([threadId]),
- getRuntimeRecoveryProjection: () => Effect.succeed(projection),
- }),
- Layer.mock(EventSink.EventSinkV2)({
- commitCommand: (input) => {
- committedInput = input;
- return Effect.succeed({ committed: true, cancelledEffectCount: 1 } as never);
- },
- }),
- IdAllocator.layer,
- Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
- runRecoveryOnce: Effect.succeed(false),
- }),
- Layer.mock(EffectOutbox.EffectOutboxV2)({
- reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
- }),
- ),
- ),
- );
-
- return Effect.gen(function* () {
- const summary =
- yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("shutdown");
- assert.equal(summary.closedRequests, 1);
- assert.equal(summary.retiredEffects, 1);
- const requestEvent = committedInput?.events[0];
- assert.equal(requestEvent?.type, "runtime-request.updated");
- if (requestEvent?.type === "runtime-request.updated") {
- assert.equal(requestEvent.payload.status, "cancelled");
- assert.equal(requestEvent.payload.responseCapability.type, "not_resumable");
- if (requestEvent.payload.responseCapability.type === "not_resumable") {
- assert.match(requestEvent.payload.responseCapability.reason, /shut down/);
- }
- }
- }).pipe(Effect.provide(layer));
-});
-
it.effect(
"preserves a replayable waiting run while cancelling its process-bound background work",
() => {
@@ -479,71 +418,6 @@ it.effect("cancels a stale waiting run when no checkpoint capture can finish it"
}).pipe(Effect.provide(layer));
});
-it.effect("closes a secret request card's form when its run is recovered", () => {
- const threadId = ThreadId.make("thread_secret_recovery");
- const runId = RunId.make("run_secret_recovery");
- let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
- null;
- const projection = {
- thread: { id: threadId },
- runtimeRequests: [],
- providerSessions: [],
- providerThreads: [],
- providerTurns: [],
- runs: [{ id: runId, status: "running", providerInstanceId: ProviderInstanceId.make("codex") }],
- attempts: [],
- nodes: [],
- subagents: [],
- messages: [],
- turnItems: [
- {
- id: "turn-item:secret-request:recovery",
- threadId,
- runId,
- nodeId: null,
- type: "secret_request",
- status: "waiting",
- secretStatus: "pending",
- label: "GitHub token",
- reason: "Used as GH_TOKEN.",
- },
- ],
- } as unknown as OrchestrationV2ThreadProjection;
- const layer = ProviderRuntimeRecovery.layer.pipe(
- Layer.provide(ServerSettings.layerTest()),
- Layer.provide(
- Layer.mergeAll(
- Layer.mock(ProjectionStore.ProjectionStoreV2)({
- getRecoveryThreadIds: () => Effect.succeed([threadId]),
- getRuntimeRecoveryProjection: () => Effect.succeed(projection),
- }),
- Layer.mock(EventSink.EventSinkV2)({
- commitCommand: (input) => {
- committedInput = input;
- return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
- },
- }),
- IdAllocator.layer,
- Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
- runRecoveryOnce: Effect.succeed(false),
- }),
- Layer.mock(EffectOutbox.EffectOutboxV2)({
- listByCommandId: () => Effect.succeed([]),
- reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
- }),
- ),
- ),
- );
-
- return Effect.gen(function* () {
- yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
- const itemEvent = committedInput?.events.find((event) => event.type === "turn-item.updated");
- const card = itemEvent?.type === "turn-item.updated" ? itemEvent.payload : null;
- assert.equal(card?.status, "cancelled");
- assert.equal(card?.type === "secret_request" ? card.secretStatus : null, "cancelled");
- }).pipe(Effect.provide(layer));
-});
-
it.effect.each(["queued", "preparing"] as const)("recovers $0 work after restart", (status) => {
const threadId = ThreadId.make("thread_queued_restart");
const runId = RunId.make("run_queued_restart");
diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
index 2d38db5c383..b60758e80c7 100644
--- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
@@ -1236,6 +1236,7 @@ it.effect(
}),
);
+// regression: #15571 an interrupted session start did not clean up
it.effect(
"ProviderSessionManagerV2 keeps a shared session busy when a stopped start still ends its turn",
() =>
@@ -1389,48 +1390,6 @@ it.effect("ProviderSessionManagerV2 stops a session still opening when its layer
}),
);
-it.effect("ProviderSessionManagerV2 releases live sessions when its layer shuts down", () =>
- Effect.gen(function* () {
- const state = yield* Ref.make(emptyState);
- const effect = Effect.gen(function* () {
- const eventSink = yield* EventSink.EventSinkV2;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
- const now = yield* DateTime.now;
- const threadId = ThreadId.make("thread-provider-session-manager-shutdown");
- const providerSessionId = yield* idAllocator.allocate.providerSession({
- providerInstanceId: modelSelection.instanceId,
- threadId,
- });
-
- yield* eventSink.write({
- events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
- });
- yield* manager.open({
- threadId,
- providerSessionId,
- modelSelection,
- runtimePolicy,
- });
-
- const liveState = yield* Ref.get(state);
- assert.equal(liveState.openCount, 1);
- assert.equal(liveState.closeCount, 0);
- });
-
- yield* effect.pipe(
- Effect.provide(
- layerTest({
- state,
- idleTimeoutMs: 60_000,
- }),
- ),
- );
-
- assert.equal((yield* Ref.get(state)).closeCount, 1);
- }),
-);
-
it.effect("ProviderSessionManagerV2 interrupts event subscriptions on server shutdown", () =>
Effect.gen(function* () {
const state = yield* Ref.make(emptyState);
@@ -1673,17 +1632,6 @@ it.effect("ProviderSessionManagerV2 honors a project browser-access opt-out", ()
}),
);
-it.effect("ProviderSessionManagerV2 honors a project browser-access opt-in", () =>
- Effect.gen(function* () {
- const captured = yield* runBrowserAccessScenario({
- enableAgentBrowserAccess: false,
- projectOverride: true,
- });
- assert.isDefined(captured);
- assert.equal(captured?.browserToolsAvailable, true);
- }),
-);
-
it.effect("ProviderSessionManagerV2 fails browser access closed for a missing project", () =>
Effect.gen(function* () {
const captured = yield* runBrowserAccessScenario({
@@ -1696,18 +1644,6 @@ it.effect("ProviderSessionManagerV2 fails browser access closed for a missing pr
}),
);
-it.effect("ProviderSessionManagerV2 fails browser access closed for a missing thread", () =>
- Effect.gen(function* () {
- const captured = yield* runBrowserAccessScenario({
- enableAgentBrowserAccess: true,
- projectOverride: true,
- createThread: false,
- });
- assert.isDefined(captured);
- assert.equal(captured?.browserToolsAvailable, false);
- }),
-);
-
it.effect("ProviderSessionManagerV2 revokes MCP credentials when release persistence fails", () =>
Effect.gen(function* () {
const state = yield* Ref.make(emptyState);
@@ -1822,6 +1758,7 @@ it.effect(
}),
);
+// regression: #15571 an interrupted session start did not clean up
it.effect(
"ProviderSessionManagerV2 keeps a replacement session's attachment when a stale attach is interrupted",
() =>
@@ -1914,6 +1851,7 @@ it.effect(
}),
);
+// regression: #15571 an interrupted session start did not clean up
it.effect(
"ProviderSessionManagerV2 revokes a reused credential after a resume stopped while checking it",
() =>
@@ -2125,56 +2063,6 @@ it.effect(
}),
);
-it.effect(
- "ProviderSessionManagerV2 revokes a rotated credential despite a stale record on another live session",
- () =>
- Effect.gen(function* () {
- const state = yield* Ref.make(emptyState);
- const mcpConfigs = yield* Ref.make<
- ReadonlyArray<McpProviderSession.McpProviderSessionConfig | undefined>
- >([]);
- const effect = Effect.gen(function* () {
- const eventSink = yield* EventSink.EventSinkV2;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
- const registry = yield* McpSessionRegistry.McpSessionRegistry;
- const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
- const now = yield* DateTime.now;
- const threadId = ThreadId.make("thread-provider-session-manager-stale-record");
- const s1 = yield* idAllocator.allocate.providerSession({
- providerInstanceId: modelSelection.instanceId,
- threadId,
- });
- const s2 = yield* idAllocator.allocate.providerSession({
- providerInstanceId: modelSelection.instanceId,
- threadId,
- });
-
- yield* eventSink.write({
- events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
- });
- yield* manager.open({ threadId, providerSessionId: s1, modelSelection, runtimePolicy });
- yield* manager.detach({ providerSessionId: s1, threadId });
-
- yield* registry.revokeThread(threadId);
- yield* manager.open({ threadId, providerSessionId: s2, modelSelection, runtimePolicy });
- const rotated = yield* mcpSessions.read(threadId);
- assert.isDefined(rotated);
- const rotatedToken = rotated?.authorizationHeader.replace(/^Bearer\s+/, "");
- assert.isDefined(yield* registry.resolve(rotatedToken!));
-
- yield* manager.close(s2);
- assert.isUndefined(
- yield* registry.resolve(rotatedToken!),
- "stale record on S1 must not veto revoking S2's rotated credential",
- );
- yield* manager.close(s1);
- });
-
- yield* effect.pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 1_000, mcpConfigs })));
- }),
-);
-
it.effect(
"ProviderSessionManagerV2 protects a reused credential from a predecessor release during open",
() =>
@@ -2410,6 +2298,7 @@ it.effect("ProviderSessionManagerV2 keeps the roster of a runtime whose tasks ca
}),
);
+// regression: #19355 settled and idle-released threads stayed Waiting
it.effect("ProviderSessionManagerV2 keeps a provider update that lands while release clears", () =>
Effect.gen(function* () {
const state = yield* Ref.make(emptyState);
@@ -2564,90 +2453,6 @@ it.effect(
}),
);
-it.effect("ProviderSessionManagerV2 does not apply a stale idle pin to a replacement session", () =>
- Effect.gen(function* () {
- const state = yield* Ref.make(emptyState);
- const firstCheck = yield* Ref.make(true);
- const checkEntered = yield* Deferred.make<void>();
- const checkGate = yield* Deferred.make<void>();
- const effect = Effect.gen(function* () {
- const eventSink = yield* EventSink.EventSinkV2;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
- const now = yield* DateTime.now;
- const threadId = yield* idAllocator.allocate.thread({
- fixtureName: "provider-session-manager-stale-pin",
- projectId: yield* idAllocator.allocate.project({
- fixtureName: "provider-session-manager-stale-pin",
- }),
- });
- const providerSessionId = yield* idAllocator.allocate.providerSession({
- providerInstanceId: modelSelection.instanceId,
- threadId,
- });
-
- yield* eventSink.write({
- events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
- });
- yield* manager.open({
- threadId,
- providerSessionId,
- modelSelection,
- runtimePolicy,
- });
-
- yield* TestClock.adjust("1 second");
- yield* Deferred.await(checkEntered);
-
- const closeFiber = yield* manager.close(providerSessionId).pipe(Effect.forkDetach);
- for (let i = 0; i < 20; i += 1) {
- yield* Effect.yieldNow;
- }
- yield* manager.open({
- threadId,
- providerSessionId,
- modelSelection,
- runtimePolicy,
- });
- assert.equal((yield* Ref.get(state)).openCount, 2);
-
- yield* Deferred.succeed(checkGate, undefined);
- yield* Fiber.join(closeFiber);
- for (let i = 0; i < 10; i += 1) {
- yield* Effect.yieldNow;
- }
-
- assert.isTrue(Option.isSome(yield* manager.get(providerSessionId)));
- assert.equal((yield* Ref.get(state)).closeCount, 1);
-
- yield* TestClock.adjust("1 second");
- yield* Effect.yieldNow;
- assert.isTrue(Option.isNone(yield* manager.get(providerSessionId)));
- assert.equal((yield* Ref.get(state)).closeCount, 2);
- });
-
- yield* effect.pipe(
- Effect.provide(
- layerTest({
- state,
- idleTimeoutMs: 1000,
- maxIdlePinMs: 60_000,
- hasPendingBackgroundWork: Effect.uninterruptible(
- Effect.gen(function* () {
- if (yield* Ref.getAndSet(firstCheck, false)) {
- yield* Deferred.succeed(checkEntered, undefined);
- yield* Deferred.await(checkGate);
- return true;
- }
- return false;
- }),
- ),
- }),
- ),
- );
- }),
-);
-
it.effect("ProviderSessionManagerV2 releases sessions when provider event streams fail", () =>
Effect.gen(function* () {
const state = yield* Ref.make(emptyState);
@@ -2829,6 +2634,7 @@ it.effect("ProviderSessionManagerV2 retries release records that failed to persi
}),
);
+// regression: #15048 runs got stuck after a failed session release
it.effect("ProviderSessionManagerV2 release retries leave a replacement session alone", () =>
Effect.gen(function* () {
const state = yield* Ref.make(emptyState);
@@ -2901,6 +2707,7 @@ it.effect("ProviderSessionManagerV2 release retries leave a replacement session
}),
);
+// regression: #15048 runs got stuck after a failed session release
it.effect("ProviderSessionManagerV2 keeps each failed release's cleanup", () =>
Effect.gen(function* () {
const state = yield* Ref.make(emptyState);
diff --git a/apps/server/src/orchestration-v2/ProviderSessionTransitionPolicy.test.ts b/apps/server/src/orchestration-v2/ProviderSessionTransitionPolicy.test.ts
index 80071a8cd2a..63945207e00 100644
--- a/apps/server/src/orchestration-v2/ProviderSessionTransitionPolicy.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderSessionTransitionPolicy.test.ts
@@ -63,30 +63,6 @@ it("uses the adapter's selection transition classification", () => {
);
});
-it("treats provider option changes as selection changes", () => {
- assert.deepEqual(
- decideProviderSessionTransition({
- current: {
- ...base,
- modelSelection: {
- ...base.modelSelection,
- options: [{ id: "reasoningEffort", value: "medium" }],
- },
- },
- target: {
- ...base,
- modelSelection: {
- ...base.modelSelection,
- options: [{ id: "reasoningEffort", value: "high" }],
- },
- available: true,
- },
- selectionTransition: { type: "apply_on_next_turn" },
- }),
- { type: "switch_model_in_session" },
- );
-});
-
it("restarts compatible instances for workspace or runtime changes", () => {
assert.deepEqual(
decideProviderSessionTransition({
@@ -97,25 +73,6 @@ it("restarts compatible instances for workspace or runtime changes", () => {
);
});
-it("preserves a rejected selection when the workspace also changes", () => {
- assert.deepEqual(
- decideProviderSessionTransition({
- current: base,
- target: {
- ...base,
- modelSelection: { ...base.modelSelection, model: "gpt-5.2-codex" },
- workspace: "/other",
- available: true,
- },
- selectionTransition: {
- type: "reject",
- reason: "The active session cannot apply that model.",
- },
- }),
- { type: "reject", reason: "The active session cannot apply that model." },
- );
-});
-
it("preserves handoff and missing-classification outcomes across workspace changes", () => {
const target = {
...base,
@@ -154,23 +111,3 @@ it("uses portable handoff for incompatible continuation identities", () => {
{ type: "create_with_handoff" },
);
});
-
-it("uses portable handoff for cross-driver transitions", () => {
- const claudeDriver = ProviderDriverKind.make("claude");
- assert.deepEqual(
- decideProviderSessionTransition({
- current: base,
- target: {
- ...base,
- driver: claudeDriver,
- continuationIdentity: { driverKind: claudeDriver, continuationKey: "claude:account:one" },
- modelSelection: {
- instanceId: ProviderInstanceId.make("claude"),
- model: "claude-opus-4-1",
- },
- available: true,
- },
- }),
- { type: "create_with_handoff" },
- );
-});
diff --git a/apps/server/src/orchestration-v2/ProviderSwitchService.test.ts b/apps/server/src/orchestration-v2/ProviderSwitchService.test.ts
index d9b1de61a57..f44ee018750 100644
--- a/apps/server/src/orchestration-v2/ProviderSwitchService.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderSwitchService.test.ts
@@ -104,49 +104,6 @@ function layerTest(
return ProviderSwitch.layer.pipe(Layer.provide(layerRegistry));
}
-it.effect(
- "restarts and releases the current session for unsupported in-session model changes",
- () =>
- Effect.gen(function* () {
- const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
- const result = yield* service.plan({
- projection: projection(),
- targetModelSelection: { instanceId: currentInstanceId, model: "gpt-5.2-codex" },
- });
- assert.equal(result.transition.type, "restart_and_resume");
- assert.deepEqual(result.releaseProviderSessionIds, [currentSessionId]);
- }).pipe(
- Effect.provide(
- layerTest({ [currentInstanceId]: { continuationKey: "codex:account:primary" } }),
- ),
- ),
-);
-
-it.effect.each(["stopped", "error"] as const)(
- "restarts and releases the live session when a newer %s session exists",
- (deadStatus) =>
- Effect.gen(function* () {
- const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
- const thread = projection();
- const result = yield* service.plan({
- projection: {
- ...thread,
- providerSessions: [
- ...thread.providerSessions,
- deadSessionRecord("dead_session", deadStatus),
- ],
- },
- targetModelSelection: { instanceId: currentInstanceId, model: "gpt-5.2-codex" },
- });
- assert.equal(result.transition.type, "restart_and_resume");
- assert.deepEqual(result.releaseProviderSessionIds, [currentSessionId]);
- }).pipe(
- Effect.provide(
- layerTest({ [currentInstanceId]: { continuationKey: "codex:account:primary" } }),
- ),
- ),
-);
-
it.effect("releases the newest live session, not the newest record overall", () =>
Effect.gen(function* () {
const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
index 9beee5977fb..0e7ecfa9f01 100644
--- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
@@ -3,7 +3,6 @@ import { expect, it, vi } from "vite-plus/test";
import { it as effectIt } from "@effect/vitest";
import {
CheckpointScopeId,
- ContextTransferId,
MessageId,
NodeId,
ProviderSessionId,
@@ -202,23 +201,6 @@ function startWithMissingWorktree(
};
}
-it("does not commit running state when inherited background routing cannot be read", async () => {
- const worktreePath = `${managedWorktreesDir}/project/feature-restore`;
- const harness = startWithMissingWorktree(worktreePath);
- const error = await harness.start;
-
- expect(error._tag).toBe("ProviderTurnStartError");
- expect(harness.projectionReads()).toBe(3);
- expect(harness.pruneWorktrees).toHaveBeenCalledWith({ cwd: "/tmp/provider-turn-start-project" });
- expect(harness.createWorktree).toHaveBeenCalledWith({
- cwd: "/tmp/provider-turn-start-project",
- refName: "feature/restore",
- path: worktreePath,
- });
- expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
- expect(harness.startRootRun).not.toHaveBeenCalled();
-});
-
it.each([
{
label: "<managed>/<repo>/<branch>",
@@ -816,123 +798,66 @@ effectIt.effect("reads current startup state after waiting for the workspace lea
}),
);
+// regression: #15784 superseded provider startups kept running
effectIt.effect.each([
- { boundary: "policy resolution", nativeMode: "ensure", loss: "replaced" },
- { boundary: "policy resolution", nativeMode: "ensure", loss: "interrupted" },
- { boundary: "session opening", nativeMode: "ensure", loss: "replaced" },
- { boundary: "session opening", nativeMode: "ensure", loss: "interrupted" },
- { boundary: "session opening", nativeMode: "resume", loss: "replaced" },
- { boundary: "session opening", nativeMode: "fork", loss: "replaced" },
-])(
- "does not continue $nativeMode startup when $loss during $boundary",
- ({ boundary, nativeMode, loss }) =>
- Effect.gen(function* () {
- const entered = yield* Deferred.make<void>();
- const release = yield* Deferred.make<void>();
- const gate = Deferred.succeed(entered, undefined).pipe(
- Effect.andThen(Deferred.await(release)),
- );
- const harness = makeLocalCommandHarness({ text: "Continue" });
- const projection = harness.projection();
- const run = projection.runs[0]!;
- const providerThread = projection.providerThreads[0]!;
- if (nativeMode === "resume") {
- harness.setProjection({
- ...projection,
- providerThreads: [
- {
- ...providerThread,
- nativeThreadRef: {
- driver: providerThread.driver,
- nativeId: "existing",
- strength: "strong",
- },
- },
- ],
- });
- } else if (nativeMode === "fork") {
- const sourceThreadId = ThreadId.make("fork-source");
- harness.getThreadRecords.mockReturnValue(
- Effect.succeed({
- ...projection,
- thread: { ...projection.thread, id: sourceThreadId },
- }),
- );
- harness.setProjection({
- ...projection,
- contextTransfers: [
- {
- id: ContextTransferId.make("pending-fork"),
- type: "fork",
- sourceThreadId,
- targetThreadId: projection.thread.id,
- sourcePoint: { threadId: sourceThreadId, runId: run.id },
- basePoint: null,
- sourceProviderInstanceId: run.providerInstanceId,
- targetProviderInstanceId: run.providerInstanceId,
- targetRunId: run.id,
- status: "pending",
- resolution: null,
- createdBy: "user",
- error: null,
- createdAt: projection.updatedAt,
- updatedAt: projection.updatedAt,
- consumedAt: null,
- },
- ],
- });
- }
- const ensureThread = vi.fn(() => Effect.succeed(providerThread));
- const resumeThread = vi.fn(() => Effect.succeed(providerThread));
- const forkThread = vi.fn(() => Effect.succeed(providerThread));
- harness.open.mockReturnValue(
- (boundary === "session opening" ? gate : Effect.void).pipe(
- Effect.as({
- driver: providerThread.driver,
- ensureThread,
- resumeThread,
- forkThread,
- } as never),
- ),
+ { boundary: "policy resolution", loss: "replaced" },
+ { boundary: "session opening", loss: "interrupted" },
+])("does not continue startup when $loss during $boundary", ({ boundary, loss }) =>
+ Effect.gen(function* () {
+ const entered = yield* Deferred.make<void>();
+ const release = yield* Deferred.make<void>();
+ const gate = Deferred.succeed(entered, undefined).pipe(Effect.andThen(Deferred.await(release)));
+ const harness = makeLocalCommandHarness({ text: "Continue" });
+ const projection = harness.projection();
+ const providerThread = projection.providerThreads[0]!;
+ const ensureThread = vi.fn(() => Effect.succeed(providerThread));
+ const resumeThread = vi.fn(() => Effect.succeed(providerThread));
+ const forkThread = vi.fn(() => Effect.succeed(providerThread));
+ harness.open.mockReturnValue(
+ (boundary === "session opening" ? gate : Effect.void).pipe(
+ Effect.as({
+ driver: providerThread.driver,
+ ensureThread,
+ resumeThread,
+ forkThread,
+ } as never),
+ ),
+ );
+ if (boundary === "policy resolution") {
+ harness.resolveRuntimePolicy.mockReturnValue(
+ gate.pipe(Effect.as({ cwd: "/tmp/native-account-command" } as never)),
);
- if (boundary === "policy resolution") {
- harness.resolveRuntimePolicy.mockReturnValue(
- gate.pipe(Effect.as({ cwd: "/tmp/native-account-command" } as never)),
- );
- }
+ }
- const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true }));
- yield* Deferred.await(entered);
- const current = harness.projection();
- const replacementId = RunAttemptId.make("replacement-attempt");
- const updated = {
- ...current,
- runs: current.runs.map((candidate) =>
- loss === "replaced"
- ? { ...candidate, activeAttemptId: replacementId }
- : { ...candidate, status: "interrupted" as const, completedAt: current.updatedAt },
- ),
- attempts:
- loss === "replaced"
- ? [
- ...current.attempts,
- { ...current.attempts[0]!, id: replacementId, attemptOrdinal: 2 },
- ]
- : current.attempts,
- };
- harness.setProjection(updated);
- yield* Deferred.succeed(release, undefined);
- yield* Fiber.join(startup);
+ const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true }));
+ yield* Deferred.await(entered);
+ const current = harness.projection();
+ const replacementId = RunAttemptId.make("replacement-attempt");
+ const updated = {
+ ...current,
+ runs: current.runs.map((candidate) =>
+ loss === "replaced"
+ ? { ...candidate, activeAttemptId: replacementId }
+ : { ...candidate, status: "interrupted" as const, completedAt: current.updatedAt },
+ ),
+ attempts:
+ loss === "replaced"
+ ? [...current.attempts, { ...current.attempts[0]!, id: replacementId, attemptOrdinal: 2 }]
+ : current.attempts,
+ };
+ harness.setProjection(updated);
+ yield* Deferred.succeed(release, undefined);
+ yield* Fiber.join(startup);
- expect(harness.open).toHaveBeenCalledTimes(boundary === "session opening" ? 1 : 0);
- expect(ensureThread).not.toHaveBeenCalled();
- expect(resumeThread).not.toHaveBeenCalled();
- expect(forkThread).not.toHaveBeenCalled();
- expect(harness.startRootRun).not.toHaveBeenCalled();
- expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
- expect(harness.events).toEqual([]);
- expect(harness.projection()).toEqual(updated);
- }),
+ expect(harness.open).toHaveBeenCalledTimes(boundary === "session opening" ? 1 : 0);
+ expect(ensureThread).not.toHaveBeenCalled();
+ expect(resumeThread).not.toHaveBeenCalled();
+ expect(forkThread).not.toHaveBeenCalled();
+ expect(harness.startRootRun).not.toHaveBeenCalled();
+ expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
+ expect(harness.events).toEqual([]);
+ expect(harness.projection()).toEqual(updated);
+ }),
);
effectIt.effect("starts another provider in the same checkout while a turn is pending", () =>
@@ -1012,24 +937,6 @@ effectIt.effect("leaves the run starting when a session-open failure will be ret
}),
);
-effectIt.effect("keeps a session-open failure retryable when terminal persistence fails", () =>
- Effect.gen(function* () {
- const harness = makeLocalCommandHarness({
- text: "Continue",
- openFailure: new Error("provider session rejected"),
- writeFailure: new Error("database unavailable"),
- });
-
- const error = yield* harness.start.pipe(Effect.flip);
-
- expect(error._tag).toBe("ProviderTurnStartError");
- expect(harness.writeIfRunCurrent).toHaveBeenCalledOnce();
- expect(harness.startRootRun).not.toHaveBeenCalled();
- expect(harness.projection().runs.at(-1)?.status).toBe("starting");
- expect(harness.events).toEqual([]);
- }),
-);
-
effectIt.effect("does not terminalize a provider-session open interruption", () =>
Effect.gen(function* () {
const harness = makeLocalCommandHarness({ text: "Continue", interruptOpen: true });
@@ -1068,52 +975,6 @@ effectIt.effect("does not overwrite a run interrupted while its provider session
}),
);
-effectIt.effect("fails a starting run when its last start attempt cannot load the thread", () =>
- Effect.gen(function* () {
- const harness = makeLocalCommandHarness({
- text: "Continue",
- ensureThreadFailure: new Error("Pi RPC read failed: pi process exited with code 1."),
- });
-
- yield* harness.start;
-
- expect(harness.startRootRun).not.toHaveBeenCalled();
- const projection = harness.projection();
- expect(projection.runs.at(-1)).toMatchObject({ status: "failed", startedAt: null });
- expect(projection.attempts[0]).toMatchObject({ status: "failed", startedAt: null });
- expect(projection.nodes[0]).toMatchObject({ status: "failed", startedAt: null });
- expect(projection.turnItems).toMatchObject([
- {
- type: "error",
- title: "Provider turn failed to start",
- failure: {
- class: "provider_error",
- message: "Pi RPC read failed: pi process exited with code 1.",
- },
- },
- ]);
- }),
-);
-
-effectIt.effect(
- "keeps a store failure after the provider loaded the thread typed and retryable",
- () =>
- Effect.gen(function* () {
- const harness = makeLocalCommandHarness({
- text: "Continue",
- historyReadFailureAfterFallback: new Error("database unavailable"),
- });
-
- const error = yield* harness.start.pipe(Effect.flip);
-
- expect(error._tag).toBe("ProviderTurnStartError");
- expect((error.cause as { _tag?: string } | undefined)?._tag).toBe("ProjectionStoreReadError");
- expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
- expect(harness.projection().runs.at(-1)?.status).toBe("starting");
- expect(harness.events).toEqual([]);
- }),
-);
-
effectIt.effect("does not mistake a failed state read for a superseded run", () =>
Effect.gen(function* () {
const harness = makeLocalCommandHarness({ text: "Continue", failReadsAfterRunning: true });
@@ -1164,31 +1025,6 @@ effectIt.effect(
}),
);
-effectIt.effect("persists a failed sign-out without starting a provider turn", () =>
- Effect.gen(function* () {
- const harness = makeLocalCommandHarness({
- text: "/logout",
- logoutFailure: "Could not stop all sessions for this provider. Try again.",
- });
-
- yield* harness.start;
-
- expect(harness.open).not.toHaveBeenCalled();
- expect(harness.startRootRun).not.toHaveBeenCalled();
- expect(harness.projection().runs.at(-1)?.status).toBe("failed");
- expect(harness.projection().turnItems).toMatchObject([
- {
- type: "error",
- title: "Provider sign-out failed",
- failure: {
- class: "permission_error",
- message: "Could not stop all sessions for this provider. Try again.",
- },
- },
- ]);
- }),
-);
-
for (const previousMessages of [[], ["/compact", " /COMPACT "]]) {
effectIt.effect(
`rejects compaction without conversation context after ${previousMessages.length} prior compactions`,
diff --git a/apps/server/src/orchestration-v2/ProviderTurnTokenUsage.test.ts b/apps/server/src/orchestration-v2/ProviderTurnTokenUsage.test.ts
deleted file mode 100644
index c8fd51902fd..00000000000
--- a/apps/server/src/orchestration-v2/ProviderTurnTokenUsage.test.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import {
- NodeId,
- type OrchestrationV2ProviderTurn,
- ProviderThreadId,
- ProviderTurnId,
-} from "@t3tools/contracts";
-import { assert, describe, it } from "@effect/vitest";
-import * as DateTime from "effect/DateTime";
-
-import { upsertProviderTurn } from "./ProjectionStore.ts";
-
-describe("provider turn token usage projection", () => {
- it("keeps live usage when a terminal update omits it", () => {
- const now = DateTime.makeUnsafe("2026-08-29T00:00:00.000Z");
- const running = {
- id: ProviderTurnId.make("provider-turn-usage"),
- providerThreadId: ProviderThreadId.make("provider-thread-usage"),
- nodeId: NodeId.make("node-usage"),
- runAttemptId: null,
- nativeTurnRef: null,
- ordinal: 1,
- status: "running",
- startedAt: now,
- completedAt: null,
- tokenUsage: {
- usedTokens: 50_000,
- maxTokens: 200_000,
- updatedAt: "2026-08-29T00:00:00.000Z",
- },
- } satisfies OrchestrationV2ProviderTurn;
- const completed = {
- ...running,
- status: "completed",
- completedAt: now,
- tokenUsage: undefined,
- } satisfies OrchestrationV2ProviderTurn;
-
- const projected = upsertProviderTurn([running], completed);
-
- assert.deepEqual(projected[0]?.tokenUsage, running.tokenUsage);
- assert.equal(projected[0]?.status, "completed");
- });
-});
diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts
index 8b03641bbb9..df184a61082 100644
--- a/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts
+++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts
@@ -14,7 +14,6 @@ import {
isAwaitedWork,
isRestartNoteContinuation,
pendingRestartCancelledBackgroundWork,
- restartCancelledBackgroundWorkNote,
restartContinuationNote,
mergeRestartCancelledBackgroundWork,
} from "./RestartBackgroundNote.ts";
@@ -86,22 +85,7 @@ it("delivers a resumed queued run's note even after a higher-ordinal run", () =>
);
});
-it("bounds the note so it cannot crowd out the turn's context", () => {
- const work = Array.from({ length: 25 }, (_, index) => ({
- kind: "shell" as const,
- label: `sleep ${index}`,
- }));
- const note = restartCancelledBackgroundWorkNote(work);
- assert.lengthOf(note.split("\n"), 12);
- assert.isTrue(note.endsWith("- and 15 more"));
- const command = cancelledTurnItemWork({
- type: "command_execution",
- input: "x".repeat(10_000),
- title: null,
- } as never);
- assert.isAtMost(command?.label.length ?? 0, 160);
-});
-
+// regression: #19750 wake threads whose subagents' background work a restart cut
it("names a lost subagent by the id the agent resumes it with", () => {
const ownShell = cancelledRosterTaskWork({
kind: "command",
diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts
index a2f210c47b0..4dcfaa069f5 100644
--- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts
+++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts
@@ -4,7 +4,6 @@ import {
ChatAttachmentId,
ChatFileAttachment,
CommandId,
- EventId,
MessageId,
NodeId,
type OrchestrationV2AppThread,
@@ -1827,26 +1826,6 @@ it.effect.each([null, "run:nested-sdk"] as const)(
}),
);
-it.effect("keeps ingesting until the last of several background items terminalizes", () =>
- Effect.gen(function* () {
- const secondItemId = TurnItemId.make("turn-item:bg-multi:second");
- const observed = yield* runBackgroundItemScenario("bg-multi", (ids) => [
- backgroundTurnItemEvent(ids, "command_execution", "running", 1),
- backgroundTurnItemEvent(ids, "dynamic_tool", "running", 2, secondItemId),
- rootTerminalEvent(ids, "completed"),
- backgroundTurnItemEvent(ids, "command_execution", "completed", 3),
- backgroundTurnItemEvent(ids, "dynamic_tool", "completed", 4, secondItemId),
- ]);
- assert.deepEqual(observed, [
- "turn_item:running",
- "turn_item:running",
- "root-finalized",
- "turn_item:completed",
- "turn_item:completed",
- ]);
- }),
-);
-
it.effect("does not pin ingestion on background items when the root turn is interrupted", () =>
Effect.gen(function* () {
const observed = yield* runBackgroundItemScenario("bg-interrupted", (ids) => [
@@ -1878,27 +1857,6 @@ it.effect("seeds inherited background items before their next update", () =>
}),
);
-it.effect("releases the live run after an inherited background item terminalizes", () =>
- Effect.gen(function* () {
- const key = "inherited-background-terminal";
- const priorRunId = RunId.make(`run:${key}:prior`);
- const observed = yield* runBackgroundItemScenario(
- key,
- (ids) => [
- backgroundTurnItemEventForRun(ids, priorRunId, "subagent", "running", 1),
- rootTerminalEvent(ids, "completed"),
- backgroundTurnItemEventForRun(ids, priorRunId, "subagent", "completed", 2),
- ],
- {
- loadInheritedBackgroundTurnItems: () =>
- Effect.succeed([{ id: TurnItemId.make(`turn-item:${key}`), runId: priorRunId }]),
- },
- );
-
- assert.deepEqual(observed, ["turn_item:running", "root-finalized", "turn_item:completed"]);
- }),
-);
-
it.effect("refreshes inherited background items after event subscription", () =>
Effect.gen(function* () {
const key = "inherited-background-subscription-refresh";
@@ -2391,248 +2349,6 @@ it.effect(
}),
);
-it.effect("cascade helper is provider-neutral for Claude and Codex-shaped child projections", () =>
- Effect.gen(function* () {
- const now = yield* DateTime.now;
- let nextId = 0;
- const allocateEventId = () =>
- Effect.sync(() => EventId.make(`event:cascade-helper:${nextId++}`));
-
- for (const driverKind of [
- ProviderDriverKind.make("claudeAgent"),
- ProviderDriverKind.make("codex"),
- ] as const) {
- const runId = RunId.make(`run:cascade-helper:${driverKind}`);
- const threadId = ThreadId.make(`thread:cascade-helper:${driverKind}`);
- const childThreadId = ThreadId.make(`thread:cascade-helper:${driverKind}:child`);
- const subagentId = NodeId.make(`node:cascade-helper:${driverKind}:subagent`);
- const childNodeId = NodeId.make(`node:cascade-helper:${driverKind}:child-root`);
- const providerInstanceId = ProviderInstanceId.make(String(driverKind));
- const terminalStatus = driverKind === "claudeAgent" ? "failed" : "cancelled";
- const subagent: OrchestrationV2Subagent = {
- id: subagentId,
- threadId,
- runId,
- parentNodeId: NodeId.make(`node:cascade-helper:${driverKind}:root`),
- origin: "provider_native",
- createdBy: "agent",
- driver: driverKind,
- providerInstanceId,
- providerThreadId: null,
- childThreadId,
- nativeTaskRef: {
- driver: driverKind,
- nativeId: `native-${driverKind}`,
- strength: "strong",
- },
- prompt: "hold",
- title: "hold",
- model: null,
- status: "running",
- progress: "partial progress",
- result: "partial result",
- startedAt: now,
- completedAt: null,
- updatedAt: now,
- };
- const turnItem = {
- id: TurnItemId.make(`turn-item:cascade-helper:${driverKind}`),
- threadId,
- runId,
- nodeId: subagentId,
- providerThreadId: null,
- providerTurnId: null,
- nativeItemRef: subagent.nativeTaskRef,
- parentItemId: null,
- ordinal: 3,
- status: "running" as const,
- title: "hold",
- startedAt: now,
- completedAt: null,
- updatedAt: now,
- type: "subagent" as const,
- subagentId,
- origin: "provider_native" as const,
- driver: driverKind,
- providerInstanceId,
- childThreadId,
- prompt: "hold",
- progress: "partial progress",
- result: "partial result",
- } satisfies Extract<OrchestrationV2TurnItem, { type: "subagent" }>;
- const node: OrchestrationV2ExecutionNode = {
- id: subagentId,
- threadId,
- runId,
- parentNodeId: NodeId.make(`node:cascade-helper:${driverKind}:root`),
- rootNodeId: NodeId.make(`node:cascade-helper:${driverKind}:root`),
- kind: "subagent",
- status: "running",
- countsForRun: false,
- providerThreadId: null,
- providerTurnId: null,
- nativeItemRef: subagent.nativeTaskRef,
- runtimeRequestId: null,
- checkpointScopeId: null,
- startedAt: now,
- completedAt: null,
- };
- const openChildNode: OrchestrationV2ExecutionNode = {
- id: childNodeId,
- threadId: childThreadId,
- runId: null,
- parentNodeId: null,
- rootNodeId: childNodeId,
- kind: "root_turn",
- status: "running",
- countsForRun: false,
- providerThreadId: null,
- providerTurnId: null,
- nativeItemRef: null,
- runtimeRequestId: null,
- checkpointScopeId: null,
- startedAt: now,
- completedAt: null,
- };
- const childTurnItem: OrchestrationV2TurnItem =
- driverKind === "claudeAgent"
- ? {
- id: TurnItemId.make(`turn-item:cascade-helper:${driverKind}:child-reasoning`),
- threadId: childThreadId,
- runId: null,
- nodeId: childNodeId,
- providerThreadId: null,
- providerTurnId: null,
- nativeItemRef: null,
- parentItemId: null,
- ordinal: 1,
- status: "running",
- title: "Working",
- startedAt: now,
- completedAt: null,
- updatedAt: now,
- type: "reasoning",
- text: "partial progress",
- streaming: true,
- }
- : {
- id: TurnItemId.make(`turn-item:cascade-helper:${driverKind}:child-command`),
- threadId: childThreadId,
- runId: null,
- nodeId: childNodeId,
- providerThreadId: null,
- providerTurnId: null,
- nativeItemRef: null,
- parentItemId: null,
- ordinal: 1,
- status: "running",
- title: "sleep 300",
- startedAt: now,
- completedAt: null,
- updatedAt: now,
- type: "command_execution",
- input: "sleep 300",
- };
-
- const events = yield* RunExecutionService.cascadeTerminalizeRunOwnedSubagents({
- run: {
- id: runId,
- threadId,
- ordinal: 1,
- providerInstanceId,
- } as OrchestrationV2Run,
- open: {
- subagents: new Map([[subagentId, subagent]]),
- turnItems: new Map([[subagentId, turnItem]]),
- childTurnItems: new Map(),
- nodes: new Map([[subagentId, node]]),
- linkedChildThreadIds: new Set([childThreadId]),
- },
- status: terminalStatus,
- completedAt: now,
- allocateEventId,
- });
-
- assert.equal(events.length, 3, `${driverKind}: subagent + node + turn item`);
- const terminalSubagent = events.find((event) => event.type === "subagent.updated");
- assert.isDefined(terminalSubagent);
- if (terminalSubagent?.type !== "subagent.updated") {
- assert.fail("expected subagent.updated event");
- return;
- }
- assert.equal(terminalSubagent.payload.status, terminalStatus);
- assert.equal(terminalSubagent.payload.childThreadId, childThreadId);
- assert.equal(terminalSubagent.payload.progress, "partial progress");
- assert.equal(terminalSubagent.payload.result, "partial result");
- assert.equal(terminalSubagent.payload.driver, driverKind);
-
- const terminalItem = events.find(
- (event) => event.type === "turn-item.updated" && event.payload.type === "subagent",
- );
- assert.isDefined(terminalItem);
- if (terminalItem?.type !== "turn-item.updated" || terminalItem.payload.type !== "subagent") {
- assert.fail("expected subagent turn-item.updated event");
- return;
- }
- assert.equal(terminalItem.payload.status, terminalStatus);
- assert.equal(terminalItem.payload.childThreadId, childThreadId);
- assert.equal(terminalItem.payload.progress, "partial progress");
- assert.equal(terminalItem.payload.result, "partial result");
-
- const afterTerminalLinkEvents =
- yield* RunExecutionService.cascadeTerminalizeRunOwnedSubagents({
- run: {
- id: runId,
- threadId,
- ordinal: 1,
- providerInstanceId,
- } as OrchestrationV2Run,
- open: {
- subagents: new Map(),
- turnItems: new Map(),
- childTurnItems: new Map([[childTurnItem.id, childTurnItem]]),
- nodes: new Map([[childNodeId, openChildNode]]),
- linkedChildThreadIds: new Set([childThreadId]),
- },
- status: terminalStatus,
- completedAt: now,
- allocateEventId,
- });
- assert.equal(
- afterTerminalLinkEvents.length,
- 2,
- `${driverKind}: linked child node and turn item cascade after link rows terminalize`,
- );
- const cascadedChild = afterTerminalLinkEvents.find((event) => event.type === "node.updated");
- assert.isDefined(cascadedChild);
- if (cascadedChild?.type !== "node.updated") {
- assert.fail("expected node.updated for linked child thread");
- return;
- }
- assert.equal(cascadedChild.payload.id, childNodeId);
- assert.equal(cascadedChild.payload.threadId, childThreadId);
- assert.equal(cascadedChild.payload.status, terminalStatus);
- assert.equal(cascadedChild.payload.kind, "root_turn");
- const cascadedChildTurnItem = afterTerminalLinkEvents.find(
- (event) => event.type === "turn-item.updated",
- );
- assert.isDefined(cascadedChildTurnItem);
- if (cascadedChildTurnItem?.type !== "turn-item.updated") {
- assert.fail("expected turn-item.updated for linked child thread");
- return;
- }
- assert.equal(cascadedChildTurnItem.threadId, childThreadId);
- assert.equal(cascadedChildTurnItem.payload.id, childTurnItem.id);
- assert.equal(cascadedChildTurnItem.payload.status, terminalStatus);
- assert.equal(cascadedChildTurnItem.payload.runId, null);
- assert.equal(cascadedChildTurnItem.payload.type, childTurnItem.type);
- if (cascadedChildTurnItem.payload.type === "reasoning") {
- assert.isFalse(cascadedChildTurnItem.payload.streaming);
- }
- }
- }),
-);
-
it.effect("omits interrupt results and subagent cascade for a superseded attempt", () =>
Effect.gen(function* () {
const { written, observed } = yield* captureRootRunTermination({
diff --git a/apps/server/src/orchestration-v2/RuntimePolicy.test.ts b/apps/server/src/orchestration-v2/RuntimePolicy.test.ts
index a629093f8ad..b6136de68c2 100644
--- a/apps/server/src/orchestration-v2/RuntimePolicy.test.ts
+++ b/apps/server/src/orchestration-v2/RuntimePolicy.test.ts
@@ -108,18 +108,6 @@ const layerTest = RuntimePolicy.layerFromProjectStore.pipe(
);
it.layer(layerTest)("RuntimePolicyV2", (it) => {
- it.effect("prefers a provisioned worktree over the project root", () =>
- Effect.gen(function* () {
- const policy = yield* RuntimePolicy.RuntimePolicyV2;
- const now = yield* DateTime.now;
- const resolved = yield* policy.resolve({
- thread: makeThread({ now, worktreePath: "/project-worktree" }),
- modelSelection,
- });
- assert.equal(resolved.cwd, "/project-worktree");
- }),
- );
-
it.effect("runs a mode the provider does not offer in Supervised", () =>
Effect.gen(function* () {
const policy = yield* RuntimePolicy.RuntimePolicyV2;
diff --git a/apps/server/src/orchestration-v2/RuntimeRequestService.test.ts b/apps/server/src/orchestration-v2/RuntimeRequestService.test.ts
index 4400e853e3a..70ddb5e84ef 100644
--- a/apps/server/src/orchestration-v2/RuntimeRequestService.test.ts
+++ b/apps/server/src/orchestration-v2/RuntimeRequestService.test.ts
@@ -4,7 +4,6 @@ import {
ProviderSessionId,
RuntimeRequestId,
ThreadId,
- type OrchestrationV2RuntimeRequest,
type OrchestrationV2ThreadProjection,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
@@ -17,53 +16,6 @@ import * as ProjectionStore from "./ProjectionStore.ts";
import * as ProviderSessionManager from "./ProviderSessionManager.ts";
import * as RuntimeRequestService from "./RuntimeRequestService.ts";
-function projectionWithRuntimeRequest(
- runtimeRequest?: OrchestrationV2RuntimeRequest,
-): OrchestrationV2ThreadProjection {
- return {
- runtimeRequests: runtimeRequest === undefined ? [] : [runtimeRequest],
- } as unknown as OrchestrationV2ThreadProjection;
-}
-
-function resolvedRuntimeRequest(
- requestId: RuntimeRequestId,
- providerSessionId: ProviderSessionId,
-): OrchestrationV2RuntimeRequest {
- return {
- id: requestId,
- nodeId: NodeId.make(`node-${requestId}`),
- providerTurnId: null,
- nativeRequestRef: null,
- kind: "command",
- status: "resolved",
- responseCapability: {
- type: "live",
- providerSessionId,
- },
- createdAt: DateTime.makeUnsafe("2026-07-29T00:00:00.000Z"),
- resolvedAt: DateTime.makeUnsafe("2026-07-29T00:00:01.000Z"),
- };
-}
-
-function layerRuntimeRequestTest(
- projection: OrchestrationV2ThreadProjection,
- getSession: ProviderSessionManager.ProviderSessionManagerV2Shape["get"],
-) {
- return RuntimeRequestService.layer.pipe(
- Layer.provide(
- Layer.mergeAll(
- Layer.mock(ProjectionStore.ProjectionStoreV2)({
- getRuntimeRequest: (_threadId, requestId) =>
- Effect.succeed(projection.runtimeRequests.find((request) => request.id === requestId)),
- }),
- Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
- get: getSession,
- }),
- ),
- ),
- );
-}
-
it.effect("rejects expired runtime requests before invoking the live adapter", () => {
const threadId = ThreadId.make("thread-runtime-request-expired");
const providerSessionId = ProviderSessionId.make("provider-session-runtime-request-expired");
@@ -131,63 +83,3 @@ it.effect("rejects expired runtime requests before invoking the live adapter", (
assert.equal(respondToRuntimeRequest.mock.calls.length, 0);
}).pipe(Effect.provide(layerTest));
});
-
-it.effect("classifies runtime request response validation failures", () => {
- const threadId = ThreadId.make("thread-runtime-request-validation");
- const providerSessionId = ProviderSessionId.make("provider-session-runtime-request-validation");
- const otherProviderSessionId = ProviderSessionId.make(
- "provider-session-runtime-request-validation-other",
- );
- const requestId = RuntimeRequestId.make("request-validation");
- const unexpectedGetSession = vi.fn(() => Effect.succeed(Option.none()));
- const layerMissing = layerRuntimeRequestTest(
- projectionWithRuntimeRequest(),
- unexpectedGetSession,
- );
- const layerNotResumable = layerRuntimeRequestTest(
- projectionWithRuntimeRequest(resolvedRuntimeRequest(requestId, otherProviderSessionId)),
- unexpectedGetSession,
- );
- const layerInactive = layerRuntimeRequestTest(
- projectionWithRuntimeRequest(resolvedRuntimeRequest(requestId, providerSessionId)),
- () => Effect.succeed(Option.none()),
- );
- const respond = Effect.gen(function* () {
- const service = yield* RuntimeRequestService.RuntimeRequestServiceV2;
- return yield* service
- .respond({
- threadId,
- providerSessionId,
- requestId,
- decision: "accept",
- })
- .pipe(Effect.flip);
- });
-
- return Effect.gen(function* () {
- const missing = yield* respond.pipe(Effect.provide(layerMissing));
- assert.equal(missing.reason, "request-missing");
- assert.equal(
- missing.message,
- `Runtime request ${requestId} no longer exists on thread ${threadId}.`,
- );
- assert.isUndefined(missing.cause);
-
- const notResumable = yield* respond.pipe(Effect.provide(layerNotResumable));
- assert.equal(notResumable.reason, "request-not-resumable");
- assert.equal(
- notResumable.message,
- `Runtime request ${requestId} on thread ${threadId} is not resumable on provider session ${providerSessionId}.`,
- );
- assert.isUndefined(notResumable.cause);
-
- const inactive = yield* respond.pipe(Effect.provide(layerInactive));
- assert.equal(inactive.reason, "provider-session-not-active");
- assert.equal(
- inactive.message,
- `Provider session ${providerSessionId} is not active for runtime request ${requestId} on thread ${threadId}.`,
- );
- assert.isUndefined(inactive.cause);
- assert.equal(unexpectedGetSession.mock.calls.length, 0);
- });
-});
diff --git a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts
index afabcdeb5ee..03cdf5e85a6 100644
--- a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts
+++ b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts
@@ -438,12 +438,12 @@ it.live("retries a failed selection restart session open before completing", ()
),
);
-it.live.each(["stopped", "error"] as const)(
- "restarts the live session on a model change when a newer %s session record exists",
- (deadStatus) =>
+it.live(
+ "restarts the live session on a model change when a newer stopped session record exists",
+ () =>
Effect.scoped(
Effect.gen(function* () {
- const name = `selection-restart-dead-${deadStatus}`;
+ const name = "selection-restart-dead-stopped";
const cwd = yield* checkpointWorkspace(name);
const threadId = ThreadId.make(`thread:${name}`);
const state = yield* Ref.make<RestartAdapterState>({
@@ -541,9 +541,9 @@ it.live.each(["stopped", "error"] as const)(
occurredAt: deadAt,
payload: {
...deadSession,
- status: deadStatus,
+ status: "stopped",
updatedAt: deadAt,
- lastError: deadStatus === "error" ? "Simulated session failure." : null,
+ lastError: null,
},
},
],
diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
index 884683979fb..441cf0a6e90 100644
--- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
+++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
@@ -34,31 +34,20 @@ const instanceId = ProviderInstanceId.make("codex");
const modelSelection = { instanceId, model: "test-model" };
it.effect.each(
- [false, true]
- .flatMap((mailbox) =>
- (
- [
- "before delivery",
- "during delivery",
- "before dispatch",
- "after delivery",
- "without native steering",
- "with interrupting native steering",
- "settled only",
- ] as const
- ).map((timing) => ({
- mailbox,
- timing,
- label: mailbox ? "mailbox notification" : "steering",
- })),
- )
- .filter(
- ({ mailbox, timing }) =>
- mailbox ||
- (timing !== "without native steering" &&
- timing !== "with interrupting native steering" &&
- timing !== "settled only"),
- ),
+ (
+ [
+ [false, "during delivery"],
+ [false, "before dispatch"],
+ [true, "after delivery"],
+ [true, "without native steering"],
+ [true, "with interrupting native steering"],
+ [true, "settled only"],
+ ] as const
+ ).map(([mailbox, timing]) => ({
+ mailbox,
+ timing,
+ label: mailbox ? "mailbox notification" : "steering",
+ })),
)("delivers $label when completion wins $timing", ({ mailbox, timing }) =>
Effect.scoped(
Effect.gen(function* () {
@@ -561,14 +550,15 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function*
return { events, started, steered, layer, startFirstTurn };
});
-it.effect.each([{ canRestart: false }, { canRestart: true }])(
- "steers a changed turn-scoped selection into the running turn (canRestart=$canRestart)",
- ({ canRestart }) =>
+// regression: #19210 a provider that can restart the turn must still steer, since restarting ends its native subagents
+it.effect(
+ "steers a changed turn-scoped selection into a running turn the provider could restart",
+ () =>
Effect.scoped(
Effect.gen(function* () {
const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
- `steering-selection-change-${canRestart}`,
- canRestart,
+ "steering-selection-change",
+ true,
);
yield* Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
diff --git a/apps/server/src/orchestration-v2/ThreadFind.test.ts b/apps/server/src/orchestration-v2/ThreadFind.test.ts
index 8459e10e6b3..3d261ed85e2 100644
--- a/apps/server/src/orchestration-v2/ThreadFind.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadFind.test.ts
@@ -225,25 +225,6 @@ describe("V2 thread find", () => {
}).pipe(Effect.provide(layerTest)),
);
- it.effect("returns only a final frame for empty searches and relative navigation", () =>
- Effect.gen(function* () {
- const projection = yield* setup;
- yield* putItems([item("only", 0, "needle needle")]);
- const empty = yield* projection
- .searchThreadStream({ threadId, query: "missing" })
- .pipe(Stream.runCollect);
- assert.equal(empty.length, 1);
- assert.equal(empty[0]!.totalMatches, 0);
- assert.notEqual(empty[0]!.complete, false);
- const relative = yield* projection
- .searchThreadStream({ threadId, query: "needle", offset: 1 })
- .pipe(Stream.runCollect);
- assert.equal(relative.length, 1);
- assert.equal(relative[0]!.match?.occurrence, 1);
- assert.notEqual(relative[0]!.complete, false);
- }).pipe(Effect.provide(layerTest)),
- );
-
it.effect("returns bounded navigation counts around the selection, including wraparound", () =>
Effect.gen(function* () {
const projection = yield* setup;
diff --git a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts
index 920b5fe321b..f857738742a 100644
--- a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts
@@ -26,7 +26,12 @@ import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
-const forkCases = (["codex", "claudeAgent"] as const).flatMap((driverName) => {
+const forkCases = (
+ [
+ ["codex", "interrupted"],
+ ["claudeAgent", "failed"],
+ ] as const
+).map(([driverName, status]) => {
const driver = ProviderDriverKind.make(driverName);
const instanceId = ProviderInstanceId.make(driver);
const modelSelection = { instanceId, model: "test-model" };
@@ -46,13 +51,7 @@ const forkCases = (["codex", "claudeAgent"] as const).flatMap((driverName) => {
{ runEffectWorker: false },
);
- return (["failed", "interrupted", "cancelled"] as const).map((status) => ({
- driver,
- status,
- instanceId,
- modelSelection,
- layer,
- }));
+ return { driver, status, instanceId, modelSelection, layer };
});
it.effect("a persisted fork leaves PR watching with its parent until explicitly opted in", () =>
diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
index 3886b209c83..0391412fe5f 100644
--- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
@@ -550,7 +550,7 @@ it.effect("provisions independent launches concurrently instead of behind a glob
}),
);
-it.effect.each([" /COMPACT ", "/logout"])(
+it.effect.each([" /COMPACT "])(
"uses the first conversation message for a title after %s",
(nativeCommand) =>
Effect.gen(function* () {
@@ -1386,33 +1386,6 @@ it.effect("replays a server-allocated launch", () =>
}),
);
-it.effect("refuses a launch when the project disables the model's provider instance", () => {
- const harness = makeHarness({
- serverSettings: {
- projectSettingsOverrides: {
- [projectId]: { providerInstances: { [modelSelection.instanceId]: { enabled: false } } },
- },
- },
- });
- return Effect.gen(function* () {
- const launches = yield* ThreadLaunch.ThreadLaunchService;
- const failed = yield* launches
- .launch(
- launchInput({
- command: "command:launch:project-disabled-instance",
- thread: "thread:launch:project-disabled-instance",
- message: "Hello",
- }),
- )
- .pipe(Effect.flip);
- if (failed._tag !== "ThreadManagementProviderInstanceDisabledError") {
- assert.fail(`expected ThreadManagementProviderInstanceDisabledError, got ${failed._tag}`);
- }
- assert.equal(failed.projectId, projectId);
- assert.equal(failed.instanceId, modelSelection.instanceId);
- }).pipe(Effect.provide(harness.layer));
-});
-
it.effect("replays an accepted launch after the project disables the instance", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -1475,59 +1448,6 @@ it.effect("rejects a server-allocated launch replay with a mismatching thread id
}).pipe(Effect.provide(harness.layer));
});
-it.effect("rejects a server-allocated launch receipt from another project", () => {
- const harness = makeHarness();
- return Effect.gen(function* () {
- const launches = yield* ThreadLaunch.ThreadLaunchService;
- const { threadId: _unusedThreadId, ...rest } = launchInput({
- command: "command:launch:allocated-wrong-project",
- thread: "unused",
- message: "Wrong project",
- });
- const first = yield* launches.launch(rest);
- const failed = yield* launches
- .launch({
- ...rest,
- projectId: otherProjectId,
- })
- .pipe(Effect.flip);
- if (failed._tag !== "ThreadLaunchError") {
- assert.fail(`expected ThreadLaunchError, got ${failed._tag}`);
- }
- assert.equal(failed.operation, "resolve-project");
- assert.equal(failed.threadId, first.threadId);
- assert.equal(failed.cause, "Project identity changed.");
- }).pipe(Effect.provide(harness.layer));
-});
-
-it.effect("rejects a server-allocated launch retry after the thread is deleted", () => {
- const harness = makeHarness();
- return Effect.gen(function* () {
- const launches = yield* ThreadLaunch.ThreadLaunchService;
- const threads = yield* ThreadManagement.ThreadManagementService;
- const { threadId: _unusedThreadId, ...rest } = launchInput({
- command: "command:launch:allocated-deleted",
- thread: "unused",
- message: "Deleted before retry",
- });
- const first = yield* launches.launch(rest);
- yield* threads.dispatch({
- type: "thread.delete",
- commandId: CommandId.make("command:launch:allocated-deleted:delete"),
- threadId: first.threadId,
- });
- const failed = yield* launches.launch(rest).pipe(Effect.flip);
- if (failed._tag !== "ThreadLaunchError") {
- assert.fail(`expected ThreadLaunchError, got ${failed._tag}`);
- }
- assert.equal(failed.operation, "create-thread");
- assert.equal(failed.threadId, first.threadId);
- assert.equal(failed.cause, "Thread not found.");
- const shells = yield* threads.listProjectThreads({ projectId, includeSubagents: true });
- assert.equal(shells.length, 0);
- }).pipe(Effect.provide(harness.layer));
-});
-
it.effect("does not treat an unrelated accepted command receipt as a launch", () => {
const harness = makeHarness();
return Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.test.ts b/apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.test.ts
index aa6a4217eb9..de8fee88508 100644
--- a/apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.test.ts
@@ -125,32 +125,6 @@ describe("ThreadLiveEventCoalescer", () => {
expect(coalesceLiveToolUpdatedEvents(events).map((event) => event.sequence)).toEqual([2, 3, 4]);
});
- it.effect("fails and clears pending updates when their serialized payload fills the budget", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const first = makeToolActivity(1);
- const coalescer = yield* makeThreadLiveEventCoalescer({
- coalesceWindow: "500 millis",
- maxSerializedBytes: Buffer.byteLength(encodeEvent(first)),
- });
- yield* coalescer.offer(first);
- expect(yield* coalescer.usage).toEqual({
- retainedItems: 1,
- retainedSerializedBytes: Buffer.byteLength(encodeEvent(first)),
- });
-
- const overflow = yield* coalescer.offer(makeToolActivity(2)).pipe(Effect.result);
- expect(overflow._tag).toBe("Failure");
- yield* coalescer.closed;
- expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
- const marker = yield* coalescer.offer({ kind: "synchronized" }).pipe(Effect.result);
- expect(marker._tag).toBe("Failure");
- const delivered = yield* coalescer.stream.pipe(Stream.runCollect, Effect.result);
- expect(delivered._tag).toBe("Failure");
- }),
- ),
- );
-
it.effect("keeps the flush timer alive when an offer's shorter scope closes", () =>
Effect.scoped(
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts
index 9fe58f9f9b2..8d1f613180a 100644
--- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts
@@ -18,7 +18,6 @@ import * as Layer from "effect/Layer";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
-import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
import * as CommandReceiptStore from "./CommandReceiptStore.ts";
@@ -30,43 +29,6 @@ const layerReceiptsTest = CommandReceiptStore.layer.pipe(
Layer.provide(SqlitePersistence.layerMemory),
);
-const layerThreadManagementTest = (settingsLayer: ReturnType<typeof ServerSettings.layerTest>) =>
- ThreadManagementService.layer.pipe(
- Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
- Layer.provide(Layer.mock(Orchestrator.OrchestratorV2)({})),
- Layer.provide(settingsLayer),
- Layer.provide(layerReceiptsTest),
- );
-
-it.effect("refuses a new turn when the project effectively disables the instance", () => {
- const projectId = ProjectId.make("project:thread-management:gate-disabled");
- const instanceId = ProviderInstanceId.make("codex_work");
- const commandId = CommandId.make("command:thread-management:gate-disabled");
- const layerTest = layerThreadManagementTest(
- ServerSettings.layerTest({
- providerInstances: { [instanceId]: { driver: "codex", enabled: true } },
- projectSettingsOverrides: {
- [projectId]: { providerInstances: { [instanceId]: { enabled: false } } },
- },
- }),
- );
-
- return Effect.gen(function* () {
- const threads = yield* ThreadManagementService.ThreadManagementService;
- const error = yield* Effect.flip(
- threads.assertProviderInstanceEnabled({ projectId, commandId, instanceId }),
- );
-
- expect(error).toBeInstanceOf(
- ThreadManagementService.ThreadManagementProviderInstanceDisabledError,
- );
- expect(error).toMatchObject({ projectId, instanceId });
- expect(error.message).toBe(
- `Provider instance "${instanceId}" is disabled for project ${projectId}.`,
- );
- }).pipe(Effect.provide(layerTest));
-});
-
const layerDispatchChokepointTest =
(settingsLayer: ReturnType<typeof ServerSettings.layerTest>) => (dispatched: Array<string>) =>
ThreadManagementService.layer.pipe(
@@ -185,39 +147,6 @@ it.effect(
},
);
-it.effect("classifies projection infrastructure failures separately from a missing thread", () => {
- const projectId = ProjectId.make("project:thread-management:projection-failure");
- const threadId = ThreadId.make("thread:thread-management:projection-failure");
- const infrastructureCause = new Error("sqlite read failed");
- const projectionError = new Orchestrator.OrchestratorProjectionError({
- threadId,
- cause: infrastructureCause,
- });
- const layerTest = ThreadManagementService.layer.pipe(
- Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
- Layer.provide(
- Layer.mock(Orchestrator.OrchestratorV2)({
- getThreadProjection: () => Effect.fail(projectionError),
- }),
- ),
- Layer.provide(ServerSettings.layerTest()),
- Layer.provide(layerReceiptsTest),
- );
-
- return Effect.gen(function* () {
- const service = yield* ThreadManagementService.ThreadManagementService;
- const error = yield* Effect.flip(service.getProjectThread({ projectId, threadId }));
-
- expect(error).toBeInstanceOf(ThreadManagementService.ThreadManagementProjectionLoadError);
- expect(error).toMatchObject({
- projectId,
- threadId,
- cause: projectionError,
- });
- expect(error.message).toBe(`Unable to load thread ${threadId} in project ${projectId}.`);
- }).pipe(Effect.provide(layerTest));
-});
-
it.effect("uses thread-not-found only after a projection loads outside the project", () => {
const projectId = ProjectId.make("project:thread-management:requested");
const otherProjectId = ProjectId.make("project:thread-management:other");
@@ -250,37 +179,6 @@ it.effect("uses thread-not-found only after a projection loads outside the proje
}).pipe(Effect.provide(layerTest));
});
-it.effect("preserves failed legacy materialization when reading checkpoint context", () => {
- const threadId = ThreadId.make("thread:thread-management:checkpoint-import-failure");
- const importError = new LegacyV1ThreadImporter.LegacyV1ThreadImportError({
- threadId,
- operation: "hydrate transcript for",
- cause: new Error("checkpoint import failed"),
- });
- const layerTest = ThreadManagementService.layerWithLegacyImporter.pipe(
- Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
- Layer.provide(
- Layer.mergeAll(
- Layer.mock(Orchestrator.OrchestratorV2)({
- getCheckpointContext: () =>
- Effect.succeed({ runs: [], checkpointScopes: [], checkpoints: [] }),
- }),
- Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
- ensureTranscript: () => Effect.fail(importError),
- }),
- ),
- ),
- Layer.provide(ServerSettings.layerTest()),
- Layer.provide(layerReceiptsTest),
- );
- return Effect.gen(function* () {
- const service = yield* ThreadManagementService.ThreadManagementService;
- const error = yield* service.getCheckpointContext(threadId).pipe(Effect.flip);
- expect(error).toBeInstanceOf(Orchestrator.OrchestratorProjectionError);
- expect(error).toMatchObject({ threadId, cause: importError });
- }).pipe(Effect.provide(layerTest));
-});
-
it.effect("waitForThread follows a restart continuation instead of the cut run", () =>
Effect.gen(function* () {
const projectId = ProjectId.make("project:thread-management:wait-restart");
diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts
index e1e6a6583e7..2a884d19d3f 100644
--- a/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts
@@ -7,9 +7,6 @@ import {
ChatAttachmentId,
CommandId,
EventId,
- MessageId,
- ProjectId,
- ProviderInstanceId,
RuntimeRequestId,
ThreadId,
TurnItemId,
@@ -29,7 +26,7 @@ import {
OrchestratorDispatchError,
} from "./Orchestrator.ts";
import * as ThreadManagementService from "./ThreadManagementService.ts";
-import { dispatchCommand, sendToThread } from "./ThreadMessageIntake.ts";
+import { dispatchCommand } from "./ThreadMessageIntake.ts";
const layerIntakeTest = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-question-intake-",
@@ -92,41 +89,6 @@ const answeredRespondEvents = (input: {
},
];
-const textOnlyRespondEvents = (input: {
- readonly threadId: ThreadId;
- readonly requestId: string;
-}): OrchestrationV2StoredEvent[] => [
- {
- sequence: 1,
- commandId: null,
- event: {
- id: EventId.make("evt-recorded-answer"),
- type: "turn-item.updated",
- threadId: input.threadId,
- occurredAt: NOW,
- payload: {
- id: TurnItemId.make("item-recorded-answer"),
- type: "user_input_request",
- threadId: input.threadId,
- runId: null,
- nodeId: null,
- providerThreadId: null,
- providerTurnId: null,
- nativeItemRef: null,
- parentItemId: null,
- ordinal: 1,
- status: "completed",
- title: null,
- startedAt: null,
- completedAt: NOW,
- updatedAt: NOW,
- requestId: RuntimeRequestId.make(input.requestId),
- questions: [],
- },
- },
- },
-];
-
it.effect("claims question uploads and passes readable paths through the V2 request command", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
@@ -165,71 +127,6 @@ it.effect("claims question uploads and passes readable paths through the V2 requ
}).pipe(Effect.provide(layerIntakeTest)),
);
-it.effect("rolls back earlier question claims when a later pending upload is missing", () =>
- Effect.gen(function* () {
- const config = yield* ServerConfig.ServerConfig;
- const threadId = ThreadId.make("thread-q-fail");
- const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
- const existingId = ChatAttachmentId.make("thread-q-fail-00000000-0000-4000-8000-000000000001");
- NodeFS.writeFileSync(
- NodePath.join(config.attachmentsDir, `${pendingId}.png`),
- new Uint8Array([1, 2, 3]),
- );
- NodeFS.writeFileSync(
- NodePath.join(config.attachmentsDir, `${existingId}.png`),
- new Uint8Array([9, 9, 9, 9]),
- );
- const captured: OrchestrationV2ServerCommand[] = [];
- const result = yield* dispatchCommand({
- type: "runtime-request.respond",
- commandId: CommandId.make("answer-missing-pending"),
- threadId,
- requestId: RuntimeRequestId.make("request-missing-pending"),
- answers: { q1: ["one"], q2: ["two"] },
- attachmentsByQuestionId: {
- q1: [
- {
- type: "image",
- id: existingId,
- name: "keep.png",
- mimeType: "image/png",
- sizeBytes: 4,
- },
- {
- type: "image",
- id: pendingId,
- name: "screen.png",
- mimeType: "image/png",
- sizeBytes: 3,
- },
- ],
- q2: [
- {
- type: "image",
- id: ChatAttachmentId.make(createPendingAttachmentId()!),
- name: "gone.png",
- mimeType: "image/png",
- sizeBytes: 3,
- },
- ],
- },
- }).pipe(Effect.provide(layerFailingDispatch(captured)), Effect.result);
- expect(result._tag).toBe("Failure");
- if (result._tag === "Failure") {
- expect(result.failure._tag).toBe("AttachmentClaimError");
- }
- expect(captured).toHaveLength(0);
- expect(NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toEqual(
- Buffer.from([1, 2, 3]),
- );
- expect(
- NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
- entry.startsWith("thread-q-fail-"),
- ),
- ).toEqual([`${existingId}.png`]);
- }).pipe(Effect.provide(layerIntakeTest)),
-);
-
it.effect("retains claimed copies when dispatch failure may have been accepted", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
@@ -380,166 +277,6 @@ it.effect("releases claimed copies when dispatch replays an earlier accepted res
}).pipe(Effect.provide(layerIntakeTest)),
);
-it.effect("releases claimed copies when the recorded answer was text-only", () =>
- Effect.gen(function* () {
- const config = yield* ServerConfig.ServerConfig;
- const threadId = ThreadId.make("thread-text-only-answer");
- const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
- NodeFS.writeFileSync(
- NodePath.join(config.attachmentsDir, `${pendingId}.png`),
- new Uint8Array([1, 2, 3]),
- );
- const storedEvents = textOnlyRespondEvents({
- threadId,
- requestId: "request-text-only",
- });
- const result = yield* dispatchCommand({
- type: "runtime-request.respond",
- commandId: CommandId.make("answer-text-only"),
- threadId,
- requestId: RuntimeRequestId.make("request-text-only"),
- answers: { q: ["one"] },
- attachmentsByQuestionId: {
- q: [
- {
- type: "image",
- id: pendingId,
- name: "screen.png",
- mimeType: "image/png",
- sizeBytes: 3,
- },
- ],
- },
- }).pipe(
- Effect.provide(
- Layer.mock(ThreadManagementService.ThreadManagementService)({
- dispatch: () => Effect.succeed({ sequence: 1, storedEvents }),
- }),
- ),
- Effect.result,
- );
- expect(result._tag).toBe("Success");
- expect(
- NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
- entry.startsWith("thread-text-only-answer-"),
- ),
- ).toEqual([]);
- expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
- }).pipe(Effect.provide(layerIntakeTest)),
-);
-
-it.effect("retains claimed copies referenced by a fresh recorded answer", () =>
- Effect.gen(function* () {
- const config = yield* ServerConfig.ServerConfig;
- const threadId = ThreadId.make("thread-fresh-answer");
- const firstId = ChatAttachmentId.make(createPendingAttachmentId()!);
- const secondId = ChatAttachmentId.make(createPendingAttachmentId()!);
- NodeFS.writeFileSync(
- NodePath.join(config.attachmentsDir, `${firstId}.png`),
- new Uint8Array([1, 2, 3]),
- );
- NodeFS.writeFileSync(
- NodePath.join(config.attachmentsDir, `${secondId}.png`),
- new Uint8Array([7, 7]),
- );
- const result = yield* dispatchCommand({
- type: "runtime-request.respond",
- commandId: CommandId.make("answer-fresh"),
- threadId,
- requestId: RuntimeRequestId.make("request-fresh"),
- answers: { q1: ["one"], q2: ["two"] },
- attachmentsByQuestionId: {
- q1: [
- {
- type: "image",
- id: firstId,
- name: "one.png",
- mimeType: "image/png",
- sizeBytes: 3,
- },
- ],
- q2: [
- {
- type: "image",
- id: secondId,
- name: "two.png",
- mimeType: "image/png",
- sizeBytes: 2,
- },
- ],
- },
- }).pipe(
- Effect.provide(
- Layer.mock(ThreadManagementService.ThreadManagementService)({
- dispatch: (command) =>
- Effect.succeed({
- sequence: 1,
- storedEvents: answeredRespondEvents({
- threadId,
- requestId: "request-fresh",
- attachmentsByQuestionId:
- command.type === "runtime-request.respond"
- ? (command.attachmentsByQuestionId ?? {})
- : {},
- }),
- }),
- }),
- ),
- Effect.result,
- );
- expect(result._tag).toBe("Success");
- expect(
- NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
- entry.startsWith("thread-fresh-answer-"),
- ),
- ).toHaveLength(2);
- }).pipe(Effect.provide(layerIntakeTest)),
-);
-
-it.effect("releases claimed copies when preparation dies with a defect", () =>
- Effect.gen(function* () {
- const config = yield* ServerConfig.ServerConfig;
- const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
- NodeFS.writeFileSync(
- NodePath.join(config.attachmentsDir, `${pendingId}.png`),
- new Uint8Array([1, 2, 3]),
- );
- const poisoned = {
- get id(): string {
- throw new Error("poisoned");
- },
- };
- const captured: OrchestrationV2ServerCommand[] = [];
- const result = yield* dispatchCommand({
- type: "runtime-request.respond",
- commandId: CommandId.make("answer-defect"),
- threadId: ThreadId.make("thread-defect"),
- requestId: RuntimeRequestId.make("request-defect"),
- answers: { q1: ["one"], q2: ["two"] },
- attachmentsByQuestionId: {
- q1: [
- {
- type: "image",
- id: pendingId,
- name: "screen.png",
- mimeType: "image/png",
- sizeBytes: 3,
- },
- ],
- q2: [poisoned] as never,
- },
- }).pipe(Effect.provide(layerFailingDispatch(captured)), Effect.exit);
- expect(result._tag).toBe("Failure");
- expect(captured).toHaveLength(0);
- expect(
- NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
- entry.startsWith("thread-defect-"),
- ),
- ).toEqual([]);
- expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
- }).pipe(Effect.provide(layerIntakeTest)),
-);
-
it.effect("a retried response re-claims the preserved pending uploads", () =>
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
@@ -622,79 +359,3 @@ it.effect("a retried response re-claims the preserved pending uploads", () =>
).toHaveLength(2);
}).pipe(Effect.provide(layerIntakeTest)),
);
-
-it.effect("applies the image budget across all questions before dispatch", () =>
- Effect.gen(function* () {
- const attachments = Array.from({ length: 5 }, (_, index) => ({
- type: "image" as const,
- id: ChatAttachmentId.make(`existing-budget-${index}`),
- name: `${index}.png`,
- mimeType: "image/png",
- sizeBytes: 10 * 1024 * 1024,
- }));
- const captured: OrchestrationV2ServerCommand[] = [];
- const result = yield* Effect.exit(
- dispatchCommand({
- type: "runtime-request.respond",
- commandId: CommandId.make("command-image-budget"),
- threadId: ThreadId.make("thread-image-budget"),
- requestId: RuntimeRequestId.make("question-image-budget"),
- answers: {},
- attachmentsByQuestionId: { q1: attachments, q2: attachments },
- }).pipe(Effect.provide(layerFailingDispatch(captured))),
- );
- expect(result._tag).toBe("Failure");
- if (result._tag === "Failure") expect(String(result.cause)).toContain("80 MiB");
- expect(captured).toEqual([]);
- }).pipe(Effect.provide(layerIntakeTest)),
-);
-
-it.effect("releases claimed copies when a project disables the message's provider instance", () =>
- Effect.gen(function* () {
- const config = yield* ServerConfig.ServerConfig;
- const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
- NodeFS.writeFileSync(
- NodePath.join(config.attachmentsDir, `${pendingId}.png`),
- new Uint8Array([1, 2, 3]),
- );
- const result = yield* sendToThread({
- projectId: ProjectId.make("project-disabled-send"),
- commandId: CommandId.make("command-disabled-send"),
- threadId: ThreadId.make("thread-disabled-send"),
- messageId: MessageId.make("message-disabled-send"),
- text: "Hello",
- attachments: [
- {
- type: "image",
- id: pendingId,
- name: "screen.png",
- mimeType: "image/png",
- sizeBytes: 3,
- },
- ],
- mode: "auto",
- createdBy: "user",
- creationSource: "web",
- }).pipe(
- Effect.provide(
- Layer.mock(ThreadManagementService.ThreadManagementService)({
- sendToThread: (input) =>
- Effect.fail(
- new ThreadManagementService.ThreadManagementProviderInstanceDisabledError({
- projectId: input.projectId,
- instanceId: ProviderInstanceId.make("codex"),
- }),
- ),
- }),
- ),
- Effect.result,
- );
- expect(result._tag).toBe("Failure");
- expect(
- NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
- entry.startsWith("thread-disabled-send-"),
- ),
- ).toEqual([]);
- expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
- }).pipe(Effect.provide(layerIntakeTest)),
-);
diff --git a/apps/server/src/orchestration-v2/ThreadSearch.test.ts b/apps/server/src/orchestration-v2/ThreadSearch.test.ts
index 7ea506c7cab..f12355a49e5 100644
--- a/apps/server/src/orchestration-v2/ThreadSearch.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadSearch.test.ts
@@ -178,30 +178,6 @@ it.layer(layerTest)("ThreadSearch", (it) => {
assert.deepEqual((yield* search.search({ query: "ne%le" })).matches, []);
}),
);
-
- it.effect("reports an unreadable match as a decode failure", () =>
- Effect.gen(function* () {
- const projections = yield* ProjectionStore.ProjectionStoreV2;
- const search = yield* ThreadSearch.ThreadSearch;
- const sql = yield* SqlClient.SqlClient;
- const project = ProjectId.make("project:search-corrupt");
- const threadId = ThreadId.make("thread:corrupt");
- yield* createProject(project);
- yield* Effect.forEach(
- [thread(threadId, project), message(threadId, "corrupt", "user", "20260927")],
- projections.apply,
- { discard: true },
- );
- yield* sql`
- UPDATE orchestration_v2_projection_messages
- SET payload_json = json_set(payload_json, '$.text', 20260927)
- WHERE message_id = 'corrupt'
- `;
-
- const error = yield* Effect.flip(search.search({ query: "0260927" }));
- assert.equal(error.operation, "decode");
- }),
- );
});
it.effect("searches on the reader worker while the writer is busy", () =>
diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
index 7808f79a857..10caf988e47 100644
--- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
@@ -724,31 +724,6 @@ describe("ThreadSettlementServiceV2 worker", () => {
),
);
- it.effect("dispatches the last activity time with the v2 snapshot guard", () =>
- Effect.scoped(
- Effect.gen(function* () {
- yield* TestClock.setTime(Date.parse(NOW));
- const thread = makeThread("inactive-open-pr", {
- branch: "feature",
- latestRunCompletedAt: DateTime.makeUnsafe("2026-08-25T00:00:00.000Z"),
- });
- const fixture = yield* makeHarness({
- snapshot: makeSnapshot([thread]),
- settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 2 },
- branchPullRequest: () => Effect.succeed(makeBranchPullRequest("open")),
- });
- yield* Effect.gen(function* () {
- const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
- yield* startHarness(service, fixture.activation, fixture.snapshotReads);
- const commands = yield* Ref.get(fixture.commands);
- expect(commands).toHaveLength(1);
- expect(commands[0]?.settledAt).toEqual(thread.latestRunCompletedAt);
- expect(commands[0]?.snapshotAt).toEqual(thread.updatedAt);
- }).pipe(Effect.provide(fixture.layer));
- }),
- ),
- );
-
it.effect("reevaluates immediately after a pull request merge", () =>
Effect.scoped(
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/ThreadStream.test.ts b/apps/server/src/orchestration-v2/ThreadStream.test.ts
index 17513a5b3c8..438a24743a7 100644
--- a/apps/server/src/orchestration-v2/ThreadStream.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadStream.test.ts
@@ -126,17 +126,6 @@ describe("decideThreadResume", () => {
});
});
- it("falls back to a snapshot when the event count exceeds the bound", () => {
- expect(
- decideThreadResume({
- afterSequence: 10,
- highWater: 20_000,
- replayEventCount: THREAD_RESUME_MAX_REPLAY_EVENTS + 1,
- replayEncodedBytes: 1,
- }),
- ).toEqual({ mode: "snapshot" });
- });
-
it("falls back to a snapshot when encoded replay bytes exceed the bound", () => {
expect(
decideThreadResume({
diff --git a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts
index 5e0fcf06810..78ca87f8abf 100644
--- a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts
@@ -278,34 +278,6 @@ describe("ThreadTitleRegenerationService", () => {
}),
);
- it.effect("keeps the current title when generation returns the fallback", () =>
- Effect.gen(function* () {
- const harness = makeHarness({
- generateTitle: () => Effect.succeed({ title: "New thread" }),
- });
- yield* Effect.gen(function* () {
- const threads = yield* ThreadManagement.ThreadManagementService;
- const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
- const threadId = yield* createThread({
- command: "command:title:fallback:create",
- thread: "thread:title:fallback",
- });
- yield* dispatchUserMessage({
- command: "command:title:fallback:message",
- threadId,
- text: "Some conversation",
- });
- const requestId = yield* armRegeneration({ command: "command:title:fallback:1", threadId });
-
- yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
-
- const projection = yield* threads.getThreadProjection(threadId);
- assert.equal(projection.thread.title, "Seed title");
- assert.isNotOk(projection.thread.titleRegeneration);
- }).pipe(Effect.provide(harness.layer));
- }),
- );
-
it.effect("clears the marker and keeps the title when generation fails", () =>
Effect.gen(function* () {
const harness = makeHarness({
@@ -334,30 +306,4 @@ describe("ThreadTitleRegenerationService", () => {
}).pipe(Effect.provide(harness.layer));
}),
);
-
- it.effect("completes without generating when the initial message is unavailable", () =>
- Effect.gen(function* () {
- const harness = makeHarness();
- yield* Effect.gen(function* () {
- const threads = yield* ThreadManagement.ThreadManagementService;
- const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
- const threadId = yield* createThread({
- command: "command:title:missing:create",
- thread: "thread:title:missing",
- });
- const requestId = yield* armRegeneration({ command: "command:title:missing:1", threadId });
-
- yield* titleRegeneration.execute({
- threadId,
- requestId,
- kind: { type: "initial", messageId: MessageId.make("message:title:missing") },
- });
-
- assert.equal(harness.generateThreadTitle.mock.calls.length, 0);
- const projection = yield* threads.getThreadProjection(threadId);
- assert.equal(projection.thread.title, "Seed title");
- assert.isNotOk(projection.thread.titleRegeneration);
- }).pipe(Effect.provide(harness.layer));
- }),
- );
});
diff --git a/apps/server/src/orchestration-v2/ThreadTransportPerformance.test.ts b/apps/server/src/orchestration-v2/ThreadTransportPerformance.test.ts
index 205f9a33e71..7eb434176a1 100644
--- a/apps/server/src/orchestration-v2/ThreadTransportPerformance.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadTransportPerformance.test.ts
@@ -1,13 +1,9 @@
import {
EventId,
OrchestrationV2RpcSchemas,
- ProjectId,
- ProviderInstanceId,
ThreadId,
TurnItemId,
- type OrchestrationV2ProjectedTurnItem,
type OrchestrationV2DomainEvent,
- type OrchestrationV2ThreadProjection,
type OrchestrationV2ThreadStreamItem,
type OrchestrationV2TurnItem,
} from "@t3tools/contracts";
@@ -16,21 +12,12 @@ import * as Schema from "effect/Schema";
import type * as RpcMessage from "effect/rpc/RpcMessage";
import { describe, expect, it } from "vite-plus/test";
-import { buildBoundedThreadStreamSnapshot } from "./ThreadStream.ts";
-import { buildBoundedThreadProjection } from "./threadHistoryPaging.ts";
import { projectDomainEventForWire } from "./WireProjection.ts";
-const SNAPSHOT_SEQUENCE = 600;
-const ROW_COUNT = 600;
const OUTPUT_BYTES_PER_ROW = 8_192;
const NOW = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
const THREAD_ID = ThreadId.make("thread-perf");
-const PROVIDER_INSTANCE_ID = ProviderInstanceId.make("codex");
-const HISTORICAL_FULL_SNAPSHOT_APPLICATION_BYTES = 10_375_079;
-const FULL_SNAPSHOT_RPC_JSON_BYTES = 10_375_121;
-const PRE_OMISSION_BOUNDED_SNAPSHOT_RPC_JSON_BYTES = 1_038_647;
-const MAX_PROJECTED_BOUNDED_SNAPSHOT_RPC_JSON_BYTES = 131_072;
const PRE_OMISSION_COMMAND_EVENT_RPC_JSON_BYTES = 8_790;
const MAX_PROJECTED_COMMAND_EVENT_RPC_JSON_BYTES = 1_024;
@@ -74,69 +61,6 @@ function makeCommandItem(index: number): OrchestrationV2TurnItem {
};
}
-function makeProjection(): OrchestrationV2ThreadProjection {
- const visibleTurnItems: OrchestrationV2ProjectedTurnItem[] = Array.from(
- { length: ROW_COUNT },
- (_, index) => {
- const item = makeCommandItem(index);
- return {
- position: index,
- visibility: "local",
- sourceThreadId: THREAD_ID,
- sourceItemId: item.id,
- item,
- };
- },
- );
-
- return {
- thread: {
- id: THREAD_ID,
- projectId: ProjectId.make("project-perf"),
- title: "Thread",
- providerInstanceId: PROVIDER_INSTANCE_ID,
- modelSelection: { instanceId: PROVIDER_INSTANCE_ID, model: "gpt-5" },
- runtimeMode: "full-access",
- interactionMode: "default",
- branch: null,
- worktreePath: null,
- activeProviderThreadId: null,
- lineage: {
- parentThreadId: null,
- relationshipToParent: null,
- rootThreadId: THREAD_ID,
- },
- forkedFrom: null,
- createdBy: "user",
- creationSource: "web",
- createdAt: NOW,
- updatedAt: NOW,
- archivedAt: null,
- deletedAt: null,
- settledOverride: null,
- settledAt: null,
- lastVisitedAt: null,
- },
- runs: [],
- attempts: [],
- nodes: [],
- subagents: [],
- providerSessions: [],
- providerThreads: [],
- providerTurns: [],
- runtimeRequests: [],
- messages: [],
- plans: [],
- turnItems: visibleTurnItems.map((row) => row.item),
- checkpointScopes: [],
- checkpoints: [],
- contextHandoffs: [],
- contextTransfers: [],
- visibleTurnItems,
- updatedAt: NOW,
- };
-}
-
function makeTurnItemEvent(item: OrchestrationV2TurnItem): OrchestrationV2DomainEvent {
return {
id: EventId.make(`event-${item.id}`),
@@ -148,51 +72,6 @@ function makeTurnItemEvent(item: OrchestrationV2TurnItem): OrchestrationV2Domain
}
describe("thread transport payload budget", () => {
- it("records full, bounded, and payload-omitting snapshot improvements", () => {
- const projection = makeProjection();
- const historicalFullSnapshot: OrchestrationV2ThreadStreamItem = {
- kind: "snapshot",
- snapshotSequence: SNAPSHOT_SEQUENCE,
- projection,
- };
- const preOmissionBounded = buildBoundedThreadProjection({
- projection,
- snapshotSequence: SNAPSHOT_SEQUENCE,
- });
- const preOmissionBoundedSnapshot: OrchestrationV2ThreadStreamItem = {
- kind: "snapshot",
- snapshotSequence: SNAPSHOT_SEQUENCE,
- projection: preOmissionBounded.projection,
- historyCursor: preOmissionBounded.historyCursor,
- hasMoreHistory: preOmissionBounded.hasMoreHistory,
- latestLocalTurnOrdinal: preOmissionBounded.latestLocalTurnOrdinal,
- payloadBudgetExceeded: preOmissionBounded.payloadBudgetExceeded,
- };
- const projectedBoundedSnapshot = buildBoundedThreadStreamSnapshot({
- projection,
- snapshotSequence: SNAPSHOT_SEQUENCE,
- });
-
- const historicalApplicationBytes = encodedBytes(historicalFullSnapshot);
- const fullRpcJsonBytes = encodedThreadStreamChunkBytes(historicalFullSnapshot);
- const preOmissionBoundedRpcJsonBytes = encodedThreadStreamChunkBytes(
- preOmissionBoundedSnapshot,
- );
- const projectedBoundedRpcJsonBytes = encodedThreadStreamChunkBytes(projectedBoundedSnapshot);
-
- expect(historicalApplicationBytes).toBe(HISTORICAL_FULL_SNAPSHOT_APPLICATION_BYTES);
- expect(fullRpcJsonBytes).toBe(FULL_SNAPSHOT_RPC_JSON_BYTES);
- expect(preOmissionBoundedRpcJsonBytes).toBe(PRE_OMISSION_BOUNDED_SNAPSHOT_RPC_JSON_BYTES);
- expect(projectedBoundedRpcJsonBytes).toBeLessThanOrEqual(
- MAX_PROJECTED_BOUNDED_SNAPSHOT_RPC_JSON_BYTES,
- );
- expect(projectedBoundedRpcJsonBytes / fullRpcJsonBytes).toBeLessThanOrEqual(0.02);
- expect(preOmissionBoundedSnapshot.projection.visibleTurnItems).toHaveLength(60);
- expect(projectedBoundedSnapshot.projection.visibleTurnItems).toHaveLength(75);
- expect(projectedBoundedSnapshot.hasMoreHistory).toBe(true);
- expect(projectedBoundedSnapshot.payloadBudgetExceeded).toBe(false);
- });
-
it("omits command output from a live event without changing persisted source data", () => {
const sourceItem = makeCommandItem(0);
const sourceEvent = makeTurnItemEvent(sourceItem);
diff --git a/apps/server/src/orchestration-v2/WireProjection.test.ts b/apps/server/src/orchestration-v2/WireProjection.test.ts
index 12256809554..17213d37810 100644
--- a/apps/server/src/orchestration-v2/WireProjection.test.ts
+++ b/apps/server/src/orchestration-v2/WireProjection.test.ts
@@ -94,23 +94,6 @@ describe("orchestration V2 wire projection", () => {
expect(item.output.data).toBe("private-image-data");
});
- it("preserves provider notices in bounded items and live events", () => {
- const item = {
- ...base,
- type: "system_notice" as const,
- message: "Safeguards flagged this message. Switched to Opus 4.8.",
- };
- expect(projectTurnItemForWire(item)).toEqual(item);
- const event = {
- id: EventId.make("notice-wire-event"),
- type: "turn-item.updated" as const,
- threadId: item.threadId,
- occurredAt: item.updatedAt,
- payload: item,
- };
- expect(projectDomainEventForWire(event)).toEqual(event);
- });
-
it("keeps transcript bodies out of shell rows", () => {
const now = DateTime.makeUnsafe("2026-08-13T00:00:00.000Z");
const threadId = ThreadId.make("thread-shell-budget");
@@ -166,17 +149,6 @@ describe("orchestration V2 wire projection", () => {
expect(JSON.stringify(shell).length).toBeLessThan(2_000);
});
- it("omits oversized dynamic tool results without mutating persistence data", () => {
- const output = { content: [{ type: "text", text: "first line\n" + "x".repeat(100_000) }] };
- const item = { ...base, output } satisfies OrchestrationV2TurnItem;
- const projected = projectTurnItemForWire(item);
-
- expect(item.output).toBe(output);
- expect(projected).not.toBe(item);
- expect(JSON.stringify(projected).length).toBeLessThan(2_000);
- expect(projected).not.toHaveProperty("output");
- });
-
it("omits even small dynamic tool results while retaining input", () => {
const item = { ...base, output: { ok: true } } satisfies OrchestrationV2TurnItem;
expect(projectTurnItemForWire(item)).toEqual({ ...base, outputOmitted: true });
diff --git a/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.test.ts b/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.test.ts
index 40359ce02b2..3b2351b28a1 100644
--- a/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.test.ts
+++ b/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.test.ts
@@ -114,6 +114,7 @@ it.effect(
}).pipe(Effect.provide(layerTest)),
);
+// regression: #15920 one bad legacy message stopped the server from starting
it.effect("propagates interruption from transcript reads and retry-marker writes", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts
index 0c86a31d169..4ab9e8b6d67 100644
--- a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts
+++ b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts
@@ -124,6 +124,7 @@ describe("evaluatePullRequestWatch", () => {
]);
});
+ // regression: #16208 PR watches burned GitHub's rate limit and gave up
it("does not report passed again for a new passed check where none is required", () => {
const first = evaluatePullRequestWatch(
watch(),
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
index 996abf1494d..9db0564cced 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
@@ -636,50 +636,6 @@ const layerSharedApplicationDataPlaneTest = Layer.mergeAll(
);
it.layer(layerTest)("OrchestrationV2LayerLive", (it) => {
- it.effect("emits model updates separately from provider switches", () =>
- Effect.gen(function* () {
- const orchestrator = yield* Orchestrator.OrchestratorV2;
- const threadId = ThreadId.make("runtime-layer-model-selection-events");
-
- yield* orchestrator.dispatch({
- type: "thread.create",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make("runtime-layer-model-selection-events-create"),
- threadId,
- projectId: ProjectId.make("runtime-layer-model-selection-events-project"),
- title: "Model selection events",
- modelSelection,
- runtimeMode: "full-access",
- interactionMode: "default",
- branch: null,
- worktreePath: null,
- });
-
- const sameInstance = yield* orchestrator.dispatch({
- type: "thread.model-selection.set",
- commandId: CommandId.make("runtime-layer-model-selection-events-update"),
- threadId,
- modelSelection: { ...modelSelection, model: "gpt-5.5" },
- });
- assert.deepEqual(
- sameInstance.storedEvents.map((stored) => stored.event.type),
- ["thread.model-selection-updated"],
- );
-
- const differentInstance = yield* orchestrator.dispatch({
- type: "thread.model-selection.set",
- commandId: CommandId.make("runtime-layer-model-selection-events-switch"),
- threadId,
- modelSelection: { instanceId: alternateInstanceId, model: "gpt-5.5" },
- });
- assert.deepEqual(
- differentInstance.storedEvents.map((stored) => stored.event.type),
- ["thread.provider-switched"],
- );
- }),
- );
-
const seedFailingRollbackThread = (name: string) =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -786,44 +742,6 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => {
}),
);
- it.effect("ignores a late failure from a rollback that a newer one superseded", () =>
- Effect.gen(function* () {
- const orchestrator = yield* Orchestrator.OrchestratorV2;
- const outbox = yield* EffectOutbox.EffectOutboxV2;
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
- const { threadId, rollback } = yield* seedFailingRollbackThread(
- "runtime-rollback-superseded",
- );
-
- const olderCommandId = CommandId.make("runtime-rollback-superseded-older");
- yield* rollback(olderCommandId);
- for (let attempt = 0; attempt < 4; attempt++) {
- yield* worker.drain();
- yield* TestClock.adjust("30 seconds");
- }
- const newerCommandId = CommandId.make("runtime-rollback-superseded-newer");
- yield* rollback(newerCommandId);
- yield* worker.drain();
-
- const [olderEffect] = yield* outbox.listByCommandId(olderCommandId);
- assert.equal(olderEffect?.status, "failed");
- const superseded = yield* orchestrator.getThreadProjection(threadId);
- assert.isNull(superseded.thread.rollbackFailure);
-
- for (let attempt = 0; attempt < 5; attempt++) {
- yield* TestClock.adjust("30 seconds");
- yield* worker.drain();
- }
- const [newerEffect] = yield* outbox.listByCommandId(newerCommandId);
- assert.equal(newerEffect?.status, "failed");
- const failed = yield* orchestrator.getThreadProjection(threadId);
- assert.deepEqual(failed.thread.rollbackFailure, {
- requestId: newerCommandId,
- message: ROLLBACK_FAILED_MESSAGE,
- });
- }),
- );
-
it.effect("rejects non-ready rollback targets before persisting events or effects", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -2111,67 +2029,6 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
}),
);
- it.effect("persists linked pull requests through projection rebuilds and unlinking", () =>
- Effect.gen(function* () {
- const orchestrator = yield* Orchestrator.OrchestratorV2;
- const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
- const threadId = ThreadId.make("runtime-layer-linked-pull-request-thread");
- const linkedPullRequest = {
- projectId: ProjectId.make("runtime-layer-linked-pull-request-project"),
- repository: "pingdotgg/t3code",
- number: 8160,
- url: "https://github.com/pingdotgg/t3code/pull/8160",
- } as const;
-
- yield* orchestrator.dispatch({
- type: "thread.create",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make("runtime-layer-linked-pull-request-create"),
- threadId,
- projectId: linkedPullRequest.projectId,
- title: "Linked pull request thread",
- modelSelection,
- runtimeMode: "full-access",
- interactionMode: "default",
- branch: null,
- worktreePath: null,
- });
- yield* orchestrator.dispatch({
- type: "thread.metadata.update",
- commandId: CommandId.make("runtime-layer-linked-pull-request-link"),
- threadId,
- linkedPullRequest,
- });
-
- assert.deepEqual(
- (yield* orchestrator.getThreadProjection(threadId)).thread.linkedPullRequest,
- linkedPullRequest,
- );
- const linkedShell = yield* orchestrator.getThreadShell(threadId);
- assert.isNotNull(linkedShell);
- assert.deepEqual(linkedShell.linkedPullRequest, linkedPullRequest);
-
- const rebuilt = yield* maintenance.rebuild;
- assert.isTrue(rebuilt.valid);
- assert.deepEqual(
- (yield* orchestrator.getThreadProjection(threadId)).thread.linkedPullRequest,
- linkedPullRequest,
- );
-
- yield* orchestrator.dispatch({
- type: "thread.metadata.update",
- commandId: CommandId.make("runtime-layer-linked-pull-request-unlink"),
- threadId,
- linkedPullRequest: null,
- });
- assert.isNull((yield* orchestrator.getThreadProjection(threadId)).thread.linkedPullRequest);
- const unlinkedShell = yield* orchestrator.getThreadShell(threadId);
- assert.isNotNull(unlinkedShell);
- assert.isNull(unlinkedShell.linkedPullRequest);
- }),
- );
-
it.effect("keeps the branch pull request when linking another pull request", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -2765,6 +2622,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
}),
);
+ // regression: #21155 watching a pull request again repeated news the thread already got
it.effect("a watch that ends on the comment limit keeps what its last pass saw", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -2888,6 +2746,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
}),
);
+ // regression: #21155 watching a pull request again repeated news the thread already got
it.effect("watching a dismissed stack layer again keeps what its last watch told", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -3736,88 +3595,6 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
}),
);
- it.effect("cancels queued work when a thread is archived", () =>
- Effect.gen(function* () {
- const orchestrator = yield* Orchestrator.OrchestratorV2;
- const threadId = ThreadId.make("runtime-layer-archive-queued-thread");
-
- yield* orchestrator.dispatch({
- type: "thread.create",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make("runtime-layer-archive-queued-create"),
- threadId,
- projectId: ProjectId.make("runtime-layer-archive-queued-project"),
- title: "Archive queued work",
- modelSelection,
- runtimeMode: "full-access",
- interactionMode: "default",
- branch: null,
- worktreePath: "/tmp/runtime-layer-archive-queued",
- });
- yield* orchestrator.dispatch({
- type: "message.dispatch",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make("runtime-layer-archive-queued-active-message"),
- threadId,
- messageId: MessageId.make("runtime-layer-archive-queued-active-message"),
- text: "Keep the provider occupied.",
- attachments: [],
- modelSelection,
- dispatchMode: { type: "start_immediately" },
- });
- yield* orchestrator.dispatch({
- type: "message.dispatch",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make("runtime-layer-archive-queued-next-message"),
- threadId,
- messageId: MessageId.make("runtime-layer-archive-queued-next-message"),
- text: "Do not run this after archive.",
- attachments: [],
- modelSelection,
- dispatchMode: { type: "queue_after_active" },
- });
-
- const beforeArchive = yield* orchestrator.getThreadProjection(threadId);
- const activeRun = beforeArchive.runs.find((run) => run.status === "starting");
- const queuedRun = beforeArchive.runs.find((run) => run.status === "queued");
- assert.isDefined(activeRun);
- assert.isDefined(queuedRun);
-
- yield* orchestrator.dispatch({
- type: "thread.archive",
- commandId: CommandId.make("runtime-layer-archive-queued-archive"),
- threadId,
- });
-
- const archived = yield* orchestrator.getThreadProjection(threadId);
- assert.isNotNull(archived.thread.archivedAt);
- assert.equal(archived.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled");
- assert.equal(
- archived.attempts.find((attempt) => attempt.runId === queuedRun.id)?.status,
- "cancelled",
- );
- assert.equal(archived.nodes.find((node) => node.runId === queuedRun.id)?.status, "cancelled");
- assert.equal(yield* orchestrator.resumeQueuedRuns, 0);
-
- const promoteError = yield* orchestrator
- .dispatch({
- type: "queued-message.promote-to-steer",
- commandId: CommandId.make("runtime-layer-archive-queued-promote"),
- threadId,
- queuedRunId: queuedRun.id,
- targetRunId: activeRun.id,
- })
- .pipe(Effect.flip);
- assert.equal(promoteError._tag, "OrchestratorDispatchError");
-
- const afterPromotion = yield* orchestrator.getThreadProjection(threadId);
- assert.equal(afterPromotion.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled");
- }),
- );
-
it.effect.each([false, true])(
"promotes only one queued run after each terminal run (notification: %s)",
(automatic) =>
@@ -5856,20 +5633,13 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
it.effect.each([
"resume",
"queued-resume",
- "cancel",
"rearm",
"snooze-race",
- "new-message",
"archive",
- "settle",
"replacement",
"manual-snooze",
- "manual-snooze-after-recovery",
"invalid-snooze",
- "snooze-only",
- "snooze-resume",
"cancel-resume-keep-snooze",
- "wake-preserve-resume",
"independent-patches",
"expired-snooze",
"wake",
@@ -6022,15 +5792,8 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
assert.isNull(current.thread.snoozedUntil);
return;
}
- const snooze = [
- "snooze-only",
- "manual-snooze-after-recovery",
- "snooze-resume",
- "wake",
- "cancel-resume-keep-snooze",
- "wake-preserve-resume",
- ].includes(scenario);
- const autoResume = scenario !== "snooze-only" && scenario !== "wake";
+ const snooze = scenario === "wake" || scenario === "cancel-resume-keep-snooze";
+ const autoResume = scenario !== "wake";
const arm = limitRecoveryCommand(shell, autoResume, DateTime.toEpochMillis(now), snooze);
assert(arm?.type === "thread.metadata.update" && arm.limitRecovery != null);
const automaticArm = {
@@ -6106,7 +5869,7 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
});
if (snooze)
assert.equal(DateTime.toEpochMillis(armedShell.snoozedUntil!), Date.parse(resetAt));
- if (scenario === "cancel-resume-keep-snooze" || scenario === "wake-preserve-resume") {
+ if (scenario === "cancel-resume-keep-snooze") {
yield* TestClock.adjust("10 seconds");
yield* orchestrator.dispatch({
type: "thread.metadata.update",
@@ -6115,25 +5878,19 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
limitRecovery: {
runId: run.id,
resetAt,
- autoResume: scenario === "wake-preserve-resume",
- snooze: scenario === "cancel-resume-keep-snooze",
+ autoResume: false,
+ snooze: true,
},
});
armedShell = (yield* orchestrator.getShellSnapshot()).threads.find(
(thread) => thread.id === threadId,
)!;
- if (scenario === "cancel-resume-keep-snooze") {
- assert.equal(DateTime.toEpochMillis(armedShell.snoozedUntil!), Date.parse(resetAt));
- assert.equal(
- DateTime.toEpochMillis(armedShell.snoozedAt!),
- DateTime.toEpochMillis(armedShell.updatedAt),
- );
- assert.isFalse(armedShell.limitRecovery!.autoResume);
- } else {
- assert.isNull(armedShell.snoozedUntil);
- assert.isNull(armedShell.snoozedAt);
- assert.isTrue(armedShell.limitRecovery!.autoResume);
- }
+ assert.equal(DateTime.toEpochMillis(armedShell.snoozedUntil!), Date.parse(resetAt));
+ assert.equal(
+ DateTime.toEpochMillis(armedShell.snoozedAt!),
+ DateTime.toEpochMillis(armedShell.updatedAt),
+ );
+ assert.isFalse(armedShell.limitRecovery!.autoResume);
}
if (scenario === "independent-patches") {
yield* TestClock.adjust("10 seconds");
@@ -6173,7 +5930,7 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
assert.isTrue(armedShell.limitRecovery!.autoResume);
assert.isTrue(armedShell.limitRecovery!.snooze);
}
- if (scenario === "manual-snooze" || scenario === "manual-snooze-after-recovery") {
+ if (scenario === "manual-snooze") {
yield* orchestrator.dispatch({
type: "thread.snooze",
commandId: CommandId.make(`recovery:manual-snooze:${scenario}`),
@@ -6275,7 +6032,7 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
assert.isTrue(current.thread.limitRecovery!.autoResume);
}
- if (scenario === "cancel" || scenario === "rearm")
+ if (scenario === "rearm")
yield* orchestrator.dispatch({
type: "thread.metadata.update",
commandId: CommandId.make(`recovery:cancel:${scenario}`),
@@ -6288,24 +6045,6 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
commandId: CommandId.make(`recovery:archive:${scenario}`),
threadId,
});
- if (scenario === "new-message")
- yield* orchestrator.dispatch({
- type: "message.dispatch",
- commandId: CommandId.make(`recovery:new-message:${scenario}`),
- threadId,
- messageId: MessageId.make(`recovery:new-message:${scenario}`),
- text: "I will continue manually.",
- attachments: [],
- dispatchMode: { type: "defer_start" },
- createdBy: "user",
- creationSource: "web",
- });
- if (scenario === "settle")
- yield* orchestrator.dispatch({
- type: "thread.settle",
- commandId: CommandId.make(`recovery:settle:${scenario}`),
- threadId,
- });
if (scenario === "stop") {
yield* orchestrator.dispatch({
type: "thread.stop",
@@ -6377,8 +6116,6 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
(scenario === "resume" ||
stopBeforeArm ||
scenario === "queued-resume" ||
- scenario === "snooze-resume" ||
- scenario === "wake-preserve-resume" ||
scenario === "independent-patches" ||
scenario === "expired-snooze"
? 1
@@ -6390,8 +6127,6 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
(scenario === "resume" ||
stopBeforeArm ||
scenario === "queued-resume" ||
- scenario === "snooze-resume" ||
- scenario === "wake-preserve-resume" ||
scenario === "independent-patches" ||
scenario === "expired-snooze"
? 1
diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts
index c62e6e8e5b3..3a3fe85ffc4 100644
--- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts
+++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts
@@ -572,13 +572,11 @@ describe("orchestrator replay fixtures", () => {
}),
);
- it.effect.each(
- (["WebFetch", "Write"] as const).flatMap((tool) =>
- (["before root settles", "while root is idle"] as const).flatMap((opens) =>
- (["stopped", "failed"] as const).map((status) => [tool, opens, status] as const),
- ),
- ),
- )(
+ // regression: #16486 a background subagent's tool left open while its parent is idle never settled
+ it.effect.each([
+ ["WebFetch", "while root is idle", "stopped"],
+ ["Write", "before root settles", "failed"],
+ ] as const)(
"ends a background subagent's open %s (opened %s) when its notification is %s",
([tool, opens, notificationStatus]) =>
runFixtureProviderWithRegisteredHarness({
diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
index 820736bc7ee..72aae60c0d0 100644
--- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
+++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
@@ -37,7 +37,6 @@ import * as SqlitePersistence from "../../persistence/Sqlite.ts";
import { CommandPolicyCapabilityUnsupportedError } from "../CommandPolicy.ts";
import {
ClaudeAppendSystemPromptFileError,
- ClaudeAppendSystemPromptMissingValueError,
ClaudeBackgroundWorkBlocksQueryReplacementError,
ClaudeProviderCapabilitiesV2,
} from "../Adapters/ClaudeAdapterV2.ts";
@@ -408,36 +407,15 @@ const waitForIdle = Effect.fn("ProviderSwitchTest.waitForIdle")(function* (
describe("orchestration v2 provider switching", () => {
it.live.each([
"compact-native",
- "compact-fallback",
"compact-legacy",
"large-current-input",
- "screenshot-native",
"screenshot-fallback",
- "screenshot-pair-native",
- "screenshot-pair-fallback",
- "screenshot-eight-native",
- "screenshot-eight-fallback",
- "screenshot-large-model-native",
"screenshot-reported-capacity-native",
- "screenshot-model-change-native",
- "screenshot-option-change-native",
- "screenshot-model-change-retry-native",
"screenshot-option-change-retry-native",
- "prior-images-reasoning-change-replacement-native",
"prior-images-reasoning-change-replacement-small-native",
- "prior-images-reasoning-change-native",
- "prior-images-turn-usage-native",
- "prior-images-turn-usage-replacement-native",
- "prior-images-turn-usage-model-change-native",
- "prior-images-turn-usage-option-change-retry-native",
- "prior-images-reasoning-change-retry-native",
- "prior-images-native",
- "prior-images-fallback",
- "imported-prior-images-native",
"imported-prior-images-fallback",
"prior-images-telemetry-native",
"prior-images-unsent-native",
- "prior-images-replacement-native",
"prior-images-legacy-replacement-native",
"delivery-write-failure",
] as const)("preserves handoffs through %s", (scenario) =>
@@ -852,22 +830,20 @@ describe("orchestration v2 provider switching", () => {
if (scenario.startsWith("screenshot")) {
assert.deepEqual((yield* Ref.get(capturedTurns)).at(-1)!.attachments, screenshots);
}
- if (scenario === "compact-fallback" || scenario === "compact-legacy") {
- if (scenario === "compact-legacy") {
- const { history: _history, ...legacyHandoff } = handoff;
- yield* eventSink.write({
- events: [
- {
- id: EventId.make("legacy-handoff-shape"),
- type: "context-handoff.updated",
- threadId,
- runId: handoff.targetRunId,
- occurredAt: yield* DateTime.now,
- payload: legacyHandoff,
- },
- ],
- });
- }
+ if (scenario === "compact-legacy") {
+ const { history: _history, ...legacyHandoff } = handoff;
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make("legacy-handoff-shape"),
+ type: "context-handoff.updated",
+ threadId,
+ runId: handoff.targetRunId,
+ occurredAt: yield* DateTime.now,
+ payload: legacyHandoff,
+ },
+ ],
+ });
assert.isUndefined(handoff.delivery);
yield* dispatch(3, "Continue after compact", CLAUDE_MODEL_SELECTION);
yield* wait(3);
@@ -1209,10 +1185,6 @@ describe("orchestration v2 provider switching", () => {
it.live.each([
["background work", new ClaudeBackgroundWorkBlocksQueryReplacementError()],
["an unreadable append file", new ClaudeAppendSystemPromptFileError({ path: "missing.md" })],
- [
- "a missing append value",
- new ClaudeAppendSystemPromptMissingValueError({ flag: "--append-system-prompt" }),
- ],
] as const)("keeps the native session after turns refused for %s", ([, refusalCause]) =>
Effect.scoped(
Effect.gen(function* () {
@@ -1307,18 +1279,19 @@ describe("orchestration v2 provider switching", () => {
);
it.live.each(
- (["failed", "interrupted"] as const).flatMap((status) =>
- [false, true].flatMap((queued) =>
- [false, true].flatMap((returning) =>
- [false, true].map(
- (native) =>
- [
- `${status} context ${queued ? "through the queue" : "immediately"} to ${returning ? "a returning" : "a new"} provider via ${native ? "native history" : "text"}`,
- { status, queued, returning, native },
- ] as const,
- ),
- ),
- ),
+ (
+ [
+ ["failed", false, false, false],
+ ["failed", true, true, true],
+ ["interrupted", false, true, false],
+ ["interrupted", true, false, true],
+ ] as const
+ ).map(
+ ([status, queued, returning, native]) =>
+ [
+ `${status} context ${queued ? "through the queue" : "immediately"} to ${returning ? "a returning" : "a new"} provider via ${native ? "native history" : "text"}`,
+ { status, queued, returning, native },
+ ] as const,
),
)("hands off %s", ([, { status, queued, returning, native }]) =>
Effect.scoped(
@@ -2252,10 +2225,9 @@ describe("orchestration v2 provider switching", () => {
),
);
+ // regression: #21314 a queued PR update must follow the provider that took over the thread
it.live.each([
["automatic", "Claude"],
- ["queue.resume", "Claude"],
- ["automatic", "compatible Codex"],
["queue.resume", "compatible Codex"],
] as const)(
"delivers a queued PR update on the current provider through %s (%s)",
@@ -2448,9 +2420,6 @@ describe("orchestration v2 provider switching", () => {
if (compatible) {
assert.equal(executed.nativeThreadId, turns[0]!.nativeThreadId);
assert.isEmpty(after.contextHandoffs);
- if (delivery === "automatic") {
- assert.equal(delivered.providerThreadId, wake.providerThreadId);
- }
}
assert.equal(
after.providerThreads.find((entry) => entry.id === delivered.providerThreadId)
diff --git a/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts
index 4f97583fd3d..d90886835a2 100644
--- a/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts
+++ b/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts
@@ -41,7 +41,6 @@ const CLAUDE_MODEL_SELECTION = {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
} as const;
-const TRANSCRIPT_PATH = `${import.meta.dirname}/fixtures/thread_fork_native/codex_transcript.ndjson`;
const PRIOR_TURN_TRANSCRIPT_PATH = `${import.meta.dirname}/fixtures/thread_fork_native_prior_turn/codex_transcript.ndjson`;
const CLAUDE_TRANSCRIPT_PATH = `${import.meta.dirname}/fixtures/thread_fork_native/claude_transcript.ndjson`;
const CLAUDE_PRIOR_TURN_TRANSCRIPT_PATH = `${import.meta.dirname}/fixtures/thread_fork_native_prior_turn/claude_transcript.ndjson`;
@@ -100,7 +99,7 @@ const makeCheckpointWorkspace = Effect.gen(function* () {
return cwd;
});
-function readTranscript(transcriptPath: string = TRANSCRIPT_PATH) {
+function readTranscript(transcriptPath: string) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const text = yield* fs.readFileString(transcriptPath);
@@ -139,185 +138,6 @@ function userAndAssistantText(
}
describe("orchestration V2 thread fork", () => {
- it.effect(
- "creates an idle app fork and resolves it with Codex native thread/fork on first dispatch",
- () =>
- Effect.gen(function* () {
- const rawTranscript = yield* readTranscript();
- const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) =>
- Effect.service(FileSystem.FileSystem).pipe(
- Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })),
- Effect.orDie,
- ),
- );
- const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript(
- materializeReplayTranscriptWorkspace(rawTranscript, cwd),
- );
-
- const materialized = yield* Effect.gen(function* () {
- const ids = yield* IdAllocator.IdAllocatorV2;
- const projectId = yield* ids.allocate.project({ fixtureName: "thread-fork-native" });
- const sourceThreadId = yield* ids.allocate.thread({
- fixtureName: "thread-fork-native-source",
- projectId,
- });
- const targetThreadId = ThreadId.make("thread-fork-native-target");
-
- const commands = [
- {
- type: "thread.create",
- createdBy: "user",
- creationSource: "web",
- commandId: yield* ids.allocate.command({
- fixtureName: "thread-fork-native",
- commandName: "thread-create-source",
- }),
- threadId: sourceThreadId,
- projectId,
- title: "Source thread",
- modelSelection: CODEX_MODEL_SELECTION,
- runtimeMode: "full-access",
- interactionMode: "default",
- branch: null,
- worktreePath: null,
- },
- {
- type: "message.dispatch",
- createdBy: "user",
- creationSource: "web",
- commandId: yield* ids.allocate.command({
- fixtureName: "thread-fork-native",
- commandName: "source-message",
- }),
- threadId: sourceThreadId,
- messageId: MessageId.make("message-thread-fork-native-source"),
- text: THREAD_FORK_NATIVE_SOURCE_PROMPT,
- attachments: [],
- modelSelection: CODEX_MODEL_SELECTION,
- dispatchMode: { type: "start_immediately" },
- },
- {
- type: "thread.fork",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make("command-thread-fork-native"),
- sourceThreadId,
- targetThreadId,
- sourcePoint: { type: "latest_stable" },
- title: "Forked thread",
- },
- {
- type: "thread.fork",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make("command-thread-fork-native"),
- sourceThreadId,
- targetThreadId,
- sourcePoint: { type: "latest_stable" },
- title: "Forked thread",
- },
- {
- type: "message.dispatch",
- createdBy: "user",
- creationSource: "web",
- commandId: yield* ids.allocate.command({
- fixtureName: "thread-fork-native",
- commandName: "target-message",
- }),
- threadId: targetThreadId,
- messageId: MessageId.make("message-thread-fork-native-target"),
- text: THREAD_FORK_NATIVE_TARGET_PROMPT,
- attachments: [],
- modelSelection: CODEX_MODEL_SELECTION,
- dispatchMode: { type: "start_immediately" },
- },
- ] satisfies ReadonlyArray<OrchestrationV2Command>;
-
- return {
- sourceThreadId,
- targetThreadId,
- commands,
- };
- }).pipe(Effect.provide(IdAllocator.layer), provideDeterministicTestRuntime);
-
- const result = yield* runOrchestratorV2ProviderReplayScenario(
- {
- name: "thread_fork_native/codex",
- transcript,
- commands: materialized.commands,
- steps: [
- { type: "dispatch", command: materialized.commands[0]!, await: true },
- { type: "advance_clock", duration: "1 millis" },
- { type: "dispatch", command: materialized.commands[1]!, await: true },
- { type: "await_thread_idle", threadId: materialized.sourceThreadId },
- { type: "dispatch", command: materialized.commands[2]!, await: true },
- { type: "dispatch", command: materialized.commands[3]!, await: true },
- { type: "dispatch", command: materialized.commands[4]!, await: true },
- { type: "await_thread_idle", threadId: materialized.targetThreadId },
- ],
- projectionThreadIds: [materialized.sourceThreadId, materialized.targetThreadId],
- runtimePolicyOverride: { cwd },
- },
- CodexOrchestratorReplayHarness,
- ).pipe(provideDeterministicTestRuntime);
-
- const sourceProjection = result.projections.get(materialized.sourceThreadId);
- const targetProjection = result.projections.get(materialized.targetThreadId);
- assert.isDefined(sourceProjection);
- assert.isDefined(targetProjection);
- assert.equal(targetProjection.thread.lineage.parentThreadId, materialized.sourceThreadId);
- assert.equal(targetProjection.thread.lineage.relationshipToParent, "fork");
- assert.lengthOf(targetProjection.providerSessions, 1);
- assert.lengthOf(targetProjection.providerThreads, 1);
- assert.equal(
- targetProjection.providerThreads[0]?.nativeThreadRef?.nativeId,
- "native-fork-thread",
- );
- assert.equal(
- targetProjection.providerThreads[0]?.forkedFrom?.providerThreadId,
- sourceProjection.providerThreads[0]?.id,
- );
-
- const transfers = targetProjection.contextTransfers.filter(
- (transfer) => transfer.targetThreadId === materialized.targetThreadId,
- );
- assert.lengthOf(transfers, 1);
- assert.equal(transfers[0]?.status, "consumed");
- assert.equal(transfers[0]?.resolution?.strategy, "native_fork");
- assert.isUndefined(sourceProjection.providerTurns[0]?.tokenUsage);
- assert.isUndefined(transfers[0]?.sourceTokenUsage);
- assert.equal(transfers[0]?.targetRunId, targetProjection.runs[0]?.id);
-
- const transferCreatedIndex = result.domainEvents.findIndex(
- (event) => event.type === "context-transfer.created",
- );
- const targetProviderSessionIndex = result.domainEvents.findIndex(
- (event) =>
- event.threadId === materialized.targetThreadId &&
- event.type === "provider-session.updated",
- );
- const targetRunCreatedIndex = result.domainEvents.findIndex(
- (event) => event.threadId === materialized.targetThreadId && event.type === "run.created",
- );
- assert.isAtLeast(transferCreatedIndex, 0);
- assert.isAbove(targetProviderSessionIndex, transferCreatedIndex);
- assert.isAbove(
- targetProviderSessionIndex,
- targetRunCreatedIndex,
- "provider runtime state must be materialized only after the target run commits",
- );
-
- const forkEvents = result.domainEvents.filter(
- (event) => event.type === "context-transfer.created",
- );
- assert.lengthOf(
- forkEvents,
- 1,
- "duplicate fork command must return the receipt without creating another transfer",
- );
- }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
- );
-
it.effect(
"creates an idle app fork and resolves it with Claude native session fork on first dispatch",
() =>
diff --git a/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts
index 058841fd852..836e06e74fb 100644
--- a/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts
+++ b/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts
@@ -23,10 +23,6 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import { provideDeterministicTestRuntime } from "./DeterministicRuntime.ts";
import {
CODEX_MODEL_SELECTION,
- THREAD_MERGE_BACK_FORK_PROMPT,
- THREAD_MERGE_BACK_HANDOFF_PROMPT,
- THREAD_MERGE_BACK_RECALL,
- THREAD_MERGE_BACK_RECALL_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_FIRST_FORK_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_FIRST_HANDOFF_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_RECALL,
@@ -34,7 +30,6 @@ import {
THREAD_MERGE_BACK_SIBLINGS_SECOND_FORK_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_SECOND_HANDOFF_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_SOURCE_PROMPT,
- THREAD_MERGE_BACK_SOURCE_PROMPT,
} from "./fixtures/shared.ts";
import { runOrchestratorV2ProviderReplayScenario } from "./ProviderReplayHarness.ts";
import { makeCheckpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
@@ -68,7 +63,6 @@ const CodexHistoryReplayHarness: typeof CodexOrchestratorReplayHarness = {
assert.lengthOf(userTexts, 1);
assert.include(
[
- THREAD_MERGE_BACK_FORK_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_FIRST_FORK_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_SECOND_FORK_PROMPT,
],
@@ -99,8 +93,6 @@ const CLAUDE_MODEL_SELECTION = {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
} as const;
-const MERGE_BACK_USER_TEXT =
- "Retain the transferred fork marker for later. Respond with exactly: merge delta stored";
const FIRST_SIBLING_MERGE_USER_TEXT =
"Retain the first transferred marker for later. Respond with exactly: first merge delta stored";
const SECOND_SIBLING_MERGE_USER_TEXT =
@@ -254,204 +246,6 @@ function makeCreateCommand(input: {
}
describe("orchestration V2 merge-back provider replay", () => {
- it.effect.each(PROVIDERS)(
- "merges one fork delta back into the original $driver thread",
- (variant) =>
- Effect.gen(function* () {
- const rawTranscript = yield* readTranscript("thread_merge_back_continue", variant.driver);
- const materialized = yield* Effect.gen(function* () {
- const ids = yield* IdAllocator.IdAllocatorV2;
- const projectId = yield* ids.allocate.project({
- fixtureName: `thread-merge-back-${variant.driver}`,
- });
- const sourceThreadId = yield* ids.allocate.thread({
- fixtureName: `thread-merge-back-${variant.driver}-source`,
- projectId,
- });
- const forkThreadId = ThreadId.make(`thread-merge-back-${variant.driver}-fork`);
- const forkRunId = ids.derive.run({ threadId: forkThreadId, ordinal: 1 });
- const commands = [
- makeCreateCommand({
- commandId: yield* ids.allocate.command({
- fixtureName: `thread-merge-back-${variant.driver}`,
- commandName: "create",
- }),
- threadId: sourceThreadId,
- projectId,
- modelSelection: variant.modelSelection,
- }),
- {
- type: "message.dispatch",
- createdBy: "user",
- creationSource: "web",
- commandId: yield* ids.allocate.command({
- fixtureName: `thread-merge-back-${variant.driver}`,
- commandName: "source",
- }),
- threadId: sourceThreadId,
- messageId: MessageId.make(`message-merge-source-${variant.driver}`),
- text: THREAD_MERGE_BACK_SOURCE_PROMPT,
- attachments: [],
- modelSelection: variant.modelSelection,
- dispatchMode: { type: "start_immediately" },
- },
- {
- type: "thread.fork",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make(`command-merge-fork-${variant.driver}`),
- sourceThreadId,
- targetThreadId: forkThreadId,
- sourcePoint: { type: "latest_stable" },
- title: "Merge-back fork",
- },
- {
- type: "message.dispatch",
- createdBy: "user",
- creationSource: "web",
- commandId: yield* ids.allocate.command({
- fixtureName: `thread-merge-back-${variant.driver}`,
- commandName: "fork-delta",
- }),
- threadId: forkThreadId,
- messageId: MessageId.make(`message-merge-fork-${variant.driver}`),
- text: THREAD_MERGE_BACK_FORK_PROMPT,
- attachments: [],
- modelSelection: variant.modelSelection,
- dispatchMode: { type: "start_immediately" },
- },
- {
- type: "thread.merge_back",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make(`command-merge-back-${variant.driver}`),
- sourceThreadId: forkThreadId,
- targetThreadId: sourceThreadId,
- sourcePoint: { type: "run", runId: forkRunId },
- },
- {
- type: "message.dispatch",
- createdBy: "user",
- creationSource: "web",
- commandId: yield* ids.allocate.command({
- fixtureName: `thread-merge-back-${variant.driver}`,
- commandName: "consume-merge",
- }),
- threadId: sourceThreadId,
- messageId: MessageId.make(`message-consume-merge-${variant.driver}`),
- text: MERGE_BACK_USER_TEXT,
- attachments: [],
- modelSelection: variant.modelSelection,
- dispatchMode: { type: "start_immediately" },
- },
- {
- type: "message.dispatch",
- createdBy: "user",
- creationSource: "web",
- commandId: yield* ids.allocate.command({
- fixtureName: `thread-merge-back-${variant.driver}`,
- commandName: "recall",
- }),
- threadId: sourceThreadId,
- messageId: MessageId.make(`message-merge-recall-${variant.driver}`),
- text: THREAD_MERGE_BACK_RECALL_PROMPT,
- attachments: [],
- modelSelection: variant.modelSelection,
- dispatchMode: { type: "start_immediately" },
- },
- ] satisfies ReadonlyArray<OrchestrationV2Command>;
- return { commands, sourceThreadId, forkThreadId, forkRunId };
- }).pipe(Effect.provide(IdAllocator.layer), provideDeterministicTestRuntime);
- const summary = forkDeltaSummary({
- sourceThreadId: materialized.forkThreadId,
- targetThreadId: materialized.sourceThreadId,
- forkUserText: THREAD_MERGE_BACK_FORK_PROMPT,
- forkAssistantText: "merge fork stored",
- });
- const generatedProviderMessage = providerMessage(summary, MERGE_BACK_USER_TEXT);
- const parameterizedTranscript = parameterizeHandoffs(rawTranscript, [
- [
- THREAD_MERGE_BACK_HANDOFF_PROMPT,
- variant.driver === "codex" ? MERGE_BACK_USER_TEXT : generatedProviderMessage,
- ],
- ]);
- const cwd = yield* Effect.acquireRelease(
- Effect.promise(() => makeCheckpointWorkspace(`merge-back-${variant.driver}`)),
- (directory) =>
- Effect.service(FileSystem.FileSystem).pipe(
- Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })),
- Effect.orDie,
- ),
- );
- const scenario = {
- name: `thread_merge_back_continue/${variant.driver}`,
- commands: materialized.commands,
- steps: [
- { type: "dispatch" as const, command: materialized.commands[0]!, await: true },
- { type: "advance_clock" as const, duration: "1 millis" as const },
- { type: "dispatch" as const, command: materialized.commands[1]!, await: true },
- { type: "await_thread_idle" as const, threadId: materialized.sourceThreadId },
- { type: "dispatch" as const, command: materialized.commands[2]!, await: true },
- { type: "dispatch" as const, command: materialized.commands[3]!, await: true },
- { type: "await_thread_idle" as const, threadId: materialized.forkThreadId },
- { type: "dispatch" as const, command: materialized.commands[4]!, await: true },
- { type: "dispatch" as const, command: materialized.commands[5]!, await: true },
- { type: "await_thread_idle" as const, threadId: materialized.sourceThreadId },
- { type: "dispatch" as const, command: materialized.commands[6]!, await: true },
- { type: "await_thread_idle" as const, threadId: materialized.sourceThreadId },
- ],
- projectionThreadIds: [materialized.sourceThreadId, materialized.forkThreadId],
- runtimePolicyOverride: { cwd },
- };
- const result =
- variant.driver === "codex"
- ? yield* runOrchestratorV2ProviderReplayScenario(
- {
- ...scenario,
- transcript: yield* CodexOrchestratorReplayHarness.decodeTranscript(
- materializeReplayTranscriptWorkspace(parameterizedTranscript, cwd),
- ),
- },
- CodexHistoryReplayHarness,
- ).pipe(provideDeterministicTestRuntime)
- : yield* runOrchestratorV2ProviderReplayScenario(
- {
- ...scenario,
- transcript:
- yield* ClaudeOrchestratorReplayHarness.decodeTranscript(
- parameterizedTranscript,
- ),
- },
- ClaudeOrchestratorReplayHarness,
- ).pipe(provideDeterministicTestRuntime);
-
- const source = result.projections.get(materialized.sourceThreadId);
- const fork = result.projections.get(materialized.forkThreadId);
- assert.isDefined(source);
- assert.isDefined(fork);
- assert.equal(
- source.providerThreads[0]?.nativeThreadRef?.nativeId,
- nativeSourceThreadId(rawTranscript),
- );
- assert.lengthOf(source.contextHandoffs, 1);
- assert.equal(source.contextHandoffs[0]?.summaryText, summary);
- assert.equal(source.contextHandoffs[0]?.strategy, "fork_delta_summary");
- const mergeTransfer = source.contextTransfers.find(
- (transfer) => transfer.type === "merge_back",
- );
- assert.isDefined(mergeTransfer);
- assert.equal(mergeTransfer.status, "consumed");
- assert.equal(mergeTransfer.sourcePoint.runId, materialized.forkRunId);
- assert.equal(mergeTransfer.resolution?.strategy, "fork_delta_context");
- assert.include(
- normalizePipeSpacing(visibleConversationText(source)),
- THREAD_MERGE_BACK_RECALL,
- );
- assert.notInclude(visibleConversationText(source), "Context handoff (");
- assert.include(visibleConversationText(fork), "merge fork stored");
- }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
- );
-
it.effect.each(PROVIDERS)(
"merges two sibling fork deltas into the original $driver thread",
(variant) =>
diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts
index 0d0227c9da5..5fd4d3590cc 100644
--- a/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts
+++ b/apps/server/src/orchestration-v2/testkit/fixtures/shared.ts
@@ -144,7 +144,6 @@ export const THREAD_MERGE_BACK_HANDOFF_PROMPT = [
"User message:",
"Retain the transferred fork marker for later. Respond with exactly: merge delta stored",
].join("\n");
-export const THREAD_MERGE_BACK_RECALL = `${THREAD_MERGE_BACK_SOURCE_MARKER}|${THREAD_MERGE_BACK_FORK_MARKER}`;
export const THREAD_MERGE_BACK_RECALL_PROMPT =
"Return the source marker followed by the transferred fork marker, separated by a single | character. Respond with only the markers and separator.";
const THREAD_MERGE_BACK_SIBLINGS_SOURCE_MARKER = "merge-sibling-source-3C7K";
diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native/codex_transcript.ndjson
deleted file mode 100644
index 2e2c60fdcd9..00000000000
--- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native/codex_transcript.ndjson
+++ /dev/null
@@ -1,21 +0,0 @@
-{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.120.0","scenario":"thread_fork_native","metadata":{"source":"hand-authored-replay","description":"One completed source turn, a native thread/fork, and the first target fork turn.","normalization":"The thread/fork expected request gains lastTurnId (inclusive native boundary) to match the V2 adapter's native-boundary fork."}}
-{"type":"expect_outbound","label":"initialize/source","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
-{"type":"emit_inbound","label":"initialize/source","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.120.0","codexHome":"/tmp/codex","platformFamily":"unix","platformOs":"macos"}}}
-{"type":"expect_outbound","label":"initialized/source","frame":{"method":"initialized"}}
-{"type":"expect_outbound","label":"thread/start/source","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000}}}}
-{"type":"emit_inbound","label":"thread/start/source","frame":{"id":2,"result":{"thread":{"id":"native-source-thread","forkedFromId":null,"preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739349,"updatedAt":1776739349,"status":{"type":"idle"},"path":"/tmp/source.jsonl","cwd":"/tmp/project","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/tmp/project","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}}
-{"type":"expect_outbound","label":"turn/start/source","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"<workspace>","input":[{"text":"Respond with the following text: source fork seed ok","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"native-source-thread","approvalsReviewer":"user","summary":"detailed"}}}
-{"type":"emit_inbound","label":"turn/start/source","frame":{"id":3,"result":{"turn":{"id":"native-source-turn","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}}
-{"type":"emit_inbound","label":"turn/started/source","frame":{"method":"turn/started","params":{"threadId":"native-source-thread","turn":{"id":"native-source-turn","items":[],"status":"inProgress","error":null,"startedAt":1776739349,"completedAt":null,"durationMs":null}}}}
-{"type":"emit_inbound","label":"item/completed/source-user","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"native-source-user-item","content":[{"type":"text","text":"Respond with the following text: source fork seed ok","text_elements":[]}]},"threadId":"native-source-thread","turnId":"native-source-turn"}}}
-{"type":"emit_inbound","label":"item/completed/source-agent","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"native-source-agent-item","text":"source fork seed ok","phase":"final_answer","memoryCitation":null},"threadId":"native-source-thread","turnId":"native-source-turn"}}}
-{"type":"emit_inbound","label":"turn/completed/source","frame":{"method":"turn/completed","params":{"threadId":"native-source-thread","turn":{"id":"native-source-turn","items":[],"status":"completed","error":null,"startedAt":1776739349,"completedAt":1776739356,"durationMs":6434}}}}
-{"type":"expect_outbound","label":"thread/fork","frame":{"id":4,"method":"thread/fork","params":{"threadId":"native-source-thread","lastTurnId":"native-source-turn","config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000}}}}
-{"type":"emit_inbound","label":"thread/fork","frame":{"id":4,"result":{"thread":{"id":"native-fork-thread","forkedFromId":"native-source-thread","preview":"","ephemeral":false,"modelProvider":"openai","createdAt":1776739360,"updatedAt":1776739360,"status":{"type":"idle"},"path":"/tmp/fork.jsonl","cwd":"/tmp/project","cliVersion":"0.120.0","source":"vscode","agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]},"model":"gpt-5.4","modelProvider":"openai","serviceTier":"fast","cwd":"/tmp/project","approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"readOnlyAccess":{"type":"fullAccess"},"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"reasoningEffort":"xhigh"}}}
-{"type":"expect_outbound","label":"turn/start/fork","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","cwd":"<workspace>","input":[{"text":"Respond with the following text: fork native ok","type":"text"}],"model":"gpt-5.4","sandboxPolicy":{"type":"dangerFullAccess"},"threadId":"native-fork-thread","approvalsReviewer":"user","summary":"detailed"}}}
-{"type":"emit_inbound","label":"turn/start/fork","frame":{"id":5,"result":{"turn":{"id":"native-fork-turn","items":[],"status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}}
-{"type":"emit_inbound","label":"turn/started/fork","frame":{"method":"turn/started","params":{"threadId":"native-fork-thread","turn":{"id":"native-fork-turn","items":[],"status":"inProgress","error":null,"startedAt":1776739361,"completedAt":null,"durationMs":null}}}}
-{"type":"emit_inbound","label":"item/completed/fork-user","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"native-fork-user-item","content":[{"type":"text","text":"Respond with the following text: fork native ok","text_elements":[]}]},"threadId":"native-fork-thread","turnId":"native-fork-turn"}}}
-{"type":"emit_inbound","label":"item/completed/fork-agent","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"native-fork-agent-item","text":"fork native ok","phase":"final_answer","memoryCitation":null},"threadId":"native-fork-thread","turnId":"native-fork-turn"}}}
-{"type":"emit_inbound","label":"turn/completed/fork","frame":{"method":"turn/completed","params":{"threadId":"native-fork-thread","turn":{"id":"native-fork-turn","items":[],"status":"completed","error":null,"startedAt":1776739361,"completedAt":1776739363,"durationMs":2000}}}}
-{"type":"runtime_exit","status":"success"}
diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_continue/README.md b/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_continue/README.md
deleted file mode 100644
index cf2a76e4526..00000000000
--- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_continue/README.md
+++ /dev/null
@@ -1,45 +0,0 @@
-# Merge-Back Continuation Fixture
-
-This fixture records a native fork, a fork-local delta, and an app-style
-merge-back handoff consumed by the original provider thread. A later source
-turn recalls both markers without receiving either marker in its prompt.
-
-Both provider transcripts execute the same graph.
-
-## Conversation Graph
-
-```text
-Source provider thread
-|
-+-- Turn 1
-| User: remember merge-source-4H8Q
-| Assistant: merge source stored
-|
-+-- native fork
-| |
-| `-- Forked provider thread
-| `-- Turn 2
-| User: remember merge-fork-7T2W
-| Assistant: merge fork stored
-|
-`-- original source provider thread
- |
- +-- Turn 3
- | App input: merge_back handoff containing merge-fork-7T2W
- | Assistant: merge delta stored
- |
- `-- Turn 4
- User: recall source and transferred markers without restating them
- Assistant: merge-source-4H8Q|merge-fork-7T2W
-```
-
-## Assertions
-
-- The fork uses a different native provider thread or session.
-- The handoff and recall turns continue the original source provider thread.
-- The recall prompt contains neither marker.
-- The final response recalls both source and transferred fork context.
-
-The transcript records the provider-facing handoff format. The app-level
-`thread.merge_back` command and context-transfer lifecycle remain covered by
-the orchestrator integration tests.
diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_continue/claude_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_continue/claude_transcript.ndjson
deleted file mode 100644
index 4ed256d65dc..00000000000
--- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_continue/claude_transcript.ndjson
+++ /dev/null
@@ -1,34 +0,0 @@
-{"type":"transcript_start","provider":"claudeAgent","protocol":"claude-agent-sdk.query","version":"0.2.111","scenario":"thread_merge_back_continue","metadata":{"prompts":["Remember the opaque marker merge-source-4H8Q for later in this conversation. Respond with exactly: merge source stored","Remember the fork-local marker merge-fork-7T2W. Respond with exactly: merge fork stored","Context handoff (merge_back / fork_delta_summary):\nMerge-back context from forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-fork-7T2W.\n- Assistant confirmed: merge fork stored\n\nUser message:\nRetain the transferred fork marker for later. Respond with exactly: merge delta stored","Return the source marker followed by the transferred fork marker, separated by a single | character. Respond with only the markers and separator."],"model":"claude-sonnet-4-6","nativeSessionId":"79522bc8-3de1-41c4-a2fd-902246ef1290","queryMode":"fork_session_merge_back","tools":"claude_code","permissionMode":"bypassPermissions","generatedBy":"recordClaudeAgentSdkReplayTranscript","sourceAssistantMessageUuids":["a4647f9c-80c4-458e-be3a-b15e5105fa4f"],"forkUpToMessageId":"a4647f9c-80c4-458e-be3a-b15e5105fa4f","forkedNativeSessionId":"8baac83f-471d-4d65-9091-2e7e66557251","forkedNativeSessionIds":["8baac83f-471d-4d65-9091-2e7e66557251"],"sourceContinuationPromptCount":2}}
-{"type":"expect_outbound","label":"query.open:source","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"sessionId":"79522bc8-3de1-41c4-a2fd-902246ef1290","settings":{"showThinkingSummaries":true}}}}
-{"type":"expect_outbound","label":"prompt.offer:1","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Remember the opaque marker merge-source-4H8Q for later in this conversation. Respond with exactly: merge source stored"},"parent_tool_use_id":null}}}
-{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"ca138fb7-425e-49c2-81c3-74bba4794caa","hook_name":"SessionStart:startup","hook_event":"SessionStart","uuid":"8683c9cc-5740-4f87-8692-4f475d2ba357","session_id":"79522bc8-3de1-41c4-a2fd-902246ef1290"}}
-{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"ca138fb7-425e-49c2-81c3-74bba4794caa","hook_name":"SessionStart:startup","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"98fb5ba2-d12a-40e6-b114-26da116f7360","session_id":"79522bc8-3de1-41c4-a2fd-902246ef1290"}}
-{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.159","cwd":"/tmp/claude-replay-thread_merge_back_continue","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"2a2e49f2-27b0-40b0-b1ac-7367b908dcb8","session_id":"79522bc8-3de1-41c4-a2fd-902246ef1290"}}
-{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01MNXMZ2663k7u7x7qvgyrpx","type":"message","role":"assistant","content":[{"type":"text","text":"merge source stored"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":18977,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"79522bc8-3de1-41c4-a2fd-902246ef1290","uuid":"a4647f9c-80c4-458e-be3a-b15e5105fa4f","request_id":"req_011CbrhadoaKaXmYQpTYNbHv"}}
-{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"41517fd7-973f-44ed-86e1-779bac6e6ab2","session_id":"79522bc8-3de1-41c4-a2fd-902246ef1290"}}
-{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2584,"duration_api_ms":1954,"ttft_ms":1885,"num_turns":1,"result":"merge source stored","stop_reason":"end_turn","session_id":"79522bc8-3de1-41c4-a2fd-902246ef1290","total_cost_usd":0.0057921000000000005,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":18977,"output_tokens":6,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[{"input_tokens":3,"output_tokens":6,"cache_read_input_tokens":18977,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":6,"cacheReadInputTokens":18977,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.0057921000000000005,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"ea85fb12-2387-44cf-b6c9-b62e2fc48696"}}
-{"type":"runtime_exit","status":"success"}
-{"type":"expect_outbound","label":"session.fork","frame":{"type":"session.fork","sessionId":"79522bc8-3de1-41c4-a2fd-902246ef1290","options":{"dir":"/tmp/claude-replay-thread_merge_back_continue","upToMessageId":"a4647f9c-80c4-458e-be3a-b15e5105fa4f"}}}
-{"type":"emit_inbound","label":"session.forked","frame":{"type":"session.forked","sessionId":"8baac83f-471d-4d65-9091-2e7e66557251"}}
-{"type":"expect_outbound","label":"query.open:fork","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"resume":"8baac83f-471d-4d65-9091-2e7e66557251","settings":{"showThinkingSummaries":true}}}}
-{"type":"expect_outbound","label":"prompt.offer:2","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Remember the fork-local marker merge-fork-7T2W. Respond with exactly: merge fork stored"},"parent_tool_use_id":null}}}
-{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"a2cb0c98-569d-4b16-9e71-937c6f38bfb2","hook_name":"SessionStart:resume","hook_event":"SessionStart","uuid":"8786da30-2c27-4fa8-aa71-ff7fecaa37f8","session_id":"350f8022-de90-440c-b32e-c559a60e7383"}}
-{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"a2cb0c98-569d-4b16-9e71-937c6f38bfb2","hook_name":"SessionStart:resume","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"8da14dd3-d942-4ed4-a80d-a5eaf5c39d50","session_id":"350f8022-de90-440c-b32e-c559a60e7383"}}
-{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.159","cwd":"/tmp/claude-replay-thread_merge_back_continue","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"a3110ea8-1198-4a03-a8df-670c78523fd4","session_id":"8baac83f-471d-4d65-9091-2e7e66557251"}}
-{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01BxoJ9bgjaXn24qSchFoFnQ","type":"message","role":"assistant","content":[{"type":"text","text":"merge fork stored"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":19009,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"8baac83f-471d-4d65-9091-2e7e66557251","uuid":"e2c1b56e-9ade-44ab-9087-bf293eb3aeaf","request_id":"req_011CbrhauAJJxiGXkMuAb2aA"}}
-{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"0ef1ea39-53df-4c70-81ac-ae4e11960937","session_id":"8baac83f-471d-4d65-9091-2e7e66557251"}}
-{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2531,"duration_api_ms":1866,"ttft_ms":2102,"num_turns":1,"result":"merge fork stored","stop_reason":"end_turn","session_id":"8baac83f-471d-4d65-9091-2e7e66557251","total_cost_usd":0.005801700000000001,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":19009,"output_tokens":6,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[{"input_tokens":3,"output_tokens":6,"cache_read_input_tokens":19009,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":6,"cacheReadInputTokens":19009,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.005801700000000001,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"e22495dc-0ab1-4e99-bd90-3d2ac8295c6f"}}
-{"type":"runtime_exit","status":"success"}
-{"type":"expect_outbound","label":"query.open:source-continuation","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"resume":"79522bc8-3de1-41c4-a2fd-902246ef1290","settings":{"showThinkingSummaries":true}}}}
-{"type":"expect_outbound","label":"prompt.offer:3","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-fork-7T2W.\n- Assistant confirmed: merge fork stored\n\nUser message:\nRetain the transferred fork marker for later. Respond with exactly: merge delta stored"},"parent_tool_use_id":null}}}
-{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"5e475fe2-aef6-4282-b1d8-334acfa4c4cd","hook_name":"SessionStart:resume","hook_event":"SessionStart","uuid":"9888cede-fed1-4dc7-b75c-0ce156547e70","session_id":"49021892-2f16-4f92-98ee-1d2943382082"}}
-{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"5e475fe2-aef6-4282-b1d8-334acfa4c4cd","hook_name":"SessionStart:resume","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"3faffda5-2087-4eb1-bdb9-27bfad62b5f1","session_id":"49021892-2f16-4f92-98ee-1d2943382082"}}
-{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.159","cwd":"/tmp/claude-replay-thread_merge_back_continue","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"370aeede-59f6-4d9c-a0f5-a4810fec3651","session_id":"79522bc8-3de1-41c4-a2fd-902246ef1290"}}
-{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01QywCNnUUGSBbcW4HG5Fbj6","type":"message","role":"assistant","content":[{"type":"text","text":"merge delta stored"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":84,"cache_read_input_tokens":18977,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":84},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"79522bc8-3de1-41c4-a2fd-902246ef1290","uuid":"7f1e76ac-a80e-48e5-8a5e-d54099bb68e2","request_id":"req_011CbrhbAZkbickYjaYkr1MU"}}
-{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"c31657df-4b5d-4b81-b1ae-c2da7df3c68a","session_id":"79522bc8-3de1-41c4-a2fd-902246ef1290"}}
-{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2399,"duration_api_ms":1773,"ttft_ms":2000,"num_turns":1,"result":"merge delta stored","stop_reason":"end_turn","session_id":"79522bc8-3de1-41c4-a2fd-902246ef1290","total_cost_usd":0.006107100000000001,"usage":{"input_tokens":3,"cache_creation_input_tokens":84,"cache_read_input_tokens":18977,"output_tokens":6,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":84,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[{"input_tokens":3,"output_tokens":6,"cache_read_input_tokens":18977,"cache_creation_input_tokens":84,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":84},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":6,"cacheReadInputTokens":18977,"cacheCreationInputTokens":84,"webSearchRequests":0,"costUSD":0.006107100000000001,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"d8fdda24-40ab-4bbe-9147-b0433c5a5d5b"}}
-{"type":"expect_outbound","label":"prompt.offer:4","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Return the source marker followed by the transferred fork marker, separated by a single | character. Respond with only the markers and separator."},"parent_tool_use_id":null}}}
-{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.159","cwd":"/tmp/claude-replay-thread_merge_back_continue","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"930c142a-b5e9-4056-8636-329558eb401f","session_id":"79522bc8-3de1-41c4-a2fd-902246ef1290"}}
-{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01RovhD68EryidHLBGQMKjeQ","type":"message","role":"assistant","content":[{"type":"text","text":"merge-source-4H8Q | merge-fork-7T2W"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":135,"cache_read_input_tokens":19061,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":135},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"79522bc8-3de1-41c4-a2fd-902246ef1290","uuid":"0ed8c280-8f05-46b8-a7f8-40c98b1993f1","request_id":"req_011CbrhbNGTNVZmtXQuy7R5V"}}
-{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2611,"duration_api_ms":3876,"ttft_ms":2308,"num_turns":1,"result":"merge-source-4H8Q | merge-fork-7T2W","stop_reason":"end_turn","session_id":"79522bc8-3de1-41c4-a2fd-902246ef1290","total_cost_usd":0.01264065,"usage":{"input_tokens":3,"cache_creation_input_tokens":135,"cache_read_input_tokens":19061,"output_tokens":20,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":135,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[{"input_tokens":3,"output_tokens":20,"cache_read_input_tokens":19061,"cache_creation_input_tokens":135,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":135},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":6,"outputTokens":26,"cacheReadInputTokens":38038,"cacheCreationInputTokens":219,"webSearchRequests":0,"costUSD":0.01264065,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"e6282264-d155-4e72-8289-fc0310eaca0c"}}
-{"type":"runtime_exit","status":"success"}
diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_continue/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_continue/codex_transcript.ndjson
deleted file mode 100644
index 1308e039e28..00000000000
--- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_continue/codex_transcript.ndjson
+++ /dev/null
@@ -1,95 +0,0 @@
-{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"thread_merge_back_continue","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"thread_merge_back_continue.ndjson","description":"A source thread consumes one fork-delta handoff and later recalls source and transferred context.","model":"gpt-6-sol"}}
-{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}
-{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}
-{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
-{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000},"cwd":"<workspace>","model":"gpt-6-sol"}}}
-{"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790297758148}}
-{"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790297758148}}
-{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297758,"updatedAt":1790297758,"recencyAt":1790297758,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-55-58-01a0d60f-d9dd-7d82-8842-6efe9b7b5152.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}}
-{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"<workspace>","input":[{"text":"Remember the opaque marker merge-source-4H8Q for later in this conversation. Respond with exactly: merge source stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"detailed","threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152"}}}
-{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297758370}}
-{"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297758,"updatedAt":1790297758,"recencyAt":1790297758,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-55-58-01a0d60f-d9dd-7d82-8842-6efe9b7b5152.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790297758370}}
-{"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790297758380}}
-{"type":"emit_inbound","label":"turn/start","frame":{"id":3,"result":{"turn":{"id":"01a0d60f-daa8-7020-b1c9-2fee56b42739","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}}
-{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297758428}}
-{"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turn":{"id":"01a0d60f-daa8-7020-b1c9-2fee56b42739","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297758,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297758428}}
-{"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790297758731}}
-{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297758880}}
-{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790297759784}}
-{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d60f-e412-7581-bda2-d126ca6132c9","clientId":null,"content":[{"type":"text","text":"Remember the opaque marker merge-source-4H8Q for later in this conversation. Respond with exactly: merge source stored","text_elements":[]}]},"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d60f-daa8-7020-b1c9-2fee56b42739","startedAtMs":1790297760790},"emittedAtMs":1790297760793}}
-{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"01a0d60f-e412-7581-bda2-d126ca6132c9","clientId":null,"content":[{"type":"text","text":"Remember the opaque marker merge-source-4H8Q for later in this conversation. Respond with exactly: merge source stored","text_elements":[]}]},"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d60f-daa8-7020-b1c9-2fee56b42739","completedAtMs":1790297760792},"emittedAtMs":1790297760801}}
-{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_01a6f3bdd4e03630016ab5c6a2dc0887d0afb50d9a544badba","text":"","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d60f-daa8-7020-b1c9-2fee56b42739","startedAtMs":1790297763141},"emittedAtMs":1790297763142}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d60f-daa8-7020-b1c9-2fee56b42739","itemId":"msg_01a6f3bdd4e03630016ab5c6a2dc0887d0afb50d9a544badba","delta":"merge"},"emittedAtMs":1790297763142}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d60f-daa8-7020-b1c9-2fee56b42739","itemId":"msg_01a6f3bdd4e03630016ab5c6a2dc0887d0afb50d9a544badba","delta":" source"},"emittedAtMs":1790297763142}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d60f-daa8-7020-b1c9-2fee56b42739","itemId":"msg_01a6f3bdd4e03630016ab5c6a2dc0887d0afb50d9a544badba","delta":" stored"},"emittedAtMs":1790297763143}}
-{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_01a6f3bdd4e03630016ab5c6a2dc0887d0afb50d9a544badba","text":"merge source stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d60f-daa8-7020-b1c9-2fee56b42739","completedAtMs":1790297763224},"emittedAtMs":1790297763230}}
-{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","name":"xcodebuildmcp","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790297763356}}
-{"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d60f-daa8-7020-b1c9-2fee56b42739","tokenUsage":{"total":{"totalTokens":17748,"inputTokens":17741,"cachedInputTokens":7040,"cacheWriteInputTokens":0,"outputTokens":7,"reasoningOutputTokens":0},"last":{"totalTokens":17748,"inputTokens":17741,"cachedInputTokens":7040,"cacheWriteInputTokens":0,"outputTokens":7,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790297763358}}
-{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","status":{"type":"idle"}},"emittedAtMs":1790297763365}}
-{"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turn":{"id":"01a0d60f-daa8-7020-b1c9-2fee56b42739","items":[{"type":"agentMessage","id":"msg_01a6f3bdd4e03630016ab5c6a2dc0887d0afb50d9a544badba","text":"merge source stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790297758,"completedAt":1790297763,"durationMs":4983}},"emittedAtMs":1790297763365}}
-{"type":"expect_outbound","label":"thread/fork","frame":{"id":4,"method":"thread/fork","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000},"cwd":"<workspace>","lastTurnId":"01a0d60f-daa8-7020-b1c9-2fee56b42739","model":"gpt-6-sol","threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152"}}}
-{"type":"emit_inbound","label":"deprecationNotice","frame":{"method":"deprecationNotice","params":{"summary":"Full-history hydration is deprecated for paginated threads; use `excludeTurns: true`, then page with `thread/turns/list` and `thread/items/list`.","details":null},"emittedAtMs":1790297763374}}
-{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297763613}}
-{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790297763613}}
-{"type":"emit_inbound","label":"thread/fork","frame":{"id":4,"result":{"thread":{"id":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","forkedFromId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297763,"updatedAt":1790297763,"recencyAt":1790297763,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-03-01a0d60f-ee79-77b0-8e97-bb27c81fd026.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[{"id":"01a0d60f-daa8-7020-b1c9-2fee56b42739","items":[{"type":"userMessage","id":"01a0d60f-e412-7581-bda2-d126ca6132c9","clientId":null,"content":[{"type":"text","text":"Remember the opaque marker merge-source-4H8Q for later in this conversation. Respond with exactly: merge source stored","text_elements":[]}]},{"type":"agentMessage","id":"msg_01a6f3bdd4e03630016ab5c6a2dc0887d0afb50d9a544badba","text":"merge source stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"full","status":"completed","error":null,"startedAt":1790297758,"completedAt":1790297763,"durationMs":4983}]},"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md"],"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}}
-{"type":"expect_outbound","label":"turn/start","frame":{"id":5,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"<workspace>","input":[{"text":"Remember the fork-local marker merge-fork-7T2W. Respond with exactly: merge fork stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"detailed","threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026"}}}
-{"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","turnId":"01a0d60f-daa8-7020-b1c9-2fee56b42739","tokenUsage":{"total":{"totalTokens":17748,"inputTokens":17741,"cachedInputTokens":7040,"cacheWriteInputTokens":0,"outputTokens":7,"reasoningOutputTokens":0},"last":{"totalTokens":17748,"inputTokens":17741,"cachedInputTokens":7040,"cacheWriteInputTokens":0,"outputTokens":7,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790297763630}}
-{"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","forkedFromId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-sol","reasoningEffort":null,"createdAt":1790297763,"updatedAt":1790297763,"recencyAt":1790297763,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-56-03-01a0d60f-ee79-77b0-8e97-bb27c81fd026.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":{"sha":"1563a64b41d5e7e2e640b46f52cee724913f8851","branch":"v2/codex-gpt6-luna-rerecord","originUrl":"https://github.com/pingdotgg/t3code.git"},"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790297763630}}
-{"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-sol","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-sol","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790297763652}}
-{"type":"emit_inbound","label":"turn/start","frame":{"id":5,"result":{"turn":{"id":"01a0d60f-ef35-7a63-b460-84ede485ec85","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}}
-{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297763665}}
-{"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","turn":{"id":"01a0d60f-ef35-7a63-b460-84ede485ec85","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297763,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297763665}}
-{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790297764218}}
-{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d60f-f3a5-7101-872b-90a9426624ab","clientId":null,"content":[{"type":"text","text":"Remember the fork-local marker merge-fork-7T2W. Respond with exactly: merge fork stored","text_elements":[]}]},"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","turnId":"01a0d60f-ef35-7a63-b460-84ede485ec85","startedAtMs":1790297764776},"emittedAtMs":1790297764776}}
-{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"01a0d60f-f3a5-7101-872b-90a9426624ab","clientId":null,"content":[{"type":"text","text":"Remember the fork-local marker merge-fork-7T2W. Respond with exactly: merge fork stored","text_elements":[]}]},"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","turnId":"01a0d60f-ef35-7a63-b460-84ede485ec85","completedAtMs":1790297764776},"emittedAtMs":1790297764785}}
-{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_01a6f3bdd4e03630016ab5c6a6795887d0ab300c0c07e3a285","text":"","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","turnId":"01a0d60f-ef35-7a63-b460-84ede485ec85","startedAtMs":1790297766760},"emittedAtMs":1790297766760}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","turnId":"01a0d60f-ef35-7a63-b460-84ede485ec85","itemId":"msg_01a6f3bdd4e03630016ab5c6a6795887d0ab300c0c07e3a285","delta":"merge"},"emittedAtMs":1790297766760}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","turnId":"01a0d60f-ef35-7a63-b460-84ede485ec85","itemId":"msg_01a6f3bdd4e03630016ab5c6a6795887d0ab300c0c07e3a285","delta":" fork"},"emittedAtMs":1790297766760}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","turnId":"01a0d60f-ef35-7a63-b460-84ede485ec85","itemId":"msg_01a6f3bdd4e03630016ab5c6a6795887d0ab300c0c07e3a285","delta":" stored"},"emittedAtMs":1790297766760}}
-{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_01a6f3bdd4e03630016ab5c6a6795887d0ab300c0c07e3a285","text":"merge fork stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","turnId":"01a0d60f-ef35-7a63-b460-84ede485ec85","completedAtMs":1790297766760},"emittedAtMs":1790297766789}}
-{"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","turnId":"01a0d60f-ef35-7a63-b460-84ede485ec85","tokenUsage":{"total":{"totalTokens":39712,"inputTokens":39698,"cachedInputTokens":21888,"cacheWriteInputTokens":0,"outputTokens":14,"reasoningOutputTokens":0},"last":{"totalTokens":21964,"inputTokens":21957,"cachedInputTokens":14848,"cacheWriteInputTokens":0,"outputTokens":7,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790297766829}}
-{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","status":{"type":"idle"}},"emittedAtMs":1790297766848}}
-{"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","turn":{"id":"01a0d60f-ef35-7a63-b460-84ede485ec85","items":[{"type":"agentMessage","id":"msg_01a6f3bdd4e03630016ab5c6a6795887d0ab300c0c07e3a285","text":"merge fork stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790297763,"completedAt":1790297766,"durationMs":3191}},"emittedAtMs":1790297766848}}
-{"type":"expect_outbound","label":"turn/start","frame":{"id":6,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"<workspace>","input":[{"text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-fork-7T2W.\n- Assistant confirmed: merge fork stored\n\nUser message:\nRetain the transferred fork marker for later. Respond with exactly: merge delta stored","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"detailed","threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152"}}}
-{"type":"emit_inbound","label":"turn/start","frame":{"id":6,"result":{"turn":{"id":"01a0d60f-fbc3-7921-a57c-5b571eddbcf8","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}}
-{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297766878}}
-{"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turn":{"id":"01a0d60f-fbc3-7921-a57c-5b571eddbcf8","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297766,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297766878}}
-{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d60f-fc9d-7151-bd36-33ef393fdcb0","clientId":null,"content":[{"type":"text","text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-fork-7T2W.\n- Assistant confirmed: merge fork stored\n\nUser message:\nRetain the transferred fork marker for later. Respond with exactly: merge delta stored","text_elements":[]}]},"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d60f-fbc3-7921-a57c-5b571eddbcf8","startedAtMs":1790297767071},"emittedAtMs":1790297767071}}
-{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"01a0d60f-fc9d-7151-bd36-33ef393fdcb0","clientId":null,"content":[{"type":"text","text":"Context handoff (merge_back / fork_delta_summary):\nMerge-back context from forked conversation.\n\nFork delta:\n- User introduced opaque marker merge-fork-7T2W.\n- Assistant confirmed: merge fork stored\n\nUser message:\nRetain the transferred fork marker for later. Respond with exactly: merge delta stored","text_elements":[]}]},"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d60f-fbc3-7921-a57c-5b571eddbcf8","completedAtMs":1790297767071},"emittedAtMs":1790297767076}}
-{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","name":"xcodebuildmcp","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790297767988}}
-{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_01a6f3bdd4e03630016ab5c6a8c55487d0ace5b685a25be087","text":"","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d60f-fbc3-7921-a57c-5b571eddbcf8","startedAtMs":1790297768987},"emittedAtMs":1790297768988}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d60f-fbc3-7921-a57c-5b571eddbcf8","itemId":"msg_01a6f3bdd4e03630016ab5c6a8c55487d0ace5b685a25be087","delta":"merge"},"emittedAtMs":1790297769063}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d60f-fbc3-7921-a57c-5b571eddbcf8","itemId":"msg_01a6f3bdd4e03630016ab5c6a8c55487d0ace5b685a25be087","delta":" delta"},"emittedAtMs":1790297769063}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d60f-fbc3-7921-a57c-5b571eddbcf8","itemId":"msg_01a6f3bdd4e03630016ab5c6a8c55487d0ace5b685a25be087","delta":" stored"},"emittedAtMs":1790297769063}}
-{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_01a6f3bdd4e03630016ab5c6a8c55487d0ace5b685a25be087","text":"merge delta stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d60f-fbc3-7921-a57c-5b571eddbcf8","completedAtMs":1790297769063},"emittedAtMs":1790297769068}}
-{"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d60f-fbc3-7921-a57c-5b571eddbcf8","tokenUsage":{"total":{"totalTokens":39754,"inputTokens":39740,"cachedInputTokens":24576,"cacheWriteInputTokens":0,"outputTokens":14,"reasoningOutputTokens":0},"last":{"totalTokens":22006,"inputTokens":21999,"cachedInputTokens":17536,"cacheWriteInputTokens":0,"outputTokens":7,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790297769076}}
-{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","status":{"type":"idle"}},"emittedAtMs":1790297769081}}
-{"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turn":{"id":"01a0d60f-fbc3-7921-a57c-5b571eddbcf8","items":[{"type":"agentMessage","id":"msg_01a6f3bdd4e03630016ab5c6a8c55487d0ace5b685a25be087","text":"merge delta stored","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790297766,"completedAt":1790297769,"durationMs":2211}},"emittedAtMs":1790297769081}}
-{"type":"expect_outbound","label":"turn/start","frame":{"id":7,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"<workspace>","input":[{"text":"Return the source marker followed by the transferred fork marker, separated by a single | character. Respond with only the markers and separator.","type":"text"}],"model":"gpt-6-sol","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"detailed","threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152"}}}
-{"type":"emit_inbound","label":"turn/start","frame":{"id":7,"result":{"turn":{"id":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}}
-{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790297769101}}
-{"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turn":{"id":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790297769,"completedAt":null,"durationMs":null}},"emittedAtMs":1790297769101}}
-{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d610-0529-7c62-8a34-a646ec8a9f8f","clientId":null,"content":[{"type":"text","text":"Return the source marker followed by the transferred fork marker, separated by a single | character. Respond with only the markers and separator.","text_elements":[]}]},"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","startedAtMs":1790297769258},"emittedAtMs":1790297769259}}
-{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"01a0d610-0529-7c62-8a34-a646ec8a9f8f","clientId":null,"content":[{"type":"text","text":"Return the source marker followed by the transferred fork marker, separated by a single | character. Respond with only the markers and separator.","text_elements":[]}]},"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","completedAtMs":1790297769258},"emittedAtMs":1790297769264}}
-{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","text":"","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","startedAtMs":1790297771119},"emittedAtMs":1790297771119}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","itemId":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","delta":"merge"},"emittedAtMs":1790297771119}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","itemId":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","delta":"-source"},"emittedAtMs":1790297771119}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","itemId":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","delta":"-"},"emittedAtMs":1790297771119}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","itemId":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","delta":"4"},"emittedAtMs":1790297771119}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","itemId":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","delta":"H"},"emittedAtMs":1790297771119}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","itemId":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","delta":"8"},"emittedAtMs":1790297771119}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","itemId":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","delta":"Q"},"emittedAtMs":1790297771119}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","itemId":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","delta":"|"},"emittedAtMs":1790297771119}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","itemId":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","delta":"merge"},"emittedAtMs":1790297771119}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","itemId":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","delta":"-f"},"emittedAtMs":1790297771119}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","itemId":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","delta":"ork"},"emittedAtMs":1790297771119}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","itemId":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","delta":"-"},"emittedAtMs":1790297771119}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","itemId":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","delta":"7"},"emittedAtMs":1790297771119}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","itemId":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","delta":"T"},"emittedAtMs":1790297771119}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","itemId":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","delta":"2"},"emittedAtMs":1790297771119}}
-{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","itemId":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","delta":"W"},"emittedAtMs":1790297771119}}
-{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","text":"merge-source-4H8Q|merge-fork-7T2W","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","completedAtMs":1790297771282},"emittedAtMs":1790297771285}}
-{"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turnId":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","tokenUsage":{"total":{"totalTokens":61812,"inputTokens":61778,"cachedInputTokens":46336,"cacheWriteInputTokens":0,"outputTokens":34,"reasoningOutputTokens":0},"last":{"totalTokens":22058,"inputTokens":22038,"cachedInputTokens":21760,"cacheWriteInputTokens":0,"outputTokens":20,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790297771334}}
-{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","status":{"type":"idle"}},"emittedAtMs":1790297771343}}
-{"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","turn":{"id":"01a0d610-047d-7b93-92bb-f5a8ffa0666c","items":[{"type":"agentMessage","id":"msg_01a6f3bdd4e03630016ab5c6aad45087d0924564d55dae9a2f","text":"merge-source-4H8Q|merge-fork-7T2W","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790297769,"completedAt":1790297771,"durationMs":2246}},"emittedAtMs":1790297771343}}
-{"type":"runtime_exit","status":"success"}
diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts
index 1cff37136b1..4055fd85b7a 100644
--- a/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts
+++ b/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts
@@ -14,9 +14,7 @@ import {
buildBoundedThreadProjection,
boundedTimelineEncodedBytes,
computeLatestLocalTurnOrdinal,
- decodeThreadHistoryCursor,
encodeThreadHistoryCursor,
- InvalidThreadHistoryCursorError,
projectedRowBoundedSnapshotEncodedBytes,
projectedRowEncodedBytes,
selectHistoryPageFromCursor,
@@ -289,13 +287,6 @@ describe("threadHistoryPaging", () => {
expect([...older.items, ...recent.items]).toHaveLength(items.length);
});
- it("rejects malformed cursors", () => {
- expect(() => decodeThreadHistoryCursor("not-valid")).toThrow(InvalidThreadHistoryCursorError);
- expect(() =>
- decodeThreadHistoryCursor(Buffer.from("{}", "utf8").toString("base64url")),
- ).toThrow(InvalidThreadHistoryCursorError);
- });
-
it("always includes at least one pathological oversized item", () => {
const items = [makeRow(0, { outputBytes: 2_000_000 }), makeRow(1, { outputBytes: 10 })];
const page = selectRecentTimelineWindow({
@@ -433,32 +424,6 @@ describe("threadHistoryPaging", () => {
expect(bounded.hasMoreHistory).toBe(true);
});
- it("retains all run_interrupt_request items even when no result is in the initial window", () => {
- const request = interruptRow(0, "run_interrupt_request");
- const result = interruptRow(1, "run_interrupt_result");
- const recent = makeRow(2);
- const full = makeProjection([request, result, recent]);
- const bounded = buildBoundedThreadProjection({
- projection: full,
- snapshotSequence: 4,
- policy: { maxItems: 1, maxEncodedBytes: 10_000_000 },
- });
-
- expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([
- "item-2",
- ]);
- expect(bounded.projection.turnItems.map((item) => String(item.id)).sort()).toEqual([
- "interrupt-req",
- "item-2",
- ]);
- expect(bounded.projection.turnItems.some((item) => item.type === "run_interrupt_request")).toBe(
- true,
- );
- expect(bounded.projection.turnItems.some((item) => item.type === "run_interrupt_result")).toBe(
- false,
- );
- });
-
it("charges local row.item duplication when measuring bounded timeline bytes", () => {
const rows = Array.from({ length: 8 }, (_, index) => makeRow(index, { outputBytes: 2_000 }));
const full = makeProjection(rows);
diff --git a/apps/server/src/orchestration-v2/toolOutputImageBytes.test.ts b/apps/server/src/orchestration-v2/toolOutputImageBytes.test.ts
index 6d40f5f44ad..4a885dd4cf0 100644
--- a/apps/server/src/orchestration-v2/toolOutputImageBytes.test.ts
+++ b/apps/server/src/orchestration-v2/toolOutputImageBytes.test.ts
@@ -90,6 +90,7 @@ describe("stripUnservedToolOutputImageBytes", () => {
});
});
+ // regression: #16652 stop storing tool image bytes no client reads
it("strips a Cursor image part that names no mime type", () => {
const item = toolItem({
content: [{ text: { text: "captured" } }, { image: { data: PNG_BASE64 } }],
@@ -184,6 +185,7 @@ describe("stripUnservedToolOutputImageBytes", () => {
expect(stripUnservedToolOutputImageBytes(item)).toBe(item);
});
+ // regression: #16652 stop storing tool image bytes no client reads
it("measures the size instead of trusting one the provider supplied", () => {
const item = toolItem({
type: "image",
diff --git a/apps/server/src/orchestration-v2/workflowScriptQuery.test.ts b/apps/server/src/orchestration-v2/workflowScriptQuery.test.ts
index f408534245e..b1106f7bca5 100644
--- a/apps/server/src/orchestration-v2/workflowScriptQuery.test.ts
+++ b/apps/server/src/orchestration-v2/workflowScriptQuery.test.ts
@@ -3,7 +3,6 @@ import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeChildProcess from "node:child_process";
-import { OrchestrationWorkflowFileError } from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { it as effectIt } from "@effect/vitest";
import * as Effect from "effect/Effect";
@@ -51,23 +50,6 @@ describe("workflow script containment", () => {
}),
);
- effectIt.effect("rejects relative and non-js paths", () =>
- Effect.gen(function* () {
- const relative = yield* Effect.exit(readWorkflowScript({ scriptPath: "run.js" }));
- assert.equal(relative._tag, "Failure");
- const nonJs = yield* Effect.exit(
- readWorkflowScript({ scriptPath: scriptPath.replace(".js", ".ts") }),
- );
- assert.equal(nonJs._tag, "Failure");
- const error = yield* Effect.flip(readWorkflowScript({ scriptPath: "run.js" }));
- assert.equal(error._tag, "OrchestrationGetWorkflowScriptError");
- assert.equal(error.scriptPath, "run.js");
- assert.equal(error.reason, "invalid-path");
- assert.equal(error.message, "Workflow scripts must be absolute .js paths.");
- assert.instanceOf(error.cause, OrchestrationWorkflowFileError);
- }),
- );
-
effectIt.effect.skipIf(!symlinksSupported)(
"rejects paths outside the root and symlink escapes",
() =>
diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts
index a8b19d154f4..202f26c32e9 100644
--- a/packages/provider-acp/src/server/adapter.ts
+++ b/packages/provider-acp/src/server/adapter.ts
@@ -384,7 +384,7 @@ export function acpScopedNativeId(instanceId: ProviderInstanceId, nativeId: stri
return `provider-instance:${encodeURIComponent(instanceId)}:${nativeId}`;
}
-export function acpProviderItemNativeId(input: {
+function acpProviderItemNativeId(input: {
readonly instanceId: ProviderInstanceId;
readonly itemIdentityVersion: 2 | undefined;
readonly nativeId: string;
@@ -1219,14 +1219,14 @@ function acpIsProviderContinuationMessage(message: {
return message.createdBy === "agent" && message.creationSource === "provider";
}
-export function acpCarryoverTerminalShouldClearContinuation(input: {
+function acpCarryoverTerminalShouldClearContinuation(input: {
readonly continuationOffered: boolean;
readonly wakeBufferLength: number;
}): boolean {
return !input.continuationOffered && input.wakeBufferLength === 0;
}
-export function acpTurnStartShouldPreserveContinuation(input: {
+function acpTurnStartShouldPreserveContinuation(input: {
readonly continuationRequested: boolean;
readonly isContinuationTurn: boolean;
readonly wakeBufferLength: number;