feat(web): import recent Codex and Claude threads during onboarding #8066
Mergedt3dotgg(GitHub profile, opens in a new tab)merged 7 commits into
t3code/overhaul-onboarding-flow fromrefs/pull/8066/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/project/AgentSessionScanner.ts line 870Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -522,4 +745,14 @@522745 };523746 });524747525- return AgentSessionScanner.of({ scan });748+ const recentThreads: AgentSessionScanner["Service"]["recentThreads"] = Effect.fn(749+ "AgentSessionScanner.recentThreads",750+ )(function* (workspaceRoot) {751+ const root = path.resolve(expandHomePath(workspaceRoot));752+ const realRoot = yield* fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root));753+ const normalizedRoot = normalizeProjectPathForComparison(realRoot);754+ const cutoffMs = DateTime.toEpochMillis(yield* DateTime.now) - RECENT_THREAD_WINDOW_MS;755+ const threads: Array<AgentSessionThread> = [];756+ const importedSessions = new Set<string>();757+758+ const candidates = cachedCandidates ?? (yield* collectCandidates());apps/server/src/orchestration/decider.ts line 1360Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -1281,0 +1292,21 @@1292+ ...(yield* withEventBase({1293+ aggregateKind: "thread",1294+ aggregateId: command.threadId,1295+ occurredAt: message.createdAt,1296+ commandId: command.commandId,1297+ metadata: { historyImport: true },1298+ })),1299+ type: "thread.message-sent",1300+ payload: {1301+ threadId: command.threadId,1302+ messageId: message.messageId,1303+ role: message.role,1304+ text: message.text,1305+ turnId: null,1306+ streaming: false,1307+ createdAt: message.createdAt,1308+ updatedAt: message.createdAt,1309+ },1310+ });1311+ }1312+ return events;@@ -1957,3 +1963,16 @@19571963 observeRpcEffect(WS_METHODS.agentSessionsScan, agentSessionScanner.scan, {19581964 "rpc.aggregate": "workspace",19591965 }),1966+ [WS_METHODS.agentSessionsImport]: (input) =>1967+ observeRpcEffect(1968+ WS_METHODS.agentSessionsImport,1969+ Option.match(providerSessionDirectory, {1970+ onNone: () =>1971+ Effect.fail(1972+ new AgentSessionScanError({1973+ operation: "read-projects",1974+ cause: new Error("Provider session storage is not available."),1975+ }),1976+ ),1977+ onSome: (directory) =>1978+ importRecentAgentThreads(input).pipe(apps/web/src/components/onboarding/WelcomeWizard.tsx line 1023OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1018,3 +1020,4 @@10181020 if (result._tag === "Success") {10191021 imported += 1;10201022 importedPaths.add(candidate.path);1023+ await importThreads({apps/server/src/orchestration/decider.ts line 1336Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -1281,0 +1287,21 @@1287+ });1288+1289+ const events: Array<PlannedOrchestrationEvent> = [];1290+ for (const message of command.messages) {1291+ events.push({1292+ ...(yield* withEventBase({1293+ aggregateKind: "thread",1294+ aggregateId: command.threadId,1295+ occurredAt: message.createdAt,1296+ commandId: command.commandId,1297+ metadata: { historyImport: true },1298+ })),1299+ type: "thread.message-sent",1300+ payload: {1301+ threadId: command.threadId,1302+ messageId: message.messageId,1303+ role: message.role,1304+ text: message.text,1305+ turnId: null,1306+ streaming: false,1307+ createdAt: message.createdAt,apps/server/src/project/AgentSessionScanner.ts line 623OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -412,2 +622,2 @@412622 const homeKey = `${source}\0${normalizeProjectPathForComparison(realHomePath)}`;413623 if (scannedHomes.has(homeKey)) continue;
- apps/server/src/ws.ts lines 1969 to 1976OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -1957,3 +1963,14 @@19571963 observeRpcEffect(WS_METHODS.agentSessionsScan, agentSessionScanner.scan, {19581964 "rpc.aggregate": "workspace",19591965 }),1966+ [WS_METHODS.agentSessionsImport]: (input) =>1967+ observeRpcEffect(1968+ WS_METHODS.agentSessionsImport,1969+ Option.match(providerSessionDirectory, {1970+ onNone: () =>1971+ Effect.fail(1972+ new AgentSessionScanError({1973+ operation: "read-projects",1974+ cause: new Error("Provider session storage is not available."),1975+ }),1976+ ),
- apps/server/src/project/AgentSessionImporter.ts line 89OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +69,21 @@69+ provider,70+ providerInstanceId: thread.providerInstanceId,71+ status: "stopped",72+ runtimeMode: DEFAULT_RUNTIME_MODE,73+ resumeCursor:74+ thread.source === "codex"75+ ? { threadId: thread.providerSessionId }76+ : { threadId, resume: thread.providerSessionId },77+ runtimePayload: { cwd: input.workspaceRoot },78+ });79+80+ return true;81+ }).pipe(82+ Effect.catch((cause) =>83+ Effect.logWarning("Could not import an agent session", {84+ provider: thread.source,85+ sessionId: thread.providerSessionId,86+ cause,87+ }).pipe(Effect.as(false)),88+ ),89+ );apps/web/src/components/onboarding/WelcomeWizard.tsx line 1032OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -1018,3 +1020,13 @@10181020 if (result._tag === "Success") {10191021 imported += 1;10201022 importedPaths.add(candidate.path);1023+ await importThreads({1024+ environmentId,1025+ input: { projectId, workspaceRoot: candidate.path },1026+ });1027+ if (1028+ importGeneration !== importGenerationRef.current ||1029+ importedPaths !== importedPathsRef.current1030+ ) {1031+ return;1032+ }
- apps/server/src/project/AgentSessionImporter.ts line 54OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +34,21 @@34+ );35+ const provider = ProviderDriverKind.make(thread.source);36+ const model = thread.model ?? DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;37+38+ yield* engine.dispatch({39+ type: "thread.create",40+ commandId: CommandId.make(`agent-session:create:${threadId}`),41+ threadId,42+ projectId: input.projectId,43+ title: thread.title,44+ modelSelection: { instanceId: thread.providerInstanceId, model },45+ runtimeMode: DEFAULT_RUNTIME_MODE,46+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,47+ branch: null,48+ worktreePath: null,49+ createdAt: thread.createdAt,50+ });51+52+ yield* engine.dispatch({53+ type: "thread.history.import",54+ commandId: CommandId.make(`agent-session:history:${threadId}`),
- apps/server/src/project/AgentSessionScanner.ts lines 183 to 183OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +163,21 @@163+ .map((block) => block.text?.trim() ?? "")164+ .filter((text) => text.length > 0)165+ .join("\n");166+}167+168+function normalizeTimestamp(value: string | undefined, fallback: string): string {169+ if (value === undefined) return fallback;170+ const parsed = DateTime.make(value);171+ return Option.isSome(parsed) ? DateTime.formatIso(parsed.value) : fallback;172+}173+174+/** Codex records injected workspace context as user input even though it is not conversation text. */175+function visibleCodexUserText(value: string): string {176+ return value177+ .replaceAll(/<environment_context>[\s\S]*?<\/environment_context>/gu, "")178+ .replaceAll(/<user_instructions>[\s\S]*?<\/user_instructions>/gu, "")179+ .replaceAll(180+ /# AGENTS\.md instructions for[^\r\n]*\s*<INSTRUCTIONS>[\s\S]*?<\/INSTRUCTIONS>/gu,181+ "",182+ )183+ .trim();apps/server/src/project/AgentSessionScanner.ts line 267OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +247,21 @@247+ record.type !== "response_item" ||248+ record.payload?.type !== "message" ||249+ (record.payload.role !== "user" && record.payload.role !== "assistant")250+ ) {251+ continue;252+ }253+254+ const extractedText = extractText(record.payload.content);255+ const text =256+ record.payload.role === "user" ? visibleCodexUserText(extractedText) : extractedText;257+ if (text.length === 0) continue;258+ messages.push({259+ role: record.payload.role,260+ text,261+ createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),262+ codexResponseUser: record.payload.role === "user",263+ });264+ }265+266+ const visibleMessages = messages267+ .filter((message) => !hasExplicitCodexUserMessages || !message.codexResponseUser)
- apps/web/src/components/onboarding/WelcomeWizard.tsx line 1019Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -967,0 +974,21 @@974+ const result = await createProject({975+ environmentId,976+ input: {977+ projectId,978+ title: candidate.title,979+ workspaceRoot: candidate.path,980+ createWorkspaceRootIfMissing: false,981+ defaultModelSelection,982+ },983+ });984+ if (985+ importGeneration !== importGenerationRef.current ||986+ importedPaths !== importedPathsRef.current987+ ) {988+ return;989+ }990+ if (result._tag !== "Success") continue;991+ createdProjectIds.set(candidate.path, projectId);992+ }993+994+ const threadImportResult = await importThreads({apps/web/src/components/onboarding/WelcomeWizard.tsx line 1031Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -968,16 +994,13 @@994+ const threadImportResult = await importThreads({968995 environmentId,969- input: {970- projectId: newProjectId(),971- title: candidate.title,972- workspaceRoot: candidate.path,973- createWorkspaceRootIfMissing: false,974- defaultModelSelection,975- },996+ input: { projectId, workspaceRoot: candidate.path },976997 });977998 if (978999 importGeneration !== importGenerationRef.current ||9791000 importedPaths !== importedPathsRef.current9801001 ) {9811002 return;9821003 }983- if (result._tag === "Success") {1004+ if (1005+ threadImportResult._tag === "Success" &&1006+ (threadImportResult.value.importedCount > 0 || threadImportResult.value.skippedCount === 0)apps/server/src/project/AgentSessionImporter.ts line 42OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +22,21 @@22+) {23+ const scanner = yield* AgentSessionScanner.AgentSessionScanner;24+ const engine = yield* OrchestrationEngine.OrchestrationEngineService;25+ const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;26+ const threads = yield* scanner.recentThreads(input.workspaceRoot);27+ let importedCount = 0;28+ let skippedCount = 0;29+30+ for (const thread of threads) {31+ const imported = yield* Effect.gen(function* () {32+ const threadId = ThreadId.make(33+ `import:${thread.providerInstanceId}:${thread.providerSessionId}`,34+ );35+ const provider = ProviderDriverKind.make(thread.source);36+ const model = thread.model ?? DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;37+38+ yield* engine.dispatch({39+ type: "thread.create",40+ commandId: CommandId.make(`agent-session:create:${threadId}`),41+ threadId,42+ projectId: input.projectId,apps/server/src/orchestration/decider.ts line 1319Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -1282,3 +1289,12 @@12821289 };12831290 }128412911292+ case "thread.history.import": {1293+ yield* requireThread({1294+ readModel,1295+ command,1296+ threadId: command.threadId,1297+ });1298+1299+ const events: Array<PlannedOrchestrationEvent> = [];1300+ for (const message of command.messages) {packages/contracts/src/agentSessions.ts line 43OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -33,3 +38,6 @@3338 });3439 export type AgentSessionScanResult = typeof AgentSessionScanResult.Type;354041+export const AgentSessionImportInput = Schema.Struct({42+ projectId: ProjectId,43+ workspaceRoot: TrimmedNonEmptyString,apps/server/src/project/AgentSessionScanner.ts line 271OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -89,0 +251,21 @@251+ continue;252+ }253+254+ const extractedText = extractText(record.payload.content);255+ const text =256+ record.payload.role === "user" ? visibleCodexUserText(extractedText) : extractedText;257+ if (text.length === 0) continue;258+ messages.push({259+ role: record.payload.role,260+ text,261+ createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),262+ codexResponseUser: record.payload.role === "user",263+ });264+ }265+266+ const visibleMessages = messages267+ .filter((message) => !hasExplicitCodexUserMessages || !message.codexResponseUser)268+ .map(({ codexResponseUser: _codexResponseUser, ...message }) => message);269+ const firstUserMessage = visibleMessages.find((message) => message.role === "user");270+ if (providerSessionId.trim().length === 0 || firstUserMessage === undefined) return null;271+ const latestMessages = visibleMessages.slice(-MAX_IMPORTED_MESSAGES);apps/server/src/project/AgentSessionScanner.ts line 226OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -89,0 +206,21 @@206+ if (input.source === "claudeAgent") {207+ if (record.sessionId?.trim()) providerSessionId = record.sessionId.trim();208+ if (record.aiTitle?.trim()) title = record.aiTitle.trim();209+ if (record.message?.model?.trim()) model = record.message.model.trim();210+ if (record.isSidechain === true || (record.type !== "user" && record.type !== "assistant")) {211+ continue;212+ }213+214+ const text = extractText(record.message?.content);215+ if (text.length === 0) continue;216+ messages.push({217+ role: record.type,218+ text,219+ createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),220+ codexResponseUser: false,221+ });222+ continue;223+ }224+225+ if (record.type === "session_meta") {226+ providerSessionId =apps/server/src/orchestration/decider.ts line 1334Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -1284,0 +1295,21 @@1295+ command,1296+ threadId: command.threadId,1297+ });1298+1299+ const events: Array<PlannedOrchestrationEvent> = [];1300+ for (const message of command.messages) {1301+ events.push({1302+ ...(yield* withEventBase({1303+ aggregateKind: "thread",1304+ aggregateId: command.threadId,1305+ occurredAt: message.createdAt,1306+ commandId: command.commandId,1307+ metadata: { historyImport: true },1308+ })),1309+ type: "thread.message-sent",1310+ payload: {1311+ threadId: command.threadId,1312+ messageId: message.messageId,1313+ role: message.role,1314+ text: message.text,1315+ turnId: null,
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/project/AgentSessionImporter.ts lines 63 to 77OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +57,21 @@57+ );58+ const provider = ProviderDriverKind.make(thread.source);59+ const model = thread.model ?? DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;60+ const existingThread = yield* snapshots.getThreadDetailById(threadId);61+ const existingBinding = yield* directory.getBinding(threadId);62+63+ if (64+ thread.source === "claudeAgent" &&65+ !CLAUDE_SESSION_ID_PATTERN.test(thread.providerSessionId)66+ ) {67+ return yield* new OrchestrationCommandInvariantError({68+ commandType: "agentSessions.import",69+ detail: `Claude session '${thread.providerSessionId}' cannot be resumed.`,70+ });71+ }72+73+ if (Option.isSome(existingThread) && existingThread.value.projectId !== input.projectId) {74+ return yield* new OrchestrationCommandInvariantError({75+ commandType: "agentSessions.import",76+ detail: `Imported thread '${threadId}' already belongs to project '${existingThread.value.projectId}'.`,77+ });
- apps/server/src/project/AgentSessionImporter.ts line 49OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +29,21 @@29+/** Import recent transcript text and persist the cursor needed to resume its provider session. */30+export const importRecentAgentThreads = Effect.fn("importRecentAgentThreads")(function* (31+ input: AgentSessionImportInput,32+) {33+ const scanner = yield* AgentSessionScanner.AgentSessionScanner;34+ const engine = yield* OrchestrationEngine.OrchestrationEngineService;35+ const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;36+ const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;37+ const crypto = yield* Crypto.Crypto;38+ const project = yield* snapshots.getProjectShellById(input.projectId).pipe(39+ Effect.mapError((cause) => new AgentSessionScanError({ operation: "read-projects", cause })),40+ Effect.flatMap(41+ Option.match({42+ onNone: () =>43+ Effect.fail(new AgentSessionImportProjectNotFoundError({ projectId: input.projectId })),44+ onSome: Effect.succeed,45+ }),46+ ),47+ );48+ const workspaceRoot = project.workspaceRoot;49+ const threads = yield* scanner.recentThreads(workspaceRoot);apps/server/src/project/AgentSessionScanner.ts line 850OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -525,0 +830,21 @@830+ const importedSessions = new Set<string>();831+832+ const candidates = cachedCandidates ?? (yield* collectCandidates());833+ cachedCandidates = candidates;834+835+ for (const candidate of candidates) {836+ const expanded = expandHomePath(candidate.cwd.trim());837+ if (!path.isAbsolute(expanded)) continue;838+ const resolved = path.resolve(expanded);839+ const realCandidate = yield* fileSystem840+ .realPath(resolved)841+ .pipe(Effect.orElseSucceed(() => resolved));842+ if (normalizeProjectPathForComparison(realCandidate) !== normalizedRoot) continue;843+844+ for (const transcript of candidate.transcripts) {845+ if (transcript.mtimeMs === null || transcript.mtimeMs < cutoffMs) continue;846+ const stats = yield* statOption(transcript.filePath);847+ if (Option.isNone(stats) || stats.value.size > BigInt(MAX_IMPORTED_TRANSCRIPT_BYTES)) {848+ continue;849+ }850+ const contents = yield* fileSystem
- apps/web/src/components/onboarding/WelcomeWizard.tsx line 1039Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -975,11 +1021,19 @@975- },1021+ input: { projectId },9761022 });9771023 if (9781024 importGeneration !== importGenerationRef.current ||9791025 importedPaths !== importedPathsRef.current9801026 ) {9811027 return;9821028 }983- if (result._tag === "Success") {1029+ if (1030+ threadImportResult._tag === "Success" &&1031+ (threadImportResult.value.importedCount > 0 || threadImportResult.value.skippedCount === 0)1032+ ) {9841033 imported += 1;9851034 importedPaths.add(candidate.path);1035+ } else if (1036+ threadImportResult._tag !== "Success" &&1037+ !isAtomCommandInterrupted(threadImportResult)1038+ ) {1039+ projectAttempts.delete(candidate.path);
- apps/server/src/project/AgentSessionImporter.ts line 151Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +131,21 @@131+132+ const hasImportedHistory = Option.isSome(existingThread)133+ ? existingThread.value.messages.some((message) =>134+ isImportedAgentSessionMessageId(message.id),135+ )136+ : false;137+ if (!hasImportedHistory) {138+ yield* engine.dispatch({139+ type: "thread.history.import",140+ commandId: CommandId.make(yield* crypto.randomUUIDv4),141+ threadId,142+ messages: thread.messages.map((message, index) => ({143+ messageId: MessageId.make(`${threadId}:${String(index).padStart(6, "0")}`),144+ role: message.role,145+ text: message.text,146+ createdAt: message.createdAt,147+ })),148+ });149+ }150+151+ if (Option.isNone(existingBinding)) {
t3dotgg(GitHub profile, opens in a new tab) 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:
ea1d009b-29f9-4179-964a-5fbd7691ab25You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Comment `@coderabbitai help` to get the list of available commands.