The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
v2.5.0 Feature CC: chatbot-export importer (ChatGPT/Claude/Gemini)
purplee4ed7582cc53
diff --git a/src/components/import/ChatbotImporter.tsx b/src/components/import/ChatbotImporter.tsxnew file mode 100644index 00000000..41d10376--- /dev/null+++ b/src/components/import/ChatbotImporter.tsx@@ -0,0 +1,234 @@+// Feature CC v2.5.0 — Chatbot export importer (MikeS++ Discord 2026-05-27).+// User picks an export file (ChatGPT / Claude / Gemini, .json or .zip),+// we parse it, render the conversation list with checkboxes, and on+// "Import" we feed each selected conversation into the RAG pipeline as+// if the user had dropped a markdown file.+//+// Why RAG instead of memoryStore: RAG is the right surface for bulk+// transfer (potentially thousands of past Q+A turns). memoryStore is+// curated facts. The Settings copy steers the user accordingly.++import { useState } from 'react'+import { Upload, FileText, CheckCircle2, AlertTriangle, Loader2, X } from 'lucide-react'+import { parseExportFile, conversationToFile, type NormalisedConversation, type ChatbotPlatform } from '../../lib/parsers/chatbot-export'+import { useRAG } from '../../hooks/useRAG'+import { useChatStore } from '../../stores/chatStore'++const PLATFORM_LABEL: Record<ChatbotPlatform, string> = {+ chatgpt: 'ChatGPT',+ claude: 'Claude',+ gemini: 'Gemini',+ unknown: 'Unknown',+}++export function ChatbotImporter() {+ const conversationId = useChatStore(s => s.activeConversationId)+ const rag = useRAG(conversationId || undefined)+ const uploadDocument = rag.uploadDocument++ const [conversations, setConversations] = useState<NormalisedConversation[]>([])+ const [selected, setSelected] = useState<Set<string>>(new Set())+ const [parsing, setParsing] = useState(false)+ const [importing, setImporting] = useState(false)+ const [importProgress, setImportProgress] = useState<{ current: number; total: number } | null>(null)+ const [error, setError] = useState<string | null>(null)+ const [skipped, setSkipped] = useState(0)+ const [detectedPlatform, setDetectedPlatform] = useState<ChatbotPlatform>('unknown')+ const [doneCount, setDoneCount] = useState<number>(0)++ const handleFile = async (file: File) => {+ setParsing(true)+ setError(null)+ setConversations([])+ setSelected(new Set())+ setDoneCount(0)+ try {+ const result = await parseExportFile(file)+ setConversations(result.conversations)+ setSkipped(result.skipped)+ setDetectedPlatform(result.detectedPlatform)+ // Pre-select everything; user can deselect noisy ones.+ setSelected(new Set(result.conversations.map(c => c.id)))+ if (result.conversations.length === 0) {+ setError('No conversations found. The file may be in an unsupported format. Supported: ChatGPT conversations.json, Claude conversations.json, Gemini activity JSON.')+ }+ } catch (e) {+ setError(`Parse failed: ${e instanceof Error ? e.message : String(e)}`)+ } finally {+ setParsing(false)+ }+ }++ const onFileInput = (e: React.ChangeEvent<HTMLInputElement>) => {+ const f = e.target.files?.[0]+ if (f) handleFile(f)+ }++ const toggleSelection = (id: string) => {+ setSelected(prev => {+ const next = new Set(prev)+ if (next.has(id)) next.delete(id); else next.add(id)+ return next+ })+ }++ const selectAll = () => setSelected(new Set(conversations.map(c => c.id)))+ const selectNone = () => setSelected(new Set())++ const handleImport = async () => {+ if (!conversationId) {+ setError('Open or create a chat first — imports attach to whichever conversation is currently active in the chat view.')+ return+ }+ const toImport = conversations.filter(c => selected.has(c.id))+ if (toImport.length === 0) return+ setImporting(true)+ setImportProgress({ current: 0, total: toImport.length })+ setError(null)+ setDoneCount(0)+ let done = 0+ let failed: string[] = []+ for (const conv of toImport) {+ try {+ const file = conversationToFile(conv)+ await uploadDocument(file)+ done+++ } catch (e) {+ failed.push(`${conv.title}: ${e instanceof Error ? e.message : String(e)}`)+ }+ setImportProgress({ current: done + failed.length, total: toImport.length })+ setDoneCount(done)+ }+ setImporting(false)+ setImportProgress(null)+ if (failed.length > 0) {+ setError(`${done} imported, ${failed.length} failed:\n${failed.slice(0, 5).join('\n')}${failed.length > 5 ? `\n…+${failed.length - 5} more` : ''}`)+ }+ }++ const allSelected = conversations.length > 0 && selected.size === conversations.length+ const someSelected = selected.size > 0++ return (+ <div className="space-y-3">+ <div className="flex items-start gap-2.5 p-2.5 rounded-lg border border-blue-200 dark:border-blue-500/20 bg-blue-50 dark:bg-blue-500/[0.08] text-blue-900 dark:text-blue-200">+ <Upload size={14} className="mt-0.5 shrink-0" />+ <div className="text-[0.65rem] leading-relaxed">+ <strong>Import past conversations</strong> from ChatGPT, Claude, or Gemini exports. Each conversation lands in the active chat's RAG store — your local model can reference past turns just like any other document you upload. Stays on your machine.+ </div>+ </div>++ <div>+ <label className="block cursor-pointer">+ <input+ type="file"+ accept=".json,.zip,application/json,application/zip"+ onChange={onFileInput}+ disabled={parsing || importing}+ className="sr-only"+ />+ <div className={`flex items-center gap-2 px-3 py-2 rounded-lg border-2 border-dashed text-[0.7rem] ${+ parsing || importing+ ? 'border-white/8 text-gray-500 cursor-not-allowed'+ : 'border-white/15 hover:border-white/30 text-gray-300 hover:bg-white/[0.03]'+ }`}>+ {parsing ? <Loader2 size={14} className="animate-spin" /> : <FileText size={14} />}+ <span>+ {parsing ? 'Parsing…' : 'Choose export file (.json or .zip)'}+ </span>+ </div>+ </label>+ <div className="text-[0.55rem] text-gray-500 mt-1 leading-relaxed">+ ChatGPT: <code className="font-mono">conversations.json</code> from the official data export. Claude: <code className="font-mono">conversations.json</code> from Settings → Privacy → Export. Gemini: Google Takeout activity JSON.+ </div>+ </div>++ {error && (+ <div className="flex items-start gap-2 p-2 rounded border border-red-500/20 bg-red-500/[0.06] text-red-300">+ <AlertTriangle size={12} className="mt-0.5 shrink-0" />+ <span className="text-[0.6rem] whitespace-pre-wrap">{error}</span>+ <button onClick={() => setError(null)} className="text-red-400 hover:text-red-200 ml-auto"><X size={10} /></button>+ </div>+ )}++ {conversations.length > 0 && (+ <>+ <div className="flex items-center justify-between text-[0.6rem]">+ <span className="text-gray-400">+ Detected: <strong>{PLATFORM_LABEL[detectedPlatform]}</strong>+ {' · '}+ {conversations.length} conversation{conversations.length === 1 ? '' : 's'}+ {skipped > 0 ? ` · ${skipped} skipped` : ''}+ {' · '}+ {selected.size} selected+ </span>+ <div className="flex gap-2">+ <button+ onClick={allSelected ? selectNone : selectAll}+ className="text-gray-400 hover:text-white"+ disabled={importing}+ >+ {allSelected ? 'Select none' : 'Select all'}+ </button>+ </div>+ </div>++ <div className="space-y-1 max-h-80 overflow-y-auto pr-1 scrollbar-thin">+ {conversations.map(c => {+ const isOn = selected.has(c.id)+ return (+ <label+ key={c.id}+ className={`flex items-start gap-2 p-1.5 rounded border ${+ isOn ? 'border-white/15 bg-white/[0.04]' : 'border-white/5 hover:bg-white/[0.02]'+ } cursor-pointer`}+ >+ <input+ type="checkbox"+ checked={isOn}+ onChange={() => toggleSelection(c.id)}+ disabled={importing}+ className="mt-0.5"+ />+ <div className="flex-1 min-w-0">+ <div className="text-[0.65rem] text-gray-200 truncate">{c.title}</div>+ <div className="text-[0.55rem] text-gray-500">+ {c.messageCount} message{c.messageCount === 1 ? '' : 's'}+ {c.timestamp ? ` · ${new Date(c.timestamp).toLocaleDateString()}` : ''}+ </div>+ </div>+ </label>+ )+ })}+ </div>++ <div className="flex items-center gap-2 pt-1">+ <button+ onClick={handleImport}+ disabled={!someSelected || importing || !conversationId}+ className="px-3 py-1.5 rounded text-[0.7rem] font-medium bg-blue-500 hover:bg-blue-600 disabled:opacity-40 disabled:cursor-not-allowed text-white inline-flex items-center gap-1.5"+ >+ {importing ? <Loader2 size={12} className="animate-spin" /> : <Upload size={12} />}+ Import {selected.size} → RAG+ </button>+ {importProgress && (+ <span className="text-[0.6rem] text-gray-400">+ {importProgress.current} / {importProgress.total}+ </span>+ )}+ {!importing && doneCount > 0 && !error && (+ <span className="text-[0.6rem] text-green-400 inline-flex items-center gap-1">+ <CheckCircle2 size={10} /> {doneCount} imported+ </span>+ )}+ </div>+ {!conversationId && (+ <div className="text-[0.6rem] text-amber-300 italic">+ Open or create a chat first — imports attach to the active conversation's RAG store.+ </div>+ )}+ </>+ )}+ </div>+ )+}diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsxindex a13fc10b..6fcc7348 100644--- a/src/components/settings/SettingsPage.tsx+++ b/src/components/settings/SettingsPage.tsx@@ -13,6 +13,7 @@ import { getRecommendedAgentModels } from '../../lib/model-compatibility'import { MemorySettings } from './MemorySettings'import { RemoteAccessSettings } from './RemoteAccessSettings'import { HardwareSettings } from './HardwareSettings'+import { ChatbotImporter } from '../import/ChatbotImporter'import { ProviderSettings } from './ProviderConfig'import { PermissionSettings } from './PermissionSettings'import { MCPServerSettings } from './MCPServerSettings'@@ -759,6 +760,14 @@ export function SettingsPage() {<HardwareSettings /></Section>+ {/* Feature CC v2.5.0 — MikeS++ chatbot export importer. Parses+ ChatGPT / Claude / Gemini export JSON (or .zip), pre-selects+ every conversation, feeds the chosen ones into the active+ chat's RAG store. */}+ <Section title="Import past chatbot conversations">+ <ChatbotImporter />+ </Section>+<Section title="Image / Video Generation Timeouts"><div className="text-[0.6rem] text-gray-500 dark:text-gray-500 leading-relaxed pb-1.5">Maximum minutes a ComfyUI generation can run before LU aborts it. Bump these up if you run on iGPU or CPU only — a 1024px image on integrated graphics can take 30+ min.diff --git a/src/lib/__tests__/chatbot-export.test.ts b/src/lib/__tests__/chatbot-export.test.tsnew file mode 100644index 00000000..a815739d--- /dev/null+++ b/src/lib/__tests__/chatbot-export.test.ts@@ -0,0 +1,146 @@+// Feature CC v2.5.0 — chatbot export parser tests. Each schema fixture is a+// minimal real-world shape (verified against actual exports during the dev+// session) trimmed to one or two messages so the tests stay readable.++import { describe, it, expect } from 'vitest'+import { parseJsonText, detectPlatform } from '../parsers/chatbot-export'++const chatgptFixture = JSON.stringify([+ {+ title: 'Recipes for pasta',+ create_time: 1700000000.0,+ update_time: 1700001000.0,+ mapping: {+ root: { id: 'root', message: null, parent: null, children: ['u1'] },+ u1: {+ id: 'u1',+ message: {+ id: 'u1',+ author: { role: 'user' },+ create_time: 1700000010.0,+ content: { content_type: 'text', parts: ['Got pasta recipes?'] },+ },+ parent: 'root',+ children: ['a1'],+ },+ a1: {+ id: 'a1',+ message: {+ id: 'a1',+ author: { role: 'assistant' },+ create_time: 1700000020.0,+ content: { content_type: 'text', parts: ['Carbonara, cacio e pepe, aglio e olio.'] },+ },+ parent: 'u1',+ children: [],+ },+ },+ },+])++const claudeFixture = JSON.stringify([+ {+ uuid: 'abc-123',+ name: 'JS array methods',+ created_at: '2026-05-01T10:00:00Z',+ updated_at: '2026-05-01T10:05:00Z',+ chat_messages: [+ { uuid: 'm1', text: 'Explain map vs forEach', sender: 'human', created_at: '2026-05-01T10:00:01Z' },+ { uuid: 'm2', text: 'map returns a new array, forEach returns undefined.', sender: 'assistant', created_at: '2026-05-01T10:00:30Z' },+ ],+ },+])++const geminiFixture = JSON.stringify([+ {+ header: 'Gemini Apps',+ title: 'Asked Gemini about quantum entanglement',+ time: '2026-04-12T15:23:00Z',+ messages: [+ { role: 'user', text: 'What is quantum entanglement?' },+ { role: 'assistant', text: 'Two particles linked such that one\'s state correlates with the other.' },+ ],+ },+])++describe('detectPlatform', () => {+ it('detects ChatGPT exports by the mapping field', () => {+ expect(detectPlatform(JSON.parse(chatgptFixture))).toBe('chatgpt')+ })+ it('detects Claude exports by the chat_messages field', () => {+ expect(detectPlatform(JSON.parse(claudeFixture))).toBe('claude')+ })+ it('detects Gemini exports by the Gemini Apps header', () => {+ expect(detectPlatform(JSON.parse(geminiFixture))).toBe('gemini')+ })+ it('falls back to unknown for foreign shapes', () => {+ expect(detectPlatform({ foo: 'bar' })).toBe('unknown')+ expect(detectPlatform([])).toBe('unknown')+ expect(detectPlatform(null)).toBe('unknown')+ })+})++describe('parseJsonText — ChatGPT', () => {+ it('extracts title + user + assistant turn in order', () => {+ const result = parseJsonText(chatgptFixture)+ expect(result.detectedPlatform).toBe('chatgpt')+ expect(result.conversations).toHaveLength(1)+ const c = result.conversations[0]+ expect(c.title).toBe('Recipes for pasta')+ expect(c.platform).toBe('chatgpt')+ expect(c.messageCount).toBe(2)+ expect(c.markdown).toContain('# Recipes for pasta')+ expect(c.markdown).toContain('**You**')+ expect(c.markdown).toContain('Got pasta recipes?')+ expect(c.markdown).toContain('**Assistant**')+ expect(c.markdown).toContain('Carbonara, cacio e pepe, aglio e olio.')+ })+ it('skips empty mapping conversations', () => {+ const empty = JSON.stringify([{ title: 'empty', mapping: {} }])+ const r = parseJsonText(empty)+ expect(r.conversations).toHaveLength(0)+ expect(r.skipped).toBeGreaterThan(0)+ })+})++describe('parseJsonText — Claude', () => {+ it('extracts the chat_messages array as markdown', () => {+ const result = parseJsonText(claudeFixture)+ expect(result.detectedPlatform).toBe('claude')+ expect(result.conversations).toHaveLength(1)+ const c = result.conversations[0]+ expect(c.title).toBe('JS array methods')+ expect(c.messageCount).toBe(2)+ expect(c.markdown).toContain('Explain map vs forEach')+ expect(c.markdown).toContain('map returns a new array')+ })+ it('skips conversations with no messages', () => {+ const empty = JSON.stringify([{ uuid: 'x', name: 'empty', chat_messages: [] }])+ const r = parseJsonText(empty)+ expect(r.conversations).toHaveLength(0)+ })+})++describe('parseJsonText — Gemini', () => {+ it('extracts the messages array when present', () => {+ const result = parseJsonText(geminiFixture)+ expect(result.detectedPlatform).toBe('gemini')+ expect(result.conversations).toHaveLength(1)+ const c = result.conversations[0]+ expect(c.markdown).toContain('quantum entanglement')+ expect(c.markdown).toContain('**You**')+ expect(c.markdown).toContain('**Assistant**')+ })+})++describe('parseJsonText — robustness', () => {+ it('returns an empty result for invalid JSON without throwing', () => {+ const r = parseJsonText('not actually json {')+ expect(r.conversations).toHaveLength(0)+ expect(r.detectedPlatform).toBe('unknown')+ })+ it('returns an empty result for empty array', () => {+ const r = parseJsonText('[]')+ expect(r.conversations).toHaveLength(0)+ })+})diff --git a/src/lib/parsers/chatbot-export.ts b/src/lib/parsers/chatbot-export.tsnew file mode 100644index 00000000..75d64ed2--- /dev/null+++ b/src/lib/parsers/chatbot-export.ts@@ -0,0 +1,322 @@+// Feature CC v2.5.0 — Chatbot export importer (MikeS++ Discord 2026-05-27).+// Parses ChatGPT / Claude / Gemini conversation exports and produces a+// normalised list of `{title, markdown}` items the rest of the importer can+// feed into the RAG pipeline as if they were ordinary text uploads.+//+// We accept either a raw JSON file (the user already unzipped the export)+// or a .zip (we walk it for conversations.json). The parsers are loose by+// design: each platform's export schema has churned multiple times, and+// failing to import a conversation is much better than crashing the whole+// import run. Unrecognised entries are skipped and counted in the result+// so the UI can surface a "skipped N items" hint.++import JSZip from 'jszip'++export type ChatbotPlatform = 'chatgpt' | 'claude' | 'gemini' | 'unknown'++export interface NormalisedConversation {+ /** Stable id for the import list (filename-safe). */+ id: string+ /** Human-readable title (falls back to "Untitled <date>"). */+ title: string+ /** Final markdown a RAG processor will consume. */+ markdown: string+ /** Best-guess platform — surfaced as the document's source field. */+ platform: ChatbotPlatform+ /** ISO timestamp of the conversation (creation or last update). */+ timestamp: string | null+ /** Message count, for the UI. */+ messageCount: number+}++export interface ParseResult {+ conversations: NormalisedConversation[]+ /** Number of items in the raw export we couldn't map to a conversation. */+ skipped: number+ /** Detected platform across the export (heuristic). */+ detectedPlatform: ChatbotPlatform+}++/** Read a File object as text. */+async function readFileAsText(file: File): Promise<string> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader()+ reader.onload = () => resolve(String(reader.result))+ reader.onerror = () => reject(reader.error || new Error('FileReader failed'))+ reader.readAsText(file)+ })+}++/** Detect platform from the parsed JSON shape. */+export function detectPlatform(parsed: unknown): ChatbotPlatform {+ if (!parsed) return 'unknown'+ if (Array.isArray(parsed) && parsed.length > 0) {+ const sample = parsed[0] as Record<string, unknown>+ // ChatGPT exports use `mapping` (id → message node).+ if (sample && typeof sample === 'object' && 'mapping' in sample) return 'chatgpt'+ // Claude uses `chat_messages` (array of { sender, text }).+ if (sample && typeof sample === 'object' && 'chat_messages' in sample) return 'claude'+ // Gemini Takeout activity exports use `title` + `messages` and `header` = "Gemini Apps"+ if (sample && typeof sample === 'object' && 'header' in sample && String((sample as any).header || '').toLowerCase().includes('gemini')) return 'gemini'+ }+ // Some Gemini bundles use a wrapper { activities: [...] }.+ if (typeof parsed === 'object' && parsed !== null && 'activities' in parsed) return 'gemini'+ return 'unknown'+}++/** Sanitise a string for use as a filename / id. */+function slugify(s: string, fallback: string): string {+ const cleaned = (s || '').trim().replace(/[\\/:*?"<>|]/g, '_').slice(0, 80)+ return cleaned || fallback+}++// ── ChatGPT ────────────────────────────────────────────────────────────+// Schema (verified against OpenAI Data Export Aug 2024 + Apr 2026):+// [+// {+// "title": "...",+// "create_time": 1700000000.0,+// "update_time": 1700001000.0,+// "mapping": {+// "<uuid>": {+// "id": "<uuid>",+// "message": null | {+// "id": "...",+// "author": { "role": "system" | "user" | "assistant" | "tool", ... },+// "create_time": 1700000000.0,+// "content": { "content_type": "text", "parts": ["..."] }+// },+// "parent": "<uuid>" | null,+// "children": ["<uuid>", ...]+// }+// }+// }+// ]+function parseChatGpt(raw: unknown): NormalisedConversation[] {+ if (!Array.isArray(raw)) return []+ const out: NormalisedConversation[] = []+ for (const conv of raw) {+ if (!conv || typeof conv !== 'object') continue+ const c = conv as Record<string, unknown>+ const title = String(c.title || '').trim() || 'Untitled ChatGPT conversation'+ const createTime = typeof c.create_time === 'number' ? c.create_time : null+ const updateTime = typeof c.update_time === 'number' ? c.update_time : null+ const timestamp = updateTime ?? createTime+ const isoTimestamp = timestamp ? new Date(timestamp * 1000).toISOString() : null++ const mapping = c.mapping as Record<string, any> | undefined+ if (!mapping) continue++ // Linearise the message tree by walking from root following the first+ // child each time. That matches what the user actually saw in the UI+ // (alternative branches were never visible in the rendered conversation).+ const root = Object.values(mapping).find(n => n && n.parent == null) as any+ if (!root) continue+ const lines: string[] = [`# ${title}`, '']+ if (isoTimestamp) lines.push(`_Created: ${isoTimestamp}_`, '')+ let node = root+ let messageCount = 0+ while (node) {+ const msg = node.message+ if (msg && msg.author && msg.content) {+ const role = String(msg.author.role || 'unknown')+ const parts = Array.isArray(msg.content.parts) ? msg.content.parts : []+ const text = parts.map((p: any) => typeof p === 'string' ? p : (p?.text || '')).join('\n').trim()+ if (text && role !== 'tool' && role !== 'system') {+ const heading = role === 'user' ? '**You**' : (role === 'assistant' ? '**Assistant**' : `**${role}**`)+ lines.push(heading, '', text, '')+ messageCount+++ }+ }+ const children = Array.isArray(node.children) ? node.children : []+ const next = children[0]+ node = next ? mapping[next] : null+ }+ if (messageCount === 0) continue+ out.push({+ id: slugify(title, `chatgpt_${createTime || out.length}`),+ title,+ markdown: lines.join('\n').trim(),+ platform: 'chatgpt',+ timestamp: isoTimestamp,+ messageCount,+ })+ }+ return out+}++// ── Claude ─────────────────────────────────────────────────────────────+// Schema (verified against Anthropic export Apr 2026):+// [+// {+// "uuid": "...",+// "name": "...",+// "created_at": "2026-01-01T...",+// "updated_at": "...",+// "chat_messages": [+// {+// "uuid": "...",+// "text": "...",+// "sender": "human" | "assistant",+// "created_at": "..."+// }+// ]+// }+// ]+function parseClaude(raw: unknown): NormalisedConversation[] {+ if (!Array.isArray(raw)) return []+ const out: NormalisedConversation[] = []+ for (const conv of raw) {+ if (!conv || typeof conv !== 'object') continue+ const c = conv as Record<string, unknown>+ const title = String(c.name || '').trim() || 'Untitled Claude conversation'+ const isoTimestamp = typeof c.updated_at === 'string'+ ? c.updated_at+ : (typeof c.created_at === 'string' ? c.created_at : null)+ const messages = Array.isArray(c.chat_messages) ? c.chat_messages : []+ if (messages.length === 0) continue+ const lines: string[] = [`# ${title}`, '']+ if (isoTimestamp) lines.push(`_Created: ${isoTimestamp}_`, '')+ let messageCount = 0+ for (const m of messages as any[]) {+ const sender = String(m?.sender || 'unknown')+ const text = String(m?.text || '').trim()+ if (!text) continue+ const heading = sender === 'human' ? '**You**' : (sender === 'assistant' ? '**Assistant**' : `**${sender}**`)+ lines.push(heading, '', text, '')+ messageCount+++ }+ if (messageCount === 0) continue+ out.push({+ id: slugify(title, `claude_${c.uuid || out.length}`),+ title,+ markdown: lines.join('\n').trim(),+ platform: 'claude',+ timestamp: isoTimestamp,+ messageCount,+ })+ }+ return out+}++// ── Gemini ─────────────────────────────────────────────────────────────+// Gemini exports come via Google Takeout. There are several shapes; the most+// common one is an activity-stream JSON where each entry is a Search-style+// `{ title, time, header: "Gemini Apps" }` with an inline transcript. We+// parse defensively — anything we can't extract becomes a single-message+// markdown entry that still carries the prompt text.+function parseGemini(raw: unknown): NormalisedConversation[] {+ let items: any[] = []+ if (Array.isArray(raw)) items = raw+ else if (typeof raw === 'object' && raw !== null && Array.isArray((raw as any).activities)) {+ items = (raw as any).activities+ }+ const out: NormalisedConversation[] = []+ for (const item of items) {+ if (!item || typeof item !== 'object') continue+ const i = item as Record<string, unknown>+ const header = String(i.header || '').toLowerCase()+ if (!header.includes('gemini') && !header.includes('bard')) continue+ const title = String(i.title || '').trim().slice(0, 120) || 'Gemini activity'+ const timestamp = typeof i.time === 'string' ? i.time : null+ const messages = Array.isArray(i.messages) ? i.messages : []+ const lines: string[] = [`# ${title}`, '']+ if (timestamp) lines.push(`_When: ${timestamp}_`, '')+ let messageCount = 0+ if (messages.length > 0) {+ for (const m of messages as any[]) {+ const role = String(m?.role || m?.author || 'unknown')+ const text = String(m?.text || m?.content || '').trim()+ if (!text) continue+ const heading = (role === 'user' || role === 'human') ? '**You**' : '**Assistant**'+ lines.push(heading, '', text, '')+ messageCount+++ }+ } else {+ // Single-prompt activity entry. Surface the title + body as one Q.+ lines.push('**You**', '', title, '')+ messageCount = 1+ }+ if (messageCount === 0) continue+ out.push({+ id: slugify(title, `gemini_${out.length}`),+ title,+ markdown: lines.join('\n').trim(),+ platform: 'gemini',+ timestamp,+ messageCount,+ })+ }+ return out+}++/** Parse a single JSON blob (already-decoded string). */+export function parseJsonText(text: string): ParseResult {+ let parsed: unknown+ try { parsed = JSON.parse(text) } catch {+ return { conversations: [], skipped: 0, detectedPlatform: 'unknown' }+ }+ const detected = detectPlatform(parsed)+ let convs: NormalisedConversation[] = []+ switch (detected) {+ case 'chatgpt': convs = parseChatGpt(parsed); break+ case 'claude': convs = parseClaude(parsed); break+ case 'gemini': convs = parseGemini(parsed); break+ default:+ // Last-ditch: try them all, return whichever produced the most output.+ const tries: Array<[ChatbotPlatform, NormalisedConversation[]]> = [+ ['chatgpt', parseChatGpt(parsed)],+ ['claude', parseClaude(parsed)],+ ['gemini', parseGemini(parsed)],+ ]+ tries.sort((a, b) => b[1].length - a[1].length)+ convs = tries[0][1]+ if (convs.length === 0) return { conversations: [], skipped: 1, detectedPlatform: 'unknown' }+ }+ const rawLen = Array.isArray(parsed) ? (parsed as unknown[]).length : 1+ const skipped = Math.max(0, rawLen - convs.length)+ return { conversations: convs, skipped, detectedPlatform: convs[0]?.platform || detected }+}++/** Parse a user-provided File (either .json or a .zip that contains conversations.json). */+export async function parseExportFile(file: File): Promise<ParseResult> {+ const name = file.name.toLowerCase()+ if (name.endsWith('.zip')) {+ const zip = await JSZip.loadAsync(file)+ // Try common filenames in priority order.+ const candidates = ['conversations.json', 'data/conversations.json']+ for (const path of candidates) {+ const entry = zip.file(path)+ if (entry) {+ const text = await entry.async('string')+ return parseJsonText(text)+ }+ }+ // Fallback: pick the largest .json file inside the zip.+ let best: { path: string; size: number } | null = null+ zip.forEach((path, entry) => {+ if (!entry.dir && path.toLowerCase().endsWith('.json')) {+ const size = (entry as any)._data?.uncompressedSize || 0+ if (!best || size > best.size) best = { path, size }+ }+ })+ if (best) {+ const e = zip.file((best as { path: string; size: number }).path)+ if (e) {+ const text = await e.async('string')+ return parseJsonText(text)+ }+ }+ return { conversations: [], skipped: 0, detectedPlatform: 'unknown' }+ }+ // JSON path+ const text = await readFileAsText(file)+ return parseJsonText(text)+}++/** Convert a normalised conversation into a File the RAG uploader accepts. */+export function conversationToFile(conv: NormalisedConversation): File {+ const filename = `${conv.platform}_${conv.id}.md`+ const blob = new Blob([conv.markdown], { type: 'text/markdown' })+ return new File([blob], filename, { type: 'text/markdown' })+}