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 GitCommandError,
7 MessageId,
8 NodeId,
9 ProviderSessionId,
10 ProviderThreadId,
11 ProviderTurnId,
12 ProviderDriverKind,
13 ProviderInstanceId,
14 ProviderSetupError,
15 RunAttemptId,
16 RunId,
17 ThreadId,
18 ProjectId,
19 type OrchestrationV2ThreadProjection,
20 OrchestrationV2DomainEvent,
21} from "@t3tools/contracts";
22import * as Cause from "effect/Cause";
23import * as DateTime from "effect/DateTime";
24import * as Deferred from "effect/Deferred";
25import * as Effect from "effect/Effect";
26import * as FileSystem from "effect/FileSystem";
27import * as Fiber from "effect/Fiber";
28import * as Layer from "effect/Layer";
29import * as Option from "effect/Option";
30import * as Path from "effect/Path";
31import * as PlatformError from "effect/PlatformError";
32import * as Schema from "effect/Schema";
33
34import * as ServerConfig from "../config.ts";
35import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
36import * as GitWorkflow from "../git/GitWorkflowService.ts";
37import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
38import { layerRealGit } from "./ProviderTurnStartService.testkit.ts";
39import * as ProjectService from "../project/ProjectService.ts";
40import * as ProviderAuthService from "../provider/ProviderAuthService.ts";
41import * as ServerSettings from "../serverSettings.ts";
42import * as ContextHandoffService from "./ContextHandoffService.ts";
43import * as EventSink from "./EventSink.ts";
44import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
45import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
46import * as ProjectionStore from "./ProjectionStore.ts";
47import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
48import * as ProviderSessionManager from "./ProviderSessionManager.ts";
49import * as ProviderTurnStart from "./ProviderTurnStartService.ts";
50import * as RunExecutionService from "./RunExecutionService.ts";
51import * as RuntimePolicy from "./RuntimePolicy.ts";
52
53const isDomainEvent = Schema.is(OrchestrationV2DomainEvent);
54
55const managedWorktreesDir = "/tmp/provider-turn-start-worktrees";
56// fs.realpath applies `..` and `.` before following symlinks.
57const normalize = (target: string) => {
58 const parts: Array<string> = [];
59 for (const part of target.split("/")) {
60 if (part === "..") parts.pop();
61 else if (part !== "" && part !== ".") parts.push(part);
62 }
63 return `/${parts.join("/")}`;
64};
65const layerWorktreeLocation = (worktreesDir = managedWorktreesDir) =>
66 Layer.mergeAll(
67 Path.layer,
68 Layer.mock(ServerConfig.ServerConfig)({ worktreesDir } as ServerConfig.ServerConfig["Service"]),
69 ServerSettings.layerTest(),
70 );
71
72function startWithMissingWorktree(
73 worktreePath: string,
74 realPaths: Record<string, string> = {
75 [managedWorktreesDir]: managedWorktreesDir,
76 [`${managedWorktreesDir}/project`]: `${managedWorktreesDir}/project`,
77 },
78) {
79 const threadId = ThreadId.make("thread_provider_turn_start_projection_failure");
80 const runId = RunId.make("run_provider_turn_start_projection_failure");
81 const attemptId = RunAttemptId.make("attempt_provider_turn_start_projection_failure");
82 const rootNodeId = NodeId.make("node_provider_turn_start_projection_failure");
83 const providerThreadId = ProviderThreadId.make(
84 "provider_thread_provider_turn_start_projection_failure",
85 );
86 const providerSessionId = ProviderSessionId.make(
87 "provider_session_provider_turn_start_projection_failure",
88 );
89 const messageId = MessageId.make("message_provider_turn_start_projection_failure");
90 const checkpointScopeId = CheckpointScopeId.make(
91 "checkpoint_scope_provider_turn_start_projection_failure",
92 );
93 const projection = {
94 thread: {
95 id: threadId,
96 projectId: ProjectId.make("project_provider_turn_start_projection_failure"),
97 branch: "feature/restore",
98 worktreePath,
99 },
100 runs: [
101 {
102 id: runId,
103 status: "starting",
104 rootNodeId,
105 activeAttemptId: attemptId,
106 providerThreadId,
107 userMessageId: messageId,
108 ordinal: 2,
109 },
110 ],
111 nodes: [{ id: rootNodeId, checkpointScopeId }],
112 attempts: [{ id: attemptId }],
113 providerThreads: [{ id: providerThreadId, providerSessionId }],
114 messages: [{ id: messageId, text: "Continue", attachments: [] }],
115 checkpointScopes: [{ id: checkpointScopeId }],
116 contextHandoffs: [],
117 contextTransfers: [],
118 turnItems: [],
119 } as unknown as OrchestrationV2ThreadProjection;
120 let projectionReadCount = 0;
121 const writeIfRunCurrent = vi.fn(() =>
122 Effect.succeed({ committed: true, storedEvents: [] } as never),
123 );
124 const startRootRun = vi.fn(() => Effect.void);
125 const pruneWorktrees = vi.fn(() => Effect.void);
126 const createWorktree = vi.fn(() => Effect.succeed({} as never));
127 const listLocalBranchNames = vi.fn(() => Effect.succeed(["feature/restore"]));
128 const layer = ProviderTurnStart.layer.pipe(
129 Layer.provide(
130 Layer.mergeAll(
131 Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}),
132 Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }),
133 IdAllocator.layer,
134 Layer.succeed(FileSystem.FileSystem, {
135 exists: () => Effect.succeed(false),
136 realPath: (target: string) =>
137 normalize(target) in realPaths
138 ? Effect.succeed(realPaths[normalize(target)])
139 : Effect.fail(
140 PlatformError.systemError({
141 _tag: "NotFound",
142 module: "FileSystem",
143 method: "realPath",
144 pathOrDescriptor: target,
145 }),
146 ),
147 } as never),
148 layerWorktreeLocation(),
149 Layer.mock(GitWorkflow.GitWorkflowService)({
150 pruneWorktrees,
151 createWorktree,
152 listLocalBranchNames,
153 }),
154 Layer.mock(ProjectService.ProjectService)({
155 getById: () =>
156 Effect.succeedSome({ workspaceRoot: "/tmp/provider-turn-start-project" } as never),
157 }),
158 Layer.mock(ProjectionStore.ProjectionStoreV2)({
159 getThreadRecords: () => {
160 projectionReadCount += 1;
161 return Effect.succeed(projection);
162 },
163 getTurnStartContext: () => {
164 projectionReadCount += 1;
165 return Effect.succeed({
166 ...projection,
167 hasConversation: projection.messages.some(
168 (m) =>
169 m.role === "user" &&
170 (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0),
171 ),
172 });
173 },
174 getRuntimeRecoveryProjection: () => {
175 projectionReadCount += 1;
176 return Effect.fail(
177 new ProjectionStore.ProjectionStoreReadError({
178 threadId,
179 cause: "simulated inherited-background projection failure",
180 }),
181 );
182 },
183 }),
184 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}),
185 Layer.mock(ProviderAuthService.ProviderAuthService)({
186 tryHandlePromptCommand: () => Effect.succeed(false),
187 }),
188 Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }),
189 Layer.mock(RuntimePolicy.RuntimePolicyV2)({}),
190 ),
191 ),
192 );
193
194 const start = Effect.gen(function* () {
195 return yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2)
196 .start({ threadId, runId })
197 .pipe(Effect.flip);
198 }).pipe(Effect.provide(layer), Effect.runPromise);
199 return {
200 start,
201 pruneWorktrees,
202 createWorktree,
203 writeIfRunCurrent,
204 startRootRun,
205 projectionReads: () => projectionReadCount,
206 };
207}
208
209it.each([
210 {
211 label: "<managed>/<repo>/<branch>",
212 worktreePath: `${managedWorktreesDir}/project/feature-restore`,
213 recreated: true,
214 },
215 {
216 label: "the real path of a symlinked managed folder",
217 worktreePath: "/real-worktrees/project/feature-restore",
218 realPaths: { [managedWorktreesDir]: "/real-worktrees", "/real-worktrees": "/real-worktrees" },
219 recreated: true,
220 },
221 {
222 label: "a path outside the managed folder",
223 worktreePath: "/tmp/provider-turn-start-project/.git/hooks",
224 recreated: false,
225 },
226 {
227 label: "a symlink inside the managed folder that leads out",
228 worktreePath: `${managedWorktreesDir}/project/hooks`,
229 realPaths: {
230 [managedWorktreesDir]: managedWorktreesDir,
231 [`${managedWorktreesDir}/project`]: "/tmp/provider-turn-start-project/.git",
232 },
233 recreated: false,
234 },
235 {
236 label: "a folder nested below a worktree",
237 worktreePath: `${managedWorktreesDir}/project/feature-restore/link/hooks`,
238 recreated: false,
239 },
240 {
241 label: "'..' out of the managed folder",
242 worktreePath: `${managedWorktreesDir}/project/../../outside`,
243 recreated: false,
244 },
245 {
246 // Left raw on purpose: git follows `link` before applying `..`.
247 label: "'..' after a symlink inside the managed folder",
248 worktreePath: `${managedWorktreesDir}/project/x/link/../../hooks`,
249 realPaths: {
250 [managedWorktreesDir]: managedWorktreesDir,
251 [`${managedWorktreesDir}/project`]: `${managedWorktreesDir}/project`,
252 [`${managedWorktreesDir}/project/x`]: `${managedWorktreesDir}/project/x`,
253 [`${managedWorktreesDir}/project/x/link`]: "/tmp/provider-turn-start-project/.git/refs/heads",
254 },
255 recreated: false,
256 },
257 { label: "a relative path", worktreePath: "project/feature-restore", recreated: false },
258])("recreates a missing worktree only at the managed location: $label", async (input) => {
259 const harness = startWithMissingWorktree(input.worktreePath, input.realPaths);
260 await harness.start;
261 expect(harness.createWorktree).toHaveBeenCalledTimes(input.recreated ? 1 : 0);
262});
263
264function makeLocalCommandHarness(input: {
265 readonly text: string;
266 readonly worktreePath?: string;
267 readonly worktreesDir?: string;
268 readonly workspaceRoot?: string;
269 readonly gitWorkflow?: GitWorkflow.GitWorkflowService["Service"];
270 readonly fileSystem?: FileSystem.FileSystem;
271 readonly previousNativeSession?: boolean;
272 readonly previousMessages?: ReadonlyArray<string>;
273 readonly logoutFailure?: string;
274 readonly openFailure?: unknown;
275 readonly ensureThreadFailure?: unknown;
276 readonly historyReadFailureAfterFallback?: unknown;
277 readonly interruptOpen?: boolean;
278 readonly interruptRunBeforeOpenFailure?: boolean;
279 readonly writeFailure?: unknown;
280 readonly failReadsAfterRunning?: boolean;
281 readonly previousTurn?: {
282 readonly runStatus: "failed" | "completed";
283 readonly turnStatus: "running" | "completed" | "interrupted";
284 readonly differentThread?: boolean;
285 readonly liveSession?: boolean;
286 readonly interruptFailure?: boolean;
287 readonly interruptCurrentRun?: boolean;
288 };
289}) {
290 const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z");
291 const threadId = ThreadId.make("thread-native-account-command");
292 const runId = RunId.make("run-native-account-command");
293 const rootNodeId = NodeId.make("root-native-account-command");
294 const attemptId = RunAttemptId.make("attempt-native-account-command");
295 const providerThreadId = ProviderThreadId.make("new-provider-thread");
296 const providerSessionId = ProviderSessionId.make("new-provider-session");
297 const oldProviderThreadId = ProviderThreadId.make("existing-native-provider-thread");
298 const oldInstanceId = ProviderInstanceId.make("antigravity-personal");
299 const newInstanceId = ProviderInstanceId.make("codex-personal");
300 const checkpointScopeId = CheckpointScopeId.make("scope-native-account-command");
301 const messageId = MessageId.make("message-native-account-command");
302 const run: OrchestrationV2ThreadProjection["runs"][number] = {
303 id: runId,
304 threadId,
305 ordinal: 2,
306 providerInstanceId: newInstanceId,
307 modelSelection: { instanceId: newInstanceId, model: "gpt-5.4" },
308 providerThreadId,
309 userMessageId: messageId,
310 rootNodeId,
311 activeAttemptId: attemptId,
312 status: "starting",
313 requestedAt: now,
314 startedAt: null,
315 completedAt: null,
316 checkpointId: null,
317 contextHandoffId: null,
318 };
319 const providerThread: OrchestrationV2ThreadProjection["providerThreads"][number] = {
320 id: providerThreadId,
321 driver: ProviderDriverKind.make("codex"),
322 providerInstanceId: newInstanceId,
323 providerSessionId,
324 appThreadId: threadId,
325 ownerNodeId: null,
326 nativeThreadRef: null,
327 nativeConversationHeadRef: null,
328 status: "not_loaded",
329 firstRunOrdinal: 2,
330 lastRunOrdinal: 2,
331 handoffIds: [],
332 forkedFrom: null,
333 createdAt: now,
334 updatedAt: now,
335 };
336 const message: OrchestrationV2ThreadProjection["messages"][number] = {
337 id: messageId,
338 threadId,
339 runId,
340 nodeId: rootNodeId,
341 role: "user",
342 text: input.text,
343 attachments: [],
344 streaming: false,
345 createdBy: "user",
346 creationSource: "web",
347 createdAt: now,
348 updatedAt: now,
349 };
350 let projection: OrchestrationV2ThreadProjection = {
351 thread: {
352 id: threadId,
353 activeProviderThreadId: providerThreadId,
354 projectId: ProjectId.make("project-native-account-command"),
355 branch: input.worktreePath === undefined ? null : "feature/restore",
356 worktreePath: input.worktreePath ?? null,
357 } as OrchestrationV2ThreadProjection["thread"],
358 runs: [
359 ...(input.previousNativeSession
360 ? [
361 {
362 ...run,
363 id: RunId.make("previous-native-run"),
364 ordinal: 1,
365 status: "completed" as const,
366 providerInstanceId: oldInstanceId,
367 providerThreadId: oldProviderThreadId,
368 },
369 ]
370 : []),
371 run,
372 ],
373 attempts: [
374 {
375 id: attemptId,
376 runId,
377 rootNodeId,
378 attemptOrdinal: 1,
379 providerInstanceId: newInstanceId,
380 providerThreadId,
381 providerTurnId: null,
382 reason: "initial",
383 status: "pending",
384 startedAt: null,
385 completedAt: null,
386 },
387 ],
388 nodes: [
389 {
390 id: rootNodeId,
391 threadId,
392 runId,
393 parentNodeId: null,
394 rootNodeId,
395 kind: "root_turn",
396 status: "pending",
397 countsForRun: true,
398 providerThreadId,
399 providerTurnId: null,
400 nativeItemRef: null,
401 runtimeRequestId: null,
402 checkpointScopeId,
403 startedAt: null,
404 completedAt: null,
405 },
406 ],
407 providerThreads: [
408 ...(input.previousNativeSession
409 ? [
410 {
411 ...providerThread,
412 id: oldProviderThreadId,
413 providerInstanceId: oldInstanceId,
414 driver: ProviderDriverKind.make("antigravity"),
415 lastRunOrdinal: 1,
416 nativeThreadRef: {
417 driver: ProviderDriverKind.make("antigravity"),
418 nativeId: "existing-session",
419 strength: "strong" as const,
420 },
421 },
422 ]
423 : []),
424 providerThread,
425 ],
426 messages: [
427 ...(input.previousMessages ?? []).map((text, index) => ({
428 ...message,
429 id: MessageId.make(`previous-message-${index}`),
430 text,
431 })),
432 message,
433 ],
434 checkpointScopes: [
435 {
436 id: checkpointScopeId,
437 threadId,
438 runId,
439 nodeId: rootNodeId,
440 parentScopeId: null,
441 providerThreadId,
442 kind: "root_run",
443 ordinalWithinParent: 0,
444 advancesAppRunCount: true,
445 cwd: "/tmp/native-account-command",
446 createdAt: now,
447 },
448 ],
449 providerSessions: [],
450 providerTurns: [],
451 contextHandoffs: [],
452 contextTransfers: [],
453 turnItems: [],
454 visibleTurnItems: [],
455 runtimeRequests: [],
456 subagents: [],
457 plans: [],
458 checkpoints: [],
459 updatedAt: now,
460 };
461 if ("historyReadFailureAfterFallback" in input) {
462 const nativeThreadRef = {
463 driver: providerThread.driver,
464 nativeId: "native-resume-thread",
465 strength: "strong" as const,
466 };
467 projection = {
468 ...projection,
469 providerThreads: projection.providerThreads.map((candidate) =>
470 candidate.id === providerThreadId ? { ...candidate, nativeThreadRef } : candidate,
471 ),
472 };
473 }
474 const previousTurnId = ProviderTurnId.make("previous-provider-turn");
475 if (input.previousTurn !== undefined) {
476 const previousRunId = RunId.make("previous-failed-run");
477 const previousAttemptId = RunAttemptId.make("previous-failed-attempt");
478 const previousProviderThreadId = input.previousTurn.differentThread
479 ? oldProviderThreadId
480 : providerThreadId;
481 projection = {
482 ...projection,
483 runs: [
484 {
485 ...run,
486 id: previousRunId,
487 ordinal: 1,
488 status: input.previousTurn.runStatus,
489 rootNodeId: NodeId.make("previous-root"),
490 activeAttemptId: previousAttemptId,
491 providerThreadId: previousProviderThreadId,
492 completedAt: now,
493 },
494 run,
495 ],
496 providerThreads: [
497 {
498 ...providerThread,
499 nativeThreadRef: {
500 driver: providerThread.driver,
501 nativeId: "existing-native-conversation",
502 strength: "strong",
503 },
504 },
505 ],
506 providerTurns: [
507 {
508 id: previousTurnId,
509 providerThreadId: previousProviderThreadId,
510 nodeId: NodeId.make("previous-root"),
511 runAttemptId: previousAttemptId,
512 ordinal: 1,
513 nativeTurnRef: null,
514 status: input.previousTurn.turnStatus,
515 startedAt: now,
516 completedAt: input.previousTurn.turnStatus === "running" ? null : now,
517 },
518 ],
519 };
520 }
521 let providerBusy =
522 input.previousTurn?.runStatus === "failed" &&
523 input.previousTurn.turnStatus === "running" &&
524 !input.previousTurn.differentThread &&
525 input.previousTurn.liveSession !== false;
526 const interruptTurn = vi.fn((request: ProviderAdapter.ProviderAdapterV2InterruptInput) =>
527 Effect.gen(function* () {
528 expect(request.providerTurnId).toBe(previousTurnId);
529 expect(request.providerThread.id).toBe(providerThreadId);
530 if (input.previousTurn?.interruptFailure) {
531 return yield* new ProviderAdapter.ProviderAdapterInterruptError({
532 driver: providerThread.driver,
533 providerThreadId,
534 providerTurnId: request.providerTurnId,
535 cause: "provider interrupt failed",
536 });
537 }
538 providerBusy = false;
539 if (input.previousTurn?.interruptCurrentRun) interruptRun();
540 }),
541 );
542 const events: Array<OrchestrationV2DomainEvent> = [];
543 const interruptRun = () => {
544 projection = {
545 ...projection,
546 runs: projection.runs.map((candidate) =>
547 candidate.id === runId
548 ? { ...candidate, status: "interrupted", completedAt: now }
549 : candidate,
550 ),
551 };
552 };
553 const ensureThread = vi.fn(() =>
554 Effect.sync(() => {
555 if (input.interruptRunBeforeOpenFailure === true) interruptRun();
556 }).pipe(
557 Effect.andThen(
558 Effect.fail(
559 new ProviderAdapter.ProviderAdapterEventStreamError({
560 driver: providerThread.driver,
561 providerSessionId,
562 cause: input.ensureThreadFailure,
563 }),
564 ),
565 ),
566 ),
567 );
568 const resumeFallbackSession = {
569 driver: providerThread.driver,
570 resumeThread: () =>
571 Effect.fail(
572 new ProviderAdapter.ProviderAdapterEventStreamError({
573 driver: providerThread.driver,
574 providerSessionId,
575 cause: "native thread is gone",
576 }),
577 ),
578 ensureThread: () => Effect.succeed(providerThread),
579 };
580 const open = vi.fn(() =>
581 input.interruptOpen === true
582 ? Effect.interrupt
583 : "historyReadFailureAfterFallback" in input
584 ? Effect.succeed(resumeFallbackSession as never)
585 : "ensureThreadFailure" in input
586 ? Effect.succeed({ driver: providerThread.driver, ensureThread } as never)
587 : "openFailure" in input
588 ? Effect.sync(() => {
589 if (input.interruptRunBeforeOpenFailure === true) interruptRun();
590 }).pipe(
591 Effect.andThen(
592 Effect.fail(
593 new ProviderSessionManager.ProviderSessionOpenError({
594 instanceId: newInstanceId,
595 providerSessionId,
596 cause: input.openFailure,
597 }),
598 ),
599 ),
600 )
601 : input.failReadsAfterRunning === true || input.previousTurn !== undefined
602 ? Effect.succeed({
603 driver: providerThread.driver,
604 providerSession: {
605 id: providerSessionId,
606 driver: providerThread.driver,
607 providerInstanceId: newInstanceId,
608 status: "ready",
609 cwd: "/tmp/native-account-command",
610 model: null,
611 capabilities: CodexProviderCapabilitiesV2,
612 createdAt: now,
613 updatedAt: now,
614 lastError: null,
615 },
616 ensureThread: () => Effect.succeed(providerThread),
617 resumeThread: () => Effect.succeed(projection.providerThreads[0]),
618 } as never)
619 : Effect.die("A local command must not open a native session."),
620 );
621 const startRootRun = vi.fn<
622 (input: RunExecutionService.RunExecutionServiceV2StartRootRunInput) => Effect.Effect<void>
623 >(() =>
624 input.failReadsAfterRunning === true || input.previousTurn !== undefined
625 ? Effect.suspend(() =>
626 providerBusy ? Effect.die("The previous provider turn is still running.") : Effect.void,
627 )
628 : Effect.die("A local command must not start a native turn."),
629 );
630 const failReadIfRunning = Effect.suspend(() =>
631 input.failReadsAfterRunning === true &&
632 projection.runs.find((candidate) => candidate.id === runId)?.status === "running"
633 ? Effect.fail(
634 new ProjectionStore.ProjectionStoreReadError({ threadId, cause: "database unavailable" }),
635 )
636 : Effect.void,
637 );
638 const tryHandlePromptCommand = vi.fn(() =>
639 input.logoutFailure === undefined
640 ? Effect.succeed(true)
641 : Effect.fail(
642 new ProviderSetupError({
643 instanceId: oldInstanceId,
644 operation: "logout",
645 detail: input.logoutFailure,
646 }),
647 ),
648 );
649 const writeIfRunCurrent = vi.fn(({ events: incoming, activeAttemptId, expectedStatus }) =>
650 "writeFailure" in input
651 ? Effect.fail(
652 new EventSink.EventSinkWriteError({
653 eventCount: incoming.length,
654 cause: input.writeFailure,
655 }),
656 )
657 : Effect.sync(() => {
658 const current = projection.runs.find((candidate) => candidate.id === runId);
659 const committed =
660 current !== undefined &&
661 current.activeAttemptId === activeAttemptId &&
662 current.status === expectedStatus;
663 if (committed) {
664 for (const event of incoming) {
665 expect(isDomainEvent(event)).toBe(true);
666 events.push(event);
667 projection = ProjectionStore.applyToProjection(projection, event);
668 }
669 }
670 return { committed, storedEvents: [] };
671 }),
672 );
673 const resolveRuntimePolicy = vi.fn(
674 ({ thread }: Parameters<RuntimePolicy.RuntimePolicyV2Shape["resolve"]>[0]) =>
675 Effect.succeed({ cwd: thread.worktreePath ?? "/tmp/native-account-command" } as never),
676 );
677 const createWorktree = vi.fn<GitWorkflow.GitWorkflowService["Service"]["createWorktree"]>(() =>
678 Effect.succeed({} as never),
679 );
680 const getThreadRecords = vi.fn<ProjectionStore.ProjectionStoreV2Shape["getThreadRecords"]>(() =>
681 Effect.succeed(projection),
682 );
683 const getTurnStartContext = vi.fn(() =>
684 Effect.succeed({
685 ...projection,
686 hasConversation: projection.messages.some(
687 (m) =>
688 m.role === "user" &&
689 (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0),
690 ),
691 }),
692 );
693 const layer = ProviderTurnStart.layer.pipe(
694 Layer.provide(
695 Layer.mergeAll(
696 Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({
697 prepareProviderHandoff: () => Effect.die("history read must fail first"),
698 }),
699 Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }),
700 IdAllocator.layer,
701 layerWorktreeLocation(input.worktreesDir),
702 input.fileSystem === undefined
703 ? FileSystem.layerNoop({ exists: () => Effect.succeed(true) })
704 : Layer.succeed(FileSystem.FileSystem, input.fileSystem),
705 input.gitWorkflow === undefined
706 ? Layer.mock(GitWorkflow.GitWorkflowService)({
707 pruneWorktrees: () => Effect.void,
708 listLocalBranchNames: () => Effect.succeed(["feature/restore"]),
709 createWorktree,
710 })
711 : Layer.succeed(GitWorkflow.GitWorkflowService, input.gitWorkflow),
712 Layer.mock(ProjectService.ProjectService)({
713 getById: () =>
714 Effect.succeedSome({
715 workspaceRoot: input.workspaceRoot ?? "/tmp/native-account-project",
716 } as never),
717 }),
718 Layer.mock(ProjectionStore.ProjectionStoreV2)({
719 getThreadRecords,
720 getTurnStartContext,
721 getRuntimeRecoveryProjection: () =>
722 Effect.as(failReadIfRunning, {
723 ...projection,
724 hasConversation: projection.messages.some(
725 (m) =>
726 m.role === "user" &&
727 (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0),
728 ),
729 }),
730 getTurnStartHistory: () =>
731 Effect.fail(
732 new ProjectionStore.ProjectionStoreReadError({
733 threadId,
734 cause: input.historyReadFailureAfterFallback,
735 }),
736 ),
737 }),
738 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
739 open,
740 get: () =>
741 Effect.succeed(
742 input.previousTurn?.liveSession === false
743 ? Option.none()
744 : Option.some({
745 driver: providerThread.driver,
746 providerSessionId,
747 interruptTurn,
748 } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime),
749 ),
750 }),
751 Layer.mock(ProviderAuthService.ProviderAuthService)({ tryHandlePromptCommand }),
752 Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }),
753 Layer.mock(RuntimePolicy.RuntimePolicyV2)({
754 resolve: resolveRuntimePolicy,
755 }),
756 ),
757 ),
758 );
759 return {
760 getThreadRecords,
761 getTurnStartContext,
762 setProjection: (next: OrchestrationV2ThreadProjection) => {
763 projection = next;
764 },
765 resolveRuntimePolicy,
766 createWorktree,
767 open,
768 writeIfRunCurrent,
769 startRootRun,
770 interruptTurn,
771 tryHandlePromptCommand,
772 events,
773 oldInstanceId,
774 newInstanceId,
775 attemptId,
776 projection: () => projection,
777 start: Effect.gen(function* () {
778 yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2).start({ threadId, runId });
779 }).pipe(Effect.provide(layer)),
780 startWithRetry: Effect.gen(function* () {
781 yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2).start({
782 threadId,
783 runId,
784 willRetry: true,
785 });
786 }).pipe(Effect.provide(layer)),
787 };
788}
789
790effectIt.effect(
791 "recovers the thread branch tip, falls back to the current project branch, and rejects detached HEAD",
792 () =>
793 Effect.gen(function* () {
794 const fileSystem = yield* FileSystem.FileSystem;
795 const path = yield* Path.Path;
796 const gitWorkflow = yield* GitWorkflow.GitWorkflowService;
797 const driver = yield* GitVcsDriver.GitVcsDriver;
798 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-recreate-repo-" });
799 const workspaceRoot = path.join(root, "project");
800 const worktreesDir = path.join(root, "worktrees");
801 const worktreePath = path.join(worktreesDir, "project", "restore");
802 yield* fileSystem.makeDirectory(workspaceRoot);
803 const git = (cwd: string, args: ReadonlyArray<string>) =>
804 driver
805 .execute({ operation: "test.worktreeRecovery", cwd, args })
806 .pipe(Effect.map((result) => result.stdout.trim()));
807 yield* git(workspaceRoot, ["init", "-b", "main"]);
808 yield* git(workspaceRoot, ["config", "user.name", "Test"]);
809 yield* git(workspaceRoot, ["config", "user.email", "test@example.com"]);
810 yield* git(workspaceRoot, ["commit", "--allow-empty", "-m", "base"]);
811 yield* git(workspaceRoot, ["worktree", "add", "-b", "feature/restore", worktreePath]);
812 yield* fileSystem.writeFileString(path.join(worktreePath, "thread.txt"), "thread work");
813 yield* git(worktreePath, ["add", "."]);
814 yield* git(worktreePath, ["commit", "-m", "thread tip"]);
815 const threadTip = yield* git(worktreePath, ["rev-parse", "HEAD"]);
816 yield* git(workspaceRoot, ["switch", "-c", "project-current"]);
817 yield* fileSystem.writeFileString(
818 path.join(workspaceRoot, "project.txt"),
819 "new project code",
820 );
821 yield* git(workspaceRoot, ["add", "."]);
822 yield* git(workspaceRoot, ["commit", "-m", "project tip"]);
823 const projectTip = yield* git(workspaceRoot, ["rev-parse", "HEAD"]);
824 expect(projectTip).not.toBe(threadTip);
825 // Tags must neither hide the thread branch nor select a different recovery tip.
826 yield* git(workspaceRoot, ["tag", "feature/restore", projectTip]);
827 yield* git(workspaceRoot, ["tag", "project-current", threadTip]);
828
829 // Reuse the workflow across turns so recovery cannot select a cached project branch.
830 for (const scenario of ["retained", "deleted", "detached"] as const) {
831 yield* fileSystem.remove(worktreePath, { recursive: true });
832 if (scenario !== "retained") {
833 yield* git(workspaceRoot, ["worktree", "prune"]);
834 yield* git(workspaceRoot, ["branch", "-D", "feature/restore"]);
835 }
836 if (scenario === "detached") {
837 yield* git(workspaceRoot, ["switch", "--detach"]);
838 expect(yield* git(workspaceRoot, ["branch", "--show-current"])).toBe("");
839 }
840 const harness = makeLocalCommandHarness({
841 text: "Continue",
842 workspaceRoot,
843 worktreePath,
844 worktreesDir,
845 fileSystem,
846 gitWorkflow,
847 failReadsAfterRunning: true,
848 });
849 const open = harness.open.getMockImplementation()!;
850 harness.open.mockImplementation(() =>
851 Effect.gen(function* () {
852 expect(yield* git(worktreePath, ["branch", "--show-current"])).toBe("feature/restore");
853 expect(yield* git(worktreePath, ["rev-parse", "HEAD"])).toBe(
854 scenario === "retained" ? threadTip : projectTip,
855 );
856 expect(
857 yield* fileSystem.readFileString(
858 path.join(worktreePath, scenario === "retained" ? "thread.txt" : "project.txt"),
859 ),
860 ).toBe(scenario === "retained" ? "thread work" : "new project code");
861 return yield* open();
862 }).pipe(Effect.orDie),
863 );
864
865 yield* harness.start;
866
867 if (scenario === "detached") {
868 expect(harness.open).not.toHaveBeenCalled();
869 expect(harness.startRootRun).not.toHaveBeenCalled();
870 expect(harness.projection().runs.at(-1)?.status).toBe("failed");
871 expect(harness.projection().turnItems).toMatchObject([
872 { type: "error", failure: { message: expect.stringContaining("no current branch") } },
873 ]);
874 expect(yield* fileSystem.exists(worktreePath)).toBe(false);
875 expect(yield* git(workspaceRoot, ["branch", "--list", "feature/restore"])).toBe("");
876 } else {
877 expect(harness.open).toHaveBeenCalledOnce();
878 expect(harness.startRootRun).toHaveBeenCalledWith(
879 expect.objectContaining({
880 runtimePolicy: expect.objectContaining({ cwd: worktreePath }),
881 }),
882 );
883 expect(harness.projection().runs.at(-1)?.status).toBe("running");
884 }
885 }
886 }).pipe(Effect.scoped, Effect.provide(layerRealGit)),
887);
888
889effectIt.effect(
890 "preserves recreation interrupts and retries, then fails the final attempt before provider start",
891 () =>
892 Effect.gen(function* () {
893 const fileSystem = yield* FileSystem.FileSystem;
894 const path = yield* Path.Path;
895 const worktreesDir = yield* fileSystem.makeTempDirectoryScoped({
896 prefix: "t3-recreate-failure-",
897 });
898 const worktreePath = path.join(worktreesDir, "project", "restore");
899 const harness = makeLocalCommandHarness({
900 text: "Continue",
901 worktreesDir,
902 worktreePath,
903 fileSystem,
904 failReadsAfterRunning: true,
905 });
906 harness.createWorktree.mockImplementationOnce(() => Effect.interrupt);
907 harness.createWorktree.mockImplementation(() =>
908 Effect.fail(
909 new GitCommandError({
910 operation: "worktree-add",
911 command: "git worktree add",
912 cwd: "/tmp/native-account-project",
913 detail: "fatal: private git diagnostic",
914 }),
915 ),
916 );
917
918 const interrupted = yield* Effect.exit(harness.start);
919 expect(interrupted._tag).toBe("Failure");
920 if (interrupted._tag === "Failure")
921 expect(Cause.hasInterruptsOnly(interrupted.cause)).toBe(true);
922 expect(harness.events).toEqual([]);
923 expect(harness.projection().runs.at(-1)?.status).toBe("starting");
924
925 const retry = yield* Effect.result(harness.startWithRetry);
926 expect(retry).toMatchObject({ _tag: "Failure", failure: { _tag: "ProviderTurnStartError" } });
927 expect(harness.events).toEqual([]);
928 expect(harness.projection().runs.at(-1)?.status).toBe("starting");
929
930 yield* harness.start;
931 expect(harness.createWorktree).toHaveBeenCalledTimes(3);
932 expect(harness.writeIfRunCurrent).toHaveBeenCalledOnce();
933 expect(harness.open).not.toHaveBeenCalled();
934 expect(harness.startRootRun).not.toHaveBeenCalled();
935 const projection = harness.projection();
936 expect(projection.runs.at(-1)).toMatchObject({ status: "failed", startedAt: null });
937 expect(projection.attempts[0]).toMatchObject({ status: "failed", startedAt: null });
938 expect(projection.nodes[0]).toMatchObject({ status: "failed", startedAt: null });
939 expect(projection.turnItems).toMatchObject([
940 {
941 type: "error",
942 failure: {
943 message: `Could not recreate the worktree for branch 'feature/restore' at ${worktreePath}.`,
944 },
945 },
946 ]);
947 expect(JSON.stringify(harness.events)).not.toContain("private git diagnostic");
948 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
949);
950
951effectIt.effect("recovers an abandoned failed turn before continuing its native conversation", () =>
952 Effect.gen(function* () {
953 const harness = makeLocalCommandHarness({
954 text: "Continue",
955 previousTurn: { runStatus: "failed", turnStatus: "running" },
956 });
957
958 yield* harness.start;
959
960 expect(harness.interruptTurn).toHaveBeenCalledOnce();
961 expect(harness.projection().runs.at(-1)?.status).toBe("running");
962 expect(harness.projection().providerTurns[0]).toMatchObject({
963 status: "interrupted",
964 completedAt: expect.anything(),
965 });
966 expect(harness.startRootRun).toHaveBeenCalledOnce();
967 expect(harness.startRootRun.mock.calls[0]?.[0].providerThread.nativeThreadRef?.nativeId).toBe(
968 "existing-native-conversation",
969 );
970 }),
971);
972
973effectIt.effect.each([
974 { runStatus: "failed", turnStatus: "completed" },
975 { runStatus: "completed", turnStatus: "completed" },
976 { runStatus: "failed", turnStatus: "running", differentThread: true },
977 { runStatus: "failed", turnStatus: "running", liveSession: false },
978 { runStatus: "failed", turnStatus: "interrupted", interruptFailure: true },
979] as const)("continues without interrupting when recovery does not apply: %j", (previousTurn) =>
980 Effect.gen(function* () {
981 const harness = makeLocalCommandHarness({ text: "Continue", previousTurn });
982
983 yield* harness.start;
984
985 expect(harness.interruptTurn).not.toHaveBeenCalled();
986 expect(harness.projection().runs.at(-1)?.status).toBe("running");
987 }),
988);
989
990effectIt.effect("does not start another turn when abandoned-turn cleanup fails", () =>
991 Effect.gen(function* () {
992 const harness = makeLocalCommandHarness({
993 text: "Continue",
994 previousTurn: { runStatus: "failed", turnStatus: "running", interruptFailure: true },
995 });
996
997 yield* harness.start;
998
999 expect(harness.interruptTurn).toHaveBeenCalledOnce();
1000 expect(harness.startRootRun).not.toHaveBeenCalled();
1001 expect(harness.projection().runs.at(-1)?.status).toBe("failed");
1002 }),
1003);
1004
1005effectIt.effect("retries abandoned-turn cleanup without failing the continuation early", () =>
1006 Effect.gen(function* () {
1007 const harness = makeLocalCommandHarness({
1008 text: "Continue",
1009 previousTurn: { runStatus: "failed", turnStatus: "running", interruptFailure: true },
1010 });
1011
1012 const error = yield* harness.startWithRetry.pipe(Effect.flip);
1013
1014 expect(error._tag).toBe("ProviderTurnStartError");
1015 expect(harness.projection().runs.at(-1)?.status).toBe("starting");
1016 expect(harness.open).not.toHaveBeenCalled();
1017 }),
1018);
1019
1020effectIt.effect("does not start the continuation if recording recovery fails", () =>
1021 Effect.gen(function* () {
1022 const harness = makeLocalCommandHarness({
1023 text: "Continue",
1024 previousTurn: { runStatus: "failed", turnStatus: "running" },
1025 writeFailure: new Error("database unavailable"),
1026 });
1027
1028 const error = yield* harness.start.pipe(Effect.flip);
1029
1030 expect(error._tag).toBe("ProviderTurnStartError");
1031 expect(harness.projection().runs.at(-1)?.status).toBe("starting");
1032 expect(harness.projection().providerTurns[0]?.status).toBe("running");
1033 expect(harness.open).not.toHaveBeenCalled();
1034 }),
1035);
1036
1037effectIt.effect("does not resume a continuation stopped while recovery was in flight", () =>
1038 Effect.gen(function* () {
1039 const harness = makeLocalCommandHarness({
1040 text: "Continue",
1041 previousTurn: { runStatus: "failed", turnStatus: "running", interruptCurrentRun: true },
1042 });
1043
1044 yield* harness.start;
1045
1046 expect(harness.projection().runs.at(-1)?.status).toBe("interrupted");
1047 expect(harness.open).not.toHaveBeenCalled();
1048 }),
1049);
1050
1051effectIt.effect.each(["cleanup-first", "startup-first"])(
1052 "coordinates provider startup with %s",
1053 (order) =>
1054 Effect.gen(function* () {
1055 const fileSystem = yield* FileSystem.FileSystem;
1056 const path = yield* Path.Path;
1057 const workspaceRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-start-" });
1058 const worktreePath = path.join(workspaceRoot, "project", "worktree");
1059 yield* fileSystem.makeDirectory(worktreePath, { recursive: true });
1060 const release = yield* Deferred.make<void>();
1061 const openEntered = yield* Deferred.make<void>();
1062 const harness = makeLocalCommandHarness({
1063 text: "Continue",
1064 worktreePath,
1065 worktreesDir: workspaceRoot,
1066 fileSystem,
1067 failReadsAfterRunning: true,
1068 });
1069 harness.createWorktree.mockImplementation(() =>
1070 fileSystem.makeDirectory(worktreePath).pipe(Effect.as({} as never), Effect.orDie),
1071 );
1072 const open = harness.open.getMockImplementation()!;
1073 harness.open.mockImplementation(() =>
1074 Effect.gen(function* () {
1075 expect(yield* fileSystem.exists(worktreePath).pipe(Effect.orDie)).toBe(true);
1076 yield* Deferred.succeed(openEntered, undefined);
1077 if (order === "startup-first") yield* Deferred.await(release);
1078 return yield* open();
1079 }),
1080 );
1081 let cleanupEntered = false;
1082 const cleanupEffect = withWorkspaceLease(
1083 worktreePath,
1084 Effect.gen(function* () {
1085 cleanupEntered = true;
1086 if (order === "cleanup-first") yield* Deferred.await(release);
1087 else {
1088 expect(harness.projection().providerSessions).toHaveLength(1);
1089 expect(harness.projection().runs.at(-1)?.status).toBe("running");
1090 }
1091 yield* fileSystem.remove(worktreePath, { recursive: true, force: true });
1092 }),
1093 );
1094 const cleanup =
1095 order === "cleanup-first"
1096 ? yield* cleanupEffect.pipe(Effect.forkChild({ startImmediately: true }))
1097 : undefined;
1098 const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true }));
1099 if (order === "cleanup-first") expect(harness.open).not.toHaveBeenCalled();
1100 if (order === "startup-first") yield* Deferred.await(openEntered);
1101 const laterCleanup =
1102 order === "startup-first"
1103 ? yield* cleanupEffect.pipe(Effect.forkChild({ startImmediately: true }))
1104 : undefined;
1105 if (order === "startup-first") expect(cleanupEntered).toBe(false);
1106 yield* Deferred.succeed(release, undefined);
1107 if (cleanup !== undefined) yield* Fiber.join(cleanup);
1108 yield* Fiber.join(startup);
1109 if (laterCleanup !== undefined) yield* Fiber.join(laterCleanup);
1110 if (order === "cleanup-first") {
1111 expect(harness.createWorktree).toHaveBeenCalledWith({
1112 cwd: "/tmp/native-account-project",
1113 refName: "feature/restore",
1114 path: worktreePath,
1115 });
1116 }
1117 expect(harness.resolveRuntimePolicy).toHaveBeenCalledWith(
1118 expect.objectContaining({
1119 thread: expect.objectContaining({ worktreePath }),
1120 }),
1121 );
1122 expect(harness.open).toHaveBeenCalledWith(
1123 expect.objectContaining({
1124 runtimePolicy: expect.objectContaining({ cwd: worktreePath }),
1125 }),
1126 );
1127 expect(harness.startRootRun).toHaveBeenCalledWith(
1128 expect.objectContaining({
1129 appThread: expect.objectContaining({ worktreePath }),
1130 runtimePolicy: expect.objectContaining({ cwd: worktreePath }),
1131 }),
1132 );
1133 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1134);
1135
1136effectIt.effect("reads current startup state after waiting for the workspace lease", () =>
1137 Effect.gen(function* () {
1138 const worktreePath = "/tmp/provider-start-fresh-state";
1139 const release = yield* Deferred.make<void>();
1140 const readEntered = yield* Deferred.make<void>();
1141 const harness = makeLocalCommandHarness({
1142 text: "Continue",
1143 worktreePath,
1144 failReadsAfterRunning: true,
1145 });
1146 harness.getThreadRecords.mockImplementationOnce(() =>
1147 Deferred.succeed(readEntered, undefined).pipe(Effect.as(harness.projection())),
1148 );
1149 const holder = yield* withWorkspaceLease(worktreePath, Deferred.await(release)).pipe(
1150 Effect.forkChild({ startImmediately: true }),
1151 );
1152 const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true }));
1153 yield* Deferred.await(readEntered);
1154 expect(harness.getTurnStartContext).not.toHaveBeenCalled();
1155 const projection = harness.projection();
1156 harness.setProjection({
1157 ...projection,
1158 runs: projection.runs.map((run) => ({ ...run, status: "running" })),
1159 });
1160 yield* Deferred.succeed(release, undefined);
1161 yield* Fiber.join(holder);
1162 yield* Fiber.join(startup);
1163 expect(harness.open).not.toHaveBeenCalled();
1164 expect(harness.startRootRun).not.toHaveBeenCalled();
1165 }),
1166);
1167
1168// regression: #15784 superseded provider startups kept running
1169effectIt.effect.each([
1170 { boundary: "policy resolution", loss: "replaced" },
1171 { boundary: "session opening", loss: "interrupted" },
1172])("does not continue startup when $loss during $boundary", ({ boundary, loss }) =>
1173 Effect.gen(function* () {
1174 const entered = yield* Deferred.make<void>();
1175 const release = yield* Deferred.make<void>();
1176 const gate = Deferred.succeed(entered, undefined).pipe(Effect.andThen(Deferred.await(release)));
1177 const harness = makeLocalCommandHarness({ text: "Continue" });
1178 const projection = harness.projection();
1179 const providerThread = projection.providerThreads[0]!;
1180 const ensureThread = vi.fn(() => Effect.succeed(providerThread));
1181 const resumeThread = vi.fn(() => Effect.succeed(providerThread));
1182 const forkThread = vi.fn(() => Effect.succeed(providerThread));
1183 harness.open.mockReturnValue(
1184 (boundary === "session opening" ? gate : Effect.void).pipe(
1185 Effect.as({
1186 driver: providerThread.driver,
1187 ensureThread,
1188 resumeThread,
1189 forkThread,
1190 } as never),
1191 ),
1192 );
1193 if (boundary === "policy resolution") {
1194 harness.resolveRuntimePolicy.mockReturnValue(
1195 gate.pipe(Effect.as({ cwd: "/tmp/native-account-command" } as never)),
1196 );
1197 }
1198
1199 const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true }));
1200 yield* Deferred.await(entered);
1201 const current = harness.projection();
1202 const replacementId = RunAttemptId.make("replacement-attempt");
1203 const updated = {
1204 ...current,
1205 runs: current.runs.map((candidate) =>
1206 loss === "replaced"
1207 ? { ...candidate, activeAttemptId: replacementId }
1208 : { ...candidate, status: "interrupted" as const, completedAt: current.updatedAt },
1209 ),
1210 attempts:
1211 loss === "replaced"
1212 ? [...current.attempts, { ...current.attempts[0]!, id: replacementId, attemptOrdinal: 2 }]
1213 : current.attempts,
1214 };
1215 harness.setProjection(updated);
1216 yield* Deferred.succeed(release, undefined);
1217 yield* Fiber.join(startup);
1218
1219 expect(harness.open).toHaveBeenCalledTimes(boundary === "session opening" ? 1 : 0);
1220 expect(ensureThread).not.toHaveBeenCalled();
1221 expect(resumeThread).not.toHaveBeenCalled();
1222 expect(forkThread).not.toHaveBeenCalled();
1223 expect(harness.startRootRun).not.toHaveBeenCalled();
1224 expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
1225 expect(harness.events).toEqual([]);
1226 expect(harness.projection()).toEqual(updated);
1227 }),
1228);
1229
1230effectIt.effect("starts another provider in the same checkout while a turn is pending", () =>
1231 Effect.gen(function* () {
1232 const worktreePath = "/tmp/provider-start-shared-checkout";
1233 const turnEntered = yield* Deferred.make<void>();
1234 const releaseTurn = yield* Deferred.make<void>();
1235 const first = makeLocalCommandHarness({
1236 text: "Continue",
1237 worktreePath,
1238 failReadsAfterRunning: true,
1239 });
1240 const second = makeLocalCommandHarness({
1241 text: "Continue",
1242 worktreePath,
1243 failReadsAfterRunning: true,
1244 });
1245 first.startRootRun.mockImplementation(() =>
1246 Deferred.succeed(turnEntered, undefined).pipe(Effect.andThen(Deferred.await(releaseTurn))),
1247 );
1248 const pending = yield* first.start.pipe(Effect.forkChild({ startImmediately: true }));
1249 yield* Deferred.await(turnEntered);
1250 yield* second.start;
1251 expect(second.startRootRun).toHaveBeenCalledOnce();
1252 expect(second.projection().runs.at(-1)?.status).toBe("running");
1253 yield* Deferred.succeed(releaseTurn, undefined);
1254 yield* Fiber.join(pending);
1255 }),
1256);
1257
1258effectIt.effect("terminalizes a starting run when its provider session cannot open", () =>
1259 Effect.gen(function* () {
1260 const harness = makeLocalCommandHarness({
1261 text: "Continue",
1262 openFailure: new Error("DESCRIPTION is not valid ACP JSON"),
1263 });
1264
1265 yield* harness.start;
1266
1267 expect(harness.open).toHaveBeenCalledOnce();
1268 expect(harness.startRootRun).not.toHaveBeenCalled();
1269 expect(harness.writeIfRunCurrent).toHaveBeenCalledWith(
1270 expect.objectContaining({
1271 activeAttemptId: harness.attemptId,
1272 expectedStatus: "starting",
1273 }),
1274 );
1275 const projection = harness.projection();
1276 expect(projection.runs.at(-1)).toMatchObject({ status: "failed", startedAt: null });
1277 expect(projection.attempts[0]).toMatchObject({ status: "failed", startedAt: null });
1278 expect(projection.nodes[0]).toMatchObject({ status: "failed", startedAt: null });
1279 expect(projection.turnItems).toMatchObject([
1280 {
1281 type: "error",
1282 status: "failed",
1283 failure: {
1284 class: "provider_error",
1285 message: "DESCRIPTION is not valid ACP JSON",
1286 },
1287 },
1288 ]);
1289 }),
1290);
1291
1292effectIt.effect("leaves the run starting when a session-open failure will be retried", () =>
1293 Effect.gen(function* () {
1294 const harness = makeLocalCommandHarness({
1295 text: "Continue",
1296 openFailure: new Error("provider session rejected"),
1297 });
1298
1299 const error = yield* harness.startWithRetry.pipe(Effect.flip);
1300
1301 expect(error._tag).toBe("ProviderTurnStartError");
1302 expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
1303 expect(harness.projection().runs.at(-1)?.status).toBe("starting");
1304 }),
1305);
1306
1307effectIt.effect("does not terminalize a provider-session open interruption", () =>
1308 Effect.gen(function* () {
1309 const harness = makeLocalCommandHarness({ text: "Continue", interruptOpen: true });
1310
1311 const exit = yield* Effect.exit(harness.start);
1312
1313 expect(exit._tag).toBe("Failure");
1314 if (exit._tag === "Failure") {
1315 expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
1316 }
1317 expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
1318 expect(harness.startRootRun).not.toHaveBeenCalled();
1319 expect(harness.projection().runs.at(-1)?.status).toBe("starting");
1320 expect(harness.events).toEqual([]);
1321 }),
1322);
1323
1324effectIt.effect("does not overwrite a run interrupted while its provider session opens", () =>
1325 Effect.gen(function* () {
1326 const harness = makeLocalCommandHarness({
1327 text: "Continue",
1328 openFailure: new Error("provider session rejected"),
1329 interruptRunBeforeOpenFailure: true,
1330 });
1331
1332 yield* harness.start;
1333
1334 expect(harness.writeIfRunCurrent).toHaveBeenCalledOnce();
1335 expect(harness.startRootRun).not.toHaveBeenCalled();
1336 const projection = harness.projection();
1337 expect(projection.runs.at(-1)?.status).toBe("interrupted");
1338 expect(projection.attempts[0]?.status).toBe("pending");
1339 expect(projection.nodes[0]?.status).toBe("pending");
1340 expect(projection.turnItems).toEqual([]);
1341 expect(harness.events).toEqual([]);
1342 }),
1343);
1344
1345effectIt.effect("does not mistake a failed state read for a superseded run", () =>
1346 Effect.gen(function* () {
1347 const harness = makeLocalCommandHarness({ text: "Continue", failReadsAfterRunning: true });
1348
1349 yield* harness.start;
1350
1351 expect(harness.projection().runs.at(-1)?.status).toBe("running");
1352 const controls = harness.startRootRun.mock.calls[0]?.[0];
1353 expect(controls).toBeDefined();
1354 if (controls === undefined) return;
1355 const startCheck = yield* Effect.flip(controls.shouldStartProviderTurn!());
1356 const finalizeCheck = yield* Effect.flip(controls.shouldFinalizeRun!());
1357 expect(startCheck._tag).toBe("ProjectionStoreReadError");
1358 expect(finalizeCheck._tag).toBe("ProjectionStoreReadError");
1359 }),
1360);
1361
1362effectIt.effect(
1363 "signs out the existing native provider before opening the newly selected provider",
1364 () =>
1365 Effect.gen(function* () {
1366 const harness = makeLocalCommandHarness({ text: "/logout", previousNativeSession: true });
1367
1368 yield* harness.start;
1369 yield* harness.start;
1370
1371 expect(harness.tryHandlePromptCommand).toHaveBeenCalledExactlyOnceWith({
1372 instanceId: harness.oldInstanceId,
1373 text: "/logout",
1374 hasAttachments: false,
1375 });
1376 expect(harness.open).not.toHaveBeenCalled();
1377 expect(harness.startRootRun).not.toHaveBeenCalled();
1378 const projection = harness.projection();
1379 expect(projection.runs.at(-1)?.status).toBe("completed");
1380 expect(projection.attempts[0]?.status).toBe("completed");
1381 expect(projection.nodes[0]?.status).toBe("completed");
1382 expect(projection.turnItems).toMatchObject([
1383 {
1384 type: "command_execution",
1385 title: "Provider signed out",
1386 output: "Provider signed out",
1387 status: "completed",
1388 },
1389 ]);
1390 expect(projection.providerTurns).toEqual([]);
1391 expect(projection.checkpoints).toEqual([]);
1392 }),
1393);
1394
1395for (const previousMessages of [[], ["/compact", " /COMPACT "]]) {
1396 effectIt.effect(
1397 `rejects compaction without conversation context after ${previousMessages.length} prior compactions`,
1398 () =>
1399 Effect.gen(function* () {
1400 const harness = makeLocalCommandHarness({ text: "/compact", previousMessages });
1401
1402 yield* harness.start;
1403
1404 expect(harness.open).not.toHaveBeenCalled();
1405 expect(harness.tryHandlePromptCommand).not.toHaveBeenCalled();
1406 expect(harness.startRootRun).not.toHaveBeenCalled();
1407 expect(harness.projection().runs.at(-1)?.status).toBe("failed");
1408 expect(harness.projection().turnItems).toMatchObject([
1409 {
1410 type: "error",
1411 failure: {
1412 class: "validation_error",
1413 message: "Start a conversation before compacting this thread.",
1414 },
1415 },
1416 ]);
1417 }),
1418 );
1419}