Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProviderTurnStartService.test.ts

1,243 lines44.4 KB

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