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

feat: add Brain memory readers and image previews

[._.]/ Adam Eivy7e793baaef5c
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 3f9a91ad95..d9c981bb15 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -345,6 +345,7 @@ export default function App() {
<Route path="calendar/:tab" element={<CalendarPage />} />
<Route path="brain" element={<Navigate to="/brain/inbox" replace />} />
<Route path="brain/links/:id/scan-report" element={<BrainScanReport />} />
+ <Route path="brain/:tab/:recordType/:recordId" element={<Brain />} />
<Route path="brain/:tab" element={<Brain />} />
<Route path="digital-twin" element={<Navigate to="/digital-twin/overview" replace />} />
<Route path="digital-twin/:tab" element={<DigitalTwin />} />
diff --git a/client/src/components/brain/ConversationViewer.jsx b/client/src/components/brain/ConversationViewer.jsx
index 89a1d63db2..d455a1c559 100644
--- a/client/src/components/brain/ConversationViewer.jsx
+++ b/client/src/components/brain/ConversationViewer.jsx
@@ -7,30 +7,32 @@ import MarkdownOutput from '../cos/MarkdownOutput';
import Modal from '../ui/Modal';
/**
- * Full-transcript viewer for an imported ChatGPT conversation. The Memory
+ * Full-content reader for handwritten memories and imported conversations. 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 [loading, setLoading] = useState(record.source === 'chatgpt-import' && !!record.sourceRef);
const [error, setError] = useState(null);
useEffect(() => {
+ if (record.source !== 'chatgpt-import' || !record.sourceRef) return;
let active = true;
+ setArchive(null);
setLoading(true);
setError(null);
- api.getChatgptArchive(record.sourceRef)
+ api.getChatgptArchive(record.sourceRef, { silent: true })
.then((data) => { if (active) { setArchive(data); setLoading(false); } })
.catch((err) => { if (active) { setError(err.message); setLoading(false); } });
return () => { active = false; };
- }, [record.sourceRef]);
+ }, [record.source, record.sourceRef]);
return (
<Modal
open
onClose={onClose}
- size="xl"
+ size="3xl"
ariaLabel={record.title}
panelClassName="bg-port-card border border-port-border rounded-lg flex flex-col"
>
@@ -39,12 +41,12 @@ export default function ConversationViewer({ record, onClose }) {
<button
onClick={onClose}
className="text-gray-400 hover:text-white flex-shrink-0 min-h-[44px] min-w-[44px] flex items-center justify-center"
- aria-label="Close conversation viewer"
+ aria-label="Close entry reader"
>
<X size={18} />
</button>
</div>
- <div className="overflow-y-auto p-4">
+ <div className="min-h-0 overflow-y-auto p-4 sm:p-6 break-words">
{loading && (
<div className="text-center py-12 text-gray-400">
<BrailleSpinner /> Loading conversation…
@@ -53,10 +55,9 @@ export default function ConversationViewer({ record, onClose }) {
{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} />}
+ {!loading && <MarkdownOutput content={archive?.transcript || record.content || record.notes || record.context || 'No content yet.'} />}
</div>
</Modal>
);
diff --git a/client/src/components/brain/MemoryImagePreview.jsx b/client/src/components/brain/MemoryImagePreview.jsx
new file mode 100644
index 0000000000..ec3554b3f6
--- /dev/null
+++ b/client/src/components/brain/MemoryImagePreview.jsx
@@ -0,0 +1,43 @@
+import { useEffect, useRef, useState } from 'react';
+import { markdownImages } from '../../../../server/lib/markdownImages.js';
+import { getChatgptArchive } from '../../services/apiBrain';
+
+/** Only visible cards fetch a small archive image projection, never the transcript. */
+export default function MemoryImagePreview({ record }) {
+ const root = useRef(null);
+ const [images, setImages] = useState(() => markdownImages(record.content));
+ const [unavailable, setUnavailable] = useState(false);
+
+ useEffect(() => {
+ let active = true;
+ setImages(markdownImages(record.content));
+ setUnavailable(false);
+ if (record.source !== 'chatgpt-import' || !record.sourceRef) return;
+ const fetchImages = () => {
+ getChatgptArchive(record.sourceRef, { preview: 'images', silent: true })
+ .then(data => { if (active && data.images) setImages(data.images); })
+ .catch(() => { if (active) setUnavailable(true); });
+ };
+ const observer = new IntersectionObserver(entries => {
+ if (!entries.some(entry => entry.isIntersecting)) return;
+ observer.disconnect();
+ fetchImages();
+ }, { rootMargin: '200px' });
+ observer.observe(root.current);
+ return () => { active = false; observer.disconnect(); };
+ }, [record.content, record.source, record.sourceRef]);
+
+ return (
+ <span ref={root} className="block">
+ {images.length > 0 && (
+ <span className="flex flex-wrap gap-2 mt-3">
+ {images.map(image => (
+ <img key={image.src} src={image.src} alt={image.alt || 'Entry image'} loading="lazy"
+ className="h-24 w-24 sm:h-28 sm:w-28 object-cover rounded-lg border border-port-border bg-port-bg" />
+ ))}
+ </span>
+ )}
+ {unavailable && <span className="block text-xs text-gray-500 mt-2">Archive previews unavailable</span>}
+ </span>
+ );
+}
diff --git a/client/src/components/brain/tabs/MemoryTab.jsx b/client/src/components/brain/tabs/MemoryTab.jsx
index 797a409358..4af5f07ad0 100644
--- a/client/src/components/brain/tabs/MemoryTab.jsx
+++ b/client/src/components/brain/tabs/MemoryTab.jsx
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback, useMemo } from 'react';
-import { useNavigate } from 'react-router';
+import { useNavigate, useParams, useLocation } from 'react-router';
import * as api from '../../../services/api';
import {Plus,
Edit2,
@@ -15,6 +15,7 @@ import toast from '../../ui/Toast';
import Banner from '../../ui/Banner';
import { FormField } from '../../ui/FormField';
import ConversationViewer from '../ConversationViewer';
+import MemoryImagePreview from '../MemoryImagePreview';
import {
MEMORY_TABS,
@@ -55,7 +56,11 @@ export function transcriptTeaser(content, maxLen = 220) {
// federation continue to use the same idea model and API.
export default function MemoryTab({ onRefresh, fixedType = null }) {
const navigate = useNavigate();
- const [activeType, setActiveType] = useState(fixedType || 'memories');
+ const { recordType, recordId } = useParams();
+ const location = useLocation();
+ const basePath = fixedType ? '/brain/ideas' : '/brain/memory';
+ const closeReader = () => navigate(basePath + location.search);
+ const [activeType, setActiveType] = useState(fixedType || recordType || 'memories');
const [records, setRecords] = useState([]);
const [loading, setLoading] = useState(true);
const [editingId, setEditingId] = useState(null);
@@ -65,8 +70,10 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {
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 viewerRecord = records.find(record => record.id === recordId);
+ useEffect(() => {
+ if (recordType && MEMORY_TABS.some(tab => tab.id === recordType)) setActiveType(recordType);
+ }, [recordType]);
const [visibleCount, setVisibleCount] = useState(INITIAL_VISIBLE);
const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
@@ -556,12 +563,12 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {
return (
<div key={record.id} className="p-4 bg-port-card border border-port-border rounded-lg hover:border-port-border/80 transition-colors">
- <div className="flex items-start justify-between gap-2">
+ <div className="flex flex-col sm:flex-row items-start justify-between gap-2">
{/* min-w-0: without it a flex child won't shrink below its content's
intrinsic width, so a long unbreakable code block in an imported
transcript blows the row out and shoves the action buttons off
the page. */}
- <div className="flex-1 min-w-0">
+ <div className="flex-1 min-w-0 w-full">
{activeType === 'people' && (
<>
<h3 className="font-medium text-white">{record.name}</h3>
@@ -623,31 +630,24 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {
{activeType === 'memories' && (
<>
<div className="flex items-center gap-2">
- <h3 className="font-medium text-white">{record.title}</h3>
+ <h3 className="font-medium text-white"><button className="text-left hover:text-port-accent" onClick={() => navigate(`${basePath}/memories/${encodeURIComponent(record.id)}${location.search}`)}>{record.title}</button></h3>
{record.mood && (
<span className="px-2 py-0.5 text-xs rounded border bg-pink-500/20 text-pink-400 border-pink-500/30">
{record.mood}
</span>
)}
</div>
- {record.content && (
- // Imported ChatGPT transcripts can be multi-KB markdown with
- // images. Rendering full MarkdownOutput for every card was
- // ballooning the Memory tab past 100k DOM nodes. Show a
- // plain teaser here; the full thread opens in ConversationViewer.
- // Hand-written memories stay plain pre-wrap text.
- record.source === 'chatgpt-import'
- ? <p className="text-sm text-gray-400 mt-1 line-clamp-3 break-words">{transcriptTeaser(record.content)}</p>
- : <p className="text-sm text-gray-400 mt-1 whitespace-pre-wrap break-words">{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>
- )}
+ <button
+ onClick={() => navigate(`${basePath}/memories/${encodeURIComponent(record.id)}${location.search}`)}
+ className="mt-1 w-full text-left rounded-lg focus-visible:outline focus-visible:outline-2 focus-visible:outline-port-accent"
+ aria-label={`Read ${record.title || 'memory'}`}
+ >
+ <span className="block text-sm text-gray-400 line-clamp-3 break-words">{transcriptTeaser(record.content)}</span>
+ <MemoryImagePreview record={record} />
+ <span className="mt-2 inline-flex min-h-[44px] items-center gap-1 text-xs text-port-accent">
+ <MessageSquareText size={13} aria-hidden="true" /> Read full entry
+ </span>
+ </button>
{record.tags?.length > 0 && (
<div className="flex gap-1 mt-2 flex-wrap">
{record.tags.map((tag, i) => (
@@ -756,7 +756,7 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {
return (
<button
key={tab.id}
- onClick={() => { setActiveType(tab.id); setStatusFilter(''); setSearchQuery(''); }}
+ onClick={() => { closeReader(); setActiveType(tab.id); setStatusFilter(''); setSearchQuery(''); }}
className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${
isActive
? `${destInfo.color}`
@@ -882,8 +882,14 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {
</div>
)}
- {viewerRecord && (
- <ConversationViewer record={viewerRecord} onClose={() => setViewerRecord(null)} />
+ {recordId && !loading && !viewerRecord && (
+ <Banner tone="warning" title="Entry not found">
+ This entry may have been deleted or archived.
+ <button onClick={closeReader} className="block min-h-[44px] text-port-accent">Back to entries</button>
+ </Banner>
+ )}
+ {viewerRecord && !loading && (
+ <ConversationViewer key={viewerRecord.id} record={viewerRecord} onClose={closeReader} />
)}
</div>
);
diff --git a/client/src/components/brain/tabs/MemoryTab.reader.test.jsx b/client/src/components/brain/tabs/MemoryTab.reader.test.jsx
new file mode 100644
index 0000000000..be7436e2c9
--- /dev/null
+++ b/client/src/components/brain/tabs/MemoryTab.reader.test.jsx
@@ -0,0 +1,60 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter, Route, Routes, useLocation } from 'react-router';
+import MemoryTab from './MemoryTab';
+
+const api = vi.hoisted(() => ({
+ getBrainMemories: vi.fn(), getMemoryBackendStatus: vi.fn().mockResolvedValue({ backend: 'postgres' }),
+ getChatgptArchive: vi.fn()
+}));
+vi.mock('../../../services/api', () => api);
+vi.mock('../../../services/apiBrain', () => api);
+afterEach(() => { cleanup(); vi.clearAllMocks(); vi.unstubAllGlobals(); });
+function Location() { return <output data-testid="location">{useLocation().pathname}</output>; }
+function mount(path = '/brain/memory') {
+ vi.stubGlobal('IntersectionObserver', class {
+ constructor(callback) { this.callback = callback; }
+ observe() { this.callback([{ isIntersecting: true }]); }
+ disconnect() {}
+ });
+ return render(<MemoryRouter initialEntries={[path]}><Location /><Routes>
+ <Route path="/brain/:tab/:recordType?/:recordId?" element={<MemoryTab />} />
+ </Routes></MemoryRouter>);
+}
+
+describe('Brain memory reader', () => {
+ it('previews images, opens rendered handwritten content through a record URL, and closes', async () => {
+ api.getBrainMemories.mockResolvedValue([{ id: 'note-1', title: 'Example note', content: '# Heading\n\n**Important**\n\n![Sketch](https://example.com/sketch.png)' }]);
+ mount();
+ expect(await screen.findByAltText('Sketch')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Read Example note' }));
+ expect(screen.getByTestId('location').textContent).toBe('/brain/memory/memories/note-1');
+ expect(await screen.findByRole('heading', { name: 'Heading' })).toBeTruthy();
+ expect(screen.getByText('Important').tagName).toBe('STRONG');
+ fireEvent.click(screen.getByRole('button', { name: 'Close entry reader' }));
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(api.getChatgptArchive).not.toHaveBeenCalled();
+ });
+
+ it('loads archive-only thumbnails and the complete transcript from a direct URL', async () => {
+ api.getBrainMemories.mockResolvedValue([{ id: 'import-1', title: 'Example import', source: 'chatgpt-import', sourceRef: 'example.json', content: 'Short preview' }]);
+ api.getChatgptArchive.mockImplementation((_ref, options) => Promise.resolve(options?.preview
+ ? { images: [{ src: '/data/brain-imports/example.png', alt: 'Archive thumbnail' }] }
+ : { transcript: '# Complete conversation\n\n![Full image](/data/brain-imports/example.png)' }));
+ mount('/brain/memory/memories/import-1');
+ expect(await screen.findByRole('heading', { name: 'Complete conversation' })).toBeTruthy();
+ expect(await screen.findByAltText('Archive thumbnail')).toBeTruthy();
+ expect(screen.getByAltText('Full image')).toBeTruthy();
+ });
+
+ it('renders saved markdown when an archive is unavailable and identifies stale record URLs', async () => {
+ api.getBrainMemories.mockResolvedValue([{ id: 'import-1', title: 'Example import', source: 'chatgpt-import', sourceRef: 'missing.json', content: '**Saved preview**' }]);
+ api.getChatgptArchive.mockRejectedValue(new Error('Not found'));
+ const view = mount('/brain/memory/memories/import-1');
+ await waitFor(() => expect(screen.getByText('Saved preview', { selector: 'strong' }).tagName).toBe('STRONG'));
+ expect(screen.getByText(/Couldn't load the full transcript/)).toBeTruthy();
+ view.unmount();
+ mount('/brain/memory/memories/deleted');
+ expect(await screen.findByText('Entry not found')).toBeTruthy();
+ });
+});
diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.js
index 5a968ca57b..c1a4b430e2 100644
--- a/client/src/services/apiBrain.js
+++ b/client/src/services/apiBrain.js
@@ -195,8 +195,8 @@ export const uploadChatgptZip = (file, { tags = '', skipEmpty = true, ...options
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)}`);
+export const getChatgptArchive = (name, { preview, ...options } = {}) =>
+ request(`/brain/import/chatgpt/archive/${encodeURIComponent(name)}${preview === 'images' ? '?preview=images' : ''}`, options);
// Brain - Digests & Reviews
export const getBrainLatestDigest = () => request('/brain/digest/latest');
diff --git a/server/lib/README.md b/server/lib/README.md
index 16a2dc8e68..d950270c9c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -730,3 +730,4 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `developmentWorkIdentity.js` | Canonical development task identity and cross-producer ownership matching. |
| `persistentMindProcessAudit.js` | Bounded process-audit schemas, deterministic observations, measured recovery ratios, and closed-vocabulary synthetic finding renderer. |
+| `markdownImages.js` | `markdownImages(content, limit)` — bounded, deduplicated safe markdown image previews for Brain cards and import archives. |
diff --git a/server/lib/index.js b/server/lib/index.js
index d993d2df0d..e400ed7f7a 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -713,3 +713,4 @@ export * from './persistentMindProcessAudit.js';
export * from './contributionSecurityPolicy.js';
export * from './catalogExtractionDraft.js';
+export * from './markdownImages.js';
diff --git a/server/lib/markdownImages.js b/server/lib/markdownImages.js
new file mode 100644
index 0000000000..5ea8e32914
--- /dev/null
+++ b/server/lib/markdownImages.js
@@ -0,0 +1,13 @@
+/** Bounded image projection for cards; accepts the same URL schemes as MarkdownOutput. */
+export function markdownImages(content, limit = 4) {
+ const images = [];
+ const seen = new Set();
+ for (const match of String(content || '').matchAll(/!\[([^\]]*)\]\(([^)]+)\)/g)) {
+ const [, alt, src] = match;
+ if (!/^(https?:\/\/|\/[^/])/.test(src) || seen.has(src)) continue;
+ seen.add(src);
+ images.push({ src, alt });
+ if (images.length >= limit) break;
+ }
+ return images;
+}
diff --git a/server/routes/brainImport.js b/server/routes/brainImport.js
index d358c66a6d..352626dd90 100644
--- a/server/routes/brainImport.js
+++ b/server/routes/brainImport.js
@@ -15,6 +15,7 @@
* GET /api/brain/import/chatgpt/archive/:name Fetch one archived conversation transcript
*/
+import { markdownImages } from '../lib/markdownImages.js';
import { Router } from 'express';
import { z } from 'zod';
import { unlink } from 'fs/promises';
@@ -126,7 +127,7 @@ router.get('/chatgpt/archive/:name', asyncHandler(async (req, res) => {
if (!archived) {
throw new ServerError('Archived conversation not found', { status: 404, code: 'NOT_FOUND' });
}
- res.json(archived);
+ res.json(req.query.preview === 'images' ? { images: markdownImages(archived.transcript) } : archived);
}));
export default router;
diff --git a/server/routes/brainImport.test.js b/server/routes/brainImport.test.js
index 701ab5cdf2..31714e17e2 100644
--- a/server/routes/brainImport.test.js
+++ b/server/routes/brainImport.test.js
@@ -166,3 +166,16 @@ describe('brainImport routes', () => {
expect(res.status).toBe(404);
});
});
+
+it('projects bounded archive-only image previews without transferring the transcript', async () => {
+ chatgptImport.readArchivedConversation.mockResolvedValue({
+ transcript: `${'Long conversation '.repeat(1000)}\n![Cover](/data/brain-imports/example.png)\n![Duplicate](/data/brain-imports/example.png)\n![Unsafe](javascript:alert)\n${Array.from({ length: 8 }, (_, i) => `![Image](https://example.com/${i}.png)`).join('\n')}`,
+ messages: ['private transcript']
+ });
+ const res = await request(buildApp()).get('/api/brain/import/chatgpt/archive/example.json?preview=images');
+ expect(res.status).toBe(200);
+ expect(Object.keys(res.body)).toEqual(['images']);
+ expect(res.body.images).toHaveLength(4);
+ expect(res.body.images[0]).toEqual({ src: '/data/brain-imports/example.png', alt: 'Cover' });
+ expect(res.body.images.every(image => !image.src.startsWith('javascript:'))).toBe(true);
+});