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 rejected Brain captures recoverable with Retry/Edit/Discard (#9722)
[._.]/ Adam Eivye26a9d0010e7
diff --git a/client/src/components/QuickBrainCapture.jsx b/client/src/components/QuickBrainCapture.jsxindex bb8a6b81a0..7281bf502b 100644--- a/client/src/components/QuickBrainCapture.jsx+++ b/client/src/components/QuickBrainCapture.jsx@@ -10,6 +10,8 @@ import { INGEST_OPTIONS, defaultIngestOptions, ingestOptionsFromSettings, isYoutimport RepoIntakeOptions from './brain/RepoIntakeOptions';import RepoStudyFields from './brain/RepoStudyFields';import useRepoStudyConfig from '../hooks/useRepoStudyConfig';+import { useFailedCaptures } from '../hooks/useFailedCaptures';+import FailedCaptureList from './brain/FailedCaptureList';import ProgressBar from './ui/ProgressBar';import ToggleChip from './ui/ToggleChip';@@ -57,11 +59,28 @@ export default function QuickBrainCapture() {.catch(() => {}); // defaultIngestOptions() is already sensible}, [isYoutube]);+ const failedCaptures = useFailedCaptures();+ // Which failed row a YouTube Retry came from, so its kickoff outcome updates+ // or retires that row instead of stacking a new one.+ const retryingYoutubeRef = useRef(null);+const ingest = useYoutubeIngest({onComplete: () => {setAgentPrompt('');setTagsInput('');},+ // The kickoff was rejected (the toast still fires): keep the exact request —+ // URL, note, selected options, agent brief — in a "Not saved" row.+ onKickoffError: (err, body) => {+ const failedId = retryingYoutubeRef.current;+ retryingYoutubeRef.current = null;+ failedCaptures.fail({ kind: 'youtube', body }, err?.message || 'Failed to start the ingest', failedId ?? undefined);+ },+ onKickoffSuccess: () => {+ const failedId = retryingYoutubeRef.current;+ retryingYoutubeRef.current = null;+ if (failedId) failedCaptures.discard(failedId);+ },});const nothingSelected = !INGEST_OPTIONS.some((o) => ingestOpts[o.key]);@@ -82,14 +101,14 @@ export default function QuickBrainCapture() {setInput('');setLinkNote('');const { studyContext: _context, ...agentOptions } = analysis.studyPayload();- ingest.start({+ ingest.start(Object.freeze({url: text,...ingestOpts,...(note ? { note } : {}),agentPrompt: agentPrompt.trim(),...(agentPrompt.trim() ? { ...agentOptions, workMode } : {}),tags: tagsInput.split(',').map((t) => t.trim()).filter(Boolean),- });+ }));return;}@@ -106,23 +125,50 @@ export default function QuickBrainCapture() {// the request honest about what will be stored.// `intakeFor` re-derives from the submitted text, so a sticky tick can't ride// along on a capture that is no longer a repo URL.- const captureOptions = {+ const payload = Object.freeze({+ kind: 'thought',+ text,+ note,creative: creative && !isUrl,repoIntake: repoIntake.intakeFor(text),- };- if (note) captureOptions.note = note;- const result = await api.captureBrainThought(text, undefined, undefined, captureOptions, { silent: true }).catch(err => {- toast.error(err.message || 'Failed to capture');- setInput(prev => prev || text);+ });+ // The note and study brief now live in the payload, so they clear with the+ // composer instead of on acknowledgement (which could wipe the next draft's).+ repoIntake.setStudyContext('');+ setLinkNote('');+ await sendCapture(payload);+ submittingRef.current = false;+ setIsSubmitting(false);+ };++ // Sends one thought/link capture from its retained payload. A rejection keeps+ // the payload in a persistent "Not saved" row; the composer is never touched.+ const sendCapture = async (payload, failedId) => {+ const captureOptions = { creative: payload.creative, repoIntake: payload.repoIntake };+ if (payload.note) captureOptions.note = payload.note;+ const result = await api.captureBrainThought(payload.text, undefined, undefined, captureOptions, { silent: true }).catch(err => {+ const message = err.message || 'Failed to capture';+ toast.error(message);+ failedCaptures.fail(payload, message, failedId);return null;});if (result) {+ if (failedId) failedCaptures.discard(failedId);toast.success(result.message || 'Captured');- repoIntake.setStudyContext('');- setLinkNote('');}- submittingRef.current = false;- setIsSubmitting(false);+ return result;+ };++ // Explicit Retry only: re-sends the retained payload (with any edit made in+ // the row) once, and leaves the composer draft and its options alone.+ const handleRetryFailed = (failure, text) => {+ if (!failedCaptures.markRetrying(failure.id)) return;+ if (failure.payload.kind === 'youtube') {+ retryingYoutubeRef.current = failure.id;+ ingest.start(Object.freeze({ ...failure.payload.body, url: text }));+ return;+ }+ return sendCapture({ ...failure.payload, text }, failure.id);};// Paste without having to click into the box first — the usual flow here is@@ -291,6 +337,16 @@ export default function QuickBrainCapture() {{...repoIntake}/>+ <FailedCaptureList+ idPrefix="quick-brain-failed"+ failures={failedCaptures.failures}+ getText={(f) => f.payload.kind === 'youtube' ? f.payload.body.url : f.payload.text}+ getNote={(f) => f.payload.kind === 'youtube' ? f.payload.body.note : f.payload.note}+ onRetry={handleRetryFailed}+ onDiscard={failedCaptures.discard}+ retryDisabled={ingest.active}+ />+{ingest.active && (<div className="mt-3 flex items-center gap-2 text-xs text-gray-400"><Film size={14} className="text-red-400 shrink-0" />diff --git a/client/src/components/QuickBrainCapture.test.jsx b/client/src/components/QuickBrainCapture.test.jsxindex 3b53570b96..7c1c3374d6 100644--- a/client/src/components/QuickBrainCapture.test.jsx+++ b/client/src/components/QuickBrainCapture.test.jsx@@ -503,4 +503,50 @@ describe('QuickBrainCapture', () => {expect(screen.getByPlaceholderText(PLACEHOLDER)).toHaveValue('');});});++ describe('rejected capture recovery', () => {+ it('keeps a rejected thought recoverable beside a different draft, and retries it once', async () => {+ let rejectFirst;+ captureBrainThought.mockImplementationOnce(() => new Promise((_res, rej) => { rejectFirst = rej; }));+ renderWidget();+ submit('invented thought A');+ type('invented thought B');+ await act(async () => { rejectFirst(new Error('Server said no')); });++ const row = await screen.findByRole('group', { name: 'Not saved capture' });+ expect(row.textContent).toContain('invented thought A');+ expect(row.textContent).toContain('Server said no');+ expect(screen.getByPlaceholderText(PLACEHOLDER)).toHaveValue('invented thought B');++ const retry = screen.getByRole('button', { name: /Retry/ });+ fireEvent.click(retry);+ fireEvent.click(retry);+ await waitFor(() => expect(screen.queryByRole('group', { name: 'Not saved capture' })).toBeNull());+ expect(captureBrainThought).toHaveBeenCalledTimes(2);+ expect(captureBrainThought.mock.calls[1][0]).toBe('invented thought A');+ expect(screen.getByPlaceholderText(PLACEHOLDER)).toHaveValue('invented thought B');+ });++ it('preserves a rejected YouTube kickoff with its note and options, and retries without starting twice', async () => {+ startYoutubeIngest.mockRejectedValueOnce(new Error('Ingest refused'));+ renderWidget();+ type(YT);+ await openAdvanced();+ fireEvent.click(screen.getByLabelText(/Audio/i));+ fireEvent.change(screen.getByLabelText(/Tags/i), { target: { value: 'alpha, beta' } });+ fireEvent.click(screen.getByLabelText('Capture'));++ const row = await screen.findByRole('group', { name: 'Not saved capture' });+ expect(row.textContent).toContain(YT);+ expect(row.textContent).toContain('Ingest refused');+ expect(screen.getByPlaceholderText(PLACEHOLDER)).toHaveValue('');+ const firstBody = startYoutubeIngest.mock.calls[0][0];+ expect(firstBody).toMatchObject({ ingestAudio: true, tags: ['alpha', 'beta'] });++ fireEvent.click(screen.getByRole('button', { name: /Retry/ }));+ await waitFor(() => expect(screen.queryByRole('group', { name: 'Not saved capture' })).toBeNull());+ expect(startYoutubeIngest).toHaveBeenCalledTimes(2);+ expect(startYoutubeIngest.mock.calls[1][0]).toEqual(firstBody);+ });+ });});diff --git a/client/src/components/brain/FailedCaptureList.jsx b/client/src/components/brain/FailedCaptureList.jsxnew file mode 100644index 0000000000..740b7e2cb7--- /dev/null+++ b/client/src/components/brain/FailedCaptureList.jsx@@ -0,0 +1,85 @@+import { useState } from 'react';+import { AlertCircle, Pencil, RotateCcw, Trash2 } from 'lucide-react';++/**+ * Persistent "Not saved" rows for rejected Brain captures. The text shown is+ * the submitted text, never the composer's current draft. Edit changes the+ * retained text in place (so a newer draft in the composer is untouched) and+ * Retry sends whatever the row currently says. The row only leaves when the+ * host discards it or a retry is acknowledged.+ *+ * `failures` come from `useFailedCaptures`; `getText(failure)` / `getNote(failure)`+ * project the payload so each surface keeps its own payload shape.+ */+export default function FailedCaptureList({ failures, getText, getNote, onRetry, onDiscard, retryDisabled = false, idPrefix = 'failed-capture' }) {+ const [edits, setEdits] = useState({});++ if (!failures.length) return null;++ const closeEdit = (id) => setEdits((prev) => {+ const { [id]: _removed, ...rest } = prev;+ return rest;+ });++ return (+ <ul className="mt-3 space-y-2 min-w-0" aria-label="Captures not saved">+ {failures.map((f) => {+ const editing = edits[f.id] !== undefined;+ const text = edits[f.id] ?? getText(f);+ const note = getNote?.(f);+ return (+ <li key={f.id} className="min-w-0 p-3 bg-port-error/10 border border-port-error/40 rounded-lg" role="group" aria-label="Not saved capture">+ <div className="flex items-start gap-2 min-w-0">+ <AlertCircle size={14} className="text-port-error shrink-0 mt-0.5" aria-hidden="true" />+ <div className="min-w-0 flex-1">+ <p className="text-xs font-medium text-port-error">Not saved</p>+ <p className="text-xs text-gray-400 break-words [overflow-wrap:anywhere]">{f.error}</p>+ {editing ? (+ <>+ <label htmlFor={`${idPrefix}-${f.id}`} className="sr-only">Edit unsaved capture</label>+ <textarea+ id={`${idPrefix}-${f.id}`}+ rows={3}+ value={text}+ onChange={(e) => setEdits((prev) => ({ ...prev, [f.id]: e.target.value }))}+ className="mt-2 w-full min-w-0 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm resize-y"+ />+ </>+ ) : (+ <p className="mt-1 text-sm text-white whitespace-pre-wrap break-words [overflow-wrap:anywhere]">{text}</p>+ )}+ {note ? <p className="mt-1 text-xs text-gray-500 break-words [overflow-wrap:anywhere]">Note: {note}</p> : null}+ </div>+ </div>+ <div className="mt-2 flex flex-wrap gap-2">+ <button+ type="button"+ onClick={() => (editing ? closeEdit(f.id) : setEdits((prev) => ({ ...prev, [f.id]: getText(f) })))}+ aria-pressed={editing}+ className="min-h-[36px] inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-port-border text-xs text-gray-300 hover:text-white transition-colors"+ >+ <Pencil size={12} aria-hidden="true" /> {editing ? 'Done editing' : 'Edit'}+ </button>+ <button+ type="button"+ disabled={f.retrying || retryDisabled || !text.trim()}+ onClick={() => onRetry(f, text.trim())}+ className="min-h-[36px] inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-port-accent/40 bg-port-accent/20 text-xs text-port-accent hover:bg-port-accent/30 transition-colors disabled:opacity-50"+ >+ <RotateCcw size={12} aria-hidden="true" /> {f.retrying ? 'Retrying…' : 'Retry'}+ </button>+ <button+ type="button"+ disabled={f.retrying}+ onClick={() => { closeEdit(f.id); onDiscard(f.id); }}+ className="min-h-[36px] inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-port-border text-xs text-gray-400 hover:text-port-error transition-colors disabled:opacity-50"+ >+ <Trash2 size={12} aria-hidden="true" /> Discard+ </button>+ </div>+ </li>+ );+ })}+ </ul>+ );+}diff --git a/client/src/components/brain/tabs/InboxTab.jsx b/client/src/components/brain/tabs/InboxTab.jsxindex 39df603e2a..9d0952b4e0 100644--- a/client/src/components/brain/tabs/InboxTab.jsx+++ b/client/src/components/brain/tabs/InboxTab.jsx@@ -24,6 +24,8 @@ import toast from '../../ui/Toast';import InlineConfirmRow from '../../ui/InlineConfirmRow';import InfiniteScrollFooter from '../../ui/InfiniteScrollFooter';import { useLocalStorageBool } from '../../../hooks';+import { useFailedCaptures } from '../../../hooks/useFailedCaptures';+import FailedCaptureList from '../FailedCaptureList';import { usePagedCollection } from '../../../hooks/usePagedCollection';import {@@ -74,6 +76,7 @@ export default function InboxTab({ onRefresh, settings }) {const [showDone, setShowDone] = useState(false);const [confirmingDeleteId, setConfirmingDeleteId] = useState(null);const [retryingId, setRetryingId] = useState(null);+ const failedCaptures = useFailedCaptures();const inputRef = useRef(null);const tempIdCounter = useRef(0);@@ -137,6 +140,45 @@ export default function InboxTab({ onRefresh, settings }) {return () => socket.off('brain:classified', handleClassified);}, [paged.refreshFirst, onRefresh]);+ // Sends one capture. `payload` is the immutable request the submit built+ // (text, note, creative flag, repo-intake options) so a Retry re-sends exactly+ // what the user submitted, not whatever the composer holds now. A rejection+ // keeps the payload in a persistent "Not saved" row (`failedId` refreshes the+ // row a Retry came from instead of stacking a second one).+ const sendCapture = async (payload, { failedId } = {}) => {+ const tempId = `_pending_${++tempIdCounter.current}`;+ setOptimisticEntries(prev => [{+ id: tempId,+ capturedText: payload.text,+ status: 'classifying',+ capturedAt: new Date().toISOString(),+ ...(payload.creative ? { creative: true } : {})+ }, ...prev]);++ const captureOptions = { creative: payload.creative, repoIntake: payload.repoIntake };+ if (payload.note) captureOptions.note = payload.note;+ const result = await api.captureBrainThought(payload.text, undefined, undefined, captureOptions, { silent: true }).catch(err => {+ const message = err.message || 'Failed to capture thought';+ toast.error(message);+ setOptimisticEntries(prev => prev.filter(e => e.id !== tempId));+ failedCaptures.fail(payload, message, failedId);+ return null;+ });+ if (!result) return;++ if (failedId) failedCaptures.discard(failedId);+ if (result.inboxLog) {+ setOptimisticEntries(prev => prev.map(e => e.id === tempId ? result.inboxLog : e));+ } else {+ setOptimisticEntries(prev => prev.filter(e => e.id !== tempId));+ }+ paged.refreshFirst();+ // A capture that was just a URL is filed to Links synchronously — no+ // brain:classified event follows, so announce the outcome here.+ if (result.link) toast.success(result.message || 'Saved to Links');+ onRefresh?.();+ };+const handleSubmit = async (e) => {e.preventDefault();const text = inputText.trim();@@ -150,47 +192,26 @@ export default function InboxTab({ onRefresh, settings }) {// The server files a URL to Links regardless of the sticky Creative flag;// dropping it here keeps the optimistic entry matching what gets stored.- const asCreative = creative && !inputIsUrl;- const tempId = `_pending_${++tempIdCounter.current}`;- const optimisticEntry = {- id: tempId,- capturedText: text,- status: 'classifying',- capturedAt: new Date().toISOString(),- ...(asCreative ? { creative: true } : {})- };- setInputText('');- setOptimisticEntries(prev => [optimisticEntry, ...prev]);-// `intakeFor` re-derives from the submitted text, so a sticky tick can't ride// along on a capture that is no longer a repo URL.- const captureOptions = {- creative: asCreative,+ const payload = Object.freeze({+ text,+ note,+ creative: creative && !inputIsUrl,repoIntake: repoIntake.intakeFor(text),- };- if (note) captureOptions.note = note;- const result = await api.captureBrainThought(text, undefined, undefined, captureOptions, { silent: true }).catch(err => {- toast.error(err.message || 'Failed to capture thought');- setOptimisticEntries(prev => prev.filter(e => e.id !== tempId));- return null;});-+ // The note and study brief now live in the payload, so they clear with the+ // composer rather than on acknowledgement (which could wipe the next draft's).+ setInputText('');+ setLinkNote('');+ repoIntake.setStudyContext('');+ await sendCapture(payload);if (inputRef.current) inputRef.current.dataset.lastSubmit = '';+ };- if (result) {- if (result.inboxLog) {- setOptimisticEntries(prev => prev.map(e => e.id === tempId ? result.inboxLog : e));- } else {- setOptimisticEntries(prev => prev.filter(e => e.id !== tempId));- }- paged.refreshFirst();- // A capture that was just a URL is filed to Links synchronously — no- // brain:classified event follows, so announce the outcome here.- if (result.link) toast.success(result.message || 'Saved to Links');- setLinkNote('');- repoIntake.setStudyContext('');- onRefresh?.();- }+ const handleRetryFailed = (failure, text) => {+ if (!failedCaptures.markRetrying(failure.id)) return;+ return sendCapture({ ...failure.payload, text }, { failedId: failure.id });};const handleResolve = async (entryId, destination) => {@@ -440,6 +461,14 @@ export default function InboxTab({ onRefresh, settings }) {idPrefix="inbox-capture-repo"{...repoIntake}/>+ <FailedCaptureList+ idPrefix="inbox-failed-capture"+ failures={failedCaptures.failures}+ getText={(f) => f.payload.text}+ getNote={(f) => f.payload.note}+ onRetry={handleRetryFailed}+ onDiscard={failedCaptures.discard}+ /></form>{/* Creative batch action — appears once any captured note is flaggeddiff --git a/client/src/components/brain/tabs/InboxTab.test.jsx b/client/src/components/brain/tabs/InboxTab.test.jsxindex 347e8ce374..70d31e5b0f 100644--- a/client/src/components/brain/tabs/InboxTab.test.jsx+++ b/client/src/components/brain/tabs/InboxTab.test.jsx@@ -115,4 +115,61 @@ describe('Brain inbox capture', () => {}),}));});++ describe('rejected capture recovery', () => {+ const deferred = () => {+ let resolve; let reject;+ const promise = new Promise((res, rej) => { resolve = res; reject = rej; });+ return { promise, resolve, reject };+ };++ it('keeps the rejected text until an explicit Retry, without touching the next draft', async () => {+ const first = deferred();+ captureBrainThought.mockReturnValueOnce(first.promise);+ render(<MemoryRouter><InboxTab /></MemoryRouter>);+ const input = await screen.findByLabelText('New inbox thought');++ fireEvent.change(input, { target: { value: 'invented thought A' } });+ fireEvent.click(screen.getByLabelText('Capture thought'));+ await waitFor(() => expect(input.value).toBe(''));+ // The next draft is typed while A is still pending.+ fireEvent.change(input, { target: { value: 'invented thought B' } });++ first.reject(new Error('Server said no'));+ const row = await screen.findByRole('group', { name: 'Not saved capture' });+ expect(row.textContent).toContain('invented thought A');+ expect(row.textContent).toContain('Server said no');+ expect(input.value).toBe('invented thought B');+ expect(captureBrainThought).toHaveBeenCalledTimes(1);++ // Editing the failed row leaves the composer alone; Retry sends the edit once.+ fireEvent.click(screen.getByRole('button', { name: /^Edit$/ }));+ fireEvent.change(screen.getByLabelText('Edit unsaved capture'), { target: { value: 'invented thought A, fixed' } });+ fireEvent.click(screen.getByRole('button', { name: /Retry/ }));+ fireEvent.click(screen.getByRole('button', { name: /Retry|Retrying/ }));++ await waitFor(() => expect(screen.queryByRole('group', { name: 'Not saved capture' })).toBeNull());+ expect(captureBrainThought).toHaveBeenCalledTimes(2);+ expect(captureBrainThought.mock.calls[1][0]).toBe('invented thought A, fixed');+ expect(input.value).toBe('invented thought B');+ });++ it('lets the user discard a failed capture and keeps it on a second failure', async () => {+ captureBrainThought.mockRejectedValue(new Error('Still down'));+ render(<MemoryRouter><InboxTab /></MemoryRouter>);+ const input = await screen.findByLabelText('New inbox thought');+ fireEvent.change(input, { target: { value: 'invented thought C' } });+ fireEvent.click(screen.getByLabelText('Capture thought'));+ await screen.findByRole('group', { name: 'Not saved capture' });++ fireEvent.click(screen.getByRole('button', { name: /Retry/ }));+ await waitFor(() => expect(captureBrainThought).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(screen.getByRole('button', { name: /Retry/ }).disabled).toBe(false));+ expect(screen.getAllByRole('group', { name: 'Not saved capture' })).toHaveLength(1);++ fireEvent.click(screen.getByRole('button', { name: /Discard/ }));+ expect(screen.queryByRole('group', { name: 'Not saved capture' })).toBeNull();+ expect(captureBrainThought).toHaveBeenCalledTimes(2);+ });+ });});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 2c5a3dc8f6..59dea3ffcf 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -163,6 +163,7 @@ grep -i "what you want to do" client/src/hooks/README.md| Hook | Purpose | Use when ||---|---|---|+| `useFailedCaptures` | Recoverable rejected Brain captures: `{ failures, fail(payload, error, id?), markRetrying(id), discard(id) }` keeps each failed submission's immutable payload apart from the composer's next draft; never re-sends by itself (the host's explicit Retry does). | A capture box that clears its input on submit (Inbox, Quick Capture) and must not lose the text when the server rejects it. Pair with `components/brain/FailedCaptureList`. || `useLocalStorageBool` | Boolean `useState` mirrored to `localStorage`; returns `[value, setValue, toggle]`. | Per-user UI preference toggle, and any remembered disclosure (the SongBook viewer's Audio / Sheet controls / Chords used cards). || `useNavWorkingSet` | Sidebar Pinned + Recent working set (localStorage MRU + pins); resolves stored paths to `{ path, label, icon }` rows via a `resolveNavEntry` arg. | Rendering the sidebar's Pinned/Recent sections. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 358e5784be..200229c15d 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -218,6 +218,7 @@ export { default as useUrlParams } from './useUrlParams.js';export * from './useValidTab.js';// === Storage & persistence ===+export * from './useFailedCaptures.js';export * from './useLocalStorageBool.js';export * from './useNavWorkingSet.js';diff --git a/client/src/hooks/useFailedCaptures.js b/client/src/hooks/useFailedCaptures.jsnew file mode 100644index 0000000000..f829c8b53a--- /dev/null+++ b/client/src/hooks/useFailedCaptures.js@@ -0,0 +1,51 @@+import { useCallback, useRef, useState } from 'react';++/**+ * Rejected Brain captures that the user can still recover.+ *+ * A capture box clears its composer the moment a submit starts so the user can+ * keep typing; when the server then rejects it, the submitted work would be+ * gone. Each failure is kept here as an immutable `payload` (the exact request+ * the surface built, including its settings) plus the human-readable `error`,+ * separate from whatever the composer holds now. Nothing in here ever re-sends:+ * the host's Retry action does that, once, on explicit activation.+ *+ * @returns {{+ * failures: Array<{ id: string, payload: object, error: string, retrying: boolean }>,+ * fail: (payload: object, error: string, id?: string) => string,+ * markRetrying: (id: string) => boolean,+ * discard: (id: string) => void,+ * }} `fail` adds a row (or, given the `id` of an existing row, refreshes its+ * error and clears `retrying`) and returns the row id. `markRetrying` returns+ * false when that row is already retrying, so a double click sends once.+ */+export function useFailedCaptures() {+ const [failures, setFailures] = useState([]);+ const counter = useRef(0);+ const retryingRef = useRef(new Set());++ const fail = useCallback((payload, error, id) => {+ const rowId = id ?? `failed-capture-${++counter.current}`;+ retryingRef.current.delete(rowId);+ setFailures((prev) => (prev.some((f) => f.id === rowId)+ ? prev.map((f) => (f.id === rowId ? { ...f, error, retrying: false } : f))+ : [{ id: rowId, payload, error, retrying: false }, ...prev]));+ return rowId;+ }, []);++ const markRetrying = useCallback((id) => {+ if (retryingRef.current.has(id)) return false;+ retryingRef.current.add(id);+ setFailures((prev) => prev.map((f) => (f.id === id ? { ...f, retrying: true } : f)));+ return true;+ }, []);++ const discard = useCallback((id) => {+ retryingRef.current.delete(id);+ setFailures((prev) => prev.filter((f) => f.id !== id));+ }, []);++ return { failures, fail, markRetrying, discard };+}++export default useFailedCaptures;diff --git a/client/src/hooks/useYoutubeIngest.js b/client/src/hooks/useYoutubeIngest.jsindex ec5f09d34e..89dfb9624c 100644--- a/client/src/hooks/useYoutubeIngest.js+++ b/client/src/hooks/useYoutubeIngest.js@@ -11,11 +11,14 @@ import useSseJobSlot from './useSseJobSlot.js';* downloadVideo, ingestAudio, note, agentPrompt, tags }`) rather than a bare URL, so* `trimStartArg` stays false and the payload passes through untouched.*+ * `onKickoffError(err, body)` / `onKickoffSuccess(jobId, body)` hand the host the+ * rejected (or acknowledged) payload so it can keep a failed one recoverable.+ ** Non-fatal outcomes (no captions, a duplicate review task) ride along on the* terminal `complete` frame as `warnings[]` — the hook only ever sees the* terminal payload, so a live-only warning frame would be lost.*/-export default function useYoutubeIngest({ onComplete } = {}) {+export default function useYoutubeIngest({ onComplete, onKickoffError, onKickoffSuccess } = {}) {const { active, percent, stage, start, cancel } = useSseJobSlot({startRequest: (body) => startYoutubeIngest(body, { silent: true }),eventsUrl: youtubeIngestEventsUrl,@@ -33,6 +36,8 @@ export default function useYoutubeIngest({ onComplete } = {}) {canceledMessage: 'YouTube ingest cancelled',lostConnectionMessage: 'Lost connection to the ingest — check Brain → Links',startErrorFallback: 'Failed to start the ingest',+ onKickoffError,+ onKickoffSuccess,});return { active, percent, stage, start, cancel };}