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

AgentSessionImporter.test.ts

838 lines32.3 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 record a changed transcript as imported without its new messages", () =>
457 Effect.gen(function* () {
458 const projections = yield* ProjectionStore.ProjectionStoreV2;
459 const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
460 const first = candidate(
461 CLAUDE_MODEL_SELECTION,
462 "6f1c2a7e-3b4d-4e5f-9a8b-1c2d3e4f5a6b",
463 "claudeAgent",
464 );
465 const threadId = importId(first);
466 expect(yield* (yield* makeImporter([first])).run).toEqual({
467 importedCount: 1,
468 skippedCount: 0,
469 });
470​
471 const continued = candidate(
472 CLAUDE_MODEL_SELECTION,
473 first.source.providerSessionId,
474 "claudeAgent",
475 );
476 continued.source.size = 200;
477 continued.source.mtimeMs = 3;
478 continued.thread.messages.push(
479 { role: "user", text: "Continue", createdAt: timestamp },
480 { role: "assistant", text: "Continued", createdAt: timestamp },
481 );
482 yield* (yield* makeImporter([continued])).run;
483​
484 const recorded = AgentSessionScanner.decodeImportedTranscriptPayload(
485 Option.getOrThrow(yield* runtimes.getByThreadId({ threadId })).runtimePayload,
486 ).pipe(Option.getOrThrow).importedTranscripts;
487 const texts = (yield* projections.getThreadRecords(threadId, ["messages"])).messages.map(
488 (message) => message.text,
489 );
490 expect({
491 recordsChangedTranscript: recorded?.some((source) => source.size === 200) ?? false,
492 showsNewMessages: texts.includes("Continued"),
493 }).not.toEqual({ recordsChangedTranscript: true, showsNewMessages: false });
494 }).pipe(Effect.scoped, Effect.provide(persistence)),
495);
496​
497it.effect(
498 "copies native session history into the imported thread once, retrying a failed read",
499 () =>
500 Effect.gen(function* () {
501 const projections = yield* ProjectionStore.ProjectionStoreV2;
502 const source = candidate(CODEX_MODEL_SELECTION, "native-history");
503 const threadId = yield* seedOwner(source);
504 const resolved: Array<ProviderInstanceId> = [];
505 const opened: Array<ProviderAdapter.ProviderAdapterV2OpenSessionInput> = [];
506 let closed = false;
507 let failRead = true;
508 const replayed = (role: "user" | "assistant", text: string) => ({
509 createdBy: role === "user" ? ("user" as const) : ("agent" as const),
510 creationSource: "provider" as const,
511 id: MessageId.make(`replayed:${text}`),
512 threadId,
513 runId: null,
514 nodeId: null,
515 role,
516 text,
517 attachments: [],
518 streaming: false,
519 createdAt: now,
520 updatedAt: now,
521 });
522 const adapter = {
523 openSession: (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) =>
524 Effect.acquireRelease(
525 Effect.sync(() => {
526 opened.push(input);
527 return {
528 readThreadSnapshot: ({ providerThread }) =>
529 failRead
530 ? Effect.fail(
531 new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({
532 driver: providerThread.driver,
533 providerThreadId: providerThread.id,
534 }),
535 )
536 : Effect.succeed({
537 providerThread,
538 providerTurns: [],
539 runtimeRequests: [],
540 reasoningMessageIds: [MessageId.make("replayed:Check the build log")],
541 messages: [
542 replayed("user", "Fix the build"),
543 replayed("assistant", "Check the build log"),
544 replayed("assistant", "Fixed it"),
545 replayed("assistant", " "),
546 ],
547 }),
548 } as Pick<ProviderAdapter.ProviderAdapterV2SessionRuntime, "readThreadSnapshot">;
549 }),
550 () =>
551 Effect.sync(() => {
552 closed = true;
553 }),
554 ),
555 } as unknown as ProviderAdapter.ProviderAdapterV2["Service"];
556 const importer = yield* makeImporter([], Effect.void, (instanceId) =>
557 Effect.sync(() => {
558 resolved.push(instanceId);
559 return adapter;
560 }),
561 );
562​
563 const importHistory = importer.importNativeHistory({
564 threadId,
565 workspaceRoot: "/workspace/project",
566 });
567​
568 expect((yield* Effect.flip(importHistory))._tag).toBe(
569 "ProviderAdapterReadThreadSnapshotError",
570 );
571 expect(closed).toBe(true);
572 expect(
573 (yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin,
574 ).toBeUndefined();
575​
576 failRead = false;
577 expect(yield* importHistory).toBe(3);
578 expect(resolved).toEqual([
579 CODEX_MODEL_SELECTION.instanceId,
580 CODEX_MODEL_SELECTION.instanceId,
581 ]);
582 expect(opened[1]).toMatchObject({
583 threadId,
584 initialNativeThreadId: source.source.providerSessionId,
585 runtimePolicy: { cwd: "/workspace/project" },
586 });
587 // Forks keep run-less history only for this origin.
588 expect((yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin).toBe(
589 "v1_import",
590 );
591 expect(yield* importHistory).toBe(0);
592 expect(opened).toHaveLength(2);
593 const page = yield* projections.getTimelinePage(threadId, { view: "activity", limit: 10 });
594 expect(
595 page.items.map(({ item }) => [
596 item.type,
597 item.runId,
598 "text" in item ? item.text : undefined,
599 ]),
600 ).toEqual([
601 ["user_message", null, "Fix the build"],
602 ["reasoning", null, "Check the build log"],
603 ["assistant_message", null, "Fixed it"],
604 ]);
605 }).pipe(Effect.scoped, Effect.provide(persistence)),
606);
607​
608it.effect("releases the ACP import lock when a native session never answers", () =>
609 Effect.gen(function* () {
610 const projections = yield* ProjectionStore.ProjectionStoreV2;
611 const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator;
612 const threadId = yield* seedOwner(candidate(CODEX_MODEL_SELECTION, "native-history-hang"));
613 const opened = yield* Deferred.make<void>();
614 let closed = false;
615 // An agent that only resumes sessions and never answers its first session/resume.
616 const adapter = {
617 openSession: () =>
618 Effect.suspend(() => {
619 if (!closed) {
620 return Effect.addFinalizer(() =>
621 Effect.sync(() => {
622 closed = true;
623 }),
624 ).pipe(
625 Effect.andThen(Deferred.succeed(opened, undefined)),
626 Effect.andThen(Effect.never),
627 );
628 }
629 return Effect.succeed({
630 readThreadSnapshot: ({ providerThread }) =>
631 Effect.succeed({
632 providerThread,
633 providerTurns: [],
634 runtimeRequests: [],
635 messages: [
636 {
637 createdBy: "user",
638 creationSource: "provider",
639 id: MessageId.make("replayed:hang"),
640 threadId,
641 runId: null,
642 nodeId: null,
643 role: "user",
644 text: "Fix the build",
645 attachments: [],
646 streaming: false,
647 createdAt: now,
648 updatedAt: now,
649 },
650 ],
651 }),
652 } as Pick<ProviderAdapter.ProviderAdapterV2SessionRuntime, "readThreadSnapshot">);
653 }),
654 } as unknown as ProviderAdapter.ProviderAdapterV2["Service"];
655 const importer = yield* makeImporter([], Effect.void, () => Effect.succeed(adapter));
656 const importHistory = coordinator.withSessionMutation(
657 importer.importNativeHistory({ threadId, workspaceRoot: "/workspace/project" }),
658 );
659​
660 const importing = yield* importHistory.pipe(Effect.flip, Effect.forkChild);
661 yield* Deferred.await(opened);
662 // Any other ACP import or delete waits for the same lock.
663 const next = yield* coordinator
664 .withSessionMutation(Effect.succeed("next"))
665 .pipe(Effect.forkChild);
666 yield* TestClock.adjust("2 minutes");
667​
668 expect((yield* Fiber.join(importing))._tag).toBe("TimeoutError");
669 expect(closed).toBe(true);
670 expect(yield* Fiber.join(next)).toBe("next");
671 expect(
672 (yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin,
673 ).toBeUndefined();
674 expect(yield* importHistory).toBe(1);
675 expect((yield* projections.getThreadRecords(threadId, [])).thread.historyOrigin).toBe(
676 "v1_import",
677 );
678 }).pipe(
679 Effect.scoped,
680 Effect.provide(Layer.merge(persistence, AcpRegistryRuntimeCoordinator.layer)),
681 ),
682);
683​
684/**
685 * Runs a thread command that read the thread before the history load ended and
686 * writes once the importer is about to commit, as an unserialized write would.
687 */
688const importDuringCommand = Effect.fn(function* (
689 name: string,
690 command: (thread: OrchestrationV2AppThread) => ReadonlyArray<OrchestrationV2DomainEvent>,
691) {
692 const projections = yield* ProjectionStore.ProjectionStoreV2;
693 const sink = yield* EventSink.EventSinkV2;
694 const threadId = yield* seedOwner(candidate(CODEX_MODEL_SELECTION, name));
695 const lock = yield* KeyedLock.make<ThreadId>();
696 const loaded = yield* Deferred.make<void>();
697 const importerCommitting = yield* Deferred.make<void>();
698 const commandWritten = yield* Deferred.make<void>();
699 const committing = Deferred.succeed(importerCommitting, undefined);
700 const adapter = {
701 openSession: () =>
702 Effect.succeed({
703 readThreadSnapshot: ({ providerThread }) =>
704 Deferred.await(loaded).pipe(
705 Effect.as({
706 providerThread,
707 providerTurns: [],
708 runtimeRequests: [],
709 messages: [
710 {
711 createdBy: "user" as const,
712 creationSource: "provider" as const,
713 id: MessageId.make(`replayed:${name}`),
714 threadId,
715 runId: null,
716 nodeId: null,
717 role: "user" as const,
718 text: "Fix the build",
719 attachments: [],
720 streaming: false,
721 createdAt: now,
722 updatedAt: now,
723 },
724 ],
725 }),
726 ),
727 } as Pick<ProviderAdapter.ProviderAdapterV2SessionRuntime, "readThreadSnapshot">),
728 } as unknown as ProviderAdapter.ProviderAdapterV2["Service"];
729 const importer = yield* makeImporter(
730 [],
731 committing.pipe(Effect.andThen(Deferred.await(commandWritten))),
732 () => Effect.succeed(adapter),
733 {
734 ...lock,
735 withLock: (key, effect) => committing.pipe(Effect.andThen(lock.withLock(key, effect))),
736 },
737 );
738 const commanding = yield* Effect.forkScoped(
739 lock.withLock(
740 threadId,
741 Effect.gen(function* () {
742 const { thread } = yield* projections.getThreadRecords(threadId, []);
743 yield* Deferred.succeed(loaded, undefined);
744 yield* Deferred.await(importerCommitting);
745 yield* sink.write({ events: command(thread) });
746 yield* Deferred.succeed(commandWritten, undefined);
747 }),
748 ),
749 );
750 const imported = yield* importer.importNativeHistory({
751 threadId,
752 workspaceRoot: "/workspace/project",
753 });
754 yield* Fiber.join(commanding);
755 const records = yield* projections.getThreadRecords(threadId, ["runs"]);
756 const page = yield* projections.getTimelinePage(threadId, { view: "messages", limit: 10 });
757 return { imported, thread: records.thread, runs: records.runs, items: page.items };
758});
759​
760it.effect("keeps a thread edit made while the native history loads", () =>
761 Effect.gen(function* () {
762 const result = yield* importDuringCommand("renamed-during-load", (thread) => [
763 {
764 id: EventId.make(`${thread.id}:renamed`),
765 type: "thread.metadata-updated",
766 threadId: thread.id,
767 occurredAt: now,
768 payload: { ...thread, title: "Renamed" },
769 },
770 ]);
771 expect(result.imported).toBe(1);
772 expect(result.thread.title).toBe("Renamed");
773 expect(result.thread.historyOrigin).toBe("v1_import");
774 expect(result.items).toHaveLength(1);
775 }).pipe(Effect.scoped, Effect.provide(persistence)),
776);
777​
778it.effect("skips the native history when a run starts while it loads", () =>
779 Effect.gen(function* () {
780 const result = yield* importDuringCommand("run-during-load", (thread) => [
781 {
782 id: EventId.make(`${thread.id}:run`),
783 type: "run.updated",
784 threadId: thread.id,
785 occurredAt: now,
786 payload: {
787 id: RunId.make(`${thread.id}:run`),
788 threadId: thread.id,
789 ordinal: 1,
790 providerInstanceId: thread.providerInstanceId,
791 modelSelection: thread.modelSelection,
792 providerThreadId: null,
793 userMessageId: MessageId.make(`${thread.id}:prompt`),
794 rootNodeId: null,
795 activeAttemptId: null,
796 status: "queued",
797 requestedAt: now,
798 startedAt: null,
799 completedAt: null,
800 checkpointId: null,
801 contextHandoffId: null,
802 },
803 },
804 ]);
805 expect(result.imported).toBe(0);
806 expect(result.runs).toHaveLength(1);
807 expect(result.thread.historyOrigin).toBeUndefined();
808 expect(result.items).toEqual([]);
809 }).pipe(Effect.scoped, Effect.provide(persistence)),
810);
811​
812it.effect("imports under a policy ceiling in the project's default, kept under the ceiling", () =>
813 Effect.gen(function* () {
814 const projections = yield* ProjectionStore.ProjectionStoreV2;
815 const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
816 const source = candidate(CODEX_MODEL_SELECTION, "ceiling");
817 const threadId = importId(source);
818 const importer = yield* makeImporter(
819 [source],
820 Effect.void,
821 undefined,
822 undefined,
823 ServerSettings.layerTest(
824 { defaultRuntimeMode: "full-access" },
825 {
826 organization: "Example Corp",
827 lockedSettings: [],
828 limits: { maxRuntimeMode: "auto-accept-edits" },
829 },
830 ),
831 );
832 expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 });
833 expect((yield* projections.getThread(threadId)).runtimeMode).toBe("auto-accept-edits");
834 expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId })).runtimeMode).toBe(
835 "auto-accept-edits",
836 );
837 }).pipe(Effect.scoped, Effect.provide(persistence)),
838);