@devries-cameron20 / t3code Mirror · read-only / commits / 32d8f8f0d0
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 20:45 UTC

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 20, 2026 at 18:36 UTC 32d8f8f0d0e35b7230803e14ad65e886d80864aa
63 files changed +732 -11367
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+234 -2819
@@ -72,13 +72,10 @@ import { makeTurnInput } from "./AcpAdapterV2.testkit.ts";
72 import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
73 import {
74 AcpProviderCapabilitiesV2,
75 - acpProviderItemNativeId,
75 acpScopedNativeId,
77 - acpCarryoverTerminalShouldClearContinuation,
76 acpPostSettleContinuationOfferEvidence,
77 acpPostSettleWakeEvidence,
78 acpToolCallDiffPatch,
81 - acpTurnStartShouldPreserveContinuation,
79 makeAcpAdapterV2,
80 type AcpAdapterV2ExtensionContext,
81 type AcpAdapterV2Flavor,
@@ -133,63 +130,6 @@ describe("acpToolCallDiffPatch", () => {
130 ].join("\n"),
131 );
132 });
136 -
137 - it("drops the patch for a rewrite too large to diff cheaply", () => {
138 - const lines = (prefix: string) =>
139 - Array.from({ length: 2_000 }, (_, index) => `${prefix} ${index}`).join("\n");
140 - assert.isUndefined(
141 - acpToolCallDiffPatch([
142 - { type: "diff", path: "/repo/big.ts", oldText: lines("old"), newText: lines("new") },
143 - ]),
144 - );
145 - });
146 -});
147 -
148 -describe("ACP continuation ownership", () => {
149 - it("preserves a continuation offered during non-buffered carryover handling", () => {
150 - assert.isFalse(
151 - acpCarryoverTerminalShouldClearContinuation({
152 - continuationOffered: true,
153 - wakeBufferLength: 0,
154 - }),
155 - );
156 - assert.isFalse(
157 - acpCarryoverTerminalShouldClearContinuation({
158 - continuationOffered: false,
159 - wakeBufferLength: 1,
160 - }),
161 - );
162 - assert.isTrue(
163 - acpCarryoverTerminalShouldClearContinuation({
164 - continuationOffered: false,
165 - wakeBufferLength: 0,
166 - }),
167 - );
168 - });
169 -
170 - it("preserves only user-raced offers that still own buffered wake traffic", () => {
171 - assert.isTrue(
172 - acpTurnStartShouldPreserveContinuation({
173 - continuationRequested: true,
174 - isContinuationTurn: false,
175 - wakeBufferLength: 1,
176 - }),
177 - );
178 - assert.isFalse(
179 - acpTurnStartShouldPreserveContinuation({
180 - continuationRequested: true,
181 - isContinuationTurn: false,
182 - wakeBufferLength: 0,
183 - }),
184 - );
185 - assert.isFalse(
186 - acpTurnStartShouldPreserveContinuation({
187 - continuationRequested: true,
188 - isContinuationTurn: true,
189 - wakeBufferLength: 1,
190 - }),
191 - );
192 - });
133 });
134
135 function makeMockRuntime(input: {
@@ -487,6 +427,7 @@ describe("AcpAdapterV2", () => {
427 ],
428 }));
429
430 + // regression: #20417 Droid AskUser answers were sent as a cancel
431 it.live.each([
432 {
433 scenario: "preserves selected IDs and encodes custom answers",
@@ -531,19 +472,6 @@ describe("AcpAdapterV2", () => {
472 answers: { name: "Ada" },
473 result: { action: "accept", content: { name: "Ada" } },
474 },
534 - {
535 - scenario: "falls back when the companion field is missing",
536 - schema: {
537 - type: "object",
538 - properties: { question_1: droidChoice },
539 - required: ["question_1"],
540 - },
541 - questions: [
542 - { id: "question_1", header: "Format", question: "Which reply format?", options: [] },
543 - ],
544 - answers: { question_1: "Markdown" },
545 - result: { action: "accept", content: { question_1: "Markdown" } },
546 - },
475 ])("Droid elicitation $scenario", ({ schema, questions, answers, result, withAttachments }) =>
476 Effect.gen(function* () {
477 const fileSystem = yield* FileSystem.FileSystem;
@@ -719,7 +647,7 @@ describe("AcpAdapterV2", () => {
647 }).pipe(Effect.provide(layerTest), Effect.scoped),
648 );
649
722 - it.live.each(["failed", "recovered", "completed", "cancelled"] as const)(
650 + it.live.each(["failed", "recovered", "cancelled"] as const)(
651 "projects Mistral retry notices and their %s outcome",
652 (outcome) =>
653 Effect.gen(function* () {
@@ -806,18 +734,6 @@ describe("AcpAdapterV2", () => {
734 }).pipe(Effect.provide(layerTest), Effect.scoped),
735 );
736
809 - it("preserves legacy ids and scopes v2 ids by provider instance", () => {
810 - const instanceId = ProviderInstanceId.make("acp-identity-test");
811 - assert.equal(
812 - acpProviderItemNativeId({ instanceId, itemIdentityVersion: undefined, nativeId: "item-1" }),
813 - "item-1",
814 - );
815 - assert.equal(
816 - acpProviderItemNativeId({ instanceId, itemIdentityVersion: 2, nativeId: "item-1" }),
817 - acpScopedNativeId(instanceId, "item-1"),
818 - );
819 - });
820 -
737 it.live("refreshes ACP prompt instructions when the interaction mode changes", () =>
738 Effect.gen(function* () {
739 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -1080,7 +996,8 @@ describe("AcpAdapterV2", () => {
996 }).pipe(Effect.provide(layerTest), Effect.scoped),
997 );
998
1083 - it.effect.each(["agent_message_chunk", "agent_thought_chunk"] as const)(
999 + // regression: #21499 turns blocked only on T3 thread waits must show as waiting
1000 + it.effect.each(["agent_message_chunk"] as const)(
1001 "keeps named ACP %s open while deriving thread wait execution state",
1002 (sessionUpdate) =>
1003 Effect.gen(function* () {
@@ -3162,158 +3079,6 @@ describe("AcpAdapterV2", () => {
3079 }).pipe(Effect.provide(layerTest), Effect.scoped),
3080 );
3081
3165 - it.effect("keeps the original ACP session usable when a staged replacement terminates", () =>
3166 - Effect.gen(function* () {
3167 - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
3168 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
3169 - const path = yield* Path.Path;
3170 - const selfInvocation = yield* resolveSelfInvocation();
3171 - const mockAgentPath = yield* path.fromFileUrl(
3172 - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
3173 - );
3174 - let runtimeOrdinal = 0;
3175 - const makeBaseRuntime = makeMockRuntime({
3176 - childProcessSpawner,
3177 - mockAgentPath,
3178 - });
3179 - const makeRuntime: AcpAdapterV2Flavor["makeRuntime"] = (runtimeInput) =>
3180 - Effect.gen(function* () {
3181 - const currentOrdinal = runtimeOrdinal + 1;
3182 - runtimeOrdinal = currentOrdinal;
3183 - const currentRuntime = yield* makeBaseRuntime(runtimeInput);
3184 - if (currentOrdinal === 1) return currentRuntime;
3185 - return {
3186 - ...currentRuntime,
3187 - start: () =>
3188 - currentRuntime.start().pipe(
3189 - Effect.tap(() =>
3190 - runtimeInput.onTermination(
3191 - new EffectAcpErrors.AcpTransportError({
3192 - detail: "Forced staged rollback replacement termination",
3193 - cause: "test",
3194 - }),
3195 - ),
3196 - ),
3197 - ),
3198 - };
3199 - });
3200 - const instanceId = ProviderInstanceId.make("acp-test-rollback-failure-compensation");
3201 - const adapter = yield* makeAcpAdapterV2({
3202 - instanceId,
3203 - flavor: {
3204 - driver: ACP_TEST_DRIVER,
3205 - capabilities: AcpProviderCapabilitiesV2,
3206 - makeRuntime,
3207 - },
3208 - selfInvocation,
3209 - });
3210 - const threadId = ThreadId.make("thread-acp-rollback-failure-compensation");
3211 - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
3212 - runtimeMode: "full-access",
3213 - interactionMode: "default",
3214 - cwd: process.cwd(),
3215 - });
3216 - const modelSelection = { instanceId, model: "default" } as const;
3217 - const runtime = yield* adapter.openSession({
3218 - threadId,
3219 - providerSessionId: ProviderSessionId.make(
3220 - "provider-session-acp-rollback-failure-compensation",
3221 - ),
3222 - modelSelection,
3223 - runtimePolicy,
3224 - });
3225 - const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
3226 - yield* runtime.events.pipe(
3227 - Stream.runForEach((event) => Queue.offer(events, event)),
3228 - Effect.forkScoped,
3229 - );
3230 - const providerThread = yield* runtime.ensureThread({
3231 - threadId,
3232 - modelSelection,
3233 - runtimePolicy,
3234 - });
3235 -
3236 - const rollback = yield* runtime
3237 - .rollbackThread({
3238 - providerThread,
3239 - providerThreadTurns: [],
3240 - target: {
3241 - type: "thread_start",
3242 - checkpointId: CheckpointId.make("checkpoint-acp-rollback-failure-compensation"),
3243 - appRunOrdinal: 0,
3244 - },
3245 - })
3246 - .pipe(Effect.result);
3247 - assert.equal(rollback._tag, "Failure");
3248 -
3249 - yield* runtime.startTurn(
3250 - makeTurnInput({
3251 - threadId,
3252 - providerThread,
3253 - instanceId,
3254 - runtimePolicy,
3255 - now: yield* DateTime.now,
3256 - }),
3257 - );
3258 - const providerTurnId = idAllocator.derive.providerTurn({
3259 - driver: ACP_TEST_DRIVER,
3260 - nativeTurnId: acpScopedNativeId(
3261 - instanceId,
3262 - `${providerThread.nativeThreadRef?.nativeId}:turn:1`,
3263 - ),
3264 - });
3265 - while (true) {
3266 - const event = yield* Queue.take(events);
3267 - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) {
3268 - assert.equal(event.status, "completed");
3269 - break;
3270 - }
3271 - }
3272 - }).pipe(Effect.provide(layerTest), Effect.scoped),
3273 - );
3274 -
3275 - it.effect("closes an idle ACP session exactly once through the transition permit", () =>
3276 - Effect.gen(function* () {
3277 - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
3278 - const path = yield* Path.Path;
3279 - const selfInvocation = yield* resolveSelfInvocation();
3280 - const mockAgentPath = yield* path.fromFileUrl(
3281 - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
3282 - );
3283 - const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
3284 - const instanceId = ProviderInstanceId.make("acp-test");
3285 - const adapter = yield* makeAcpAdapterV2({
3286 - instanceId,
3287 - flavor: {
3288 - driver: ACP_TEST_DRIVER,
3289 - capabilities: AcpProviderCapabilitiesV2,
3290 - makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, protocolEvents }),
3291 - },
3292 - selfInvocation,
3293 - });
3294 - const threadId = ThreadId.make("thread-acp-idle-finalizer");
3295 - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
3296 - runtimeMode: "full-access",
3297 - interactionMode: "default",
3298 - cwd: process.cwd(),
3299 - });
3300 - const modelSelection = { instanceId, model: "default" } as const;
3301 - const sessionScope = yield* Scope.make();
3302 - yield* adapter
3303 - .openSession({
3304 - threadId,
3305 - providerSessionId: ProviderSessionId.make("provider-session-acp-idle-finalizer"),
3306 - modelSelection,
3307 - runtimePolicy,
3308 - })
3309 - .pipe(Effect.provideService(Scope.Scope, sessionScope));
3310 - yield* pollProtocolMethods(protocolEvents);
3311 - yield* Scope.close(sessionScope, Exit.void);
3312 - const finalizerMethods = yield* pollProtocolMethods(protocolEvents);
3313 - assert.equal(finalizerMethods.filter((method) => method === "session/close").length, 1);
3314 - }).pipe(Effect.provide(layerTest)),
3315 - );
3316 -
3082 it.effect("keeps an agent's empty-valued default choice selectable", () =>
3083 Effect.gen(function* () {
3084 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -4009,408 +3774,96 @@ describe("AcpAdapterV2", () => {
3774 }).pipe(Effect.provide(layerTest), Effect.scoped),
3775 );
3776
4012 - it.live("rejects delayed native response registration when normal close wins the permit", () =>
3777 + it.live("treats a second hard Stop as success when the turn is already gone", () =>
3778 Effect.gen(function* () {
3779 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
3780 + const idAllocator = yield* IdAllocator.IdAllocatorV2;
3781 const path = yield* Path.Path;
3782 const selfInvocation = yield* resolveSelfInvocation();
3783 const mockAgentPath = yield* path.fromFileUrl(
3784 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
3785 );
4020 - const registrationStarted = yield* Deferred.make<void>();
4021 - const releaseRegistration = yield* Deferred.make<void>();
4022 - const transportClosed = yield* Deferred.make<void>();
4023 - const releaseTransportClose = yield* Deferred.make<void>();
4024 - const responseLifecycle: Array<string> = [];
4025 - const instanceId = ProviderInstanceId.make("acp-test-close-wins-registration");
3786 + const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
3787 + const instanceId = ProviderInstanceId.make("acp-test");
3788 const adapter = yield* makeAcpAdapterV2({
3789 instanceId,
3790 flavor: {
3791 driver: ACP_TEST_DRIVER,
3792 capabilities: AcpProviderCapabilitiesV2,
3793 + interruptPromptOnCancel: false,
3794 + restartRuntimeAfterInterrupt: true,
3795 + terminateRuntimeProcessGroupOnInterrupt: true,
3796 makeRuntime: makeMockRuntime({
3797 childProcessSpawner,
3798 mockAgentPath,
4034 - environment: { T3_ACP_EMIT_TOOL_CALLS: "1" },
3799 + ownDetachedProcessGroup: true,
3800 + environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" },
3801 + protocolEvents,
3802 }),
3803 },
3804 selfInvocation,
4038 - testHooks: {
4039 - afterNativeResponseTransportClosed: () =>
4040 - Deferred.succeed(transportClosed, undefined).pipe(
4041 - Effect.andThen(Deferred.await(releaseTransportClose)),
4042 - ),
4043 - beforeNativeResponseAdmissionCheck: () =>
4044 - Deferred.succeed(registrationStarted, undefined).pipe(
4045 - Effect.andThen(Deferred.await(releaseRegistration)),
4046 - ),
4047 - onNativeResponseLifecycle: (event) =>
4048 - Effect.sync(() => {
4049 - responseLifecycle.push(event.type);
4050 - }),
4051 - },
3805 });
4053 - const threadId = ThreadId.make("thread-acp-close-wins-registration");
3806 + const threadId = ThreadId.make("thread-acp-double-stop");
3807 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
4055 - runtimeMode: "approval-required",
3808 + runtimeMode: "full-access",
3809 interactionMode: "default",
3810 cwd: process.cwd(),
3811 });
3812 const modelSelection = { instanceId, model: "default" } as const;
4060 - const sessionScope = yield* Scope.make();
4061 - const runtime = yield* adapter
4062 - .openSession({
4063 - threadId,
4064 - providerSessionId: ProviderSessionId.make("provider-session-acp-close-wins-registration"),
4065 - modelSelection,
4066 - runtimePolicy,
4067 - })
4068 - .pipe(Effect.provideService(Scope.Scope, sessionScope));
3813 + const runtime = yield* adapter.openSession({
3814 + threadId,
3815 + providerSessionId: ProviderSessionId.make("provider-session-acp-double-stop"),
3816 + modelSelection,
3817 + runtimePolicy,
3818 + });
3819 + const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
3820 + yield* runtime.events.pipe(
3821 + Stream.runForEach((event) => Queue.offer(events, event)),
3822 + Effect.forkScoped,
3823 + );
3824 const providerThread = yield* runtime.ensureThread({
3825 threadId,
3826 modelSelection,
3827 runtimePolicy,
3828 });
4074 - yield* runtime.startTurn(
4075 - makeTurnInput({
4076 - threadId,
3829 + const now = yield* DateTime.now;
3830 + yield* runtime
3831 + .startTurn(makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }))
3832 + .pipe(Effect.forkScoped);
3833 + yield* Stream.fromQueue(protocolEvents).pipe(
3834 + Stream.filter(
3835 + (event) =>
3836 + event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt",
3837 + ),
3838 + Stream.runHead,
3839 + );
3840 + const providerTurnId = idAllocator.derive.providerTurn({
3841 + driver: ACP_TEST_DRIVER,
3842 + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
3843 + });
3844 + yield* runtime.interruptTurn({
3845 + providerThread,
3846 + providerTurnId,
3847 + requestRuntimeRestart: true,
3848 + });
3849 + const second = yield* Effect.exit(
3850 + runtime.interruptTurn({
3851 providerThread,
4078 - instanceId,
4079 - runtimePolicy,
4080 - now: yield* DateTime.now,
3852 + providerTurnId,
3853 + requestRuntimeRestart: true,
3854 }),
3855 );
4083 - const pending = Option.getOrThrow(
4084 - yield* runtime.events.pipe(
4085 - Stream.filter(
4086 - (event) =>
4087 - event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
4088 - ),
4089 - Stream.runHead,
4090 - ),
4091 - );
4092 - if (pending.type !== "runtime_request.updated") {
4093 - return yield* Effect.die("Expected a pending permission request");
3856 + assert.isTrue(Exit.isSuccess(second), "duplicate hard Stop must be idempotent");
3857 + let terminal: string | null = null;
3858 + while (terminal === null) {
3859 + const event = yield* Queue.take(events);
3860 + if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) {
3861 + terminal = event.status;
3862 + }
3863 }
4095 - const responseFiber = yield* runtime
4096 - .respondToRuntimeRequest({ requestId: pending.runtimeRequest.id, decision: "accept" })
4097 - .pipe(Effect.exit, Effect.forkScoped);
4098 - yield* Deferred.await(registrationStarted);
4099 -
4100 - const closeFiber = yield* Scope.close(sessionScope, Exit.void).pipe(Effect.forkScoped);
4101 - yield* Deferred.await(transportClosed);
4102 - yield* Deferred.succeed(releaseRegistration, undefined);
4103 - while (!responseLifecycle.includes("admission_rejected")) {
4104 - yield* Effect.yieldNow;
4105 - }
4106 - const responseExit = yield* Fiber.join(responseFiber);
4107 - if (Exit.isSuccess(responseExit)) {
4108 - assert.fail("normal close must reject a response delayed before transport registration");
4109 - }
4110 - assert.include(Cause.pretty(responseExit.cause), "ACP session transport closed");
4111 - assert.equal(responseLifecycle.filter((event) => event === "registered").length, 1);
4112 - assert.equal(responseLifecycle.filter((event) => event === "removed").length, 1);
4113 - assert.equal(responseLifecycle.filter((event) => event === "admission_rejected").length, 1);
4114 - yield* Deferred.succeed(releaseTransportClose, undefined);
4115 - yield* Fiber.join(closeFiber);
4116 - }).pipe(Effect.provide(layerTest), Effect.scoped),
4117 - );
4118 -
4119 - it.live("waits for immediate allow and deny permission responses before hard teardown", () =>
4120 - Effect.gen(function* () {
4121 - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
4122 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
4123 - const path = yield* Path.Path;
4124 - const selfInvocation = yield* resolveSelfInvocation();
4125 - const mockAgentPath = yield* path.fromFileUrl(
4126 - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
4127 - );
4128 -
4129 - for (const [name, sandboxPolicy] of [
4130 - ["allow", undefined],
4131 - ["deny", { type: "readOnly" } as const],
4132 - ] as const) {
4133 - yield* Effect.gen(function* () {
4134 - const responseEnqueued = yield* Deferred.make<void>();
4135 - const releaseResponseAcknowledgement = yield* Deferred.make<void>();
4136 - const instanceId = ProviderInstanceId.make(`acp-test-${name}`);
4137 - const adapter = yield* makeAcpAdapterV2({
4138 - instanceId,
4139 - flavor: {
4140 - driver: ACP_TEST_DRIVER,
4141 - capabilities: AcpProviderCapabilitiesV2,
4142 - restartRuntimeAfterInterrupt: true,
4143 - terminateRuntimeProcessGroupOnInterrupt: true,
4144 - makeRuntime: makeMockRuntime({
4145 - childProcessSpawner,
4146 - mockAgentPath,
4147 - environment: { T3_ACP_EMIT_TOOL_CALLS: "1" },
4148 - ownDetachedProcessGroup: true,
4149 - processGroupPlatform: "win32",
4150 - windowsProcessTreeTerminator: (pid) =>
4151 - Effect.sync(() => {
4152 - process.kill(pid, "SIGTERM");
4153 - }),
4154 - wrapOutgoingResponse: (onOutgoingResponse) => (requestId) =>
4155 - Deferred.succeed(responseEnqueued, undefined).pipe(
4156 - Effect.andThen(Deferred.await(releaseResponseAcknowledgement)),
4157 - Effect.andThen(onOutgoingResponse(requestId)),
4158 - ),
4159 - }),
4160 - },
4161 - selfInvocation,
4162 - });
4163 - const threadId = ThreadId.make(`thread-acp-immediate-permission-${name}`);
4164 - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
4165 - runtimeMode: "full-access",
4166 - interactionMode: "default",
4167 - approvalPolicy: "never",
4168 - cwd: process.cwd(),
4169 - ...(sandboxPolicy === undefined ? {} : { sandboxPolicy }),
4170 - });
4171 - const modelSelection = { instanceId, model: "default" } as const;
4172 - const runtime = yield* adapter.openSession({
4173 - threadId,
4174 - providerSessionId: ProviderSessionId.make(
4175 - `provider-session-acp-immediate-permission-${name}`,
4176 - ),
4177 - modelSelection,
4178 - runtimePolicy,
4179 - });
4180 - const providerThread = yield* runtime.ensureThread({
4181 - threadId,
4182 - modelSelection,
4183 - runtimePolicy,
4184 - });
4185 - const turnFiber = yield* runtime
4186 - .startTurn(
4187 - makeTurnInput({
4188 - threadId,
4189 - providerThread,
4190 - instanceId,
4191 - runtimePolicy,
4192 - now: yield* DateTime.now,
4193 - }),
4194 - )
4195 - .pipe(Effect.forkDetach);
4196 - yield* Deferred.await(responseEnqueued);
4197 - const interruptFiber = yield* runtime
4198 - .interruptTurn({
4199 - providerThread,
4200 - providerTurnId: idAllocator.derive.providerTurn({
4201 - driver: ACP_TEST_DRIVER,
4202 - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
4203 - }),
4204 - requestRuntimeRestart: true,
4205 - })
4206 - .pipe(Effect.forkScoped);
4207 - yield* Effect.yieldNow;
4208 - assert.isUndefined(interruptFiber.pollUnsafe());
4209 -
4210 - yield* Deferred.succeed(releaseResponseAcknowledgement, undefined);
4211 - yield* Fiber.join(interruptFiber);
4212 - yield* Fiber.interrupt(turnFiber).pipe(Effect.forkDetach);
4213 - }).pipe(Effect.scoped);
4214 - }
4215 - }).pipe(Effect.provide(layerTest), Effect.scoped),
4216 - );
4217 -
4218 - it.live("rejects an elicitation response when hard teardown wins admission", () =>
4219 - Effect.gen(function* () {
4220 - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
4221 - const path = yield* Path.Path;
4222 - const selfInvocation = yield* resolveSelfInvocation();
4223 - const mockAgentPath = yield* path.fromFileUrl(
4224 - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
4225 - );
4226 - const teardownStarted = yield* Deferred.make<void>();
4227 - const releaseTeardown = yield* Deferred.make<void>();
4228 - const instanceId = ProviderInstanceId.make("acp-test");
4229 - const adapter = yield* makeAcpAdapterV2({
4230 - instanceId,
4231 - flavor: {
4232 - driver: ACP_TEST_DRIVER,
4233 - capabilities: AcpProviderCapabilitiesV2,
4234 - restartRuntimeAfterInterrupt: true,
4235 - terminateRuntimeProcessGroupOnInterrupt: true,
4236 - makeRuntime: makeMockRuntime({
4237 - childProcessSpawner,
4238 - mockAgentPath,
4239 - environment: { T3_ACP_EMIT_ELICITATION: "1" },
4240 - ownDetachedProcessGroup: true,
4241 - processGroupPlatform: "win32",
4242 - windowsProcessTreeTerminator: (pid) =>
4243 - Deferred.succeed(teardownStarted, undefined).pipe(
4244 - Effect.andThen(Deferred.await(releaseTeardown)),
4245 - Effect.andThen(
4246 - Effect.sync(() => {
4247 - process.kill(pid, "SIGTERM");
4248 - }),
4249 - ),
4250 - ),
4251 - }),
4252 - },
4253 - selfInvocation,
4254 - });
4255 - const threadId = ThreadId.make("thread-acp-teardown-wins-elicitation");
4256 - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
4257 - runtimeMode: "approval-required",
4258 - interactionMode: "default",
4259 - cwd: process.cwd(),
4260 - });
4261 - const modelSelection = { instanceId, model: "default" } as const;
4262 - const runtime = yield* adapter.openSession({
4263 - threadId,
4264 - providerSessionId: ProviderSessionId.make("provider-session-acp-teardown-wins-elicitation"),
4265 - modelSelection,
4266 - runtimePolicy,
4267 - });
4268 - const providerThread = yield* runtime.ensureThread({
4269 - threadId,
4270 - modelSelection,
4271 - runtimePolicy,
4272 - });
4273 - yield* runtime.startTurn(
4274 - makeTurnInput({
4275 - threadId,
4276 - providerThread,
4277 - instanceId,
4278 - runtimePolicy,
4279 - now: yield* DateTime.now,
4280 - }),
4281 - );
4282 - const pending = Option.getOrThrow(
4283 - yield* runtime.events.pipe(
4284 - Stream.filter(
4285 - (event) =>
4286 - event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
4287 - ),
4288 - Stream.runHead,
4289 - ),
4290 - );
4291 - if (
4292 - pending.type !== "runtime_request.updated" ||
4293 - pending.runtimeRequest.providerTurnId === null
4294 - ) {
4295 - return yield* Effect.die("Expected a pending elicitation request");
4296 - }
4297 - const interruptFiber = yield* runtime
4298 - .interruptTurn({
4299 - providerThread,
4300 - providerTurnId: pending.runtimeRequest.providerTurnId,
4301 - requestRuntimeRestart: true,
4302 - })
4303 - .pipe(Effect.forkScoped);
4304 - yield* Deferred.await(teardownStarted);
4305 - const responseFiber = yield* runtime
4306 - .respondToRuntimeRequest({
4307 - requestId: pending.runtimeRequest.id,
4308 - answers: { approved: ["true"] },
4309 - })
4310 - .pipe(Effect.exit, Effect.forkScoped);
4311 - yield* Effect.yieldNow;
4312 - assert.isUndefined(responseFiber.pollUnsafe());
4313 -
4314 - yield* Deferred.succeed(releaseTeardown, undefined);
4315 - yield* Fiber.join(interruptFiber);
4316 - const responseExit = yield* Fiber.join(responseFiber);
4317 - if (Exit.isSuccess(responseExit)) {
4318 - assert.fail("teardown winning admission must reject the elicitation response");
4319 - }
4320 - assert.include(Cause.pretty(responseExit.cause), "No pending ACP runtime request");
4321 - }).pipe(Effect.provide(layerTest), Effect.scoped),
4322 - );
4323 -
4324 - it.live("treats a second hard Stop as success when the turn is already gone", () =>
4325 - Effect.gen(function* () {
4326 - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
4327 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
4328 - const path = yield* Path.Path;
4329 - const selfInvocation = yield* resolveSelfInvocation();
4330 - const mockAgentPath = yield* path.fromFileUrl(
4331 - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
4332 - );
4333 - const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
4334 - const instanceId = ProviderInstanceId.make("acp-test");
4335 - const adapter = yield* makeAcpAdapterV2({
4336 - instanceId,
4337 - flavor: {
4338 - driver: ACP_TEST_DRIVER,
4339 - capabilities: AcpProviderCapabilitiesV2,
4340 - interruptPromptOnCancel: false,
4341 - restartRuntimeAfterInterrupt: true,
4342 - terminateRuntimeProcessGroupOnInterrupt: true,
4343 - makeRuntime: makeMockRuntime({
4344 - childProcessSpawner,
4345 - mockAgentPath,
4346 - ownDetachedProcessGroup: true,
4347 - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" },
4348 - protocolEvents,
4349 - }),
4350 - },
4351 - selfInvocation,
4352 - });
4353 - const threadId = ThreadId.make("thread-acp-double-stop");
4354 - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
4355 - runtimeMode: "full-access",
4356 - interactionMode: "default",
4357 - cwd: process.cwd(),
4358 - });
4359 - const modelSelection = { instanceId, model: "default" } as const;
4360 - const runtime = yield* adapter.openSession({
4361 - threadId,
4362 - providerSessionId: ProviderSessionId.make("provider-session-acp-double-stop"),
4363 - modelSelection,
4364 - runtimePolicy,
4365 - });
4366 - const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
4367 - yield* runtime.events.pipe(
4368 - Stream.runForEach((event) => Queue.offer(events, event)),
4369 - Effect.forkScoped,
4370 - );
4371 - const providerThread = yield* runtime.ensureThread({
4372 - threadId,
4373 - modelSelection,
4374 - runtimePolicy,
4375 - });
4376 - const now = yield* DateTime.now;
4377 - yield* runtime
4378 - .startTurn(makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }))
4379 - .pipe(Effect.forkScoped);
4380 - yield* Stream.fromQueue(protocolEvents).pipe(
4381 - Stream.filter(
4382 - (event) =>
4383 - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt",
4384 - ),
4385 - Stream.runHead,
4386 - );
4387 - const providerTurnId = idAllocator.derive.providerTurn({
4388 - driver: ACP_TEST_DRIVER,
4389 - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
4390 - });
4391 - yield* runtime.interruptTurn({
4392 - providerThread,
4393 - providerTurnId,
4394 - requestRuntimeRestart: true,
4395 - });
4396 - const second = yield* Effect.exit(
4397 - runtime.interruptTurn({
4398 - providerThread,
4399 - providerTurnId,
4400 - requestRuntimeRestart: true,
4401 - }),
4402 - );
4403 - assert.isTrue(Exit.isSuccess(second), "duplicate hard Stop must be idempotent");
4404 - let terminal: string | null = null;
4405 - while (terminal === null) {
4406 - const event = yield* Queue.take(events);
4407 - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) {
4408 - terminal = event.status;
4409 - }
4410 - }
4411 - assert.equal(terminal, "interrupted");
4412 - }).pipe(Effect.provide(layerTest), Effect.scoped),
4413 - );
3864 + assert.equal(terminal, "interrupted");
3865 + }).pipe(Effect.provide(layerTest), Effect.scoped),
3866 + );
3867
3868 it.effect("finalizes a settled turn held open for background work when interrupted", () =>
3869 Effect.gen(function* () {
@@ -4638,230 +4091,6 @@ describe("AcpAdapterV2", () => {
4091 }).pipe(Effect.provide(layerTest), Effect.scoped),
4092 );
4093
4641 - it.effect("handles a child terminal after carryover rehydrate", () =>
4642 - Effect.gen(function* () {
4643 - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
4644 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
4645 - const path = yield* Path.Path;
4646 - const selfInvocation = yield* resolveSelfInvocation();
4647 - const mockAgentPath = yield* path.fromFileUrl(
4648 - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
4649 - );
4650 - const secondPromptWireReturned = yield* Deferred.make<void>();
4651 - const releaseSecondPromptCompletion = yield* Deferred.make<void>();
4652 - const instanceId = ProviderInstanceId.make("acp-test");
4653 - const childSessionId = "mock-child-session-active-carryover";
4654 - let promptCount = 0;
4655 - let subagentPhase: "spawn" | "complete" = "spawn";
4656 - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
4657 - let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
4658 - const promptSettled = yield* Deferred.make<void>();
4659 - const adapter = yield* makeAcpAdapterV2({
4660 - testHooks: {
4661 - afterPromptSettledWithBackgroundWork: () =>
4662 - Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid),
4663 - },
4664 - instanceId,
4665 - flavor: {
4666 - driver: ACP_TEST_DRIVER,
4667 - capabilities: AcpProviderCapabilitiesV2,
4668 - deferFinalizeForBackgroundWork: true,
4669 - enablePostSettleContinuation: true,
4670 - extractSubagentUpdate: (toolCall) =>
4671 - toolCall.toolCallId !== "tool-call-generic-1"
4672 - ? undefined
4673 - : subagentPhase === "spawn"
4674 - ? {
4675 - nativeTaskId: "task-generic-1",
4676 - prompt: "background subagent",
4677 - title: "background subagent",
4678 - model: null,
4679 - status: "running",
4680 - childSessionId,
4681 - result: null,
4682 - }
4683 - : {
4684 - nativeTaskId: "task-generic-1",
4685 - prompt: "",
4686 - title: null,
4687 - model: null,
4688 - status: "completed",
4689 - childSessionId,
4690 - result: "SUB_DONE",
4691 - },
4692 - makeRuntime: makeMockRuntime({
4693 - childProcessSpawner,
4694 - mockAgentPath,
4695 - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" },
4696 - wrapRuntime: (runtime) => ({
4697 - ...runtime,
4698 - handleSessionUpdate: (handler) =>
4699 - Effect.sync(() => {
4700 - sessionUpdateHandler = handler;
4701 - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
4702 - prompt: (payload) =>
4703 - Effect.gen(function* () {
4704 - const currentPrompt = ++promptCount;
4705 - const result = yield* runtime.prompt(payload);
4706 - if (currentPrompt === 2) {
4707 - yield* Deferred.succeed(secondPromptWireReturned, undefined);
4708 - yield* Deferred.await(releaseSecondPromptCompletion);
4709 - }
4710 - return result;
4711 - }),
4712 - }),
4713 - }),
4714 - },
4715 - selfInvocation,
4716 - continuationRequests: { offer: () => Effect.void },
4717 - });
4718 - const threadId = ThreadId.make("thread-acp-active-carryover-pending-pin");
4719 - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
4720 - runtimeMode: "full-access",
4721 - interactionMode: "default",
4722 - cwd: process.cwd(),
4723 - });
4724 - const modelSelection = { instanceId, model: "default" } as const;
4725 - const runtime = yield* adapter.openSession({
4726 - threadId,
4727 - providerSessionId: ProviderSessionId.make(
4728 - "provider-session-acp-active-carryover-pending-pin",
4729 - ),
4730 - modelSelection,
4731 - runtimePolicy,
4732 - });
4733 - if (runtime.hasPendingBackgroundWork === undefined) {
4734 - return yield* Effect.die(
4735 - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.",
4736 - );
4737 - }
4738 - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
4739 - const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
4740 - yield* runtime.events.pipe(
4741 - Stream.runForEach((event) => Queue.offer(events, event)),
4742 - Effect.forkScoped,
4743 - );
4744 - const providerThread = yield* runtime.ensureThread({
4745 - threadId,
4746 - modelSelection,
4747 - runtimePolicy,
4748 - });
4749 - const now = yield* DateTime.now;
4750 - yield* runtime.startTurn(
4751 - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }),
4752 - );
4753 - yield* Deferred.await(promptSettled);
4754 -
4755 - const firstProviderTurnId = idAllocator.derive.providerTurn({
4756 - driver: ACP_TEST_DRIVER,
4757 - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
4758 - });
4759 - yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId });
4760 -
4761 - let firstTerminalStatus: string | null = null;
4762 - while (firstTerminalStatus === null) {
4763 - const event = yield* Queue.take(events);
4764 - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) {
4765 - firstTerminalStatus = event.status;
4766 - }
4767 - }
4768 - assert.equal(firstTerminalStatus, "interrupted");
4769 - assert.isTrue(yield* hasPendingBackgroundWork);
4770 - assert.isDefined(sessionUpdateHandler, "session update handler must be wired");
4771 -
4772 - const secondNow = yield* DateTime.now;
4773 - const secondTurnFiber = yield* runtime
4774 - .startTurn(
4775 - makeTurnInput({
4776 - threadId,
4777 - providerThread,
4778 - instanceId,
4779 - runtimePolicy,
4780 - now: secondNow,
4781 - ordinal: 2,
4782 - }),
4783 - )
4784 - .pipe(Effect.forkScoped);
4785 - yield* Deferred.await(secondPromptWireReturned);
4786 - assert.isTrue(
4787 - yield* hasPendingBackgroundWork,
4788 - "rehydrated live subagent must pin from activeTurn",
4789 - );
4790 - while (Option.isSome(yield* Queue.poll(events))) {}
4791 -
4792 - subagentPhase = "complete";
4793 - yield* sessionUpdateHandler!({
4794 - sessionId: childSessionId,
4795 - update: {
4796 - sessionUpdate: "tool_call_update",
4797 - toolCallId: "tool-call-generic-1",
4798 - title: "background subagent",
4799 - kind: "other",
4800 - status: "completed",
4801 - rawOutput: { content: "SUB_DONE" },
4802 - },
4803 - });
4804 - yield* sessionUpdateHandler!({
4805 - sessionId: childSessionId,
4806 - update: {
4807 - sessionUpdate: "tool_call_update",
4808 - toolCallId: "tool-call-generic-1",
4809 - title: "background subagent",
4810 - kind: "other",
4811 - status: "completed",
4812 - rawOutput: { content: "SUB_DONE" },
4813 - },
4814 - });
4815 - subagentPhase = "spawn";
4816 - yield* sessionUpdateHandler!({
4817 - sessionId: childSessionId,
4818 - update: {
4819 - sessionUpdate: "tool_call_update",
4820 - toolCallId: "tool-call-generic-1",
4821 - title: "background subagent",
4822 - kind: "other",
4823 - status: "in_progress",
4824 - rawOutput: {},
4825 - },
4826 - });
4827 - yield* Effect.yieldNow;
4828 - yield* Effect.yieldNow;
4829 - assert.isFalse(
4830 - yield* hasPendingBackgroundWork,
4831 - "active-turn pin must clear after the child-session terminal is projected",
4832 - );
4833 - let completedSubagentUpdates = 0;
4834 - let resurrectedSubagentUpdates = 0;
4835 - let normalChildToolUpdates = 0;
4836 - let polled = yield* Queue.poll(events);
4837 - while (Option.isSome(polled)) {
4838 - const event = polled.value;
4839 - if (event.type === "turn_item.updated") {
4840 - if (event.turnItem.type === "subagent") {
4841 - if (event.turnItem.status === "completed") {
4842 - completedSubagentUpdates += 1;
4843 - }
4844 - if (
4845 - event.turnItem.status === "running" &&
4846 - event.turnItem.nativeItemRef?.nativeId === "task-generic-1"
4847 - ) {
4848 - resurrectedSubagentUpdates += 1;
4849 - }
4850 - } else if (event.turnItem.nativeItemRef?.nativeId === "tool-call-generic-1") {
4851 - normalChildToolUpdates += 1;
4852 - }
4853 - }
4854 - polled = yield* Queue.poll(events);
4855 - }
4856 - assert.equal(completedSubagentUpdates, 1);
4857 - assert.equal(resurrectedSubagentUpdates, 0);
4858 - assert.equal(normalChildToolUpdates, 0);
4859 -
4860 - yield* Deferred.succeed(releaseSecondPromptCompletion, undefined);
4861 - yield* Fiber.join(secondTurnFiber);
4862 - }).pipe(Effect.provide(layerTest), Effect.scoped),
4863 - );
4864 -
4094 it.effect(
4095 "projects a child terminal in the completed-root finalization window exactly once",
4096 () =>
@@ -5075,357 +4304,6 @@ describe("AcpAdapterV2", () => {
4304 }).pipe(Effect.provide(layerTest), Effect.scoped),
4305 );
4306
5078 - it.effect(
5079 - "defers an interrupted pending-spawn carryover terminal until the next observable attach",
5080 - () =>
5081 - Effect.gen(function* () {
5082 - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
5083 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
5084 - const path = yield* Path.Path;
5085 - const selfInvocation = yield* resolveSelfInvocation();
5086 - const mockAgentPath = yield* path.fromFileUrl(
5087 - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
5088 - );
5089 - const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
5090 - const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
5091 - [];
5092 - const promptSettled = yield* Deferred.make<void>();
5093 - const instanceId = ProviderInstanceId.make("acp-test");
5094 - const childSessionId = "mock-child-session-post-settle";
5095 - let subagentPhase: "spawn" | "complete" = "spawn";
5096 - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
5097 - let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
5098 - const adapter = yield* makeAcpAdapterV2({
5099 - testHooks: {
5100 - afterPromptSettledWithBackgroundWork: () =>
5101 - Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid),
5102 - },
5103 - instanceId,
5104 - flavor: {
5105 - driver: ACP_TEST_DRIVER,
5106 - capabilities: AcpProviderCapabilitiesV2,
5107 - deferFinalizeForBackgroundWork: true,
5108 - enablePostSettleContinuation: true,
5109 - extractSubagentUpdate: (toolCall) =>
5110 - toolCall.toolCallId !== "tool-call-generic-1"
5111 - ? undefined
5112 - : subagentPhase === "spawn"
5113 - ? {
5114 - nativeTaskId: "task-generic-1",
5115 - prompt: "background subagent",
5116 - title: "background subagent",
5117 - model: null,
5118 - status: "pending",
5119 - childSessionId,
5120 - result: null,
5121 - }
5122 - : {
5123 - nativeTaskId: "task-generic-1",
5124 - prompt: "",
5125 - title: null,
5126 - model: null,
5127 - status: "completed",
5128 - childSessionId,
5129 - result: "SUB_DONE",
5130 - },
5131 - makeRuntime: makeMockRuntime({
5132 - childProcessSpawner,
5133 - mockAgentPath,
5134 - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" },
5135 - protocolEvents,
5136 - wrapRuntime: (runtime) => ({
5137 - ...runtime,
5138 - handleSessionUpdate: (handler) =>
5139 - Effect.sync(() => {
5140 - sessionUpdateHandler = handler;
5141 - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
5142 - }),
5143 - }),
5144 - },
5145 - selfInvocation,
5146 - continuationRequests: {
5147 - offer: (request) =>
5148 - Effect.sync(() => {
5149 - continuationRequests.push(request);
5150 - }),
5151 - },
5152 - });
5153 - const threadId = ThreadId.make("thread-acp-carryover-child-session-post-settle");
5154 - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
5155 - runtimeMode: "full-access",
5156 - interactionMode: "default",
5157 - cwd: process.cwd(),
5158 - });
5159 - const modelSelection = { instanceId, model: "default" } as const;
5160 - const runtime = yield* adapter.openSession({
5161 - threadId,
5162 - providerSessionId: ProviderSessionId.make(
5163 - "provider-session-acp-carryover-child-session-post-settle",
5164 - ),
5165 - modelSelection,
5166 - runtimePolicy,
5167 - });
5168 - if (runtime.hasPendingBackgroundWork === undefined) {
5169 - return yield* Effect.die(
5170 - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.",
5171 - );
5172 - }
5173 - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
5174 - const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
5175 - yield* runtime.events.pipe(
5176 - Stream.runForEach((event) => Queue.offer(events, event)),
5177 - Effect.forkScoped,
5178 - );
5179 - const providerThread = yield* runtime.ensureThread({
5180 - threadId,
5181 - modelSelection,
5182 - runtimePolicy,
5183 - });
5184 - const now = yield* DateTime.now;
5185 - yield* runtime.startTurn(
5186 - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }),
5187 - );
5188 - yield* Deferred.await(promptSettled);
5189 -
5190 - const firstProviderTurnId = idAllocator.derive.providerTurn({
5191 - driver: ACP_TEST_DRIVER,
5192 - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
5193 - });
5194 - yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId });
5195 -
5196 - let firstTerminalStatus: string | null = null;
5197 - while (firstTerminalStatus === null) {
5198 - const event = yield* Queue.take(events);
5199 - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) {
5200 - firstTerminalStatus = event.status;
5201 - }
5202 - }
5203 - assert.equal(firstTerminalStatus, "interrupted");
5204 - assert.isTrue(
5205 - yield* hasPendingBackgroundWork,
5206 - "carryover live subagent must pin hasPendingBackgroundWork after root settle",
5207 - );
5208 - assert.isDefined(sessionUpdateHandler, "session update handler must be wired");
5209 -
5210 - subagentPhase = "complete";
5211 - yield* sessionUpdateHandler!({
5212 - sessionId: childSessionId,
5213 - update: {
5214 - sessionUpdate: "tool_call_update",
5215 - toolCallId: "tool-call-generic-1",
5216 - title: "background subagent",
5217 - kind: "other",
5218 - status: "completed",
5219 - rawOutput: { content: "SUB_DONE" },
5220 - },
5221 - });
5222 - yield* Effect.yieldNow;
5223 - yield* Effect.yieldNow;
5224 - let completedBeforeAttach = 0;
5225 - let polled = yield* Queue.poll(events);
5226 - while (Option.isSome(polled)) {
5227 - const event = polled.value;
5228 - if (
5229 - event.type === "turn_item.updated" &&
5230 - event.turnItem.type === "subagent" &&
5231 - event.turnItem.status === "completed"
5232 - ) {
5233 - completedBeforeAttach += 1;
5234 - }
5235 - polled = yield* Queue.poll(events);
5236 - }
5237 - assert.equal(
5238 - completedBeforeAttach,
5239 - 0,
5240 - "closed interrupted subscription must not be treated as projected",
5241 - );
5242 - assert.isTrue(
5243 - yield* hasPendingBackgroundWork,
5244 - "terminal carryover must stay pinned until an attach can project it",
5245 - );
5246 - assert.lengthOf(
5247 - continuationRequests,
5248 - 0,
5249 - "child-session completion must not open a root continuation",
5250 - );
5251 -
5252 - const attachNow = yield* DateTime.now;
5253 - yield* runtime.startTurn(
5254 - makeTurnInput({
5255 - threadId,
5256 - providerThread,
5257 - instanceId,
5258 - runtimePolicy,
5259 - now: attachNow,
5260 - ordinal: 2,
5261 - messageCreatedBy: "agent",
5262 - messageCreationSource: "provider",
5263 - messageText: "Attach deferred completion.",
5264 - }),
5265 - );
5266 - const attachProviderTurnId = idAllocator.derive.providerTurn({
5267 - driver: ACP_TEST_DRIVER,
5268 - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"),
5269 - });
5270 - let attachTerminal: string | null = null;
5271 - let completedAfterAttach = 0;
5272 - while (attachTerminal === null) {
5273 - const event = yield* Queue.take(events);
5274 - if (
5275 - event.type === "turn_item.updated" &&
5276 - event.turnItem.type === "subagent" &&
5277 - event.turnItem.status === "completed"
5278 - ) {
5279 - completedAfterAttach += 1;
5280 - }
5281 - if (event.type === "turn.terminal" && event.providerTurnId === attachProviderTurnId) {
5282 - attachTerminal = event.status;
5283 - }
5284 - }
5285 - assert.equal(attachTerminal, "completed");
5286 - assert.equal(completedAfterAttach, 1);
5287 - assert.isFalse(yield* hasPendingBackgroundWork);
5288 - }).pipe(Effect.provide(layerTest), Effect.scoped),
5289 - );
5290 -
5291 - it.effect("finishes a settled root's carryover subagent from its structured end", () =>
5292 - Effect.gen(function* () {
5293 - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
5294 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
5295 - const path = yield* Path.Path;
5296 - const selfInvocation = yield* resolveSelfInvocation();
5297 - const mockAgentPath = yield* path.fromFileUrl(
5298 - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
5299 - );
5300 - const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
5301 - const instanceId = ProviderInstanceId.make("acp-test");
5302 - const childSessionId = "019f44a6-4820-7402-925d-bc862ee711dd";
5303 - let finishSubagent: AcpAdapterV2ExtensionContext["finishSubagent"] | undefined;
5304 - const adapter = yield* makeAcpAdapterV2({
5305 - instanceId,
5306 - flavor: {
5307 - driver: ACP_TEST_DRIVER,
5308 - capabilities: AcpProviderCapabilitiesV2,
5309 - enablePostSettleContinuation: true,
5310 - extractSubagentUpdate: (toolCall) =>
5311 - toolCall.toolCallId !== "tool-call-generic-1"
5312 - ? undefined
5313 - : {
5314 - nativeTaskId: "task-generic-1",
5315 - prompt: "background subagent",
5316 - title: "background subagent",
5317 - model: null,
5318 - status: "running",
5319 - childSessionId,
5320 - result: null,
5321 - },
5322 - registerExtensions: (context) =>
5323 - Effect.sync(() => {
5324 - finishSubagent = context.finishSubagent;
5325 - }),
5326 - makeRuntime: makeMockRuntime({
5327 - childProcessSpawner,
5328 - mockAgentPath,
5329 - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" },
5330 - protocolEvents,
5331 - }),
5332 - },
5333 - selfInvocation,
5334 - continuationRequests: { offer: () => Effect.void },
5335 - });
5336 - const threadId = ThreadId.make("thread-acp-carryover-subagent-finished");
5337 - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
5338 - runtimeMode: "full-access",
5339 - interactionMode: "default",
5340 - cwd: process.cwd(),
5341 - });
5342 - const modelSelection = { instanceId, model: "default" } as const;
5343 - const runtime = yield* adapter.openSession({
5344 - threadId,
5345 - providerSessionId: ProviderSessionId.make("provider-session-acp-carryover-finished"),
5346 - modelSelection,
5347 - runtimePolicy,
5348 - });
5349 - if (runtime.hasPendingBackgroundWork === undefined) {
5350 - return yield* Effect.die("post-settle continuation must expose hasPendingBackgroundWork");
5351 - }
5352 - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
5353 - const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
5354 - yield* runtime.events.pipe(
5355 - Stream.runForEach((event) => Queue.offer(events, event)),
5356 - Effect.forkScoped,
5357 - );
5358 - const providerThread = yield* runtime.ensureThread({
5359 - threadId,
5360 - modelSelection,
5361 - runtimePolicy,
5362 - });
5363 - yield* runtime.startTurn(
5364 - makeTurnInput({
5365 - threadId,
5366 - providerThread,
5367 - instanceId,
5368 - runtimePolicy,
5369 - now: yield* DateTime.now,
5370 - }),
5371 - );
5372 - const providerTurnId = idAllocator.derive.providerTurn({
5373 - driver: ACP_TEST_DRIVER,
5374 - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
5375 - });
5376 - let rootStatus: string | null = null;
5377 - while (rootStatus === null) {
5378 - const event = yield* Queue.take(events);
5379 - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) {
5380 - rootStatus = event.status;
5381 - }
5382 - }
5383 - assert.equal(rootStatus, "completed");
5384 - assert.isTrue(yield* hasPendingBackgroundWork);
5385 - assert.isDefined(finishSubagent);
5386 - const subagentStatuses = Effect.gen(function* () {
5387 - yield* Effect.yieldNow;
5388 - yield* Effect.yieldNow;
5389 - const statuses: Array<[string, string | null]> = [];
5390 - let polled = yield* Queue.poll(events);
5391 - while (Option.isSome(polled)) {
5392 - const event = polled.value;
5393 - if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") {
5394 - statuses.push([event.turnItem.status, event.turnItem.result]);
5395 - }
5396 - polled = yield* Queue.poll(events);
5397 - }
5398 - return statuses;
5399 - });
5400 - yield* subagentStatuses;
5401 -
5402 - yield* finishSubagent!({
5403 - sessionId: "some-other-session",
5404 - childSessionId,
5405 - status: "completed",
5406 - result: "WRONG_PARENT",
5407 - });
5408 - assert.deepEqual(yield* subagentStatuses, [], "non-root notices must be dropped");
5409 - assert.isTrue(yield* hasPendingBackgroundWork);
5410 -
5411 - yield* finishSubagent!({
5412 - sessionId: "mock-session-1",
5413 - childSessionId,
5414 - status: "failed",
5415 - result: "tool crashed",
5416 - });
5417 - assert.deepEqual(
5418 - yield* subagentStatuses,
5419 - [["failed", "tool crashed"]],
5420 - "the completed root still owns the run, so the carryover end projects at once",
5421 - );
5422 - assert.isFalse(
5423 - yield* hasPendingBackgroundWork,
5424 - "a finished carryover subagent stops pinning",
5425 - );
5426 - }).pipe(Effect.provide(layerTest), Effect.scoped),
5427 - );
5428 -
4307 it.effect("projects completed-root carryover eagerly and drain cannot resurrect it", () =>
4308 Effect.gen(function* () {
4309 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -5647,572 +4525,29 @@ describe("AcpAdapterV2", () => {
4525 }
4526 if (
4527 event.type === "turn_item.updated" &&
5650 - event.turnItem.runId === continuationInput.runId
5651 - ) {
5652 - replayedTurnItems += 1;
5653 - }
5654 - polled = yield* Queue.poll(events);
5655 - }
5656 - assert.equal(replayedLineages, 0, "buffered spawn ACK must not create a second lineage");
5657 - assert.equal(
5658 - replayedSubagentUpdates,
5659 - 0,
5660 - "buffered spawn ACK must not re-open the terminal subagent",
5661 - );
5662 - assert.equal(
5663 - replayedTurnItems,
5664 - 0,
5665 - "buffered spawn ACK must not create a continuation-owned turn item",
5666 - );
5667 - assert.isFalse(yield* hasPendingBackgroundWork);
5668 - }).pipe(Effect.provide(layerTest), Effect.scoped),
5669 - );
5670 -
5671 - it.effect(
5672 - "user attach flushes a deferred terminal but leaves wake traffic for its continuation",
5673 - () =>
5674 - Effect.gen(function* () {
5675 - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
5676 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
5677 - const path = yield* Path.Path;
5678 - const selfInvocation = yield* resolveSelfInvocation();
5679 - const mockAgentPath = yield* path.fromFileUrl(
5680 - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
5681 - );
5682 - const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
5683 - [];
5684 - const bufferedAssistantText = "BUFFERED_WAKE_AFTER_USER_ATTACH";
5685 - const instanceId = ProviderInstanceId.make("acp-test");
5686 - let subagentPhase: "spawn" | "complete" = "spawn";
5687 - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
5688 - let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
5689 - const promptSettled = yield* Deferred.make<void>();
5690 - const adapter = yield* makeAcpAdapterV2({
5691 - testHooks: {
5692 - afterPromptSettledWithBackgroundWork: () =>
5693 - Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid),
5694 - },
5695 - instanceId,
5696 - flavor: {
5697 - driver: ACP_TEST_DRIVER,
5698 - capabilities: AcpProviderCapabilitiesV2,
5699 - deferFinalizeForBackgroundWork: true,
5700 - enablePostSettleContinuation: true,
5701 - extractSubagentUpdate: (toolCall) =>
5702 - toolCall.toolCallId !== "tool-call-generic-1"
5703 - ? undefined
5704 - : subagentPhase === "spawn"
5705 - ? {
5706 - nativeTaskId: "task-generic-1",
5707 - prompt: "background subagent",
5708 - title: "background subagent",
5709 - model: null,
5710 - status: "running",
5711 - childSessionId: null,
5712 - result: null,
5713 - }
5714 - : {
5715 - nativeTaskId: "task-generic-1",
5716 - prompt: "",
5717 - title: null,
5718 - model: null,
5719 - status: "completed",
5720 - childSessionId: null,
5721 - result: "SUB_DONE",
5722 - },
5723 - makeRuntime: makeMockRuntime({
5724 - childProcessSpawner,
5725 - mockAgentPath,
5726 - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" },
5727 - wrapRuntime: (runtime) => ({
5728 - ...runtime,
5729 - handleSessionUpdate: (handler) =>
5730 - Effect.sync(() => {
5731 - sessionUpdateHandler = handler;
5732 - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
5733 - }),
5734 - }),
5735 - },
5736 - selfInvocation,
5737 - continuationRequests: {
5738 - offer: (request) =>
5739 - Effect.sync(() => {
5740 - continuationRequests.push(request);
5741 - }),
5742 - },
5743 - });
5744 - const threadId = ThreadId.make("thread-acp-carryover-root-session-continuation");
5745 - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
5746 - runtimeMode: "full-access",
5747 - interactionMode: "default",
5748 - cwd: process.cwd(),
5749 - });
5750 - const modelSelection = { instanceId, model: "default" } as const;
5751 - const runtime = yield* adapter.openSession({
5752 - threadId,
5753 - providerSessionId: ProviderSessionId.make(
5754 - "provider-session-acp-carryover-root-session-continuation",
5755 - ),
5756 - modelSelection,
5757 - runtimePolicy,
5758 - });
5759 - if (runtime.hasPendingBackgroundWork === undefined) {
5760 - return yield* Effect.die(
5761 - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.",
5762 - );
5763 - }
5764 - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
5765 - const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
5766 - yield* runtime.events.pipe(
5767 - Stream.runForEach((event) => Queue.offer(events, event)),
5768 - Effect.forkScoped,
5769 - );
5770 - const providerThread = yield* runtime.ensureThread({
5771 - threadId,
5772 - modelSelection,
5773 - runtimePolicy,
5774 - });
5775 - const now = yield* DateTime.now;
5776 - yield* runtime.startTurn(
5777 - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }),
5778 - );
5779 - yield* Deferred.await(promptSettled);
5780 -
5781 - const firstProviderTurnId = idAllocator.derive.providerTurn({
5782 - driver: ACP_TEST_DRIVER,
5783 - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
5784 - });
5785 - yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId });
5786 -
5787 - let firstTerminalStatus: string | null = null;
5788 - while (firstTerminalStatus === null) {
5789 - const event = yield* Queue.take(events);
5790 - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) {
5791 - firstTerminalStatus = event.status;
5792 - }
5793 - }
5794 - assert.equal(firstTerminalStatus, "interrupted");
5795 - assert.isTrue(
5796 - yield* hasPendingBackgroundWork,
5797 - "carryover live subagent must pin hasPendingBackgroundWork after root settle",
5798 - );
5799 - assert.isDefined(sessionUpdateHandler, "session update handler must be wired");
5800 -
5801 - subagentPhase = "complete";
5802 - yield* sessionUpdateHandler!({
5803 - sessionId: "mock-session-1",
5804 - update: {
5805 - sessionUpdate: "tool_call_update",
5806 - toolCallId: "tool-call-generic-1",
5807 - title: "background subagent",
5808 - kind: "other",
5809 - status: "completed",
5810 - rawOutput: { content: "SUB_DONE" },
5811 - },
5812 - });
5813 - yield* sessionUpdateHandler!({
5814 - sessionId: "mock-session-1",
5815 - update: {
5816 - sessionUpdate: "agent_message_chunk",
5817 - content: { type: "text", text: bufferedAssistantText },
5818 - },
5819 - });
5820 - yield* Effect.yieldNow;
5821 - yield* Effect.yieldNow;
5822 -
5823 - let completedBeforeDrain = 0;
5824 - let polled = yield* Queue.poll(events);
5825 - while (Option.isSome(polled)) {
5826 - const event = polled.value;
5827 - if (
5828 - event.type === "turn_item.updated" &&
5829 - event.turnItem.type === "subagent" &&
5830 - event.turnItem.status === "completed"
5831 - ) {
5832 - completedBeforeDrain += 1;
5833 - }
5834 - polled = yield* Queue.poll(events);
5835 - }
5836 - assert.equal(
5837 - completedBeforeDrain,
5838 - 0,
5839 - "interrupted root-session terminal must wait for an observable attach",
5840 - );
5841 - assert.lengthOf(
5842 - continuationRequests,
5843 - 1,
5844 - "root-session post-settle subagent terminal must offer a continuation",
5845 - );
5846 - assert.isTrue(
5847 - yield* hasPendingBackgroundWork,
5848 - "interrupted unprojected terminal must pin hasPendingBackgroundWork until attach",
5849 - );
5850 -
5851 - const userTurnNow = yield* DateTime.now;
5852 - yield* runtime.startTurn(
5853 - makeTurnInput({
5854 - threadId,
5855 - providerThread,
5856 - instanceId,
5857 - runtimePolicy,
5858 - now: userTurnNow,
5859 - ordinal: 2,
5860 - messageText: "What finished while the prior turn was settling?",
5861 - }),
5862 - );
5863 - yield* TestClock.adjust("3 seconds");
5864 - yield* Effect.yieldNow;
5865 - yield* Effect.yieldNow;
5866 -
5867 - const userProviderTurnId = idAllocator.derive.providerTurn({
5868 - driver: ACP_TEST_DRIVER,
5869 - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"),
5870 - });
5871 - let userTurnTerminal: string | null = null;
5872 - let completedSubagentTurnItems = 0;
5873 - let bufferedTextSeenInUserTurn = false;
5874 - while (userTurnTerminal === null) {
5875 - const event = yield* Queue.take(events);
5876 - if (
5877 - event.type === "turn_item.updated" &&
5878 - event.turnItem.type === "subagent" &&
5879 - event.turnItem.status === "completed"
5880 - ) {
5881 - completedSubagentTurnItems += 1;
5882 - }
5883 - if (
5884 - event.type === "message.updated" &&
5885 - event.message.role === "assistant" &&
5886 - event.message.text.includes(bufferedAssistantText)
5887 - ) {
5888 - bufferedTextSeenInUserTurn = true;
5889 - }
5890 - if (event.type === "turn.terminal" && event.providerTurnId === userProviderTurnId) {
5891 - userTurnTerminal = event.status;
5892 - }
5893 - }
5894 - assert.equal(userTurnTerminal, "completed");
5895 - assert.equal(
5896 - completedSubagentTurnItems,
5897 - 1,
5898 - "user attach must project the deferred terminal subagent turn item once",
5899 - );
5900 - assert.isFalse(bufferedTextSeenInUserTurn, "user attach must not drain wake traffic");
5901 - assert.isTrue(
5902 - yield* hasPendingBackgroundWork,
5903 - "wake traffic must remain pinned for the already-dispatched continuation",
5904 - );
5905 -
5906 - const continuationNow = yield* DateTime.now;
5907 - yield* runtime.startTurn(
5908 - makeTurnInput({
5909 - threadId,
5910 - providerThread,
5911 - instanceId,
5912 - runtimePolicy,
5913 - now: continuationNow,
5914 - ordinal: 3,
5915 - messageCreatedBy: "agent",
5916 - messageCreationSource: "provider",
5917 - messageText: "Background task completed.",
5918 - }),
5919 - );
5920 - yield* TestClock.adjust("3 seconds");
5921 - const continuationProviderTurnId = idAllocator.derive.providerTurn({
5922 - driver: ACP_TEST_DRIVER,
5923 - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:3"),
5924 - });
5925 - let continuationTerminal: string | null = null;
5926 - let bufferedTextSeenInContinuation = false;
5927 - while (continuationTerminal === null) {
5928 - const event = yield* Queue.take(events);
5929 - if (
5930 - event.type === "message.updated" &&
5931 - event.message.role === "assistant" &&
5932 - event.message.text.includes(bufferedAssistantText)
5933 - ) {
5934 - bufferedTextSeenInContinuation = true;
5935 - }
5936 - if (
5937 - event.type === "turn.terminal" &&
5938 - event.providerTurnId === continuationProviderTurnId
5939 - ) {
5940 - continuationTerminal = event.status;
5941 - }
5942 - }
5943 - assert.equal(continuationTerminal, "completed");
5944 - assert.isTrue(
5945 - bufferedTextSeenInContinuation,
5946 - "queued continuation must drain the wake content after the user run",
5947 - );
5948 - assert.isFalse(yield* hasPendingBackgroundWork);
5949 - }).pipe(Effect.provide(layerTest), Effect.scoped),
5950 - );
5951 -
5952 - it.effect(
5953 - "preserves wakeBuffer when a child-session completes while a continuation is pending",
5954 - () =>
5955 - Effect.gen(function* () {
5956 - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
5957 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
5958 - const path = yield* Path.Path;
5959 - const selfInvocation = yield* resolveSelfInvocation();
5960 - const mockAgentPath = yield* path.fromFileUrl(
5961 - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
5962 - );
5963 - const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
5964 - [];
5965 - const instanceId = ProviderInstanceId.make("acp-test");
5966 - const childSessionId = "mock-child-session-pending-continuation";
5967 - const bufferedAssistantText = "POST_SETTLE_BUFFERED_ASSISTANT_TEXT";
5968 - let subagentPhase: "spawn" | "complete" = "spawn";
5969 - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
5970 - let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
5971 - const promptSettled = yield* Deferred.make<void>();
5972 - const adapter = yield* makeAcpAdapterV2({
5973 - testHooks: {
5974 - afterPromptSettledWithBackgroundWork: () =>
5975 - Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid),
5976 - },
5977 - instanceId,
5978 - flavor: {
5979 - driver: ACP_TEST_DRIVER,
5980 - capabilities: AcpProviderCapabilitiesV2,
5981 - deferFinalizeForBackgroundWork: true,
5982 - enablePostSettleContinuation: true,
5983 - extractSubagentUpdate: (toolCall) =>
5984 - toolCall.toolCallId !== "tool-call-generic-1"
5985 - ? undefined
5986 - : subagentPhase === "spawn"
5987 - ? {
5988 - nativeTaskId: "task-generic-1",
5989 - prompt: "background subagent",
5990 - title: "background subagent",
5991 - model: null,
5992 - status: "running",
5993 - childSessionId,
5994 - result: null,
5995 - }
5996 - : {
5997 - nativeTaskId: "task-generic-1",
5998 - prompt: "",
5999 - title: null,
6000 - model: null,
6001 - status: "completed",
6002 - childSessionId,
6003 - result: "SUB_DONE",
6004 - },
6005 - makeRuntime: makeMockRuntime({
6006 - childProcessSpawner,
6007 - mockAgentPath,
6008 - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" },
6009 - wrapRuntime: (runtime) => ({
6010 - ...runtime,
6011 - handleSessionUpdate: (handler) =>
6012 - Effect.sync(() => {
6013 - sessionUpdateHandler = handler;
6014 - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
6015 - }),
6016 - }),
6017 - },
6018 - selfInvocation,
6019 - continuationRequests: {
6020 - offer: (request) =>
6021 - Effect.sync(() => {
6022 - continuationRequests.push(request);
6023 - }),
6024 - },
6025 - });
6026 - const threadId = ThreadId.make("thread-acp-carryover-child-pending-continuation");
6027 - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
6028 - runtimeMode: "full-access",
6029 - interactionMode: "default",
6030 - cwd: process.cwd(),
6031 - });
6032 - const modelSelection = { instanceId, model: "default" } as const;
6033 - const runtime = yield* adapter.openSession({
6034 - threadId,
6035 - providerSessionId: ProviderSessionId.make(
6036 - "provider-session-acp-carryover-child-pending-continuation",
6037 - ),
6038 - modelSelection,
6039 - runtimePolicy,
6040 - });
6041 - if (runtime.hasPendingBackgroundWork === undefined) {
6042 - return yield* Effect.die(
6043 - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.",
6044 - );
6045 - }
6046 - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
6047 - const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
6048 - yield* runtime.events.pipe(
6049 - Stream.runForEach((event) => Queue.offer(events, event)),
6050 - Effect.forkScoped,
6051 - );
6052 - const providerThread = yield* runtime.ensureThread({
6053 - threadId,
6054 - modelSelection,
6055 - runtimePolicy,
6056 - });
6057 - const now = yield* DateTime.now;
6058 - yield* runtime.startTurn(
6059 - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }),
6060 - );
6061 - yield* Deferred.await(promptSettled);
6062 -
6063 - const firstProviderTurnId = idAllocator.derive.providerTurn({
6064 - driver: ACP_TEST_DRIVER,
6065 - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
6066 - });
6067 - yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId });
6068 -
6069 - let firstTerminalStatus: string | null = null;
6070 - while (firstTerminalStatus === null) {
6071 - const event = yield* Queue.take(events);
6072 - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) {
6073 - firstTerminalStatus = event.status;
6074 - }
6075 - }
6076 - assert.equal(firstTerminalStatus, "interrupted");
6077 - assert.isTrue(
6078 - yield* hasPendingBackgroundWork,
6079 - "carryover live subagent must pin hasPendingBackgroundWork after root settle",
6080 - );
6081 - assert.isDefined(sessionUpdateHandler, "session update handler must be wired");
6082 -
6083 - subagentPhase = "complete";
6084 - yield* sessionUpdateHandler!({
6085 - sessionId: "mock-session-1",
6086 - update: {
6087 - sessionUpdate: "tool_call_update",
6088 - toolCallId: "tool-call-generic-1",
6089 - title: "background subagent",
6090 - kind: "other",
6091 - status: "completed",
6092 - rawOutput: { content: "SUB_DONE" },
6093 - },
6094 - });
6095 - yield* sessionUpdateHandler!({
6096 - sessionId: "mock-session-1",
6097 - update: {
6098 - sessionUpdate: "agent_message_chunk",
6099 - content: { type: "text", text: bufferedAssistantText },
6100 - },
6101 - });
6102 - assert.lengthOf(
6103 - continuationRequests,
6104 - 1,
6105 - "root-session terminal must offer a continuation before child completion",
6106 - );
6107 - assert.isTrue(
6108 - yield* hasPendingBackgroundWork,
6109 - "pending continuation must keep hasPendingBackgroundWork pinned",
6110 - );
6111 -
6112 - yield* sessionUpdateHandler!({
6113 - sessionId: childSessionId,
6114 - update: {
6115 - sessionUpdate: "tool_call_update",
6116 - toolCallId: "tool-call-generic-1",
6117 - title: "background subagent",
6118 - kind: "other",
6119 - status: "completed",
6120 - rawOutput: { content: "SUB_DONE" },
6121 - },
6122 - });
6123 - yield* Effect.yieldNow;
6124 - yield* Effect.yieldNow;
6125 -
6126 - let completedBeforeDrain = 0;
6127 - let polled = yield* Queue.poll(events);
6128 - while (Option.isSome(polled)) {
6129 - const event = polled.value;
6130 - if (
6131 - event.type === "turn_item.updated" &&
6132 - event.turnItem.type === "subagent" &&
6133 - event.turnItem.status === "completed"
6134 - ) {
6135 - completedBeforeDrain += 1;
6136 - }
6137 - polled = yield* Queue.poll(events);
6138 - }
6139 - assert.equal(
6140 - completedBeforeDrain,
6141 - 0,
6142 - "interrupted child-session terminal must wait for the continuation attach",
6143 - );
6144 - assert.isTrue(
6145 - yield* hasPendingBackgroundWork,
6146 - "child-session must not clear the pin while wakeBuffer still has delivery",
6147 - );
6148 -
6149 - const continuationNow = yield* DateTime.now;
6150 - yield* runtime.startTurn(
6151 - makeTurnInput({
6152 - threadId,
6153 - providerThread,
6154 - instanceId,
6155 - runtimePolicy,
6156 - now: continuationNow,
6157 - ordinal: 2,
6158 - messageCreatedBy: "agent",
6159 - messageCreationSource: "provider",
6160 - messageText: "Background task completed.",
6161 - }),
6162 - );
6163 - yield* TestClock.adjust("3 seconds");
6164 - yield* Effect.yieldNow;
6165 - yield* Effect.yieldNow;
6166 -
6167 - const continuationProviderTurnId = idAllocator.derive.providerTurn({
6168 - driver: ACP_TEST_DRIVER,
6169 - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"),
6170 - });
6171 - let continuationTerminal: string | null = null;
6172 - let completedSubagentTurnItems = 0;
6173 - let bufferedTextSeen = false;
6174 - while (continuationTerminal === null) {
6175 - const event = yield* Queue.take(events);
6176 - if (
6177 - event.type === "turn_item.updated" &&
6178 - event.turnItem.type === "subagent" &&
6179 - event.turnItem.status === "completed"
6180 - ) {
6181 - completedSubagentTurnItems += 1;
6182 - }
6183 - if (
6184 - event.type === "message.updated" &&
6185 - event.message.role === "assistant" &&
6186 - event.message.text.includes(bufferedAssistantText)
6187 - ) {
6188 - bufferedTextSeen = true;
6189 - }
6190 - if (
6191 - event.type === "turn.terminal" &&
6192 - event.providerTurnId === continuationProviderTurnId
6193 - ) {
6194 - continuationTerminal = event.status;
6195 - }
4528 + event.turnItem.runId === continuationInput.runId
4529 + ) {
4530 + replayedTurnItems += 1;
4531 }
6197 - assert.equal(continuationTerminal, "completed");
6198 - assert.isTrue(
6199 - bufferedTextSeen,
6200 - "continuation drain must project buffered post-settle assistant text (buffer not wiped)",
6201 - );
6202 - assert.equal(
6203 - completedSubagentTurnItems,
6204 - 1,
6205 - "continuation drain must project the terminal subagent turn item once",
6206 - );
6207 - assert.isFalse(
6208 - yield* hasPendingBackgroundWork,
6209 - "pin must clear after the continuation drains, not when the child session completed",
6210 - );
6211 - }).pipe(Effect.provide(layerTest), Effect.scoped),
4532 + polled = yield* Queue.poll(events);
4533 + }
4534 + assert.equal(replayedLineages, 0, "buffered spawn ACK must not create a second lineage");
4535 + assert.equal(
4536 + replayedSubagentUpdates,
4537 + 0,
4538 + "buffered spawn ACK must not re-open the terminal subagent",
4539 + );
4540 + assert.equal(
4541 + replayedTurnItems,
4542 + 0,
4543 + "buffered spawn ACK must not create a continuation-owned turn item",
4544 + );
4545 + assert.isFalse(yield* hasPendingBackgroundWork);
4546 + }).pipe(Effect.provide(layerTest), Effect.scoped),
4547 );
4548
4549 it.effect(
6215 - "projects once when root-session then child-session complete the same carryover subagent",
4550 + "user attach flushes a deferred terminal but leaves wake traffic for its continuation",
4551 () =>
4552 Effect.gen(function* () {
4553 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -6224,8 +4559,8 @@ describe("AcpAdapterV2", () => {
4559 );
4560 const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
4561 [];
4562 + const bufferedAssistantText = "BUFFERED_WAKE_AFTER_USER_ATTACH";
4563 const instanceId = ProviderInstanceId.make("acp-test");
6228 - const childSessionId = "mock-child-session-root-then-child";
4564 let subagentPhase: "spawn" | "complete" = "spawn";
4565 type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
4566 let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
@@ -6251,7 +4586,7 @@ describe("AcpAdapterV2", () => {
4586 title: "background subagent",
4587 model: null,
4588 status: "running",
6254 - childSessionId,
4589 + childSessionId: null,
4590 result: null,
4591 }
4592 : {
@@ -6260,7 +4595,7 @@ describe("AcpAdapterV2", () => {
4595 title: null,
4596 model: null,
4597 status: "completed",
6263 - childSessionId,
4598 + childSessionId: null,
4599 result: "SUB_DONE",
4600 },
4601 makeRuntime: makeMockRuntime({
@@ -6284,7 +4619,7 @@ describe("AcpAdapterV2", () => {
4619 }),
4620 },
4621 });
6287 - const threadId = ThreadId.make("thread-acp-carryover-root-then-child");
4622 + const threadId = ThreadId.make("thread-acp-carryover-root-session-continuation");
4623 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
4624 runtimeMode: "full-access",
4625 interactionMode: "default",
@@ -6294,7 +4629,7 @@ describe("AcpAdapterV2", () => {
4629 const runtime = yield* adapter.openSession({
4630 threadId,
4631 providerSessionId: ProviderSessionId.make(
6297 - "provider-session-acp-carryover-root-then-child",
4632 + "provider-session-acp-carryover-root-session-continuation",
4633 ),
4634 modelSelection,
4635 runtimePolicy,
@@ -6353,21 +4688,11 @@ describe("AcpAdapterV2", () => {
4688 rawOutput: { content: "SUB_DONE" },
4689 },
4690 });
6356 - assert.lengthOf(
6357 - continuationRequests,
6358 - 1,
6359 - "root-session terminal must still offer a continuation",
6360 - );
6361 -
4691 yield* sessionUpdateHandler!({
6363 - sessionId: childSessionId,
4692 + sessionId: "mock-session-1",
4693 update: {
6365 - sessionUpdate: "tool_call_update",
6366 - toolCallId: "tool-call-generic-1",
6367 - title: "background subagent",
6368 - kind: "other",
6369 - status: "completed",
6370 - rawOutput: { content: "SUB_DONE" },
4694 + sessionUpdate: "agent_message_chunk",
4695 + content: { type: "text", text: bufferedAssistantText },
4696 },
4697 });
4698 yield* Effect.yieldNow;
@@ -6389,34 +4714,42 @@ describe("AcpAdapterV2", () => {
4714 assert.equal(
4715 completedBeforeDrain,
4716 0,
6392 - "interrupted root-then-child completion must defer to the continuation attach",
4717 + "interrupted root-session terminal must wait for an observable attach",
4718 + );
4719 + assert.lengthOf(
4720 + continuationRequests,
4721 + 1,
4722 + "root-session post-settle subagent terminal must offer a continuation",
4723 + );
4724 + assert.isTrue(
4725 + yield* hasPendingBackgroundWork,
4726 + "interrupted unprojected terminal must pin hasPendingBackgroundWork until attach",
4727 );
4728
6395 - const continuationNow = yield* DateTime.now;
4729 + const userTurnNow = yield* DateTime.now;
4730 yield* runtime.startTurn(
4731 makeTurnInput({
4732 threadId,
4733 providerThread,
4734 instanceId,
4735 runtimePolicy,
6402 - now: continuationNow,
4736 + now: userTurnNow,
4737 ordinal: 2,
6404 - messageCreatedBy: "agent",
6405 - messageCreationSource: "provider",
6406 - messageText: "Background task completed.",
4738 + messageText: "What finished while the prior turn was settling?",
4739 }),
4740 );
4741 yield* TestClock.adjust("3 seconds");
4742 yield* Effect.yieldNow;
4743 yield* Effect.yieldNow;
4744
6413 - const continuationProviderTurnId = idAllocator.derive.providerTurn({
4745 + const userProviderTurnId = idAllocator.derive.providerTurn({
4746 driver: ACP_TEST_DRIVER,
4747 nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"),
4748 });
6417 - let continuationTerminal: string | null = null;
4749 + let userTurnTerminal: string | null = null;
4750 let completedSubagentTurnItems = 0;
6419 - while (continuationTerminal === null) {
4751 + let bufferedTextSeenInUserTurn = false;
4752 + while (userTurnTerminal === null) {
4753 const event = yield* Queue.take(events);
4754 if (
4755 event.type === "turn_item.updated" &&
@@ -6426,22 +4759,71 @@ describe("AcpAdapterV2", () => {
4759 completedSubagentTurnItems += 1;
4760 }
4761 if (
6429 - event.type === "turn.terminal" &&
6430 - event.providerTurnId === continuationProviderTurnId
4762 + event.type === "message.updated" &&
4763 + event.message.role === "assistant" &&
4764 + event.message.text.includes(bufferedAssistantText)
4765 ) {
6432 - continuationTerminal = event.status;
4766 + bufferedTextSeenInUserTurn = true;
4767 + }
4768 + if (event.type === "turn.terminal" && event.providerTurnId === userProviderTurnId) {
4769 + userTurnTerminal = event.status;
4770 }
4771 }
6435 - assert.equal(continuationTerminal, "completed");
4772 + assert.equal(userTurnTerminal, "completed");
4773 assert.equal(
4774 completedSubagentTurnItems,
4775 1,
6439 - "root-then-child completion must project the terminal subagent turn item exactly once",
4776 + "user attach must project the deferred terminal subagent turn item once",
4777 );
6441 - assert.isFalse(
4778 + assert.isFalse(bufferedTextSeenInUserTurn, "user attach must not drain wake traffic");
4779 + assert.isTrue(
4780 yield* hasPendingBackgroundWork,
6443 - "hasPendingBackgroundWork must end false after the continuation drains",
4781 + "wake traffic must remain pinned for the already-dispatched continuation",
4782 + );
4783 +
4784 + const continuationNow = yield* DateTime.now;
4785 + yield* runtime.startTurn(
4786 + makeTurnInput({
4787 + threadId,
4788 + providerThread,
4789 + instanceId,
4790 + runtimePolicy,
4791 + now: continuationNow,
4792 + ordinal: 3,
4793 + messageCreatedBy: "agent",
4794 + messageCreationSource: "provider",
4795 + messageText: "Background task completed.",
4796 + }),
4797 + );
4798 + yield* TestClock.adjust("3 seconds");
4799 + const continuationProviderTurnId = idAllocator.derive.providerTurn({
4800 + driver: ACP_TEST_DRIVER,
4801 + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:3"),
4802 + });
4803 + let continuationTerminal: string | null = null;
4804 + let bufferedTextSeenInContinuation = false;
4805 + while (continuationTerminal === null) {
4806 + const event = yield* Queue.take(events);
4807 + if (
4808 + event.type === "message.updated" &&
4809 + event.message.role === "assistant" &&
4810 + event.message.text.includes(bufferedAssistantText)
4811 + ) {
4812 + bufferedTextSeenInContinuation = true;
4813 + }
4814 + if (
4815 + event.type === "turn.terminal" &&
4816 + event.providerTurnId === continuationProviderTurnId
4817 + ) {
4818 + continuationTerminal = event.status;
4819 + }
4820 + }
4821 + assert.equal(continuationTerminal, "completed");
4822 + assert.isTrue(
4823 + bufferedTextSeenInContinuation,
4824 + "queued continuation must drain the wake content after the user run",
4825 );
4826 + assert.isFalse(yield* hasPendingBackgroundWork);
4827 }).pipe(Effect.provide(layerTest), Effect.scoped),
4828 );
4829
@@ -6842,138 +5224,21 @@ describe("AcpAdapterV2", () => {
5224 toolCall.toolCallId === "tool-call-monitor-1" ? "task-monitor-1" : undefined,
5225 extractBackgroundTaskCompletion: (toolCall) =>
5226 toolCall.toolCallId === "tool-call-fetch-1"
6845 - ? [
6846 - {
6847 - taskId: "task-monitor-1",
6848 - status: toolCall.status === "completed" ? "completed" : "running",
6849 - appendOutput: toolCall.status === "completed" ? "MONITOR_LISTING_TOKEN" : "",
6850 - },
6851 - ]
6852 - : [],
6853 - makeRuntime: makeMockRuntime({
6854 - childProcessSpawner,
6855 - mockAgentPath,
6856 - environment: {
6857 - T3_ACP_EMIT_IN_TURN_TASKOUTPUT_THEN_LATE_DUPLICATE: "1",
6858 - },
6859 - protocolEvents,
6860 - }),
6861 - },
6862 - selfInvocation,
6863 - continuationRequests: {
6864 - offer: (request) =>
6865 - Effect.sync(() => {
6866 - continuationRequests.push(request);
6867 - }),
6868 - },
6869 - });
6870 - const threadId = ThreadId.make("thread-acp-already-handled-wake-pin");
6871 - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
6872 - runtimeMode: "full-access",
6873 - interactionMode: "default",
6874 - cwd: process.cwd(),
6875 - });
6876 - const modelSelection = { instanceId, model: "default" } as const;
6877 - const runtime = yield* adapter.openSession({
6878 - threadId,
6879 - providerSessionId: ProviderSessionId.make(
6880 - "provider-session-acp-already-handled-wake-pin",
6881 - ),
6882 - modelSelection,
6883 - runtimePolicy,
6884 - });
6885 - if (runtime.hasPendingBackgroundWork === undefined) {
6886 - return yield* Effect.die(
6887 - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.",
6888 - );
6889 - }
6890 - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
6891 - const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
6892 - yield* runtime.events.pipe(
6893 - Stream.runForEach((event) => Queue.offer(events, event)),
6894 - Effect.forkScoped,
6895 - );
6896 - const providerThread = yield* runtime.ensureThread({
6897 - threadId,
6898 - modelSelection,
6899 - runtimePolicy,
6900 - });
6901 - const now = yield* DateTime.now;
6902 - yield* runtime.startTurn(
6903 - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }),
6904 - );
6905 - const providerTurnId = idAllocator.derive.providerTurn({
6906 - driver: ACP_TEST_DRIVER,
6907 - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
6908 - });
6909 -
6910 - let terminalStatus: string | null = null;
6911 - while (terminalStatus === null) {
6912 - const event = yield* Queue.take(events);
6913 - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) {
6914 - terminalStatus = event.status;
6915 - }
6916 - }
6917 - assert.equal(terminalStatus, "completed");
6918 -
6919 - yield* Stream.fromQueue(protocolEvents).pipe(
6920 - Stream.filter(
6921 - (event) =>
6922 - event.direction === "incoming" &&
6923 - event.stage === "raw" &&
6924 - typeof event.payload === "string" &&
6925 - event.payload.includes("MONITOR_LISTING_TOKEN_LATE"),
6926 - ),
6927 - Stream.runHead,
6928 - );
6929 - yield* Effect.yieldNow;
6930 - yield* Effect.yieldNow;
6931 - yield* Effect.yieldNow;
6932 -
6933 - assert.lengthOf(
6934 - continuationRequests,
6935 - 0,
6936 - "already-handled late TaskOutput must not open a continuation run",
6937 - );
6938 - assert.isFalse(
6939 - yield* hasPendingBackgroundWork,
6940 - "wake buffer must not stay non-empty and pin idle release after an already-handled re-report",
6941 - );
6942 - }).pipe(Effect.provide(layerTest), Effect.scoped),
6943 - );
6944 -
6945 - it.effect(
6946 - "keeps a dispatched continuation offer sticky until a turn starts or the worker drops it",
6947 - () =>
6948 - Effect.gen(function* () {
6949 - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
6950 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
6951 - const path = yield* Path.Path;
6952 - const selfInvocation = yield* resolveSelfInvocation();
6953 - const mockAgentPath = yield* path.fromFileUrl(
6954 - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
6955 - );
6956 - const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
6957 - [];
6958 - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
6959 - let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
6960 - const instanceId = ProviderInstanceId.make("acp-test");
6961 - const adapter = yield* makeAcpAdapterV2({
6962 - instanceId,
6963 - flavor: {
6964 - driver: ACP_TEST_DRIVER,
6965 - capabilities: AcpProviderCapabilitiesV2,
6966 - enablePostSettleContinuation: true,
5227 + ? [
5228 + {
5229 + taskId: "task-monitor-1",
5230 + status: toolCall.status === "completed" ? "completed" : "running",
5231 + appendOutput: toolCall.status === "completed" ? "MONITOR_LISTING_TOKEN" : "",
5232 + },
5233 + ]
5234 + : [],
5235 makeRuntime: makeMockRuntime({
5236 childProcessSpawner,
5237 mockAgentPath,
6970 - wrapRuntime: (runtime) => ({
6971 - ...runtime,
6972 - handleSessionUpdate: (handler) =>
6973 - Effect.sync(() => {
6974 - sessionUpdateHandler = handler;
6975 - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
6976 - }),
5238 + environment: {
5239 + T3_ACP_EMIT_IN_TURN_TASKOUTPUT_THEN_LATE_DUPLICATE: "1",
5240 + },
5241 + protocolEvents,
5242 }),
5243 },
5244 selfInvocation,
@@ -6984,7 +5249,7 @@ describe("AcpAdapterV2", () => {
5249 }),
5250 },
5251 });
6987 - const threadId = ThreadId.make("thread-acp-sticky-continuation-dispatch");
5252 + const threadId = ThreadId.make("thread-acp-already-handled-wake-pin");
5253 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
5254 runtimeMode: "full-access",
5255 interactionMode: "default",
@@ -6994,11 +5259,17 @@ describe("AcpAdapterV2", () => {
5259 const runtime = yield* adapter.openSession({
5260 threadId,
5261 providerSessionId: ProviderSessionId.make(
6997 - "provider-session-acp-sticky-continuation-dispatch",
5262 + "provider-session-acp-already-handled-wake-pin",
5263 ),
5264 modelSelection,
5265 runtimePolicy,
5266 });
5267 + if (runtime.hasPendingBackgroundWork === undefined) {
5268 + return yield* Effect.die(
5269 + "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.",
5270 + );
5271 + }
5272 + const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
5273 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
5274 yield* runtime.events.pipe(
5275 Stream.runForEach((event) => Queue.offer(events, event)),
@@ -7017,6 +5288,7 @@ describe("AcpAdapterV2", () => {
5288 driver: ACP_TEST_DRIVER,
5289 nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
5290 });
5291 +
5292 let terminalStatus: string | null = null;
5293 while (terminalStatus === null) {
5294 const event = yield* Queue.take(events);
@@ -7025,37 +5297,30 @@ describe("AcpAdapterV2", () => {
5297 }
5298 }
5299 assert.equal(terminalStatus, "completed");
7028 - assert.isDefined(sessionUpdateHandler, "session update handler must be wired");
5300
7030 - const lateTool = (toolCallId: string) =>
7031 - sessionUpdateHandler!({
7032 - sessionId: "mock-session-1",
7033 - update: {
7034 - sessionUpdate: "tool_call_update",
7035 - toolCallId,
7036 - title: "Late tool result",
7037 - kind: "other",
7038 - status: "completed",
7039 - rawOutput: { output: toolCallId },
7040 - },
7041 - });
7042 - yield* lateTool("first-late-result");
7043 - assert.lengthOf(continuationRequests, 1);
7044 - const first = continuationRequests[0]!;
7045 - assert.isDefined(first.dispatchIfCurrent);
7046 - assert.isTrue(Option.isSome(yield* first.dispatchIfCurrent!(Effect.void)));
5301 + yield* Stream.fromQueue(protocolEvents).pipe(
5302 + Stream.filter(
5303 + (event) =>
5304 + event.direction === "incoming" &&
5305 + event.stage === "raw" &&
5306 + typeof event.payload === "string" &&
5307 + event.payload.includes("MONITOR_LISTING_TOKEN_LATE"),
5308 + ),
5309 + Stream.runHead,
5310 + );
5311 + yield* Effect.yieldNow;
5312 + yield* Effect.yieldNow;
5313 + yield* Effect.yieldNow;
5314
7048 - yield* lateTool("second-frame-before-dispatched-turn-starts");
5315 assert.lengthOf(
5316 continuationRequests,
7051 - 1,
7052 - "late frames must not enqueue duplicate continuations during dispatch-to-start",
5317 + 0,
5318 + "already-handled late TaskOutput must not open a continuation run",
5319 + );
5320 + assert.isFalse(
5321 + yield* hasPendingBackgroundWork,
5322 + "wake buffer must not stay non-empty and pin idle release after an already-handled re-report",
5323 );
7054 -
7055 - assert.isDefined(first.clearIfCurrent);
7056 - yield* first.clearIfCurrent!();
7057 - yield* lateTool("new-result-after-worker-drop");
7058 - assert.lengthOf(continuationRequests, 2);
5324 }).pipe(Effect.provide(layerTest), Effect.scoped),
5325 );
5326
@@ -7456,219 +5721,14 @@ describe("AcpAdapterV2", () => {
5721 : [],
5722 }),
5723 "mutation-only end-notice must not count as post-settle wake evidence",
7459 - );
7460 - yield* sessionUpdateHandler!(bEndNotice);
7461 - yield* Effect.yieldNow;
7462 - yield* Effect.yieldNow;
7463 - assert.lengthOf(
7464 - continuationRequests,
7465 - 1,
7466 - "exactly one continuation when the last running task ends post-finalize with kept midTurn marks",
7467 - );
7468 - }).pipe(Effect.provide(layerTest), Effect.scoped),
7469 - );
7470 -
7471 - it.effect(
7472 - "staggered pre-settle completion does not keep midTurn marks when the turn is interrupted",
7473 - () =>
7474 - Effect.gen(function* () {
7475 - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
7476 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
7477 - const path = yield* Path.Path;
7478 - const selfInvocation = yield* resolveSelfInvocation();
7479 - const mockAgentPath = yield* path.fromFileUrl(
7480 - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
7481 - );
7482 - const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
7483 - const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
7484 - [];
7485 - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
7486 - let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
7487 - const promptGate = yield* Deferred.make<EffectAcpSchema.PromptResponse>();
7488 - const capturedMutation: {
7489 - current:
7490 - | ((mutation: {
7491 - readonly sessionId: string;
7492 - readonly taskId: string;
7493 - readonly status: "running" | "completed" | "failed";
7494 - }) => Effect.Effect<void>)
7495 - | null;
7496 - } = { current: null };
7497 - const instanceId = ProviderInstanceId.make("acp-test");
7498 - const adapter = yield* makeAcpAdapterV2({
7499 - instanceId,
7500 - flavor: {
7501 - driver: ACP_TEST_DRIVER,
7502 - capabilities: AcpProviderCapabilitiesV2,
7503 - deferFinalizeForBackgroundWork: true,
7504 - enablePostSettleContinuation: true,
7505 - extractBackgroundTaskId: (toolCall) => {
7506 - if (toolCall.toolCallId === "tool-call-monitor-a") return "task-monitor-a";
7507 - if (toolCall.toolCallId === "tool-call-monitor-b") return "task-monitor-b";
7508 - return undefined;
7509 - },
7510 - extractBackgroundToolMutation: (text) => {
7511 - if (text.includes('Monitor "task-monitor-a" ended')) {
7512 - return [{ taskId: "task-monitor-a", status: "completed", appendOutput: "" }];
7513 - }
7514 - if (text.includes('Monitor "task-monitor-b" ended')) {
7515 - return [{ taskId: "task-monitor-b", status: "completed", appendOutput: "" }];
7516 - }
7517 - return [];
7518 - },
7519 - registerExtensions: (context) =>
7520 - Effect.sync(() => {
7521 - capturedMutation.current = context.applyBackgroundTaskMutation;
7522 - }),
7523 - makeRuntime: makeMockRuntime({
7524 - childProcessSpawner,
7525 - mockAgentPath,
7526 - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" },
7527 - protocolEvents,
7528 - wrapRuntime: (runtime) => ({
7529 - ...runtime,
7530 - handleSessionUpdate: (handler) =>
7531 - Effect.sync(() => {
7532 - sessionUpdateHandler = handler;
7533 - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
7534 - prompt: () => Deferred.await(promptGate),
7535 - }),
7536 - }),
7537 - },
7538 - selfInvocation,
7539 - continuationRequests: {
7540 - offer: (request) =>
7541 - Effect.sync(() => {
7542 - continuationRequests.push(request);
7543 - }),
7544 - },
7545 - });
7546 - const threadId = ThreadId.make("thread-acp-staggered-midturn-clear-on-interrupt");
7547 - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
7548 - runtimeMode: "full-access",
7549 - interactionMode: "default",
7550 - cwd: process.cwd(),
7551 - });
7552 - const modelSelection = { instanceId, model: "default" } as const;
7553 - const runtime = yield* adapter.openSession({
7554 - threadId,
7555 - providerSessionId: ProviderSessionId.make(
7556 - "provider-session-acp-staggered-midturn-clear-on-interrupt",
7557 - ),
7558 - modelSelection,
7559 - runtimePolicy,
7560 - });
7561 - const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
7562 - yield* runtime.events.pipe(
7563 - Stream.runForEach((event) => Queue.offer(events, event)),
7564 - Effect.forkScoped,
7565 - );
7566 - const providerThread = yield* runtime.ensureThread({
7567 - threadId,
7568 - modelSelection,
7569 - runtimePolicy,
7570 - });
7571 - const now = yield* DateTime.now;
7572 - yield* runtime
7573 - .startTurn(
7574 - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }),
7575 - )
7576 - .pipe(Effect.forkScoped);
7577 - yield* Effect.yieldNow;
7578 - yield* Effect.yieldNow;
7579 - assert.isDefined(sessionUpdateHandler);
7580 - const applyMutation = capturedMutation.current;
7581 - if (applyMutation === null) {
7582 - return yield* Effect.die("registerExtensions must capture applyBackgroundTaskMutation");
7583 - }
7584 -
7585 - for (const [toolCallId, title] of [
7586 - ["tool-call-monitor-a", "Monitor: staggered interrupt A"],
7587 - ["tool-call-monitor-b", "Monitor: staggered interrupt B"],
7588 - ] as const) {
7589 - yield* sessionUpdateHandler!({
7590 - sessionId: "mock-session-1",
7591 - update: {
7592 - sessionUpdate: "tool_call",
7593 - toolCallId,
7594 - title,
7595 - kind: "execute",
7596 - status: "pending",
7597 - rawInput: {},
7598 - },
7599 - });
7600 - yield* sessionUpdateHandler!({
7601 - sessionId: "mock-session-1",
7602 - update: {
7603 - sessionUpdate: "tool_call_update",
7604 - toolCallId,
7605 - status: "in_progress",
7606 - },
7607 - });
7608 - }
7609 - yield* applyMutation({
7610 - sessionId: "mock-session-1",
7611 - taskId: "task-monitor-a",
7612 - status: "running",
7613 - });
7614 - yield* applyMutation({
7615 - sessionId: "mock-session-1",
7616 - taskId: "task-monitor-b",
7617 - status: "running",
7618 - });
7619 - yield* applyMutation({
7620 - sessionId: "mock-session-1",
7621 - taskId: "task-monitor-a",
7622 - status: "completed",
7623 - });
7624 - assert.lengthOf(continuationRequests, 0);
7625 -
7626 - yield* Deferred.succeed(promptGate, { stopReason: "end_turn" });
7627 - yield* Effect.yieldNow;
7628 - yield* Effect.yieldNow;
7629 - yield* Effect.yieldNow;
7630 - assert.lengthOf(
7631 - continuationRequests,
7632 - 0,
7633 - "settle must hold for deferred background tools; no mid-hold offer",
7634 - );
7635 -
7636 - const providerTurnId = idAllocator.derive.providerTurn({
7637 - driver: ACP_TEST_DRIVER,
7638 - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
7639 - });
7640 - yield* runtime.interruptTurn({ providerThread, providerTurnId });
7641 -
7642 - let terminalStatus: string | null = null;
7643 - while (terminalStatus === null) {
7644 - const event = yield* Queue.take(events);
7645 - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) {
7646 - terminalStatus = event.status;
7647 - }
7648 - }
7649 - assert.equal(terminalStatus, "interrupted");
7650 - assert.lengthOf(
7651 - continuationRequests,
7652 - 0,
7653 - "interrupted finalize must not offer a continuation",
7654 - );
7655 -
7656 - yield* sessionUpdateHandler!({
7657 - sessionId: "mock-session-1",
7658 - update: {
7659 - sessionUpdate: "user_message_chunk",
7660 - content: {
7661 - type: "text",
7662 - text: 'Monitor "task-monitor-b" ended: [monitor ended: exit 0]',
7663 - },
7664 - },
7665 - });
5724 + );
5725 + yield* sessionUpdateHandler!(bEndNotice);
5726 yield* Effect.yieldNow;
5727 yield* Effect.yieldNow;
5728 assert.lengthOf(
5729 continuationRequests,
7670 - 0,
7671 - "interrupted turns must clear midTurn marks; B ending post-finalize must not offer",
5730 + 1,
5731 + "exactly one continuation when the last running task ends post-finalize with kept midTurn marks",
5732 );
5733 }).pipe(Effect.provide(layerTest), Effect.scoped),
5734 );
@@ -8153,351 +6213,36 @@ describe("AcpAdapterV2", () => {
6213 update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } },
6214 });
6215
8156 - yield* endCommand("task-a", "sleep a");
8157 - yield* agentText("A_DONE");
8158 - assert.lengthOf(continuationRequests, 1);
8159 - assert.equal(continuationRequests[0]?.notification?.summary, 'Command "sleep a" finished');
8160 - yield* endCommand("task-b", "sleep b");
8161 - assert.lengthOf(continuationRequests, 1);
8162 -
8163 - yield* runtime.startTurn(
8164 - makeTurnInput({
8165 - threadId,
8166 - providerThread,
8167 - instanceId,
8168 - runtimePolicy,
8169 - now: yield* DateTime.now,
8170 - ordinal: 2,
8171 - messageCreatedBy: "agent",
8172 - messageCreationSource: "provider",
8173 - messageText: "Background task completed.",
8174 - }),
8175 - );
8176 - yield* TestClock.adjust("3 seconds");
8177 - assert.equal(yield* awaitTerminal(2), "completed");
8178 -
8179 - yield* agentText("B_DONE");
8180 - assert.lengthOf(continuationRequests, 2);
8181 - assert.deepEqual(continuationRequests[1]?.notification, {
8182 - source: { kind: "command" },
8183 - outcome: "completed",
8184 - summary: 'Command "sleep b" finished',
8185 - });
8186 - }).pipe(Effect.provide(layerTest), Effect.scoped),
8187 - );
8188 -
8189 - it.effect("mid-turn completed mutation defers offer until finalize only when unhandled", () =>
8190 - Effect.gen(function* () {
8191 - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
8192 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
8193 - const path = yield* Path.Path;
8194 - const selfInvocation = yield* resolveSelfInvocation();
8195 - const mockAgentPath = yield* path.fromFileUrl(
8196 - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
8197 - );
8198 - const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
8199 - const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
8200 - [];
8201 - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
8202 - let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
8203 - const promptGates: Array<Deferred.Deferred<EffectAcpSchema.PromptResponse, never>> = [];
8204 - const capturedMutation: {
8205 - current:
8206 - | ((mutation: {
8207 - readonly sessionId: string;
8208 - readonly taskId: string;
8209 - readonly status: "running" | "completed" | "failed";
8210 - }) => Effect.Effect<void>)
8211 - | null;
8212 - } = { current: null };
8213 - const instanceId = ProviderInstanceId.make("acp-test");
8214 - const adapter = yield* makeAcpAdapterV2({
8215 - instanceId,
8216 - flavor: {
8217 - driver: ACP_TEST_DRIVER,
8218 - capabilities: AcpProviderCapabilitiesV2,
8219 - enablePostSettleContinuation: true,
8220 - extractBackgroundTaskId: (toolCall) =>
8221 - toolCall.toolCallId === "tool-call-monitor-unhandled"
8222 - ? "task-monitor-unhandled"
8223 - : toolCall.toolCallId === "tool-call-monitor-handled"
8224 - ? "task-monitor-handled"
8225 - : undefined,
8226 - extractBackgroundTaskCompletion: (toolCall) =>
8227 - toolCall.toolCallId === "tool-call-fetch-handled"
8228 - ? [
8229 - {
8230 - taskId: "task-monitor-handled",
8231 - status: toolCall.status === "completed" ? "completed" : "running",
8232 - appendOutput: toolCall.status === "completed" ? "HANDLED_LISTING" : "",
8233 - },
8234 - ]
8235 - : [],
8236 - registerExtensions: (context) =>
8237 - Effect.sync(() => {
8238 - capturedMutation.current = context.applyBackgroundTaskMutation;
8239 - }),
8240 - makeRuntime: makeMockRuntime({
8241 - childProcessSpawner,
8242 - mockAgentPath,
8243 - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" },
8244 - protocolEvents,
8245 - wrapRuntime: (runtime) => ({
8246 - ...runtime,
8247 - handleSessionUpdate: (handler) =>
8248 - Effect.sync(() => {
8249 - sessionUpdateHandler = handler;
8250 - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
8251 - prompt: () =>
8252 - Effect.gen(function* () {
8253 - const gate = yield* Deferred.make<EffectAcpSchema.PromptResponse>();
8254 - promptGates.push(gate);
8255 - return yield* Deferred.await(gate);
8256 - }),
8257 - }),
8258 - }),
8259 - },
8260 - selfInvocation,
8261 - continuationRequests: {
8262 - offer: (request) =>
8263 - Effect.sync(() => {
8264 - continuationRequests.push(request);
8265 - }),
8266 - },
8267 - });
8268 - const threadId = ThreadId.make("thread-acp-mid-turn-dirty-wake-buffer");
8269 - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
8270 - runtimeMode: "full-access",
8271 - interactionMode: "default",
8272 - cwd: process.cwd(),
8273 - });
8274 - const modelSelection = { instanceId, model: "default" } as const;
8275 - const runtime = yield* adapter.openSession({
8276 - threadId,
8277 - providerSessionId: ProviderSessionId.make(
8278 - "provider-session-acp-mid-turn-dirty-wake-buffer",
8279 - ),
8280 - modelSelection,
8281 - runtimePolicy,
8282 - });
8283 - if (runtime.hasPendingBackgroundWork === undefined) {
8284 - return yield* Effect.die(
8285 - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.",
8286 - );
8287 - }
8288 - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
8289 - const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
8290 - yield* runtime.events.pipe(
8291 - Stream.runForEach((event) => Queue.offer(events, event)),
8292 - Effect.forkScoped,
8293 - );
8294 - const providerThread = yield* runtime.ensureThread({
8295 - threadId,
8296 - modelSelection,
8297 - runtimePolicy,
8298 - });
8299 - const now = yield* DateTime.now;
8300 - yield* runtime
8301 - .startTurn(
8302 - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }),
8303 - )
8304 - .pipe(Effect.forkScoped);
8305 - while (promptGates.length < 1) {
8306 - yield* Effect.yieldNow;
8307 - }
8308 - yield* Deferred.succeed(promptGates[0]!, { stopReason: "end_turn" });
8309 - const firstProviderTurnId = idAllocator.derive.providerTurn({
8310 - driver: ACP_TEST_DRIVER,
8311 - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
8312 - });
8313 - let firstTerminal: string | null = null;
8314 - while (firstTerminal === null) {
8315 - const event = yield* Queue.take(events);
8316 - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) {
8317 - firstTerminal = event.status;
8318 - }
8319 - }
8320 - assert.equal(firstTerminal, "completed");
8321 - assert.isDefined(sessionUpdateHandler);
8322 - yield* sessionUpdateHandler!({
8323 - sessionId: "mock-session-1",
8324 - update: {
8325 - sessionUpdate: "agent_thought_chunk",
8326 - content: { type: "text", text: "stale wake residue from prior turn" },
8327 - },
8328 - });
8329 - assert.isTrue(yield* hasPendingBackgroundWork, "thought residue must dirty the wake buffer");
8330 - assert.lengthOf(continuationRequests, 0);
8331 -
8332 - yield* runtime
8333 - .startTurn(
8334 - makeTurnInput({
8335 - threadId,
8336 - providerThread,
8337 - instanceId,
8338 - runtimePolicy,
8339 - now: yield* DateTime.now,
8340 - ordinal: 2,
8341 - }),
8342 - )
8343 - .pipe(Effect.forkScoped);
8344 - while (promptGates.length < 2) {
8345 - yield* Effect.yieldNow;
8346 - }
8347 - assert.isFalse(
8348 - yield* hasPendingBackgroundWork,
8349 - "user-turn start must drop prior-turn wake residue",
8350 - );
8351 - const applyMutation = capturedMutation.current;
8352 - if (applyMutation === null || sessionUpdateHandler === undefined) {
8353 - return yield* Effect.die("extensions and session handler must be wired for turn 2");
8354 - }
8355 -
8356 - yield* sessionUpdateHandler({
8357 - sessionId: "mock-session-1",
8358 - update: {
8359 - sessionUpdate: "tool_call",
8360 - toolCallId: "tool-call-monitor-unhandled",
8361 - title: "Monitor: unhandled",
8362 - kind: "execute",
8363 - status: "pending",
8364 - rawInput: {},
8365 - },
8366 - });
8367 - yield* sessionUpdateHandler({
8368 - sessionId: "mock-session-1",
8369 - update: {
8370 - sessionUpdate: "tool_call_update",
8371 - toolCallId: "tool-call-monitor-unhandled",
8372 - status: "in_progress",
8373 - },
8374 - });
8375 - yield* applyMutation({
8376 - sessionId: "mock-session-1",
8377 - taskId: "task-monitor-unhandled",
8378 - status: "running",
8379 - });
8380 - yield* applyMutation({
8381 - sessionId: "mock-session-1",
8382 - taskId: "task-monitor-unhandled",
8383 - status: "completed",
8384 - });
8385 - assert.lengthOf(
8386 - continuationRequests,
8387 - 0,
8388 - "mid-turn completed mutation must not offer while the root turn is active",
8389 - );
8390 -
8391 - yield* Deferred.succeed(promptGates[1]!, { stopReason: "end_turn" });
8392 - const secondProviderTurnId = idAllocator.derive.providerTurn({
8393 - driver: ACP_TEST_DRIVER,
8394 - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"),
8395 - });
8396 - let secondTerminal: string | null = null;
8397 - while (secondTerminal === null) {
8398 - const event = yield* Queue.take(events);
8399 - if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) {
8400 - secondTerminal = event.status;
8401 - }
8402 - }
8403 - assert.equal(secondTerminal, "completed");
8404 - assert.lengthOf(
8405 - continuationRequests,
8406 - 1,
8407 - "post-finalize must offer when mid-turn completion was never handled in-turn",
8408 - );
8409 -
8410 - const firstOffer = continuationRequests[0]!;
8411 - if (firstOffer.clearIfCurrent !== undefined) {
8412 - yield* firstOffer.clearIfCurrent();
8413 - }
8414 - continuationRequests.length = 0;
8415 - yield* runtime
8416 - .startTurn(
8417 - makeTurnInput({
8418 - threadId,
8419 - providerThread,
8420 - instanceId,
8421 - runtimePolicy,
8422 - now: yield* DateTime.now,
8423 - ordinal: 3,
8424 - }),
8425 - )
8426 - .pipe(Effect.forkScoped);
8427 - while (promptGates.length < 3) {
8428 - yield* Effect.yieldNow;
8429 - }
8430 - if (sessionUpdateHandler === undefined || capturedMutation.current === null) {
8431 - return yield* Effect.die("handler must remain wired for turn 3");
8432 - }
8433 - yield* sessionUpdateHandler({
8434 - sessionId: "mock-session-1",
8435 - update: {
8436 - sessionUpdate: "tool_call",
8437 - toolCallId: "tool-call-monitor-handled",
8438 - title: "Monitor: handled",
8439 - kind: "execute",
8440 - status: "pending",
8441 - rawInput: {},
8442 - },
8443 - });
8444 - yield* sessionUpdateHandler({
8445 - sessionId: "mock-session-1",
8446 - update: {
8447 - sessionUpdate: "tool_call_update",
8448 - toolCallId: "tool-call-monitor-handled",
8449 - status: "in_progress",
8450 - },
8451 - });
8452 - yield* capturedMutation.current({
8453 - sessionId: "mock-session-1",
8454 - taskId: "task-monitor-handled",
8455 - status: "running",
8456 - });
8457 - yield* sessionUpdateHandler({
8458 - sessionId: "mock-session-1",
8459 - update: {
8460 - sessionUpdate: "tool_call",
8461 - toolCallId: "tool-call-fetch-handled",
8462 - title: "get_command_or_subagent_output",
8463 - kind: "other",
8464 - status: "pending",
8465 - rawInput: {},
8466 - },
8467 - });
8468 - yield* sessionUpdateHandler({
8469 - sessionId: "mock-session-1",
8470 - update: {
8471 - sessionUpdate: "tool_call_update",
8472 - toolCallId: "tool-call-fetch-handled",
8473 - status: "completed",
8474 - rawOutput: { output: "HANDLED_LISTING" },
8475 - },
8476 - });
8477 - yield* capturedMutation.current({
8478 - sessionId: "mock-session-1",
8479 - taskId: "task-monitor-handled",
8480 - status: "completed",
8481 - });
8482 - assert.lengthOf(continuationRequests, 0, "handled mid-turn completion must not offer");
8483 - yield* Deferred.succeed(promptGates[2]!, { stopReason: "end_turn" });
8484 - const thirdProviderTurnId = idAllocator.derive.providerTurn({
8485 - driver: ACP_TEST_DRIVER,
8486 - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:3"),
8487 - });
8488 - let thirdTerminal: string | null = null;
8489 - while (thirdTerminal === null) {
8490 - const event = yield* Queue.take(events);
8491 - if (event.type === "turn.terminal" && event.providerTurnId === thirdProviderTurnId) {
8492 - thirdTerminal = event.status;
8493 - }
8494 - }
8495 - assert.equal(thirdTerminal, "completed");
8496 - assert.lengthOf(
8497 - continuationRequests,
8498 - 0,
8499 - "post-finalize must not offer when the mid-turn completion was handled in-turn",
6216 + yield* endCommand("task-a", "sleep a");
6217 + yield* agentText("A_DONE");
6218 + assert.lengthOf(continuationRequests, 1);
6219 + assert.equal(continuationRequests[0]?.notification?.summary, 'Command "sleep a" finished');
6220 + yield* endCommand("task-b", "sleep b");
6221 + assert.lengthOf(continuationRequests, 1);
6222 +
6223 + yield* runtime.startTurn(
6224 + makeTurnInput({
6225 + threadId,
6226 + providerThread,
6227 + instanceId,
6228 + runtimePolicy,
6229 + now: yield* DateTime.now,
6230 + ordinal: 2,
6231 + messageCreatedBy: "agent",
6232 + messageCreationSource: "provider",
6233 + messageText: "Background task completed.",
6234 + }),
6235 );
6236 + yield* TestClock.adjust("3 seconds");
6237 + assert.equal(yield* awaitTerminal(2), "completed");
6238 +
6239 + yield* agentText("B_DONE");
6240 + assert.lengthOf(continuationRequests, 2);
6241 + assert.deepEqual(continuationRequests[1]?.notification, {
6242 + source: { kind: "command" },
6243 + outcome: "completed",
6244 + summary: 'Command "sleep b" finished',
6245 + });
6246 }).pipe(Effect.provide(layerTest), Effect.scoped),
6247 );
6248
@@ -8912,249 +6657,6 @@ describe("AcpAdapterV2", () => {
6657 }).pipe(Effect.provide(layerTest), Effect.scoped),
6658 );
6659
8915 - it.live("keeps stale deferred cleanup inert while replacement requests remain live", () =>
8916 - Effect.gen(function* () {
8917 - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
8918 - const path = yield* Path.Path;
8919 - const selfInvocation = yield* resolveSelfInvocation();
8920 - const mockAgentPath = yield* path.fromFileUrl(
8921 - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
8922 - );
8923 - const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
8924 - const instanceId = ProviderInstanceId.make("acp-test");
8925 - const adapter = yield* makeAcpAdapterV2({
8926 - instanceId,
8927 - flavor: {
8928 - driver: ACP_TEST_DRIVER,
8929 - capabilities: AcpProviderCapabilitiesV2,
8930 - restartRuntimeAfterInterrupt: true,
8931 - terminateRuntimeProcessGroupOnInterrupt: true,
8932 - makeRuntime: makeMockRuntime({
8933 - childProcessSpawner,
8934 - mockAgentPath,
8935 - ownDetachedProcessGroup: true,
8936 - processGroupPlatform: "win32",
8937 - windowsProcessTreeTerminator: () => Effect.void,
8938 - environment: { T3_ACP_EMIT_TOOL_CALLS: "1" },
8939 - protocolEvents,
8940 - }),
8941 - },
8942 - selfInvocation,
8943 - });
8944 - const threadId = ThreadId.make("thread-acp-stale-deferred-cleanup");
8945 - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
8946 - runtimeMode: "approval-required",
8947 - interactionMode: "default",
8948 - cwd: process.cwd(),
8949 - });
8950 - const modelSelection = { instanceId, model: "default" } as const;
8951 - const runtime = yield* adapter.openSession({
8952 - threadId,
8953 - providerSessionId: ProviderSessionId.make("provider-session-acp-stale-deferred-cleanup"),
8954 - modelSelection,
8955 - runtimePolicy,
8956 - });
8957 - const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
8958 - yield* runtime.events.pipe(
8959 - Stream.runForEach((event) => Queue.offer(events, event)),
8960 - Effect.forkScoped,
8961 - );
8962 - const providerThread = yield* runtime.ensureThread({
8963 - threadId,
8964 - modelSelection,
8965 - runtimePolicy,
8966 - });
8967 - const now = yield* DateTime.now;
8968 - yield* runtime.startTurn(
8969 - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }),
8970 - );
8971 - const oldPending = yield* Queue.take(events).pipe(
8972 - Effect.repeat({
8973 - until: (event) =>
8974 - event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
8975 - }),
8976 - );
8977 - if (
8978 - oldPending.type !== "runtime_request.updated" ||
8979 - oldPending.runtimeRequest.providerTurnId === null
8980 - ) {
8981 - return yield* Effect.die("Expected the old runtime permission request");
8982 - }
8983 - yield* runtime.interruptTurn({
8984 - providerThread,
8985 - providerTurnId: oldPending.runtimeRequest.providerTurnId,
8986 - requestRuntimeRestart: true,
8987 - });
8988 - const staleResponse = yield* runtime
8989 - .respondToRuntimeRequest({
8990 - requestId: oldPending.runtimeRequest.id,
8991 - decision: "accept",
8992 - })
8993 - .pipe(Effect.exit);
8994 - if (Exit.isSuccess(staleResponse)) {
8995 - assert.fail("teardown must synchronously remove the old pending request");
8996 - }
8997 - while (Option.isSome(yield* Queue.poll(events))) {}
8998 -
8999 - yield* runtime.startTurn(
9000 - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }),
9001 - );
9002 - let replacementPending: ProviderAdapter.ProviderAdapterV2Event | undefined;
9003 - while (replacementPending === undefined) {
9004 - const event = yield* Queue.take(events);
9005 - if (event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending") {
9006 - replacementPending = event;
9007 - }
9008 - }
9009 - if (replacementPending.type !== "runtime_request.updated") {
9010 - return yield* Effect.die("Expected the replacement runtime permission request");
9011 - }
9012 - assert.notEqual(replacementPending.runtimeRequest.id, oldPending.runtimeRequest.id);
9013 - yield* runtime.respondToRuntimeRequest({
9014 - requestId: replacementPending.runtimeRequest.id,
9015 - decision: "accept",
9016 - });
9017 - let replacementTerminal = false;
9018 - while (!replacementTerminal) {
9019 - const event = yield* Queue.take(events);
9020 - if (
9021 - event.type === "runtime_request.updated" &&
9022 - event.runtimeRequest.id === oldPending.runtimeRequest.id
9023 - ) {
9024 - assert.fail("stale deferred cleanup must not emit into generation 2");
9025 - }
9026 - replacementTerminal = event.type === "turn.terminal";
9027 - }
9028 - }).pipe(Effect.provide(layerTest), Effect.scoped),
9029 - );
9030 -
9031 - it.live("resolves owner cancellation and concurrent resume waiters after hard teardown", () =>
9032 - Effect.gen(function* () {
9033 - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
9034 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
9035 - const path = yield* Path.Path;
9036 - const selfInvocation = yield* resolveSelfInvocation();
9037 - const mockAgentPath = yield* path.fromFileUrl(
9038 - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
9039 - );
9040 - const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
9041 - const teardownStarted = yield* Deferred.make<void>();
9042 - const releaseTeardown = yield* Deferred.make<void>();
9043 - let runtimeOrdinalSeen = 0;
9044 - const instanceId = ProviderInstanceId.make("acp-test");
9045 - const adapter = yield* makeAcpAdapterV2({
9046 - instanceId,
9047 - flavor: {
9048 - driver: ACP_TEST_DRIVER,
9049 - capabilities: AcpProviderCapabilitiesV2,
9050 - interruptPromptOnCancel: true,
9051 - restartRuntimeAfterInterrupt: true,
9052 - terminateRuntimeProcessGroupOnInterrupt: true,
9053 - makeRuntime: makeMockRuntime({
9054 - childProcessSpawner,
9055 - mockAgentPath,
9056 - ownDetachedProcessGroup: true,
9057 - processGroupPlatform: "win32",
9058 - windowsProcessTreeTerminator: () =>
9059 - Deferred.succeed(teardownStarted, undefined).pipe(
9060 - Effect.andThen(Deferred.await(releaseTeardown)),
9061 - ),
9062 - environment: (runtimeOrdinal) => {
9063 - runtimeOrdinalSeen = runtimeOrdinal;
9064 - return runtimeOrdinal === 1 ? { T3_ACP_HANG_PROMPT_FOREVER: "1" } : {};
9065 - },
9066 - protocolEvents,
9067 - }),
9068 - },
9069 - selfInvocation,
9070 - });
9071 - const threadId = ThreadId.make("thread-acp-concurrent-resume-teardown");
9072 - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
9073 - runtimeMode: "full-access",
9074 - interactionMode: "default",
9075 - cwd: process.cwd(),
9076 - });
9077 - const modelSelection = { instanceId, model: "default" } as const;
9078 - const runtime = yield* adapter.openSession({
9079 - threadId,
9080 - providerSessionId: ProviderSessionId.make(
9081 - "provider-session-acp-concurrent-resume-teardown",
9082 - ),
9083 - modelSelection,
9084 - runtimePolicy,
9085 - });
9086 - const providerThread = yield* runtime.ensureThread({
9087 - threadId,
9088 - modelSelection,
9089 - runtimePolicy,
9090 - });
9091 - const now = yield* DateTime.now;
9092 - yield* runtime
9093 - .startTurn(
9094 - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }),
9095 - )
9096 - .pipe(Effect.forkScoped);
9097 - yield* Effect.yieldNow;
9098 - yield* Effect.yieldNow;
9099 - yield* Effect.yieldNow;
9100 - yield* pollProtocolMethods(protocolEvents);
9101 - const providerTurnId = idAllocator.derive.providerTurn({
9102 - driver: ACP_TEST_DRIVER,
9103 - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"),
9104 - });
9105 - const interruptFiber = yield* runtime
9106 - .interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true })
9107 - .pipe(Effect.forkScoped);
9108 - yield* Deferred.await(teardownStarted);
9109 - const resumeFiber = yield* runtime
9110 - .resumeThread({ providerThread, modelSelection, runtimePolicy })
9111 - .pipe(Effect.forkScoped);
9112 - const secondResumeFiber = yield* runtime
9113 - .resumeThread({ providerThread, modelSelection, runtimePolicy })
9114 - .pipe(Effect.forkScoped);
9115 - const snapshotProviderThread = {
9116 - ...providerThread,
9117 - nativeThreadRef: {
9118 - ...providerThread.nativeThreadRef!,
9119 - nativeId: "mock-session-snapshot",
9120 - },
9121 - };
9122 - const snapshotFiber = yield* runtime
9123 - .readThreadSnapshot({ providerThread: snapshotProviderThread })
9124 - .pipe(Effect.forkScoped);
9125 - const forkFiber = yield* runtime
9126 - .forkThread({
9127 - sourceProviderThread: providerThread,
9128 - targetThreadId: ThreadId.make("thread-acp-concurrent-fork-after-teardown"),
9129 - })
9130 - .pipe(Effect.forkScoped);
9131 - yield* Effect.yieldNow;
9132 - yield* Effect.yieldNow;
9133 - assert.isUndefined(resumeFiber.pollUnsafe());
9134 - assert.isUndefined(secondResumeFiber.pollUnsafe());
9135 - assert.isUndefined(snapshotFiber.pollUnsafe());
9136 - assert.isUndefined(forkFiber.pollUnsafe());
9137 - assert.equal(runtimeOrdinalSeen, 1);
9138 - const methodsDuringTeardown = yield* pollProtocolMethods(protocolEvents);
9139 - assert.notInclude(methodsDuringTeardown, "session/resume");
9140 - assert.notInclude(methodsDuringTeardown, "session/fork");
9141 - const cancelInterruptOwner = yield* Fiber.interrupt(interruptFiber).pipe(Effect.forkScoped);
9142 - yield* Effect.yieldNow;
9143 - yield* Effect.yieldNow;
9144 - assert.isUndefined(cancelInterruptOwner.pollUnsafe());
9145 - yield* Deferred.succeed(releaseTeardown, undefined);
9146 - yield* Fiber.join(cancelInterruptOwner);
9147 - yield* Fiber.join(resumeFiber);
9148 - yield* Fiber.join(secondResumeFiber);
9149 - yield* Fiber.join(snapshotFiber);
9150 - yield* Fiber.join(forkFiber);
9151 - assert.equal(runtimeOrdinalSeen, 2);
9152 - const methodsAfterRestart = yield* pollProtocolMethods(protocolEvents);
9153 - assert.equal(methodsAfterRestart.filter((method) => method === "session/resume").length, 2);
9154 - assert.equal(methodsAfterRestart.filter((method) => method === "session/fork").length, 1);
9155 - }).pipe(Effect.provide(layerTest), Effect.scoped),
9156 - );
9157 -
6660 it.effect(
6661 "direct Stop on a deferred subagent hold terminalizes the subagent and does not carry it forward",
6662 () =>
@@ -9305,96 +6807,9 @@ describe("AcpAdapterV2", () => {
6807 );
6808 });
6809
9308 -describe("acpPostSettleWakeEvidence", () => {
9309 - const sessionId = "session-wake";
9310 -
9311 - it("rejects monitor end chatter and background mutations", () => {
9312 - assert.isFalse(
9313 - acpPostSettleWakeEvidence({
9314 - sessionId,
9315 - update: {
9316 - sessionUpdate: "agent_message_chunk",
9317 - content: {
9318 - type: "text",
9319 - text: 'Monitor "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" ended',
9320 - },
9321 - },
9322 - }),
9323 - );
9324 - assert.isFalse(
9325 - acpPostSettleWakeEvidence(
9326 - {
9327 - sessionId,
9328 - update: {
9329 - sessionUpdate: "user_message_chunk",
9330 - content: { type: "text", text: "task-1 completed" },
9331 - },
9332 - },
9333 - {
9334 - extractBackgroundToolMutation: () => [
9335 - {
9336 - taskId: "task-1",
9337 - status: "completed",
9338 - appendOutput: "",
9339 - },
9340 - ],
9341 - },
9342 - ),
9343 - );
9344 - });
9345 -});
9346 -
6810 describe("acpPostSettleContinuationOfferEvidence", () => {
6811 const sessionId = "session-wake-offer";
6812
9350 - it("buffers in-progress tool updates without offering", () => {
9351 - assert.isTrue(
9352 - acpPostSettleWakeEvidence({
9353 - sessionId,
9354 - update: {
9355 - sessionUpdate: "tool_call_update",
9356 - toolCallId: "call-1",
9357 - title: "run_terminal_command",
9358 - status: "in_progress",
9359 - kind: "other",
9360 - content: [],
9361 - locations: [],
9362 - rawInput: {},
9363 - },
9364 - }),
9365 - );
9366 - assert.isFalse(
9367 - acpPostSettleContinuationOfferEvidence({
9368 - sessionId,
9369 - update: {
9370 - sessionUpdate: "tool_call_update",
9371 - toolCallId: "call-1",
9372 - title: "run_terminal_command",
9373 - status: "in_progress",
9374 - kind: "other",
9375 - content: [],
9376 - locations: [],
9377 - rawInput: {},
9378 - },
9379 - }),
9380 - );
9381 - assert.isFalse(
9382 - acpPostSettleContinuationOfferEvidence({
9383 - sessionId,
9384 - update: {
9385 - sessionUpdate: "tool_call",
9386 - toolCallId: "call-1",
9387 - title: "run_terminal_command",
9388 - status: "pending",
9389 - kind: "other",
9390 - content: [],
9391 - locations: [],
9392 - rawInput: {},
9393 - },
9394 - }),
9395 - );
9396 - });
9397 -
6813 it("does not offer on a normalized monitor start ACK despite raw completed status", () => {
6814 const monitorStartAck = {
6815 sessionId,
apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
+2 -67
@@ -757,6 +757,7 @@ describe("AcpRegistryAdapterV2", () => {
757 }).pipe(Effect.provide(layerTest), Effect.scoped),
758 );
759
760 + // regression: #19519 models come from session model state, not a hardcoded list
761 it.effect("leaves unadvertised model IDs alone in both model selection protocols", () =>
762 Effect.gen(function* () {
763 const { configurations } = yield* openWithStoredPicks({
@@ -898,73 +899,7 @@ describe("AcpRegistryAdapterV2", () => {
899 );
900 });
901
901 - it.effect("offers client terminals to Devin only and client fs to no registry agent", () =>
902 - Effect.gen(function* () {
903 - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
904 - const path = yield* Path.Path;
905 - const mockAgentPath = yield* path.fromFileUrl(
906 - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
907 - );
908 - const advertisedCapabilities = Effect.fn("advertisedCapabilities")(function* (
909 - agentId: string,
910 - ) {
911 - let clientCapabilities: unknown;
912 - const instanceId = ProviderInstanceId.make(`acp-registry-capabilities-${agentId}`);
913 - const adapter = yield* makeAcpRegistryAdapterV2({
914 - selfInvocation: yield* resolveSelfInvocation(),
915 - instanceId,
916 - settings: yield* decodeAcpRegistryAdapterSettings({ agentId, authMethodId: "test" }),
917 - environment: {},
918 - makeRuntime: (input) =>
919 - Effect.gen(function* () {
920 - clientCapabilities = input.clientCapabilities;
921 - const { processEnvironment: _processEnvironment, ...runtimeInput } = input;
922 - const context = yield* Layer.build(
923 - AcpSessionRuntime.layer({
924 - ...runtimeInput,
925 - spawn: {
926 - command: process.execPath,
927 - args: [mockAgentPath],
928 - cwd: input.cwd,
929 - env: { T3_ACP_SESSION_LIFECYCLE: "1" },
930 - },
931 - authMethodId: "test",
932 - }).pipe(
933 - Layer.provide(
934 - Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
935 - ),
936 - ),
937 - );
938 - return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
939 - Effect.provide(context),
940 - );
941 - }),
942 - }).pipe(Effect.provide(layerInjectedRuntimeCatalog));
943 - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
944 - runtimeMode: "full-access",
945 - interactionMode: "default",
946 - cwd: process.cwd(),
947 - });
948 - yield* adapter.openSession({
949 - threadId: ThreadId.make(`thread-acp-registry-capabilities-${agentId}`),
950 - providerSessionId: ProviderSessionId.make(`provider-session-capabilities-${agentId}`),
951 - modelSelection: { instanceId, model: "default" },
952 - runtimePolicy,
953 - });
954 - return clientCapabilities;
955 - });
956 -
957 - assert.deepInclude(yield* advertisedCapabilities("devin"), {
958 - fs: { readTextFile: false, writeTextFile: false },
959 - terminal: true,
960 - });
961 - assert.deepInclude(yield* advertisedCapabilities("gemini"), {
962 - fs: { readTextFile: false, writeTextFile: false },
963 - terminal: false,
964 - });
965 - }).pipe(Effect.provide(layerTest), Effect.scoped),
966 - );
967 -
902 + // regression: #21618 Claude Agent needs ACP v2 for native background lifecycle
903 it.effect("launches Claude Agent on ACP v2 unless its instance environment decides", () =>
904 Effect.gen(function* () {
905 const launchSwitch = Effect.fn("launchSwitch")(function* (
apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
-105
@@ -377,111 +377,6 @@ describe("AntigravityAdapterV2 workspace changes", () => {
377 );
378 });
379
380 -describe("AntigravityAdapterV2 client file system under restrictive policies", () => {
381 - it.effect("serves in-workspace reads and writes and still refuses outside paths", () =>
382 - Effect.gen(function* () {
383 - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
384 - const fileSystem = yield* FileSystem.FileSystem;
385 - const path = yield* Path.Path;
386 - const crypto = yield* Crypto.Crypto;
387 - const mockAgentPath = yield* path.fromFileUrl(
388 - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
389 - );
390 - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
391 - const policies = [
392 - {
393 - name: "read-only sandbox",
394 - policy: {
395 - runtimeMode: "full-access",
396 - approvalPolicy: "never",
397 - sandboxPolicy: { type: "readOnly" },
398 - },
399 - },
400 - { name: "approval-required", policy: { runtimeMode: "approval-required" } },
401 - ] as const;
402 - for (const { name, policy } of policies) {
403 - let readTextFile: Parameters<RuntimeService["handleReadTextFile"]>[0] | undefined;
404 - let writeTextFile: Parameters<RuntimeService["handleWriteTextFile"]>[0] | undefined;
405 - const instanceId = ProviderInstanceId.make(`antigravity-restrictive-${policy.runtimeMode}`);
406 - const adapter = yield* makeAntigravityAdapterV2({
407 - instanceId,
408 - selfInvocation: yield* resolveSelfInvocation(),
409 - makeRuntime: (input) =>
410 - makeAntigravityAcpRuntime({
411 - ...input,
412 - childProcessSpawner,
413 - spawn: {
414 - command: process.execPath,
415 - args: [mockAgentPath],
416 - cwd: input.cwd,
417 - env: { T3_ACP_ANTIGRAVITY: "1" },
418 - },
419 - }).pipe(
420 - Effect.provideService(Crypto.Crypto, crypto),
421 - Effect.map((runtime): RuntimeService => ({
422 - ...runtime,
423 - handleReadTextFile: (handler) =>
424 - Effect.sync(() => {
425 - readTextFile = handler;
426 - }).pipe(Effect.andThen(runtime.handleReadTextFile(handler))),
427 - handleWriteTextFile: (handler) =>
428 - Effect.sync(() => {
429 - writeTextFile = handler;
430 - }).pipe(Effect.andThen(runtime.handleWriteTextFile(handler))),
431 - })),
432 - ),
433 - withProcess: (_stop, task) => task,
434 - defaultModel: Effect.succeed(undefined),
435 - });
436 - const workspace = yield* fileSystem.makeTempDirectoryScoped({
437 - prefix: "t3-ag-restrictive-",
438 - });
439 - const outside = yield* fileSystem.makeTempDirectoryScoped({
440 - prefix: "t3-ag-restrictive-outside-",
441 - });
442 - yield* fileSystem.writeFileString(path.join(workspace, "existing.ts"), "existing");
443 - const threadId = ThreadId.make(`thread-antigravity-restrictive-${policy.runtimeMode}`);
444 - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
445 - ...policy,
446 - interactionMode: "default",
447 - cwd: workspace,
448 - });
449 - const modelSelection = { instanceId, model: "gemini-test-low" } as const;
450 - const session = yield* adapter.openSession({
451 - threadId,
452 - providerSessionId: ProviderSessionId.make(
453 - `provider-session-antigravity-restrictive-${policy.runtimeMode}`,
454 - ),
455 - modelSelection,
456 - runtimePolicy,
457 - });
458 - yield* session.ensureThread({ threadId, modelSelection, runtimePolicy });
459 - if (readTextFile === undefined || writeTextFile === undefined) {
460 - return yield* Effect.die("Antigravity sessions must serve client file requests");
461 - }
462 - const context = (method: string) => ({ requestId: `test-${method}`, method });
463 - const read = yield* readTextFile(
464 - { sessionId: "mock-session-1", path: path.join(workspace, "existing.ts") },
465 - context("fs/read_text_file"),
466 - );
467 - assert.equal(read.content, "existing", name);
468 - const written = path.join(workspace, "src", "edited.ts");
469 - yield* writeTextFile(
470 - { sessionId: "mock-session-1", path: written, content: "edited" },
471 - context("fs/write_text_file"),
472 - );
473 - assert.equal(yield* fileSystem.readFileString(written), "edited", name);
474 - const outsideWrite = yield* writeTextFile(
475 - { sessionId: "mock-session-1", path: path.join(outside, "x.ts"), content: "x" },
476 - context("fs/write_text_file"),
477 - ).pipe(Effect.exit);
478 - assert.isTrue(Exit.isFailure(outsideWrite), name);
479 - assert.isFalse(yield* fileSystem.exists(path.join(outside, "x.ts")), name);
480 - }
481 - }).pipe(Effect.provide(layerSession), Effect.scoped),
482 - );
483 -});
484 -
380 describe("AntigravityAdapterV2 html_render pages", () => {
381 it.effect("shows the page html_render published when the agent reports only a summary", () =>
382 Effect.gen(function* () {
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+282 -2384
@@ -49,7 +49,6 @@ import {
49 ThreadId,
50 } from "@t3tools/contracts";
51 import { assert, describe, it } from "@effect/vitest";
52 -import * as Clock from "effect/Clock";
52 import * as Context from "effect/Context";
53 import * as DateTime from "effect/DateTime";
54 import * as Deferred from "effect/Deferred";
@@ -316,29 +315,6 @@ describe("ClaudeAdapterV2 runtime query policy", () => {
315 });
316 });
317
319 - it("maps canonical read-only on-request policy to Claude default with callbacks", () => {
320 - const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
321 - ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
322 - runtimeMode: "full-access",
323 - interactionMode: "default",
324 - cwd: "/workspace",
325 - approvalPolicy: "on-request",
326 - sandboxPolicy: {
327 - type: "readOnly",
328 - access: { type: "fullAccess" },
329 - networkAccess: false,
330 - },
331 - }),
332 - );
333 -
334 - assert.deepEqual(queryPolicy, {
335 - permissionMode: "default",
336 - tools: ClaudeAdapterV2.CLAUDE_READ_ONLY_ALLOWED_TOOLS,
337 - allowedTools: ClaudeAdapterV2.CLAUDE_READ_ONLY_ALLOWED_TOOLS,
338 - installPermissionCallback: true,
339 - });
340 - });
341 -
318 it("does not auto-allow reads for canonical restricted read-only never policy", () => {
319 const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
320 ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
@@ -422,45 +398,6 @@ describe("ClaudeAdapterV2 runtime query policy", () => {
398 installPermissionCallback: true,
399 });
400 });
425 -
426 - it("honors never approvals for approval-required workspace-write policy", () => {
427 - const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
428 - ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
429 - runtimeMode: "approval-required",
430 - interactionMode: "default",
431 - cwd: "/workspace",
432 - approvalPolicy: "never",
433 - sandboxPolicy: {
434 - type: "workspaceWrite",
435 - },
436 - }),
437 - );
438 -
439 - assert.deepEqual(queryPolicy, {
440 - permissionMode: "dontAsk",
441 - installPermissionCallback: false,
442 - });
443 - });
444 -
445 - it("honors never approvals for externally sandboxed policy", () => {
446 - const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
447 - ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
448 - runtimeMode: "approval-required",
449 - interactionMode: "default",
450 - cwd: "/workspace",
451 - approvalPolicy: "never",
452 - sandboxPolicy: {
453 - type: "externalSandbox",
454 - },
455 - }),
456 - );
457 -
458 - assert.deepEqual(queryPolicy, {
459 - permissionMode: "bypassPermissions",
460 - allowDangerouslySkipPermissions: true,
461 - installPermissionCallback: false,
462 - });
463 - });
401 });
402
403 describe("ClaudeAdapterV2 MCP query overrides", () => {
@@ -507,37 +444,6 @@ describe("ClaudeAdapterV2 MCP query overrides", () => {
444 assert.isFalse(overrides.allowedTools?.includes(ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_WILDCARD));
445 });
446
510 - it("keys live-query reuse on the MCP-derived pre-approvals", () => {
511 - const threadId = ThreadId.make("thread-claude-mcp-query-key");
512 - const mcpSession = mcpSessionFor(threadId);
513 - const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(
514 - ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
515 - runtimeMode: "full-access",
516 - interactionMode: "default",
517 - cwd: "/workspace",
518 - approvalPolicy: "on-request",
519 - sandboxPolicy: {
520 - type: "readOnly",
521 - access: { type: "fullAccess" },
522 - networkAccess: false,
523 - },
524 - }),
525 - );
526 -
527 - const readOnlyKey = ClaudeAdapterV2.claudeEffectiveQueryPolicyKey(
528 - queryPolicy,
529 - ClaudeAdapterV2.claudeMcpQueryOverrides({ mcpSession, readOnlySandbox: true }),
530 - );
531 - const fullAccessKey = ClaudeAdapterV2.claudeEffectiveQueryPolicyKey(
532 - queryPolicy,
533 - ClaudeAdapterV2.claudeMcpQueryOverrides({ mcpSession, readOnlySandbox: false }),
534 - );
535 - const detachedKey = ClaudeAdapterV2.claudeEffectiveQueryPolicyKey(queryPolicy, {});
536 -
537 - assert.notEqual(readOnlyKey, fullAccessKey);
538 - assert.notEqual(fullAccessKey, detachedKey);
539 - });
540 -
447 it("invalidates live-query reuse when MCP credentials rotate", () => {
448 const threadId = ThreadId.make("thread-claude-mcp-credential-rotation");
449 const mcpSession = mcpSessionFor(threadId);
@@ -641,50 +547,6 @@ describe("ClaudeAdapterV2 native protocol logging", () => {
547 assert.equal(logged.hasMcpServers, true);
548 assert.notInclude(JSON.stringify(logged), "secret-claude-token");
549 });
644 -
645 - it("logs query options without leaking environment values or callback functions", () => {
646 - const options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions = {
647 - model: "claude-sonnet-4-6",
648 - tools: {
649 - type: "preset",
650 - preset: "claude_code",
651 - },
652 - permissionMode: "default",
653 - sessionId: "native-thread-1",
654 - cwd: "/workspace",
655 - env: {
656 - ANTHROPIC_API_KEY: "secret",
657 - },
658 - extraArgs: {
659 - "append-system-prompt": "secret launch prompt",
660 - },
661 - canUseTool: (_toolName, input, callbackOptions) =>
662 - Promise.resolve({
663 - behavior: "allow",
664 - updatedInput: input,
665 - toolUseID: callbackOptions.toolUseID,
666 - decisionClassification: "user_temporary",
667 - }),
668 - };
669 -
670 - assert.deepEqual(ClaudeAdapterV2.loggedClaudeQueryOptions(options), {
671 - model: "claude-sonnet-4-6",
672 - tools: {
673 - type: "preset",
674 - preset: "claude_code",
675 - },
676 - permissionMode: "default",
677 - sessionId: "native-thread-1",
678 - cwd: "/workspace",
679 - hasCanUseTool: true,
680 - hasEnvironment: true,
681 - hasExtraArgs: true,
682 - });
683 - assert.notInclude(
684 - JSON.stringify(ClaudeAdapterV2.loggedClaudeQueryOptions(options)),
685 - "secret launch prompt",
686 - );
687 - });
550 });
551
552 describe("ClaudeAdapterV2 context usage", () => {
@@ -705,6 +567,7 @@ describe("ClaudeAdapterV2 context usage", () => {
567 });
568
569 describe("ClaudeAdapterV2 session permissions", () => {
570 + // regression: #15892 an explicit user refusal must stay user_reject, not a tool failure
571 it("keeps explicit user refusals classified as user_reject", () => {
572 const result = ClaudeAdapterV2.permissionResultFromDecision({
573 toolName: "Bash",
@@ -986,6 +849,7 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {
849 ),
850 );
851
852 + // regression: #20413 malformed append-system-prompt launch args fail before a query opens
853 it.effect.each([
854 [
855 "--append-system-prompt-file missing.md",
@@ -1630,95 +1494,6 @@ describe("ClaudeAdapterV2 attachments", () => {
1494 ),
1495 ),
1496 );
1633 -
1634 - it.effect("rejects unsupported image types before opening a provider query", () =>
1635 - Effect.scoped(
1636 - Effect.gen(function* () {
1637 - const fileSystem = yield* FileSystem.FileSystem;
1638 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
1639 - const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
1640 - prefix: "t3-claude-v2-unsupported-attachment-",
1641 - });
1642 - let openCount = 0;
1643 - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
1644 - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
1645 - settings: DEFAULT_CLAUDE_SETTINGS,
1646 - environment: {},
1647 - attachmentsDir,
1648 - fileSystem,
1649 - path: yield* Path.Path,
1650 - crypto: yield* Crypto.Crypto,
1651 - idAllocator,
1652 - queryRunner: {
1653 - allocateSessionId: Effect.succeed("native-thread-claude-unsupported-attachment"),
1654 - open: () =>
1655 - Effect.sync(() => {
1656 - openCount += 1;
1657 - return {
1658 - messages: Stream.never,
1659 - offer: () => Effect.void,
1660 - setModel: () => Effect.void,
1661 - applyFlagSettings: () => Effect.void,
1662 - setPermissionMode: () => Effect.void,
1663 - backgroundTasks: () => Effect.succeed(false),
1664 - stopTask: () => Effect.void,
1665 - interrupt: Effect.void,
1666 - close: Effect.void,
1667 - };
1668 - }),
1669 - forkSession: () => Effect.die("unused forkSession"),
1670 - subagentLaunchToolUseId: () => Effect.succeed(null),
1671 - assertComplete: Effect.void,
1672 - },
1673 - });
1674 - const threadId = ThreadId.make("thread-claude-unsupported-attachment");
1675 - const runtime = yield* adapter.openSession({
1676 - threadId,
1677 - providerSessionId: ProviderSessionId.make(
1678 - "provider-session-claude-unsupported-attachment",
1679 - ),
1680 - modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1681 - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
1682 - });
1683 - const providerThread = yield* runtime.ensureThread({
1684 - threadId,
1685 - modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1686 - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
1687 - });
1688 - const attachment = ChatImageAttachment.make({
1689 - type: "image",
1690 - id: ChatAttachmentId.make(
1691 - "thread-claude-unsupported-12345678-1234-1234-1234-123456789abc",
1692 - ),
1693 - name: "diagram.svg",
1694 - mimeType: "image/svg+xml",
1695 - sizeBytes: 4,
1696 - });
1697 - const now = yield* DateTime.now;
1698 -
1699 - const error = yield* runtime
1700 - .startTurn(
1701 - makeClaudeTestTurnInput({
1702 - threadId,
1703 - providerThread,
1704 - now,
1705 - attemptId: RunAttemptId.make("attempt-claude-unsupported-attachment"),
1706 - text: "Inspect this image.",
1707 - attachments: [attachment],
1708 - }),
1709 - )
1710 - .pipe(Effect.flip);
1711 -
1712 - assert.equal(error._tag, "ProviderAdapterTurnStartError");
1713 - assert.include(String(error.cause), "Unsupported Claude image attachment type");
1714 - assert.equal(openCount, 0);
1715 - }).pipe(
1716 - Effect.provide(
1717 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
1718 - ),
1719 - ),
1720 - ),
1721 - );
1497 });
1498
1499 describe("ClaudeAdapterV2 native fork", () => {
@@ -2864,6 +2639,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2639 ),
2640 );
2641
2642 + // regression: #21806 bypass policy reads the custom home and project, never ambient ~/.claude
2643 it.effect(
2644 "combines a normalized custom home with project policy without reading the ambient user tier",
2645 () =>
@@ -2912,6 +2688,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2688 ),
2689 );
2690
2691 + // regression: #21806 only a missing custom settings file is benign; bad policy fails
2692 it.effect(
2693 "distinguishes missing custom settings from unreadable, malformed, or unresolved policy",
2694 () =>
@@ -3220,6 +2997,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2997 ),
2998 );
2999
3000 + // regression: #15475 MCP title arriving after the tool starts must survive to completion
3001 it.effect.each([
3002 { isError: false, title: "Check weather" },
3003 { isError: true, title: "Check weather" },
@@ -3545,6 +3323,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
3323 ),
3324 );
3325
3326 + // regression: #15892 non-execution metadata is carried through, not guessed from result text
3327 it.effect.each(["cancelled", "denied", "permission_denied", undefined])(
3328 "preserves native tool non-execution metadata %s without inferring a denial from text",
3329 (kind) =>
@@ -4869,70 +4648,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
4648 ),
4649 );
4650
4872 - it.effect("surfaces a Claude safety model fallback without failing the turn", () =>
4873 - Effect.gen(function* () {
4874 - const harness = yield* makeWakeHarness;
4875 - const now = yield* DateTime.now;
4876 - yield* harness.runtime.startTurn(
4877 - makeClaudeTestTurnInput({
4878 - threadId: harness.threadId,
4879 - providerThread: harness.providerThread,
4880 - now,
4881 - attemptId: RunAttemptId.make("claude-safety-fallback-attempt"),
4882 - text: "Continue the audit",
4883 - attachments: [],
4884 - }),
4885 - );
4886 - const notice = "Safeguards flagged this message. Switched to Opus 4.8.";
4887 - const uuid = "00000000-0000-4000-8000-000000000301";
4888 - yield* Queue.offer(
4889 - harness.sdkMessages,
4890 - claudeSdkFrame({
4891 - type: "system",
4892 - subtype: "model_refusal_fallback",
4893 - trigger: "refusal",
4894 - direction: "retry",
4895 - original_model: "claude-fable-5",
4896 - fallback_model: "claude-opus-4-8",
4897 - request_id: "request-safety-fallback",
4898 - api_refusal_category: "cyber",
4899 - api_refusal_explanation: null,
4900 - content: notice,
4901 - session_id: WAKE_NATIVE_SESSION,
4902 - uuid,
4903 - }),
4904 - );
4905 - yield* Queue.offer(
4906 - harness.sdkMessages,
4907 - makeResultFrame({
4908 - uuid: "00000000-0000-4000-8000-000000000302",
4909 - result: "Audit complete.",
4910 - }),
4911 - );
4912 - yield* Queue.take(harness.terminalReceipts);
4913 - const notices = harness.events.flatMap((event) =>
4914 - event.type === "turn_item.updated" && event.turnItem.type === "system_notice"
4915 - ? [event.turnItem]
4916 - : [],
4917 - );
4918 - assert.lengthOf(notices, 1);
4919 - assert.equal(notices[0]?.message, notice);
4920 - assert.equal(notices[0]?.status, "completed");
4921 - assert.equal(notices[0]?.nativeItemRef?.nativeId, uuid);
4922 - assert.equal(harness.terminalEvents()[0]?.status, "completed");
4923 - assert.isFalse(
4924 - harness.events.some(
4925 - (event) => event.type === "turn_item.updated" && event.turnItem.type === "error",
4926 - ),
4927 - );
4928 - }).pipe(
4929 - Effect.scoped,
4930 - Effect.provide(
4931 - Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
4932 - ),
4933 - ),
4934 - );
4935 -
4651 it.effect("shows a hook-dropped Claude prompt once and skips info-level lines", () =>
4652 Effect.gen(function* () {
4653 const harness = yield* makeWakeHarness;
@@ -6194,6 +5909,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
5909 ),
5910 );
5911
5912 + // regression: #14964 structured task output attaches to exactly one tool result
5913 it.effect("does not associate structured task output with multiple tool results", () =>
5914 Effect.gen(function* () {
5915 const harness = yield* makeTaskToolHarness;
@@ -6287,125 +6003,56 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6003 ),
6004 );
6005
6290 - it.effect("carries exhausted retry progress into the terminal provider error", () =>
6291 - Effect.scoped(
6292 - Effect.gen(function* () {
6293 - const harness = yield* makeWakeHarness;
6294 - const now = yield* DateTime.now;
6295 - yield* harness.runtime.startTurn(
6296 - makeClaudeTestTurnInput({
6297 - threadId: harness.threadId,
6298 - providerThread: harness.providerThread,
6299 - now,
6300 - attemptId: RunAttemptId.make("attempt-claude-api-retry-exhausted"),
6301 - text: "Open github.com.",
6302 - attachments: [],
6303 - }),
6304 - );
6305 - yield* Queue.offer(
6306 - harness.sdkMessages,
6307 - claudeSdkFrame({
6308 - type: "system",
6309 - subtype: "api_retry",
6310 - attempt: 10,
6311 - max_retries: 10,
6312 - retry_delay_ms: 38_010,
6313 - error_status: 529,
6314 - error: "overloaded",
6315 - uuid: "00000000-0000-4000-8000-000000000203",
6316 - session_id: WAKE_NATIVE_SESSION,
6317 - }),
6318 - );
6319 - yield* Queue.offer(
6320 - harness.sdkMessages,
6321 - makeResultFrame({
6322 - uuid: "00000000-0000-4000-8000-000000000204",
6323 - result: "Claude is temporarily overloaded.",
6324 - isError: true,
6325 - apiErrorStatus: 529,
6326 - }),
6327 - );
6328 - yield* harness.awaitTerminal(1);
6329 -
6330 - const terminal = harness.terminalEvents()[0];
6331 - assert.equal(terminal?.status, "failed");
6332 - if (terminal?.status !== "failed") return;
6333 - assert.deepEqual(terminal.retry, {
6334 - attempt: 10,
6335 - maxAttempts: 10,
6336 - retryDelayMs: 38_010,
6337 - });
6338 - assert.isDefined(terminal.retryStartedAt);
6339 - assert.equal(terminal.failure.code, "api_error_529");
6340 - }).pipe(
6341 - Effect.provide(
6342 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
6343 - ),
6344 - ),
6345 - ),
6346 - );
6347 -
6348 - it.effect.each([
6349 - "api_error",
6350 - "malformed_tool_use_exhausted",
6351 - "budget_exhausted",
6352 - "structured_output_retry_exhausted",
6353 - "tool_deferred_unavailable",
6354 - "turn_setup_failed",
6355 - "blocking_limit",
6356 - "rapid_refill_breaker",
6357 - "prompt_too_long",
6358 - "image_error",
6359 - "model_error",
6360 - "overloaded_status",
6361 - ] as const)("fails a success-shaped Claude result with %s", (terminalReason) =>
6362 - Effect.scoped(
6363 - Effect.gen(function* () {
6364 - const harness = yield* makeWakeHarness;
6365 - const now = yield* DateTime.now;
6366 - yield* harness.runtime.startTurn(
6367 - makeClaudeTestTurnInput({
6368 - threadId: harness.threadId,
6369 - providerThread: harness.providerThread,
6370 - now,
6371 - attemptId: RunAttemptId.make("attempt-structured-terminal-failure"),
6372 - text: "Complete the task.",
6373 - attachments: [],
6374 - }),
6375 - );
6376 - yield* Queue.offer(
6377 - harness.sdkMessages,
6378 - makeResultFrame({
6379 - uuid: "00000000-0000-4000-8000-000000000205",
6380 - result: "Provider failure details.",
6381 - isError: false,
6382 - ...(terminalReason === "overloaded_status"
6383 - ? { apiErrorStatus: 529 }
6384 - : { terminalReason }),
6385 - }),
6386 - );
6387 - const terminal = yield* Queue.take(harness.terminalReceipts);
6388 - assert.equal(terminal.status, "failed");
6389 - if (terminal.status !== "failed") return;
6390 - assert.isNotEmpty(terminal.failure.message);
6391 - assert.equal(terminal.failure.class, "provider_error");
6392 - assert.isFalse(
6393 - harness.events.some(
6394 - (event) =>
6395 - event.type === "message.updated" &&
6396 - event.message.text === "Provider failure details.",
6006 + it.effect.each(["api_error", "overloaded_status"] as const)(
6007 + "fails a success-shaped Claude result with %s",
6008 + (terminalReason) =>
6009 + Effect.scoped(
6010 + Effect.gen(function* () {
6011 + const harness = yield* makeWakeHarness;
6012 + const now = yield* DateTime.now;
6013 + yield* harness.runtime.startTurn(
6014 + makeClaudeTestTurnInput({
6015 + threadId: harness.threadId,
6016 + providerThread: harness.providerThread,
6017 + now,
6018 + attemptId: RunAttemptId.make("attempt-structured-terminal-failure"),
6019 + text: "Complete the task.",
6020 + attachments: [],
6021 + }),
6022 + );
6023 + yield* Queue.offer(
6024 + harness.sdkMessages,
6025 + makeResultFrame({
6026 + uuid: "00000000-0000-4000-8000-000000000205",
6027 + result: "Provider failure details.",
6028 + isError: false,
6029 + ...(terminalReason === "overloaded_status"
6030 + ? { apiErrorStatus: 529 }
6031 + : { terminalReason }),
6032 + }),
6033 + );
6034 + const terminal = yield* Queue.take(harness.terminalReceipts);
6035 + assert.equal(terminal.status, "failed");
6036 + if (terminal.status !== "failed") return;
6037 + assert.isNotEmpty(terminal.failure.message);
6038 + assert.equal(terminal.failure.class, "provider_error");
6039 + assert.isFalse(
6040 + harness.events.some(
6041 + (event) =>
6042 + event.type === "message.updated" &&
6043 + event.message.text === "Provider failure details.",
6044 + ),
6045 + );
6046 + assert.equal(
6047 + terminal.failure.code,
6048 + terminalReason === "overloaded_status" ? "api_error_529" : terminalReason,
6049 + );
6050 + }).pipe(
6051 + Effect.provide(
6052 + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
6053 ),
6398 - );
6399 - assert.equal(
6400 - terminal.failure.code,
6401 - terminalReason === "overloaded_status" ? "api_error_529" : terminalReason,
6402 - );
6403 - }).pipe(
6404 - Effect.provide(
6405 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
6054 ),
6055 ),
6408 - ),
6056 );
6057
6058 // Frames follow #19832: a full context window ends the turn with
@@ -7605,101 +7252,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7252 ),
7253 );
7254
7608 - it.effect("drops a zero-turn task-notification result while awaiting a prompt echo", () =>
7609 - Effect.scoped(
7610 - Effect.gen(function* () {
7611 - const harness = yield* makeWakeHarness;
7612 - const now = yield* DateTime.now;
7613 - const firstAttempt = RunAttemptId.make("attempt-claude-echo-debris-1");
7614 - const secondAttempt = RunAttemptId.make("attempt-claude-echo-debris-2");
7615 - const stamp = (frame: SDKMessage, promptIndex: number) =>
7616 - claudeSdkFrame({
7617 - ...frame,
7618 - user_message_uuid: harness.promptUuid(promptIndex),
7619 - });
7620 -
7621 - yield* harness.runtime.startTurn(
7622 - makeClaudeTestTurnInput({
7623 - threadId: harness.threadId,
7624 - providerThread: harness.providerThread,
7625 - now,
7626 - attemptId: firstAttempt,
7627 - text: "First.",
7628 - attachments: [],
7629 - }),
7630 - );
7631 - yield* Queue.offer(
7632 - harness.sdkMessages,
7633 - stamp(
7634 - makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000760", text: "One." }),
7635 - 0,
7636 - ),
7637 - );
7638 - yield* Queue.offer(
7639 - harness.sdkMessages,
7640 - stamp(
7641 - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000761", result: "One." }),
7642 - 0,
7643 - ),
7644 - );
7645 - yield* harness.awaitTerminal(1);
7646 -
7647 - yield* harness.runtime.startTurn(
7648 - makeClaudeTestTurnInput({
7649 - threadId: harness.threadId,
7650 - providerThread: harness.providerThread,
7651 - now,
7652 - attemptId: secondAttempt,
7653 - text: "Second.",
7654 - attachments: [],
7655 - providerTurnOrdinal: 2,
7656 - }),
7657 - );
7658 - yield* Queue.offer(
7659 - harness.sdkMessages,
7660 - makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000764", text: "Stale." }),
7661 - );
7662 - yield* Queue.offer(harness.sdkMessages, staleTaskNotificationResult);
7663 - yield* Queue.offer(
7664 - harness.sdkMessages,
7665 - stamp(
7666 - makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000762", text: "Two." }),
7667 - 1,
7668 - ),
7669 - );
7670 - yield* Queue.offer(
7671 - harness.sdkMessages,
7672 - stamp(
7673 - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000763", result: "Two." }),
7674 - 1,
7675 - ),
7676 - );
7677 - yield* harness.awaitTerminal(2);
7678 - assert.equal(harness.terminalEvents()[1]?.status, "completed");
7679 - assert.lengthOf(harness.continuationRequests, 0);
7680 - assert.deepEqual(
7681 - harness.events.flatMap((event) =>
7682 - event.type === "message.updated" && event.message.role === "assistant"
7683 - ? [event.message.text]
7684 - : [],
7685 - ),
7686 - ["One.", "Stale.", "Two."],
7687 - );
7688 - assert.isFalse(
7689 - harness.events.some(
7690 - (event) =>
7691 - event.type === "message.updated" &&
7692 - event.message.text === STALE_TASK_NOTIFICATION_RESULT_TEXT,
7693 - ),
7694 - );
7695 - }).pipe(
7696 - Effect.provide(
7697 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
7698 - ),
7699 - ),
7700 - ),
7701 - );
7702 -
7255 it.effect("releases output held for a prompt echo when the stream ends", () =>
7256 Effect.scoped(
7257 Effect.gen(function* () {
@@ -7816,6 +7368,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7368 ),
7369 );
7370
7371 + // regression: #16897 a prompt whose uuid the session already holds must not hang or end early
7372 it.effect("keeps a started prompt running until its result", () =>
7373 Effect.scoped(
7374 Effect.gen(function* () {
@@ -8177,72 +7730,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7730 ),
7731 );
7732
8180 - it.effect("terminalizes an agent server wake from a positive task-notification result", () =>
8181 - Effect.scoped(
8182 - Effect.gen(function* () {
8183 - const harness = yield* makeWakeHarness;
8184 - const now = yield* DateTime.now;
8185 - const wakeText = "The background command completed.";
8186 -
8187 - yield* harness.runtime.startTurn(
8188 - makeClaudeTestTurnInput({
8189 - threadId: harness.threadId,
8190 - providerThread: harness.providerThread,
8191 - now,
8192 - attemptId: RunAttemptId.make("attempt-claude-agent-server-wake"),
8193 - text: "Background task completed.",
8194 - attachments: [],
8195 - messageCreatedBy: "agent",
8196 - messageCreationSource: "server",
8197 - }),
8198 - );
8199 - yield* Queue.offer(
8200 - harness.sdkMessages,
8201 - makeAssistantTextFrame({
8202 - uuid: "00000000-0000-4000-8000-00000000010b",
8203 - text: wakeText,
8204 - }),
8205 - );
8206 - yield* Queue.offer(
8207 - harness.sdkMessages,
8208 - makeResultFrame({
8209 - uuid: "00000000-0000-4000-8000-00000000010c",
8210 - result: wakeText,
8211 - numTurns: 154,
8212 - origin: { kind: "task-notification" },
8213 - }),
8214 - );
8215 - yield* harness.awaitTerminal(1);
8216 - assert.equal(harness.terminalEvents()[0]?.status, "completed");
8217 -
8218 - yield* harness.runtime.startTurn(
8219 - makeClaudeTestTurnInput({
8220 - threadId: harness.threadId,
8221 - providerThread: harness.providerThread,
8222 - now,
8223 - attemptId: RunAttemptId.make("attempt-claude-agent-server-next"),
8224 - text: "What finished?",
8225 - attachments: [],
8226 - providerTurnOrdinal: 2,
8227 - }),
8228 - );
8229 - yield* Queue.offer(
8230 - harness.sdkMessages,
8231 - makeResultFrame({
8232 - uuid: "00000000-0000-4000-8000-00000000010d",
8233 - result: "The background command finished.",
8234 - }),
8235 - );
8236 - yield* harness.awaitTerminal(2);
8237 - assert.equal(harness.terminalEvents()[1]?.status, "completed");
8238 - }).pipe(
8239 - Effect.provide(
8240 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
8241 - ),
8242 - ),
8243 - ),
8244 - );
8245 -
7733 it.effect("ignores a zero-turn task-notification origin result during a normal user turn", () =>
7734 Effect.scoped(
7735 Effect.gen(function* () {
@@ -8655,375 +8142,118 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8142 ),
8143 );
8144
8658 - it.effect("a subagent re-run in the foreground does not join a later wake", () =>
8145 + it.effect("streams a background subagent's work while the root turn is idle", () =>
8146 Effect.scoped(
8147 Effect.gen(function* () {
8148 + const TASK_ID = "task-live-idle";
8149 + const TOOL_USE_ID = "toolu-live-idle";
8150 + const STRADDLING_BASH = "toolu-live-straddling-bash";
8151 + const IDLE_BASH = "toolu-live-idle-bash";
8152 const harness = yield* makeWakeHarness;
8153 const now = yield* DateTime.now;
8663 - const taskId = "task-foreground-rerun";
8664 - const toolUseId = "toolu_foreground_rerun";
8665 - const userTurn = (attempt: string, providerTurnOrdinal: number) =>
8666 - harness.runtime.startTurn(
8667 - makeClaudeTestTurnInput({
8668 - threadId: harness.threadId,
8669 - providerThread: harness.providerThread,
8670 - now,
8671 - attemptId: RunAttemptId.make(attempt),
8672 - text: "Go on.",
8673 - attachments: [],
8674 - providerTurnOrdinal,
8675 - }),
8154 + const latestToolItem = (nativeId: string) =>
8155 + harness.events.findLast(
8156 + (event) =>
8157 + event.type === "turn_item.updated" &&
8158 + event.turnItem.nativeItemRef?.nativeId === nativeId,
8159 );
8677 - const result = (uuid: string) => makeResultFrame({ uuid, result: "Done." });
8678 - const ended = (uuid: string) =>
8679 - makeSubagentNotificationFrame({ taskId, toolUseId, summary: "AUDITED", uuid });
8680 -
8681 - yield* userTurn("attempt-rerun-1", 1);
8682 - yield* Queue.offer(
8683 - harness.sdkMessages,
8684 - makeSubagentTaskStartedFrame({
8685 - taskId,
8686 - toolUseId,
8687 - uuid: "00000000-0000-4000-8000-000000000901",
8688 - }),
8689 - );
8690 - yield* Queue.offer(harness.sdkMessages, result("00000000-0000-4000-8000-000000000902"));
8691 - yield* harness.awaitTerminal(1);
8692 - yield* Queue.offer(harness.sdkMessages, ended("00000000-0000-4000-8000-000000000903"));
8693 - yield* harness.awaitContinuation(1);
8694 - yield* Queue.offer(harness.sdkMessages, result("00000000-0000-4000-8000-000000000904"));
8160 yield* harness.runtime.startTurn(
8161 makeClaudeTestTurnInput({
8162 threadId: harness.threadId,
8163 providerThread: harness.providerThread,
8164 now,
8700 - attemptId: RunAttemptId.make("attempt-rerun-2"),
8701 - text: "Background task completed.",
8165 + attemptId: RunAttemptId.make("attempt-claude-live-idle-1"),
8166 + text: "Audit in the background.",
8167 attachments: [],
8703 - providerTurnOrdinal: 2,
8704 - messageCreatedBy: "agent",
8705 - messageCreationSource: "provider",
8168 }),
8169 );
8708 - yield* harness.awaitTerminal(2);
8709 -
8710 - yield* userTurn("attempt-rerun-3", 3);
8711 - yield* Queue.offer(
8712 - harness.sdkMessages,
8713 - claudeSdkFrame({
8714 - ...makeSubagentTaskStartedFrame({
8715 - taskId,
8716 - toolUseId,
8717 - uuid: "00000000-0000-4000-8000-000000000905",
8718 - }),
8719 - is_backgrounded: false,
8170 + for (const frame of [
8171 + makeSubagentTaskStartedFrame({
8172 + taskId: TASK_ID,
8173 + toolUseId: TOOL_USE_ID,
8174 + uuid: "00000000-0000-4000-8000-000000000951",
8175 }),
8721 - );
8722 - yield* Queue.offer(harness.sdkMessages, ended("00000000-0000-4000-8000-000000000906"));
8723 - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
8724 - yield* Queue.offer(harness.sdkMessages, result("00000000-0000-4000-8000-000000000907"));
8725 - yield* harness.awaitTerminal(3);
8726 -
8727 - yield* Queue.offer(harness.sdkMessages, wakeNotification);
8728 - yield* Queue.offer(harness.sdkMessages, wakeAssistant);
8729 - yield* harness.awaitContinuation(2);
8730 - assert.equal(
8731 - harness.continuationRequests[1]?.notification?.summary,
8732 - `Command "${WAKE_TASK_DESCRIPTION}" finished`,
8733 - );
8734 - }).pipe(
8735 - Effect.provide(
8736 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
8737 - ),
8738 - ),
8739 - ),
8740 - );
8741 -
8742 - it.effect("a turn that fails to start does not expire a queued wake's report", () =>
8743 - Effect.scoped(
8744 - Effect.gen(function* () {
8745 - const harness = yield* makeWakeHarness;
8746 - const now = yield* DateTime.now;
8747 - const userTurn = (
8748 - attempt: string,
8749 - providerTurnOrdinal: number,
8750 - attachments: ProviderAdapter.ProviderAdapterV2TurnInput["message"]["attachments"] = [],
8751 - ) =>
8752 - harness.runtime.startTurn(
8753 - makeClaudeTestTurnInput({
8754 - threadId: harness.threadId,
8755 - providerThread: harness.providerThread,
8756 - now,
8757 - attemptId: RunAttemptId.make(attempt),
8758 - text: "Go on.",
8759 - attachments,
8760 - providerTurnOrdinal,
8761 - }),
8762 - );
8763 -
8764 - yield* userTurn("attempt-failed-start-1", 1);
8765 - yield* harness.offerAndWait(wakeTaskStarted);
8766 - yield* harness.offerAndWait(turnOneResult);
8767 - yield* Queue.take(harness.terminalReceipts);
8768 - yield* harness.offerAndWait(wakeNotification);
8769 - assert.isFalse(yield* harness.hasPendingBackgroundWork);
8770 -
8771 - const missing = ChatImageAttachment.make({
8772 - type: "image",
8773 - id: ChatAttachmentId.make("thread-claude-wake-12345678-1234-1234-1234-123456789abc"),
8774 - name: "gone.png",
8775 - mimeType: "image/png",
8776 - sizeBytes: 4,
8777 - });
8778 - const failed = yield* userTurn("attempt-failed-start-2", 2, [missing]).pipe(Effect.flip);
8779 - assert.equal(
8780 - makeProviderFailure({ cause: failed }).message,
8781 - "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.",
8782 - );
8783 -
8784 - yield* userTurn("attempt-failed-start-3", 2);
8785 - yield* harness.offerAndWait(
8786 - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000911", result: "Answered." }),
8787 - );
8788 - yield* Queue.take(harness.terminalReceipts);
8789 -
8790 - yield* harness.offerAndWait(wakeAssistant);
8791 - const continuation = yield* Queue.take(harness.continuationReceipts);
8792 - assert.equal(
8793 - continuation.notification?.summary,
8794 - `Command "${WAKE_TASK_DESCRIPTION}" finished`,
8795 - );
8796 - }).pipe(
8797 - Effect.provide(
8798 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
8799 - ),
8800 - ),
8801 - ),
8802 - );
8803 -
8804 - it.effect("keeps a subagent a queued wake turn launches with its continuation", () =>
8805 - Effect.scoped(
8806 - Effect.gen(function* () {
8807 - const TASK_ID = "a-wake-launched-subagent";
8808 - const TOOL_USE_ID = "toolu_01WakeLaunchedAgent";
8809 - const harness = yield* makeWakeHarness;
8810 - const now = yield* DateTime.now;
8811 - const firstAttempt = RunAttemptId.make("attempt-claude-wake-subagent-1");
8812 - const userAttempt = RunAttemptId.make("attempt-claude-wake-subagent-2");
8813 - const continuationAttempt = RunAttemptId.make("attempt-claude-wake-subagent-3");
8814 - const runOf = (attemptId: RunAttemptId) => RunId.make(`run-${attemptId}`);
8815 - const stamp = (frame: SDKMessage, promptIndex: number) =>
8816 - claudeSdkFrame({
8817 - ...frame,
8818 - user_message_uuid: harness.promptUuid(promptIndex),
8819 - });
8820 -
8821 - yield* harness.runtime.startTurn(
8822 - makeClaudeTestTurnInput({
8823 - threadId: harness.threadId,
8824 - providerThread: harness.providerThread,
8825 - now,
8826 - attemptId: firstAttempt,
8827 - text: "Run the build in the background.",
8828 - attachments: [],
8176 + ...makeSubagentAssistantFrames({
8177 + parentToolUseId: TOOL_USE_ID,
8178 + uuid: "00000000-0000-4000-8000-000000000952",
8179 + bashToolUseId: STRADDLING_BASH,
8180 }),
8830 - );
8831 - yield* Queue.offer(harness.sdkMessages, stamp(wakeTaskStarted, 0));
8832 - yield* Queue.offer(
8833 - harness.sdkMessages,
8834 - stamp(
8835 - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000770", result: "STARTED" }),
8836 - 0,
8837 - ),
8838 - );
8181 + makeResultFrame({
8182 + uuid: "00000000-0000-4000-8000-000000000953",
8183 + result: "Auditing in the background.",
8184 + }),
8185 + ]) {
8186 + yield* Queue.offer(harness.sdkMessages, frame);
8187 + }
8188 yield* harness.awaitTerminal(1);
8189
8841 - yield* harness.runtime.startTurn(
8842 - makeClaudeTestTurnInput({
8843 - threadId: harness.threadId,
8844 - providerThread: harness.providerThread,
8845 - now,
8846 - attemptId: userAttempt,
8847 - text: "Reply with exactly: USER_REPLY",
8848 - attachments: [],
8849 - providerTurnOrdinal: 2,
8850 - }),
8851 - );
8852 - const wakeFrames = [
8853 - wakeNotification,
8854 - claudeSdkFrame({
8855 - type: "assistant",
8856 - message: {
8857 - model: "claude-sonnet-4-6",
8858 - id: "msg_wake_agent",
8859 - type: "message",
8860 - role: "assistant",
8861 - content: [
8862 - {
8863 - type: "tool_use",
8864 - id: TOOL_USE_ID,
8865 - name: "Agent",
8866 - input: { description: "Audit recent commits", prompt: "Audit them." },
8867 - },
8868 - ],
8869 - },
8870 - parent_tool_use_id: null,
8871 - uuid: "00000000-0000-4000-8000-000000000771",
8872 - session_id: WAKE_NATIVE_SESSION,
8873 - }),
8874 - makeSubagentTaskStartedFrame({
8875 - taskId: TASK_ID,
8876 - toolUseId: TOOL_USE_ID,
8877 - uuid: "00000000-0000-4000-8000-000000000772",
8190 + for (const frame of [
8191 + makeSubagentToolResultFrame({
8192 + parentToolUseId: TOOL_USE_ID,
8193 + uuid: "00000000-0000-4000-8000-000000000954",
8194 + toolUseId: STRADDLING_BASH,
8195 }),
8196 ...makeSubagentAssistantFrames({
8197 parentToolUseId: TOOL_USE_ID,
8881 - uuid: "00000000-0000-4000-8000-000000000773",
8882 - text: "AUDIT_DONE",
8883 - }),
8884 - makeSubagentNotificationFrame({
8885 - taskId: TASK_ID,
8886 - toolUseId: TOOL_USE_ID,
8887 - summary: "AUDIT_DONE",
8888 - uuid: "00000000-0000-4000-8000-000000000774",
8198 + uuid: "00000000-0000-4000-8000-000000000955",
8199 + text: "Still auditing.",
8200 + bashToolUseId: IDLE_BASH,
8201 }),
8202 claudeSdkFrame({
8891 - type: "user",
8892 - message: {
8893 - role: "user",
8894 - content: [{ type: "tool_result", tool_use_id: TOOL_USE_ID, content: "AUDIT_DONE" }],
8895 - },
8896 - parent_tool_use_id: null,
8897 - uuid: "00000000-0000-4000-8000-000000000775",
8203 + type: "system",
8204 + subtype: "task_progress",
8205 + task_id: TASK_ID,
8206 + description: "Reading the last commits",
8207 + uuid: "00000000-0000-4000-8000-000000000956",
8208 session_id: WAKE_NATIVE_SESSION,
8209 }),
8900 - wakeResult,
8901 - stamp(
8902 - makeAssistantTextFrame({
8903 - uuid: "00000000-0000-4000-8000-000000000776",
8904 - text: "USER_REPLY",
8905 - }),
8906 - 1,
8907 - ),
8908 - stamp(
8909 - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000777", result: "USER_REPLY" }),
8910 - 1,
8911 - ),
8912 - ];
8913 - for (const frame of wakeFrames) {
8210 + ]) {
8211 yield* Queue.offer(harness.sdkMessages, frame);
8212 }
8916 - yield* harness.awaitTerminal(2);
8917 -
8918 - yield* harness.runtime.startTurn(
8919 - makeClaudeTestTurnInput({
8920 - threadId: harness.threadId,
8921 - providerThread: harness.providerThread,
8922 - now,
8923 - attemptId: continuationAttempt,
8924 - text: "Background task completed.",
8925 - attachments: [],
8926 - providerTurnOrdinal: 3,
8927 - messageCreatedBy: "agent",
8928 - messageCreationSource: "provider",
8929 - }),
8930 - );
8931 - yield* harness.awaitTerminal(3);
8932 -
8933 - const subagentRuns = harness.events.flatMap((event) =>
8934 - event.type === "subagent.updated" && event.subagent.nativeTaskRef?.nativeId === TASK_ID
8935 - ? [event.subagent.runId]
8936 - : [],
8937 - );
8938 - assert.isNotEmpty(subagentRuns);
8939 - assert.isTrue(subagentRuns.every((runId) => runId === runOf(continuationAttempt)));
8940 - const finalSubagent = harness.events.findLast(
8941 - (event) =>
8942 - event.type === "subagent.updated" && event.subagent.nativeTaskRef?.nativeId === TASK_ID,
8213 + yield* harness.until(() => {
8214 + const event = latestToolItem(IDLE_BASH);
8215 + return event?.type === "turn_item.updated" && event.turnItem.status === "running";
8216 + });
8217 + yield* harness.until(() =>
8218 + harness.events.some(
8219 + (event) =>
8220 + event.type === "subagent.updated" &&
8221 + event.subagent.progress === "Reading the last commits",
8222 + ),
8223 );
8224 + const routing = subagentRouting(harness.events, [STRADDLING_BASH, IDLE_BASH]);
8225 + assert.deepEqual(routing.assistantTexts(routing.childThreadId), ["Still auditing."]);
8226 + const straddling = latestToolItem(STRADDLING_BASH);
8227 + const straddlingItem =
8228 + straddling?.type === "turn_item.updated" ? straddling.turnItem : undefined;
8229 + assert.equal(straddlingItem?.status, "completed");
8230 assert.equal(
8945 - finalSubagent?.type === "subagent.updated" && finalSubagent.subagent.status,
8946 - "completed",
8947 - );
8948 - const userRunItems = harness.events.flatMap((event) =>
8949 - event.type === "turn_item.updated" && event.turnItem.runId === runOf(userAttempt)
8950 - ? [event.turnItem.type]
8951 - : [],
8952 - );
8953 - assert.deepEqual([...new Set(userRunItems)], ["assistant_message"]);
8954 - }).pipe(
8955 - Effect.provide(
8956 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
8957 - ),
8958 - ),
8959 - ),
8960 - );
8961 -
8962 - it.effect("routes a subagent that starts while the root turn is idle", () =>
8963 - Effect.scoped(
8964 - Effect.gen(function* () {
8965 - const TASK_ID = "task-idle-subagent";
8966 - const TOOL_USE_ID = "toolu-idle-subagent";
8967 - const FINAL_REPORT = "Idle auditor done.";
8968 - const harness = yield* makeWakeHarness;
8969 - const now = yield* DateTime.now;
8970 - yield* harness.runtime.startTurn(
8971 - makeClaudeTestTurnInput({
8972 - threadId: harness.threadId,
8973 - providerThread: harness.providerThread,
8974 - now,
8975 - attemptId: RunAttemptId.make("attempt-claude-idle-subagent-1"),
8976 - text: "Wait for background work.",
8977 - attachments: [],
8978 - }),
8979 - );
8980 - yield* Queue.offer(
8981 - harness.sdkMessages,
8982 - makeResultFrame({
8983 - uuid: "00000000-0000-4000-8000-000000000331",
8984 - result: "Waiting in the background.",
8985 - }),
8231 + straddlingItem?.type === "command_execution" ? straddlingItem.input : undefined,
8232 + "git log -5",
8233 );
8987 - yield* harness.awaitTerminal(1);
8234 + assert.equal(harness.continuationRequests.length, 0);
8235
8989 - const idleFrames = [
8990 - makeSubagentTaskStartedFrame({
8991 - taskId: TASK_ID,
8992 - toolUseId: TOOL_USE_ID,
8993 - uuid: "00000000-0000-4000-8000-000000000332",
8994 - }),
8995 - ...makeSubagentAssistantFrames({
8996 - parentToolUseId: TOOL_USE_ID,
8997 - uuid: "00000000-0000-4000-8000-000000000333",
8998 - text: "Idle auditor working.",
8999 - bashToolUseId: "toolu-idle-bash",
9000 - }),
8236 + for (const frame of [
8237 makeSubagentToolResultFrame({
8238 parentToolUseId: TOOL_USE_ID,
9003 - uuid: "00000000-0000-4000-8000-000000000334",
9004 - toolUseId: "toolu-idle-bash",
9005 - }),
9006 - ...makeSubagentAssistantFrames({
9007 - parentToolUseId: TOOL_USE_ID,
9008 - uuid: "00000000-0000-4000-8000-000000000335",
9009 - text: FINAL_REPORT,
8239 + uuid: "00000000-0000-4000-8000-000000000957",
8240 + toolUseId: IDLE_BASH,
8241 }),
8242 makeSubagentNotificationFrame({
8243 taskId: TASK_ID,
8244 toolUseId: TOOL_USE_ID,
9014 - summary: FINAL_REPORT,
9015 - uuid: "00000000-0000-4000-8000-000000000336",
8245 + summary: "Still auditing.",
8246 + uuid: "00000000-0000-4000-8000-000000000958",
8247 }),
9017 - ];
9018 - for (const frame of idleFrames) {
8248 + ]) {
8249 yield* Queue.offer(harness.sdkMessages, frame);
8250 }
8251 yield* harness.awaitContinuation(1);
8252 yield* Queue.offer(
8253 harness.sdkMessages,
8254 makeResultFrame({
9025 - uuid: "00000000-0000-4000-8000-000000000337",
9026 - result: "The idle auditor finished.",
8255 + uuid: "00000000-0000-4000-8000-000000000959",
8256 + result: "The auditor finished.",
8257 }),
8258 );
8259 yield* harness.runtime.startTurn(
@@ -9031,7 +8261,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8261 threadId: harness.threadId,
8262 providerThread: harness.providerThread,
8263 now,
9034 - attemptId: RunAttemptId.make("attempt-claude-idle-subagent-2"),
8264 + attemptId: RunAttemptId.make("attempt-claude-live-idle-2"),
8265 text: "Background task completed.",
8266 attachments: [],
8267 providerTurnOrdinal: 2,
@@ -9041,179 +8271,23 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8271 );
8272 yield* harness.awaitTerminal(2);
8273
9044 - const routing = subagentRouting(harness.events, ["toolu-idle-bash"]);
9045 - assert.isDefined(routing.childThreadId);
9046 - assert.deepEqual(
9047 - [...(routing.toolThreadIds.get("toolu-idle-bash") ?? [])],
9048 - [routing.childThreadId],
9049 - );
9050 - assert.deepEqual(routing.assistantTexts(routing.childThreadId), [
9051 - "Idle auditor working.",
9052 - FINAL_REPORT,
9053 - ]);
9054 - assert.deepEqual(routing.assistantTexts(harness.threadId), [
9055 - "Waiting in the background.",
9056 - "The idle auditor finished.",
8274 + const finalRouting = subagentRouting(harness.events, [STRADDLING_BASH, IDLE_BASH]);
8275 + assert.deepEqual(finalRouting.assistantTexts(finalRouting.childThreadId), [
8276 + "Still auditing.",
8277 ]);
9058 - const finalSubagent = harness.events.findLast((event) => event.type === "subagent.updated");
9059 - assert.equal(
9060 - finalSubagent?.type === "subagent.updated" && finalSubagent.subagent.status,
9061 - "completed",
9062 - );
9063 - }).pipe(
9064 - Effect.provide(
9065 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
9066 - ),
9067 - ),
9068 - ),
9069 - );
9070 -
9071 - it.effect("streams a background subagent's work while the root turn is idle", () =>
9072 - Effect.scoped(
9073 - Effect.gen(function* () {
9074 - const TASK_ID = "task-live-idle";
9075 - const TOOL_USE_ID = "toolu-live-idle";
9076 - const STRADDLING_BASH = "toolu-live-straddling-bash";
9077 - const IDLE_BASH = "toolu-live-idle-bash";
9078 - const harness = yield* makeWakeHarness;
9079 - const now = yield* DateTime.now;
9080 - const latestToolItem = (nativeId: string) =>
9081 - harness.events.findLast(
9082 - (event) =>
9083 - event.type === "turn_item.updated" &&
9084 - event.turnItem.nativeItemRef?.nativeId === nativeId,
9085 - );
9086 - yield* harness.runtime.startTurn(
9087 - makeClaudeTestTurnInput({
9088 - threadId: harness.threadId,
9089 - providerThread: harness.providerThread,
9090 - now,
9091 - attemptId: RunAttemptId.make("attempt-claude-live-idle-1"),
9092 - text: "Audit in the background.",
9093 - attachments: [],
9094 - }),
9095 - );
9096 - for (const frame of [
9097 - makeSubagentTaskStartedFrame({
9098 - taskId: TASK_ID,
9099 - toolUseId: TOOL_USE_ID,
9100 - uuid: "00000000-0000-4000-8000-000000000951",
9101 - }),
9102 - ...makeSubagentAssistantFrames({
9103 - parentToolUseId: TOOL_USE_ID,
9104 - uuid: "00000000-0000-4000-8000-000000000952",
9105 - bashToolUseId: STRADDLING_BASH,
9106 - }),
9107 - makeResultFrame({
9108 - uuid: "00000000-0000-4000-8000-000000000953",
9109 - result: "Auditing in the background.",
9110 - }),
9111 - ]) {
9112 - yield* Queue.offer(harness.sdkMessages, frame);
9113 - }
9114 - yield* harness.awaitTerminal(1);
9115 -
9116 - for (const frame of [
9117 - makeSubagentToolResultFrame({
9118 - parentToolUseId: TOOL_USE_ID,
9119 - uuid: "00000000-0000-4000-8000-000000000954",
9120 - toolUseId: STRADDLING_BASH,
9121 - }),
9122 - ...makeSubagentAssistantFrames({
9123 - parentToolUseId: TOOL_USE_ID,
9124 - uuid: "00000000-0000-4000-8000-000000000955",
9125 - text: "Still auditing.",
9126 - bashToolUseId: IDLE_BASH,
9127 - }),
9128 - claudeSdkFrame({
9129 - type: "system",
9130 - subtype: "task_progress",
9131 - task_id: TASK_ID,
9132 - description: "Reading the last commits",
9133 - uuid: "00000000-0000-4000-8000-000000000956",
9134 - session_id: WAKE_NATIVE_SESSION,
9135 - }),
9136 - ]) {
9137 - yield* Queue.offer(harness.sdkMessages, frame);
9138 - }
9139 - yield* harness.until(() => {
9140 - const event = latestToolItem(IDLE_BASH);
9141 - return event?.type === "turn_item.updated" && event.turnItem.status === "running";
9142 - });
9143 - yield* harness.until(() =>
9144 - harness.events.some(
9145 - (event) =>
9146 - event.type === "subagent.updated" &&
9147 - event.subagent.progress === "Reading the last commits",
9148 - ),
9149 - );
9150 - const routing = subagentRouting(harness.events, [STRADDLING_BASH, IDLE_BASH]);
9151 - assert.deepEqual(routing.assistantTexts(routing.childThreadId), ["Still auditing."]);
9152 - const straddling = latestToolItem(STRADDLING_BASH);
9153 - const straddlingItem =
9154 - straddling?.type === "turn_item.updated" ? straddling.turnItem : undefined;
9155 - assert.equal(straddlingItem?.status, "completed");
9156 - assert.equal(
9157 - straddlingItem?.type === "command_execution" ? straddlingItem.input : undefined,
9158 - "git log -5",
9159 - );
9160 - assert.equal(harness.continuationRequests.length, 0);
9161 -
9162 - for (const frame of [
9163 - makeSubagentToolResultFrame({
9164 - parentToolUseId: TOOL_USE_ID,
9165 - uuid: "00000000-0000-4000-8000-000000000957",
9166 - toolUseId: IDLE_BASH,
9167 - }),
9168 - makeSubagentNotificationFrame({
9169 - taskId: TASK_ID,
9170 - toolUseId: TOOL_USE_ID,
9171 - summary: "Still auditing.",
9172 - uuid: "00000000-0000-4000-8000-000000000958",
9173 - }),
9174 - ]) {
9175 - yield* Queue.offer(harness.sdkMessages, frame);
9176 - }
9177 - yield* harness.awaitContinuation(1);
9178 - yield* Queue.offer(
9179 - harness.sdkMessages,
9180 - makeResultFrame({
9181 - uuid: "00000000-0000-4000-8000-000000000959",
9182 - result: "The auditor finished.",
9183 - }),
9184 - );
9185 - yield* harness.runtime.startTurn(
9186 - makeClaudeTestTurnInput({
9187 - threadId: harness.threadId,
9188 - providerThread: harness.providerThread,
9189 - now,
9190 - attemptId: RunAttemptId.make("attempt-claude-live-idle-2"),
9191 - text: "Background task completed.",
9192 - attachments: [],
9193 - providerTurnOrdinal: 2,
9194 - messageCreatedBy: "agent",
9195 - messageCreationSource: "provider",
9196 - }),
9197 - );
9198 - yield* harness.awaitTerminal(2);
9199 -
9200 - const finalRouting = subagentRouting(harness.events, [STRADDLING_BASH, IDLE_BASH]);
9201 - assert.deepEqual(finalRouting.assistantTexts(finalRouting.childThreadId), [
9202 - "Still auditing.",
9203 - ]);
9204 - for (const nativeId of [STRADDLING_BASH, IDLE_BASH]) {
9205 - assert.deepEqual(
9206 - [...(finalRouting.toolThreadIds.get(nativeId) ?? [])],
9207 - [finalRouting.childThreadId],
9208 - );
9209 - const statuses = harness.events.flatMap((event) =>
9210 - event.type === "turn_item.updated" &&
9211 - event.turnItem.nativeItemRef?.nativeId === nativeId
9212 - ? [`${event.turnItem.type}:${event.turnItem.status}`]
9213 - : [],
9214 - );
9215 - assert.deepEqual(statuses, ["command_execution:running", "command_execution:completed"]);
9216 - }
8278 + for (const nativeId of [STRADDLING_BASH, IDLE_BASH]) {
8279 + assert.deepEqual(
8280 + [...(finalRouting.toolThreadIds.get(nativeId) ?? [])],
8281 + [finalRouting.childThreadId],
8282 + );
8283 + const statuses = harness.events.flatMap((event) =>
8284 + event.type === "turn_item.updated" &&
8285 + event.turnItem.nativeItemRef?.nativeId === nativeId
8286 + ? [`${event.turnItem.type}:${event.turnItem.status}`]
8287 + : [],
8288 + );
8289 + assert.deepEqual(statuses, ["command_execution:running", "command_execution:completed"]);
8290 + }
8291 const finalSubagent = harness.events.findLast((event) => event.type === "subagent.updated");
8292 assert.equal(
8293 finalSubagent?.type === "subagent.updated" && finalSubagent.subagent.status,
@@ -10094,71 +9168,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9168 ),
9169 );
9170
10097 - it.effect("does not resolve a newer API retry when replaying a held subagent frame", () =>
10098 - Effect.scoped(
10099 - Effect.gen(function* () {
10100 - const TOOL_USE_ID = "toolu-retry-subagent";
10101 - const harness = yield* makeWakeHarness;
10102 - const now = yield* DateTime.now;
10103 - yield* harness.runtime.startTurn(
10104 - makeClaudeTestTurnInput({
10105 - threadId: harness.threadId,
10106 - providerThread: harness.providerThread,
10107 - now,
10108 - attemptId: RunAttemptId.make("attempt-claude-retry-subagent"),
10109 - text: "Run an auditor.",
10110 - attachments: [],
10111 - }),
10112 - );
10113 - const frames = [
10114 - ...makeSubagentAssistantFrames({
10115 - parentToolUseId: TOOL_USE_ID,
10116 - uuid: "00000000-0000-4000-8000-000000000351",
10117 - text: "Held before registration.",
10118 - }),
10119 - claudeSdkFrame({
10120 - type: "system",
10121 - subtype: "api_retry",
10122 - attempt: 2,
10123 - max_retries: 10,
10124 - retry_delay_ms: 1_500,
10125 - error_status: 529,
10126 - error: "overloaded",
10127 - uuid: "00000000-0000-4000-8000-000000000352",
10128 - session_id: WAKE_NATIVE_SESSION,
10129 - }),
10130 - makeSubagentTaskStartedFrame({
10131 - taskId: "task-retry-subagent",
10132 - toolUseId: TOOL_USE_ID,
10133 - uuid: "00000000-0000-4000-8000-000000000353",
10134 - }),
10135 - ];
10136 - for (const frame of frames) {
10137 - yield* Queue.offer(harness.sdkMessages, frame);
10138 - }
10139 - const childTexts = () => {
10140 - const routing = subagentRouting(harness.events, []);
10141 - return routing.childThreadId === undefined
10142 - ? []
10143 - : routing.assistantTexts(routing.childThreadId);
10144 - };
10145 - yield* harness.until(() => childTexts().length === 1);
10146 - const retryStatuses = harness.events.flatMap((event) =>
10147 - event.type === "turn_item.updated" &&
10148 - event.turnItem.type === "error" &&
10149 - event.turnItem.retry !== undefined
10150 - ? [event.turnItem.status]
10151 - : [],
10152 - );
10153 - assert.deepEqual(retryStatuses, ["running"]);
10154 - }).pipe(
10155 - Effect.provide(
10156 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
10157 - ),
10158 - ),
10159 - ),
10160 - );
10161 -
9171 it.effect("holds subagent frames that precede task_started and shows its result once", () =>
9172 Effect.scoped(
9173 Effect.gen(function* () {
@@ -11696,253 +10705,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
10705 ),
10706 );
10707
11699 - it.effect(
11700 - "does not opaque-misclassify a buffered subagent notification across model/policy query replacement",
11701 - () =>
11702 - Effect.scoped(
11703 - Effect.gen(function* () {
11704 - const changes = yield* makeChangeSignal;
11705 - const SUBAGENT_TASK_ID = "task-buffer-replace-subagent";
11706 - const SUBAGENT_TOOL_USE_ID = "toolu-buffer-replace-subagent";
11707 - const SUBAGENT_SUMMARY = "SUB_BUFFER_REPLACE_DONE";
11708 - const subagentTaskStarted = claudeSdkFrame({
11709 - type: "system",
11710 - subtype: "task_started",
11711 - task_id: SUBAGENT_TASK_ID,
11712 - tool_use_id: SUBAGENT_TOOL_USE_ID,
11713 - description: "Background research",
11714 - subagent_type: "general-purpose",
11715 - task_type: "local_agent",
11716 - prompt: "Research then return SUB_BUFFER_REPLACE_DONE.",
11717 - uuid: "00000000-0000-4000-8000-000000000801",
11718 - session_id: WAKE_NATIVE_SESSION,
11719 - });
11720 - const subagentNotification = claudeSdkFrame({
11721 - type: "system",
11722 - subtype: "task_notification",
11723 - task_id: SUBAGENT_TASK_ID,
11724 - tool_use_id: SUBAGENT_TOOL_USE_ID,
11725 - status: "completed",
11726 - output_file: "/tmp/task-buffer-replace-subagent.output",
11727 - summary: SUBAGENT_SUMMARY,
11728 - uuid: "00000000-0000-4000-8000-000000000802",
11729 - session_id: WAKE_NATIVE_SESSION,
11730 - });
11731 - const subagentAsyncAck = claudeSdkFrame({
11732 - type: "user",
11733 - message: {
11734 - role: "user",
11735 - content: [
11736 - {
11737 - type: "tool_result",
11738 - tool_use_id: SUBAGENT_TOOL_USE_ID,
11739 - content: [{ type: "text", text: "Async agent launched successfully." }],
11740 - },
11741 - ],
11742 - },
11743 - parent_tool_use_id: null,
11744 - uuid: "00000000-0000-4000-8000-000000000803",
11745 - session_id: WAKE_NATIVE_SESSION,
11746 - tool_use_result: {
11747 - isAsync: true,
11748 - status: "async_launched",
11749 - agentId: SUBAGENT_TASK_ID,
11750 - prompt: "Research then return SUB_BUFFER_REPLACE_DONE.",
11751 - },
11752 - });
11753 -
11754 - const fileSystem = yield* FileSystem.FileSystem;
11755 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
11756 - const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
11757 - prefix: "t3-claude-v2-subagent-buffer-replace-",
11758 - });
11759 - const processQueues: Array<Queue.Queue<SDKMessage>> = [];
11760 - const events: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
11761 - const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
11762 - [];
11763 - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
11764 - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
11765 - settings: DEFAULT_CLAUDE_SETTINGS,
11766 - environment: {},
11767 - attachmentsDir,
11768 - fileSystem,
11769 - path: yield* Path.Path,
11770 - crypto: yield* Crypto.Crypto,
11771 - idAllocator,
11772 - continuationRequests: {
11773 - offer: (request) =>
11774 - Effect.sync(() => {
11775 - continuationRequests.push(request);
11776 - }).pipe(Effect.andThen(changes.notify)),
11777 - },
11778 - queryRunner: {
11779 - allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION),
11780 - open: () =>
11781 - Effect.gen(function* () {
11782 - const sdkMessages = yield* Queue.unbounded<SDKMessage>();
11783 - processQueues.push(sdkMessages);
11784 - return {
11785 - messages: Stream.fromQueue(sdkMessages),
11786 - offer: () => Effect.void,
11787 - setModel: () => Effect.void,
11788 - applyFlagSettings: () => Effect.void,
11789 - setPermissionMode: () => Effect.void,
11790 - backgroundTasks: () => Effect.succeed(false),
11791 - stopTask: () => Effect.void,
11792 - interrupt: Effect.void,
11793 - close: Queue.shutdown(sdkMessages),
11794 - };
11795 - }),
11796 - forkSession: () => Effect.die("unused forkSession"),
11797 - subagentLaunchToolUseId: () => Effect.succeed(null),
11798 - assertComplete: Effect.void,
11799 - },
11800 - });
11801 - const threadId = ThreadId.make("thread-claude-subagent-buffer-replace");
11802 - const runtime = yield* adapter.openSession({
11803 - threadId,
11804 - providerSessionId: ProviderSessionId.make(
11805 - "provider-session-claude-subagent-buffer-replace",
11806 - ),
11807 - modelSelection: CLAUDE_TEST_MODEL_SELECTION,
11808 - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
11809 - });
11810 - const providerThread = yield* runtime.ensureThread({
11811 - threadId,
11812 - modelSelection: CLAUDE_TEST_MODEL_SELECTION,
11813 - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
11814 - });
11815 - yield* runtime.events.pipe(
11816 - Stream.runForEach((event) =>
11817 - Effect.sync(() => {
11818 - events.push(event);
11819 - }).pipe(Effect.andThen(changes.notify)),
11820 - ),
11821 - Effect.forkScoped,
11822 - );
11823 - if (runtime.hasPendingBackgroundWork === undefined) {
11824 - return yield* Effect.die(
11825 - "Claude adapter runtime must expose hasPendingBackgroundWork.",
11826 - );
11827 - }
11828 - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
11829 - const subagentEvents = () =>
11830 - events.filter(
11831 - (
11832 - event,
11833 - ): event is Extract<
11834 - ProviderAdapter.ProviderAdapterV2Event,
11835 - { type: "subagent.updated" }
11836 - > => event.type === "subagent.updated",
11837 - );
11838 - const now = yield* DateTime.now;
11839 -
11840 - yield* runtime.startTurn(
11841 - makeClaudeTestTurnInput({
11842 - threadId,
11843 - providerThread,
11844 - now,
11845 - attemptId: RunAttemptId.make("attempt-claude-subagent-buffer-replace-a"),
11846 - text: "Spawn a background subagent and stop.",
11847 - attachments: [],
11848 - }),
11849 - );
11850 - assert.equal(processQueues.length, 1);
11851 - const firstProcess = processQueues[0]!;
11852 - yield* Queue.offer(firstProcess, subagentTaskStarted);
11853 - yield* changes.until(() => subagentEvents().length >= 1);
11854 - assert.equal(subagentEvents()[0]?.subagent.status, "running");
11855 - yield* Queue.offer(firstProcess, subagentAsyncAck);
11856 - yield* Queue.offer(
11857 - firstProcess,
11858 - makeResultFrame({
11859 - uuid: "00000000-0000-4000-8000-000000000804",
11860 - result: "Spawned the subagent in the background.",
11861 - }),
11862 - );
11863 - yield* changes.until(() => events.some((event) => event.type === "turn.terminal"));
11864 - assert.isTrue(yield* hasPendingBackgroundWork);
11865 -
11866 - yield* Queue.offer(firstProcess, subagentNotification);
11867 - yield* changes.until(() => continuationRequests.length === 1);
11868 - assert.equal(continuationRequests[0]?.detail, SUBAGENT_SUMMARY);
11869 -
11870 - const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION;
11871 - yield* runtime.startTurn(
11872 - makeClaudeTestTurnInput({
11873 - threadId,
11874 - providerThread: { ...providerThread, status: "active" },
11875 - now,
11876 - attemptId: RunAttemptId.make("attempt-claude-subagent-buffer-replace-user"),
11877 - text: "Switch model while the subagent completes.",
11878 - attachments: [],
11879 - providerTurnOrdinal: 2,
11880 - modelSelection: alternateModel,
11881 - }),
11882 - );
11883 - assert.equal(processQueues.length, 2);
11884 - const secondProcess = processQueues[1]!;
11885 - yield* Queue.offer(
11886 - secondProcess,
11887 - makeResultFrame({
11888 - uuid: "00000000-0000-4000-8000-000000000805",
11889 - result: "User turn finished after model switch.",
11890 - }),
11891 - );
11892 - yield* changes.until(
11893 - () => events.filter((event) => event.type === "turn.terminal").length === 2,
11894 - );
11895 - assert.isFalse(yield* hasPendingBackgroundWork);
11896 - assert.equal(subagentEvents().at(-1)?.subagent.status, "completed");
11897 - assert.lengthOf(continuationRequests, 1);
11898 -
11899 - yield* Queue.offer(
11900 - secondProcess,
11901 - makeResultFrame({
11902 - uuid: "00000000-0000-4000-8000-000000000806",
11903 - result: "The subagent finished with SUB_BUFFER_REPLACE_DONE.",
11904 - }),
11905 - );
11906 - yield* runtime.startTurn(
11907 - makeClaudeTestTurnInput({
11908 - threadId,
11909 - providerThread: { ...providerThread, status: "active" },
11910 - now,
11911 - attemptId: RunAttemptId.make("attempt-claude-subagent-buffer-replace-cont"),
11912 - text: "Background task completed.",
11913 - attachments: [],
11914 - providerTurnOrdinal: 3,
11915 - modelSelection: alternateModel,
11916 - messageCreatedBy: "agent",
11917 - messageCreationSource: "provider",
11918 - }),
11919 - );
11920 - yield* changes.until(
11921 - () => events.filter((event) => event.type === "turn.terminal").length === 3,
11922 - );
11923 -
11924 - const finalSubagent = subagentEvents().at(-1)?.subagent;
11925 - assert.equal(finalSubagent?.status, "completed");
11926 - assert.equal(finalSubagent?.result, SUBAGENT_SUMMARY);
11927 - assert.equal(finalSubagent?.runId, subagentEvents()[0]?.subagent.runId);
11928 - const subagentNodeEvents = events.filter(
11929 - (
11930 - event,
11931 - ): event is Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "node.updated" }> =>
11932 - event.type === "node.updated" &&
11933 - event.node.kind === "subagent" &&
11934 - event.node.nativeItemRef?.nativeId === SUBAGENT_TASK_ID,
11935 - );
11936 - assert.equal(subagentNodeEvents.at(-1)?.node.status, "completed");
11937 - assert.isFalse(yield* hasPendingBackgroundWork);
11938 - }).pipe(
11939 - Effect.provide(
11940 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
11941 - ),
11942 - ),
11943 - ),
11944 - );
11945 -
10708 it.effect("refuses a thinking change that would kill a running background subagent", () =>
10709 Effect.scoped(
10710 Effect.gen(function* () {
@@ -12109,6 +10871,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
10871 ),
10872 );
10873
10874 + // regression: #20413 an unreadable append file must not tear down the running process
10875 it.effect("keeps the live process when its replacement cannot read the append file", () =>
10876 Effect.scoped(
10877 Effect.gen(function* () {
@@ -12368,228 +11131,27 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11131 ),
11132 );
11133
12371 - it.effect(
12372 - "clears buffered wake and continuation state when same-native-thread replacement open fails",
12373 - () =>
12374 - Effect.scoped(
12375 - Effect.gen(function* () {
12376 - const changes = yield* makeChangeSignal;
12377 - const fileSystem = yield* FileSystem.FileSystem;
12378 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
12379 - const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
12380 - prefix: "t3-claude-v2-replace-open-fail-wake-",
12381 - });
12382 - let openCount = 0;
12383 - const processQueues: Array<Queue.Queue<SDKMessage>> = [];
12384 - const events: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
12385 - const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
12386 - [];
12387 - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
12388 - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
12389 - settings: DEFAULT_CLAUDE_SETTINGS,
12390 - environment: {},
12391 - attachmentsDir,
12392 - fileSystem,
12393 - path: yield* Path.Path,
12394 - crypto: yield* Crypto.Crypto,
12395 - idAllocator,
12396 - continuationRequests: {
12397 - offer: (request) =>
12398 - Effect.sync(() => {
12399 - continuationRequests.push(request);
12400 - }).pipe(Effect.andThen(changes.notify)),
12401 - },
12402 - queryRunner: {
12403 - allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION),
12404 - open: () => {
12405 - openCount += 1;
12406 - if (openCount === 2) {
12407 - return Effect.fail(
12408 - new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
12409 - method: "open",
12410 - cause: "forced replacement open failure",
12411 - }),
12412 - );
12413 - }
12414 - return Effect.gen(function* () {
12415 - const sdkMessages = yield* Queue.unbounded<SDKMessage>();
12416 - processQueues.push(sdkMessages);
12417 - return {
12418 - messages: Stream.fromQueue(sdkMessages),
12419 - offer: () => Effect.void,
12420 - setModel: () => Effect.void,
12421 - applyFlagSettings: () => Effect.void,
12422 - setPermissionMode: () => Effect.void,
12423 - backgroundTasks: () => Effect.succeed(false),
12424 - stopTask: () => Effect.void,
12425 - interrupt: Effect.void,
12426 - close: Queue.shutdown(sdkMessages),
12427 - };
12428 - });
12429 - },
12430 - forkSession: () => Effect.die("unused forkSession"),
12431 - subagentLaunchToolUseId: () => Effect.succeed(null),
12432 - assertComplete: Effect.void,
12433 - },
12434 - });
12435 - const threadId = ThreadId.make("thread-claude-replace-open-fail-wake");
12436 - const runtime = yield* adapter.openSession({
12437 - threadId,
12438 - providerSessionId: ProviderSessionId.make(
12439 - "provider-session-claude-replace-open-fail-wake",
12440 - ),
12441 - modelSelection: CLAUDE_TEST_MODEL_SELECTION,
12442 - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
12443 - });
12444 - const providerThread = yield* runtime.ensureThread({
12445 - threadId,
12446 - modelSelection: CLAUDE_TEST_MODEL_SELECTION,
12447 - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
12448 - });
12449 - yield* runtime.events.pipe(
12450 - Stream.runForEach((event) =>
12451 - Effect.sync(() => {
12452 - events.push(event);
12453 - }).pipe(Effect.andThen(changes.notify)),
12454 - ),
12455 - Effect.forkScoped,
12456 - );
12457 - if (runtime.hasPendingBackgroundWork === undefined) {
12458 - return yield* Effect.die(
12459 - "Claude adapter runtime must expose hasPendingBackgroundWork.",
12460 - );
12461 - }
12462 - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
12463 - const now = yield* DateTime.now;
12464 -
12465 - yield* runtime.startTurn(
12466 - makeClaudeTestTurnInput({
12467 - threadId,
12468 - providerThread,
12469 - now,
12470 - attemptId: RunAttemptId.make("attempt-claude-replace-open-fail-wake-a"),
12471 - text: "Run the build in the background.",
12472 - attachments: [],
12473 - }),
12474 - );
12475 - yield* Queue.offer(processQueues[0]!, wakeTaskStarted);
12476 - yield* Queue.offer(processQueues[0]!, turnOneResult);
12477 - yield* changes.until(
12478 - () => events.filter((event) => event.type === "turn.terminal").length === 1,
12479 - );
12480 - yield* Queue.offer(processQueues[0]!, wakeNotification);
12481 - yield* Queue.offer(processQueues[0]!, wakeAssistant);
12482 - yield* changes.until(() => continuationRequests.length === 1);
12483 - assert.isTrue(yield* hasPendingBackgroundWork);
12484 -
12485 - const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION;
12486 - const failedStart = yield* runtime
12487 - .startTurn(
12488 - makeClaudeTestTurnInput({
12489 - threadId,
12490 - providerThread: { ...providerThread, status: "active" },
12491 - now,
12492 - attemptId: RunAttemptId.make("attempt-claude-replace-open-fail-wake-b"),
12493 - text: "Replace process but fail open.",
12494 - attachments: [],
12495 - providerTurnOrdinal: 2,
12496 - modelSelection: alternateModel,
12497 - }),
12498 - )
12499 - .pipe(Effect.exit);
12500 - assert.isTrue(Exit.isFailure(failedStart));
12501 - assert.isFalse(yield* hasPendingBackgroundWork);
12502 -
12503 - yield* runtime.startTurn(
12504 - makeClaudeTestTurnInput({
12505 - threadId,
12506 - providerThread: { ...providerThread, status: "active" },
12507 - now,
12508 - attemptId: RunAttemptId.make("attempt-claude-replace-open-fail-wake-c"),
12509 - text: "Retry after the failed replacement.",
12510 - attachments: [],
12511 - providerTurnOrdinal: 2,
12512 - modelSelection: alternateModel,
12513 - }),
12514 - );
12515 - const retryProcess = processQueues[1]!;
12516 - const retryTaskId = "task-wake-build-after-retry";
12517 - yield* Queue.offer(
12518 - retryProcess,
12519 - claudeSdkFrame({
12520 - type: "system",
12521 - subtype: "task_started",
12522 - task_id: retryTaskId,
12523 - tool_use_id: "toolu-wake-build-after-retry",
12524 - description: "npm run build after retry",
12525 - is_backgrounded: true,
12526 - task_type: "local_bash",
12527 - uuid: "00000000-0000-4000-8000-000000000901",
12528 - session_id: WAKE_NATIVE_SESSION,
12529 - }),
12530 - );
12531 - yield* Queue.offer(
12532 - retryProcess,
12533 - makeResultFrame({
12534 - uuid: "00000000-0000-4000-8000-000000000902",
12535 - result: "Kicked off the retry build in the background.",
12536 - }),
12537 - );
12538 - yield* changes.until(
12539 - () => events.filter((event) => event.type === "turn.terminal").length === 2,
12540 - );
12541 - yield* Queue.offer(
12542 - retryProcess,
12543 - claudeSdkFrame({
12544 - type: "system",
12545 - subtype: "task_notification",
12546 - task_id: retryTaskId,
12547 - tool_use_id: "toolu-wake-build-after-retry",
12548 - status: "completed",
12549 - output_file: "/tmp/task-wake-build-after-retry.log",
12550 - summary: "Retry build completed successfully",
12551 - uuid: "00000000-0000-4000-8000-000000000903",
12552 - session_id: WAKE_NATIVE_SESSION,
12553 - }),
12554 - );
12555 - yield* Queue.offer(
12556 - retryProcess,
12557 - makeAssistantTextFrame({
12558 - uuid: "00000000-0000-4000-8000-000000000904",
12559 - text: "The retry build has finished.",
12560 - }),
12561 - );
12562 - yield* changes.until(() => continuationRequests.length === 2);
12563 - assert.equal(continuationRequests[1]?.detail, "Retry build completed successfully");
12564 - }).pipe(
12565 - Effect.provide(
12566 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
12567 - ),
12568 - ),
12569 - ),
12570 - );
12571 -
12572 - const WORKFLOW_TASK_ID = "task-workflow-run";
12573 - const WORKFLOW_TOOL_USE_ID = "toolu-workflow-run";
12574 - const makeWorkflowHarnessWithOptions = (
12575 - options?: Parameters<typeof makeWakeHarnessWithOptions>[0],
12576 - ) =>
12577 - Effect.gen(function* () {
12578 - const fileSystem = yield* FileSystem.FileSystem;
12579 - const configDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-wf-" });
12580 - const transcriptDir = NodePath.join(configDir, "projects", "workflow");
12581 - yield* fileSystem.makeDirectory(transcriptDir, { recursive: true });
12582 - yield* fileSystem.writeFileString(
12583 - NodePath.join(transcriptDir, "agent-a1.jsonl"),
12584 - `{"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`,
12585 - );
12586 - const harness = yield* makeWakeHarnessWithOptions({
12587 - ...options,
12588 - environment: { ...options?.environment, CLAUDE_CONFIG_DIR: configDir },
12589 - });
12590 - return { ...harness, transcriptDir };
12591 - });
12592 - const makeWorkflowHarness = makeWorkflowHarnessWithOptions();
11134 + const WORKFLOW_TASK_ID = "task-workflow-run";
11135 + const WORKFLOW_TOOL_USE_ID = "toolu-workflow-run";
11136 + const makeWorkflowHarnessWithOptions = (
11137 + options?: Parameters<typeof makeWakeHarnessWithOptions>[0],
11138 + ) =>
11139 + Effect.gen(function* () {
11140 + const fileSystem = yield* FileSystem.FileSystem;
11141 + const configDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-wf-" });
11142 + const transcriptDir = NodePath.join(configDir, "projects", "workflow");
11143 + yield* fileSystem.makeDirectory(transcriptDir, { recursive: true });
11144 + yield* fileSystem.writeFileString(
11145 + NodePath.join(transcriptDir, "agent-a1.jsonl"),
11146 + `{"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`,
11147 + );
11148 + const harness = yield* makeWakeHarnessWithOptions({
11149 + ...options,
11150 + environment: { ...options?.environment, CLAUDE_CONFIG_DIR: configDir },
11151 + });
11152 + return { ...harness, transcriptDir };
11153 + });
11154 + const makeWorkflowHarness = makeWorkflowHarnessWithOptions();
11155
11156 const workflowToolUse = claudeSdkFrame({
11157 type: "assistant",
@@ -12934,75 +11496,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11496 ),
11497 );
11498
12937 - it.effect("scopes workflow member artifacts to the provider thread", () =>
12938 - Effect.scoped(
12939 - Effect.gen(function* () {
12940 - const memberArtifacts: Array<Array<string>> = [];
12941 - const memberThreads: Array<ThreadId | null | undefined> = [];
12942 - for (const nativeSessionId of ["workflow-session-a", "workflow-session-b"]) {
12943 - const harness = yield* makeWorkflowHarnessWithOptions({ nativeSessionId });
12944 - yield* harness.runtime.startTurn(
12945 - makeClaudeTestTurnInput({
12946 - threadId: harness.threadId,
12947 - providerThread: harness.providerThread,
12948 - now: yield* DateTime.now,
12949 - attemptId: RunAttemptId.make(`attempt-${nativeSessionId}`),
12950 - text: "Run the workflow.",
12951 - attachments: [],
12952 - }),
12953 - );
12954 - for (const frame of [
12955 - workflowToolUse,
12956 - workflowTaskStarted,
12957 - workflowLaunchAck(harness.transcriptDir),
12958 - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001203", state: "done" }),
12959 - ]) {
12960 - yield* harness.offerAndWait(claudeSdkFrame({ ...frame, session_id: nativeSessionId }));
12961 - }
12962 - yield* Queue.offer(
12963 - harness.sdkMessages,
12964 - claudeSdkFrame({
12965 - ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001204", result: "Done." }),
12966 - session_id: nativeSessionId,
12967 - }),
12968 - );
12969 - yield* Queue.take(harness.terminalReceipts);
12970 - const member = workflowMemberEvents(harness.events, 1).at(-1)?.subagent;
12971 - assert.isDefined(member);
12972 - memberThreads.push(member?.childThreadId);
12973 - const ids = harness.events.flatMap<string>((event) => {
12974 - if (event.type === "subagent.updated" && event.subagent.id === member?.id)
12975 - return [event.subagent.id];
12976 - if (event.type === "node.updated" && event.node.threadId === member?.childThreadId)
12977 - return [event.node.id];
12978 - if (
12979 - event.type === "message.updated" &&
12980 - event.message.threadId === member?.childThreadId
12981 - )
12982 - return [event.message.id];
12983 - if (
12984 - event.type === "turn_item.updated" &&
12985 - event.turnItem.threadId === member?.childThreadId
12986 - )
12987 - return [event.turnItem.id];
12988 - return [];
12989 - });
12990 - assert.isAtLeast(new Set(ids).size, 6);
12991 - memberArtifacts.push(ids);
12992 - }
12993 - assert.notEqual(memberThreads[0], memberThreads[1]);
12994 - assert.deepEqual(
12995 - memberArtifacts[0]?.filter((id) => memberArtifacts[1]?.includes(id)),
12996 - [],
12997 - );
12998 - }).pipe(
12999 - Effect.provide(
13000 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
13001 - ),
13002 - ),
13003 - ),
13004 - );
13005 -
11499 it.effect("stops only a live workflow task and waits for its stopped notification", () =>
11500 Effect.scoped(
11501 Effect.gen(function* () {
@@ -13328,626 +11821,132 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11821 assert.deepEqual(excerpt.subagent.completedAt, completedAt);
11822 const finishedRoot = harness.events.findLast(
11823 (event) => event.type === "node.updated" && event.node.threadId === firstThreadId,
13331 - );
13332 - assert.deepEqual(
13333 - finishedRoot?.type === "node.updated" ? finishedRoot.node.completedAt : undefined,
13334 - completedAt,
13335 - );
13336 -
13337 - yield* harness.offerAndWait(
13338 - workflowNotification({ uuid: "00000000-0000-4000-8000-000000001008", status: "stopped" }),
13339 - );
13340 - yield* Queue.offer(
13341 - harness.sdkMessages,
13342 - makeResultFrame({
13343 - uuid: "00000000-0000-4000-8000-000000001006",
13344 - result: "Launched the workflow.",
13345 - }),
13346 - );
13347 - yield* Queue.take(harness.terminalReceipts);
13348 - const stopped = workflowMemberEvents(harness.events, 2).at(-1)?.subagent;
13349 - assert.equal(stopped?.status, "cancelled");
13350 - assert.isNull(stopped?.startedAt);
13351 - const stoppedRoot = harness.events.findLast(
13352 - (event) => event.type === "node.updated" && event.node.threadId === second?.childThreadId,
13353 - );
13354 - assert.equal(
13355 - stoppedRoot?.type === "node.updated" ? stoppedRoot.node.status : null,
13356 - "cancelled",
13357 - );
13358 - assert.isNull(
13359 - stoppedRoot?.type === "node.updated" ? stoppedRoot.node.startedAt : undefined,
13360 - );
13361 - }).pipe(
13362 - Effect.provide(
13363 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
13364 - ),
13365 - ),
13366 - ),
13367 - );
13368 -
13369 - it.effect("projects workflow member threads after resuming a restarted session", () =>
13370 - Effect.scoped(
13371 - Effect.gen(function* () {
13372 - const harness = yield* makeWorkflowHarnessWithOptions({
13373 - subagentLaunchToolUseId: WORKFLOW_TOOL_USE_ID,
13374 - });
13375 - yield* harness.runtime.startTurn(
13376 - makeClaudeTestTurnInput({
13377 - threadId: harness.threadId,
13378 - providerThread: harness.providerThread,
13379 - now: yield* DateTime.now,
13380 - attemptId: RunAttemptId.make("attempt-claude-workflow-resume"),
13381 - text: "Continue the workflow.",
13382 - attachments: [],
13383 - }),
13384 - );
13385 - yield* harness.offerAndWait(
13386 - claudeSdkFrame({
13387 - ...workflowToolUse,
13388 - message: {
13389 - model: "claude-sonnet-4-6",
13390 - content: [
13391 - { type: "tool_use", id: "toolu-resume-workflow", name: "SendMessage", input: {} },
13392 - ],
13393 - },
13394 - }),
13395 - );
13396 - yield* harness.offerAndWait(
13397 - claudeSdkFrame({
13398 - ...workflowTaskStarted,
13399 - tool_use_id: "toolu-resume-workflow",
13400 - prompt: "Continue the workflow.",
13401 - }),
13402 - );
13403 - yield* harness.offerAndWait(workflowLaunchAck(harness.transcriptDir));
13404 - yield* harness.offerAndWait(
13405 - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001040", state: "start" }),
13406 - );
13407 - yield* harness.offerAndWait(
13408 - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001041", result: "Resumed." }),
13409 - );
13410 - yield* Queue.take(harness.terminalReceipts);
13411 - const member = workflowMemberEvents(harness.events, 1).at(-1)?.subagent;
13412 - const coordinator = workflowCoordinatorEvents(harness.events).at(-1)?.subagent;
13413 - assert.isDefined(member);
13414 - assert.equal(member?.status, "running");
13415 - assert.isTrue(
13416 - harness.events.some(
13417 - (event) =>
13418 - event.type === "app_thread.created" && event.appThread.id === member?.childThreadId,
13419 - ),
13420 - );
13421 - assert.deepEqual(
13422 - threadMessages(harness.events, member?.childThreadId).map((event) => event.message.text),
13423 - ["Reply with exactly: A1", "A1 from the transcript"],
13424 - );
13425 - assert.isDefined(coordinator?.childThreadId);
13426 - const recoveredThreads = harness.events.filter(
13427 - (event) =>
13428 - event.type === "app_thread.created" &&
13429 - event.appThread.id === coordinator?.childThreadId,
13430 - );
13431 - assert.lengthOf(recoveredThreads, 1);
13432 - const recovered = recoveredThreads[0];
13433 - assert.equal(recovered?.type, "app_thread.created");
13434 - if (recovered?.type !== "app_thread.created") throw new Error("Expected recovered thread");
13435 - assert.isTrue(recovered.createOnly);
13436 - assert.deepEqual(recovered.appThread.lineage, {
13437 - parentThreadId: harness.threadId,
13438 - relationshipToParent: "subagent",
13439 - rootThreadId: harness.threadId,
13440 - });
13441 - assert.equal(recovered.appThread.createdBy, "agent");
13442 - assert.equal(recovered.appThread.creationSource, "provider");
13443 - assert.isBelow(
13444 - harness.events.indexOf(recovered),
13445 - harness.events.findIndex(
13446 - (event) =>
13447 - event.type === "subagent.updated" &&
13448 - event.subagent.childThreadId === coordinator?.childThreadId,
13449 - ),
13450 - );
13451 - }).pipe(
13452 - Effect.provide(
13453 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
13454 - ),
13455 - ),
13456 - ),
13457 - );
13458 -
13459 - it.effect("does not republish a workflow roster on progress-only frames", () =>
13460 - Effect.scoped(
13461 - Effect.gen(function* () {
13462 - const harness = yield* makeWorkflowHarness;
13463 - const now = yield* DateTime.now;
13464 - yield* harness.runtime.startTurn(
13465 - makeClaudeTestTurnInput({
13466 - threadId: harness.threadId,
13467 - providerThread: harness.providerThread,
13468 - now,
13469 - attemptId: RunAttemptId.make("attempt-claude-workflow-progress-only"),
13470 - text: "Run the alpha workflow.",
13471 - attachments: [],
13472 - }),
13473 - );
13474 - yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001120" });
13475 - const coordinatorCount = () => workflowCoordinatorEvents(harness.events).length;
13476 - const offerProgressOnly = (index: number) =>
13477 - Queue.offer(
13478 - harness.sdkMessages,
13479 - claudeSdkFrame({
13480 - type: "system",
13481 - subtype: "task_progress",
13482 - task_id: WORKFLOW_TASK_ID,
13483 - tool_use_id: WORKFLOW_TOOL_USE_ID,
13484 - description: "Member is working",
13485 - uuid: `00000000-0000-4000-8000-${String(1200 + index).padStart(12, "0")}`,
13486 - session_id: WAKE_NATIVE_SESSION,
13487 - }),
13488 - );
13489 -
13490 - const inTurnCount = coordinatorCount();
13491 - for (let index = 0; index < 5; index++) yield* offerProgressOnly(index);
13492 - yield* Queue.offer(
13493 - harness.sdkMessages,
13494 - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001121", state: "start" }),
13495 - );
13496 - yield* harness.until(() => coordinatorCount() > inTurnCount);
13497 - assert.equal(coordinatorCount(), inTurnCount + 1);
13498 -
13499 - yield* Queue.offer(
13500 - harness.sdkMessages,
13501 - makeResultFrame({
13502 - uuid: "00000000-0000-4000-8000-000000001122",
13503 - result: "Launched the workflow.",
13504 - }),
13505 - );
13506 - yield* Queue.take(harness.terminalReceipts);
13507 -
13508 - const betweenTurnCount = coordinatorCount();
13509 - for (let index = 5; index < 10; index++) yield* offerProgressOnly(index);
13510 - yield* Queue.offer(
13511 - harness.sdkMessages,
13512 - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001123", state: "done" }),
13513 - );
13514 - yield* harness.until(() => coordinatorCount() > betweenTurnCount);
13515 - assert.equal(coordinatorCount(), betweenTurnCount + 1);
13516 - }).pipe(
13517 - Effect.provide(
13518 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
13519 - ),
13520 - ),
13521 - ),
13522 - );
13523 -
13524 - it.effect("keeps resumed workflow tools open after stale interrupted cleanup", () =>
13525 - Effect.scoped(
13526 - Effect.gen(function* () {
13527 - const clock = yield* Clock.Clock;
13528 - const cleanupPaused = yield* Deferred.make<void>();
13529 - const releaseCleanup = yield* Deferred.make<void>();
13530 - let readsUntilPause = 0;
13531 - yield* Effect.gen(function* () {
13532 - const harness = yield* makeWorkflowHarnessWithOptions({
13533 - close: Queue.shutdown,
13534 - freshQueueOnReopen: true,
13535 - });
13536 - const oldAttempt = RunAttemptId.make("attempt-workflow-stale-cleanup-old");
13537 - const oldBash = "toolu-workflow-stale-cleanup-old-bash";
13538 - const newBash = "toolu-workflow-stale-cleanup-new-bash";
13539 - const resumeTool = "toolu-workflow-stale-cleanup-resume";
13540 - const toolUpdates = (nativeId: string) =>
13541 - harness.events.flatMap((event) =>
13542 - event.type === "turn_item.updated" &&
13543 - event.turnItem.type === "command_execution" &&
13544 - event.turnItem.nativeItemRef?.nativeId === nativeId
13545 - ? [event.turnItem]
13546 - : [],
13547 - );
13548 - yield* harness.runtime.startTurn(
13549 - makeClaudeTestTurnInput({
13550 - threadId: harness.threadId,
13551 - providerThread: harness.providerThread,
13552 - now: yield* DateTime.now,
13553 - attemptId: oldAttempt,
13554 - text: "Run the workflow.",
13555 - attachments: [],
13556 - }),
13557 - );
13558 - yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001150" });
13559 - for (const frame of makeSubagentAssistantFrames({
13560 - parentToolUseId: WORKFLOW_TOOL_USE_ID,
13561 - uuid: "00000000-0000-4000-8000-000000001151",
13562 - bashToolUseId: oldBash,
13563 - })) {
13564 - yield* harness.offerAndWait(frame);
13565 - }
13566 - yield* harness.until(() => toolUpdates(oldBash).length === 1);
13567 - readsUntilPause = 2;
13568 - const stop = yield* harness.runtime
13569 - .interruptTurn({
13570 - providerThread: harness.providerThread,
13571 - providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
13572 - driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
13573 - nativeTurnId: `turn:${oldAttempt}`,
13574 - }),
13575 - })
13576 - .pipe(Effect.forkScoped);
13577 - yield* Deferred.await(cleanupPaused);
13578 - yield* TestClock.adjust("10 seconds");
13579 - yield* Fiber.join(stop);
13580 - yield* Queue.take(harness.terminalReceipts);
13581 - const oldToolCount = toolUpdates(oldBash).length;
13582 - yield* harness.runtime.startTurn(
13583 - makeClaudeTestTurnInput({
13584 - threadId: harness.threadId,
13585 - providerThread: harness.providerThread,
13586 - now: yield* DateTime.now,
13587 - attemptId: RunAttemptId.make("attempt-workflow-stale-cleanup-new"),
13588 - text: "Resume the workflow.",
13589 - attachments: [],
13590 - providerTurnOrdinal: 2,
13591 - }),
13592 - );
13593 - const resumedQueue = harness.processQueues[1]!;
13594 - yield* Queue.offer(
13595 - resumedQueue,
13596 - claudeSdkFrame({
13597 - ...workflowTaskStarted,
13598 - tool_use_id: resumeTool,
13599 - prompt: "Resume the workflow.",
13600 - uuid: "00000000-0000-4000-8000-000000001152",
13601 - }),
13602 - );
13603 - for (const frame of makeSubagentAssistantFrames({
13604 - parentToolUseId: resumeTool,
13605 - uuid: "00000000-0000-4000-8000-000000001153",
13606 - bashToolUseId: newBash,
13607 - })) {
13608 - yield* Queue.offer(resumedQueue, frame);
13609 - }
13610 - yield* harness.until(() => toolUpdates(newBash).length === 1);
13611 - yield* Deferred.succeed(releaseCleanup, undefined);
13612 - yield* Queue.take(harness.terminalReceipts);
13613 - assert.lengthOf(toolUpdates(oldBash), oldToolCount);
13614 - assert.deepEqual(
13615 - toolUpdates(newBash).map((item) => item.status),
13616 - ["running"],
13617 - );
13618 - yield* Queue.offer(
13619 - resumedQueue,
13620 - makeSubagentToolResultFrame({
13621 - parentToolUseId: resumeTool,
13622 - uuid: "00000000-0000-4000-8000-000000001154",
13623 - toolUseId: newBash,
13624 - }),
13625 - );
13626 - yield* harness.until(() => toolUpdates(newBash).at(-1)?.status === "completed");
13627 - assert.equal(toolUpdates(newBash).at(-1)?.output, "ok");
13628 - }).pipe(
13629 - Effect.provideService(Clock.Clock, {
13630 - ...clock,
13631 - currentTimeMillis: Effect.gen(function* () {
13632 - if (readsUntilPause > 0 && --readsUntilPause === 0) {
13633 - yield* Deferred.succeed(cleanupPaused, undefined);
13634 - yield* Deferred.await(releaseCleanup);
13635 - }
13636 - return yield* clock.currentTimeMillis;
13637 - }),
13638 - }),
13639 - );
13640 - }).pipe(
13641 - Effect.provide(
13642 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
13643 - ),
13644 - ),
13645 - ),
13646 - );
13647 -
13648 - it.effect.each(["root result", "query close"] as const)(
13649 - "keeps a waiting continuation inactive until replay can handle %s",
13650 - (arrival) =>
13651 - Effect.scoped(
13652 - Effect.gen(function* () {
13653 - const digestStarted = yield* Deferred.make<void>();
13654 - const releaseDigest = yield* Deferred.make<void>();
13655 - const closeStarted = yield* Deferred.make<void>();
13656 - let pauseDigest = false;
13657 - yield* Effect.gen(function* () {
13658 - const harness = yield* makeWorkflowHarnessWithOptions({
13659 - freshQueueOnReopen: true,
13660 - close: (messages) =>
13661 - Deferred.succeed(closeStarted, undefined).pipe(
13662 - Effect.andThen(Queue.shutdown(messages)),
13663 - ),
13664 - });
13665 - const start = (attemptId: string, ordinal: number, continuation: boolean) =>
13666 - harness.runtime.startTurn(
13667 - makeClaudeTestTurnInput({
13668 - threadId: harness.threadId,
13669 - providerThread: harness.providerThread,
13670 - now: DateTime.makeUnsafe(0),
13671 - attemptId: RunAttemptId.make(attemptId),
13672 - providerTurnOrdinal: ordinal,
13673 - text: "Continue working.",
13674 - attachments: [],
13675 - ...(continuation
13676 - ? { messageCreatedBy: "agent", messageCreationSource: "provider" }
13677 - : {}),
13678 - }),
13679 - );
13680 - yield* start("attempt-workflow-waiting-launch", 1, false);
13681 - yield* launchWorkflow({
13682 - harness,
13683 - snapshotUuid: "00000000-0000-4000-8000-000000003200",
13684 - });
13685 - const fileSystem = yield* FileSystem.FileSystem;
13686 - const liveTranscriptDir = NodePath.join(harness.transcriptDir, "live");
13687 - yield* fileSystem.makeDirectory(liveTranscriptDir);
13688 - yield* fileSystem.writeFileString(
13689 - NodePath.join(liveTranscriptDir, "agent-a1.jsonl"),
13690 - '{"type":"assistant","uuid":"wf-line-2","message":{"role":"assistant","stop_reason":"end_turn","content":[{"type":"text","text":"Live member answer"}]}}\n',
13691 - );
13692 - const liveTaskId = "task-workflow-live-while-waiting";
13693 - const liveToolUseId = "toolu-workflow-live-while-waiting";
13694 - yield* harness.offerAndWait(
13695 - claudeSdkFrame({
13696 - type: "assistant",
13697 - message: {
13698 - model: "claude-sonnet-4-6",
13699 - content: [{ type: "tool_use", id: liveToolUseId, name: "Workflow", input: {} }],
13700 - },
13701 - parent_tool_use_id: null,
13702 - session_id: WAKE_NATIVE_SESSION,
13703 - uuid: "00000000-0000-4000-8000-000000003201",
13704 - }),
13705 - );
13706 - yield* harness.offerAndWait(
13707 - claudeSdkFrame({
13708 - ...workflowTaskStarted,
13709 - task_id: liveTaskId,
13710 - tool_use_id: liveToolUseId,
13711 - uuid: "00000000-0000-4000-8000-000000003202",
13712 - }),
13713 - );
13714 - yield* harness.offerAndWait(
13715 - claudeSdkFrame({
13716 - type: "user",
13717 - message: {
13718 - role: "user",
13719 - content: [
13720 - { type: "tool_result", tool_use_id: liveToolUseId, content: "Launched." },
13721 - ],
13722 - },
13723 - tool_use_result: {
13724 - taskType: "local_workflow",
13725 - runId: "wf_live_while_waiting",
13726 - transcriptDir: liveTranscriptDir,
13727 - },
13728 - parent_tool_use_id: null,
13729 - session_id: WAKE_NATIVE_SESSION,
13730 - uuid: "00000000-0000-4000-8000-000000003203",
13731 - }),
13732 - );
13733 - const liveProgress = (state: "start" | "done", uuid: string) =>
13734 - claudeSdkFrame({
13735 - ...workflowSnapshot({ state, uuid }),
13736 - task_id: liveTaskId,
13737 - tool_use_id: liveToolUseId,
13738 - });
13739 - yield* harness.offerAndWait(
13740 - liveProgress("start", "00000000-0000-4000-8000-000000003204"),
13741 - );
13742 - yield* harness.offerAndWait(
13743 - makeResultFrame({
13744 - uuid: "00000000-0000-4000-8000-000000003205",
13745 - result: "Launched both workflows.",
13746 - }),
13747 - );
13748 - yield* Queue.take(harness.terminalReceipts);
13749 - yield* harness.offerAndWait(
13750 - workflowNotification({
13751 - uuid: "00000000-0000-4000-8000-000000003206",
13752 - status: "completed",
13753 - }),
13754 - );
13755 - yield* Queue.take(harness.continuationReceipts);
13756 - yield* harness.offerAndWait(wakeTurnInit);
13757 - pauseDigest = true;
13758 - const progress = yield* harness
13759 - .offerAndWait(liveProgress("done", "00000000-0000-4000-8000-000000003207"))
13760 - .pipe(Effect.forkScoped);
13761 - yield* Deferred.await(digestStarted);
13762 - const replay = yield* start("attempt-workflow-waiting-replay", 2, true).pipe(
13763 - Effect.forkScoped({ startImmediately: true }),
13764 - );
13765 - if (arrival === "query close") {
13766 - const stop = yield* harness.runtime
13767 - .interruptTurn({
13768 - providerThread: harness.providerThread,
13769 - providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
13770 - driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
13771 - nativeTurnId: "turn:attempt-workflow-waiting-replay",
13772 - }),
13773 - requestRuntimeRestart: true,
13774 - })
13775 - .pipe(Effect.forkScoped);
13776 - yield* Deferred.await(closeStarted);
13777 - yield* Deferred.succeed(releaseDigest, undefined);
13778 - yield* Fiber.join(progress);
13779 - yield* Fiber.join(stop);
13780 - assert.isTrue(Exit.isFailure(yield* Fiber.await(replay)));
13781 - } else {
13782 - const offered = yield* Deferred.make<void>();
13783 - const result = yield* harness
13784 - .offerAndWait(wakeResult, offered)
13785 - .pipe(Effect.forkScoped);
13786 - yield* Deferred.await(offered);
13787 - yield* Deferred.succeed(releaseDigest, undefined);
13788 - yield* Fiber.join(progress);
13789 - yield* Fiber.join(replay);
13790 - yield* Fiber.join(result);
13791 - yield* Queue.take(harness.terminalReceipts);
13792 - assert.lengthOf(harness.continuationRequests, 1);
13793 - }
13794 - yield* start("attempt-workflow-waiting-next-user", 3, false);
13795 - }).pipe(
13796 - Effect.provideService(WorkflowAgentTranscriptReadObserver, () =>
13797 - Effect.gen(function* () {
13798 - if (pauseDigest) {
13799 - pauseDigest = false;
13800 - yield* Deferred.succeed(digestStarted, undefined);
13801 - yield* Deferred.await(releaseDigest);
13802 - }
13803 - }),
13804 - ),
13805 - );
13806 - }).pipe(
13807 - Effect.provide(
13808 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
13809 - ),
11824 + );
11825 + assert.deepEqual(
11826 + finishedRoot?.type === "node.updated" ? finishedRoot.node.completedAt : undefined,
11827 + completedAt,
11828 + );
11829 +
11830 + yield* harness.offerAndWait(
11831 + workflowNotification({ uuid: "00000000-0000-4000-8000-000000001008", status: "stopped" }),
11832 + );
11833 + yield* Queue.offer(
11834 + harness.sdkMessages,
11835 + makeResultFrame({
11836 + uuid: "00000000-0000-4000-8000-000000001006",
11837 + result: "Launched the workflow.",
11838 + }),
11839 + );
11840 + yield* Queue.take(harness.terminalReceipts);
11841 + const stopped = workflowMemberEvents(harness.events, 2).at(-1)?.subagent;
11842 + assert.equal(stopped?.status, "cancelled");
11843 + assert.isNull(stopped?.startedAt);
11844 + const stoppedRoot = harness.events.findLast(
11845 + (event) => event.type === "node.updated" && event.node.threadId === second?.childThreadId,
11846 + );
11847 + assert.equal(
11848 + stoppedRoot?.type === "node.updated" ? stoppedRoot.node.status : null,
11849 + "cancelled",
11850 + );
11851 + assert.isNull(
11852 + stoppedRoot?.type === "node.updated" ? stoppedRoot.node.startedAt : undefined,
11853 + );
11854 + }).pipe(
11855 + Effect.provide(
11856 + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
11857 ),
11858 ),
11859 + ),
11860 );
11861
13814 - it.effect.each(["registry", "transcript"] as const)(
13815 - "does not replay stale idle progress over a completed workflow after awaiting %s",
13816 - (boundary) =>
13817 - Effect.scoped(
13818 - Effect.gen(function* () {
13819 - const clock = yield* Clock.Clock;
13820 - const progressRead = yield* Deferred.make<void>();
13821 - const releaseProgress = yield* Deferred.make<void>();
13822 - let pauseNextRead = false;
13823 - yield* Effect.gen(function* () {
13824 - const harness = yield* makeWorkflowHarness;
13825 - yield* harness.runtime.startTurn(
13826 - makeClaudeTestTurnInput({
13827 - threadId: harness.threadId,
13828 - providerThread: harness.providerThread,
13829 - now: yield* DateTime.now,
13830 - attemptId: RunAttemptId.make("attempt-claude-idle-race-launch"),
13831 - text: "Run the workflow.",
13832 - attachments: [],
13833 - }),
13834 - );
13835 - yield* launchWorkflow({
13836 - harness,
13837 - snapshotUuid: "00000000-0000-4000-8000-000000001060",
13838 - });
13839 - yield* harness.offerAndWait(
13840 - makeResultFrame({
13841 - uuid: "00000000-0000-4000-8000-000000001061",
13842 - result: "Launched.",
13843 - }),
13844 - );
13845 - yield* Queue.take(harness.terminalReceipts);
13846 - yield* harness.offerAndWait(
13847 - workflowNotification({
13848 - uuid: "00000000-0000-4000-8000-000000001062",
13849 - status: "completed",
13850 - }),
13851 - );
13852 - if (boundary === "registry") {
13853 - yield* harness.offerAndWait(
13854 - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001063", result: "Done." }),
13855 - );
13856 - }
13857 - const continuationInput = makeClaudeTestTurnInput({
13858 - threadId: harness.threadId,
13859 - providerThread: harness.providerThread,
13860 - now: yield* DateTime.now,
13861 - attemptId: RunAttemptId.make("attempt-claude-idle-race-continuation"),
13862 - text: "Continue.",
13863 - attachments: [],
13864 - providerTurnOrdinal: 2,
13865 - messageCreatedBy: "agent",
13866 - messageCreationSource: "provider",
13867 - });
13868 - pauseNextRead = true;
13869 - const progress = yield* harness
13870 - .offerAndWait(
13871 - workflowSnapshot({
13872 - uuid: "00000000-0000-4000-8000-000000001064",
13873 - state: boundary === "transcript" ? "done" : "start",
13874 - secondState: "start",
13875 - }),
13876 - )
13877 - .pipe(Effect.forkScoped);
13878 - yield* Deferred.await(progressRead);
13879 - const continuation = yield* harness.runtime
13880 - .startTurn(continuationInput)
13881 - .pipe(Effect.forkScoped);
13882 - yield* Deferred.succeed(releaseProgress, undefined);
13883 - yield* Fiber.join(progress);
13884 - yield* Fiber.join(continuation);
13885 - if (boundary === "registry") {
13886 - yield* Queue.take(harness.terminalReceipts);
13887 - } else {
13888 - const lastMemberId = workflowMemberEvents(harness.events, 2)[0]?.subagent.id;
13889 - while (true) {
13890 - const event = yield* Queue.take(harness.subagentReceipts);
13891 - if (event.subagent.id === lastMemberId && event.subagent.status === "completed")
13892 - break;
13893 - }
13894 - }
13895 - if (boundary === "transcript") {
13896 - yield* harness.offerAndWait(
13897 - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001065", result: "Done." }),
13898 - );
13899 - yield* Queue.take(harness.terminalReceipts);
13900 - }
13901 - assert.isFalse(yield* harness.hasPendingBackgroundWork);
13902 - assert.equal(
13903 - workflowCoordinatorEvents(harness.events).at(-1)?.subagent.status,
13904 - "completed",
13905 - );
13906 - const member = workflowMemberEvents(harness.events, 2).at(-1)?.subagent;
13907 - assert.equal(member?.status, "completed");
13908 - const root = harness.events.findLast(
13909 - (event) =>
13910 - event.type === "node.updated" && event.node.threadId === member?.childThreadId,
13911 - );
13912 - assert.equal(root?.type === "node.updated" ? root.node.status : null, "completed");
13913 - const item = harness.events.findLast(
13914 - (event) =>
13915 - event.type === "turn_item.updated" &&
13916 - event.turnItem.type === "subagent" &&
13917 - event.turnItem.nativeItemRef?.nativeId === WORKFLOW_TASK_ID,
13918 - );
13919 - assert.equal(
13920 - item?.type === "turn_item.updated" ? item.turnItem.status : null,
13921 - "completed",
13922 - );
13923 - }).pipe(
13924 - Effect.provideService(Clock.Clock, {
13925 - ...clock,
13926 - currentTimeMillis: Effect.gen(function* () {
13927 - if (boundary === "registry" && pauseNextRead) {
13928 - pauseNextRead = false;
13929 - yield* Deferred.succeed(progressRead, undefined);
13930 - yield* Deferred.await(releaseProgress);
13931 - }
13932 - return yield* clock.currentTimeMillis;
13933 - }),
13934 - }),
13935 - Effect.provideService(WorkflowAgentTranscriptReadObserver, () =>
13936 - Effect.gen(function* () {
13937 - if (boundary === "transcript" && pauseNextRead) {
13938 - pauseNextRead = false;
13939 - yield* Deferred.succeed(progressRead, undefined);
13940 - yield* Deferred.await(releaseProgress);
13941 - }
13942 - }),
13943 - ),
13944 - );
13945 - }).pipe(
13946 - Effect.provide(
13947 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
11862 + it.effect("projects workflow member threads after resuming a restarted session", () =>
11863 + Effect.scoped(
11864 + Effect.gen(function* () {
11865 + const harness = yield* makeWorkflowHarnessWithOptions({
11866 + subagentLaunchToolUseId: WORKFLOW_TOOL_USE_ID,
11867 + });
11868 + yield* harness.runtime.startTurn(
11869 + makeClaudeTestTurnInput({
11870 + threadId: harness.threadId,
11871 + providerThread: harness.providerThread,
11872 + now: yield* DateTime.now,
11873 + attemptId: RunAttemptId.make("attempt-claude-workflow-resume"),
11874 + text: "Continue the workflow.",
11875 + attachments: [],
11876 + }),
11877 + );
11878 + yield* harness.offerAndWait(
11879 + claudeSdkFrame({
11880 + ...workflowToolUse,
11881 + message: {
11882 + model: "claude-sonnet-4-6",
11883 + content: [
11884 + { type: "tool_use", id: "toolu-resume-workflow", name: "SendMessage", input: {} },
11885 + ],
11886 + },
11887 + }),
11888 + );
11889 + yield* harness.offerAndWait(
11890 + claudeSdkFrame({
11891 + ...workflowTaskStarted,
11892 + tool_use_id: "toolu-resume-workflow",
11893 + prompt: "Continue the workflow.",
11894 + }),
11895 + );
11896 + yield* harness.offerAndWait(workflowLaunchAck(harness.transcriptDir));
11897 + yield* harness.offerAndWait(
11898 + workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001040", state: "start" }),
11899 + );
11900 + yield* harness.offerAndWait(
11901 + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001041", result: "Resumed." }),
11902 + );
11903 + yield* Queue.take(harness.terminalReceipts);
11904 + const member = workflowMemberEvents(harness.events, 1).at(-1)?.subagent;
11905 + const coordinator = workflowCoordinatorEvents(harness.events).at(-1)?.subagent;
11906 + assert.isDefined(member);
11907 + assert.equal(member?.status, "running");
11908 + assert.isTrue(
11909 + harness.events.some(
11910 + (event) =>
11911 + event.type === "app_thread.created" && event.appThread.id === member?.childThreadId,
11912 + ),
11913 + );
11914 + assert.deepEqual(
11915 + threadMessages(harness.events, member?.childThreadId).map((event) => event.message.text),
11916 + ["Reply with exactly: A1", "A1 from the transcript"],
11917 + );
11918 + assert.isDefined(coordinator?.childThreadId);
11919 + const recoveredThreads = harness.events.filter(
11920 + (event) =>
11921 + event.type === "app_thread.created" &&
11922 + event.appThread.id === coordinator?.childThreadId,
11923 + );
11924 + assert.lengthOf(recoveredThreads, 1);
11925 + const recovered = recoveredThreads[0];
11926 + assert.equal(recovered?.type, "app_thread.created");
11927 + if (recovered?.type !== "app_thread.created") throw new Error("Expected recovered thread");
11928 + assert.isTrue(recovered.createOnly);
11929 + assert.deepEqual(recovered.appThread.lineage, {
11930 + parentThreadId: harness.threadId,
11931 + relationshipToParent: "subagent",
11932 + rootThreadId: harness.threadId,
11933 + });
11934 + assert.equal(recovered.appThread.createdBy, "agent");
11935 + assert.equal(recovered.appThread.creationSource, "provider");
11936 + assert.isBelow(
11937 + harness.events.indexOf(recovered),
11938 + harness.events.findIndex(
11939 + (event) =>
11940 + event.type === "subagent.updated" &&
11941 + event.subagent.childThreadId === coordinator?.childThreadId,
11942 ),
11943 + );
11944 + }).pipe(
11945 + Effect.provide(
11946 + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
11947 ),
11948 ),
11949 + ),
11950 );
11951
11952 it.effect.each([
@@ -14404,68 +12403,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12403 ),
12404 );
12405
14407 - it.effect("reads a transcript that appears after a terminal workflow notification", () =>
14408 - Effect.scoped(
14409 - Effect.gen(function* () {
14410 - const harness = yield* makeWorkflowHarness;
14411 - const now = yield* DateTime.now;
14412 - yield* harness.runtime.startTurn(
14413 - makeClaudeTestTurnInput({
14414 - threadId: harness.threadId,
14415 - providerThread: harness.providerThread,
14416 - now,
14417 - attemptId: RunAttemptId.make("attempt-claude-workflow-late-terminal-answer"),
14418 - text: "Run the alpha workflow.",
14419 - attachments: [],
14420 - }),
14421 - );
14422 - yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001030" });
14423 - const secondThreadId = workflowMemberEvents(harness.events, 2)[0]?.subagent.childThreadId;
14424 - yield* Queue.offer(
14425 - harness.sdkMessages,
14426 - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001031", state: "done" }),
14427 - );
14428 - yield* harness.until(() => threadMessages(harness.events, secondThreadId).length === 2);
14429 - const notification = workflowNotification({
14430 - uuid: "00000000-0000-4000-8000-000000001032",
14431 - status: "completed",
14432 - });
14433 - yield* Queue.offer(harness.sdkMessages, notification);
14434 - yield* harness.until(() =>
14435 - harness.events.some(
14436 - (event) =>
14437 - event.type === "turn_item.updated" &&
14438 - event.turnItem.type === "subagent" &&
14439 - event.turnItem.nativeItemRef?.nativeId === WORKFLOW_TASK_ID &&
14440 - event.turnItem.status === "completed",
14441 - ),
14442 - );
14443 - NodeFS.writeFileSync(
14444 - NodePath.join(harness.transcriptDir, "agent-a2.jsonl"),
14445 - '{"type":"assistant","uuid":"wf-line-3","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_late","content":[{"type":"text","text":"A2 final answer"}]}}\n',
14446 - );
14447 - yield* Queue.offer(
14448 - harness.sdkMessages,
14449 - claudeSdkFrame({ ...notification, uuid: "00000000-0000-4000-8000-000000001033" }),
14450 - );
14451 - yield* harness.until(
14452 - () =>
14453 - threadMessages(harness.events, secondThreadId).at(-1)?.message.text ===
14454 - "A2 final answer",
14455 - );
14456 - yield* Queue.offer(
14457 - harness.sdkMessages,
14458 - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001034", result: "Done." }),
14459 - );
14460 - yield* Queue.take(harness.terminalReceipts);
14461 - }).pipe(
14462 - Effect.provide(
14463 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
14464 - ),
14465 - ),
14466 - ),
14467 - );
14468 -
12406 it.effect("answers settled workflow members from a transcript, or the snapshot excerpt", () =>
12407 Effect.scoped(
12408 Effect.gen(function* () {
@@ -15124,45 +13061,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13061 ),
13062 );
13063
15127 - it.effect("keeps a goal active when a hook stops the turn before the goal passes", () =>
15128 - Effect.gen(function* () {
15129 - const harness = yield* makeWakeHarness;
15130 - const condition = "the deploy succeeds";
15131 - yield* harness.runtime.startTurn(
15132 - makeClaudeTestTurnInput({
15133 - threadId: harness.threadId,
15134 - providerThread: harness.providerThread,
15135 - now: yield* DateTime.now,
15136 - attemptId: RunAttemptId.make("goal-hook-stop-attempt"),
15137 - text: `/goal ${condition}`,
15138 - attachments: [],
15139 - }),
15140 - );
15141 - for (const frame of [
15142 - syntheticFrame("goal-hook-set", `Goal set: ${condition}`),
15143 - makeAssistantTextFrame({ uuid: "goal-hook-work", text: "Deploying." }),
15144 - makeResultFrame({
15145 - uuid: "goal-hook-result",
15146 - result: "Deploying.",
15147 - terminalReason: "hook_stopped",
15148 - }),
15149 - ]) {
15150 - yield* Queue.offer(harness.sdkMessages, frame);
15151 - }
15152 - yield* Queue.take(harness.terminalReceipts);
15153 - assert.deepEqual(goalStatuses(harness.events).at(-1), {
15154 - objective: condition,
15155 - status: "active",
15156 - checks: 0,
15157 - });
15158 - }).pipe(
15159 - Effect.scoped,
15160 - Effect.provide(
15161 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
15162 - ),
15163 - ),
15164 - );
15165 -
13064 it.effect(
13065 "defers goal completion until an ambient subagent finishes and Claude checks again",
13066 () =>
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+14 -1240
@@ -29,8 +29,6 @@ import {
29 TurnItemId,
30 } from "@t3tools/contracts";
31 import { assert, describe, it } from "@effect/vitest";
32 -import * as HostProcess from "@t3tools/shared/HostProcess";
33 -import { SpawnExecutableResolution } from "@t3tools/shared/shell";
32 import * as CodexClient from "effect-codex-app-server/client";
33 import * as CodexReplay from "effect-codex-app-server/replay";
34 import type * as CodexSchema from "effect-codex-app-server/schema";
@@ -44,7 +42,6 @@ import { MCP_APP_OUTPUT_KEY, readMcpAppReference } from "@t3tools/shared/mcpApp"
42 import { resolveAttachmentPathById } from "../../attachmentStore.ts";
43 import * as Fiber from "effect/Fiber";
44 import * as Layer from "effect/Layer";
47 -import * as PlatformError from "effect/PlatformError";
45 import * as PubSub from "effect/PubSub";
46 import * as Queue from "effect/Queue";
47 import * as Ref from "effect/Ref";
@@ -66,7 +63,6 @@ import * as CodexAdapterV2 from "./CodexAdapterV2.ts";
63 import { makeReplayServerConfig, withCodexReplayChildMetadata } from "./CodexAdapterV2.testkit.ts";
64 import * as CodexAdapterV2Testkit from "./CodexAdapterV2.testkit.ts";
65
69 -const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
66 const replayTranscriptJson = Schema.fromJsonString(CodexReplay.CodexAppServerReplayTranscript);
67 const encodeReplayTranscriptJson = Schema.encodeEffect(replayTranscriptJson);
68 const decodeReplayTranscriptJson = Schema.decodeUnknownEffect(replayTranscriptJson);
@@ -135,77 +131,6 @@ describe("CodexAdapterV2 assistant message streaming", () => {
131 assert.equal((yield* Ref.get(updates)).length, 2);
132 }),
133 );
138 -
139 - it.effect("retains buffered text until completion updates are emitted", () =>
140 - Effect.gen(function* () {
141 - const updates = yield* Ref.make<ReadonlyArray<ProviderTextDeltaUpdate>>([]);
142 - const failNext = yield* Ref.make(true);
143 - const coalescer = yield* makeProviderTextDeltaCoalescer({
144 - flushIntervalMs: 50,
145 - emit: (update) =>
146 - Ref.getAndSet(failNext, false).pipe(
147 - Effect.flatMap((shouldFail) =>
148 - shouldFail
149 - ? Effect.die("projection unavailable")
150 - : Ref.update(updates, (current) => [...current, update]),
151 - ),
152 - ),
153 - });
154 -
155 - yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: "turn final" });
156 - const failedFlush = yield* coalescer.flushTurn("turn-1").pipe(Effect.exit);
157 - assert.equal(failedFlush._tag, "Failure");
158 - yield* coalescer.flushTurn("turn-1");
159 -
160 - yield* coalescer.append({ turnId: "turn-1", itemId: "message-2", delta: "item final" });
161 - yield* Ref.set(failNext, true);
162 - const failedComplete = yield* coalescer
163 - .complete({ turnId: "turn-1", itemId: "message-2" })
164 - .pipe(Effect.exit);
165 - assert.equal(failedComplete._tag, "Failure");
166 - const completedText = yield* coalescer.complete({
167 - turnId: "turn-1",
168 - itemId: "message-2",
169 - });
170 -
171 - assert.equal(completedText, "item final");
172 - assert.deepEqual(yield* Ref.get(updates), [
173 - { turnId: "turn-1", itemId: "message-1", text: "turn final", completed: true },
174 - { turnId: "turn-1", itemId: "message-2", text: "item final", completed: true },
175 - ]);
176 - }),
177 - );
178 -
179 - it.effect("treats explicit empty final text as authoritative over buffered deltas", () =>
180 - Effect.gen(function* () {
181 - const updates = yield* Ref.make<ReadonlyArray<ProviderTextDeltaUpdate>>([]);
182 - const coalescer = yield* makeProviderTextDeltaCoalescer({
183 - flushIntervalMs: 50,
184 - emit: (update) => Ref.update(updates, (current) => [...current, update]),
185 - });
186 -
187 - yield* coalescer.append({
188 - turnId: "turn-1",
189 - itemId: "message-1",
190 - delta: "stale buffered text",
191 - });
192 - const completedText = yield* coalescer.complete({
193 - turnId: "turn-1",
194 - itemId: "message-1",
195 - finalText: "",
196 - });
197 -
198 - assert.equal(completedText, "");
199 - assert.deepEqual(yield* Ref.get(updates), [
200 - {
201 - turnId: "turn-1",
202 - itemId: "message-1",
203 - text: "",
204 - completed: true,
205 - },
206 - ]);
207 - }),
208 - );
134 });
135
136 describe("CodexAdapterV2 runtime policy", () => {
@@ -248,31 +173,6 @@ describe("CodexAdapterV2 runtime policy", () => {
173 }),
174 );
175
251 - it.effect("preserves explicit Codex turn policy overrides", () =>
252 - Effect.gen(function* () {
253 - const params = yield* CodexAdapterV2.buildCodexTurnStartParams({
254 - nativeThreadId: "native-override",
255 - codexInput: [{ type: "text", text: "test" }],
256 - runtimePolicy: {
257 - runtimeMode: "full-access",
258 - interactionMode: "default",
259 - cwd: null,
260 - approvalPolicy: "on-request",
261 - sandboxPolicy: {
262 - type: "readOnly",
263 - },
264 - },
265 - modelSelection: {
266 - instanceId: ProviderInstanceId.make("codex"),
267 - model: "gpt-5.4",
268 - },
269 - });
270 -
271 - assert.equal(params.approvalPolicy, "on-request");
272 - assert.equal(params.sandboxPolicy?.type, "readOnly");
273 - }),
274 - );
275 -
176 it.effect("sends MCP app model context as untrusted Codex context", () =>
177 Effect.gen(function* () {
178 const policy = { runtimeMode: "full-access", interactionMode: "default", cwd: null } as const;
@@ -305,91 +205,6 @@ describe("CodexAdapterV2 runtime policy", () => {
205 );
206 });
207
308 -describe("CodexAdapterV2 process spawning", () => {
309 - it.effect("resolves Windows command shims through the shared spawn policy", () =>
310 - Effect.gen(function* () {
311 - const command = yield* CodexAdapterV2.makeCodexAppServerSpawnCommand({
312 - command: "codex",
313 - args: ["app-server", "argument with spaces"],
314 - cwd: "C:\\workspace",
315 - env: { CUSTOM: "1" },
316 - extendEnv: true,
317 - });
318 -
319 - assert.isTrue(ChildProcess.isStandardCommand(command));
320 - if (!ChildProcess.isStandardCommand(command)) {
321 - return;
322 - }
323 - assert.equal(
324 - command.command,
325 - '^"C:\\npm\\codex.cmd^" ^"app-server^" ^"argument^ with^ spaces^"',
326 - );
327 - assert.deepEqual(command.args, []);
328 - assert.equal(command.options.shell, true);
329 - assert.equal(command.options.cwd, "C:\\workspace");
330 - assert.deepEqual(command.options.env, { CUSTOM: "1" });
331 - assert.equal(command.options.extendEnv, true);
332 - }).pipe(
333 - Effect.provideService(HostProcess.Platform, "win32"),
334 - Effect.provideService(HostProcess.Environment, {
335 - PATH: "C:\\Windows\\System32",
336 - HOST_ONLY: "1",
337 - }),
338 - Effect.provideService(SpawnExecutableResolution, (_command, _platform, environment) => {
339 - assert.equal(environment.HOST_ONLY, "1");
340 - assert.equal(environment.CUSTOM, "1");
341 - return "C:\\npm\\codex.cmd";
342 - }),
343 - ),
344 - );
345 -
346 - it.effect("launches the app-server with the configured launch arguments", () =>
347 - Effect.gen(function* () {
348 - const spawnedArgs: Array<ReadonlyArray<string>> = [];
349 - const spawner = ChildProcessSpawner.make((command) => {
350 - if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args);
351 - return Effect.fail(
352 - PlatformError.systemError({ _tag: "NotFound", module: "ChildProcess", method: "spawn" }),
353 - );
354 - });
355 - const factory = yield* CodexAdapterV2.CodexAppServerClientFactory.pipe(
356 - Effect.provide(CodexAdapterV2.layerAppServerClientFactory),
357 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
358 - Effect.provideService(
359 - ProviderEventLoggers.ProviderEventLoggers,
360 - ProviderEventLoggers.NoOpProviderEventLoggers,
361 - ),
362 - );
363 - const open = (environment: NodeJS.ProcessEnv) =>
364 - factory
365 - .open({
366 - instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID,
367 - threadId: ThreadId.make("thread-launch-args"),
368 - providerSessionId: ProviderSessionId.make("provider-session-launch-args"),
369 - runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
370 - runtimeMode: "full-access",
371 - interactionMode: "default",
372 - cwd: "/workspace",
373 - }),
374 - settings: {
375 - ...DEFAULT_CODEX_SETTINGS,
376 - launchArgs: " --strict-config -c model_reasoning_summary=detailed ",
377 - },
378 - environment,
379 - })
380 - .pipe(Effect.scoped, Effect.exit);
381 -
382 - yield* open({});
383 - yield* open({ T3CODE_CODEX_LAUNCH_ARGS: " --enable env-feature " });
384 -
385 - assert.deepEqual(spawnedArgs, [
386 - ["app-server", "--strict-config", "-c", "model_reasoning_summary=detailed"],
387 - ["app-server", "--enable", "env-feature"],
388 - ]);
389 - }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
390 - );
391 -});
392 -
208 describe("CodexAdapterV2 native protocol logging", () => {
209 it.effect("logs decoded app-server frames once with credentials redacted", () =>
210 Effect.gen(function* () {
@@ -459,51 +274,6 @@ describe("CodexAdapterV2 native protocol logging", () => {
274 });
275 }),
276 );
462 -
463 - it.effect("retains redacted failures when large payloads are summarized", () =>
464 - Effect.gen(function* () {
465 - const writes: Array<unknown> = [];
466 - const protocolLogger = CodexAdapterV2.makeCodexAppServerProtocolLogger({
467 - nativeEventLogger: {
468 - filePath: "/tmp/events.log",
469 - write: (event) =>
470 - Effect.sync(() => {
471 - writes.push(event);
472 - }),
473 - close: () => Effect.void,
474 - },
475 - threadId: ThreadId.make("thread-1"),
476 - providerSessionId: ProviderSessionId.make("provider-session-1"),
477 - });
478 - assert.exists(protocolLogger);
479 - if (protocolLogger === undefined) return;
480 -
481 - yield* protocolLogger({
482 - direction: "incoming",
483 - stage: "decoded",
484 - payload: {
485 - method: "error",
486 - params: {
487 - threadId: "native-thread",
488 - turnId: "native-turn",
489 - error: {
490 - code: "unauthorized",
491 - message: '{"message":"Unauthorized","Authorization":"Bearer secret-token"}',
492 - },
493 - history: "x".repeat(128 * 1_024),
494 - },
495 - },
496 - });
497 -
498 - const serialized = encodeUnknownJson(writes);
499 - assert.equal(writes.length, 1);
500 - assert.isBelow(serialized.length, 2_048);
501 - assert.notInclude(serialized, "secret-token");
502 - assert.include(serialized, "[REDACTED]");
503 - assert.nestedPropertyVal(writes[0], "event.payload.params.error.code", "unauthorized");
504 - assert.nestedPropertyVal(writes[0], "event.payload.params.turnId", "native-turn");
505 - }),
506 - );
277 });
278
279 describe("CodexAdapterV2 rollback mapping", () => {
@@ -655,38 +425,6 @@ describe("CodexAdapterV2 fork boundary", () => {
425 assert.deepEqual(boundary, { lastTurnId: undefined, rollbackTurnCount: 1 });
426 }),
427 );
658 -
659 - it.effect("forks at head without a boundary when no provider turn is selected", () =>
660 - Effect.gen(function* () {
661 - const now = yield* DateTime.now;
662 -
663 - const boundary = yield* CodexAdapterV2.resolveCodexForkBoundary({
664 - sourceProviderThread: makeProviderThread(now),
665 - targetThreadId: ThreadId.make("thread-codex-fork-target"),
666 - });
667 -
668 - assert.deepEqual(boundary, { lastTurnId: undefined, rollbackTurnCount: 0 });
669 - }),
670 - );
671 -
672 - it.effect("fails with a typed error when the selected source turn is missing", () =>
673 - Effect.gen(function* () {
674 - const now = yield* DateTime.now;
675 - const firstTurn = makeProviderTurn("provider-turn-first", 1, "native-turn-first", now);
676 -
677 - const error = yield* Effect.flip(
678 - CodexAdapterV2.resolveCodexForkBoundary({
679 - sourceProviderThread: makeProviderThread(now),
680 - sourceProviderTurns: [firstTurn],
681 - providerTurnId: ProviderTurnId.make("provider-turn-missing"),
682 - targetThreadId: ThreadId.make("thread-codex-fork-target"),
683 - }),
684 - );
685 -
686 - assert.instanceOf(error, ProviderAdapter.ProviderAdapterForkThreadError);
687 - assert.include(String(error.cause), "provider-turn-missing");
688 - }),
689 - );
428 });
429
430 const DEFAULT_CODEX_SETTINGS = Schema.decodeSync(CodexSettings)({});
@@ -1042,6 +780,7 @@ describe("CodexAdapterV2 session initialize", () => {
780 ),
781 );
782
783 + // regression: #16260 one-shot initializers raced; a failed handshake must be retried
784 it.effect("retries initialize after a failed handshake", () =>
785 Effect.gen(function* () {
786 const preamble = replayPreamble("initialize-retry");
@@ -1424,6 +1163,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
1163 ),
1164 );
1165
1166 + // regression: #15839 launch-arg MCP servers survive the thread's t3-code server
1167 it.effect("replays historical and dotted MCP config while enforcing other thread config", () =>
1168 Effect.gen(function* () {
1169 const recordedServer = {
@@ -1490,47 +1230,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
1230 }).pipe(Effect.scoped),
1231 );
1232
1493 - it.effect("unsubscribes from the native thread when it is unloaded", () =>
1494 - Effect.gen(function* () {
1495 - const nativeThreadId = "unload-thread";
1496 - const preamble = codexReplayPreamble({
1497 - nativeThreadId,
1498 - nativeTurnId: "unused",
1499 - prompt: "unused",
1500 - });
1501 - const transcript = makeCodexReplayTranscript({
1502 - scenario: "unload-thread",
1503 - entries: [
1504 - ...preamble.slice(0, 5),
1505 - {
1506 - type: "expect_outbound",
1507 - label: "thread/unsubscribe",
1508 - frame: { id: 3, method: "thread/unsubscribe", params: { threadId: nativeThreadId } },
1509 - },
1510 - {
1511 - type: "emit_inbound",
1512 - label: "thread/unsubscribe",
1513 - frame: { id: 3, result: { status: "unsubscribed" } },
1514 - },
1515 - ],
1516 - });
1517 - const requests: Array<string> = [];
1518 - const harness = yield* makeCodexReplayHarness(
1519 - transcript,
1520 - () => Effect.void,
1521 - (method) => Effect.sync(() => requests.push(method)),
1522 - );
1523 - assert.isDefined(harness.runtime.unloadThread);
1524 - yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread });
1525 - assert.deepEqual(requests, ["initialize", "thread/start", "thread/unsubscribe"]);
1526 - }).pipe(
1527 - Effect.scoped,
1528 - Effect.provide(
1529 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
1530 - ),
1531 - ),
1532 - );
1533 -
1233 it.effect("waits for native start before interrupting an acknowledged queued turn", () =>
1234 Effect.gen(function* () {
1235 const nativeThreadId = "early-stop-thread";
@@ -1630,93 +1329,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
1329 ),
1330 );
1331
1633 - it.effect("settles Stop when a queued native turn fails before starting", () =>
1634 - Effect.gen(function* () {
1635 - const nativeThreadId = "early-stop-thread";
1636 - const nativeTurnId = "early-stop-turn";
1637 - const prompt = "Run a command.";
1638 - const preamble = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt });
1639 - const transcript = makeCodexReplayTranscript({
1640 - scenario: "early-stop-failed-before-native-start",
1641 - entries: [
1642 - ...preamble.slice(0, -2),
1643 - {
1644 - type: "emit_inbound",
1645 - label: "turn/start/queued",
1646 - frame: {
1647 - id: 3,
1648 - result: {
1649 - turn: {
1650 - ...makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }),
1651 - startedAt: null,
1652 - },
1653 - },
1654 - },
1655 - },
1656 - {
1657 - type: "emit_inbound",
1658 - label: "turn/failed",
1659 - afterMs: 1000,
1660 - frame: {
1661 - method: "turn/completed",
1662 - params: {
1663 - threadId: nativeThreadId,
1664 - turn: {
1665 - ...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }),
1666 - startedAt: null,
1667 - error: {
1668 - message: "Failed before native start",
1669 - codexErrorInfo: null,
1670 - additionalDetails: null,
1671 - },
1672 - },
1673 - },
1674 - },
1675 - },
1676 - ],
1677 - });
1678 - let interruptSent = false;
1679 - const harness = yield* makeCodexReplayHarness(
1680 - transcript,
1681 - () => Effect.void,
1682 - (method) =>
1683 - Effect.sync(() => {
1684 - if (method === "turn/interrupt") interruptSent = true;
1685 - }),
1686 - );
1687 - yield* harness.runtime.startTurn(
1688 - makeCodexTestTurnInput({
1689 - threadId: harness.threadId,
1690 - providerThread: harness.providerThread,
1691 - now: yield* DateTime.now,
1692 - attemptId: RunAttemptId.make("early-stop-attempt"),
1693 - text: prompt,
1694 - }),
1695 - );
1696 - const providerTurnId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
1697 - driver: CodexAdapterV2.CODEX_DRIVER_KIND,
1698 - nativeTurnId,
1699 - });
1700 - const interrupt = yield* harness.runtime
1701 - .interruptTurn({ providerThread: harness.providerThread, providerTurnId })
1702 - .pipe(Effect.forkScoped);
1703 - yield* TestClock.adjust("500 millis");
1704 - assert.isFalse(interruptSent, "Stop must not reach Codex before native turn/started");
1705 - yield* TestClock.adjust("500 millis");
1706 - yield* Fiber.join(interrupt);
1707 - yield* harness.firstTerminal;
1708 - assert.equal(harness.terminalEvents()[0]?.status, "failed");
1709 - assert.lengthOf(harness.terminalEvents(), 1);
1710 - assert.isFalse(interruptSent, "A terminal native turn must not receive turn/interrupt");
1711 - assert.isFalse(yield* harness.hasPendingBackgroundWork);
1712 - }).pipe(
1713 - Effect.scoped,
1714 - Effect.provide(
1715 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
1716 - ),
1717 - ),
1718 - );
1719 -
1332 const assistantMessages = (events: ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>) =>
1333 events.filter(
1334 (
@@ -2439,49 +2051,18 @@ describe("CodexAdapterV2 post-settle continuation", () => {
2051 ),
2052 );
2053
2054 + // regression: #15389 archived native Codex sessions resume via thread/unarchive
2055 it.effect.each(
2056 (
2057 [
2058 ["recovers archived-session errors", "session saved-thread is archived", 0, ""],
2446 - [
2447 - "recovers unarchive hints",
2448 - "Run `codex unarchive saved-thread` to unarchive it first.",
2449 - 0,
2450 - "",
2451 - ],
2059 ["preserves missing-thread errors", "thread not found", 3, "thread not found"],
2453 - ["preserves missing-rollout errors", "no rollout found", 3, "no rollout found"],
2454 - ["preserves authentication errors", "authentication failed", 3, "authentication failed"],
2455 - [
2456 - "preserves archived-workspace errors",
2457 - "workspace is archived",
2458 - 3,
2459 - "workspace is archived",
2460 - ],
2461 - [
2462 - "preserves unrelated archive-path errors",
2463 - "permission denied reading archived_sessions/saved-thread",
2464 - 3,
2465 - "permission denied reading archived_sessions/saved-thread",
2466 - ],
2060 [
2061 "propagates unarchive missing-thread errors",
2062 "session saved-thread is archived",
2063 4,
2064 "thread not found",
2065 ],
2473 - [
2474 - "propagates unarchive archived errors",
2475 - "session saved-thread is archived",
2476 - 4,
2477 - "session saved-thread is archived",
2478 - ],
2479 - [
2480 - "propagates retry missing-thread errors",
2481 - "session saved-thread is archived",
2482 - 5,
2483 - "thread not found",
2484 - ],
2066 [
2067 "does not retry archived errors twice",
2068 "session saved-thread is archived",
@@ -2750,109 +2331,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
2331 ),
2332 );
2333
2753 - it.effect("stamps Codex items with their own start time, not the turn's", () =>
2754 - Effect.scoped(
2755 - Effect.gen(function* () {
2756 - const scenario = "codex-item-start-times";
2757 - const nativeThreadId = `native-${scenario}-thread`;
2758 - const nativeTurnId = `native-${scenario}-turn`;
2759 - const commandLifecycle = (id: string, startedAtMs: number) =>
2760 - (["started", "completed"] as const).map((phase) => ({
2761 - type: "emit_inbound" as const,
2762 - label: `item/${phase}/${id}`,
2763 - frame: {
2764 - method: `item/${phase}`,
2765 - params: {
2766 - threadId: nativeThreadId,
2767 - turnId: nativeTurnId,
2768 - ...(phase === "started" ? { startedAtMs } : { completedAtMs: startedAtMs + 10 }),
2769 - item: {
2770 - type: "commandExecution",
2771 - id,
2772 - command: "pwd",
2773 - cwd: "/workspace",
2774 - processId: "42",
2775 - source: "unifiedExecStartup",
2776 - status: phase === "started" ? "inProgress" : "completed",
2777 - commandActions: [{ type: "unknown", command: "pwd" }],
2778 - aggregatedOutput: phase === "started" ? null : "/workspace\n",
2779 - exitCode: phase === "started" ? null : 0,
2780 - durationMs: phase === "started" ? null : 10,
2781 - },
2782 - },
2783 - },
2784 - }));
2785 - const transcript = makeCodexReplayTranscript({
2786 - scenario,
2787 - entries: [
2788 - ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Run two commands." }),
2789 - ...commandLifecycle("first-command", 1782622445000),
2790 - ...commandLifecycle("second-command", 1782622505000),
2791 - ...(["started", "completed"] as const).map((phase) => ({
2792 - type: "emit_inbound" as const,
2793 - label: `item/${phase}/compaction`,
2794 - frame: {
2795 - method: `item/${phase}`,
2796 - params: {
2797 - threadId: nativeThreadId,
2798 - turnId: nativeTurnId,
2799 - ...(phase === "started"
2800 - ? { startedAtMs: 1782622565000 }
2801 - : { completedAtMs: 1782622575000 }),
2802 - item: { type: "contextCompaction", id: "compaction" },
2803 - },
2804 - },
2805 - })),
2806 - {
2807 - type: "emit_inbound",
2808 - label: "turn/completed",
2809 - frame: {
2810 - method: "turn/completed",
2811 - params: {
2812 - threadId: nativeThreadId,
2813 - turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
2814 - },
2815 - },
2816 - },
2817 - ],
2818 - });
2819 - const harness = yield* makeCodexReplayHarness(transcript);
2820 - yield* harness.runtime.startTurn(
2821 - makeCodexTestTurnInput({
2822 - threadId: harness.threadId,
2823 - providerThread: harness.providerThread,
2824 - now: yield* DateTime.now,
2825 - attemptId: RunAttemptId.make("attempt-codex-item-start-times"),
2826 - text: "Run two commands.",
2827 - }),
2828 - );
2829 - yield* harness.awaitTerminal(1);
2830 -
2831 - const startedAtByItem = harness.events.flatMap((event) =>
2832 - event.type === "turn_item.updated" &&
2833 - (event.turnItem.type === "command_execution" || event.turnItem.type === "compaction")
2834 - ? [[event.turnItem.nativeItemRef?.nativeId, event.turnItem.startedAt] as const]
2835 - : [],
2836 - );
2837 - assert.deepEqual(
2838 - startedAtByItem.map(([id, startedAt]) => [id, startedAt?.epochMilliseconds]),
2839 - [
2840 - ["first-command", 1782622445000],
2841 - ["first-command", 1782622445000],
2842 - ["second-command", 1782622505000],
2843 - ["second-command", 1782622505000],
2844 - ["compaction", 1782622565000],
2845 - ["compaction", 1782622565000],
2846 - ],
2847 - );
2848 - }).pipe(
2849 - Effect.provide(
2850 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
2851 - ),
2852 - ),
2853 - ),
2854 - );
2855 -
2334 it.effect.each(["completed", "interrupted"] as const)(
2335 "retains Codex reasoning parts when the turn is %s",
2336 (terminalStatus) =>
@@ -3154,39 +2632,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
2632 ),
2633 );
2634
3157 - it.effect("keeps a later non-empty final answer after an initial empty final answer", () =>
3158 - Effect.scoped(
3159 - Effect.gen(function* () {
3160 - const transcript = finalAnswerTranscript("codex-empty-then-non-empty-final", [
3161 - { id: "answer-empty", text: "" },
3162 - { id: "answer-non-empty", text: "CODEX_RECOVERY_OK" },
3163 - ]);
3164 - const harness = yield* makeCodexReplayHarness(transcript);
3165 - const now = yield* DateTime.now;
3166 -
3167 - yield* harness.runtime.startTurn(
3168 - makeCodexTestTurnInput({
3169 - threadId: harness.threadId,
3170 - providerThread: harness.providerThread,
3171 - now,
3172 - attemptId: RunAttemptId.make("attempt-codex-empty-then-non-empty-final"),
3173 - text: "Reply with the requested recovery marker.",
3174 - }),
3175 - );
3176 - yield* harness.awaitTerminal(1);
3177 -
3178 - assert.deepEqual(
3179 - assistantMessages(harness.events).map((event) => event.message.text),
3180 - ["", "CODEX_RECOVERY_OK"],
3181 - );
3182 - }).pipe(
3183 - Effect.provide(
3184 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
3185 - ),
3186 - ),
3187 - ),
3188 - );
3189 -
2635 const BG_SCENARIO = "codex-bg-exec-wake";
2636 const BG_NATIVE_THREAD = "native-codex-bg-thread";
2637 const BG_NATIVE_TURN = "native-codex-bg-turn";
@@ -4320,93 +3765,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
3765 ),
3766 );
3767
4323 - const childInterruptResponseIndex = interruptSubagentCommandTranscript.entries.findIndex(
4324 - (entry) => entry.type === "emit_inbound" && entry.label === "turn/interrupt/child",
4325 - );
4326 - const rootInterruptResponseIndex = interruptSubagentCommandTranscript.entries.findIndex(
4327 - (entry) => entry.type === "emit_inbound" && entry.label === "turn/interrupt/root",
4328 - );
4329 - const interruptSubagentRequestFailureTranscript = makeCodexReplayTranscript({
4330 - scenario: "codex-interrupt-subagent-request-failure",
4331 - entries: [
4332 - ...interruptSubagentCommandTranscript.entries.slice(0, rootInterruptResponseIndex + 1),
4333 - {
4334 - type: "emit_inbound",
4335 - label: "turn/completed/root-before-child-interrupt-failure",
4336 - frame: {
4337 - method: "turn/completed",
4338 - params: {
4339 - threadId: INTERRUPT_NATIVE_THREAD,
4340 - turn: makeCodexReplayTurn({ id: INTERRUPT_NATIVE_TURN, status: "interrupted" }),
4341 - },
4342 - },
4343 - },
4344 - ...interruptSubagentCommandTranscript.entries.slice(
4345 - rootInterruptResponseIndex + 1,
4346 - childInterruptResponseIndex,
4347 - ),
4348 - {
4349 - type: "emit_inbound",
4350 - label: "turn/interrupt/child",
4351 - frame: {
4352 - id: 5,
4353 - error: { code: -32_000, message: "child interrupt request failed" },
4354 - },
4355 - },
4356 - { type: "runtime_exit", status: "success" },
4357 - ],
4358 - });
4359 -
4360 - it.effect("terminalizes descendants before the root when an interrupt request fails", () =>
4361 - Effect.scoped(
4362 - Effect.gen(function* () {
4363 - const harness = yield* makeCodexReplayHarness(interruptSubagentRequestFailureTranscript);
4364 - const now = yield* DateTime.now;
4365 -
4366 - yield* harness.runtime.startTurn(
4367 - makeCodexTestTurnInput({
4368 - threadId: harness.threadId,
4369 - providerThread: harness.providerThread,
4370 - now,
4371 - attemptId: RunAttemptId.make("attempt-codex-interrupt-subagent-request-failure"),
4372 - text: INTERRUPT_PROMPT,
4373 - }),
4374 - );
4375 - yield* harness.until(() =>
4376 - harness.events.some(
4377 - (event) =>
4378 - event.type === "turn_item.updated" &&
4379 - event.turnItem.type === "command_execution" &&
4380 - event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_COMMAND_ITEM &&
4381 - event.turnItem.status === "running",
4382 - ),
4383 - );
4384 - const providerTurnId = harness.events.find(
4385 - (
4386 - event,
4387 - ): event is Extract<
4388 - ProviderAdapter.ProviderAdapterV2Event,
4389 - { type: "provider_turn.updated" }
4390 - > => event.type === "provider_turn.updated" && event.threadId === harness.threadId,
4391 - )?.providerTurn.id;
4392 - assert.isDefined(providerTurnId);
4393 -
4394 - const interruptExit = yield* harness.runtime
4395 - .interruptTurn({ providerThread: harness.providerThread, providerTurnId })
4396 - .pipe(Effect.exit);
4397 -
4398 - assert.equal(interruptExit._tag, "Failure");
4399 - yield* harness.awaitTerminal(1);
4400 - assertChildProviderTerminalBeforeRoot(harness.events, harness.threadId);
4401 - assert.isFalse(yield* harness.hasPendingBackgroundWork);
4402 - }).pipe(
4403 - Effect.provide(
4404 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
4405 - ),
4406 - ),
4407 - ),
4408 - );
4409 -
3768 const rootCompletionIndex = interruptSubagentCommandTranscript.entries.findIndex(
3769 (entry) => entry.type === "emit_inbound" && entry.label === "turn/completed/root",
3770 );
@@ -4518,115 +3876,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
3876 ),
3877 );
3878
4521 - const interruptTerminationFailureTranscript = makeCodexReplayTranscript({
4522 - scenario: "codex-interrupt-termination-failure",
4523 - entries: [
4524 - ...interruptMidCommandTranscript.entries
4525 - .filter(
4526 - (entry) => entry.type === "runtime_exit" || entry.label !== "item/completed/command-late",
4527 - )
4528 - .map((entry) =>
4529 - entry.type === "emit_inbound" &&
4530 - entry.label === "thread/backgroundTerminals/list/after-false"
4531 - ? {
4532 - ...entry,
4533 - frame: {
4534 - id: 6,
4535 - result: {
4536 - data: [{ processId: "57680" }],
4537 - nextCursor: null,
4538 - },
4539 - },
4540 - }
4541 - : entry,
4542 - ),
4543 - {
4544 - type: "expect_outbound",
4545 - label: "thread/backgroundTerminals/terminate/one-retry",
4546 - frame: {
4547 - id: 8,
4548 - method: "thread/backgroundTerminals/terminate",
4549 - params: { threadId: INTERRUPT_NATIVE_THREAD, processId: "57680" },
4550 - },
4551 - },
4552 - {
4553 - type: "emit_inbound",
4554 - label: "thread/backgroundTerminals/terminate/one-retry",
4555 - frame: { id: 8, result: { terminated: false } },
4556 - },
4557 - {
4558 - type: "expect_outbound",
4559 - label: "thread/backgroundTerminals/list/after-false-retry",
4560 - frame: {
4561 - id: 9,
4562 - method: "thread/backgroundTerminals/list",
4563 - params: { threadId: INTERRUPT_NATIVE_THREAD },
4564 - },
4565 - },
4566 - {
4567 - type: "emit_inbound",
4568 - label: "thread/backgroundTerminals/list/after-false-retry",
4569 - frame: {
4570 - id: 9,
4571 - result: { data: [{ processId: "57680" }], nextCursor: null },
4572 - },
4573 - },
4574 - { type: "runtime_exit", status: "success" },
4575 - ],
4576 - });
4577 -
4578 - it.effect("attempts every terminal and cleans up tracking when termination fails", () =>
4579 - Effect.scoped(
4580 - Effect.gen(function* () {
4581 - const harness = yield* makeCodexReplayHarness(interruptTerminationFailureTranscript);
4582 - const now = yield* DateTime.now;
4583 -
4584 - yield* harness.runtime.startTurn(
4585 - makeCodexTestTurnInput({
4586 - threadId: harness.threadId,
4587 - providerThread: harness.providerThread,
4588 - now,
4589 - attemptId: RunAttemptId.make("attempt-codex-interrupt-termination-failure"),
4590 - text: INTERRUPT_PROMPT,
4591 - }),
4592 - );
4593 - yield* harness.until(() =>
4594 - harness.events.some(
4595 - (event) =>
4596 - event.type === "turn_item.updated" &&
4597 - event.turnItem.type === "command_execution" &&
4598 - event.turnItem.status === "running",
4599 - ),
4600 - );
4601 - const providerTurnId = harness.events.find(
4602 - (
4603 - event,
4604 - ): event is Extract<
4605 - ProviderAdapter.ProviderAdapterV2Event,
4606 - { type: "provider_turn.updated" }
4607 - > => event.type === "provider_turn.updated",
4608 - )?.providerTurn.id;
4609 - assert.isDefined(providerTurnId);
4610 -
4611 - const interruptExit = yield* harness.runtime
4612 - .interruptTurn({
4613 - providerThread: harness.providerThread,
4614 - providerTurnId,
4615 - })
4616 - .pipe(Effect.exit);
4617 -
4618 - assert.equal(interruptExit._tag, "Failure");
4619 - yield* harness.awaitTerminal(1);
4620 - assert.equal(harness.terminalEvents()[0]?.status, "interrupted");
4621 - assert.isFalse(yield* harness.hasPendingBackgroundWork);
4622 - }).pipe(
4623 - Effect.provide(
4624 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
4625 - ),
4626 - ),
4627 - ),
4628 - );
4629 -
3879 it.effect.each([
3880 {
3881 name: "usage",
@@ -4634,31 +3883,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
3883 notification: false,
3884 expectedClass: "usage_limit",
3885 },
4637 - { name: "rate", code: "rateLimitExceeded", notification: false, expectedClass: "usage_limit" },
4638 - {
4639 - name: "ordinary",
4640 - code: "contextWindowExceeded",
4641 - notification: false,
4642 - expectedClass: "provider_error",
4643 - },
4644 - {
4645 - name: "notification",
4646 - code: "usageLimitExceeded",
4647 - notification: true,
4648 - expectedClass: "usage_limit",
4649 - },
3886 {
3887 name: "replacement",
3888 code: "usageLimitExceeded",
3889 notification: true,
3890 expectedClass: "provider_error",
3891 },
4656 - {
4657 - name: "known-reset",
4658 - code: "usageLimitExceeded",
4659 - notification: false,
4660 - expectedClass: "usage_limit",
4661 - },
3892 {
3893 name: "late-reset",
3894 code: "usageLimitExceeded",
@@ -4717,9 +3947,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
3947 scenario: `codex-limit-${scenario.name}`,
3948 entries: [
3949 ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }),
4720 - ...(scenario.name === "known-reset" || scenario.name === "deferred-reset"
4721 - ? [snapshot]
4722 - : []),
3950 + ...(scenario.name === "deferred-reset" ? [snapshot] : []),
3951 ...(scenario.name === "deferred-reset"
3952 ? [
3953 {
@@ -4859,8 +4087,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
4087 if (terminal?.status !== "failed") return;
4088 assert.equal(terminal.failure.class, scenario.expectedClass);
4089 assert.equal(terminal.threadDisposition, "reusable");
4862 - if (scenario.name === "known-reset" || scenario.name === "deferred-reset")
4863 - assert.equal(terminal.failure.resetAt, resetAt);
4090 + if (scenario.name === "deferred-reset") assert.equal(terminal.failure.resetAt, resetAt);
4091 if (scenario.name === "matching-details")
4092 assert.equal(terminal.failure.message, "Detailed provider allowance explanation.");
4093 if (scenario.name === "late-reset") {
@@ -4882,6 +4109,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
4109 ),
4110 );
4111
4112 + // regression: #17501 Codex 429 retry exhaustion classifies as a usage limit
4113 it.effect.each([
4114 {
4115 notificationStatus: 500,
@@ -5664,7 +4892,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
4892 ],
4893 });
4894
5667 - it.effect.each(["thread/settings/updated", "model/rerouted"] as const)(
4895 + it.effect.each(["model/rerouted"] as const)(
4896 "keeps %s child metadata when an older lookup finishes later",
4897 (method) =>
4898 Effect.scoped(
@@ -5676,29 +4904,13 @@ describe("CodexAdapterV2 post-settle continuation", () => {
4904 type: "emit_inbound",
4905 frame: {
4906 method,
5679 - params:
5680 - method === "model/rerouted"
5681 - ? {
5682 - threadId: RESUME_CHILD_THREAD,
5683 - turnId: RESUME_CHILD_TURN_1,
5684 - fromModel: "gpt-6-astra",
5685 - toModel: model,
5686 - reason: "highRiskCyberActivity",
5687 - }
5688 - : {
5689 - threadId: RESUME_CHILD_THREAD,
5690 - threadSettings: {
5691 - model,
5692 - effort: "low",
5693 - serviceTier: "ultrafast",
5694 - modelProvider: "openai",
5695 - cwd: "/workspace",
5696 - approvalPolicy: "never",
5697 - approvalsReviewer: "auto_review",
5698 - collaborationMode: { mode: "default", settings: { model } },
5699 - sandboxPolicy: { type: "dangerFullAccess" },
5700 - },
5701 - },
4907 + params: {
4908 + threadId: RESUME_CHILD_THREAD,
4909 + turnId: RESUME_CHILD_TURN_1,
4910 + fromModel: "gpt-6-astra",
4911 + toModel: model,
4912 + reason: "highRiskCyberActivity",
4913 + },
4914 },
4915 };
4916 const initialSettings: CodexReplay.CodexAppServerReplayEntry = {
@@ -5828,98 +5040,8 @@ describe("CodexAdapterV2 post-settle continuation", () => {
5040 ),
5041 );
5042
5831 - it.effect("rejects duplicate child starts across parent runs", () =>
5832 - Effect.scoped(
5833 - Effect.gen(function* () {
5834 - const firstDone = yield* Deferred.make<void>();
5835 - const resumed = yield* Deferred.make<void>();
5836 - const secondTurn = "native-parent-resume-turn";
5837 - const secondPrompt = "Resume the child.";
5838 - const entries = [...resumeSubagentTranscript.entries];
5839 - const resumeIndex = entries.findIndex(
5840 - (e) => e.type === "emit_inbound" && e.label === `turn/started/${RESUME_CHILD_TURN_2}`,
5841 - );
5842 - const suffix = entries.splice(resumeIndex);
5843 - for (const entry of codexReplayPreamble({
5844 - nativeThreadId: RESUME_NATIVE_THREAD,
5845 - nativeTurnId: secondTurn,
5846 - prompt: secondPrompt,
5847 - }).slice(-3)) {
5848 - entries.push(
5849 - entry.type === "expect_outbound" || entry.type === "emit_inbound"
5850 - ? {
5851 - ...entry,
5852 - frame:
5853 - Predicate.isObject(entry.frame) && "id" in entry.frame
5854 - ? { ...entry.frame, id: 4 }
5855 - : entry.frame,
5856 - }
5857 - : entry,
5858 - );
5859 - }
5860 - entries.push(childTurnStarted(RESUME_CHILD_TURN_1));
5861 - entries.push(...suffix);
5862 - const harness = yield* makeCodexReplayHarness(
5863 - makeCodexReplayTranscript({
5864 - scenario: "codex-cross-run-resume",
5865 - entries,
5866 - }),
5867 - (event) =>
5868 - event.type === "turn.terminal"
5869 - ? Deferred.succeed(firstDone, undefined)
5870 - : event.type === "subagent.updated" && event.subagent.runId === "run-cross-run-second"
5871 - ? Deferred.succeed(resumed, undefined)
5872 - : Effect.void,
5873 - );
5874 - const now = yield* DateTime.now;
5875 - yield* harness.runtime.startTurn(
5876 - makeCodexTestTurnInput({
5877 - threadId: harness.threadId,
5878 - providerThread: harness.providerThread,
5879 - now,
5880 - attemptId: RunAttemptId.make("cross-run-first"),
5881 - text: RESUME_PROMPT,
5882 - }),
5883 - );
5884 - yield* TestClock.adjust("100 millis");
5885 - yield* Deferred.await(firstDone);
5886 - yield* harness.runtime.startTurn({
5887 - ...makeCodexTestTurnInput({
5888 - threadId: harness.threadId,
5889 - providerThread: harness.providerThread,
5890 - now,
5891 - attemptId: RunAttemptId.make("cross-run-second"),
5892 - text: secondPrompt,
5893 - }),
5894 - runOrdinal: 2,
5895 - providerTurnOrdinal: 2,
5896 - });
5897 - yield* TestClock.adjust("30 seconds");
5898 - yield* Deferred.await(resumed);
5899 - const row = harness
5900 - .subagentUpdates()
5901 - .find((e) => e.subagent.runId === "run-cross-run-second")?.subagent;
5902 - assert.equal(row?.status, "running");
5903 - assert.equal(row?.parentNodeId, "node-cross-run-second");
5904 - assert.isNull(row?.completedAt);
5905 - assert.isNotNull(row?.startedAt);
5906 - assert.equal(DateTime.toEpochMillis(row!.startedAt!), 1782622470000);
5907 - }).pipe(
5908 - Effect.provide(
5909 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
5910 - ),
5911 - ),
5912 - ),
5913 - );
5914 -
5043 it.effect.each([
5916 - ["pendingInit", "pending"],
5917 - ["running", "running"],
5918 - ["interrupted", "interrupted"],
5044 ["shutdown", "cancelled"],
5920 - ["notFound", "failed"],
5921 - ["errored", "failed"],
5922 - ["completed", "completed"],
5045 ["activity-completed", "completed"],
5046 ["late-activity-completed", "completed"],
5047 ["stale-running", "completed"],
@@ -6528,55 +5650,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
5650 ),
5651 );
5652
6531 - it.effect("settles /goal pause with a reply instead of a native turn", () =>
6532 - Effect.gen(function* () {
6533 - const transcript = makeCodexReplayTranscript({
6534 - scenario: "goal-pause",
6535 - entries: [
6536 - ...sessionStart,
6537 - ...request(
6538 - 3,
6539 - "thread/goal/get",
6540 - { threadId: nativeThreadId },
6541 - { goal: codexGoal("active", 10) },
6542 - ),
6543 - ...request(
6544 - 4,
6545 - "thread/goal/set",
6546 - { threadId: nativeThreadId, status: "paused" },
6547 - { goal: codexGoal("paused", 10) },
6548 - ),
6549 - ],
6550 - });
6551 - const harness = yield* makeCodexReplayHarness(transcript);
6552 - yield* harness.runtime.startTurn(yield* goalTurnInput(harness, "/goal pause"));
6553 - yield* harness.firstTerminal;
6554 -
6555 - assert.deepEqual(
6556 - harness.terminalEvents().map((event) => event.status),
6557 - ["completed"],
6558 - );
6559 - const turns = harness.events.flatMap((event) =>
6560 - event.type === "provider_turn.updated" ? [event.providerTurn] : [],
6561 - );
6562 - assert.isTrue(turns.every((turn) => turn.nativeTurnRef === null));
6563 - assert.include(
6564 - harness.events.flatMap((event) =>
6565 - event.type === "message.updated" && event.message.role === "assistant"
6566 - ? [event.message.text]
6567 - : [],
6568 - ),
6569 - "Goal paused. Send /goal resume to continue.",
6570 - );
6571 - assert.equal(providerGoals(harness.events).at(-1), "paused");
6572 - }).pipe(
6573 - Effect.scoped,
6574 - Effect.provide(
6575 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
6576 - ),
6577 - ),
6578 - );
6579 -
5653 it.effect("settles a run held for the next goal turn when Stop arrives in between", () =>
5654 Effect.gen(function* () {
5655 const prompt = "Keep going";
@@ -6750,305 +5823,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
5823 ),
5824 );
5825
6753 - it.effect("stops a held goal run's background command when Stop arrives between turns", () =>
6754 - Effect.gen(function* () {
6755 - const prompt = "Start the server";
6756 - const command = "node server.js";
6757 - const commandItem = (status: "inProgress" | "completed") => ({
6758 - type: "commandExecution",
6759 - id: "goal-bg-command",
6760 - command,
6761 - cwd: "/workspace",
6762 - processId: "4242",
6763 - source: "unifiedExecStartup",
6764 - status,
6765 - commandActions: [{ type: "unknown", command }],
6766 - aggregatedOutput: null,
6767 - exitCode: null,
6768 - durationMs: null,
6769 - });
6770 - const transcript = makeCodexReplayTranscript({
6771 - scenario: "goal-stop-held-background",
6772 - entries: [
6773 - ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "goal-turn", prompt }),
6774 - notification("command started", "item/started", {
6775 - item: commandItem("inProgress"),
6776 - threadId: nativeThreadId,
6777 - turnId: "goal-turn",
6778 - startedAtMs: 1782622440500,
6779 - }),
6780 - notification("goal active", "thread/goal/updated", {
6781 - threadId: nativeThreadId,
6782 - turnId: "goal-turn",
6783 - goal: codexGoal("active", 10),
6784 - }),
6785 - notification("turn done", "turn/completed", {
6786 - threadId: nativeThreadId,
6787 - turn: makeCodexReplayTurn({ id: "goal-turn", status: "completed" }),
6788 - }),
6789 - notification("goal accounted", "thread/goal/updated", {
6790 - threadId: nativeThreadId,
6791 - turnId: null,
6792 - goal: codexGoal("active", 11),
6793 - }),
6794 - ...request(
6795 - 4,
6796 - "thread/goal/set",
6797 - { threadId: nativeThreadId, status: "paused" },
6798 - { goal: codexGoal("paused", 11) },
6799 - ),
6800 - ...request(
6801 - 5,
6802 - "thread/backgroundTerminals/terminate",
6803 - { threadId: nativeThreadId, processId: "4242" },
6804 - { terminated: true },
6805 - ),
6806 - ],
6807 - });
6808 - const harness = yield* makeCodexReplayHarness(transcript);
6809 - yield* harness.runtime.startTurn(
6810 - makeCodexTestTurnInput({
6811 - threadId: harness.threadId,
6812 - providerThread: harness.providerThread,
6813 - now: yield* DateTime.now,
6814 - attemptId: RunAttemptId.make("goal-held-background-attempt"),
6815 - text: prompt,
6816 - }),
6817 - );
6818 - yield* harness.until(() =>
6819 - harness.events.some(
6820 - (event) =>
6821 - event.type === "provider_thread.updated" &&
6822 - event.providerThread.goal?.tokensUsed === 11,
6823 - ),
6824 - );
6825 - yield* harness.runtime.interruptTurn({
6826 - providerThread: harness.providerThread,
6827 - providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
6828 - driver: CodexAdapterV2.CODEX_DRIVER_KIND,
6829 - nativeTurnId: "goal-turn",
6830 - }),
6831 - requestRuntimeRestart: true,
6832 - });
6833 - yield* harness.firstTerminal;
6834 - assert.deepEqual(
6835 - harness.terminalEvents().map((event) => event.status),
6836 - ["interrupted"],
6837 - );
6838 - yield* harness.until(() =>
6839 - harness.events.some(
6840 - (event) =>
6841 - event.type === "turn_item.updated" &&
6842 - event.turnItem.type === "command_execution" &&
6843 - event.turnItem.status === "interrupted",
6844 - ),
6845 - );
6846 - }).pipe(
6847 - Effect.scoped,
6848 - Effect.provide(
6849 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
6850 - ),
6851 - ),
6852 - );
6853 -
6854 - it.effect("moves Stop to a continuation Codex starts while the goal pause is in flight", () =>
6855 - Effect.gen(function* () {
6856 - const prompt = "Keep going";
6857 - const transcript = makeCodexReplayTranscript({
6858 - scenario: "goal-stop-races-continuation",
6859 - entries: [
6860 - ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "goal-turn-a", prompt }),
6861 - notification("goal active", "thread/goal/updated", {
6862 - threadId: nativeThreadId,
6863 - turnId: "goal-turn-a",
6864 - goal: codexGoal("active", 10),
6865 - }),
6866 - {
6867 - type: "expect_outbound",
6868 - label: "thread/goal/set",
6869 - frame: {
6870 - id: 4,
6871 - method: "thread/goal/set",
6872 - params: { threadId: nativeThreadId, status: "paused" },
6873 - },
6874 - },
6875 - notification("first turn done", "turn/completed", {
6876 - threadId: nativeThreadId,
6877 - turn: makeCodexReplayTurn({ id: "goal-turn-a", status: "completed" }),
6878 - }),
6879 - notification("continuation", "turn/started", {
6880 - threadId: nativeThreadId,
6881 - turn: makeCodexReplayTurn({ id: "goal-turn-b", status: "inProgress" }),
6882 - }),
6883 - {
6884 - type: "emit_inbound",
6885 - label: "thread/goal/set",
6886 - frame: { id: 4, result: { goal: codexGoal("paused", 11) } },
6887 - },
6888 - ...request(
6889 - 5,
6890 - "turn/interrupt",
6891 - { threadId: nativeThreadId, turnId: "goal-turn-b" },
6892 - {},
6893 - ),
6894 - notification("continuation interrupted", "turn/completed", {
6895 - threadId: nativeThreadId,
6896 - turn: makeCodexReplayTurn({ id: "goal-turn-b", status: "interrupted" }),
6897 - }),
6898 - ],
6899 - });
6900 - const harness = yield* makeCodexReplayHarness(transcript);
6901 - yield* harness.runtime.startTurn(
6902 - makeCodexTestTurnInput({
6903 - threadId: harness.threadId,
6904 - providerThread: harness.providerThread,
6905 - now: yield* DateTime.now,
6906 - attemptId: RunAttemptId.make("goal-stop-race-attempt"),
6907 - text: prompt,
6908 - }),
6909 - );
6910 - yield* harness.until(() =>
6911 - harness.events.some(
6912 - (event) =>
6913 - event.type === "provider_thread.updated" &&
6914 - event.providerThread.goal?.status === "active",
6915 - ),
6916 - );
6917 - yield* harness.runtime.interruptTurn({
6918 - providerThread: harness.providerThread,
6919 - providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
6920 - driver: CodexAdapterV2.CODEX_DRIVER_KIND,
6921 - nativeTurnId: "goal-turn-a",
6922 - }),
6923 - requestRuntimeRestart: true,
6924 - });
6925 - yield* harness.firstTerminal;
6926 - assert.deepEqual(
6927 - harness.terminalEvents().map((event) => event.status),
6928 - ["interrupted"],
6929 - );
6930 - }).pipe(
6931 - Effect.scoped,
6932 - Effect.provide(
6933 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
6934 - ),
6935 - ),
6936 - );
6937 -
6938 - it.effect("stops an earlier goal turn's subagent when the run settles during the pause", () =>
6939 - Effect.gen(function* () {
6940 - const prompt = "Delegate the audit";
6941 - const childThreadId = "goal-race-child-thread";
6942 - const childTurnId = "goal-race-child-turn";
6943 - const transcript = makeCodexReplayTranscript({
6944 - scenario: "goal-stop-run-settles-during-pause",
6945 - entries: [
6946 - ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "goal-turn-a", prompt }),
6947 - notification("subagent started", "item/completed", {
6948 - item: {
6949 - type: "subAgentActivity",
6950 - id: "goal-race-subagent-call",
6951 - kind: "started",
6952 - agentThreadId: childThreadId,
6953 - agentPath: "/root/audit",
6954 - },
6955 - threadId: nativeThreadId,
6956 - turnId: "goal-turn-a",
6957 - completedAtMs: 1782622441000,
6958 - }),
6959 - notification("child turn", "turn/started", {
6960 - threadId: childThreadId,
6961 - turn: makeCodexReplayTurn({ id: childTurnId, status: "inProgress" }),
6962 - }),
6963 - notification("goal active", "thread/goal/updated", {
6964 - threadId: nativeThreadId,
6965 - turnId: "goal-turn-a",
6966 - goal: codexGoal("active", 10),
6967 - }),
6968 - notification("first turn done", "turn/completed", {
6969 - threadId: nativeThreadId,
6970 - turn: makeCodexReplayTurn({ id: "goal-turn-a", status: "completed" }),
6971 - }),
6972 - notification("continuation", "turn/started", {
6973 - threadId: nativeThreadId,
6974 - turn: makeCodexReplayTurn({ id: "goal-turn-b", status: "inProgress" }),
6975 - }),
6976 - notification("goal accounted", "thread/goal/updated", {
6977 - threadId: nativeThreadId,
6978 - turnId: "goal-turn-b",
6979 - goal: codexGoal("active", 11),
6980 - }),
6981 - {
6982 - type: "expect_outbound",
6983 - label: "thread/goal/set",
6984 - frame: {
6985 - id: 4,
6986 - method: "thread/goal/set",
6987 - params: { threadId: nativeThreadId, status: "paused" },
6988 - },
6989 - },
6990 - notification("goal paused", "thread/goal/updated", {
6991 - threadId: nativeThreadId,
6992 - turnId: "goal-turn-b",
6993 - goal: codexGoal("paused", 11),
6994 - }),
6995 - notification("continuation done", "turn/completed", {
6996 - threadId: nativeThreadId,
6997 - turn: makeCodexReplayTurn({ id: "goal-turn-b", status: "completed" }),
6998 - }),
6999 - {
7000 - type: "emit_inbound",
7001 - label: "thread/goal/set",
7002 - frame: { id: 4, result: { goal: codexGoal("paused", 11) } },
7003 - },
7004 - ...request(5, "turn/interrupt", { threadId: childThreadId, turnId: childTurnId }, {}),
7005 - notification("child interrupted", "turn/completed", {
7006 - threadId: childThreadId,
7007 - turn: makeCodexReplayTurn({ id: childTurnId, status: "interrupted" }),
7008 - }),
7009 - ],
7010 - });
7011 - const harness = yield* makeCodexReplayHarness(transcript);
7012 - yield* harness.runtime.startTurn(
7013 - makeCodexTestTurnInput({
7014 - threadId: harness.threadId,
7015 - providerThread: harness.providerThread,
7016 - now: yield* DateTime.now,
7017 - attemptId: RunAttemptId.make("goal-settles-during-pause-attempt"),
7018 - text: prompt,
7019 - }),
7020 - );
7021 - yield* harness.until(() =>
7022 - harness.events.some(
7023 - (event) =>
7024 - event.type === "provider_thread.updated" &&
7025 - event.providerThread.goal?.tokensUsed === 11,
7026 - ),
7027 - );
7028 - yield* harness.runtime.interruptTurn({
7029 - providerThread: harness.providerThread,
7030 - providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
7031 - driver: CodexAdapterV2.CODEX_DRIVER_KIND,
7032 - nativeTurnId: "goal-turn-b",
7033 - }),
7034 - requestRuntimeRestart: true,
7035 - });
7036 - yield* harness.until(() =>
7037 - harness.events.some(
7038 - (event) =>
7039 - event.type === "provider_turn.updated" &&
7040 - event.providerTurn.nativeTurnRef?.nativeId === childTurnId &&
7041 - event.providerTurn.status === "interrupted",
7042 - ),
7043 - );
7044 - }).pipe(
7045 - Effect.scoped,
7046 - Effect.provide(
7047 - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
7048 - ),
7049 - ),
7050 - );
7051 -
5826 it.effect("pauses an active goal before Stop interrupts its turn", () =>
5827 Effect.gen(function* () {
5828 const prompt = "Keep going";
apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts
-33
@@ -166,20 +166,6 @@ describe("GrokAdapterV2 capabilities", () => {
166 });
167
168 describe("ACP permission policy", () => {
169 - it("honors explicit on-request approval over full-access runtime mode", () => {
170 - assert.equal(
171 - acpPermissionDisposition(
172 - runtimePolicy({
173 - runtimeMode: "full-access",
174 - approvalPolicy: "on-request",
175 - sandboxPolicy: { type: "readOnly" },
176 - }),
177 - permissionRequest("execute"),
178 - ),
179 - "ask",
180 - );
181 - });
182 -
169 it("rejects mutating escalation under a non-interactive read-only policy", () => {
170 const policy = runtimePolicy({
171 runtimeMode: "full-access",
@@ -372,25 +358,6 @@ describe("Grok launch permission mode", () => {
358 ]);
359 }),
360 );
375 -
376 - it.effect("launches asking when an explicit approval or sandbox policy governs the thread", () =>
377 - Effect.gen(function* () {
378 - const asking = [["--permission-mode", "default", "agent", "stdio"]];
379 - assert.deepEqual(
380 - yield* launchArgs(
381 - policy("full-access", {
382 - approvalPolicy: "never",
383 - sandboxPolicy: { type: "workspaceWrite", writableRoots: [], networkAccess: false },
384 - }),
385 - ),
386 - asking,
387 - );
388 - assert.deepEqual(
389 - yield* launchArgs(policy("full-access", { approvalPolicy: "on-request" })),
390 - asking,
391 - );
392 - }),
393 - );
361 });
362
363 describe("Grok native questions", () => {
apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+8 -610
@@ -486,6 +486,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
486 }).pipe(Effect.scoped),
487 );
488
489 + // regression: #18315 OpenCode Go quota stops were not shown as usage limits
490 it.effect.each([
491 ["provider.quota", "usage_limit"],
492 ["provider.rate-limit", "usage_limit"],
@@ -721,90 +722,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
722 }).pipe(Effect.scoped),
723 );
724
724 - it.effect("keeps tracking a background subagent whose Stop did not reach it", () =>
725 - Effect.gen(function* () {
726 - const { runtime, thread } = yield* resumed([
727 - ...backgroundLaunch(CHILD),
728 - out("session.interrupt", { sessionID: CHILD }),
729 - reply("session.interrupt", {
730 - status: 500,
731 - body: { _tag: "UnknownError", message: "interrupt failed" },
732 - }),
733 - out("session.interrupt", { sessionID: SESSION }),
734 - reply("session.interrupt", { interrupted: true }),
735 - event("session.execution.interrupted", { sessionID: SESSION }),
736 - ]);
737 - const watch = yield* watchBackgroundTurn(runtime);
738 - yield* runtime.startTurn(withLineage(thread));
739 - yield* watch.attached;
740 - yield* runtime.interruptTurn({
741 - providerThread: thread,
742 - providerTurnId: yield* providerTurnId,
743 - requestRuntimeRestart: true,
744 - });
745 - assert.equal((yield* watch.terminal)?.status, "interrupted");
746 - assert.isTrue(yield* runtime.hasPendingBackgroundWork!);
747 - assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
748 - }).pipe(Effect.scoped),
749 - );
750 -
751 - it.effect("stops a background subagent announced before its call named it", () =>
752 - Effect.gen(function* () {
753 - const call = "call-background";
754 - const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: call };
755 - const { runtime, thread } = yield* resumed([
756 - out("session.prompt", { sessionID: SESSION, text: "<any>" }),
757 - promptAccepted,
758 - event("session.execution.started", { sessionID: SESSION }),
759 - event("session.tool.input.started", { ...tool, name: "subagent" }),
760 - event("session.tool.called", {
761 - ...tool,
762 - name: "subagent",
763 - input: { description: "Sleep", prompt: "sleep", background: true },
764 - executed: false,
765 - }),
766 - event("session.created", childCreated(CHILD)),
767 - event("session.text.ended", {
768 - sessionID: SESSION,
769 - assistantMessageID: "msg_assistant",
770 - ordinal: 0,
771 - text: "Launched.",
772 - }),
773 - out("session.interrupt", { sessionID: CHILD }),
774 - reply("session.interrupt", { interrupted: true }),
775 - out("session.interrupt", { sessionID: SESSION }),
776 - reply("session.interrupt", { interrupted: true }),
777 - event("session.execution.interrupted", { sessionID: SESSION }),
778 - ]);
779 - const announced = yield* Deferred.make<void>();
780 - const terminal = yield* runtime.events.pipe(
781 - Stream.tap((event) =>
782 - event.type === "turn_item.updated" && event.turnItem.type === "assistant_message"
783 - ? Deferred.succeed(announced, undefined)
784 - : Effect.void,
785 - ),
786 - Stream.filter(
787 - (
788 - event,
789 - ): event is Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }> =>
790 - event.type === "turn.terminal",
791 - ),
792 - Stream.runHead,
793 - Effect.map(Option.getOrUndefined),
794 - Effect.forkScoped,
795 - );
796 - yield* runtime.startTurn(withLineage(thread));
797 - yield* Deferred.await(announced);
798 - yield* runtime.interruptTurn({
799 - providerThread: thread,
800 - providerTurnId: yield* providerTurnId,
801 - requestRuntimeRestart: true,
802 - });
803 - assert.equal((yield* Fiber.join(terminal))?.status, "interrupted");
804 - assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
805 - }).pipe(Effect.scoped),
806 - );
807 -
725 it.effect("gives a background subagent the rules of a mode changed while it runs", () =>
726 Effect.gen(function* () {
727 const { runtime, thread } = yield* resumed([
@@ -1033,6 +950,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
950 }).pipe(Effect.scoped),
951 );
952
953 + // regression: #21979 a failed background subagent pinned its thread as busy
954 it.effect("settles the background call a foreground call joined to a failed child", () =>
955 Effect.gen(function* () {
956 const again = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-again" };
@@ -1122,152 +1040,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1040 }).pipe(Effect.scoped),
1041 );
1042
1125 - it.effect("leaves no background work pending once a reconnect finds its subagent gone", () =>
1126 - Effect.gen(function* () {
1127 - const { runtime, thread } = yield* resumed([
1128 - ...backgroundLaunch(CHILD),
1129 - event("session.execution.started", { sessionID: CHILD }),
1130 - event("session.execution.succeeded", { sessionID: SESSION }),
1131 - { type: "runtime_exit", status: "success" } as const,
1132 - out("event.subscribe"),
1133 - out("session.active"),
1134 - replyData("session.active", {}),
1135 - ]);
1136 - const settled = yield* Deferred.make<string | null>();
1137 - yield* runtime.events.pipe(
1138 - Stream.tap((event) =>
1139 - event.type === "subagent.updated" && event.subagent.status === "interrupted"
1140 - ? Deferred.succeed(settled, event.subagent.result)
1141 - : Effect.void,
1142 - ),
1143 - Stream.runDrain,
1144 - Effect.forkScoped,
1145 - );
1146 - yield* runtime.startTurn(withLineage(thread));
1147 - assert.include((yield* Deferred.await(settled)) ?? "", "lost its connection to OpenCode");
1148 - assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
1149 - assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1150 - }).pipe(Effect.scoped),
1151 - );
1152 -
1153 - it.effect("stops a nested background subagent's report on its own parent's session", () =>
1154 - Effect.gen(function* () {
1155 - const MIDDLE = "ses_middle0000000000000000000";
1156 - const GRANDCHILD = "ses_grandchild00000000000000";
1157 - const tool = (session: string, id: string) => ({
1158 - sessionID: session,
1159 - assistantMessageID: `msg_assistant_${id}`,
1160 - id,
1161 - });
1162 - const report = {
1163 - inboxID: "msg_nested_report",
1164 - sessionID: MIDDLE,
1165 - item: {
1166 - type: "synthetic",
1167 - payload: {
1168 - text: `<subagent sessionID="${GRANDCHILD}" state="cancelled" description="Deep">\n</subagent>`,
1169 - description: "Deep",
1170 - metadata: {
1171 - source: "subagent",
1172 - childID: GRANDCHILD,
1173 - agent: "General",
1174 - state: "cancelled",
1175 - },
1176 - },
1177 - delivery: "steer",
1178 - },
1179 - };
1180 - const offered = yield* Deferred.make<void>();
1181 - const { runtime, thread } = yield* resumed([
1182 - out("session.prompt", { sessionID: SESSION, text: "<any>" }),
1183 - promptAccepted,
1184 - event("session.execution.started", { sessionID: SESSION }),
1185 - event("session.tool.input.started", { ...tool(SESSION, "call-middle"), name: "subagent" }),
1186 - event("session.tool.called", {
1187 - ...tool(SESSION, "call-middle"),
1188 - name: "subagent",
1189 - input: { description: "Middle", prompt: "delegate", background: true },
1190 - executed: false,
1191 - }),
1192 - event("session.created", { ...childCreated(MIDDLE), title: "Middle" }),
1193 - event("session.tool.progress", {
1194 - ...tool(SESSION, "call-middle"),
1195 - metadata: { sessionID: MIDDLE, status: "running" },
1196 - }),
1197 - event("session.execution.started", { sessionID: MIDDLE }),
1198 - event("session.tool.input.started", { ...tool(MIDDLE, "call-deep"), name: "subagent" }),
1199 - event("session.tool.called", {
1200 - ...tool(MIDDLE, "call-deep"),
1201 - name: "subagent",
1202 - input: { description: "Deep", prompt: "sleep", background: true },
1203 - executed: false,
1204 - }),
1205 - event("session.created", {
1206 - ...childCreated(GRANDCHILD),
1207 - parentID: MIDDLE,
1208 - title: "Deep",
1209 - }),
1210 - event("session.tool.progress", {
1211 - ...tool(MIDDLE, "call-deep"),
1212 - metadata: { sessionID: GRANDCHILD, status: "running" },
1213 - }),
1214 - event("session.text.ended", {
1215 - sessionID: SESSION,
1216 - assistantMessageID: "msg_assistant_root",
1217 - ordinal: 0,
1218 - text: "Launched.",
1219 - }),
1220 - out("session.interrupt", { sessionID: MIDDLE }),
1221 - reply("session.interrupt", { interrupted: true }),
1222 - out("session.interrupt", { sessionID: GRANDCHILD }),
1223 - reply("session.interrupt", { interrupted: true }),
1224 - out("session.interrupt", { sessionID: SESSION }),
1225 - reply("session.interrupt", { interrupted: true }),
1226 - event("session.execution.interrupted", { sessionID: SESSION }),
1227 - event("session.execution.interrupted", { sessionID: MIDDLE }),
1228 - event("session.inbox.enqueued", report),
1229 - event("session.execution.started", { sessionID: MIDDLE }),
1230 - out("session.interrupt", { sessionID: MIDDLE }),
1231 - reply("session.interrupt", { interrupted: true }),
1232 - event("session.execution.interrupted", { sessionID: MIDDLE }),
1233 - event("session.execution.started", { sessionID: SESSION }),
1234 - ]).pipe(
1235 - Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
1236 - offer: () => Deferred.succeed(offered, undefined).pipe(Effect.asVoid),
1237 - take: Effect.never,
1238 - }),
1239 - );
1240 - const launched = yield* Deferred.make<void>();
1241 - const middleTurns: Array<string> = [];
1242 - yield* runtime.events.pipe(
1243 - Stream.tap((event) =>
1244 - Effect.gen(function* () {
1245 - if (
1246 - event.type === "provider_turn.updated" &&
1247 - event.providerTurn.nativeTurnRef?.nativeId?.startsWith(`${MIDDLE}:turn:`) === true
1248 - ) {
1249 - middleTurns.push(event.providerTurn.nativeTurnRef.nativeId);
1250 - }
1251 - if (event.type === "turn_item.updated" && event.turnItem.type === "assistant_message") {
1252 - yield* Deferred.succeed(launched, undefined);
1253 - }
1254 - }),
1255 - ),
1256 - Stream.runDrain,
1257 - Effect.forkScoped,
1258 - );
1259 - yield* runtime.startTurn(withLineage(thread));
1260 - yield* Deferred.await(launched);
1261 - yield* runtime.interruptTurn({
1262 - providerThread: thread,
1263 - providerTurnId: yield* providerTurnId,
1264 - requestRuntimeRestart: true,
1265 - });
1266 - yield* Deferred.await(offered);
1267 - assert.deepEqual([...new Set(middleTurns)], [`${MIDDLE}:turn:1`]);
1268 - }).pipe(Effect.scoped),
1269 - );
1270 -
1043 const MIDDLE = "ses_middle0000000000000000000";
1044 const DEEP = "ses_grandchild00000000000000";
1045 const toolOf = (session: string, id: string) => ({
@@ -1409,58 +1181,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1181 }).pipe(Effect.scoped),
1182 );
1183
1412 - it.effect("keeps a reused subagent's background subagent tracked and stops it", () =>
1413 - Effect.gen(function* () {
1414 - const again = "call-middle-again";
1415 - const { runtime, thread } = yield* resumed([
1416 - ...nestedLaunch,
1417 - out("session.update", { sessionID: DEEP, permissions: "<any>" }),
1418 - reply("session.update", null),
1419 - out("session.prompt", { sessionID: SESSION, text: "<any>" }),
1420 - promptAccepted,
1421 - event("session.execution.started", { sessionID: SESSION }),
1422 - event("session.tool.input.started", { ...toolOf(SESSION, again), name: "subagent" }),
1423 - event("session.tool.called", {
1424 - ...toolOf(SESSION, again),
1425 - name: "subagent",
1426 - input: { description: "Middle", prompt: "again", sessionID: MIDDLE },
1427 - executed: false,
1428 - }),
1429 - event("session.tool.progress", {
1430 - ...toolOf(SESSION, again),
1431 - metadata: { sessionID: MIDDLE, status: "running" },
1432 - }),
1433 - out("session.update", { sessionID: MIDDLE, permissions: "<any>" }),
1434 - reply("session.update", null),
1435 - event("session.execution.started", { sessionID: MIDDLE }),
1436 - event("session.execution.succeeded", { sessionID: MIDDLE }),
1437 - event("session.tool.success", {
1438 - ...toolOf(SESSION, again),
1439 - content: [{ type: "text", text: `<subagent sessionID="${MIDDLE}" state="completed">` }],
1440 - metadata: { sessionID: MIDDLE, status: "completed", truncated: false },
1441 - executed: false,
1442 - }),
1443 - event("session.execution.succeeded", { sessionID: SESSION }),
1444 - out("session.interrupt", { sessionID: DEEP }),
1445 - reply("session.interrupt", { interrupted: true }),
1446 - ]);
1447 - const watch = yield* watchNested(runtime);
1448 - yield* runtime.startTurn(withLineage(thread));
1449 - yield* watch.until(() => watch.terminals.length === 1);
1450 - yield* runtime.startTurn({ ...secondTurn(thread), appThread: withLineage(thread).appThread });
1451 - yield* watch.until(() => watch.terminals.length === 2);
1452 - assert.deepEqual(watch.terminals, ["completed", "completed"]);
1453 - assert.equal(watch.deep.at(-1), "running");
1454 - assert.isTrue(yield* runtime.hasPendingBackgroundWork!);
1455 - yield* runtime.interruptTurn({
1456 - providerThread: thread,
1457 - providerTurnId: yield* providerTurnId,
1458 - requestRuntimeRestart: true,
1459 - });
1460 - yield* watch.until(() => watch.deep.at(-1) === "interrupted");
1461 - }).pipe(Effect.scoped),
1462 - );
1463 -
1184 it.effect("stops the turn a foreground subagent runs to answer its background subagent", () =>
1185 Effect.gen(function* () {
1186 const { runtime, thread } = yield* resumed([
@@ -1578,6 +1298,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1298 }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
1299 );
1300
1301 + // regression: #14744 continuations hung after a reconnect took a Stop's end
1302 it.effect("still checks the server when a failed prompt's execution starts late", () =>
1303 Effect.gen(function* () {
1304 const offered = yield* Deferred.make<void>();
@@ -1608,26 +1329,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1329 }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
1330 );
1331
1611 - it.effect("prompts again without a check after the server refused a prompt", () =>
1612 - Effect.gen(function* () {
1613 - const { runtime, thread } = yield* resumed([
1614 - out("session.prompt", { sessionID: SESSION, text: "<any>" }),
1615 - reply("session.prompt", {
1616 - status: 400,
1617 - body: { _tag: "InvalidRequestError", message: "bad prompt" },
1618 - }),
1619 - out("session.prompt", { sessionID: SESSION, text: "<any>" }),
1620 - promptAccepted,
1621 - event("session.execution.succeeded", { sessionID: SESSION }),
1622 - ]);
1623 - const ended = yield* terminals(runtime, 2);
1624 - yield* runtime.startTurn(turnInput(thread)).pipe(Effect.ignore);
1625 - yield* runtime.startTurn(secondTurn(thread));
1626 - const [first, second] = yield* Fiber.join(ended);
1627 - assert.deepEqual([first?.status, second?.status], ["failed", "completed"]);
1628 - }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
1629 - );
1630 -
1332 it.effect("ends a background reply's continuation after a lost stream took a Stop's end", () =>
1333 Effect.gen(function* () {
1334 const offered =
@@ -1845,29 +1546,11 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1546 );
1547 }).pipe(Effect.scoped, Effect.provide(TestClock.layer()));
1548
1549 + // regression: #14744 continuations hung after a reconnect took a Stop's end
1550 it.effect("ends a background reply's continuation after a prompt failed unclearly", () =>
1551 replyAfterUnclearFailure(false),
1552 );
1553
1852 - it.effect("does not report a Stop the server says did nothing", () =>
1853 - Effect.gen(function* () {
1854 - const { runtime, thread } = yield* resumed([
1855 - out("session.prompt", { sessionID: SESSION, text: "<any>" }),
1856 - promptAccepted,
1857 - out("session.interrupt", { sessionID: SESSION }),
1858 - reply("session.interrupt", { interrupted: false }),
1859 - ]);
1860 - yield* runtime.startTurn(turnInput(thread));
1861 - const failed = yield* runtime
1862 - .interruptTurn({
1863 - providerThread: thread,
1864 - providerTurnId: yield* providerTurnId,
1865 - })
1866 - .pipe(Effect.flip);
1867 - assert.equal(failed._tag, "ProviderAdapterProtocolError");
1868 - }).pipe(Effect.scoped),
1869 - );
1870 -
1554 it.effect("reports a turn as completed when its Stop request failed", () =>
1555 Effect.gen(function* () {
1556 const { runtime, thread } = yield* resumed([
@@ -1961,21 +1644,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1644 }).pipe(Effect.scoped),
1645 );
1646
1964 - it.effect("refuses a model slug that is not provider/model before creating a session", () =>
1965 - Effect.gen(function* () {
1966 - const runtime = yield* openCode2ReplayRuntime([...opening]);
1967 - const created = yield* runtime
1968 - .ensureThread({
1969 - threadId,
1970 - modelSelection: { instanceId, model: "big-pickle" },
1971 - runtimePolicy: policy(),
1972 - })
1973 - .pipe(Effect.flip);
1974 - assert.equal(created._tag, "ProviderAdapterProtocolError");
1975 - assert.include(created.message, "OpenCode model 'big-pickle' must use provider/model format");
1976 - }).pipe(Effect.scoped),
1977 - );
1978 -
1647 it.effect("stops the requests a session still waits on when a restarted T3 loads it", () =>
1648 Effect.gen(function* () {
1649 const runtime = yield* openCode2ReplayRuntimeWithInstructions(
@@ -2173,106 +1841,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1841 }).pipe(Effect.scoped),
1842 );
1843
2176 - const subagentAsks = (child: string): ReadonlyArray<ProviderReplayEntry> => {
2177 - const call = "call-subagent";
2178 - const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: call };
2179 - return [
2180 - out("session.prompt", { sessionID: SESSION, text: "<any>" }),
2181 - promptAccepted,
2182 - event("session.execution.started", { sessionID: SESSION }),
2183 - event("session.tool.input.started", { ...tool, name: "subagent" }),
2184 - event("session.tool.called", {
2185 - ...tool,
2186 - name: "subagent",
2187 - input: { description: "Echo", prompt: "echo" },
2188 - executed: false,
2189 - }),
2190 - event("session.created", { ...childCreated(child), title: "Echo" }),
2191 - event("session.tool.progress", {
2192 - ...tool,
2193 - metadata: { sessionID: child, status: "running" },
2194 - }),
2195 - event("session.execution.started", { sessionID: child }),
2196 - event("permission.asked", { ...shellAsk.data, sessionID: child }),
2197 - ];
2198 - };
2199 -
2200 - it.effect("keeps a subagent's 'allow this session' in the subagent's own rules", () =>
2201 - Effect.gen(function* () {
2202 - const { runtime, thread } = yield* resumed(
2203 - [
2204 - ...subagentAsks(CHILD),
2205 - out("session.update", {
2206 - sessionID: CHILD,
2207 - permissions: [
2208 - ...supervisedRules.slice(0, 3),
2209 - { action: "shell", resource: "echo *", effect: "allow" },
2210 - ...mcpRules,
2211 - ],
2212 - }),
2213 - reply("session.update", null),
2214 - out("permission.reply", {
2215 - sessionID: CHILD,
2216 - requestID: shellAsk.data.id,
2217 - decision: "once",
2218 - }),
2219 - reply("permission.reply", null),
2220 - event("session.execution.succeeded", { sessionID: CHILD }),
2221 - event("session.execution.succeeded", { sessionID: SESSION }),
2222 - ],
2223 - { supervised: true },
2224 - );
2225 - const requested = yield* requestOf(runtime).pipe(Effect.forkScoped);
2226 - const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
2227 - yield* runtime.startTurn({
2228 - ...withLineage(thread),
2229 - runtimePolicy: policy("approval-required"),
2230 - });
2231 - const request = yield* Fiber.join(requested);
2232 - yield* runtime.respondToRuntimeRequest({
2233 - requestId: request!.id,
2234 - decision: "acceptForSession",
2235 - });
2236 - assert.equal((yield* Fiber.join(terminal))?.status, "completed");
2237 - }).pipe(Effect.scoped),
2238 - );
2239 -
2240 - it.effect("ends only the subagent's turn when it declines the subagent's form", () =>
2241 - Effect.gen(function* () {
2242 - const linkForm = {
2243 - id: "frm_0eb79ab35001fkvFECSh3wYNVD",
2244 - sessionID: CHILD,
2245 - title: "MCP authorization",
2246 - metadata: { kind: "mcp" },
2247 - fields: [{ key: "authorization", type: "external", url: "https://example.com/authorize" }],
2248 - };
2249 - const { runtime, thread } = yield* resumed([
2250 - ...subagentAsks(CHILD).slice(0, -1),
2251 - event("form.created", { form: linkForm }),
2252 - out("session.form.cancel", { sessionID: CHILD, formID: linkForm.id }),
2253 - reply("session.form.cancel", null),
2254 - event("session.execution.interrupted", { sessionID: CHILD }),
2255 - event("session.tool.failed", {
2256 - sessionID: SESSION,
2257 - assistantMessageID: "msg_assistant",
2258 - id: "call-subagent",
2259 - error: { type: "unknown", message: `Subagent cancelled (sessionID: ${CHILD})` },
2260 - executed: true,
2261 - }),
2262 - event("session.text.ended", {
2263 - sessionID: SESSION,
2264 - assistantMessageID: "msg_assistant_after",
2265 - ordinal: 0,
2266 - text: "The subagent could not finish.",
2267 - }),
2268 - event("session.execution.succeeded", { sessionID: SESSION }),
2269 - ]);
2270 - const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
2271 - yield* runtime.startTurn(withLineage(thread));
2272 - assert.equal((yield* Fiber.join(terminal))?.status, "completed");
2273 - }).pipe(Effect.scoped),
2274 - );
2275 -
1844 it.effect("keeps 'allow this session' in the session's rules, not OpenCode's saved grants", () =>
1845 Effect.gen(function* () {
1846 const { runtime, thread } = yield* resumed(
@@ -2537,90 +2105,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2105 }).pipe(Effect.scoped),
2106 );
2107
2540 - it.effect(
2541 - "backfills and ends a subagent's turn whose execution ended while the stream was down",
2542 - () =>
2543 - Effect.gen(function* () {
2544 - const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-sub" };
2545 - const SUB_PROMPT = "msg_0f73f91e0002lgRNb7FtMzcoQu";
2546 - const { runtime, thread } = yield* resumed([
2547 - out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
2548 - promptAccepted,
2549 - event("session.execution.started", { sessionID: SESSION }),
2550 - event("session.tool.input.started", { ...tool, name: "subagent" }),
2551 - event("session.tool.called", {
2552 - ...tool,
2553 - name: "subagent",
2554 - input: { description: "Sleep", prompt: "sleep" },
2555 - executed: false,
2556 - }),
2557 - event("session.created", childCreated(CHILD)),
2558 - event("session.tool.progress", {
2559 - ...tool,
2560 - metadata: { sessionID: CHILD, status: "running" },
2561 - }),
2562 - event("session.inbox.enqueued", {
2563 - inboxID: SUB_PROMPT,
2564 - sessionID: CHILD,
2565 - item: { type: "user", payload: { text: "sleep" }, delivery: "steer" },
2566 - }),
2567 - event("session.execution.started", { sessionID: CHILD }),
2568 - { type: "runtime_exit", status: "success" } as const,
2569 - out("event.subscribe"),
2570 - out("session.active"),
2571 - replyData("session.active", { [SESSION]: { type: "running" } }),
2572 - out("message.list", { sessionID: CHILD, order: "desc", limit: "50" }),
2573 - reply("message.list", {
2574 - data: [
2575 - { id: "msg_idle_sub", time: { created: 4 }, type: "idle", outcome: "succeeded" },
2576 - {
2577 - id: "msg_assistant_sub",
2578 - time: { created: 3 },
2579 - type: "assistant",
2580 - agent: "general",
2581 - model: { id: "big-pickle", providerID: "opencode", variant: "default" },
2582 - content: [{ type: "text", text: "Slept while the stream was down." }],
2583 - finish: "stop",
2584 - },
2585 - { id: SUB_PROMPT, time: { created: 2 }, text: "sleep", type: "user" },
2586 - ],
2587 - cursor: {},
2588 - }),
2589 - out("message.list", { sessionID: SESSION, order: "desc", limit: "50" }),
2590 - reply("message.list", {
2591 - data: [{ id: PROMPT_ID, time: { created: 1 }, text: "hi", type: "user" }],
2592 - cursor: {},
2593 - }),
2594 - ...openRequests([]),
2595 - event("session.execution.succeeded", { sessionID: SESSION }),
2596 - ]);
2597 - const events = yield* runtime.events.pipe(
2598 - Stream.takeUntil((event) => event.type === "turn.terminal"),
2599 - Stream.runCollect,
2600 - Effect.forkScoped,
2601 - );
2602 - yield* runtime.startTurn(withLineage(thread));
2603 - const collected = yield* Fiber.join(events);
2604 - const childTurn = collected.findLast(
2605 - (event) =>
2606 - event.type === "provider_turn.updated" &&
2607 - event.providerTurn.nativeTurnRef?.nativeId === `${CHILD}:turn:1`,
2608 - );
2609 - assert.isTrue(
2610 - collected.some(
2611 - (event) =>
2612 - event.type === "turn_item.updated" &&
2613 - event.turnItem.type === "assistant_message" &&
2614 - event.turnItem.text === "Slept while the stream was down.",
2615 - ),
2616 - );
2617 - assert.equal(
2618 - childTurn?.type === "provider_turn.updated" ? childTurn.providerTurn.status : undefined,
2619 - "completed",
2620 - );
2621 - }).pipe(Effect.scoped),
2622 - );
2623 -
2108 it.effect("keeps a turn still running after a reconnect open for its next events", () =>
2109 Effect.gen(function* () {
2110 const { runtime, thread } = yield* resumed([
@@ -2756,47 +2240,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2240 }).pipe(Effect.scoped),
2241 );
2242
2759 - it.effect(
2760 - "registers T3's MCP server for the thread alone and removes it when the thread unloads",
2761 - () =>
2762 - Effect.gen(function* () {
2763 - const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
2764 - yield* mcpSessions.set({
2765 - environmentId: EnvironmentId.make("environment:opencode2-adapter"),
2766 - threadId,
2767 - providerSessionId: "mcp:opencode2-adapter",
2768 - providerInstanceId: instanceId,
2769 - endpoint: "http://127.0.0.1:3773/mcp",
2770 - authorizationHeader: "Bearer thread-credential",
2771 - browserToolsAvailable: false,
2772 - });
2773 - yield* Effect.addFinalizer(() => mcpSessions.clear(threadId));
2774 - const server = "t3-code-thread_opencode2-adapter";
2775 - const { runtime, thread } = yield* resumed([
2776 - out("mcp.add", {
2777 - server,
2778 - "location[directory]": WORK,
2779 - config: {
2780 - type: "remote",
2781 - url: "http://127.0.0.1:3773/mcp",
2782 - headers: { Authorization: "Bearer thread-credential" },
2783 - oauth: false,
2784 - },
2785 - }),
2786 - reply("mcp.add", null),
2787 - out("session.prompt", { sessionID: SESSION, text: "<any>" }),
2788 - promptAccepted,
2789 - event("session.execution.succeeded", { sessionID: SESSION }),
2790 - out("mcp.remove", { server, "location[directory]": WORK }),
2791 - reply("mcp.remove", null),
2792 - ]);
2793 - const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
2794 - yield* runtime.startTurn(turnInput(thread));
2795 - assert.equal((yield* Fiber.join(terminal))?.status, "completed");
2796 - yield* runtime.unloadThread!({ providerThread: thread });
2797 - }).pipe(Effect.scoped),
2798 - );
2799 -
2243 it.effect("re-registers T3 MCP each turn and drops its instructions when adding fails", () =>
2244 Effect.gen(function* () {
2245 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
@@ -2912,6 +2355,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2355 }).pipe(Effect.scoped),
2356 );
2357
2358 + // regression: #16142 OpenCode 2 threads were missing T3 Code's MCP tools
2359 it.effect("names each thread's MCP server within OpenCode's limits, one name per thread", () =>
2360 Effect.gen(function* () {
2361 const project = "thread:project:ce04e4e2-6c29-4ff0-a1d7-b089dd63e258";
@@ -3373,10 +2817,10 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2817 }).pipe(Effect.scoped),
2818 );
2819
2820 + // regression: #15672 OpenCode 2 provider retries ran silently instead of showing
2821 it.effect.each([
2822 { name: "restores retry pending at reconnect", pending: true, streamed: false },
2823 { name: "settles retry recovered during drop", pending: false, streamed: false },
3379 - { name: "keeps retry pending when only streamed at reconnect", pending: true, streamed: true },
2824 ])("$name", ({ pending, streamed }) =>
2825 Effect.gen(function* () {
2826 const gate = makeProviderReplayGate(["finish"]);
@@ -3819,6 +3263,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3263 }).pipe(Effect.scoped, Effect.provide(IdAllocator.layer)),
3264 );
3265
3266 + // regression: #16775 unchanged session status updates were rewritten on every event
3267 it.effect("reports the shared session's status only when it changes", () =>
3268 Effect.gen(function* () {
3269 const OTHER = "ses_f148ca2deffeOtherSession000";
@@ -3885,7 +3330,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3330
3331 it.effect.each([
3332 ["refuses a rollback while a timed-out Stop's run is still going", true],
3888 - ["rolls back once a timed-out Stop's run has left the server", false],
3333 ] as const)("%s", ([, running]) =>
3334 Effect.gen(function* () {
3335 const prompt = `msg_t3_turn_${SESSION}:attempt:opencode2-adapter`;
@@ -4164,7 +3608,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3608 );
3609
3610 it.effect.each([
4167 - ["refuses to roll back a session not loaded yet while the server runs it", true],
3611 [
3612 "keeps the recorded turns before the target when rolling back a session not loaded yet",
3613 false,
@@ -4270,23 +3713,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3713 }).pipe(Effect.scoped),
3714 );
3715
4273 - it.effect("asks the server before forking a session this runtime has not loaded", () =>
4274 - Effect.gen(function* () {
4275 - const runtime = yield* openCode2ReplayRuntime([
4276 - ...opening,
4277 - out("session.active"),
4278 - reply("session.active", { data: { [SESSION]: { type: "running" } } }),
4279 - ]);
4280 - const refused = yield* runtime
4281 - .forkThread({
4282 - sourceProviderThread: providerThread(yield* DateTime.now),
4283 - targetThreadId: ThreadId.make("thread:opencode2-adapter:fork"),
4284 - })
4285 - .pipe(Effect.flip);
4286 - assert.equal(refused._tag, "ProviderAdapterProtocolError");
4287 - }).pipe(Effect.scoped),
4288 - );
4289 -
3716 it.effect("moves a fork into its target thread's worktree before the first prompt", () =>
3717 Effect.gen(function* () {
3718 const FORK = "ses_f1484db83ffeLGtrRCFimo1H0e";
@@ -4414,35 +3840,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3840 }).pipe(Effect.scoped),
3841 );
3842
4417 - it.effect("rolls back before a continuation's report, so its answer leaves the history", () =>
4418 - Effect.gen(function* () {
4419 - const { runtime, thread, first, second } = yield* continued([
4420 - out("message.list", "<any>"),
4421 - reply("message.list", continuedHistory),
4422 - out("session.revert.stage", { sessionID: SESSION, messageID: "msg_report", files: false }),
4423 - replyData("session.revert.stage", { messageID: "msg_report", files: [] }),
4424 - out("session.revert.commit", { sessionID: SESSION }),
4425 - reply("session.revert.commit", null),
4426 - out("message.list", "<any>"),
4427 - reply("message.list", { data: [continuedHistory.data[1]], cursor: {} }),
4428 - ]);
4429 - const snapshot = yield* runtime.rollbackThread({
4430 - providerThread: thread,
4431 - target: {
4432 - type: "provider_turn",
4433 - checkpointId: CheckpointId.make("checkpoint:first"),
4434 - appRunOrdinal: 1,
4435 - providerTurn: first,
4436 - },
4437 - providerThreadTurns: [first, second],
4438 - });
4439 - assert.deepEqual(
4440 - snapshot.providerTurns.map((turn) => turn.id),
4441 - [first.id],
4442 - );
4443 - }).pipe(Effect.scoped),
4444 - );
4445 -
3843 it.effect("keeps a subagent a stopped background reply started off the next turn", () =>
3844 Effect.gen(function* () {
3845 const CHILD_B = "ses_f1485c529ffeBBBBBBBBBBBBBB";
@@ -4630,6 +4027,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4027 }).pipe(Effect.scoped),
4028 );
4029
4030 + // regression: #14752 continuations replayed background replies that were not theirs
4031 it.effect("ends a continuation while a skipped reply's subagent does not answer its Stop", () =>
4032 Effect.gen(function* () {
4033 const CHILD_B = "ses_f1485c529ffeBBBBBBBBBBBBBB";
apps/server/src/orchestration-v2/Adapters/claudeWorkflowProgress.test.ts
-91
@@ -2,14 +2,6 @@ import { describe, expect, it } from "vite-plus/test";
2
3 import { mergeClaudeWorkflowProgress } from "./claudeWorkflowProgress.ts";
4
5 -const startFrame = {
6 - type: "system",
7 - subtype: "task_started",
8 - task_id: "w1",
9 - task_type: "local_workflow",
10 - workflow_name: "probe-wf",
11 -};
12 -
5 const snapshotFrame = (
6 entries: ReadonlyArray<Record<string, unknown>>,
7 usage?: Record<string, number>,
@@ -35,21 +27,6 @@ const agent = (overrides: Record<string, unknown>) => ({
27 });
28
29 describe("mergeClaudeWorkflowProgress", () => {
38 - it("leaves an ordinary subagent's frames alone", () => {
39 - expect(
40 - mergeClaudeWorkflowProgress({
41 - previous: undefined,
42 - message: {
43 - type: "system",
44 - subtype: "task_progress",
45 - task_id: "t1",
46 - description: "reading files",
47 - usage: { total_tokens: 500, tool_uses: 2, duration_ms: 90 },
48 - },
49 - }),
50 - ).toBeUndefined();
51 - });
52 -
30 it("maps provider agent states and per-member metrics", () => {
31 const workflow = mergeClaudeWorkflowProgress({
32 previous: undefined,
@@ -128,18 +105,6 @@ describe("mergeClaudeWorkflowProgress", () => {
105 expect(second?.totalTokens).toBe(250);
106 });
107
131 - it("keeps a phase the plan reached at runtime even if a later frame omits it", () => {
132 - const first = mergeClaudeWorkflowProgress({
133 - previous: undefined,
134 - message: snapshotFrame([phase(1, "Alpha"), phase(2, "Beta"), phase(3, "Gamma")]),
135 - });
136 - const second = mergeClaudeWorkflowProgress({
137 - previous: first,
138 - message: snapshotFrame([phase(1, "Alpha")]),
139 - });
140 - expect(second?.phases.map((entry) => entry.title)).toEqual(["Alpha", "Beta", "Gamma"]);
141 - });
142 -
108 it("keeps other members and phase links when a sparse frame starts a new attempt", () => {
109 const first = mergeClaudeWorkflowProgress({
110 previous: undefined,
@@ -214,62 +179,6 @@ describe("mergeClaudeWorkflowProgress", () => {
179 expect(second?.agents).toEqual(first?.agents);
180 });
181
217 - it("retains member fields omitted by a later frame in the same attempt", () => {
218 - const first = mergeClaudeWorkflowProgress({
219 - previous: undefined,
220 - message: snapshotFrame([agent({ attempt: 2, promptPreview: "Current prompt", tokens: 100 })]),
221 - });
222 - const second = mergeClaudeWorkflowProgress({
223 - previous: first,
224 - message: snapshotFrame([agent({ state: "done", resultPreview: "Current result" })]),
225 - });
226 - expect(second?.agents[0]).toMatchObject({
227 - state: "completed",
228 - attempt: 2,
229 - prompt: "Current prompt",
230 - result: "Current result",
231 - totalTokens: 100,
232 - });
233 - });
234 -
235 - it("keeps existing run handles when a later acknowledgement supplies only a script path", () => {
236 - const first = mergeClaudeWorkflowProgress({
237 - previous: undefined,
238 - runHandles: { runId: "wf_abc", transcriptDir: "/workflows/wf_abc" },
239 - message: startFrame,
240 - });
241 - const second = mergeClaudeWorkflowProgress({
242 - previous: first,
243 - runHandles: { scriptPath: "/scripts/workflow.js" },
244 - message: startFrame,
245 - });
246 - expect(second?.runHandles).toEqual({
247 - runId: "wf_abc",
248 - transcriptDir: "/workflows/wf_abc",
249 - scriptPath: "/scripts/workflow.js",
250 - });
251 - });
252 -
253 - it("drops timestamps outside the DateTime range", () => {
254 - const workflow = mergeClaudeWorkflowProgress({
255 - previous: undefined,
256 - message: snapshotFrame([
257 - agent({
258 - state: "done",
259 - lastProgressAt: 8_640_000_000_000_001,
260 - startedAt: 8_640_000_000_000_001,
261 - queuedAt: Number.MAX_SAFE_INTEGER,
262 - }),
263 - agent({ index: 2, startedAt: 8_640_000_000_000_000, queuedAt: 0 }),
264 - ]),
265 - });
266 - expect(workflow?.agents[0]).not.toHaveProperty("startedAt");
267 - expect(workflow?.agents[0]).not.toHaveProperty("queuedAt");
268 - expect(workflow?.agents[0]).not.toHaveProperty("completedAt");
269 - expect(workflow?.agents[1]?.startedAt).toBe(8_640_000_000_000_000);
270 - expect(workflow?.agents[1]?.queuedAt).toBe(0);
271 - });
272 -
182 it("drops malformed entries instead of failing the frame", () => {
183 const workflow = mergeClaudeWorkflowProgress({
184 previous: undefined,
apps/server/src/orchestration-v2/AttachmentClaims.test.ts
+1 -57
@@ -17,11 +17,7 @@ import {
17 parseThreadSegmentFromAttachmentId,
18 } from "../attachmentStore.ts";
19 import * as ServerConfig from "../config.ts";
20 -import {
21 - attachmentIsPendingUpload,
22 - claimPendingAttachments,
23 - releaseClaimedAttachments,
24 -} from "./AttachmentClaims.ts";
20 +import { attachmentIsPendingUpload, claimPendingAttachments } from "./AttachmentClaims.ts";
21
22 const layerTest = Layer.mergeAll(NodeServices.layer).pipe(
23 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-attachment-claims-" })),
@@ -104,40 +100,6 @@ describe("AttachmentClaims", () => {
100 }).pipe(Effect.provide(layerTest)),
101 );
102
107 - it.effect("passes already-claimed attachments through untouched", () =>
108 - Effect.gen(function* () {
109 - const stored: ChatAttachment = {
110 - type: "image",
111 - id: ChatAttachmentId.make("thread-claims-2-00000000-0000-4000-8000-000000000001"),
112 - name: "existing.png",
113 - mimeType: "image/png",
114 - sizeBytes: 4,
115 - };
116 - const claimed = yield* claimPendingAttachments({
117 - threadId: "thread-claims-2",
118 - attachments: [stored],
119 - });
120 - expect(claimed.attachments[0]).toBe(stored);
121 - expect(claimed.claimedPaths).toHaveLength(0);
122 - }).pipe(Effect.provide(layerTest)),
123 - );
124 -
125 - it.effect("rejects a pending ref whose staged file is missing", () =>
126 - Effect.gen(function* () {
127 - const missing: ChatAttachment = {
128 - type: "image",
129 - id: ChatAttachmentId.make(createPendingAttachmentId()!),
130 - name: "gone.png",
131 - mimeType: "image/png",
132 - sizeBytes: 4,
133 - };
134 - const result = yield* Effect.exit(
135 - claimPendingAttachments({ threadId: "thread-claims-3", attachments: [missing] }),
136 - );
137 - expect(result._tag).toBe("Failure");
138 - }).pipe(Effect.provide(layerTest)),
139 - );
140 -
103 it.effect("rejects a size mismatch and cleans up earlier claims from the batch", () =>
104 Effect.gen(function* () {
105 const good = yield* stagePendingUpload({
@@ -250,22 +212,4 @@ describe("AttachmentClaims", () => {
212 ).toHaveLength(1);
213 }).pipe(Effect.provide(layerTest)),
214 );
253 -
254 - it.effect("releaseClaimedAttachments removes claimed copies best-effort", () =>
255 - Effect.gen(function* () {
256 - const pending = yield* stagePendingUpload({
257 - name: "release.png",
258 - bytes: new Uint8Array([9, 9]),
259 - mimeType: "image/png",
260 - });
261 - const claimed = yield* claimPendingAttachments({
262 - threadId: "thread-claims-5",
263 - attachments: [pending],
264 - });
265 - expect(NodeFS.existsSync(claimed.claimedPaths[0]!)).toBe(true);
266 - yield* releaseClaimedAttachments(claimed.claimedPaths);
267 - expect(NodeFS.existsSync(claimed.claimedPaths[0]!)).toBe(false);
268 - yield* releaseClaimedAttachments(claimed.claimedPaths);
269 - }).pipe(Effect.provide(layerTest)),
270 - );
215 });
apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts
+5 -15
@@ -47,12 +47,7 @@ const stopEarlierBackgroundWork = ({
47 readonly stopWithQueue?: "thread.stop" | "run.interrupt";
48 readonly olderStart?: boolean;
49 readonly workflowMember?: boolean;
50 - readonly stalledRun?:
51 - | "missing-session"
52 - | "missing-session-terminal"
53 - | "returned-interrupt"
54 - | "returned-interrupt-terminal"
55 - | "superseded-attempt";
50 + readonly stalledRun?: "missing-session-terminal" | "returned-interrupt" | "superseded-attempt";
51 }) =>
52 Effect.scoped(
53 Effect.gen(function* () {
@@ -235,7 +230,7 @@ const stopEarlierBackgroundWork = ({
230 const run = before.runs[0]!;
231 const node = before.nodes.find((candidate) => candidate.id === run.rootNodeId)!;
232 const attempt = before.attempts[0]!;
238 - if (stalledRun === "missing-session" || stalledRun === "missing-session-terminal") {
233 + if (stalledRun === "missing-session-terminal") {
234 const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
235 const failed = yield* watch(
236 (event) => event.type === "run.updated" && event.payload.status === "failed",
@@ -1017,12 +1012,7 @@ it.effect.each(["thread.stop", "run.interrupt"] as const)(
1012 (stopType) => stopEarlierBackgroundWork({ stopWithQueue: stopType, olderStart: true }),
1013 );
1014
1020 -it.effect.each([
1021 - "missing-session",
1022 - "missing-session-terminal",
1023 - "returned-interrupt",
1024 - "returned-interrupt-terminal",
1025 - "superseded-attempt",
1026 -] as const)("Stop recovers a stalled run after %s without changing a newer attempt", (stalledRun) =>
1027 - stopEarlierBackgroundWork({ stalledRun }),
1015 +it.effect.each(["missing-session-terminal", "returned-interrupt", "superseded-attempt"] as const)(
1016 + "Stop recovers a stalled run after %s without changing a newer attempt",
1017 + (stalledRun) => stopEarlierBackgroundWork({ stalledRun }),
1018 );
apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts
+22 -45
@@ -14,7 +14,6 @@ import * as FileSystem from "effect/FileSystem";
14 import * as Layer from "effect/Layer";
15 import * as Option from "effect/Option";
16 import * as Path from "effect/Path";
17 -import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
17 import * as ServerConfig from "../config.ts";
18 import * as ServerSettings from "../serverSettings.ts";
19 import * as GitWorkflowService from "../git/GitWorkflowService.ts";
@@ -32,14 +31,8 @@ import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
31 it.effect.each([
32 "nested",
33 "ancestor",
35 - "archived-nested",
36 - ...(symlinksSupported ? (["aliased-nested"] as const) : []),
37 - "project",
34 "provider",
39 - "scope",
35 "sibling",
41 - "stopped-provider",
42 - "errored-provider",
36 "shared-provider",
37 "conversation",
38 ] as const)("preserves overlapping workspace files, owner=%s", (owner) =>
@@ -54,8 +47,6 @@ it.effect.each([
47 yield* fs.makeDirectory(sibling);
48 const otherFile = path.join(nested, "other-thread.txt");
49 yield* fs.writeFileString(otherFile, "other thread's uncommitted work");
57 - const alias = path.join(parent, "alias");
58 - if (owner === "aliased-nested") yield* fs.symlink(nested, alias);
50 const threadId = ThreadId.make("restore-current");
51 const otherId = ThreadId.make("restore-other");
52 const projectId = ProjectId.make("restore-project");
@@ -75,15 +66,11 @@ it.effect.each([
66 projectId,
67 deletedAt: null,
68 worktreePath:
78 - owner === "project"
79 - ? null
80 - : owner === "ancestor" || owner === "conversation"
81 - ? parent
82 - : owner === "nested" || owner === "archived-nested"
83 - ? nested
84 - : owner === "aliased-nested"
85 - ? alias
86 - : sibling,
69 + owner === "ancestor" || owner === "conversation"
70 + ? parent
71 + : owner === "nested"
72 + ? nested
73 + : sibling,
74 };
75 const projection = {
76 thread: {
@@ -123,42 +110,34 @@ it.effect.each([
110 Effect.succeed({
111 schemaVersion: 1,
112 snapshotSequence: 0,
126 - threads: owner === "archived-nested" ? [] : ([otherThread] as never),
127 - archivedThreads: owner === "archived-nested" ? ([otherThread] as never) : [],
113 + threads: [otherThread] as never,
114 + archivedThreads: [],
115 }),
116 getCheckpointContext: () =>
117 Effect.succeed({
118 runs: [],
119 checkpoints: [],
133 - checkpointScopes: owner === "scope" ? ([{ cwd: nested }] as never) : [],
120 + checkpointScopes: [],
121 }),
122 getThreadProviderContext: () =>
123 Effect.succeed({
124 thread: otherThread as never,
125 providerThreads: [],
139 - providerSessions: [
140 - "provider",
141 - "stopped-provider",
142 - "errored-provider",
143 - "shared-provider",
144 - ].includes(owner)
145 - ? ([
146 - {
147 - cwd: owner === "shared-provider" ? cwd : nested,
148 - status:
149 - owner === "provider" || owner === "shared-provider"
150 - ? "running"
151 - : owner === "errored-provider"
152 - ? "error"
153 - : "stopped",
154 - capabilities: {
155 - sessions: {
156 - supportsMultipleProviderThreadsPerSession: owner === "shared-provider",
126 + providerSessions:
127 + owner === "provider" || owner === "shared-provider"
128 + ? ([
129 + {
130 + cwd: owner === "shared-provider" ? cwd : nested,
131 + status: "running",
132 + capabilities: {
133 + sessions: {
134 + supportsMultipleProviderThreadsPerSession:
135 + owner === "shared-provider",
136 + },
137 },
138 },
159 - },
160 - ] as never)
161 - : [],
139 + ] as never)
140 + : [],
141 }),
142 }),
143 Layer.mock(CheckpointServiceV2)({
@@ -187,9 +166,7 @@ it.effect.each([
166 Effect.provide(layerTest),
167 );
168 const restoreFiles = owner !== "conversation";
190 - const rejected = !["sibling", "stopped-provider", "shared-provider", "conversation"].includes(
191 - owner,
192 - );
169 + const rejected = !["sibling", "shared-provider", "conversation"].includes(owner);
170 if (rejected) {
171 const error = yield* service
172 .execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles })
apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts
+1 -157
@@ -170,162 +170,8 @@ it.effect.each(["initial", "waiting"])(
170 },
171 );
172
173 -it.effect("rejects a rollback when another provider thread became active", () => {
174 - const threadId = ThreadId.make("thread:rollback-inactive-provider-thread");
175 - const requestedProviderThreadId = ProviderThreadId.make(
176 - "provider-thread:rollback-inactive-provider-thread:requested",
177 - );
178 - const activeProviderThreadId = ProviderThreadId.make(
179 - "provider-thread:rollback-inactive-provider-thread:active",
180 - );
181 - const providerSessionId = ProviderSessionId.make(
182 - "provider-session:rollback-inactive-provider-thread",
183 - );
184 - const checkpointId = CheckpointId.make("checkpoint:rollback-inactive-provider-thread");
185 - const scopeId = CheckpointScopeId.make("checkpoint-scope:rollback-inactive-provider-thread");
186 - const providerInstanceId = ProviderInstanceId.make("provider_rollback_inactive_provider_thread");
187 - const restore = vi.fn(() => Effect.die("checkpoint restore must not run"));
188 - const open = vi.fn(() => Effect.die("provider session open must not run"));
189 - const resolveRuntimePolicy = vi.fn(() => Effect.die("runtime policy resolution must not run"));
190 - const projection = {
191 - thread: {
192 - worktreePath: null,
193 - activeProviderThreadId,
194 - modelSelection: { instanceId: providerInstanceId, model: "test-model" },
195 - },
196 - providerThread: {
197 - id: requestedProviderThreadId,
198 - providerSessionId,
199 - providerInstanceId,
200 - },
201 - checkpoint: { id: checkpointId, scopeId, status: "ready" },
202 - scope: { id: scopeId, cwd: process.cwd() },
203 - } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
204 - const layerTest = layerCheckpointRollbackService.pipe(
205 - Layer.provide(
206 - Layer.mergeAll(
207 - ThreadCommandExecutor.layer,
208 - Layer.mock(CheckpointService.CheckpointServiceV2)({ restore }),
209 - Layer.mock(EventSink.EventSinkV2)({}),
210 - IdAllocator.layer,
211 - Layer.mock(ProjectionStore.ProjectionStoreV2)({
212 - getThread: () => Effect.succeed(projection.thread),
213 - getCheckpointRollbackContext: () => Effect.succeed(projection),
214 - getShellSnapshot: () =>
215 - Effect.succeed({
216 - schemaVersion: 1,
217 - snapshotSequence: 0,
218 - threads: [],
219 - archivedThreads: [],
220 - }),
221 - }),
222 - Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open }),
223 - Layer.mock(RuntimePolicy.RuntimePolicyV2)({ resolve: resolveRuntimePolicy }),
224 - ),
225 - ),
226 - );
227 -
228 - return Effect.gen(function* () {
229 - const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2;
230 - const error = yield* service
231 - .execute({
232 - threadId,
233 - providerThreadId: requestedProviderThreadId,
234 - checkpointId,
235 - scopeId,
236 - })
237 - .pipe(Effect.flip);
238 -
239 - assert.equal(error.reason, "active-provider-changed");
240 - assert.equal(
241 - error.message,
242 - `Active provider changed before rollback target ${checkpointId} could execute on thread ${threadId}.`,
243 - );
244 - assert.equal(error.cause, undefined);
245 - assert.equal(resolveRuntimePolicy.mock.calls.length, 0);
246 - assert.equal(open.mock.calls.length, 0);
247 - assert.equal(restore.mock.calls.length, 0);
248 - }).pipe(Effect.provide(layerTest));
249 -});
250 -
251 -it.effect("rejects an unavailable rollback target before opening a session", () => {
252 - const threadId = ThreadId.make("thread:rollback-provider-turn-unavailable");
253 - const providerThreadId = ProviderThreadId.make(
254 - "provider-thread:rollback-provider-turn-unavailable",
255 - );
256 - const providerSessionId = ProviderSessionId.make(
257 - "provider-session:rollback-provider-turn-unavailable",
258 - );
259 - const checkpointId = CheckpointId.make("checkpoint:rollback-provider-turn-unavailable");
260 - const scopeId = CheckpointScopeId.make("checkpoint-scope:rollback-provider-turn-unavailable");
261 - const providerInstanceId = ProviderInstanceId.make("provider_rollback_provider_turn_unavailable");
262 - const restore = vi.fn(() => Effect.die("checkpoint restore must not run"));
263 - const open = vi.fn(() => Effect.die("provider session open must not run"));
264 - const projection = {
265 - thread: {
266 - worktreePath: "/tmp/missing-invalid-rollback-worktree",
267 - branch: "feature/rollback",
268 - activeProviderThreadId: providerThreadId,
269 - modelSelection: { instanceId: providerInstanceId, model: "test-model" },
270 - },
271 - providerThread: { id: providerThreadId, providerSessionId, providerInstanceId },
272 - providerSession: undefined,
273 - checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: 1 },
274 - scope: { id: scopeId, cwd: process.cwd() },
275 - runsToRollback: [],
276 - targetAttempt: undefined,
277 - rolledBackAttemptIds: [],
278 - staleCheckpoints: [],
279 - providerTurns: [],
280 - } as unknown as ProjectionStore.ProjectionCheckpointRollbackContext;
281 - const layerTest = layerCheckpointRollbackService.pipe(
282 - Layer.provide(
283 - Layer.mergeAll(
284 - ThreadCommandExecutor.layer,
285 - Layer.mock(CheckpointService.CheckpointServiceV2)({ restore }),
286 - Layer.mock(EventSink.EventSinkV2)({}),
287 - IdAllocator.layer,
288 - Layer.mock(ProjectionStore.ProjectionStoreV2)({
289 - getThread: () => Effect.succeed(projection.thread),
290 - getCheckpointRollbackContext: () => Effect.succeed(projection),
291 - getShellSnapshot: () =>
292 - Effect.succeed({
293 - schemaVersion: 1,
294 - snapshotSequence: 0,
295 - threads: [],
296 - archivedThreads: [],
297 - }),
298 - }),
299 - Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
300 - open,
301 - }),
302 - Layer.mock(RuntimePolicy.RuntimePolicyV2)({
303 - resolve: () => Effect.succeed({} as never),
304 - }),
305 - ),
306 - ),
307 - );
308 -
309 - return Effect.gen(function* () {
310 - const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2;
311 - const error = yield* service
312 - .execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles: false })
313 - .pipe(Effect.flip);
314 - assert.equal(open.mock.calls.length, 0);
315 - assert.equal(error.reason, "provider-turn-unavailable");
316 - assert.equal(
317 - error.message,
318 - `Provider turn for rollback target ${checkpointId} is unavailable on provider thread ${providerThreadId}.`,
319 - );
320 - assert.equal(error.cause, undefined);
321 - assert.equal(restore.mock.calls.length, 0);
322 - }).pipe(Effect.provide(layerTest));
323 -});
324 -
173 it.effect.each([
326 - { order: "normal", restoreFiles: true },
174 { order: "cleanup-first", restoreFiles: true },
328 - { order: "cleanup-first", restoreFiles: false },
175 { order: "rollback-first", restoreFiles: true },
176 // A path the server would not have made is left missing, not recreated.
177 { order: "cleanup-first", restoreFiles: false, unmanaged: true },
@@ -495,9 +341,7 @@ it.effect.each([
341 calls,
342 order === "cleanup-first"
343 ? ["cleanup", "prune", "create", ...rollbackCalls]
498 - : order === "rollback-first"
499 - ? [...rollbackCalls, "cleanup"]
500 - : rollbackCalls,
344 + : [...rollbackCalls, "cleanup"],
345 );
346 }).pipe(Effect.provide(testLayer));
347 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
apps/server/src/orchestration-v2/CheckpointService.test.ts
+1 -88
@@ -1,5 +1,5 @@
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 -import { assert, it, vi } from "@effect/vitest";
2 +import { assert, it } from "@effect/vitest";
3 import {
4 CheckpointScopeId,
5 NodeId,
@@ -12,99 +12,12 @@ import {
12 } from "@t3tools/contracts";
13 import * as DateTime from "effect/DateTime";
14 import * as Effect from "effect/Effect";
15 -import * as Exit from "effect/Exit";
15 import * as Layer from "effect/Layer";
16
17 import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
18 import * as CheckpointService from "./CheckpointService.ts";
19 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
20
22 -it.effect.each([false, true, "interrupt"] as const)(
23 - "materializes baseline, lookup fails=%s",
24 - (lookupFails) => {
25 - const scope: OrchestrationV2CheckpointScope = {
26 - id: CheckpointScopeId.make("checkpoint-scope:materialize-baseline"),
27 - threadId: ThreadId.make("thread:materialize-baseline"),
28 - runId: RunId.make("run:materialize-baseline:3"),
29 - nodeId: NodeId.make("node:materialize-baseline:3"),
30 - parentScopeId: null,
31 - providerThreadId: ProviderThreadId.make("provider-thread:materialize-baseline"),
32 - kind: "root_run",
33 - ordinalWithinParent: 0,
34 - advancesAppRunCount: true,
35 - cwd: "/repo",
36 - createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"),
37 - };
38 - const hasCheckpointRef = vi.fn((_input: CheckpointStore.RestoreCheckpointInput) =>
39 - lookupFails === "interrupt"
40 - ? Effect.interrupt
41 - : lookupFails
42 - ? Effect.fail(
43 - new VcsProcessTimeoutError({
44 - operation: "test.ref",
45 - command: "git",
46 - cwd: "/repo",
47 - timeoutMs: 30000,
48 - }),
49 - )
50 - : Effect.succeed(true),
51 - );
52 - const layerTest = CheckpointService.layer.pipe(
53 - Layer.provide(
54 - Layer.mergeAll(
55 - IdAllocator.layer,
56 - Layer.mock(CheckpointStore.CheckpointStore)({
57 - isGitRepository: () => Effect.succeed(true),
58 - hasCheckpointRef,
59 - captureCheckpoint: () => Effect.void,
60 - }),
61 - ),
62 - ),
63 - Layer.provideMerge(NodeCrypto.layer),
64 - );
65 -
66 - return Effect.gen(function* () {
67 - const checkpoints = yield* CheckpointService.CheckpointServiceV2;
68 - if (lookupFails === "interrupt") {
69 - const exit = yield* Effect.exit(
70 - checkpoints.materializeBaselineCheckpoint({ scope, ordinalWithinScope: 2 }),
71 - );
72 - assert.isTrue(Exit.hasInterrupts(exit));
73 - const captureExit = yield* Effect.exit(
74 - checkpoints.capture({
75 - scope,
76 - ordinalWithinScope: 1,
77 - runId: scope.runId!,
78 - nodeId: scope.nodeId!,
79 - appRunOrdinal: 1,
80 - capturedAt: scope.createdAt,
81 - }),
82 - );
83 - assert.isTrue(Exit.hasInterrupts(captureExit));
84 - return;
85 - }
86 - const baseline = yield* checkpoints.materializeBaselineCheckpoint({
87 - scope,
88 - ordinalWithinScope: 2,
89 - });
90 -
91 - assert.equal(baseline.ordinalWithinScope, 2);
92 - assert.equal(
93 - baseline.ref,
94 - yield* CheckpointService.checkpointRefForScopeOrdinal({
95 - scopeId: scope.id,
96 - ordinalWithinScope: 2,
97 - }),
98 - );
99 - assert.equal(baseline.status, lookupFails ? "missing" : "ready");
100 - assert.deepEqual(hasCheckpointRef.mock.calls[0]?.[0], {
101 - cwd: scope.cwd,
102 - checkpointRef: baseline.ref,
103 - });
104 - }).pipe(Effect.provide(layerTest));
105 - },
106 -);
107 -
21 it.effect(
22 "skips unsupported baseline and turn checkpoints without swallowing capture failures",
23 () =>
apps/server/src/orchestration-v2/CommandPolicy.test.ts
-248
@@ -200,222 +200,6 @@ it.each(["/compact", " /LOGOUT "])("queues a steer sent while %s runs", (text) =
200 const layer = it.layer(CommandPolicy.layer);
201
202 layer("CommandPolicyV2", (it) => {
203 - it.effect("reports the actually missing capability across the steering matrix", () =>
204 - Effect.gen(function* () {
205 - const policy = yield* CommandPolicy.CommandPolicyV2;
206 - const providerInstanceId = ProviderInstanceId.make("codex");
207 - const fallbackDetail =
208 - "providerInstanceId cannot steer active turns directly or by interrupt-and-restart";
209 - const forcedRestartDetail =
210 - "providerInstanceId cannot satisfy a required interrupt-and-restart";
211 -
212 - const cases: ReadonlyArray<{
213 - readonly forceRestart: boolean;
214 - readonly supportsActiveSteering: boolean;
215 - readonly supportsInterrupt: boolean;
216 - readonly supportsSteeringByInterruptRestart: boolean;
217 - readonly expected:
218 - | { readonly type: "policy"; readonly value: CommandPolicy.SteeringExecutionPolicyV2 }
219 - | {
220 - readonly type: "error";
221 - readonly capability: CommandPolicy.CommandPolicyCapability;
222 - readonly detail: string;
223 - };
224 - }> = [
225 - {
226 - forceRestart: false,
227 - supportsActiveSteering: true,
228 - supportsInterrupt: false,
229 - supportsSteeringByInterruptRestart: false,
230 - expected: { type: "policy", value: "active_steering" },
231 - },
232 - {
233 - forceRestart: false,
234 - supportsActiveSteering: true,
235 - supportsInterrupt: false,
236 - supportsSteeringByInterruptRestart: true,
237 - expected: { type: "policy", value: "active_steering" },
238 - },
239 - {
240 - forceRestart: false,
241 - supportsActiveSteering: true,
242 - supportsInterrupt: true,
243 - supportsSteeringByInterruptRestart: false,
244 - expected: { type: "policy", value: "active_steering" },
245 - },
246 - {
247 - forceRestart: false,
248 - supportsActiveSteering: true,
249 - supportsInterrupt: true,
250 - supportsSteeringByInterruptRestart: true,
251 - expected: { type: "policy", value: "active_steering" },
252 - },
253 - {
254 - forceRestart: false,
255 - supportsActiveSteering: false,
256 - supportsInterrupt: true,
257 - supportsSteeringByInterruptRestart: true,
258 - expected: { type: "policy", value: "interrupt_restart" },
259 - },
260 - {
261 - forceRestart: false,
262 - supportsActiveSteering: false,
263 - supportsInterrupt: true,
264 - supportsSteeringByInterruptRestart: false,
265 - expected: {
266 - type: "error",
267 - capability: "interrupt_restart_steering",
268 - detail: fallbackDetail,
269 - },
270 - },
271 - {
272 - forceRestart: false,
273 - supportsActiveSteering: false,
274 - supportsInterrupt: false,
275 - supportsSteeringByInterruptRestart: true,
276 - expected: { type: "error", capability: "active_steering", detail: fallbackDetail },
277 - },
278 - {
279 - forceRestart: false,
280 - supportsActiveSteering: false,
281 - supportsInterrupt: false,
282 - supportsSteeringByInterruptRestart: false,
283 - expected: { type: "error", capability: "active_steering", detail: fallbackDetail },
284 - },
285 - {
286 - forceRestart: true,
287 - supportsActiveSteering: true,
288 - supportsInterrupt: true,
289 - supportsSteeringByInterruptRestart: true,
290 - expected: { type: "policy", value: "interrupt_restart" },
291 - },
292 - {
293 - forceRestart: true,
294 - supportsActiveSteering: false,
295 - supportsInterrupt: true,
296 - supportsSteeringByInterruptRestart: true,
297 - expected: { type: "policy", value: "interrupt_restart" },
298 - },
299 - {
300 - forceRestart: true,
301 - supportsActiveSteering: true,
302 - supportsInterrupt: true,
303 - supportsSteeringByInterruptRestart: false,
304 - expected: {
305 - type: "error",
306 - capability: "interrupt_restart_steering",
307 - detail: forcedRestartDetail,
308 - },
309 - },
310 - {
311 - forceRestart: true,
312 - supportsActiveSteering: false,
313 - supportsInterrupt: true,
314 - supportsSteeringByInterruptRestart: false,
315 - expected: {
316 - type: "error",
317 - capability: "interrupt_restart_steering",
318 - detail: forcedRestartDetail,
319 - },
320 - },
321 - {
322 - forceRestart: true,
323 - supportsActiveSteering: true,
324 - supportsInterrupt: false,
325 - supportsSteeringByInterruptRestart: true,
326 - expected: {
327 - type: "error",
328 - capability: "interrupt_restart_steering",
329 - detail: forcedRestartDetail,
330 - },
331 - },
332 - {
333 - forceRestart: true,
334 - supportsActiveSteering: false,
335 - supportsInterrupt: false,
336 - supportsSteeringByInterruptRestart: true,
337 - expected: {
338 - type: "error",
339 - capability: "interrupt_restart_steering",
340 - detail: forcedRestartDetail,
341 - },
342 - },
343 - {
344 - forceRestart: true,
345 - supportsActiveSteering: true,
346 - supportsInterrupt: false,
347 - supportsSteeringByInterruptRestart: false,
348 - expected: {
349 - type: "error",
350 - capability: "interrupt_restart_steering",
351 - detail: forcedRestartDetail,
352 - },
353 - },
354 - {
355 - forceRestart: true,
356 - supportsActiveSteering: false,
357 - supportsInterrupt: false,
358 - supportsSteeringByInterruptRestart: false,
359 - expected: {
360 - type: "error",
361 - capability: "interrupt_restart_steering",
362 - detail: forcedRestartDetail,
363 - },
364 - },
365 - ];
366 -
367 - for (const entry of cases) {
368 - const decision = policy.decideSteeringExecution({
369 - commandId,
370 - threadId,
371 - providerInstanceId,
372 - forceRestart: entry.forceRestart,
373 - capabilities: capabilities((current) => ({
374 - ...current,
375 - turns: {
376 - ...current.turns,
377 - supportsActiveSteering: entry.supportsActiveSteering,
378 - supportsInterrupt: entry.supportsInterrupt,
379 - supportsSteeringByInterruptRestart: entry.supportsSteeringByInterruptRestart,
380 - },
381 - })),
382 - });
383 -
384 - if (entry.expected.type === "policy") {
385 - assert.equal(yield* decision, entry.expected.value);
386 - continue;
387 - }
388 -
389 - const error = yield* decision.pipe(Effect.flip);
390 - assert.instanceOf(error, CommandPolicy.CommandPolicyCapabilityUnsupportedError);
391 - assert.equal(error.commandId, commandId);
392 - assert.equal(error.threadId, threadId);
393 - assert.equal(error.providerInstanceId, providerInstanceId);
394 - assert.equal(error.capability, entry.expected.capability);
395 - assert.equal(error.detail, entry.expected.detail);
396 - }
397 - }),
398 - );
399 -
400 - it.effect("uses a native fork when the provider supports the requested source point", () =>
401 - Effect.gen(function* () {
402 - const policy = yield* CommandPolicy.CommandPolicyV2;
403 -
404 - const result = yield* policy.decideForkExecution({
405 - commandId,
406 - threadId,
407 - providerInstanceId: ProviderInstanceId.make("codex"),
408 - capabilities: CodexProviderCapabilitiesV2,
409 - sameProvider: true,
410 - hasStrongNativeSource: true,
411 - sourceRunStatus: "completed",
412 - fromSpecificTurn: true,
413 - });
414 -
415 - assert.equal(result, "native_fork");
416 - }),
417 - );
418 -
203 it.effect("falls back to portable context when Cursor cannot fork natively", () =>
204 Effect.gen(function* () {
205 const policy = yield* CommandPolicy.CommandPolicyV2;
@@ -434,36 +218,4 @@ layer("CommandPolicyV2", (it) => {
218 assert.equal(result, "portable_context");
219 }),
220 );
437 -
438 - it.effect("returns a typed error when neither native nor portable fork is available", () =>
439 - Effect.gen(function* () {
440 - const policy = yield* CommandPolicy.CommandPolicyV2;
441 -
442 - const error = yield* policy
443 - .decideForkExecution({
444 - commandId,
445 - threadId,
446 - providerInstanceId: ProviderInstanceId.make("cursor"),
447 - capabilities: capabilities((current) => ({
448 - ...current,
449 - threads: {
450 - ...current.threads,
451 - canForkThread: false,
452 - },
453 - context: {
454 - ...current.context,
455 - canConsumeHandoffSummaries: false,
456 - },
457 - })),
458 - sameProvider: true,
459 - hasStrongNativeSource: true,
460 - sourceRunStatus: "completed",
461 - fromSpecificTurn: true,
462 - })
463 - .pipe(Effect.flip);
464 -
465 - assert.instanceOf(error, CommandPolicy.CommandPolicyCapabilityUnsupportedError);
466 - assert.equal(error.capability, "context_handoff");
467 - }),
468 - );
221 });
apps/server/src/orchestration-v2/EffectWorker.test.ts
-75
@@ -475,81 +475,6 @@ it.effect("terminalizes a process-bound claim when success settlement fails", ()
475 }),
476 );
477
478 -it.effect("keeps a process-bound executor failure retryable when retry settlement fails", () =>
479 - Effect.gen(function* () {
480 - const now = DateTime.formatIso(yield* DateTime.now);
481 - const effectId = "effect:worker-process-bound-retry-settlement-failure";
482 - const workerId = "worker-process-bound-retry-settlement-failure";
483 - const claimedEffect: EffectOutbox.OrchestrationEffectV2 = {
484 - id: effectId,
485 - commandId: CommandId.make("command:worker-process-bound-retry-settlement-failure"),
486 - threadId: ThreadId.make("thread:worker-process-bound-retry-settlement-failure"),
487 - request: {
488 - type: "provider-turn.start",
489 - runId: RunId.make("run:worker-process-bound-retry-settlement-failure"),
490 - },
491 - status: "running",
492 - attemptCount: 1,
493 - availableAt: now,
494 - leaseOwner: workerId,
495 - leaseExpiresAt: now,
496 - createdAt: now,
497 - updatedAt: now,
498 - completedAt: null,
499 - lastError: null,
500 - };
501 - const retryAttempts = yield* Ref.make(0);
502 - const terminalizations = yield* Ref.make(0);
503 - const layerOutbox = Layer.mock(EffectOutbox.EffectOutboxV2)({
504 - claimNext: () => Effect.succeed(Option.some(claimedEffect)),
505 - get: () => Effect.succeed(Option.some(claimedEffect)),
506 - awaitCancellation: () => Effect.never,
507 - clearCancellation: () => Effect.void,
508 - retry: () =>
509 - Ref.updateAndGet(retryAttempts, (count) => count + 1).pipe(
510 - Effect.flatMap((attempt) =>
511 - attempt === 1
512 - ? Effect.fail(
513 - new EffectOutbox.EffectOutboxError({
514 - operation: "retry",
515 - effectId,
516 - cause: "simulated retry settlement failure",
517 - }),
518 - )
519 - : Effect.succeed(true),
520 - ),
521 - ),
522 - fail: () => Ref.update(terminalizations, (count) => count + 1).pipe(Effect.as(true)),
523 - });
524 - const layerExecutor = Layer.succeed(
525 - EffectWorker.OrchestrationEffectExecutorV2,
526 - EffectWorker.OrchestrationEffectExecutorV2.of({
527 - execute: () =>
528 - Effect.fail(
529 - new EffectWorker.OrchestrationEffectExecutionError({
530 - effectId,
531 - effectType: claimedEffect.request.type,
532 - cause: "simulated provider execution failure",
533 - }),
534 - ),
535 - }),
536 - );
537 - const layerWorker = EffectWorker.layerWithOptions({ workerId }).pipe(
538 - Layer.provide(Layer.merge(layerOutbox, layerExecutor)),
539 - );
540 -
541 - const exit = yield* EffectWorker.OrchestrationEffectWorkerV2.pipe(
542 - Effect.flatMap((worker) => worker.runOnce),
543 - Effect.provide(layerWorker),
544 - Effect.exit,
545 - );
546 -
547 - assert.isTrue(Exit.isFailure(exit));
548 - assert.equal(yield* Ref.get(retryAttempts), 2);
549 - assert.equal(yield* Ref.get(terminalizations), 0);
550 - }),
551 -);
552 -
478 it.effect("settles a delegated child once its restart continuation fails for good", () =>
479 Effect.gen(function* () {
480 const timestamp = DateTime.formatIso(yield* DateTime.now);
apps/server/src/orchestration-v2/LiveStreamBudget.test.ts
-90
@@ -8,7 +8,6 @@ import * as Stream from "effect/Stream";
8 import { describe, expect } from "vite-plus/test";
9
10 import {
11 - bufferLiveStream,
11 bufferLatestLiveStream,
12 makeLiveStreamBudget,
13 replayAndBufferLiveEvents,
@@ -133,42 +132,6 @@ describe("replayAndBufferLiveEvents", () => {
132 ),
133 );
134
136 - it.effect.each(["items", "bytes"] as const)(
137 - "counts an unacknowledged replay batch toward the live %s limit",
138 - (limit) =>
139 - Effect.scoped(
140 - Effect.gen(function* () {
141 - const pubsub = yield* PubSub.unbounded<Event>();
142 - const subscribed = yield* Deferred.make<PubSub.Subscription<Event>>();
143 - const replayed = { sequence: 1, text: "replay" };
144 - const live = { sequence: 2, text: "live" };
145 - const pull = yield* Stream.toPull(
146 - replayAndBufferLiveEvents(
147 - {
148 - subscribe: PubSub.subscribe(pubsub).pipe(
149 - Effect.tap((subscription) => Deferred.succeed(subscribed, subscription)),
150 - ),
151 - latestSequence: Effect.succeed(1),
152 - replay: () => Stream.succeed(replayed),
153 - },
154 - limit === "items"
155 - ? { maxItems: 1 }
156 - : {
157 - maxSerializedBytes: 40,
158 - },
159 - ),
160 - );
161 - expect(yield* pull).toEqual([replayed]);
162 - yield* PubSub.publish(pubsub, live);
163 - yield* (yield* Deferred.await(subscribed)).shutdownHook.await;
164 - expect(yield* PubSub.size(pubsub)).toBe(0);
165 - const result = yield* pull.pipe(Effect.result);
166 - expect(result._tag).toBe("Failure");
167 - if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
168 - }),
169 - ),
170 - );
171 -
135 it.effect("lets a fast reader replay a database page larger than both buffer limits", () =>
136 Effect.scoped(
137 Effect.gen(function* () {
@@ -229,57 +192,4 @@ describe("replayAndBufferLiveEvents", () => {
192 }),
193 ),
194 );
232 -
233 - it.effect(
234 - "caps raw and projected stages while projection and client acknowledgement are blocked",
235 - () =>
236 - Effect.scoped(
237 - Effect.gen(function* () {
238 - const pubsub = yield* PubSub.unbounded<Event>();
239 - const subscribed = yield* Deferred.make<PubSub.Subscription<Event>>();
240 - const projectionStarted = yield* Deferred.make<void>();
241 - const projectionClosed = yield* Deferred.make<void>();
242 - const releaseProjection = yield* Deferred.make<void>();
243 - const source = replayAndBufferLiveEvents(
244 - {
245 - subscribe: PubSub.subscribe(pubsub).pipe(
246 - Effect.tap((subscription) => Deferred.succeed(subscribed, subscription)),
247 - ),
248 - latestSequence: Effect.succeed(0),
249 - replay: () => Stream.empty,
250 - },
251 - { maxItems: 2 },
252 - ).pipe(
253 - Stream.mapEffect((event) =>
254 - event.sequence === 3
255 - ? Deferred.succeed(projectionStarted, undefined).pipe(
256 - Effect.andThen(Deferred.await(releaseProjection)),
257 - Effect.as(event),
258 - )
259 - : Effect.succeed(event),
260 - ),
261 - Stream.ensuring(Deferred.succeed(projectionClosed, undefined)),
262 - );
263 - const pull = yield* Stream.toPull(bufferLiveStream(source, { maxItems: 2 }));
264 - const firstPull = yield* pull.pipe(Effect.forkScoped);
265 - const subscription = yield* Deferred.await(subscribed);
266 - yield* PubSub.publish(pubsub, { sequence: 1, text: "awaiting ACK" });
267 - expect(yield* Fiber.join(firstPull)).toEqual([{ sequence: 1, text: "awaiting ACK" }]);
268 - yield* PubSub.publish(pubsub, { sequence: 2, text: "projected tail" });
269 - yield* PubSub.publish(pubsub, { sequence: 3, text: "projecting" });
270 - yield* Deferred.await(projectionStarted);
271 - yield* PubSub.publishAll(pubsub, [
272 - { sequence: 4, text: "raw tail" },
273 - { sequence: 5, text: "overflow" },
274 - ]);
275 - yield* subscription.shutdownHook.await;
276 - expect(yield* PubSub.size(pubsub)).toBe(0);
277 - yield* Deferred.succeed(releaseProjection, undefined);
278 - yield* Deferred.await(projectionClosed);
279 - const result = yield* pull.pipe(Effect.result);
280 - expect(result._tag).toBe("Failure");
281 - if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
282 - }),
283 - ),
284 - );
195 });
apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts
-105
@@ -112,19 +112,6 @@ const agentList = (directory: string) => ({
112 ],
113 });
114
115 -const noOpenRequests: ReadonlyArray<ProviderReplayEntry> = [
116 - out("permission.list", { sessionID: SESSION }),
117 - reply("permission.list", { data: [] }),
118 - out("session.form.list", { sessionID: SESSION }),
119 - reply("session.form.list", { data: [] }),
120 -];
121 -const supervisedRules = (name: string) => [
122 - { action: "shell", resource: "*", effect: "ask" },
123 - { action: "edit", resource: "*", effect: "ask" },
124 - { action: "external_directory", resource: "*", effect: "ask" },
125 - ...BUILD_PATHS,
126 - ...mcpRules(name),
127 -];
115 const autoEditRules = (name: string) => [
116 { action: "shell", resource: "*", effect: "ask" },
117 { action: "edit", resource: "*", effect: "allow" },
@@ -180,16 +167,6 @@ const answeredPrompt = (text: string): ReadonlyArray<ProviderReplayEntry> => [
167 event("session.execution.succeeded", { sessionID: SESSION }),
168 ];
169
183 -const directoryModels = (directory: string): ReadonlyArray<ProviderReplayEntry> => [
184 - out("model.list", { "location[directory]": directory }),
185 - reply("model.list", {
186 - location: { directory },
187 - data: [
188 - catalogModel("big-pickle", "Big Pickle"),
189 - catalogModel("mimo-v2.6-flash-free", "MiMo V2.6 Flash Free"),
190 - ],
191 - }),
192 -];
170 /** A `/api/model` entry as 2.0.18 lists it; a known window means no re-read after a turn. */
171 const catalogModel = (id: string, name: string) => ({
172 id,
@@ -375,88 +352,6 @@ describe("OpenCode 2 through the orchestrator", () => {
352 }).pipe(Effect.scoped),
353 );
354
378 - it.effect("gives a session made with older rules T3's rules before its next prompt", () =>
379 - Effect.gen(function* () {
380 - const name = "opencode2-resume-rules";
381 - const before = yield* checkpointWorkspace(`${name}-before`);
382 - const after = yield* checkpointWorkspace(`${name}-after`);
383 - const thread = threadCommands({ name, worktreePath: before });
384 - const projection = yield* runScenario({
385 - name,
386 - threadId: thread.threadId,
387 - entries: [
388 - ...createdSession(before, name),
389 - ...instructionsWritten,
390 - ...answeredPrompt("FIRST"),
391 - ...directoryModels(after),
392 -
393 - out("session.get", { sessionID: SESSION }),
394 - reply(
395 - "session.get",
396 - sessionInfo(
397 - before,
398 - [
399 - { action: "*", resource: "*", effect: "allow" },
400 - { action: "subagent", resource: "*", effect: "deny" },
401 - ],
402 - name,
403 - ),
404 - ),
405 - ...noOpenRequests,
406 - out("session.update", { sessionID: SESSION, permissions: t3Rules(name) }),
407 - reply("session.update", null),
408 - out("session.move", { sessionID: SESSION, directory: after }),
409 - reply("session.move", null),
410 - ...instructionsWritten,
411 - ...answeredPrompt("SECOND"),
412 - ],
413 - commands: [
414 - thread.create,
415 - thread.message("first"),
416 - {
417 - type: "thread.metadata.update",
418 - commandId: thread.command("worktree"),
419 - threadId: thread.threadId,
420 - worktreePath: after,
421 - },
422 - thread.message("second"),
423 - ],
424 - });
425 - assert.deepEqual(
426 - projection.runs.map((run) => run.status),
427 - ["completed", "completed"],
428 - );
429 - }).pipe(Effect.scoped),
430 - );
431 -
432 - it.effect(
433 - "creates a Supervised thread's session with rules that ask before shell and edits",
434 - () =>
435 - Effect.gen(function* () {
436 - const name = "opencode2-supervised-rules";
437 - const cwd = yield* checkpointWorkspace(name);
438 - const thread = threadCommands({
439 - name,
440 - worktreePath: cwd,
441 - runtimeMode: "approval-required",
442 - });
443 - const projection = yield* runScenario({
444 - name,
445 - threadId: thread.threadId,
446 - entries: [
447 - ...createdSession(cwd, name, supervisedRules(name), true),
448 - ...instructionsWritten,
449 - ...answeredPrompt("FIRST"),
450 - ],
451 - commands: [thread.create, thread.message("first")],
452 - });
453 - assert.deepEqual(
454 - projection.runs.map((run) => run.status),
455 - ["completed"],
456 - );
457 - }).pipe(Effect.scoped),
458 - );
459 -
355 it.effect("rewrites the session's rules when the thread's mode changes between turns", () =>
356 Effect.gen(function* () {
357 const name = "opencode2-mode-change";
apps/server/src/orchestration-v2/ProjectCommands.test.ts
-39
@@ -45,22 +45,6 @@ const plan = (command: ProjectCommand, state: Partial<ProjectCommandState> = {})
45 now,
46 });
47
48 -const update = (
49 - fields: Omit<
50 - Extract<ProjectCommand, { type: "project.meta.update" }>,
51 - "type" | "commandId" | "projectId"
52 - >,
53 -) =>
54 - plan(
55 - {
56 - type: "project.meta.update",
57 - commandId: CommandId.make("cmd-update"),
58 - projectId,
59 - ...fields,
60 - },
61 - { project: row() },
62 - );
63 -
48 const payloadOf = (result: ReturnType<typeof plan>) => {
49 assert.isTrue(Result.isSuccess(result));
50 return Result.getOrThrow(result).payload as Record<string, unknown>;
@@ -72,29 +56,6 @@ const failureOf = (result: ReturnType<typeof plan>) => {
56 };
57
58 describe("planProjectCommand", () => {
75 - it("carries every edited field and omits the rest", () => {
76 - const scripts = [script("lint")];
77 - const payload = payloadOf(
78 - update({
79 - scripts,
80 - defaultThreadEnvMode: "worktree",
81 - autoPull: true,
82 - faviconPath: "brand/icon.svg",
83 - projectIcon: { kind: "lucide", name: "alarm-clock", color: "violet" },
84 - }),
85 - );
86 - assert.deepInclude(payload, {
87 - scripts,
88 - defaultThreadEnvMode: "worktree",
89 - autoPull: true,
90 - faviconPath: "brand/icon.svg",
91 - projectIcon: { kind: "lucide", name: "alarm-clock", color: "violet" },
92 - });
93 - const renamed = payloadOf(update({ title: "Renamed" }));
94 - assert.isFalse("defaultThreadEnvMode" in renamed);
95 - assert.isNull(payloadOf(update({ defaultThreadEnvMode: null })).defaultThreadEnvMode);
96 - });
97 -
59 it("keeps legacy scripts editable and removable while rejecting new invalid ones", () => {
60 const legacy = script("install-javascript-dependencies");
61 const withLegacy = (scripts: ReadonlyArray<ProjectScript>) =>
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+2
@@ -1106,6 +1106,7 @@ const assertProjectScopedShells = Effect.fn("assertProjectScopedShells")(functio
1106 });
1107
1108 it.layer(layerTest)("ProjectionStoreV2", (it) => {
1109 + // regression: #21969 keep corrupt plan JSON in the typed read error
1110 it.effect("returns a typed read error for malformed stored plan JSON", () =>
1111 Effect.gen(function* () {
1112 const store = yield* ProjectionStore.ProjectionStoreV2;
@@ -2275,6 +2276,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
2276 }),
2277 );
2278
2279 + // regression: #17141 shell snapshot decoding blocked other database reads
2280 it.effect("reads the shell snapshot first and decodes it in a separate step", () =>
2281 Effect.gen(function* () {
2282 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
apps/server/src/orchestration-v2/ProjectionStore.ts
+1 -1
@@ -680,7 +680,7 @@ function upsertById<T extends { readonly id: string }>(items: ReadonlyArray<T>,
680 return updated;
681 }
682
683 -export function upsertProviderTurn(
683 +function upsertProviderTurn(
684 turns: ReadonlyArray<OrchestrationV2ProviderTurn>,
685 next: OrchestrationV2ProviderTurn,
686 ): Array<OrchestrationV2ProviderTurn> {
apps/server/src/orchestration-v2/ProviderAdapterRegistry.test.ts
-25
@@ -121,31 +121,6 @@ const trackedCreate = <A, E, R>(
121 return yield* effect;
122 });
123
124 -it.effect("closes a partially-created adapter scope immediately on typed failure", () =>
125 - Effect.gen(function* () {
126 - const releases = yield* Ref.make(0);
127 - const createError = new ProviderAdapterDriverCreateError({
128 - driver: lifecycleDriver,
129 - instanceId: lifecycleInstanceId,
130 - detail: "expected test failure",
131 - });
132 -
133 - yield* Effect.scoped(
134 - Effect.gen(function* () {
135 - const exit = yield* ProviderAdapterRegistry.makeRegistryFromConfigMap({
136 - drivers: [makeLifecycleDriver(trackedCreate(releases, Effect.fail(createError)))],
137 - configMap: lifecycleConfigMap,
138 - }).pipe(Effect.exit);
139 -
140 - assert.isTrue(Exit.isFailure(exit));
141 - assert.strictEqual(yield* Ref.get(releases), 1);
142 - }),
143 - );
144 -
145 - assert.strictEqual(yield* Ref.get(releases), 1);
146 - }),
147 -);
148 -
124 it.effect("closes a partially-created adapter scope immediately on interruption", () =>
125 Effect.gen(function* () {
126 const releases = yield* Ref.make(0);
apps/server/src/orchestration-v2/ProviderContinuationService.test.ts
-88
@@ -11,7 +11,6 @@ import {
11 type OrchestrationV2Notification,
12 } from "@t3tools/contracts";
13 import * as Deferred from "effect/Deferred";
14 -import * as DateTime from "effect/DateTime";
14 import * as Effect from "effect/Effect";
15 import * as Exit from "effect/Exit";
16 import * as Layer from "effect/Layer";
@@ -157,31 +156,6 @@ describe("ProviderContinuationService", () => {
156 }),
157 );
158
160 - it.effect("marks an adapter-buffered wake with the provider creation source", () => {
161 - return Effect.gen(function* () {
162 - const dispatched = yield* Queue.unbounded<unknown>();
163 - yield* Effect.gen(function* () {
164 - const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
165 - yield* requests.offer(request());
166 - const command = (yield* Queue.take(dispatched)) as {
167 - readonly creationSource: string;
168 - readonly notification: OrchestrationV2Notification;
169 - };
170 - assert.equal(command.creationSource, "provider");
171 - assert.deepEqual(command.notification, {
172 - source: { kind: "background_task" },
173 - outcome: "updated",
174 - summary: "Background activity updated",
175 - });
176 - }).pipe(
177 - Effect.provide(
178 - layerTest({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
179 - ),
180 - Effect.scoped,
181 - );
182 - });
183 - });
184 -
159 it.effect("delivers a message_text wake as a real prompt, not a buffered wake", () => {
160 return Effect.gen(function* () {
161 const dispatched = yield* Queue.unbounded<unknown>();
@@ -530,47 +504,6 @@ describe("ProviderContinuationService", () => {
504 });
505 });
506
533 - it.effect("drops archived and deleted delegated completions during recovery", () => {
534 - return Effect.gen(function* () {
535 - for (const barrier of ["archivedAt", "deletedAt"] as const) {
536 - const dispatched = yield* Queue.unbounded<unknown>();
537 - yield* Effect.gen(function* () {
538 - const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
539 - yield* requests.offer({
540 - threadId,
541 - providerThreadId,
542 - driver,
543 - detail: null,
544 - delivery: "message_text",
545 - delegatedCompletion: {
546 - parentRunId,
547 - generation: 1,
548 - messageId: delegatedMessageId,
549 - },
550 - });
551 - yield* Effect.yieldNow;
552 - yield* Effect.yieldNow;
553 - assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
554 - }).pipe(
555 - Effect.provide(
556 - layerTest({
557 - dispatched,
558 - getThreadRecords: () =>
559 - Effect.succeed({
560 - ...delegatedProjection(),
561 - thread: {
562 - ...projection.thread,
563 - [barrier]: DateTime.makeUnsafe("2026-08-03T00:00:00.000Z"),
564 - },
565 - } as unknown as OrchestrationV2ThreadProjection),
566 - }),
567 - ),
568 - Effect.scoped,
569 - );
570 - }
571 - });
572 - });
573 -
507 it.effect("dispatches a current request exactly once", () => {
508 return Effect.gen(function* () {
509 const dispatched = yield* Queue.unbounded<unknown>();
@@ -589,27 +522,6 @@ describe("ProviderContinuationService", () => {
522 });
523 });
524
592 - it.effect("drops a request invalidated before dispatch", () => {
593 - return Effect.gen(function* () {
594 - const dispatched = yield* Queue.unbounded<unknown>();
595 - yield* Effect.gen(function* () {
596 - const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
597 - const guard = yield* makeGuard();
598 - const dispatchIfCurrent = yield* guard.capture;
599 - yield* guard.invalidate;
600 - yield* requests.offer(request(dispatchIfCurrent));
601 - yield* Effect.yieldNow;
602 - yield* Effect.yieldNow;
603 - assert.isTrue(Option.isNone(yield* Queue.poll(dispatched)));
604 - }).pipe(
605 - Effect.provide(
606 - layerTest({ dispatched, getThreadRecords: () => Effect.succeed(projection) }),
607 - ),
608 - Effect.scoped,
609 - );
610 - });
611 - });
612 -
525 it.effect("drops a request invalidated while projection is blocked", () => {
526 return Effect.gen(function* () {
527 const dispatched = yield* Queue.unbounded<unknown>();
apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts
+5 -10
@@ -963,7 +963,7 @@ layer("ProviderEventIngestorV2", (it) => {
963 }),
964 );
965
966 - it.effect.each(["completed", "interrupted", "failed", "cancelled", "control"] as const)(
966 + it.effect.each(["interrupted", "control"] as const)(
967 "dismisses only native questions when a provider turn ends with %s",
968 (terminal) =>
969 Effect.gen(function* () {
@@ -1777,20 +1777,15 @@ layer("ProviderEventIngestorV2", (it) => {
1777 }),
1778 );
1779
1780 - it.effect.each(["explicit", "detached", "unchanged", "legacy"])(
1780 + // regression: #20079 the renamed-branch correction must not rewrite a child that needs none
1781 + it.effect.each(["explicit", "detached"])(
1782 "preserves a native child's branch when the checkout needs no correction: %s",
1783 (scenario) =>
1784 Effect.gen(function* () {
1785 const { worktreePath, command } = yield* makeSharedWorktree;
1786 const git = yield* GitVcsDriver.GitVcsDriver;
1786 - const branch =
1787 - scenario === "explicit"
1788 - ? "child-feature"
1789 - : scenario === "legacy"
1790 - ? "t3-abcd1234"
1791 - : "t3/abcd1234";
1792 - if (scenario === "explicit" || scenario === "legacy")
1793 - yield* command(worktreePath, ["branch", "-m", branch]);
1787 + const branch = scenario === "explicit" ? "child-feature" : "t3/abcd1234";
1788 + if (scenario === "explicit") yield* command(worktreePath, ["branch", "-m", branch]);
1789 if (scenario === "detached") yield* command(worktreePath, ["checkout", "--detach"]);
1790 const now = yield* DateTime.now;
1791 const sink = yield* EventSink.EventSinkV2;
apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts
-126
@@ -131,67 +131,6 @@ it.effect("preserves async questions across startup and shutdown", () => {
131 }).pipe(Effect.provide(layer));
132 });
133
134 -it.effect("uses the same reconciliation path to cancel runtime requests during shutdown", () => {
135 - const threadId = ThreadId.make("thread_shutdown_requests");
136 - let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
137 - null;
138 - const projection = {
139 - thread: { id: threadId },
140 - runtimeRequests: [
141 - {
142 - id: RuntimeRequestId.make("request_shutdown"),
143 - nodeId: NodeId.make("node_shutdown"),
144 - status: "pending",
145 - responseCapability: { type: "live" },
146 - },
147 - ],
148 - providerSessions: [],
149 - providerThreads: [],
150 - runs: [],
151 - nodes: [],
152 - } as unknown as OrchestrationV2ThreadProjection;
153 - const layer = ProviderRuntimeRecovery.layer.pipe(
154 - Layer.provide(ServerSettings.layerTest()),
155 - Layer.provide(
156 - Layer.mergeAll(
157 - Layer.mock(ProjectionStore.ProjectionStoreV2)({
158 - getRecoveryThreadIds: () => Effect.succeed([threadId]),
159 - getRuntimeRecoveryProjection: () => Effect.succeed(projection),
160 - }),
161 - Layer.mock(EventSink.EventSinkV2)({
162 - commitCommand: (input) => {
163 - committedInput = input;
164 - return Effect.succeed({ committed: true, cancelledEffectCount: 1 } as never);
165 - },
166 - }),
167 - IdAllocator.layer,
168 - Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
169 - runRecoveryOnce: Effect.succeed(false),
170 - }),
171 - Layer.mock(EffectOutbox.EffectOutboxV2)({
172 - reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
173 - }),
174 - ),
175 - ),
176 - );
177 -
178 - return Effect.gen(function* () {
179 - const summary =
180 - yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("shutdown");
181 - assert.equal(summary.closedRequests, 1);
182 - assert.equal(summary.retiredEffects, 1);
183 - const requestEvent = committedInput?.events[0];
184 - assert.equal(requestEvent?.type, "runtime-request.updated");
185 - if (requestEvent?.type === "runtime-request.updated") {
186 - assert.equal(requestEvent.payload.status, "cancelled");
187 - assert.equal(requestEvent.payload.responseCapability.type, "not_resumable");
188 - if (requestEvent.payload.responseCapability.type === "not_resumable") {
189 - assert.match(requestEvent.payload.responseCapability.reason, /shut down/);
190 - }
191 - }
192 - }).pipe(Effect.provide(layer));
193 -});
194 -
134 it.effect(
135 "preserves a replayable waiting run while cancelling its process-bound background work",
136 () => {
@@ -479,71 +418,6 @@ it.effect("cancels a stale waiting run when no checkpoint capture can finish it"
418 }).pipe(Effect.provide(layer));
419 });
420
482 -it.effect("closes a secret request card's form when its run is recovered", () => {
483 - const threadId = ThreadId.make("thread_secret_recovery");
484 - const runId = RunId.make("run_secret_recovery");
485 - let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
486 - null;
487 - const projection = {
488 - thread: { id: threadId },
489 - runtimeRequests: [],
490 - providerSessions: [],
491 - providerThreads: [],
492 - providerTurns: [],
493 - runs: [{ id: runId, status: "running", providerInstanceId: ProviderInstanceId.make("codex") }],
494 - attempts: [],
495 - nodes: [],
496 - subagents: [],
497 - messages: [],
498 - turnItems: [
499 - {
500 - id: "turn-item:secret-request:recovery",
501 - threadId,
502 - runId,
503 - nodeId: null,
504 - type: "secret_request",
505 - status: "waiting",
506 - secretStatus: "pending",
507 - label: "GitHub token",
508 - reason: "Used as GH_TOKEN.",
509 - },
510 - ],
511 - } as unknown as OrchestrationV2ThreadProjection;
512 - const layer = ProviderRuntimeRecovery.layer.pipe(
513 - Layer.provide(ServerSettings.layerTest()),
514 - Layer.provide(
515 - Layer.mergeAll(
516 - Layer.mock(ProjectionStore.ProjectionStoreV2)({
517 - getRecoveryThreadIds: () => Effect.succeed([threadId]),
518 - getRuntimeRecoveryProjection: () => Effect.succeed(projection),
519 - }),
520 - Layer.mock(EventSink.EventSinkV2)({
521 - commitCommand: (input) => {
522 - committedInput = input;
523 - return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
524 - },
525 - }),
526 - IdAllocator.layer,
527 - Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
528 - runRecoveryOnce: Effect.succeed(false),
529 - }),
530 - Layer.mock(EffectOutbox.EffectOutboxV2)({
531 - listByCommandId: () => Effect.succeed([]),
532 - reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
533 - }),
534 - ),
535 - ),
536 - );
537 -
538 - return Effect.gen(function* () {
539 - yield* (yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService).reconcile("startup");
540 - const itemEvent = committedInput?.events.find((event) => event.type === "turn-item.updated");
541 - const card = itemEvent?.type === "turn-item.updated" ? itemEvent.payload : null;
542 - assert.equal(card?.status, "cancelled");
543 - assert.equal(card?.type === "secret_request" ? card.secretStatus : null, "cancelled");
544 - }).pipe(Effect.provide(layer));
545 -});
546 -
421 it.effect.each(["queued", "preparing"] as const)("recovers $0 work after restart", (status) => {
422 const threadId = ThreadId.make("thread_queued_restart");
423 const runId = RunId.make("run_queued_restart");
apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
+6 -199
@@ -1236,6 +1236,7 @@ it.effect(
1236 }),
1237 );
1238
1239 +// regression: #15571 an interrupted session start did not clean up
1240 it.effect(
1241 "ProviderSessionManagerV2 keeps a shared session busy when a stopped start still ends its turn",
1242 () =>
@@ -1389,48 +1390,6 @@ it.effect("ProviderSessionManagerV2 stops a session still opening when its layer
1390 }),
1391 );
1392
1392 -it.effect("ProviderSessionManagerV2 releases live sessions when its layer shuts down", () =>
1393 - Effect.gen(function* () {
1394 - const state = yield* Ref.make(emptyState);
1395 - const effect = Effect.gen(function* () {
1396 - const eventSink = yield* EventSink.EventSinkV2;
1397 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
1398 - const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
1399 - const now = yield* DateTime.now;
1400 - const threadId = ThreadId.make("thread-provider-session-manager-shutdown");
1401 - const providerSessionId = yield* idAllocator.allocate.providerSession({
1402 - providerInstanceId: modelSelection.instanceId,
1403 - threadId,
1404 - });
1405 -
1406 - yield* eventSink.write({
1407 - events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
1408 - });
1409 - yield* manager.open({
1410 - threadId,
1411 - providerSessionId,
1412 - modelSelection,
1413 - runtimePolicy,
1414 - });
1415 -
1416 - const liveState = yield* Ref.get(state);
1417 - assert.equal(liveState.openCount, 1);
1418 - assert.equal(liveState.closeCount, 0);
1419 - });
1420 -
1421 - yield* effect.pipe(
1422 - Effect.provide(
1423 - layerTest({
1424 - state,
1425 - idleTimeoutMs: 60_000,
1426 - }),
1427 - ),
1428 - );
1429 -
1430 - assert.equal((yield* Ref.get(state)).closeCount, 1);
1431 - }),
1432 -);
1433 -
1393 it.effect("ProviderSessionManagerV2 interrupts event subscriptions on server shutdown", () =>
1394 Effect.gen(function* () {
1395 const state = yield* Ref.make(emptyState);
@@ -1673,17 +1632,6 @@ it.effect("ProviderSessionManagerV2 honors a project browser-access opt-out", ()
1632 }),
1633 );
1634
1676 -it.effect("ProviderSessionManagerV2 honors a project browser-access opt-in", () =>
1677 - Effect.gen(function* () {
1678 - const captured = yield* runBrowserAccessScenario({
1679 - enableAgentBrowserAccess: false,
1680 - projectOverride: true,
1681 - });
1682 - assert.isDefined(captured);
1683 - assert.equal(captured?.browserToolsAvailable, true);
1684 - }),
1685 -);
1686 -
1635 it.effect("ProviderSessionManagerV2 fails browser access closed for a missing project", () =>
1636 Effect.gen(function* () {
1637 const captured = yield* runBrowserAccessScenario({
@@ -1696,18 +1644,6 @@ it.effect("ProviderSessionManagerV2 fails browser access closed for a missing pr
1644 }),
1645 );
1646
1699 -it.effect("ProviderSessionManagerV2 fails browser access closed for a missing thread", () =>
1700 - Effect.gen(function* () {
1701 - const captured = yield* runBrowserAccessScenario({
1702 - enableAgentBrowserAccess: true,
1703 - projectOverride: true,
1704 - createThread: false,
1705 - });
1706 - assert.isDefined(captured);
1707 - assert.equal(captured?.browserToolsAvailable, false);
1708 - }),
1709 -);
1710 -
1647 it.effect("ProviderSessionManagerV2 revokes MCP credentials when release persistence fails", () =>
1648 Effect.gen(function* () {
1649 const state = yield* Ref.make(emptyState);
@@ -1822,6 +1758,7 @@ it.effect(
1758 }),
1759 );
1760
1761 +// regression: #15571 an interrupted session start did not clean up
1762 it.effect(
1763 "ProviderSessionManagerV2 keeps a replacement session's attachment when a stale attach is interrupted",
1764 () =>
@@ -1914,6 +1851,7 @@ it.effect(
1851 }),
1852 );
1853
1854 +// regression: #15571 an interrupted session start did not clean up
1855 it.effect(
1856 "ProviderSessionManagerV2 revokes a reused credential after a resume stopped while checking it",
1857 () =>
@@ -2125,56 +2063,6 @@ it.effect(
2063 }),
2064 );
2065
2128 -it.effect(
2129 - "ProviderSessionManagerV2 revokes a rotated credential despite a stale record on another live session",
2130 - () =>
2131 - Effect.gen(function* () {
2132 - const state = yield* Ref.make(emptyState);
2133 - const mcpConfigs = yield* Ref.make<
2134 - ReadonlyArray<McpProviderSession.McpProviderSessionConfig | undefined>
2135 - >([]);
2136 - const effect = Effect.gen(function* () {
2137 - const eventSink = yield* EventSink.EventSinkV2;
2138 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
2139 - const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
2140 - const registry = yield* McpSessionRegistry.McpSessionRegistry;
2141 - const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
2142 - const now = yield* DateTime.now;
2143 - const threadId = ThreadId.make("thread-provider-session-manager-stale-record");
2144 - const s1 = yield* idAllocator.allocate.providerSession({
2145 - providerInstanceId: modelSelection.instanceId,
2146 - threadId,
2147 - });
2148 - const s2 = yield* idAllocator.allocate.providerSession({
2149 - providerInstanceId: modelSelection.instanceId,
2150 - threadId,
2151 - });
2152 -
2153 - yield* eventSink.write({
2154 - events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
2155 - });
2156 - yield* manager.open({ threadId, providerSessionId: s1, modelSelection, runtimePolicy });
2157 - yield* manager.detach({ providerSessionId: s1, threadId });
2158 -
2159 - yield* registry.revokeThread(threadId);
2160 - yield* manager.open({ threadId, providerSessionId: s2, modelSelection, runtimePolicy });
2161 - const rotated = yield* mcpSessions.read(threadId);
2162 - assert.isDefined(rotated);
2163 - const rotatedToken = rotated?.authorizationHeader.replace(/^Bearer\s+/, "");
2164 - assert.isDefined(yield* registry.resolve(rotatedToken!));
2165 -
2166 - yield* manager.close(s2);
2167 - assert.isUndefined(
2168 - yield* registry.resolve(rotatedToken!),
2169 - "stale record on S1 must not veto revoking S2's rotated credential",
2170 - );
2171 - yield* manager.close(s1);
2172 - });
2173 -
2174 - yield* effect.pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 1_000, mcpConfigs })));
2175 - }),
2176 -);
2177 -
2066 it.effect(
2067 "ProviderSessionManagerV2 protects a reused credential from a predecessor release during open",
2068 () =>
@@ -2410,6 +2298,7 @@ it.effect("ProviderSessionManagerV2 keeps the roster of a runtime whose tasks ca
2298 }),
2299 );
2300
2301 +// regression: #19355 settled and idle-released threads stayed Waiting
2302 it.effect("ProviderSessionManagerV2 keeps a provider update that lands while release clears", () =>
2303 Effect.gen(function* () {
2304 const state = yield* Ref.make(emptyState);
@@ -2564,90 +2453,6 @@ it.effect(
2453 }),
2454 );
2455
2567 -it.effect("ProviderSessionManagerV2 does not apply a stale idle pin to a replacement session", () =>
2568 - Effect.gen(function* () {
2569 - const state = yield* Ref.make(emptyState);
2570 - const firstCheck = yield* Ref.make(true);
2571 - const checkEntered = yield* Deferred.make<void>();
2572 - const checkGate = yield* Deferred.make<void>();
2573 - const effect = Effect.gen(function* () {
2574 - const eventSink = yield* EventSink.EventSinkV2;
2575 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
2576 - const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
2577 - const now = yield* DateTime.now;
2578 - const threadId = yield* idAllocator.allocate.thread({
2579 - fixtureName: "provider-session-manager-stale-pin",
2580 - projectId: yield* idAllocator.allocate.project({
2581 - fixtureName: "provider-session-manager-stale-pin",
2582 - }),
2583 - });
2584 - const providerSessionId = yield* idAllocator.allocate.providerSession({
2585 - providerInstanceId: modelSelection.instanceId,
2586 - threadId,
2587 - });
2588 -
2589 - yield* eventSink.write({
2590 - events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })],
2591 - });
2592 - yield* manager.open({
2593 - threadId,
2594 - providerSessionId,
2595 - modelSelection,
2596 - runtimePolicy,
2597 - });
2598 -
2599 - yield* TestClock.adjust("1 second");
2600 - yield* Deferred.await(checkEntered);
2601 -
2602 - const closeFiber = yield* manager.close(providerSessionId).pipe(Effect.forkDetach);
2603 - for (let i = 0; i < 20; i += 1) {
2604 - yield* Effect.yieldNow;
2605 - }
2606 - yield* manager.open({
2607 - threadId,
2608 - providerSessionId,
2609 - modelSelection,
2610 - runtimePolicy,
2611 - });
2612 - assert.equal((yield* Ref.get(state)).openCount, 2);
2613 -
2614 - yield* Deferred.succeed(checkGate, undefined);
2615 - yield* Fiber.join(closeFiber);
2616 - for (let i = 0; i < 10; i += 1) {
2617 - yield* Effect.yieldNow;
2618 - }
2619 -
2620 - assert.isTrue(Option.isSome(yield* manager.get(providerSessionId)));
2621 - assert.equal((yield* Ref.get(state)).closeCount, 1);
2622 -
2623 - yield* TestClock.adjust("1 second");
2624 - yield* Effect.yieldNow;
2625 - assert.isTrue(Option.isNone(yield* manager.get(providerSessionId)));
2626 - assert.equal((yield* Ref.get(state)).closeCount, 2);
2627 - });
2628 -
2629 - yield* effect.pipe(
2630 - Effect.provide(
2631 - layerTest({
2632 - state,
2633 - idleTimeoutMs: 1000,
2634 - maxIdlePinMs: 60_000,
2635 - hasPendingBackgroundWork: Effect.uninterruptible(
2636 - Effect.gen(function* () {
2637 - if (yield* Ref.getAndSet(firstCheck, false)) {
2638 - yield* Deferred.succeed(checkEntered, undefined);
2639 - yield* Deferred.await(checkGate);
2640 - return true;
2641 - }
2642 - return false;
2643 - }),
2644 - ),
2645 - }),
2646 - ),
2647 - );
2648 - }),
2649 -);
2650 -
2456 it.effect("ProviderSessionManagerV2 releases sessions when provider event streams fail", () =>
2457 Effect.gen(function* () {
2458 const state = yield* Ref.make(emptyState);
@@ -2829,6 +2634,7 @@ it.effect("ProviderSessionManagerV2 retries release records that failed to persi
2634 }),
2635 );
2636
2637 +// regression: #15048 runs got stuck after a failed session release
2638 it.effect("ProviderSessionManagerV2 release retries leave a replacement session alone", () =>
2639 Effect.gen(function* () {
2640 const state = yield* Ref.make(emptyState);
@@ -2901,6 +2707,7 @@ it.effect("ProviderSessionManagerV2 release retries leave a replacement session
2707 }),
2708 );
2709
2710 +// regression: #15048 runs got stuck after a failed session release
2711 it.effect("ProviderSessionManagerV2 keeps each failed release's cleanup", () =>
2712 Effect.gen(function* () {
2713 const state = yield* Ref.make(emptyState);
apps/server/src/orchestration-v2/ProviderSessionTransitionPolicy.test.ts
-63
@@ -63,30 +63,6 @@ it("uses the adapter's selection transition classification", () => {
63 );
64 });
65
66 -it("treats provider option changes as selection changes", () => {
67 - assert.deepEqual(
68 - decideProviderSessionTransition({
69 - current: {
70 - ...base,
71 - modelSelection: {
72 - ...base.modelSelection,
73 - options: [{ id: "reasoningEffort", value: "medium" }],
74 - },
75 - },
76 - target: {
77 - ...base,
78 - modelSelection: {
79 - ...base.modelSelection,
80 - options: [{ id: "reasoningEffort", value: "high" }],
81 - },
82 - available: true,
83 - },
84 - selectionTransition: { type: "apply_on_next_turn" },
85 - }),
86 - { type: "switch_model_in_session" },
87 - );
88 -});
89 -
66 it("restarts compatible instances for workspace or runtime changes", () => {
67 assert.deepEqual(
68 decideProviderSessionTransition({
@@ -97,25 +73,6 @@ it("restarts compatible instances for workspace or runtime changes", () => {
73 );
74 });
75
100 -it("preserves a rejected selection when the workspace also changes", () => {
101 - assert.deepEqual(
102 - decideProviderSessionTransition({
103 - current: base,
104 - target: {
105 - ...base,
106 - modelSelection: { ...base.modelSelection, model: "gpt-5.2-codex" },
107 - workspace: "/other",
108 - available: true,
109 - },
110 - selectionTransition: {
111 - type: "reject",
112 - reason: "The active session cannot apply that model.",
113 - },
114 - }),
115 - { type: "reject", reason: "The active session cannot apply that model." },
116 - );
117 -});
118 -
76 it("preserves handoff and missing-classification outcomes across workspace changes", () => {
77 const target = {
78 ...base,
@@ -154,23 +111,3 @@ it("uses portable handoff for incompatible continuation identities", () => {
111 { type: "create_with_handoff" },
112 );
113 });
157 -
158 -it("uses portable handoff for cross-driver transitions", () => {
159 - const claudeDriver = ProviderDriverKind.make("claude");
160 - assert.deepEqual(
161 - decideProviderSessionTransition({
162 - current: base,
163 - target: {
164 - ...base,
165 - driver: claudeDriver,
166 - continuationIdentity: { driverKind: claudeDriver, continuationKey: "claude:account:one" },
167 - modelSelection: {
168 - instanceId: ProviderInstanceId.make("claude"),
169 - model: "claude-opus-4-1",
170 - },
171 - available: true,
172 - },
173 - }),
174 - { type: "create_with_handoff" },
175 - );
176 -});
apps/server/src/orchestration-v2/ProviderSwitchService.test.ts
-43
@@ -104,49 +104,6 @@ function layerTest(
104 return ProviderSwitch.layer.pipe(Layer.provide(layerRegistry));
105 }
106
107 -it.effect(
108 - "restarts and releases the current session for unsupported in-session model changes",
109 - () =>
110 - Effect.gen(function* () {
111 - const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
112 - const result = yield* service.plan({
113 - projection: projection(),
114 - targetModelSelection: { instanceId: currentInstanceId, model: "gpt-5.2-codex" },
115 - });
116 - assert.equal(result.transition.type, "restart_and_resume");
117 - assert.deepEqual(result.releaseProviderSessionIds, [currentSessionId]);
118 - }).pipe(
119 - Effect.provide(
120 - layerTest({ [currentInstanceId]: { continuationKey: "codex:account:primary" } }),
121 - ),
122 - ),
123 -);
124 -
125 -it.effect.each(["stopped", "error"] as const)(
126 - "restarts and releases the live session when a newer %s session exists",
127 - (deadStatus) =>
128 - Effect.gen(function* () {
129 - const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
130 - const thread = projection();
131 - const result = yield* service.plan({
132 - projection: {
133 - ...thread,
134 - providerSessions: [
135 - ...thread.providerSessions,
136 - deadSessionRecord("dead_session", deadStatus),
137 - ],
138 - },
139 - targetModelSelection: { instanceId: currentInstanceId, model: "gpt-5.2-codex" },
140 - });
141 - assert.equal(result.transition.type, "restart_and_resume");
142 - assert.deepEqual(result.releaseProviderSessionIds, [currentSessionId]);
143 - }).pipe(
144 - Effect.provide(
145 - layerTest({ [currentInstanceId]: { continuationKey: "codex:account:primary" } }),
146 - ),
147 - ),
148 -);
149 -
107 it.effect("releases the newest live session, not the newest record overall", () =>
108 Effect.gen(function* () {
109 const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
+56 -220
@@ -3,7 +3,6 @@ import { expect, it, vi } from "vite-plus/test";
3 import { it as effectIt } from "@effect/vitest";
4 import {
5 CheckpointScopeId,
6 - ContextTransferId,
6 MessageId,
7 NodeId,
8 ProviderSessionId,
@@ -202,23 +201,6 @@ function startWithMissingWorktree(
201 };
202 }
203
205 -it("does not commit running state when inherited background routing cannot be read", async () => {
206 - const worktreePath = `${managedWorktreesDir}/project/feature-restore`;
207 - const harness = startWithMissingWorktree(worktreePath);
208 - const error = await harness.start;
209 -
210 - expect(error._tag).toBe("ProviderTurnStartError");
211 - expect(harness.projectionReads()).toBe(3);
212 - expect(harness.pruneWorktrees).toHaveBeenCalledWith({ cwd: "/tmp/provider-turn-start-project" });
213 - expect(harness.createWorktree).toHaveBeenCalledWith({
214 - cwd: "/tmp/provider-turn-start-project",
215 - refName: "feature/restore",
216 - path: worktreePath,
217 - });
218 - expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
219 - expect(harness.startRootRun).not.toHaveBeenCalled();
220 -});
221 -
204 it.each([
205 {
206 label: "<managed>/<repo>/<branch>",
@@ -816,123 +798,66 @@ effectIt.effect("reads current startup state after waiting for the workspace lea
798 }),
799 );
800
801 +// regression: #15784 superseded provider startups kept running
802 effectIt.effect.each([
820 - { boundary: "policy resolution", nativeMode: "ensure", loss: "replaced" },
821 - { boundary: "policy resolution", nativeMode: "ensure", loss: "interrupted" },
822 - { boundary: "session opening", nativeMode: "ensure", loss: "replaced" },
823 - { boundary: "session opening", nativeMode: "ensure", loss: "interrupted" },
824 - { boundary: "session opening", nativeMode: "resume", loss: "replaced" },
825 - { boundary: "session opening", nativeMode: "fork", loss: "replaced" },
826 -])(
827 - "does not continue $nativeMode startup when $loss during $boundary",
828 - ({ boundary, nativeMode, loss }) =>
829 - Effect.gen(function* () {
830 - const entered = yield* Deferred.make<void>();
831 - const release = yield* Deferred.make<void>();
832 - const gate = Deferred.succeed(entered, undefined).pipe(
833 - Effect.andThen(Deferred.await(release)),
834 - );
835 - const harness = makeLocalCommandHarness({ text: "Continue" });
836 - const projection = harness.projection();
837 - const run = projection.runs[0]!;
838 - const providerThread = projection.providerThreads[0]!;
839 - if (nativeMode === "resume") {
840 - harness.setProjection({
841 - ...projection,
842 - providerThreads: [
843 - {
844 - ...providerThread,
845 - nativeThreadRef: {
846 - driver: providerThread.driver,
847 - nativeId: "existing",
848 - strength: "strong",
849 - },
850 - },
851 - ],
852 - });
853 - } else if (nativeMode === "fork") {
854 - const sourceThreadId = ThreadId.make("fork-source");
855 - harness.getThreadRecords.mockReturnValue(
856 - Effect.succeed({
857 - ...projection,
858 - thread: { ...projection.thread, id: sourceThreadId },
859 - }),
860 - );
861 - harness.setProjection({
862 - ...projection,
863 - contextTransfers: [
864 - {
865 - id: ContextTransferId.make("pending-fork"),
866 - type: "fork",
867 - sourceThreadId,
868 - targetThreadId: projection.thread.id,
869 - sourcePoint: { threadId: sourceThreadId, runId: run.id },
870 - basePoint: null,
871 - sourceProviderInstanceId: run.providerInstanceId,
872 - targetProviderInstanceId: run.providerInstanceId,
873 - targetRunId: run.id,
874 - status: "pending",
875 - resolution: null,
876 - createdBy: "user",
877 - error: null,
878 - createdAt: projection.updatedAt,
879 - updatedAt: projection.updatedAt,
880 - consumedAt: null,
881 - },
882 - ],
883 - });
884 - }
885 - const ensureThread = vi.fn(() => Effect.succeed(providerThread));
886 - const resumeThread = vi.fn(() => Effect.succeed(providerThread));
887 - const forkThread = vi.fn(() => Effect.succeed(providerThread));
888 - harness.open.mockReturnValue(
889 - (boundary === "session opening" ? gate : Effect.void).pipe(
890 - Effect.as({
891 - driver: providerThread.driver,
892 - ensureThread,
893 - resumeThread,
894 - forkThread,
895 - } as never),
896 - ),
803 + { boundary: "policy resolution", loss: "replaced" },
804 + { boundary: "session opening", loss: "interrupted" },
805 +])("does not continue startup when $loss during $boundary", ({ boundary, loss }) =>
806 + Effect.gen(function* () {
807 + const entered = yield* Deferred.make<void>();
808 + const release = yield* Deferred.make<void>();
809 + const gate = Deferred.succeed(entered, undefined).pipe(Effect.andThen(Deferred.await(release)));
810 + const harness = makeLocalCommandHarness({ text: "Continue" });
811 + const projection = harness.projection();
812 + const providerThread = projection.providerThreads[0]!;
813 + const ensureThread = vi.fn(() => Effect.succeed(providerThread));
814 + const resumeThread = vi.fn(() => Effect.succeed(providerThread));
815 + const forkThread = vi.fn(() => Effect.succeed(providerThread));
816 + harness.open.mockReturnValue(
817 + (boundary === "session opening" ? gate : Effect.void).pipe(
818 + Effect.as({
819 + driver: providerThread.driver,
820 + ensureThread,
821 + resumeThread,
822 + forkThread,
823 + } as never),
824 + ),
825 + );
826 + if (boundary === "policy resolution") {
827 + harness.resolveRuntimePolicy.mockReturnValue(
828 + gate.pipe(Effect.as({ cwd: "/tmp/native-account-command" } as never)),
829 );
898 - if (boundary === "policy resolution") {
899 - harness.resolveRuntimePolicy.mockReturnValue(
900 - gate.pipe(Effect.as({ cwd: "/tmp/native-account-command" } as never)),
901 - );
902 - }
830 + }
831
904 - const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true }));
905 - yield* Deferred.await(entered);
906 - const current = harness.projection();
907 - const replacementId = RunAttemptId.make("replacement-attempt");
908 - const updated = {
909 - ...current,
910 - runs: current.runs.map((candidate) =>
911 - loss === "replaced"
912 - ? { ...candidate, activeAttemptId: replacementId }
913 - : { ...candidate, status: "interrupted" as const, completedAt: current.updatedAt },
914 - ),
915 - attempts:
916 - loss === "replaced"
917 - ? [
918 - ...current.attempts,
919 - { ...current.attempts[0]!, id: replacementId, attemptOrdinal: 2 },
920 - ]
921 - : current.attempts,
922 - };
923 - harness.setProjection(updated);
924 - yield* Deferred.succeed(release, undefined);
925 - yield* Fiber.join(startup);
832 + const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true }));
833 + yield* Deferred.await(entered);
834 + const current = harness.projection();
835 + const replacementId = RunAttemptId.make("replacement-attempt");
836 + const updated = {
837 + ...current,
838 + runs: current.runs.map((candidate) =>
839 + loss === "replaced"
840 + ? { ...candidate, activeAttemptId: replacementId }
841 + : { ...candidate, status: "interrupted" as const, completedAt: current.updatedAt },
842 + ),
843 + attempts:
844 + loss === "replaced"
845 + ? [...current.attempts, { ...current.attempts[0]!, id: replacementId, attemptOrdinal: 2 }]
846 + : current.attempts,
847 + };
848 + harness.setProjection(updated);
849 + yield* Deferred.succeed(release, undefined);
850 + yield* Fiber.join(startup);
851
927 - expect(harness.open).toHaveBeenCalledTimes(boundary === "session opening" ? 1 : 0);
928 - expect(ensureThread).not.toHaveBeenCalled();
929 - expect(resumeThread).not.toHaveBeenCalled();
930 - expect(forkThread).not.toHaveBeenCalled();
931 - expect(harness.startRootRun).not.toHaveBeenCalled();
932 - expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
933 - expect(harness.events).toEqual([]);
934 - expect(harness.projection()).toEqual(updated);
935 - }),
852 + expect(harness.open).toHaveBeenCalledTimes(boundary === "session opening" ? 1 : 0);
853 + expect(ensureThread).not.toHaveBeenCalled();
854 + expect(resumeThread).not.toHaveBeenCalled();
855 + expect(forkThread).not.toHaveBeenCalled();
856 + expect(harness.startRootRun).not.toHaveBeenCalled();
857 + expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
858 + expect(harness.events).toEqual([]);
859 + expect(harness.projection()).toEqual(updated);
860 + }),
861 );
862
863 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
937 }),
938 );
939
1015 -effectIt.effect("keeps a session-open failure retryable when terminal persistence fails", () =>
1016 - Effect.gen(function* () {
1017 - const harness = makeLocalCommandHarness({
1018 - text: "Continue",
1019 - openFailure: new Error("provider session rejected"),
1020 - writeFailure: new Error("database unavailable"),
1021 - });
1022 -
1023 - const error = yield* harness.start.pipe(Effect.flip);
1024 -
1025 - expect(error._tag).toBe("ProviderTurnStartError");
1026 - expect(harness.writeIfRunCurrent).toHaveBeenCalledOnce();
1027 - expect(harness.startRootRun).not.toHaveBeenCalled();
1028 - expect(harness.projection().runs.at(-1)?.status).toBe("starting");
1029 - expect(harness.events).toEqual([]);
1030 - }),
1031 -);
1032 -
940 effectIt.effect("does not terminalize a provider-session open interruption", () =>
941 Effect.gen(function* () {
942 const harness = makeLocalCommandHarness({ text: "Continue", interruptOpen: true });
@@ -1068,52 +975,6 @@ effectIt.effect("does not overwrite a run interrupted while its provider session
975 }),
976 );
977
1071 -effectIt.effect("fails a starting run when its last start attempt cannot load the thread", () =>
1072 - Effect.gen(function* () {
1073 - const harness = makeLocalCommandHarness({
1074 - text: "Continue",
1075 - ensureThreadFailure: new Error("Pi RPC read failed: pi process exited with code 1."),
1076 - });
1077 -
1078 - yield* harness.start;
1079 -
1080 - expect(harness.startRootRun).not.toHaveBeenCalled();
1081 - const projection = harness.projection();
1082 - expect(projection.runs.at(-1)).toMatchObject({ status: "failed", startedAt: null });
1083 - expect(projection.attempts[0]).toMatchObject({ status: "failed", startedAt: null });
1084 - expect(projection.nodes[0]).toMatchObject({ status: "failed", startedAt: null });
1085 - expect(projection.turnItems).toMatchObject([
1086 - {
1087 - type: "error",
1088 - title: "Provider turn failed to start",
1089 - failure: {
1090 - class: "provider_error",
1091 - message: "Pi RPC read failed: pi process exited with code 1.",
1092 - },
1093 - },
1094 - ]);
1095 - }),
1096 -);
1097 -
1098 -effectIt.effect(
1099 - "keeps a store failure after the provider loaded the thread typed and retryable",
1100 - () =>
1101 - Effect.gen(function* () {
1102 - const harness = makeLocalCommandHarness({
1103 - text: "Continue",
1104 - historyReadFailureAfterFallback: new Error("database unavailable"),
1105 - });
1106 -
1107 - const error = yield* harness.start.pipe(Effect.flip);
1108 -
1109 - expect(error._tag).toBe("ProviderTurnStartError");
1110 - expect((error.cause as { _tag?: string } | undefined)?._tag).toBe("ProjectionStoreReadError");
1111 - expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
1112 - expect(harness.projection().runs.at(-1)?.status).toBe("starting");
1113 - expect(harness.events).toEqual([]);
1114 - }),
1115 -);
1116 -
978 effectIt.effect("does not mistake a failed state read for a superseded run", () =>
979 Effect.gen(function* () {
980 const harness = makeLocalCommandHarness({ text: "Continue", failReadsAfterRunning: true });
@@ -1164,31 +1025,6 @@ effectIt.effect(
1025 }),
1026 );
1027
1167 -effectIt.effect("persists a failed sign-out without starting a provider turn", () =>
1168 - Effect.gen(function* () {
1169 - const harness = makeLocalCommandHarness({
1170 - text: "/logout",
1171 - logoutFailure: "Could not stop all sessions for this provider. Try again.",
1172 - });
1173 -
1174 - yield* harness.start;
1175 -
1176 - expect(harness.open).not.toHaveBeenCalled();
1177 - expect(harness.startRootRun).not.toHaveBeenCalled();
1178 - expect(harness.projection().runs.at(-1)?.status).toBe("failed");
1179 - expect(harness.projection().turnItems).toMatchObject([
1180 - {
1181 - type: "error",
1182 - title: "Provider sign-out failed",
1183 - failure: {
1184 - class: "permission_error",
1185 - message: "Could not stop all sessions for this provider. Try again.",
1186 - },
1187 - },
1188 - ]);
1189 - }),
1190 -);
1191 -
1028 for (const previousMessages of [[], ["/compact", " /COMPACT "]]) {
1029 effectIt.effect(
1030 `rejects compaction without conversation context after ${previousMessages.length} prior compactions`,
apps/server/src/orchestration-v2/ProviderTurnTokenUsage.test.ts deleted
-43
@@ -1,43 +0,0 @@
1 -import {
2 - NodeId,
3 - type OrchestrationV2ProviderTurn,
4 - ProviderThreadId,
5 - ProviderTurnId,
6 -} from "@t3tools/contracts";
7 -import { assert, describe, it } from "@effect/vitest";
8 -import * as DateTime from "effect/DateTime";
9 -
10 -import { upsertProviderTurn } from "./ProjectionStore.ts";
11 -
12 -describe("provider turn token usage projection", () => {
13 - it("keeps live usage when a terminal update omits it", () => {
14 - const now = DateTime.makeUnsafe("2026-08-29T00:00:00.000Z");
15 - const running = {
16 - id: ProviderTurnId.make("provider-turn-usage"),
17 - providerThreadId: ProviderThreadId.make("provider-thread-usage"),
18 - nodeId: NodeId.make("node-usage"),
19 - runAttemptId: null,
20 - nativeTurnRef: null,
21 - ordinal: 1,
22 - status: "running",
23 - startedAt: now,
24 - completedAt: null,
25 - tokenUsage: {
26 - usedTokens: 50_000,
27 - maxTokens: 200_000,
28 - updatedAt: "2026-08-29T00:00:00.000Z",
29 - },
30 - } satisfies OrchestrationV2ProviderTurn;
31 - const completed = {
32 - ...running,
33 - status: "completed",
34 - completedAt: now,
35 - tokenUsage: undefined,
36 - } satisfies OrchestrationV2ProviderTurn;
37 -
38 - const projected = upsertProviderTurn([running], completed);
39 -
40 - assert.deepEqual(projected[0]?.tokenUsage, running.tokenUsage);
41 - assert.equal(projected[0]?.status, "completed");
42 - });
43 -});
apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts
+1 -17
@@ -14,7 +14,6 @@ import {
14 isAwaitedWork,
15 isRestartNoteContinuation,
16 pendingRestartCancelledBackgroundWork,
17 - restartCancelledBackgroundWorkNote,
17 restartContinuationNote,
18 mergeRestartCancelledBackgroundWork,
19 } from "./RestartBackgroundNote.ts";
@@ -86,22 +85,7 @@ it("delivers a resumed queued run's note even after a higher-ordinal run", () =>
85 );
86 });
87
89 -it("bounds the note so it cannot crowd out the turn's context", () => {
90 - const work = Array.from({ length: 25 }, (_, index) => ({
91 - kind: "shell" as const,
92 - label: `sleep ${index}`,
93 - }));
94 - const note = restartCancelledBackgroundWorkNote(work);
95 - assert.lengthOf(note.split("\n"), 12);
96 - assert.isTrue(note.endsWith("- and 15 more"));
97 - const command = cancelledTurnItemWork({
98 - type: "command_execution",
99 - input: "x".repeat(10_000),
100 - title: null,
101 - } as never);
102 - assert.isAtMost(command?.label.length ?? 0, 160);
103 -});
104 -
88 +// regression: #19750 wake threads whose subagents' background work a restart cut
89 it("names a lost subagent by the id the agent resumes it with", () => {
90 const ownShell = cancelledRosterTaskWork({
91 kind: "command",
apps/server/src/orchestration-v2/RunExecutionService.test.ts
-284
@@ -4,7 +4,6 @@ import {
4 ChatAttachmentId,
5 ChatFileAttachment,
6 CommandId,
7 - EventId,
7 MessageId,
8 NodeId,
9 type OrchestrationV2AppThread,
@@ -1827,26 +1826,6 @@ it.effect.each([null, "run:nested-sdk"] as const)(
1826 }),
1827 );
1828
1830 -it.effect("keeps ingesting until the last of several background items terminalizes", () =>
1831 - Effect.gen(function* () {
1832 - const secondItemId = TurnItemId.make("turn-item:bg-multi:second");
1833 - const observed = yield* runBackgroundItemScenario("bg-multi", (ids) => [
1834 - backgroundTurnItemEvent(ids, "command_execution", "running", 1),
1835 - backgroundTurnItemEvent(ids, "dynamic_tool", "running", 2, secondItemId),
1836 - rootTerminalEvent(ids, "completed"),
1837 - backgroundTurnItemEvent(ids, "command_execution", "completed", 3),
1838 - backgroundTurnItemEvent(ids, "dynamic_tool", "completed", 4, secondItemId),
1839 - ]);
1840 - assert.deepEqual(observed, [
1841 - "turn_item:running",
1842 - "turn_item:running",
1843 - "root-finalized",
1844 - "turn_item:completed",
1845 - "turn_item:completed",
1846 - ]);
1847 - }),
1848 -);
1849 -
1829 it.effect("does not pin ingestion on background items when the root turn is interrupted", () =>
1830 Effect.gen(function* () {
1831 const observed = yield* runBackgroundItemScenario("bg-interrupted", (ids) => [
@@ -1878,27 +1857,6 @@ it.effect("seeds inherited background items before their next update", () =>
1857 }),
1858 );
1859
1881 -it.effect("releases the live run after an inherited background item terminalizes", () =>
1882 - Effect.gen(function* () {
1883 - const key = "inherited-background-terminal";
1884 - const priorRunId = RunId.make(`run:${key}:prior`);
1885 - const observed = yield* runBackgroundItemScenario(
1886 - key,
1887 - (ids) => [
1888 - backgroundTurnItemEventForRun(ids, priorRunId, "subagent", "running", 1),
1889 - rootTerminalEvent(ids, "completed"),
1890 - backgroundTurnItemEventForRun(ids, priorRunId, "subagent", "completed", 2),
1891 - ],
1892 - {
1893 - loadInheritedBackgroundTurnItems: () =>
1894 - Effect.succeed([{ id: TurnItemId.make(`turn-item:${key}`), runId: priorRunId }]),
1895 - },
1896 - );
1897 -
1898 - assert.deepEqual(observed, ["turn_item:running", "root-finalized", "turn_item:completed"]);
1899 - }),
1900 -);
1901 -
1860 it.effect("refreshes inherited background items after event subscription", () =>
1861 Effect.gen(function* () {
1862 const key = "inherited-background-subscription-refresh";
@@ -2391,248 +2349,6 @@ it.effect(
2349 }),
2350 );
2351
2394 -it.effect("cascade helper is provider-neutral for Claude and Codex-shaped child projections", () =>
2395 - Effect.gen(function* () {
2396 - const now = yield* DateTime.now;
2397 - let nextId = 0;
2398 - const allocateEventId = () =>
2399 - Effect.sync(() => EventId.make(`event:cascade-helper:${nextId++}`));
2400 -
2401 - for (const driverKind of [
2402 - ProviderDriverKind.make("claudeAgent"),
2403 - ProviderDriverKind.make("codex"),
2404 - ] as const) {
2405 - const runId = RunId.make(`run:cascade-helper:${driverKind}`);
2406 - const threadId = ThreadId.make(`thread:cascade-helper:${driverKind}`);
2407 - const childThreadId = ThreadId.make(`thread:cascade-helper:${driverKind}:child`);
2408 - const subagentId = NodeId.make(`node:cascade-helper:${driverKind}:subagent`);
2409 - const childNodeId = NodeId.make(`node:cascade-helper:${driverKind}:child-root`);
2410 - const providerInstanceId = ProviderInstanceId.make(String(driverKind));
2411 - const terminalStatus = driverKind === "claudeAgent" ? "failed" : "cancelled";
2412 - const subagent: OrchestrationV2Subagent = {
2413 - id: subagentId,
2414 - threadId,
2415 - runId,
2416 - parentNodeId: NodeId.make(`node:cascade-helper:${driverKind}:root`),
2417 - origin: "provider_native",
2418 - createdBy: "agent",
2419 - driver: driverKind,
2420 - providerInstanceId,
2421 - providerThreadId: null,
2422 - childThreadId,
2423 - nativeTaskRef: {
2424 - driver: driverKind,
2425 - nativeId: `native-${driverKind}`,
2426 - strength: "strong",
2427 - },
2428 - prompt: "hold",
2429 - title: "hold",
2430 - model: null,
2431 - status: "running",
2432 - progress: "partial progress",
2433 - result: "partial result",
2434 - startedAt: now,
2435 - completedAt: null,
2436 - updatedAt: now,
2437 - };
2438 - const turnItem = {
2439 - id: TurnItemId.make(`turn-item:cascade-helper:${driverKind}`),
2440 - threadId,
2441 - runId,
2442 - nodeId: subagentId,
2443 - providerThreadId: null,
2444 - providerTurnId: null,
2445 - nativeItemRef: subagent.nativeTaskRef,
2446 - parentItemId: null,
2447 - ordinal: 3,
2448 - status: "running" as const,
2449 - title: "hold",
2450 - startedAt: now,
2451 - completedAt: null,
2452 - updatedAt: now,
2453 - type: "subagent" as const,
2454 - subagentId,
2455 - origin: "provider_native" as const,
2456 - driver: driverKind,
2457 - providerInstanceId,
2458 - childThreadId,
2459 - prompt: "hold",
2460 - progress: "partial progress",
2461 - result: "partial result",
2462 - } satisfies Extract<OrchestrationV2TurnItem, { type: "subagent" }>;
2463 - const node: OrchestrationV2ExecutionNode = {
2464 - id: subagentId,
2465 - threadId,
2466 - runId,
2467 - parentNodeId: NodeId.make(`node:cascade-helper:${driverKind}:root`),
2468 - rootNodeId: NodeId.make(`node:cascade-helper:${driverKind}:root`),
2469 - kind: "subagent",
2470 - status: "running",
2471 - countsForRun: false,
2472 - providerThreadId: null,
2473 - providerTurnId: null,
2474 - nativeItemRef: subagent.nativeTaskRef,
2475 - runtimeRequestId: null,
2476 - checkpointScopeId: null,
2477 - startedAt: now,
2478 - completedAt: null,
2479 - };
2480 - const openChildNode: OrchestrationV2ExecutionNode = {
2481 - id: childNodeId,
2482 - threadId: childThreadId,
2483 - runId: null,
2484 - parentNodeId: null,
2485 - rootNodeId: childNodeId,
2486 - kind: "root_turn",
2487 - status: "running",
2488 - countsForRun: false,
2489 - providerThreadId: null,
2490 - providerTurnId: null,
2491 - nativeItemRef: null,
2492 - runtimeRequestId: null,
2493 - checkpointScopeId: null,
2494 - startedAt: now,
2495 - completedAt: null,
2496 - };
2497 - const childTurnItem: OrchestrationV2TurnItem =
2498 - driverKind === "claudeAgent"
2499 - ? {
2500 - id: TurnItemId.make(`turn-item:cascade-helper:${driverKind}:child-reasoning`),
2501 - threadId: childThreadId,
2502 - runId: null,
2503 - nodeId: childNodeId,
2504 - providerThreadId: null,
2505 - providerTurnId: null,
2506 - nativeItemRef: null,
2507 - parentItemId: null,
2508 - ordinal: 1,
2509 - status: "running",
2510 - title: "Working",
2511 - startedAt: now,
2512 - completedAt: null,
2513 - updatedAt: now,
2514 - type: "reasoning",
2515 - text: "partial progress",
2516 - streaming: true,
2517 - }
2518 - : {
2519 - id: TurnItemId.make(`turn-item:cascade-helper:${driverKind}:child-command`),
2520 - threadId: childThreadId,
2521 - runId: null,
2522 - nodeId: childNodeId,
2523 - providerThreadId: null,
2524 - providerTurnId: null,
2525 - nativeItemRef: null,
2526 - parentItemId: null,
2527 - ordinal: 1,
2528 - status: "running",
2529 - title: "sleep 300",
2530 - startedAt: now,
2531 - completedAt: null,
2532 - updatedAt: now,
2533 - type: "command_execution",
2534 - input: "sleep 300",
2535 - };
2536 -
2537 - const events = yield* RunExecutionService.cascadeTerminalizeRunOwnedSubagents({
2538 - run: {
2539 - id: runId,
2540 - threadId,
2541 - ordinal: 1,
2542 - providerInstanceId,
2543 - } as OrchestrationV2Run,
2544 - open: {
2545 - subagents: new Map([[subagentId, subagent]]),
2546 - turnItems: new Map([[subagentId, turnItem]]),
2547 - childTurnItems: new Map(),
2548 - nodes: new Map([[subagentId, node]]),
2549 - linkedChildThreadIds: new Set([childThreadId]),
2550 - },
2551 - status: terminalStatus,
2552 - completedAt: now,
2553 - allocateEventId,
2554 - });
2555 -
2556 - assert.equal(events.length, 3, `${driverKind}: subagent + node + turn item`);
2557 - const terminalSubagent = events.find((event) => event.type === "subagent.updated");
2558 - assert.isDefined(terminalSubagent);
2559 - if (terminalSubagent?.type !== "subagent.updated") {
2560 - assert.fail("expected subagent.updated event");
2561 - return;
2562 - }
2563 - assert.equal(terminalSubagent.payload.status, terminalStatus);
2564 - assert.equal(terminalSubagent.payload.childThreadId, childThreadId);
2565 - assert.equal(terminalSubagent.payload.progress, "partial progress");
2566 - assert.equal(terminalSubagent.payload.result, "partial result");
2567 - assert.equal(terminalSubagent.payload.driver, driverKind);
2568 -
2569 - const terminalItem = events.find(
2570 - (event) => event.type === "turn-item.updated" && event.payload.type === "subagent",
2571 - );
2572 - assert.isDefined(terminalItem);
2573 - if (terminalItem?.type !== "turn-item.updated" || terminalItem.payload.type !== "subagent") {
2574 - assert.fail("expected subagent turn-item.updated event");
2575 - return;
2576 - }
2577 - assert.equal(terminalItem.payload.status, terminalStatus);
2578 - assert.equal(terminalItem.payload.childThreadId, childThreadId);
2579 - assert.equal(terminalItem.payload.progress, "partial progress");
2580 - assert.equal(terminalItem.payload.result, "partial result");
2581 -
2582 - const afterTerminalLinkEvents =
2583 - yield* RunExecutionService.cascadeTerminalizeRunOwnedSubagents({
2584 - run: {
2585 - id: runId,
2586 - threadId,
2587 - ordinal: 1,
2588 - providerInstanceId,
2589 - } as OrchestrationV2Run,
2590 - open: {
2591 - subagents: new Map(),
2592 - turnItems: new Map(),
2593 - childTurnItems: new Map([[childTurnItem.id, childTurnItem]]),
2594 - nodes: new Map([[childNodeId, openChildNode]]),
2595 - linkedChildThreadIds: new Set([childThreadId]),
2596 - },
2597 - status: terminalStatus,
2598 - completedAt: now,
2599 - allocateEventId,
2600 - });
2601 - assert.equal(
2602 - afterTerminalLinkEvents.length,
2603 - 2,
2604 - `${driverKind}: linked child node and turn item cascade after link rows terminalize`,
2605 - );
2606 - const cascadedChild = afterTerminalLinkEvents.find((event) => event.type === "node.updated");
2607 - assert.isDefined(cascadedChild);
2608 - if (cascadedChild?.type !== "node.updated") {
2609 - assert.fail("expected node.updated for linked child thread");
2610 - return;
2611 - }
2612 - assert.equal(cascadedChild.payload.id, childNodeId);
2613 - assert.equal(cascadedChild.payload.threadId, childThreadId);
2614 - assert.equal(cascadedChild.payload.status, terminalStatus);
2615 - assert.equal(cascadedChild.payload.kind, "root_turn");
2616 - const cascadedChildTurnItem = afterTerminalLinkEvents.find(
2617 - (event) => event.type === "turn-item.updated",
2618 - );
2619 - assert.isDefined(cascadedChildTurnItem);
2620 - if (cascadedChildTurnItem?.type !== "turn-item.updated") {
2621 - assert.fail("expected turn-item.updated for linked child thread");
2622 - return;
2623 - }
2624 - assert.equal(cascadedChildTurnItem.threadId, childThreadId);
2625 - assert.equal(cascadedChildTurnItem.payload.id, childTurnItem.id);
2626 - assert.equal(cascadedChildTurnItem.payload.status, terminalStatus);
2627 - assert.equal(cascadedChildTurnItem.payload.runId, null);
2628 - assert.equal(cascadedChildTurnItem.payload.type, childTurnItem.type);
2629 - if (cascadedChildTurnItem.payload.type === "reasoning") {
2630 - assert.isFalse(cascadedChildTurnItem.payload.streaming);
2631 - }
2632 - }
2633 - }),
2634 -);
2635 -
2352 it.effect("omits interrupt results and subagent cascade for a superseded attempt", () =>
2353 Effect.gen(function* () {
2354 const { written, observed } = yield* captureRootRunTermination({
apps/server/src/orchestration-v2/RuntimePolicy.test.ts
-12
@@ -108,18 +108,6 @@ const layerTest = RuntimePolicy.layerFromProjectStore.pipe(
108 );
109
110 it.layer(layerTest)("RuntimePolicyV2", (it) => {
111 - it.effect("prefers a provisioned worktree over the project root", () =>
112 - Effect.gen(function* () {
113 - const policy = yield* RuntimePolicy.RuntimePolicyV2;
114 - const now = yield* DateTime.now;
115 - const resolved = yield* policy.resolve({
116 - thread: makeThread({ now, worktreePath: "/project-worktree" }),
117 - modelSelection,
118 - });
119 - assert.equal(resolved.cwd, "/project-worktree");
120 - }),
121 - );
122 -
111 it.effect("runs a mode the provider does not offer in Supervised", () =>
112 Effect.gen(function* () {
113 const policy = yield* RuntimePolicy.RuntimePolicyV2;
apps/server/src/orchestration-v2/RuntimeRequestService.test.ts
-108
@@ -4,7 +4,6 @@ import {
4 ProviderSessionId,
5 RuntimeRequestId,
6 ThreadId,
7 - type OrchestrationV2RuntimeRequest,
7 type OrchestrationV2ThreadProjection,
8 } from "@t3tools/contracts";
9 import * as DateTime from "effect/DateTime";
@@ -17,53 +16,6 @@ import * as ProjectionStore from "./ProjectionStore.ts";
16 import * as ProviderSessionManager from "./ProviderSessionManager.ts";
17 import * as RuntimeRequestService from "./RuntimeRequestService.ts";
18
20 -function projectionWithRuntimeRequest(
21 - runtimeRequest?: OrchestrationV2RuntimeRequest,
22 -): OrchestrationV2ThreadProjection {
23 - return {
24 - runtimeRequests: runtimeRequest === undefined ? [] : [runtimeRequest],
25 - } as unknown as OrchestrationV2ThreadProjection;
26 -}
27 -
28 -function resolvedRuntimeRequest(
29 - requestId: RuntimeRequestId,
30 - providerSessionId: ProviderSessionId,
31 -): OrchestrationV2RuntimeRequest {
32 - return {
33 - id: requestId,
34 - nodeId: NodeId.make(`node-${requestId}`),
35 - providerTurnId: null,
36 - nativeRequestRef: null,
37 - kind: "command",
38 - status: "resolved",
39 - responseCapability: {
40 - type: "live",
41 - providerSessionId,
42 - },
43 - createdAt: DateTime.makeUnsafe("2026-07-29T00:00:00.000Z"),
44 - resolvedAt: DateTime.makeUnsafe("2026-07-29T00:00:01.000Z"),
45 - };
46 -}
47 -
48 -function layerRuntimeRequestTest(
49 - projection: OrchestrationV2ThreadProjection,
50 - getSession: ProviderSessionManager.ProviderSessionManagerV2Shape["get"],
51 -) {
52 - return RuntimeRequestService.layer.pipe(
53 - Layer.provide(
54 - Layer.mergeAll(
55 - Layer.mock(ProjectionStore.ProjectionStoreV2)({
56 - getRuntimeRequest: (_threadId, requestId) =>
57 - Effect.succeed(projection.runtimeRequests.find((request) => request.id === requestId)),
58 - }),
59 - Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
60 - get: getSession,
61 - }),
62 - ),
63 - ),
64 - );
65 -}
66 -
19 it.effect("rejects expired runtime requests before invoking the live adapter", () => {
20 const threadId = ThreadId.make("thread-runtime-request-expired");
21 const providerSessionId = ProviderSessionId.make("provider-session-runtime-request-expired");
@@ -131,63 +83,3 @@ it.effect("rejects expired runtime requests before invoking the live adapter", (
83 assert.equal(respondToRuntimeRequest.mock.calls.length, 0);
84 }).pipe(Effect.provide(layerTest));
85 });
134 -
135 -it.effect("classifies runtime request response validation failures", () => {
136 - const threadId = ThreadId.make("thread-runtime-request-validation");
137 - const providerSessionId = ProviderSessionId.make("provider-session-runtime-request-validation");
138 - const otherProviderSessionId = ProviderSessionId.make(
139 - "provider-session-runtime-request-validation-other",
140 - );
141 - const requestId = RuntimeRequestId.make("request-validation");
142 - const unexpectedGetSession = vi.fn(() => Effect.succeed(Option.none()));
143 - const layerMissing = layerRuntimeRequestTest(
144 - projectionWithRuntimeRequest(),
145 - unexpectedGetSession,
146 - );
147 - const layerNotResumable = layerRuntimeRequestTest(
148 - projectionWithRuntimeRequest(resolvedRuntimeRequest(requestId, otherProviderSessionId)),
149 - unexpectedGetSession,
150 - );
151 - const layerInactive = layerRuntimeRequestTest(
152 - projectionWithRuntimeRequest(resolvedRuntimeRequest(requestId, providerSessionId)),
153 - () => Effect.succeed(Option.none()),
154 - );
155 - const respond = Effect.gen(function* () {
156 - const service = yield* RuntimeRequestService.RuntimeRequestServiceV2;
157 - return yield* service
158 - .respond({
159 - threadId,
160 - providerSessionId,
161 - requestId,
162 - decision: "accept",
163 - })
164 - .pipe(Effect.flip);
165 - });
166 -
167 - return Effect.gen(function* () {
168 - const missing = yield* respond.pipe(Effect.provide(layerMissing));
169 - assert.equal(missing.reason, "request-missing");
170 - assert.equal(
171 - missing.message,
172 - `Runtime request ${requestId} no longer exists on thread ${threadId}.`,
173 - );
174 - assert.isUndefined(missing.cause);
175 -
176 - const notResumable = yield* respond.pipe(Effect.provide(layerNotResumable));
177 - assert.equal(notResumable.reason, "request-not-resumable");
178 - assert.equal(
179 - notResumable.message,
180 - `Runtime request ${requestId} on thread ${threadId} is not resumable on provider session ${providerSessionId}.`,
181 - );
182 - assert.isUndefined(notResumable.cause);
183 -
184 - const inactive = yield* respond.pipe(Effect.provide(layerInactive));
185 - assert.equal(inactive.reason, "provider-session-not-active");
186 - assert.equal(
187 - inactive.message,
188 - `Provider session ${providerSessionId} is not active for runtime request ${requestId} on thread ${threadId}.`,
189 - );
190 - assert.isUndefined(inactive.cause);
191 - assert.equal(unexpectedGetSession.mock.calls.length, 0);
192 - });
193 -});
apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts
+6 -6
@@ -438,12 +438,12 @@ it.live("retries a failed selection restart session open before completing", ()
438 ),
439 );
440
441 -it.live.each(["stopped", "error"] as const)(
442 - "restarts the live session on a model change when a newer %s session record exists",
443 - (deadStatus) =>
441 +it.live(
442 + "restarts the live session on a model change when a newer stopped session record exists",
443 + () =>
444 Effect.scoped(
445 Effect.gen(function* () {
446 - const name = `selection-restart-dead-${deadStatus}`;
446 + const name = "selection-restart-dead-stopped";
447 const cwd = yield* checkpointWorkspace(name);
448 const threadId = ThreadId.make(`thread:${name}`);
449 const state = yield* Ref.make<RestartAdapterState>({
@@ -541,9 +541,9 @@ it.live.each(["stopped", "error"] as const)(
541 occurredAt: deadAt,
542 payload: {
543 ...deadSession,
544 - status: deadStatus,
544 + status: "stopped",
545 updatedAt: deadAt,
546 - lastError: deadStatus === "error" ? "Simulated session failure." : null,
546 + lastError: null,
547 },
548 },
549 ],
apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
+20 -30
@@ -34,31 +34,20 @@ const instanceId = ProviderInstanceId.make("codex");
34 const modelSelection = { instanceId, model: "test-model" };
35
36 it.effect.each(
37 - [false, true]
38 - .flatMap((mailbox) =>
39 - (
40 - [
41 - "before delivery",
42 - "during delivery",
43 - "before dispatch",
44 - "after delivery",
45 - "without native steering",
46 - "with interrupting native steering",
47 - "settled only",
48 - ] as const
49 - ).map((timing) => ({
50 - mailbox,
51 - timing,
52 - label: mailbox ? "mailbox notification" : "steering",
53 - })),
54 - )
55 - .filter(
56 - ({ mailbox, timing }) =>
57 - mailbox ||
58 - (timing !== "without native steering" &&
59 - timing !== "with interrupting native steering" &&
60 - timing !== "settled only"),
61 - ),
37 + (
38 + [
39 + [false, "during delivery"],
40 + [false, "before dispatch"],
41 + [true, "after delivery"],
42 + [true, "without native steering"],
43 + [true, "with interrupting native steering"],
44 + [true, "settled only"],
45 + ] as const
46 + ).map(([mailbox, timing]) => ({
47 + mailbox,
48 + timing,
49 + label: mailbox ? "mailbox notification" : "steering",
50 + })),
51 )("delivers $label when completion wins $timing", ({ mailbox, timing }) =>
52 Effect.scoped(
53 Effect.gen(function* () {
@@ -561,14 +550,15 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function*
550 return { events, started, steered, layer, startFirstTurn };
551 });
552
564 -it.effect.each([{ canRestart: false }, { canRestart: true }])(
565 - "steers a changed turn-scoped selection into the running turn (canRestart=$canRestart)",
566 - ({ canRestart }) =>
553 +// regression: #19210 a provider that can restart the turn must still steer, since restarting ends its native subagents
554 +it.effect(
555 + "steers a changed turn-scoped selection into a running turn the provider could restart",
556 + () =>
557 Effect.scoped(
558 Effect.gen(function* () {
559 const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
570 - `steering-selection-change-${canRestart}`,
571 - canRestart,
560 + "steering-selection-change",
561 + true,
562 );
563 yield* Effect.gen(function* () {
564 const orchestrator = yield* Orchestrator.OrchestratorV2;
apps/server/src/orchestration-v2/ThreadFind.test.ts
-19
@@ -225,25 +225,6 @@ describe("V2 thread find", () => {
225 }).pipe(Effect.provide(layerTest)),
226 );
227
228 - it.effect("returns only a final frame for empty searches and relative navigation", () =>
229 - Effect.gen(function* () {
230 - const projection = yield* setup;
231 - yield* putItems([item("only", 0, "needle needle")]);
232 - const empty = yield* projection
233 - .searchThreadStream({ threadId, query: "missing" })
234 - .pipe(Stream.runCollect);
235 - assert.equal(empty.length, 1);
236 - assert.equal(empty[0]!.totalMatches, 0);
237 - assert.notEqual(empty[0]!.complete, false);
238 - const relative = yield* projection
239 - .searchThreadStream({ threadId, query: "needle", offset: 1 })
240 - .pipe(Stream.runCollect);
241 - assert.equal(relative.length, 1);
242 - assert.equal(relative[0]!.match?.occurrence, 1);
243 - assert.notEqual(relative[0]!.complete, false);
244 - }).pipe(Effect.provide(layerTest)),
245 - );
246 -
228 it.effect("returns bounded navigation counts around the selection, including wraparound", () =>
229 Effect.gen(function* () {
230 const projection = yield* setup;
apps/server/src/orchestration-v2/ThreadFork.execution.test.ts
+7 -8
@@ -26,7 +26,12 @@ import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
26 import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
27 import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
28
29 -const forkCases = (["codex", "claudeAgent"] as const).flatMap((driverName) => {
29 +const forkCases = (
30 + [
31 + ["codex", "interrupted"],
32 + ["claudeAgent", "failed"],
33 + ] as const
34 +).map(([driverName, status]) => {
35 const driver = ProviderDriverKind.make(driverName);
36 const instanceId = ProviderInstanceId.make(driver);
37 const modelSelection = { instanceId, model: "test-model" };
@@ -46,13 +51,7 @@ const forkCases = (["codex", "claudeAgent"] as const).flatMap((driverName) => {
51 { runEffectWorker: false },
52 );
53
49 - return (["failed", "interrupted", "cancelled"] as const).map((status) => ({
50 - driver,
51 - status,
52 - instanceId,
53 - modelSelection,
54 - layer,
55 - }));
54 + return { driver, status, instanceId, modelSelection, layer };
55 });
56
57 it.effect("a persisted fork leaves PR watching with its parent until explicitly opted in", () =>
apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+1 -81
@@ -550,7 +550,7 @@ it.effect("provisions independent launches concurrently instead of behind a glob
550 }),
551 );
552
553 -it.effect.each([" /COMPACT ", "/logout"])(
553 +it.effect.each([" /COMPACT "])(
554 "uses the first conversation message for a title after %s",
555 (nativeCommand) =>
556 Effect.gen(function* () {
@@ -1386,33 +1386,6 @@ it.effect("replays a server-allocated launch", () =>
1386 }),
1387 );
1388
1389 -it.effect("refuses a launch when the project disables the model's provider instance", () => {
1390 - const harness = makeHarness({
1391 - serverSettings: {
1392 - projectSettingsOverrides: {
1393 - [projectId]: { providerInstances: { [modelSelection.instanceId]: { enabled: false } } },
1394 - },
1395 - },
1396 - });
1397 - return Effect.gen(function* () {
1398 - const launches = yield* ThreadLaunch.ThreadLaunchService;
1399 - const failed = yield* launches
1400 - .launch(
1401 - launchInput({
1402 - command: "command:launch:project-disabled-instance",
1403 - thread: "thread:launch:project-disabled-instance",
1404 - message: "Hello",
1405 - }),
1406 - )
1407 - .pipe(Effect.flip);
1408 - if (failed._tag !== "ThreadManagementProviderInstanceDisabledError") {
1409 - assert.fail(`expected ThreadManagementProviderInstanceDisabledError, got ${failed._tag}`);
1410 - }
1411 - assert.equal(failed.projectId, projectId);
1412 - assert.equal(failed.instanceId, modelSelection.instanceId);
1413 - }).pipe(Effect.provide(harness.layer));
1414 -});
1415 -
1389 it.effect("replays an accepted launch after the project disables the instance", () => {
1390 const harness = makeHarness();
1391 return Effect.gen(function* () {
@@ -1475,59 +1448,6 @@ it.effect("rejects a server-allocated launch replay with a mismatching thread id
1448 }).pipe(Effect.provide(harness.layer));
1449 });
1450
1478 -it.effect("rejects a server-allocated launch receipt from another project", () => {
1479 - const harness = makeHarness();
1480 - return Effect.gen(function* () {
1481 - const launches = yield* ThreadLaunch.ThreadLaunchService;
1482 - const { threadId: _unusedThreadId, ...rest } = launchInput({
1483 - command: "command:launch:allocated-wrong-project",
1484 - thread: "unused",
1485 - message: "Wrong project",
1486 - });
1487 - const first = yield* launches.launch(rest);
1488 - const failed = yield* launches
1489 - .launch({
1490 - ...rest,
1491 - projectId: otherProjectId,
1492 - })
1493 - .pipe(Effect.flip);
1494 - if (failed._tag !== "ThreadLaunchError") {
1495 - assert.fail(`expected ThreadLaunchError, got ${failed._tag}`);
1496 - }
1497 - assert.equal(failed.operation, "resolve-project");
1498 - assert.equal(failed.threadId, first.threadId);
1499 - assert.equal(failed.cause, "Project identity changed.");
1500 - }).pipe(Effect.provide(harness.layer));
1501 -});
1502 -
1503 -it.effect("rejects a server-allocated launch retry after the thread is deleted", () => {
1504 - const harness = makeHarness();
1505 - return Effect.gen(function* () {
1506 - const launches = yield* ThreadLaunch.ThreadLaunchService;
1507 - const threads = yield* ThreadManagement.ThreadManagementService;
1508 - const { threadId: _unusedThreadId, ...rest } = launchInput({
1509 - command: "command:launch:allocated-deleted",
1510 - thread: "unused",
1511 - message: "Deleted before retry",
1512 - });
1513 - const first = yield* launches.launch(rest);
1514 - yield* threads.dispatch({
1515 - type: "thread.delete",
1516 - commandId: CommandId.make("command:launch:allocated-deleted:delete"),
1517 - threadId: first.threadId,
1518 - });
1519 - const failed = yield* launches.launch(rest).pipe(Effect.flip);
1520 - if (failed._tag !== "ThreadLaunchError") {
1521 - assert.fail(`expected ThreadLaunchError, got ${failed._tag}`);
1522 - }
1523 - assert.equal(failed.operation, "create-thread");
1524 - assert.equal(failed.threadId, first.threadId);
1525 - assert.equal(failed.cause, "Thread not found.");
1526 - const shells = yield* threads.listProjectThreads({ projectId, includeSubagents: true });
1527 - assert.equal(shells.length, 0);
1528 - }).pipe(Effect.provide(harness.layer));
1529 -});
1530 -
1451 it.effect("does not treat an unrelated accepted command receipt as a launch", () => {
1452 const harness = makeHarness();
1453 return Effect.gen(function* () {
apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.test.ts
-26
@@ -125,32 +125,6 @@ describe("ThreadLiveEventCoalescer", () => {
125 expect(coalesceLiveToolUpdatedEvents(events).map((event) => event.sequence)).toEqual([2, 3, 4]);
126 });
127
128 - it.effect("fails and clears pending updates when their serialized payload fills the budget", () =>
129 - Effect.scoped(
130 - Effect.gen(function* () {
131 - const first = makeToolActivity(1);
132 - const coalescer = yield* makeThreadLiveEventCoalescer({
133 - coalesceWindow: "500 millis",
134 - maxSerializedBytes: Buffer.byteLength(encodeEvent(first)),
135 - });
136 - yield* coalescer.offer(first);
137 - expect(yield* coalescer.usage).toEqual({
138 - retainedItems: 1,
139 - retainedSerializedBytes: Buffer.byteLength(encodeEvent(first)),
140 - });
141 -
142 - const overflow = yield* coalescer.offer(makeToolActivity(2)).pipe(Effect.result);
143 - expect(overflow._tag).toBe("Failure");
144 - yield* coalescer.closed;
145 - expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
146 - const marker = yield* coalescer.offer({ kind: "synchronized" }).pipe(Effect.result);
147 - expect(marker._tag).toBe("Failure");
148 - const delivered = yield* coalescer.stream.pipe(Stream.runCollect, Effect.result);
149 - expect(delivered._tag).toBe("Failure");
150 - }),
151 - ),
152 - );
153 -
128 it.effect("keeps the flush timer alive when an offer's shorter scope closes", () =>
129 Effect.scoped(
130 Effect.gen(function* () {
apps/server/src/orchestration-v2/ThreadManagementService.test.ts
-102
@@ -18,7 +18,6 @@ import * as Layer from "effect/Layer";
18 import * as Queue from "effect/Queue";
19 import * as Stream from "effect/Stream";
20
21 -import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
21 import * as ServerSettings from "../serverSettings.ts";
22 import * as SqlitePersistence from "../persistence/Sqlite.ts";
23 import * as CommandReceiptStore from "./CommandReceiptStore.ts";
@@ -30,43 +29,6 @@ const layerReceiptsTest = CommandReceiptStore.layer.pipe(
29 Layer.provide(SqlitePersistence.layerMemory),
30 );
31
33 -const layerThreadManagementTest = (settingsLayer: ReturnType<typeof ServerSettings.layerTest>) =>
34 - ThreadManagementService.layer.pipe(
35 - Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
36 - Layer.provide(Layer.mock(Orchestrator.OrchestratorV2)({})),
37 - Layer.provide(settingsLayer),
38 - Layer.provide(layerReceiptsTest),
39 - );
40 -
41 -it.effect("refuses a new turn when the project effectively disables the instance", () => {
42 - const projectId = ProjectId.make("project:thread-management:gate-disabled");
43 - const instanceId = ProviderInstanceId.make("codex_work");
44 - const commandId = CommandId.make("command:thread-management:gate-disabled");
45 - const layerTest = layerThreadManagementTest(
46 - ServerSettings.layerTest({
47 - providerInstances: { [instanceId]: { driver: "codex", enabled: true } },
48 - projectSettingsOverrides: {
49 - [projectId]: { providerInstances: { [instanceId]: { enabled: false } } },
50 - },
51 - }),
52 - );
53 -
54 - return Effect.gen(function* () {
55 - const threads = yield* ThreadManagementService.ThreadManagementService;
56 - const error = yield* Effect.flip(
57 - threads.assertProviderInstanceEnabled({ projectId, commandId, instanceId }),
58 - );
59 -
60 - expect(error).toBeInstanceOf(
61 - ThreadManagementService.ThreadManagementProviderInstanceDisabledError,
62 - );
63 - expect(error).toMatchObject({ projectId, instanceId });
64 - expect(error.message).toBe(
65 - `Provider instance "${instanceId}" is disabled for project ${projectId}.`,
66 - );
67 - }).pipe(Effect.provide(layerTest));
68 -});
69 -
32 const layerDispatchChokepointTest =
33 (settingsLayer: ReturnType<typeof ServerSettings.layerTest>) => (dispatched: Array<string>) =>
34 ThreadManagementService.layer.pipe(
@@ -185,39 +147,6 @@ it.effect(
147 },
148 );
149
188 -it.effect("classifies projection infrastructure failures separately from a missing thread", () => {
189 - const projectId = ProjectId.make("project:thread-management:projection-failure");
190 - const threadId = ThreadId.make("thread:thread-management:projection-failure");
191 - const infrastructureCause = new Error("sqlite read failed");
192 - const projectionError = new Orchestrator.OrchestratorProjectionError({
193 - threadId,
194 - cause: infrastructureCause,
195 - });
196 - const layerTest = ThreadManagementService.layer.pipe(
197 - Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
198 - Layer.provide(
199 - Layer.mock(Orchestrator.OrchestratorV2)({
200 - getThreadProjection: () => Effect.fail(projectionError),
201 - }),
202 - ),
203 - Layer.provide(ServerSettings.layerTest()),
204 - Layer.provide(layerReceiptsTest),
205 - );
206 -
207 - return Effect.gen(function* () {
208 - const service = yield* ThreadManagementService.ThreadManagementService;
209 - const error = yield* Effect.flip(service.getProjectThread({ projectId, threadId }));
210 -
211 - expect(error).toBeInstanceOf(ThreadManagementService.ThreadManagementProjectionLoadError);
212 - expect(error).toMatchObject({
213 - projectId,
214 - threadId,
215 - cause: projectionError,
216 - });
217 - expect(error.message).toBe(`Unable to load thread ${threadId} in project ${projectId}.`);
218 - }).pipe(Effect.provide(layerTest));
219 -});
220 -
150 it.effect("uses thread-not-found only after a projection loads outside the project", () => {
151 const projectId = ProjectId.make("project:thread-management:requested");
152 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
179 }).pipe(Effect.provide(layerTest));
180 });
181
253 -it.effect("preserves failed legacy materialization when reading checkpoint context", () => {
254 - const threadId = ThreadId.make("thread:thread-management:checkpoint-import-failure");
255 - const importError = new LegacyV1ThreadImporter.LegacyV1ThreadImportError({
256 - threadId,
257 - operation: "hydrate transcript for",
258 - cause: new Error("checkpoint import failed"),
259 - });
260 - const layerTest = ThreadManagementService.layerWithLegacyImporter.pipe(
261 - Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
262 - Layer.provide(
263 - Layer.mergeAll(
264 - Layer.mock(Orchestrator.OrchestratorV2)({
265 - getCheckpointContext: () =>
266 - Effect.succeed({ runs: [], checkpointScopes: [], checkpoints: [] }),
267 - }),
268 - Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
269 - ensureTranscript: () => Effect.fail(importError),
270 - }),
271 - ),
272 - ),
273 - Layer.provide(ServerSettings.layerTest()),
274 - Layer.provide(layerReceiptsTest),
275 - );
276 - return Effect.gen(function* () {
277 - const service = yield* ThreadManagementService.ThreadManagementService;
278 - const error = yield* service.getCheckpointContext(threadId).pipe(Effect.flip);
279 - expect(error).toBeInstanceOf(Orchestrator.OrchestratorProjectionError);
280 - expect(error).toMatchObject({ threadId, cause: importError });
281 - }).pipe(Effect.provide(layerTest));
282 -});
283 -
182 it.effect("waitForThread follows a restart continuation instead of the cut run", () =>
183 Effect.gen(function* () {
184 const projectId = ProjectId.make("project:thread-management:wait-restart");
apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts
+1 -340
@@ -7,9 +7,6 @@ import {
7 ChatAttachmentId,
8 CommandId,
9 EventId,
10 - MessageId,
11 - ProjectId,
12 - ProviderInstanceId,
10 RuntimeRequestId,
11 ThreadId,
12 TurnItemId,
@@ -29,7 +26,7 @@ import {
26 OrchestratorDispatchError,
27 } from "./Orchestrator.ts";
28 import * as ThreadManagementService from "./ThreadManagementService.ts";
32 -import { dispatchCommand, sendToThread } from "./ThreadMessageIntake.ts";
29 +import { dispatchCommand } from "./ThreadMessageIntake.ts";
30
31 const layerIntakeTest = ServerConfig.layerTest(process.cwd(), {
32 prefix: "t3-question-intake-",
@@ -92,41 +89,6 @@ const answeredRespondEvents = (input: {
89 },
90 ];
91
95 -const textOnlyRespondEvents = (input: {
96 - readonly threadId: ThreadId;
97 - readonly requestId: string;
98 -}): OrchestrationV2StoredEvent[] => [
99 - {
100 - sequence: 1,
101 - commandId: null,
102 - event: {
103 - id: EventId.make("evt-recorded-answer"),
104 - type: "turn-item.updated",
105 - threadId: input.threadId,
106 - occurredAt: NOW,
107 - payload: {
108 - id: TurnItemId.make("item-recorded-answer"),
109 - type: "user_input_request",
110 - threadId: input.threadId,
111 - runId: null,
112 - nodeId: null,
113 - providerThreadId: null,
114 - providerTurnId: null,
115 - nativeItemRef: null,
116 - parentItemId: null,
117 - ordinal: 1,
118 - status: "completed",
119 - title: null,
120 - startedAt: null,
121 - completedAt: NOW,
122 - updatedAt: NOW,
123 - requestId: RuntimeRequestId.make(input.requestId),
124 - questions: [],
125 - },
126 - },
127 - },
128 -];
129 -
92 it.effect("claims question uploads and passes readable paths through the V2 request command", () =>
93 Effect.gen(function* () {
94 const config = yield* ServerConfig.ServerConfig;
@@ -165,71 +127,6 @@ it.effect("claims question uploads and passes readable paths through the V2 requ
127 }).pipe(Effect.provide(layerIntakeTest)),
128 );
129
168 -it.effect("rolls back earlier question claims when a later pending upload is missing", () =>
169 - Effect.gen(function* () {
170 - const config = yield* ServerConfig.ServerConfig;
171 - const threadId = ThreadId.make("thread-q-fail");
172 - const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
173 - const existingId = ChatAttachmentId.make("thread-q-fail-00000000-0000-4000-8000-000000000001");
174 - NodeFS.writeFileSync(
175 - NodePath.join(config.attachmentsDir, `${pendingId}.png`),
176 - new Uint8Array([1, 2, 3]),
177 - );
178 - NodeFS.writeFileSync(
179 - NodePath.join(config.attachmentsDir, `${existingId}.png`),
180 - new Uint8Array([9, 9, 9, 9]),
181 - );
182 - const captured: OrchestrationV2ServerCommand[] = [];
183 - const result = yield* dispatchCommand({
184 - type: "runtime-request.respond",
185 - commandId: CommandId.make("answer-missing-pending"),
186 - threadId,
187 - requestId: RuntimeRequestId.make("request-missing-pending"),
188 - answers: { q1: ["one"], q2: ["two"] },
189 - attachmentsByQuestionId: {
190 - q1: [
191 - {
192 - type: "image",
193 - id: existingId,
194 - name: "keep.png",
195 - mimeType: "image/png",
196 - sizeBytes: 4,
197 - },
198 - {
199 - type: "image",
200 - id: pendingId,
201 - name: "screen.png",
202 - mimeType: "image/png",
203 - sizeBytes: 3,
204 - },
205 - ],
206 - q2: [
207 - {
208 - type: "image",
209 - id: ChatAttachmentId.make(createPendingAttachmentId()!),
210 - name: "gone.png",
211 - mimeType: "image/png",
212 - sizeBytes: 3,
213 - },
214 - ],
215 - },
216 - }).pipe(Effect.provide(layerFailingDispatch(captured)), Effect.result);
217 - expect(result._tag).toBe("Failure");
218 - if (result._tag === "Failure") {
219 - expect(result.failure._tag).toBe("AttachmentClaimError");
220 - }
221 - expect(captured).toHaveLength(0);
222 - expect(NodeFS.readFileSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toEqual(
223 - Buffer.from([1, 2, 3]),
224 - );
225 - expect(
226 - NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
227 - entry.startsWith("thread-q-fail-"),
228 - ),
229 - ).toEqual([`${existingId}.png`]);
230 - }).pipe(Effect.provide(layerIntakeTest)),
231 -);
232 -
130 it.effect("retains claimed copies when dispatch failure may have been accepted", () =>
131 Effect.gen(function* () {
132 const config = yield* ServerConfig.ServerConfig;
@@ -380,166 +277,6 @@ it.effect("releases claimed copies when dispatch replays an earlier accepted res
277 }).pipe(Effect.provide(layerIntakeTest)),
278 );
279
383 -it.effect("releases claimed copies when the recorded answer was text-only", () =>
384 - Effect.gen(function* () {
385 - const config = yield* ServerConfig.ServerConfig;
386 - const threadId = ThreadId.make("thread-text-only-answer");
387 - const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
388 - NodeFS.writeFileSync(
389 - NodePath.join(config.attachmentsDir, `${pendingId}.png`),
390 - new Uint8Array([1, 2, 3]),
391 - );
392 - const storedEvents = textOnlyRespondEvents({
393 - threadId,
394 - requestId: "request-text-only",
395 - });
396 - const result = yield* dispatchCommand({
397 - type: "runtime-request.respond",
398 - commandId: CommandId.make("answer-text-only"),
399 - threadId,
400 - requestId: RuntimeRequestId.make("request-text-only"),
401 - answers: { q: ["one"] },
402 - attachmentsByQuestionId: {
403 - q: [
404 - {
405 - type: "image",
406 - id: pendingId,
407 - name: "screen.png",
408 - mimeType: "image/png",
409 - sizeBytes: 3,
410 - },
411 - ],
412 - },
413 - }).pipe(
414 - Effect.provide(
415 - Layer.mock(ThreadManagementService.ThreadManagementService)({
416 - dispatch: () => Effect.succeed({ sequence: 1, storedEvents }),
417 - }),
418 - ),
419 - Effect.result,
420 - );
421 - expect(result._tag).toBe("Success");
422 - expect(
423 - NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
424 - entry.startsWith("thread-text-only-answer-"),
425 - ),
426 - ).toEqual([]);
427 - expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
428 - }).pipe(Effect.provide(layerIntakeTest)),
429 -);
430 -
431 -it.effect("retains claimed copies referenced by a fresh recorded answer", () =>
432 - Effect.gen(function* () {
433 - const config = yield* ServerConfig.ServerConfig;
434 - const threadId = ThreadId.make("thread-fresh-answer");
435 - const firstId = ChatAttachmentId.make(createPendingAttachmentId()!);
436 - const secondId = ChatAttachmentId.make(createPendingAttachmentId()!);
437 - NodeFS.writeFileSync(
438 - NodePath.join(config.attachmentsDir, `${firstId}.png`),
439 - new Uint8Array([1, 2, 3]),
440 - );
441 - NodeFS.writeFileSync(
442 - NodePath.join(config.attachmentsDir, `${secondId}.png`),
443 - new Uint8Array([7, 7]),
444 - );
445 - const result = yield* dispatchCommand({
446 - type: "runtime-request.respond",
447 - commandId: CommandId.make("answer-fresh"),
448 - threadId,
449 - requestId: RuntimeRequestId.make("request-fresh"),
450 - answers: { q1: ["one"], q2: ["two"] },
451 - attachmentsByQuestionId: {
452 - q1: [
453 - {
454 - type: "image",
455 - id: firstId,
456 - name: "one.png",
457 - mimeType: "image/png",
458 - sizeBytes: 3,
459 - },
460 - ],
461 - q2: [
462 - {
463 - type: "image",
464 - id: secondId,
465 - name: "two.png",
466 - mimeType: "image/png",
467 - sizeBytes: 2,
468 - },
469 - ],
470 - },
471 - }).pipe(
472 - Effect.provide(
473 - Layer.mock(ThreadManagementService.ThreadManagementService)({
474 - dispatch: (command) =>
475 - Effect.succeed({
476 - sequence: 1,
477 - storedEvents: answeredRespondEvents({
478 - threadId,
479 - requestId: "request-fresh",
480 - attachmentsByQuestionId:
481 - command.type === "runtime-request.respond"
482 - ? (command.attachmentsByQuestionId ?? {})
483 - : {},
484 - }),
485 - }),
486 - }),
487 - ),
488 - Effect.result,
489 - );
490 - expect(result._tag).toBe("Success");
491 - expect(
492 - NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
493 - entry.startsWith("thread-fresh-answer-"),
494 - ),
495 - ).toHaveLength(2);
496 - }).pipe(Effect.provide(layerIntakeTest)),
497 -);
498 -
499 -it.effect("releases claimed copies when preparation dies with a defect", () =>
500 - Effect.gen(function* () {
501 - const config = yield* ServerConfig.ServerConfig;
502 - const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
503 - NodeFS.writeFileSync(
504 - NodePath.join(config.attachmentsDir, `${pendingId}.png`),
505 - new Uint8Array([1, 2, 3]),
506 - );
507 - const poisoned = {
508 - get id(): string {
509 - throw new Error("poisoned");
510 - },
511 - };
512 - const captured: OrchestrationV2ServerCommand[] = [];
513 - const result = yield* dispatchCommand({
514 - type: "runtime-request.respond",
515 - commandId: CommandId.make("answer-defect"),
516 - threadId: ThreadId.make("thread-defect"),
517 - requestId: RuntimeRequestId.make("request-defect"),
518 - answers: { q1: ["one"], q2: ["two"] },
519 - attachmentsByQuestionId: {
520 - q1: [
521 - {
522 - type: "image",
523 - id: pendingId,
524 - name: "screen.png",
525 - mimeType: "image/png",
526 - sizeBytes: 3,
527 - },
528 - ],
529 - q2: [poisoned] as never,
530 - },
531 - }).pipe(Effect.provide(layerFailingDispatch(captured)), Effect.exit);
532 - expect(result._tag).toBe("Failure");
533 - expect(captured).toHaveLength(0);
534 - expect(
535 - NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
536 - entry.startsWith("thread-defect-"),
537 - ),
538 - ).toEqual([]);
539 - expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
540 - }).pipe(Effect.provide(layerIntakeTest)),
541 -);
542 -
280 it.effect("a retried response re-claims the preserved pending uploads", () =>
281 Effect.gen(function* () {
282 const config = yield* ServerConfig.ServerConfig;
@@ -622,79 +359,3 @@ it.effect("a retried response re-claims the preserved pending uploads", () =>
359 ).toHaveLength(2);
360 }).pipe(Effect.provide(layerIntakeTest)),
361 );
625 -
626 -it.effect("applies the image budget across all questions before dispatch", () =>
627 - Effect.gen(function* () {
628 - const attachments = Array.from({ length: 5 }, (_, index) => ({
629 - type: "image" as const,
630 - id: ChatAttachmentId.make(`existing-budget-${index}`),
631 - name: `${index}.png`,
632 - mimeType: "image/png",
633 - sizeBytes: 10 * 1024 * 1024,
634 - }));
635 - const captured: OrchestrationV2ServerCommand[] = [];
636 - const result = yield* Effect.exit(
637 - dispatchCommand({
638 - type: "runtime-request.respond",
639 - commandId: CommandId.make("command-image-budget"),
640 - threadId: ThreadId.make("thread-image-budget"),
641 - requestId: RuntimeRequestId.make("question-image-budget"),
642 - answers: {},
643 - attachmentsByQuestionId: { q1: attachments, q2: attachments },
644 - }).pipe(Effect.provide(layerFailingDispatch(captured))),
645 - );
646 - expect(result._tag).toBe("Failure");
647 - if (result._tag === "Failure") expect(String(result.cause)).toContain("80 MiB");
648 - expect(captured).toEqual([]);
649 - }).pipe(Effect.provide(layerIntakeTest)),
650 -);
651 -
652 -it.effect("releases claimed copies when a project disables the message's provider instance", () =>
653 - Effect.gen(function* () {
654 - const config = yield* ServerConfig.ServerConfig;
655 - const pendingId = ChatAttachmentId.make(createPendingAttachmentId()!);
656 - NodeFS.writeFileSync(
657 - NodePath.join(config.attachmentsDir, `${pendingId}.png`),
658 - new Uint8Array([1, 2, 3]),
659 - );
660 - const result = yield* sendToThread({
661 - projectId: ProjectId.make("project-disabled-send"),
662 - commandId: CommandId.make("command-disabled-send"),
663 - threadId: ThreadId.make("thread-disabled-send"),
664 - messageId: MessageId.make("message-disabled-send"),
665 - text: "Hello",
666 - attachments: [
667 - {
668 - type: "image",
669 - id: pendingId,
670 - name: "screen.png",
671 - mimeType: "image/png",
672 - sizeBytes: 3,
673 - },
674 - ],
675 - mode: "auto",
676 - createdBy: "user",
677 - creationSource: "web",
678 - }).pipe(
679 - Effect.provide(
680 - Layer.mock(ThreadManagementService.ThreadManagementService)({
681 - sendToThread: (input) =>
682 - Effect.fail(
683 - new ThreadManagementService.ThreadManagementProviderInstanceDisabledError({
684 - projectId: input.projectId,
685 - instanceId: ProviderInstanceId.make("codex"),
686 - }),
687 - ),
688 - }),
689 - ),
690 - Effect.result,
691 - );
692 - expect(result._tag).toBe("Failure");
693 - expect(
694 - NodeFS.readdirSync(config.attachmentsDir).filter((entry) =>
695 - entry.startsWith("thread-disabled-send-"),
696 - ),
697 - ).toEqual([]);
698 - expect(NodeFS.existsSync(NodePath.join(config.attachmentsDir, `${pendingId}.png`))).toBe(true);
699 - }).pipe(Effect.provide(layerIntakeTest)),
700 -);
apps/server/src/orchestration-v2/ThreadSearch.test.ts
-24
@@ -178,30 +178,6 @@ it.layer(layerTest)("ThreadSearch", (it) => {
178 assert.deepEqual((yield* search.search({ query: "ne%le" })).matches, []);
179 }),
180 );
181 -
182 - it.effect("reports an unreadable match as a decode failure", () =>
183 - Effect.gen(function* () {
184 - const projections = yield* ProjectionStore.ProjectionStoreV2;
185 - const search = yield* ThreadSearch.ThreadSearch;
186 - const sql = yield* SqlClient.SqlClient;
187 - const project = ProjectId.make("project:search-corrupt");
188 - const threadId = ThreadId.make("thread:corrupt");
189 - yield* createProject(project);
190 - yield* Effect.forEach(
191 - [thread(threadId, project), message(threadId, "corrupt", "user", "20260927")],
192 - projections.apply,
193 - { discard: true },
194 - );
195 - yield* sql`
196 - UPDATE orchestration_v2_projection_messages
197 - SET payload_json = json_set(payload_json, '$.text', 20260927)
198 - WHERE message_id = 'corrupt'
199 - `;
200 -
201 - const error = yield* Effect.flip(search.search({ query: "0260927" }));
202 - assert.equal(error.operation, "decode");
203 - }),
204 - );
181 });
182
183 it.effect("searches on the reader worker while the writer is busy", () =>
apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
-25
@@ -724,31 +724,6 @@ describe("ThreadSettlementServiceV2 worker", () => {
724 ),
725 );
726
727 - it.effect("dispatches the last activity time with the v2 snapshot guard", () =>
728 - Effect.scoped(
729 - Effect.gen(function* () {
730 - yield* TestClock.setTime(Date.parse(NOW));
731 - const thread = makeThread("inactive-open-pr", {
732 - branch: "feature",
733 - latestRunCompletedAt: DateTime.makeUnsafe("2026-08-25T00:00:00.000Z"),
734 - });
735 - const fixture = yield* makeHarness({
736 - snapshot: makeSnapshot([thread]),
737 - settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 2 },
738 - branchPullRequest: () => Effect.succeed(makeBranchPullRequest("open")),
739 - });
740 - yield* Effect.gen(function* () {
741 - const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
742 - yield* startHarness(service, fixture.activation, fixture.snapshotReads);
743 - const commands = yield* Ref.get(fixture.commands);
744 - expect(commands).toHaveLength(1);
745 - expect(commands[0]?.settledAt).toEqual(thread.latestRunCompletedAt);
746 - expect(commands[0]?.snapshotAt).toEqual(thread.updatedAt);
747 - }).pipe(Effect.provide(fixture.layer));
748 - }),
749 - ),
750 - );
751 -
727 it.effect("reevaluates immediately after a pull request merge", () =>
728 Effect.scoped(
729 Effect.gen(function* () {
apps/server/src/orchestration-v2/ThreadStream.test.ts
-11
@@ -126,17 +126,6 @@ describe("decideThreadResume", () => {
126 });
127 });
128
129 - it("falls back to a snapshot when the event count exceeds the bound", () => {
130 - expect(
131 - decideThreadResume({
132 - afterSequence: 10,
133 - highWater: 20_000,
134 - replayEventCount: THREAD_RESUME_MAX_REPLAY_EVENTS + 1,
135 - replayEncodedBytes: 1,
136 - }),
137 - ).toEqual({ mode: "snapshot" });
138 - });
139 -
129 it("falls back to a snapshot when encoded replay bytes exceed the bound", () => {
130 expect(
131 decideThreadResume({
apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts
-54
@@ -278,34 +278,6 @@ describe("ThreadTitleRegenerationService", () => {
278 }),
279 );
280
281 - it.effect("keeps the current title when generation returns the fallback", () =>
282 - Effect.gen(function* () {
283 - const harness = makeHarness({
284 - generateTitle: () => Effect.succeed({ title: "New thread" }),
285 - });
286 - yield* Effect.gen(function* () {
287 - const threads = yield* ThreadManagement.ThreadManagementService;
288 - const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
289 - const threadId = yield* createThread({
290 - command: "command:title:fallback:create",
291 - thread: "thread:title:fallback",
292 - });
293 - yield* dispatchUserMessage({
294 - command: "command:title:fallback:message",
295 - threadId,
296 - text: "Some conversation",
297 - });
298 - const requestId = yield* armRegeneration({ command: "command:title:fallback:1", threadId });
299 -
300 - yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } });
301 -
302 - const projection = yield* threads.getThreadProjection(threadId);
303 - assert.equal(projection.thread.title, "Seed title");
304 - assert.isNotOk(projection.thread.titleRegeneration);
305 - }).pipe(Effect.provide(harness.layer));
306 - }),
307 - );
308 -
281 it.effect("clears the marker and keeps the title when generation fails", () =>
282 Effect.gen(function* () {
283 const harness = makeHarness({
@@ -334,30 +306,4 @@ describe("ThreadTitleRegenerationService", () => {
306 }).pipe(Effect.provide(harness.layer));
307 }),
308 );
337 -
338 - it.effect("completes without generating when the initial message is unavailable", () =>
339 - Effect.gen(function* () {
340 - const harness = makeHarness();
341 - yield* Effect.gen(function* () {
342 - const threads = yield* ThreadManagement.ThreadManagementService;
343 - const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService;
344 - const threadId = yield* createThread({
345 - command: "command:title:missing:create",
346 - thread: "thread:title:missing",
347 - });
348 - const requestId = yield* armRegeneration({ command: "command:title:missing:1", threadId });
349 -
350 - yield* titleRegeneration.execute({
351 - threadId,
352 - requestId,
353 - kind: { type: "initial", messageId: MessageId.make("message:title:missing") },
354 - });
355 -
356 - assert.equal(harness.generateThreadTitle.mock.calls.length, 0);
357 - const projection = yield* threads.getThreadProjection(threadId);
358 - assert.equal(projection.thread.title, "Seed title");
359 - assert.isNotOk(projection.thread.titleRegeneration);
360 - }).pipe(Effect.provide(harness.layer));
361 - }),
362 - );
309 });
apps/server/src/orchestration-v2/ThreadTransportPerformance.test.ts
-121
@@ -1,13 +1,9 @@
1 import {
2 EventId,
3 OrchestrationV2RpcSchemas,
4 - ProjectId,
5 - ProviderInstanceId,
4 ThreadId,
5 TurnItemId,
8 - type OrchestrationV2ProjectedTurnItem,
6 type OrchestrationV2DomainEvent,
10 - type OrchestrationV2ThreadProjection,
7 type OrchestrationV2ThreadStreamItem,
8 type OrchestrationV2TurnItem,
9 } from "@t3tools/contracts";
@@ -16,21 +12,12 @@ import * as Schema from "effect/Schema";
12 import type * as RpcMessage from "effect/rpc/RpcMessage";
13 import { describe, expect, it } from "vite-plus/test";
14
19 -import { buildBoundedThreadStreamSnapshot } from "./ThreadStream.ts";
20 -import { buildBoundedThreadProjection } from "./threadHistoryPaging.ts";
15 import { projectDomainEventForWire } from "./WireProjection.ts";
16
23 -const SNAPSHOT_SEQUENCE = 600;
24 -const ROW_COUNT = 600;
17 const OUTPUT_BYTES_PER_ROW = 8_192;
18 const NOW = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
19 const THREAD_ID = ThreadId.make("thread-perf");
28 -const PROVIDER_INSTANCE_ID = ProviderInstanceId.make("codex");
20
30 -const HISTORICAL_FULL_SNAPSHOT_APPLICATION_BYTES = 10_375_079;
31 -const FULL_SNAPSHOT_RPC_JSON_BYTES = 10_375_121;
32 -const PRE_OMISSION_BOUNDED_SNAPSHOT_RPC_JSON_BYTES = 1_038_647;
33 -const MAX_PROJECTED_BOUNDED_SNAPSHOT_RPC_JSON_BYTES = 131_072;
21 const PRE_OMISSION_COMMAND_EVENT_RPC_JSON_BYTES = 8_790;
22 const MAX_PROJECTED_COMMAND_EVENT_RPC_JSON_BYTES = 1_024;
23
@@ -74,69 +61,6 @@ function makeCommandItem(index: number): OrchestrationV2TurnItem {
61 };
62 }
63
77 -function makeProjection(): OrchestrationV2ThreadProjection {
78 - const visibleTurnItems: OrchestrationV2ProjectedTurnItem[] = Array.from(
79 - { length: ROW_COUNT },
80 - (_, index) => {
81 - const item = makeCommandItem(index);
82 - return {
83 - position: index,
84 - visibility: "local",
85 - sourceThreadId: THREAD_ID,
86 - sourceItemId: item.id,
87 - item,
88 - };
89 - },
90 - );
91 -
92 - return {
93 - thread: {
94 - id: THREAD_ID,
95 - projectId: ProjectId.make("project-perf"),
96 - title: "Thread",
97 - providerInstanceId: PROVIDER_INSTANCE_ID,
98 - modelSelection: { instanceId: PROVIDER_INSTANCE_ID, model: "gpt-5" },
99 - runtimeMode: "full-access",
100 - interactionMode: "default",
101 - branch: null,
102 - worktreePath: null,
103 - activeProviderThreadId: null,
104 - lineage: {
105 - parentThreadId: null,
106 - relationshipToParent: null,
107 - rootThreadId: THREAD_ID,
108 - },
109 - forkedFrom: null,
110 - createdBy: "user",
111 - creationSource: "web",
112 - createdAt: NOW,
113 - updatedAt: NOW,
114 - archivedAt: null,
115 - deletedAt: null,
116 - settledOverride: null,
117 - settledAt: null,
118 - lastVisitedAt: null,
119 - },
120 - runs: [],
121 - attempts: [],
122 - nodes: [],
123 - subagents: [],
124 - providerSessions: [],
125 - providerThreads: [],
126 - providerTurns: [],
127 - runtimeRequests: [],
128 - messages: [],
129 - plans: [],
130 - turnItems: visibleTurnItems.map((row) => row.item),
131 - checkpointScopes: [],
132 - checkpoints: [],
133 - contextHandoffs: [],
134 - contextTransfers: [],
135 - visibleTurnItems,
136 - updatedAt: NOW,
137 - };
138 -}
139 -
64 function makeTurnItemEvent(item: OrchestrationV2TurnItem): OrchestrationV2DomainEvent {
65 return {
66 id: EventId.make(`event-${item.id}`),
@@ -148,51 +72,6 @@ function makeTurnItemEvent(item: OrchestrationV2TurnItem): OrchestrationV2Domain
72 }
73
74 describe("thread transport payload budget", () => {
151 - it("records full, bounded, and payload-omitting snapshot improvements", () => {
152 - const projection = makeProjection();
153 - const historicalFullSnapshot: OrchestrationV2ThreadStreamItem = {
154 - kind: "snapshot",
155 - snapshotSequence: SNAPSHOT_SEQUENCE,
156 - projection,
157 - };
158 - const preOmissionBounded = buildBoundedThreadProjection({
159 - projection,
160 - snapshotSequence: SNAPSHOT_SEQUENCE,
161 - });
162 - const preOmissionBoundedSnapshot: OrchestrationV2ThreadStreamItem = {
163 - kind: "snapshot",
164 - snapshotSequence: SNAPSHOT_SEQUENCE,
165 - projection: preOmissionBounded.projection,
166 - historyCursor: preOmissionBounded.historyCursor,
167 - hasMoreHistory: preOmissionBounded.hasMoreHistory,
168 - latestLocalTurnOrdinal: preOmissionBounded.latestLocalTurnOrdinal,
169 - payloadBudgetExceeded: preOmissionBounded.payloadBudgetExceeded,
170 - };
171 - const projectedBoundedSnapshot = buildBoundedThreadStreamSnapshot({
172 - projection,
173 - snapshotSequence: SNAPSHOT_SEQUENCE,
174 - });
175 -
176 - const historicalApplicationBytes = encodedBytes(historicalFullSnapshot);
177 - const fullRpcJsonBytes = encodedThreadStreamChunkBytes(historicalFullSnapshot);
178 - const preOmissionBoundedRpcJsonBytes = encodedThreadStreamChunkBytes(
179 - preOmissionBoundedSnapshot,
180 - );
181 - const projectedBoundedRpcJsonBytes = encodedThreadStreamChunkBytes(projectedBoundedSnapshot);
182 -
183 - expect(historicalApplicationBytes).toBe(HISTORICAL_FULL_SNAPSHOT_APPLICATION_BYTES);
184 - expect(fullRpcJsonBytes).toBe(FULL_SNAPSHOT_RPC_JSON_BYTES);
185 - expect(preOmissionBoundedRpcJsonBytes).toBe(PRE_OMISSION_BOUNDED_SNAPSHOT_RPC_JSON_BYTES);
186 - expect(projectedBoundedRpcJsonBytes).toBeLessThanOrEqual(
187 - MAX_PROJECTED_BOUNDED_SNAPSHOT_RPC_JSON_BYTES,
188 - );
189 - expect(projectedBoundedRpcJsonBytes / fullRpcJsonBytes).toBeLessThanOrEqual(0.02);
190 - expect(preOmissionBoundedSnapshot.projection.visibleTurnItems).toHaveLength(60);
191 - expect(projectedBoundedSnapshot.projection.visibleTurnItems).toHaveLength(75);
192 - expect(projectedBoundedSnapshot.hasMoreHistory).toBe(true);
193 - expect(projectedBoundedSnapshot.payloadBudgetExceeded).toBe(false);
194 - });
195 -
75 it("omits command output from a live event without changing persisted source data", () => {
76 const sourceItem = makeCommandItem(0);
77 const sourceEvent = makeTurnItemEvent(sourceItem);
apps/server/src/orchestration-v2/WireProjection.test.ts
-28
@@ -94,23 +94,6 @@ describe("orchestration V2 wire projection", () => {
94 expect(item.output.data).toBe("private-image-data");
95 });
96
97 - it("preserves provider notices in bounded items and live events", () => {
98 - const item = {
99 - ...base,
100 - type: "system_notice" as const,
101 - message: "Safeguards flagged this message. Switched to Opus 4.8.",
102 - };
103 - expect(projectTurnItemForWire(item)).toEqual(item);
104 - const event = {
105 - id: EventId.make("notice-wire-event"),
106 - type: "turn-item.updated" as const,
107 - threadId: item.threadId,
108 - occurredAt: item.updatedAt,
109 - payload: item,
110 - };
111 - expect(projectDomainEventForWire(event)).toEqual(event);
112 - });
113 -
97 it("keeps transcript bodies out of shell rows", () => {
98 const now = DateTime.makeUnsafe("2026-08-13T00:00:00.000Z");
99 const threadId = ThreadId.make("thread-shell-budget");
@@ -166,17 +149,6 @@ describe("orchestration V2 wire projection", () => {
149 expect(JSON.stringify(shell).length).toBeLessThan(2_000);
150 });
151
169 - it("omits oversized dynamic tool results without mutating persistence data", () => {
170 - const output = { content: [{ type: "text", text: "first line\n" + "x".repeat(100_000) }] };
171 - const item = { ...base, output } satisfies OrchestrationV2TurnItem;
172 - const projected = projectTurnItemForWire(item);
173 -
174 - expect(item.output).toBe(output);
175 - expect(projected).not.toBe(item);
176 - expect(JSON.stringify(projected).length).toBeLessThan(2_000);
177 - expect(projected).not.toHaveProperty("output");
178 - });
179 -
152 it("omits even small dynamic tool results while retaining input", () => {
153 const item = { ...base, output: { ok: true } } satisfies OrchestrationV2TurnItem;
154 expect(projectTurnItemForWire(item)).toEqual({ ...base, outputOmitted: true });
apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.test.ts
+1
@@ -114,6 +114,7 @@ it.effect(
114 }).pipe(Effect.provide(layerTest)),
115 );
116
117 +// regression: #15920 one bad legacy message stopped the server from starting
118 it.effect("propagates interruption from transcript reads and retry-marker writes", () =>
119 Effect.gen(function* () {
120 const sql = yield* SqlClient.SqlClient;
apps/server/src/orchestration-v2/pullRequestWatch.test.ts
+1
@@ -124,6 +124,7 @@ describe("evaluatePullRequestWatch", () => {
124 ]);
125 });
126
127 + // regression: #16208 PR watches burned GitHub's rate limit and gave up
128 it("does not report passed again for a new passed check where none is required", () => {
129 const first = evaluatePullRequestWatch(
130 watch(),
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+15 -280
@@ -636,50 +636,6 @@ const layerSharedApplicationDataPlaneTest = Layer.mergeAll(
636 );
637
638 it.layer(layerTest)("OrchestrationV2LayerLive", (it) => {
639 - it.effect("emits model updates separately from provider switches", () =>
640 - Effect.gen(function* () {
641 - const orchestrator = yield* Orchestrator.OrchestratorV2;
642 - const threadId = ThreadId.make("runtime-layer-model-selection-events");
643 -
644 - yield* orchestrator.dispatch({
645 - type: "thread.create",
646 - createdBy: "user",
647 - creationSource: "web",
648 - commandId: CommandId.make("runtime-layer-model-selection-events-create"),
649 - threadId,
650 - projectId: ProjectId.make("runtime-layer-model-selection-events-project"),
651 - title: "Model selection events",
652 - modelSelection,
653 - runtimeMode: "full-access",
654 - interactionMode: "default",
655 - branch: null,
656 - worktreePath: null,
657 - });
658 -
659 - const sameInstance = yield* orchestrator.dispatch({
660 - type: "thread.model-selection.set",
661 - commandId: CommandId.make("runtime-layer-model-selection-events-update"),
662 - threadId,
663 - modelSelection: { ...modelSelection, model: "gpt-5.5" },
664 - });
665 - assert.deepEqual(
666 - sameInstance.storedEvents.map((stored) => stored.event.type),
667 - ["thread.model-selection-updated"],
668 - );
669 -
670 - const differentInstance = yield* orchestrator.dispatch({
671 - type: "thread.model-selection.set",
672 - commandId: CommandId.make("runtime-layer-model-selection-events-switch"),
673 - threadId,
674 - modelSelection: { instanceId: alternateInstanceId, model: "gpt-5.5" },
675 - });
676 - assert.deepEqual(
677 - differentInstance.storedEvents.map((stored) => stored.event.type),
678 - ["thread.provider-switched"],
679 - );
680 - }),
681 - );
682 -
639 const seedFailingRollbackThread = (name: string) =>
640 Effect.gen(function* () {
641 const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -786,44 +742,6 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => {
742 }),
743 );
744
789 - it.effect("ignores a late failure from a rollback that a newer one superseded", () =>
790 - Effect.gen(function* () {
791 - const orchestrator = yield* Orchestrator.OrchestratorV2;
792 - const outbox = yield* EffectOutbox.EffectOutboxV2;
793 - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
794 - const { threadId, rollback } = yield* seedFailingRollbackThread(
795 - "runtime-rollback-superseded",
796 - );
797 -
798 - const olderCommandId = CommandId.make("runtime-rollback-superseded-older");
799 - yield* rollback(olderCommandId);
800 - for (let attempt = 0; attempt < 4; attempt++) {
801 - yield* worker.drain();
802 - yield* TestClock.adjust("30 seconds");
803 - }
804 - const newerCommandId = CommandId.make("runtime-rollback-superseded-newer");
805 - yield* rollback(newerCommandId);
806 - yield* worker.drain();
807 -
808 - const [olderEffect] = yield* outbox.listByCommandId(olderCommandId);
809 - assert.equal(olderEffect?.status, "failed");
810 - const superseded = yield* orchestrator.getThreadProjection(threadId);
811 - assert.isNull(superseded.thread.rollbackFailure);
812 -
813 - for (let attempt = 0; attempt < 5; attempt++) {
814 - yield* TestClock.adjust("30 seconds");
815 - yield* worker.drain();
816 - }
817 - const [newerEffect] = yield* outbox.listByCommandId(newerCommandId);
818 - assert.equal(newerEffect?.status, "failed");
819 - const failed = yield* orchestrator.getThreadProjection(threadId);
820 - assert.deepEqual(failed.thread.rollbackFailure, {
821 - requestId: newerCommandId,
822 - message: ROLLBACK_FAILED_MESSAGE,
823 - });
824 - }),
825 - );
826 -
745 it.effect("rejects non-ready rollback targets before persisting events or effects", () =>
746 Effect.gen(function* () {
747 const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -2111,67 +2029,6 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
2029 }),
2030 );
2031
2114 - it.effect("persists linked pull requests through projection rebuilds and unlinking", () =>
2115 - Effect.gen(function* () {
2116 - const orchestrator = yield* Orchestrator.OrchestratorV2;
2117 - const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
2118 - const threadId = ThreadId.make("runtime-layer-linked-pull-request-thread");
2119 - const linkedPullRequest = {
2120 - projectId: ProjectId.make("runtime-layer-linked-pull-request-project"),
2121 - repository: "pingdotgg/t3code",
2122 - number: 8160,
2123 - url: "https://github.com/pingdotgg/t3code/pull/8160",
2124 - } as const;
2125 -
2126 - yield* orchestrator.dispatch({
2127 - type: "thread.create",
2128 - createdBy: "user",
2129 - creationSource: "web",
2130 - commandId: CommandId.make("runtime-layer-linked-pull-request-create"),
2131 - threadId,
2132 - projectId: linkedPullRequest.projectId,
2133 - title: "Linked pull request thread",
2134 - modelSelection,
2135 - runtimeMode: "full-access",
2136 - interactionMode: "default",
2137 - branch: null,
2138 - worktreePath: null,
2139 - });
2140 - yield* orchestrator.dispatch({
2141 - type: "thread.metadata.update",
2142 - commandId: CommandId.make("runtime-layer-linked-pull-request-link"),
2143 - threadId,
2144 - linkedPullRequest,
2145 - });
2146 -
2147 - assert.deepEqual(
2148 - (yield* orchestrator.getThreadProjection(threadId)).thread.linkedPullRequest,
2149 - linkedPullRequest,
2150 - );
2151 - const linkedShell = yield* orchestrator.getThreadShell(threadId);
2152 - assert.isNotNull(linkedShell);
2153 - assert.deepEqual(linkedShell.linkedPullRequest, linkedPullRequest);
2154 -
2155 - const rebuilt = yield* maintenance.rebuild;
2156 - assert.isTrue(rebuilt.valid);
2157 - assert.deepEqual(
2158 - (yield* orchestrator.getThreadProjection(threadId)).thread.linkedPullRequest,
2159 - linkedPullRequest,
2160 - );
2161 -
2162 - yield* orchestrator.dispatch({
2163 - type: "thread.metadata.update",
2164 - commandId: CommandId.make("runtime-layer-linked-pull-request-unlink"),
2165 - threadId,
2166 - linkedPullRequest: null,
2167 - });
2168 - assert.isNull((yield* orchestrator.getThreadProjection(threadId)).thread.linkedPullRequest);
2169 - const unlinkedShell = yield* orchestrator.getThreadShell(threadId);
2170 - assert.isNotNull(unlinkedShell);
2171 - assert.isNull(unlinkedShell.linkedPullRequest);
2172 - }),
2173 - );
2174 -
2032 it.effect("keeps the branch pull request when linking another pull request", () =>
2033 Effect.gen(function* () {
2034 const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -2765,6 +2622,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
2622 }),
2623 );
2624
2625 + // regression: #21155 watching a pull request again repeated news the thread already got
2626 it.effect("a watch that ends on the comment limit keeps what its last pass saw", () =>
2627 Effect.gen(function* () {
2628 const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -2888,6 +2746,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
2746 }),
2747 );
2748
2749 + // regression: #21155 watching a pull request again repeated news the thread already got
2750 it.effect("watching a dismissed stack layer again keeps what its last watch told", () =>
2751 Effect.gen(function* () {
2752 const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -3736,88 +3595,6 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
3595 }),
3596 );
3597
3739 - it.effect("cancels queued work when a thread is archived", () =>
3740 - Effect.gen(function* () {
3741 - const orchestrator = yield* Orchestrator.OrchestratorV2;
3742 - const threadId = ThreadId.make("runtime-layer-archive-queued-thread");
3743 -
3744 - yield* orchestrator.dispatch({
3745 - type: "thread.create",
3746 - createdBy: "user",
3747 - creationSource: "web",
3748 - commandId: CommandId.make("runtime-layer-archive-queued-create"),
3749 - threadId,
3750 - projectId: ProjectId.make("runtime-layer-archive-queued-project"),
3751 - title: "Archive queued work",
3752 - modelSelection,
3753 - runtimeMode: "full-access",
3754 - interactionMode: "default",
3755 - branch: null,
3756 - worktreePath: "/tmp/runtime-layer-archive-queued",
3757 - });
3758 - yield* orchestrator.dispatch({
3759 - type: "message.dispatch",
3760 - createdBy: "user",
3761 - creationSource: "web",
3762 - commandId: CommandId.make("runtime-layer-archive-queued-active-message"),
3763 - threadId,
3764 - messageId: MessageId.make("runtime-layer-archive-queued-active-message"),
3765 - text: "Keep the provider occupied.",
3766 - attachments: [],
3767 - modelSelection,
3768 - dispatchMode: { type: "start_immediately" },
3769 - });
3770 - yield* orchestrator.dispatch({
3771 - type: "message.dispatch",
3772 - createdBy: "user",
3773 - creationSource: "web",
3774 - commandId: CommandId.make("runtime-layer-archive-queued-next-message"),
3775 - threadId,
3776 - messageId: MessageId.make("runtime-layer-archive-queued-next-message"),
3777 - text: "Do not run this after archive.",
3778 - attachments: [],
3779 - modelSelection,
3780 - dispatchMode: { type: "queue_after_active" },
3781 - });
3782 -
3783 - const beforeArchive = yield* orchestrator.getThreadProjection(threadId);
3784 - const activeRun = beforeArchive.runs.find((run) => run.status === "starting");
3785 - const queuedRun = beforeArchive.runs.find((run) => run.status === "queued");
3786 - assert.isDefined(activeRun);
3787 - assert.isDefined(queuedRun);
3788 -
3789 - yield* orchestrator.dispatch({
3790 - type: "thread.archive",
3791 - commandId: CommandId.make("runtime-layer-archive-queued-archive"),
3792 - threadId,
3793 - });
3794 -
3795 - const archived = yield* orchestrator.getThreadProjection(threadId);
3796 - assert.isNotNull(archived.thread.archivedAt);
3797 - assert.equal(archived.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled");
3798 - assert.equal(
3799 - archived.attempts.find((attempt) => attempt.runId === queuedRun.id)?.status,
3800 - "cancelled",
3801 - );
3802 - assert.equal(archived.nodes.find((node) => node.runId === queuedRun.id)?.status, "cancelled");
3803 - assert.equal(yield* orchestrator.resumeQueuedRuns, 0);
3804 -
3805 - const promoteError = yield* orchestrator
3806 - .dispatch({
3807 - type: "queued-message.promote-to-steer",
3808 - commandId: CommandId.make("runtime-layer-archive-queued-promote"),
3809 - threadId,
3810 - queuedRunId: queuedRun.id,
3811 - targetRunId: activeRun.id,
3812 - })
3813 - .pipe(Effect.flip);
3814 - assert.equal(promoteError._tag, "OrchestratorDispatchError");
3815 -
3816 - const afterPromotion = yield* orchestrator.getThreadProjection(threadId);
3817 - assert.equal(afterPromotion.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled");
3818 - }),
3819 - );
3820 -
3598 it.effect.each([false, true])(
3599 "promotes only one queued run after each terminal run (notification: %s)",
3600 (automatic) =>
@@ -5856,20 +5633,13 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
5633 it.effect.each([
5634 "resume",
5635 "queued-resume",
5859 - "cancel",
5636 "rearm",
5637 "snooze-race",
5862 - "new-message",
5638 "archive",
5864 - "settle",
5639 "replacement",
5640 "manual-snooze",
5867 - "manual-snooze-after-recovery",
5641 "invalid-snooze",
5869 - "snooze-only",
5870 - "snooze-resume",
5642 "cancel-resume-keep-snooze",
5872 - "wake-preserve-resume",
5643 "independent-patches",
5644 "expired-snooze",
5645 "wake",
@@ -6022,15 +5792,8 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
5792 assert.isNull(current.thread.snoozedUntil);
5793 return;
5794 }
6025 - const snooze = [
6026 - "snooze-only",
6027 - "manual-snooze-after-recovery",
6028 - "snooze-resume",
6029 - "wake",
6030 - "cancel-resume-keep-snooze",
6031 - "wake-preserve-resume",
6032 - ].includes(scenario);
6033 - const autoResume = scenario !== "snooze-only" && scenario !== "wake";
5795 + const snooze = scenario === "wake" || scenario === "cancel-resume-keep-snooze";
5796 + const autoResume = scenario !== "wake";
5797 const arm = limitRecoveryCommand(shell, autoResume, DateTime.toEpochMillis(now), snooze);
5798 assert(arm?.type === "thread.metadata.update" && arm.limitRecovery != null);
5799 const automaticArm = {
@@ -6106,7 +5869,7 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
5869 });
5870 if (snooze)
5871 assert.equal(DateTime.toEpochMillis(armedShell.snoozedUntil!), Date.parse(resetAt));
6109 - if (scenario === "cancel-resume-keep-snooze" || scenario === "wake-preserve-resume") {
5872 + if (scenario === "cancel-resume-keep-snooze") {
5873 yield* TestClock.adjust("10 seconds");
5874 yield* orchestrator.dispatch({
5875 type: "thread.metadata.update",
@@ -6115,25 +5878,19 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
5878 limitRecovery: {
5879 runId: run.id,
5880 resetAt,
6118 - autoResume: scenario === "wake-preserve-resume",
6119 - snooze: scenario === "cancel-resume-keep-snooze",
5881 + autoResume: false,
5882 + snooze: true,
5883 },
5884 });
5885 armedShell = (yield* orchestrator.getShellSnapshot()).threads.find(
5886 (thread) => thread.id === threadId,
5887 )!;
6125 - if (scenario === "cancel-resume-keep-snooze") {
6126 - assert.equal(DateTime.toEpochMillis(armedShell.snoozedUntil!), Date.parse(resetAt));
6127 - assert.equal(
6128 - DateTime.toEpochMillis(armedShell.snoozedAt!),
6129 - DateTime.toEpochMillis(armedShell.updatedAt),
6130 - );
6131 - assert.isFalse(armedShell.limitRecovery!.autoResume);
6132 - } else {
6133 - assert.isNull(armedShell.snoozedUntil);
6134 - assert.isNull(armedShell.snoozedAt);
6135 - assert.isTrue(armedShell.limitRecovery!.autoResume);
6136 - }
5888 + assert.equal(DateTime.toEpochMillis(armedShell.snoozedUntil!), Date.parse(resetAt));
5889 + assert.equal(
5890 + DateTime.toEpochMillis(armedShell.snoozedAt!),
5891 + DateTime.toEpochMillis(armedShell.updatedAt),
5892 + );
5893 + assert.isFalse(armedShell.limitRecovery!.autoResume);
5894 }
5895 if (scenario === "independent-patches") {
5896 yield* TestClock.adjust("10 seconds");
@@ -6173,7 +5930,7 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
5930 assert.isTrue(armedShell.limitRecovery!.autoResume);
5931 assert.isTrue(armedShell.limitRecovery!.snooze);
5932 }
6176 - if (scenario === "manual-snooze" || scenario === "manual-snooze-after-recovery") {
5933 + if (scenario === "manual-snooze") {
5934 yield* orchestrator.dispatch({
5935 type: "thread.snooze",
5936 commandId: CommandId.make(`recovery:manual-snooze:${scenario}`),
@@ -6275,7 +6032,7 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
6032 assert.isTrue(current.thread.limitRecovery!.autoResume);
6033 }
6034
6278 - if (scenario === "cancel" || scenario === "rearm")
6035 + if (scenario === "rearm")
6036 yield* orchestrator.dispatch({
6037 type: "thread.metadata.update",
6038 commandId: CommandId.make(`recovery:cancel:${scenario}`),
@@ -6288,24 +6045,6 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
6045 commandId: CommandId.make(`recovery:archive:${scenario}`),
6046 threadId,
6047 });
6291 - if (scenario === "new-message")
6292 - yield* orchestrator.dispatch({
6293 - type: "message.dispatch",
6294 - commandId: CommandId.make(`recovery:new-message:${scenario}`),
6295 - threadId,
6296 - messageId: MessageId.make(`recovery:new-message:${scenario}`),
6297 - text: "I will continue manually.",
6298 - attachments: [],
6299 - dispatchMode: { type: "defer_start" },
6300 - createdBy: "user",
6301 - creationSource: "web",
6302 - });
6303 - if (scenario === "settle")
6304 - yield* orchestrator.dispatch({
6305 - type: "thread.settle",
6306 - commandId: CommandId.make(`recovery:settle:${scenario}`),
6307 - threadId,
6308 - });
6048 if (scenario === "stop") {
6049 yield* orchestrator.dispatch({
6050 type: "thread.stop",
@@ -6377,8 +6116,6 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
6116 (scenario === "resume" ||
6117 stopBeforeArm ||
6118 scenario === "queued-resume" ||
6380 - scenario === "snooze-resume" ||
6381 - scenario === "wake-preserve-resume" ||
6119 scenario === "independent-patches" ||
6120 scenario === "expired-snooze"
6121 ? 1
@@ -6390,8 +6127,6 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
6127 (scenario === "resume" ||
6128 stopBeforeArm ||
6129 scenario === "queued-resume" ||
6393 - scenario === "snooze-resume" ||
6394 - scenario === "wake-preserve-resume" ||
6130 scenario === "independent-patches" ||
6131 scenario === "expired-snooze"
6132 ? 1
apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts
+5 -7
@@ -572,13 +572,11 @@ describe("orchestrator replay fixtures", () => {
572 }),
573 );
574
575 - it.effect.each(
576 - (["WebFetch", "Write"] as const).flatMap((tool) =>
577 - (["before root settles", "while root is idle"] as const).flatMap((opens) =>
578 - (["stopped", "failed"] as const).map((status) => [tool, opens, status] as const),
579 - ),
580 - ),
581 - )(
575 + // regression: #16486 a background subagent's tool left open while its parent is idle never settled
576 + it.effect.each([
577 + ["WebFetch", "while root is idle", "stopped"],
578 + ["Write", "before root settles", "failed"],
579 + ] as const)(
580 "ends a background subagent's open %s (opened %s) when its notification is %s",
581 ([tool, opens, notificationStatus]) =>
582 runFixtureProviderWithRegisteredHarness({
apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
+28 -59
@@ -37,7 +37,6 @@ import * as SqlitePersistence from "../../persistence/Sqlite.ts";
37 import { CommandPolicyCapabilityUnsupportedError } from "../CommandPolicy.ts";
38 import {
39 ClaudeAppendSystemPromptFileError,
40 - ClaudeAppendSystemPromptMissingValueError,
40 ClaudeBackgroundWorkBlocksQueryReplacementError,
41 ClaudeProviderCapabilitiesV2,
42 } from "../Adapters/ClaudeAdapterV2.ts";
@@ -408,36 +407,15 @@ const waitForIdle = Effect.fn("ProviderSwitchTest.waitForIdle")(function* (
407 describe("orchestration v2 provider switching", () => {
408 it.live.each([
409 "compact-native",
411 - "compact-fallback",
410 "compact-legacy",
411 "large-current-input",
414 - "screenshot-native",
412 "screenshot-fallback",
416 - "screenshot-pair-native",
417 - "screenshot-pair-fallback",
418 - "screenshot-eight-native",
419 - "screenshot-eight-fallback",
420 - "screenshot-large-model-native",
413 "screenshot-reported-capacity-native",
422 - "screenshot-model-change-native",
423 - "screenshot-option-change-native",
424 - "screenshot-model-change-retry-native",
414 "screenshot-option-change-retry-native",
426 - "prior-images-reasoning-change-replacement-native",
415 "prior-images-reasoning-change-replacement-small-native",
428 - "prior-images-reasoning-change-native",
429 - "prior-images-turn-usage-native",
430 - "prior-images-turn-usage-replacement-native",
431 - "prior-images-turn-usage-model-change-native",
432 - "prior-images-turn-usage-option-change-retry-native",
433 - "prior-images-reasoning-change-retry-native",
434 - "prior-images-native",
435 - "prior-images-fallback",
436 - "imported-prior-images-native",
416 "imported-prior-images-fallback",
417 "prior-images-telemetry-native",
418 "prior-images-unsent-native",
440 - "prior-images-replacement-native",
419 "prior-images-legacy-replacement-native",
420 "delivery-write-failure",
421 ] as const)("preserves handoffs through %s", (scenario) =>
@@ -852,22 +830,20 @@ describe("orchestration v2 provider switching", () => {
830 if (scenario.startsWith("screenshot")) {
831 assert.deepEqual((yield* Ref.get(capturedTurns)).at(-1)!.attachments, screenshots);
832 }
855 - if (scenario === "compact-fallback" || scenario === "compact-legacy") {
856 - if (scenario === "compact-legacy") {
857 - const { history: _history, ...legacyHandoff } = handoff;
858 - yield* eventSink.write({
859 - events: [
860 - {
861 - id: EventId.make("legacy-handoff-shape"),
862 - type: "context-handoff.updated",
863 - threadId,
864 - runId: handoff.targetRunId,
865 - occurredAt: yield* DateTime.now,
866 - payload: legacyHandoff,
867 - },
868 - ],
869 - });
870 - }
833 + if (scenario === "compact-legacy") {
834 + const { history: _history, ...legacyHandoff } = handoff;
835 + yield* eventSink.write({
836 + events: [
837 + {
838 + id: EventId.make("legacy-handoff-shape"),
839 + type: "context-handoff.updated",
840 + threadId,
841 + runId: handoff.targetRunId,
842 + occurredAt: yield* DateTime.now,
843 + payload: legacyHandoff,
844 + },
845 + ],
846 + });
847 assert.isUndefined(handoff.delivery);
848 yield* dispatch(3, "Continue after compact", CLAUDE_MODEL_SELECTION);
849 yield* wait(3);
@@ -1209,10 +1185,6 @@ describe("orchestration v2 provider switching", () => {
1185 it.live.each([
1186 ["background work", new ClaudeBackgroundWorkBlocksQueryReplacementError()],
1187 ["an unreadable append file", new ClaudeAppendSystemPromptFileError({ path: "missing.md" })],
1212 - [
1213 - "a missing append value",
1214 - new ClaudeAppendSystemPromptMissingValueError({ flag: "--append-system-prompt" }),
1215 - ],
1188 ] as const)("keeps the native session after turns refused for %s", ([, refusalCause]) =>
1189 Effect.scoped(
1190 Effect.gen(function* () {
@@ -1307,18 +1279,19 @@ describe("orchestration v2 provider switching", () => {
1279 );
1280
1281 it.live.each(
1310 - (["failed", "interrupted"] as const).flatMap((status) =>
1311 - [false, true].flatMap((queued) =>
1312 - [false, true].flatMap((returning) =>
1313 - [false, true].map(
1314 - (native) =>
1315 - [
1316 - `${status} context ${queued ? "through the queue" : "immediately"} to ${returning ? "a returning" : "a new"} provider via ${native ? "native history" : "text"}`,
1317 - { status, queued, returning, native },
1318 - ] as const,
1319 - ),
1320 - ),
1321 - ),
1282 + (
1283 + [
1284 + ["failed", false, false, false],
1285 + ["failed", true, true, true],
1286 + ["interrupted", false, true, false],
1287 + ["interrupted", true, false, true],
1288 + ] as const
1289 + ).map(
1290 + ([status, queued, returning, native]) =>
1291 + [
1292 + `${status} context ${queued ? "through the queue" : "immediately"} to ${returning ? "a returning" : "a new"} provider via ${native ? "native history" : "text"}`,
1293 + { status, queued, returning, native },
1294 + ] as const,
1295 ),
1296 )("hands off %s", ([, { status, queued, returning, native }]) =>
1297 Effect.scoped(
@@ -2252,10 +2225,9 @@ describe("orchestration v2 provider switching", () => {
2225 ),
2226 );
2227
2228 + // regression: #21314 a queued PR update must follow the provider that took over the thread
2229 it.live.each([
2230 ["automatic", "Claude"],
2257 - ["queue.resume", "Claude"],
2258 - ["automatic", "compatible Codex"],
2231 ["queue.resume", "compatible Codex"],
2232 ] as const)(
2233 "delivers a queued PR update on the current provider through %s (%s)",
@@ -2448,9 +2420,6 @@ describe("orchestration v2 provider switching", () => {
2420 if (compatible) {
2421 assert.equal(executed.nativeThreadId, turns[0]!.nativeThreadId);
2422 assert.isEmpty(after.contextHandoffs);
2451 - if (delivery === "automatic") {
2452 - assert.equal(delivered.providerThreadId, wake.providerThreadId);
2453 - }
2423 }
2424 assert.equal(
2425 after.providerThreads.find((entry) => entry.id === delivered.providerThreadId)
apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts
+1 -181
@@ -41,7 +41,6 @@ const CLAUDE_MODEL_SELECTION = {
41 instanceId: ProviderInstanceId.make("claudeAgent"),
42 model: "claude-sonnet-4-6",
43 } as const;
44 -const TRANSCRIPT_PATH = `${import.meta.dirname}/fixtures/thread_fork_native/codex_transcript.ndjson`;
44 const PRIOR_TURN_TRANSCRIPT_PATH = `${import.meta.dirname}/fixtures/thread_fork_native_prior_turn/codex_transcript.ndjson`;
45 const CLAUDE_TRANSCRIPT_PATH = `${import.meta.dirname}/fixtures/thread_fork_native/claude_transcript.ndjson`;
46 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* () {
99 return cwd;
100 });
101
103 -function readTranscript(transcriptPath: string = TRANSCRIPT_PATH) {
102 +function readTranscript(transcriptPath: string) {
103 return Effect.gen(function* () {
104 const fs = yield* FileSystem.FileSystem;
105 const text = yield* fs.readFileString(transcriptPath);
@@ -139,185 +138,6 @@ function userAndAssistantText(
138 }
139
140 describe("orchestration V2 thread fork", () => {
142 - it.effect(
143 - "creates an idle app fork and resolves it with Codex native thread/fork on first dispatch",
144 - () =>
145 - Effect.gen(function* () {
146 - const rawTranscript = yield* readTranscript();
147 - const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) =>
148 - Effect.service(FileSystem.FileSystem).pipe(
149 - Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })),
150 - Effect.orDie,
151 - ),
152 - );
153 - const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript(
154 - materializeReplayTranscriptWorkspace(rawTranscript, cwd),
155 - );
156 -
157 - const materialized = yield* Effect.gen(function* () {
158 - const ids = yield* IdAllocator.IdAllocatorV2;
159 - const projectId = yield* ids.allocate.project({ fixtureName: "thread-fork-native" });
160 - const sourceThreadId = yield* ids.allocate.thread({
161 - fixtureName: "thread-fork-native-source",
162 - projectId,
163 - });
164 - const targetThreadId = ThreadId.make("thread-fork-native-target");
165 -
166 - const commands = [
167 - {
168 - type: "thread.create",
169 - createdBy: "user",
170 - creationSource: "web",
171 - commandId: yield* ids.allocate.command({
172 - fixtureName: "thread-fork-native",
173 - commandName: "thread-create-source",
174 - }),
175 - threadId: sourceThreadId,
176 - projectId,
177 - title: "Source thread",
178 - modelSelection: CODEX_MODEL_SELECTION,
179 - runtimeMode: "full-access",
180 - interactionMode: "default",
181 - branch: null,
182 - worktreePath: null,
183 - },
184 - {
185 - type: "message.dispatch",
186 - createdBy: "user",
187 - creationSource: "web",
188 - commandId: yield* ids.allocate.command({
189 - fixtureName: "thread-fork-native",
190 - commandName: "source-message",
191 - }),
192 - threadId: sourceThreadId,
193 - messageId: MessageId.make("message-thread-fork-native-source"),
194 - text: THREAD_FORK_NATIVE_SOURCE_PROMPT,
195 - attachments: [],
196 - modelSelection: CODEX_MODEL_SELECTION,
197 - dispatchMode: { type: "start_immediately" },
198 - },
199 - {
200 - type: "thread.fork",
201 - createdBy: "user",
202 - creationSource: "web",
203 - commandId: CommandId.make("command-thread-fork-native"),
204 - sourceThreadId,
205 - targetThreadId,
206 - sourcePoint: { type: "latest_stable" },
207 - title: "Forked thread",
208 - },
209 - {
210 - type: "thread.fork",
211 - createdBy: "user",
212 - creationSource: "web",
213 - commandId: CommandId.make("command-thread-fork-native"),
214 - sourceThreadId,
215 - targetThreadId,
216 - sourcePoint: { type: "latest_stable" },
217 - title: "Forked thread",
218 - },
219 - {
220 - type: "message.dispatch",
221 - createdBy: "user",
222 - creationSource: "web",
223 - commandId: yield* ids.allocate.command({
224 - fixtureName: "thread-fork-native",
225 - commandName: "target-message",
226 - }),
227 - threadId: targetThreadId,
228 - messageId: MessageId.make("message-thread-fork-native-target"),
229 - text: THREAD_FORK_NATIVE_TARGET_PROMPT,
230 - attachments: [],
231 - modelSelection: CODEX_MODEL_SELECTION,
232 - dispatchMode: { type: "start_immediately" },
233 - },
234 - ] satisfies ReadonlyArray<OrchestrationV2Command>;
235 -
236 - return {
237 - sourceThreadId,
238 - targetThreadId,
239 - commands,
240 - };
241 - }).pipe(Effect.provide(IdAllocator.layer), provideDeterministicTestRuntime);
242 -
243 - const result = yield* runOrchestratorV2ProviderReplayScenario(
244 - {
245 - name: "thread_fork_native/codex",
246 - transcript,
247 - commands: materialized.commands,
248 - steps: [
249 - { type: "dispatch", command: materialized.commands[0]!, await: true },
250 - { type: "advance_clock", duration: "1 millis" },
251 - { type: "dispatch", command: materialized.commands[1]!, await: true },
252 - { type: "await_thread_idle", threadId: materialized.sourceThreadId },
253 - { type: "dispatch", command: materialized.commands[2]!, await: true },
254 - { type: "dispatch", command: materialized.commands[3]!, await: true },
255 - { type: "dispatch", command: materialized.commands[4]!, await: true },
256 - { type: "await_thread_idle", threadId: materialized.targetThreadId },
257 - ],
258 - projectionThreadIds: [materialized.sourceThreadId, materialized.targetThreadId],
259 - runtimePolicyOverride: { cwd },
260 - },
261 - CodexOrchestratorReplayHarness,
262 - ).pipe(provideDeterministicTestRuntime);
263 -
264 - const sourceProjection = result.projections.get(materialized.sourceThreadId);
265 - const targetProjection = result.projections.get(materialized.targetThreadId);
266 - assert.isDefined(sourceProjection);
267 - assert.isDefined(targetProjection);
268 - assert.equal(targetProjection.thread.lineage.parentThreadId, materialized.sourceThreadId);
269 - assert.equal(targetProjection.thread.lineage.relationshipToParent, "fork");
270 - assert.lengthOf(targetProjection.providerSessions, 1);
271 - assert.lengthOf(targetProjection.providerThreads, 1);
272 - assert.equal(
273 - targetProjection.providerThreads[0]?.nativeThreadRef?.nativeId,
274 - "native-fork-thread",
275 - );
276 - assert.equal(
277 - targetProjection.providerThreads[0]?.forkedFrom?.providerThreadId,
278 - sourceProjection.providerThreads[0]?.id,
279 - );
280 -
281 - const transfers = targetProjection.contextTransfers.filter(
282 - (transfer) => transfer.targetThreadId === materialized.targetThreadId,
283 - );
284 - assert.lengthOf(transfers, 1);
285 - assert.equal(transfers[0]?.status, "consumed");
286 - assert.equal(transfers[0]?.resolution?.strategy, "native_fork");
287 - assert.isUndefined(sourceProjection.providerTurns[0]?.tokenUsage);
288 - assert.isUndefined(transfers[0]?.sourceTokenUsage);
289 - assert.equal(transfers[0]?.targetRunId, targetProjection.runs[0]?.id);
290 -
291 - const transferCreatedIndex = result.domainEvents.findIndex(
292 - (event) => event.type === "context-transfer.created",
293 - );
294 - const targetProviderSessionIndex = result.domainEvents.findIndex(
295 - (event) =>
296 - event.threadId === materialized.targetThreadId &&
297 - event.type === "provider-session.updated",
298 - );
299 - const targetRunCreatedIndex = result.domainEvents.findIndex(
300 - (event) => event.threadId === materialized.targetThreadId && event.type === "run.created",
301 - );
302 - assert.isAtLeast(transferCreatedIndex, 0);
303 - assert.isAbove(targetProviderSessionIndex, transferCreatedIndex);
304 - assert.isAbove(
305 - targetProviderSessionIndex,
306 - targetRunCreatedIndex,
307 - "provider runtime state must be materialized only after the target run commits",
308 - );
309 -
310 - const forkEvents = result.domainEvents.filter(
311 - (event) => event.type === "context-transfer.created",
312 - );
313 - assert.lengthOf(
314 - forkEvents,
315 - 1,
316 - "duplicate fork command must return the receipt without creating another transfer",
317 - );
318 - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
319 - );
320 -
141 it.effect(
142 "creates an idle app fork and resolves it with Claude native session fork on first dispatch",
143 () =>
apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts
-206
@@ -23,10 +23,6 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
23 import { provideDeterministicTestRuntime } from "./DeterministicRuntime.ts";
24 import {
25 CODEX_MODEL_SELECTION,
26 - THREAD_MERGE_BACK_FORK_PROMPT,
27 - THREAD_MERGE_BACK_HANDOFF_PROMPT,
28 - THREAD_MERGE_BACK_RECALL,
29 - THREAD_MERGE_BACK_RECALL_PROMPT,
26 THREAD_MERGE_BACK_SIBLINGS_FIRST_FORK_PROMPT,
27 THREAD_MERGE_BACK_SIBLINGS_FIRST_HANDOFF_PROMPT,
28 THREAD_MERGE_BACK_SIBLINGS_RECALL,
@@ -34,7 +30,6 @@ import {
30 THREAD_MERGE_BACK_SIBLINGS_SECOND_FORK_PROMPT,
31 THREAD_MERGE_BACK_SIBLINGS_SECOND_HANDOFF_PROMPT,
32 THREAD_MERGE_BACK_SIBLINGS_SOURCE_PROMPT,
37 - THREAD_MERGE_BACK_SOURCE_PROMPT,
33 } from "./fixtures/shared.ts";
34 import { runOrchestratorV2ProviderReplayScenario } from "./ProviderReplayHarness.ts";
35 import { makeCheckpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
@@ -68,7 +63,6 @@ const CodexHistoryReplayHarness: typeof CodexOrchestratorReplayHarness = {
63 assert.lengthOf(userTexts, 1);
64 assert.include(
65 [
71 - THREAD_MERGE_BACK_FORK_PROMPT,
66 THREAD_MERGE_BACK_SIBLINGS_FIRST_FORK_PROMPT,
67 THREAD_MERGE_BACK_SIBLINGS_SECOND_FORK_PROMPT,
68 ],
@@ -99,8 +93,6 @@ const CLAUDE_MODEL_SELECTION = {
93 instanceId: ProviderInstanceId.make("claudeAgent"),
94 model: "claude-sonnet-4-6",
95 } as const;
102 -const MERGE_BACK_USER_TEXT =
103 - "Retain the transferred fork marker for later. Respond with exactly: merge delta stored";
96 const FIRST_SIBLING_MERGE_USER_TEXT =
97 "Retain the first transferred marker for later. Respond with exactly: first merge delta stored";
98 const SECOND_SIBLING_MERGE_USER_TEXT =
@@ -254,204 +246,6 @@ function makeCreateCommand(input: {
246 }
247
248 describe("orchestration V2 merge-back provider replay", () => {
257 - it.effect.each(PROVIDERS)(
258 - "merges one fork delta back into the original $driver thread",
259 - (variant) =>
260 - Effect.gen(function* () {
261 - const rawTranscript = yield* readTranscript("thread_merge_back_continue", variant.driver);
262 - const materialized = yield* Effect.gen(function* () {
263 - const ids = yield* IdAllocator.IdAllocatorV2;
264 - const projectId = yield* ids.allocate.project({
265 - fixtureName: `thread-merge-back-${variant.driver}`,
266 - });
267 - const sourceThreadId = yield* ids.allocate.thread({
268 - fixtureName: `thread-merge-back-${variant.driver}-source`,
269 - projectId,
270 - });
271 - const forkThreadId = ThreadId.make(`thread-merge-back-${variant.driver}-fork`);
272 - const forkRunId = ids.derive.run({ threadId: forkThreadId, ordinal: 1 });
273 - const commands = [
274 - makeCreateCommand({
275 - commandId: yield* ids.allocate.command({
276 - fixtureName: `thread-merge-back-${variant.driver}`,
277 - commandName: "create",
278 - }),
279 - threadId: sourceThreadId,
280 - projectId,
281 - modelSelection: variant.modelSelection,
282 - }),
283 - {
284 - type: "message.dispatch",
285 - createdBy: "user",
286 - creationSource: "web",
287 - commandId: yield* ids.allocate.command({
288 - fixtureName: `thread-merge-back-${variant.driver}`,
289 - commandName: "source",
290 - }),
291 - threadId: sourceThreadId,
292 - messageId: MessageId.make(`message-merge-source-${variant.driver}`),
293 - text: THREAD_MERGE_BACK_SOURCE_PROMPT,
294 - attachments: [],
295 - modelSelection: variant.modelSelection,
296 - dispatchMode: { type: "start_immediately" },
297 - },
298 - {
299 - type: "thread.fork",
300 - createdBy: "user",
301 - creationSource: "web",
302 - commandId: CommandId.make(`command-merge-fork-${variant.driver}`),
303 - sourceThreadId,
304 - targetThreadId: forkThreadId,
305 - sourcePoint: { type: "latest_stable" },
306 - title: "Merge-back fork",
307 - },
308 - {
309 - type: "message.dispatch",
310 - createdBy: "user",
311 - creationSource: "web",
312 - commandId: yield* ids.allocate.command({
313 - fixtureName: `thread-merge-back-${variant.driver}`,
314 - commandName: "fork-delta",
315 - }),
316 - threadId: forkThreadId,
317 - messageId: MessageId.make(`message-merge-fork-${variant.driver}`),
318 - text: THREAD_MERGE_BACK_FORK_PROMPT,
319 - attachments: [],
320 - modelSelection: variant.modelSelection,
321 - dispatchMode: { type: "start_immediately" },
322 - },
323 - {
324 - type: "thread.merge_back",
325 - createdBy: "user",
326 - creationSource: "web",
327 - commandId: CommandId.make(`command-merge-back-${variant.driver}`),
328 - sourceThreadId: forkThreadId,
329 - targetThreadId: sourceThreadId,
330 - sourcePoint: { type: "run", runId: forkRunId },
331 - },
332 - {
333 - type: "message.dispatch",
334 - createdBy: "user",
335 - creationSource: "web",
336 - commandId: yield* ids.allocate.command({
337 - fixtureName: `thread-merge-back-${variant.driver}`,
338 - commandName: "consume-merge",
339 - }),
340 - threadId: sourceThreadId,
341 - messageId: MessageId.make(`message-consume-merge-${variant.driver}`),
342 - text: MERGE_BACK_USER_TEXT,
343 - attachments: [],
344 - modelSelection: variant.modelSelection,
345 - dispatchMode: { type: "start_immediately" },
346 - },
347 - {
348 - type: "message.dispatch",
349 - createdBy: "user",
350 - creationSource: "web",
351 - commandId: yield* ids.allocate.command({
352 - fixtureName: `thread-merge-back-${variant.driver}`,
353 - commandName: "recall",
354 - }),
355 - threadId: sourceThreadId,
356 - messageId: MessageId.make(`message-merge-recall-${variant.driver}`),
357 - text: THREAD_MERGE_BACK_RECALL_PROMPT,
358 - attachments: [],
359 - modelSelection: variant.modelSelection,
360 - dispatchMode: { type: "start_immediately" },
361 - },
362 - ] satisfies ReadonlyArray<OrchestrationV2Command>;
363 - return { commands, sourceThreadId, forkThreadId, forkRunId };
364 - }).pipe(Effect.provide(IdAllocator.layer), provideDeterministicTestRuntime);
365 - const summary = forkDeltaSummary({
366 - sourceThreadId: materialized.forkThreadId,
367 - targetThreadId: materialized.sourceThreadId,
368 - forkUserText: THREAD_MERGE_BACK_FORK_PROMPT,
369 - forkAssistantText: "merge fork stored",
370 - });
371 - const generatedProviderMessage = providerMessage(summary, MERGE_BACK_USER_TEXT);
372 - const parameterizedTranscript = parameterizeHandoffs(rawTranscript, [
373 - [
374 - THREAD_MERGE_BACK_HANDOFF_PROMPT,
375 - variant.driver === "codex" ? MERGE_BACK_USER_TEXT : generatedProviderMessage,
376 - ],
377 - ]);
378 - const cwd = yield* Effect.acquireRelease(
379 - Effect.promise(() => makeCheckpointWorkspace(`merge-back-${variant.driver}`)),
380 - (directory) =>
381 - Effect.service(FileSystem.FileSystem).pipe(
382 - Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })),
383 - Effect.orDie,
384 - ),
385 - );
386 - const scenario = {
387 - name: `thread_merge_back_continue/${variant.driver}`,
388 - commands: materialized.commands,
389 - steps: [
390 - { type: "dispatch" as const, command: materialized.commands[0]!, await: true },
391 - { type: "advance_clock" as const, duration: "1 millis" as const },
392 - { type: "dispatch" as const, command: materialized.commands[1]!, await: true },
393 - { type: "await_thread_idle" as const, threadId: materialized.sourceThreadId },
394 - { type: "dispatch" as const, command: materialized.commands[2]!, await: true },
395 - { type: "dispatch" as const, command: materialized.commands[3]!, await: true },
396 - { type: "await_thread_idle" as const, threadId: materialized.forkThreadId },
397 - { type: "dispatch" as const, command: materialized.commands[4]!, await: true },
398 - { type: "dispatch" as const, command: materialized.commands[5]!, await: true },
399 - { type: "await_thread_idle" as const, threadId: materialized.sourceThreadId },
400 - { type: "dispatch" as const, command: materialized.commands[6]!, await: true },
401 - { type: "await_thread_idle" as const, threadId: materialized.sourceThreadId },
402 - ],
403 - projectionThreadIds: [materialized.sourceThreadId, materialized.forkThreadId],
404 - runtimePolicyOverride: { cwd },
405 - };
406 - const result =
407 - variant.driver === "codex"
408 - ? yield* runOrchestratorV2ProviderReplayScenario(
409 - {
410 - ...scenario,
411 - transcript: yield* CodexOrchestratorReplayHarness.decodeTranscript(
412 - materializeReplayTranscriptWorkspace(parameterizedTranscript, cwd),
413 - ),
414 - },
415 - CodexHistoryReplayHarness,
416 - ).pipe(provideDeterministicTestRuntime)
417 - : yield* runOrchestratorV2ProviderReplayScenario(
418 - {
419 - ...scenario,
420 - transcript:
421 - yield* ClaudeOrchestratorReplayHarness.decodeTranscript(
422 - parameterizedTranscript,
423 - ),
424 - },
425 - ClaudeOrchestratorReplayHarness,
426 - ).pipe(provideDeterministicTestRuntime);
427 -
428 - const source = result.projections.get(materialized.sourceThreadId);
429 - const fork = result.projections.get(materialized.forkThreadId);
430 - assert.isDefined(source);
431 - assert.isDefined(fork);
432 - assert.equal(
433 - source.providerThreads[0]?.nativeThreadRef?.nativeId,
434 - nativeSourceThreadId(rawTranscript),
435 - );
436 - assert.lengthOf(source.contextHandoffs, 1);
437 - assert.equal(source.contextHandoffs[0]?.summaryText, summary);
438 - assert.equal(source.contextHandoffs[0]?.strategy, "fork_delta_summary");
439 - const mergeTransfer = source.contextTransfers.find(
440 - (transfer) => transfer.type === "merge_back",
441 - );
442 - assert.isDefined(mergeTransfer);
443 - assert.equal(mergeTransfer.status, "consumed");
444 - assert.equal(mergeTransfer.sourcePoint.runId, materialized.forkRunId);
445 - assert.equal(mergeTransfer.resolution?.strategy, "fork_delta_context");
446 - assert.include(
447 - normalizePipeSpacing(visibleConversationText(source)),
448 - THREAD_MERGE_BACK_RECALL,
449 - );
450 - assert.notInclude(visibleConversationText(source), "Context handoff (");
451 - assert.include(visibleConversationText(fork), "merge fork stored");
452 - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
453 - );
454 -
249 it.effect.each(PROVIDERS)(
250 "merges two sibling fork deltas into the original $driver thread",
251 (variant) =>
apps/server/src/orchestration-v2/testkit/fixtures/shared.ts
-1
@@ -144,7 +144,6 @@ export const THREAD_MERGE_BACK_HANDOFF_PROMPT = [
144 "User message:",
145 "Retain the transferred fork marker for later. Respond with exactly: merge delta stored",
146 ].join("\n");
147 -export const THREAD_MERGE_BACK_RECALL = `${THREAD_MERGE_BACK_SOURCE_MARKER}|${THREAD_MERGE_BACK_FORK_MARKER}`;
147 export const THREAD_MERGE_BACK_RECALL_PROMPT =
148 "Return the source marker followed by the transferred fork marker, separated by a single | character. Respond with only the markers and separator.";
149 const THREAD_MERGE_BACK_SIBLINGS_SOURCE_MARKER = "merge-sibling-source-3C7K";
apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native/codex_transcript.ndjson deleted
-21
@@ -1,21 +0,0 @@
1 -{"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."}}
2 -{"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"}}}}
3 -{"type":"emit_inbound","label":"initialize/source","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.120.0","codexHome":"/tmp/codex","platformFamily":"unix","platformOs":"macos"}}}
4 -{"type":"expect_outbound","label":"initialized/source","frame":{"method":"initialized"}}
5 -{"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}}}}
6 -{"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"}}}
7 -{"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"}}}
8 -{"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}}}}
9 -{"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}}}}
10 -{"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"}}}
11 -{"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"}}}
12 -{"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}}}}
13 -{"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}}}}
14 -{"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"}}}
15 -{"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"}}}
16 -{"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}}}}
17 -{"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}}}}
18 -{"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"}}}
19 -{"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"}}}
20 -{"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}}}}
21 -{"type":"runtime_exit","status":"success"}
apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_continue/README.md deleted
-45
@@ -1,45 +0,0 @@
1 -# Merge-Back Continuation Fixture
2 -
3 -This fixture records a native fork, a fork-local delta, and an app-style
4 -merge-back handoff consumed by the original provider thread. A later source
5 -turn recalls both markers without receiving either marker in its prompt.
6 -
7 -Both provider transcripts execute the same graph.
8 -
9 -## Conversation Graph
10 -
11 -```text
12 -Source provider thread
13 -|
14 -+-- Turn 1
15 -| User: remember merge-source-4H8Q
16 -| Assistant: merge source stored
17 -|
18 -+-- native fork
19 -| |
20 -| `-- Forked provider thread
21 -| `-- Turn 2
22 -| User: remember merge-fork-7T2W
23 -| Assistant: merge fork stored
24 -|
25 -`-- original source provider thread
26 - |
27 - +-- Turn 3
28 - | App input: merge_back handoff containing merge-fork-7T2W
29 - | Assistant: merge delta stored
30 - |
31 - `-- Turn 4
32 - User: recall source and transferred markers without restating them
33 - Assistant: merge-source-4H8Q|merge-fork-7T2W
34 -```
35 -
36 -## Assertions
37 -
38 -- The fork uses a different native provider thread or session.
39 -- The handoff and recall turns continue the original source provider thread.
40 -- The recall prompt contains neither marker.
41 -- The final response recalls both source and transferred fork context.
42 -
43 -The transcript records the provider-facing handoff format. The app-level
44 -`thread.merge_back` command and context-transfer lifecycle remain covered by
45 -the orchestrator integration tests.
apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_continue/claude_transcript.ndjson deleted
-34
@@ -1,34 +0,0 @@
1 -{"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}}
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}}}}
3 -{"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}}}
4 -{"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"}}
5 -{"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"}}
6 -{"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"}}
7 -{"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"}}
8 -{"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"}}
9 -{"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"}}
10 -{"type":"runtime_exit","status":"success"}
11 -{"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"}}}
12 -{"type":"emit_inbound","label":"session.forked","frame":{"type":"session.forked","sessionId":"8baac83f-471d-4d65-9091-2e7e66557251"}}
13 -{"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}}}}
14 -{"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}}}
15 -{"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"}}
16 -{"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"}}
17 -{"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"}}
18 -{"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"}}
19 -{"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"}}
20 -{"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"}}
21 -{"type":"runtime_exit","status":"success"}
22 -{"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}}}}
23 -{"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}}}
24 -{"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"}}
25 -{"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"}}
26 -{"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"}}
27 -{"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"}}
28 -{"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"}}
29 -{"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"}}
30 -{"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}}}
31 -{"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"}}
32 -{"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"}}
33 -{"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"}}
34 -{"type":"runtime_exit","status":"success"}
apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_continue/codex_transcript.ndjson deleted
-95
@@ -1,95 +0,0 @@
1 -{"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"}}
2 -{"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"}}}}
3 -{"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"}}}
4 -{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}
5 -{"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"}}}
6 -{"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}}
7 -{"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}}
8 -{"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"}}}
9 -{"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"}}}
10 -{"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}}
11 -{"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}}
12 -{"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}}
13 -{"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}}}}
14 -{"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}}
15 -{"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}}
16 -{"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790297758731}}
17 -{"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}}
18 -{"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}}
19 -{"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}}
20 -{"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}}
21 -{"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}}
22 -{"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}}
23 -{"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}}
24 -{"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}}
25 -{"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}}
26 -{"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}}
27 -{"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}}
28 -{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","status":{"type":"idle"}},"emittedAtMs":1790297763365}}
29 -{"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}}
30 -{"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"}}}
31 -{"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}}
32 -{"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}}
33 -{"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}}
34 -{"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"}}}
35 -{"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"}}}
36 -{"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}}
37 -{"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}}
38 -{"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}}
39 -{"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}}}}
40 -{"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}}
41 -{"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}}
42 -{"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}}
43 -{"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}}
44 -{"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}}
45 -{"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}}
46 -{"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}}
47 -{"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}}
48 -{"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}}
49 -{"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}}
50 -{"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}}
51 -{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d60f-ee79-77b0-8e97-bb27c81fd026","status":{"type":"idle"}},"emittedAtMs":1790297766848}}
52 -{"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}}
53 -{"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"}}}
54 -{"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}}}}
55 -{"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}}
56 -{"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}}
57 -{"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}}
58 -{"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}}
59 -{"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}}
60 -{"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}}
61 -{"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}}
62 -{"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}}
63 -{"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}}
64 -{"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}}
65 -{"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}}
66 -{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","status":{"type":"idle"}},"emittedAtMs":1790297769081}}
67 -{"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}}
68 -{"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"}}}
69 -{"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}}}}
70 -{"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}}
71 -{"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}}
72 -{"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}}
73 -{"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}}
74 -{"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}}
75 -{"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}}
76 -{"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}}
77 -{"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}}
78 -{"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}}
79 -{"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}}
80 -{"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}}
81 -{"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}}
82 -{"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}}
83 -{"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}}
84 -{"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}}
85 -{"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}}
86 -{"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}}
87 -{"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}}
88 -{"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}}
89 -{"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}}
90 -{"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}}
91 -{"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}}
92 -{"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}}
93 -{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d60f-d9dd-7d82-8842-6efe9b7b5152","status":{"type":"idle"}},"emittedAtMs":1790297771343}}
94 -{"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}}
95 -{"type":"runtime_exit","status":"success"}
apps/server/src/orchestration-v2/threadHistoryPaging.test.ts
-35
@@ -14,9 +14,7 @@ import {
14 buildBoundedThreadProjection,
15 boundedTimelineEncodedBytes,
16 computeLatestLocalTurnOrdinal,
17 - decodeThreadHistoryCursor,
17 encodeThreadHistoryCursor,
19 - InvalidThreadHistoryCursorError,
18 projectedRowBoundedSnapshotEncodedBytes,
19 projectedRowEncodedBytes,
20 selectHistoryPageFromCursor,
@@ -289,13 +287,6 @@ describe("threadHistoryPaging", () => {
287 expect([...older.items, ...recent.items]).toHaveLength(items.length);
288 });
289
292 - it("rejects malformed cursors", () => {
293 - expect(() => decodeThreadHistoryCursor("not-valid")).toThrow(InvalidThreadHistoryCursorError);
294 - expect(() =>
295 - decodeThreadHistoryCursor(Buffer.from("{}", "utf8").toString("base64url")),
296 - ).toThrow(InvalidThreadHistoryCursorError);
297 - });
298 -
290 it("always includes at least one pathological oversized item", () => {
291 const items = [makeRow(0, { outputBytes: 2_000_000 }), makeRow(1, { outputBytes: 10 })];
292 const page = selectRecentTimelineWindow({
@@ -433,32 +424,6 @@ describe("threadHistoryPaging", () => {
424 expect(bounded.hasMoreHistory).toBe(true);
425 });
426
436 - it("retains all run_interrupt_request items even when no result is in the initial window", () => {
437 - const request = interruptRow(0, "run_interrupt_request");
438 - const result = interruptRow(1, "run_interrupt_result");
439 - const recent = makeRow(2);
440 - const full = makeProjection([request, result, recent]);
441 - const bounded = buildBoundedThreadProjection({
442 - projection: full,
443 - snapshotSequence: 4,
444 - policy: { maxItems: 1, maxEncodedBytes: 10_000_000 },
445 - });
446 -
447 - expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([
448 - "item-2",
449 - ]);
450 - expect(bounded.projection.turnItems.map((item) => String(item.id)).sort()).toEqual([
451 - "interrupt-req",
452 - "item-2",
453 - ]);
454 - expect(bounded.projection.turnItems.some((item) => item.type === "run_interrupt_request")).toBe(
455 - true,
456 - );
457 - expect(bounded.projection.turnItems.some((item) => item.type === "run_interrupt_result")).toBe(
458 - false,
459 - );
460 - });
461 -
427 it("charges local row.item duplication when measuring bounded timeline bytes", () => {
428 const rows = Array.from({ length: 8 }, (_, index) => makeRow(index, { outputBytes: 2_000 }));
429 const full = makeProjection(rows);
apps/server/src/orchestration-v2/toolOutputImageBytes.test.ts
+2
@@ -90,6 +90,7 @@ describe("stripUnservedToolOutputImageBytes", () => {
90 });
91 });
92
93 + // regression: #16652 stop storing tool image bytes no client reads
94 it("strips a Cursor image part that names no mime type", () => {
95 const item = toolItem({
96 content: [{ text: { text: "captured" } }, { image: { data: PNG_BASE64 } }],
@@ -184,6 +185,7 @@ describe("stripUnservedToolOutputImageBytes", () => {
185 expect(stripUnservedToolOutputImageBytes(item)).toBe(item);
186 });
187
188 + // regression: #16652 stop storing tool image bytes no client reads
189 it("measures the size instead of trusting one the provider supplied", () => {
190 const item = toolItem({
191 type: "image",
apps/server/src/orchestration-v2/workflowScriptQuery.test.ts
-18
@@ -3,7 +3,6 @@ import * as NodeFS from "node:fs";
3 import * as NodeOS from "node:os";
4 import * as NodePath from "node:path";
5 import * as NodeChildProcess from "node:child_process";
6 -import { OrchestrationWorkflowFileError } from "@t3tools/contracts";
6 import * as HostProcess from "@t3tools/shared/HostProcess";
7 import { it as effectIt } from "@effect/vitest";
8 import * as Effect from "effect/Effect";
@@ -51,23 +50,6 @@ describe("workflow script containment", () => {
50 }),
51 );
52
54 - effectIt.effect("rejects relative and non-js paths", () =>
55 - Effect.gen(function* () {
56 - const relative = yield* Effect.exit(readWorkflowScript({ scriptPath: "run.js" }));
57 - assert.equal(relative._tag, "Failure");
58 - const nonJs = yield* Effect.exit(
59 - readWorkflowScript({ scriptPath: scriptPath.replace(".js", ".ts") }),
60 - );
61 - assert.equal(nonJs._tag, "Failure");
62 - const error = yield* Effect.flip(readWorkflowScript({ scriptPath: "run.js" }));
63 - assert.equal(error._tag, "OrchestrationGetWorkflowScriptError");
64 - assert.equal(error.scriptPath, "run.js");
65 - assert.equal(error.reason, "invalid-path");
66 - assert.equal(error.message, "Workflow scripts must be absolute .js paths.");
67 - assert.instanceOf(error.cause, OrchestrationWorkflowFileError);
68 - }),
69 - );
70 -
53 effectIt.effect.skipIf(!symlinksSupported)(
54 "rejects paths outside the root and symlink escapes",
55 () =>
packages/provider-acp/src/server/adapter.ts
+3 -3
@@ -384,7 +384,7 @@ export function acpScopedNativeId(instanceId: ProviderInstanceId, nativeId: stri
384 return `provider-instance:${encodeURIComponent(instanceId)}:${nativeId}`;
385 }
386
387 -export function acpProviderItemNativeId(input: {
387 +function acpProviderItemNativeId(input: {
388 readonly instanceId: ProviderInstanceId;
389 readonly itemIdentityVersion: 2 | undefined;
390 readonly nativeId: string;
@@ -1219,14 +1219,14 @@ function acpIsProviderContinuationMessage(message: {
1219 return message.createdBy === "agent" && message.creationSource === "provider";
1220 }
1221
1222 -export function acpCarryoverTerminalShouldClearContinuation(input: {
1222 +function acpCarryoverTerminalShouldClearContinuation(input: {
1223 readonly continuationOffered: boolean;
1224 readonly wakeBufferLength: number;
1225 }): boolean {
1226 return !input.continuationOffered && input.wakeBufferLength === 0;
1227 }
1228
1229 -export function acpTurnStartShouldPreserveContinuation(input: {
1229 +function acpTurnStartShouldPreserveContinuation(input: {
1230 readonly continuationRequested: boolean;
1231 readonly isContinuationTurn: boolean;
1232 readonly wakeBufferLength: number;