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

fix: guard SongBook attachment mutations against the 'failed' presence sentinel (#3900)

[._.]/ Adam Eivyf9105fcc5a56
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2460c62e87..ec78203c1a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -52,3 +52,4 @@
- The ~460-line Sprite Manager block in `server/lib/validation.js` now lives in its own `server/lib/spriteValidation.js`, matching the eleven other per-domain validation files. A straight lift wasn't possible: the block leans on four fragments (`recordRenderPinFields`, `cloudModelIdString`, `grokVideoDurationSchema`, `isSafeSubdirFilter`) that music video, universe builder, series, video gen and backup also use, and a domain file can't read them back out of `validation.js` — ESM hoists its `export * from` re-exports, so the read lands in the temporal dead zone. Those four moved to a new leaf `server/lib/sharedSchemas.js` first, with `validation.js` still re-exporting them, so every existing deep import keeps working unchanged.
- The TUI runner's response-file tests no longer fail at random on a busy machine. They drive the runner's one-second size-stability window with fake timers, but the polls behind that window read the response file from real disk — and a real read finishes on Node's threadpool, which advancing fake timers does not wait for. Under load a poll's read could land after the test had already moved on, so the run took the timeout or fallback path and the failure looked like a regression in whatever diff happened to be under test. Those five tests now serve the response file from memory, so every read settles as a microtask the timer advance always drains, and the assertions are unchanged.
- The unused `toolUseLocalModelFilter` export was removed from the client's provider helpers. It offered to hide non-tool-capable local models from a picker, but nothing ever called it, and the approach it represented was already settled the other way: agent and coding pickers annotate each option (`🔧 tool use` / `⚠ no known tool use`) and warn below the select rather than filtering, because the underlying heuristic is a positive allowlist — a non-match means "not a recognized tool-caller", not a proven negative, so filtering would make a newer tool-capable family unselectable. The rationale now lives on the annotation helper that survived.
+- Deleting or uploading a SongBook attachment no longer crashes when the attachment presence lookup failed on page load. That failure parks the attachment state on a `'failed'` sentinel string so the synced list still renders with presence unknown, but both mutation handlers treated it as an array: the delete handler called `.find()` on it and threw `TypeError: prev.find is not a function`, leaving the row on screen, and the upload handler spread the string into six single-character rows. Both now check for an array first, falling back to the record's own synced list on upload and leaving presence genuinely unknown on delete rather than stamping a false "not on this machine" pill.
diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsx
index 9cca5d3464..1e948cb803 100644
--- a/client/src/pages/SongBookViewer.jsx
+++ b/client/src/pages/SongBookViewer.jsx
@@ -131,6 +131,7 @@ export default function SongBookViewer() {
const [retryKey, setRetryKey] = useState(0);
const [draft, setDraft] = useState(null);
// null = not fetched yet, [] = fetched-and-empty (sentinel convention).
+ // 'failed' = presence lookup errored (presence unknown, list still shown).
const [attachments, setAttachments] = useState(null);
// Once any attachment mutation has run, the (slow) initial list response is
// stale — it must not clobber the optimistic upload/delete state.
@@ -330,7 +331,12 @@ export default function SongBookViewer() {
const res = await uploadSongAttachment(id, { filename: file.name, data }, { silent: true });
if (res?.attachment) {
attachmentsMutatedRef.current = true;
- setAttachments((prev) => [...(prev || []), { ...res.attachment, present: true }]);
+ // `prev` may be the 'failed' sentinel — spreading a string would yield
+ // six single-character entries, so fall back to the synced list (#3900).
+ setAttachments((prev) => [
+ ...(Array.isArray(prev) ? prev : (song?.attachments || [])),
+ { ...res.attachment, present: true },
+ ]);
}
}
}, { errorMessage: 'Upload failed' });
@@ -340,10 +346,15 @@ export default function SongBookViewer() {
.then((res) => {
attachmentsMutatedRef.current = true;
// Server returns the updated meta list; carry over local present flags.
- setAttachments((prev) => (res?.attachments || []).map((meta) => ({
- ...meta,
- present: prev?.find((a) => a.filename === meta.filename)?.present ?? false,
- })));
+ // `prev` is the 'failed' sentinel when the presence lookup errored —
+ // `.find()` on that string throws, and presence is genuinely unknown,
+ // so leave the flag off rather than stamping a false absent (#3900).
+ setAttachments((prev) => {
+ const known = Array.isArray(prev) ? prev : null;
+ return (res?.attachments || []).map((meta) => (known
+ ? { ...meta, present: known.find((a) => a.filename === meta.filename)?.present ?? false }
+ : { ...meta }));
+ });
})
.catch((err) => toast.error(err?.message || 'Failed to delete attachment')),
), [confirmDelete, id]);
diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsx
index dd21d4972d..3d34db7fac 100644
--- a/client/src/pages/SongBookViewer.test.jsx
+++ b/client/src/pages/SongBookViewer.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { render, screen, fireEvent, waitFor, within } from '@testing-library/react';
import { MemoryRouter, Routes, Route } from 'react-router';
// Mock the api barrel (RoundEditor.test.jsx harness style).
@@ -113,6 +113,54 @@ describe('SongBookViewer', () => {
expect(screen.queryByRole('link', { name: /Sheet music/ })).toBeNull();
});
+ describe('attachment mutations after a failed presence lookup (#3900)', () => {
+ const SYNCED = [
+ { filename: 'aaaa1111-sheet.pdf', label: 'Sheet music', mime: 'application/pdf', size: 1024, sha256: 'x' },
+ { filename: 'bbbb2222-chart.pdf', label: 'Drum chart', mime: 'application/pdf', size: 2048, sha256: 'y' },
+ ];
+
+ beforeEach(() => {
+ api.getSong.mockResolvedValue(song({ attachments: SYNCED }));
+ api.listSongAttachments.mockRejectedValue(new Error('presence lookup failed'));
+ api.deleteSongAttachment.mockReset();
+ api.uploadSongAttachment.mockReset();
+ });
+
+ it('deletes without throwing on the "failed" sentinel and keeps presence unknown', async () => {
+ api.deleteSongAttachment.mockResolvedValue({ attachments: [SYNCED[1]] });
+ renderPage();
+ // Both synced entries render as links (presence unknown → no absent pill).
+ expect(await screen.findByRole('link', { name: 'Sheet music' })).toBeTruthy();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Delete attachment Sheet music' }));
+ const confirmGroup = screen.getByRole('group', { name: 'Confirm delete Sheet music' });
+ fireEvent.click(within(confirmGroup).getByRole('button', { name: 'Delete' }));
+
+ await waitFor(() => expect(screen.queryByText('Sheet music')).toBeNull());
+ // Survivor still renders, still as a link — no false "not on this machine".
+ expect(screen.getByRole('link', { name: 'Drum chart' })).toBeTruthy();
+ expect(screen.queryByText('not on this machine')).toBeNull();
+ });
+
+ it('appends an upload to the synced list instead of spreading the sentinel string', async () => {
+ api.uploadSongAttachment.mockResolvedValue({
+ attachment: { filename: 'cccc3333-new.pdf', label: 'New sheet', mime: 'application/pdf', size: 512, sha256: 'z' },
+ });
+ renderPage();
+ expect(await screen.findByRole('link', { name: 'Sheet music' })).toBeTruthy();
+
+ const input = document.querySelector('input[type="file"]');
+ const file = new File(['x'], 'new.pdf', { type: 'application/pdf' });
+ fireEvent.change(input, { target: { files: [file] } });
+
+ expect(await screen.findByRole('link', { name: 'New sheet' })).toBeTruthy();
+ // The pre-existing synced entries survive; no 'f','a','i','l','e','d' rows.
+ expect(screen.getByRole('link', { name: 'Sheet music' })).toBeTruthy();
+ expect(screen.getByRole('link', { name: 'Drum chart' })).toBeTruthy();
+ expect(screen.getAllByRole('listitem').length).toBe(3);
+ });
+ });
+
describe('instrument-view toggle (#2656)', () => {
// Sheet with a tab staff so the non-guitar collapse note is observable.
// Six staff lines: identifiably GUITAR tab, so non-guitar views collapse