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

AgentSessionImporter.test.ts

871 lines33.9 KB

1import { expect, it } from "@effect/vitest";
2import {
3 type AgentSessionSource,
4 type ServerSettingsError,
5 EventId,
6 ProjectId,
7 ProviderDriverKind,
8 ProviderInstanceId,
9 MessageId,
10 RunId,
11 ThreadId,
12 type ApplicationStoredEvent,
13 type OrchestrationV2AppThread,
14 type OrchestrationV2DomainEvent,
15 type OrchestrationV2ProviderThread,
16} from "@t3tools/contracts";
17import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
18import * as KeyedLock from "@t3tools/shared/KeyedLock";
19import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator";
20import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
21import * as Context from "effect/Context";
22import * as DateTime from "effect/DateTime";
23import * as Deferred from "effect/Deferred";
24import * as Effect from "effect/Effect";
25import * as Fiber from "effect/Fiber";
26import * as Layer from "effect/Layer";
27import * as Option from "effect/Option";
28import * as Stream from "effect/Stream";
29import * as SqlClient from "effect/sql/SqlClient";
30import * as TestClock from "effect/testing/TestClock";
31​
32import * as EventSink from "../orchestration-v2/EventSink.ts";
33import * as EventStore from "../orchestration-v2/EventStore.ts";
34import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
35import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
36import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
37import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts";
38import {
39 CLAUDE_MODEL_SELECTION,
40 CODEX_MODEL_SELECTION,
41} from "../orchestration-v2/testkit/fixtures/shared.ts";
42import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
43import * as SqlitePersistence from "../persistence/Sqlite.ts";
44import * as ServerSettings from "../serverSettings.ts";
45import * as AgentSessionImporter from "./AgentSessionImporter.ts";
46import * as AgentSessionScanner from "./AgentSessionScanner.ts";
47import * as ProjectService from "./ProjectService.ts";
48​
49const projectId = ProjectId.make("agent-session-import-project");
50const timestamp = "2026-09-01T10:00:00.000Z";
51const now = DateTime.makeUnsafe(timestamp);
52const stores = Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe(
53 Layer.provideMerge(SqlitePersistence.layerMemory),
54);
55const persistence = Layer.mergeAll(
56 stores,
57 EventSink.layer.pipe(Layer.provide(stores)),
58 ProviderSessionRuntime.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
59 IdAllocator.layer,
60);
61​
62function candidate(
63 modelSelection: typeof CODEX_MODEL_SELECTION,
64 providerSessionId: string,
65 provider: AgentSessionSource = "codex",
66) {
67 const providerInstanceId = modelSelection.instanceId;
68 return {
69 _tag: "Importable" as const,
70 source: {
71 provider,
72 providerInstanceId,
73 providerSessionId,
74 filePath: `/tmp/${providerInstanceId}/${providerSessionId}.jsonl`,
75 size: 100,
76 mtimeMs: 2,
77 device: 3,
78 inode: 4,
79 birthtimeMs: 1,
80 },
81 thread: {
82 source: provider,
83 providerInstanceId,
84 providerSessionId,
85 title: "Imported thread",
86 model: modelSelection.model,
87 createdAt: timestamp,
88 updatedAt: timestamp,
89 omittedMessageCount: 0,
90 messages: [
91 { role: "user" as const, text: "Fix it", createdAt: timestamp },
92 { role: "assistant" as const, text: "Fixed", createdAt: timestamp },
93 ],
94 },
95 worktree: null as { path: string; branch: string | null } | null,
96 } satisfies AgentSessionScanner.AgentSessionRecentThread;
98​
99const PI_MODEL_SELECTION = { instanceId: ProviderInstanceId.make("pi"), model: "default" };
100​
101// Pi threads are owned by their session file path, not the session UUID.
102const nativeId = ({ source }: ReturnType<typeof candidate>) =>
103 source.provider === "pi" ? source.filePath : source.providerSessionId;
104​
105function importId(source: ReturnType<typeof candidate>) {
106 return ThreadId.make(
107 `import:${source.source.providerInstanceId}:${source.source.providerSessionId}`,
108 );
110​
111const seedOwner = Effect.fn(function* (
112 source: ReturnType<typeof candidate>,
113 lifecycle: "active" | "archived" | "deleted" = "active",
114) {
115 const sink = yield* EventSink.EventSinkV2;
116 const ids = yield* IdAllocator.IdAllocatorV2;
117 const { providerInstanceId, providerSessionId, provider } = source.source;
118 const nativeThreadId = nativeId(source);
119 const threadId = ThreadId.make(`owner:${providerInstanceId}:${providerSessionId}`);
120 const driver = ProviderDriverKind.make(provider);
121 const providerThread: OrchestrationV2ProviderThread = {
122 id: ids.derive.providerThread({ driver, nativeThreadId }),
123 driver,
124 providerInstanceId,
125 providerSessionId: null,
126 appThreadId: threadId,
127 ownerNodeId: null,
128 nativeThreadRef: { driver, nativeId: nativeThreadId, strength: "strong" },
129 nativeConversationHeadRef: null,
130 status: "idle",
131 firstRunOrdinal: 1,
132 lastRunOrdinal: 1,
133 handoffIds: [],
134 forkedFrom: null,
135 createdAt: now,
136 updatedAt: now,
137 };
138 const thread: OrchestrationV2AppThread = {
139 createdBy: "user",
140 creationSource: "web",
141 id: threadId,
142 projectId,
143 title: "Native thread",
144 providerInstanceId,
145 modelSelection: { instanceId: providerInstanceId, model: source.thread.model },
146 runtimeMode: "full-access",
147 interactionMode: "default",
148 branch: null,
149 worktreePath: null,
150 activeProviderThreadId: providerThread.id,
151 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
152 forkedFrom: null,
153 createdAt: now,
154 updatedAt: now,
155 archivedAt: lifecycle === "archived" ? now : null,
156 deletedAt: lifecycle === "deleted" ? now : null,
157 settledOverride: null,
158 settledAt: null,
159 lastVisitedAt: null,
160 };
161 yield* sink.write({
162 events: [
163 {
164 id: EventId.make(`${threadId}:created`),
165 type: "thread.created",
166 threadId,
167 occurredAt: now,
168 payload: thread,
169 },
170 {
171 id: EventId.make(`${threadId}:provider`),
172 type: "provider-thread.updated",
173 threadId,
174 occurredAt: now,
175 payload: providerThread,
176 },
177 ],
178 });
179 return threadId;
180});
181​
182const makeImporter = Effect.fn(function* (
183 candidates: ReadonlyArray<ReturnType<typeof candidate>>,
184 beforeTransaction: Effect.Effect<void> = Effect.void,
185 getAdapter?: ProviderAdapterRegistry.ProviderAdapterRegistryV2Shape["get"],
186 threadCommands?: KeyedLock.KeyedLock<ThreadId>,
187 settings: Layer.Layer<
188 ServerSettings.ServerSettingsService,
189 ServerSettingsError
190 > = ServerSettings.layerTest(),
191) {
192 const sql = yield* SqlClient.SqlClient;
193 const events = yield* EventStore.EventStoreV2;
194 const projections = yield* ProjectionStore.ProjectionStoreV2;
195 const published: Array<ApplicationStoredEvent> = [];
196 const withTransaction: typeof sql.withTransaction = (effect) =>
197 beforeTransaction.pipe(Effect.andThen(sql.withTransaction(effect)));
198 const importSql = new Proxy(sql, {
199 get: (target, key, receiver) =>
200 key === "withTransaction" ? withTransaction : Reflect.get(target, key, receiver),
201 });
202 const sinkLayer = Layer.fresh(EventSink.layer).pipe(
203 Layer.provide(
204 Layer.mergeAll(
205 Layer.succeed(SqlClient.SqlClient, importSql),
206 Layer.succeed(ProjectionStore.ProjectionStoreV2, projections),
207 Layer.succeed(EventStore.EventStoreV2, {
208 ...events,
209 publishCommitted: (batch) =>
210 events.publishCommitted(batch).pipe(
211 Effect.tap(() =>
212 Effect.sync(() => {
213 published.push(...batch);
214 }),
215 ),
216 ),
217 }),
218 ),
219 ),
220 );
221 const context = yield* Layer.build(
222 AgentSessionImporter.layer.pipe(
223 Layer.provide(
224 Layer.mergeAll(
225 sinkLayer,
226 settings,
227 Layer.succeed(IdAllocator.IdAllocatorV2, yield* IdAllocator.IdAllocatorV2),
228 Layer.succeed(
229 ProviderSessionRuntime.ProviderSessionRuntimeRepository,
230 yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository,
231 ),
232 Layer.mock(AgentSessionScanner.AgentSessionScanner)({
233 recentThreads: () => Stream.fromIterable(candidates),
234 }),
235 Layer.mock(ProjectService.ProjectService)({
236 getById: () =>
237 Effect.succeedSome({
238 id: projectId,
239 title: "Project",
240 workspaceRoot: "/workspace/project",
241 defaultModelSelection: null,
242 scripts: [],
243 createdAt: timestamp,
244 updatedAt: timestamp,
245 deletedAt: null,
246 }),
247 }),
248 Layer.mock(Orchestrator.OrchestratorV2)({
249 getThreadRecords: (threadId, fields) =>
250 projections
251 .getThreadRecords(threadId, fields)
252 .pipe(
253 Effect.mapError(
254 (cause) => new Orchestrator.OrchestratorProjectionError({ threadId, cause }),
255 ),
256 ),
257 }),
258 Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)(
259 getAdapter === undefined ? {} : { get: getAdapter },
260 ),
261 Layer.succeed(
262 ThreadCommandExecutor.ThreadCommandExecutor,
263 threadCommands ?? (yield* KeyedLock.make<ThreadId>()),
264 ),
265 ),
266 ),
267 ),
268 );
269 const importer = Context.get(context, AgentSessionImporter.AgentSessionImporter);
270 return {
271 run: importer.importRecentAgentThreads({ projectId }),
272 importNativeHistory: importer.importNativeHistory,
273 published,
274 };
275});
276​
277it.effect(
278 "ignores owned sessions, including archived and deleted threads, but imports other instances and unowned sessions",
279 () =>
280 Effect.gen(function* () {
281 const projections = yield* ProjectionStore.ProjectionStoreV2;
282 const events = yield* EventStore.EventStoreV2;
283 const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
284 const active = candidate(CODEX_MODEL_SELECTION, "active");
285 const archived = candidate(
286 CLAUDE_MODEL_SELECTION,
287 "020e7f00-dce6-406b-8ec6-ed90498945d6",
288 "claudeAgent",
289 );
290 const deleted = candidate(CODEX_MODEL_SELECTION, "deleted");
291 const ownedPi = candidate(PI_MODEL_SELECTION, "owned-pi", "pi");
292 const owners = [
293 yield* seedOwner(active),
294 yield* seedOwner(archived, "archived"),
295 yield* seedOwner(deleted, "deleted"),
296 yield* seedOwner(ownedPi),
297 ];
298 const before = yield* Effect.forEach(owners, (id) =>
299 projections.getThreadRecords(id, ["providerThreads"]),
300 );
301 const otherInstance = candidate(
302 { ...CLAUDE_MODEL_SELECTION, instanceId: ProviderInstanceId.make("claude-other") },
303 archived.source.providerSessionId,
304 "claudeAgent",
305 );
306 const unowned = candidate(CODEX_MODEL_SELECTION, "unowned");
307 unowned.thread.omittedMessageCount = 1;
308 unowned.worktree = { path: "/workspace/project/.claude/worktrees/feat", branch: "feat" };
309 const unownedPi = candidate(PI_MODEL_SELECTION, "unowned-pi", "pi");
310 const importer = yield* makeImporter([
311 active,
312 archived,
313 deleted,
314 ownedPi,
315 otherInstance,
316 unowned,
317 unownedPi,
318 ]);
319​
320 expect(yield* importer.run).toEqual({ importedCount: 3, skippedCount: 0 });
321 for (const source of [active, archived, deleted, ownedPi]) {
322 const threadId = importId(source);
323 expect(yield* Effect.option(projections.getThread(threadId))).toEqual(Option.none());
324 expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual([]);
325 expect(yield* runtimes.getByThreadId({ threadId })).toEqual(Option.none());
326 }
327 expect(
328 yield* Effect.forEach(owners, (id) =>
329 projections.getThreadRecords(id, ["providerThreads"]),
330 ),
331 ).toEqual(before);
332 expect(
333 new Set(
334 importer.published.flatMap((stored) =>
335 "event" in stored ? [stored.event.threadId] : [],
336 ),
337 ),
338 ).toEqual(new Set([importId(otherInstance), importId(unowned), importId(unownedPi)]));
339 for (const source of [otherInstance, unowned, unownedPi]) {
340 const threadId = importId(source);
341 const records = yield* projections.getThreadRecords(threadId, [
342 "messages",
343 "turnItems",
344 "providerThreads",
345 ]);
346 expect(records.messages.map((message) => message.text)).toEqual(["Fix it", "Fixed"]);
347 const notices = records.turnItems.filter((item) => item.type === "system_notice");
348 if (source === unowned) {
349 expect(records.turnItems[0]).toBe(notices[0]);
350 expect(notices).toMatchObject([
351 {
352 ordinal: 1,
353 runId: null,
354 message: expect.stringContaining("1 earlier message was not imported"),
355 },
356 ]);
357 } else {
358 expect(notices).toEqual([]);
359 }
360 expect(records.thread.historyOrigin).toBe("v1_import");
361 expect(records.thread.worktreePath).toBe(source.worktree?.path ?? null);
362 expect(records.thread.branch).toBe(source.worktree?.branch ?? null);
363 expect(records.thread.activeProviderThreadId).toBe(records.providerThreads[0]?.id);
364 expect(records.providerThreads[0]?.nativeThreadRef?.nativeId).toBe(nativeId(source));
365 expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({
366 providerInstanceId: source.source.providerInstanceId,
367 resumeCursor:
368 source.source.provider === "claudeAgent"
369 ? { threadId, resume: source.source.providerSessionId }
370 : { threadId: nativeId(source) },
371 runtimePayload: {
372 cwd: source.worktree?.path ?? "/workspace/project",
373 importedTranscripts: [source.source],
374 },
375 });
376 }
377 }).pipe(Effect.scoped, Effect.provide(persistence)),
378);
379​
380it.effect("rechecks ownership after the import reaches the commit transaction", () =>
381 Effect.gen(function* () {
382 const enteringTransaction = yield* Deferred.make<void>();
383 const continueTransaction = yield* Deferred.make<void>();
384 const source = candidate(CODEX_MODEL_SELECTION, "claimed-during-import");
385 const importer = yield* makeImporter(
386 [source],
387 Deferred.succeed(enteringTransaction, undefined).pipe(
388 Effect.andThen(Deferred.await(continueTransaction)),
389 ),
390 );
391 const pending = yield* Effect.forkScoped(importer.run);
392 yield* Deferred.await(enteringTransaction);
393 // Commit ownership after all pre-transaction reads, before the import acquires SQLite.
394 const ownerId = yield* seedOwner(source);
395 yield* Deferred.succeed(continueTransaction, undefined);
396 expect(yield* Fiber.join(pending)).toEqual({ importedCount: 0, skippedCount: 0 });
397 expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 0 });
398 const projections = yield* ProjectionStore.ProjectionStoreV2;
399 const events = yield* EventStore.EventStoreV2;
400 const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
401 expect(yield* Effect.option(projections.getThread(importId(source)))).toEqual(Option.none());
402 expect(yield* events.read({ threadId: importId(source) }).pipe(Stream.runCollect)).toEqual([]);
403 expect(yield* runtimes.list()).toEqual([]);
404 expect(importer.published).toEqual([]);
405 expect(
406 (yield* projections.getThreadRecords(ownerId, ["providerThreads"])).providerThreads[0]
407 ?.appThreadId,
408 ).toBe(ownerId);
409 }).pipe(Effect.scoped, Effect.provide(persistence)),
410);
411​
412it.effect(
413 "retries failed commits and runtime persistence without replaying committed history",
414 () =>
415 Effect.gen(function* () {
416 const sql = yield* SqlClient.SqlClient;
417 const events = yield* EventStore.EventStoreV2;
418 const projections = yield* ProjectionStore.ProjectionStoreV2;
419 const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
420 const source = candidate(CODEX_MODEL_SELECTION, "retry");
421 const threadId = importId(source);
422 const importer = yield* makeImporter([source]);
423 yield* sql`CREATE TEMP TRIGGER fail_import BEFORE INSERT ON orchestration_events WHEN NEW.event_type = 'message.updated' BEGIN SELECT RAISE(ABORT, 'test publication failure'); END`;
424 expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 1 });
425 expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual([]);
426 expect(yield* Effect.option(projections.getThread(threadId))).toEqual(Option.none());
427 expect(yield* runtimes.list()).toEqual([]);
428 expect(importer.published).toEqual([]);
429 yield* sql`DROP TRIGGER fail_import`;
430​
431 yield* sql`CREATE TEMP TRIGGER fail_runtime BEFORE INSERT ON provider_session_runtime BEGIN SELECT RAISE(ABORT, 'test runtime failure'); END`;
432 expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 1 });
433 const committed = yield* events.read({ threadId }).pipe(Stream.runCollect);
434 expect(committed).toHaveLength(6);
435 expect(importer.published).toHaveLength(6);
436 expect(yield* runtimes.list()).toEqual([]);
437 yield* sql`DROP TRIGGER fail_runtime`;
438​
439 expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 });
440 expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 });
441 expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual(committed);
442 expect(importer.published).toHaveLength(6);
443 expect(
444 (yield* projections.getThreadRecords(threadId, ["messages"])).messages.map(
445 (message) => message.text,
446 ),
447 ).toEqual(["Fix it", "Fixed"]);
448 expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({
449 providerInstanceId: source.source.providerInstanceId,
450 resumeCursor: { threadId: source.source.providerSessionId },
451 runtimePayload: { importedTranscripts: [source.source] },
452 });
453 }).pipe(Effect.scoped, Effect.provide(persistence)),
454);
455​
456it.effect("does not certify new native history after a partial import retry", () =>
457 Effect.gen(function* () {
458 const sql = yield* SqlClient.SqlClient;
459 const projections = yield* ProjectionStore.ProjectionStoreV2;
460 const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
461 const original = candidate(CODEX_MODEL_SELECTION, "partial-retry");
462 const threadId = importId(original);
463 const importer = yield* makeImporter([original]);
464 yield* sql`CREATE TEMP TRIGGER fail_runtime BEFORE INSERT ON provider_session_runtime BEGIN SELECT RAISE(ABORT, 'test runtime failure'); END`;
465 expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 1 });
466 yield* sql`DROP TRIGGER fail_runtime`;
467 expect(yield* runtimes.list()).toEqual([]);
468 const continued = candidate(CODEX_MODEL_SELECTION, original.source.providerSessionId);
469 continued.source.size = 200;
470 continued.source.mtimeMs = 3;
471 continued.thread.messages.push(
472 { role: "user", text: "Continue outside T3", createdAt: timestamp },
473 { role: "assistant", text: "Native continuation", createdAt: timestamp },
474 );
475 // The thread holds only the original messages, so the continued transcript stays unrecorded.
476 expect(yield* (yield* makeImporter([continued])).run).toEqual({
477 importedCount: 0,
478 skippedCount: 1,
479 });
480 expect(yield* runtimes.list()).toEqual([]);
481 expect(
482 (yield* projections.getThreadRecords(threadId, ["messages"])).messages.map(
483 (message) => message.text,
484 ),
485 ).toEqual(["Fix it", "Fixed"]);
486 }).pipe(Effect.scoped, Effect.provide(persistence)),
487);
488​
489it.effect("does not record a changed transcript as imported without its new messages", () =>
490 Effect.gen(function* () {
491 const projections = yield* ProjectionStore.ProjectionStoreV2;
492 const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
493 const first = candidate(
494 CLAUDE_MODEL_SELECTION,
495 "6f1c2a7e-3b4d-4e5f-9a8b-1c2d3e4f5a6b",
496 "claudeAgent",
497 );
498 const threadId = importId(first);
499 expect(yield* (yield* makeImporter([first])).run).toEqual({
500 importedCount: 1,
501 skippedCount: 0,
502 });
503​
504 const continued = candidate(
505 CLAUDE_MODEL_SELECTION,
506 first.source.providerSessionId,
507 "claudeAgent",
508 );
509 continued.source.size = 200;
510 continued.source.mtimeMs = 3;
511 continued.thread.messages.push(
512 { role: "user", text: "Continue", createdAt: timestamp },
513 { role: "assistant", text: "Continued", createdAt: timestamp },
514 );
515 yield* (yield* makeImporter([continued])).run;
516​
517 const recorded = AgentSessionScanner.decodeImportedTranscriptPayload(
518 Option.getOrThrow(yield* runtimes.getByThreadId({ threadId })).runtimePayload,
519 ).pipe(Option.getOrThrow).importedTranscripts;
520 const texts = (yield* projections.getThreadRecords(threadId, ["messages"])).messages.map(
521 (message) => message.text,
522 );
523 expect({
524 recordsChangedTranscript: recorded?.some((source) => source.size === 200) ?? false,
525 showsNewMessages: texts.includes("Continued"),
526 }).not.toEqual({ recordsChangedTranscript: true, showsNewMessages: false });
527 }).pipe(Effect.scoped, Effect.provide(persistence)),
528);
529​
530it.effect(
531 "copies native session history into the imported thread once, retrying a failed read",
532 () =>
533 Effect.gen(function* () {
534 const projections = yield* ProjectionStore.ProjectionStoreV2;
535 const source = candidate(CODEX_MODEL_SELECTION, "native-history");
536 const threadId = yield* seedOwner(source);
537 const resolved: Array<ProviderInstanceId> = [];
538 const opened: Array<ProviderAdapter.ProviderAdapterV2OpenSessionInput> = [];
539 let closed = false;
540 let failRead = true;
541 const replayed = (role: "user" | "assistant", text: string) => ({
542 createdBy: role === "user" ? ("user" as const) : ("agent" as const),
543 creationSource: "provider" as const,
544 id: MessageId.make(`replayed:${text}`),
545 threadId,
546 runId: null,
547 nodeId: null,
548 role,
549 text,
550 attachments: [],
551 streaming: false,
552 createdAt: now,
553 updatedAt: now,
554 });
555 const adapter = {
556 openSession: (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) =>
557 Effect.acquireRelease(
558 Effect.sync(() => {
559 opened.push(input);
560 return {
561 readThreadSnapshot: ({ providerThread }) =>
562 failRead
563 ? Effect.fail(
564 new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({
565 driver: providerThread.driver,
566 providerThreadId: providerThread.id,
567 }),
568 )
569 : Effect.succeed({
570 providerThread,
571 providerTurns: [],
572 runtimeRequests: [],
573 reasoningMessageIds: [MessageId.make("replayed:Check the build log")],
574 messages: [
575 replayed("user", "Fix the build"),
576 replayed("assistant", "Check the build log"),
577 replayed("assistant", "Fixed it"),
578 replayed("assistant", " "),
579 ],
580 }),
581 } as Pick<ProviderAdapter.ProviderAdapterV2SessionRuntime, "readThreadSnapshot">;
582 }),
583 () =>
584 Effect.sync(() => {
585 closed = true;
586 }),
587 ),
588 } as unknown as ProviderAdapter.ProviderAdapterV2["Service"];
589 const importer = yield* makeImporter([], Effect.void, (instanceId) =>
590 Effect.sync(() => {
591 resolved.push(instanceId);
592 return adapter;
593 }),
594 );
595​
596 const importHistory = importer.importNativeHistory({
597 threadId,
598 workspaceRoot: "/workspace/project",
599 });
600​
601 expect((yield* Effect.flip(importHistory))._tag).toBe(
602 "ProviderAdapterReadThreadSnapshotError",
603 );
604 expect(closed).toBe(true);
605 expect(
606 (yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin,
607 ).toBeUndefined();
608​
609 failRead = false;
610 expect(yield* importHistory).toBe(3);
611 expect(resolved).toEqual([
612 CODEX_MODEL_SELECTION.instanceId,
613 CODEX_MODEL_SELECTION.instanceId,
614 ]);
615 expect(opened[1]).toMatchObject({
616 threadId,
617 initialNativeThreadId: source.source.providerSessionId,
618 runtimePolicy: { cwd: "/workspace/project" },
619 });
620 // Forks keep run-less history only for this origin.
621 expect((yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin).toBe(
622 "v1_import",
623 );
624 expect(yield* importHistory).toBe(0);
625 expect(opened).toHaveLength(2);
626 const page = yield* projections.getTimelinePage(threadId, { view: "activity", limit: 10 });
627 expect(
628 page.items.map(({ item }) => [
629 item.type,
630 item.runId,
631 "text" in item ? item.text : undefined,
632 ]),
633 ).toEqual([
634 ["user_message", null, "Fix the build"],
635 ["reasoning", null, "Check the build log"],
636 ["assistant_message", null, "Fixed it"],
637 ]);
638 }).pipe(Effect.scoped, Effect.provide(persistence)),
639);
640​
641it.effect("releases the ACP import lock when a native session never answers", () =>
642 Effect.gen(function* () {
643 const projections = yield* ProjectionStore.ProjectionStoreV2;
644 const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator;
645 const threadId = yield* seedOwner(candidate(CODEX_MODEL_SELECTION, "native-history-hang"));
646 const opened = yield* Deferred.make<void>();
647 let closed = false;
648 // An agent that only resumes sessions and never answers its first session/resume.
649 const adapter = {
650 openSession: () =>
651 Effect.suspend(() => {
652 if (!closed) {
653 return Effect.addFinalizer(() =>
654 Effect.sync(() => {
655 closed = true;
656 }),
657 ).pipe(
658 Effect.andThen(Deferred.succeed(opened, undefined)),
659 Effect.andThen(Effect.never),
660 );
661 }
662 return Effect.succeed({
663 readThreadSnapshot: ({ providerThread }) =>
664 Effect.succeed({
665 providerThread,
666 providerTurns: [],
667 runtimeRequests: [],
668 messages: [
669 {
670 createdBy: "user",
671 creationSource: "provider",
672 id: MessageId.make("replayed:hang"),
673 threadId,
674 runId: null,
675 nodeId: null,
676 role: "user",
677 text: "Fix the build",
678 attachments: [],
679 streaming: false,
680 createdAt: now,
681 updatedAt: now,
682 },
683 ],
684 }),
685 } as Pick<ProviderAdapter.ProviderAdapterV2SessionRuntime, "readThreadSnapshot">);
686 }),
687 } as unknown as ProviderAdapter.ProviderAdapterV2["Service"];
688 const importer = yield* makeImporter([], Effect.void, () => Effect.succeed(adapter));
689 const importHistory = coordinator.withSessionMutation(
690 importer.importNativeHistory({ threadId, workspaceRoot: "/workspace/project" }),
691 );
692​
693 const importing = yield* importHistory.pipe(Effect.flip, Effect.forkChild);
694 yield* Deferred.await(opened);
695 // Any other ACP import or delete waits for the same lock.
696 const next = yield* coordinator
697 .withSessionMutation(Effect.succeed("next"))
698 .pipe(Effect.forkChild);
699 yield* TestClock.adjust("2 minutes");
700​
701 expect((yield* Fiber.join(importing))._tag).toBe("TimeoutError");
702 expect(closed).toBe(true);
703 expect(yield* Fiber.join(next)).toBe("next");
704 expect(
705 (yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin,
706 ).toBeUndefined();
707 expect(yield* importHistory).toBe(1);
708 expect((yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin).toBe(
709 "v1_import",
710 );
711 }).pipe(
712 Effect.scoped,
713 Effect.provide(Layer.merge(persistence, AcpRegistryRuntimeCoordinator.layer)),
714 ),
715);
716​
717/**
718 * Runs a thread command that read the thread before the history load ended and
719 * writes once the importer is about to commit, as an unserialized write would.
720 */
721const importDuringCommand = Effect.fn(function* (
722 name: string,
723 command: (thread: OrchestrationV2AppThread) => ReadonlyArray<OrchestrationV2DomainEvent>,
724) {
725 const projections = yield* ProjectionStore.ProjectionStoreV2;
726 const sink = yield* EventSink.EventSinkV2;
727 const threadId = yield* seedOwner(candidate(CODEX_MODEL_SELECTION, name));
728 const lock = yield* KeyedLock.make<ThreadId>();
729 const loaded = yield* Deferred.make<void>();
730 const importerCommitting = yield* Deferred.make<void>();
731 const commandWritten = yield* Deferred.make<void>();
732 const committing = Deferred.succeed(importerCommitting, undefined);
733 const adapter = {
734 openSession: () =>
735 Effect.succeed({
736 readThreadSnapshot: ({ providerThread }) =>
737 Deferred.await(loaded).pipe(
738 Effect.as({
739 providerThread,
740 providerTurns: [],
741 runtimeRequests: [],
742 messages: [
743 {
744 createdBy: "user" as const,
745 creationSource: "provider" as const,
746 id: MessageId.make(`replayed:${name}`),
747 threadId,
748 runId: null,
749 nodeId: null,
750 role: "user" as const,
751 text: "Fix the build",
752 attachments: [],
753 streaming: false,
754 createdAt: now,
755 updatedAt: now,
756 },
757 ],
758 }),
759 ),
760 } as Pick<ProviderAdapter.ProviderAdapterV2SessionRuntime, "readThreadSnapshot">),
761 } as unknown as ProviderAdapter.ProviderAdapterV2["Service"];
762 const importer = yield* makeImporter(
763 [],
764 committing.pipe(Effect.andThen(Deferred.await(commandWritten))),
765 () => Effect.succeed(adapter),
766 {
767 ...lock,
768 withLock: (key, effect) => committing.pipe(Effect.andThen(lock.withLock(key, effect))),
769 },
770 );
771 const commanding = yield* Effect.forkScoped(
772 lock.withLock(
773 threadId,
774 Effect.gen(function* () {
775 const { thread } = yield* projections.getThreadRecords(threadId, []);
776 yield* Deferred.succeed(loaded, undefined);
777 yield* Deferred.await(importerCommitting);
778 yield* sink.write({ events: command(thread) });
779 yield* Deferred.succeed(commandWritten, undefined);
780 }),
781 ),
782 );
783 const imported = yield* importer.importNativeHistory({
784 threadId,
785 workspaceRoot: "/workspace/project",
786 });
787 yield* Fiber.join(commanding);
788 const records = yield* projections.getThreadRecords(threadId, ["runs"]);
789 const page = yield* projections.getTimelinePage(threadId, { view: "messages", limit: 10 });
790 return { imported, thread: records.thread, runs: records.runs, items: page.items };
791});
792​
793it.effect("keeps a thread edit made while the native history loads", () =>
794 Effect.gen(function* () {
795 const result = yield* importDuringCommand("renamed-during-load", (thread) => [
796 {
797 id: EventId.make(`${thread.id}:renamed`),
798 type: "thread.metadata-updated",
799 threadId: thread.id,
800 occurredAt: now,
801 payload: { ...thread, title: "Renamed" },
802 },
803 ]);
804 expect(result.imported).toBe(1);
805 expect(result.thread.title).toBe("Renamed");
806 expect(result.thread.historyOrigin).toBe("v1_import");
807 expect(result.items).toHaveLength(1);
808 }).pipe(Effect.scoped, Effect.provide(persistence)),
809);
810​
811it.effect("skips the native history when a run starts while it loads", () =>
812 Effect.gen(function* () {
813 const result = yield* importDuringCommand("run-during-load", (thread) => [
814 {
815 id: EventId.make(`${thread.id}:run`),
816 type: "run.updated",
817 threadId: thread.id,
818 occurredAt: now,
819 payload: {
820 id: RunId.make(`${thread.id}:run`),
821 threadId: thread.id,
822 ordinal: 1,
823 providerInstanceId: thread.providerInstanceId,
824 modelSelection: thread.modelSelection,
825 providerThreadId: null,
826 userMessageId: MessageId.make(`${thread.id}:prompt`),
827 rootNodeId: null,
828 activeAttemptId: null,
829 status: "queued",
830 requestedAt: now,
831 startedAt: null,
832 completedAt: null,
833 checkpointId: null,
834 contextHandoffId: null,
835 },
836 },
837 ]);
838 expect(result.imported).toBe(0);
839 expect(result.runs).toHaveLength(1);
840 expect(result.thread.historyOrigin).toBeUndefined();
841 expect(result.items).toEqual([]);
842 }).pipe(Effect.scoped, Effect.provide(persistence)),
843);
844​
845it.effect("imports under a policy ceiling in the project's default, kept under the ceiling", () =>
846 Effect.gen(function* () {
847 const projections = yield* ProjectionStore.ProjectionStoreV2;
848 const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
849 const source = candidate(CODEX_MODEL_SELECTION, "ceiling");
850 const threadId = importId(source);
851 const importer = yield* makeImporter(
852 [source],
853 Effect.void,
854 undefined,
855 undefined,
856 ServerSettings.layerTest(
857 { defaultRuntimeMode: "full-access" },
858 {
859 organization: "Example Corp",
860 lockedSettings: [],
861 limits: { maxRuntimeMode: "auto-accept-edits" },
862 },
863 ),
864 );
865 expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 });
866 expect((yield* projections.getThread(threadId)).runtimeMode).toBe("auto-accept-edits");
867 expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId })).runtimeMode).toBe(
868 "auto-accept-edits",
869 );
870 }).pipe(Effect.scoped, Effect.provide(persistence)),
871);