Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it, vi } from "vite-plus/test";
3import { it as effectIt } from "@effect/vitest";
4import {
5 CheckpointScopeId,
6 MessageId,
7 NodeId,
8 ProviderSessionId,
9 ProviderThreadId,
10 ProviderDriverKind,
11 ProviderInstanceId,
12 ProviderSetupError,
13 RunAttemptId,
14 RunId,
15 ThreadId,
16 ProjectId,
17 type OrchestrationV2ThreadProjection,
18 OrchestrationV2DomainEvent,
19} from "@t3tools/contracts";
20import * as Cause from "effect/Cause";
21import * as DateTime from "effect/DateTime";
22import * as Deferred from "effect/Deferred";
23import * as Effect from "effect/Effect";
24import * as FileSystem from "effect/FileSystem";
25import * as Fiber from "effect/Fiber";
26import * as Layer from "effect/Layer";
27import * as Option from "effect/Option";
28import * as Path from "effect/Path";
29import * as Schema from "effect/Schema";
30
31import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
32import * as GitWorkflow from "../git/GitWorkflowService.ts";
33import * as ProjectService from "../project/ProjectService.ts";
34import * as ProviderAuthService from "../provider/ProviderAuthService.ts";
35import * as ContextHandoffService from "./ContextHandoffService.ts";
36import * as EventSink from "./EventSink.ts";
37import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
38import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
39import * as ProjectionStore from "./ProjectionStore.ts";
40import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
41import * as ProviderSessionManager from "./ProviderSessionManager.ts";
42import * as ProviderTurnStart from "./ProviderTurnStartService.ts";
43import * as RunExecutionService from "./RunExecutionService.ts";
44import * as RuntimePolicy from "./RuntimePolicy.ts";
45
46const isDomainEvent = Schema.is(OrchestrationV2DomainEvent);
47
48it("does not commit running state when inherited background routing cannot be read", async () => {
49 const threadId = ThreadId.make("thread_provider_turn_start_projection_failure");
50 const runId = RunId.make("run_provider_turn_start_projection_failure");
51 const attemptId = RunAttemptId.make("attempt_provider_turn_start_projection_failure");
52 const rootNodeId = NodeId.make("node_provider_turn_start_projection_failure");
53 const providerThreadId = ProviderThreadId.make(
54 "provider_thread_provider_turn_start_projection_failure",
55 );
56 const providerSessionId = ProviderSessionId.make(
57 "provider_session_provider_turn_start_projection_failure",
58 );
59 const messageId = MessageId.make("message_provider_turn_start_projection_failure");
60 const checkpointScopeId = CheckpointScopeId.make(
61 "checkpoint_scope_provider_turn_start_projection_failure",
62 );
63 const projection = {
64 thread: {
65 id: threadId,
66 projectId: ProjectId.make("project_provider_turn_start_projection_failure"),
67 branch: "feature/restore",
68 worktreePath: "/tmp/missing-provider-turn-start-worktree",
69 },
70 runs: [
71 {
72 id: runId,
73 status: "starting",
74 rootNodeId,
75 activeAttemptId: attemptId,
76 providerThreadId,
77 userMessageId: messageId,
78 ordinal: 2,
79 },
80 ],
81 nodes: [{ id: rootNodeId, checkpointScopeId }],
82 attempts: [{ id: attemptId }],
83 providerThreads: [{ id: providerThreadId, providerSessionId }],
84 messages: [{ id: messageId, text: "Continue", attachments: [] }],
85 checkpointScopes: [{ id: checkpointScopeId }],
86 contextHandoffs: [],
87 contextTransfers: [],
88 turnItems: [],
89 } as unknown as OrchestrationV2ThreadProjection;
90 let projectionReadCount = 0;
91 const writeIfRunCurrent = vi.fn(() =>
92 Effect.succeed({ committed: true, storedEvents: [] } as never),
93 );
94 const startRootRun = vi.fn(() => Effect.void);
95 const pruneWorktrees = vi.fn(() => Effect.void);
96 const createWorktree = vi.fn(() => Effect.succeed({} as never));
97 const layer = ProviderTurnStart.layer.pipe(
98 Layer.provide(
99 Layer.mergeAll(
100 Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}),
101 Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }),
102 IdAllocator.layer,
103 Path.layer,
104 FileSystem.layerNoop({ exists: () => Effect.succeed(false) }),
105 Layer.mock(GitWorkflow.GitWorkflowService)({ pruneWorktrees, createWorktree }),
106 Layer.mock(ProjectService.ProjectService)({
107 getById: () =>
108 Effect.succeed(
109 Option.some({ workspaceRoot: "/tmp/provider-turn-start-project" } as never),
110 ),
111 }),
112 Layer.mock(ProjectionStore.ProjectionStoreV2)({
113 getThreadRecords: () => {
114 projectionReadCount += 1;
115 return Effect.succeed(projection);
116 },
117 getTurnStartContext: () => {
118 projectionReadCount += 1;
119 return Effect.succeed({
120 ...projection,
121 hasConversation: projection.messages.some(
122 (m) =>
123 m.role === "user" &&
124 (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0),
125 ),
126 });
127 },
128 getRuntimeRecoveryProjection: () => {
129 projectionReadCount += 1;
130 return Effect.fail(
131 new ProjectionStore.ProjectionStoreReadError({
132 threadId,
133 cause: "simulated inherited-background projection failure",
134 }),
135 );
136 },
137 }),
138 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}),
139 Layer.mock(ProviderAuthService.ProviderAuthService)({
140 tryHandlePromptCommand: () => Effect.succeed(false),
141 }),
142 Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }),
143 Layer.mock(RuntimePolicy.RuntimePolicyV2)({}),
144 ),
145 ),
146 );
147
148 await Effect.gen(function* () {
149 const error = yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2)
150 .start({ threadId, runId })
151 .pipe(Effect.flip);
152
153 expect(error._tag).toBe("ProviderTurnStartError");
154 expect(projectionReadCount).toBe(3);
155 expect(pruneWorktrees).toHaveBeenCalledWith({ cwd: "/tmp/provider-turn-start-project" });
156 expect(createWorktree).toHaveBeenCalledWith({
157 cwd: "/tmp/provider-turn-start-project",
158 refName: "feature/restore",
159 path: "/tmp/missing-provider-turn-start-worktree",
160 });
161 expect(writeIfRunCurrent).not.toHaveBeenCalled();
162 expect(startRootRun).not.toHaveBeenCalled();
163 }).pipe(Effect.provide(layer), Effect.runPromise);
164});
165
166function makeLocalCommandHarness(input: {
167 readonly text: string;
168 readonly worktreePath?: string;
169 readonly fileSystem?: FileSystem.FileSystem;
170 readonly previousNativeSession?: boolean;
171 readonly previousMessages?: ReadonlyArray<string>;
172 readonly logoutFailure?: string;
173 readonly openFailure?: unknown;
174 readonly ensureThreadFailure?: unknown;
175 readonly historyReadFailureAfterFallback?: unknown;
176 readonly interruptOpen?: boolean;
177 readonly interruptRunBeforeOpenFailure?: boolean;
178 readonly writeFailure?: unknown;
179 readonly failReadsAfterRunning?: boolean;
180}) {
181 const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z");
182 const threadId = ThreadId.make("thread-native-account-command");
183 const runId = RunId.make("run-native-account-command");
184 const rootNodeId = NodeId.make("root-native-account-command");
185 const attemptId = RunAttemptId.make("attempt-native-account-command");
186 const providerThreadId = ProviderThreadId.make("new-provider-thread");
187 const providerSessionId = ProviderSessionId.make("new-provider-session");
188 const oldProviderThreadId = ProviderThreadId.make("existing-native-provider-thread");
189 const oldInstanceId = ProviderInstanceId.make("antigravity-personal");
190 const newInstanceId = ProviderInstanceId.make("codex-personal");
191 const checkpointScopeId = CheckpointScopeId.make("scope-native-account-command");
192 const messageId = MessageId.make("message-native-account-command");
193 const run: OrchestrationV2ThreadProjection["runs"][number] = {
194 id: runId,
195 threadId,
196 ordinal: 2,
197 providerInstanceId: newInstanceId,
198 modelSelection: { instanceId: newInstanceId, model: "gpt-5.4" },
199 providerThreadId,
200 userMessageId: messageId,
201 rootNodeId,
202 activeAttemptId: attemptId,
203 status: "starting",
204 requestedAt: now,
205 startedAt: null,
206 completedAt: null,
207 checkpointId: null,
208 contextHandoffId: null,
209 };
210 const providerThread: OrchestrationV2ThreadProjection["providerThreads"][number] = {
211 id: providerThreadId,
212 driver: ProviderDriverKind.make("codex"),
213 providerInstanceId: newInstanceId,
214 providerSessionId,
215 appThreadId: threadId,
216 ownerNodeId: null,
217 nativeThreadRef: null,
218 nativeConversationHeadRef: null,
219 status: "not_loaded",
220 firstRunOrdinal: 2,
221 lastRunOrdinal: 2,
222 handoffIds: [],
223 forkedFrom: null,
224 createdAt: now,
225 updatedAt: now,
226 };
227 const message: OrchestrationV2ThreadProjection["messages"][number] = {
228 id: messageId,
229 threadId,
230 runId,
231 nodeId: rootNodeId,
232 role: "user",
233 text: input.text,
234 attachments: [],
235 streaming: false,
236 createdBy: "user",
237 creationSource: "web",
238 createdAt: now,
239 updatedAt: now,
240 };
241 let projection: OrchestrationV2ThreadProjection = {
242 thread: {
243 id: threadId,
244 activeProviderThreadId: providerThreadId,
245 projectId: ProjectId.make("project-native-account-command"),
246 branch: input.worktreePath === undefined ? null : "feature/restore",
247 worktreePath: input.worktreePath ?? null,
248 } as OrchestrationV2ThreadProjection["thread"],
249 runs: [
250 ...(input.previousNativeSession
251 ? [
252 {
253 ...run,
254 id: RunId.make("previous-native-run"),
255 ordinal: 1,
256 status: "completed" as const,
257 providerInstanceId: oldInstanceId,
258 providerThreadId: oldProviderThreadId,
259 },
260 ]
261 : []),
262 run,
263 ],
264 attempts: [
265 {
266 id: attemptId,
267 runId,
268 rootNodeId,
269 attemptOrdinal: 1,
270 providerInstanceId: newInstanceId,
271 providerThreadId,
272 providerTurnId: null,
273 reason: "initial",
274 status: "pending",
275 startedAt: null,
276 completedAt: null,
277 },
278 ],
279 nodes: [
280 {
281 id: rootNodeId,
282 threadId,
283 runId,
284 parentNodeId: null,
285 rootNodeId,
286 kind: "root_turn",
287 status: "pending",
288 countsForRun: true,
289 providerThreadId,
290 providerTurnId: null,
291 nativeItemRef: null,
292 runtimeRequestId: null,
293 checkpointScopeId,
294 startedAt: null,
295 completedAt: null,
296 },
297 ],
298 providerThreads: [
299 ...(input.previousNativeSession
300 ? [
301 {
302 ...providerThread,
303 id: oldProviderThreadId,
304 providerInstanceId: oldInstanceId,
305 driver: ProviderDriverKind.make("antigravity"),
306 lastRunOrdinal: 1,
307 nativeThreadRef: {
308 driver: ProviderDriverKind.make("antigravity"),
309 nativeId: "existing-session",
310 strength: "strong" as const,
311 },
312 },
313 ]
314 : []),
315 providerThread,
316 ],
317 messages: [
318 ...(input.previousMessages ?? []).map((text, index) => ({
319 ...message,
320 id: MessageId.make(`previous-message-${index}`),
321 text,
322 })),
323 message,
324 ],
325 checkpointScopes: [
326 {
327 id: checkpointScopeId,
328 threadId,
329 runId,
330 nodeId: rootNodeId,
331 parentScopeId: null,
332 providerThreadId,
333 kind: "root_run",
334 ordinalWithinParent: 0,
335 advancesAppRunCount: true,
336 cwd: "/tmp/native-account-command",
337 createdAt: now,
338 },
339 ],
340 providerSessions: [],
341 providerTurns: [],
342 contextHandoffs: [],
343 contextTransfers: [],
344 turnItems: [],
345 visibleTurnItems: [],
346 runtimeRequests: [],
347 subagents: [],
348 plans: [],
349 checkpoints: [],
350 updatedAt: now,
351 };
352 if ("historyReadFailureAfterFallback" in input) {
353 const nativeThreadRef = {
354 driver: providerThread.driver,
355 nativeId: "native-resume-thread",
356 strength: "strong" as const,
357 };
358 projection = {
359 ...projection,
360 providerThreads: projection.providerThreads.map((candidate) =>
361 candidate.id === providerThreadId ? { ...candidate, nativeThreadRef } : candidate,
362 ),
363 };
364 }
365 const events: Array<OrchestrationV2DomainEvent> = [];
366 const interruptRun = () => {
367 projection = {
368 ...projection,
369 runs: projection.runs.map((candidate) =>
370 candidate.id === runId
371 ? { ...candidate, status: "interrupted", completedAt: now }
372 : candidate,
373 ),
374 };
375 };
376 const ensureThread = vi.fn(() =>
377 Effect.sync(() => {
378 if (input.interruptRunBeforeOpenFailure === true) interruptRun();
379 }).pipe(
380 Effect.andThen(
381 Effect.fail(
382 new ProviderAdapter.ProviderAdapterEventStreamError({
383 driver: providerThread.driver,
384 providerSessionId,
385 cause: input.ensureThreadFailure,
386 }),
387 ),
388 ),
389 ),
390 );
391 const resumeFallbackSession = {
392 driver: providerThread.driver,
393 resumeThread: () =>
394 Effect.fail(
395 new ProviderAdapter.ProviderAdapterEventStreamError({
396 driver: providerThread.driver,
397 providerSessionId,
398 cause: "native thread is gone",
399 }),
400 ),
401 ensureThread: () => Effect.succeed(providerThread),
402 };
403 const open = vi.fn(() =>
404 input.interruptOpen === true
405 ? Effect.interrupt
406 : "historyReadFailureAfterFallback" in input
407 ? Effect.succeed(resumeFallbackSession as never)
408 : "ensureThreadFailure" in input
409 ? Effect.succeed({ driver: providerThread.driver, ensureThread } as never)
410 : "openFailure" in input
411 ? Effect.sync(() => {
412 if (input.interruptRunBeforeOpenFailure === true) interruptRun();
413 }).pipe(
414 Effect.andThen(
415 Effect.fail(
416 new ProviderSessionManager.ProviderSessionOpenError({
417 instanceId: newInstanceId,
418 providerSessionId,
419 cause: input.openFailure,
420 }),
421 ),
422 ),
423 )
424 : input.failReadsAfterRunning === true
425 ? Effect.succeed({
426 driver: providerThread.driver,
427 providerSession: {
428 id: providerSessionId,
429 driver: providerThread.driver,
430 providerInstanceId: newInstanceId,
431 status: "ready",
432 cwd: "/tmp/native-account-command",
433 model: null,
434 capabilities: CodexProviderCapabilitiesV2,
435 createdAt: now,
436 updatedAt: now,
437 lastError: null,
438 },
439 ensureThread: () => Effect.succeed(providerThread),
440 } as never)
441 : Effect.die("A local command must not open a native session."),
442 );
443 const startRootRun = vi.fn<
444 (input: RunExecutionService.RunExecutionServiceV2StartRootRunInput) => Effect.Effect<void>
445 >(() =>
446 input.failReadsAfterRunning === true
447 ? Effect.void
448 : Effect.die("A local command must not start a native turn."),
449 );
450 const failReadIfRunning = Effect.suspend(() =>
451 input.failReadsAfterRunning === true &&
452 projection.runs.find((candidate) => candidate.id === runId)?.status === "running"
453 ? Effect.fail(
454 new ProjectionStore.ProjectionStoreReadError({ threadId, cause: "database unavailable" }),
455 )
456 : Effect.void,
457 );
458 const tryHandlePromptCommand = vi.fn(() =>
459 input.logoutFailure === undefined
460 ? Effect.succeed(true)
461 : Effect.fail(
462 new ProviderSetupError({
463 instanceId: oldInstanceId,
464 operation: "logout",
465 detail: input.logoutFailure,
466 }),
467 ),
468 );
469 const writeIfRunCurrent = vi.fn(({ events: incoming, activeAttemptId, expectedStatus }) =>
470 "writeFailure" in input
471 ? Effect.fail(
472 new EventSink.EventSinkWriteError({
473 eventCount: incoming.length,
474 cause: input.writeFailure,
475 }),
476 )
477 : Effect.sync(() => {
478 const current = projection.runs.find((candidate) => candidate.id === runId);
479 const committed =
480 current !== undefined &&
481 current.activeAttemptId === activeAttemptId &&
482 current.status === expectedStatus;
483 if (committed) {
484 for (const event of incoming) {
485 expect(isDomainEvent(event)).toBe(true);
486 events.push(event);
487 projection = ProjectionStore.applyToProjection(projection, event);
488 }
489 }
490 return { committed, storedEvents: [] };
491 }),
492 );
493 const resolveRuntimePolicy = vi.fn(
494 ({ thread }: Parameters<RuntimePolicy.RuntimePolicyV2Shape["resolve"]>[0]) =>
495 Effect.succeed({ cwd: thread.worktreePath ?? "/tmp/native-account-command" } as never),
496 );
497 const createWorktree = vi.fn(() => Effect.succeed({} as never));
498 const getThreadRecords = vi.fn<ProjectionStore.ProjectionStoreV2Shape["getThreadRecords"]>(() =>
499 Effect.succeed(projection),
500 );
501 const getTurnStartContext = vi.fn(() =>
502 Effect.succeed({
503 ...projection,
504 hasConversation: projection.messages.some(
505 (m) =>
506 m.role === "user" &&
507 (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0),
508 ),
509 }),
510 );
511 const layer = ProviderTurnStart.layer.pipe(
512 Layer.provide(
513 Layer.mergeAll(
514 Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({
515 prepareProviderHandoff: () => Effect.die("history read must fail first"),
516 }),
517 Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }),
518 IdAllocator.layer,
519 Path.layer,
520 input.fileSystem === undefined
521 ? FileSystem.layerNoop({ exists: () => Effect.succeed(true) })
522 : Layer.succeed(FileSystem.FileSystem, input.fileSystem),
523 Layer.mock(GitWorkflow.GitWorkflowService)({
524 pruneWorktrees: () => Effect.void,
525 createWorktree,
526 }),
527 Layer.mock(ProjectService.ProjectService)({
528 getById: () =>
529 Effect.succeed(Option.some({ workspaceRoot: "/tmp/native-account-project" } as never)),
530 }),
531 Layer.mock(ProjectionStore.ProjectionStoreV2)({
532 getThreadRecords,
533 getTurnStartContext,
534 getRuntimeRecoveryProjection: () =>
535 Effect.as(failReadIfRunning, {
536 ...projection,
537 hasConversation: projection.messages.some(
538 (m) =>
539 m.role === "user" &&
540 (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0),
541 ),
542 }),
543 getTurnStartHistory: () =>
544 Effect.fail(
545 new ProjectionStore.ProjectionStoreReadError({
546 threadId,
547 cause: input.historyReadFailureAfterFallback,
548 }),
549 ),
550 }),
551 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open }),
552 Layer.mock(ProviderAuthService.ProviderAuthService)({ tryHandlePromptCommand }),
553 Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }),
554 Layer.mock(RuntimePolicy.RuntimePolicyV2)({
555 resolve: resolveRuntimePolicy,
556 }),
557 ),
558 ),
559 );
560 return {
561 getThreadRecords,
562 getTurnStartContext,
563 setProjection: (next: OrchestrationV2ThreadProjection) => {
564 projection = next;
565 },
566 resolveRuntimePolicy,
567 createWorktree,
568 open,
569 writeIfRunCurrent,
570 startRootRun,
571 tryHandlePromptCommand,
572 events,
573 oldInstanceId,
574 newInstanceId,
575 attemptId,
576 projection: () => projection,
577 start: Effect.gen(function* () {
578 yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2).start({ threadId, runId });
579 }).pipe(Effect.provide(layer)),
580 startWithRetry: Effect.gen(function* () {
581 yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2).start({
582 threadId,
583 runId,
584 willRetry: true,
585 });
586 }).pipe(Effect.provide(layer)),
587 };
588}
589
590effectIt.effect.each(["cleanup-first", "startup-first"])(
591 "coordinates provider startup with %s",
592 (order) =>
593 Effect.gen(function* () {
594 const fileSystem = yield* FileSystem.FileSystem;
595 const path = yield* Path.Path;
596 const workspaceRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-start-" });
597 const worktreePath = path.join(workspaceRoot, "worktree");
598 yield* fileSystem.makeDirectory(worktreePath);
599 const release = yield* Deferred.make<void>();
600 const openEntered = yield* Deferred.make<void>();
601 const harness = makeLocalCommandHarness({
602 text: "Continue",
603 worktreePath,
604 fileSystem,
605 failReadsAfterRunning: true,
606 });
607 harness.createWorktree.mockImplementation(() =>
608 fileSystem.makeDirectory(worktreePath).pipe(Effect.as({} as never), Effect.orDie),
609 );
610 const open = harness.open.getMockImplementation()!;
611 harness.open.mockImplementation(() =>
612 Effect.gen(function* () {
613 expect(yield* fileSystem.exists(worktreePath).pipe(Effect.orDie)).toBe(true);
614 yield* Deferred.succeed(openEntered, undefined);
615 if (order === "startup-first") yield* Deferred.await(release);
616 return yield* open();
617 }),
618 );
619 let cleanupEntered = false;
620 const cleanupEffect = withWorkspaceLease(
621 worktreePath,
622 Effect.gen(function* () {
623 cleanupEntered = true;
624 if (order === "cleanup-first") yield* Deferred.await(release);
625 else {
626 expect(harness.projection().providerSessions).toHaveLength(1);
627 expect(harness.projection().runs.at(-1)?.status).toBe("running");
628 }
629 yield* fileSystem.remove(worktreePath, { recursive: true, force: true });
630 }),
631 );
632 const cleanup =
633 order === "cleanup-first"
634 ? yield* cleanupEffect.pipe(Effect.forkChild({ startImmediately: true }))
635 : undefined;
636 const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true }));
637 if (order === "cleanup-first") expect(harness.open).not.toHaveBeenCalled();
638 if (order === "startup-first") yield* Deferred.await(openEntered);
639 const laterCleanup =
640 order === "startup-first"
641 ? yield* cleanupEffect.pipe(Effect.forkChild({ startImmediately: true }))
642 : undefined;
643 if (order === "startup-first") expect(cleanupEntered).toBe(false);
644 yield* Deferred.succeed(release, undefined);
645 if (cleanup !== undefined) yield* Fiber.join(cleanup);
646 yield* Fiber.join(startup);
647 if (laterCleanup !== undefined) yield* Fiber.join(laterCleanup);
648 if (order === "cleanup-first") {
649 expect(harness.createWorktree).toHaveBeenCalledWith({
650 cwd: "/tmp/native-account-project",
651 refName: "feature/restore",
652 path: worktreePath,
653 });
654 }
655 expect(harness.resolveRuntimePolicy).toHaveBeenCalledWith(
656 expect.objectContaining({
657 thread: expect.objectContaining({ worktreePath }),
658 }),
659 );
660 expect(harness.open).toHaveBeenCalledWith(
661 expect.objectContaining({
662 runtimePolicy: expect.objectContaining({ cwd: worktreePath }),
663 }),
664 );
665 expect(harness.startRootRun).toHaveBeenCalledWith(
666 expect.objectContaining({
667 appThread: expect.objectContaining({ worktreePath }),
668 runtimePolicy: expect.objectContaining({ cwd: worktreePath }),
669 }),
670 );
671 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
672);
673
674effectIt.effect("reads only thread state before taking the startup lease", () =>
675 Effect.gen(function* () {
676 const harness = makeLocalCommandHarness({ text: "/logout", previousNativeSession: true });
677 yield* harness.start;
678 expect(harness.getThreadRecords).toHaveBeenCalledExactlyOnceWith(
679 harness.projection().thread.id,
680 [],
681 );
682 expect(harness.getTurnStartContext).toHaveBeenCalledOnce();
683 expect(harness.projection().runs.at(-1)?.status).toBe("completed");
684 }),
685);
686
687effectIt.effect("reads current startup state after waiting for the workspace lease", () =>
688 Effect.gen(function* () {
689 const worktreePath = "/tmp/provider-start-fresh-state";
690 const release = yield* Deferred.make<void>();
691 const readEntered = yield* Deferred.make<void>();
692 const harness = makeLocalCommandHarness({
693 text: "Continue",
694 worktreePath,
695 failReadsAfterRunning: true,
696 });
697 harness.getThreadRecords.mockImplementationOnce(() =>
698 Deferred.succeed(readEntered, undefined).pipe(Effect.as(harness.projection())),
699 );
700 const holder = yield* withWorkspaceLease(worktreePath, Deferred.await(release)).pipe(
701 Effect.forkChild({ startImmediately: true }),
702 );
703 const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true }));
704 yield* Deferred.await(readEntered);
705 expect(harness.getTurnStartContext).not.toHaveBeenCalled();
706 const projection = harness.projection();
707 harness.setProjection({
708 ...projection,
709 runs: projection.runs.map((run) => ({ ...run, status: "running" })),
710 });
711 yield* Deferred.succeed(release, undefined);
712 yield* Fiber.join(holder);
713 yield* Fiber.join(startup);
714 expect(harness.open).not.toHaveBeenCalled();
715 expect(harness.startRootRun).not.toHaveBeenCalled();
716 }),
717);
718
719effectIt.effect("starts another provider in the same checkout while a turn is pending", () =>
720 Effect.gen(function* () {
721 const worktreePath = "/tmp/provider-start-shared-checkout";
722 const turnEntered = yield* Deferred.make<void>();
723 const releaseTurn = yield* Deferred.make<void>();
724 const first = makeLocalCommandHarness({
725 text: "Continue",
726 worktreePath,
727 failReadsAfterRunning: true,
728 });
729 const second = makeLocalCommandHarness({
730 text: "Continue",
731 worktreePath,
732 failReadsAfterRunning: true,
733 });
734 first.startRootRun.mockImplementation(() =>
735 Deferred.succeed(turnEntered, undefined).pipe(Effect.andThen(Deferred.await(releaseTurn))),
736 );
737 const pending = yield* first.start.pipe(Effect.forkChild({ startImmediately: true }));
738 yield* Deferred.await(turnEntered);
739 yield* second.start;
740 expect(second.startRootRun).toHaveBeenCalledOnce();
741 expect(second.projection().runs.at(-1)?.status).toBe("running");
742 yield* Deferred.succeed(releaseTurn, undefined);
743 yield* Fiber.join(pending);
744 }),
745);
746
747effectIt.effect("terminalizes a starting run when its provider session cannot open", () =>
748 Effect.gen(function* () {
749 const harness = makeLocalCommandHarness({
750 text: "Continue",
751 openFailure: new Error("DESCRIPTION is not valid ACP JSON"),
752 });
753
754 yield* harness.start;
755
756 expect(harness.open).toHaveBeenCalledOnce();
757 expect(harness.startRootRun).not.toHaveBeenCalled();
758 expect(harness.writeIfRunCurrent).toHaveBeenCalledWith(
759 expect.objectContaining({
760 activeAttemptId: harness.attemptId,
761 expectedStatus: "starting",
762 }),
763 );
764 const projection = harness.projection();
765 expect(projection.runs.at(-1)).toMatchObject({ status: "failed", startedAt: null });
766 expect(projection.attempts[0]).toMatchObject({ status: "failed", startedAt: null });
767 expect(projection.nodes[0]).toMatchObject({ status: "failed", startedAt: null });
768 expect(projection.turnItems).toMatchObject([
769 {
770 type: "error",
771 status: "failed",
772 failure: {
773 class: "provider_error",
774 message: "DESCRIPTION is not valid ACP JSON",
775 },
776 },
777 ]);
778 }),
779);
780
781effectIt.effect("leaves the run starting when a session-open failure will be retried", () =>
782 Effect.gen(function* () {
783 const harness = makeLocalCommandHarness({
784 text: "Continue",
785 openFailure: new Error("provider session rejected"),
786 });
787
788 const error = yield* harness.startWithRetry.pipe(Effect.flip);
789
790 expect(error._tag).toBe("ProviderTurnStartError");
791 expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
792 expect(harness.projection().runs.at(-1)?.status).toBe("starting");
793 }),
794);
795
796effectIt.effect("keeps a session-open failure retryable when terminal persistence fails", () =>
797 Effect.gen(function* () {
798 const harness = makeLocalCommandHarness({
799 text: "Continue",
800 openFailure: new Error("provider session rejected"),
801 writeFailure: new Error("database unavailable"),
802 });
803
804 const error = yield* harness.start.pipe(Effect.flip);
805
806 expect(error._tag).toBe("ProviderTurnStartError");
807 expect(harness.writeIfRunCurrent).toHaveBeenCalledOnce();
808 expect(harness.startRootRun).not.toHaveBeenCalled();
809 expect(harness.projection().runs.at(-1)?.status).toBe("starting");
810 expect(harness.events).toEqual([]);
811 }),
812);
813
814effectIt.effect("does not terminalize a provider-session open interruption", () =>
815 Effect.gen(function* () {
816 const harness = makeLocalCommandHarness({ text: "Continue", interruptOpen: true });
817
818 const exit = yield* Effect.exit(harness.start);
819
820 expect(exit._tag).toBe("Failure");
821 if (exit._tag === "Failure") {
822 expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
823 }
824 expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
825 expect(harness.startRootRun).not.toHaveBeenCalled();
826 expect(harness.projection().runs.at(-1)?.status).toBe("starting");
827 expect(harness.events).toEqual([]);
828 }),
829);
830
831effectIt.effect("does not overwrite a run interrupted while its provider session opens", () =>
832 Effect.gen(function* () {
833 const harness = makeLocalCommandHarness({
834 text: "Continue",
835 openFailure: new Error("provider session rejected"),
836 interruptRunBeforeOpenFailure: true,
837 });
838
839 yield* harness.start;
840
841 expect(harness.writeIfRunCurrent).toHaveBeenCalledOnce();
842 expect(harness.startRootRun).not.toHaveBeenCalled();
843 const projection = harness.projection();
844 expect(projection.runs.at(-1)?.status).toBe("interrupted");
845 expect(projection.attempts[0]?.status).toBe("pending");
846 expect(projection.nodes[0]?.status).toBe("pending");
847 expect(projection.turnItems).toEqual([]);
848 expect(harness.events).toEqual([]);
849 }),
850);
851
852effectIt.effect("fails a starting run when its last start attempt cannot load the thread", () =>
853 Effect.gen(function* () {
854 const harness = makeLocalCommandHarness({
855 text: "Continue",
856 ensureThreadFailure: new Error("Pi RPC read failed: pi process exited with code 1."),
857 });
858
859 yield* harness.start;
860
861 expect(harness.startRootRun).not.toHaveBeenCalled();
862 const projection = harness.projection();
863 expect(projection.runs.at(-1)).toMatchObject({ status: "failed", startedAt: null });
864 expect(projection.attempts[0]).toMatchObject({ status: "failed", startedAt: null });
865 expect(projection.nodes[0]).toMatchObject({ status: "failed", startedAt: null });
866 expect(projection.turnItems).toMatchObject([
867 {
868 type: "error",
869 title: "Provider turn failed to start",
870 failure: {
871 class: "provider_error",
872 message: "Pi RPC read failed: pi process exited with code 1.",
873 },
874 },
875 ]);
876 }),
877);
878
879effectIt.effect("leaves the run starting when a thread-load failure will be retried", () =>
880 Effect.gen(function* () {
881 const harness = makeLocalCommandHarness({
882 text: "Continue",
883 ensureThreadFailure: new Error("pi process exited with code 1"),
884 });
885
886 const error = yield* harness.startWithRetry.pipe(Effect.flip);
887
888 expect(error._tag).toBe("ProviderTurnStartError");
889 expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
890 expect(harness.projection().runs.at(-1)?.status).toBe("starting");
891 }),
892);
893
894effectIt.effect("keeps a thread-load failure retryable when terminal persistence fails", () =>
895 Effect.gen(function* () {
896 const harness = makeLocalCommandHarness({
897 text: "Continue",
898 ensureThreadFailure: new Error("pi process exited with code 1"),
899 writeFailure: new Error("database unavailable"),
900 });
901
902 const error = yield* harness.start.pipe(Effect.flip);
903
904 expect(error._tag).toBe("ProviderTurnStartError");
905 expect(harness.projection().runs.at(-1)?.status).toBe("starting");
906 expect(harness.events).toEqual([]);
907 }),
908);
909
910effectIt.effect(
911 "keeps a store failure after the provider loaded the thread typed and retryable",
912 () =>
913 Effect.gen(function* () {
914 const harness = makeLocalCommandHarness({
915 text: "Continue",
916 historyReadFailureAfterFallback: new Error("database unavailable"),
917 });
918
919 const error = yield* harness.start.pipe(Effect.flip);
920
921 expect(error._tag).toBe("ProviderTurnStartError");
922 expect((error.cause as { _tag?: string } | undefined)?._tag).toBe("ProjectionStoreReadError");
923 expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
924 expect(harness.projection().runs.at(-1)?.status).toBe("starting");
925 expect(harness.events).toEqual([]);
926 }),
927);
928
929effectIt.effect("does not mistake a failed state read for a superseded run", () =>
930 Effect.gen(function* () {
931 const harness = makeLocalCommandHarness({ text: "Continue", failReadsAfterRunning: true });
932
933 yield* harness.start;
934
935 expect(harness.projection().runs.at(-1)?.status).toBe("running");
936 const controls = harness.startRootRun.mock.calls[0]?.[0];
937 expect(controls).toBeDefined();
938 if (controls === undefined) return;
939 const startCheck = yield* Effect.flip(controls.shouldStartProviderTurn!());
940 const finalizeCheck = yield* Effect.flip(controls.shouldFinalizeRun!());
941 expect(startCheck._tag).toBe("ProjectionStoreReadError");
942 expect(finalizeCheck._tag).toBe("ProjectionStoreReadError");
943 }),
944);
945
946effectIt.effect("does not overwrite a run interrupted while its thread loads", () =>
947 Effect.gen(function* () {
948 const harness = makeLocalCommandHarness({
949 text: "Continue",
950 ensureThreadFailure: new Error("pi process exited with code 1"),
951 interruptRunBeforeOpenFailure: true,
952 });
953
954 yield* harness.start;
955
956 expect(harness.projection().runs.at(-1)?.status).toBe("interrupted");
957 expect(harness.projection().turnItems).toEqual([]);
958 expect(harness.events).toEqual([]);
959 }),
960);
961
962effectIt.effect(
963 "signs out the existing native provider before opening the newly selected provider",
964 () =>
965 Effect.gen(function* () {
966 const harness = makeLocalCommandHarness({ text: "/logout", previousNativeSession: true });
967
968 yield* harness.start;
969 yield* harness.start;
970
971 expect(harness.tryHandlePromptCommand).toHaveBeenCalledExactlyOnceWith({
972 instanceId: harness.oldInstanceId,
973 text: "/logout",
974 hasAttachments: false,
975 });
976 expect(harness.open).not.toHaveBeenCalled();
977 expect(harness.startRootRun).not.toHaveBeenCalled();
978 const projection = harness.projection();
979 expect(projection.runs.at(-1)?.status).toBe("completed");
980 expect(projection.attempts[0]?.status).toBe("completed");
981 expect(projection.nodes[0]?.status).toBe("completed");
982 expect(projection.turnItems).toMatchObject([
983 {
984 type: "command_execution",
985 title: "Provider signed out",
986 output: "Provider signed out",
987 status: "completed",
988 },
989 ]);
990 expect(projection.providerTurns).toEqual([]);
991 expect(projection.checkpoints).toEqual([]);
992 }),
993);
994
995effectIt.effect("persists a failed sign-out without starting a provider turn", () =>
996 Effect.gen(function* () {
997 const harness = makeLocalCommandHarness({
998 text: "/logout",
999 logoutFailure: "Could not stop all sessions for this provider. Try again.",
1000 });
1001
1002 yield* harness.start;
1003
1004 expect(harness.open).not.toHaveBeenCalled();
1005 expect(harness.startRootRun).not.toHaveBeenCalled();
1006 expect(harness.projection().runs.at(-1)?.status).toBe("failed");
1007 expect(harness.projection().turnItems).toMatchObject([
1008 {
1009 type: "error",
1010 title: "Provider sign-out failed",
1011 failure: {
1012 class: "permission_error",
1013 message: "Could not stop all sessions for this provider. Try again.",
1014 },
1015 },
1016 ]);
1017 }),
1018);
1019
1020for (const previousMessages of [[], ["/compact", " /COMPACT "]]) {
1021 effectIt.effect(
1022 `rejects compaction without conversation context after ${previousMessages.length} prior compactions`,
1023 () =>
1024 Effect.gen(function* () {
1025 const harness = makeLocalCommandHarness({ text: "/compact", previousMessages });
1026
1027 yield* harness.start;
1028
1029 expect(harness.open).not.toHaveBeenCalled();
1030 expect(harness.tryHandlePromptCommand).not.toHaveBeenCalled();
1031 expect(harness.startRootRun).not.toHaveBeenCalled();
1032 expect(harness.projection().runs.at(-1)?.status).toBe("failed");
1033 expect(harness.projection().turnItems).toMatchObject([
1034 {
1035 type: "error",
1036 failure: {
1037 class: "validation_error",
1038 message: "Start a conversation before compacting this thread.",
1039 },
1040 },
1041 ]);
1042 }),
1043 );
1044}