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

ProviderTurnStartService.test.ts

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