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