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