Skip to content

Commit 2c3095f

Browse files
committed
fix(server): check native sessions when reserving imports
1 parent 69c8372 commit 2c3095f

4 files changed

Lines changed: 118 additions & 63 deletions

File tree

‎apps/server/src/persistence/ProviderSessionRuntime.ts‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ export type RecordImportedTranscriptInput = typeof RecordImportedTranscriptInput
6767

6868
export interface ProviderSessionRuntimeUpsertOptions {
6969
readonly onConflict?: "update" | "ignore";
70+
readonly unlessNativeSessionId?: string;
7071
}
7172

7273
/**
@@ -235,7 +236,9 @@ export const make = Effect.gen(function* () {
235236
});
236237

237238
const insertRuntimeRow = SqlSchema.void({
238-
Request: ProviderSessionRuntimeDbRowSchema,
239+
Request: ProviderSessionRuntimeDbRowSchema.mapFields(
240+
Struct.assign({ unlessNativeSessionId: Schema.NullOr(Schema.String) }),
241+
),
239242
execute: (runtime) =>
240243
sql`
241244
INSERT INTO provider_session_runtime (
@@ -249,7 +252,7 @@ export const make = Effect.gen(function* () {
249252
resume_cursor_json,
250253
runtime_payload_json
251254
)
252-
VALUES (
255+
SELECT
253256
${runtime.threadId},
254257
${runtime.providerName},
255258
${runtime.providerInstanceId},
@@ -263,6 +266,17 @@ export const make = Effect.gen(function* () {
263266
THEN json_remove(${runtime.runtimePayload}, '$.importedTranscripts')
264267
ELSE ${runtime.runtimePayload}
265268
END
269+
WHERE ${runtime.unlessNativeSessionId} IS NULL OR NOT EXISTS (
270+
SELECT 1 FROM provider_session_runtime
271+
WHERE thread_id NOT LIKE 'import:%'
272+
AND provider_name = ${runtime.providerName}
273+
AND COALESCE(provider_instance_id, provider_name) = ${runtime.providerInstanceId}
274+
AND CASE WHEN json_valid(resume_cursor_json) THEN
275+
json_extract(resume_cursor_json, CASE provider_name
276+
WHEN 'claudeAgent' THEN '$.resume'
277+
WHEN 'codex' THEN '$.threadId'
278+
END)
279+
END = ${runtime.unlessNativeSessionId}
266280
)
267281
ON CONFLICT (thread_id) DO NOTHING
268282
`,
@@ -365,7 +379,13 @@ export const make = Effect.gen(function* () {
365379
});
366380

367381
const upsert: ProviderSessionRuntimeRepository["Service"]["upsert"] = (runtime, options) =>
368-
(options?.onConflict === "ignore" ? insertRuntimeRow(runtime) : upsertRuntimeRow(runtime)).pipe(
382+
(options?.onConflict === "ignore"
383+
? insertRuntimeRow({
384+
...runtime,
385+
unlessNativeSessionId: options.unlessNativeSessionId ?? null,
386+
})
387+
: upsertRuntimeRow(runtime)
388+
).pipe(
369389
Effect.mapError(
370390
toPersistenceSqlOrDecodeError(
371391
"ProviderSessionRuntimeRepository.upsert:query",

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

Lines changed: 91 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,10 @@ it.layer(NodeServices.layer)("AgentSessionImporter", (it) => {
231231
upsert: (binding) => Effect.sync(() => void bindings.push(binding)),
232232
getProvider: () => Effect.die("unused"),
233233
recordImportedTranscript: () => Effect.void,
234-
getBinding: () => Effect.succeed(Option.none()),
234+
getBinding: (threadId) =>
235+
Effect.succeed(
236+
Option.fromUndefinedOr(bindings.find((binding) => binding.threadId === threadId)),
237+
),
235238
listThreadIds: () => Effect.die("unused"),
236239
listBindings: () =>
237240
Effect.succeed([
@@ -590,64 +593,93 @@ const integrationLayer = Layer.mergeAll(
590593

591594
it.layer(integrationLayer)("AgentSessionImporter integration", (it) => {
592595
for (const source of ["codex", "claudeAgent"] as const) {
593-
it.effect(`does not import a ${source} session already owned by a native thread`, () =>
594-
Effect.gen(function* () {
595-
const engine = yield* OrchestrationEngine.OrchestrationEngineService;
596-
const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
597-
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
598-
const projectId = ProjectId.make(`native-import-${source}`);
599-
const threadId = ThreadId.make(`native-${source}`);
600-
const thread = {
601-
...makeThread(source),
602-
providerSessionId:
603-
source === "codex" ? "native-codex-session" : "123e4567-e89b-42d3-a456-426614174001",
604-
};
605-
yield* engine.dispatch({
606-
type: "project.create",
607-
commandId: CommandId.make(`create-${projectId}`),
608-
projectId,
609-
title: "Native project",
610-
workspaceRoot: `/tmp/${projectId}`,
611-
defaultModelSelection: null,
612-
createdAt: thread.createdAt,
613-
});
614-
yield* engine.dispatch({
615-
type: "thread.create",
616-
commandId: CommandId.make(`create-${threadId}`),
617-
threadId,
618-
projectId,
619-
title: "Native conversation",
620-
modelSelection: { instanceId: thread.providerInstanceId, model: "default" },
621-
runtimeMode: "full-access",
622-
interactionMode: "default",
623-
branch: null,
624-
worktreePath: null,
625-
createdAt: thread.createdAt,
626-
});
627-
yield* directory.upsert({
628-
threadId,
629-
provider: ProviderDriverKind.make(source),
630-
providerInstanceId: thread.providerInstanceId,
631-
status: "stopped",
632-
resumeCursor:
633-
source === "codex"
634-
? { threadId: thread.providerSessionId }
635-
: { threadId, resume: thread.providerSessionId },
636-
});
637-
const before = yield* snapshots.getThreadDetailById(threadId);
638-
const result = yield* importRecentAgentThreads({ projectId }).pipe(
639-
Effect.provideService(AgentSessionScanner.AgentSessionScanner, {
640-
scan: Effect.die("unused"),
641-
recentThreads: () => Stream.succeed(makeThreadOutcome(thread)),
642-
}),
643-
);
644-
const importedId = ThreadId.make(`import:${source}:${thread.providerSessionId}`);
645-
expect(result).toEqual({ importedCount: 0, skippedCount: 1 });
646-
expect(yield* snapshots.getThreadDetailById(importedId)).toEqual(Option.none());
647-
expect(yield* directory.getBinding(importedId)).toEqual(Option.none());
648-
expect(yield* snapshots.getThreadDetailById(threadId)).toEqual(before);
649-
}),
650-
);
596+
for (const timing of ["before scan", "before reservation"] as const) {
597+
it.effect(`skips native ${source} sessions bound ${timing}`, () =>
598+
Effect.gen(function* () {
599+
const engine = yield* OrchestrationEngine.OrchestrationEngineService;
600+
const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
601+
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
602+
const projectId = ProjectId.make(`native-import-${source}-${timing}`);
603+
const threadId = ThreadId.make(`native-${source}-${timing}`);
604+
const thread = {
605+
...makeThread(source),
606+
providerSessionId:
607+
source === "codex"
608+
? `native-codex-session-${timing}`
609+
: timing === "before scan"
610+
? "123e4567-e89b-42d3-a456-426614174001"
611+
: "123e4567-e89b-42d3-a456-426614174002",
612+
};
613+
yield* engine.dispatch({
614+
type: "project.create",
615+
commandId: CommandId.make(`create-${projectId}`),
616+
projectId,
617+
title: "Native project",
618+
workspaceRoot: `/tmp/${projectId}`,
619+
defaultModelSelection: null,
620+
createdAt: thread.createdAt,
621+
});
622+
yield* engine.dispatch({
623+
type: "thread.create",
624+
commandId: CommandId.make(`create-${threadId}`),
625+
threadId,
626+
projectId,
627+
title: "Native conversation",
628+
modelSelection: { instanceId: thread.providerInstanceId, model: "default" },
629+
runtimeMode: "full-access",
630+
interactionMode: "default",
631+
branch: null,
632+
worktreePath: null,
633+
createdAt: thread.createdAt,
634+
});
635+
const bindNative = directory.upsert({
636+
threadId,
637+
provider: ProviderDriverKind.make(source),
638+
providerInstanceId: thread.providerInstanceId,
639+
status: "stopped",
640+
resumeCursor:
641+
source === "codex"
642+
? { threadId: thread.providerSessionId }
643+
: { threadId, resume: thread.providerSessionId },
644+
});
645+
if (timing === "before scan") yield* bindNative;
646+
const before = yield* snapshots.getThreadDetailById(threadId);
647+
const result = yield* importRecentAgentThreads({ projectId }).pipe(
648+
Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, {
649+
...directory,
650+
upsert: (binding, options) =>
651+
bindNative.pipe(Effect.andThen(directory.upsert(binding, options))),
652+
}),
653+
Effect.provideService(AgentSessionScanner.AgentSessionScanner, {
654+
scan: Effect.die("unused"),
655+
recentThreads: () => Stream.succeed(makeThreadOutcome(thread)),
656+
}),
657+
);
658+
const importedId = ThreadId.make(`import:${source}:${thread.providerSessionId}`);
659+
expect(result).toEqual({ importedCount: 0, skippedCount: 1 });
660+
expect(yield* snapshots.getThreadDetailById(importedId)).toEqual(Option.none());
661+
expect(yield* directory.getBinding(importedId)).toEqual(Option.none());
662+
expect(yield* snapshots.getThreadDetailById(threadId)).toEqual(before);
663+
const otherInstance = ProviderInstanceId.make(`${source}-other`);
664+
const otherThreadId = ThreadId.make(
665+
`import:${otherInstance}:${thread.providerSessionId}`,
666+
);
667+
yield* directory.upsert(
668+
{
669+
threadId: otherThreadId,
670+
provider: ProviderDriverKind.make(source),
671+
providerInstanceId: otherInstance,
672+
resumeCursor:
673+
source === "codex"
674+
? { threadId: thread.providerSessionId }
675+
: { resume: thread.providerSessionId },
676+
},
677+
{ onConflict: "ignore", unlessNativeSessionId: thread.providerSessionId },
678+
);
679+
expect(Option.isSome(yield* directory.getBinding(otherThreadId))).toBe(true);
680+
}),
681+
);
682+
}
651683
}
652684

653685
it.effect("imports once after the real engine persists an old rejected receipt", () =>

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,8 +261,9 @@ export const importRecentAgentThreads = Effect.fn("importRecentAgentThreads")(fu
261261
: { threadId, resume: thread.providerSessionId },
262262
runtimePayload: { cwd: workspaceRoot },
263263
},
264-
{ onConflict: "ignore" },
264+
{ onConflict: "ignore", unlessNativeSessionId: thread.providerSessionId },
265265
);
266+
if (Option.isNone(yield* directory.getBinding(threadId))) return false;
266267
}
267268

268269
if (Option.isNone(existingThread)) {

‎apps/server/src/provider/Services/ProviderSessionDirectory.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ export type ProviderSessionDirectoryWriteError =
4343

4444
export interface ProviderSessionDirectoryUpsertOptions {
4545
readonly onConflict?: "update" | "ignore";
46+
// For insert-ignore imports, reserve only if no native binding owns this session.
47+
readonly unlessNativeSessionId?: string;
4648
}
4749

4850
export interface ProviderSessionDirectoryShape {

0 commit comments

Comments
 (0)