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

ProviderTurnStartService.test.ts

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