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: keep import and ingest progress markers on the server so a reload cannot duplicate work (#9943)
[._.]/ Adam Eivye9bf0e913f58
diff --git a/client/src/components/brain/tabs/BrainCollectionPagination.test.jsx b/client/src/components/brain/tabs/BrainCollectionPagination.test.jsxindex a264cc731d..165dccab6d 100644--- a/client/src/components/brain/tabs/BrainCollectionPagination.test.jsx+++ b/client/src/components/brain/tabs/BrainCollectionPagination.test.jsx@@ -28,7 +28,6 @@ const api = vi.hoisted(() => ({updateBrainInboxEntry: vi.fn(),deleteBrainInboxEntry: vi.fn(),markBrainInboxDone: vi.fn(),- markBrainInboxSentToCatalog: vi.fn(),getBrainMemories: vi.fn(),getBrainMemory: vi.fn(),createBrainMemory: vi.fn(),diff --git a/client/src/components/brain/tabs/InboxTab.test.jsx b/client/src/components/brain/tabs/InboxTab.test.jsxindex a51df4aa49..4f4dcf655c 100644--- a/client/src/components/brain/tabs/InboxTab.test.jsx+++ b/client/src/components/brain/tabs/InboxTab.test.jsx@@ -11,7 +11,6 @@ vi.mock('../../../services/api', () => ({updateBrainInboxEntry: vi.fn(),deleteBrainInboxEntry: vi.fn(),markBrainInboxDone: vi.fn(),- markBrainInboxSentToCatalog: vi.fn(),}));vi.mock('../../../services/socket', () => ({diff --git a/client/src/components/songs/ReferenceAnalysis.jsx b/client/src/components/songs/ReferenceAnalysis.jsxindex 85a87bbc2b..9434c29aef 100644--- a/client/src/components/songs/ReferenceAnalysis.jsx+++ b/client/src/components/songs/ReferenceAnalysis.jsx@@ -30,6 +30,7 @@ import toast from '../ui/Toast';import FilePickerButton from '../ui/FilePickerButton';import ScoreSheet from './ScoreSheet.jsx';import { uploadFile, getUploadUrl } from '../../services/api';+import { TEMP_ID_RE } from '../../lib/roundDraft.js';import {transcribeReferenceMidi,referenceMidiTranscriptionEventsUrl,@@ -89,7 +90,7 @@ function SecondsInput({ valueMs, onCommit, ariaLabel }) {* reference fields); the file itself is uploaded immediately so it exists,* matching the recordings flow (upload now, persist the filename on Save).*/-export function ReferenceAudioAttach({ reference, onUpdate }) {+export function ReferenceAudioAttach({ reference, onUpdate, roundId }) {const [busy, setBusy] = useState(false);const [recording, setRecording] = useState(false);const [url, setUrl] = useState('');@@ -101,9 +102,15 @@ export function ReferenceAudioAttach({ reference, onUpdate }) {// "Download audio from URL" (#2120) — best-effort yt-dlp fetch straight onto// the reference. On completion the returned uploads-dir filename is set on the- // draft (flipping to the attached state); the user Saves to keep it, same as- // upload/mic capture.+ // draft (flipping to the attached state). A SAVED reference also gets the file+ // attached server-side as the download finishes, so a reload before Save keeps+ // it (#9943); a row still carrying a temp id exists only in this draft, so for+ // that one the user Saves to keep it, same as upload/mic capture.+ const savedTarget = roundId && !TEMP_ID_RE.test(reference.id)+ ? { roundId, referenceId: reference.id }+ : null;const audioImport = useReferenceAudioImport({+ target: savedTarget,onComplete: (filename) => { setUrl(''); onUpdate('audioFilename', filename); },});diff --git a/client/src/components/songs/ReferenceAnalysis.test.jsx b/client/src/components/songs/ReferenceAnalysis.test.jsxindex 2b8fb309c1..928be6dc79 100644--- a/client/src/components/songs/ReferenceAnalysis.test.jsx+++ b/client/src/components/songs/ReferenceAnalysis.test.jsx@@ -32,11 +32,13 @@ const refImport = vi.hoisted(() => ({start: vi.fn(),cancel: vi.fn(),onComplete: null,+ target: undefined,state: { active: false, percent: 0, stage: null },}));vi.mock('../../hooks/useReferenceAudioImport.js', () => ({default: (opts = {}) => {refImport.onComplete = opts.onComplete;+ refImport.target = opts.target;return { ...refImport.state, start: refImport.start, cancel: refImport.cancel };},}));@@ -421,6 +423,28 @@ describe('ReferenceAudioAttach', () => {expect(onUpdate).toHaveBeenCalledWith('segments', []);});+ // #9943: the server attaches the finished download to a SAVED reference, so a+ // reload before Save keeps it. A row still carrying a temp id exists only in+ // this draft — there is nothing server-side to attach to, so no target.+ describe('download target (#9943)', () => {+ const targetFor = (reference, roundId) => {+ render(<ReferenceAudioAttach reference={reference} roundId={roundId} onUpdate={vi.fn()} />);+ return refImport.target;+ };++ it('names the saved reference so the server can attach the file', () => {+ expect(targetFor({ id: 'ref-1a2b3c4d', url: 'https://x.com' }, 'round-1')).toEqual({ roundId: 'round-1', referenceId: 'ref-1a2b3c4d' });+ });++ it('sends no target for a reference that only exists in the unsaved draft', () => {+ expect(targetFor({ id: 'ref-new-1', url: 'https://x.com' }, 'round-1')).toBeNull();+ });++ it('sends no target when the round id is unknown', () => {+ expect(targetFor({ id: 'ref-1a2b3c4d', url: 'https://x.com' }, undefined)).toBeNull();+ });+ });+it('starts a URL download and wires the finished filename onto the reference draft (#2120)', () => {refImport.start.mockClear();refImport.state = { active: false, percent: 0, stage: null };diff --git a/client/src/components/songs/RoundEditForm.jsx b/client/src/components/songs/RoundEditForm.jsxindex 9c1d207836..6df67d24e4 100644--- a/client/src/components/songs/RoundEditForm.jsx+++ b/client/src/components/songs/RoundEditForm.jsx@@ -307,7 +307,7 @@ export default function RoundEditForm({<div className="flex flex-wrap items-center gap-2 pt-1 border-t border-port-border/60">{isHttpUrl(r.url) ? (<>- <ReferenceAudioAttach reference={r} onUpdate={(key, value) => updateReference(r.id, key, value)} />+ <ReferenceAudioAttach reference={r} roundId={song.id} onUpdate={(key, value) => updateReference(r.id, key, value)} />{r.audioFilename && (<buttontype="button"diff --git a/client/src/hooks/useReferenceAudioImport.js b/client/src/hooks/useReferenceAudioImport.jsindex 20483ceae2..a14f35bbff 100644--- a/client/src/hooks/useReferenceAudioImport.js+++ b/client/src/hooks/useReferenceAudioImport.js@@ -20,15 +20,22 @@ import useSseJobSlot from './useSseJobSlot.js';* uploads dir — `context` is whatever was passed to `start(url, context)`,* captured at kickoff so a slow-finishing job still attaches to the right* target even if the caller's own state changed while it was in flight.+ *+ * `target` is `{ roundId, referenceId }` for a reference that is already saved+ * (or null for an unsaved draft row). It is read at each kickoff, and the server+ * attaches the finished file to that reference itself (#9943), so `onComplete`+ * only has to mirror it into the editor draft.*/-export default function useReferenceAudioImport({ onComplete } = {}) {+export default function useReferenceAudioImport({ onComplete, target = null } = {}) {const { active, percent, stage, start, cancel } = useSseJobSlot({- startRequest: (url) => importReferenceAudio(url, { silent: true }),+ startRequest: (url) => importReferenceAudio(url, { ...target, silent: true }),eventsUrl: referenceAudioImportEventsUrl,cancelRequest: cancelReferenceAudioImport,trimStartArg: true,onComplete: (frame, context) => onComplete?.(frame.filename, context),- successToast: () => 'Reference audio downloaded — Save the song to keep it',+ successToast: (frame) => (frame.attached+ ? 'Reference audio downloaded and attached'+ : 'Reference audio downloaded — Save the song to keep it'),errorFallback: 'Reference audio download failed',canceledMessage: 'Reference audio download cancelled',lostConnectionMessage: 'Lost connection to the reference-audio download',diff --git a/client/src/hooks/useStoryImportIntake.js b/client/src/hooks/useStoryImportIntake.jsindex d9fc93fcaf..e0630d4057 100644--- a/client/src/hooks/useStoryImportIntake.js+++ b/client/src/hooks/useStoryImportIntake.js@@ -33,6 +33,10 @@ export const IMPORT_INTAKE_INITIAL = {// then failed — a re-click must skip commitImport entirely and resume at// session creation, otherwise it re-creates the already-created issues and// overwrites the arc.+ //+ // Both flags are a CACHE of the server's import session (#9943), not the+ // source of truth: a reload loses them, and re-analyzing the same text+ // re-seeds them from `preview.importSession`.committed: false,};@@ -78,7 +82,17 @@ export default function useStoryImportIntake(onCreated) {},{ silent: true },).catch((err) => { toast.error(err?.message || 'Analyze failed'); return null; });- patch({ analyzing: false, ...(res ? { preview: res } : {}) });+ if (res?.importSession?.status === 'committed') {+ toast.info('This manuscript was already imported — Import & build resumes without creating the issues again.');+ }+ patch({+ analyzing: false,+ ...(res ? {+ preview: res,+ committed: res.importSession?.status === 'committed',+ arcAlreadyPersisted: res.importSession?.status === 'arc-persisted',+ } : {}),+ });}, [state, patch]);const retryIssues = useCallback(async () => {@@ -101,7 +115,8 @@ export default function useStoryImportIntake(onCreated) {const { preview: p, contentType, seriesName, universeName, llm, committed, arcAlreadyPersisted } = state;if (!p) return;const issues = p.issueProposals || [];- if (issues.length === 0) { toast.error('No issues were extracted — retry the issue split or adjust the source'); return; }+ // A committed import needs no issues from this payload — it only resumes.+ if (!committed && issues.length === 0) { toast.error('No issues were extracted — retry the issue split or adjust the source'); return; }patch({ committing: true });// Skip commitImport when a prior click already committed (only the later// createStorySession failed) — re-running it would duplicate the@@ -110,7 +125,14 @@ export default function useStoryImportIntake(onCreated) {// On an arcAlreadyPersisted retry the server kept arc/seasons/canon from// the failed commit, so resend issues only — re-sending the full payload// would clobber the persisted state and risk duplicate issues.- const base = { universeId: p.universe.id, seriesId: p.series.id, issues, contentType };+ const base = {+ universeId: p.universe.id,+ seriesId: p.series.id,+ // Server-side session: replays or resumes instead of duplicating (#9943).+ ...(p.importId ? { importId: p.importId } : {}),+ issues,+ contentType,+ };const payload = arcAlreadyPersisted? { ...base, canonSelections: { characters: [], places: [], objects: [] }, arc: null, seasons: [] }: {diff --git a/client/src/hooks/useStoryImportIntake.test.jsx b/client/src/hooks/useStoryImportIntake.test.jsxnew file mode 100644index 0000000000..a91021386d--- /dev/null+++ b/client/src/hooks/useStoryImportIntake.test.jsx@@ -0,0 +1,98 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { renderHook, act } from '@testing-library/react';+import useStoryImportIntake from './useStoryImportIntake';+import { analyzeImport, commitImport, createStorySession } from '../services/api';++vi.mock('../services/api', () => ({+ analyzeImport: vi.fn(),+ commitImport: vi.fn(),+ retryImporterIssues: vi.fn(),+ createStorySession: vi.fn(),+}));+vi.mock('../components/ui/Toast', () => ({+ default: { error: vi.fn(), warning: vi.fn(), info: vi.fn(), success: vi.fn() },+}));++const IMPORT_ID = `imp-${'a'.repeat(32)}`;+const analysis = (importSession = null) => ({+ universe: { id: 'uni-1', name: 'Example Universe' },+ series: { id: 'ser-1', name: 'Example Series' },+ importId: IMPORT_ID,+ importSession,+ canonPreview: { characters: [{ name: 'Aria' }], places: [], objects: [] },+ arcPreview: { logline: 'A logline.', summary: 'A summary.', shape: 'man-in-hole' },+ seasonsPreview: [{ number: 1, title: 'S1' }],+ issueProposals: [{ title: 'Cold Iron', arcPosition: 1 }],+});++// A freshly mounted hook is what a reload leaves behind: no committed flag, no+// persisted-arc flag, no preview. Only the manuscript is re-entered.+async function reanalyze(importSession) {+ analyzeImport.mockResolvedValue(analysis(importSession));+ const onCreated = vi.fn();+ const hook = renderHook(() => useStoryImportIntake(onCreated));+ act(() => hook.result.current.patch({+ universeName: 'Example Universe', seriesName: 'Example Series', source: 'Example manuscript text.',+ }));+ await act(async () => { await hook.result.current.analyze(); });+ return { hook, onCreated };+}++describe('useStoryImportIntake — server import session (#9943)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ createStorySession.mockResolvedValue({ id: 'story-1' });+ });++ it('sends the import id analyze returned, with the full payload on a first commit', async () => {+ const { hook, onCreated } = await reanalyze(null);+ commitImport.mockResolvedValue({ createdIssueIds: ['iss-1'] });++ await act(async () => { await hook.result.current.importAndBuild(); });++ const payload = commitImport.mock.calls[0][0];+ expect(payload.importId).toBe(IMPORT_ID);+ expect(payload.arc).toMatchObject({ shape: 'man-in-hole' });+ expect(onCreated).toHaveBeenCalledWith({ id: 'story-1' });+ });++ it('resumes at session creation after a reload when the server says the import committed', async () => {+ const { hook, onCreated } = await reanalyze({ status: 'committed', createdIssueIds: ['iss-1'] });++ await act(async () => { await hook.result.current.importAndBuild(); });++ expect(commitImport).not.toHaveBeenCalled();+ expect(createStorySession).toHaveBeenCalledOnce();+ expect(onCreated).toHaveBeenCalledWith({ id: 'story-1' });+ });++ it('resumes a committed import even when the re-analysis proposed no issues', async () => {+ analyzeImport.mockResolvedValue({+ ...analysis({ status: 'committed', createdIssueIds: ['iss-1'] }),+ issueProposals: [],+ issueSplitFailed: true,+ });+ const onCreated = vi.fn();+ const hook = renderHook(() => useStoryImportIntake(onCreated));+ act(() => hook.result.current.patch({+ universeName: 'Example Universe', seriesName: 'Example Series', source: 'Example manuscript text.',+ }));+ await act(async () => { await hook.result.current.analyze(); });++ await act(async () => { await hook.result.current.importAndBuild(); });++ expect(commitImport).not.toHaveBeenCalled();+ expect(onCreated).toHaveBeenCalled();+ });++ it('drops the arc from the retry after a reload when the server kept it from a failed commit', async () => {+ const { hook } = await reanalyze({ status: 'arc-persisted', createdIssueIds: [] });+ commitImport.mockResolvedValue({ createdIssueIds: ['iss-1'] });++ await act(async () => { await hook.result.current.importAndBuild(); });++ const payload = commitImport.mock.calls[0][0];+ expect(payload).toMatchObject({ importId: IMPORT_ID, arc: null, seasons: [] });+ expect(payload.canonSelections).toEqual({ characters: [], places: [], objects: [] });+ });+});diff --git a/client/src/pages/CatalogIngest.jsx b/client/src/pages/CatalogIngest.jsxindex be9799fe60..79d64fe48e 100644--- a/client/src/pages/CatalogIngest.jsx+++ b/client/src/pages/CatalogIngest.jsx@@ -29,7 +29,6 @@ import {ingestCatalogVoice,ingestCatalogBrain,} from '../services/apiCatalog';-import { markBrainInboxSentToCatalog } from '../services/apiBrain';import { listUniverseNames } from '../services/apiUniverseBuilder';import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage';@@ -131,10 +130,11 @@ export default function CatalogIngest() {const universesRef = useRef([]);const [universeRef, setUniverseRef] = useState(UNASSIGNED_UNIVERSE);const brainHandledRef = useRef(false);- // Creative inbox note ids handed off from the Brain batch-send. Once the- // commit below succeeds we stamp these consumed so they drop out of the- // inbox's "ready to become ingredients" banner (issue #1722). Held in a ref so- // it survives the history-state clear and the extract/review re-renders.+ // Creative inbox note ids handed off from the Brain batch-send. They ride the+ // commit request, and the server stamps them consumed in that same request so+ // they drop out of the inbox's "ready to become ingredients" banner (issue+ // #1722) — no follow-up call a reload could lose (#9943). Held in a ref so it+ // survives the history-state clear and the extract/review re-renders.const creativeNoteIdsRef = useRef([]);// The scrap id the handoff ids are bound to — set only when the PREFILLED// paste is ingested. Commit consumes the notes ONLY when it commits this exact@@ -572,12 +572,18 @@ export default function CatalogIngest() {universeRef: universeRef === UNASSIGNED_UNIVERSE ? undefined : universeRef,relationships: relsToCommit,};+ // Only a commit of the exact scrap built from the Brain handoff consumes its+ // notes. Not part of `submission` below: they are bookkeeping about the+ // source, not the reviewed content whose identity the operation key tracks.+ const noteIds = creativeNoteIdsRef.current;+ const consumesNotes = noteIds.length > 0 && scrapId === creativeNoteScrapIdRef.current;const submission = JSON.stringify({ scrapId, accepted, ...commitOptions });if (commitOperationRef.current?.submission !== submission) {commitOperationRef.current = { submission, key: uuidv4() };}const result = await commitCatalogScrapDraft(scrapId, accepted, {...commitOptions,+ ...(consumesNotes ? { creativeNoteIds: noteIds } : {}),operationKey: commitOperationRef.current.key,silent: true,}).catch((err) => {@@ -586,22 +592,16 @@ export default function CatalogIngest() {});if (!result) { setCommitting(false); return; }commitOperationRef.current = null;- // Keep `committing` true through the mark request + navigate: re-enabling the- // Commit button before the awaited follow-up finishes would open a- // double-submit window that re-commits the same scrap and duplicates- // ingredients. We navigate away on success, so it never needs clearing.+ // Keep `committing` true through the navigate: re-enabling the Commit button+ // would open a double-submit window that re-commits the same scrap and+ // duplicates ingredients. We navigate away on success, so it never needs+ // clearing.const n = Array.isArray(result.ingredients) ? result.ingredients.length : accepted.length;toast.success(`Added ${n} ingredient${n === 1 ? '' : 's'} to the catalog.`);- // Best-effort: mark the source creative notes consumed so the inbox banner- // stops offering them. Only fires when this ingest came from the Brain- // batch-send (ids present). Failure is non-fatal — the notes just stay- // re-sendable (the prior behavior) — so swallow it silently rather than- // toasting a confusing error after a successful commit.- const noteIds = creativeNoteIdsRef.current;- if (noteIds.length && scrapId && scrapId === creativeNoteScrapIdRef.current) {+ // The server already stamped the source notes consumed; drop the handoff.+ if (consumesNotes) {creativeNoteIdsRef.current = [];creativeNoteScrapIdRef.current = null;- await markBrainInboxSentToCatalog(noteIds, { silent: true }).catch(() => {});}navigate('/catalog');};diff --git a/client/src/pages/CatalogIngest.test.jsx b/client/src/pages/CatalogIngest.test.jsxindex 05a29b1f83..e9567e5442 100644--- a/client/src/pages/CatalogIngest.test.jsx+++ b/client/src/pages/CatalogIngest.test.jsx@@ -377,3 +377,36 @@ it('retains the operation key after a lost response and rotates it for edited reawait waitFor(() => expect(commit()).not.toBeDisabled());expect(commitCatalogScrapDraft.mock.lastCall[2].operationKey).not.toBe(firstKey);});++// #9943: the Brain notes are consumed by the commit request itself. A follow-up+// client call after the commit is lost on a reload, leaving the notes+// re-sendable; riding the commit leaves no gap for that to happen in.+it('sends the Brain handoff note ids with the commit of the scrap built from them', async () => {+ const noteIds = ['3f1c0c52-8d5e-4b8e-9d3c-111111111111', '3f1c0c52-8d5e-4b8e-9d3c-222222222222'];+ createCatalogScrap.mockResolvedValue({ scrap: { id: 'notes-scrap' } });+ extractFromCatalogScrap.mockResolvedValue({+ scrap: { id: 'notes-scrap' },+ draft: { ideas: [{ name: 'A captured idea', summary: 'A useful fragment.' }] },+ });+ commitCatalogScrapDraft.mockResolvedValue({ ingredients: [{ id: 'cat-idea-1' }] });++ render(+ <MemoryRouter initialEntries={[{+ pathname: '/catalog/ingest',+ state: { prefill: { title: 'Creative notes from Brain', rawText: 'A captured idea.', creativeNoteIds: noteIds } },+ }]}>+ <CatalogIngest />+ </MemoryRouter>,+ );++ await screen.findByDisplayValue('A captured idea.');+ fireEvent.click(screen.getByRole('button', { name: 'Ingest' }));+ await screen.findByDisplayValue('A captured idea');+ fireEvent.click(screen.getByRole('button', { name: /Commit/ }));++ await waitFor(() => expect(commitCatalogScrapDraft).toHaveBeenCalledWith(+ 'notes-scrap',+ expect.any(Array),+ expect.objectContaining({ creativeNoteIds: noteIds, operationKey: expect.any(String) }),+ ));+});diff --git a/client/src/pages/Importer.jsx b/client/src/pages/Importer.jsxindex 50340edf0f..830efc5018 100644--- a/client/src/pages/Importer.jsx+++ b/client/src/pages/Importer.jsx@@ -341,7 +341,9 @@ export default function Importer() {}setIssueSplitFailed(Boolean(result.issueSplitFailed));setIssueSplitError(result.issueSplitError || null);- setArcAlreadyPersisted(false);+ // The server remembers a failed commit's persisted arc across a reload; seed+ // the retry flag from it rather than assuming a fresh start.+ setArcAlreadyPersisted(result.importSession?.status === 'arc-persisted');setReplaceMode(false);// Re-arm the AI-cleanup opt-in off for each fresh analysis — it's// off-by-default (one LLM call per issue), so a prior import's choice must@@ -388,6 +390,9 @@ export default function Importer() {const base = {universeId: preview.universe.id,seriesId: preview.series.id,+ // Lets the server replay or resume this import instead of duplicating it+ // after a reload dropped the markers kept above (#9943).+ ...(preview.importId ? { importId: preview.importId } : {}),issues: issuesDraft,// Routes the verbatim excerpt to the right stage server-side — a// script-form import (comic-script → comicScript, screenplay → teleplay)@@ -419,7 +424,9 @@ export default function Importer() {throw err;});if (!result) return null;- toast.success(`Imported ${result.createdIssueIds.length} issue${result.createdIssueIds.length === 1 ? '' : 's'} into "${result.series.name}"`);+ toast.success(result.replayed+ ? `Already imported into "${result.series.name}" — opening it without creating duplicates`+ : `Imported ${result.createdIssueIds.length} issue${result.createdIssueIds.length === 1 ? '' : 's'} into "${result.series.name}"`);if (Array.isArray(result.remappedIssues) && result.remappedIssues.length > 0) {const n = result.remappedIssues.length;const noun = `${n} issue${n === 1 ? '' : 's'}`;@@ -866,6 +873,12 @@ function ReviewPanel({the pipeline. The verbatim excerpt for each issue lands in{' '}<code>{seedStagePath}</code>.</p>+ {preview.importSession?.status === 'committed' && (+ <p className="text-xs mt-2 text-port-warning flex items-center gap-1.5">+ <AlertTriangle className="w-3 h-3 flex-shrink-0" />+ This manuscript was already imported into this series. Commit opens it without creating duplicates.+ </p>+ )}{preview.isExistingSeries && (<label className={`text-xs mt-2 flex items-center gap-2 cursor-pointer ${replaceMode ? 'text-port-error' : 'text-port-text-muted'}`}><inputdiff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.jsindex 4a3d080cd7..96c76a27b9 100644--- a/client/src/services/apiBrain.js+++ b/client/src/services/apiBrain.js@@ -56,12 +56,6 @@ export const updateBrainInboxEntry = (id, capturedText, options = {}) => request});export const deleteBrainInboxEntry = (id, options = {}) => request(`/brain/inbox/${id}`, { method: 'DELETE', ...options });export const markBrainInboxDone = (id, options = {}) => request(`/brain/inbox/${id}/done`, { method: 'POST', ...options });-// Stamp a batch of creative notes as consumed once their catalog ingest commits.-export const markBrainInboxSentToCatalog = (ids, options) => request('/brain/inbox/sent-to-catalog', {- method: 'POST',- body: JSON.stringify({ ids }),- ...options-});// Brain - Peopleexport const getBrainPeople = (options = {}) => {diff --git a/client/src/services/apiCatalog.js b/client/src/services/apiCatalog.jsindex 361cee4286..6ed8e364f3 100644--- a/client/src/services/apiCatalog.js+++ b/client/src/services/apiCatalog.js@@ -33,13 +33,16 @@ export const pruneCatalogScrap = (id, body, options) =>// when the caller passes 'unassigned' (the "no universe" choice), reproducing// prior behavior exactly (source link only, no homing ref).// `relationships` forwards explicit grounded graph relationships (including [] for structured drafts).-export const commitCatalogScrapDraft = (id, accepted, { universeRef, role, relationships, operationKey, ...options } = {}, maybeRelationships) => {+// `creativeNoteIds` names the Brain inbox notes this scrap came from; the server+// stamps them consumed in the same request as the commit (#9943).+export const commitCatalogScrapDraft = (id, accepted, { universeRef, role, relationships, operationKey, creativeNoteIds, ...options } = {}, maybeRelationships) => {const rels = maybeRelationships !== undefined ? maybeRelationships : relationships;return request(`/catalog/scraps/${enc(id)}/commit`, {method: 'POST',body: JSON.stringify({accepted,...(operationKey ? { operationKey } : {}),+ ...(creativeNoteIds?.length ? { creativeNoteIds } : {}),...(universeRef ? { universeRef, ...(role ? { role } : {}) } : {}),...(rels !== undefined ? { relationships: rels } : {}),}),diff --git a/client/src/services/apiCatalog.test.js b/client/src/services/apiCatalog.test.jsindex 06f670adf3..8a711f712a 100644--- a/client/src/services/apiCatalog.test.js+++ b/client/src/services/apiCatalog.test.js@@ -112,3 +112,14 @@ it('serializes the commit operation key into the HTTP body while retaining requeexpect(options.silent).toBe(true);expect(options).not.toHaveProperty('operationKey');});++it('serializes the source note ids so the server can consume them in the commit request', async () => {+ const { commitCatalogScrapDraft } = await import('./apiCatalog.js');+ const creativeNoteIds = ['3f1c0c52-8d5e-4b8e-9d3c-111111111111'];+ await commitCatalogScrapDraft('example-scrap', [], { creativeNoteIds, silent: true });+ const [, options] = request.mock.lastCall;+ expect(JSON.parse(options.body)).toEqual({ accepted: [], creativeNoteIds });+ expect(options).not.toHaveProperty('creativeNoteIds');+ await commitCatalogScrapDraft('example-scrap', [], { creativeNoteIds: [], silent: true });+ expect(JSON.parse(request.mock.lastCall[1].body)).toEqual({ accepted: [] });+});diff --git a/client/src/services/apiRounds.js b/client/src/services/apiRounds.jsindex da9c9351d4..f282105c7b 100644--- a/client/src/services/apiRounds.js+++ b/client/src/services/apiRounds.js@@ -52,8 +52,15 @@ export const deriveRoundParts = (id, body = {}, options) =>// streams over SSE (subscribe with useSseProgress); the terminal `complete` frame// carries the { filename } the caller persists on the reference. Upload/mic// capture remain the primary attach paths.-export const importReferenceAudio = (url, options = {}) =>- request('/rounds/reference-audio/import', { method: 'POST', body: JSON.stringify({ url }), ...options });+// `roundId` + `referenceId` name a SAVED reference: the server then attaches the+// file to it when the download finishes (the frame reports `attached`), so a+// reload before Save cannot lose it (#9943). Omit both for an unsaved draft row.+export const importReferenceAudio = (url, { roundId, referenceId, ...options } = {}) =>+ request('/rounds/reference-audio/import', {+ method: 'POST',+ body: JSON.stringify({ url, ...(roundId && referenceId ? { roundId, referenceId } : {}) }),+ ...options,+ });export const referenceAudioImportEventsUrl = (jobId) =>`/api/rounds/reference-audio/import/${enc(jobId)}/events`;diff --git a/client/src/services/apiRounds.test.js b/client/src/services/apiRounds.test.jsnew file mode 100644index 0000000000..de4d9312f1--- /dev/null+++ b/client/src/services/apiRounds.test.js@@ -0,0 +1,35 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('./apiCore.js', () => ({ request: vi.fn() }));++let request;+let importReferenceAudio;++beforeEach(async () => {+ vi.resetModules();+ ({ request } = await import('./apiCore.js'));+ ({ importReferenceAudio } = await import('./apiRounds.js'));+ request.mockReset();+});++describe('importReferenceAudio', () => {+ it('sends the saved reference target so the server can attach the finished file (#9943)', async () => {+ await importReferenceAudio('https://example.com/clip', { roundId: 'round-1', referenceId: 'ref-1', silent: true });+ const [path, options] = request.mock.lastCall;+ expect(path).toBe('/rounds/reference-audio/import');+ expect(JSON.parse(options.body)).toEqual({ url: 'https://example.com/clip', roundId: 'round-1', referenceId: 'ref-1' });+ // The target is wire data; request options pass through untouched.+ expect(options.silent).toBe(true);+ expect(options).not.toHaveProperty('roundId');+ });++ it('sends only the url for an unsaved draft row', async () => {+ await importReferenceAudio('https://example.com/clip', { silent: true });+ expect(JSON.parse(request.mock.lastCall[1].body)).toEqual({ url: 'https://example.com/clip' });+ });++ it('never sends half a target, which the server rejects', async () => {+ await importReferenceAudio('https://example.com/clip', { roundId: 'round-1' });+ expect(JSON.parse(request.mock.lastCall[1].body)).toEqual({ url: 'https://example.com/clip' });+ });+});diff --git a/docs/API.md b/docs/API.mdindex d37949e47e..f8f7da7cc6 100644--- a/docs/API.md+++ b/docs/API.md@@ -1004,7 +1004,7 @@ Common error codes:An optional UUID `operationKey` makes a reviewed submission retry-safe. Reuse it for retries with the same accepted content, relationships, scrap, universe and role: the server returns the original ingredient response without creating another batch, including after restart or concurrent requests. Reusing it with different input returns HTTP 409. Embedding output is excluded from request identity. Mint a new key for an intentional new submission; callers omitting it keep legacy behavior. Receipts remain local to the accepting instance and persist with its database.-`POST /api/catalog/scraps/:id/commit` accepts up to 200 `accepted` entries and an optional `relationships` array (at most 1,000 edges). Each explicit edge has `fromDraftId`, `toDraftId`, `kind`, and nonempty `evidence` (at most 400 characters). When the array is present, every accepted entry needs a unique nonempty `draftId` (at most 120 characters); both endpoints must be accepted IDs and self-edges are rejected. Draft IDs stay outside persisted payloads. Renaming or reordering entries does not change endpoint identity.+`POST /api/catalog/scraps/:id/commit` accepts up to 200 `accepted` entries and an optional `relationships` array (at most 1,000 edges). Each explicit edge has `fromDraftId`, `toDraftId`, `kind`, and nonempty `evidence` (at most 400 characters). When the array is present, every accepted entry needs a unique nonempty `draftId` (at most 120 characters); both endpoints must be accepted IDs and self-edges are rejected. Draft IDs stay outside persisted payloads. Renaming or reordering entries does not change endpoint identity. An optional `creativeNoteIds` array (at most 200 Brain inbox note GUIDs) names the creative notes the scrap was built from; the commit stamps them consumed in the same request — including when `operationKey` replays an earlier commit — so a reload between the commit and any follow-up call cannot leave them re-sendable.The server validates the graph before embedding or writing. Duplicate directed tuples create one edge, retaining every distinct evidence passage in the source ingredient's existing `payload.evidence` field with the kind and target name. Bible entries keep their evidence arrays (20 passages, 500 characters each including the contextual prefix); light entries keep string evidence, or arrays when supplied. Overflow is rejected explicitly, never truncated. The existing 200KB payload limit still applies after evidence enrichment.diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 96c5b3a38c..1c7f914f28 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -720,3 +720,7 @@ originals and is distinct from space reclamation.### SuperCollider runtime evidence`data/supercollider/` is `ephemeral-file`: `runtime-evidence.json` caches the last synthetic render probe for the managed SuperCollider image (bound to this machine's local image id, runtime version and containment policy), `jobs/` holds in-flight probe/render scratch that each run removes, and `previews/` holds validated Music Designer render previews (WAV + provenance sidecar) for 24 hours until the user saves one as a take. Nothing in it relates to other records, needs search, or federates. Setup re-derives it, so it is excluded from backups (`/supercollider/`) and purgeable from the Data Manager. Saving a preview copies its WAV into the music library and records `codeProvenance` (source, hash, seed, runtime version, settings) on the track render in the `tracks` table, so the durable take never depends on this directory. See [SUPERCOLLIDER.md](./SUPERCOLLIDER.md).++### Importer sessions++`data/importer-sessions.json` is `file-primary`, machine-local operational state: for each manuscript imported into a series, how far `POST /api/importer/commit` got (`arc-persisted` after canon/arc/seasons landed, `committed` with the created issue ids). It exists so a reload between the commit and the next step cannot lose the client's own "already committed" markers and re-send the payload (#9943). It is keyed by a derived import id (`imp-` + hash of series id and the normalized manuscript), so a re-analyze of the same text reads the same session back. It is a bounded ledger of what THIS machine's commit did to THIS machine's records, with no foreign keys, cross-record queries, or search, so it stays out of PostgreSQL; each entry is only honored while the issues it recorded still exist. It is deliberately **never federated**: a peer's issues arrive through record sync, and replaying a commit there would describe records that machine did not create. Schema version 1, newest 500 sessions kept, rewritten whole behind a write queue (`services/importerSessions.js`); a payload declaring another version reads as empty rather than half-read, so no migration or `data.reference/` seed is needed. Rsync backups include it.diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.jsindex f2ea980816..2c8bfebf37 100644--- a/server/lib/catalogValidation.js+++ b/server/lib/catalogValidation.js@@ -430,6 +430,12 @@ export const catalogScrapCommitSchema = z.object({relationships: z.array(catalogDraftRelationshipSchema).max(1000).optional(),universeRef: z.string().trim().min(1).max(120).optional(),role: z.string().trim().min(1).max(64).optional(),+ // Brain creative-inbox notes this scrap was built from. The commit itself+ // stamps them consumed (#9943), so a reload between the commit and a+ // follow-up client call cannot leave them re-sendable. The ids ride the+ // request rather than the fingerprint: they are bookkeeping about the source+ // notes, not part of the reviewed submission's identity.+ creativeNoteIds: z.array(z.string().guid()).min(1).max(200).optional(),}).strict().superRefine((body, ctx) => {if (body.relationships === undefined) return;const ids = new Set();diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.jsindex 2d5dd41ff1..1bfd6e0f38 100644--- a/server/lib/creativeDirectorValidation.js+++ b/server/lib/creativeDirectorValidation.js@@ -593,9 +593,18 @@ const importerIssueEntry = z.object({).optional(),}).passthrough();+// The id analyze derives for one manuscript imported into one series (see+// services/importerSessions.js). Declared here so the wire schema and the+// session store validate the same shape.+export const IMPORT_ID_RE = /^imp-[0-9a-f]{32}$/;+export const importerCommitSchema = z.object({universeId: z.string().trim().min(1).max(120),seriesId: z.string().trim().min(1).max(120),+ // Optional so older clients keep the unguarded behavior. When sent, the+ // server's import session decides whether this commit replays, resumes, or+ // runs fresh (#9943).+ importId: z.string().regex(IMPORT_ID_RE).optional(),canonSelections: z.object({characters: z.array(importerCanonEntry).max(BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX).default([]),places: z.array(importerCanonEntry).max(BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX).default([]),diff --git a/server/routes/catalog.js b/server/routes/catalog.jsindex e823d742e0..dc8dfdb8cd 100644--- a/server/routes/catalog.js+++ b/server/routes/catalog.js@@ -166,9 +166,23 @@ router.post('/scraps/:id/commit', asyncHandler(async (req, res) => {const scrap = await catalogDB.getScrap(req.params.id);if (!scrap) throw new ServerError('Scrap not found', { status: 404 });+ // Source notes are stamped consumed in THIS request — on a replay too, so a+ // retry that follows a crash between the commit and the stamp heals it. A+ // stamp failure fails the request; the retry (same key) replays the receipt+ // rather than committing again, which is why the commit is safe to leave in+ // place when the stamp below it fails.+ const consumeSourceNotes = async () => {+ if (!body.creativeNoteIds) return;+ const { markInboxSentToCatalog } = await import('../services/brain.js');+ await markInboxSentToCatalog(body.creativeNoteIds);+ };+if (body.operationKey) {const replay = await catalogDB.getScrapCommitReceipt({ ...body, scrapId: scrap.id });- if (replay) return res.status(201).json({ scrap, ingredients: replay });+ if (replay) {+ await consumeSourceNotes();+ return res.status(201).json({ scrap, ingredients: replay });+ }}// Embed all drafts in parallel (concurrency-4 inside embedBatch) before@@ -189,6 +203,7 @@ router.post('/scraps/:id/commit', asyncHandler(async (req, res) => {role: body.role,});+ await consumeSourceNotes();res.status(201).json({ scrap, ingredients: created });}));diff --git a/server/routes/catalogCommitNotes.test.js b/server/routes/catalogCommitNotes.test.jsnew file mode 100644index 0000000000..63f7d9660a--- /dev/null+++ b/server/routes/catalogCommitNotes.test.js@@ -0,0 +1,122 @@+/**+ * `POST /api/catalog/scraps/:id/commit` stamps the Brain notes a scrap was built+ * from as consumed in the SAME request (#9943), including when the request is a+ * replay of an already-committed operation key.+ *+ * Why the request, not a follow-up client call: the client used to mark the notes+ * after the commit response arrived, so a reload in between left them re-sendable+ * and a second ingest of the same notes duplicated the ingredients. The commit+ * receipt/idempotency half of this contract is covered against a real database in+ * catalog.test.js; this file needs none — the catalog DB layer and the brain store+ * are doubled so the only thing under test is the route's sequencing.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++const SCRAP = { id: 'scrap-example', rawText: 'Example source text.' };+const NOTE_A = '3f1c0c52-8d5e-4b8e-9d3c-111111111111';+const NOTE_B = '3f1c0c52-8d5e-4b8e-9d3c-222222222222';+const KEY = '9b2f6d1a-4c1e-4f0a-8c55-aaaaaaaaaaaa';+const CREATED = [{ id: 'ing-1', name: 'Example idea' }];++const { getScrap, getScrapCommitReceipt, commitScrap, markInboxSentToCatalog, embedBatch } = vi.hoisted(() => ({+ getScrap: vi.fn(),+ getScrapCommitReceipt: vi.fn(),+ commitScrap: vi.fn(),+ markInboxSentToCatalog: vi.fn(),+ embedBatch: vi.fn(),+}));++vi.mock('../services/catalogDB.js', async (importOriginal) => ({+ ...(await importOriginal()),+ getScrap, getScrapCommitReceipt, commitScrap,+}));+vi.mock('../services/embeddings.js', () => ({+ embedBatch,+ ingredientEmbedSeed: vi.fn((draft) => draft),+ embedIngredient: vi.fn(async () => ({})),+}));+vi.mock('../services/brain.js', () => ({ markInboxSentToCatalog }));++const router = (await import('./catalog.js')).default;+const app = express();+app.use(express.json());+app.use('/api/catalog', router);+app.use(errorMiddleware);++const accepted = [{ type: 'idea', name: 'Example idea' }];+const commit = (body) => request(app).post(`/api/catalog/scraps/${SCRAP.id}/commit`).send({ accepted, ...body });++beforeEach(() => {+ vi.clearAllMocks();+ getScrap.mockResolvedValue(SCRAP);+ getScrapCommitReceipt.mockResolvedValue(null);+ commitScrap.mockResolvedValue(CREATED);+ embedBatch.mockResolvedValue([{ embedding: null, model: null }]);+ markInboxSentToCatalog.mockResolvedValue([]);+});++describe('POST /api/catalog/scraps/:id/commit — source notes', () => {+ it('stamps the source notes consumed after the commit lands', async () => {+ const res = await commit({ operationKey: KEY, creativeNoteIds: [NOTE_A, NOTE_B] });++ expect(res.status).toBe(201);+ expect(res.body.ingredients).toEqual(CREATED);+ expect(markInboxSentToCatalog).toHaveBeenCalledWith([NOTE_A, NOTE_B]);+ expect(commitScrap.mock.invocationCallOrder[0]).toBeLessThan(markInboxSentToCatalog.mock.invocationCallOrder[0]);+ // The ids are bookkeeping about the source, not part of what is committed.+ expect(commitScrap.mock.calls[0][0]).not.toHaveProperty('creativeNoteIds');+ });++ it('still stamps them when the key replays an earlier commit, creating nothing new', async () => {+ getScrapCommitReceipt.mockResolvedValue(CREATED);++ const res = await commit({ operationKey: KEY, creativeNoteIds: [NOTE_A] });++ expect(res.status).toBe(201);+ expect(res.body.ingredients).toEqual(CREATED);+ expect(commitScrap).not.toHaveBeenCalled();+ expect(embedBatch).not.toHaveBeenCalled();+ expect(markInboxSentToCatalog).toHaveBeenCalledWith([NOTE_A]);+ });++ it('leaves the notes alone when the commit fails, so the retry can still consume them', async () => {+ commitScrap.mockRejectedValue(new Error('simulated commit failure'));++ const res = await commit({ operationKey: KEY, creativeNoteIds: [NOTE_A] });++ expect(res.status).toBe(500);+ expect(markInboxSentToCatalog).not.toHaveBeenCalled();+ });++ it('fails the request when the stamp fails, and the same-key retry replays and stamps again', async () => {+ markInboxSentToCatalog.mockRejectedValueOnce(new Error('simulated brain store failure'));+ const failed = await commit({ operationKey: KEY, creativeNoteIds: [NOTE_A] });+ expect(failed.status).toBe(500);++ getScrapCommitReceipt.mockResolvedValue(CREATED);+ const retried = await commit({ operationKey: KEY, creativeNoteIds: [NOTE_A] });++ expect(retried.status).toBe(201);+ expect(commitScrap).toHaveBeenCalledTimes(1);+ expect(markInboxSentToCatalog).toHaveBeenCalledTimes(2);+ });++ it('does not touch the Brain store for a commit with no source notes', async () => {+ const res = await commit({ operationKey: KEY });++ expect(res.status).toBe(201);+ expect(markInboxSentToCatalog).not.toHaveBeenCalled();+ });++ it('rejects malformed note ids before anything is committed', async () => {+ const res = await commit({ creativeNoteIds: ['not-a-guid'] });++ expect(res.status).toBe(400);+ expect(commitScrap).not.toHaveBeenCalled();+ expect(markInboxSentToCatalog).not.toHaveBeenCalled();+ });+});diff --git a/server/routes/importerSessions.test.js b/server/routes/importerSessions.test.jsnew file mode 100644index 0000000000..26a8e648ec--- /dev/null+++ b/server/routes/importerSessions.test.js@@ -0,0 +1,93 @@+/**+ * HTTP-level proof of the import-session contract (#9943): a repeated+ * `POST /api/importer/commit` with the same import id creates nothing new, and+ * a re-analyze after the client lost its state reports the committed session.+ *+ * Mounts the real router over the real services (importer, series, issues,+ * session store) with only the data root and the LLM runner doubled, so the+ * assertions are about persisted records, not mock calls. The service-level+ * matrix (resume, stale session, concurrency) lives in services/importer.test.js.+ */++import { describe, it, expect, vi, afterAll } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import {+ makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots, mockNoPeers, mockNoPeerSync,+} from '../lib/mockPathsDataRoot.js';++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-importer-sessions-') }));+vi.mock('../services/instances.js', () => mockNoPeers());+vi.mock('../services/sharing/peerSync.js', () => mockNoPeerSync());++const canon = { characters: [{ name: 'Aria', role: 'protagonist' }], places: [], objects: [] };+const arc = { logline: 'A logline.', summary: 'A summary.', shape: 'man-in-hole', seasons: [] };+const issues = { issues: [{ title: 'Cold Iron', arcPosition: 1, proseExcerpt: 'The vault loomed.' }] };++vi.mock('../services/stageRunner.js', () => ({+ tryReadFile: vi.fn().mockResolvedValue(null),+ runStagedLLM: vi.fn(async (stage) => ({+ content: { 'importer-canon-extract': canon, 'importer-arc-extract': arc, 'importer-issue-proposal': issues }[stage],+ model: 'mock', providerId: 'mock', runId: `run-${stage}`,+ })),+}));++const importerRoutes = (await import('../routes/importer.js')).default;+const issuesSvc = await import('../services/pipeline/issues.js');++afterAll(cleanupTempDataRoots);++const app = express();+app.use(express.json());+app.use('/api/importer', importerRoutes);+app.use(errorMiddleware);++const analyze = (source) => request(app).post('/api/importer/analyze').send({+ universeName: 'Route Universe', seriesName: 'Route Series', contentType: 'short-story', source,+});+const commit = (preview) => request(app).post('/api/importer/commit').send({+ universeId: preview.universe.id,+ seriesId: preview.series.id,+ importId: preview.importId,+ arc: { logline: 'A logline.', summary: 'A summary.', shape: 'man-in-hole' },+ issues: preview.issueProposals,+});++describe('POST /api/importer/commit with an import id', () => {+ it('creates nothing on a repeat, including after a re-analyze that has no client state', async () => {+ const first = await analyze('The vault loomed in the dark.');+ expect(first.status).toBe(200);+ expect(first.body.importId).toMatch(/^imp-[0-9a-f]{32}$/);+ expect(first.body.importSession).toBeNull();++ const committed = await commit(first.body);+ expect(committed.status).toBe(200);+ expect(committed.body.createdIssueIds).toHaveLength(1);+ expect(committed.body.replayed).toBeUndefined();++ const repeat = await commit(first.body);+ expect(repeat.status).toBe(200);+ expect(repeat.body.replayed).toBe(true);+ expect(repeat.body.createdIssueIds).toEqual(committed.body.createdIssueIds);++ // The "reload": nothing carried over but the manuscript text.+ const reanalyzed = await analyze('The vault loomed in the dark.');+ expect(reanalyzed.body.importId).toBe(first.body.importId);+ expect(reanalyzed.body.importSession).toEqual({+ status: 'committed', createdIssueIds: committed.body.createdIssueIds,+ });+ const afterReload = await commit(reanalyzed.body);+ expect(afterReload.body.replayed).toBe(true);++ expect(await issuesSvc.listIssues({ seriesId: first.body.series.id })).toHaveLength(1);+ });++ it('rejects a malformed import id at the Zod layer', async () => {+ const res = await request(app).post('/api/importer/commit').send({+ universeId: 'u', seriesId: 's', importId: 'not-an-import-id', issues: [{ title: 'x' }],+ });+ expect(res.status).toBe(400);+ });+});diff --git a/server/routes/rounds.js b/server/routes/rounds.jsindex a4e0467ece..c4ed27ac6e 100644--- a/server/routes/rounds.js+++ b/server/routes/rounds.js@@ -241,11 +241,18 @@ router.get('/:id', asyncHandler(async (req, res) => {// literal segment can't be read as a round id. The kickoff returns 202 + a// jobId; progress streams over SSE; the client persists the returned filename// on the reference via the normal PATCH on Save.-const referenceAudioImportSchema = z.object({ url: str(2048).min(1) });+// `roundId` + `referenceId` (both or neither) name the saved reference the file is+// for, so the server attaches it when the download finishes instead of leaving+// it in the editor's draft until Save (#9943).+const referenceAudioImportSchema = z.object({+ url: str(2048).min(1),+ roundId: str(svc.ID_MAX_LENGTH).min(1).optional(),+ referenceId: str(svc.ID_MAX_LENGTH).min(1).optional(),+}).refine((v) => !v.roundId === !v.referenceId, { message: 'roundId and referenceId must be sent together' });router.post('/reference-audio/import', asyncHandler(async (req, res) => {- const { url } = validateRequest(referenceAudioImportSchema, req.body || {});- res.status(202).json(await startReferenceAudioImport(url));+ const { url, roundId, referenceId } = validateRequest(referenceAudioImportSchema, req.body || {});+ res.status(202).json(await startReferenceAudioImport(url, { roundId, referenceId }));}));router.get('/reference-audio/import/:jobId/events', (req, res) => {diff --git a/server/routes/rounds.test.js b/server/routes/rounds.test.jsindex cad5ecdbdd..ce43af878b 100644--- a/server/routes/rounds.test.js+++ b/server/routes/rounds.test.js@@ -364,7 +364,28 @@ describe('rounds route', () => {.send({ url: 'https://tiktok.com/@a/video/1' });expect(res.status).toBe(202);expect(res.body).toEqual({ jobId: 'job-1' });- expect(importMocks.startReferenceAudioImport).toHaveBeenCalledWith('https://tiktok.com/@a/video/1');+ expect(importMocks.startReferenceAudioImport).toHaveBeenCalledWith('https://tiktok.com/@a/video/1', {});+ });++ // #9943: the target rides the kickoff so the server can attach the finished+ // file to the saved reference instead of the editor carrying it until Save.+ it('POST /reference-audio/import forwards the round + reference the download is for', async () => {+ importMocks.startReferenceAudioImport.mockResolvedValue({ jobId: 'job-2' });+ const res = await request(makeApp())+ .post('/api/rounds/reference-audio/import')+ .send({ url: 'https://tiktok.com/@a/video/1', roundId: 'round-1', referenceId: 'ref-1' });+ expect(res.status).toBe(202);+ expect(importMocks.startReferenceAudioImport).toHaveBeenCalledWith(+ 'https://tiktok.com/@a/video/1', { roundId: 'round-1', referenceId: 'ref-1' },+ );+ });++ it('POST /reference-audio/import 400s when only one half of the target is sent', async () => {+ const res = await request(makeApp())+ .post('/api/rounds/reference-audio/import')+ .send({ url: 'https://tiktok.com/@a/video/1', roundId: 'round-1' });+ expect(res.status).toBe(400);+ expect(importMocks.startReferenceAudioImport).not.toHaveBeenCalled();});it('POST /reference-audio/import 400s on a missing url (not read as a round id)', async () => {diff --git a/server/services/importer.js b/server/services/importer.jsindex a3601a3100..f7ff6275b6 100644--- a/server/services/importer.js+++ b/server/services/importer.js@@ -40,6 +40,9 @@ import { IMPORTER_CONTENT_TYPES, IMPORTER_PROSE_EXCERPT_MAX } from '../lib/validexport { IMPORTER_PROSE_EXCERPT_MAX };import { mergeExtractedBible, BIBLE_KIND } from '../lib/storyBible.js';import { isStr } from '../lib/textUtils.js';+import {+ deriveImportId, getImportSession, recordImportProgress, withImportLock, SESSION_STATUS,+} from './importerSessions.js';// Surfaced to the route layer so the importer's policy errors become 400s// with stable codes.@@ -699,6 +702,25 @@ export async function classifyImportContent({ source, providerOverride, modelOve};}+/**+ * The recorded progress of this manuscript's import into this series (#9943),+ * or null when there is none worth honoring. A `committed` session only counts+ * while at least one issue it created still exists: a user who deleted the+ * imported issues and re-imports the same text is starting over, and treating+ * that as a replay would silently create nothing.+ */+async function resolveImportSession(importId, seriesId) {+ const session = await getImportSession(importId);+ if (!session || session.seriesId !== seriesId) return null;+ if (session.status !== SESSION_STATUS.COMMITTED) return session;+ const live = new Set((await listIssues({ seriesId })).map((issue) => issue.id));+ return session.createdIssueIds.some((id) => live.has(id)) ? session : null;+}++const summarizeImportSession = (session) => (session+ ? { status: session.status, createdIssueIds: session.createdIssueIds }+ : null);+/*** Phase 1: analyze. Runs canon-extract + arc-extract in parallel (both read* source independently); after arc resolves, runs issue-proposal with the@@ -908,6 +930,20 @@ export async function analyzeImport({const arcPreview = buildArcPreview(arcRun.content);+ // Progress this manuscript's earlier commit left behind (#9943). A series+ // created a moment ago has none, so only a pre-existing one is looked up. The+ // id travels back on commit; `importSession` tells the client to resume+ // instead of re-sending a payload the server already applied.+ const importId = deriveImportId({ seriesId: series.id, source });+ // Best-effort here: an unreadable ledger must not throw away the canon + arc+ // passes that just ran. The commit reads it again and refuses on its own.+ const importSession = isExistingSeries+ ? await resolveImportSession(importId, series.id).catch((err) => {+ console.error(`❌ importer session lookup failed for series ${series.id}: ${err.message}`);+ return null;+ })+ : null;+// Terminal frame: clears the live snapshot so a tab that opens after this// run finishes isn't replayed a stale (all-done) checklist. A throw before// here (an LLM timeout on canon/arc, a series-create failure) leaves the@@ -921,6 +957,8 @@ export async function analyzeImport({series,isExistingUniverse,isExistingSeries,+ importId,+ importSession: summarizeImportSession(importSession),canonPreview: {characters: Array.isArray(canonRun.content?.characters) ? canonRun.content.characters : [],places: Array.isArray(canonRun.content?.places) ? canonRun.content.places : [],@@ -998,10 +1036,22 @@ export async function retryIssueSplit({* writes the arc + seasons onto the series, then creates one issue per* proposal with prose pre-seeded. Validates the locked-arc guard one more* time (the series could have been locked between analyze + commit).+ *+ * `importId` (from analyze, #9943) makes the commit resumable: its server-side+ * session records how far an earlier attempt got, so a repeat — a double click,+ * a second tab, a retry after a reload dropped the client's own markers —+ * replays the recorded result or resumes at the issues instead of re-sending+ * canon/arc and duplicating the issue set. Absent, the commit behaves as before.*/-export async function commitImport({+export async function commitImport(args = {}) {+ const { importId = null } = args;+ return importId ? withImportLock(importId, () => commitImportOnce(args)) : commitImportOnce(args);+}++async function commitImportOnce({universeId,seriesId,+ importId = null,canonSelections = {},arc = null,seasons = [],@@ -1056,6 +1106,30 @@ export async function commitImport({);}+ // An earlier attempt at this same import (#9943). Replace mode wipes and+ // rewrites the series, so it is idempotent by construction and never consults+ // the session; additive mode would duplicate, so it does.+ const session = importId && !replaceMode ? await resolveImportSession(importId, series.id) : null;+ if (session?.status === SESSION_STATUS.COMMITTED) {+ // Answered before the locked-arc gate: nothing is written, so a lock added+ // since the commit cannot turn a recorded success into an error.+ return {+ universe,+ series,+ createdIssueIds: session.createdIssueIds,+ remappedIssues: session.remappedIssues,+ replayed: true,+ };+ }+ if (session?.status === SESSION_STATUS.ARC_PERSISTED) {+ // The server kept canon/arc/seasons from the attempt whose issues rolled+ // back. Resending them would overwrite edits made since, so the server+ // drops them itself rather than trusting the client to have remembered.+ canonSelections = {};+ arc = null;+ seasons = [];+ }+if (series.locked?.arc === true) {throw makeErr(`Series "${series.name}" has a locked arc — commit refused. Unlock the arc to import.`,@@ -1395,6 +1469,17 @@ export async function commitImport({const fallbackSeason = sortedSeasons[0] || null;const fallbackSeasonId = fallbackSeason?.id || null;+ // Canon, arc and seasons are on disk. Mark that BEFORE the issue loop and let a+ // failure here stop the commit: issues created without a way to find them+ // again are exactly what a retry would duplicate.+ if (importId) {+ await recordImportProgress(importId, {+ universeId: updatedUniverse.id,+ seriesId: updatedSeries.id,+ status: SESSION_STATUS.ARC_PERSISTED,+ });+ }+const createdIssueIds = [];// Surface season-remap events so the UI can warn "issue 3 wanted season 5// but landed in S2 — Diaspora." Each entry carries the actual landed@@ -1515,6 +1600,17 @@ export async function commitImport({promotedSeries = await updateSeries(updatedSeries.id, { ephemeral: false, importDraft: false });}+ // The issues exist now, so a failure to record that must not fail the commit:+ // the client would retry and duplicate them. Worst case the next re-analyze+ // finds no session and the import is guarded only by the client, as before.+ if (importId) {+ await recordImportProgress(importId, {+ status: SESSION_STATUS.COMMITTED,+ createdIssueIds,+ remappedIssues,+ }).catch((err) => console.error(`❌ importer session ${importId} not marked committed: ${err.message}`));+ }+return {universe: promotedUniverse,series: promotedSeries,diff --git a/server/services/importer.test.js b/server/services/importer.test.jsindex 6fe220f708..22d88b7144 100644--- a/server/services/importer.test.js+++ b/server/services/importer.test.js@@ -1706,6 +1706,145 @@ describe('commitImport', () => {});});+// Import sessions (#9943): the server, not the client's React state, remembers+// how far an import got, so a repeat commit cannot duplicate the issue set.+describe('commitImport import sessions (#9943)', () => {+ const analyze = (source = 'The vault loomed in the dark.') => importerSvc.analyzeImport({+ universeName: 'Session U', seriesName: 'Session S', contentType: 'short-story', source,+ });+ const payloadFor = (preview, extra = {}) => ({+ universeId: preview.universe.id,+ seriesId: preview.series.id,+ importId: preview.importId,+ arc: { logline: 'Original logline', summary: 'Original summary', shape: 'man-in-hole' },+ seasons: [{ number: 1, title: 'S1', logline: '', synopsis: '', endingHook: '' }],+ issues: [+ { title: 'I1', arcPosition: 1, proseExcerpt: 'p1' },+ { title: 'I2', arcPosition: 2, proseExcerpt: 'p2' },+ ],+ ...extra,+ });+ const issueCount = async (preview) => (await issuesSvc.listIssues({ seriesId: preview.series.id })).length;++ it('replays a repeated commit: nothing new is created and the recorded ids come back', async () => {+ wireDefaultLLMResponses();+ const preview = await analyze();+ const first = await importerSvc.commitImport(payloadFor(preview));+ expect(first.createdIssueIds).toHaveLength(2);+ expect(first.replayed).toBeUndefined();++ // An edit made after the commit must survive a repeat: the replay writes nothing.+ await seriesSvc.updateSeries(preview.series.id, { logline: 'Edited since' });+ const again = await importerSvc.commitImport(payloadFor(preview));++ expect(again.replayed).toBe(true);+ expect(again.createdIssueIds).toEqual(first.createdIssueIds);+ expect(await issueCount(preview)).toBe(2);+ expect((await seriesSvc.getSeries(preview.series.id)).logline).toBe('Edited since');+ });++ it('survives a reload: re-analyzing the same text reads the committed session back', async () => {+ wireDefaultLLMResponses();+ const preview = await analyze();+ expect(preview.importSession).toBeNull();+ const first = await importerSvc.commitImport(payloadFor(preview));++ // The reload dropped every client marker; analyze is all the client has.+ const reanalyzed = await analyze(' The vault loomed in the dark.\r\n');+ expect(reanalyzed.isExistingSeries).toBe(true);+ expect(reanalyzed.importId).toBe(preview.importId);+ expect(reanalyzed.importSession).toEqual({ status: 'committed', createdIssueIds: first.createdIssueIds });++ const resumed = await importerSvc.commitImport(payloadFor(reanalyzed));+ expect(resumed.replayed).toBe(true);+ expect(await issueCount(preview)).toBe(2);+ });++ it('resumes after a rolled-back issue loop without resending canon or the arc', async () => {+ wireDefaultLLMResponses();+ const preview = await analyze();+ let call = 0;+ mockCreateIssue.mockImplementation(async (...args) => {+ call++;+ if (call === 2) throw new Error('simulated mid-loop FS error');+ return realIssuesRef.current.createIssue(...args);+ });+ await expect(importerSvc.commitImport(payloadFor(preview))).rejects.toMatchObject({+ code: importerSvc.ERR_PARTIAL_COMMIT_ISSUES,+ });+ expect(await issueCount(preview)).toBe(0);++ const reanalyzed = await analyze();+ expect(reanalyzed.importSession).toMatchObject({ status: 'arc-persisted' });+ await seriesSvc.updateSeries(preview.series.id, { arc: { logline: 'Edited arc', summary: 'Edited', shape: 'rags-to-riches' } });++ // A client with no memory of the failure resends the full payload, arc included.+ const retried = await importerSvc.commitImport(payloadFor(reanalyzed));+ expect(retried.createdIssueIds).toHaveLength(2);+ expect((await seriesSvc.getSeries(preview.series.id)).arc.shape).toBe('rags-to-riches');+ expect((await analyze()).importSession.status).toBe('committed');+ });++ it('does not block a different manuscript imported into the same series', async () => {+ wireDefaultLLMResponses();+ const first = await analyze('Chapter one text.');+ await importerSvc.commitImport(payloadFor(first, { issues: [{ title: 'A', arcPosition: 1, proseExcerpt: 'a' }] }));++ const second = await analyze('A different manuscript entirely.');+ expect(second.importId).not.toBe(first.importId);+ expect(second.importSession).toBeNull();+ const result = await importerSvc.commitImport(payloadFor(second, { issues: [{ title: 'B', proseExcerpt: 'b' }] }));+ expect(result.replayed).toBeUndefined();+ expect(await issueCount(first)).toBe(2);+ });++ it('treats a committed session whose issues were all deleted as a fresh start', async () => {+ wireDefaultLLMResponses();+ const preview = await analyze();+ const first = await importerSvc.commitImport(payloadFor(preview));+ for (const id of first.createdIssueIds) await issuesSvc.deleteIssue(id);++ const reanalyzed = await analyze();+ expect(reanalyzed.importSession).toBeNull();+ const again = await importerSvc.commitImport(payloadFor(reanalyzed));+ expect(again.replayed).toBeUndefined();+ expect(again.createdIssueIds).toHaveLength(2);+ });++ it('serializes concurrent commits of one import into a single issue set', async () => {+ wireDefaultLLMResponses();+ const preview = await analyze();+ const [a, b] = await Promise.all([+ importerSvc.commitImport(payloadFor(preview)),+ importerSvc.commitImport(payloadFor(preview)),+ ]);+ expect([a.replayed, b.replayed].filter(Boolean)).toHaveLength(1);+ expect(a.createdIssueIds).toEqual(b.createdIssueIds);+ expect(await issueCount(preview)).toBe(2);+ });++ it('keeps replace mode independent of the session — it rewrites rather than replays', async () => {+ wireDefaultLLMResponses();+ const preview = await analyze();+ await importerSvc.commitImport(payloadFor(preview));+ const replaced = await importerSvc.commitImport(payloadFor(preview, {+ replaceMode: true,+ issues: [{ title: 'Replacement', arcPosition: 1, proseExcerpt: 'r' }],+ }));+ expect(replaced.replayed).toBeUndefined();+ const after = await issuesSvc.listIssues({ seriesId: preview.series.id });+ expect(after.map((i) => i.title)).toEqual(['Replacement']);+ });++ it('commits without an importId exactly as before (older clients)', async () => {+ const { uni, ser } = await setupForCommit();+ const body = { universeId: uni.id, seriesId: ser.id, issues: [{ title: 'Solo', proseExcerpt: 'p' }] };+ await importerSvc.commitImport(body);+ await importerSvc.commitImport(body);+ expect(await issuesSvc.listIssues({ seriesId: ser.id })).toHaveLength(2);+ });+});+describe('mergeSeasons (pure helper)', () => {const stubBuildSeason = (input) => ({id: `built-${input.number}`,diff --git a/server/services/importerSessions.js b/server/services/importerSessions.jsnew file mode 100644index 0000000000..3a31dfbb9b--- /dev/null+++ b/server/services/importerSessions.js@@ -0,0 +1,136 @@+/**+ * Importer sessions — server-side progress markers for the analyze → commit+ * workflow (#9943).+ *+ * The Importer page and the Story Builder import intake used to keep "this+ * import already committed" / "arc already persisted" in React state, so a+ * reload between the commit and the next step lost the marker: re-analyzing the+ * same manuscript matches the universe + series by name, and the client then+ * re-sent the full payload — duplicated issues and an overwritten arc.+ *+ * One session per (series, manuscript). The import id is DERIVED from those two+ * inputs rather than minted, so the client holds nothing across a reload: a+ * re-analyze of the same text into the same series recomputes the same id and+ * reads the same session back.+ *+ * Machine-local `file-primary` store (`data/importer-sessions.json`), never+ * federated — it records what THIS machine's commit did to THIS machine's+ * records; docs/STORAGE.md carries the classification. Absent file = no+ * sessions, so no seed and no migration.+ */++import { createHash } from 'crypto';+import { join } from 'path';+import { PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { IMPORT_ID_RE } from '../lib/creativeDirectorValidation.js';++const STORE_PATH = join(PATHS.data, 'importer-sessions.json');+const STORE_VERSION = 1;+// Oldest sessions drop first. A session is a few hundred bytes, so this bounds+// the file without ever evicting anything a user could plausibly still resume.+export const IMPORT_SESSION_MAX = 500;++export const SESSION_STATUS = Object.freeze({+ // Canon + arc + seasons landed; the issue set did not (it rolled back).+ ARC_PERSISTED: 'arc-persisted',+ // Every issue was created.+ COMMITTED: 'committed',+});+const STATUSES = new Set(Object.values(SESSION_STATUS));++// Serializes the read-modify-write cycle on the one shared file.+const enqueue = createFileWriteQueue();++/**+ * Deterministic import id for one manuscript imported into one series. Line+ * endings and surrounding whitespace are normalized so a CRLF paste of the same+ * text lands on the same session. `contentType` is deliberately NOT part of it:+ * re-classifying the same text must not open a second import of it.+ */+export function deriveImportId({ seriesId, source }) {+ const digest = createHash('sha256')+ .update(String(source ?? '').replace(/\r\n?/g, '\n').trim())+ .digest('hex');+ const id = createHash('sha256').update(`${seriesId}\n${digest}`).digest('hex').slice(0, 32);+ return `imp-${id}`;+}++const strArray = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string' && x) : []);++function sanitizeSession(id, raw) {+ if (!raw || typeof raw !== 'object' || !STATUSES.has(raw.status)) return null;+ if (typeof raw.seriesId !== 'string' || !raw.seriesId) return null;+ return {+ id,+ universeId: typeof raw.universeId === 'string' ? raw.universeId : null,+ seriesId: raw.seriesId,+ status: raw.status,+ createdIssueIds: strArray(raw.createdIssueIds),+ remappedIssues: Array.isArray(raw.remappedIssues) ? raw.remappedIssues : [],+ updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : new Date(0).toISOString(),+ };+}++// An absent file is a fresh install (no sessions); an unreadable one rejects+// rather than reading as empty, because the next write would then replace+// markers this reader merely failed to parse.+async function readSessions() {+ const state = await readJSONFile(STORE_PATH, null, { allowArray: false, strict: true });+ const out = new Map();+ if (state?.version !== STORE_VERSION || !state.sessions || typeof state.sessions !== 'object') return out;+ for (const [id, raw] of Object.entries(state.sessions)) {+ if (!IMPORT_ID_RE.test(id)) continue;+ const session = sanitizeSession(id, raw);+ if (session) out.set(id, session);+ }+ return out;+}++export async function getImportSession(importId) {+ if (!IMPORT_ID_RE.test(importId || '')) return null;+ return (await readSessions()).get(importId) ?? null;+}++/**+ * Upsert a session's progress. `patch` carries `status` and, for a committed+ * session, the ids it created. Returns the stored session.+ */+export async function recordImportProgress(importId, patch) {+ if (!IMPORT_ID_RE.test(importId || '')) throw new Error(`Invalid import id: ${importId}`);+ return enqueue(async () => {+ const sessions = await readSessions();+ const session = sanitizeSession(importId, {+ ...sessions.get(importId),+ ...patch,+ updatedAt: new Date().toISOString(),+ });+ if (!session) throw new Error(`Invalid import session for ${importId}`);+ // Re-insert so the Map's iteration order is also recency order.+ sessions.delete(importId);+ sessions.set(importId, session);+ const kept = [...sessions.values()]+ .sort((a, b) => a.updatedAt.localeCompare(b.updatedAt))+ .slice(-IMPORT_SESSION_MAX);+ await atomicWrite(STORE_PATH, {+ version: STORE_VERSION,+ sessions: Object.fromEntries(kept.map((s) => [s.id, s])),+ });+ return session;+ });+}++// Per-import in-flight chain. A commit can run for minutes (the optional+// per-issue cleanup pass is one LLM call each), so a double-click or a second+// tab re-committing the same import must wait for the first and then see its+// `committed` session — not race it into a second issue set.+const inFlight = new Map();++export function withImportLock(importId, fn) {+ const prev = inFlight.get(importId) ?? Promise.resolve();+ const run = prev.then(fn);+ const tail = run.catch(() => {});+ inFlight.set(importId, tail);+ tail.then(() => { if (inFlight.get(importId) === tail) inFlight.delete(importId); });+ return run;+}diff --git a/server/services/importerSessions.test.js b/server/services/importerSessions.test.jsnew file mode 100644index 0000000000..b13f6a254f--- /dev/null+++ b/server/services/importerSessions.test.js@@ -0,0 +1,98 @@+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { join } from 'path';+import {+ makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots,+} from '../lib/mockPathsDataRoot.js';++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-importer-sessions-store-') }));++const {+ deriveImportId, getImportSession, recordImportProgress, withImportLock, IMPORT_SESSION_MAX,+} = await import('./importerSessions.js');++const STORE = join(lazyTempDataRoot('portos-importer-sessions-store-'), 'importer-sessions.json');+const idFor = (n) => `imp-${n.toString(16).padStart(32, '0')}`;++beforeEach(() => {+ rmSync(STORE, { force: true });+ mkdirSync(join(STORE, '..'), { recursive: true });+});+afterAll(cleanupTempDataRoots);++describe('deriveImportId', () => {+ it('is stable across line endings and surrounding whitespace, so a re-paste lands on the same session', () => {+ const id = deriveImportId({ seriesId: 'ser-1', source: 'Line one.\nLine two.' });+ expect(id).toMatch(/^imp-[0-9a-f]{32}$/);+ expect(deriveImportId({ seriesId: 'ser-1', source: ' Line one.\r\nLine two.\n\n' })).toBe(id);+ });++ it('separates a different manuscript, and the same manuscript in a different series', () => {+ const id = deriveImportId({ seriesId: 'ser-1', source: 'Text A' });+ expect(deriveImportId({ seriesId: 'ser-1', source: 'Text B' })).not.toBe(id);+ expect(deriveImportId({ seriesId: 'ser-2', source: 'Text A' })).not.toBe(id);+ });+});++describe('session store', () => {+ it('upserts progress, keeping what an earlier step recorded', async () => {+ const id = idFor(1);+ await recordImportProgress(id, { seriesId: 'ser-1', universeId: 'uni-1', status: 'arc-persisted' });+ await recordImportProgress(id, { status: 'committed', createdIssueIds: ['iss-1'] });++ expect(await getImportSession(id)).toMatchObject({+ id, seriesId: 'ser-1', universeId: 'uni-1', status: 'committed', createdIssueIds: ['iss-1'],+ });+ });++ it('keeps only the newest sessions, evicting the oldest first', async () => {+ const seeded = Object.fromEntries(Array.from({ length: IMPORT_SESSION_MAX }, (_, i) => [idFor(i), {+ seriesId: 'ser-1', status: 'committed', createdIssueIds: ['iss-1'],+ updatedAt: new Date(Date.UTC(2026, 0, 1, 0, 0, i)).toISOString(),+ }]));+ writeFileSync(STORE, JSON.stringify({ version: 1, sessions: seeded }));++ await recordImportProgress(idFor(IMPORT_SESSION_MAX), { seriesId: 'ser-1', status: 'arc-persisted' });++ expect(await getImportSession(idFor(0))).toBeNull();+ expect(await getImportSession(idFor(1))).not.toBeNull();+ expect(await getImportSession(idFor(IMPORT_SESSION_MAX))).not.toBeNull();+ expect(Object.keys(JSON.parse(readFileSync(STORE, 'utf8')).sessions)).toHaveLength(IMPORT_SESSION_MAX);+ });++ it('reads a file from another schema version as empty rather than half-reading it', async () => {+ writeFileSync(STORE, JSON.stringify({+ version: 2, sessions: { [idFor(1)]: { seriesId: 'ser-1', status: 'committed' } },+ }));+ expect(await getImportSession(idFor(1))).toBeNull();+ });++ it('refuses to overwrite a file it cannot parse', async () => {+ writeFileSync(STORE, '{ not json');+ await expect(recordImportProgress(idFor(1), { seriesId: 'ser-1', status: 'committed' })).rejects.toThrow();+ expect(readFileSync(STORE, 'utf8')).toBe('{ not json');+ });++ it('rejects a malformed import id instead of keying the file by it', async () => {+ await expect(recordImportProgress('../escape', { seriesId: 'ser-1', status: 'committed' })).rejects.toThrow(/Invalid import id/);+ expect(await getImportSession('../escape')).toBeNull();+ });+});++describe('withImportLock', () => {+ it('runs one import id at a time, in call order, even when an earlier run fails', async () => {+ const order = [];+ const run = (label, ms, fail = false) => withImportLock(idFor(9), async () => {+ order.push(`start ${label}`);+ await new Promise((r) => setTimeout(r, ms));+ order.push(`end ${label}`);+ if (fail) throw new Error('boom');+ });++ const results = await Promise.allSettled([run('a', 20, true), run('b', 0)]);++ expect(order).toEqual(['start a', 'end a', 'start b', 'end b']);+ expect(results.map((r) => r.status)).toEqual(['rejected', 'fulfilled']);+ });+});diff --git a/server/services/roundReferenceAudioImport.js b/server/services/roundReferenceAudioImport.jsindex e1c0fc507d..474f209168 100644--- a/server/services/roundReferenceAudioImport.js+++ b/server/services/roundReferenceAudioImport.js@@ -20,6 +20,7 @@ import { assertPublicHttpUrl } from '../lib/safeUrlFetch.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../lib/sseUtils.js';import { killWithEscalation } from '../lib/killWithEscalation.js';import { resolveYtDlpBinaries, downloadAudioToTempMp3, cleanupYtDlpTemp } from './ytdlpAudioImport.js';+import { attachReferenceAudio } from './rounds.js';// Reference performances are short clips — bound resource use so a mistyped// link to a long archive/livestream can't download + transcode unbounded.@@ -60,11 +61,17 @@ export function cancelReferenceAudioImport(jobId) {/*** Kick off a reference-audio download. Returns `{ jobId }` immediately; the* download+extract runs detached and streams progress over SSE. Terminal- * frames: `{ type: 'complete', filename }`, `{ type: 'error', error }`, or+ * frames: `{ type: 'complete', filename, attached }`, `{ type: 'error', error }`, or* `{ type: 'canceled' }`. Throws (before returning a jobId) on an unsafe URL or* a missing yt-dlp/ffmpeg binary, so those surface as real HTTP errors.+ *+ * Given the round + reference the download is for, the finished file is attached+ * to that saved reference server-side (#9943) rather than left for the client to+ * carry until Save — `attached` reports whether that happened. A reference that+ * is still an unsaved draft has nothing server-side to attach to, so it stays the+ * client's job (`attached: false`).*/-export async function startReferenceAudioImport(url) {+export async function startReferenceAudioImport(url, { roundId = null, referenceId = null } = {}) {// SSRF guard: http(s) only, reject loopback/link-local/metadata AND private// LAN hosts (blockPrivate) — yt-dlp fetches the URL itself, so it never// reaches our SSRF-guarded fetcher; validate before handing it the URL.@@ -114,8 +121,17 @@ export async function startReferenceAudioImport(url) {const { title, outPath } = result;const { filename } = await importFileToUploads(outPath, `${title || 'Reference Audio'}.mp3`);- console.log(`🎧 Reference-audio import ${shortId(jobId)} complete — ${filename}`);- broadcastSse(job, { type: 'complete', filename, title: title || null });+ // A failed attach must not turn a finished download into an error frame:+ // the file is in uploads and the client can still attach it on Save.+ const attached = roundId && referenceId+ ? await attachReferenceAudio(roundId, referenceId, filename).catch((err) => {+ console.error(`❌ Reference-audio import ${shortId(jobId)} could not attach ${filename}: ${err?.message || err}`);+ return false;+ })+ : false;++ console.log(`🎧 Reference-audio import ${shortId(jobId)} complete — ${filename}${attached ? ' (attached)' : ''}`);+ broadcastSse(job, { type: 'complete', filename, title: title || null, attached });} catch (err) {console.error(`❌ Reference-audio import ${shortId(jobId)} failed: ${err?.message || err}`);broadcastSse(job, { type: 'error', error: err?.message || String(err) });diff --git a/server/services/roundReferenceAudioImport.test.js b/server/services/roundReferenceAudioImport.test.jsindex 0c46deebf3..0f571eb9fa 100644--- a/server/services/roundReferenceAudioImport.test.js+++ b/server/services/roundReferenceAudioImport.test.js@@ -13,6 +13,7 @@ vi.mock('./ytdlpAudioImport.js', () => ({downloadAudioToTempMp3: vi.fn(),cleanupYtDlpTemp: vi.fn(async () => {}),}));+vi.mock('./rounds.js', () => ({ attachReferenceAudio: vi.fn() }));vi.mock('../lib/fileUtils.js', async (importOriginal) => ({...(await importOriginal()),importFileToUploads: vi.fn(async () => ({ filename: 'ab12cd34-Reference_Audio.mp3', sizeBytes: 100 })),@@ -23,6 +24,7 @@ const { broadcastSse } = await import('../lib/sseUtils.js');const { resolveYtDlpBinaries, downloadAudioToTempMp3, cleanupYtDlpTemp } = await import('./ytdlpAudioImport.js');const { importFileToUploads } = await import('../lib/fileUtils.js');const { killWithEscalation } = await import('../lib/killWithEscalation.js');+const { attachReferenceAudio } = await import('./rounds.js');const {startReferenceAudioImport, cancelReferenceAudioImport, __testing,} = await import('./roundReferenceAudioImport.js');@@ -68,6 +70,40 @@ describe('startReferenceAudioImport — outcomes', () => {);});+ // #9943: the file lands on the saved reference at download time, so a reload+ // between the download and Save no longer orphans it.+ describe('attaching to the saved reference', () => {+ const FILE = 'ab12cd34-Reference_Audio.mp3';+ const target = { roundId: 'round-1', referenceId: 'ref-1' };+ const completeFrame = () => broadcastSse.mock.calls.map(([, frame]) => frame).find((f) => f.type === 'complete');+ beforeEach(() => {+ downloadAudioToTempMp3.mockResolvedValue({ outcome: 'complete', outPath: '/tmp/x.mp3', title: 'My Clip' });+ });++ it('attaches the finished file and reports it on the complete frame', async () => {+ attachReferenceAudio.mockResolvedValue(true);+ await startReferenceAudioImport('https://example.com/clip', target);+ await flush();+ expect(attachReferenceAudio).toHaveBeenCalledWith('round-1', 'ref-1', FILE);+ expect(completeFrame()).toMatchObject({ filename: FILE, attached: true });+ });++ it('leaves attaching to the client when no target was given (an unsaved reference)', async () => {+ await startReferenceAudioImport('https://example.com/clip');+ await flush();+ expect(attachReferenceAudio).not.toHaveBeenCalled();+ expect(completeFrame()).toMatchObject({ filename: FILE, attached: false });+ });++ it('still completes with the filename when the attach fails', async () => {+ attachReferenceAudio.mockRejectedValue(new Error('disk full'));+ await startReferenceAudioImport('https://example.com/clip', target);+ await flush();+ expect(completeFrame()).toMatchObject({ filename: FILE, attached: false });+ expect(broadcastSse).not.toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ type: 'error' }));+ });+ });+it('falls back to a default title when yt-dlp reported none', async () => {downloadAudioToTempMp3.mockResolvedValue({ outcome: 'complete', outPath: '/tmp/x.mp3', title: '' });await startReferenceAudioImport('https://example.com/clip');diff --git a/server/services/rounds.js b/server/services/rounds.jsindex ddd1cd467d..8dca0d4d9b 100644--- a/server/services/rounds.js+++ b/server/services/rounds.js@@ -592,6 +592,35 @@ export async function updateRound(id, patch) {});}+// Attach a downloaded reference-audio file to a reference that is ALREADY+// persisted on the round (#9943). The download used to leave the filename only+// in the editor's draft until Save, so a reload orphaned the file and lost the+// result; attaching at download time puts it on the song itself, and Save then+// merely confirms what the server already holds.+//+// Returns whether it attached. A missing round or reference (the row is still an+// unsaved draft, or was deleted mid-download) and a reference that already has+// audio are both a clean `false`: this never replaces a recording the user+// attached, and never throws into the finished download that called it.+export async function attachReferenceAudio(roundId, referenceId, audioFilename) {+ return enqueue(async () => {+ const songs = await readRounds();+ const idx = songs.findIndex((s) => s.id === roundId);+ if (idx === -1) return false;+ const references = songs[idx].references || [];+ const refIdx = references.findIndex((r) => r.id === referenceId);+ if (refIdx === -1 || references[refIdx].audioFilename) return false;+ songs[idx] = sanitizeRound({+ ...songs[idx],+ references: references.map((r, i) => (i === refIdx ? { ...r, audioFilename } : r)),+ updatedAt: new Date().toISOString(),+ });+ await atomicWrite(STATE_PATH, { rounds: songs });+ console.log(`🎧 Attached reference audio ${audioFilename} to "${songs[idx].title}" (${roundId})`);+ return true;+ });+}+// Restore a built-in default song's shipped content (metadata, lyrics, layers,// notation, notes) to the current bundled template — for installs that seeded// an older version of the song and want the newer shipped one. User-owned statediff --git a/server/services/rounds.test.js b/server/services/rounds.test.jsindex 68d75e3f32..9fea5a0365 100644--- a/server/services/rounds.test.js+++ b/server/services/rounds.test.js@@ -716,6 +716,50 @@ describe('rounds service', () => {expect(patched.partnerRoundIds).toEqual(['song-other']); // self dropped});+ // #9943: a finished reference-audio download attaches to the saved reference+ // itself, so a reload (a fresh read of the store) still shows the file.+ describe('attachReferenceAudio', () => {+ const makeRound = (references) => svc.createRound({ title: 'Attach test', references });++ it('persists the file on the reference so a fresh read still shows it', async () => {+ const round = await makeRound([{ id: 'ref-a', url: 'https://example.com/clip' }]);++ expect(await svc.attachReferenceAudio(round.id, 'ref-a', 'clip.mp3')).toBe(true);++ const reloaded = await svc.getRound(round.id);+ expect(reloaded.references[0]).toMatchObject({ id: 'ref-a', audioFilename: 'clip.mp3' });+ });++ it('never replaces audio already attached to the reference', async () => {+ const round = await makeRound([{ id: 'ref-a', url: 'https://example.com/clip', audioFilename: 'first.mp3' }]);++ expect(await svc.attachReferenceAudio(round.id, 'ref-a', 'second.mp3')).toBe(false);++ expect((await svc.getRound(round.id)).references[0].audioFilename).toBe('first.mp3');+ });++ it('attaches only to the named reference', async () => {+ const round = await makeRound([+ { id: 'ref-a', url: 'https://example.com/a' },+ { id: 'ref-b', url: 'https://example.com/b' },+ ]);++ await svc.attachReferenceAudio(round.id, 'ref-b', 'b.mp3');++ const [a, b] = (await svc.getRound(round.id)).references;+ expect(a.audioFilename).toBeUndefined();+ expect(b.audioFilename).toBe('b.mp3');+ });++ it('reports false for a round or reference that is not on disk (an unsaved draft row)', async () => {+ const round = await makeRound([{ id: 'ref-a', url: 'https://example.com/clip' }]);++ expect(await svc.attachReferenceAudio('round-missing', 'ref-a', 'clip.mp3')).toBe(false);+ expect(await svc.attachReferenceAudio(round.id, 'tmp-ref-draft', 'clip.mp3')).toBe(false);+ expect((await svc.getRound(round.id)).references[0].audioFilename).toBeUndefined();+ });+ });+it('getRound returns null for a non-existent id', async () => {await svc.listRounds(); // ensure seededconst missing = await svc.getRound('song-does-not-exist-xyz');