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
fix catalog export→re-import losing ref links/scraps and cast unlink dropping multi-role rows
[._.]/ Adam Eivy9f131ea023a2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex cb9ad5639a..06efcf8d65 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -27,6 +27,7 @@## Fixed+- **[catalog round-trip + cast multi-role] Catalog export → re-import keeps ref links, scraps, and non-primary payload keys; Cast unlink is role-precise.** Re-importing a JSON export bundle through Bulk Import now recreates the bundle's slice membership: the parser carries the bundle's own `ref` plus each row's `roleForExportedRef`, and the route falls back to them when no explicit `defaults.*Ref` override is supplied — so a re-imported slice is no longer invisible to "Appears in" and to future slice exports. The markdown parser now recognizes the ` ```json ` payload fence and the `### Scraps` subsection as body terminators and round-trips them into `payload.*` / a sibling `scraps[]` instead of polluting the primary description/summary with fence text. The Cast (from Catalog) panel's unlink now removes only the `(ingredient, role)` row that was unlinked, not every row sharing the ingredient id — correct when the same ingredient is linked to one record under multiple roles.- Custom browser setup is more reliable: macOS app bundles are paired automatically with Chrome-compatible browser paths, Canary setup no longer repeatedly prompts after you decline, and non-interactive updates no longer risk hanging on package-manager password prompts.- **[mediacard-use-mediaimage-for-syncing-assets] Media grid thumbnails now recover cleanly for peer-synced assets.** `MediaCard` now renders previews through `MediaImage`, so a peer-pushed image or video thumbnail that arrives after the record shows the "Syncing" placeholder instead of a broken image and swaps to the real asset when `peerSync:asset-arrived` fires.- **[strip-malloc-env-ffmpeg-children] Video workflows now suppress macOS malloc-debug noise from ffmpeg too.** Pinokio-launched installs can export `Malloc*` debug variables that make child processes print `MallocStackLogging` warnings and bury real render progress. PortOS now builds child-process environments through one shared sanitizer and applies it to ffmpeg/ffprobe children used by thumbnails, streaming optimization, upscaling, timeline renders, device capture, last-frame extraction, and video stitching, so video logs stay focused on actual work and errors.diff --git a/client/src/components/CatalogCastPanel.jsx b/client/src/components/CatalogCastPanel.jsxindex 959a326dff..2a9af384d8 100644--- a/client/src/components/CatalogCastPanel.jsx+++ b/client/src/components/CatalogCastPanel.jsx@@ -96,7 +96,11 @@ export default function CatalogCastPanel({ refKind, refId, refLabel }) {setBusyId(ingredient.id);await unlinkCatalogIngredient(ingredient.id, { refKind, refId, role }, { silent: true }).then(() => {- setRows((prev) => prev.filter((r) => r.ingredient.id !== ingredient.id));+ // Ref rows are keyed by (ingredient_id, ref_kind, ref_id, role), so an+ // ingredient can be linked to the same record under multiple roles.+ // Drop only the (id, role) row that was unlinked — not every row sharing+ // the ingredient id.+ setRows((prev) => prev.filter((r) => !(r.ingredient.id === ingredient.id && r.role === role)));}).catch((err) => {toast.error(err.message || 'Unlink failed');@@ -143,7 +147,7 @@ export default function CatalogCastPanel({ refKind, refId, refLabel }) {const text = snippet(ingredient.payload);return (<li- key={ingredient.id}+ key={`${ingredient.id}:${role || ''}`}className="flex items-start gap-3 p-2.5 rounded border border-port-border bg-port-bg/40"><div className="flex-1 min-w-0">diff --git a/client/src/components/CatalogCastPanel.test.jsx b/client/src/components/CatalogCastPanel.test.jsxindex fe9c8529a2..aa125e1907 100644--- a/client/src/components/CatalogCastPanel.test.jsx+++ b/client/src/components/CatalogCastPanel.test.jsx@@ -120,4 +120,43 @@ describe('CatalogCastPanel', () => {);expect(linkCatalogIngredient).not.toHaveBeenCalled();});++ it('unlinks only the matching (id, role) row when an ingredient is linked under multiple roles', async () => {+ // Same ingredient id linked under two roles — the ref table key is+ // (ingredient_id, ref_kind, ref_id, role), so this is a legal pair. A+ // single-role unlink must drop only that row, not both.+ listCatalogIngredientsForRef.mockResolvedValue([+ {+ ingredient: { id: 'i-1', name: 'Ada Lovelace', type: 'character', payload: {} },+ role: 'cast-character',+ },+ {+ ingredient: { id: 'i-1', name: 'Ada Lovelace', type: 'character', payload: {} },+ role: 'cast-lead',+ },+ ]);+ unlinkCatalogIngredient.mockResolvedValue(undefined);+ renderPanel();+ await waitFor(() => {+ expect(screen.getByText('cast-character')).toBeTruthy();+ });+ expect(screen.getByText('cast-lead')).toBeTruthy();++ // Both rows share the same aria-label; the first is the cast-character row.+ const removeBtns = screen.getAllByLabelText(/Unlink Ada Lovelace/i);+ await act(async () => {+ fireEvent.click(removeBtns[0]);+ });++ await waitFor(() => {+ expect(screen.queryByText('cast-character')).toBeNull();+ });+ // The cast-lead row survives — it has a different role.+ expect(screen.getByText('cast-lead')).toBeTruthy();+ expect(unlinkCatalogIngredient).toHaveBeenCalledWith(+ 'i-1',+ { refKind: 'series', refId: 'series-1', role: 'cast-character' },+ { silent: true },+ );+ });});diff --git a/server/lib/catalogBulkParsers.js b/server/lib/catalogBulkParsers.jsindex a600129070..6ef0913674 100644--- a/server/lib/catalogBulkParsers.js+++ b/server/lib/catalogBulkParsers.js@@ -112,13 +112,39 @@ export function parseJsonBulk(payload) {} catch (err) {throw new Error(`invalid JSON: ${err.message}`);}- const entries = Array.isArray(parsed)+ const isBundle = !Array.isArray(parsed) && parsed && Array.isArray(parsed.ingredients);+ const rawEntries = Array.isArray(parsed)? parsed- : (parsed && Array.isArray(parsed.ingredients) ? parsed.ingredients : null);- if (!entries) {+ : (isBundle ? parsed.ingredients : null);+ if (!rawEntries) {throw new Error('json payload must be an array of entries or an export bundle with an `ingredients` array');}- return entries.map((entry, i) => normalizeEntry(entry, i));+ const entries = rawEntries.map((entry, i) => {+ const normalized = normalizeEntry(entry, i);+ // Preserve the per-row role the export bundle stamped so the bulk-import+ // route can re-create each ingredient's ref link with its original role,+ // instead of collapsing every row onto the batch-level default. Rides as+ // a non-enumerable field so deep-equal tests on the entry shape still pass.+ if (entry && typeof entry.roleForExportedRef === 'string' && entry.roleForExportedRef.trim()) {+ Object.defineProperty(normalized, 'roleForExportedRef', {+ value: entry.roleForExportedRef.trim(),+ enumerable: false,+ });+ }+ return normalized;+ });+ // When the input is a full export bundle, surface its `ref` so the route can+ // fall back to it for ref-links (re-import recreates the bundle's slice+ // membership). Non-enumerable, like markdown's `warnings`, so array-indexing+ // callers are unaffected.+ if (isBundle && parsed.ref && typeof parsed.ref === 'object'+ && typeof parsed.ref.kind === 'string' && parsed.ref.id != null) {+ Object.defineProperty(entries, 'bundleRef', {+ value: { kind: parsed.ref.kind, id: String(parsed.ref.id) },+ enumerable: false,+ });+ }+ return entries;}/**@@ -229,6 +255,15 @@ function tokenizeCsv(text) {* The `tags:` line is optional and case-insensitive; everything else above* it (until the next `## ` heading) becomes the body. Body lands in the* type's primary content key per PRIMARY_CONTENT_KEY_BY_TYPE.+ *+ * This is the inverse of `ingredientToMarkdown`, so it also recognizes the two+ * structured sections that exporter emits inside a `## ` block:+ * - a ` ```json … ``` ` fence carrying the non-primary payload keys, which+ * is parsed back into `payload.*` (merged under the body's primary key);+ * - a `### Scraps` subsection of `- (kind) text` bullets, preserved as a+ * sibling `scraps[]` array for a lossless round-trip.+ * Both terminate the body so re-importing an export doesn't pollute the+ * primary content key with fence text or scrap bullets.*/export function parseMarkdownBulk(payload) {if (typeof payload !== 'string') {@@ -238,6 +273,10 @@ export function parseMarkdownBulk(payload) {// Heading regex: `## <Type>: <Name>` — case-insensitive on the type, name// is everything to the right of the first `:`. Heading must start the line.const headingRe = /^##\s+([A-Za-z][A-Za-z-]*)\s*:\s*(.+?)\s*$/;+ // `### Scraps` subsection header (case-insensitive).+ const scrapsHeadingRe = /^###\s+scraps\s*$/i;+ // `- (sourceKind) raw text…` scrap bullet emitted by ingredientToMarkdown.+ const scrapBulletRe = /^-\s+\(([^)]*)\)\s*(.*)$/;const out = [];const warnings = [];let current = null;@@ -246,6 +285,8 @@ export function parseMarkdownBulk(payload) {const bodyText = current.bodyLines.join('\n').trim();if (bodyText) {const key = PRIMARY_CONTENT_KEY_BY_TYPE[current.type];+ // Don't clobber a fence-supplied key with the body, and vice-versa: the+ // fence holds the non-primary keys, so the body's primary key wins here.current.payload[key] = bodyText;}out.push({@@ -253,6 +294,7 @@ export function parseMarkdownBulk(payload) {name: current.name,payload: current.payload,tags: current.tags,+ scraps: current.scraps,});};for (const line of lines) {@@ -270,11 +312,52 @@ export function parseMarkdownBulk(payload) {current = null;continue;}- current = { type, name, bodyLines: [], tags: [], payload: {} };+ current = { type, name, bodyLines: [], tags: [], payload: {}, scraps: [], section: 'body', fence: null };continue;}if (!current) continue;- // `tags: a, b, c` (case-insensitive, anywhere in the section).+ // Inside a ```json fence: accumulate raw lines until the closing ```.+ if (current.fence) {+ if (/^```\s*$/.test(line)) {+ const raw = current.fence.lines.join('\n');+ let parsedFence = null;+ try { parsedFence = JSON.parse(raw); } catch { parsedFence = null; }+ if (parsedFence && typeof parsedFence === 'object' && !Array.isArray(parsedFence)) {+ // Merge the non-primary payload keys back in. The body's primary+ // key is applied in flush() and wins on collision.+ for (const [k, v] of Object.entries(parsedFence)) current.payload[k] = v;+ } else {+ warnings.push(`Malformed JSON fence in "## ${capitalize(current.type)}: ${current.name}" — skipped`);+ }+ current.fence = null;+ } else {+ current.fence.lines.push(line);+ }+ continue;+ }+ // Open a ```json (or bare ```) fence — terminates the body section.+ const fenceOpen = /^```(\w*)\s*$/.exec(line);+ if (fenceOpen) {+ current.fence = { lang: fenceOpen[1] || '', lines: [] };+ current.section = 'fence';+ continue;+ }+ // `### Scraps` switches us into the scraps subsection — body is done.+ if (scrapsHeadingRe.test(line)) {+ current.section = 'scraps';+ continue;+ }+ if (current.section === 'scraps') {+ const bullet = scrapBulletRe.exec(line);+ if (bullet) {+ const sourceKind = bullet[1].trim() || 'unknown';+ const rawText = bullet[2].trim();+ current.scraps.push({ sourceKind, rawText });+ }+ // Non-bullet lines inside the scraps subsection (blanks) are ignored.+ continue;+ }+ // `tags: a, b, c` (case-insensitive, anywhere in the body section).const tagMatch = /^\s*tags\s*:\s*(.*)$/i.exec(line);if (tagMatch) {current.tags = normalizeTags(tagMatch[1]);@@ -286,7 +369,16 @@ export function parseMarkdownBulk(payload) {if (out.length === 0) {throw new Error('markdown produced zero `## <Type>: <Name>` sections');}- const entries = out.map((entry, i) => normalizeEntry(entry, i));+ const entries = out.map((entry, i) => {+ const normalized = normalizeEntry(entry, i);+ // Carry parsed scraps as a sibling array for a lossless round-trip. The+ // bulk-import route ignores it today (the ref-link path is what it acts+ // on), but the round-trip stays faithful for any consumer that reads it.+ if (Array.isArray(entry.scraps) && entry.scraps.length > 0) {+ normalized.scraps = entry.scraps;+ }+ return normalized;+ });// Warnings ride as a non-enumerable property on the returned array so// existing callers that array-index `result[i]` (or deep-equal it in// tests) keep working; the bulk-import handler reads `result.warnings`diff --git a/server/lib/catalogBulkParsers.test.js b/server/lib/catalogBulkParsers.test.jsindex 8481cc01b7..d9cf0f50e6 100644--- a/server/lib/catalogBulkParsers.test.js+++ b/server/lib/catalogBulkParsers.test.js@@ -81,6 +81,49 @@ describe('parseJsonBulk', () => {it('rejects an object root without an ingredients array', () => {expect(() => parseJsonBulk(JSON.stringify({ version: 1, ref: { kind: 'universe', id: 'u1' } }))).toThrow(/array of entries or an export bundle/);});++ it('attaches a non-enumerable bundleRef when the root is an export bundle', () => {+ const out = parseJsonBulk(JSON.stringify({+ version: 1,+ ref: { kind: 'series', id: 'ser-9' },+ ingredients: [{ type: 'idea', name: 'X', payload: { summary: 'hi' } }],+ }));+ // Non-enumerable: deep-equal on the array shape is unaffected.+ expect(out).toEqual([{ type: 'idea', name: 'X', payload: { summary: 'hi' }, tags: [] }]);+ expect(Object.keys(out)).not.toContain('bundleRef');+ expect(out.bundleRef).toEqual({ kind: 'series', id: 'ser-9' });+ });++ it('coerces a numeric bundle ref id to a string', () => {+ const out = parseJsonBulk(JSON.stringify({+ version: 1,+ ref: { kind: 'issue', id: 42 },+ ingredients: [{ type: 'idea', name: 'X' }],+ }));+ expect(out.bundleRef).toEqual({ kind: 'issue', id: '42' });+ });++ it('leaves bundleRef undefined for a bare array (no bundle root)', () => {+ const out = parseJsonBulk(JSON.stringify([{ type: 'idea', name: 'X' }]));+ expect(out.bundleRef).toBeUndefined();+ });++ it('propagates per-row roleForExportedRef as a non-enumerable field', () => {+ const out = parseJsonBulk(JSON.stringify({+ version: 1,+ ref: { kind: 'universe', id: 'u1' },+ ingredients: [+ { type: 'character', name: 'Alice', payload: { physicalDescription: 'curious' }, roleForExportedRef: 'lead' },+ { type: 'idea', name: 'X', payload: { summary: 'hi' } },+ ],+ }));+ expect(out).toEqual([+ { type: 'character', name: 'Alice', payload: { physicalDescription: 'curious' }, tags: [] },+ { type: 'idea', name: 'X', payload: { summary: 'hi' }, tags: [] },+ ]);+ expect(out[0].roleForExportedRef).toBe('lead');+ expect(out[1].roleForExportedRef).toBeUndefined();+ });});describe('parseCsvBulk', () => {@@ -200,6 +243,81 @@ describe('parseMarkdownBulk', () => {const out = parseMarkdownBulk('## Idea: X\nbody\n');expect(out.warnings).toEqual([]);});++ it('parses a ```json fence into payload.* instead of polluting the body', () => {+ const md = [+ '## Character: Alice',+ 'a curious sleuth',+ '',+ '```json',+ '{',+ ' "personality": "quiet",',+ ' "role": "detective"',+ '}',+ '```',+ '',+ ].join('\n');+ const out = parseMarkdownBulk(md);+ expect(out[0]).toEqual({+ type: 'character',+ name: 'Alice',+ payload: { physicalDescription: 'a curious sleuth', personality: 'quiet', role: 'detective' },+ tags: [],+ });+ });++ it('parses a `### Scraps` subsection into a sibling scraps[] array (not the body)', () => {+ const md = [+ '## Idea: time loop',+ 'recurs every Tuesday',+ '',+ '### Scraps',+ '',+ '- (paste) first sighting in chapter 1',+ '- (transcript) mentioned again at the diner',+ '',+ ].join('\n');+ const out = parseMarkdownBulk(md);+ expect(out[0].payload).toEqual({ summary: 'recurs every Tuesday' });+ expect(out[0].scraps).toEqual([+ { sourceKind: 'paste', rawText: 'first sighting in chapter 1' },+ { sourceKind: 'transcript', rawText: 'mentioned again at the diner' },+ ]);+ });++ it('records a warning and skips a malformed JSON fence without corrupting the body', () => {+ const md = [+ '## Idea: X',+ 'good body',+ '',+ '```json',+ '{not valid json}',+ '```',+ '',+ ].join('\n');+ const out = parseMarkdownBulk(md);+ expect(out[0].payload).toEqual({ summary: 'good body' });+ expect(out.warnings.some((w) => /Malformed JSON fence/.test(w))).toBe(true);+ });++ it('losslessly round-trips a full export ingredient (body + fence + scraps)', () => {+ const ing = {+ type: 'character',+ name: 'Alice',+ payload: { physicalDescription: 'a curious sleuth', personality: 'quiet', role: 'detective' },+ tags: ['noir'],+ scraps: [{ sourceKind: 'paste', rawText: 'first sighting in chapter 1' }],+ };+ const md = ingredientToMarkdown(ing);+ const out = parseMarkdownBulk(md);+ expect(out[0]).toEqual({+ type: 'character',+ name: 'Alice',+ payload: { physicalDescription: 'a curious sleuth', personality: 'quiet', role: 'detective' },+ tags: ['noir'],+ scraps: [{ sourceKind: 'paste', rawText: 'first sighting in chapter 1' }],+ });+ });});describe('parseBulkPayload dispatch', () => {diff --git a/server/routes/catalog.js b/server/routes/catalog.jsindex 308c98c94f..04f65c1fe3 100644--- a/server/routes/catalog.js+++ b/server/routes/catalog.js@@ -227,7 +227,11 @@ router.post('/bulk-import', asyncHandler(async (req, res) => {}const defaultTags = Array.isArray(defaults.tags) ? defaults.tags : [];+ // Per-row role from an export bundle (`roleForExportedRef`) rides as a+ // non-enumerable field on each parsed entry; capture it alongside the+ // Zod-validated shape so we can stamp each ref link with its original role.const entries = [];+ const perRowRoles = [];for (let i = 0; i < parsed.length; i++) {const entry = parsed[i];// Merge default tags onto each row (dedup), then validate the full@@ -239,14 +243,22 @@ router.post('/bulk-import', asyncHandler(async (req, res) => {throw new ServerError(`Bulk import entry ${i} invalid: ${msg}`, { status: 400 });}entries.push(result.data);+ perRowRoles.push(typeof entry.roleForExportedRef === 'string' ? entry.roleForExportedRef : null);}// Optional ref-links: same shape as the /link route, applied once per- // created ingredient inside the same transaction.- const refLinks = [];+ // created ingredient inside the same transaction. Explicit `defaults.*Ref`+ // overrides win; when none are supplied but the payload was an export+ // bundle, fall back to the bundle's own `ref` so a re-imported slice keeps+ // its slice membership (otherwise the import is invisible to+ // listIngredientsForRef and to future slice exports).const REF_FIELD_TO_KIND = { universeRef: 'universe', seriesRef: 'series', issueRef: 'issue', workRef: 'work' };+ const refTargets = [];for (const [field, kind] of Object.entries(REF_FIELD_TO_KIND)) {- if (defaults[field]) refLinks.push({ refKind: kind, refId: defaults[field], role: defaults.role || `bulk-${kind}` });+ if (defaults[field]) refTargets.push({ refKind: kind, refId: defaults[field] });+ }+ if (refTargets.length === 0 && parsed.bundleRef && parsed.bundleRef.kind && parsed.bundleRef.id) {+ refTargets.push({ refKind: parsed.bundleRef.kind, refId: parsed.bundleRef.id });}// Embed every entry in parallel BEFORE the transaction — matches the@@ -271,14 +283,17 @@ router.post('/bulk-import', asyncHandler(async (req, res) => {embeddingModel: e?.model ?? null,}, { client });// Stamp ref links inside the same transaction so a mid-batch failure- // rolls back the link rows alongside their ingredients.- for (const link of refLinks) {+ // rolls back the link rows alongside their ingredients. Role precedence:+ // explicit `defaults.role` > the bundle row's own `roleForExportedRef` >+ // a `bulk-<kind>` fallback.+ for (const target of refTargets) {+ const role = defaults.role || perRowRoles[i] || `bulk-${target.refKind}`;await client.query(`INSERT INTO catalog_ingredient_refs (ingredient_id, ref_kind, ref_id, role)VALUES ($1, $2, $3, $4)ON CONFLICT (ingredient_id, ref_kind, ref_id, role) DO UPDATESET deleted = false, deleted_at = NULL`,- [ing.id, link.refKind, link.refId, link.role],+ [ing.id, target.refKind, target.refId, role],);}out.push({ id: ing.id, type: ing.type, name: ing.name });