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

ProviderTurnStartService.test.ts

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