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

AgentSessionImporter.test.ts

1,226 lines50.9 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { describe, expect, it, vi } from "@effect/vitest";
3import {
4 AgentSessionImportProjectChangedError,
5 CommandId,
6 MessageId,
7 ProjectId,
8 ProviderDriverKind,
9 ProviderInstanceId,
10 ThreadId,
11 type OrchestrationCommand,
12 type OrchestrationProjectShell,
13 type OrchestrationThread,
14 type ProviderSendTurnInput,
15} from "@t3tools/contracts";
16import * as Effect from "effect/Effect";
17import * as Deferred from "effect/Deferred";
18import * as Fiber from "effect/Fiber";
19import * as FileSystem from "effect/FileSystem";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Path from "effect/Path";
23import * as Schema from "effect/Schema";
24import * as Stream from "effect/Stream";
25import * as TestClock from "effect/testing/TestClock";
26​
27import { makeTestProviderAdapterHarness } from "../../integration/TestProviderAdapter.integration.ts";
28import { ServerConfig } from "../config.ts";
29import { GitWorkflowService } from "../git/GitWorkflowService.ts";
30import { OrchestrationCommandReceiptRepositoryLive } from "../persistence/Layers/OrchestrationCommandReceipts.ts";
31import { OrchestrationEventStoreLive } from "../persistence/Layers/OrchestrationEventStore.ts";
32import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
33import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
34import { OrchestrationEngineLive } from "../orchestration/Layers/OrchestrationEngine.ts";
35import { OrchestrationProjectionPipelineLive } from "../orchestration/Layers/ProjectionPipeline.ts";
36import { OrchestrationProjectionSnapshotQueryLive } from "../orchestration/Layers/ProjectionSnapshotQuery.ts";
37import { ProviderCommandReactorLive } from "../orchestration/Layers/ProviderCommandReactor.ts";
38import { OrchestrationCommandInvariantError } from "../orchestration/Errors.ts";
39import * as ThreadBackgroundLiveness from "../orchestration/ThreadBackgroundLiveness.ts";
40import * as ThreadPlanProgress from "../orchestration/ThreadPlanProgress.ts";
41import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts";
42import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
43import { ProviderCommandReactor } from "../orchestration/Services/ProviderCommandReactor.ts";
44import { ProviderSessionDirectoryLive } from "../provider/Layers/ProviderSessionDirectory.ts";
45import { makeProviderServiceLive } from "../provider/Layers/ProviderService.ts";
46import {
47 NoOpProviderEventLoggers,
48 ProviderEventLoggers,
49} from "../provider/Layers/ProviderEventLoggers.ts";
50import { ProviderSessionDirectoryPersistenceError } from "../provider/Errors.ts";
51import { ProviderAdapterRegistry } from "../provider/Services/ProviderAdapterRegistry.ts";
52import { ProviderAuthService } from "../provider/Services/ProviderAuthService.ts";
53import * as ProviderSessionDirectory from "../provider/Services/ProviderSessionDirectory.ts";
54import { makeAdapterRegistryMock } from "../provider/testUtils/providerAdapterRegistryMock.ts";
55import { makeProviderRegistryLayer } from "../provider/testUtils/providerRegistryMock.ts";
56import { ServerSettingsService } from "../serverSettings.ts";
57import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
58import { TextGeneration } from "../textGeneration/TextGeneration.ts";
59import { TerminalManager } from "../terminal/Manager.ts";
60import { VcsStatusBroadcaster } from "../vcs/VcsStatusBroadcaster.ts";
61import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts";
62import { importRecentAgentThreads } from "./AgentSessionImporter.ts";
63import * as AgentSessionScanner from "./AgentSessionScanner.ts";
64​
65const PROJECT_ID = ProjectId.make("project-1");
66const WORKSPACE_ROOT = "/tmp/project-from-server";
67const CLAUDE_SESSION_ID = "123e4567-e89b-42d3-a456-426614174000";
68const encodeTranscriptRecord = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
69​
70const makeThread = (source: "codex" | "claudeAgent"): AgentSessionScanner.AgentSessionThread => ({
71 source,
72 providerInstanceId: ProviderInstanceId.make(source),
73 providerSessionId: source === "codex" ? "codex-session" : CLAUDE_SESSION_ID,
74 title: `Imported ${source} thread`,
75 model: null,
76 createdAt: "2026-08-24T10:00:00.000Z",
77 updatedAt: "2026-08-24T10:01:00.000Z",
78 messages: [
79 { role: "user", text: "Fix the bug", createdAt: "2026-08-24T10:00:00.000Z" },
80 { role: "assistant", text: "Fixed", createdAt: "2026-08-24T10:01:00.000Z" },
81 ],
82});
83​
84const makeThreadOutcome = (thread: AgentSessionScanner.AgentSessionThread) =>
85 ({
86 _tag: "Importable",
87 thread,
88 source: {
89 provider: thread.source,
90 providerInstanceId: thread.providerInstanceId,
91 providerSessionId: thread.providerSessionId,
92 filePath: `/tmp/transcripts/${thread.providerInstanceId}/${thread.providerSessionId}.jsonl`,
93 size: 0,
94 mtimeMs: 0,
95 device: 0,
96 inode: 0,
97 birthtimeMs: 0,
98 },
99 }) satisfies AgentSessionScanner.AgentSessionRecentThread;
100​
101const makeProject = (): OrchestrationProjectShell => ({
102 id: PROJECT_ID,
103 title: "Project",
104 workspaceRoot: WORKSPACE_ROOT,
105 defaultModelSelection: null,
106 scripts: [],
107 createdAt: "2026-08-24T09:00:00.000Z",
108 updatedAt: "2026-08-24T09:00:00.000Z",
109});
110​
111const makeProjectedThread = (input: {
112 readonly source: "codex" | "claudeAgent";
113 readonly projectId?: ProjectId;
114 readonly imported?: boolean;
115 readonly includeFollowup?: boolean;
116}): OrchestrationThread => {
117 const sourceThread = makeThread(input.source);
118 const threadId = ThreadId.make(
119 `import:${sourceThread.providerInstanceId}:${sourceThread.providerSessionId}`,
120 );
121 return {
122 id: threadId,
123 projectId: input.projectId ?? PROJECT_ID,
124 title: sourceThread.title,
125 modelSelection: { instanceId: sourceThread.providerInstanceId, model: "default" },
126 runtimeMode: "full-access",
127 interactionMode: "default",
128 pullRequests: [],
129 branch: null,
130 worktreePath: null,
131 latestTurn: null,
132 createdAt: sourceThread.createdAt,
133 updatedAt: sourceThread.updatedAt,
134 archivedAt: null,
135 settledOverride: null,
136 settledAt: null,
137 deletedAt: null,
138 messages: input.imported
139 ? [
140 {
141 id: MessageId.make(`${threadId}:000000`),
142 role: "user",
143 text: "Fix the bug",
144 turnId: null,
145 streaming: false,
146 createdAt: "2026-08-24T10:00:00.000Z",
147 updatedAt: "2026-08-24T10:00:00.000Z",
148 },
149 ...(input.includeFollowup
150 ? [
151 {
152 id: MessageId.make("user-followup"),
153 role: "user" as const,
154 text: "Keep going",
155 turnId: null,
156 streaming: false,
157 createdAt: "2026-08-24T10:02:00.000Z",
158 updatedAt: "2026-08-24T10:02:00.000Z",
159 },
160 ]
161 : []),
162 ]
163 : [],
164 proposedPlans: [],
165 activities: [],
166 checkpoints: [],
167 session: null,
168 };
169};
170​
171const makeSnapshotsLayer = (input: {
172 readonly project?: OrchestrationProjectShell;
173 readonly getThread?: (threadId: ThreadId) => Option.Option<OrchestrationThread>;
174}) =>
175 Layer.mock(ProjectionSnapshotQuery.ProjectionSnapshotQuery)({
176 getProjectShellById: () =>
177 Effect.succeed(input.project === undefined ? Option.none() : Option.some(input.project)),
178 getImportedAgentSessionSources: () => Effect.succeed([]),
179 getThreadDetailById: (threadId) => Effect.succeed(input.getThread?.(threadId) ?? Option.none()),
180 });
181​
182const runImport = (input: {
183 readonly scanner: AgentSessionScanner.AgentSessionScanner["Service"];
184 readonly engine: OrchestrationEngine.OrchestrationEngineService["Service"];
185 readonly directory: ProviderSessionDirectory.ProviderSessionDirectory["Service"];
186 readonly snapshots: ReturnType<typeof makeSnapshotsLayer>;
187 readonly expectedWorkspaceRoot?: string;
188}) =>
189 importRecentAgentThreads({
190 projectId: PROJECT_ID,
191 ...(input.expectedWorkspaceRoot === undefined
192 ? {}
193 : { expectedWorkspaceRoot: input.expectedWorkspaceRoot }),
194 }).pipe(
195 Effect.provideService(AgentSessionScanner.AgentSessionScanner, input.scanner),
196 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, input.engine),
197 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, input.directory),
198 Effect.provide(input.snapshots),
199 );
200​
201it.layer(NodeServices.layer)("AgentSessionImporter", (it) => {
202 describe("importRecentAgentThreads", () => {
203 it.effect("uses the project root and stores provider-specific resume cursors", () =>
204 Effect.gen(function* () {
205 const commands: Array<OrchestrationCommand> = [];
206 const bindings: Array<ProviderSessionDirectory.ProviderRuntimeBinding> = [];
207 let scannedRoot: string | undefined;
208 const scanner = AgentSessionScanner.AgentSessionScanner.of({
209 scan: Effect.die("unused"),
210 recentThreads: (workspaceRoot) => {
211 scannedRoot = workspaceRoot;
212 return Stream.concat(
213 Stream.succeed(makeThreadOutcome(makeThread("codex"))),
214 Stream.fromEffect(
215 Effect.sync(() => {
216 expect(bindings).toHaveLength(1);
217 return makeThreadOutcome(makeThread("claudeAgent"));
218 }),
219 ),
220 );
221 },
222 });
223 const engine = OrchestrationEngine.OrchestrationEngineService.of({
224 dispatch: (command) => Effect.sync(() => ({ sequence: commands.push(command) })),
225 readEvents: () => Stream.empty,
226 readThreadEvents: () => Stream.empty,
227 getThreadReplayStats: () => Effect.die("unused"),
228 streamDomainEvents: Stream.empty,
229 subscribeDomainEvents: Effect.succeed(Stream.empty),
230 withWorktreeCleanup: <A, E>(_paths: ReadonlyArray<string>, effect: Effect.Effect<A, E>) =>
231 effect,
232 latestSequence: Effect.succeed(0),
233 });
234 const directory = ProviderSessionDirectory.ProviderSessionDirectory.of({
235 upsert: (binding) => Effect.sync(() => void bindings.push(binding)),
236 getProvider: () => Effect.die("unused"),
237 recordImportedTranscript: () => Effect.void,
238 getBinding: () => Effect.succeedNone,
239 listThreadIds: () => Effect.die("unused"),
240 listBindings: () => Effect.die("unused"),
241 });
242​
243 const result = yield* runImport({
244 scanner,
245 engine,
246 directory,
247 snapshots: makeSnapshotsLayer({ project: makeProject() }),
248 expectedWorkspaceRoot: `${WORKSPACE_ROOT}/`,
249 });
250​
251 expect(result).toEqual({ importedCount: 2, skippedCount: 0 });
252 expect(scannedRoot).toBe(WORKSPACE_ROOT);
253 expect(commands.map((command) => command.type)).toEqual([
254 "thread.create",
255 "thread.history.import",
256 "thread.create",
257 "thread.history.import",
258 ]);
259 expect(commands.filter((command) => command.type === "thread.create")).toMatchObject([
260 { historyImport: true },
261 { historyImport: true },
262 ]);
263 expect(
264 commands
265 .filter((command) => command.type === "thread.history.import")
266 .flatMap((command) => command.messages.map((message) => message.messageId)),
267 ).toEqual([
268 "import:codex:codex-session:000000",
269 "import:codex:codex-session:000001",
270 `import:claudeAgent:${CLAUDE_SESSION_ID}:000000`,
271 `import:claudeAgent:${CLAUDE_SESSION_ID}:000001`,
272 ]);
273 expect(bindings).toMatchObject([
274 {
275 provider: "codex",
276 providerInstanceId: "codex",
277 resumeCursor: { threadId: "codex-session" },
278 runtimePayload: { cwd: WORKSPACE_ROOT },
279 },
280 {
281 provider: "claudeAgent",
282 providerInstanceId: "claudeAgent",
283 resumeCursor: {
284 threadId: `import:claudeAgent:${CLAUDE_SESSION_ID}`,
285 resume: CLAUDE_SESSION_ID,
286 },
287 runtimePayload: { cwd: WORKSPACE_ROOT },
288 },
289 ]);
290 }),
291 );
292​
293 it.effect("rejects a changed project root before scanning or writing", () =>
294 Effect.gen(function* () {
295 const recentThreads = vi.fn(() => Stream.empty);
296 const error = yield* importRecentAgentThreads({
297 projectId: PROJECT_ID,
298 expectedWorkspaceRoot: WORKSPACE_ROOT,
299 }).pipe(
300 Effect.provideService(
301 AgentSessionScanner.AgentSessionScanner,
302 AgentSessionScanner.AgentSessionScanner.of({
303 scan: Effect.die("must not scan a changed project"),
304 recentThreads,
305 }),
306 ),
307 Effect.provide(
308 Layer.mergeAll(
309 Layer.mock(OrchestrationEngine.OrchestrationEngineService)({}),
310 Layer.mock(ProviderSessionDirectory.ProviderSessionDirectory)({}),
311 makeSnapshotsLayer({
312 project: { ...makeProject(), workspaceRoot: "/tmp/project-moved" },
313 }),
314 ),
315 ),
316 Effect.flip,
317 );
318​
319 expect(error).toEqual(new AgentSessionImportProjectChangedError({ projectId: PROJECT_ID }));
320 expect(recentThreads).not.toHaveBeenCalled();
321 }),
322 );
323​
324 it.effect("counts scanner skips without writing a thread or binding", () =>
325 Effect.gen(function* () {
326 const scanner = AgentSessionScanner.AgentSessionScanner.of({
327 scan: Effect.die("unused"),
328 recentThreads: () => Stream.succeed({ _tag: "Skipped" }),
329 });
330 const engine = OrchestrationEngine.OrchestrationEngineService.of({
331 dispatch: () => Effect.die("must not dispatch for a scanner skip"),
332 readEvents: () => Stream.empty,
333 readThreadEvents: () => Stream.empty,
334 getThreadReplayStats: () => Effect.die("unused"),
335 streamDomainEvents: Stream.empty,
336 subscribeDomainEvents: Effect.succeed(Stream.empty),
337 withWorktreeCleanup: <A, E>(_paths: ReadonlyArray<string>, effect: Effect.Effect<A, E>) =>
338 effect,
339 latestSequence: Effect.succeed(0),
340 });
341 const directory = ProviderSessionDirectory.ProviderSessionDirectory.of({
342 upsert: () => Effect.die("must not bind a scanner skip"),
343 getProvider: () => Effect.die("unused"),
344 recordImportedTranscript: () => Effect.die("unused"),
345 getBinding: () => Effect.die("must not read a scanner skip binding"),
346 listThreadIds: () => Effect.die("unused"),
347 listBindings: () => Effect.die("unused"),
348 });
349​
350 const result = yield* runImport({
351 scanner,
352 engine,
353 directory,
354 snapshots: makeSnapshotsLayer({ project: makeProject() }),
355 });
356​
357 expect(result).toEqual({ importedCount: 0, skippedCount: 1 });
358 }),
359 );
360​
361 it.effect("recovers after a rejected history receipt and a failed binding write", () =>
362 Effect.gen(function* () {
363 let threadCreated = false;
364 let historyImported = false;
365 let historyAttemptCount = 0;
366 let bindingAttemptCount = 0;
367 const rejectedCommandIds = new Set<string>();
368 const bindings: Array<ProviderSessionDirectory.ProviderRuntimeBinding> = [];
369 const scanner = AgentSessionScanner.AgentSessionScanner.of({
370 scan: Effect.die("unused"),
371 recentThreads: () => Stream.fromIterable([makeThreadOutcome(makeThread("codex"))]),
372 });
373 const engine = OrchestrationEngine.OrchestrationEngineService.of({
374 dispatch: (command) => {
375 if (rejectedCommandIds.has(command.commandId)) {
376 return Effect.fail(
377 new OrchestrationCommandInvariantError({
378 commandType: command.type,
379 detail: "Previously rejected.",
380 }),
381 );
382 }
383 if (command.type === "thread.create") threadCreated = true;
384 if (command.type === "thread.history.import") {
385 historyAttemptCount += 1;
386 if (historyAttemptCount === 1) {
387 rejectedCommandIds.add(command.commandId);
388 return Effect.fail(
389 new OrchestrationCommandInvariantError({
390 commandType: command.type,
391 detail: "Temporary history import failure.",
392 }),
393 );
394 }
395 historyImported = true;
396 }
397 return Effect.succeed({ sequence: 1 });
398 },
399 readEvents: () => Stream.empty,
400 readThreadEvents: () => Stream.empty,
401 getThreadReplayStats: () => Effect.die("unused"),
402 streamDomainEvents: Stream.empty,
403 subscribeDomainEvents: Effect.succeed(Stream.empty),
404 withWorktreeCleanup: <A, E>(_paths: ReadonlyArray<string>, effect: Effect.Effect<A, E>) =>
405 effect,
406 latestSequence: Effect.succeed(0),
407 });
408 const directory = ProviderSessionDirectory.ProviderSessionDirectory.of({
409 upsert: (binding) => {
410 bindingAttemptCount += 1;
411 if (bindingAttemptCount === 1) {
412 return Effect.fail(
413 new ProviderSessionDirectoryPersistenceError({
414 operation: "upsert",
415 detail: "Temporary session storage failure.",
416 }),
417 );
418 }
419 bindings.push(binding);
420 return Effect.void;
421 },
422 getProvider: () => Effect.die("unused"),
423 recordImportedTranscript: () => Effect.void,
424 getBinding: () =>
425 Effect.succeed(bindings[0] === undefined ? Option.none() : Option.some(bindings[0])),
426 listThreadIds: () => Effect.die("unused"),
427 listBindings: () => Effect.die("unused"),
428 });
429 const snapshots = makeSnapshotsLayer({
430 project: makeProject(),
431 getThread: () =>
432 threadCreated
433 ? Option.some(makeProjectedThread({ source: "codex", imported: historyImported }))
434 : Option.none(),
435 });
436 const importOnce = () => runImport({ scanner, engine, directory, snapshots });
437​
438 expect(yield* importOnce()).toEqual({ importedCount: 0, skippedCount: 1 });
439 expect(yield* importOnce()).toEqual({ importedCount: 0, skippedCount: 1 });
440 expect(yield* importOnce()).toEqual({ importedCount: 1, skippedCount: 0 });
441 const historyAttemptsAfterCompletion = historyAttemptCount;
442 expect(yield* importOnce()).toEqual({ importedCount: 1, skippedCount: 0 });
443 expect(historyAttemptCount).toBe(historyAttemptsAfterCompletion);
444 expect(historyAttemptCount).toBe(2);
445 expect(bindings).toHaveLength(1);
446 }),
447 );
448​
449 it.effect("does not replace completed history or an active binding on retry", () =>
450 Effect.gen(function* () {
451 const scanner = AgentSessionScanner.AgentSessionScanner.of({
452 scan: Effect.die("unused"),
453 recentThreads: () => Stream.fromIterable([makeThreadOutcome(makeThread("codex"))]),
454 });
455 const runningBinding: ProviderSessionDirectory.ProviderRuntimeBinding = {
456 threadId: ThreadId.make("import:codex:codex-session"),
457 provider: ProviderDriverKind.make("codex"),
458 providerInstanceId: ProviderInstanceId.make("codex"),
459 status: "running",
460 resumeCursor: { threadId: "newer-codex-session" },
461 };
462 const directory = ProviderSessionDirectory.ProviderSessionDirectory.of({
463 upsert: () => Effect.die("must not replace an active binding"),
464 getProvider: () => Effect.die("unused"),
465 recordImportedTranscript: () => Effect.void,
466 getBinding: () => Effect.succeedSome(runningBinding),
467 listThreadIds: () => Effect.die("unused"),
468 listBindings: () => Effect.die("unused"),
469 });
470 const engine = OrchestrationEngine.OrchestrationEngineService.of({
471 dispatch: () => Effect.die("must not replay history or settle active work"),
472 readEvents: () => Stream.empty,
473 readThreadEvents: () => Stream.empty,
474 getThreadReplayStats: () => Effect.die("unused"),
475 streamDomainEvents: Stream.empty,
476 subscribeDomainEvents: Effect.succeed(Stream.empty),
477 withWorktreeCleanup: <A, E>(_paths: ReadonlyArray<string>, effect: Effect.Effect<A, E>) =>
478 effect,
479 latestSequence: Effect.succeed(0),
480 });
481​
482 const result = yield* runImport({
483 scanner,
484 engine,
485 directory,
486 snapshots: makeSnapshotsLayer({
487 project: makeProject(),
488 getThread: () =>
489 Option.some(
490 makeProjectedThread({ source: "codex", imported: true, includeFollowup: true }),
491 ),
492 }),
493 });
494​
495 expect(result).toEqual({ importedCount: 1, skippedCount: 0 });
496 }),
497 );
498​
499 it.effect("skips malformed Claude ids and wrong-project thread collisions", () =>
500 Effect.gen(function* () {
501 const scanner = AgentSessionScanner.AgentSessionScanner.of({
502 scan: Effect.die("unused"),
503 recentThreads: () =>
504 Stream.fromIterable([
505 makeThreadOutcome({ ...makeThread("claudeAgent"), providerSessionId: "not-a-uuid" }),
506 makeThreadOutcome(makeThread("codex")),
507 ]),
508 });
509 const commands: Array<OrchestrationCommand> = [];
510 const engine = OrchestrationEngine.OrchestrationEngineService.of({
511 dispatch: (command) => Effect.sync(() => ({ sequence: commands.push(command) })),
512 readEvents: () => Stream.empty,
513 readThreadEvents: () => Stream.empty,
514 getThreadReplayStats: () => Effect.die("unused"),
515 streamDomainEvents: Stream.empty,
516 subscribeDomainEvents: Effect.succeed(Stream.empty),
517 withWorktreeCleanup: <A, E>(_paths: ReadonlyArray<string>, effect: Effect.Effect<A, E>) =>
518 effect,
519 latestSequence: Effect.succeed(0),
520 });
521 const directory = ProviderSessionDirectory.ProviderSessionDirectory.of({
522 upsert: () => Effect.die("must not bind malformed or wrong-project sessions"),
523 getProvider: () => Effect.die("unused"),
524 recordImportedTranscript: () => Effect.die("unused"),
525 getBinding: () => Effect.succeedNone,
526 listThreadIds: () => Effect.die("unused"),
527 listBindings: () => Effect.die("unused"),
528 });
529​
530 const result = yield* runImport({
531 scanner,
532 engine,
533 directory,
534 snapshots: makeSnapshotsLayer({
535 project: makeProject(),
536 getThread: (threadId) =>
537 threadId === "import:codex:codex-session"
538 ? Option.some(
539 makeProjectedThread({
540 source: "codex",
541 projectId: ProjectId.make("project-other"),
542 }),
543 )
544 : Option.none(),
545 }),
546 });
547​
548 expect(result).toEqual({ importedCount: 0, skippedCount: 2 });
549 expect(commands).toHaveLength(0);
550 }),
551 );
552 });
553});
554​
555const integrationThread = {
556 ...makeThread("codex"),
557 updatedAt: "2026-08-24T10:00:00.000Z",
558 messages: Array.from({ length: 12 }, (_, index) => ({
559 role: index % 2 === 0 ? ("user" as const) : ("assistant" as const),
560 text: `Message ${index}`,
561 createdAt: "2026-08-24T10:00:00.000Z",
562 })),
563};
564const integrationScanner = AgentSessionScanner.AgentSessionScanner.of({
565 scan: Effect.die("unused"),
566 recentThreads: () => Stream.fromIterable([makeThreadOutcome(integrationThread)]),
567});
568const integrationServerConfig = ServerConfig.layerTest(process.cwd(), {
569 prefix: "t3-agent-session-importer-test-",
570});
571const integrationRuntimeRepository = ProviderSessionRuntime.layer.pipe(
572 Layer.provide(SqlitePersistenceMemory),
573);
574const integrationLayer = Layer.mergeAll(
575 OrchestrationEngineLive.pipe(
576 Layer.provide(OrchestrationProjectionSnapshotQueryLive),
577 Layer.provide(OrchestrationProjectionPipelineLive),
578 ),
579 OrchestrationProjectionSnapshotQueryLive,
580 integrationRuntimeRepository,
581 ProviderSessionDirectoryLive.pipe(Layer.provide(integrationRuntimeRepository)),
582 Layer.succeed(AgentSessionScanner.AgentSessionScanner, integrationScanner),
583).pipe(
584 Layer.provide(ThreadBackgroundLiveness.layer),
585 Layer.provide(ThreadPlanProgress.layer),
586 Layer.provide(OrchestrationEventStoreLive),
587 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
588 Layer.provide(RepositoryIdentityResolver.layer),
589 Layer.provide(SqlitePersistenceMemory),
590 Layer.provideMerge(integrationServerConfig),
591 Layer.provideMerge(NodeServices.layer),
592);
593​
594it.layer(integrationLayer)("AgentSessionImporter integration", (it) => {
595 it.effect("imports once after the real engine persists an old rejected receipt", () =>
596 Effect.gen(function* () {
597 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
598 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
599 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
600 const threadId = ThreadId.make("import:codex:codex-session");
601​
602 yield* engine.dispatch({
603 type: "project.create",
604 commandId: CommandId.make("create-import-integration-project"),
605 projectId: PROJECT_ID,
606 title: "Project",
607 workspaceRoot: WORKSPACE_ROOT,
608 defaultModelSelection: null,
609 createdAt: "2026-08-24T09:00:00.000Z",
610 });
611 const rejected = yield* Effect.result(
612 engine.dispatch({
613 type: "thread.history.import",
614 commandId: CommandId.make(`agent-session:history:${threadId}`),
615 threadId,
616 messages: [
617 {
618 messageId: MessageId.make(`${threadId}:000000`),
619 role: "user",
620 text: "Fix the bug",
621 createdAt: "2026-08-24T10:00:00.000Z",
622 },
623 ],
624 }),
625 );
626 expect(rejected._tag).toBe("Failure");
627​
628 const result = yield* importRecentAgentThreads({ projectId: PROJECT_ID });
629 const importedThread = yield* snapshots.getThreadDetailById(threadId);
630 const binding = yield* directory.getBinding(threadId);
631​
632 expect(result).toEqual({ importedCount: 1, skippedCount: 0 });
633 expect(Option.getOrThrow(importedThread).messages.map((message) => message.text)).toEqual(
634 integrationThread.messages.map((message) => message.text),
635 );
636 expect(Option.getOrThrow(importedThread).settledOverride).toBe("settled");
637 expect(Option.getOrThrow(importedThread).updatedAt).toBe("2026-08-24T10:00:00.000Z");
638 expect(Option.getOrThrow(binding)).toMatchObject({
639 provider: "codex",
640 providerInstanceId: "codex",
641 resumeCursor: { threadId: "codex-session" },
642 runtimePayload: { cwd: WORKSPACE_ROOT },
643 });
644​
645 yield* engine.dispatch({
646 type: "thread.revert.complete",
647 commandId: CommandId.make("revert-imported-thread-to-baseline"),
648 threadId,
649 turnCount: 0,
650 createdAt: "2026-08-24T10:05:00.000Z",
651 });
652 const afterRevert = yield* snapshots.getThreadDetailById(threadId);
653 expect(Option.getOrThrow(afterRevert).messages.map((message) => message.text)).toEqual(
654 integrationThread.messages.map((message) => message.text),
655 );
656 }),
657 );
658​
659 it.effect(
660 "retries a bounded import after scanner restart without rereading completed transcripts",
661 () =>
662 Effect.gen(function* () {
663 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
664 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
665 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
666 const fileSystem = yield* FileSystem.FileSystem;
667 const path = yield* Path.Path;
668 const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
669 yield* TestClock.setTime(nowMs);
670 const fixtureDir = yield* fileSystem.makeTempDirectoryScoped({
671 prefix: "t3-import-retry-",
672 });
673 const workspaceRoot = path.join(fixtureDir, "workspace");
674 const claudeHomePath = path.join(fixtureDir, "claude");
675 const codexHomePath = path.join(fixtureDir, "codex");
676 const sessionsDir = path.join(codexHomePath, "sessions", "2026", "08", "24");
677 yield* fileSystem.makeDirectory(workspaceRoot);
678 yield* fileSystem.makeDirectory(claudeHomePath);
679 yield* fileSystem.makeDirectory(sessionsDir, { recursive: true });
680​
681 const projectId = ProjectId.make("project-bounded-import-retry");
682 const transcripts = Array.from({ length: 101 }, (_, index) => {
683 const providerSessionId = `bounded-session-${String(index).padStart(3, "0")}`;
684 return {
685 providerSessionId,
686 threadId: ThreadId.make(`import:codex:${providerSessionId}`),
687 filePath: path.join(sessionsDir, `rollout-${providerSessionId}.jsonl`),
688 };
689 });
690 for (const [index, transcript] of transcripts.entries()) {
691 yield* fileSystem.writeFileString(
692 transcript.filePath,
693 [
694 encodeTranscriptRecord({
695 type: "session_meta",
696 payload: { id: transcript.providerSessionId, cwd: workspaceRoot },
697 }),
698 encodeTranscriptRecord({
699 type: "event_msg",
700 payload: {
701 type: "user_message",
702 message: `Prompt ${transcript.providerSessionId}`,
703 },
704 }),
705 ].join("\n"),
706 );
707 const seconds = nowMs / 1_000 - index;
708 yield* fileSystem.utimes(transcript.filePath, seconds, seconds);
709 }
710 const legacy = transcripts[0]!;
711 const failed = transcripts[1]!;
712 const remaining = transcripts[100]!;
713 yield* engine.dispatch({
714 type: "project.create",
715 commandId: CommandId.make("create-bounded-import-project"),
716 projectId,
717 title: "Bounded import",
718 workspaceRoot,
719 defaultModelSelection: null,
720 createdAt: "2026-08-24T09:00:00.000Z",
721 });
722​
723 // This completed import predates persisted transcript source metadata.
724 yield* directory.upsert({
725 threadId: legacy.threadId,
726 provider: ProviderDriverKind.make("codex"),
727 providerInstanceId: ProviderInstanceId.make("codex"),
728 status: "stopped",
729 resumeCursor: { threadId: "legacy-current-session" },
730 runtimePayload: { cwd: workspaceRoot },
731 });
732 yield* engine.dispatch({
733 type: "thread.create",
734 commandId: CommandId.make("create-legacy-bounded-import"),
735 threadId: legacy.threadId,
736 projectId,
737 title: "Legacy import",
738 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "default" },
739 runtimeMode: "full-access",
740 interactionMode: "default",
741 branch: null,
742 worktreePath: null,
743 createdAt: "2026-08-24T10:00:00.000Z",
744 historyImport: true,
745 });
746 yield* engine.dispatch({
747 type: "thread.history.import",
748 commandId: CommandId.make("import-legacy-bounded-history"),
749 threadId: legacy.threadId,
750 messages: [
751 {
752 messageId: MessageId.make(`${legacy.threadId}:000000`),
753 role: "user",
754 text: "Legacy imported history",
755 createdAt: "2026-08-24T10:00:00.000Z",
756 },
757 ],
758 });
759 expect(yield* snapshots.getImportedAgentSessionSources(projectId)).toEqual([]);
760​
761 let failHistory = true;
762 const importerEngine = OrchestrationEngine.OrchestrationEngineService.of({
763 ...engine,
764 dispatch: (command) => {
765 if (
766 failHistory &&
767 command.type === "thread.history.import" &&
768 command.threadId === failed.threadId
769 ) {
770 failHistory = false;
771 return Effect.fail(
772 new OrchestrationCommandInvariantError({
773 commandType: command.type,
774 detail: "Injected history import failure.",
775 }),
776 );
777 }
778 return engine.dispatch(command);
779 },
780 });
781 const settingsLayer = ServerSettingsService.layerTest({
782 providers: {
783 claudeAgent: { homePath: claudeHomePath },
784 codex: { homePath: codexHomePath },
785 },
786 });
787 const transcriptPaths = new Set(transcripts.map((transcript) => transcript.filePath));
788 const runAttempt = Effect.fn("runBoundedImportAttempt")(function* (
789 completedPaths: ReadonlySet<string>,
790 ) {
791 const openCounts = new Map<string, number>();
792 const fullReads: string[] = [];
793 const observedFileSystem = FileSystem.FileSystem.of({
794 ...fileSystem,
795 open: (filePath, options) =>
796 Effect.suspend(() => {
797 if (transcriptPaths.has(filePath)) {
798 const count = (openCounts.get(filePath) ?? 0) + 1;
799 openCounts.set(filePath, count);
800 // A fresh scanner first opens each file for project discovery.
801 if (count > 1) {
802 fullReads.push(filePath);
803 if (completedPaths.has(filePath)) {
804 return Effect.die(new Error(`Completed transcript reopened: ${filePath}`));
805 }
806 }
807 }
808 return fileSystem.open(filePath, options);
809 }),
810 });
811 const result = yield* importRecentAgentThreads({ projectId }).pipe(
812 Effect.provide(
813 Layer.fresh(AgentSessionScanner.layer).pipe(
814 Layer.provide(settingsLayer),
815 Layer.provide(Layer.succeed(FileSystem.FileSystem, observedFileSystem)),
816 ),
817 ),
818 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, importerEngine),
819 );
820 return { result, fullReads, openCounts };
821 });
822​
823 const first = yield* runAttempt(new Set());
824 expect(first.result).toEqual({ importedCount: 99, skippedCount: 2 });
825 expect(failHistory).toBe(false);
826 expect(first.fullReads).toEqual(transcripts.slice(0, 100).map((entry) => entry.filePath));
827 expect(first.openCounts.get(remaining.filePath)).toBe(1);
828 const completedSources = yield* snapshots.getImportedAgentSessionSources(projectId);
829 expect(completedSources).toHaveLength(99);
830 expect(completedSources).toContainEqual({
831 threadId: legacy.threadId,
832 source: expect.objectContaining({ filePath: legacy.filePath }),
833 });
834 expect(
835 Option.getOrThrow(yield* snapshots.getThreadDetailById(failed.threadId)).messages,
836 ).toEqual([]);
837 expect(Option.getOrThrow(yield* directory.getBinding(failed.threadId))).toMatchObject({
838 status: "stopped",
839 resumeCursor: { threadId: failed.providerSessionId },
840 });
841 expect(Option.isNone(yield* snapshots.getThreadDetailById(remaining.threadId))).toBe(true);
842​
843 const completedPaths = new Set(completedSources.map((entry) => entry.source.filePath));
844 const second = yield* runAttempt(completedPaths);
845 expect(second.result).toEqual({ importedCount: 101, skippedCount: 0 });
846 expect(second.fullReads).toEqual([failed.filePath, remaining.filePath]);
847 for (const transcript of transcripts) {
848 expect(second.openCounts.get(transcript.filePath)).toBe(
849 completedPaths.has(transcript.filePath) ? 1 : 2,
850 );
851 }
852 expect(yield* snapshots.getImportedAgentSessionSources(projectId)).toHaveLength(101);
853 expect(
854 Option.getOrThrow(yield* snapshots.getThreadDetailById(legacy.threadId)).messages.map(
855 (message) => message.text,
856 ),
857 ).toEqual(["Legacy imported history"]);
858 expect(
859 Option.getOrThrow(yield* directory.getBinding(legacy.threadId)).resumeCursor,
860 ).toEqual({
861 threadId: "legacy-current-session",
862 });
863 for (const transcript of [failed, remaining]) {
864 expect(
865 Option.getOrThrow(
866 yield* snapshots.getThreadDetailById(transcript.threadId),
867 ).messages.map((message) => message.text),
868 ).toEqual([`Prompt ${transcript.providerSessionId}`]);
869 }
870 }),
871 );
872​
873 for (const source of ["codex", "claudeAgent"] as const) {
874 it.effect(`resumes imported ${source} history only after the first prompt`, () =>
875 Effect.gen(function* () {
876 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
877 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
878 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
879 const fileSystem = yield* FileSystem.FileSystem;
880 const workspaceRoot = yield* fileSystem.makeTempDirectoryScoped();
881 const projectId = ProjectId.make(`project-import-resume-${source}`);
882 const sourceThread = {
883 ...makeThread(source),
884 providerSessionId: source === "codex" ? "codex-first-resume" : CLAUDE_SESSION_ID,
885 };
886 const threadId = ThreadId.make(
887 `import:${sourceThread.providerInstanceId}:${sourceThread.providerSessionId}`,
888 );
889 const resumeCursor =
890 source === "codex"
891 ? { threadId: sourceThread.providerSessionId }
892 : { threadId, resume: sourceThread.providerSessionId };
893 const provider = ProviderDriverKind.make(source);
894 const harness = yield* makeTestProviderAdapterHarness({ provider });
895 const importSettled = yield* Deferred.make<void>();
896 const turnSent = yield* Deferred.make<void>();
897 const startSession = vi.fn(harness.adapter.startSession);
898 const sendTurn = vi.fn((input: ProviderSendTurnInput) =>
899 harness.adapter
900 .sendTurn(input)
901 .pipe(Effect.tap(() => Deferred.succeed(turnSent, undefined))),
902 );
903 const providerLayer = makeProviderServiceLive().pipe(
904 Layer.provide(
905 Layer.succeed(
906 ProviderAdapterRegistry,
907 makeAdapterRegistryMock({
908 [provider]: { ...harness.adapter, startSession, sendTurn },
909 }),
910 ),
911 ),
912 Layer.provide(
913 Layer.succeed(ProviderSessionDirectory.ProviderSessionDirectory, directory),
914 ),
915 Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
916 Layer.provide(AnalyticsService.layerTest),
917 );
918 const reactorLayer = ProviderCommandReactorLive.pipe(
919 Layer.provideMerge(providerLayer),
920 Layer.provide(
921 Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
922 ...snapshots,
923 // Acknowledge the imported settlement before draining the reactor.
924 getThreadShellById: (requestedThreadId) =>
925 snapshots
926 .getThreadShellById(requestedThreadId)
927 .pipe(
928 Effect.tap(() =>
929 requestedThreadId === threadId
930 ? Deferred.succeed(importSettled, undefined)
931 : Effect.void,
932 ),
933 ),
934 }),
935 ),
936 Layer.provide(
937 Layer.mock(ProviderAuthService)({
938 tryHandlePromptCommand: () => Effect.succeed(false),
939 }),
940 ),
941 Layer.provide(makeProviderRegistryLayer()),
942 Layer.provide(Layer.mock(GitWorkflowService)({})),
943 Layer.provide(Layer.mock(VcsStatusBroadcaster)({})),
944 Layer.provide(Layer.mock(TextGeneration)({})),
945 Layer.provide(Layer.mock(TerminalManager)({ closeIdle: () => Effect.void })),
946 Layer.provide(ServerSettingsService.layerTest()),
947 );
948​
949 yield* engine.dispatch({
950 type: "project.create",
951 commandId: CommandId.make(`create-import-resume-project-${source}`),
952 projectId,
953 title: "Import resume",
954 workspaceRoot,
955 defaultModelSelection: null,
956 createdAt: "2026-08-24T09:00:00.000Z",
957 });
958 yield* harness.queueTurnResponseForNextSession({ events: [] });
959​
960 yield* Effect.gen(function* () {
961 const reactor = yield* ProviderCommandReactor;
962 yield* reactor.start();
963 expect(yield* importRecentAgentThreads({ projectId })).toEqual({
964 importedCount: 1,
965 skippedCount: 0,
966 });
967 yield* Deferred.await(importSettled);
968 yield* reactor.drain;
969 expect(startSession).not.toHaveBeenCalled();
970 expect(sendTurn).not.toHaveBeenCalled();
971 const importedThread = Option.getOrThrow(yield* snapshots.getThreadDetailById(threadId));
972 expect(importedThread.session).toBeNull();
973 expect(importedThread.latestTurn).toBeNull();
974​
975 yield* engine.dispatch({
976 type: "thread.turn.start",
977 commandId: CommandId.make(`resume-imported-${source}`),
978 threadId,
979 message: {
980 messageId: MessageId.make(`resume-imported-message-${source}`),
981 role: "user",
982 text: "Continue this session",
983 attachments: [],
984 },
985 modelSelection: importedThread.modelSelection,
986 runtimeMode: importedThread.runtimeMode,
987 interactionMode: importedThread.interactionMode,
988 createdAt: "2026-08-24T10:02:00.000Z",
989 });
990 yield* Deferred.await(turnSent);
991 yield* reactor.drain;
992 expect(startSession).toHaveBeenCalledExactlyOnceWith(
993 expect.objectContaining({
994 threadId,
995 provider,
996 providerInstanceId: sourceThread.providerInstanceId,
997 resumeCursor,
998 cwd: workspaceRoot,
999 }),
1000 );
1001 expect(sendTurn).toHaveBeenCalledExactlyOnceWith(
1002 expect.objectContaining({ threadId, input: "Continue this session" }),
1003 );
1004 expect(Option.getOrThrow(yield* directory.getBinding(threadId))).toMatchObject({
1005 provider,
1006 providerInstanceId: sourceThread.providerInstanceId,
1007 resumeCursor,
1008 });
1009 }).pipe(
1010 Effect.provide(reactorLayer),
1011 Effect.provideService(
1012 AgentSessionScanner.AgentSessionScanner,
1013 AgentSessionScanner.AgentSessionScanner.of({
1014 scan: Effect.die("unused"),
1015 recentThreads: () => Stream.succeed(makeThreadOutcome(sourceThread)),
1016 }),
1017 ),
1018 );
1019 }),
1020 );
1022​
1023 it.effect("persists the resume cursor before publishing a new imported thread", () =>
1024 Effect.gen(function* () {
1025 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
1026 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
1027 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
1028 const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
1029 const projectId = ProjectId.make("project-import-binding-race");
1030 const workspaceRoot = "/tmp/project-import-binding-race";
1031 const providerSessionId = "codex-binding-race";
1032 const threadId = ThreadId.make(`import:codex:${providerSessionId}`);
1033 const scanner = AgentSessionScanner.AgentSessionScanner.of({
1034 scan: Effect.die("unused"),
1035 recentThreads: () =>
1036 Stream.succeed(
1037 makeThreadOutcome({ ...integrationThread, providerSessionId, title: "Binding race" }),
1038 ),
1039 });
1040 const importerAtBindingWrite = yield* Deferred.make<void>();
1041 const releaseImporter = yield* Deferred.make<void>();
1042 const importerRepository = ProviderSessionRuntime.ProviderSessionRuntimeRepository.of({
1043 ...repository,
1044 upsert: (runtime, options) =>
1045 options?.onConflict === "ignore"
1046 ? Deferred.succeed(importerAtBindingWrite, undefined).pipe(
1047 Effect.andThen(Deferred.await(releaseImporter)),
1048 Effect.andThen(repository.upsert(runtime, options)),
1050 : repository.upsert(runtime, options),
1051 });
1052 const importerDirectory = yield* ProviderSessionDirectory.ProviderSessionDirectory.pipe(
1053 Effect.provide(
1054 Layer.fresh(ProviderSessionDirectoryLive).pipe(
1055 Layer.provide(
1056 Layer.succeed(
1057 ProviderSessionRuntime.ProviderSessionRuntimeRepository,
1058 importerRepository,
1059 ),
1060 ),
1061 ),
1062 ),
1063 );
1064​
1065 yield* engine.dispatch({
1066 type: "project.create",
1067 commandId: CommandId.make("create-import-binding-race-project"),
1068 projectId,
1069 title: "Binding race",
1070 workspaceRoot,
1071 defaultModelSelection: null,
1072 createdAt: "2026-08-24T09:00:00.000Z",
1073 });
1074​
1075 const importFiber = yield* importRecentAgentThreads({ projectId }).pipe(
1076 Effect.provideService(AgentSessionScanner.AgentSessionScanner, scanner),
1077 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, importerDirectory),
1078 Effect.forkChild,
1079 );
1080​
1081 yield* Effect.raceFirst(
1082 Deferred.await(importerAtBindingWrite),
1083 Fiber.join(importFiber).pipe(
1084 Effect.flatMap((result) =>
1085 Effect.die(
1086 new Error(`Import completed before the binding write: ${JSON.stringify(result)}`),
1087 ),
1088 ),
1089 ),
1090 );
1091 expect(Option.isNone(yield* snapshots.getThreadDetailById(threadId))).toBe(true);
1092​
1093 yield* directory.upsert({
1094 threadId,
1095 provider: ProviderDriverKind.make("codex"),
1096 providerInstanceId: ProviderInstanceId.make("codex"),
1097 status: "running",
1098 resumeCursor: { threadId: "active-client-session" },
1099 runtimePayload: { cwd: workspaceRoot, activeTurnId: "turn-active" },
1100 });
1101 yield* Deferred.succeed(releaseImporter, undefined);
1102​
1103 expect(yield* Fiber.join(importFiber)).toEqual({ importedCount: 1, skippedCount: 0 });
1104 expect(
1105 Option.getOrThrow(yield* snapshots.getThreadDetailById(threadId)).messages.map(
1106 (message) => message.text,
1107 ),
1108 ).toEqual(integrationThread.messages.map((message) => message.text));
1109 expect(Option.getOrThrow(yield* directory.getBinding(threadId))).toMatchObject({
1110 status: "running",
1111 resumeCursor: { threadId: "active-client-session" },
1112 runtimePayload: { cwd: workspaceRoot, activeTurnId: "turn-active" },
1113 });
1114 }),
1115 );
1116​
1117 it.effect("does not import history over a turn started on a partial thread", () =>
1118 Effect.gen(function* () {
1119 const engine = yield* OrchestrationEngine.OrchestrationEngineService;
1120 const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
1121 const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
1122 const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
1123 const projectId = ProjectId.make("project-import-turn-race");
1124 const workspaceRoot = "/tmp/project-import-turn-race";
1125 const providerSessionId = "codex-turn-race";
1126 const threadId = ThreadId.make(`import:codex:${providerSessionId}`);
1127 const scanner = AgentSessionScanner.AgentSessionScanner.of({
1128 scan: Effect.die("unused"),
1129 recentThreads: () =>
1130 Stream.succeed(
1131 makeThreadOutcome({ ...integrationThread, providerSessionId, title: "Turn race" }),
1132 ),
1133 });
1134 const importerAtBindingWrite = yield* Deferred.make<void>();
1135 const releaseImporter = yield* Deferred.make<void>();
1136 const importerRepository = ProviderSessionRuntime.ProviderSessionRuntimeRepository.of({
1137 ...repository,
1138 upsert: (runtime, options) =>
1139 options?.onConflict === "ignore"
1140 ? Deferred.succeed(importerAtBindingWrite, undefined).pipe(
1141 Effect.andThen(Deferred.await(releaseImporter)),
1142 Effect.andThen(repository.upsert(runtime, options)),
1144 : repository.upsert(runtime, options),
1145 });
1146 const importerDirectory = yield* ProviderSessionDirectory.ProviderSessionDirectory.pipe(
1147 Effect.provide(
1148 Layer.fresh(ProviderSessionDirectoryLive).pipe(
1149 Layer.provide(
1150 Layer.succeed(
1151 ProviderSessionRuntime.ProviderSessionRuntimeRepository,
1152 importerRepository,
1153 ),
1154 ),
1155 ),
1156 ),
1157 );
1158​
1159 yield* engine.dispatch({
1160 type: "project.create",
1161 commandId: CommandId.make("create-import-turn-race-project"),
1162 projectId,
1163 title: "Turn race",
1164 workspaceRoot,
1165 defaultModelSelection: null,
1166 createdAt: "2026-08-24T09:00:00.000Z",
1167 });
1168 yield* engine.dispatch({
1169 type: "thread.create",
1170 commandId: CommandId.make("create-import-turn-race-thread"),
1171 threadId,
1172 projectId,
1173 title: "Turn race",
1174 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "default" },
1175 runtimeMode: "full-access",
1176 interactionMode: "default",
1177 branch: null,
1178 worktreePath: null,
1179 createdAt: "2026-08-24T10:00:00.000Z",
1180 });
1181​
1182 const importFiber = yield* importRecentAgentThreads({ projectId }).pipe(
1183 Effect.provideService(AgentSessionScanner.AgentSessionScanner, scanner),
1184 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, importerDirectory),
1185 Effect.forkChild,
1186 );
1187 yield* Deferred.await(importerAtBindingWrite);
1188​
1189 yield* directory.upsert({
1190 threadId,
1191 provider: ProviderDriverKind.make("codex"),
1192 providerInstanceId: ProviderInstanceId.make("codex"),
1193 status: "running",
1194 resumeCursor: { threadId: "active-client-session" },
1195 runtimePayload: { cwd: workspaceRoot, activeTurnId: "turn-active" },
1196 });
1197 yield* engine.dispatch({
1198 type: "thread.turn.start",
1199 commandId: CommandId.make("start-turn-during-import"),
1200 threadId,
1201 message: {
1202 messageId: MessageId.make("message-during-import"),
1203 role: "user",
1204 text: "Continue while import waits",
1205 attachments: [],
1206 },
1207 runtimeMode: "full-access",
1208 interactionMode: "default",
1209 createdAt: "2026-08-24T10:02:00.000Z",
1210 });
1211 yield* Deferred.succeed(releaseImporter, undefined);
1212​
1213 expect(yield* Fiber.join(importFiber)).toEqual({ importedCount: 0, skippedCount: 1 });
1214 expect(Option.getOrThrow(yield* directory.getBinding(threadId))).toMatchObject({
1215 status: "running",
1216 resumeCursor: { threadId: "active-client-session" },
1217 runtimePayload: { cwd: workspaceRoot, activeTurnId: "turn-active" },
1218 });
1219 expect(
1220 Option.getOrThrow(yield* snapshots.getThreadDetailById(threadId)).messages.map(
1221 (message) => message.text,
1222 ),
1223 ).toEqual(["Continue while import waits"]);
1224 }),
1225 );
1226});