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