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

ProviderTurnStartService.test.ts

488 lines16.6 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 DateTime from "effect/DateTime";
20import * as Effect from "effect/Effect";
21import * as FileSystem from "effect/FileSystem";
22import * as Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import * as Schema from "effect/Schema";
25​
26import * as GitWorkflow from "../git/GitWorkflowService.ts";
27import * as ProjectService from "../project/ProjectService.ts";
28import { ProviderAuthService } from "../provider/Services/ProviderAuthService.ts";
29import * as ContextHandoffService from "./ContextHandoffService.ts";
30import * as EventSink from "./EventSink.ts";
31import * as IdAllocator from "./IdAllocator.ts";
32import * as ProjectionStore from "./ProjectionStore.ts";
33import * as ProviderSessionManager from "./ProviderSessionManager.ts";
34import * as ProviderTurnStart from "./ProviderTurnStartService.ts";
35import * as RunExecutionService from "./RunExecutionService.ts";
36import * as RuntimePolicy from "./RuntimePolicy.ts";
37​
38const isDomainEvent = Schema.is(OrchestrationV2DomainEvent);
39​
40it("does not commit running state when inherited background routing cannot be read", async () => {
41 const threadId = ThreadId.make("thread_provider_turn_start_projection_failure");
42 const runId = RunId.make("run_provider_turn_start_projection_failure");
43 const attemptId = RunAttemptId.make("attempt_provider_turn_start_projection_failure");
44 const rootNodeId = NodeId.make("node_provider_turn_start_projection_failure");
45 const providerThreadId = ProviderThreadId.make(
46 "provider_thread_provider_turn_start_projection_failure",
47 );
48 const providerSessionId = ProviderSessionId.make(
49 "provider_session_provider_turn_start_projection_failure",
50 );
51 const messageId = MessageId.make("message_provider_turn_start_projection_failure");
52 const checkpointScopeId = CheckpointScopeId.make(
53 "checkpoint_scope_provider_turn_start_projection_failure",
54 );
55 const projection = {
56 thread: {
57 id: threadId,
58 projectId: ProjectId.make("project_provider_turn_start_projection_failure"),
59 branch: "feature/restore",
60 worktreePath: "/tmp/missing-provider-turn-start-worktree",
61 },
62 runs: [
63 {
64 id: runId,
65 status: "starting",
66 rootNodeId,
67 activeAttemptId: attemptId,
68 providerThreadId,
69 userMessageId: messageId,
70 ordinal: 2,
71 },
72 ],
73 nodes: [{ id: rootNodeId, checkpointScopeId }],
74 attempts: [{ id: attemptId }],
75 providerThreads: [{ id: providerThreadId, providerSessionId }],
76 messages: [{ id: messageId, text: "Continue", attachments: [] }],
77 checkpointScopes: [{ id: checkpointScopeId }],
78 contextHandoffs: [],
79 contextTransfers: [],
80 turnItems: [],
81 } as unknown as OrchestrationV2ThreadProjection;
82 let projectionReadCount = 0;
83 const writeIfRunCurrent = vi.fn(() =>
84 Effect.succeed({ committed: true, storedEvents: [] } as never),
85 );
86 const startRootRun = vi.fn(() => Effect.void);
87 const pruneWorktrees = vi.fn(() => Effect.void);
88 const createWorktree = vi.fn(() => Effect.succeed({} as never));
89 const layer = ProviderTurnStart.layer.pipe(
90 Layer.provide(
91 Layer.mergeAll(
92 Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}),
93 Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }),
94 IdAllocator.layer,
95 Layer.succeed(FileSystem.FileSystem, { exists: () => Effect.succeed(false) } as never),
96 Layer.mock(GitWorkflow.GitWorkflowService)({ pruneWorktrees, createWorktree }),
97 Layer.mock(ProjectService.ProjectService)({
98 getById: () =>
99 Effect.succeed(
100 Option.some({ workspaceRoot: "/tmp/provider-turn-start-project" } as never),
101 ),
102 }),
103 Layer.mock(ProjectionStore.ProjectionStoreV2)({
104 getTurnStartContext: () => {
105 projectionReadCount += 1;
106 return Effect.succeed({
107 ...projection,
108 hasConversation: projection.messages.some(
109 (m) =>
110 m.role === "user" &&
111 (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0),
112 ),
113 });
114 },
115 getRuntimeRecoveryProjection: () => {
116 projectionReadCount += 1;
117 return Effect.fail(
118 new ProjectionStore.ProjectionStoreReadError({
119 threadId,
120 cause: "simulated inherited-background projection failure",
121 }),
122 );
123 },
124 }),
125 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}),
126 Layer.mock(ProviderAuthService)({ tryHandlePromptCommand: () => Effect.succeed(false) }),
127 Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }),
128 Layer.mock(RuntimePolicy.RuntimePolicyV2)({}),
129 ),
130 ),
131 );
132​
133 await Effect.gen(function* () {
134 const error = yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2)
135 .start({ threadId, runId })
136 .pipe(Effect.flip);
137​
138 expect(error._tag).toBe("ProviderTurnStartError");
139 expect(projectionReadCount).toBe(2);
140 expect(pruneWorktrees).toHaveBeenCalledWith({ cwd: "/tmp/provider-turn-start-project" });
141 expect(createWorktree).toHaveBeenCalledWith({
142 cwd: "/tmp/provider-turn-start-project",
143 refName: "feature/restore",
144 path: "/tmp/missing-provider-turn-start-worktree",
145 });
146 expect(writeIfRunCurrent).not.toHaveBeenCalled();
147 expect(startRootRun).not.toHaveBeenCalled();
148 }).pipe(Effect.provide(layer), Effect.runPromise);
149});
150​
151function makeLocalCommandHarness(input: {
152 readonly text: string;
153 readonly previousNativeSession?: boolean;
154 readonly previousMessages?: ReadonlyArray<string>;
155 readonly logoutFailure?: string;
156}) {
157 const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z");
158 const threadId = ThreadId.make("thread-native-account-command");
159 const runId = RunId.make("run-native-account-command");
160 const rootNodeId = NodeId.make("root-native-account-command");
161 const attemptId = RunAttemptId.make("attempt-native-account-command");
162 const providerThreadId = ProviderThreadId.make("new-provider-thread");
163 const providerSessionId = ProviderSessionId.make("new-provider-session");
164 const oldProviderThreadId = ProviderThreadId.make("existing-native-provider-thread");
165 const oldInstanceId = ProviderInstanceId.make("antigravity-personal");
166 const newInstanceId = ProviderInstanceId.make("codex-personal");
167 const checkpointScopeId = CheckpointScopeId.make("scope-native-account-command");
168 const messageId = MessageId.make("message-native-account-command");
169 const run: OrchestrationV2ThreadProjection["runs"][number] = {
170 id: runId,
171 threadId,
172 ordinal: 2,
173 providerInstanceId: newInstanceId,
174 modelSelection: { instanceId: newInstanceId, model: "gpt-5.4" },
175 providerThreadId,
176 userMessageId: messageId,
177 rootNodeId,
178 activeAttemptId: attemptId,
179 status: "starting",
180 requestedAt: now,
181 startedAt: null,
182 completedAt: null,
183 checkpointId: null,
184 contextHandoffId: null,
185 };
186 const providerThread: OrchestrationV2ThreadProjection["providerThreads"][number] = {
187 id: providerThreadId,
188 driver: ProviderDriverKind.make("codex"),
189 providerInstanceId: newInstanceId,
190 providerSessionId,
191 appThreadId: threadId,
192 ownerNodeId: null,
193 nativeThreadRef: null,
194 nativeConversationHeadRef: null,
195 status: "not_loaded",
196 firstRunOrdinal: 2,
197 lastRunOrdinal: 2,
198 handoffIds: [],
199 forkedFrom: null,
200 createdAt: now,
201 updatedAt: now,
202 };
203 const message: OrchestrationV2ThreadProjection["messages"][number] = {
204 id: messageId,
205 threadId,
206 runId,
207 nodeId: rootNodeId,
208 role: "user",
209 text: input.text,
210 attachments: [],
211 streaming: false,
212 createdBy: "user",
213 creationSource: "web",
214 createdAt: now,
215 updatedAt: now,
216 };
217 let projection: OrchestrationV2ThreadProjection = {
218 thread: {
219 id: threadId,
220 activeProviderThreadId: providerThreadId,
221 branch: null,
222 worktreePath: null,
223 } as OrchestrationV2ThreadProjection["thread"],
224 runs: [
225 ...(input.previousNativeSession
226 ? [
227 {
228 ...run,
229 id: RunId.make("previous-native-run"),
230 ordinal: 1,
231 status: "completed" as const,
232 providerInstanceId: oldInstanceId,
233 providerThreadId: oldProviderThreadId,
234 },
235 ]
236 : []),
237 run,
238 ],
239 attempts: [
240 {
241 id: attemptId,
242 runId,
243 rootNodeId,
244 attemptOrdinal: 1,
245 providerInstanceId: newInstanceId,
246 providerThreadId,
247 providerTurnId: null,
248 reason: "initial",
249 status: "pending",
250 startedAt: null,
251 completedAt: null,
252 },
253 ],
254 nodes: [
255 {
256 id: rootNodeId,
257 threadId,
258 runId,
259 parentNodeId: null,
260 rootNodeId,
261 kind: "root_turn",
262 status: "pending",
263 countsForRun: true,
264 providerThreadId,
265 providerTurnId: null,
266 nativeItemRef: null,
267 runtimeRequestId: null,
268 checkpointScopeId,
269 startedAt: null,
270 completedAt: null,
271 },
272 ],
273 providerThreads: [
274 ...(input.previousNativeSession
275 ? [
276 {
277 ...providerThread,
278 id: oldProviderThreadId,
279 providerInstanceId: oldInstanceId,
280 driver: ProviderDriverKind.make("antigravity"),
281 lastRunOrdinal: 1,
282 nativeThreadRef: {
283 driver: ProviderDriverKind.make("antigravity"),
284 nativeId: "existing-session",
285 strength: "strong" as const,
286 },
287 },
288 ]
289 : []),
290 providerThread,
291 ],
292 messages: [
293 ...(input.previousMessages ?? []).map((text, index) => ({
294 ...message,
295 id: MessageId.make(`previous-message-${index}`),
296 text,
297 })),
298 message,
299 ],
300 checkpointScopes: [
301 {
302 id: checkpointScopeId,
303 threadId,
304 runId,
305 nodeId: rootNodeId,
306 parentScopeId: null,
307 providerThreadId,
308 kind: "root_run",
309 ordinalWithinParent: 0,
310 advancesAppRunCount: true,
311 cwd: "/tmp/native-account-command",
312 createdAt: now,
313 },
314 ],
315 providerSessions: [],
316 providerTurns: [],
317 contextHandoffs: [],
318 contextTransfers: [],
319 turnItems: [],
320 visibleTurnItems: [],
321 runtimeRequests: [],
322 subagents: [],
323 plans: [],
324 checkpoints: [],
325 updatedAt: now,
326 };
327 const events: Array<OrchestrationV2DomainEvent> = [];
328 const open = vi.fn(() => Effect.die("A local command must not open a native session."));
329 const startRootRun = vi.fn(() => Effect.die("A local command must not start a native turn."));
330 const tryHandlePromptCommand = vi.fn(() =>
331 input.logoutFailure === undefined
332 ? Effect.succeed(true)
333 : Effect.fail(
334 new ProviderSetupError({
335 instanceId: oldInstanceId,
336 operation: "logout",
337 detail: input.logoutFailure,
338 }),
339 ),
340 );
341 const layer = ProviderTurnStart.layer.pipe(
342 Layer.provide(
343 Layer.mergeAll(
344 Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}),
345 Layer.mock(EventSink.EventSinkV2)({
346 writeIfRunCurrent: ({ events: incoming, activeAttemptId, expectedStatus }) =>
347 Effect.sync(() => {
348 const current = projection.runs.find((candidate) => candidate.id === runId);
349 const committed =
350 current?.activeAttemptId === activeAttemptId && current.status === expectedStatus;
351 if (committed) {
352 for (const event of incoming) {
353 expect(isDomainEvent(event)).toBe(true);
354 events.push(event);
355 projection = ProjectionStore.applyToProjection(projection, event);
356 }
357 }
358 return { committed, storedEvents: [] };
359 }),
360 }),
361 IdAllocator.layer,
362 FileSystem.layerNoop({}),
363 Layer.mock(GitWorkflow.GitWorkflowService)({}),
364 Layer.mock(ProjectService.ProjectService)({}),
365 Layer.mock(ProjectionStore.ProjectionStoreV2)({
366 getTurnStartContext: () =>
367 Effect.succeed({
368 ...projection,
369 hasConversation: projection.messages.some(
370 (m) =>
371 m.role === "user" &&
372 (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0),
373 ),
374 }),
375 getRuntimeRecoveryProjection: () =>
376 Effect.succeed({
377 ...projection,
378 hasConversation: projection.messages.some(
379 (m) =>
380 m.role === "user" &&
381 (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0),
382 ),
383 }),
384 }),
385 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open }),
386 Layer.mock(ProviderAuthService)({ tryHandlePromptCommand }),
387 Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }),
388 Layer.mock(RuntimePolicy.RuntimePolicyV2)({}),
389 ),
390 ),
391 );
392 return {
393 open,
394 startRootRun,
395 tryHandlePromptCommand,
396 events,
397 oldInstanceId,
398 newInstanceId,
399 projection: () => projection,
400 start: Effect.gen(function* () {
401 yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2).start({ threadId, runId });
402 }).pipe(Effect.provide(layer)),
403 };
405​
406effectIt.effect(
407 "signs out the existing native provider before opening the newly selected provider",
408 () =>
409 Effect.gen(function* () {
410 const harness = makeLocalCommandHarness({ text: "/logout", previousNativeSession: true });
411​
412 yield* harness.start;
413 yield* harness.start;
414​
415 expect(harness.tryHandlePromptCommand).toHaveBeenCalledExactlyOnceWith({
416 instanceId: harness.oldInstanceId,
417 text: "/logout",
418 hasAttachments: false,
419 });
420 expect(harness.open).not.toHaveBeenCalled();
421 expect(harness.startRootRun).not.toHaveBeenCalled();
422 const projection = harness.projection();
423 expect(projection.runs.at(-1)?.status).toBe("completed");
424 expect(projection.attempts[0]?.status).toBe("completed");
425 expect(projection.nodes[0]?.status).toBe("completed");
426 expect(projection.turnItems).toMatchObject([
427 {
428 type: "command_execution",
429 title: "Provider signed out",
430 output: "Provider signed out",
431 status: "completed",
432 },
433 ]);
434 expect(projection.providerTurns).toEqual([]);
435 expect(projection.checkpoints).toEqual([]);
436 }),
437);
438​
439effectIt.effect("persists a failed sign-out without starting a provider turn", () =>
440 Effect.gen(function* () {
441 const harness = makeLocalCommandHarness({
442 text: "/logout",
443 logoutFailure: "Could not stop all sessions for this provider. Try again.",
444 });
445​
446 yield* harness.start;
447​
448 expect(harness.open).not.toHaveBeenCalled();
449 expect(harness.startRootRun).not.toHaveBeenCalled();
450 expect(harness.projection().runs.at(-1)?.status).toBe("failed");
451 expect(harness.projection().turnItems).toMatchObject([
452 {
453 type: "error",
454 title: "Provider sign-out failed",
455 failure: {
456 class: "permission_error",
457 message: "Could not stop all sessions for this provider. Try again.",
458 },
459 },
460 ]);
461 }),
462);
463​
464for (const previousMessages of [[], ["/compact", " /COMPACT "]]) {
465 effectIt.effect(
466 `rejects compaction without conversation context after ${previousMessages.length} prior compactions`,
467 () =>
468 Effect.gen(function* () {
469 const harness = makeLocalCommandHarness({ text: "/compact", previousMessages });
470​
471 yield* harness.start;
472​
473 expect(harness.open).not.toHaveBeenCalled();
474 expect(harness.tryHandlePromptCommand).not.toHaveBeenCalled();
475 expect(harness.startRootRun).not.toHaveBeenCalled();
476 expect(harness.projection().runs.at(-1)?.status).toBe("failed");
477 expect(harness.projection().turnItems).toMatchObject([
478 {
479 type: "error",
480 failure: {
481 class: "validation_error",
482 message: "Start a conversation before compacting this thread.",
483 },
484 },
485 ]);
486 }),
487 );