Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add retention and deletion for database backup snapshots (#8334)

[._.]/ Adam Eivy9bf40c56b590
diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsx
index f966df5c4e..1880c68ac4 100644
--- a/client/src/components/settings/BackupTab.jsx
+++ b/client/src/components/settings/BackupTab.jsx
@@ -1,5 +1,5 @@
import { useState, useEffect, useId, useRef } from 'react';
-import { AlertTriangle, Archive, CalendarClock, CheckCircle2, Database, Play, Plus, Save, ShieldOff, X, ChevronDown, ChevronRight } from 'lucide-react';
+import { AlertTriangle, Archive, CalendarClock, CheckCircle2, Database, Play, Plus, Save, ShieldOff, Trash2, X, ChevronDown, ChevronRight } from 'lucide-react';
import toast from '../ui/Toast';
import BrailleSpinner from '../BrailleSpinner';
import ToggleSwitch from '../ToggleSwitch';
@@ -8,12 +8,20 @@ import { useBackupRun } from '../../hooks/useBackupRun';
import Modal from '../ui/Modal';
import Banner from '../ui/Banner';
import CollapsibleSection from '../ui/CollapsibleSection';
-import { getSettings, updateSettings, getBackupStatus, getBackupSnapshots, restoreDatabase } from '../../services/api';
+import CollapsibleListItem from '../ui/CollapsibleListItem';
+import { getSettings, updateSettings, getBackupStatus, getBackupSnapshots, restoreDatabase, deleteBackupSnapshot } from '../../services/api';
import { formatBytes } from '../../utils/formatters';
import { describeCron } from '../../utils/cronHelpers';
import CronSchedulePicker from '../CronSchedulePicker';
import { anchorUserExclude, anchorUserExcludes, isSafeExcludePattern } from '../../lib/backupExcludes';
+// Mirrors MIN_RETENTION_COUNT/MAX_RETENTION_COUNT in server/lib/backupConfig.js —
+// the server is the source of truth and re-validates on save; these only bound
+// the input control.
+const MIN_RETENTION_COUNT = 1;
+const MAX_RETENTION_COUNT = 365;
+const DEFAULT_RETENTION_COUNT = 30;
+
// Set equality — rsync --exclude flags are order-independent, so reordering
// is NOT a dirty state; only membership changes (added/removed entries) are.
const sameSet = (a, b) => a.length === b.length && a.every(x => b.includes(x));
@@ -36,6 +44,7 @@ const snapshotSourceLabel = (snapshot) =>
export function BackupTab() {
const destPathId = useId();
+ const retentionId = useId();
const additionalExcludeId = useId();
const defaultExcludesPanelId = useId();
const effectiveExcludesPanelId = useId();
@@ -60,6 +69,9 @@ export function BackupTab() {
const [savedEnabled, setSavedEnabled] = useState(null);
const [cronExpression, setCronExpression] = useState(null);
const [savedCronExpression, setSavedCronExpression] = useState(null);
+ // `null` = unlimited. Undefined only before the initial load resolves.
+ const [retentionCount, setRetentionCount] = useState(undefined);
+ const [savedRetentionCount, setSavedRetentionCount] = useState(undefined);
const [excludePaths, setExcludePaths] = useState([]);
const [savedExcludePaths, setSavedExcludePaths] = useState([]);
const [disabledDefaultExcludes, setDisabledDefaultExcludes] = useState([]);
@@ -75,6 +87,9 @@ export function BackupTab() {
const [restoreTarget, setRestoreTarget] = useState(null); // source-bound request pending confirm
const [restorePreview, setRestorePreview] = useState(null); // dry-run result
const restorePreviewGenerationRef = useRef(0);
+ const [deleteTarget, setDeleteTarget] = useState(null); // snapshot pending delete confirm
+ const [deletingIds, setDeletingIds] = useState(new Set());
+ const pendingDeletes = useRef(new Set());
// The default-exclusions catalog is a 15+ row reference list the user rarely
// edits — collapsed by default so the fields they came to change (destination,
// enabled, schedule) and the action bar are what the tab actually shows.
@@ -113,12 +128,21 @@ export function BackupTab() {
|| !backup.cronExpression.trim()) {
throw new Error('Settings response did not include a resolved backup schedule');
}
+ // retentionCount is resolved server-side too (null = unlimited), so
+ // an absent KEY (not merely a null/number value) means the same
+ // unresolved-response case as enabled/cronExpression above.
+ if (!('retentionCount' in backup)) {
+ throw new Error('Settings response did not include a resolved backup schedule');
+ }
const savedEnabledValue = backup.enabled;
const savedCron = backup.cronExpression;
+ const savedRetention = backup.retentionCount;
setEnabled(savedEnabledValue);
setSavedEnabled(savedEnabledValue);
setCronExpression(savedCron);
setSavedCronExpression(savedCron);
+ setRetentionCount(savedRetention);
+ setSavedRetentionCount(savedRetention);
setExcludePaths(savedExcludes);
setSavedExcludePaths(savedExcludes);
setDisabledDefaultExcludes(savedDisabled);
@@ -138,10 +162,11 @@ export function BackupTab() {
const handleSave = async () => {
setSaving(true);
try {
- await updateSettings({ backup: { destPath, enabled, cronExpression, excludePaths, disabledDefaultExcludes } }, { silent: true });
+ await updateSettings({ backup: { destPath, enabled, cronExpression, retentionCount, excludePaths, disabledDefaultExcludes } }, { silent: true });
setSavedDestPath(destPath);
setSavedEnabled(enabled);
setSavedCronExpression(cronExpression);
+ setSavedRetentionCount(retentionCount);
setSavedExcludePaths(excludePaths);
setSavedDisabledDefaultExcludes(disabledDefaultExcludes);
toast.success('Settings saved');
@@ -208,6 +233,7 @@ export function BackupTab() {
const dirty = destPath !== savedDestPath
|| enabled !== savedEnabled
|| cronExpression !== savedCronExpression
+ || retentionCount !== savedRetentionCount
|| !sameSet(excludePaths, savedExcludePaths)
|| !sameSet(disabledDefaultExcludes, savedDisabledDefaultExcludes);
const canRun = !!savedDestPath && !running && !saving && !dirty;
@@ -316,6 +342,31 @@ export function BackupTab() {
setRestorePreview(null);
};
+ const handleDeleteSnapshot = (snapshot) => {
+ setDeleteTarget({
+ identity: snapshotIdentity(snapshot),
+ snapshotId: snapshot.id,
+ source: snapshot.source,
+ sourceLabel: snapshotSourceLabel(snapshot),
+ });
+ };
+
+ const confirmDeleteSnapshot = async () => {
+ const target = deleteTarget;
+ setDeleteTarget(null);
+ if (!target || pendingDeletes.current.has(target.identity)) return;
+ pendingDeletes.current.add(target.identity);
+ const result = await deleteBackupSnapshot(target.snapshotId, target.source, { silent: true })
+ .catch(err => ({ deleted: false, error: err }));
+ pendingDeletes.current.delete(target.identity);
+ if (!result?.deleted) {
+ toast.error(result?.error?.message || 'Failed to delete snapshot');
+ return;
+ }
+ toast.success(`Deleted snapshot ${target.snapshotId}`);
+ setDeletingIds(previous => new Set(previous).add(target.identity));
+ };
+
return (
<section
aria-labelledby="backup-settings-heading"
@@ -403,6 +454,39 @@ export function BackupTab() {
<CronSchedulePicker value={cronExpression} onChange={setCronExpression} cronAriaLabel="Schedule (cron)" />
<p className="text-xs text-gray-500">Default: 2:00 AM daily. Times use the configured timezone.</p>
</div>
+ <div className="space-y-1">
+ <label htmlFor={retentionId} className="block text-sm text-gray-400">Retention (snapshots kept on this machine)</label>
+ <div className="flex flex-wrap items-center gap-3">
+ <input
+ id={retentionId}
+ type="number"
+ min={MIN_RETENTION_COUNT}
+ max={MAX_RETENTION_COUNT}
+ step={1}
+ disabled={retentionCount === null}
+ value={retentionCount === null ? '' : (retentionCount ?? '')}
+ onChange={e => {
+ const parsed = Number.parseInt(e.target.value, 10);
+ // Ignore an unparseable/blank in-progress edit rather than committing
+ // `undefined` — that would drop the key from the save payload
+ // (JSON.stringify omits it) and silently leave the prior value.
+ if (Number.isNaN(parsed)) return;
+ setRetentionCount(Math.min(MAX_RETENTION_COUNT, Math.max(MIN_RETENTION_COUNT, parsed)));
+ }}
+ className="w-24 bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
+ />
+ <span className="inline-flex items-center gap-2 text-sm text-gray-400">
+ <ToggleSwitch
+ enabled={retentionCount === null}
+ onChange={() => setRetentionCount(prev => prev === null ? DEFAULT_RETENTION_COUNT : null)}
+ size="sm"
+ ariaLabel="Unlimited retention"
+ />
+ Unlimited
+ </span>
+ </div>
+ <p className="text-xs text-gray-500">After each successful backup, the oldest completed snapshots on this machine beyond this count are deleted. Other machines&apos; snapshots in a shared destination are never affected.</p>
+ </div>
</div>
</div>
</div>
@@ -586,28 +670,56 @@ export function BackupTab() {
) : (
<>
<ul className="space-y-1.5">
- {(showAllSnapshots ? snapshots : snapshots.slice(0, 10)).map((snap) => (
- <li key={snapshotIdentity(snap)} className="flex items-center justify-between gap-2 text-xs bg-port-bg border border-port-border rounded-lg px-2.5 py-1.5">
- <span className="min-w-0">
- <span className="block text-gray-300 truncate">{snap.id}</span>
- <span className="block text-gray-500 truncate">Source: {snapshotSourceLabel(snap)}</span>
- {snap.failed && (
- <span className="block text-port-error">Backup failed — download only</span>
- )}
- {snap.incomplete && (
- <span className="block text-gray-500">Still being written…</span>
- )}
- </span>
- <button
- onClick={() => handleRestoreDb(snap)}
- disabled={snap.failed || snap.incomplete}
- title={snap.failed ? 'Failed backup snapshots can only be downloaded for salvage' : undefined}
- className="shrink-0 px-2 py-2 min-h-[40px] bg-port-border hover:bg-port-border/70 text-white rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
+ {(showAllSnapshots ? snapshots : snapshots.slice(0, 10)).map((snap) => {
+ const identity = snapshotIdentity(snap);
+ return (
+ <CollapsibleListItem
+ key={identity}
+ removing={deletingIds.has(identity)}
+ spacing="0.375rem"
+ onExited={() => {
+ setSnapshots(previous => previous.filter(s => snapshotIdentity(s) !== identity));
+ setDeletingIds(previous => {
+ const next = new Set(previous);
+ next.delete(identity);
+ return next;
+ });
+ }}
>
- Restore DB
- </button>
- </li>
- ))}
+ <li className="flex items-center justify-between gap-2 text-xs bg-port-bg border border-port-border rounded-lg px-2.5 py-1.5">
+ <span className="min-w-0">
+ <span className="block text-gray-300 truncate">{snap.id}</span>
+ <span className="block text-gray-500 truncate">Source: {snapshotSourceLabel(snap)}</span>
+ {snap.failed && (
+ <span className="block text-port-error">Backup failed — download only</span>
+ )}
+ {snap.incomplete && (
+ <span className="block text-gray-500">Still being written…</span>
+ )}
+ </span>
+ <span className="flex shrink-0 items-center gap-1.5">
+ <button
+ onClick={() => handleRestoreDb(snap)}
+ disabled={snap.failed || snap.incomplete}
+ title={snap.failed ? 'Failed backup snapshots can only be downloaded for salvage' : undefined}
+ className="px-2 py-2 min-h-[40px] bg-port-border hover:bg-port-border/70 text-white rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ Restore DB
+ </button>
+ <button
+ onClick={() => handleDeleteSnapshot(snap)}
+ disabled={snap.incomplete}
+ title="Permanently delete this snapshot"
+ aria-label={`Delete snapshot ${snap.id}`}
+ className="p-2 min-h-[40px] min-w-[40px] bg-port-border hover:bg-port-error/80 text-white rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ <Trash2 size={14} />
+ </button>
+ </span>
+ </li>
+ </CollapsibleListItem>
+ );
+ })}
</ul>
{snapshots.length > 10 && (
<button
@@ -646,6 +758,26 @@ export function BackupTab() {
</div>
</Modal>
+ <Modal
+ open={!!deleteTarget}
+ onClose={() => setDeleteTarget(null)}
+ size="sm"
+ usePortal
+ ariaLabel="Delete snapshot"
+ >
+ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-4">
+ <h3 className="text-white text-sm font-medium">Delete snapshot?</h3>
+ <p className="text-sm text-gray-400">
+ This permanently deletes snapshot <code className="text-gray-300">{deleteTarget?.snapshotId}</code>
+ {' '}on <span className="text-gray-300">{deleteTarget?.sourceLabel}</span>, including its files and database dump. This cannot be undone.
+ </p>
+ <div className="flex justify-end gap-2">
+ <button onClick={() => setDeleteTarget(null)} className="px-3 py-2 text-sm text-gray-400 hover:text-white transition-colors">Cancel</button>
+ <button onClick={confirmDeleteSnapshot} className="px-3 py-2 text-sm bg-port-error hover:bg-port-error/80 text-white font-medium rounded-lg transition-colors">Delete</button>
+ </div>
+ </div>
+ </Modal>
+
</section>
);
}
diff --git a/client/src/components/settings/BackupTab.test.jsx b/client/src/components/settings/BackupTab.test.jsx
index 734b0ef176..8840901cf0 100644
--- a/client/src/components/settings/BackupTab.test.jsx
+++ b/client/src/components/settings/BackupTab.test.jsx
@@ -8,6 +8,7 @@ vi.mock('../../services/api', () => ({
triggerBackup: vi.fn(),
getBackupSnapshots: vi.fn(),
restoreDatabase: vi.fn(),
+ deleteBackupSnapshot: vi.fn(),
// FolderPicker imports `* as api` from the same module; it only calls this
// when its picker is opened (never in these tests), but the mock defines it
// so the import doesn't resolve to undefined if the picker ever mounts eagerly.
@@ -33,6 +34,7 @@ import {
triggerBackup,
getBackupSnapshots,
restoreDatabase,
+ deleteBackupSnapshot,
} from '../../services/api';
import toast from '../ui/Toast';
import { BackupTab } from './BackupTab';
@@ -40,7 +42,7 @@ import { BackupTab } from './BackupTab';
beforeEach(() => {
vi.clearAllMocks();
// Sensible defaults — individual tests override as needed.
- getSettings.mockResolvedValue({ backup: { destPath: '/backups', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [] } });
+ getSettings.mockResolvedValue({ backup: { destPath: '/backups', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [], retentionCount: null } });
getBackupStatus.mockResolvedValue({ status: 'never', defaultExcludes: [], pgBackup: null });
getBackupSnapshots.mockResolvedValue([]);
});
@@ -113,6 +115,7 @@ describe('BackupTab', () => {
destPath: '/new/dest',
enabled: false,
cronExpression: '0 2 * * *',
+ retentionCount: null,
excludePaths: [],
disabledDefaultExcludes: [],
},
@@ -132,6 +135,60 @@ describe('BackupTab', () => {
});
});
+ describe('retention control (#8334)', () => {
+ it('saves a numeric retentionCount typed into the field', async () => {
+ getSettings.mockResolvedValue({
+ backup: { destPath: '/backups', enabled: false, cronExpression: '0 2 * * *', retentionCount: 30, excludePaths: [], disabledDefaultExcludes: [] },
+ });
+ updateSettings.mockResolvedValue({});
+ await renderTab({ openExclusions: false, openSnapshots: false });
+
+ const input = screen.getByLabelText(/Retention \(snapshots kept on this machine\)/i);
+ expect(input).not.toBeDisabled();
+ fireEvent.change(input, { target: { value: '14' } });
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /^Save$/i }));
+ });
+
+ expect(updateSettings).toHaveBeenCalledWith(
+ { backup: expect.objectContaining({ retentionCount: 14 }) },
+ { silent: true }
+ );
+ });
+
+ it('toggling Unlimited clears the field and saves retentionCount: null', async () => {
+ getSettings.mockResolvedValue({
+ backup: { destPath: '/backups', enabled: false, cronExpression: '0 2 * * *', retentionCount: 30, excludePaths: [], disabledDefaultExcludes: [] },
+ });
+ updateSettings.mockResolvedValue({});
+ await renderTab({ openExclusions: false, openSnapshots: false });
+
+ const input = screen.getByLabelText(/Retention \(snapshots kept on this machine\)/i);
+ expect(input.value).toBe('30');
+
+ fireEvent.click(screen.getByRole('switch', { name: 'Unlimited retention' }));
+ expect(input).toBeDisabled();
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /^Save$/i }));
+ });
+
+ expect(updateSettings).toHaveBeenCalledWith(
+ { backup: expect.objectContaining({ retentionCount: null }) },
+ { silent: true }
+ );
+ });
+
+ it('refuses to render the form when retentionCount is not projected', async () => {
+ getSettings.mockResolvedValue({
+ backup: { destPath: '/backups', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [] },
+ });
+ render(<BackupTab />);
+ await waitFor(() => expect(screen.getByText(/Failed to load backup settings/i)).toBeTruthy());
+ });
+ });
+
describe('restore-confirm modal gate', () => {
const withSnapshot = () => {
getBackupSnapshots.mockResolvedValue([{ id: 'snap-2026-06-09' }]);
@@ -335,11 +392,62 @@ describe('BackupTab', () => {
});
});
+ describe('snapshot deletion (#8334)', () => {
+ it('does not delete until the confirmation modal is confirmed', async () => {
+ getBackupSnapshots.mockResolvedValue([{ id: 'snap-2026-06-09' }]);
+ await renderTab();
+
+ fireEvent.click(await screen.findByRole('button', { name: /Delete snapshot snap-2026-06-09/i }));
+ expect(screen.getByText(/Delete snapshot\?/i)).toBeInTheDocument();
+ expect(deleteBackupSnapshot).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole('button', { name: /^Cancel$/i }));
+ await waitFor(() => expect(screen.queryByText(/Delete snapshot\?/i)).toBeNull());
+ expect(deleteBackupSnapshot).not.toHaveBeenCalled();
+ });
+
+ it('deletes the exact source/ID pair and removes the row on confirm', async () => {
+ getBackupSnapshots.mockResolvedValue([{ id: 'snap-2026-06-09', source: 'previous-machine', selectionKey: 'previous-machine/snap-2026-06-09' }]);
+ deleteBackupSnapshot.mockResolvedValue({ deleted: true, snapshotId: 'snap-2026-06-09', source: 'previous-machine' });
+ await renderTab();
+
+ fireEvent.click(await screen.findByRole('button', { name: /Delete snapshot snap-2026-06-09/i }));
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /^Delete$/i }));
+ });
+
+ expect(deleteBackupSnapshot).toHaveBeenCalledWith('snap-2026-06-09', 'previous-machine', { silent: true });
+ expect(toast.success).toHaveBeenCalledWith('Deleted snapshot snap-2026-06-09');
+ await waitFor(() => expect(screen.queryByText('snap-2026-06-09')).not.toBeInTheDocument());
+ });
+
+ it('toasts an error and keeps the row when deletion fails', async () => {
+ getBackupSnapshots.mockResolvedValue([{ id: 'snap-2026-06-09' }]);
+ deleteBackupSnapshot.mockResolvedValue({ deleted: false });
+ await renderTab();
+
+ fireEvent.click(await screen.findByRole('button', { name: /Delete snapshot snap-2026-06-09/i }));
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /^Delete$/i }));
+ });
+
+ expect(toast.error).toHaveBeenCalledWith('Failed to delete snapshot');
+ expect(screen.getByText('snap-2026-06-09')).toBeInTheDocument();
+ });
+
+ it('disables delete for a snapshot still being written', async () => {
+ getBackupSnapshots.mockResolvedValue([{ id: 'snap-incomplete', incomplete: true }]);
+ await renderTab();
+
+ expect(await screen.findByRole('button', { name: /Delete snapshot snap-incomplete/i })).toBeDisabled();
+ });
+ });
+
describe('Run Now gating (saved state)', () => {
// The AGENTS.md invariant: "Run Now must gate on saved state, not the form
// input." `canRun` keys off `savedDestPath` + `dirty`, never the live input.
it('disables Run Backup Now when no destination is saved', async () => {
- getSettings.mockResolvedValue({ backup: { destPath: '', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [] } });
+ getSettings.mockResolvedValue({ backup: { destPath: '', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [], retentionCount: null } });
await renderTab();
const runBtn = screen.getByRole('button', { name: /Run Backup Now/i });
@@ -350,7 +458,7 @@ describe('BackupTab', () => {
});
it('disables Run Backup Now while the destination is edited-but-unsaved (dirty)', async () => {
- getSettings.mockResolvedValue({ backup: { destPath: '/backups', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [] } });
+ getSettings.mockResolvedValue({ backup: { destPath: '/backups', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [], retentionCount: null } });
await renderTab();
// Enabled at rest with a saved destination.
@@ -368,7 +476,7 @@ describe('BackupTab', () => {
});
it('re-enables Run Backup Now once the edited destination is saved', async () => {
- getSettings.mockResolvedValue({ backup: { destPath: '/backups', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [] } });
+ getSettings.mockResolvedValue({ backup: { destPath: '/backups', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [], retentionCount: null } });
updateSettings.mockResolvedValue({});
await renderTab();
@@ -387,7 +495,7 @@ describe('BackupTab', () => {
});
it('disables Run Backup Now while a save is in flight (not just when dirty)', async () => {
- getSettings.mockResolvedValue({ backup: { destPath: '/backups', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [] } });
+ getSettings.mockResolvedValue({ backup: { destPath: '/backups', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [], retentionCount: null } });
// Hold the save pending so we can observe the in-flight window. The
// invariant is "disable while dirty *or* a save is in flight" — the
// pending save (not dirtiness) is what must keep the action locked here.
@@ -416,7 +524,7 @@ describe('BackupTab', () => {
});
it('explains that a first destination save is in flight', async () => {
- getSettings.mockResolvedValue({ backup: { destPath: '', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [] } });
+ getSettings.mockResolvedValue({ backup: { destPath: '', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [], retentionCount: null } });
let resolveSave;
updateSettings.mockReturnValue(new Promise((resolve) => { resolveSave = resolve; }));
await renderTab();
@@ -555,7 +663,7 @@ describe('BackupTab', () => {
it('preserves independent custom rules through default toggles, save, and reload', async () => {
const loraPath = '/loras/*.safetensors';
const custom = ['*.safetensors', '/lo*/', 'loras/'];
- const backup = { destPath: '/backups', enabled: false, cronExpression: '0 2 * * *', excludePaths: custom, disabledDefaultExcludes: [loraPath, '/cache'] };
+ const backup = { destPath: '/backups', enabled: false, cronExpression: '0 2 * * *', retentionCount: null, excludePaths: custom, disabledDefaultExcludes: [loraPath, '/cache'] };
getSettings.mockResolvedValue({ backup });
getBackupStatus.mockResolvedValue({ defaultExcludes: [EXCLUDES[0], { path: loraPath, reason: 'LoRA weights', overridable: true }] });
updateSettings.mockImplementation(async payload => { getSettings.mockResolvedValue(payload); return {}; });
@@ -615,7 +723,7 @@ describe('BackupTab', () => {
});
it('keeps the configure-first reason during an empty no-op save', async () => {
- getSettings.mockResolvedValue({ backup: { destPath: '', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [] } });
+ getSettings.mockResolvedValue({ backup: { destPath: '', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [], retentionCount: null } });
let resolveSave;
updateSettings.mockReturnValue(new Promise((resolve) => { resolveSave = resolve; }));
await renderTab();
@@ -629,7 +737,7 @@ describe('BackupTab', () => {
});
it('toasts "Backup already running" and leaves rendered status/snapshots untouched when skipped', async () => {
- getSettings.mockResolvedValue({ backup: { destPath: '/backups', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [] } });
+ getSettings.mockResolvedValue({ backup: { destPath: '/backups', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [], retentionCount: null } });
// Seed real prior state so the test catches a regression that mutates the
// VISIBLE status/snapshots (not just one that triggers a refetch): a healthy
// last-dump line and one existing snapshot must both survive the skip.
@@ -660,7 +768,7 @@ describe('BackupTab', () => {
});
it('refreshes snapshots and toasts success on a non-skipped run', async () => {
- getSettings.mockResolvedValue({ backup: { destPath: '/backups', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [] } });
+ getSettings.mockResolvedValue({ backup: { destPath: '/backups', enabled: false, cronExpression: '0 2 * * *', excludePaths: [], disabledDefaultExcludes: [], retentionCount: null } });
// Empty on mount, a named snapshot on the post-run refetch — so the test
// proves the returned snapshots are actually applied to state and rendered,
// not merely that a second fetch happened.
@@ -758,7 +866,7 @@ describe('BackupTab', () => {
// screen's own defaults over the schedule, cancelling it.
it('preserves the resolved schedule when only an exclusion is edited and saved', async () => {
getSettings.mockResolvedValue({
- backup: { destPath: '/example-backups', enabled: true, cronExpression: '0 0 * * *', excludePaths: [], disabledDefaultExcludes: [] }
+ backup: { destPath: '/example-backups', enabled: true, cronExpression: '0 0 * * *', retentionCount: null, excludePaths: [], disabledDefaultExcludes: [] }
});
updateSettings.mockResolvedValue({});
await renderTab();
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 5f02704380..00d972c31e 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -359,6 +359,10 @@ export async function downloadBackupSnapshot(snapshotId, source) {
return { filename };
}
export const restoreDatabase = (data, options) => request('/backup/restore-db', { method: 'POST', body: JSON.stringify(data), ...options });
+export const deleteBackupSnapshot = (snapshotId, source, options = {}) => {
+ const query = source ? `?source=${encodeURIComponent(source)}` : '';
+ return request(`/backup/snapshots/${encodeURIComponent(snapshotId)}${query}`, { method: 'DELETE', ...options });
+};
// Data Manager
export const getDataOverview = () => request('/data');
diff --git a/data.reference/settings.json b/data.reference/settings.json
index aadbe6fcd9..0cd6fc1b98 100644
--- a/data.reference/settings.json
+++ b/data.reference/settings.json
@@ -51,5 +51,8 @@
"maxQueuedJobs": 2,
"audioModels": []
}
+ },
+ "backup": {
+ "retentionCount": 30
}
}
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index b21ee5d99e..50b16a61ef 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -116,6 +116,16 @@ A non-dry-run restore requires a reachable DB first (`checkHealth()`), so a rest
Separate from snapshot restore: `server/routes/database.js` can copy data **between** the native (port 5432) and Docker (port 5561) Postgres backends. It exports the active backend with `pg_dump`, ensures the target backend has the `portos` role/database/extensions, then imports under `ON_ERROR_STOP=1 --single-transaction`. `POST /api/database/export` produces an on-demand dump under `data/db-dumps/`. These power the Database settings tab's mode-switch/sync flows; they are independent of the rsync snapshot backups above.
+## Retention & deletion
+
+Left unbounded, `snapshots/<hostname>/` grows forever — every prior full DB dump stays reachable, so a record deleted from the live database (including `privacy_vault_records`, `privacy_consents`, and `privacy_broker_cases`) remains restorable from an old snapshot indefinitely. `server/lib/backupConfig.js` resolves a per-source `retentionCount`, and `runBackup()` prunes with it after every successful run (`pruneOldSnapshots()` in `backup.js`).
+
+- **New installs default to 30 completed snapshots per source.** The default ships as `backup.retentionCount: 30` in `data.reference/settings.json`, copied only into an install that has no `data/settings.json` yet — see the comment on `resolveRetentionCount()` for why this, not a migration, is what keeps an existing install from silently losing its archive. Operators choose 1–365, or Unlimited, from the Backup settings tab.
+- **`retentionCount` absent or explicitly `null` both mean unlimited** — no pruning runs. This is why an install that predates this setting keeps every snapshot until the operator saves a choice: it has no stored value, and absence resolves to unlimited, not to the new-install default.
+- **Pruning runs only after a run reaches a completed snapshot** (rsync finished and a `pg_dump` was attempted, even if it degraded) — a run that fails before that point takes `runBackup()`'s `fail()` path and never prunes. A prune failure is logged and does not fail an otherwise-successful backup.
+- **Pruning is scoped to the CURRENT machine's namespace** (`snapshots/<hostname>/`) and only ever deletes snapshots whose `snapshotState()` reports neither `incomplete` nor `failed`. It never touches another machine's namespace in a shared destination, the legacy pre-namespace root, or an in-progress/failed snapshot — those stay until the operator deletes them explicitly.
+- **`DELETE /api/backup/snapshots/:snapshotId?source=<source>`** (`backup.deleteSnapshot()`) permanently removes exactly the selected source/ID pair, immediately — there is no undo and it is never automatic. It shares `resolveSnapshotPath()`'s path-traversal and symlink guards with restore/download, and refuses a snapshot that is still being written (`SNAPSHOT_INCOMPLETE`); unlike restore, a `.failed` snapshot **is** deletable. The Backup settings tab's snapshot history exposes this as a per-row delete action behind a confirmation dialog.
+
## Scheduling & status
- Daily backups are driven by `backupScheduler.js` via the `backup-daily` cron event; `getNextRunTime()` reports the next run.
@@ -131,6 +141,7 @@ The backup settings slice is stored **sparsely** — an install where the user o
| `enabled` absent | **enabled** — an omitted toggle has never meant "off" on the server, and changing that would silently stop nightly backups on existing installs |
| `cronExpression` absent or blank | `0 0 * * *` (midnight, in the user's timezone) |
| `destPath` absent or blank | **nothing is scheduled**, whatever `enabled` says |
+| `retentionCount` absent or `null` | **unlimited** — nothing is pruned. A NEW install ships an explicit `30` in `data/settings.json` (see [Retention & deletion](#retention--deletion)); an existing install's absence is never reinterpreted as that default. |
`GET /api/settings` projects these effective values over the stored slice, so the Backup settings tab renders exactly what the scheduler will do. **The client owns no fallback of its own** — it used to read the same sparse config as "disabled at 02:00" while the scheduler read it as "enabled at midnight", so saving an unrelated preference wrote that misreading back and cancelled a live schedule (#6632). If a settings response ever arrives without a resolved schedule the tab shows a load error instead of a form, rather than saving invented values.
diff --git a/server/lib/README.md b/server/lib/README.md
index 1d5281b3fc..b74f066bf6 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -584,7 +584,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
-| `backupConfig.js` | `resolveBackupConfig(settings.backup)` + `DEFAULT_BACKUP_CRON` — the single declaring module for how a SPARSE backup settings slice resolves (#6632): an omitted `enabled` means enabled, a missing/blank `cronExpression` means midnight (`0 0 * * *`), and `scheduled` additionally requires a `destPath`. Read-time resolution only — nothing on disk changes. Shared by `services/backupScheduler.js` (registration + handler eligibility) and `routes/settings.js` (the GET projects effective values), so the Settings screen can render what the scheduler will actually do instead of inventing its own defaults. |
+| `backupConfig.js` | `resolveBackupConfig(settings.backup)` + `DEFAULT_BACKUP_CRON` — the single declaring module for how a SPARSE backup settings slice resolves (#6632): an omitted `enabled` means enabled, a missing/blank `cronExpression` means midnight (`0 0 * * *`), and `scheduled` additionally requires a `destPath`. Also `resolveRetentionCount(settings.backup)` + `DEFAULT_RETENTION_COUNT`/`MIN_RETENTION_COUNT`/`MAX_RETENTION_COUNT` (#8334): per-source completed-snapshot retention, where an omitted or `null` `retentionCount` means unlimited — a NEW install ships the `30` default on disk via `data.reference/settings.json`, never invented here for an absent value. Read-time resolution only — nothing on disk changes. Shared by `services/backupScheduler.js` (registration + handler eligibility, and the retention count `services/backup.js#runBackup` prunes with) and `routes/settings.js` (the GET projects effective values), so the Settings screen can render what the scheduler will actually do instead of inventing its own defaults. |
| `systemIdle.js` | `summarizeSystemActivity(processingSnapshot)` → `{ idle, activeCount, queuedCount, blockers[] }` + `describeActivityBlockers` — the ONE definition of "is this install doing anything", derived from the `/api/system/processing` snapshot. Queued work counts as active. Rendered by the dashboard's Live activity widget and refused on by the unattended auto-updater, so the two can never disagree about a window in which PortOS may restart itself. Every blocker label is generated prose (a count and a noun); no snapshot content is echoed. |
| `browserConfig.js` | Shared custom browser path helpers for deriving macOS app bundles, detecting configured browser choices, normalizing browser config, and validating Chrome-compatible binary paths. |
| `condaEnv.js` | Resolves a NAMED conda environment's interpreter: `condaEnvPythonCandidates(envName)` builds the ordered candidate list (`CONDA_PREFIX` — walking up two levels when it points at an `envs/<name>` rather than a root — then `CONDA_ROOT`, `~/miniconda3`, `~/anaconda3`, `~/miniforge3`, `~/mambaforge`, `/opt/conda`), and `resolveCondaEnvPython(envName, { exists })` returns the first that exists or `null`. Separate from `pythonSetup.js` (which probes *venv* layouts and computes candidates from `PATHS` at module load) so a conda lookup pulls in no eager path work. Used by the image-to-3D CUDA lanes, which each own a distinct env (`trellis2`, `pixal3d`) so one lane's pinned deps can't disturb the other's. |
diff --git a/server/lib/backupConfig.js b/server/lib/backupConfig.js
index b2f5c15aaf..f82e13c99c 100644
--- a/server/lib/backupConfig.js
+++ b/server/lib/backupConfig.js
@@ -21,17 +21,54 @@
/** Cron expression used when the stored backup settings omit one. */
export const DEFAULT_BACKUP_CRON = '0 0 * * *';
+/**
+ * Per-source completed-snapshot retention bounds and the default a NEW
+ * install ships with. Unlike `enabled`/`cronExpression`, an install that
+ * predates this setting does NOT get this default at read time — see
+ * `resolveRetentionCount` below for why the distinction matters and how it is
+ * made without a migration.
+ */
+export const DEFAULT_RETENTION_COUNT = 30;
+export const MIN_RETENTION_COUNT = 1;
+export const MAX_RETENTION_COUNT = 365;
+
+/**
+ * Resolve the effective per-source snapshot retention count.
+ *
+ * `retentionCount` absent or explicitly `null` both mean UNLIMITED — no
+ * pruning. That single interpretation is what makes "new installs default to
+ * 30, existing installs keep everything until the operator chooses" work
+ * without a migration or an install-age flag: `data.reference/settings.json`
+ * ships `backup.retentionCount: 30` on disk, and `setup-data.js` only copies
+ * that file into an install that has NO `data/settings.json` yet (a brand
+ * new install). Every install that already had a settings file — including
+ * one that has never touched Backup settings — keeps reading `undefined`
+ * here, which resolves to unlimited, exactly matching the acceptance
+ * criterion that an upgrade must never start silently deleting an existing
+ * archive.
+ * @param {object} [backup] - the `settings.backup` slice, or undefined
+ * @returns {number|null} snapshots to keep per source, or `null` for unlimited
+ */
+export function resolveRetentionCount(backup) {
+ const raw = backup?.retentionCount;
+ if (raw === null || raw === undefined) return null;
+ if (!Number.isInteger(raw) || raw < MIN_RETENTION_COUNT || raw > MAX_RETENTION_COUNT) return null;
+ return raw;
+}
+
/**
* Resolve the effective backup schedule from a (possibly sparse) settings slice.
* @param {object} [backup] - the `settings.backup` slice, or undefined
- * @returns {{ destPath: string|null, enabled: boolean, cronExpression: string, scheduled: boolean }}
+ * @returns {{ destPath: string|null, enabled: boolean, cronExpression: string, scheduled: boolean, retentionCount: number|null }}
* `enabled` is the user's intent (an absent value means enabled);
* `scheduled` is whether a cron should actually be registered, which
- * additionally requires a destination.
+ * additionally requires a destination; `retentionCount` is `null` for
+ * unlimited (see `resolveRetentionCount`).
*/
export function resolveBackupConfig(backup) {
const destPath = backup?.destPath || null;
const enabled = backup?.enabled !== false;
const cronExpression = backup?.cronExpression || DEFAULT_BACKUP_CRON;
- return { destPath, enabled, cronExpression, scheduled: enabled && Boolean(destPath) };
+ const retentionCount = resolveRetentionCount(backup);
+ return { destPath, enabled, cronExpression, scheduled: enabled && Boolean(destPath), retentionCount };
}
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 78f1ebc9b3..e8f614df57 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1,5 +1,5 @@
import { CREDENTIALS } from './credentialRegistry.js';
-import { DEFAULT_BACKUP_CRON } from './backupConfig.js';
+import { DEFAULT_BACKUP_CRON, MIN_RETENTION_COUNT, MAX_RETENTION_COUNT } from './backupConfig.js';
import { z } from 'zod';
export const gitDeleteBranchBodySchema = z.object({
@@ -1001,7 +1001,13 @@ export const backupConfigSchema = z.object({
z.string().trim().min(1).max(EXCLUDE_PATTERN_MAX_LENGTH + 1)
.refine(isSafeExcludePattern, { message: `Exclude pattern must be at most ${EXCLUDE_PATTERN_MAX_LENGTH} characters once anchored, and may not contain ".." or a NUL byte` })
).optional().default([]),
- disabledDefaultExcludes: z.array(z.string()).optional().default([])
+ disabledDefaultExcludes: z.array(z.string()).optional().default([]),
+ // Per-source completed-snapshot retention. `null` (and an omitted field, via
+ // `resolveRetentionCount`) both mean unlimited — see backupConfig.js for why
+ // an existing install must never see this default itself. `.nullable()`
+ // rather than `emptyToUndefined`: the UI's explicit "Unlimited" choice IS a
+ // value worth persisting distinctly from "never touched this setting".
+ retentionCount: z.number().int().min(MIN_RETENTION_COUNT).max(MAX_RETENTION_COUNT).nullable().optional()
});
// Automatic PortOS self-update (Update tab). Stored under the top-level
diff --git a/server/routes/backup.js b/server/routes/backup.js
index 376c707eaa..cd657cdc34 100644
--- a/server/routes/backup.js
+++ b/server/routes/backup.js
@@ -9,6 +9,7 @@ import {
} from '../lib/validation.js';
import * as backup from '../services/backup.js';
import { getSettings } from '../services/settings.js';
+import { resolveBackupConfig } from '../lib/backupConfig.js';
const router = Router();
@@ -34,8 +35,9 @@ router.post('/run', asyncHandler(async (req, res) => {
}
const excludePaths = settings.backup?.excludePaths || [];
const disabledDefaultExcludes = settings.backup?.disabledDefaultExcludes || [];
+ const { retentionCount } = resolveBackupConfig(settings.backup);
const io = req.app.get('io');
- const result = await backup.runBackup(destPath, io, { excludePaths, disabledDefaultExcludes });
+ const result = await backup.runBackup(destPath, io, { excludePaths, disabledDefaultExcludes, retentionCount });
res.json(result);
}));
@@ -66,6 +68,19 @@ router.get('/snapshots/:snapshotId/download', asyncHandler(async (req, res) => {
});
}));
+// DELETE /api/backup/snapshots/:snapshotId
+router.delete('/snapshots/:snapshotId', asyncHandler(async (req, res) => {
+ const settings = await getSettings();
+ const destPath = settings.backup?.destPath;
+ if (!destPath) {
+ throw new ServerError('No backup destination configured in settings', { status: 400, code: 'BACKUP_NOT_CONFIGURED' });
+ }
+ const { snapshotId } = req.params;
+ const { source } = validateRequest(snapshotDownloadQuerySchema, req.query);
+ const result = await backup.deleteSnapshot(destPath, snapshotId, { source });
+ res.json(result);
+}));
+
// POST /api/backup/restore
router.post('/restore', asyncHandler(async (req, res) => {
const { snapshotId, source, subdirFilter, dryRun } = validateRequest(restoreRequestSchema, req.body);
diff --git a/server/routes/backup.test.js b/server/routes/backup.test.js
index 9bf1e286d7..641b9f9d6e 100644
--- a/server/routes/backup.test.js
+++ b/server/routes/backup.test.js
@@ -12,6 +12,7 @@ vi.mock('../services/backup.js', () => ({
openSnapshotStream: vi.fn(),
restoreSnapshot: vi.fn(),
restorePostgres: vi.fn(),
+ deleteSnapshot: vi.fn(),
DEFAULT_EXCLUDES: [
{ path: '/browser-profile/', reason: 'test', overridable: false },
{ path: '/loras/*.safetensors', reason: 'test', overridable: true }
@@ -94,7 +95,7 @@ describe('backup routes', () => {
expect(backup.runBackup).toHaveBeenCalledWith(
'/dest',
undefined,
- { excludePaths: ['/node_modules', '.git'], disabledDefaultExcludes: [] }
+ { excludePaths: ['/node_modules', '.git'], disabledDefaultExcludes: [], retentionCount: null }
);
});
@@ -105,7 +106,7 @@ describe('backup routes', () => {
expect(backup.runBackup).toHaveBeenCalledWith(
'/dest',
undefined,
- { excludePaths: [], disabledDefaultExcludes: [] }
+ { excludePaths: [], disabledDefaultExcludes: [], retentionCount: null }
);
});
@@ -118,7 +119,20 @@ describe('backup routes', () => {
expect(backup.runBackup).toHaveBeenCalledWith(
'/dest',
undefined,
- { excludePaths: [], disabledDefaultExcludes: ['/loras/*.safetensors'] }
+ { excludePaths: [], disabledDefaultExcludes: ['/loras/*.safetensors'], retentionCount: null }
+ );
+ });
+
+ it('forwards the resolved retentionCount', async () => {
+ getSettings.mockResolvedValue({
+ backup: { destPath: '/dest', retentionCount: 14 }
+ });
+ backup.runBackup.mockResolvedValue({ success: true });
+ await request(buildApp()).post('/api/backup/run');
+ expect(backup.runBackup).toHaveBeenCalledWith(
+ '/dest',
+ undefined,
+ { excludePaths: [], disabledDefaultExcludes: [], retentionCount: 14 }
);
});
});
@@ -191,6 +205,48 @@ describe('backup routes', () => {
});
});
+ describe('DELETE /api/backup/snapshots/:snapshotId', () => {
+ it('deletes a snapshot on the current machine by default', async () => {
+ getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });
+ backup.deleteSnapshot.mockResolvedValue({ deleted: true, snapshotId: 'snap-1', source: 'this-machine' });
+
+ const res = await request(buildApp()).delete('/api/backup/snapshots/snap-1');
+
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ deleted: true, snapshotId: 'snap-1', source: 'this-machine' });
+ expect(backup.deleteSnapshot).toHaveBeenCalledWith('/dest', 'snap-1', { source: undefined });
+ });
+
+ it('forwards an explicitly selected source', async () => {
+ getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });
+ backup.deleteSnapshot.mockResolvedValue({ deleted: true, snapshotId: 'snap-1', source: 'previous-machine' });
+
+ const res = await request(buildApp())
+ .delete('/api/backup/snapshots/snap-1?source=previous-machine');
+
+ expect(res.status).toBe(200);
+ expect(backup.deleteSnapshot).toHaveBeenCalledWith('/dest', 'snap-1', { source: 'previous-machine' });
+ });
+
+ it('rejects a traversing source before deleting anything', async () => {
+ getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });
+ const res = await request(buildApp())
+ .delete('/api/backup/snapshots/snap-1?source=..%2Fother-machine');
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ expect(backup.deleteSnapshot).not.toHaveBeenCalled();
+ });
+
+ it('returns 400 when the backup destination is not configured', async () => {
+ getSettings.mockResolvedValue({ backup: {} });
+ const res = await request(buildApp()).delete('/api/backup/snapshots/snap-1');
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('BACKUP_NOT_CONFIGURED');
+ expect(backup.deleteSnapshot).not.toHaveBeenCalled();
+ });
+ });
+
describe('POST /api/backup/restore', () => {
it('returns 400 when snapshotId is missing', async () => {
getSettings.mockResolvedValue({ backup: { destPath: '/dest' } });
diff --git a/server/routes/settings.js b/server/routes/settings.js
index 9927fcf732..081f6b0bf5 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -173,7 +173,8 @@ const projectEffectiveBackup = (safe) => {
...safe.backup,
destPath: effective.destPath,
enabled: effective.enabled,
- cronExpression: effective.cronExpression
+ cronExpression: effective.cronExpression,
+ retentionCount: effective.retentionCount
}
};
};
diff --git a/server/routes/settings.test.js b/server/routes/settings.test.js
index 2d8706f11a..badb5f980d 100644
--- a/server/routes/settings.test.js
+++ b/server/routes/settings.test.js
@@ -1319,6 +1319,35 @@ describe('Settings routes — backup schedule resolution (#6632)', () => {
expect(res.body.backup).toMatchObject({ destPath: null, enabled: true, cronExpression: '0 0 * * *' });
});
+ // #8334: an install that predates the retention setting has no stored value —
+ // that must resolve to unlimited (null), never to the new-install default of
+ // 30. A migration/reference-seed is what gives a genuinely new install 30 on
+ // disk; the resolver itself must never invent that default for an absence.
+ it('resolves retentionCount to null (unlimited) when absent', async () => {
+ store = { backup: { destPath: '/example-backups' } };
+ const res = await request(buildApp()).get('/api/settings');
+ expect(res.body.backup.retentionCount).toBeNull();
+ });
+
+ it('preserves an explicitly stored retentionCount', async () => {
+ store = { backup: { destPath: '/example-backups', retentionCount: 14 } };
+ const res = await request(buildApp()).get('/api/settings');
+ expect(res.body.backup.retentionCount).toBe(14);
+ });
+
+ it('rejects an out-of-range retentionCount on save', async () => {
+ const res = await request(buildApp()).put('/api/settings').send({ backup: { retentionCount: 366 } });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ });
+
+ it('accepts an explicit null retentionCount (operator choosing Unlimited) on save', async () => {
+ store = { backup: { destPath: '/example-backups', retentionCount: 30 } };
+ const res = await request(buildApp()).put('/api/settings').send({ backup: { retentionCount: null } });
+ expect(res.status).toBe(200);
+ expect(store.backup.retentionCount).toBeNull();
+ });
+
// Resolution is read-time only: the sparse shape survives on disk, so an older
// peer/client reading settings.json still sees exactly what it wrote.
it('does not persist the resolved values back into the store', async () => {
diff --git a/server/services/backup.js b/server/services/backup.js
index e503b0d052..1a77c30487 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -8,7 +8,7 @@
import { spawn } from '../lib/childProcess.js';
import { killWithEscalation } from '../lib/killWithEscalation.js';
-import { access, lstat, readdir, readFile, stat, unlink, writeFile } from 'fs/promises';
+import { access, lstat, readdir, readFile, rm, stat, unlink, writeFile } from 'fs/promises';
import { PassThrough } from 'node:stream';
import { hostname } from 'os';
import { basename, join, resolve, relative, isAbsolute } from 'path';
@@ -494,7 +494,7 @@ export function computeEffectiveExcludes({ excludePaths, disabledDefaultExcludes
* @param {string} destPath - Path to external drive backup root
* @param {object|null} io - Socket.IO instance for real-time events (optional)
*/
-export async function runBackup(destPath, io = null, { excludePaths = [], disabledDefaultExcludes = [] } = {}) {
+export async function runBackup(destPath, io = null, { excludePaths = [], disabledDefaultExcludes = [], retentionCount = null } = {}) {
if (isRunning) {
console.log('💾 Backup already running — skipping');
return { skipped: true };
@@ -612,7 +612,22 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disabl
}
}
- return complete({ snapshotId, filesChanged: changedFiles.length, status, lastRun, manifest, pgBackup: pgResult });
+ const result = await complete({ snapshotId, filesChanged: changedFiles.length, status, lastRun, manifest, pgBackup: pgResult });
+
+ // Prune only after `complete()` has cleared this snapshot's own
+ // `.in-progress` marker and released `activeSnapshotId` — pruning any
+ // earlier would make the run's OWN fresh snapshot read as incomplete
+ // (via `snapshotState`) and drop out of the retention count entirely,
+ // silently keeping one snapshot MORE than configured. A run that throws
+ // before this point takes the `fail()` path below and never reaches
+ // here, so a failed or in-progress snapshot is never a prune candidate.
+ // Retention failures must not fail an otherwise-successful backup.
+ const pruned = await pruneOldSnapshots(destPath, retentionCount).catch(err => {
+ console.error(`❌ Backup retention prune failed: ${err.message}`);
+ return { pruned: 0 };
+ });
+
+ return { ...result, prunedSnapshots: pruned.pruned };
} catch (err) {
return fail(err);
}
@@ -887,6 +902,59 @@ export async function listSnapshots(destPath) {
});
}
+/**
+ * Delete the oldest COMPLETED snapshots in the CURRENT machine's source
+ * namespace beyond `retentionCount`. Called only from `runBackup()` after a
+ * run reaches a completed snapshot (rsync + a pg_dump attempt, even a
+ * degraded one) — a run that fails earlier never reaches this call, so an
+ * in-progress or `.failed` snapshot is never a candidate; both are re-checked
+ * here anyway via `snapshotState` in case an unrelated run left one behind.
+ * Only ever walks `snapshots/<MACHINE_HOST>/` — never another machine's
+ * namespace and never the legacy pre-namespace root, both of which this
+ * install has no authority to prune.
+ * `retentionCount` of `null`/`undefined` means unlimited: no-op.
+ * @param {string} destPath
+ * @param {number|null} retentionCount
+ * @returns {Promise<{ pruned: number }>}
+ */
+async function pruneOldSnapshots(destPath, retentionCount) {
+ if (retentionCount === null || retentionCount === undefined) return { pruned: 0 };
+
+ const sourceRoot = join(destPath, 'snapshots', MACHINE_HOST);
+ const entries = await readdir(sourceRoot, { withFileTypes: true }).catch(() => []);
+ const candidateIds = entries
+ .filter(entry => entry.isDirectory() && !entry.name.startsWith('.') && SNAPSHOT_ID_PATTERN.test(entry.name))
+ .map(entry => entry.name);
+
+ const descriptors = (await Promise.all(candidateIds.map(async (id) => {
+ const snapshotDir = join(sourceRoot, id);
+ const { incomplete, failed } = await snapshotState(snapshotDir, id, true);
+ if (incomplete || failed) return null;
+ // Read-only listing metadata; matches listSnapshots' own read.
+ const manifest = await readJSONFile(join(snapshotDir, 'manifest.json'), null, { logError: false });
+ return { id, snapshotDir, createdAt: manifest?.generatedAt ?? null };
+ }))).filter(Boolean);
+
+ // Newest-first, same tiebreak as listSnapshots: dated entries by date, then
+ // undated (pre-manifest legacy-in-namespace) entries by id.
+ descriptors.sort((a, b) => {
+ if (a.createdAt && b.createdAt) return b.createdAt.localeCompare(a.createdAt);
+ if (a.createdAt) return -1;
+ if (b.createdAt) return 1;
+ return b.id.localeCompare(a.id);
+ });
+
+ const toDelete = descriptors.slice(retentionCount);
+ for (const { snapshotDir, id } of toDelete) {
+ await rm(snapshotDir, { recursive: true, force: true }).catch(err =>
+ console.error(`❌ Backup retention: failed to remove snapshot ${id}: ${err.message}`));
+ }
+ if (toDelete.length) {
+ console.log(`💾 Backup retention: pruned ${toDelete.length} snapshot(s), keeping ${retentionCount}`);
+ }
+ return { pruned: toDelete.length };
+}
+
function resolveSnapshotPath(destPath, snapshotId, source) {
if (!snapshotId || !SNAPSHOT_ID_PATTERN.test(snapshotId)) {
throw new ServerError(`Invalid snapshotId: ${snapshotId}`, {
@@ -929,6 +997,7 @@ function resolveSnapshotPath(destPath, snapshotId, source) {
snapshotsRoot: sourceRoot,
snapshotsBase: snapshotsRoot,
snapshotDir,
+ resolvedSource,
currentSource: resolvedSource === MACHINE_HOST,
explicitSource: source !== undefined,
};
@@ -957,6 +1026,41 @@ async function assertExplicitSnapshotSourceSafe({
}
}
+/**
+ * Permanently delete one snapshot, identified by its (source, id) pair.
+ * Immediate — there is no undo — so this is reserved for an explicit operator
+ * action, never automatic retention (see `pruneOldSnapshots`, which shares the
+ * traversal/symlink guards through `resolveSnapshotPath` but is driven by
+ * `runBackup()` instead). Refuses a snapshot that is still being written
+ * (`.in-progress`), matching the guard that blocks restore and download,
+ * because the partial directory may still be owned by an in-flight
+ * `runBackup()`. A `.failed` snapshot IS deletable — unlike restore, deletion
+ * has no reason to require a successful backup.
+ * @param {string} destPath - Path to external drive backup root
+ * @param {string} snapshotId - Snapshot ID to delete
+ * @param {{ source?: string }} [options]
+ * @returns {Promise<{ deleted: true, snapshotId: string, source: string }>}
+ */
+export async function deleteSnapshot(destPath, snapshotId, { source } = {}) {
+ const resolved = resolveSnapshotPath(destPath, snapshotId, source);
+ const { snapshotDir, currentSource, resolvedSource } = resolved;
+ await assertExplicitSnapshotSourceSafe(resolved, snapshotId);
+ const info = await stat(snapshotDir).catch(() => null);
+ if (!info?.isDirectory?.()) {
+ throw new ServerError(`Snapshot not found: ${snapshotId}`, { status: 404, code: 'NOT_FOUND' });
+ }
+ const { incomplete } = await snapshotState(snapshotDir, snapshotId, currentSource);
+ if (incomplete) {
+ throw new ServerError(`Snapshot is still being written: ${snapshotId}`, {
+ status: 409,
+ code: 'SNAPSHOT_INCOMPLETE',
+ });
+ }
+ await rm(snapshotDir, { recursive: true, force: true });
+ console.log(`💾 Backup snapshot deleted: ${resolvedSource}/${snapshotId}`);
+ return { deleted: true, snapshotId, source: resolvedSource };
+}
+
/**
* Open a gzip tar stream for one complete snapshot.
* @param {string} destPath - Path to external drive backup root
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 283748ba3c..dfd882b110 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -110,7 +110,7 @@ vi.mock('./brainStorage.js', async (importOriginal) => ({
}));
import { reloadSettings } from './settings.js';
import { invalidateAllCaches as invalidateBrainCaches } from './brainStorage.js';
-import { DEFAULT_EXCLUDES, computeEffectiveExcludes, listSnapshots, openSnapshotStream, restoreSnapshot, resolveRsyncBinary } from './backup.js';
+import { DEFAULT_EXCLUDES, computeEffectiveExcludes, listSnapshots, openSnapshotStream, restoreSnapshot, resolveRsyncBinary, deleteSnapshot } from './backup.js';
import { EXCLUDE_PATTERN_MAX_LENGTH, anchorUserExclude, anchorUserExcludes, isSafeExcludePattern } from '../lib/sharedSchemas.js';
// fs.access is mocked file-wide because backup.js probes the .in-progress marker
@@ -455,6 +455,74 @@ describe('listSnapshots', () => {
});
});
+describe('deleteSnapshot', () => {
+ let destRoot;
+
+ beforeEach(async () => {
+ destRoot = await fs.mkdtemp(joinPath(tmpdir(), 'portos-backup-delete-'));
+ });
+
+ afterEach(async () => {
+ await fs.rm(destRoot, { recursive: true, force: true });
+ });
+
+ async function makeSnapshot(source, id, { marker } = {}) {
+ const dir = joinPath(destRoot, 'snapshots', source, id);
+ await fs.mkdir(joinPath(dir, 'data'), { recursive: true });
+ await fs.writeFile(joinPath(dir, 'manifest.json'), JSON.stringify({ generatedAt: '2026-01-01T00:00:00Z', fileCount: 0 }));
+ if (marker) await fs.writeFile(joinPath(dir, marker), '');
+ return dir;
+ }
+
+ it('removes exactly the selected source/ID pair, leaving a same-ID snapshot on another source untouched', async () => {
+ const targetDir = await makeSnapshot(machineHost, '2026-06-08T15-18-34');
+ const siblingDir = await makeSnapshot('previous-machine', '2026-06-08T15-18-34');
+
+ const result = await deleteSnapshot(destRoot, '2026-06-08T15-18-34', { source: machineHost });
+
+ expect(result).toEqual({ deleted: true, snapshotId: '2026-06-08T15-18-34', source: machineHost });
+ await expect(fs.stat(targetDir)).rejects.toThrow();
+ await expect(fs.stat(siblingDir)).resolves.toBeDefined();
+ });
+
+ it('defaults to the current machine when source is omitted', async () => {
+ const targetDir = await makeSnapshot(machineHost, '2026-06-08T15-18-34');
+ await deleteSnapshot(destRoot, '2026-06-08T15-18-34');
+ await expect(fs.stat(targetDir)).rejects.toThrow();
+ });
+
+ it('404s for a snapshot that does not exist, without touching the disk', async () => {
+ await expect(deleteSnapshot(destRoot, '2026-06-08T15-18-34', { source: machineHost }))
+ .rejects.toMatchObject({ status: 404, code: 'NOT_FOUND' });
+ });
+
+ it('refuses a snapshot that is still being written (409 SNAPSHOT_INCOMPLETE), leaving it on disk', async () => {
+ const dir = await makeSnapshot(machineHost, '2026-06-08T15-18-34', { marker: '.in-progress' });
+ await expect(deleteSnapshot(destRoot, '2026-06-08T15-18-34', { source: machineHost }))
+ .rejects.toMatchObject({ status: 409, code: 'SNAPSHOT_INCOMPLETE' });
+ await expect(fs.stat(dir)).resolves.toBeDefined();
+ });
+
+ it('allows deleting a failed snapshot — unlike restore, deletion has no reason to require success', async () => {
+ const dir = await makeSnapshot(machineHost, '2026-06-08T15-18-34', { marker: '.failed' });
+ await deleteSnapshot(destRoot, '2026-06-08T15-18-34', { source: machineHost });
+ await expect(fs.stat(dir)).rejects.toThrow();
+ });
+
+ it('rejects an explicitly selected source namespace that is a symbolic link', async () => {
+ const outsideRoot = await fs.mkdtemp(joinPath(tmpdir(), 'portos-backup-delete-outside-'));
+ try {
+ await makeSnapshot('evil', '2026-06-08T15-18-34');
+ await fs.rm(joinPath(destRoot, 'snapshots', 'evil'), { recursive: true, force: true });
+ await fs.symlink(outsideRoot, joinPath(destRoot, 'snapshots', 'evil'), 'dir');
+ await expect(deleteSnapshot(destRoot, '2026-06-08T15-18-34', { source: 'evil' }))
+ .rejects.toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });
+ } finally {
+ await fs.rm(outsideRoot, { recursive: true, force: true });
+ }
+ });
+});
+
describe('openSnapshotStream', () => {
afterEach(async () => {
const actual = await vi.importActual('fs/promises');
@@ -2884,4 +2952,72 @@ describe('runBackup lifecycle', () => {
expect(await getState()).toMatchObject({ status: 'ok', error: null });
});
+ // -----------------------------------------------------------------------
+ // Retention pruning (#8334) — after a successful run, the oldest COMPLETED
+ // snapshots on THIS machine beyond retentionCount are deleted. Failed,
+ // in-progress, and other-source snapshots must never be touched, and
+ // retentionCount null/undefined must never prune anything (an existing
+ // install with no stored value keeps everything — see backupConfig.js).
+ // -----------------------------------------------------------------------
+ describe('retention pruning', () => {
+ async function seedSnapshot(source, id, { generatedAt, marker } = {}) {
+ const fsp = await actualFs();
+ const dir = joinPath(destRoot, 'snapshots', source, id);
+ await fsp.mkdir(joinPath(dir, 'data'), { recursive: true });
+ if (generatedAt) {
+ await fsp.writeFile(joinPath(dir, 'manifest.json'), JSON.stringify({ generatedAt, fileCount: 0 }));
+ }
+ if (marker) await fsp.writeFile(joinPath(dir, marker), '');
+ return dir;
+ }
+
+ it('prunes only the oldest completed snapshots in the current machine namespace, keeping failed/in-progress/other-source snapshots', async () => {
+ const fsp = await actualFs();
+ const old1 = await seedSnapshot(machineHost, '2020-01-01T00-00-00', { generatedAt: '2020-01-01T00:00:00.000Z' });
+ const old2 = await seedSnapshot(machineHost, '2020-01-02T00-00-00', { generatedAt: '2020-01-02T00:00:00.000Z' });
+ const old3 = await seedSnapshot(machineHost, '2020-01-03T00-00-00', { generatedAt: '2020-01-03T00:00:00.000Z' });
+ const incomplete = await seedSnapshot(machineHost, '2020-01-04T00-00-00', { marker: '.in-progress' });
+ const failed = await seedSnapshot(machineHost, '2020-01-05T00-00-00', { generatedAt: '2020-01-05T00:00:00.000Z', marker: '.failed' });
+ const otherMachine = await seedSnapshot('previous-machine', '2020-01-01T00-00-00', { generatedAt: '2020-01-01T00:00:00.000Z' });
+
+ const io = { emit: vi.fn() };
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+ const pending = runBackup(destRoot, io, { retentionCount: 2 });
+ await waitFor(() => spawn.mock.calls.length === 1, 'rsync spawn');
+ proc.emit('close', 0);
+ const result = await pending;
+
+ // Keeps the newest 2 completed snapshots on this machine: the run just
+ // created and old3. old1 and old2 are pruned.
+ await expect(fsp.stat(old1)).rejects.toThrow();
+ await expect(fsp.stat(old2)).rejects.toThrow();
+ await expect(fsp.stat(old3)).resolves.toBeDefined();
+ const newSnapshotDir = joinPath(destRoot, 'snapshots', machineHost, result.snapshotId);
+ await expect(fsp.stat(newSnapshotDir)).resolves.toBeDefined();
+
+ // Never touched: still-being-written, failed, and another machine's namespace.
+ await expect(fsp.stat(incomplete)).resolves.toBeDefined();
+ await expect(fsp.stat(failed)).resolves.toBeDefined();
+ await expect(fsp.stat(otherMachine)).resolves.toBeDefined();
+ });
+
+ it('does not prune anything when retentionCount is null (unlimited — the legacy/unset default)', async () => {
+ const fsp = await actualFs();
+ const old1 = await seedSnapshot(machineHost, '2020-01-01T00-00-00', { generatedAt: '2020-01-01T00:00:00.000Z' });
+ const old2 = await seedSnapshot(machineHost, '2020-01-02T00-00-00', { generatedAt: '2020-01-02T00:00:00.000Z' });
+
+ const io = { emit: vi.fn() };
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+ const pending = runBackup(destRoot, io, { retentionCount: null });
+ await waitFor(() => spawn.mock.calls.length === 1, 'rsync spawn');
+ proc.emit('close', 0);
+ await pending;
+
+ await expect(fsp.stat(old1)).resolves.toBeDefined();
+ await expect(fsp.stat(old2)).resolves.toBeDefined();
+ });
+ });
+
});
diff --git a/server/services/backupScheduler.js b/server/services/backupScheduler.js
index c54b9ae2e1..5fda480738 100644
--- a/server/services/backupScheduler.js
+++ b/server/services/backupScheduler.js
@@ -93,7 +93,7 @@ function attemptRegistration(inputs, timezone, signature) {
const excludePaths = fresh.backup?.excludePaths || [];
const disabledDefaultExcludes = fresh.backup?.disabledDefaultExcludes || [];
console.log('💾 Backup scheduler: running scheduled backup');
- await runBackup(effective.destPath, null, { excludePaths, disabledDefaultExcludes });
+ await runBackup(effective.destPath, null, { excludePaths, disabledDefaultExcludes, retentionCount: effective.retentionCount });
},
metadata: { source: 'backupScheduler' }
});
diff --git a/server/services/backupScheduler.test.js b/server/services/backupScheduler.test.js
index 58df30eac0..1eda922bee 100644
--- a/server/services/backupScheduler.test.js
+++ b/server/services/backupScheduler.test.js
@@ -110,7 +110,7 @@ describe('startBackupScheduler', () => {
expect(runBackup).toHaveBeenCalledWith(
'/dest-fresh',
null,
- { excludePaths: ['fresh/'], disabledDefaultExcludes: ['/loras/*.safetensors'] }
+ { excludePaths: ['fresh/'], disabledDefaultExcludes: ['/loras/*.safetensors'], retentionCount: null }
);
});
@@ -290,7 +290,7 @@ describe('backup schedule defaults (#6632)', () => {
await startBackupScheduler();
await schedule.mock.calls[0][0].handler();
expect(runBackup).toHaveBeenCalledWith('/example-backups', null, {
- excludePaths: [], disabledDefaultExcludes: []
+ excludePaths: [], disabledDefaultExcludes: [], retentionCount: null
});
});
});