Skip to content

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

ingest the full ChatGPT export .zip (images, voice, files) into Brain

[._.]/ Adam Eivy94a30a2f9441
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5a025bc4eb..9433132300 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Import your whole ChatGPT export — images, voice clips, and files included** — The Brain → Import ChatGPT wizard now takes the **entire export `.zip`** instead of just `conversations.json`, removing the old 50 MB upload cap (the JSON was parsed in the browser and POSTed as a body; the ZIP streams straight to your PortOS like the Apple Health importer, with no size limit). It handles the **modern multi-file export** (conversations split across `conversations-NNN.json` shards) and **extracts every asset** — the `.dat` image / voice-audio / PDF files — into a served directory, sniffing each file's real type from its magic bytes and naming it from the export's asset map. Each conversation's archived transcript is rendered as **markdown with inline images** (`image_asset_pointer` parts resolve to the extracted image), plus `🔊`/`🎙️` links for voice clips and `📎` links for attached files; assets ChatGPT omitted from the export degrade to a plain placeholder rather than a broken link. Imported conversations render rich in Brain → Memory with a **View full conversation** viewer (the Memory entry keeps a truncated preview; the full thread + assets live in the archive). A lone `conversations.json` still works as before (just without images). (`server/services/chatgptZipImport.js`, `server/services/chatgptImport.js`, `server/routes/brainImport.js`, `server/lib/fileUtils.js`, `server/index.js`, `client/src/components/brain/tabs/ImportTab.jsx`, `client/src/components/brain/tabs/MemoryTab.jsx`, `client/src/components/brain/ConversationViewer.jsx`, `client/src/components/cos/MarkdownOutput.jsx`, `client/src/services/apiBrain.js`)
+
- **Jump to the Importer from the Series Pipeline — with the universe & series carried over** — Starting a series and realizing you already have a manuscript no longer means hunting for the Importer. The Series Pipeline index gains an **Import** button beside **New Series**, the create form carries an inline "Already have a manuscript? **Import it instead**" link (deep-linking your in-progress universe + typed series name), and a series detail page gains an **Import** action that opens the Importer pre-targeted at *that* universe and series. The Importer's **Universe Name** and **Series Name** fields are now **autocomplete comboboxes** — the same match-or-create UX as the Universe creator — so you land an exact match instead of guessing the spelling; the series picker is scoped to the matched universe (its existing series, or type a new name). Deep links resolve via `?universeId=…&seriesId=…` (with raw `universe`/`series` name params as a fallback), where a `seriesId` also pins its parent universe so the pair can't drift. The autocomplete itself is extracted into a shared `EntityCombobox` (the Universe creator's selector now wraps it). (`client/src/components/EntityCombobox.jsx`, `client/src/pages/Importer.jsx`, `client/src/pages/Pipeline.jsx`, `client/src/pages/PipelineSeries.jsx`, `client/src/pages/UniverseBuilder.jsx`)
- **Generate an author headshot from the persona's description + style** — The Authors editor's headshot field gains a **Generate** button alongside Upload and Choose from gallery: it folds the author's **physical description** (the subject) and **headshot style** (the art direction) into one portrait prompt and renders through the existing image-gen system, dropping the result straight into the headshot slot. The button stays disabled until at least one of those fields is filled. While a render is in flight the thumbnail shows the live diffusion preview and step percentage (async local/codex backends), and the Upload / gallery / URL controls lock so a manual choice can't be clobbered when the render lands; the synchronous external SD-API backend lands the image directly. Switching authors mid-render cancels the in-flight tracking so a completed (or still-pending) render can't write the wrong persona's headshot. (`client/src/pages/Authors.jsx`)
diff --git a/client/src/components/brain/ConversationViewer.jsx b/client/src/components/brain/ConversationViewer.jsx
new file mode 100644
index 0000000000..4911e22319
--- /dev/null
+++ b/client/src/components/brain/ConversationViewer.jsx
@@ -0,0 +1,71 @@
+import { useState, useEffect } from 'react';
+import { X } from 'lucide-react';
+import * as api from '../../services/api';
+import Banner from '../ui/Banner';
+import BrailleSpinner from '../BrailleSpinner';
+import MarkdownOutput from '../cos/MarkdownOutput';
+
+/**
+ * Full-transcript viewer for an imported ChatGPT conversation. The Memory
+ * record stores only a truncated preview; the complete thread (with inline
+ * images and asset links) lives in the import archive, fetched on open.
+ */
+export default function ConversationViewer({ record, onClose }) {
+ const [archive, setArchive] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+
+ useEffect(() => {
+ let active = true;
+ setLoading(true);
+ setError(null);
+ api.getChatgptArchive(record.sourceRef)
+ .then((data) => { if (active) { setArchive(data); setLoading(false); } })
+ .catch((err) => { if (active) { setError(err.message); setLoading(false); } });
+ return () => { active = false; };
+ }, [record.sourceRef]);
+
+ // Close on Escape.
+ useEffect(() => {
+ const onKey = (e) => { if (e.key === 'Escape') onClose(); };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [onClose]);
+
+ return (
+ <div
+ className="fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4"
+ onClick={onClose}
+ >
+ <div
+ className="bg-port-card border border-port-border rounded-lg w-full max-w-3xl max-h-[85vh] flex flex-col"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div className="flex items-center justify-between px-4 py-3 border-b border-port-border">
+ <h3 className="font-medium text-white truncate pr-4">{record.title}</h3>
+ <button
+ onClick={onClose}
+ className="text-gray-400 hover:text-white flex-shrink-0"
+ aria-label="Close conversation viewer"
+ >
+ <X size={18} />
+ </button>
+ </div>
+ <div className="overflow-y-auto p-4">
+ {loading && (
+ <div className="text-center py-12 text-gray-400">
+ <BrailleSpinner /> Loading conversation…
+ </div>
+ )}
+ {error && (
+ <Banner tone="error" size="sm">
+ Couldn't load the full transcript ({error}). Showing the preview instead.
+ <div className="mt-2 text-sm text-gray-300 whitespace-pre-wrap">{record.content}</div>
+ </Banner>
+ )}
+ {archive && <MarkdownOutput content={archive.transcript || record.content} />}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/brain/tabs/ImportTab.jsx b/client/src/components/brain/tabs/ImportTab.jsx
index a435cdce88..ddf89809c6 100644
--- a/client/src/components/brain/tabs/ImportTab.jsx
+++ b/client/src/components/brain/tabs/ImportTab.jsx
@@ -15,7 +15,6 @@ import toast from '../../ui/Toast';
import Banner from '../../ui/Banner';
import BrailleSpinner from '../../BrailleSpinner';
import { formatBytes, formatDateShort } from '../../../utils/formatters';
-import { ATTACHMENT_MAX_FILE_SIZE } from '../../../utils/fileUpload';
// Sources we plan to support. Only `available` ones are clickable.
const SOURCES = [
@@ -125,8 +124,9 @@ function SourcePicker({ onPick, navigate }) {
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 [parsedRaw, setParsedRaw] = useState(null); // legacy JSON path: the parsed conversations.json
+ const [zipFile, setZipFile] = useState(null); // ZIP path: the raw File to stream-upload
+ const [preview, setPreview] = useState(null); // JSON path only — ZIPs are parsed server-side
const [fileMeta, setFileMeta] = useState(null);
const [uploading, setUploading] = useState(false);
const [importing, setImporting] = useState(false);
@@ -142,18 +142,28 @@ function ChatGPTWizard({ onExit, navigate }) {
const handleFile = async (file) => {
if (!file) return;
- if (!/\.json$/i.test(file.name)) {
- setError('Please select the conversations.json file from your ChatGPT export.');
+ const isZip = /\.zip$/i.test(file.name);
+ const isJson = /\.json$/i.test(file.name);
+ if (!isZip && !isJson) {
+ setError('Select your ChatGPT export .zip (recommended) or the conversations.json inside it.');
return;
}
- if (file.size > ATTACHMENT_MAX_FILE_SIZE) {
- setError(`File is ${formatBytes(file.size)}, larger than the 50 MB upload limit. See instructions for splitting the file.`);
+ setError(null);
+ setFileMeta({ name: file.name, size: file.size, isZip });
+
+ // ZIP path: no browser-side parse — the whole archive streams to the server
+ // which extracts conversations + image/voice/file assets. Just stash the
+ // File and advance to the options step.
+ if (isZip) {
+ setZipFile(file);
+ setParsedRaw(null);
+ setPreview(null);
+ goNext();
return;
}
- setError(null);
- setUploading(true);
- setFileMeta({ name: file.name, size: file.size });
+ // Legacy JSON path: parse + preview in the browser as before.
+ setUploading(true);
const text = await file.text();
let parsed;
try {
@@ -170,27 +180,43 @@ function ChatGPTWizard({ onExit, navigate }) {
setError(res?.error || 'Server rejected the upload.');
return;
}
+ setZipFile(null);
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(true);
+ setError(null);
+
+ let res;
+ if (zipFile) {
+ res = await api
+ .uploadChatgptZip(zipFile, { tags: tags.join(','), skipEmpty, silent: true })
+ .catch((err) => ({ error: err.message }));
+ } else if (parsedRaw) {
+ res = await api
+ .runChatgptImport(parsedRaw, { tags, skipEmpty })
+ .catch((err) => ({ error: err.message }));
+ } else {
+ setImporting(false);
+ return;
+ }
+
setImporting(false);
if (res?.error || !res?.ok) {
setError(res?.error || 'Import failed.');
+ setStepIdx(STEPS.findIndex((s) => s.id === 'review'));
return;
}
setResult(res);
- toast.success(`Imported ${res.imported} conversation${res.imported === 1 ? '' : 's'} into Memory`);
+ const assetNote = res.assetStats?.assetCount ? ` and ${res.assetStats.assetCount} assets` : '';
+ toast.success(`Imported ${res.imported} conversation${res.imported === 1 ? '' : 's'}${assetNote} into Memory`);
setStepIdx(STEPS.findIndex((s) => s.id === 'done'));
};
@@ -227,9 +253,10 @@ function ChatGPTWizard({ onExit, navigate }) {
/>
)}
- {step.id === 'review' && preview && (
+ {step.id === 'review' && (preview || zipFile) && (
<StepReview
preview={preview}
+ isZip={!!zipFile}
fileMeta={fileMeta}
tagsInput={tagsInput}
setTagsInput={setTagsInput}
@@ -243,9 +270,13 @@ function ChatGPTWizard({ onExit, navigate }) {
{step.id === 'run' && (
<div className="text-center py-12">
<BrailleSpinner />
- <p className="text-white">Importing conversations into Memory…</p>
+ <p className="text-white">
+ {zipFile ? 'Uploading & extracting your export…' : 'Importing conversations into Memory…'}
+ </p>
<p className="text-xs text-gray-500 mt-1">
- {importing ? 'Don\'t close this tab.' : 'Finalising…'}
+ {importing
+ ? (zipFile ? 'Large exports can take a minute — don\'t close this tab.' : 'Don\'t close this tab.')
+ : 'Finalising…'}
</p>
</div>
)}
@@ -322,10 +353,12 @@ function StepInstructions({ onNext }) {
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.
+ Download the <span className="font-mono text-port-accent">.zip</span>. You don't need to unzip it.
</li>
<li>
- On the next step, upload that <span className="font-mono text-port-accent">conversations.json</span> file.
+ On the next step, upload the whole <span className="font-mono text-port-accent">.zip</span> — PortOS extracts your conversations
+ {' '}<span className="text-white">and their images, voice clips, and files</span> for you. (You can still upload a
+ {' '}lone <span className="font-mono text-port-accent">conversations.json</span> instead, but it won't include images.)
</li>
</ol>
<div className="flex items-center justify-between pt-4">
@@ -358,7 +391,7 @@ function StepUpload({ uploading, fileMeta, onPick, onFile, fileInputRef, onBack
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.
+ Drop your ChatGPT export <span className="font-mono text-port-accent">.zip</span> here, or click to browse.
The file stays on this device — nothing is uploaded to OpenAI or any third party.
</p>
@@ -376,8 +409,8 @@ function StepUpload({ uploading, fileMeta, onPick, onFile, fileInputRef, onBack
</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>
+ <p className="text-white font-medium">Drop your export .zip here</p>
+ <p className="text-xs text-gray-400 mt-1">or click to browse — no size limit</p>
</>
)}
{uploading && (
@@ -388,7 +421,7 @@ function StepUpload({ uploading, fileMeta, onPick, onFile, fileInputRef, onBack
<input
ref={fileInputRef}
type="file"
- accept=".json,application/json"
+ accept=".zip,application/zip,.json,application/json"
className="hidden"
onChange={(e) => onFile(e.target.files?.[0])}
/>
@@ -402,15 +435,16 @@ function StepUpload({ uploading, fileMeta, onPick, onFile, fileInputRef, onBack
<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.
+ The whole <span className="font-mono">.zip</span> is fine — it streams straight to your PortOS, no size cap.
</p>
</div>
</div>
);
}
-function StepReview({ preview, fileMeta, tagsInput, setTagsInput, skipEmpty, setSkipEmpty, onBack, onRun }) {
- const { summary, conversations } = preview;
+function StepReview({ preview, isZip, fileMeta, tagsInput, setTagsInput, skipEmpty, setSkipEmpty, onBack, onRun }) {
+ const summary = preview?.summary;
+ const conversations = preview?.conversations || [];
const sample = conversations.slice(0, 8);
const remaining = conversations.length - sample.length;
@@ -419,46 +453,63 @@ function StepReview({ preview, fileMeta, tagsInput, setTagsInput, skipEmpty, set
<div className="grid grid-cols-1 lg:grid-cols-[1fr_320px] gap-6 items-start">
{/* Left — preview of what was found */}
<div className="space-y-4 min-w-0">
- <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-3 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={formatDateShort(summary.earliest)} />
- <Stat label="Latest" value={formatDateShort(summary.latest)} />
- </div>
+ {isZip ? (
+ <>
+ <p className="text-sm text-gray-300">
+ Ready to import <span className="font-mono text-gray-200">{fileMeta?.name}</span>
+ {' '}(<span className="text-white">{formatBytes(fileMeta?.size || 0)}</span>).
+ </p>
+ <Banner tone="info" size="sm">
+ The full archive — every conversation plus all images, voice clips, and files — streams to your
+ PortOS and is extracted here. Counts appear once the import finishes. This can take a minute for
+ large exports.
+ </Banner>
+ </>
+ ) : (
+ <>
+ <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-3 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={formatDateShort(summary.earliest)} />
+ <Stat label="Latest" value={formatDateShort(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 · {formatDateShort(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="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 · {formatDateShort(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>
{/* Right — import options */}
<div className="space-y-4 lg:sticky lg:top-4 self-start">
<p className="text-sm text-gray-300">
- Each conversation becomes a Memory entry in Brain → Memory. The full transcript is also archived to
+ Each conversation becomes a Memory entry in Brain → Memory. The full transcript
+ {isZip ? ' (with inline images and asset links)' : ''} is also archived to
<span className="font-mono text-port-accent"> data/brain/imports/chatgpt</span>.
</p>
@@ -526,6 +577,7 @@ function StepDone({ result, onExit, navigate }) {
<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
+ {result.assetStats?.assetCount ? ` · ${result.assetStats.assetCount} assets` : ''}
</p>
</div>
@@ -551,7 +603,9 @@ function StepDone({ result, onExit, navigate }) {
<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}
+ {r.status === 'imported'
+ ? `${r.messageCount} msg${r.assetCount ? ` · ${r.assetCount} assets` : ''}`
+ : r.reason || r.status}
</span>
</li>
))}
diff --git a/client/src/components/brain/tabs/MemoryTab.jsx b/client/src/components/brain/tabs/MemoryTab.jsx
index e24935c2f5..8555b4f603 100644
--- a/client/src/components/brain/tabs/MemoryTab.jsx
+++ b/client/src/components/brain/tabs/MemoryTab.jsx
@@ -7,9 +7,12 @@ import {Plus,
Save,
CheckCircle2,
Search,
- AlertTriangle} from 'lucide-react';
+ AlertTriangle,
+ MessageSquareText} from 'lucide-react';
import toast from '../../ui/Toast';
import Banner from '../../ui/Banner';
+import MarkdownOutput from '../../cos/MarkdownOutput';
+import ConversationViewer from '../ConversationViewer';
import {
MEMORY_TABS,
@@ -32,6 +35,8 @@ export default function MemoryTab({ onRefresh }) {
const [statusFilter, setStatusFilter] = useState('');
const [searchQuery, setSearchQuery] = useState('');
const [backendStatus, setBackendStatus] = useState(null);
+ // The chatgpt-import conversation currently open in the full-transcript viewer.
+ const [viewerRecord, setViewerRecord] = useState(null);
const fetchRecords = useCallback(async () => {
setLoading(true);
@@ -516,7 +521,22 @@ export default function MemoryTab({ onRefresh }) {
</span>
)}
</div>
- {record.content && <p className="text-sm text-gray-400 mt-1 whitespace-pre-wrap">{record.content}</p>}
+ {record.content && (
+ // Imported ChatGPT transcripts carry markdown (inline images,
+ // asset links) — render them rich. Hand-written memories stay
+ // plain pre-wrap text.
+ record.source === 'chatgpt-import'
+ ? <div className="text-sm text-gray-400 mt-1"><MarkdownOutput content={record.content} /></div>
+ : <p className="text-sm text-gray-400 mt-1 whitespace-pre-wrap">{record.content}</p>
+ )}
+ {record.source === 'chatgpt-import' && record.sourceRef && (
+ <button
+ onClick={() => setViewerRecord(record)}
+ className="mt-2 inline-flex items-center gap-1 text-xs text-port-accent hover:underline"
+ >
+ <MessageSquareText size={13} aria-hidden="true" /> View full conversation
+ </button>
+ )}
{record.tags?.length > 0 && (
<div className="flex gap-1 mt-2 flex-wrap">
{record.tags.map((tag, i) => (
@@ -720,6 +740,10 @@ export default function MemoryTab({ onRefresh }) {
</div>
);
})()}
+
+ {viewerRecord && (
+ <ConversationViewer record={viewerRecord} onClose={() => setViewerRecord(null)} />
+ )}
</div>
);
}
diff --git a/client/src/components/cos/MarkdownOutput.jsx b/client/src/components/cos/MarkdownOutput.jsx
index 39987dc080..be452e4d02 100644
--- a/client/src/components/cos/MarkdownOutput.jsx
+++ b/client/src/components/cos/MarkdownOutput.jsx
@@ -1,6 +1,11 @@
// Inline markdown parser — replaces react-markdown
-const INLINE_RE = /(`[^`]*`|\*\*[^*]+\*\*|\*[^*]+\*|_[^_]+_|\[[^\]]+\]\([^)]+\))/g;
+// `![alt](url)` image embeds are matched BEFORE the `[text](url)` link form so
+// the leading `!` isn't dropped. A same-origin (`/…`) or http(s) src is allowed;
+// anything else (data:, javascript:, etc.) renders as the alt text only.
+const INLINE_RE = /(!\[[^\]]*\]\([^)]+\)|`[^`]*`|\*\*[^*]+\*\*|\*[^*]+\*|_[^_]+_|\[[^\]]+\]\([^)]+\))/g;
+
+const safeSrc = (url) => (/^(https?:\/\/|\/[^/])/.test(url) ? url : null);
function parseInline(text) {
const parts = [];
@@ -10,7 +15,16 @@ function parseInline(text) {
while ((m = INLINE_RE.exec(text)) !== null) {
if (m.index > last) parts.push(text.slice(last, m.index));
const s = m[0];
- if (s[0] === '`') {
+ if (s[0] === '!') {
+ const im = s.match(/^!\[([^\]]*)\]\(([^)]+)\)/);
+ if (im) {
+ const src = safeSrc(im[2]);
+ parts.push(src
+ ? <img key={m.index} src={src} alt={im[1]} loading="lazy"
+ className="max-w-full sm:max-w-md rounded border border-port-border my-2" />
+ : <span key={m.index} className="text-gray-500 italic">[{im[1] || 'image'}]</span>);
+ }
+ } else if (s[0] === '`') {
parts.push(<code key={m.index} className="bg-port-bg px-1 py-0.5 rounded text-port-accent font-mono text-xs break-all">{s.slice(1, -1)}</code>);
} else if (s.startsWith('**')) {
parts.push(<strong key={m.index} className="text-white font-semibold">{s.slice(2, -2)}</strong>);
@@ -19,10 +33,9 @@ function parseInline(text) {
} else {
const lm = s.match(/\[([^\]]+)\]\(([^)]+)\)/);
if (lm) {
- const href = lm[2];
- const safeHref = /^(https?:\/\/|\/[^/])/.test(href) ? href : null;
- parts.push(safeHref
- ? <a key={m.index} href={safeHref} className="text-port-accent hover:underline" target="_blank" rel="noopener noreferrer">{lm[1]}</a>
+ const href = safeSrc(lm[2]);
+ parts.push(href
+ ? <a key={m.index} href={href} className="text-port-accent hover:underline" target="_blank" rel="noopener noreferrer">{lm[1]}</a>
: <span key={m.index} className="text-port-accent">{lm[1]}</span>);
}
}
diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.js
index 437556caa5..79013539e5 100644
--- a/client/src/services/apiBrain.js
+++ b/client/src/services/apiBrain.js
@@ -130,6 +130,19 @@ export const runChatgptImport = (data, options = {}) => request('/brain/import/c
method: 'POST',
body: JSON.stringify({ data, ...options })
});
+// Stream the whole export ZIP up via multipart — no JSON-body size cap, and the
+// server extracts conversations + image/voice/file assets. `tags` is a comma-
+// separated string; `skipEmpty` a boolean. request() detects the FormData body
+// and lets the browser set the multipart boundary itself.
+export const uploadChatgptZip = (file, { tags = '', skipEmpty = true, ...options } = {}) => {
+ const formData = new FormData();
+ formData.append('file', file);
+ if (tags) formData.append('tags', tags);
+ formData.append('skipEmpty', skipEmpty ? 'true' : 'false');
+ return request('/brain/import/chatgpt/zip', { method: 'POST', body: formData, ...options });
+};
+export const getChatgptArchive = (name) =>
+ request(`/brain/import/chatgpt/archive/${encodeURIComponent(name)}`);
// Brain - Digests & Reviews
export const getBrainLatestDigest = () => request('/brain/digest/latest');
diff --git a/server/index.js b/server/index.js
index 49561ed214..efa9c5f2c6 100644
--- a/server/index.js
+++ b/server/index.js
@@ -683,6 +683,10 @@ app.use('/data/audio', express.static(PATHS.audio));
// Background-music tracks (uploaded today, generated locally tomorrow). The
// AudioStage music picker plays them inline via <audio src="/data/music/...">.
app.use('/data/music', express.static(PATHS.music));
+// Extracted third-party import assets (ChatGPT export images/audio/PDFs). The
+// Brain Memory conversation viewer renders these inline (`![](/data/brain-
+// imports/...)`) and as asset links. Read-only; range support for large PDFs.
+app.use('/data/brain-imports', express.static(PATHS.brainImportAssets, ASSET_STATIC_OPTS));
// Serve built client UI (production mode — no Vite dev server needed)
const CLIENT_DIST = join(__dirname, '..', 'client', 'dist');
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index e2975b159f..6f1955c04e 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -93,6 +93,14 @@ export const PATHS = {
// `audio/` so the user can browse + reuse a track across issues without
// walking through the VO-line filenames.
music: join(__lib_dirname, '../../data/music'),
+ // Extracted assets from third-party imports (ChatGPT export images/audio/
+ // PDFs). Served read-only at `/data/brain-imports/...` so the Memory
+ // conversation viewer can render inline `![](url)` images and asset links.
+ // Flat per-source dir keyed by the asset's globally-unique id, so the same
+ // asset referenced from multiple conversations is stored once. The transcript
+ // archive JSON lives one level up (data/brain/imports/<source>/) and is NOT
+ // served — only this assets subtree is.
+ brainImportAssets: join(__lib_dirname, '../../data/brain/imports/assets'),
slashdo: join(__lib_dirname, '../../lib/slashdo')
};
diff --git a/server/lib/testHelper.js b/server/lib/testHelper.js
index 240de9921f..d2b5d881e1 100644
--- a/server/lib/testHelper.js
+++ b/server/lib/testHelper.js
@@ -52,7 +52,11 @@ class RequestBuilder {
const headers = { ...this._headers };
let body;
if (this._body !== undefined) {
- if (typeof this._body === 'object' && this._body !== null) {
+ if (Buffer.isBuffer(this._body) || this._body instanceof Uint8Array) {
+ // Raw bytes (e.g. a multipart body) — pass through untouched; the
+ // caller sets its own content-type (multipart boundary, etc.).
+ body = this._body;
+ } else if (typeof this._body === 'object' && this._body !== null) {
body = JSON.stringify(this._body);
headers['content-type'] ??= 'application/json';
} else {
diff --git a/server/routes/brainImport.js b/server/routes/brainImport.js
index a4f988cb5c..d358c66a6d 100644
--- a/server/routes/brainImport.js
+++ b/server/routes/brainImport.js
@@ -2,20 +2,27 @@
* Brain Import Routes
*
* Guided workflows for pulling content from third-party sources into the
- * digital brain. Currently supports ChatGPT data exports
- * (`conversations.json`).
+ * digital brain. Currently supports ChatGPT data exports — both the legacy
+ * single `conversations.json` (parsed in the browser, POSTed as JSON) and the
+ * modern multi-file ZIP export (streamed up whole and extracted server-side,
+ * which also ingests image / voice-audio / PDF assets).
*
* 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
+ * GET /api/brain/import/sources List available import sources
+ * POST /api/brain/import/chatgpt/preview Validate + summarize a parsed JSON payload
+ * POST /api/brain/import/chatgpt Run a JSON-payload import
+ * POST /api/brain/import/chatgpt/zip Stream-upload + import a full export ZIP
+ * GET /api/brain/import/chatgpt/archive/:name Fetch one archived conversation transcript
*/
import { Router } from 'express';
import { z } from 'zod';
+import { unlink } from 'fs/promises';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
-import { parseExport, stripPreview, importConversations } from '../services/chatgptImport.js';
+import { uploadSingle } from '../lib/multipart.js';
+import { parseExport, stripPreview, importConversations, readArchivedConversation } from '../services/chatgptImport.js';
+import { importChatgptZip } from '../services/chatgptZipImport.js';
const router = Router();
@@ -24,14 +31,14 @@ const SOURCES = [
id: 'chatgpt',
label: 'ChatGPT',
status: 'available',
- description: 'Import every conversation from your ChatGPT data export.',
- fileExpected: 'conversations.json',
+ description: 'Import every conversation — and the images, voice clips, and files — from your ChatGPT data export.',
+ fileExpected: 'the export .zip (or 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.'
+ 'Download the ZIP.',
+ 'Upload the whole .zip here — PortOS extracts your conversations and their images/voice/files for you.'
]
}
];
@@ -72,4 +79,54 @@ router.post('/chatgpt', asyncHandler(async (req, res) => {
res.json(result);
}));
+// Stream the whole export ZIP up (no JSON-body size cap — mirrors the Apple
+// Health importer). 2 GB ceiling; the file is written to a temp path by the
+// streaming multipart parser and removed once the import finishes.
+const uploadZip = uploadSingle('file', {
+ limits: { fileSize: 2 * 1024 * 1024 * 1024 },
+ fileFilter: (req, file, cb) => {
+ const ok = file.mimetype === 'application/zip'
+ || file.mimetype === 'application/x-zip-compressed'
+ || file.originalname.toLowerCase().endsWith('.zip');
+ if (ok) cb(null, true);
+ else cb(new ServerError('Upload the ChatGPT export .zip file.', { status: 400, code: 'BAD_REQUEST' }));
+ }
+});
+
+router.post('/chatgpt/zip', uploadZip, asyncHandler(async (req, res) => {
+ const filePath = req.file?.path;
+ if (!filePath) throw new ServerError('No file uploaded', { status: 400, code: 'BAD_REQUEST' });
+
+ // `tags` arrives as a multipart text field — a comma-separated string.
+ const tags = String(req.body?.tags || '')
+ .split(',')
+ .map((t) => t.trim())
+ .filter(Boolean)
+ .slice(0, 10);
+ const skipEmpty = req.body?.skipEmpty !== 'false';
+
+ console.log(`📥 ChatGPT ZIP import start: ${req.file.originalname} (${req.file.size} bytes)`);
+ try {
+ const result = await importChatgptZip(filePath, { tags: tags.length ? tags : undefined, skipEmpty });
+ if (!result.ok) {
+ throw new ServerError(result.error, { status: 400, code: 'INVALID_CHATGPT_EXPORT' });
+ }
+ console.log(`✅ ChatGPT ZIP import complete: imported=${result.imported} skipped=${result.skipped} assets=${result.assetStats?.assetCount}`);
+ res.json(result);
+ } finally {
+ await unlink(filePath).catch(() => {});
+ }
+}));
+
+// Fetch one archived conversation's full transcript + structured messages for
+// the Memory conversation viewer (the Memory record itself stores a truncated
+// preview; the archive holds the complete thread).
+router.get('/chatgpt/archive/:name', asyncHandler(async (req, res) => {
+ const archived = await readArchivedConversation(req.params.name);
+ if (!archived) {
+ throw new ServerError('Archived conversation not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(archived);
+}));
+
export default router;
diff --git a/server/routes/brainImport.test.js b/server/routes/brainImport.test.js
index 0e5ff92bf8..701ab5cdf2 100644
--- a/server/routes/brainImport.test.js
+++ b/server/routes/brainImport.test.js
@@ -6,21 +6,31 @@ import { errorMiddleware } from '../lib/errorHandler.js';
vi.mock('../services/chatgptImport.js', () => ({
parseExport: vi.fn(),
stripPreview: vi.fn((p) => p),
- importConversations: vi.fn()
+ importConversations: vi.fn(),
+ readArchivedConversation: vi.fn()
+}));
+vi.mock('../services/chatgptZipImport.js', () => ({
+ importChatgptZip: vi.fn()
}));
let brainImportRoutes;
let chatgptImport;
+let chatgptZipImport;
beforeEach(async () => {
vi.resetModules();
vi.doMock('../services/chatgptImport.js', () => ({
parseExport: vi.fn(),
stripPreview: vi.fn((p) => p),
- importConversations: vi.fn()
+ importConversations: vi.fn(),
+ readArchivedConversation: vi.fn()
+ }));
+ vi.doMock('../services/chatgptZipImport.js', () => ({
+ importChatgptZip: vi.fn()
}));
brainImportRoutes = (await import('./brainImport.js')).default;
chatgptImport = await import('../services/chatgptImport.js');
+ chatgptZipImport = await import('../services/chatgptZipImport.js');
});
const buildApp = () => {
@@ -94,4 +104,65 @@ describe('brainImport routes', () => {
expect.objectContaining({ tags: ['chatgpt-import'] })
);
});
+
+ // Build a multipart/form-data body with one file part + text fields.
+ const buildMultipart = (boundary, { fileField = 'file', fileName = 'export.zip', fileBytes = Buffer.from('PK\x03\x04zipbytes'), fields = {} }) => {
+ const parts = [];
+ for (const [k, v] of Object.entries(fields)) {
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${k}"\r\n\r\n${v}\r\n`));
+ }
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${fileField}"; filename="${fileName}"\r\nContent-Type: application/zip\r\n\r\n`));
+ parts.push(fileBytes);
+ parts.push(Buffer.from(`\r\n--${boundary}--\r\n`));
+ return Buffer.concat(parts);
+ };
+
+ it('POST /chatgpt/zip streams the upload and runs the ZIP import', async () => {
+ chatgptZipImport.importChatgptZip.mockResolvedValue({
+ ok: true, imported: 3, skipped: 1, archived: 3,
+ assetStats: { assetCount: 12 }, results: []
+ });
+ const boundary = '----portostest';
+ const body = buildMultipart(boundary, { fields: { tags: 'chatgpt-import,archive', skipEmpty: 'true' } });
+ const res = await request(buildApp())
+ .post('/api/brain/import/chatgpt/zip')
+ .set('content-type', `multipart/form-data; boundary=${boundary}`)
+ .send(body);
+ expect(res.status).toBe(200);
+ expect(res.body.imported).toBe(3);
+ expect(res.body.assetStats.assetCount).toBe(12);
+ expect(chatgptZipImport.importChatgptZip).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ tags: ['chatgpt-import', 'archive'], skipEmpty: true })
+ );
+ });
+
+ it('POST /chatgpt/zip rejects a non-zip upload', async () => {
+ const boundary = '----portostest2';
+ const parts = [
+ Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="notes.txt"\r\nContent-Type: text/plain\r\n\r\n`),
+ Buffer.from('hello'),
+ Buffer.from(`\r\n--${boundary}--\r\n`)
+ ];
+ const res = await request(buildApp())
+ .post('/api/brain/import/chatgpt/zip')
+ .set('content-type', `multipart/form-data; boundary=${boundary}`)
+ .send(Buffer.concat(parts));
+ expect(res.status).toBe(400);
+ expect(chatgptZipImport.importChatgptZip).not.toHaveBeenCalled();
+ });
+
+ it('GET /chatgpt/archive/:name returns the archived transcript', async () => {
+ chatgptImport.readArchivedConversation.mockResolvedValue({ id: 'c1', title: 'X', transcript: '**You**:\nhi' });
+ const res = await request(buildApp()).get('/api/brain/import/chatgpt/archive/c1.json');
+ expect(res.status).toBe(200);
+ expect(res.body.transcript).toContain('hi');
+ expect(chatgptImport.readArchivedConversation).toHaveBeenCalledWith('c1.json');
+ });
+
+ it('GET /chatgpt/archive/:name returns 404 when missing', async () => {
+ chatgptImport.readArchivedConversation.mockResolvedValue(null);
+ const res = await request(buildApp()).get('/api/brain/import/chatgpt/archive/missing.json');
+ expect(res.status).toBe(404);
+ });
});
diff --git a/server/services/chatgptImport.js b/server/services/chatgptImport.js
index a5b7306c72..985ca6f155 100644
--- a/server/services/chatgptImport.js
+++ b/server/services/chatgptImport.js
@@ -1,16 +1,27 @@
/**
* 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.
+ * Parses ChatGPT data exports and imports them as Brain Memory entries. Full
+ * conversation transcripts are also archived to
+ * `data/brain/imports/chatgpt/<conversation-id>.json` so the original structure
+ * (mapping tree, model, citations) and a rich markdown transcript are preserved
+ * for the in-app conversation viewer.
+ *
+ * Two upload shapes are supported:
+ * - The legacy single `conversations.json` (parsed in the browser, POSTed as
+ * JSON). No assets — image/audio parts render as `[image]` / `[audio]`.
+ * - The modern multi-file ZIP export (streamed up whole, extracted server-
+ * side by `chatgptZipImport.js`). That path passes an `assetResolver` so
+ * image/audio/file parts render as inline markdown (`![name](url)`,
+ * `[🔊 audio](url)`, `[📎 file](url)`) pointing at the extracted assets.
+ *
+ * `parseExport` / `summarizeConversation` / `extractMessages` all accept an
+ * optional `{ assetResolver }`; when omitted they behave exactly as before.
*/
import { join } from 'path';
import { writeFile } from 'fs/promises';
-import { ensureDir, PATHS } from '../lib/fileUtils.js';
+import { ensureDir, PATHS, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';
import { createMemoryEntry } from './brainStorage.js';
const MAX_MEMORY_CONTENT = 9800;
@@ -32,24 +43,102 @@ const cleanTitle = (s, fallback = 'Untitled conversation') => {
};
/**
- * 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.).
+ * Normalize a ChatGPT asset pointer to its bare file id. Pointers appear as
+ * `file-service://file-XXX`, `sediment://file_HASH`, or (in `attachments`) a
+ * bare `file-XXX` id. The matching on-disk asset is `<id>.dat`.
*/
-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 '';
- })
+export const assetPointerId = (pointer) => String(pointer || '')
+ .replace(/^file-service:\/\//, '')
+ .replace(/^sediment:\/\//, '')
+ .trim();
+
+const escapeMd = (s) => String(s || '').replace(/([\\`*_[\]()])/g, '\\$1');
+
+/**
+ * Render one message part to markdown text. `assetResolver(pointer)` returns
+ * `{ url, name, mime } | null` for an extracted asset (ZIP path), or is null
+ * (legacy JSON path) — in which case asset parts degrade to `[image]` etc.
+ * `renderedIds` collects the asset ids we inlined so `extractMessages` can
+ * avoid double-listing them in the message's attachment footer.
+ */
+const partToText = (part, assetResolver, renderedIds) => {
+ if (typeof part === 'string') return part;
+ if (!part || typeof part !== 'object') return '';
+
+ const ct = part.content_type;
+
+ // Spoken-turn transcript text — render the words, not a placeholder.
+ if (ct === 'audio_transcription' && typeof part.text === 'string') return part.text;
+
+ if (ct === 'image_asset_pointer') {
+ const resolved = assetResolver?.(part.asset_pointer);
+ if (resolved?.url) {
+ if (renderedIds) renderedIds.add(assetPointerId(part.asset_pointer));
+ return `\n\n![${escapeMd(resolved.name || 'image')}](${resolved.url})\n`;
+ }
+ return '[image]';
+ }
+
+ if (ct === 'audio_asset_pointer') {
+ const resolved = assetResolver?.(part.asset_pointer);
+ if (resolved?.url) {
+ if (renderedIds) renderedIds.add(assetPointerId(part.asset_pointer));
+ return `[🔊 ${escapeMd(resolved.name || 'audio')}](${resolved.url})`;
+ }
+ return '[audio]';
+ }
+
+ if (ct === 'real_time_user_audio_video_asset_pointer') {
+ const resolved = assetResolver?.(part.asset_pointer);
+ if (resolved?.url) {
+ if (renderedIds) renderedIds.add(assetPointerId(part.asset_pointer));
+ return `[🎙️ ${escapeMd(resolved.name || 'voice message')}](${resolved.url})`;
+ }
+ return '[voice message]';
+ }
+
+ if (typeof part.text === 'string') return part.text;
+ if (ct) return `[${ct}]`;
+ return '';
+};
+
+/**
+ * Reduce a single message's `content.parts` array into a plain text / markdown
+ * string. Returns `{ text, renderedIds }` so the caller can dedupe attachments.
+ */
+const renderParts = (parts, assetResolver) => {
+ const renderedIds = new Set();
+ if (!Array.isArray(parts)) return { text: '', renderedIds };
+ const text = parts
+ .map((part) => partToText(part, assetResolver, renderedIds))
.filter(Boolean)
.join('\n');
+ return { text, renderedIds };
+};
+
+// Kept for back-compat with the existing unit tests (`__test.partsToText`).
+const partsToText = (parts) => renderParts(parts, null).text;
+
+/**
+ * Render a message's `metadata.attachments` (files the user attached) as a
+ * markdown footer of links — skipping any already inlined as image parts.
+ * Non-image attachments (PDFs, docs, spreadsheets) only appear here, never as
+ * parts, so this is the only place they surface.
+ */
+const renderAttachments = (msg, assetResolver, renderedIds) => {
+ const attachments = msg?.metadata?.attachments;
+ if (!Array.isArray(attachments) || attachments.length === 0) return '';
+ const links = [];
+ for (const att of attachments) {
+ const id = att?.id;
+ if (!id || renderedIds.has(id)) continue;
+ const resolved = assetResolver?.(id);
+ if (resolved?.url) {
+ const icon = (resolved.mime || att.mime_type || '').startsWith('image/') ? '🖼️' : '📎';
+ links.push(`[${icon} ${escapeMd(resolved.name || att.name || 'file')}](${resolved.url})`);
+ }
+ }
+ return links.length ? `\n\n${links.join('\n')}` : '';
};
/**
@@ -57,7 +146,7 @@ const partsToText = (parts) => {
* root, then reverse — that path is the visible conversation thread (ChatGPT
* mappings can include alternate branches from edits/regenerations).
*/
-export function extractMessages(conversation) {
+export function extractMessages(conversation, { assetResolver = null } = {}) {
if (!conversation || typeof conversation !== 'object') return [];
const mapping = conversation.mapping || {};
const seen = new Set();
@@ -76,7 +165,9 @@ export function extractMessages(conversation) {
if (!msg) continue;
const role = msg.author?.role;
if (!role || role === 'system') continue;
- const text = partsToText(msg.content?.parts);
+ const { text: partsText, renderedIds } = renderParts(msg.content?.parts, assetResolver);
+ const attachmentText = renderAttachments(msg, assetResolver, renderedIds);
+ const text = `${partsText}${attachmentText}`;
if (!text.trim()) continue;
messages.push({
id: msg.id || node.id,
@@ -105,11 +196,14 @@ const epochToISO = (epoch) => {
/**
* Build a lightweight summary record for a parsed conversation.
*/
-export function summarizeConversation(conversation) {
- const messages = extractMessages(conversation);
+export function summarizeConversation(conversation, { assetResolver = null } = {}) {
+ const messages = extractMessages(conversation, { assetResolver });
const userMessages = messages.filter((m) => m.role === 'user').length;
const assistantMessages = messages.filter((m) => m.role === 'assistant').length;
const transcript = formatTranscript(messages);
+ // Count inlined assets (markdown image embeds + asset link icons) for the
+ // preview/summary so the wizard can report "N conversations, M assets".
+ const assetCount = (transcript.match(/!\[[^\]]*\]\([^)]+\)|\[(?:🔊|🎙️|🖼️|📎)[^\]]*\]\([^)]+\)/g) || []).length;
return {
id: conversation.id || conversation.conversation_id || null,
title: cleanTitle(conversation.title),
@@ -119,6 +213,7 @@ export function summarizeConversation(conversation) {
userMessages,
assistantMessages,
charCount: transcript.length,
+ assetCount,
gizmoId: conversation.gizmo_id || null,
messages,
transcript
@@ -126,16 +221,22 @@ export function summarizeConversation(conversation) {
}
/**
- * 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.
+ * Parse a raw conversations payload into analysis + per-conversation summaries.
+ * Accepts: a top-level array of conversations, an object with a `conversations`
+ * array (legacy single-file `conversations.json`), OR an object with a
+ * `conversationFiles` array of already-parsed JSON payloads (the multi-file ZIP
+ * path, where each `conversations-NNN.json` is its own array/object).
*/
-export function parseExport(raw) {
+export function parseExport(raw, { assetResolver = null } = {}) {
let conversations;
if (Array.isArray(raw)) {
conversations = raw;
} else if (raw && Array.isArray(raw.conversations)) {
conversations = raw.conversations;
+ } else if (raw && Array.isArray(raw.conversationFiles)) {
+ // Multi-file export: flatten every shard into one conversation list.
+ conversations = raw.conversationFiles.flatMap((shard) =>
+ Array.isArray(shard) ? shard : (Array.isArray(shard?.conversations) ? shard.conversations : []));
} else {
return { ok: false, error: 'Expected an array of conversations or an object with a "conversations" array.' };
}
@@ -147,15 +248,17 @@ export function parseExport(raw) {
const summaries = [];
let totalMessages = 0;
let totalChars = 0;
+ let totalAssets = 0;
let earliest = null;
let latest = null;
const gizmos = new Set();
for (const c of conversations) {
- const s = summarizeConversation(c);
+ const s = summarizeConversation(c, { assetResolver });
summaries.push(s);
totalMessages += s.messageCount;
totalChars += s.charCount;
+ totalAssets += s.assetCount;
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;
@@ -167,6 +270,7 @@ export function parseExport(raw) {
totalConversations: summaries.length,
totalMessages,
totalChars,
+ totalAssets,
earliest,
latest,
gizmoCount: gizmos.size
@@ -193,6 +297,21 @@ const safeFilename = (s) => String(s || 'conversation')
.replace(/^-+|-+$/g, '')
.slice(0, 80) || 'conversation';
+/**
+ * Read one archived conversation transcript by its archive filename (the
+ * `sourceRef` stored on a chatgpt-import Memory entry). Returns null if the
+ * name escapes the archive dir or the file is missing — the conversation
+ * viewer falls back to the truncated Memory `content` in that case.
+ */
+export async function readArchivedConversation(archiveName) {
+ const name = String(archiveName || '');
+ // Reject path traversal — archive names are flat `<safe-id>.json`.
+ if (!/^[a-zA-Z0-9-_]+\.json$/.test(name)) return null;
+ const raw = await tryReadFile(join(IMPORT_ROOT, name));
+ if (!raw) return null;
+ return safeJSONParse(raw, null, { allowArray: false });
+}
+
/**
* Persist one conversation's full transcript + structured messages to the
* import archive directory.
@@ -208,6 +327,7 @@ async function archiveConversation(summary) {
createTime: summary.createTime,
updateTime: summary.updateTime,
messageCount: summary.messageCount,
+ assetCount: summary.assetCount,
gizmoId: summary.gizmoId,
messages: summary.messages,
transcript: summary.transcript,
@@ -222,13 +342,14 @@ const buildContent = (summary) => {
`Source: ChatGPT export`,
summary.createTime ? `Started: ${summary.createTime}` : null,
summary.updateTime ? `Updated: ${summary.updateTime}` : null,
- `Messages: ${summary.messageCount}`
+ `Messages: ${summary.messageCount}`,
+ summary.assetCount ? `Assets: ${summary.assetCount}` : null
].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)`;
+ return `${truncated}\n\n…(transcript truncated — open the full conversation to see everything)`;
};
/**
@@ -283,6 +404,7 @@ export async function importConversations(parsed, options = {}) {
memoryId: entry.id,
title: summary.title,
messageCount: summary.messageCount,
+ assetCount: summary.assetCount,
archiveName,
status: 'imported'
});
@@ -299,4 +421,4 @@ export async function importConversations(parsed, options = {}) {
};
}
-export const __test = { sanitizeTag, cleanTitle, partsToText, buildContent };
+export const __test = { sanitizeTag, cleanTitle, partsToText, buildContent, assetPointerId };
diff --git a/server/services/chatgptImport.test.js b/server/services/chatgptImport.test.js
index db348268e1..a69a6e5f48 100644
--- a/server/services/chatgptImport.test.js
+++ b/server/services/chatgptImport.test.js
@@ -100,6 +100,49 @@ describe('chatgptImport service', () => {
const messages = extractMessages(conv);
expect(messages[0].text).toContain('[image]');
});
+
+ it('inlines image/audio assets as markdown when an assetResolver is supplied', () => {
+ const conv = sampleConversation();
+ conv.mapping.n1.message.content.parts = [
+ 'See:',
+ { content_type: 'image_asset_pointer', asset_pointer: 'file-service://file-IMG' },
+ { content_type: 'audio_asset_pointer', asset_pointer: 'sediment://file_SND' },
+ ];
+ const assetResolver = (ptr) => {
+ const id = String(ptr).replace(/^file-service:\/\/|^sediment:\/\//, '');
+ if (id === 'file-IMG') return { url: '/data/brain-imports/file-IMG.png', name: 'pic.png', mime: 'image/png' };
+ if (id === 'file_SND') return { url: '/data/brain-imports/file_SND.wav', name: 'clip.wav', mime: 'audio/wav' };
+ return null;
+ };
+ const messages = extractMessages(conv, { assetResolver });
+ expect(messages[0].text).toContain('![pic.png](/data/brain-imports/file-IMG.png)');
+ expect(messages[0].text).toContain('[🔊 clip.wav](/data/brain-imports/file_SND.wav)');
+ expect(messages[0].text).not.toContain('[image]');
+ });
+
+ it('renders message attachments (PDFs/docs) as a link footer, deduped against inlined images', () => {
+ const conv = sampleConversation();
+ conv.mapping.n1.message.content.parts = [
+ { content_type: 'image_asset_pointer', asset_pointer: 'file-service://file-IMG' },
+ ];
+ conv.mapping.n1.message.metadata = {
+ attachments: [
+ { id: 'file-IMG', name: 'pic.png', mime_type: 'image/png' }, // already inlined → skipped
+ { id: 'file-DOC', name: 'report.pdf', mime_type: 'application/pdf' },
+ ],
+ };
+ const assetResolver = (ptr) => {
+ const id = String(ptr).replace(/^file-service:\/\//, '');
+ if (id === 'file-IMG') return { url: '/data/brain-imports/file-IMG.png', name: 'pic.png', mime: 'image/png' };
+ if (id === 'file-DOC') return { url: '/data/brain-imports/file-DOC.pdf', name: 'report.pdf', mime: 'application/pdf' };
+ return null;
+ };
+ const messages = extractMessages(conv, { assetResolver });
+ // image inlined once, pdf in the footer, no duplicate image link
+ expect(messages[0].text).toContain('![pic.png](/data/brain-imports/file-IMG.png)');
+ expect(messages[0].text).toContain('[📎 report.pdf](/data/brain-imports/file-DOC.pdf)');
+ expect((messages[0].text.match(/file-IMG\.png/g) || []).length).toBe(1);
+ });
});
describe('parseExport', () => {
@@ -122,6 +165,17 @@ describe('chatgptImport service', () => {
expect(parseExport({ random: 'thing' }).ok).toBe(false);
expect(parseExport([]).ok).toBe(false);
});
+
+ it('flattens a multi-file export (conversationFiles: array of shards)', () => {
+ const result = parseExport({
+ conversationFiles: [
+ [sampleConversation({ id: 'a' })],
+ { conversations: [sampleConversation({ id: 'b' }), sampleConversation({ id: 'c' })] },
+ ],
+ });
+ expect(result.ok).toBe(true);
+ expect(result.summary.totalConversations).toBe(3);
+ });
});
describe('importConversations', () => {
diff --git a/server/services/chatgptZipImport.js b/server/services/chatgptZipImport.js
new file mode 100644
index 0000000000..f2b0dac695
--- /dev/null
+++ b/server/services/chatgptZipImport.js
@@ -0,0 +1,226 @@
+/**
+ * ChatGPT ZIP Import Service
+ *
+ * Ingests the modern multi-file ChatGPT data export (a `.zip`, streamed up
+ * whole — no in-memory cap) end to end:
+ *
+ * 1. Stream-extract the ZIP (`parseZip`) — never buffer the whole archive.
+ * - `conversations*.json` + `conversation_asset_file_names.json` are small
+ * relative to the assets and are buffered in memory.
+ * - `*.dat` asset files (images / voice audio / PDFs) are written to the
+ * served assets dir (`PATHS.brainImportAssets`) keyed by their global
+ * asset id, with a real extension sniffed from magic bytes (falling back
+ * to the friendly name in the asset-name map). `chat.html` and other
+ * bulky members are drained without buffering.
+ * 2. Build a `pointer -> { url, name, mime }` resolver so transcript rendering
+ * can inline `![](url)` images and `[🔊 audio](url)` / `[📎 file](url)`
+ * links pointing at the extracted assets.
+ * 3. Parse + import via the shared `chatgptImport` service, passing the
+ * resolver so every conversation's transcript embeds its assets.
+ *
+ * Both the legacy single-`conversations.json` JSON path (browser-parsed) and
+ * this ZIP path converge on the same `parseExport`/`importConversations` — the
+ * only difference is the `assetResolver`.
+ */
+
+import { createReadStream } from 'fs';
+import { mkdir, unlink, writeFile } from 'fs/promises';
+import { Writable } from 'stream';
+import { PATHS, getMimeType } from '../lib/fileUtils.js';
+import { parseZip } from '../lib/zipStream.js';
+import { parseExport, importConversations, assetPointerId } from './chatgptImport.js';
+
+// Cap an individual buffered JSON member. The largest conversation shard in a
+// real export is ~6 MB; 100 MB is a generous backstop against a malicious zip
+// claiming a JSON member is enormous. Asset `.dat` files are streamed to disk,
+// not buffered, so they aren't bound by this.
+const MAX_JSON_MEMBER_BYTES = 100 * 1024 * 1024;
+
+// Magic-byte sniffers — `.dat` files carry no extension, so we detect the real
+// type from the leading bytes and give the served file a correct extension.
+// Order matters (WebP's RIFF prefix is also used by WAV, so check the form id).
+const sniffExtension = (buf) => {
+ if (!buf || buf.length < 12) return null;
+ if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) return '.png';
+ if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return '.jpg';
+ if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46) return '.gif';
+ if (buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46) return '.pdf';
+ if (buf.slice(0, 4).toString('ascii') === 'RIFF') {
+ const form = buf.slice(8, 12).toString('ascii');
+ if (form === 'WEBP') return '.webp';
+ if (form === 'WAVE') return '.wav';
+ return null;
+ }
+ // ID3-tagged or raw MPEG audio.
+ if (buf.slice(0, 3).toString('ascii') === 'ID3') return '.mp3';
+ if (buf[0] === 0xff && (buf[1] & 0xe0) === 0xe0) return '.mp3';
+ return null;
+};
+
+// Friendly-name → extension fallback when magic-byte sniffing comes up empty.
+const extFromName = (name) => {
+ const m = String(name || '').match(/\.([a-z0-9]{1,5})$/i);
+ return m ? `.${m[1].toLowerCase()}` : null;
+};
+
+const IS_DAT = (path) => path.endsWith('.dat');
+const IS_CONVO_JSON = (path) => /(?:^|\/)conversations(?:-\d+)?\.json$/i.test(path);
+const IS_ASSET_NAME_MAP = (path) => /(?:^|\/)conversation_asset_file_names\.json$/i.test(path);
+
+// A `.dat` member's asset id is its basename without extension. Conversations
+// reference assets as `file-service://file-XXX` / `sediment://file_HASH`, both
+// of which `assetPointerId()` reduces to that same bare id.
+const datAssetId = (path) => path.replace(/^.*\//, '').replace(/\.dat$/i, '');
+
+// `parseZip` entries aren't readable streams — they expose `.pipe(dest)` /
+// `.autodrain()`. Pipe the entry into a size-capped collecting Writable and
+// resolve with the concatenated buffer.
+const collect = (entry, max) => new Promise((resolve, reject) => {
+ const chunks = [];
+ let size = 0;
+ const sink = new Writable({
+ write(chunk, _enc, cb) {
+ size += chunk.length;
+ if (size > max) { cb(new Error(`ZIP member exceeds ${max} byte limit`)); return; }
+ chunks.push(chunk);
+ cb();
+ }
+ });
+ sink.on('finish', () => resolve(Buffer.concat(chunks)));
+ sink.on('error', reject);
+ entry.pipe(sink);
+});
+
+/**
+ * Stream-extract a ChatGPT export ZIP at `zipPath`.
+ *
+ * Returns:
+ * {
+ * conversationFiles: Array<parsed JSON>, // each conversations*.json
+ * assets: Map<assetId, { url, name, mime, file }>,
+ * assetNameMap: Record<datFilename, friendlyName>,
+ * stats: { assetCount, conversationFileCount, skippedAssets }
+ * }
+ *
+ * Assets are written to `data/brain/imports/assets/<assetId><ext>` and surfaced
+ * at `/data/brain-imports/<assetId><ext>`.
+ */
+export async function extractChatgptZip(zipPath, { assetDir = PATHS.brainImportAssets } = {}) {
+ await mkdir(assetDir, { recursive: true });
+
+ const convoBuffers = []; // { path, buffer }
+ let assetNameMap = {};
+ // assetId -> { datPath, buffer } collected during the stream; we resolve
+ // extensions + write files after, because the name map may arrive after the
+ // .dat members (member order in the ZIP isn't guaranteed).
+ const pendingAssets = new Map();
+
+ await new Promise((resolve, reject) => {
+ let settled = false;
+ const settle = (fn) => (arg) => { if (!settled) { settled = true; fn(arg); } };
+ const onErr = settle(reject);
+ const inFlight = [];
+
+ createReadStream(zipPath)
+ .on('error', onErr)
+ .pipe(parseZip())
+ .on('entry', (entry) => {
+ const { path } = entry;
+ if (IS_ASSET_NAME_MAP(path)) {
+ inFlight.push(collect(entry, MAX_JSON_MEMBER_BYTES)
+ .then((buf) => { assetNameMap = JSON.parse(buf.toString('utf8')); })
+ .catch(onErr));
+ } else if (IS_CONVO_JSON(path)) {
+ inFlight.push(collect(entry, MAX_JSON_MEMBER_BYTES)
+ .then((buf) => { convoBuffers.push({ path, buffer: buf }); })
+ .catch(onErr));
+ } else if (IS_DAT(path)) {
+ // Buffer the asset bytes. Asset `.dat` files in real exports are
+ // individual media files (KB–few MB); collecting one at a time is
+ // fine and lets us sniff magic bytes for the extension.
+ inFlight.push(collect(entry, MAX_JSON_MEMBER_BYTES)
+ .then((buf) => { pendingAssets.set(datAssetId(path), { datPath: path, buffer: buf }); })
+ .catch(onErr));
+ } else {
+ // chat.html, export_manifest.json, library_files.json, user.json, etc.
+ // — not needed for the transcript+asset import. Drain without buffering.
+ entry.autodrain();
+ }
+ })
+ .on('close', () => { Promise.all(inFlight).then(settle(resolve), onErr); })
+ .on('error', onErr);
+ });
+
+ // Resolve each buffered asset's extension + write it to the served dir.
+ const assets = new Map();
+ for (const [assetId, { datPath, buffer }] of pendingAssets) {
+ const friendlyName = assetNameMap[`${assetId}.dat`] || assetNameMap[datPath] || null;
+ const ext = sniffExtension(buffer) || extFromName(friendlyName) || '.bin';
+ const fileName = `${assetId}${ext}`;
+ const filePath = `${assetDir}/${fileName}`;
+ // eslint-disable-next-line no-await-in-loop -- sequential write keeps peak
+ // disk/IO bounded; an export has a few hundred assets, not millions.
+ await writeFile(filePath, buffer);
+ assets.set(assetId, {
+ url: `/data/brain-imports/${fileName}`,
+ name: friendlyName || fileName,
+ mime: getMimeType(ext),
+ file: fileName,
+ });
+ }
+
+ const conversationFiles = [];
+ for (const { buffer } of convoBuffers) {
+ conversationFiles.push(JSON.parse(buffer.toString('utf8')));
+ }
+
+ return {
+ conversationFiles,
+ assets,
+ assetNameMap,
+ stats: {
+ assetCount: assets.size,
+ conversationFileCount: conversationFiles.length,
+ },
+ };
+}
+
+/**
+ * Build an `assetResolver(pointer)` closure over an extracted-assets Map.
+ * Resolves `file-service://`, `sediment://`, and bare-id pointers to the
+ * served asset descriptor, or null when the pointer's asset wasn't in the
+ * export (ChatGPT omits expired/server-side-only assets — normal, not an error).
+ */
+export function makeAssetResolver(assets) {
+ return (pointer) => {
+ if (!pointer) return null;
+ const id = assetPointerId(pointer);
+ return assets.get(id) || null;
+ };
+}
+
+/**
+ * Full ZIP-import pipeline: extract → resolve assets → parse → import.
+ * `zipPath` is a temp file (the streamed multipart upload); the caller owns
+ * unlinking it. Returns the `importConversations` result augmented with asset
+ * stats, plus the parsed preview summary.
+ */
+export async function importChatgptZip(zipPath, { tags, skipEmpty } = {}) {
+ const { conversationFiles, assets, stats } = await extractChatgptZip(zipPath);
+ if (conversationFiles.length === 0) {
+ return { ok: false, error: 'No conversations*.json files found in the ZIP. Is this a ChatGPT data export?' };
+ }
+
+ const assetResolver = makeAssetResolver(assets);
+ const parsed = parseExport({ conversationFiles }, { assetResolver });
+ if (!parsed.ok) return parsed;
+
+ const result = await importConversations(parsed, { tags, skipEmpty });
+ return {
+ ...result,
+ summary: parsed.summary,
+ assetStats: stats,
+ };
+}
+
+export const __test = { sniffExtension, extFromName, datAssetId, makeAssetResolver };
diff --git a/server/services/chatgptZipImport.test.js b/server/services/chatgptZipImport.test.js
new file mode 100644
index 0000000000..654f05db64
--- /dev/null
+++ b/server/services/chatgptZipImport.test.js
@@ -0,0 +1,194 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtemp, rm, writeFile, readdir, readFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+// --- Minimal ZIP fixture builder (mirrors lib/zipStream.test.js) -----------
+const LOCAL_SIG = 0x04034b50;
+const CENTRAL_SIG = 0x02014b50;
+
+function buildEntry(name, payload) {
+ const nameBuf = Buffer.from(name, 'utf-8');
+ const header = Buffer.alloc(30);
+ header.writeUInt32LE(LOCAL_SIG, 0);
+ header.writeUInt16LE(20, 4);
+ header.writeUInt16LE(0, 6);
+ header.writeUInt16LE(0, 8); // stored (no compression)
+ header.writeUInt32LE(payload.length, 18);
+ header.writeUInt32LE(payload.length, 22);
+ header.writeUInt16LE(nameBuf.length, 26);
+ header.writeUInt16LE(0, 28);
+ return Buffer.concat([header, nameBuf, payload]);
+}
+function buildEocd() {
+ const buf = Buffer.alloc(4);
+ buf.writeUInt32LE(CENTRAL_SIG, 0);
+ return buf;
+}
+const buildZip = (entries) =>
+ Buffer.concat([...entries.map(([n, p]) => buildEntry(n, Buffer.isBuffer(p) ? p : Buffer.from(p))), buildEocd()]);
+
+// Magic-byte payloads for asset extension sniffing.
+const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, ...Array(8).fill(0)]);
+const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, ...Array(8).fill(0)]);
+const WAV = Buffer.concat([Buffer.from('RIFF'), Buffer.alloc(4), Buffer.from('WAVE'), Buffer.alloc(4)]);
+const PDF = Buffer.concat([Buffer.from('%PDF-1.4'), Buffer.alloc(8)]);
+
+let TMP;
+let extractChatgptZip, makeAssetResolver, importChatgptZip, sniffExtension, datAssetId;
+
+describe('chatgptZipImport service', () => {
+ beforeEach(async () => {
+ TMP = await mkdtemp(join(tmpdir(), 'portos-cgptzip-'));
+ const mod = await import('./chatgptZipImport.js');
+ extractChatgptZip = mod.extractChatgptZip;
+ makeAssetResolver = mod.makeAssetResolver;
+ importChatgptZip = mod.importChatgptZip;
+ sniffExtension = mod.__test.sniffExtension;
+ datAssetId = mod.__test.datAssetId;
+ });
+ afterEach(async () => { await rm(TMP, { recursive: true, force: true }); });
+
+ const writeZip = async (entries) => {
+ const p = join(TMP, 'export.zip');
+ await writeFile(p, buildZip(entries));
+ return p;
+ };
+
+ describe('sniffExtension', () => {
+ it('detects png/jpeg/wav/pdf from magic bytes', () => {
+ expect(sniffExtension(PNG)).toBe('.png');
+ expect(sniffExtension(JPEG)).toBe('.jpg');
+ expect(sniffExtension(WAV)).toBe('.wav');
+ expect(sniffExtension(PDF)).toBe('.pdf');
+ });
+ it('returns null for unrecognized bytes', () => {
+ expect(sniffExtension(Buffer.from('not a known magic header here'))).toBe(null);
+ });
+ });
+
+ describe('datAssetId', () => {
+ it('strips path + .dat extension to the bare asset id', () => {
+ expect(datAssetId('file-ABC123.dat')).toBe('file-ABC123');
+ expect(datAssetId('nested/dir/file_DEADBEEF.dat')).toBe('file_DEADBEEF');
+ });
+ });
+
+ describe('extractChatgptZip', () => {
+ it('extracts conversation shards + assets with sniffed extensions and friendly names', async () => {
+ const zipPath = await writeZip([
+ ['conversations-000.json', JSON.stringify([{ id: 'c1', title: 'A', mapping: {} }])],
+ ['conversations-001.json', JSON.stringify([{ id: 'c2', title: 'B', mapping: {} }])],
+ ['conversation_asset_file_names.json', JSON.stringify({ 'file-IMG.dat': 'photo.png' })],
+ ['file-IMG.dat', PNG],
+ ['file-SND.dat', WAV],
+ ['chat.html', '<html>ignored</html>'],
+ ['export_manifest.json', JSON.stringify({ export_files: [] })],
+ ]);
+ const { conversationFiles, assets, stats } = await extractChatgptZip(zipPath, { assetDir: join(TMP, 'assets') });
+
+ expect(conversationFiles.length).toBe(2);
+ expect(stats.assetCount).toBe(2);
+
+ const img = assets.get('file-IMG');
+ expect(img.file).toBe('file-IMG.png');
+ expect(img.url).toBe('/data/brain-imports/file-IMG.png');
+ expect(img.name).toBe('photo.png'); // friendly name from the map
+ expect(img.mime).toBe('image/png');
+
+ const snd = assets.get('file-SND');
+ expect(snd.file).toBe('file-SND.wav'); // sniffed even with no map entry
+ expect(snd.mime).toBe('audio/wav');
+
+ // Files actually written to the served dir.
+ const written = (await readdir(join(TMP, 'assets'))).sort();
+ expect(written).toEqual(['file-IMG.png', 'file-SND.wav']);
+ // chat.html / export_manifest.json were drained, not extracted.
+ expect(written).not.toContain('chat.html');
+ });
+
+ it('falls back to the friendly-name extension when magic bytes are unknown', async () => {
+ const zipPath = await writeZip([
+ ['conversations-000.json', JSON.stringify([{ id: 'c1', title: 'A', mapping: {} }])],
+ ['conversation_asset_file_names.json', JSON.stringify({ 'file-DOC.dat': 'report.csv' })],
+ ['file-DOC.dat', 'col1,col2\n1,2\n'],
+ ]);
+ const { assets } = await extractChatgptZip(zipPath, { assetDir: join(TMP, 'assets') });
+ expect(assets.get('file-DOC').file).toBe('file-DOC.csv');
+ });
+ });
+
+ describe('makeAssetResolver', () => {
+ it('resolves file-service://, sediment://, and bare-id pointers; null for unknown', () => {
+ const assets = new Map([['file-XYZ', { url: '/data/brain-imports/file-XYZ.png', name: 'p.png', mime: 'image/png' }]]);
+ const resolve = makeAssetResolver(assets);
+ expect(resolve('file-service://file-XYZ').url).toBe('/data/brain-imports/file-XYZ.png');
+ expect(resolve('file-XYZ').url).toBe('/data/brain-imports/file-XYZ.png');
+ expect(resolve('sediment://file-XYZ').url).toBe('/data/brain-imports/file-XYZ.png');
+ expect(resolve('file-service://file-MISSING')).toBe(null);
+ expect(resolve(null)).toBe(null);
+ });
+ });
+
+ describe('importChatgptZip', () => {
+ // Drive the full pipeline against a mocked brainStorage + brain PATH so the
+ // archive lands in TMP and no real DB/store is touched.
+ it('imports conversations and inlines local image assets into the transcript', async () => {
+ const { vi } = await import('vitest');
+ vi.resetModules();
+ const ARCHIVE = await mkdtemp(join(tmpdir(), 'portos-cgptzip-arch-'));
+ vi.doMock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ return { ...actual, PATHS: { ...actual.PATHS, brain: ARCHIVE, brainImportAssets: join(TMP, 'assets') } };
+ });
+ const created = [];
+ vi.doMock('./brainStorage.js', () => ({
+ createMemoryEntry: vi.fn(async (d) => { created.push(d); return { id: `mem-${created.length}`, ...d }; })
+ }));
+ const { importChatgptZip: run } = await import('./chatgptZipImport.js');
+
+ const conv = {
+ id: 'c1', title: 'Knot help', create_time: 1700000000, current_node: 'n1',
+ mapping: {
+ n1: {
+ id: 'n1', parent: null, children: [],
+ message: {
+ id: 'm1', author: { role: 'user' }, create_time: 1700000001,
+ content: {
+ content_type: 'multimodal_text',
+ parts: ['Look at this:', { content_type: 'image_asset_pointer', asset_pointer: 'file-service://file-IMG' }]
+ }
+ }
+ }
+ }
+ };
+ const zipPath = await writeZip([
+ ['conversations-000.json', JSON.stringify([conv])],
+ ['conversation_asset_file_names.json', JSON.stringify({ 'file-IMG.dat': 'knot.png' })],
+ ['file-IMG.dat', PNG],
+ ]);
+
+ const result = await run(zipPath, { tags: ['chatgpt-import'] });
+ expect(result.ok).toBe(true);
+ expect(result.imported).toBe(1);
+ expect(result.assetStats.assetCount).toBe(1);
+ expect(created[0].source).toBe('chatgpt-import');
+ // The image part rendered as an inline markdown image pointing at the
+ // extracted, served asset (not a `[image]` placeholder).
+ expect(created[0].content).toContain('![knot.png](/data/brain-imports/file-IMG.png)');
+
+ await rm(ARCHIVE, { recursive: true, force: true });
+ vi.resetModules();
+ });
+
+ it('rejects a ZIP with no conversation shards', async () => {
+ const zipPath = await writeZip([
+ ['export_manifest.json', JSON.stringify({ export_files: [] })],
+ ['file-IMG.dat', PNG],
+ ]);
+ const result = await importChatgptZip(zipPath, {});
+ expect(result.ok).toBe(false);
+ expect(result.error).toMatch(/no conversations/i);
+ });
+ });
+});