Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(imports): add ChatGPT conversation export support

AoHanBeid0f4875e2ce7
diff --git a/README.md b/README.md
index 5e484cfd7..577c323b7 100644
--- a/README.md
+++ b/README.md
@@ -693,7 +693,7 @@ My Agents turns other agents into context for DeepTutor, and does two distinct t
<img src="assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Consulting a Claude Code subagent live" width="900">
</div>
-**Import past conversations** — bring in your existing Claude Code and Codex history as named, searchable, resumable agents. Choose Claude history by project / working directory and Codex history by calendar date; refresh re-syncs that scope and pulls in new conversations. Reference one from a Chat turn via `+` → My Agents, and DeepTutor reads it as a third-party transcript — it stays *their* conversation, not DeepTutor's own voice.
+**Import past conversations** — bring in your existing ChatGPT, Claude Code, and Codex history as searchable, resumable conversations. Select `conversations.json` from an official ChatGPT data export for a safe, idempotent snapshot import, choose Claude history by project / working directory, or choose Codex history by calendar date. Folder-based agents remain refreshable so their selected scope can pull in new conversations. Reference one from a Chat turn via `+` → My Agents, and DeepTutor reads it as a third-party transcript — it stays *their* conversation, not DeepTutor's own voice.
</details>
diff --git a/deeptutor/api/routers/imports.py b/deeptutor/api/routers/imports.py
index 1547fa43e..a0e7a58a9 100644
--- a/deeptutor/api/routers/imports.py
+++ b/deeptutor/api/routers/imports.py
@@ -1,11 +1,11 @@
"""
-Import chat histories from external coding CLIs (Claude Code, Codex) into the
-user's learning space as normal, re-openable sessions.
+Import chat histories from ChatGPT exports and external coding CLIs (Claude
+Code, Codex) into the user's learning space as normal, re-openable sessions.
-Reading the user's local ``~/.claude`` / ``~/.codex`` happens in the browser
-(File System Access API) — those files live on the user's machine, not the
-server. The browser normalizes each conversation to the small JSON shape below
-and POSTs it here; this router only validates and persists. Imported sessions
+Reading the user's local ``~/.claude`` / ``~/.codex`` or ChatGPT export happens
+in the browser — those files live on the user's machine, not the server. The
+browser normalizes each conversation to the small JSON shape below and POSTs
+it here; this router only validates and persists. Imported sessions
share the session tables with native chats (so the chat loop can re-open and
continue them) but carry an ``imported_`` id prefix that keeps them in their
own Space category. Re-importing the same folder is idempotent (dedup by id).
@@ -30,7 +30,7 @@ router = APIRouter()
# Browser adapters only emit these; reject anything else so a malformed payload
# can never seed an unsupported provider category.
-_ALLOWED_SOURCES = {"claude_code", "codex"}
+_ALLOWED_SOURCES = {"chatgpt", "claude_code", "codex"}
# Defensive ceilings — a single import request should never grow unbounded.
_MAX_SESSIONS_PER_REQUEST = 1000
diff --git a/tests/api/test_imports.py b/tests/api/test_imports.py
index 177a8f949..b0b4a8473 100644
--- a/tests/api/test_imports.py
+++ b/tests/api/test_imports.py
@@ -69,6 +69,7 @@ def test_source_validation_rejects_unknown() -> None:
def test_source_is_normalized_lowercase() -> None:
assert ChatHistoryImportRequest(source="Claude_Code", sessions=[]).source == ("claude_code")
+ assert ChatHistoryImportRequest(source="ChatGPT", sessions=[]).source == "chatgpt"
def test_import_endpoint_persists_and_dedups(store: SQLiteSessionStore) -> None:
diff --git a/web/components/space/ImportWizard.tsx b/web/components/space/ImportWizard.tsx
index ea8e5d919..89b9af576 100644
--- a/web/components/space/ImportWizard.tsx
+++ b/web/components/space/ImportWizard.tsx
@@ -1,10 +1,18 @@
"use client";
-import { useCallback, useMemo, useState, type ReactNode } from "react";
+import {
+ useCallback,
+ useMemo,
+ useRef,
+ useState,
+ type ChangeEvent,
+ type ReactNode,
+} from "react";
import {
AlertTriangle,
CheckCircle2,
Eye,
+ FileJson,
FolderInput,
FolderOpen,
Loader2,
@@ -13,12 +21,16 @@ import { useTranslation } from "react-i18next";
import Modal from "@/components/common/Modal";
import Button from "@/components/ui/Button";
import ScopePicker from "@/components/space/ScopePicker";
-import { importChatHistory } from "@/lib/imports-api";
+import {
+ importChatHistory,
+ importChatHistoryInBatches,
+} from "@/lib/imports-api";
import { newAgentId, saveAgent } from "@/lib/chat-import/agent-store";
import {
buildSelectGroups,
ImportScanError,
isFileSystemAccessSupported,
+ parseChatGptExportFile,
parseSessions,
pickAndScan,
selectionUnit,
@@ -49,6 +61,7 @@ export default function ImportWizard({
onImported,
}: ImportWizardProps) {
const { t, i18n } = useTranslation();
+ const chatGptFileRef = useRef<HTMLInputElement>(null);
const [phase, setPhase] = useState<Phase>("intro");
const [scan, setScan] = useState<ScanResult | null>(null);
const [name, setName] = useState("");
@@ -98,6 +111,37 @@ export default function ImportWizard({
}
}, []);
+ const runChatGptImport = useCallback(async (file: File) => {
+ setPhase("importing");
+ setProgress({ stage: "parsing", done: 0, total: 0 });
+ try {
+ const normalized = await parseChatGptExportFile(file, (done, total) =>
+ setProgress({ stage: "parsing", done, total }),
+ );
+ setProgress({ stage: "saving", done: 0, total: normalized.length });
+ const res = await importChatHistoryInBatches("chatgpt", normalized, {
+ onProgress: (done, total) =>
+ setProgress({ stage: "saving", done, total }),
+ });
+ setResult({ imported: res.imported, skipped: res.skipped });
+ setPhase("done");
+ } catch (err) {
+ setErrorCode(err instanceof ImportScanError ? err.code : "generic");
+ setPhase("error");
+ }
+ }, []);
+
+ const handleChatGptFile = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => {
+ const file = event.target.files?.[0];
+ // Selecting the same export again must still fire a change event after a
+ // failed or partial import.
+ event.target.value = "";
+ if (file) void runChatGptImport(file);
+ },
+ [runChatGptImport],
+ );
+
const toggleKey = useCallback((key: string) => {
setSelectedKeys((prev) => {
const next = new Set(prev);
@@ -161,7 +205,7 @@ export default function ImportWizard({
<Modal
isOpen
onClose={onClose}
- title={t("Add agent")}
+ title={t("Import conversations")}
titleIcon={titleIcon}
width="xl"
closeOnBackdrop={phase !== "importing"}
@@ -175,6 +219,7 @@ export default function ImportWizard({
canImport={selectedRefs.length > 0}
onCancel={onClose}
onPick={runScan}
+ onPickChatGpt={() => chatGptFileRef.current?.click()}
onImport={runImport}
onDone={onImported}
onRetry={() => setPhase("intro")}
@@ -182,6 +227,13 @@ export default function ImportWizard({
}
>
<div className="px-5 py-5">
+ <input
+ ref={chatGptFileRef}
+ type="file"
+ accept=".json,application/json"
+ className="hidden"
+ onChange={handleChatGptFile}
+ />
{phase === "intro" && <IntroView />}
{phase === "scanning" && (
<CenteredStatus
@@ -259,12 +311,12 @@ function IntroView() {
<div className="min-w-0 space-y-1">
<p className="text-[13px] leading-relaxed text-[var(--foreground)]">
{t(
- "Select your local .claude or .codex folder. DeepTutor reads it right here in your browser — nothing leaves your machine until you choose what to import.",
+ "Import a local Claude Code or Codex folder, or choose the conversations.json file from an official ChatGPT data export. DeepTutor parses it in your browser before saving the conversations you import.",
)}
</p>
<p className="text-[12px] leading-relaxed text-[var(--muted-foreground)]">
{t(
- "It auto-detects the tool, groups conversations by project, and lets you pick exactly what to bring in.",
+ "Folder imports remain refreshable agents. ChatGPT exports are one-time snapshots that can be imported again safely without duplicating conversations.",
)}
</p>
</div>
@@ -275,7 +327,7 @@ function IntroView() {
<AlertTriangle className="mt-px h-4 w-4 shrink-0" />
<span>
{t(
- "Your browser doesn't support folder access. Please use a Chromium-based browser (Chrome, Edge, Arc).",
+ "Your browser doesn't support folder access, but you can still import a ChatGPT JSON export.",
)}
</span>
</div>
@@ -363,11 +415,15 @@ function ErrorView({ code }: { code: ImportScanErrorCode | "generic" }) {
? t(
"This folder doesn't look like a .claude or .codex home. Please select the right folder.",
)
- : code === "unsupported_browser"
+ : code === "invalid_export"
? t(
- "Your browser doesn't support folder access. Please use a Chromium-based browser.",
+ "This file doesn't contain readable ChatGPT conversations. Select the conversations.json file from an official ChatGPT data export.",
)
- : t("Something went wrong while importing. Please try again.");
+ : code === "unsupported_browser"
+ ? t(
+ "Your browser doesn't support folder access. Please use a Chromium-based browser.",
+ )
+ : t("Something went wrong while importing. Please try again.");
return (
<CenteredStatus
icon={
@@ -414,6 +470,7 @@ function WizardFooter({
canImport,
onCancel,
onPick,
+ onPickChatGpt,
onImport,
onDone,
onRetry,
@@ -424,6 +481,7 @@ function WizardFooter({
canImport: boolean;
onCancel: () => void;
onPick: () => void;
+ onPickChatGpt: () => void;
onImport: () => void;
onDone: () => void;
onRetry: () => void;
@@ -432,7 +490,7 @@ function WizardFooter({
if (phase === "intro") {
return (
- <div className="flex items-center justify-end gap-2">
+ <div className="flex flex-wrap items-center justify-end gap-2">
<Button variant="ghost" size="sm" onClick={onCancel}>
{t("Cancel")}
</Button>
@@ -445,6 +503,14 @@ function WizardFooter({
>
{t("Select folder")}
</Button>
+ <Button
+ variant="primary"
+ size="sm"
+ icon={<FileJson className="h-4 w-4" />}
+ onClick={onPickChatGpt}
+ >
+ {t("Select ChatGPT export")}
+ </Button>
</div>
);
}
diff --git a/web/components/space/MyAgentsSection.tsx b/web/components/space/MyAgentsSection.tsx
index 461e331f8..86cab7871 100644
--- a/web/components/space/MyAgentsSection.tsx
+++ b/web/components/space/MyAgentsSection.tsx
@@ -274,7 +274,7 @@ export default function MyAgentsSection() {
icon={Bot}
title={t("Imported conversations")}
description={t(
- "Your Claude Code and Codex conversations as named agents — open one to keep chatting, edit what each imports, or refresh to pull in new conversations.",
+ "Import ChatGPT exports or connect Claude Code and Codex folders. Open any imported conversation to keep chatting.",
)}
action={
!isEmpty ? (
@@ -284,7 +284,7 @@ export default function MyAgentsSection() {
className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] shadow-sm transition-opacity hover:opacity-90"
>
<Plus className="h-3.5 w-3.5" />
- {t("Add agent")}
+ {t("Import conversations")}
</button>
) : null
}
@@ -656,7 +656,7 @@ function UngroupedCard({
}}
className="shrink-0 rounded-lg border border-[var(--border)]/50 px-2.5 py-1.5 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
>
- {t("Add agent")}
+ {t("Import conversations")}
</button>
</div>
);
@@ -675,7 +675,7 @@ function EmptyState({ onAdd }: { onAdd: () => void }) {
</h2>
<p className="mx-auto max-w-sm text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">
{t(
- "Add your Claude Code or Codex folder to bring its conversations in — then chat with them or refresh anytime.",
+ "Import a ChatGPT data export or add a Claude Code or Codex folder, then open any conversation to continue it in DeepTutor.",
)}
</p>
</div>
@@ -685,7 +685,7 @@ function EmptyState({ onAdd }: { onAdd: () => void }) {
className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-4 py-2 text-[12.5px] font-medium text-[var(--background)] shadow-sm transition-opacity hover:opacity-90"
>
<Plus className="h-3.5 w-3.5" />
- {t("Add agent")}
+ {t("Import conversations")}
</button>
</section>
);
diff --git a/web/lib/chat-import/chatgpt.ts b/web/lib/chat-import/chatgpt.ts
new file mode 100644
index 000000000..1b24f6a96
--- /dev/null
+++ b/web/lib/chat-import/chatgpt.ts
@@ -0,0 +1,257 @@
+import { deriveTitle } from "./shared";
+import {
+ ImportScanError,
+ type NormalizedMessage,
+ type NormalizedSession,
+} from "./types";
+
+type UnknownRecord = Record<string, unknown>;
+
+interface ChatGptNode {
+ id: string;
+ parent: string | null;
+ children: string[];
+ message: UnknownRecord | null;
+}
+
+interface ChatGptConversation {
+ id: string;
+ title: string;
+ createTime: number;
+ updateTime: number;
+ currentNode: string;
+ mapping: Map<string, ChatGptNode>;
+}
+
+const HIDDEN_CONTENT_TYPES = new Set([
+ "computer_initialize_state",
+ "model_editable_context",
+ "thoughts",
+ "tether_browsing_display",
+ "user_editable_context",
+]);
+
+function record(value: unknown): UnknownRecord | null {
+ return value !== null && typeof value === "object" && !Array.isArray(value)
+ ? (value as UnknownRecord)
+ : null;
+}
+
+function text(value: unknown): string {
+ return typeof value === "string" ? value.trim() : "";
+}
+
+function epochSeconds(value: unknown, fallback = 0): number {
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
+ return fallback;
+ }
+ // Official exports use seconds, but accepting milliseconds makes copied or
+ // transformed exports deterministic too.
+ return value > 10_000_000_000 ? value / 1000 : value;
+}
+
+function stringArray(value: unknown): string[] {
+ return Array.isArray(value)
+ ? value.filter((item): item is string => typeof item === "string")
+ : [];
+}
+
+function normalizeNode(id: string, value: unknown): ChatGptNode | null {
+ const row = record(value);
+ if (!row) return null;
+ return {
+ // Parent/child pointers reference the mapping key. Prefer it over the
+ // embedded message node id so transformed exports cannot break lineage.
+ id,
+ parent: text(row.parent) || null,
+ children: stringArray(row.children),
+ message: record(row.message),
+ };
+}
+
+function normalizeConversation(
+ value: unknown,
+ fallbackTimestamp: number,
+): ChatGptConversation | null {
+ const row = record(value);
+ if (!row) return null;
+ const id = text(row.id) || text(row.conversation_id);
+ const rawMapping = record(row.mapping);
+ if (!id || !rawMapping) return null;
+
+ const mapping = new Map<string, ChatGptNode>();
+ for (const [key, candidate] of Object.entries(rawMapping)) {
+ const node = normalizeNode(key, candidate);
+ if (node) mapping.set(node.id, node);
+ }
+ if (!mapping.size) return null;
+
+ const createTime = epochSeconds(row.create_time, fallbackTimestamp);
+ const updateTime = epochSeconds(row.update_time, createTime);
+ return {
+ id: id.slice(0, 256),
+ title: text(row.title),
+ createTime,
+ updateTime,
+ currentNode: text(row.current_node),
+ mapping,
+ };
+}
+
+function messageTimestamp(node: ChatGptNode): number {
+ return epochSeconds(node.message?.create_time, 0);
+}
+
+function terminalNode(conversation: ChatGptConversation): string {
+ if (
+ conversation.currentNode &&
+ conversation.mapping.has(conversation.currentNode)
+ ) {
+ return conversation.currentNode;
+ }
+
+ // Some redacted exports omit current_node. Choose the newest leaf so we
+ // still recover one coherent branch instead of interleaving siblings.
+ const leaves = [...conversation.mapping.values()].filter(
+ (node) => !node.children.some((child) => conversation.mapping.has(child)),
+ );
+ const candidates = leaves.length
+ ? leaves
+ : [...conversation.mapping.values()];
+ candidates.sort(
+ (a, b) =>
+ messageTimestamp(b) - messageTimestamp(a) || b.id.localeCompare(a.id),
+ );
+ return candidates[0]?.id ?? "";
+}
+
+function activePath(conversation: ChatGptConversation): ChatGptNode[] {
+ const path: ChatGptNode[] = [];
+ const seen = new Set<string>();
+ let cursor = terminalNode(conversation);
+ while (
+ cursor &&
+ !seen.has(cursor) &&
+ path.length <= conversation.mapping.size
+ ) {
+ seen.add(cursor);
+ const node = conversation.mapping.get(cursor);
+ if (!node) break;
+ path.push(node);
+ cursor = node.parent ?? "";
+ }
+ return path.reverse();
+}
+
+function partText(value: unknown): string {
+ if (typeof value === "string") return value.trim();
+ const item = record(value);
+ if (!item) return "";
+ return text(item.text) || text(item.content);
+}
+
+function messageContent(message: UnknownRecord): string {
+ const content = record(message.content);
+ if (!content) return "";
+ const contentType = text(content.content_type).toLowerCase();
+ if (HIDDEN_CONTENT_TYPES.has(contentType)) return "";
+
+ const parts = Array.isArray(content.parts) ? content.parts : [];
+ const rendered = parts.map(partText).filter(Boolean).join("\n\n").trim();
+ return rendered || text(content.text);
+}
+
+function normalizeMessage(node: ChatGptNode): NormalizedMessage | null {
+ const message = node.message;
+ if (!message) return null;
+ const author = record(message.author);
+ const role = text(author?.role).toLowerCase();
+ if (role !== "user" && role !== "assistant") return null;
+ const metadata = record(message.metadata);
+ if (metadata?.is_visually_hidden_from_conversation === true) return null;
+ const content = messageContent(message);
+ if (!content) return null;
+ const createdAt = epochSeconds(message.create_time, 0);
+ return {
+ role,
+ content,
+ ...(createdAt ? { created_at: createdAt } : {}),
+ };
+}
+
+function exportedConversations(payload: unknown): unknown[] {
+ if (Array.isArray(payload)) return payload;
+ const wrapper = record(payload);
+ return Array.isArray(wrapper?.conversations) ? wrapper.conversations : [];
+}
+
+export function parseChatGptExport(
+ payload: unknown,
+ fallbackTimestamp = 0,
+ onProgress?: (done: number, total: number) => void,
+): NormalizedSession[] {
+ const rows = exportedConversations(payload);
+ if (!rows.length) {
+ throw new ImportScanError(
+ "invalid_export",
+ "The selected file has no ChatGPT conversations",
+ );
+ }
+
+ const sessions: NormalizedSession[] = [];
+ const seenIds = new Set<string>();
+ rows.forEach((row, index) => {
+ const conversation = normalizeConversation(row, fallbackTimestamp);
+ if (conversation && !seenIds.has(conversation.id)) {
+ const messages = activePath(conversation)
+ .map(normalizeMessage)
+ .filter((message): message is NormalizedMessage => message !== null);
+ if (messages.length) {
+ const firstUser = messages.find((message) => message.role === "user");
+ const createdAt =
+ conversation.createTime ||
+ messages[0]?.created_at ||
+ fallbackTimestamp;
+ const updatedAt =
+ conversation.updateTime || messages.at(-1)?.created_at || createdAt;
+ sessions.push({
+ external_id: conversation.id,
+ title:
+ conversation.title.slice(0, 256) ||
+ deriveTitle(firstUser?.content ?? "") ||
+ "Imported conversation",
+ source_cwd: "",
+ created_at: createdAt,
+ updated_at: Math.max(createdAt, updatedAt),
+ messages,
+ });
+ seenIds.add(conversation.id);
+ }
+ }
+ onProgress?.(index + 1, rows.length);
+ });
+
+ if (!sessions.length) {
+ throw new ImportScanError(
+ "invalid_export",
+ "The selected file has no readable ChatGPT conversations",
+ );
+ }
+ return sessions.sort((a, b) => b.updated_at - a.updated_at);
+}
+
+export async function parseChatGptExportFile(
+ file: File,
+ onProgress?: (done: number, total: number) => void,
+): Promise<NormalizedSession[]> {
+ let payload: unknown;
+ try {
+ payload = JSON.parse(await file.text()) as unknown;
+ } catch {
+ throw new ImportScanError(
+ "invalid_export",
+ "The selected file is not valid JSON",
+ );
+ }
+ return parseChatGptExport(payload, file.lastModified / 1000, onProgress);
+}
diff --git a/web/lib/chat-import/index.ts b/web/lib/chat-import/index.ts
index 95f86de82..e6864d3df 100644
--- a/web/lib/chat-import/index.ts
+++ b/web/lib/chat-import/index.ts
@@ -7,6 +7,7 @@
*/
import { parseClaudeSession, scanClaude } from "./claude-code";
+export { parseChatGptExport, parseChatGptExportFile } from "./chatgpt";
import { parseCodexSession, scanCodex } from "./codex";
import { detectSource } from "./detect";
import { projectLabel } from "./shared";
diff --git a/web/lib/chat-import/shared.ts b/web/lib/chat-import/shared.ts
index 423fcc447..b3ac3fe95 100644
--- a/web/lib/chat-import/shared.ts
+++ b/web/lib/chat-import/shared.ts
@@ -6,6 +6,7 @@ import type { ImportSource } from "./types";
export const SOURCE_LABEL: Record<ImportSource, string> = {
claude_code: "Claude Code",
codex: "Codex",
+ chatgpt: "ChatGPT",
};
// Harness-injected context the user never typed — stripped so imported
diff --git a/web/lib/chat-import/types.ts b/web/lib/chat-import/types.ts
index 6dfb7cedb..20eb70827 100644
--- a/web/lib/chat-import/types.ts
+++ b/web/lib/chat-import/types.ts
@@ -6,8 +6,8 @@
* {@link NormalizedSession} shape that mirrors the backend Pydantic models.
*/
-/** Provider whose on-disk chat history we know how to read. */
-export type ImportSource = "claude_code" | "codex";
+/** Provider whose local folder or exported chat history we know how to read. */
+export type ImportSource = "claude_code" | "codex" | "chatgpt";
/**
* A conversation discovered during the scan pass — enough metadata to list and
@@ -85,9 +85,7 @@ export interface NormalizedSession {
}
export type ImportScanErrorCode =
- | "unsupported_browser"
- | "not_recognized"
- | "aborted";
+ "unsupported_browser" | "not_recognized" | "invalid_export" | "aborted";
export class ImportScanError extends Error {
code: ImportScanErrorCode;
diff --git a/web/lib/imports-api.ts b/web/lib/imports-api.ts
index 67ddb80b5..82bfb1731 100644
--- a/web/lib/imports-api.ts
+++ b/web/lib/imports-api.ts
@@ -45,6 +45,36 @@ export async function importChatHistory(
return data;
}
+/**
+ * Upload a large static export without crossing the backend's per-request
+ * session ceiling. Re-imports are idempotent, so a retry after a partial
+ * network failure safely skips batches that already landed.
+ */
+export async function importChatHistoryInBatches(
+ source: ImportSource,
+ sessions: NormalizedSession[],
+ options?: {
+ batchSize?: number;
+ onProgress?: (done: number, total: number) => void;
+ },
+): Promise<ImportResult> {
+ if (sessions.length === 0) throw new Error("No sessions to import");
+ const batchSize = Math.max(1, Math.min(1000, options?.batchSize ?? 100));
+ const combined: ImportResult = { imported: 0, skipped: 0, sessions: [] };
+ for (let start = 0; start < sessions.length; start += batchSize) {
+ const batch = sessions.slice(start, start + batchSize);
+ const result = await importChatHistory(source, batch);
+ combined.imported += result.imported;
+ combined.skipped += result.skipped;
+ combined.sessions.push(...result.sessions);
+ options?.onProgress?.(
+ Math.min(start + batch.length, sessions.length),
+ sessions.length,
+ );
+ }
+ return combined;
+}
+
export async function listImportedSessions(
limit = 200,
offset = 0,
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index ea72027d8..d258daf53 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -2328,6 +2328,12 @@
"Reading your folder…": "Reading your folder…",
"Finding projects and conversations.": "Finding projects and conversations.",
"No conversations found": "No conversations found",
+ "Import conversations": "Import conversations",
+ "Select ChatGPT export": "Select ChatGPT export",
+ "Import a local Claude Code or Codex folder, or choose the conversations.json file from an official ChatGPT data export. DeepTutor parses it in your browser before saving the conversations you import.": "Import a local Claude Code or Codex folder, or choose the conversations.json file from an official ChatGPT data export. DeepTutor parses it in your browser before saving the conversations you import.",
+ "Folder imports remain refreshable agents. ChatGPT exports are one-time snapshots that can be imported again safely without duplicating conversations.": "Folder imports remain refreshable agents. ChatGPT exports are one-time snapshots that can be imported again safely without duplicating conversations.",
+ "Your browser doesn't support folder access, but you can still import a ChatGPT JSON export.": "Your browser doesn't support folder access, but you can still import a ChatGPT JSON export.",
+ "This file doesn't contain readable ChatGPT conversations. Select the conversations.json file from an official ChatGPT data export.": "This file doesn't contain readable ChatGPT conversations. Select the conversations.json file from an official ChatGPT data export.",
"This folder has no readable chat history. Pick your .claude or .codex folder.": "This folder has no readable chat history. Pick your .claude or .codex folder.",
"Select your local .claude or .codex folder. DeepTutor reads it right here in your browser — nothing leaves your machine until you choose what to import.": "Select your local .claude or .codex folder. DeepTutor reads it right here in your browser — nothing leaves your machine until you choose what to import.",
"It auto-detects the tool, groups conversations by project, and lets you pick exactly what to bring in.": "It auto-detects the tool, groups conversations by project, and lets you pick exactly what to bring in.",
@@ -2352,6 +2358,8 @@
"Try again": "Try again",
"My Agents": "My Agents",
"Imported conversations": "Imported conversations",
+ "Import ChatGPT exports or connect Claude Code and Codex folders. Open any imported conversation to keep chatting.": "Import ChatGPT exports or connect Claude Code and Codex folders. Open any imported conversation to keep chatting.",
+ "Import a ChatGPT data export or add a Claude Code or Codex folder, then open any conversation to continue it in DeepTutor.": "Import a ChatGPT data export or add a Claude Code or Codex folder, then open any conversation to continue it in DeepTutor.",
"Agent": "Agent",
"Select a connected agent": "Select a connected agent",
"Consult Subagent": "Consult Subagent",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 702df3f39..f93205478 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -2328,6 +2328,12 @@
"Reading your folder…": "正在读取文件夹…",
"Finding projects and conversations.": "正在查找项目与对话。",
"No conversations found": "未找到对话",
+ "Import conversations": "导入对话",
+ "Select ChatGPT export": "选择 ChatGPT 导出文件",
+ "Import a local Claude Code or Codex folder, or choose the conversations.json file from an official ChatGPT data export. DeepTutor parses it in your browser before saving the conversations you import.": "导入本地 Claude Code 或 Codex 文件夹,或者选择 ChatGPT 官方数据导出中的 conversations.json 文件。DeepTutor 会先在浏览器中解析,再保存你导入的对话。",
+ "Folder imports remain refreshable agents. ChatGPT exports are one-time snapshots that can be imported again safely without duplicating conversations.": "文件夹导入会保留为可刷新的智能体;ChatGPT 导出是一次性快照,可安全地再次导入而不会产生重复对话。",
+ "Your browser doesn't support folder access, but you can still import a ChatGPT JSON export.": "你的浏览器不支持文件夹访问,但仍可导入 ChatGPT JSON 导出文件。",
+ "This file doesn't contain readable ChatGPT conversations. Select the conversations.json file from an official ChatGPT data export.": "该文件不包含可读取的 ChatGPT 对话。请选择 ChatGPT 官方数据导出中的 conversations.json 文件。",
"This folder has no readable chat history. Pick your .claude or .codex folder.": "该文件夹中没有可读取的聊天记录。请选择你的 .claude 或 .codex 文件夹。",
"Select your local .claude or .codex folder. DeepTutor reads it right here in your browser — nothing leaves your machine until you choose what to import.": "选择本地的 .claude 或 .codex 文件夹。DeepTutor 直接在浏览器中读取——在你选择导入内容之前,数据不会离开你的设备。",
"It auto-detects the tool, groups conversations by project, and lets you pick exactly what to bring in.": "它会自动识别工具、按项目归类对话,并让你精确选择要导入的内容。",
@@ -2352,6 +2358,8 @@
"Try again": "重试",
"My Agents": "我的智能体",
"Imported conversations": "导入的对话",
+ "Import ChatGPT exports or connect Claude Code and Codex folders. Open any imported conversation to keep chatting.": "导入 ChatGPT 数据,或连接 Claude Code 与 Codex 文件夹。打开任意已导入对话即可继续聊天。",
+ "Import a ChatGPT data export or add a Claude Code or Codex folder, then open any conversation to continue it in DeepTutor.": "导入 ChatGPT 数据导出,或添加 Claude Code、Codex 文件夹,然后打开任意对话并在 DeepTutor 中继续。",
"Agent": "智能体",
"Select a connected agent": "选择已连接的智能体",
"Consult Subagent": "咨询子代理",
diff --git a/web/tests/chat-import-chatgpt.spec.ts b/web/tests/chat-import-chatgpt.spec.ts
new file mode 100644
index 000000000..bfdcf1d58
--- /dev/null
+++ b/web/tests/chat-import-chatgpt.spec.ts
@@ -0,0 +1,167 @@
+import { File as NodeFile } from "node:buffer";
+
+import { describe, expect, it } from "vitest";
+
+import {
+ parseChatGptExport,
+ parseChatGptExportFile,
+} from "@/lib/chat-import/chatgpt";
+import { ImportScanError } from "@/lib/chat-import/types";
+
+function node(
+ id: string,
+ parent: string | null,
+ role: string,
+ content: unknown,
+ createdAt: number,
+ options?: { children?: string[]; hidden?: boolean },
+) {
+ return {
+ id,
+ parent,
+ children: options?.children ?? [],
+ message: {
+ id: `message-${id}`,
+ author: { role },
+ create_time: createdAt,
+ content: { content_type: "text", parts: [content] },
+ metadata: options?.hidden
+ ? { is_visually_hidden_from_conversation: true }
+ : {},
+ },
+ };
+}
+
+describe("parseChatGptExport", () => {
+ it("keeps only the active branch and visible user/assistant messages", () => {
+ const parsed = parseChatGptExport([
+ {
+ id: "conversation-1",
+ title: "Calculus review",
+ create_time: 100,
+ update_time: 140,
+ current_node: "a-current",
+ mapping: {
+ root: node("root", null, "system", "hidden prompt", 100, {
+ children: ["u1"],
+ }),
+ u1: node("u1", "root", "user", "Explain the chain rule", 110, {
+ children: ["a-old", "a-current"],
+ }),
+ "a-old": node("a-old", "u1", "assistant", "Old branch", 120),
+ "a-current": node(
+ "a-current",
+ "u1",
+ "assistant",
+ { text: "Differentiate the outer function first." },
+ 130,
+ ),
+ },
+ },
+ ]);
+
+ expect(parsed).toEqual([
+ {
+ external_id: "conversation-1",
+ title: "Calculus review",
+ source_cwd: "",
+ created_at: 100,
+ updated_at: 140,
+ messages: [
+ {
+ role: "user",
+ content: "Explain the chain rule",
+ created_at: 110,
+ },
+ {
+ role: "assistant",
+ content: "Differentiate the outer function first.",
+ created_at: 130,
+ },
+ ],
+ },
+ ]);
+ });
+
+ it("chooses the newest leaf when current_node is absent", () => {
+ const parsed = parseChatGptExport([
+ {
+ conversation_id: "conversation-2",
+ title: "",
+ mapping: {
+ user: node("user", null, "user", "Original question", 10, {
+ children: ["older", "newer"],
+ }),
+ older: node("older", "user", "assistant", "Older answer", 20),
+ newer: node("newer", "user", "assistant", "Newer answer", 30),
+ },
+ },
+ ]);
+
+ expect(parsed[0].title).toBe("Original question");
+ expect(parsed[0].messages.map((message) => message.content)).toEqual([
+ "Original question",
+ "Newer answer",
+ ]);
+ });
+
+ it("skips hidden, tool, and non-text media rows without breaking lineage", () => {
+ const parsed = parseChatGptExport([
+ {
+ id: "conversation-3",
+ current_node: "assistant",
+ mapping: {
+ user: node("user", null, "user", "Read this chart", 10, {
+ children: ["hidden"],
+ }),
+ hidden: node("hidden", "user", "assistant", "internal", 11, {
+ children: ["tool"],
+ hidden: true,
+ }),
+ tool: node("tool", "hidden", "tool", "tool output", 12, {
+ children: ["assistant"],
+ }),
+ assistant: node(
+ "assistant",
+ "tool",
+ "assistant",
+ "The trend rises.",
+ 13,
+ ),
+ },
+ },
+ ]);
+
+ expect(parsed[0].messages.map((message) => message.content)).toEqual([
+ "Read this chart",
+ "The trend rises.",
+ ]);
+ });
+
+ it("deduplicates repeated conversation ids", () => {
+ const conversation = {
+ id: "same-id",
+ current_node: "user",
+ mapping: { user: node("user", null, "user", "Keep once", 10) },
+ };
+ expect(parseChatGptExport([conversation, conversation])).toHaveLength(1);
+ });
+
+ it("rejects malformed JSON and exports without readable conversations", async () => {
+ const invalid = new NodeFile(["{"], "conversations.json");
+ await expect(
+ parseChatGptExportFile(invalid as unknown as File),
+ ).rejects.toMatchObject({
+ code: "invalid_export",
+ });
+
+ expect(() => parseChatGptExport({ conversations: [] })).toThrow(
+ ImportScanError,
+ );
+ expect(() =>
+ parseChatGptExport([
+ { id: "empty", current_node: "root", mapping: { root: {} } },
+ ]),
+ ).toThrow(/no readable ChatGPT conversations/i);
+ });
+});
diff --git a/web/tests/imports-api.spec.ts b/web/tests/imports-api.spec.ts
index 6d969bda0..c9d3d834c 100644
--- a/web/tests/imports-api.spec.ts
+++ b/web/tests/imports-api.spec.ts
@@ -1,6 +1,10 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { importChatHistory } from "@/lib/imports-api";
+import {
+ importChatHistory,
+ importChatHistoryInBatches,
+} from "@/lib/imports-api";
+import type { NormalizedSession } from "@/lib/chat-import/types";
describe("importChatHistory", () => {
afterEach(() => {
@@ -16,4 +20,59 @@ describe("importChatHistory", () => {
);
expect(fetchMock).not.toHaveBeenCalled();
});
+
+ it("uploads large static exports in bounded batches", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ imported: 2,
+ skipped: 0,
+ sessions: [
+ { external_id: "s1", imported: true },
+ { external_id: "s2", imported: true },
+ ],
+ }),
+ { status: 200 },
+ ),
+ )
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ imported: 0,
+ skipped: 1,
+ sessions: [{ external_id: "s3", imported: false }],
+ }),
+ { status: 200 },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const sessions = ["s1", "s2", "s3"].map(
+ (external_id): NormalizedSession => ({
+ external_id,
+ title: external_id,
+ source_cwd: "",
+ created_at: 1,
+ updated_at: 1,
+ messages: [{ role: "user", content: "hello" }],
+ }),
+ );
+ const progress: number[] = [];
+
+ const result = await importChatHistoryInBatches("chatgpt", sessions, {
+ batchSize: 2,
+ onProgress: (done) => progress.push(done),
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ const firstBody = JSON.parse(fetchMock.mock.calls[0][1].body as string);
+ const secondBody = JSON.parse(fetchMock.mock.calls[1][1].body as string);
+ expect(firstBody.source).toBe("chatgpt");
+ expect(firstBody.sessions).toHaveLength(2);
+ expect(secondBody.sessions).toHaveLength(1);
+ expect(progress).toEqual([2, 3]);
+ expect(result).toMatchObject({ imported: 2, skipped: 1 });
+ expect(result.sessions).toHaveLength(3);
+ });
});