Skip to content

Commit de8d700

Browse files
committed
fix(server): stamp the import origin on provider threads imported earlier
Rows written before the import origin existed carry no marker, so their first Claude follow-up still reopened the session with a fixed id. Both already-imported paths of AgentSessionImporter now load the thread's provider threads and stamp `nativeThreadOrigin: "imported"` on the row for the imported session when it is missing; rows that already carry it are left alone.
1 parent 7e46f87 commit de8d700

2 files changed

Lines changed: 198 additions & 1 deletion

File tree

‎apps/server/src/project/AgentSessionImporter.test.ts‎

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
ThreadId,
66
type OrchestrationV2DomainEvent,
77
} from "@t3tools/contracts";
8+
import * as DateTime from "effect/DateTime";
89
import * as Effect from "effect/Effect";
910
import * as Layer from "effect/Layer";
1011
import * as Option from "effect/Option";
@@ -146,3 +147,134 @@ it.effect("imports messages once and preserves the provider native resume bindin
146147
expect(recorded).toHaveLength(2);
147148
}).pipe(Effect.provide(testLayer));
148149
});
150+
151+
it.effect("stamps the import origin on provider threads imported before it existed", () => {
152+
const originProjectId = ProjectId.make("project-import-origin");
153+
const originInstanceId = ProviderInstanceId.make("codex");
154+
const originSessionId = "native-codex-thread-origin";
155+
const originThreadId = ThreadId.make(`import:${originInstanceId}:${originSessionId}`);
156+
const writes: Array<ReadonlyArray<OrchestrationV2DomainEvent>> = [];
157+
let imported = false;
158+
let stamped = false;
159+
const legacyProviderThread = {
160+
id: `provider-thread:${originSessionId}`,
161+
driver: "codex",
162+
providerInstanceId: originInstanceId,
163+
providerSessionId: "provider-session-1",
164+
appThreadId: originThreadId,
165+
ownerNodeId: null,
166+
nativeThreadRef: { driver: "codex", nativeId: originSessionId, strength: "strong" },
167+
nativeConversationHeadRef: null,
168+
status: "idle",
169+
firstRunOrdinal: null,
170+
lastRunOrdinal: null,
171+
handoffIds: [],
172+
forkedFrom: null,
173+
createdAt: DateTime.makeUnsafe("2026-09-01T10:00:00.000Z"),
174+
updatedAt: DateTime.makeUnsafe("2026-09-01T10:01:00.000Z"),
175+
};
176+
const scanner = AgentSessionScanner.AgentSessionScanner.of({
177+
scan: Effect.die("unused"),
178+
recentThreads: () =>
179+
Stream.succeed({
180+
_tag: "Importable",
181+
source: {
182+
provider: "codex",
183+
providerInstanceId: originInstanceId,
184+
providerSessionId: originSessionId,
185+
filePath: "/tmp/native-codex-thread-origin.jsonl",
186+
size: 100,
187+
mtimeMs: 2,
188+
device: 3,
189+
inode: 4,
190+
birthtimeMs: 1,
191+
},
192+
thread: {
193+
source: "codex",
194+
providerInstanceId: originInstanceId,
195+
providerSessionId: originSessionId,
196+
title: "Imported thread",
197+
model: "gpt-5.4",
198+
createdAt: "2026-09-01T10:00:00.000Z",
199+
updatedAt: "2026-09-01T10:01:00.000Z",
200+
messages: [{ role: "user", text: "Fix it", createdAt: "2026-09-01T10:00:00.000Z" }],
201+
},
202+
}),
203+
});
204+
const testLayer = AgentSessionImporter.layer.pipe(
205+
Layer.provide(
206+
Layer.mergeAll(
207+
Layer.succeed(AgentSessionScanner.AgentSessionScanner, scanner),
208+
Layer.mock(ProjectService.ProjectService)({
209+
getById: () =>
210+
Effect.succeed(
211+
Option.some({ id: originProjectId, workspaceRoot: "/workspace/project" } as never),
212+
),
213+
}),
214+
Layer.mock(Orchestrator.OrchestratorV2)({
215+
// A thread imported before the origin marker existed: its provider
216+
// thread row carries no nativeMetadata until a later import stamps it.
217+
getThreadRecords: () =>
218+
imported
219+
? Effect.succeed({
220+
thread: {
221+
id: originThreadId,
222+
projectId: originProjectId,
223+
historyOrigin: "v1_import",
224+
},
225+
providerThreads: [
226+
stamped
227+
? {
228+
...legacyProviderThread,
229+
nativeMetadata: { nativeThreadOrigin: "imported" },
230+
}
231+
: legacyProviderThread,
232+
],
233+
} as never)
234+
: Effect.fail(
235+
new Orchestrator.OrchestratorProjectionError({ threadId: originThreadId }),
236+
),
237+
}),
238+
Layer.mock(EventSink.EventSinkV2)({
239+
write: (input) =>
240+
Effect.sync(() => {
241+
writes.push(input.events);
242+
imported = true;
243+
return [];
244+
}),
245+
}),
246+
Layer.mock(ProviderSessionRuntime.ProviderSessionRuntimeRepository)({
247+
list: () => Effect.succeed([]),
248+
upsert: () => Effect.void,
249+
recordImportedTranscript: () => Effect.void,
250+
}),
251+
IdAllocator.layer,
252+
),
253+
),
254+
);
255+
256+
return Effect.gen(function* () {
257+
const importer = yield* AgentSessionImporter.AgentSessionImporter;
258+
yield* importer.importRecentAgentThreads({ projectId: originProjectId });
259+
expect(writes).toHaveLength(1);
260+
261+
// The second pass finds the thread already imported and stamps its row.
262+
yield* importer.importRecentAgentThreads({ projectId: originProjectId });
263+
expect(writes).toHaveLength(2);
264+
expect(writes[1]?.map((event) => event.type)).toEqual(["provider-thread.updated"]);
265+
const stampedEvent = writes[1]?.[0];
266+
expect(stampedEvent?.id).toBe(
267+
`agent-session-import:v2:provider-thread:${legacyProviderThread.id}:imported-origin`,
268+
);
269+
expect(stampedEvent?.payload).toMatchObject({
270+
id: legacyProviderThread.id,
271+
nativeThreadRef: legacyProviderThread.nativeThreadRef,
272+
nativeMetadata: { nativeThreadOrigin: "imported" },
273+
});
274+
275+
// A row that already carries the origin is left alone.
276+
stamped = true;
277+
yield* importer.importRecentAgentThreads({ projectId: originProjectId });
278+
expect(writes).toHaveLength(2);
279+
}).pipe(Effect.provide(testLayer));
280+
});

‎apps/server/src/project/AgentSessionImporter.ts‎

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,54 @@ const make = Effect.gen(function* () {
172172
const eventSink = yield* EventSink.EventSinkV2;
173173
const idAllocator = yield* IdAllocator.IdAllocatorV2;
174174
const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
175+
// Provider threads written before the import origin existed carry no
176+
// marker, so a thread the scanner reports as already imported gets it
177+
// stamped here; otherwise its first Claude follow-up still reopens the
178+
// session with a fixed id.
179+
const stampImportedOrigin = Effect.fn("stampImportedOriginV2")(function* (input: {
180+
readonly threadId: ThreadId;
181+
readonly providerSessionId: string;
182+
readonly providerThreads: ReadonlyArray<OrchestrationV2ProviderThread> | undefined;
183+
}) {
184+
const providerThread = input.providerThreads?.find(
185+
(candidate) => candidate.nativeThreadRef?.nativeId === input.providerSessionId,
186+
);
187+
if (
188+
providerThread === undefined ||
189+
providerThread.nativeMetadata?.nativeThreadOrigin === "imported"
190+
) {
191+
return;
192+
}
193+
const now = yield* DateTime.now;
194+
yield* eventSink.write({
195+
events: [
196+
{
197+
id: EventId.make(
198+
`${IMPORT_EVENT_PREFIX}:provider-thread:${providerThread.id}:imported-origin`,
199+
),
200+
type: "provider-thread.updated",
201+
threadId: input.threadId,
202+
driver: providerThread.driver,
203+
providerInstanceId: providerThread.providerInstanceId,
204+
occurredAt: now,
205+
payload: {
206+
...providerThread,
207+
nativeMetadata: { ...providerThread.nativeMetadata, nativeThreadOrigin: "imported" },
208+
updatedAt: now,
209+
},
210+
},
211+
],
212+
});
213+
});
214+
const stampImportedOriginOrWarn = (input: Parameters<typeof stampImportedOrigin>[0]) =>
215+
stampImportedOrigin(input).pipe(
216+
Effect.catch((cause) =>
217+
Effect.logWarning("Could not stamp the import origin on a provider thread", {
218+
threadId: input.threadId,
219+
cause,
220+
}),
221+
),
222+
);
175223
const importRecentAgentThreads = Effect.fn("importRecentAgentThreadsV2")(function* (
176224
input: AgentSessionImportInput,
177225
) {
@@ -229,6 +277,16 @@ const make = Effect.gen(function* () {
229277
if (outcome._tag === "AlreadyImported") {
230278
importedThreadIds.add(threadId);
231279
importedCount += 1;
280+
const records = yield* Effect.option(
281+
orchestrator.getThreadRecords(threadId, ["providerThreads"]),
282+
);
283+
if (Option.isSome(records)) {
284+
yield* stampImportedOriginOrWarn({
285+
threadId,
286+
providerSessionId: source.providerSessionId,
287+
providerThreads: records.value.providerThreads,
288+
});
289+
}
232290
return;
233291
}
234292
if (outcome._tag === "Duplicate") {
@@ -249,7 +307,9 @@ const make = Effect.gen(function* () {
249307
providerSessionId: thread.providerSessionId,
250308
});
251309
}
252-
const existing = yield* Effect.option(orchestrator.getThreadRecords(threadId, []));
310+
const existing = yield* Effect.option(
311+
orchestrator.getThreadRecords(threadId, ["providerThreads"]),
312+
);
253313
if (Option.isSome(existing)) {
254314
if (existing.value.thread.projectId !== input.projectId) {
255315
return yield* new AgentSessionThreadProjectConflictError({
@@ -262,6 +322,11 @@ const make = Effect.gen(function* () {
262322
return yield* new AgentSessionThreadModifiedError({ threadId });
263323
}
264324
yield* runtimes.recordImportedTranscript({ threadId, source });
325+
yield* stampImportedOriginOrWarn({
326+
threadId,
327+
providerSessionId: thread.providerSessionId,
328+
providerThreads: existing.value.providerThreads,
329+
});
265330
return true;
266331
}
267332

0 commit comments

Comments
 (0)