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: report completed backup outcomes consistently (#6665)
[._.]/ Adam Eivyfeabe0351764
diff --git a/client/src/components/BackupWidget.jsx b/client/src/components/BackupWidget.jsxindex e1447c5f67..095cea943c 100644--- a/client/src/components/BackupWidget.jsx+++ b/client/src/components/BackupWidget.jsx@@ -14,6 +14,7 @@ import {HardDrive,import BrailleSpinner from './BrailleSpinner';import toast from './ui/Toast';import * as api from '../services/api';+import { useBackupRun } from '../hooks/useBackupRun';import { useAutoRefetch } from '../hooks/useAutoRefetch';import { useTimeTick } from '../hooks/useTimeTick';import { equalByKeys, equalListByKeys } from '../lib/compareHelpers';@@ -293,7 +294,7 @@ const BackupWidget = memo(function BackupWidget() {]),},);- const [triggering, setTriggering] = useState(false);+ const [handleBackupNow, triggering] = useBackupRun();const [snapshotsOpen, setSnapshotsOpen] = useState(false);// Tick every minute so the dedup-skipped widget still recomputes// `relativeTime(lastRun/nextRun)` labels and the `computeHealth` 25h/49h@@ -304,18 +305,6 @@ const BackupWidget = memo(function BackupWidget() {const health = computeHealth(status);const { dot, text, icon: HealthIcon } = HEALTH_STYLES[health];- const handleBackupNow = useCallback(async () => {- setTriggering(true);- await api.triggerBackup({ silent: true }).catch(err => {- toast.error(`Backup failed: ${err.message}`);- }).then(result => {- if (result) {- toast.success('Backup started', { icon: '💾' });- }- });- setTriggering(false);- }, []);-const isRunning = status?.status === 'running';const isNever = status?.status === 'never';diff --git a/client/src/components/BackupWidget.test.jsx b/client/src/components/BackupWidget.test.jsxindex 2d635cabb0..cb1bb8eba2 100644--- a/client/src/components/BackupWidget.test.jsx+++ b/client/src/components/BackupWidget.test.jsx@@ -1,5 +1,5 @@import { MemoryRouter } from 'react-router';-import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';const {@@ -95,3 +95,52 @@ describe('BackupWidget snapshots', () => {await waitFor(() => expect(mockToast.error).toHaveBeenCalledWith('Download failed: Connection lost'));});});++describe('BackupWidget manual backup', () => {+ it('announces an already-running backup without success feedback', async () => {+ mockTriggerBackup.mockResolvedValue({ skipped: true });+ renderWidget();+ fireEvent.click(await screen.findByRole('button', { name: 'Backup Now' }));++ await waitFor(() => expect(mockToast).toHaveBeenCalledWith('Backup already running'));+ expect(mockToast.success).not.toHaveBeenCalled();+ expect(mockToast.error).not.toHaveBeenCalled();+ expect(screen.getByRole('button', { name: 'Backup Now' })).toBeEnabled();+ });++ it('reports the completed file count for a healthy backup', async () => {+ mockTriggerBackup.mockResolvedValue({ status: 'ok', filesChanged: 3, pgBackup: { status: 'ok' } });+ renderWidget();+ fireEvent.click(await screen.findByRole('button', { name: 'Backup Now' }));++ await waitFor(() => expect(mockToast.success).toHaveBeenCalledWith('Backup complete — 3 files changed', { icon: '💾' }));+ expect(mockToast.success).toHaveBeenCalledTimes(1);+ expect(mockTriggerBackup).toHaveBeenCalledWith({ silent: true });+ expect(mockToast.error).not.toHaveBeenCalled();+ });++ it('qualifies file completion when the database dump failed', async () => {+ mockTriggerBackup.mockResolvedValue({ status: 'degraded', filesChanged: 3, pgBackup: { status: 'failed' } });+ renderWidget();+ fireEvent.click(await screen.findByRole('button', { name: 'Backup Now' }));++ await waitFor(() => expect(mockToast).toHaveBeenCalledWith('Backup complete — 3 files changed; database dump failed', { icon: '⚠️' }));+ expect(mockToast.success).not.toHaveBeenCalled();+ expect(mockToast.error).not.toHaveBeenCalled();+ });++ it('disables the pending action and clears it with one error on rejection', async () => {+ let rejectRun;+ mockTriggerBackup.mockReturnValue(new Promise((_, reject) => { rejectRun = reject; }));+ renderWidget();+ fireEvent.click(await screen.findByRole('button', { name: 'Backup Now' }));+ expect(screen.getByRole('button', { name: /Backup Now/ })).toBeDisabled();++ await act(async () => { rejectRun(new Error('Connection lost')); });++ expect(mockTriggerBackup).toHaveBeenCalledWith({ silent: true });+ expect(mockToast.error).toHaveBeenCalledExactlyOnceWith('Connection lost');+ expect(mockToast.success).not.toHaveBeenCalled();+ expect(screen.getByRole('button', { name: 'Backup Now' })).toBeEnabled();+ });+});diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsxindex a049f6a290..5a50bff3fc 100644--- a/client/src/components/settings/BackupTab.jsx+++ b/client/src/components/settings/BackupTab.jsx@@ -4,9 +4,9 @@ import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';import ToggleSwitch from '../ToggleSwitch';import FolderPicker from '../FolderPicker';-import useAsyncAction from '../../hooks/useAsyncAction';+import { useBackupRun } from '../../hooks/useBackupRun';import Modal from '../ui/Modal';-import { getSettings, updateSettings, getBackupStatus, triggerBackup, getBackupSnapshots, restoreDatabase } from '../../services/api';+import { getSettings, updateSettings, getBackupStatus, getBackupSnapshots, restoreDatabase } from '../../services/api';import { formatBytes } from '../../utils/formatters';import CronSchedulePicker from '../CronSchedulePicker';@@ -120,27 +120,11 @@ export function BackupTab() {: [...prev, path]);};- const [handleRunNow, running] = useAsyncAction(async () => {- const result = await triggerBackup({ silent: true });- if (result?.skipped) {- toast('Backup already running');- } else {- setPgBackup(result?.pgBackup ?? null);- setBackupStatus(result?.status ?? 'ok');- const filesChanged = result?.filesChanged ?? 0;- if (result?.pgBackup?.status === 'failed') {- // Degraded run: the file backup succeeded but the DB dump didn't. Don't- // dress it up as a success — and don't double-announce the DB failure,- // which the BACKUP_DB_DUMP_FAILED socket error toast already surfaces- // (useErrorNotifications). This toast just acknowledges the file portion.- toast(`Backup complete — ${filesChanged} files changed; database dump failed`, { icon: '⚠️' });- } else {- toast.success(`Backup complete — ${filesChanged} files changed`, { icon: '💾' });- }- getBackupSnapshots({ silent: true }).then(s => setSnapshots(Array.isArray(s) ? s : [])).catch((err) => { console.warn(`⚠️ Failed to refresh snapshots: ${err?.message || err}`); });- }- return result;- }, { errorMessage: 'Backup failed' });+ const [handleRunNow, running] = useBackupRun((result) => {+ setPgBackup(result?.pgBackup ?? null);+ setBackupStatus(result?.status ?? 'ok');+ getBackupSnapshots({ silent: true }).then(s => setSnapshots(Array.isArray(s) ? s : [])).catch((err) => { console.warn(`⚠️ Failed to refresh snapshots: ${err?.message || err}`); });+ });const addExclude = () => {const trimmed = newExclude.trim();diff --git a/client/src/components/settings/BackupTab.test.jsx b/client/src/components/settings/BackupTab.test.jsxindex a89b7d2571..1f2dbbc928 100644--- a/client/src/components/settings/BackupTab.test.jsx+++ b/client/src/components/settings/BackupTab.test.jsx@@ -484,12 +484,53 @@ describe('BackupTab', () => {expect(toast).not.toHaveBeenCalledWith('Backup already running');expect(toast.success).toHaveBeenCalledWith('Backup complete — 3 files changed', { icon: '💾' });+ expect(screen.getByText(/7 tables/i)).toBeInTheDocument();// A real run refetches AND applies the result — the new snapshot renders.expect(getBackupSnapshots).toHaveBeenCalledTimes(2);await waitFor(() => expect(screen.getByText('snap-fresh')).toBeTruthy());});});+ describe('manual backup failures', () => {+ it('updates the rendered degraded status and snapshots without an extra error toast', async () => {+ getBackupSnapshots.mockResolvedValueOnce([]).mockResolvedValueOnce([{ id: 'snap-degraded' }]);+ triggerBackup.mockResolvedValue({+ status: 'degraded', filesChanged: 3, pgBackup: { status: 'failed', reason: 'version_mismatch' },+ });+ await renderTab();+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: /Run Backup Now/i }));+ });++ expect(toast).toHaveBeenCalledWith('Backup complete — 3 files changed; database dump failed', { icon: '⚠️' });+ expect(toast.success).not.toHaveBeenCalled();+ expect(toast.error).not.toHaveBeenCalled();+ expect(screen.getByText(/Last backup degraded/i)).toBeInTheDocument();+ expect(screen.getByText(/Dump failed: version_mismatch/i)).toBeInTheDocument();+ expect(await screen.findByText('snap-degraded')).toBeInTheDocument();+ });++ it('clears pending state with one error and preserves prior status on rejection', async () => {+ getBackupStatus.mockResolvedValue({ status: 'ok', defaultExcludes: [], pgBackup: { status: 'ok', sizeBytes: 1024, tableCount: 7 } });+ getBackupSnapshots.mockResolvedValue([{ id: 'snap-existing' }]);+ let rejectRun;+ triggerBackup.mockReturnValue(new Promise((_, reject) => { rejectRun = reject; }));+ await renderTab();+ fireEvent.click(screen.getByRole('button', { name: /Run Backup Now/i }));+ expect(screen.getByRole('button', { name: /Running…/i })).toBeDisabled();++ await act(async () => { rejectRun(new Error('Connection lost')); });++ expect(triggerBackup).toHaveBeenCalledWith({ silent: true });+ expect(toast.error).toHaveBeenCalledExactlyOnceWith('Connection lost');+ expect(toast.success).not.toHaveBeenCalled();+ expect(screen.getByRole('button', { name: /Run Backup Now/i })).toBeEnabled();+ expect(screen.getByText(/7 tables/i)).toBeInTheDocument();+ expect(screen.getByText('snap-existing')).toBeInTheDocument();+ expect(getBackupSnapshots).toHaveBeenCalledTimes(1);+ });+ });+describe('pgBackup conditional rendering', () => {it('shows "No backup run yet" when pgBackup is null', async () => {getBackupStatus.mockResolvedValue({ status: 'never', defaultExcludes: [], pgBackup: null });diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 98fe07fcfd..c9481d3192 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -133,6 +133,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useUrlParams` | `[searchParams, updateParams]` — `updateParams(patch, { replace })` merges a patch into the query string and deletes keys set to `null`/`undefined`/`''` so a cleared filter leaves the URL clean. Reads the live params off a ref (react-router's functional updater is closure-stale) and is referentially stable. | Any page whose filter/sort/selection state lives in the URL (Catalog, MediaCollections, Media3D) — don't re-roll the merge-and-prune loop. || `useValidTab` | Resolve the active tab from the `:tab` URL param against a TABS list, falling back to a default on invalid/missing. | Any tabbed page whose tab lives in the URL — don't re-roll the `new Set(TABS.map(...))` guard. || `useAsyncAction` | `running` state + toast-on-error. | Buttons that await an async action. |+| `useBackupRun` | Manual backup pending state, result feedback, and completion callback. | Dashboard and Settings backup actions. || `useAutoscroll` | rAF autoscroll for a scrollable container: advances `scrollTop` by `pxPerSec`, auto-stops at the bottom, pauses on user wheel/touchmove, live speed changes via ref. `fitToDuration(sec)` solves the speed for a target run time from the measured scroll travel (returns the applied px/s, or `null` when there is nothing to scroll). Returns `{ playing, toggle, stop, pxPerSec, setPxPerSec, fitToDuration }`. | SongBook play view; any teleprompter-style surface. || `useAudioSessionClaim` | `useAudioSessionClaim(type)` → `{ claim, release }` — one arbitrated `acquireAudioSession(type)` slot with a React lifecycle: `claim()` drops this instance's previous claim before taking a fresh one, `release()` is idempotent, and unmount releases whatever is still held. | A surface owning its OWN `AudioContext` (MorseTrainer, the Security monitor) or `getUserMedia` stream (`useSingToScore`/`useSingToVerify`) needs the iOS session. An output-only player on the shared transport passes `audioSession: 'playback'` to `createLookaheadTransport` instead — don't hand-roll either. || `useAsyncCaptureGuard` | Shared pending-request and generation guard for microphone permission prompts; returns `{ tryStart, settleStart, isCurrent, cancel }` and delegates resource teardown plus caller-owned idle reset. | Any capture hook that must reject concurrent `getUserMedia` starts and dispose a stream resolved after cancellation. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 0dd1150ebf..fe2489e9b6 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -103,6 +103,7 @@ export { default as useTokenPopover } from './useTokenPopover.js';// === Mixed (both default and named) — surface both ===export { default as useAsyncAction } from './useAsyncAction.js';export * from './useAsyncAction.js';+export * from './useBackupRun.js';// === Notifications & toasts ===export * from './useAIStatusNotifications.js';diff --git a/client/src/hooks/useBackupRun.js b/client/src/hooks/useBackupRun.jsnew file mode 100644index 0000000000..e6087649a4--- /dev/null+++ b/client/src/hooks/useBackupRun.js@@ -0,0 +1,25 @@+import { useAsyncAction } from './useAsyncAction';+import { triggerBackup } from '../services/api';+import toast from '../components/ui/Toast';++// Both manual entry points report the completed run returned by the server.+// Completion callbacks update caller-owned state only when the run wasn't skipped.+export function useBackupRun(onComplete) {+ return useAsyncAction(async () => {+ const result = await triggerBackup({ silent: true });+ if (result?.skipped) {+ toast('Backup already running');+ } else {+ const filesChanged = result?.filesChanged ?? 0;+ if (result?.pgBackup?.status === 'failed') {+ // The socket error toast already announces the dump failure; acknowledge+ // the file portion without an extra error toast or unqualified success.+ toast(`Backup complete — ${filesChanged} files changed; database dump failed`, { icon: '⚠️' });+ } else {+ toast.success(`Backup complete — ${filesChanged} files changed`, { icon: '💾' });+ }+ await onComplete?.(result);+ }+ return result;+ }, { errorMessage: 'Backup failed' });+}