@devries-cameron20 / t3code-1 / commits / 2b4a806fe4
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): skip native sessions during bulk import (#15634)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

maria committed Oct 19, 2026 at 18:38 UTC 2b4a806fe402fe917e3f1c45f51fd67b730e3f7c
3 files changed +408 -137
apps/server/src/orchestration-v2/EventSink.ts
+23
@@ -67,11 +67,20 @@ export type EventSinkV2Error = typeof EventSinkV2Error.Type;
67
68 export interface EventSinkV2Shape {
69 readonly write: (input: {
70 + /** Return no events if another thread owns this native session at commit time. */
71 + readonly unlessNativeThreadOwned?: Pick<
72 + OrchestrationV2ProviderThread,
73 + "driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef"
74 + >;
75 readonly guardPendingUserInputCancellations?: boolean;
76 readonly commandId?: CommandId;
77 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
78 }) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
79 readonly writeWithEffects: (input: {
80 + readonly unlessNativeThreadOwned?: Pick<
81 + OrchestrationV2ProviderThread,
82 + "driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef"
83 + >;
84 readonly guardPendingUserInputCancellations?: boolean;
85 readonly commandId?: CommandId;
86 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
@@ -369,6 +378,20 @@ const layerBase: Layer.Layer<
378
379 return yield* commitThenPublish(
380 Effect.gen(function* () {
381 + // Check ownership in the same transaction that claims the native session.
382 + const imported = input.unlessNativeThreadOwned;
383 + if (imported?.nativeThreadRef != null) {
384 + const owners = yield* sql`
385 + SELECT provider_thread_id
386 + FROM orchestration_v2_projection_provider_threads
387 + WHERE driver = ${imported.driver}
388 + AND provider_instance_id = ${imported.providerInstanceId}
389 + AND thread_id IS NOT ${imported.appThreadId}
390 + AND json_extract(payload_json, '$.nativeThreadRef.nativeId') = ${imported.nativeThreadRef.nativeId}
391 + LIMIT 1
392 + `;
393 + if (owners.length > 0) return [];
394 + }
395 const normalized = yield* normalizeEvents(
396 input.guardPendingUserInputCancellations === true
397 ? yield* guardUserInputCancellations(input.events)
apps/server/src/project/AgentSessionImporter.test.ts
+359 -116
@@ -1,147 +1,390 @@
1 import { expect, it } from "@effect/vitest";
2 import {
3 + EventId,
4 ProjectId,
5 + ProviderDriverKind,
6 ProviderInstanceId,
7 ThreadId,
6 - type OrchestrationV2DomainEvent,
8 + type ApplicationStoredEvent,
9 + type OrchestrationV2AppThread,
10 + type OrchestrationV2ProviderThread,
11 } from "@t3tools/contracts";
12 +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
13 +import * as Context from "effect/Context";
14 +import * as DateTime from "effect/DateTime";
15 +import * as Deferred from "effect/Deferred";
16 import * as Effect from "effect/Effect";
17 +import * as Fiber from "effect/Fiber";
18 import * as Layer from "effect/Layer";
19 import * as Option from "effect/Option";
20 import * as Stream from "effect/Stream";
21 +import * as SqlClient from "effect/sql/SqlClient";
22
23 import * as EventSink from "../orchestration-v2/EventSink.ts";
14 -import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
24 +import * as EventStore from "../orchestration-v2/EventStore.ts";
25 import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
26 +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
27 +import {
28 + CLAUDE_MODEL_SELECTION,
29 + CODEX_MODEL_SELECTION,
30 +} from "../orchestration-v2/testkit/fixtures/shared.ts";
31 import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
32 +import * as SqlitePersistence from "../persistence/Sqlite.ts";
33 import * as AgentSessionImporter from "./AgentSessionImporter.ts";
34 import * as AgentSessionScanner from "./AgentSessionScanner.ts";
35 import * as ProjectService from "./ProjectService.ts";
36
37 const projectId = ProjectId.make("agent-session-import-project");
22 -const providerInstanceId = ProviderInstanceId.make("codex");
23 -const providerSessionId = "native-codex-thread";
24 -const threadId = ThreadId.make(`import:${providerInstanceId}:${providerSessionId}`);
38 +const timestamp = "2026-09-01T10:00:00.000Z";
39 +const now = DateTime.makeUnsafe(timestamp);
40 +const stores = Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe(
41 + Layer.provideMerge(SqlitePersistence.layerMemory),
42 +);
43 +const persistence = Layer.mergeAll(
44 + stores,
45 + EventSink.layer.pipe(Layer.provide(stores)),
46 + ProviderSessionRuntime.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
47 + IdAllocator.layer,
48 +);
49 +
50 +function candidate(
51 + modelSelection: typeof CODEX_MODEL_SELECTION,
52 + providerSessionId: string,
53 + provider: "codex" | "claudeAgent" = "codex",
54 +) {
55 + const providerInstanceId = modelSelection.instanceId;
56 + return {
57 + _tag: "Importable" as const,
58 + source: {
59 + provider,
60 + providerInstanceId,
61 + providerSessionId,
62 + filePath: `/tmp/${providerInstanceId}/${providerSessionId}.jsonl`,
63 + size: 100,
64 + mtimeMs: 2,
65 + device: 3,
66 + inode: 4,
67 + birthtimeMs: 1,
68 + },
69 + thread: {
70 + source: provider,
71 + providerInstanceId,
72 + providerSessionId,
73 + title: "Imported thread",
74 + model: modelSelection.model,
75 + createdAt: timestamp,
76 + updatedAt: timestamp,
77 + messages: [
78 + { role: "user" as const, text: "Fix it", createdAt: timestamp },
79 + { role: "assistant" as const, text: "Fixed", createdAt: timestamp },
80 + ],
81 + },
82 + } satisfies AgentSessionScanner.AgentSessionRecentThread;
83 +}
84 +
85 +function importId(source: ReturnType<typeof candidate>) {
86 + return ThreadId.make(
87 + `import:${source.source.providerInstanceId}:${source.source.providerSessionId}`,
88 + );
89 +}
90 +
91 +const seedOwner = Effect.fn(function* (
92 + source: ReturnType<typeof candidate>,
93 + lifecycle: "active" | "archived" | "deleted" = "active",
94 +) {
95 + const sink = yield* EventSink.EventSinkV2;
96 + const ids = yield* IdAllocator.IdAllocatorV2;
97 + const { providerInstanceId, providerSessionId, provider } = source.source;
98 + const threadId = ThreadId.make(`owner:${providerInstanceId}:${providerSessionId}`);
99 + const driver = ProviderDriverKind.make(provider);
100 + const providerThread: OrchestrationV2ProviderThread = {
101 + id: ids.derive.providerThread({
102 + driver,
103 + nativeThreadId: providerSessionId,
104 + }),
105 + driver,
106 + providerInstanceId,
107 + providerSessionId: null,
108 + appThreadId: threadId,
109 + ownerNodeId: null,
110 + nativeThreadRef: { driver, nativeId: providerSessionId, strength: "strong" },
111 + nativeConversationHeadRef: null,
112 + status: "idle",
113 + firstRunOrdinal: 1,
114 + lastRunOrdinal: 1,
115 + handoffIds: [],
116 + forkedFrom: null,
117 + createdAt: now,
118 + updatedAt: now,
119 + };
120 + const thread: OrchestrationV2AppThread = {
121 + createdBy: "user",
122 + creationSource: "web",
123 + id: threadId,
124 + projectId,
125 + title: "Native thread",
126 + providerInstanceId,
127 + modelSelection: { instanceId: providerInstanceId, model: source.thread.model },
128 + runtimeMode: "full-access",
129 + interactionMode: "default",
130 + branch: null,
131 + worktreePath: null,
132 + activeProviderThreadId: providerThread.id,
133 + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
134 + forkedFrom: null,
135 + createdAt: now,
136 + updatedAt: now,
137 + archivedAt: lifecycle === "archived" ? now : null,
138 + deletedAt: lifecycle === "deleted" ? now : null,
139 + settledOverride: null,
140 + settledAt: null,
141 + lastVisitedAt: null,
142 + };
143 + yield* sink.write({
144 + events: [
145 + {
146 + id: EventId.make(`${threadId}:created`),
147 + type: "thread.created",
148 + threadId,
149 + occurredAt: now,
150 + payload: thread,
151 + },
152 + {
153 + id: EventId.make(`${threadId}:provider`),
154 + type: "provider-thread.updated",
155 + threadId,
156 + occurredAt: now,
157 + payload: providerThread,
158 + },
159 + ],
160 + });
161 + return threadId;
162 +});
163
26 -it.effect("imports messages once and preserves the provider native resume binding", () => {
27 - const writes: Array<ReadonlyArray<OrchestrationV2DomainEvent>> = [];
28 - const upserts: Array<unknown> = [];
29 - const recorded: Array<unknown> = [];
30 - let imported = false;
31 - const scanner = AgentSessionScanner.AgentSessionScanner.of({
32 - scan: Effect.die("unused"),
33 - recentThreads: () =>
34 - Stream.succeed({
35 - _tag: "Importable",
36 - source: {
37 - provider: "codex",
38 - providerInstanceId,
39 - providerSessionId,
40 - filePath: "/tmp/native-codex-thread.jsonl",
41 - size: 100,
42 - mtimeMs: 2,
43 - device: 3,
44 - inode: 4,
45 - birthtimeMs: 1,
46 - },
47 - thread: {
48 - source: "codex",
49 - providerInstanceId,
50 - providerSessionId,
51 - title: "Imported thread",
52 - model: "gpt-5.4",
53 - createdAt: "2026-09-01T10:00:00.000Z",
54 - updatedAt: "2026-09-01T10:01:00.000Z",
55 - messages: [
56 - { role: "user", text: "Fix it", createdAt: "2026-09-01T10:00:00.000Z" },
57 - { role: "assistant", text: "Fixed", createdAt: "2026-09-01T10:01:00.000Z" },
58 - ],
59 - },
60 - }),
164 +const makeImporter = Effect.fn(function* (
165 + candidates: ReadonlyArray<ReturnType<typeof candidate>>,
166 + beforeTransaction: Effect.Effect<void> = Effect.void,
167 +) {
168 + const sql = yield* SqlClient.SqlClient;
169 + const events = yield* EventStore.EventStoreV2;
170 + const projections = yield* ProjectionStore.ProjectionStoreV2;
171 + const published: Array<ApplicationStoredEvent> = [];
172 + const withTransaction: typeof sql.withTransaction = (effect) =>
173 + beforeTransaction.pipe(Effect.andThen(sql.withTransaction(effect)));
174 + const importSql = new Proxy(sql, {
175 + get: (target, key, receiver) =>
176 + key === "withTransaction" ? withTransaction : Reflect.get(target, key, receiver),
177 });
62 - const layerTest = AgentSessionImporter.layer.pipe(
178 + const sinkLayer = Layer.fresh(EventSink.layer).pipe(
179 Layer.provide(
180 Layer.mergeAll(
65 - Layer.succeed(AgentSessionScanner.AgentSessionScanner, scanner),
66 - Layer.mock(ProjectService.ProjectService)({
67 - getById: () =>
68 - Effect.succeed(
69 - Option.some({ id: projectId, workspaceRoot: "/workspace/project" } as never),
181 + Layer.succeed(SqlClient.SqlClient, importSql),
182 + Layer.succeed(ProjectionStore.ProjectionStoreV2, projections),
183 + Layer.succeed(EventStore.EventStoreV2, {
184 + ...events,
185 + publishCommitted: (batch) =>
186 + events.publishCommitted(batch).pipe(
187 + Effect.tap(() =>
188 + Effect.sync(() => {
189 + published.push(...batch);
190 + }),
191 + ),
192 ),
193 }),
72 - Layer.mock(Orchestrator.OrchestratorV2)({
73 - getThreadRecords: () =>
74 - imported
75 - ? Effect.succeed({
76 - thread: { id: threadId, projectId, historyOrigin: "v1_import" },
77 - } as never)
78 - : Effect.fail(new Orchestrator.OrchestratorProjectionError({ threadId })),
79 - }),
80 - Layer.mock(EventSink.EventSinkV2)({
81 - write: (input) =>
82 - Effect.sync(() => {
83 - writes.push(input.events);
84 - imported = true;
85 - return [];
86 - }),
87 - }),
88 - Layer.mock(ProviderSessionRuntime.ProviderSessionRuntimeRepository)({
89 - list: () => Effect.succeed([]),
90 - upsert: (input) => Effect.sync(() => void upserts.push(input)),
91 - recordImportedTranscript: (input) => Effect.sync(() => void recorded.push(input)),
92 - }),
93 - IdAllocator.layer,
194 ),
195 ),
196 );
197 + const context = yield* Layer.build(
198 + AgentSessionImporter.layer.pipe(
199 + Layer.provide(
200 + Layer.mergeAll(
201 + sinkLayer,
202 + Layer.succeed(IdAllocator.IdAllocatorV2, yield* IdAllocator.IdAllocatorV2),
203 + Layer.succeed(
204 + ProviderSessionRuntime.ProviderSessionRuntimeRepository,
205 + yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository,
206 + ),
207 + Layer.mock(AgentSessionScanner.AgentSessionScanner)({
208 + recentThreads: () => Stream.fromIterable(candidates),
209 + }),
210 + Layer.mock(ProjectService.ProjectService)({
211 + getById: () =>
212 + Effect.succeed(
213 + Option.some({
214 + id: projectId,
215 + title: "Project",
216 + workspaceRoot: "/workspace/project",
217 + defaultModelSelection: null,
218 + scripts: [],
219 + createdAt: timestamp,
220 + updatedAt: timestamp,
221 + deletedAt: null,
222 + }),
223 + ),
224 + }),
225 + Layer.mock(Orchestrator.OrchestratorV2)({
226 + getThreadRecords: (threadId, fields) =>
227 + projections
228 + .getThreadRecords(threadId, fields)
229 + .pipe(
230 + Effect.mapError(
231 + (cause) => new Orchestrator.OrchestratorProjectionError({ threadId, cause }),
232 + ),
233 + ),
234 + }),
235 + ),
236 + ),
237 + ),
238 + );
239 + const importer = Context.get(context, AgentSessionImporter.AgentSessionImporter);
240 + return { run: importer.importRecentAgentThreads({ projectId }), published };
241 +});
242
98 - return Effect.gen(function* () {
99 - const importer = yield* AgentSessionImporter.AgentSessionImporter;
100 - expect(yield* importer.importRecentAgentThreads({ projectId })).toEqual({
101 - importedCount: 1,
102 - skippedCount: 0,
103 - });
104 - expect(yield* importer.importRecentAgentThreads({ projectId })).toEqual({
105 - importedCount: 1,
106 - skippedCount: 0,
107 - });
243 +it.effect(
244 + "ignores owned sessions, including archived and deleted threads, but imports other instances and unowned sessions",
245 + () =>
246 + Effect.gen(function* () {
247 + const projections = yield* ProjectionStore.ProjectionStoreV2;
248 + const events = yield* EventStore.EventStoreV2;
249 + const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
250 + const active = candidate(CODEX_MODEL_SELECTION, "active");
251 + const archived = candidate(
252 + CLAUDE_MODEL_SELECTION,
253 + "020e7f00-dce6-406b-8ec6-ed90498945d6",
254 + "claudeAgent",
255 + );
256 + const deleted = candidate(CODEX_MODEL_SELECTION, "deleted");
257 + const owners = [
258 + yield* seedOwner(active),
259 + yield* seedOwner(archived, "archived"),
260 + yield* seedOwner(deleted, "deleted"),
261 + ];
262 + const before = yield* Effect.forEach(owners, (id) =>
263 + projections.getThreadRecords(id, ["providerThreads"]),
264 + );
265 + const otherInstance = candidate(
266 + { ...CLAUDE_MODEL_SELECTION, instanceId: ProviderInstanceId.make("claude-other") },
267 + archived.source.providerSessionId,
268 + "claudeAgent",
269 + );
270 + const unowned = candidate(CODEX_MODEL_SELECTION, "unowned");
271 + const importer = yield* makeImporter([active, archived, deleted, otherInstance, unowned]);
272
109 - expect(writes).toHaveLength(1);
110 - expect(writes[0]?.map((event) => event.type)).toEqual([
111 - "thread.created",
112 - "message.updated",
113 - "turn-item.updated",
114 - "message.updated",
115 - "turn-item.updated",
116 - "provider-thread.updated",
117 - ]);
118 - const created = writes[0]?.find((event) => event.type === "thread.created");
119 - const providerThread = writes[0]?.find((event) => event.type === "provider-thread.updated");
120 - expect(created?.payload).toMatchObject({
121 - id: threadId,
122 - activeProviderThreadId: providerThread?.payload.id,
123 - historyOrigin: "v1_import",
124 - });
125 - expect(providerThread?.payload).toMatchObject({
126 - appThreadId: threadId,
127 - nativeThreadRef: {
128 - driver: "codex",
129 - nativeId: providerSessionId,
130 - strength: "strong",
131 - },
132 - });
273 + expect(yield* importer.run).toEqual({ importedCount: 2, skippedCount: 0 });
274 + for (const source of [active, archived, deleted]) {
275 + const threadId = importId(source);
276 + expect(yield* Effect.option(projections.getThread(threadId))).toEqual(Option.none());
277 + expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual([]);
278 + expect(yield* runtimes.getByThreadId({ threadId })).toEqual(Option.none());
279 + }
280 + expect(
281 + yield* Effect.forEach(owners, (id) =>
282 + projections.getThreadRecords(id, ["providerThreads"]),
283 + ),
284 + ).toEqual(before);
285 + expect(
286 + new Set(
287 + importer.published.flatMap((stored) =>
288 + "event" in stored ? [stored.event.threadId] : [],
289 + ),
290 + ),
291 + ).toEqual(new Set([importId(otherInstance), importId(unowned)]));
292 + for (const source of [otherInstance, unowned]) {
293 + const threadId = importId(source);
294 + const records = yield* projections.getThreadRecords(threadId, [
295 + "messages",
296 + "providerThreads",
297 + ]);
298 + expect(records.messages.map((message) => message.text)).toEqual(["Fix it", "Fixed"]);
299 + expect(records.thread.historyOrigin).toBe("v1_import");
300 + expect(records.thread.activeProviderThreadId).toBe(records.providerThreads[0]?.id);
301 + expect(records.providerThreads[0]?.nativeThreadRef?.nativeId).toBe(
302 + source.source.providerSessionId,
303 + );
304 + expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({
305 + providerInstanceId: source.source.providerInstanceId,
306 + resumeCursor:
307 + source.source.provider === "codex"
308 + ? { threadId: source.source.providerSessionId }
309 + : { threadId, resume: source.source.providerSessionId },
310 + runtimePayload: { importedTranscripts: [source.source] },
311 + });
312 + }
313 + }).pipe(Effect.scoped, Effect.provide(persistence)),
314 +);
315 +
316 +it.effect("rechecks ownership after the import reaches the commit transaction", () =>
317 + Effect.gen(function* () {
318 + const enteringTransaction = yield* Deferred.make<void>();
319 + const continueTransaction = yield* Deferred.make<void>();
320 + const source = candidate(CODEX_MODEL_SELECTION, "claimed-during-import");
321 + const importer = yield* makeImporter(
322 + [source],
323 + Deferred.succeed(enteringTransaction, undefined).pipe(
324 + Effect.andThen(Deferred.await(continueTransaction)),
325 + ),
326 + );
327 + const pending = yield* Effect.forkScoped(importer.run);
328 + yield* Deferred.await(enteringTransaction);
329 + // Commit ownership after all pre-transaction reads, before the import acquires SQLite.
330 + const ownerId = yield* seedOwner(source);
331 + yield* Deferred.succeed(continueTransaction, undefined);
332 + expect(yield* Fiber.join(pending)).toEqual({ importedCount: 0, skippedCount: 0 });
333 + expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 0 });
334 + const projections = yield* ProjectionStore.ProjectionStoreV2;
335 + const events = yield* EventStore.EventStoreV2;
336 + const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
337 + expect(yield* Effect.option(projections.getThread(importId(source)))).toEqual(Option.none());
338 + expect(yield* events.read({ threadId: importId(source) }).pipe(Stream.runCollect)).toEqual([]);
339 + expect(yield* runtimes.list()).toEqual([]);
340 + expect(importer.published).toEqual([]);
341 expect(
134 - writes[0]
135 - ?.filter((event) => event.type === "message.updated")
136 - .map((event) => event.payload.text),
137 - ).toEqual(["Fix it", "Fixed"]);
138 - expect(upserts).toEqual([
139 - expect.objectContaining({
140 - threadId,
141 - providerInstanceId,
142 - resumeCursor: { threadId: providerSessionId },
143 - }),
144 - ]);
145 - expect(recorded).toHaveLength(2);
146 - }).pipe(Effect.provide(layerTest));
147 -});
342 + (yield* projections.getThreadRecords(ownerId, ["providerThreads"])).providerThreads[0]
343 + ?.appThreadId,
344 + ).toBe(ownerId);
345 + }).pipe(Effect.scoped, Effect.provide(persistence)),
346 +);
347 +
348 +it.effect(
349 + "retries failed commits and runtime persistence without replaying committed history",
350 + () =>
351 + Effect.gen(function* () {
352 + const sql = yield* SqlClient.SqlClient;
353 + const events = yield* EventStore.EventStoreV2;
354 + const projections = yield* ProjectionStore.ProjectionStoreV2;
355 + const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
356 + const source = candidate(CODEX_MODEL_SELECTION, "retry");
357 + const threadId = importId(source);
358 + const importer = yield* makeImporter([source]);
359 + 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`;
360 + expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 1 });
361 + expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual([]);
362 + expect(yield* Effect.option(projections.getThread(threadId))).toEqual(Option.none());
363 + expect(yield* runtimes.list()).toEqual([]);
364 + expect(importer.published).toEqual([]);
365 + yield* sql`DROP TRIGGER fail_import`;
366 +
367 + yield* sql`CREATE TEMP TRIGGER fail_runtime BEFORE INSERT ON provider_session_runtime BEGIN SELECT RAISE(ABORT, 'test runtime failure'); END`;
368 + expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 1 });
369 + const committed = yield* events.read({ threadId }).pipe(Stream.runCollect);
370 + expect(committed).toHaveLength(6);
371 + expect(importer.published).toHaveLength(6);
372 + expect(yield* runtimes.list()).toEqual([]);
373 + yield* sql`DROP TRIGGER fail_runtime`;
374 +
375 + expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 });
376 + expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 });
377 + expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual(committed);
378 + expect(importer.published).toHaveLength(6);
379 + expect(
380 + (yield* projections.getThreadRecords(threadId, ["messages"])).messages.map(
381 + (message) => message.text,
382 + ),
383 + ).toEqual(["Fix it", "Fixed"]);
384 + expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({
385 + providerInstanceId: source.source.providerInstanceId,
386 + resumeCursor: { threadId: source.source.providerSessionId },
387 + runtimePayload: { importedTranscripts: [source.source] },
388 + });
389 + }).pipe(Effect.scoped, Effect.provide(persistence)),
390 +);
apps/server/src/project/AgentSessionImporter.ts
+26 -21
@@ -249,6 +249,24 @@ const make = Effect.gen(function* () {
249 providerSessionId: thread.providerSessionId,
250 });
251 }
252 + const driver = ProviderDriverKind.make(thread.source);
253 + const persistRuntime = runtimes.upsert(
254 + {
255 + threadId,
256 + providerName: driver,
257 + providerInstanceId: thread.providerInstanceId,
258 + adapterKey: driver,
259 + runtimeMode: DEFAULT_RUNTIME_MODE,
260 + status: "stopped",
261 + lastSeenAt: thread.updatedAt,
262 + resumeCursor:
263 + thread.source === "codex"
264 + ? { threadId: thread.providerSessionId }
265 + : { threadId, resume: thread.providerSessionId },
266 + runtimePayload: { cwd: project.workspaceRoot },
267 + },
268 + { onConflict: "ignore" },
269 + );
270 const existing = yield* Effect.option(orchestrator.getThreadRecords(threadId, []));
271 if (Option.isSome(existing)) {
272 if (existing.value.thread.projectId !== input.projectId) {
@@ -261,14 +279,15 @@ const make = Effect.gen(function* () {
279 if (existing.value.thread.historyOrigin !== "v1_import") {
280 return yield* new AgentSessionThreadModifiedError({ threadId });
281 }
282 + yield* persistRuntime;
283 yield* runtimes.recordImportedTranscript({ threadId, source });
284 return true;
285 }
286
268 - const driver = ProviderDriverKind.make(thread.source);
287 const model = thread.model ?? DEFAULT_MODEL_BY_PROVIDER[driver] ?? DEFAULT_MODEL;
288 const providerThreadId = idAllocator.derive.providerThread({
289 driver,
290 + providerInstanceId: thread.providerInstanceId,
291 nativeThreadId: thread.providerSessionId,
292 });
293 const createdAt = dateTime(thread.createdAt);
@@ -332,24 +351,8 @@ const make = Effect.gen(function* () {
351 updatedAt,
352 };
353
335 - yield* runtimes.upsert(
336 - {
337 - threadId,
338 - providerName: driver,
339 - providerInstanceId: thread.providerInstanceId,
340 - adapterKey: driver,
341 - runtimeMode: DEFAULT_RUNTIME_MODE,
342 - status: "stopped",
343 - lastSeenAt: thread.updatedAt,
344 - resumeCursor:
345 - thread.source === "codex"
346 - ? { threadId: thread.providerSessionId }
347 - : { threadId, resume: thread.providerSessionId },
348 - runtimePayload: { cwd: project.workspaceRoot },
349 - },
350 - { onConflict: "ignore" },
351 - );
352 - yield* eventSink.write({
354 + const committed = yield* eventSink.write({
355 + unlessNativeThreadOwned: providerThread,
356 events: [
357 {
358 id: EventId.make(`${IMPORT_EVENT_PREFIX}:thread:${threadId}:created`),
@@ -373,6 +376,8 @@ const make = Effect.gen(function* () {
376 },
377 ],
378 });
379 + if (committed.length === 0) return null;
380 + yield* persistRuntime;
381 yield* runtimes.recordImportedTranscript({ threadId, source });
382 return true;
383 }).pipe(
@@ -384,10 +389,10 @@ const make = Effect.gen(function* () {
389 }).pipe(Effect.as(false)),
390 ),
391 );
387 - if (imported) {
392 + if (imported === true) {
393 importedThreadIds.add(threadId);
394 importedCount += 1;
390 - } else {
395 + } else if (imported === false) {
396 skippedCount += 1;
397 }
398 }),