Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(brain): guided ChatGPT import wizard
Adam Eivy2d907fc32def
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b8423b0527..d78c80b1ec 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -14,6 +14,10 @@## Added+- **Brain → Import: guided ChatGPT data-export wizard** — first slice of a "import from third parties" workflow lives at `/brain/import`. The page presents a source picker (ChatGPT available now; Claude/Notion placeholders for future slices; Obsidian short-circuits to the existing Brain → Notes vault flow) and on selection drives a 6-step wizard: (1) inline OpenAI export instructions with a deep link to the official help article, (2) drag-or-browse upload of the extracted `conversations.json` with client-side parse + 50 MB guard, (3) preview pane showing total conversations, message count, character total, custom-GPT (`gizmo`) count, earliest/latest dates and a sample of titles, (4) configure tags + skip-empty toggle, (5) progress, (6) per-conversation results with a deep-link to `Brain → Memory` and an expandable list of imported/skipped IDs. Each conversation becomes a Brain Memory record (title, transcript truncated to fit the 10K content cap, tags including any `gizmo-*` indicator, `source: 'chatgpt-import'` and `sourceCreatedAt` set from ChatGPT's `create_time`) while the full structured transcript and message tree is archived to `data/brain/imports/chatgpt/<conversation-id>.json` so a richer viewer or re-tagger can be built later without re-uploading. The mapping-tree walk reconstructs the visible conversation thread by following `current_node` back to the root (so edited/regenerated branches don't pollute the import) and gracefully renders non-text parts (`image_asset_pointer` becomes `[image]`, etc.). New endpoints: `GET /api/brain/import/sources`, `POST /api/brain/import/chatgpt/preview`, `POST /api/brain/import/chatgpt`. Nav manifest registers `nav.brain.import` with aliases `brain-import`, `import-chatgpt`, `chatgpt-import` and keywords `chatgpt`, `openai`, `export`, `third-party` so `⌘K` and voice resolve "import chatgpt" / "chatgpt import" straight to the wizard.++ Files: `server/services/chatgptImport.js` (new — parser + Memory writer + transcript archiver), `server/routes/brainImport.js` (new), `server/services/chatgptImport.test.js` (new — 12 unit tests for tree walk, parts coercion, tag sanitisation, truncation, skip-empty), `server/routes/brainImport.test.js` (new — 4 route tests covering sources, preview validation, and import dispatch), `server/index.js` (mount), `server/lib/navManifest.js` (entry), `client/src/components/brain/tabs/ImportTab.jsx` (new — source picker + ChatGPT wizard), `client/src/pages/Brain.jsx` (case wiring), `client/src/components/brain/constants.js` (TABS entry), `client/src/components/Layout.jsx` (sidebar link), `client/src/services/apiBrain.js` (3 new helpers).+- **Image Gen page + custom-prompt test render in Settings** — the Image Gen settings tab no longer caps out at "test the connection". A new **Test Render** card lets you write a real prompt (and optional negative prompt) and watch a live diffusion preview, so saving the SD API URL is verified end-to-end without leaving the settings screen. A dedicated **Image Gen** page (`/image-gen`) is now reachable from the sidebar (alphabetized between Goals and Insights) and from `⌘K` (aliases `image-gen`, `imagegen`, `generate-image`, `sd`, `stable-diffusion`). The page exposes positive/negative prompts, six preset resolutions (square / landscape / portrait + Flux 832×1216 / 1216×832 + 1024² HD), Steps and CFG Scale sliders, a seed input with a randomize-die button, a live preview (base64 progressive frames piped through Socket.IO `image-gen:*` events), step/ETA readout, and a session history grid (last 24 renders, persisted to `localStorage`) with one-click "Reuse settings" and Download. UI guidance was lifted from the sibling `pixie-forge` project. The settings tab's previously bare `image-gen` alias was renamed to `image-gen-settings` so the bare alias now lands on the new page. The duplicated diffusion-progress socket subscription pattern (also present in `CharacterSheet.jsx`) was extracted into a shared `useImageGenProgress()` hook so the new ImageGenTab + ImageGen page consume one source of truth via `begin()` / `end()` lifecycle calls.Files: `client/src/pages/ImageGen.jsx` (new), `client/src/hooks/useImageGenProgress.js` (new), `client/src/components/settings/ImageGenTab.jsx` (Test Render card + hook adoption), `client/src/App.jsx` (lazy `/image-gen` route), `client/src/components/Layout.jsx` (sidebar entry), `server/lib/navManifest.js` (`nav.image-gen` Main entry, settings alias renamed to disambiguate).diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 0f44b387f3..6a468a8aae 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -116,6 +116,7 @@ const navItems = [{ to: '/brain/digest', label: 'Digest', icon: Calendar },{ to: '/brain/feeds', label: 'Feeds', icon: Rss },{ to: '/brain/graph', label: 'Graph', icon: Network },+ { to: '/brain/import', label: 'Import', icon: Upload },{ to: '/brain/inbox', label: 'Inbox', icon: MessageSquare },{ to: '/insights/overview', label: 'Insights', icon: Lightbulb },{ to: '/brain/links', label: 'Links', icon: Link2 },diff --git a/client/src/components/brain/constants.js b/client/src/components/brain/constants.jsindex 36a157e1ac..da0cf2f039 100644--- a/client/src/components/brain/constants.js+++ b/client/src/components/brain/constants.js@@ -1,4 +1,4 @@-import { MessageSquare, Database, Calendar, Rss, Shield, Users, FolderKanban, Lightbulb, ClipboardList, Settings, Link2, BookOpen, Network, FileText, NotebookPen } from 'lucide-react';+import { MessageSquare, Database, Calendar, Rss, Shield, Users, FolderKanban, Lightbulb, ClipboardList, Settings, Link2, BookOpen, Network, FileText, NotebookPen, Upload } from 'lucide-react';// Main navigation tabsexport const TABS = [@@ -11,6 +11,7 @@ export const TABS = [{ id: 'digest', label: 'Digest', icon: Calendar },{ id: 'feeds', label: 'Feeds', icon: Rss },{ id: 'trust', label: 'Trust', icon: Shield },+ { id: 'import', label: 'Import', icon: Upload },{ id: 'config', label: 'Config', icon: Settings }];diff --git a/client/src/components/brain/tabs/ImportTab.jsx b/client/src/components/brain/tabs/ImportTab.jsxnew file mode 100644index 0000000000..5944250087--- /dev/null+++ b/client/src/components/brain/tabs/ImportTab.jsx@@ -0,0 +1,584 @@+import { useEffect, useRef, useState } from 'react';+import { useNavigate } from 'react-router-dom';+import {+ Upload,+ ArrowLeft,+ ArrowRight,+ Check,+ CheckCircle2,+ AlertCircle,+ FileJson,+ ExternalLink,+ RefreshCw,+ X,+ Sparkles+} from 'lucide-react';+import * as api from '../../../services/api';+import toast from '../../ui/Toast';++// Sources we plan to support. Only `available` ones are clickable.+const SOURCES = [+ {+ id: 'chatgpt',+ label: 'ChatGPT',+ blurb: 'Conversations and projects from chatgpt.com',+ status: 'available'+ },+ {+ id: 'claude',+ label: 'Claude',+ blurb: 'Coming soon — claude.ai conversations',+ status: 'coming-soon'+ },+ {+ id: 'notion',+ label: 'Notion',+ blurb: 'Coming soon — pages and databases',+ status: 'coming-soon'+ },+ {+ id: 'obsidian',+ label: 'Obsidian',+ blurb: 'Already supported via Brain → Notes',+ status: 'see-other',+ href: '/brain/notes'+ }+];++const STEPS = [+ { id: 'instructions', label: 'Get your data' },+ { id: 'upload', label: 'Upload' },+ { id: 'preview', label: 'Preview' },+ { id: 'configure', label: 'Configure' },+ { id: 'run', label: 'Import' },+ { id: 'done', label: 'Done' }+];++const formatBytes = (bytes) => {+ if (!bytes) return '0 B';+ const units = ['B', 'KB', 'MB', 'GB'];+ let i = 0;+ let n = bytes;+ while (n >= 1024 && i < units.length - 1) { n /= 1024; i += 1; }+ return `${n.toFixed(n < 10 ? 1 : 0)} ${units[i]}`;+};++const formatDate = (iso) => {+ if (!iso) return '—';+ const d = new Date(iso);+ if (Number.isNaN(d.getTime())) return '—';+ return d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });+};++export default function ImportTab() {+ const navigate = useNavigate();+ const [source, setSource] = useState(null);++ if (!source) {+ return <SourcePicker onPick={setSource} navigate={navigate} />;+ }+ if (source === 'chatgpt') {+ return <ChatGPTWizard onExit={() => setSource(null)} navigate={navigate} />;+ }+ return null;+}++function SourcePicker({ onPick, navigate }) {+ return (+ <div className="max-w-4xl mx-auto">+ <div className="mb-6">+ <h2 className="text-lg font-semibold text-white flex items-center gap-2">+ <Sparkles size={20} className="text-port-accent" aria-hidden="true" />+ Import from a third-party source+ </h2>+ <p className="text-sm text-gray-400 mt-1">+ Bring conversations, notes, and history from other tools into your second brain.+ Each source has a guided step-by-step wizard.+ </p>+ </div>++ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ {SOURCES.map((s) => {+ const available = s.status === 'available';+ const seeOther = s.status === 'see-other';+ const onClick = available+ ? () => onPick(s.id)+ : seeOther+ ? () => navigate(s.href)+ : undefined;+ return (+ <button+ key={s.id}+ onClick={onClick}+ disabled={!available && !seeOther}+ className={`text-left p-4 rounded-lg border transition-colors min-h-[80px] flex flex-col justify-between+ ${available+ ? 'bg-port-card border-port-border hover:border-port-accent hover:bg-port-card/70'+ : seeOther+ ? 'bg-port-card border-port-border hover:border-port-accent/50'+ : 'bg-port-card/50 border-port-border opacity-60 cursor-not-allowed'}`}+ >+ <div className="flex items-center justify-between">+ <span className="font-medium text-white">{s.label}</span>+ {available && (+ <span className="text-xs px-2 py-0.5 rounded bg-port-accent/20 text-port-accent">Available</span>+ )}+ {s.status === 'coming-soon' && (+ <span className="text-xs px-2 py-0.5 rounded bg-port-warning/20 text-port-warning">Soon</span>+ )}+ {seeOther && (+ <ExternalLink size={14} className="text-gray-400" aria-hidden="true" />+ )}+ </div>+ <p className="text-xs text-gray-400 mt-2">{s.blurb}</p>+ </button>+ );+ })}+ </div>+ </div>+ );+}++function ChatGPTWizard({ onExit, navigate }) {+ const [stepIdx, setStepIdx] = useState(0);+ const [parsedRaw, setParsedRaw] = useState(null); // the original parsed JSON from the file+ const [preview, setPreview] = useState(null);+ const [fileMeta, setFileMeta] = useState(null);+ const [uploading, setUploading] = useState(false);+ const [importing, setImporting] = useState(false);+ const [tagsInput, setTagsInput] = useState('chatgpt-import');+ const [skipEmpty, setSkipEmpty] = useState(true);+ const [result, setResult] = useState(null);+ const [error, setError] = useState(null);+ const fileInputRef = useRef(null);++ const step = STEPS[stepIdx];+ const goNext = () => setStepIdx((i) => Math.min(i + 1, STEPS.length - 1));+ const goBack = () => setStepIdx((i) => Math.max(i - 1, 0));++ const handleFile = async (file) => {+ if (!file) return;+ if (!/\.json$/i.test(file.name)) {+ setError('Please select the conversations.json file from your ChatGPT export.');+ return;+ }+ if (file.size > 50 * 1024 * 1024) {+ setError(`File is ${formatBytes(file.size)}, larger than the 50 MB upload limit. See instructions for splitting the file.`);+ return;+ }+ setError(null);+ setUploading(true);+ setFileMeta({ name: file.name, size: file.size });++ const text = await file.text();+ let parsed;+ try {+ parsed = JSON.parse(text);+ } catch (err) {+ setError(`Could not parse JSON: ${err.message}`);+ setUploading(false);+ return;+ }++ const res = await api.previewChatgptImport(parsed).catch((err) => ({ error: err.message }));+ setUploading(false);+ if (res?.error || !res?.ok) {+ setError(res?.error || 'Server rejected the upload.');+ return;+ }+ setParsedRaw(parsed);+ setPreview(res);+ goNext();+ };++ const runImport = async () => {+ if (!parsedRaw) return;+ setImporting(true);+ setError(null);+ const tags = tagsInput+ .split(',')+ .map((t) => t.trim())+ .filter(Boolean);+ const res = await api.runChatgptImport(parsedRaw, { tags, skipEmpty }).catch((err) => ({ error: err.message }));+ setImporting(false);+ if (res?.error || !res?.ok) {+ setError(res?.error || 'Import failed.');+ return;+ }+ setResult(res);+ toast.success(`Imported ${res.imported} conversation${res.imported === 1 ? '' : 's'} into Memory`);+ setStepIdx(STEPS.findIndex((s) => s.id === 'done'));+ };++ return (+ <div className="max-w-4xl mx-auto">+ <Header onExit={onExit} />+ <Stepper steps={STEPS} activeIdx={stepIdx} />+ {error && (+ <div className="mb-4 p-3 rounded border border-port-error/30 bg-port-error/10 text-sm text-port-error flex items-start gap-2">+ <AlertCircle size={16} className="mt-0.5 flex-shrink-0" aria-hidden="true" />+ <span>{error}</span>+ <button className="ml-auto text-gray-400 hover:text-white" onClick={() => setError(null)} aria-label="Dismiss">+ <X size={14} />+ </button>+ </div>+ )}++ {step.id === 'instructions' && <StepInstructions onNext={goNext} />}++ {step.id === 'upload' && (+ <StepUpload+ uploading={uploading}+ fileMeta={fileMeta}+ onPick={() => fileInputRef.current?.click()}+ onFile={handleFile}+ fileInputRef={fileInputRef}+ onBack={goBack}+ />+ )}++ {step.id === 'preview' && preview && (+ <StepPreview preview={preview} fileMeta={fileMeta} onNext={goNext} onBack={goBack} />+ )}++ {step.id === 'configure' && (+ <StepConfigure+ tagsInput={tagsInput}+ setTagsInput={setTagsInput}+ skipEmpty={skipEmpty}+ setSkipEmpty={setSkipEmpty}+ onBack={goBack}+ onNext={() => { setStepIdx(STEPS.findIndex((s) => s.id === 'run')); runImport(); }}+ />+ )}++ {step.id === 'run' && (+ <div className="text-center py-12">+ <RefreshCw size={32} className="text-port-accent animate-spin mx-auto mb-3" />+ <p className="text-white">Importing conversations into Memory…</p>+ <p className="text-xs text-gray-500 mt-1">+ {importing ? 'Don\'t close this tab.' : 'Finalising…'}+ </p>+ </div>+ )}++ {step.id === 'done' && result && (+ <StepDone result={result} onExit={onExit} navigate={navigate} />+ )}+ </div>+ );+}++function Header({ onExit }) {+ return (+ <div className="flex items-center justify-between mb-6">+ <div className="flex items-center gap-3">+ <Upload size={24} className="text-port-accent" aria-hidden="true" />+ <div>+ <h2 className="text-lg font-semibold text-white">Import from ChatGPT</h2>+ <p className="text-xs text-gray-400">Bring all your conversations into Brain → Memory</p>+ </div>+ </div>+ <button+ onClick={onExit}+ className="text-sm text-gray-400 hover:text-white flex items-center gap-1"+ >+ <ArrowLeft size={14} aria-hidden="true" /> All sources+ </button>+ </div>+ );+}++function Stepper({ steps, activeIdx }) {+ return (+ <ol className="hidden sm:flex items-center gap-2 mb-6 text-xs">+ {steps.map((s, i) => {+ const active = i === activeIdx;+ const done = i < activeIdx;+ return (+ <li key={s.id} className="flex items-center gap-2">+ <span+ className={`flex items-center justify-center w-6 h-6 rounded-full border text-xs+ ${active ? 'bg-port-accent text-white border-port-accent' :+ done ? 'bg-port-success/20 text-port-success border-port-success/40' :+ 'bg-port-card text-gray-500 border-port-border'}`}+ >+ {done ? <Check size={12} /> : i + 1}+ </span>+ <span className={active ? 'text-white' : done ? 'text-gray-300' : 'text-gray-500'}>{s.label}</span>+ {i < steps.length - 1 && <span className="text-gray-700">›</span>}+ </li>+ );+ })}+ </ol>+ );+}++function StepInstructions({ onNext }) {+ return (+ <div className="space-y-4">+ <p className="text-sm text-gray-300">+ OpenAI lets you export everything you've ever said to ChatGPT as a downloadable archive.+ Follow these steps in your ChatGPT account, then come back here to upload the file.+ </p>+ <ol className="space-y-3 list-decimal list-inside text-sm text-gray-300">+ <li>+ Open <span className="font-mono text-port-accent">chatgpt.com</span> and sign in.+ </li>+ <li>+ Click your avatar → <span className="font-medium text-white">Settings</span> →+ {' '}<span className="font-medium text-white">Data Controls</span> →+ {' '}<span className="font-medium text-white">Export data</span> → <span className="font-medium text-white">Confirm export</span>.+ </li>+ <li>+ OpenAI emails you a download link (usually within a few minutes; the link expires in 24 hours).+ </li>+ <li>+ Download the ZIP and unzip it on your machine. You'll see <span className="font-mono text-port-accent">conversations.json</span> alongside other files.+ </li>+ <li>+ On the next step, upload that <span className="font-mono text-port-accent">conversations.json</span> file.+ </li>+ </ol>+ <div className="flex items-center justify-between pt-4">+ <a+ href="https://help.openai.com/en/articles/7260999-how-do-i-export-my-chatgpt-history-and-data"+ target="_blank"+ rel="noreferrer"+ className="text-xs text-port-accent hover:underline flex items-center gap-1"+ >+ Official OpenAI help page <ExternalLink size={12} aria-hidden="true" />+ </a>+ <button+ onClick={onNext}+ className="px-4 py-2 bg-port-accent text-white text-sm font-medium rounded hover:bg-port-accent/90 flex items-center gap-1 min-h-[40px]"+ >+ I have the file <ArrowRight size={14} aria-hidden="true" />+ </button>+ </div>+ </div>+ );+}++function StepUpload({ uploading, fileMeta, onPick, onFile, fileInputRef, onBack }) {+ const handleDrop = (e) => {+ e.preventDefault();+ const file = e.dataTransfer.files?.[0];+ if (file) onFile(file);+ };++ return (+ <div className="space-y-4">+ <p className="text-sm text-gray-300">+ Drop your <span className="font-mono text-port-accent">conversations.json</span> file here, or click to browse.+ The file stays on this device — nothing is uploaded to OpenAI or any third party.+ </p>++ <div+ onClick={onPick}+ onDragOver={(e) => e.preventDefault()}+ onDrop={handleDrop}+ className="border-2 border-dashed border-port-border rounded-lg p-8 text-center cursor-pointer hover:border-port-accent hover:bg-port-card/40 transition-colors"+ >+ <FileJson size={32} className="text-gray-500 mx-auto mb-3" aria-hidden="true" />+ {fileMeta ? (+ <div>+ <p className="text-white font-medium">{fileMeta.name}</p>+ <p className="text-xs text-gray-400 mt-1">{formatBytes(fileMeta.size)}</p>+ </div>+ ) : (+ <>+ <p className="text-white font-medium">Drop conversations.json here</p>+ <p className="text-xs text-gray-400 mt-1">or click to browse — max 50 MB</p>+ </>+ )}+ {uploading && (+ <div className="mt-3 text-xs text-port-accent flex items-center justify-center gap-1">+ <RefreshCw size={12} className="animate-spin" aria-hidden="true" /> Parsing…+ </div>+ )}+ <input+ ref={fileInputRef}+ type="file"+ accept=".json,application/json"+ className="hidden"+ onChange={(e) => onFile(e.target.files?.[0])}+ />+ </div>++ <div className="flex items-center justify-between pt-2">+ <button+ onClick={onBack}+ className="px-4 py-2 text-sm text-gray-400 hover:text-white flex items-center gap-1 min-h-[40px]"+ >+ <ArrowLeft size={14} aria-hidden="true" /> Back+ </button>+ <p className="text-xs text-gray-500">+ Tip: if your export is larger than 50 MB, split <span className="font-mono">conversations.json</span> into chunks and import each.+ </p>+ </div>+ </div>+ );+}++function StepPreview({ preview, fileMeta, onNext, onBack }) {+ const { summary, conversations } = preview;+ const sample = conversations.slice(0, 8);+ const remaining = conversations.length - sample.length;++ return (+ <div className="space-y-4">+ <p className="text-sm text-gray-300">+ Found <span className="text-white font-medium">{summary.totalConversations}</span> conversations+ in <span className="font-mono text-gray-200">{fileMeta?.name}</span>. Quick stats:+ </p>++ <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">+ <Stat label="Conversations" value={summary.totalConversations.toLocaleString()} />+ <Stat label="Messages" value={summary.totalMessages.toLocaleString()} />+ <Stat label="Total chars" value={summary.totalChars.toLocaleString()} />+ <Stat label="Custom GPTs" value={summary.gizmoCount.toString()} />+ <Stat label="Earliest" value={formatDate(summary.earliest)} />+ <Stat label="Latest" value={formatDate(summary.latest)} />+ </div>++ <div className="border border-port-border rounded">+ <div className="px-3 py-2 border-b border-port-border text-xs font-medium text-gray-400 uppercase">+ Sample conversations+ </div>+ <ul className="divide-y divide-port-border">+ {sample.map((c) => (+ <li key={c.id || c.title} className="px-3 py-2 flex items-center justify-between gap-2">+ <span className="text-sm text-white truncate">{c.title}</span>+ <span className="text-xs text-gray-500 flex-shrink-0">+ {c.messageCount} msg · {formatDate(c.createTime)}+ </span>+ </li>+ ))}+ {remaining > 0 && (+ <li className="px-3 py-2 text-xs text-gray-500">+ …and {remaining.toLocaleString()} more+ </li>+ )}+ </ul>+ </div>++ <div className="flex items-center justify-between pt-2">+ <button+ onClick={onBack}+ className="px-4 py-2 text-sm text-gray-400 hover:text-white flex items-center gap-1 min-h-[40px]"+ >+ <ArrowLeft size={14} aria-hidden="true" /> Back+ </button>+ <button+ onClick={onNext}+ className="px-4 py-2 bg-port-accent text-white text-sm font-medium rounded hover:bg-port-accent/90 flex items-center gap-1 min-h-[40px]"+ >+ Configure import <ArrowRight size={14} aria-hidden="true" />+ </button>+ </div>+ </div>+ );+}++function Stat({ label, value }) {+ return (+ <div className="p-3 bg-port-card border border-port-border rounded">+ <div className="text-xs text-gray-500 uppercase">{label}</div>+ <div className="text-base text-white font-medium">{value}</div>+ </div>+ );+}++function StepConfigure({ tagsInput, setTagsInput, skipEmpty, setSkipEmpty, onBack, onNext }) {+ return (+ <div className="space-y-4">+ <p className="text-sm text-gray-300">+ Each conversation becomes a Memory entry in Brain → Memory. The full transcript is also archived to+ <span className="font-mono text-port-accent"> data/brain/imports/chatgpt</span>.+ </p>++ <div>+ <label className="block text-sm text-white mb-1">Tags</label>+ <input+ type="text"+ value={tagsInput}+ onChange={(e) => setTagsInput(e.target.value)}+ placeholder="chatgpt-import, archive"+ className="w-full px-3 py-2 bg-port-card border border-port-border rounded text-sm text-white focus:outline-none focus:border-port-accent min-h-[40px]"+ />+ <p className="text-xs text-gray-500 mt-1">+ Comma-separated. Each conversation gets these tags so you can filter on them later in Memory.+ </p>+ </div>++ <label className="flex items-center gap-2 text-sm text-gray-300 select-none">+ <input+ type="checkbox"+ checked={skipEmpty}+ onChange={(e) => setSkipEmpty(e.target.checked)}+ className="rounded border-port-border bg-port-card"+ />+ Skip empty conversations (chats started but never sent)+ </label>++ <div className="flex items-center justify-between pt-2">+ <button+ onClick={onBack}+ className="px-4 py-2 text-sm text-gray-400 hover:text-white flex items-center gap-1 min-h-[40px]"+ >+ <ArrowLeft size={14} aria-hidden="true" /> Back+ </button>+ <button+ onClick={onNext}+ className="px-4 py-2 bg-port-success text-white text-sm font-medium rounded hover:bg-port-success/90 flex items-center gap-1 min-h-[40px]"+ >+ Run import <ArrowRight size={14} aria-hidden="true" />+ </button>+ </div>+ </div>+ );+}++function StepDone({ result, onExit, navigate }) {+ return (+ <div className="space-y-4">+ <div className="text-center py-6">+ <CheckCircle2 size={48} className="text-port-success mx-auto mb-3" aria-hidden="true" />+ <h3 className="text-lg font-semibold text-white">Import complete</h3>+ <p className="text-sm text-gray-400 mt-1">+ {result.imported} imported · {result.skipped} skipped · {result.archived} archived+ </p>+ </div>++ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">+ <button+ onClick={() => navigate('/brain/memory')}+ className="px-4 py-3 bg-port-accent text-white text-sm font-medium rounded hover:bg-port-accent/90 min-h-[44px]"+ >+ View in Memory+ </button>+ <button+ onClick={onExit}+ className="px-4 py-3 bg-port-card border border-port-border text-white text-sm font-medium rounded hover:bg-port-card/70 min-h-[44px]"+ >+ Import another source+ </button>+ </div>++ <details className="text-xs text-gray-400">+ <summary className="cursor-pointer hover:text-white">Per-conversation results ({result.results.length})</summary>+ <ul className="mt-2 max-h-64 overflow-auto divide-y divide-port-border border border-port-border rounded">+ {result.results.map((r, i) => (+ <li key={r.id || i} className="px-2 py-1 flex items-center justify-between gap-2">+ <span className="truncate text-gray-300">{r.title || '(untitled)'}</span>+ <span className={r.status === 'imported' ? 'text-port-success' : 'text-gray-500'}>+ {r.status === 'imported' ? `${r.messageCount} msg` : r.reason || r.status}+ </span>+ </li>+ ))}+ </ul>+ </details>+ </div>+ );+}diff --git a/client/src/pages/Brain.jsx b/client/src/pages/Brain.jsxindex 5651c35691..3d1a051484 100644--- a/client/src/pages/Brain.jsx+++ b/client/src/pages/Brain.jsx@@ -16,6 +16,7 @@ import TrustTab from '../components/brain/tabs/TrustTab';import NotesTab from '../components/brain/tabs/NotesTab';import DailyLogTab from '../components/brain/tabs/DailyLogTab';import ConfigTab from '../components/brain/tabs/ConfigTab';+import ImportTab from '../components/brain/tabs/ImportTab';export default function Brain() {const { tab } = useParams();@@ -66,6 +67,8 @@ export default function Brain() {return <FeedsTab onRefresh={fetchData} />;case 'trust':return <TrustTab onRefresh={fetchData} />;+ case 'import':+ return <ImportTab />;case 'config':return <ConfigTab onRefresh={fetchData} />;default:diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.jsindex 82ca660a1d..1024d06f65 100644--- a/client/src/services/apiBrain.js+++ b/client/src/services/apiBrain.js@@ -117,6 +117,17 @@ export const updateBrainMemory = (id, data) => request(`/brain/memories/${id}`,});export const deleteBrainMemory = (id) => request(`/brain/memories/${id}`, { method: 'DELETE' });+// Brain - Third-party Imports+export const getBrainImportSources = () => request('/brain/import/sources');+export const previewChatgptImport = (data) => request('/brain/import/chatgpt/preview', {+ method: 'POST',+ body: JSON.stringify({ data })+});+export const runChatgptImport = (data, options = {}) => request('/brain/import/chatgpt', {+ method: 'POST',+ body: JSON.stringify({ data, ...options })+});+// Brain - Digests & Reviewsexport const getBrainLatestDigest = () => request('/brain/digest/latest');export const getBrainDigests = (limit = 10) => request(`/brain/digests?limit=${limit}`);diff --git a/server/index.js b/server/index.jsindex 43d436d10b..e3b70a1cca 100644--- a/server/index.js+++ b/server/index.js@@ -38,6 +38,7 @@ import memoryRoutes from './routes/memory.js';import notificationsRoutes from './routes/notifications.js';import standardizeRoutes from './routes/standardize.js';import brainRoutes from './routes/brain.js';+import brainImportRoutes from './routes/brainImport.js';import notesRoutes from './routes/notes.js';import mediaRoutes from './routes/media.js';import calendarRoutes from './routes/calendar.js';@@ -270,6 +271,7 @@ app.use('/api/feeds', feedsRoutes);app.use('/api/memory', memoryRoutes);app.use('/api/notifications', notificationsRoutes);app.use('/api/standardize', standardizeRoutes);+app.use('/api/brain/import', brainImportRoutes);app.use('/api/brain', brainRoutes);app.use('/api/notes', notesRoutes);app.use('/api/media', mediaRoutes);diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 3f4f457014..ba0c11977b 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -20,6 +20,7 @@ export const NAV_COMMANDS = [{ id: 'nav.brain.digest', path: '/brain/digest', label: 'Digest', section: 'Brain', aliases: ['brain-digest'] },{ id: 'nav.brain.feeds', path: '/brain/feeds', label: 'Feeds', section: 'Brain', aliases: ['brain-feeds', 'feeds', 'rss'], keywords: ['rss', 'subscriptions'] },{ id: 'nav.brain.graph', path: '/brain/graph', label: 'Graph', section: 'Brain', aliases: ['brain-graph'] },+ { id: 'nav.brain.import', path: '/brain/import', label: 'Import', section: 'Brain', aliases: ['brain-import', 'import-chatgpt', 'chatgpt-import'], keywords: ['chatgpt', 'openai', 'export', 'third-party'] },{ id: 'nav.insights', path: '/insights/overview', label: 'Insights', section: 'Brain', aliases: ['insights'] },{ id: 'nav.brain.links', path: '/brain/links', label: 'Links', section: 'Brain', aliases: ['brain-links'] },{ id: 'nav.brain.memory', path: '/brain/memory', label: 'Memory', section: 'Brain', aliases: ['brain-memory', 'memory'] },diff --git a/server/routes/brainImport.js b/server/routes/brainImport.jsnew file mode 100644index 0000000000..a4f988cb5c--- /dev/null+++ b/server/routes/brainImport.js@@ -0,0 +1,75 @@+/**+ * Brain Import Routes+ *+ * Guided workflows for pulling content from third-party sources into the+ * digital brain. Currently supports ChatGPT data exports+ * (`conversations.json`).+ *+ * Endpoints:+ * GET /api/brain/import/sources List available import sources+ * POST /api/brain/import/chatgpt/preview Validate + summarize a parsed payload+ * POST /api/brain/import/chatgpt Run the import, returning per-conversation results+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { parseExport, stripPreview, importConversations } from '../services/chatgptImport.js';++const router = Router();++const SOURCES = [+ {+ id: 'chatgpt',+ label: 'ChatGPT',+ status: 'available',+ description: 'Import every conversation from your ChatGPT data export.',+ fileExpected: 'conversations.json',+ helpUrl: 'https://help.openai.com/en/articles/7260999-how-do-i-export-my-chatgpt-history-and-data',+ instructions: [+ 'Open chatgpt.com → Settings → Data Controls → Export data → Confirm export.',+ 'OpenAI emails you a download link within a few minutes (link expires in 24h).',+ 'Download the ZIP and extract it on your machine.',+ 'Upload the `conversations.json` file from the extracted folder using this wizard.'+ ]+ }+];++router.get('/sources', asyncHandler(async (_req, res) => {+ res.json({ sources: SOURCES });+}));++const previewSchema = z.object({+ data: z.unknown()+});++const importSchema = z.object({+ data: z.unknown(),+ tags: z.array(z.string().min(1).max(50)).max(10).optional(),+ skipEmpty: z.boolean().optional()+});++router.post('/chatgpt/preview', asyncHandler(async (req, res) => {+ const { data } = validateRequest(previewSchema, req.body);+ const parsed = parseExport(data);+ if (!parsed.ok) {+ throw new ServerError(parsed.error, { status: 400, code: 'INVALID_CHATGPT_EXPORT' });+ }+ console.log(`📥 ChatGPT import preview: ${parsed.summary.totalConversations} conversations, ${parsed.summary.totalMessages} messages`);+ res.json(stripPreview(parsed));+}));++router.post('/chatgpt', asyncHandler(async (req, res) => {+ const { data, tags, skipEmpty } = validateRequest(importSchema, req.body);+ const parsed = parseExport(data);+ if (!parsed.ok) {+ throw new ServerError(parsed.error, { status: 400, code: 'INVALID_CHATGPT_EXPORT' });+ }+ console.log(`📥 ChatGPT import start: ${parsed.summary.totalConversations} conversations`);+ const result = await importConversations(parsed, { tags, skipEmpty });+ console.log(`✅ ChatGPT import complete: imported=${result.imported} skipped=${result.skipped} archived=${result.archived}`);+ res.json(result);+}));++export default router;diff --git a/server/routes/brainImport.test.js b/server/routes/brainImport.test.jsnew file mode 100644index 0000000000..0e5ff92bf8--- /dev/null+++ b/server/routes/brainImport.test.js@@ -0,0 +1,97 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++vi.mock('../services/chatgptImport.js', () => ({+ parseExport: vi.fn(),+ stripPreview: vi.fn((p) => p),+ importConversations: vi.fn()+}));++let brainImportRoutes;+let chatgptImport;++beforeEach(async () => {+ vi.resetModules();+ vi.doMock('../services/chatgptImport.js', () => ({+ parseExport: vi.fn(),+ stripPreview: vi.fn((p) => p),+ importConversations: vi.fn()+ }));+ brainImportRoutes = (await import('./brainImport.js')).default;+ chatgptImport = await import('../services/chatgptImport.js');+});++const buildApp = () => {+ const app = express();+ app.use(express.json({ limit: '55mb' }));+ app.use('/api/brain/import', brainImportRoutes);+ app.use(errorMiddleware);+ return app;+};++describe('brainImport routes', () => {+ it('GET /sources returns the available sources list', async () => {+ const res = await request(buildApp()).get('/api/brain/import/sources');+ expect(res.status).toBe(200);+ expect(res.body.sources).toBeInstanceOf(Array);+ const chatgpt = res.body.sources.find((s) => s.id === 'chatgpt');+ expect(chatgpt).toBeDefined();+ expect(chatgpt.status).toBe('available');+ expect(chatgpt.instructions.length).toBeGreaterThan(0);+ });++ it('POST /chatgpt/preview returns 400 when payload is invalid', async () => {+ chatgptImport.parseExport.mockReturnValue({ ok: false, error: 'bad shape' });+ const res = await request(buildApp())+ .post('/api/brain/import/preview-fake-path')+ .send({ data: 'whatever' });+ // sanity: route doesn't exist+ expect(res.status).toBe(404);++ const real = await request(buildApp())+ .post('/api/brain/import/chatgpt/preview')+ .send({ data: 'whatever' });+ expect(real.status).toBe(400);+ expect(real.body.error || real.body.message).toBeTruthy();+ });++ it('POST /chatgpt/preview returns parsed summary on valid payload', async () => {+ chatgptImport.parseExport.mockReturnValue({+ ok: true,+ summary: { totalConversations: 2, totalMessages: 5, totalChars: 100, earliest: null, latest: null, gizmoCount: 0 },+ conversations: [{ id: 'c1', title: 'X', messageCount: 3 }]+ });+ const res = await request(buildApp())+ .post('/api/brain/import/chatgpt/preview')+ .send({ data: [{ id: 'c1' }] });+ expect(res.status).toBe(200);+ expect(res.body.ok).toBe(true);+ expect(res.body.summary.totalConversations).toBe(2);+ });++ it('POST /chatgpt runs the import when payload is valid', async () => {+ chatgptImport.parseExport.mockReturnValue({+ ok: true,+ summary: { totalConversations: 1 },+ conversations: [{ id: 'c1', title: 'X' }]+ });+ chatgptImport.importConversations.mockResolvedValue({+ ok: true,+ imported: 1,+ skipped: 0,+ archived: 1,+ results: [{ id: 'c1', status: 'imported' }]+ });+ const res = await request(buildApp())+ .post('/api/brain/import/chatgpt')+ .send({ data: [{ id: 'c1' }], tags: ['chatgpt-import'] });+ expect(res.status).toBe(200);+ expect(res.body.imported).toBe(1);+ expect(chatgptImport.importConversations).toHaveBeenCalledWith(+ expect.objectContaining({ ok: true }),+ expect.objectContaining({ tags: ['chatgpt-import'] })+ );+ });+});diff --git a/server/services/chatgptImport.js b/server/services/chatgptImport.jsnew file mode 100644index 0000000000..a5b7306c72--- /dev/null+++ b/server/services/chatgptImport.js@@ -0,0 +1,302 @@+/**+ * ChatGPT Import Service+ *+ * Parses ChatGPT data exports (`conversations.json`) and imports them as+ * Brain Memory entries. Full conversation transcripts are also archived to+ * `data/brain/imports/chatgpt/<conversation-id>.json` so that the original+ * structure (mapping tree, model, citations) is preserved if a richer viewer+ * is added later.+ */++import { join } from 'path';+import { writeFile } from 'fs/promises';+import { ensureDir, PATHS } from '../lib/fileUtils.js';+import { createMemoryEntry } from './brainStorage.js';++const MAX_MEMORY_CONTENT = 9800;+const MAX_TITLE_LEN = 200;+const MAX_TAG_LEN = 50;+const ROLE_LABEL = { user: 'You', assistant: 'ChatGPT', system: 'System', tool: 'Tool' };+const IMPORT_ROOT = join(PATHS.brain, 'imports', 'chatgpt');++const sanitizeTag = (s) => String(s || '')+ .toLowerCase()+ .replace(/[^a-z0-9-_]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, MAX_TAG_LEN);++const cleanTitle = (s, fallback = 'Untitled conversation') => {+ const trimmed = String(s || '').trim();+ if (!trimmed) return fallback;+ return trimmed.length > MAX_TITLE_LEN ? `${trimmed.slice(0, MAX_TITLE_LEN - 1)}…` : trimmed;+};++/**+ * Reduce a single message's `content.parts` array into a plain text string.+ * ChatGPT parts can be strings, or objects (image_asset_pointer, code, etc.).+ */+const partsToText = (parts) => {+ if (!Array.isArray(parts)) return '';+ return parts+ .map((part) => {+ if (typeof part === 'string') return part;+ if (part && typeof part === 'object') {+ if (typeof part.text === 'string') return part.text;+ if (part.content_type === 'image_asset_pointer') return '[image]';+ if (part.content_type === 'audio_transcription' && typeof part.text === 'string') return part.text;+ if (part.content_type) return `[${part.content_type}]`;+ }+ return '';+ })+ .filter(Boolean)+ .join('\n');+};++/**+ * Walk the `mapping` tree of a conversation from `current_node` back to the+ * root, then reverse — that path is the visible conversation thread (ChatGPT+ * mappings can include alternate branches from edits/regenerations).+ */+export function extractMessages(conversation) {+ if (!conversation || typeof conversation !== 'object') return [];+ const mapping = conversation.mapping || {};+ const seen = new Set();+ const path = [];+ let nodeId = conversation.current_node;+ while (nodeId && mapping[nodeId] && !seen.has(nodeId)) {+ seen.add(nodeId);+ path.push(mapping[nodeId]);+ nodeId = mapping[nodeId].parent;+ }+ path.reverse();++ const messages = [];+ for (const node of path) {+ const msg = node.message;+ if (!msg) continue;+ const role = msg.author?.role;+ if (!role || role === 'system') continue;+ const text = partsToText(msg.content?.parts);+ if (!text.trim()) continue;+ messages.push({+ id: msg.id || node.id,+ role,+ text,+ createTime: typeof msg.create_time === 'number' ? msg.create_time : null+ });+ }+ return messages;+}++/**+ * Render an array of {role,text} messages as a markdown-ish transcript.+ */+export function formatTranscript(messages) {+ return messages+ .map((m) => `**${ROLE_LABEL[m.role] || m.role}**:\n${m.text}`)+ .join('\n\n---\n\n');+}++const epochToISO = (epoch) => {+ if (typeof epoch !== 'number' || !isFinite(epoch) || epoch <= 0) return null;+ return new Date(epoch * 1000).toISOString();+};++/**+ * Build a lightweight summary record for a parsed conversation.+ */+export function summarizeConversation(conversation) {+ const messages = extractMessages(conversation);+ const userMessages = messages.filter((m) => m.role === 'user').length;+ const assistantMessages = messages.filter((m) => m.role === 'assistant').length;+ const transcript = formatTranscript(messages);+ return {+ id: conversation.id || conversation.conversation_id || null,+ title: cleanTitle(conversation.title),+ createTime: epochToISO(conversation.create_time),+ updateTime: epochToISO(conversation.update_time),+ messageCount: messages.length,+ userMessages,+ assistantMessages,+ charCount: transcript.length,+ gizmoId: conversation.gizmo_id || null,+ messages,+ transcript+ };+}++/**+ * Parse a raw `conversations.json` payload (array OR object with `conversations`).+ * Returns analysis + per-conversation summaries (without full transcripts) so+ * the client can render a preview without round-tripping huge payloads.+ */+export function parseExport(raw) {+ let conversations;+ if (Array.isArray(raw)) {+ conversations = raw;+ } else if (raw && Array.isArray(raw.conversations)) {+ conversations = raw.conversations;+ } else {+ return { ok: false, error: 'Expected an array of conversations or an object with a "conversations" array.' };+ }++ if (conversations.length === 0) {+ return { ok: false, error: 'No conversations found in the upload.' };+ }++ const summaries = [];+ let totalMessages = 0;+ let totalChars = 0;+ let earliest = null;+ let latest = null;+ const gizmos = new Set();++ for (const c of conversations) {+ const s = summarizeConversation(c);+ summaries.push(s);+ totalMessages += s.messageCount;+ totalChars += s.charCount;+ if (s.gizmoId) gizmos.add(s.gizmoId);+ if (s.createTime && (!earliest || s.createTime < earliest)) earliest = s.createTime;+ if (s.updateTime && (!latest || s.updateTime > latest)) latest = s.updateTime;+ }++ return {+ ok: true,+ summary: {+ totalConversations: summaries.length,+ totalMessages,+ totalChars,+ earliest,+ latest,+ gizmoCount: gizmos.size+ },+ conversations: summaries+ };+}++/**+ * Strip the heavy transcript/messages fields so the preview payload sent to+ * the client stays small for large exports.+ */+export function stripPreview(parsed) {+ if (!parsed?.ok) return parsed;+ return {+ ok: true,+ summary: parsed.summary,+ conversations: parsed.conversations.map(({ messages, transcript, ...rest }) => rest)+ };+}++const safeFilename = (s) => String(s || 'conversation')+ .replace(/[^a-zA-Z0-9-_]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 80) || 'conversation';++/**+ * Persist one conversation's full transcript + structured messages to the+ * import archive directory.+ */+async function archiveConversation(summary) {+ await ensureDir(IMPORT_ROOT);+ const id = summary.id || `conv-${Date.now()}`;+ const fname = `${safeFilename(id)}.json`;+ const filePath = join(IMPORT_ROOT, fname);+ const payload = {+ id,+ title: summary.title,+ createTime: summary.createTime,+ updateTime: summary.updateTime,+ messageCount: summary.messageCount,+ gizmoId: summary.gizmoId,+ messages: summary.messages,+ transcript: summary.transcript,+ importedAt: new Date().toISOString()+ };+ await writeFile(filePath, JSON.stringify(payload, null, 2), 'utf8');+ return fname;+}++const buildContent = (summary) => {+ const header = [+ `Source: ChatGPT export`,+ summary.createTime ? `Started: ${summary.createTime}` : null,+ summary.updateTime ? `Updated: ${summary.updateTime}` : null,+ `Messages: ${summary.messageCount}`+ ].filter(Boolean).join('\n');+ const body = summary.transcript;+ const combined = `${header}\n\n${body}`;+ if (combined.length <= MAX_MEMORY_CONTENT) return combined;+ const truncated = combined.slice(0, MAX_MEMORY_CONTENT - 80).trimEnd();+ return `${truncated}\n\n…(transcript truncated — full content archived in data/brain/imports/chatgpt)`;+};++/**+ * Create a Brain Memory entry for each summarised conversation. Conversations+ * with zero messages are skipped (they appear in ChatGPT exports as empty+ * shells when the user starts a chat but never sends a message).+ *+ * Returns counts and per-conversation result records so the wizard can show+ * which entries were skipped/imported.+ */+export async function importConversations(parsed, options = {}) {+ if (!parsed?.ok) return { ok: false, error: parsed?.error || 'Invalid parsed payload' };++ const baseTags = (options.tags || ['chatgpt-import'])+ .map(sanitizeTag)+ .filter(Boolean);+ const skipEmpty = options.skipEmpty !== false;++ await ensureDir(IMPORT_ROOT);++ const results = [];+ let imported = 0;+ let skipped = 0;+ let archived = 0;++ for (const summary of parsed.conversations) {+ if (skipEmpty && summary.messageCount === 0) {+ results.push({ id: summary.id, title: summary.title, status: 'skipped', reason: 'empty' });+ skipped += 1;+ continue;+ }++ const archiveName = await archiveConversation(summary);+ archived += 1;++ const tags = [+ ...baseTags,+ summary.gizmoId ? sanitizeTag(`gizmo-${summary.gizmoId}`) : null+ ].filter(Boolean);++ const entry = await createMemoryEntry({+ title: summary.title,+ content: buildContent(summary),+ tags,+ source: 'chatgpt-import',+ sourceRef: archiveName,+ sourceCreatedAt: summary.createTime || null+ });++ results.push({+ id: summary.id,+ memoryId: entry.id,+ title: summary.title,+ messageCount: summary.messageCount,+ archiveName,+ status: 'imported'+ });+ imported += 1;+ }++ return {+ ok: true,+ imported,+ skipped,+ archived,+ archiveDir: IMPORT_ROOT,+ results+ };+}++export const __test = { sanitizeTag, cleanTitle, partsToText, buildContent };diff --git a/server/services/chatgptImport.test.js b/server/services/chatgptImport.test.jsnew file mode 100644index 0000000000..d19e4767e6--- /dev/null+++ b/server/services/chatgptImport.test.js@@ -0,0 +1,199 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { mkdtemp, rm, readdir, readFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';++// Redirect PATHS.brain to a temp dir BEFORE importing the service so that+// IMPORT_ROOT (computed at module load) lands inside the temp tree.+let TMP;+let createMemoryEntryMock;++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return {+ ...actual,+ PATHS: { ...actual.PATHS, brain: TMP }+ };+});++vi.mock('./brainStorage.js', () => ({+ createMemoryEntry: vi.fn(async (data) => ({ id: `mem-${Math.random().toString(36).slice(2, 8)}`, ...data }))+}));++let parseExport;+let importConversations;+let extractMessages;+let formatTranscript;++describe('chatgptImport service', () => {+ beforeEach(async () => {+ TMP = await mkdtemp(join(tmpdir(), 'portos-chatgpt-'));+ // Re-require the module so it picks up the new TMP+ vi.resetModules();+ vi.doMock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return { ...actual, PATHS: { ...actual.PATHS, brain: TMP } };+ });+ vi.doMock('./brainStorage.js', () => ({+ createMemoryEntry: vi.fn(async (data) => ({ id: `mem-${Math.random().toString(36).slice(2, 8)}`, ...data }))+ }));+ const mod = await import('./chatgptImport.js');+ parseExport = mod.parseExport;+ importConversations = mod.importConversations;+ extractMessages = mod.extractMessages;+ formatTranscript = mod.formatTranscript;+ const storage = await import('./brainStorage.js');+ createMemoryEntryMock = storage.createMemoryEntry;+ });++ afterEach(async () => {+ await rm(TMP, { recursive: true, force: true });+ });++ const sampleConversation = (overrides = {}) => ({+ id: 'conv-1',+ title: 'Hello world',+ create_time: 1700000000,+ update_time: 1700000100,+ current_node: 'n2',+ mapping: {+ 'root': { id: 'root', message: null, parent: null, children: ['n1'] },+ 'n1': {+ id: 'n1',+ parent: 'root',+ children: ['n2'],+ message: {+ id: 'm1',+ author: { role: 'user' },+ create_time: 1700000010,+ content: { content_type: 'text', parts: ['What is 2+2?'] }+ }+ },+ 'n2': {+ id: 'n2',+ parent: 'n1',+ children: [],+ message: {+ id: 'm2',+ author: { role: 'assistant' },+ create_time: 1700000020,+ content: { content_type: 'text', parts: ['4'] }+ }+ }+ },+ ...overrides+ });++ describe('extractMessages', () => {+ it('walks the mapping tree from current_node back to root, in order', () => {+ const messages = extractMessages(sampleConversation());+ expect(messages.map((m) => m.role)).toEqual(['user', 'assistant']);+ expect(messages[0].text).toBe('What is 2+2?');+ expect(messages[1].text).toBe('4');+ });++ it('skips system messages and empty messages', () => {+ const conv = sampleConversation();+ conv.mapping.n1.message.author.role = 'system';+ const messages = extractMessages(conv);+ expect(messages.map((m) => m.role)).toEqual(['assistant']);+ });++ it('returns [] for malformed input', () => {+ expect(extractMessages(null)).toEqual([]);+ expect(extractMessages({})).toEqual([]);+ expect(extractMessages({ mapping: {}, current_node: 'missing' })).toEqual([]);+ });++ it('handles parts that are objects (image_asset_pointer)', () => {+ const conv = sampleConversation();+ conv.mapping.n1.message.content.parts = [{ content_type: 'image_asset_pointer', asset_pointer: 'foo' }];+ const messages = extractMessages(conv);+ expect(messages[0].text).toContain('[image]');+ });+ });++ describe('parseExport', () => {+ it('accepts a top-level array of conversations', () => {+ const result = parseExport([sampleConversation()]);+ expect(result.ok).toBe(true);+ expect(result.summary.totalConversations).toBe(1);+ expect(result.summary.totalMessages).toBe(2);+ expect(result.summary.earliest).toBe(new Date(1700000000 * 1000).toISOString());+ });++ it('accepts an object with a conversations array', () => {+ const result = parseExport({ conversations: [sampleConversation()] });+ expect(result.ok).toBe(true);+ expect(result.summary.totalConversations).toBe(1);+ });++ it('rejects non-array, non-object payloads', () => {+ expect(parseExport('not json').ok).toBe(false);+ expect(parseExport({ random: 'thing' }).ok).toBe(false);+ expect(parseExport([]).ok).toBe(false);+ });+ });++ describe('importConversations', () => {+ it('creates a Memory entry per conversation and archives full transcripts', async () => {+ const parsed = parseExport([sampleConversation(), sampleConversation({ id: 'conv-2', title: 'Second' })]);+ const result = await importConversations(parsed, { tags: ['chatgpt-import', 'archive'] });+ expect(result.ok).toBe(true);+ expect(result.imported).toBe(2);+ expect(result.skipped).toBe(0);+ expect(result.archived).toBe(2);+ expect(createMemoryEntryMock).toHaveBeenCalledTimes(2);+ const firstCall = createMemoryEntryMock.mock.calls[0][0];+ expect(firstCall.title).toBe('Hello world');+ expect(firstCall.tags).toEqual(expect.arrayContaining(['chatgpt-import', 'archive']));+ expect(firstCall.source).toBe('chatgpt-import');+ expect(firstCall.content).toContain('What is 2+2?');++ const archives = await readdir(join(TMP, 'imports', 'chatgpt'));+ expect(archives.length).toBe(2);+ const archived = JSON.parse(await readFile(join(TMP, 'imports', 'chatgpt', archives[0]), 'utf8'));+ expect(archived.messages.length).toBe(2);+ expect(archived.transcript).toContain('What is 2+2?');+ });++ it('skips empty conversations when skipEmpty is true (default)', async () => {+ const empty = sampleConversation({ id: 'empty', current_node: 'root', mapping: { root: { id: 'root', parent: null, children: [], message: null } } });+ const parsed = parseExport([empty, sampleConversation()]);+ const result = await importConversations(parsed);+ expect(result.imported).toBe(1);+ expect(result.skipped).toBe(1);+ });++ it('sanitizes user-supplied tags', async () => {+ const parsed = parseExport([sampleConversation()]);+ const result = await importConversations(parsed, { tags: ['Hello World!', ' ', 'a/b'] });+ expect(result.ok).toBe(true);+ const tags = createMemoryEntryMock.mock.calls[0][0].tags;+ expect(tags).toContain('hello-world');+ expect(tags).toContain('a-b');+ expect(tags).not.toContain(' ');+ });++ it('truncates very long transcripts but preserves a pointer', async () => {+ const huge = sampleConversation();+ huge.mapping.n2.message.content.parts = ['x'.repeat(50000)];+ const parsed = parseExport([huge]);+ const result = await importConversations(parsed);+ expect(result.ok).toBe(true);+ const content = createMemoryEntryMock.mock.calls[0][0].content;+ expect(content.length).toBeLessThan(10000);+ expect(content).toContain('truncated');+ });+ });++ describe('formatTranscript', () => {+ it('renders user and assistant messages with role labels', () => {+ const messages = extractMessages(sampleConversation());+ const transcript = formatTranscript(messages);+ expect(transcript).toContain('**You**');+ expect(transcript).toContain('**ChatGPT**');+ expect(transcript).toContain('What is 2+2?');+ });+ });+});