Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Clean up Brain memory assets on delete; show copyable memory ids in UI
Adam Eivy701c0eabcb34
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f309caa8ea..5d66d8dc4a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -129,6 +129,10 @@## Fixed+- **Deleting a Brain memory imported from ChatGPT now removes its on-disk assets instead of orphaning them.** A `chatgpt-import` memory references an archived conversation transcript (`data/brain/imports/chatgpt/<sourceRef>`) and any number of served image/audio/PDF assets (`data/brain/imports/assets/`, embedded as `` links in the transcript). Deleting the memory only tombstoned the JSON record, so those files lived on disk forever — repeatedly importing and deleting exports slowly filled the disk with orphans. The Brain service's `deleteMemoryEntry` now cleans up after a successful delete: it removes the 1:1 archived transcript and unlinks every asset the deleted memory referenced that **no surviving import memory still uses** (a ChatGPT `file-service://` id can legitimately recur across conversations, so shared assets are kept). Cleanup is best-effort — an already-missing file is a no-op and an unlink failure is logged, never thrown, so it can't turn a successful delete into an error. (`server/services/brain.js`, `server/services/chatgptImport.js`)++- **Memory cards now show a copyable short id.** Both the Brain memories list (Brain → Memory) and the CoS memories list (Chief of Staff → Memory) render each record's unique id as a click-to-copy badge in the card's metadata row — so you can read an id off the UI and ask the agent about that specific memory by id. The badge shows a short prefix with the full id in its tooltip; clicking copies the full id. (`client/src/components/ui/CopyableId.jsx`, `client/src/components/brain/tabs/MemoryTab.jsx`, `client/src/components/cos/tabs/MemoryTab.jsx`)+- **Tribe "Add" / "Add Relationship" now visibly surface the new-relationship form.** The Add button (header), the empty-state *Add Relationship* button, and the Care Queue's empty-state all reset to a blank draft — but the contact form is statically rendered in the side column, so resetting an already-empty draft produced no visible change, and on narrow screens the form sat below the fold. Clicking Add now switches to a tab that has the form (Circle, if you're on Focus), resets the draft, scrolls the form into view, and focuses the Name field — so adding a person clearly does something on every screen size. Saving a *new* person also clears the form back to a blank draft (Name re-focused) so the next entry adds another person instead of overwriting the one just saved; editing an existing person still keeps them selected. (`client/src/pages/Tribe.jsx`)- **[issue-1393] The universe base-style probe now scopes its in-flight render per universe instead of remounting on every switch.** The probe spinner used to be kept from leaking across universe switches by remounting the whole `StyleProbeImage` (a `key={universe.id}` in the Universe Builder and Story Builder). That worked but had two costs: every switch re-ran the probe's `{ silent: true }` image-settings GET, and switching *away* from an in-flight render abandoned its completion — the server still filed the image, but switching back never resumed the spinner or pinned the result onto the universe's style refs for that session. `useSingleImageRender` now takes a `scopeId` that namespaces the single-target key per universe (`<id>:__single__`), so the displayed universe's job is read without a remount: no per-switch settings refetch, and switching back to a still-running (or already-finished) render resumes it and captures its completion. The mid-render style-drift guard is now keyed per universe too, so a stale image can't pin to the wrong record when two probes overlap across a switch. And because the render slot no longer remounts to reset itself, a render that *fails or is canceled* (which never produces a filename, so the slot's completion path can't clear it) now clears the stuck job explicitly — so a failed probe leaves the slot ready to re-render instead of disabling regenerate for the rest of the session. (`client/src/hooks/useSingleImageRender.js`, `client/src/components/universe/{StyleProbeImage,EntryThumbSlot}.jsx`, `client/src/pages/{UniverseBuilder,StoryBuilder}.jsx`, #1393)diff --git a/client/src/components/brain/tabs/MemoryTab.jsx b/client/src/components/brain/tabs/MemoryTab.jsxindex 4a45bc424a..6bd31cf078 100644--- a/client/src/components/brain/tabs/MemoryTab.jsx+++ b/client/src/components/brain/tabs/MemoryTab.jsx@@ -24,6 +24,7 @@ import {import { timeAgo } from '../../../utils/formatters';import BrailleSpinner from '../../BrailleSpinner';import InlineConfirmRow from '../../ui/InlineConfirmRow';+import CopyableId from '../../ui/CopyableId';import { useConfirmDelete } from '../../../hooks/useConfirmDelete';export default function MemoryTab({ onRefresh }) {@@ -558,15 +559,18 @@ export default function MemoryTab({ onRefresh }) {</>)}- <p className="text-xs text-gray-500 mt-2">- {activeType === 'memories' && record.source === 'chatgpt-import' && (record.sourceUpdatedAt || record.sourceCreatedAt)- // Imported entries all share the bulk-import updatedAt, so show the- // original conversation recency instead (matches the list sort order) —- // but only when a source clock exists; a clockless import falls back to- // the honest "Updated {import time}" rather than mislabeling it.- ? `Conversation ${timeAgo(record.sourceUpdatedAt || record.sourceCreatedAt)}`- : `Updated ${timeAgo(record.updatedAt)}`}- </p>+ <div className="flex items-center gap-2 mt-2 flex-wrap">+ <p className="text-xs text-gray-500">+ {activeType === 'memories' && record.source === 'chatgpt-import' && (record.sourceUpdatedAt || record.sourceCreatedAt)+ // Imported entries all share the bulk-import updatedAt, so show the+ // original conversation recency instead (matches the list sort order) —+ // but only when a source clock exists; a clockless import falls back to+ // the honest "Updated {import time}" rather than mislabeling it.+ ? `Conversation ${timeAgo(record.sourceUpdatedAt || record.sourceCreatedAt)}`+ : `Updated ${timeAgo(record.updatedAt)}`}+ </p>+ <CopyableId id={record.id} />+ </div></div><div className="flex items-center gap-1">diff --git a/client/src/components/cos/tabs/MemoryTab.jsx b/client/src/components/cos/tabs/MemoryTab.jsxindex d1dbedb58a..8ce7f5aa63 100644--- a/client/src/components/cos/tabs/MemoryTab.jsx+++ b/client/src/components/cos/tabs/MemoryTab.jsx@@ -14,6 +14,7 @@ import ProviderModelSelector from '../../ProviderModelSelector';import useProviderModels from '../../../hooks/useProviderModels';import BrailleSpinner from '../../BrailleSpinner';import InlineConfirmRow from '../../ui/InlineConfirmRow';+import CopyableId from '../../ui/CopyableId';import { useConfirmDelete } from '../../../hooks/useConfirmDelete';export default function MemoryTab({ apps = [] }) {@@ -423,7 +424,7 @@ export default function MemoryTab({ apps = [] }) {))}</div>)}- <div className="text-xs text-gray-500 mt-2 flex flex-wrap gap-2">+ <div className="text-xs text-gray-500 mt-2 flex flex-wrap items-center gap-2"><span>{new Date(memory.createdAt).toLocaleDateString()}</span><span>*</span><span>importance: {((memory.importance || 0.5) * 100).toFixed(0)}%</span>@@ -433,6 +434,8 @@ export default function MemoryTab({ apps = [] }) {<span className="text-port-accent">{getAppName(memory.sourceAppId, apps)}</span></>)}+ <span>*</span>+ <CopyableId id={memory.id} /></div></div><div className="flex gap-2 sm:gap-1">diff --git a/client/src/components/ui/CopyableId.jsx b/client/src/components/ui/CopyableId.jsxnew file mode 100644index 0000000000..30102f7f4d--- /dev/null+++ b/client/src/components/ui/CopyableId.jsx@@ -0,0 +1,26 @@+import { Copy } from 'lucide-react';+import { copyToClipboard } from '../../lib/clipboard';++// Inline, click-to-copy record id badge. Shows a short prefix of the id (full+// id stays in the `title` tooltip and is what gets copied) so the user can read+// it off a card and reference a specific record by id when asking the agent+// questions about it. Monospace + muted so it reads as metadata, not content.+//+// id — the full record id (required; renders nothing when absent)+// chars — how many leading chars to show before the ellipsis (default 8)+export default function CopyableId({ id, chars = 8, className = '' }) {+ if (!id) return null;+ const short = id.length > chars ? `${id.slice(0, chars)}…` : id;+ return (+ <button+ type="button"+ onClick={(e) => { e.stopPropagation(); copyToClipboard(id, 'ID copied'); }}+ title={`Copy id: ${id}`}+ aria-label={`Copy id ${id}`}+ className={`inline-flex items-center gap-1 font-mono text-[10px] text-gray-500 hover:text-gray-300 transition-colors ${className}`.trim()}+ >+ <span>{short}</span>+ <Copy size={10} aria-hidden="true" className="shrink-0" />+ </button>+ );+}diff --git a/client/src/components/ui/CopyableId.test.jsx b/client/src/components/ui/CopyableId.test.jsxnew file mode 100644index 0000000000..472a9caf02--- /dev/null+++ b/client/src/components/ui/CopyableId.test.jsx@@ -0,0 +1,42 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent } from '@testing-library/react';++const copyToClipboard = vi.fn();+vi.mock('../../lib/clipboard', () => ({+ copyToClipboard: (...args) => copyToClipboard(...args),+}));++import CopyableId from './CopyableId';++describe('CopyableId', () => {+ beforeEach(() => copyToClipboard.mockClear());++ it('renders nothing without an id', () => {+ const { container } = render(<CopyableId id={undefined} />);+ expect(container.firstChild).toBeNull();+ });++ it('shows a truncated id but copies the full id on click', () => {+ render(<CopyableId id="abcdef1234567890" />);+ // Default 8-char prefix + ellipsis.+ expect(screen.getByText('abcdef12…')).toBeTruthy();+ fireEvent.click(screen.getByRole('button'));+ expect(copyToClipboard).toHaveBeenCalledWith('abcdef1234567890', 'ID copied');+ });++ it('does not truncate an id shorter than the char window', () => {+ render(<CopyableId id="short" chars={8} />);+ expect(screen.getByText('short')).toBeTruthy();+ });++ it('stops click propagation so it does not trigger row handlers', () => {+ const onRowClick = vi.fn();+ render(+ <div onClick={onRowClick}>+ <CopyableId id="abcdef1234567890" />+ </div>+ );+ fireEvent.click(screen.getByRole('button'));+ expect(onRowClick).not.toHaveBeenCalled();+ });+});diff --git a/server/services/brain.js b/server/services/brain.jsindex b1f8c17214..bfdc2a8edf 100644--- a/server/services/brain.js+++ b/server/services/brain.js@@ -18,6 +18,7 @@ import { safeJSONParse } from '../lib/fileUtils.js';import { runPromptThroughProvider } from '../lib/promptRunner.js';import { getDomainAutonomyMode } from './cosState.js';import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';+import { deleteMemoryAssets } from './chatgptImport.js';import {classifierOutputSchema,digestOutputSchema,@@ -768,7 +769,29 @@ export const getMemoryEntries = storage.getMemoryEntries;export const getMemoryEntryById = storage.getMemoryEntryById;export const createMemoryEntry = storage.createMemoryEntry;export const updateMemoryEntry = storage.updateMemoryEntry;-export const deleteMemoryEntry = storage.deleteMemoryEntry;++/**+ * Delete a memory entry AND clean up its on-disk assets.+ *+ * A `chatgpt-import` memory references an archived transcript (`sourceRef`) and+ * any number of served asset files (images/audio/PDFs) embedded in its markdown+ * `content`. The storage-level delete only tombstones the JSON record — without+ * this wrapper those files orphan forever under `data/brain/imports/`. We load+ * the record first (to know what it referenced) and the surviving import+ * memories (so a shared asset still in use isn't pulled out from under them).+ */+export async function deleteMemoryEntry(id) {+ const record = await storage.getMemoryEntryById(id);+ const deleted = await storage.deleteMemoryEntry(id);+ if (deleted && record?.source === 'chatgpt-import') {+ const survivors = (await storage.getMemoryEntries())+ .filter((m) => m.id !== id && m.source === 'chatgpt-import')+ .map((m) => m.content);+ await deleteMemoryAssets(record, survivors);+ }+ return deleted;+}+export const getLinks = storage.getLinks;export const getLinkById = storage.getLinkById;export const getLinkByUrl = storage.getLinkByUrl;diff --git a/server/services/chatgptImport.js b/server/services/chatgptImport.jsindex 5e5788f795..abbfef995f 100644--- a/server/services/chatgptImport.js+++ b/server/services/chatgptImport.js@@ -20,7 +20,7 @@*/import { join } from 'path';-import { writeFile } from 'fs/promises';+import { writeFile, unlink } from 'fs/promises';import { ensureDir, PATHS, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';import { createMemoryEntry } from './brainStorage.js';@@ -28,7 +28,10 @@ const MAX_MEMORY_CONTENT = 9800;const MAX_TITLE_LEN = 200;const MAX_TAG_LEN = 50;const ROLE_LABEL = { user: 'You', assistant: 'ChatGPT', system: 'System', tool: 'Tool' };-const IMPORT_ROOT = join(PATHS.brain, 'imports', 'chatgpt');+// Resolve lazily — computing it at module load reads PATHS.brain, which is+// undefined in suites that mock fileUtils with a partial PATHS (e.g.+// brain.test.js) and would crash the import. Each call is a cheap path join.+const importRoot = () => join(PATHS.brain, 'imports', 'chatgpt');const sanitizeTag = (s) => String(s || '').toLowerCase()@@ -307,20 +310,90 @@ 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));+ const raw = await tryReadFile(join(importRoot(), name));if (!raw) return null;return safeJSONParse(raw, null, { allowArray: false });}+// Served-asset URL prefix every imported image/audio/file link points at (see+// chatgptZipImport.js — assets land at `/data/brain-imports/<assetId><ext>`).+const ASSET_URL_PREFIX = '/data/brain-imports/';++/**+ * Extract the bare asset filenames an imported memory's markdown `content`+ * references (`/data/brain-imports/<file>`). Returns a Set of filenames (no+ * directory, no query/hash). The leading-bytes restriction in the asset+ * filename charset means a simple bounded match is safe against path traversal —+ * we additionally reject any name that isn't a flat basename below.+ */+export const extractAssetFileNames = (content) => {+ const names = new Set();+ if (typeof content !== 'string') return names;+ // Match the served prefix followed by a flat filename (no slash) up to the+ // markdown link close `)`, whitespace, or end — then strip any trailing+ // punctuation a transcript might place right after the URL.+ const re = new RegExp(`${ASSET_URL_PREFIX.replace(/\//g, '\\/')}([^)\\s]+)`, 'g');+ let m;+ while ((m = re.exec(content)) !== null) {+ const name = m[1].replace(/[).,]+$/, '');+ // Flat basename only — never a path that could escape the assets dir.+ if (name && !name.includes('/') && !name.includes('\\') && !name.includes('..')) {+ names.add(name);+ }+ }+ return names;+};++/**+ * Delete the on-disk assets + archived transcript that belonged to a deleted+ * `chatgpt-import` memory, leaving no orphans under `data/brain/imports/`.+ *+ * `survivingContents` is the `content` of every OTHER live import memory — an+ * asset id can legitimately appear in more than one conversation (ChatGPT+ * reuses a `file-service://` id across chats), so an asset is only unlinked when+ * NO surviving memory still references it. The archived transcript JSON is keyed+ * 1:1 by `sourceRef`, so it's always safe to remove with its memory.+ *+ * Best-effort: a missing file is a no-op (already gone), and any unlink failure+ * is logged but never thrown — cleanup must not turn a successful delete into a+ * request error.+ */+export async function deleteMemoryAssets(record, survivingContents = []) {+ if (!record || record.source !== 'chatgpt-import') return;++ // 1. Archived transcript — 1:1 with this memory's sourceRef, always removable.+ const ref = String(record.sourceRef || '');+ if (/^[a-zA-Z0-9-_]+\.json$/.test(ref)) {+ await unlink(join(importRoot(), ref)).catch((err) => {+ if (err?.code !== 'ENOENT') console.error(`⚠️ Failed to remove archived transcript ${ref}: ${err.message}`);+ });+ }++ // 2. Served assets — only those no surviving import memory still references.+ const referenced = extractAssetFileNames(record.content);+ if (referenced.size === 0) return;+ const stillUsed = new Set();+ for (const content of survivingContents) {+ for (const name of extractAssetFileNames(content)) stillUsed.add(name);+ }+ const orphaned = [...referenced].filter((name) => !stillUsed.has(name));+ await Promise.all(orphaned.map((name) =>+ unlink(join(PATHS.brainImportAssets, name)).catch((err) => {+ if (err?.code !== 'ENOENT') console.error(`⚠️ Failed to remove import asset ${name}: ${err.message}`);+ })+ ));+ if (orphaned.length) console.log(`🧠 Removed ${orphaned.length} orphaned import asset(s) for memory ${record.id}`);+}+/*** Persist one conversation's full transcript + structured messages to the* import archive directory.*/async function archiveConversation(summary) {- await ensureDir(IMPORT_ROOT);+ await ensureDir(importRoot());const id = summary.id || `conv-${Date.now()}`;const fname = `${safeFilename(id)}.json`;- const filePath = join(IMPORT_ROOT, fname);+ const filePath = join(importRoot(), fname);const payload = {id,title: summary.title,@@ -368,7 +441,7 @@ export async function importConversations(parsed, options = {}) {.filter(Boolean);const skipEmpty = options.skipEmpty !== false;- await ensureDir(IMPORT_ROOT);+ await ensureDir(importRoot());const results = [];let imported = 0;@@ -420,9 +493,9 @@ export async function importConversations(parsed, options = {}) {imported,skipped,archived,- archiveDir: IMPORT_ROOT,+ archiveDir: importRoot(),results};}-export const __test = { sanitizeTag, cleanTitle, partsToText, buildContent, assetPointerId };+export const __test = { sanitizeTag, cleanTitle, partsToText, buildContent, assetPointerId, extractAssetFileNames };diff --git a/server/services/chatgptImport.test.js b/server/services/chatgptImport.test.jsindex 7072d41841..79cb7c5dc1 100644--- a/server/services/chatgptImport.test.js+++ b/server/services/chatgptImport.test.js@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { mkdtemp, rm, readdir, readFile } from 'fs/promises';+import { mkdtemp, rm, readdir, readFile, mkdir, writeFile } from 'fs/promises';+import { existsSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';@@ -14,15 +15,19 @@ let importConversations;let extractMessages;let formatTranscript;let readArchivedConversation;+let deleteMemoryAssets;+let extractAssetFileNames;+let ASSETS_DIR;describe('chatgptImport service', () => {beforeEach(async () => {TMP = await mkdtemp(join(tmpdir(), 'portos-chatgpt-'));// Re-require the module so it picks up the new TMPvi.resetModules();+ ASSETS_DIR = join(TMP, 'imports', 'assets');vi.doMock('../lib/fileUtils.js', async () => {const actual = await vi.importActual('../lib/fileUtils.js');- return { ...actual, PATHS: { ...actual.PATHS, brain: TMP } };+ return { ...actual, PATHS: { ...actual.PATHS, brain: TMP, brainImportAssets: ASSETS_DIR } };});vi.doMock('./brainStorage.js', () => ({createMemoryEntry: vi.fn(async (data) => ({ id: `mem-${Math.random().toString(36).slice(2, 8)}`, ...data }))@@ -33,6 +38,8 @@ describe('chatgptImport service', () => {extractMessages = mod.extractMessages;formatTranscript = mod.formatTranscript;readArchivedConversation = mod.readArchivedConversation;+ deleteMemoryAssets = mod.deleteMemoryAssets;+ extractAssetFileNames = mod.__test.extractAssetFileNames;const storage = await import('./brainStorage.js');createMemoryEntryMock = storage.createMemoryEntry;});@@ -269,4 +276,90 @@ describe('chatgptImport service', () => {expect(await readArchivedConversation('does-not-exist.json')).toBeNull();});});++ describe('extractAssetFileNames', () => {+ it('pulls flat asset filenames out of markdown content', () => {+ const content = [+ '',+ '[🔊 voice](/data/brain-imports/file-def.mp3)',+ 'Some text with a [📎 doc](/data/brain-imports/file-ghi.pdf).',+ ].join('\n');+ const names = extractAssetFileNames(content);+ expect([...names].sort()).toEqual(['file-abc.png', 'file-def.mp3', 'file-ghi.pdf']);+ });++ it('ignores unrelated urls and rejects path-traversal segments', () => {+ const content = [+ '',+ '',+ '',+ ].join('\n');+ expect([...extractAssetFileNames(content)]).toEqual(['file-ok.png']);+ });++ it('returns an empty set for non-string / asset-free content', () => {+ expect(extractAssetFileNames(null).size).toBe(0);+ expect(extractAssetFileNames('plain memory text').size).toBe(0);+ });+ });++ describe('deleteMemoryAssets', () => {+ const writeAsset = async (name) => {+ await mkdir(ASSETS_DIR, { recursive: true });+ await writeFile(join(ASSETS_DIR, name), 'x');+ };++ it('removes the archived transcript and orphaned assets of a deleted import', async () => {+ await importConversations(parseExport([sampleConversation()])); // writes conv-1.json archive+ await writeAsset('file-a.png');+ await writeAsset('file-b.mp3');+ expect(existsSync(join(TMP, 'imports', 'chatgpt', 'conv-1.json'))).toBe(true);++ await deleteMemoryAssets({+ id: 'mem-1',+ source: 'chatgpt-import',+ sourceRef: 'conv-1.json',+ content: '\n[🔊](/data/brain-imports/file-b.mp3)',+ }, []);++ expect(existsSync(join(TMP, 'imports', 'chatgpt', 'conv-1.json'))).toBe(false);+ expect(existsSync(join(ASSETS_DIR, 'file-a.png'))).toBe(false);+ expect(existsSync(join(ASSETS_DIR, 'file-b.mp3'))).toBe(false);+ });++ it('keeps an asset that a surviving import memory still references', async () => {+ await writeAsset('file-shared.png');+ await writeAsset('file-solo.png');++ await deleteMemoryAssets({+ id: 'mem-1',+ source: 'chatgpt-import',+ sourceRef: 'gone.json',+ content: '\n',+ }, ['']);++ // Shared asset survives (another memory uses it); solo asset is removed.+ expect(existsSync(join(ASSETS_DIR, 'file-shared.png'))).toBe(true);+ expect(existsSync(join(ASSETS_DIR, 'file-solo.png'))).toBe(false);+ });++ it('is a no-op for non-import memories', async () => {+ await writeAsset('file-keep.png');+ await deleteMemoryAssets({+ id: 'mem-1',+ source: undefined,+ content: '',+ }, []);+ expect(existsSync(join(ASSETS_DIR, 'file-keep.png'))).toBe(true);+ });++ it('tolerates already-missing files without throwing', async () => {+ await expect(deleteMemoryAssets({+ id: 'mem-1',+ source: 'chatgpt-import',+ sourceRef: 'never-written.json',+ content: '',+ }, [])).resolves.toBeUndefined();+ });+ });});