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

ProviderTurnStartService.test.ts

462 lines15.7 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 getThreadProjection: () => {
105 projectionReadCount += 1;
106 return projectionReadCount === 1
107 ? Effect.succeed(projection)
108 : Effect.fail(
109 new ProjectionStore.ProjectionStoreReadError({
110 threadId,
111 cause: "simulated inherited-background projection failure",
112 }),
113 );
114 },
115 }),
116 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}),
117 Layer.mock(ProviderAuthService)({ tryHandlePromptCommand: () => Effect.succeed(false) }),
118 Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }),
119 Layer.mock(RuntimePolicy.RuntimePolicyV2)({}),
120 ),
121 ),
122 );
123​
124 await Effect.gen(function* () {
125 const error = yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2)
126 .start({ threadId, runId })
127 .pipe(Effect.flip);
128​
129 expect(error._tag).toBe("ProviderTurnStartError");
130 expect(projectionReadCount).toBe(2);
131 expect(pruneWorktrees).toHaveBeenCalledWith({ cwd: "/tmp/provider-turn-start-project" });
132 expect(createWorktree).toHaveBeenCalledWith({
133 cwd: "/tmp/provider-turn-start-project",
134 refName: "feature/restore",
135 path: "/tmp/missing-provider-turn-start-worktree",
136 });
137 expect(writeIfRunCurrent).not.toHaveBeenCalled();
138 expect(startRootRun).not.toHaveBeenCalled();
139 }).pipe(Effect.provide(layer), Effect.runPromise);
140});
141​
142function makeLocalCommandHarness(input: {
143 readonly text: string;
144 readonly previousNativeSession?: boolean;
145 readonly previousMessages?: ReadonlyArray<string>;
146 readonly logoutFailure?: string;
147}) {
148 const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z");
149 const threadId = ThreadId.make("thread-native-account-command");
150 const runId = RunId.make("run-native-account-command");
151 const rootNodeId = NodeId.make("root-native-account-command");
152 const attemptId = RunAttemptId.make("attempt-native-account-command");
153 const providerThreadId = ProviderThreadId.make("new-provider-thread");
154 const providerSessionId = ProviderSessionId.make("new-provider-session");
155 const oldProviderThreadId = ProviderThreadId.make("existing-native-provider-thread");
156 const oldInstanceId = ProviderInstanceId.make("antigravity-personal");
157 const newInstanceId = ProviderInstanceId.make("codex-personal");
158 const checkpointScopeId = CheckpointScopeId.make("scope-native-account-command");
159 const messageId = MessageId.make("message-native-account-command");
160 const run: OrchestrationV2ThreadProjection["runs"][number] = {
161 id: runId,
162 threadId,
163 ordinal: 2,
164 providerInstanceId: newInstanceId,
165 modelSelection: { instanceId: newInstanceId, model: "gpt-5.4" },
166 providerThreadId,
167 userMessageId: messageId,
168 rootNodeId,
169 activeAttemptId: attemptId,
170 status: "starting",
171 requestedAt: now,
172 startedAt: null,
173 completedAt: null,
174 checkpointId: null,
175 contextHandoffId: null,
176 };
177 const providerThread: OrchestrationV2ThreadProjection["providerThreads"][number] = {
178 id: providerThreadId,
179 driver: ProviderDriverKind.make("codex"),
180 providerInstanceId: newInstanceId,
181 providerSessionId,
182 appThreadId: threadId,
183 ownerNodeId: null,
184 nativeThreadRef: null,
185 nativeConversationHeadRef: null,
186 status: "not_loaded",
187 firstRunOrdinal: 2,
188 lastRunOrdinal: 2,
189 handoffIds: [],
190 forkedFrom: null,
191 createdAt: now,
192 updatedAt: now,
193 };
194 const message: OrchestrationV2ThreadProjection["messages"][number] = {
195 id: messageId,
196 threadId,
197 runId,
198 nodeId: rootNodeId,
199 role: "user",
200 text: input.text,
201 attachments: [],
202 streaming: false,
203 createdBy: "user",
204 creationSource: "web",
205 createdAt: now,
206 updatedAt: now,
207 };
208 let projection: OrchestrationV2ThreadProjection = {
209 thread: {
210 id: threadId,
211 activeProviderThreadId: providerThreadId,
212 branch: null,
213 worktreePath: null,
214 } as OrchestrationV2ThreadProjection["thread"],
215 runs: [
216 ...(input.previousNativeSession
217 ? [
218 {
219 ...run,
220 id: RunId.make("previous-native-run"),
221 ordinal: 1,
222 status: "completed" as const,
223 providerInstanceId: oldInstanceId,
224 providerThreadId: oldProviderThreadId,
225 },
226 ]
227 : []),
228 run,
229 ],
230 attempts: [
231 {
232 id: attemptId,
233 runId,
234 rootNodeId,
235 attemptOrdinal: 1,
236 providerInstanceId: newInstanceId,
237 providerThreadId,
238 providerTurnId: null,
239 reason: "initial",
240 status: "pending",
241 startedAt: null,
242 completedAt: null,
243 },
244 ],
245 nodes: [
246 {
247 id: rootNodeId,
248 threadId,
249 runId,
250 parentNodeId: null,
251 rootNodeId,
252 kind: "root_turn",
253 status: "pending",
254 countsForRun: true,
255 providerThreadId,
256 providerTurnId: null,
257 nativeItemRef: null,
258 runtimeRequestId: null,
259 checkpointScopeId,
260 startedAt: null,
261 completedAt: null,
262 },
263 ],
264 providerThreads: [
265 ...(input.previousNativeSession
266 ? [
267 {
268 ...providerThread,
269 id: oldProviderThreadId,
270 providerInstanceId: oldInstanceId,
271 driver: ProviderDriverKind.make("antigravity"),
272 lastRunOrdinal: 1,
273 nativeThreadRef: {
274 driver: ProviderDriverKind.make("antigravity"),
275 nativeId: "existing-session",
276 strength: "strong" as const,
277 },
278 },
279 ]
280 : []),
281 providerThread,
282 ],
283 messages: [
284 ...(input.previousMessages ?? []).map((text, index) => ({
285 ...message,
286 id: MessageId.make(`previous-message-${index}`),
287 text,
288 })),
289 message,
290 ],
291 checkpointScopes: [
292 {
293 id: checkpointScopeId,
294 threadId,
295 runId,
296 nodeId: rootNodeId,
297 parentScopeId: null,
298 providerThreadId,
299 kind: "root_run",
300 ordinalWithinParent: 0,
301 advancesAppRunCount: true,
302 cwd: "/tmp/native-account-command",
303 createdAt: now,
304 },
305 ],
306 providerSessions: [],
307 providerTurns: [],
308 contextHandoffs: [],
309 contextTransfers: [],
310 turnItems: [],
311 visibleTurnItems: [],
312 runtimeRequests: [],
313 subagents: [],
314 plans: [],
315 checkpoints: [],
316 updatedAt: now,
317 };
318 const events: Array<OrchestrationV2DomainEvent> = [];
319 const open = vi.fn(() => Effect.die("A local command must not open a native session."));
320 const startRootRun = vi.fn(() => Effect.die("A local command must not start a native turn."));
321 const tryHandlePromptCommand = vi.fn(() =>
322 input.logoutFailure === undefined
323 ? Effect.succeed(true)
324 : Effect.fail(
325 new ProviderSetupError({
326 instanceId: oldInstanceId,
327 operation: "logout",
328 detail: input.logoutFailure,
329 }),
330 ),
331 );
332 const layer = ProviderTurnStart.layer.pipe(
333 Layer.provide(
334 Layer.mergeAll(
335 Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}),
336 Layer.mock(EventSink.EventSinkV2)({
337 writeIfRunCurrent: ({ events: incoming, activeAttemptId, expectedStatus }) =>
338 Effect.sync(() => {
339 const current = projection.runs.find((candidate) => candidate.id === runId);
340 const committed =
341 current?.activeAttemptId === activeAttemptId && current.status === expectedStatus;
342 if (committed) {
343 for (const event of incoming) {
344 expect(isDomainEvent(event)).toBe(true);
345 events.push(event);
346 projection = ProjectionStore.applyToProjection(projection, event);
347 }
348 }
349 return { committed, storedEvents: [] };
350 }),
351 }),
352 IdAllocator.layer,
353 FileSystem.layerNoop({}),
354 Layer.mock(GitWorkflow.GitWorkflowService)({}),
355 Layer.mock(ProjectService.ProjectService)({}),
356 Layer.mock(ProjectionStore.ProjectionStoreV2)({
357 getThreadProjection: () => Effect.succeed(projection),
358 }),
359 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open }),
360 Layer.mock(ProviderAuthService)({ tryHandlePromptCommand }),
361 Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }),
362 Layer.mock(RuntimePolicy.RuntimePolicyV2)({}),
363 ),
364 ),
365 );
366 return {
367 open,
368 startRootRun,
369 tryHandlePromptCommand,
370 events,
371 oldInstanceId,
372 newInstanceId,
373 projection: () => projection,
374 start: Effect.gen(function* () {
375 yield* (yield* ProviderTurnStart.ProviderTurnStartServiceV2).start({ threadId, runId });
376 }).pipe(Effect.provide(layer)),
377 };
379​
380effectIt.effect(
381 "signs out the existing native provider before opening the newly selected provider",
382 () =>
383 Effect.gen(function* () {
384 const harness = makeLocalCommandHarness({ text: "/logout", previousNativeSession: true });
385​
386 yield* harness.start;
387 yield* harness.start;
388​
389 expect(harness.tryHandlePromptCommand).toHaveBeenCalledExactlyOnceWith({
390 instanceId: harness.oldInstanceId,
391 text: "/logout",
392 hasAttachments: false,
393 });
394 expect(harness.open).not.toHaveBeenCalled();
395 expect(harness.startRootRun).not.toHaveBeenCalled();
396 const projection = harness.projection();
397 expect(projection.runs.at(-1)?.status).toBe("completed");
398 expect(projection.attempts[0]?.status).toBe("completed");
399 expect(projection.nodes[0]?.status).toBe("completed");
400 expect(projection.turnItems).toMatchObject([
401 {
402 type: "command_execution",
403 title: "Provider signed out",
404 output: "Provider signed out",
405 status: "completed",
406 },
407 ]);
408 expect(projection.providerTurns).toEqual([]);
409 expect(projection.checkpoints).toEqual([]);
410 }),
411);
412​
413effectIt.effect("persists a failed sign-out without starting a provider turn", () =>
414 Effect.gen(function* () {
415 const harness = makeLocalCommandHarness({
416 text: "/logout",
417 logoutFailure: "Could not stop all sessions for this provider. Try again.",
418 });
419​
420 yield* harness.start;
421​
422 expect(harness.open).not.toHaveBeenCalled();
423 expect(harness.startRootRun).not.toHaveBeenCalled();
424 expect(harness.projection().runs.at(-1)?.status).toBe("failed");
425 expect(harness.projection().turnItems).toMatchObject([
426 {
427 type: "error",
428 title: "Provider sign-out failed",
429 failure: {
430 class: "permission_error",
431 message: "Could not stop all sessions for this provider. Try again.",
432 },
433 },
434 ]);
435 }),
436);
437​
438for (const previousMessages of [[], ["/compact", " /COMPACT "]]) {
439 effectIt.effect(
440 `rejects compaction without conversation context after ${previousMessages.length} prior compactions`,
441 () =>
442 Effect.gen(function* () {
443 const harness = makeLocalCommandHarness({ text: "/compact", previousMessages });
444​
445 yield* harness.start;
446​
447 expect(harness.open).not.toHaveBeenCalled();
448 expect(harness.tryHandlePromptCommand).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 failure: {
455 class: "validation_error",
456 message: "Start a conversation before compacting this thread.",
457 },
458 },
459 ]);
460 }),
461 );