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

ProviderTurnStartService.test.ts

645 lines21.8 KB

1import { expect, it, vi } from "vite-plus/test";
2import { it as effectIt } from "@effect/vitest";
3import {
4 CheckpointScopeId,
5 MessageId,
6 NodeId,
7 ProviderSessionId,
8 ProviderThreadId,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 ProviderSetupError,
12 RunAttemptId,
13 RunId,
14 ThreadId,
15 ProjectId,
16 type OrchestrationV2ThreadProjection,
17 OrchestrationV2DomainEvent,
18} from "@t3tools/contracts";
19import * as Cause from "effect/Cause";
20import * as DateTime from "effect/DateTime";
21import * as Effect from "effect/Effect";
22import * as FileSystem from "effect/FileSystem";
23import * as Layer from "effect/Layer";
24import * as Option from "effect/Option";
25import * as Schema from "effect/Schema";
26​
27import * as GitWorkflow from "../git/GitWorkflowService.ts";
28import * as ProjectService from "../project/ProjectService.ts";
29import { ProviderAuthService } from "../provider/Services/ProviderAuthService.ts";
30import * as ContextHandoffService from "./ContextHandoffService.ts";
31import * as EventSink from "./EventSink.ts";
32import * as IdAllocator from "./IdAllocator.ts";
33import * as ProjectionStore from "./ProjectionStore.ts";
34import * as ProviderSessionManager from "./ProviderSessionManager.ts";
35import * as ProviderTurnStart from "./ProviderTurnStartService.ts";
36import * as RunExecutionService from "./RunExecutionService.ts";
37import * as RuntimePolicy from "./RuntimePolicy.ts";
38​
39const isDomainEvent = Schema.is(OrchestrationV2DomainEvent);
40​
41it("does not commit running state when inherited background routing cannot be read", async () => {
42 const threadId = ThreadId.make("thread_provider_turn_start_projection_failure");
43 const runId = RunId.make("run_provider_turn_start_projection_failure");
44 const attemptId = RunAttemptId.make("attempt_provider_turn_start_projection_failure");
45 const rootNodeId = NodeId.make("node_provider_turn_start_projection_failure");
46 const providerThreadId = ProviderThreadId.make(
47 "provider_thread_provider_turn_start_projection_failure",
48 );
49 const providerSessionId = ProviderSessionId.make(
50 "provider_session_provider_turn_start_projection_failure",
51 );
52 const messageId = MessageId.make("message_provider_turn_start_projection_failure");
53 const checkpointScopeId = CheckpointScopeId.make(
54 "checkpoint_scope_provider_turn_start_projection_failure",
55 );
56 const projection = {
57 thread: {
58 id: threadId,
59 projectId: ProjectId.make("project_provider_turn_start_projection_failure"),
60 branch: "feature/restore",
61 worktreePath: "/tmp/missing-provider-turn-start-worktree",
62 },
63 runs: [
64 {
65 id: runId,
66 status: "starting",
67 rootNodeId,
68 activeAttemptId: attemptId,
69 providerThreadId,
70 userMessageId: messageId,
71 ordinal: 2,
72 },
73 ],
74 nodes: [{ id: rootNodeId, checkpointScopeId }],
75 attempts: [{ id: attemptId }],
76 providerThreads: [{ id: providerThreadId, providerSessionId }],
77 messages: [{ id: messageId, text: "Continue", attachments: [] }],
78 checkpointScopes: [{ id: checkpointScopeId }],
79 contextHandoffs: [],
80 contextTransfers: [],
81 turnItems: [],
82 } as unknown as OrchestrationV2ThreadProjection;
83 let projectionReadCount = 0;
84 const writeIfRunCurrent = vi.fn(() =>
85 Effect.succeed({ committed: true, storedEvents: [] } as never),
86 );
87 const startRootRun = vi.fn(() => Effect.void);
88 const pruneWorktrees = vi.fn(() => Effect.void);
89 const createWorktree = vi.fn(() => Effect.succeed({} as never));
90 const layer = ProviderTurnStart.layer.pipe(
91 Layer.provide(
92 Layer.mergeAll(
93 Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}),
94 Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }),
95 IdAllocator.layer,
96 Layer.succeed(FileSystem.FileSystem, { exists: () => Effect.succeed(false) } as never),
97 Layer.mock(GitWorkflow.GitWorkflowService)({ pruneWorktrees, createWorktree }),
98 Layer.mock(ProjectService.ProjectService)({
99 getById: () =>
100 Effect.succeed(
101 Option.some({ workspaceRoot: "/tmp/provider-turn-start-project" } as never),
102 ),
103 }),
104 Layer.mock(ProjectionStore.ProjectionStoreV2)({
105 getTurnStartContext: () => {
106 projectionReadCount += 1;
107 return Effect.succeed({
108 ...projection,
109 hasConversation: projection.messages.some(
110 (m) =>
111 m.role === "user" &&
112 (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0),
113 ),
114 });
115 },
116 getRuntimeRecoveryProjection: () => {
117 projectionReadCount += 1;
118 return Effect.fail(
119 new ProjectionStore.ProjectionStoreReadError({
120 threadId,
121 cause: "simulated inherited-background projection failure",
122 }),
123 );
124 },
125 }),
126 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}),
127 Layer.mock(ProviderAuthService)({ tryHandlePromptCommand: () => Effect.succeed(false) }),
128 Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }),
129 Layer.mock(RuntimePolicy.RuntimePolicyV2)({}),
130 ),
131 ),
132 );
133​
134 await Effect.gen(function* () {
135 const error = yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2)
136 .start({ threadId, runId })
137 .pipe(Effect.flip);
138​
139 expect(error._tag).toBe("ProviderTurnStartError");
140 expect(projectionReadCount).toBe(2);
141 expect(pruneWorktrees).toHaveBeenCalledWith({ cwd: "/tmp/provider-turn-start-project" });
142 expect(createWorktree).toHaveBeenCalledWith({
143 cwd: "/tmp/provider-turn-start-project",
144 refName: "feature/restore",
145 path: "/tmp/missing-provider-turn-start-worktree",
146 });
147 expect(writeIfRunCurrent).not.toHaveBeenCalled();
148 expect(startRootRun).not.toHaveBeenCalled();
149 }).pipe(Effect.provide(layer), Effect.runPromise);
150});
151​
152function makeLocalCommandHarness(input: {
153 readonly text: string;
154 readonly previousNativeSession?: boolean;
155 readonly previousMessages?: ReadonlyArray<string>;
156 readonly logoutFailure?: string;
157 readonly openFailure?: unknown;
158 readonly interruptOpen?: boolean;
159 readonly interruptRunBeforeOpenFailure?: boolean;
160 readonly writeFailure?: unknown;
161}) {
162 const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z");
163 const threadId = ThreadId.make("thread-native-account-command");
164 const runId = RunId.make("run-native-account-command");
165 const rootNodeId = NodeId.make("root-native-account-command");
166 const attemptId = RunAttemptId.make("attempt-native-account-command");
167 const providerThreadId = ProviderThreadId.make("new-provider-thread");
168 const providerSessionId = ProviderSessionId.make("new-provider-session");
169 const oldProviderThreadId = ProviderThreadId.make("existing-native-provider-thread");
170 const oldInstanceId = ProviderInstanceId.make("antigravity-personal");
171 const newInstanceId = ProviderInstanceId.make("codex-personal");
172 const checkpointScopeId = CheckpointScopeId.make("scope-native-account-command");
173 const messageId = MessageId.make("message-native-account-command");
174 const run: OrchestrationV2ThreadProjection["runs"][number] = {
175 id: runId,
176 threadId,
177 ordinal: 2,
178 providerInstanceId: newInstanceId,
179 modelSelection: { instanceId: newInstanceId, model: "gpt-5.4" },
180 providerThreadId,
181 userMessageId: messageId,
182 rootNodeId,
183 activeAttemptId: attemptId,
184 status: "starting",
185 requestedAt: now,
186 startedAt: null,
187 completedAt: null,
188 checkpointId: null,
189 contextHandoffId: null,
190 };
191 const providerThread: OrchestrationV2ThreadProjection["providerThreads"][number] = {
192 id: providerThreadId,
193 driver: ProviderDriverKind.make("codex"),
194 providerInstanceId: newInstanceId,
195 providerSessionId,
196 appThreadId: threadId,
197 ownerNodeId: null,
198 nativeThreadRef: null,
199 nativeConversationHeadRef: null,
200 status: "not_loaded",
201 firstRunOrdinal: 2,
202 lastRunOrdinal: 2,
203 handoffIds: [],
204 forkedFrom: null,
205 createdAt: now,
206 updatedAt: now,
207 };
208 const message: OrchestrationV2ThreadProjection["messages"][number] = {
209 id: messageId,
210 threadId,
211 runId,
212 nodeId: rootNodeId,
213 role: "user",
214 text: input.text,
215 attachments: [],
216 streaming: false,
217 createdBy: "user",
218 creationSource: "web",
219 createdAt: now,
220 updatedAt: now,
221 };
222 let projection: OrchestrationV2ThreadProjection = {
223 thread: {
224 id: threadId,
225 activeProviderThreadId: providerThreadId,
226 branch: null,
227 worktreePath: null,
228 } as OrchestrationV2ThreadProjection["thread"],
229 runs: [
230 ...(input.previousNativeSession
231 ? [
232 {
233 ...run,
234 id: RunId.make("previous-native-run"),
235 ordinal: 1,
236 status: "completed" as const,
237 providerInstanceId: oldInstanceId,
238 providerThreadId: oldProviderThreadId,
239 },
240 ]
241 : []),
242 run,
243 ],
244 attempts: [
245 {
246 id: attemptId,
247 runId,
248 rootNodeId,
249 attemptOrdinal: 1,
250 providerInstanceId: newInstanceId,
251 providerThreadId,
252 providerTurnId: null,
253 reason: "initial",
254 status: "pending",
255 startedAt: null,
256 completedAt: null,
257 },
258 ],
259 nodes: [
260 {
261 id: rootNodeId,
262 threadId,
263 runId,
264 parentNodeId: null,
265 rootNodeId,
266 kind: "root_turn",
267 status: "pending",
268 countsForRun: true,
269 providerThreadId,
270 providerTurnId: null,
271 nativeItemRef: null,
272 runtimeRequestId: null,
273 checkpointScopeId,
274 startedAt: null,
275 completedAt: null,
276 },
277 ],
278 providerThreads: [
279 ...(input.previousNativeSession
280 ? [
281 {
282 ...providerThread,
283 id: oldProviderThreadId,
284 providerInstanceId: oldInstanceId,
285 driver: ProviderDriverKind.make("antigravity"),
286 lastRunOrdinal: 1,
287 nativeThreadRef: {
288 driver: ProviderDriverKind.make("antigravity"),
289 nativeId: "existing-session",
290 strength: "strong" as const,
291 },
292 },
293 ]
294 : []),
295 providerThread,
296 ],
297 messages: [
298 ...(input.previousMessages ?? []).map((text, index) => ({
299 ...message,
300 id: MessageId.make(`previous-message-${index}`),
301 text,
302 })),
303 message,
304 ],
305 checkpointScopes: [
306 {
307 id: checkpointScopeId,
308 threadId,
309 runId,
310 nodeId: rootNodeId,
311 parentScopeId: null,
312 providerThreadId,
313 kind: "root_run",
314 ordinalWithinParent: 0,
315 advancesAppRunCount: true,
316 cwd: "/tmp/native-account-command",
317 createdAt: now,
318 },
319 ],
320 providerSessions: [],
321 providerTurns: [],
322 contextHandoffs: [],
323 contextTransfers: [],
324 turnItems: [],
325 visibleTurnItems: [],
326 runtimeRequests: [],
327 subagents: [],
328 plans: [],
329 checkpoints: [],
330 updatedAt: now,
331 };
332 const events: Array<OrchestrationV2DomainEvent> = [];
333 const open = vi.fn(() =>
334 input.interruptOpen === true
335 ? Effect.interrupt
336 : "openFailure" in input
337 ? Effect.sync(() => {
338 if (input.interruptRunBeforeOpenFailure === true) {
339 projection = {
340 ...projection,
341 runs: projection.runs.map((candidate) =>
342 candidate.id === runId
343 ? { ...candidate, status: "interrupted", completedAt: now }
344 : candidate,
345 ),
346 };
347 }
348 }).pipe(
349 Effect.andThen(
350 Effect.fail(
351 new ProviderSessionManager.ProviderSessionOpenError({
352 instanceId: newInstanceId,
353 providerSessionId,
354 cause: input.openFailure,
355 }),
356 ),
357 ),
358 )
359 : Effect.die("A local command must not open a native session."),
360 );
361 const startRootRun = vi.fn(() => Effect.die("A local command must not start a native turn."));
362 const tryHandlePromptCommand = vi.fn(() =>
363 input.logoutFailure === undefined
364 ? Effect.succeed(true)
365 : Effect.fail(
366 new ProviderSetupError({
367 instanceId: oldInstanceId,
368 operation: "logout",
369 detail: input.logoutFailure,
370 }),
371 ),
372 );
373 const writeIfRunCurrent = vi.fn(({ events: incoming, activeAttemptId, expectedStatus }) =>
374 "writeFailure" in input
375 ? Effect.fail(
376 new EventSink.EventSinkWriteError({
377 eventCount: incoming.length,
378 cause: input.writeFailure,
379 }),
380 )
381 : Effect.sync(() => {
382 const current = projection.runs.find((candidate) => candidate.id === runId);
383 const committed =
384 current !== undefined &&
385 current.activeAttemptId === activeAttemptId &&
386 current.status === expectedStatus;
387 if (committed) {
388 for (const event of incoming) {
389 expect(isDomainEvent(event)).toBe(true);
390 events.push(event);
391 projection = ProjectionStore.applyToProjection(projection, event);
392 }
393 }
394 return { committed, storedEvents: [] };
395 }),
396 );
397 const layer = ProviderTurnStart.layer.pipe(
398 Layer.provide(
399 Layer.mergeAll(
400 Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}),
401 Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }),
402 IdAllocator.layer,
403 FileSystem.layerNoop({}),
404 Layer.mock(GitWorkflow.GitWorkflowService)({}),
405 Layer.mock(ProjectService.ProjectService)({}),
406 Layer.mock(ProjectionStore.ProjectionStoreV2)({
407 getTurnStartContext: () =>
408 Effect.succeed({
409 ...projection,
410 hasConversation: projection.messages.some(
411 (m) =>
412 m.role === "user" &&
413 (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0),
414 ),
415 }),
416 getRuntimeRecoveryProjection: () =>
417 Effect.succeed({
418 ...projection,
419 hasConversation: projection.messages.some(
420 (m) =>
421 m.role === "user" &&
422 (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0),
423 ),
424 }),
425 }),
426 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open }),
427 Layer.mock(ProviderAuthService)({ tryHandlePromptCommand }),
428 Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }),
429 Layer.mock(RuntimePolicy.RuntimePolicyV2)({
430 resolve: () => Effect.succeed({} as never),
431 }),
432 ),
433 ),
434 );
435 return {
436 open,
437 writeIfRunCurrent,
438 startRootRun,
439 tryHandlePromptCommand,
440 events,
441 oldInstanceId,
442 newInstanceId,
443 attemptId,
444 projection: () => projection,
445 start: Effect.gen(function* () {
446 yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2).start({ threadId, runId });
447 }).pipe(Effect.provide(layer)),
448 startWithRetry: Effect.gen(function* () {
449 yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2).start({
450 threadId,
451 runId,
452 willRetry: true,
453 });
454 }).pipe(Effect.provide(layer)),
455 };
457​
458effectIt.effect("terminalizes a starting run when its provider session cannot open", () =>
459 Effect.gen(function* () {
460 const harness = makeLocalCommandHarness({
461 text: "Continue",
462 openFailure: new Error("DESCRIPTION is not valid ACP JSON"),
463 });
464​
465 yield* harness.start;
466​
467 expect(harness.open).toHaveBeenCalledOnce();
468 expect(harness.startRootRun).not.toHaveBeenCalled();
469 expect(harness.writeIfRunCurrent).toHaveBeenCalledWith(
470 expect.objectContaining({
471 activeAttemptId: harness.attemptId,
472 expectedStatus: "starting",
473 }),
474 );
475 const projection = harness.projection();
476 expect(projection.runs.at(-1)).toMatchObject({ status: "failed", startedAt: null });
477 expect(projection.attempts[0]).toMatchObject({ status: "failed", startedAt: null });
478 expect(projection.nodes[0]).toMatchObject({ status: "failed", startedAt: null });
479 expect(projection.turnItems).toMatchObject([
480 {
481 type: "error",
482 status: "failed",
483 failure: {
484 class: "provider_error",
485 message: "DESCRIPTION is not valid ACP JSON",
486 },
487 },
488 ]);
489 }),
490);
491​
492effectIt.effect("leaves the run starting when a session-open failure will be retried", () =>
493 Effect.gen(function* () {
494 const harness = makeLocalCommandHarness({
495 text: "Continue",
496 openFailure: new Error("provider session rejected"),
497 });
498​
499 const error = yield* harness.startWithRetry.pipe(Effect.flip);
500​
501 expect(error._tag).toBe("ProviderTurnStartError");
502 expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
503 expect(harness.projection().runs.at(-1)?.status).toBe("starting");
504 }),
505);
506​
507effectIt.effect("keeps a session-open failure retryable when terminal persistence fails", () =>
508 Effect.gen(function* () {
509 const harness = makeLocalCommandHarness({
510 text: "Continue",
511 openFailure: new Error("provider session rejected"),
512 writeFailure: new Error("database unavailable"),
513 });
514​
515 const error = yield* harness.start.pipe(Effect.flip);
516​
517 expect(error._tag).toBe("ProviderTurnStartError");
518 expect(harness.writeIfRunCurrent).toHaveBeenCalledOnce();
519 expect(harness.startRootRun).not.toHaveBeenCalled();
520 expect(harness.projection().runs.at(-1)?.status).toBe("starting");
521 expect(harness.events).toEqual([]);
522 }),
523);
524​
525effectIt.effect("does not terminalize a provider-session open interruption", () =>
526 Effect.gen(function* () {
527 const harness = makeLocalCommandHarness({ text: "Continue", interruptOpen: true });
528​
529 const exit = yield* Effect.exit(harness.start);
530​
531 expect(exit._tag).toBe("Failure");
532 if (exit._tag === "Failure") {
533 expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
534 }
535 expect(harness.writeIfRunCurrent).not.toHaveBeenCalled();
536 expect(harness.startRootRun).not.toHaveBeenCalled();
537 expect(harness.projection().runs.at(-1)?.status).toBe("starting");
538 expect(harness.events).toEqual([]);
539 }),
540);
541​
542effectIt.effect("does not overwrite a run interrupted while its provider session opens", () =>
543 Effect.gen(function* () {
544 const harness = makeLocalCommandHarness({
545 text: "Continue",
546 openFailure: new Error("provider session rejected"),
547 interruptRunBeforeOpenFailure: true,
548 });
549​
550 yield* harness.start;
551​
552 expect(harness.writeIfRunCurrent).toHaveBeenCalledOnce();
553 expect(harness.startRootRun).not.toHaveBeenCalled();
554 const projection = harness.projection();
555 expect(projection.runs.at(-1)?.status).toBe("interrupted");
556 expect(projection.attempts[0]?.status).toBe("pending");
557 expect(projection.nodes[0]?.status).toBe("pending");
558 expect(projection.turnItems).toEqual([]);
559 expect(harness.events).toEqual([]);
560 }),
561);
562​
563effectIt.effect(
564 "signs out the existing native provider before opening the newly selected provider",
565 () =>
566 Effect.gen(function* () {
567 const harness = makeLocalCommandHarness({ text: "/logout", previousNativeSession: true });
568​
569 yield* harness.start;
570 yield* harness.start;
571​
572 expect(harness.tryHandlePromptCommand).toHaveBeenCalledExactlyOnceWith({
573 instanceId: harness.oldInstanceId,
574 text: "/logout",
575 hasAttachments: false,
576 });
577 expect(harness.open).not.toHaveBeenCalled();
578 expect(harness.startRootRun).not.toHaveBeenCalled();
579 const projection = harness.projection();
580 expect(projection.runs.at(-1)?.status).toBe("completed");
581 expect(projection.attempts[0]?.status).toBe("completed");
582 expect(projection.nodes[0]?.status).toBe("completed");
583 expect(projection.turnItems).toMatchObject([
584 {
585 type: "command_execution",
586 title: "Provider signed out",
587 output: "Provider signed out",
588 status: "completed",
589 },
590 ]);
591 expect(projection.providerTurns).toEqual([]);
592 expect(projection.checkpoints).toEqual([]);
593 }),
594);
595​
596effectIt.effect("persists a failed sign-out without starting a provider turn", () =>
597 Effect.gen(function* () {
598 const harness = makeLocalCommandHarness({
599 text: "/logout",
600 logoutFailure: "Could not stop all sessions for this provider. Try again.",
601 });
602​
603 yield* harness.start;
604​
605 expect(harness.open).not.toHaveBeenCalled();
606 expect(harness.startRootRun).not.toHaveBeenCalled();
607 expect(harness.projection().runs.at(-1)?.status).toBe("failed");
608 expect(harness.projection().turnItems).toMatchObject([
609 {
610 type: "error",
611 title: "Provider sign-out failed",
612 failure: {
613 class: "permission_error",
614 message: "Could not stop all sessions for this provider. Try again.",
615 },
616 },
617 ]);
618 }),
619);
620​
621for (const previousMessages of [[], ["/compact", " /COMPACT "]]) {
622 effectIt.effect(
623 `rejects compaction without conversation context after ${previousMessages.length} prior compactions`,
624 () =>
625 Effect.gen(function* () {
626 const harness = makeLocalCommandHarness({ text: "/compact", previousMessages });
627​
628 yield* harness.start;
629​
630 expect(harness.open).not.toHaveBeenCalled();
631 expect(harness.tryHandlePromptCommand).not.toHaveBeenCalled();
632 expect(harness.startRootRun).not.toHaveBeenCalled();
633 expect(harness.projection().runs.at(-1)?.status).toBe("failed");
634 expect(harness.projection().turnItems).toMatchObject([
635 {
636 type: "error",
637 failure: {
638 class: "validation_error",
639 message: "Start a conversation before compacting this thread.",
640 },
641 },
642 ]);
643 }),
644 );