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

ProviderTurnStartService.test.ts

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