feat(orchestration-v2): import an existing Claude Code or Codex session by id, with two-way transcript sync #5499
ClosedBil0000(GitHub profile, opens in a new tab)wants to merge 215 commits into
t3code/codex-turn-mapping fromrefs/pull/5499/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/orchestration-v2/SessionImportService.ts lines 76 to 79OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +59,21 @@59+ readonly importSession: (60+ input: OrchestrationV2ImportSessionInput,61+ ) => Effect.Effect<OrchestrationV2ImportSessionResult, OrchestrationV2ImportSessionError>;62+ /**63+ * Re-reads the provider's on-disk transcript behind an imported thread and64+ * appends any conversation that happened outside T3 since the last sync.65+ * No-op for threads that were not created by an import. Never fails the66+ * caller: sync problems are logged and surfaced via the imports table.67+ */68+ readonly ensureSynced: (threadId: ThreadId) => Effect.Effect<void>;69+}70+71+export class SessionImportService extends Context.Service<72+ SessionImportService,73+ SessionImportServiceShape74+>()("t3/orchestration-v2/SessionImportService") {}75+76+const importError = (message: string, cause?: unknown) =>77+ cause === undefined78+ ? new OrchestrationV2ImportSessionError({ message })79+ : new OrchestrationV2ImportSessionError({ message, cause });packages/contracts/src/orchestrationV2.ts lines 2368 to 2376Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -2320,0 +2341,21 @@2341+ typeof OrchestrationV2ResolveImportSessionResult.Type;2342+2343+export const OrchestrationV2ImportSessionInput = Schema.Struct({2344+ projectId: ProjectId,2345+ modelSelection: ModelSelection,2346+ externalId: TrimmedNonEmptyString,2347+});2348+export type OrchestrationV2ImportSessionInput = typeof OrchestrationV2ImportSessionInput.Type;2349+2350+export const OrchestrationV2ImportSessionResult = Schema.Struct({2351+ threadId: ThreadId,2352+});2353+export type OrchestrationV2ImportSessionResult = typeof OrchestrationV2ImportSessionResult.Type;2354+2355+export class OrchestrationV2ImportSessionError extends Schema.TaggedErrorClass<OrchestrationV2ImportSessionError>()(2356+ "OrchestrationV2ImportSessionError",2357+ {2358+ message: TrimmedNonEmptyString,2359+ cause: Schema.optional(Schema.Defect()),2360+ },2361+) {}apps/server/src/orchestration-v2/SessionImportService.ts lines 55 to 74OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +54,21 @@54+55+export interface SessionImportServiceShape {56+ readonly resolveImportSession: (57+ input: OrchestrationV2ResolveImportSessionInput,58+ ) => Effect.Effect<OrchestrationV2ResolveImportSessionResult, OrchestrationV2ImportSessionError>;59+ readonly importSession: (60+ input: OrchestrationV2ImportSessionInput,61+ ) => Effect.Effect<OrchestrationV2ImportSessionResult, OrchestrationV2ImportSessionError>;62+ /**63+ * Re-reads the provider's on-disk transcript behind an imported thread and64+ * appends any conversation that happened outside T3 since the last sync.65+ * No-op for threads that were not created by an import. Never fails the66+ * caller: sync problems are logged and surfaced via the imports table.67+ */68+ readonly ensureSynced: (threadId: ThreadId) => Effect.Effect<void>;69+}70+71+export class SessionImportService extends Context.Service<72+ SessionImportService,73+ SessionImportServiceShape74+>()("t3/orchestration-v2/SessionImportService") {}apps/server/src/orchestration-v2/SessionImportService.ts lines 112 to 115OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +95,21 @@95+ });96+97+const readClaudeTranscript = (externalId: string) =>98+ Effect.tryPromise({99+ try: () => getSessionMessages(externalId, {}),100+ catch: (cause) =>101+ importError(`Could not read the transcript for Claude Code session '${externalId}'.`, cause),102+ }).pipe(Effect.map(mapClaudeSessionMessages));103+104+/**105+ * Locates and reads the rollout transcript for a Codex thread id under106+ * `$CODEX_HOME/sessions/**` (`~/.codex/sessions` by default). The sessions107+ * directory is shared between the user's own Codex CLI and T3's Codex108+ * app-server homes, so a thread started in either is found here.109+ */110+// ponytail: honors CODEX_HOME only; a codex instance configured with a custom111+// homePath would need that instance's CodexHomeLayout threaded in instead.112+const makeReadCodexRollout = (deps: {113+ readonly fileSystem: FileSystem.FileSystem;114+ readonly path: Path.Path;115+}) =>
- apps/server/src/orchestration-v2/SessionImportService.ts lines 628 to 634Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +484,21 @@484+ ON CONFLICT(thread_id) DO NOTHING485+ `.pipe(486+ Effect.mapError((cause) => importError("Could not record the imported session.", cause)),487+ );488+ return { threadId };489+ },490+ );491+492+ const syncImportedTranscript = Effect.fnUntraced(function* (threadId: ThreadId) {493+ const rows = yield* sql<SessionImportRow>`494+ SELECT thread_id, driver, provider_instance_id, external_id, source_modified_at495+ FROM orchestration_v2_session_imports496+ WHERE thread_id = ${threadId}497+ LIMIT 1498+ `;499+ const row = rows[0];500+ if (row === undefined) {501+ nonImportedThreadIds.add(threadId);502+ return;503+ }504+ const driver = row.driver;apps/web/src/components/ImportSessionDialog.tsx line 151Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +128,21 @@128+ const createdProjectId = newProjectId();129+ const createResult = await createProject({130+ environmentId: projectRef.environmentId,131+ input: {132+ projectId: createdProjectId,133+ title: inferProjectTitleFromPath(session.workspaceRoot),134+ workspaceRoot: session.workspaceRoot,135+ defaultModelSelection: selectedOption.modelSelection,136+ },137+ });138+ if (createResult._tag === "Failure") {139+ return stopImporting(140+ failureMessage(createResult, `Could not add ${session.workspaceRoot} as a project.`),141+ );142+ }143+ projectId = createdProjectId;144+ session = { ...session, projectId: createdProjectId };145+ setResolved(session);146+ }147+148+ const importResult = await importSession({apps/server/src/orchestration-v2/ProjectionStore.ts line 728OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -725,4 +725,4 @@725725 readonly sourceRunOrdinal: number;726726 }): boolean {727727 if (input.itemRunId === null) {728- return input.historyOrigin === "v1_import";728+ return input.historyOrigin === "v1_import" || input.historyOrigin === "provider_import";apps/server/src/orchestration-v2/SessionImportService.ts lines 126 to 126OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +106,21 @@106+ * `$CODEX_HOME/sessions/**` (`~/.codex/sessions` by default). The sessions107+ * directory is shared between the user's own Codex CLI and T3's Codex108+ * app-server homes, so a thread started in either is found here.109+ */110+// ponytail: honors CODEX_HOME only; a codex instance configured with a custom111+// homePath would need that instance's CodexHomeLayout threaded in instead.112+const makeReadCodexRollout = (deps: {113+ readonly fileSystem: FileSystem.FileSystem;114+ readonly path: Path.Path;115+}) =>116+ Effect.fnUntraced(function* (externalId: string) {117+ const { fileSystem, path } = deps;118+ const home = process.env["CODEX_HOME"]?.trim();119+ const root = path.join(120+ home !== undefined && home.length > 0 ? home : path.join(NodeOS.homedir(), ".codex"),121+ "sessions",122+ );123+ const names = yield* fileSystem124+ .readDirectory(root, { recursive: true })125+ .pipe(Effect.orElseSucceed(() => [] as Array<string>));126+ const relative = names.find((name) => name.endsWith(`${externalId}.jsonl`));apps/server/src/orchestration-v2/SessionImportService.ts line 568OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +548,21 @@548+ AND stream_id = ${threadId}549+ AND event_id LIKE ${`${SESSION_IMPORT_EVENT_PREFIX}:message:%`}550+ `;551+ const existingEventIds = new Set(existingEventRows.map((existing) => existing.event_id));552+553+ const missing = source.entries554+ .map((entry, index) => ({ entry, index }))555+ .filter(({ entry, index }) => {556+ const eventId = `${SESSION_IMPORT_EVENT_PREFIX}:message:${importedMessageId({557+ driver,558+ threadId,559+ index,560+ sourceId: entry.sourceId,561+ })}`;562+ if (existingEventIds.has(eventId)) return false;563+ // Turns T3 itself drove are already in the thread as native run564+ // items; the provider transcript echoes them back. Match by native565+ // id first, then by exact role+text as a backstop for entries whose566+ // native ids the adapter did not record.567+ if (knownNativeIds.has(entry.sourceId)) return false;568+ if (knownRunMessages.has(`${entry.role}\n${entry.text.trim()}`)) return false;apps/server/src/orchestration-v2/SessionImportService.ts line 452OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +432,21 @@432+ {433+ id: EventId.make(`${SESSION_IMPORT_EVENT_PREFIX}:thread:${threadId}:created`),434+ type: "thread.created",435+ threadId,436+ providerInstanceId: input.modelSelection.instanceId,437+ occurredAt: now,438+ payload: thread,439+ },440+ ...batch.events,441+ {442+ id: EventId.make(`${SESSION_IMPORT_EVENT_PREFIX}:provider-thread:${threadId}`),443+ type: "provider-thread.updated",444+ threadId,445+ driver: providerDriver,446+ providerInstanceId: input.modelSelection.instanceId,447+ occurredAt: now,448+ payload: providerThread,449+ },450+ ];451+452+ yield* insertPositions(threadId, batch.positions).pipe(
- apps/server/src/orchestration-v2/SessionImportService.ts lines 138 to 142OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +122,21 @@122+ const home =123+ instanceHome ??124+ (envHome !== undefined && envHome.length > 0125+ ? envHome126+ : path.join(NodeOS.homedir(), ".codex"));127+ const root = path.join(home, "sessions");128+ const names = yield* fileSystem129+ .readDirectory(root, { recursive: true })130+ .pipe(Effect.orElseSucceed(() => [] as Array<string>));131+ const relative = names.find((name) => name.endsWith(`${externalId}.jsonl`));132+ if (relative === undefined) {133+ return undefined;134+ }135+ const rolloutPath = path.isAbsolute(relative) ? relative : path.join(root, relative);136+ const readFailure = (cause: unknown) =>137+ importError(`Could not read the transcript for Codex thread '${externalId}'.`, cause);138+ const content = yield* fileSystem139+ .readFileString(rolloutPath)140+ .pipe(Effect.mapError(readFailure));141+ const stat = yield* fileSystem.stat(rolloutPath).pipe(Effect.mapError(readFailure));142+ const modifiedAtMs = Option.getOrUndefined(Option.map(stat.mtime, (mtime) => mtime.getTime()));apps/server/src/orchestration-v2/SessionImportService.ts line 128OutdatedResolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +108,21 @@108+ * Locates and reads the rollout transcript for a Codex thread id under109+ * `<codex home>/sessions/**`. The home comes from the instance's resolved110+ * home layout when available (its continuation key is `codex:home:<path>`),111+ * else `$CODEX_HOME`, else `~/.codex`. The sessions directory is shared112+ * between the user's own Codex CLI and T3's Codex app-server homes, so a113+ * thread started in either is found here.114+ */115+const makeReadCodexRollout = (deps: {116+ readonly fileSystem: FileSystem.FileSystem;117+ readonly path: Path.Path;118+}) =>119+ Effect.fnUntraced(function* (externalId: string, instanceHome: string | undefined) {120+ const { fileSystem, path } = deps;121+ const envHome = process.env["CODEX_HOME"]?.trim();122+ const home =123+ instanceHome ??124+ (envHome !== undefined && envHome.length > 0125+ ? envHome126+ : path.join(NodeOS.homedir(), ".codex"));127+ const root = path.join(home, "sessions");128+ const names = yield* fileSystem
- apps/server/src/orchestration-v2/SessionImportService.ts line 642Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +620,21 @@620+ SELECT thread_id, driver, provider_instance_id, external_id, source_modified_at621+ FROM orchestration_v2_session_imports622+ WHERE thread_id = ${threadId}623+ LIMIT 1624+ `;625+ const row = rows[0];626+ if (row === undefined) {627+ // Safe to cache negatively: import's write phase holds this thread's628+ // lock while inserting the row and clears the cache afterwards.629+ nonImportedThreadIds.add(threadId);630+ return;631+ }632+ const driver = row.driver;633+ if (!isImportableSessionDriver(driver)) {634+ return;635+ }636+ const projection = yield* projectionStore.getThreadProjection(threadId);637+ // Never interleave a sync with a live provider turn: the transcript is638+ // mid-write and the projection is about to receive the same content as639+ // native run items.640+ const hasActiveRun = projection.runs.some(
- apps/server/src/orchestration-v2/SessionImportService.ts line 693Resolvedby Bil0000(GitHub profile, opens in a new tab)@@ -0,0 +671,21 @@671+ // user genuinely repeating the same prompt in the CLI still imports.672+ const knownRunMessageCounts = new Map<string, number>();673+ for (const message of projection.messages) {674+ if (message.runId === null) continue;675+ const key = `${message.role}\n${message.text.trim()}`;676+ knownRunMessageCounts.set(key, (knownRunMessageCounts.get(key) ?? 0) + 1);677+ }678+ const existingEventRows = yield* sql<{ readonly event_id: string }>`679+ SELECT event_id680+ FROM orchestration_events681+ WHERE application_event_version = 2682+ AND aggregate_kind = 'thread'683+ AND stream_id = ${threadId}684+ AND event_id LIKE ${`${SESSION_IMPORT_EVENT_PREFIX}:%`}685+ `;686+ const existingEventIds = new Set(existingEventRows.map((existing) => existing.event_id));687+688+ const missing = source.entries689+ .map((entry, index) => ({ entry, index }))690+ .filter(({ entry, index }) => {691+ if (existingEventIds.has(importedEntryEventId({ driver, threadId, index, entry }))) {
github-actions[bot](GitHub profile, opens in a new tab) removed labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge closed this
Sign in to join this conversation.
Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
03f2d775-30e0-4dcb-9164-f8d6822ba669You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share