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(backup): skip large re-downloadable assets by default, per-default override (#234)

[._.]/ Adam Eivya284f04c8868
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index cba1050aa9..52f0b24b7c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -482,6 +482,62 @@
PATCH round-trips cleanly through the canonical sanitizer with no other
schema changes.
+- **Backup defaults — skip large re-downloadable assets, with per-default override.**
+ `loras/*.safetensors`, `repos/`, `cos/reference-repos/`, and `browser-downloads/`
+ are now in the built-in `DEFAULT_EXCLUDES` for scheduled and manual backups,
+ so the default snapshot no longer balloons by tens of GB of LoRA weights,
+ cloned upstream repos, and browser download cache when the user just wants
+ their data backed up to iCloud or an external drive. Each new entry is
+ tagged `overridable: true`; the Backup settings page renders a toggle per
+ overridable default so users can opt to back them up by adding the path
+ to a new `backup.disabledDefaultExcludes` array. The pre-existing
+ `browser-profile/` + `cos/worktrees/` + `cos/feature-agents/*/worktree/`
+ entries stay `overridable: false` (cache/ephemeral data with no
+ irreplaceable user content) and continue to be skipped unconditionally.
+ Plumbed through `runBackup()`, the route, the scheduler, and
+ `backupConfigSchema`; tests updated.
+
+ **Notes on review feedback:**
+ - All `DEFAULT_EXCLUDES` paths are anchored with a leading `/` (rsync
+ filter syntax for "relative to the transfer root"). Without the anchor
+ a pattern like `loras/*.safetensors` would match any `loras/` directory
+ anywhere under data/ — including user-managed collections under e.g.
+ `brain/.../loras/` — and silently exclude unrelated user data.
+ - The LoRA exclude is `/loras/*.safetensors`, not `/loras/`. The
+ `.metadata.json` sidecars next to each `.safetensors` file (Civitai
+ metadata + user-editable name / recommendedScale / notes) are the
+ source of truth for that user data and ARE backed up.
+ - The cron handler in `backupScheduler.js` re-reads settings on each
+ invocation, so toggling a default exclude in the UI takes effect on the
+ next scheduled run without a server restart. The handler also re-checks
+ `backup.enabled` and `backup.destPath`, so disabling backups or clearing
+ the destination after startup short-circuits the run. (Only the cron
+ expression itself is captured at registration.)
+ - `runBackup()` guards `excludePaths` and `disabledDefaultExcludes` with
+ `Array.isArray` before filtering, so a hand-edited settings.json with
+ the wrong shape doesn't abort the backup. Exclude-computation extracted
+ into `computeEffectiveExcludes()` (pure, unit-tested).
+ - The Backup tab `<isExcluded>` state now accounts for paths also listed
+ in Additional Exclude Paths via a `shadowsDefault()` helper that
+ catches exact matches AND broader rsync patterns (`loras/`, `loras/**`,
+ `/cos/` covering `/cos/reference-repos/`). Toggling a default to
+ "included" strips every shadowing custom entry, and `addExclude`
+ refuses to add a pattern that would shadow any default. The warning
+ chip names the offending custom entry so the user knows which one to
+ delete.
+ - `backupConfigSchema` is now wired into the settings PUT route (used as
+ `.partial()` so an unrelated settings save doesn't require a full
+ backup config). The schema's `destPath` was loosened to
+ `z.string().nullable().optional()` to match the route's existing
+ "empty / missing destPath = not configured" semantics — saving an
+ empty input no longer 400s.
+ - Client-side `asArray()` normalizer wraps `settings.backup.excludePaths`
+ and `disabledDefaultExcludes` (and the `defaultExcludes` returned from
+ `/api/backup/status`) before they reach React state — settings.json is
+ hand-editable and the GET endpoint is unvalidated, so an incoming
+ non-array shape no longer crashes downstream `.some` / `.includes` /
+ `.filter` calls in the Backup tab.
+
## Changed
- **Data migration scripts for bringing old machines forward.** Two new
diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsx
index 55466170d2..a0a26d260a 100644
--- a/client/src/components/settings/BackupTab.jsx
+++ b/client/src/components/settings/BackupTab.jsx
@@ -2,9 +2,37 @@ import { useState, useEffect } from 'react';
import { Save, Plus, X, Play, ShieldOff } from 'lucide-react';
import toast from '../ui/Toast';
import BrailleSpinner from '../BrailleSpinner';
+import ToggleSwitch from '../ToggleSwitch';
import useAsyncAction from '../../hooks/useAsyncAction';
import { getSettings, updateSettings, getBackupStatus, triggerBackup } from '../../services/api';
+// 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));
+
+// settings.json is hand-editable and the GET /settings endpoint is unvalidated,
+// so an incoming `excludePaths`/`disabledDefaultExcludes` value can be a string,
+// null, or any other shape. Normalize before it reaches React state — otherwise
+// downstream `.some` / `.includes` / `.filter` calls crash the Backup tab.
+const asArray = (v) => Array.isArray(v) ? v : [];
+
+// Whether a user-supplied custom rsync exclude pattern covers (shadows) a default
+// exclude path — broader than a bare `===` check so the UI doesn't mark a default
+// as "included" while a custom entry like `loras/`, `loras/**`, or `/cos/` is
+// still effectively excluding it via rsync. Strips leading `/`, trailing `/`, and
+// a trailing `**`/`*` glob from both sides, then compares directory prefixes:
+// the custom path shadows the default when the default's normalized form equals
+// the custom's OR lives inside the custom's subtree.
+const normalizePattern = (p) =>
+ String(p ?? '').replace(/^\/+/, '').replace(/\/+\*+$/, '').replace(/\*+$/, '').replace(/\/+$/, '');
+const shadowsDefault = (customPath, defaultPath) => {
+ if (customPath === defaultPath) return true;
+ const c = normalizePattern(customPath);
+ const d = normalizePattern(defaultPath);
+ if (!c || !d) return false;
+ return d === c || d.startsWith(c + '/');
+};
+
export function BackupTab() {
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
@@ -14,6 +42,8 @@ export function BackupTab() {
const [cronExpression, setCronExpression] = useState('0 2 * * *');
const [excludePaths, setExcludePaths] = useState([]);
const [savedExcludePaths, setSavedExcludePaths] = useState([]);
+ const [disabledDefaultExcludes, setDisabledDefaultExcludes] = useState([]);
+ const [savedDisabledDefaultExcludes, setSavedDisabledDefaultExcludes] = useState([]);
const [defaultExcludes, setDefaultExcludes] = useState([]);
const [newExclude, setNewExclude] = useState('');
@@ -22,14 +52,17 @@ export function BackupTab() {
.then(([settings, status]) => {
const backup = settings?.backup || {};
const saved = backup.destPath || '';
- const savedExcludes = backup.excludePaths || [];
+ const savedExcludes = asArray(backup.excludePaths);
+ const savedDisabled = asArray(backup.disabledDefaultExcludes);
setDestPath(saved);
setSavedDestPath(saved);
setEnabled(backup.enabled ?? false);
setCronExpression(backup.cronExpression || '0 2 * * *');
setExcludePaths(savedExcludes);
setSavedExcludePaths(savedExcludes);
- setDefaultExcludes(status?.defaultExcludes || []);
+ setDisabledDefaultExcludes(savedDisabled);
+ setSavedDisabledDefaultExcludes(savedDisabled);
+ setDefaultExcludes(asArray(status?.defaultExcludes));
})
.catch(() => toast.error('Failed to load settings'))
.finally(() => setLoading(false));
@@ -38,9 +71,10 @@ export function BackupTab() {
const handleSave = async () => {
setSaving(true);
try {
- await updateSettings({ backup: { destPath, enabled, cronExpression, excludePaths } });
+ await updateSettings({ backup: { destPath, enabled, cronExpression, excludePaths, disabledDefaultExcludes } });
setSavedDestPath(destPath);
setSavedExcludePaths(excludePaths);
+ setSavedDisabledDefaultExcludes(disabledDefaultExcludes);
toast.success('Settings saved');
} catch (err) {
toast.error(err.message || 'Failed to save settings');
@@ -49,6 +83,21 @@ export function BackupTab() {
}
};
+ const toggleDefaultExclude = (path) => {
+ const currentlyDisabled = disabledDefaultExcludes.includes(path);
+ if (currentlyDisabled) {
+ // Re-enabling the default exclude — path goes back to being excluded.
+ setDisabledDefaultExcludes(prev => prev.filter(p => p !== path));
+ } else {
+ // Disabling the default — the user is opting this path back IN to backups.
+ // Strip every shadowing custom entry (exact match AND broader patterns
+ // like `loras/`, `loras/**`); otherwise rsync would still exclude it and
+ // the toggle would lie about the actual behavior.
+ setDisabledDefaultExcludes(prev => [...prev, path]);
+ setExcludePaths(prev => prev.filter(p => !shadowsDefault(p, path)));
+ }
+ };
+
const [handleRunNow, running] = useAsyncAction(async () => {
const result = await triggerBackup({ silent: true });
if (result?.skipped) {
@@ -62,6 +111,14 @@ export function BackupTab() {
const addExclude = () => {
const trimmed = newExclude.trim();
if (!trimmed || excludePaths.includes(trimmed)) return;
+ // A custom exclude that shadows a default would lie about toggle state
+ // (toggle "included" but rsync still excludes via the custom entry).
+ // Catches exact matches AND broader patterns like `loras/` or `loras/**`.
+ const shadowed = defaultExcludes.find(d => shadowsDefault(trimmed, d.path));
+ if (shadowed) {
+ toast.error(`"${trimmed}" shadows the default exclusion "${shadowed.path}" — use the toggle above instead`);
+ return;
+ }
setExcludePaths([...excludePaths, trimmed]);
setNewExclude('');
};
@@ -74,9 +131,9 @@ export function BackupTab() {
return <BrailleSpinner text="Loading backup settings" />;
}
- const excludesDirty = excludePaths.length !== savedExcludePaths.length
- || excludePaths.some((p, i) => p !== savedExcludePaths[i]);
- const dirty = destPath !== savedDestPath || excludesDirty;
+ const dirty = destPath !== savedDestPath
+ || !sameSet(excludePaths, savedExcludePaths)
+ || !sameSet(disabledDefaultExcludes, savedDisabledDefaultExcludes);
const canRun = !!savedDestPath && !running && !saving && !dirty;
const runTitle = !savedDestPath
? 'Configure and save a destination path first'
@@ -125,16 +182,44 @@ export function BackupTab() {
<div className="space-y-2">
<div className="flex items-center gap-2">
<ShieldOff size={14} className="text-gray-500" />
- <label className="block text-sm text-gray-400">Default Exclusions (always skipped)</label>
+ <label className="block text-sm text-gray-400">Default Exclusions</label>
</div>
- <p className="text-xs text-gray-500">Built-in paths that are never backed up — they hold large or ephemeral data that would bloat snapshots.</p>
- <ul className="space-y-1 mt-1">
- {defaultExcludes.map((d, i) => (
- <li key={i} className="flex items-start gap-2 text-xs">
- <code className="px-1.5 py-0.5 bg-port-bg border border-port-border rounded text-gray-300 shrink-0">{d.path}</code>
- <span className="text-gray-500">{d.reason}</span>
- </li>
- ))}
+ <p className="text-xs text-gray-500">Built-in paths skipped by default to keep snapshots small. Overridable entries (large re-downloadable assets) can be re-enabled below; fixed entries hold ephemeral data and stay off.</p>
+ <ul className="space-y-1.5 mt-1">
+ {defaultExcludes.map((d, i) => {
+ const isDisabled = disabledDefaultExcludes.includes(d.path);
+ // Custom excludes can shadow a default via exact match (`loras/...`)
+ // OR a broader pattern (`loras/`, `loras/**`, `/cos/`). The broader
+ // check is necessary because rsync still applies the custom pattern
+ // even when the default toggle says "included".
+ const shadowingCustom = excludePaths.find(p => shadowsDefault(p, d.path));
+ const defaultActive = !(d.overridable && isDisabled);
+ const isExcluded = defaultActive || !!shadowingCustom;
+ const shadowedByCustom = !defaultActive && !!shadowingCustom;
+ return (
+ <li key={i} className="flex items-start gap-2 text-xs">
+ {d.overridable ? (
+ <ToggleSwitch
+ enabled={!isExcluded}
+ onChange={() => toggleDefaultExclude(d.path)}
+ size="sm"
+ ariaLabel={isExcluded ? `Include ${d.path} in backups` : `Exclude ${d.path} from backups`}
+ className="mt-0.5"
+ />
+ ) : (
+ <span className="inline-flex items-center justify-center w-12 h-7 shrink-0 text-gray-600" title="Always excluded — cannot be backed up">
+ <ShieldOff size={14} />
+ </span>
+ )}
+ <code className={`px-1.5 py-0.5 bg-port-bg border rounded shrink-0 ${isExcluded ? 'text-gray-300 border-port-border' : 'text-port-success border-port-success/30'}`}>{d.path}</code>
+ <span className="text-gray-500">
+ {d.reason}
+ {!isExcluded && <span className="text-port-success/80 ml-1">(included)</span>}
+ {shadowedByCustom && <span className="text-port-warning ml-1">(still excluded via Additional Exclude Paths — remove <code>{shadowingCustom}</code> below)</span>}
+ </span>
+ </li>
+ );
+ })}
</ul>
</div>
)}
diff --git a/server/lib/validation.js b/server/lib/validation.js
index c201b52be8..efa26569c6 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -523,10 +523,16 @@ export const searchQuerySchema = z.object({
// BACKUP SCHEMAS
// =============================================================================
+// Used by both the settings PUT route (.partial() for incremental updates) and
+// any direct backup-config endpoint. destPath is nullable: the UI persists an
+// empty string when the field is cleared, and the route handler treats empty/
+// missing destPath as "not configured" rather than rejecting the save.
export const backupConfigSchema = z.object({
- destPath: z.string().min(1),
+ destPath: z.string().nullable().optional(),
cronExpression: z.string().optional(),
- enabled: z.boolean().optional().default(true)
+ enabled: z.boolean().optional().default(true),
+ excludePaths: z.array(z.string()).optional().default([]),
+ disabledDefaultExcludes: z.array(z.string()).optional().default([])
});
export const restoreRequestSchema = z.object({
diff --git a/server/routes/backup.js b/server/routes/backup.js
index 5f0ecc00ce..ed600fe29c 100644
--- a/server/routes/backup.js
+++ b/server/routes/backup.js
@@ -27,8 +27,9 @@ router.post('/run', asyncHandler(async (req, res) => {
return res.status(400).json({ error: 'BACKUP_NOT_CONFIGURED', message: 'No backup destination configured in settings' });
}
const excludePaths = settings.backup?.excludePaths || [];
+ const disabledDefaultExcludes = settings.backup?.disabledDefaultExcludes || [];
const io = req.app.get('io');
- const result = await backup.runBackup(destPath, io, { excludePaths });
+ const result = await backup.runBackup(destPath, io, { excludePaths, disabledDefaultExcludes });
res.json(result);
}));
diff --git a/server/routes/backup.test.js b/server/routes/backup.test.js
index 5b5b9d29e8..a376870e2b 100644
--- a/server/routes/backup.test.js
+++ b/server/routes/backup.test.js
@@ -9,7 +9,10 @@ vi.mock('../services/backup.js', () => ({
runBackup: vi.fn(),
listSnapshots: vi.fn(),
restoreSnapshot: vi.fn(),
- DEFAULT_EXCLUDES: [{ path: 'browser-profile/', reason: 'test' }]
+ DEFAULT_EXCLUDES: [
+ { path: '/browser-profile/', reason: 'test', overridable: false },
+ { path: '/loras/*.safetensors', reason: 'test', overridable: true }
+ ]
}));
vi.mock('../services/settings.js', () => ({
@@ -46,7 +49,10 @@ describe('backup routes', () => {
success: true,
destPath: '/backup/target',
nextRun: '2026-04-08T00:00:00Z',
- defaultExcludes: [{ path: 'browser-profile/', reason: 'test' }]
+ defaultExcludes: [
+ { path: '/browser-profile/', reason: 'test', overridable: false },
+ { path: '/loras/*.safetensors', reason: 'test', overridable: true }
+ ]
});
});
@@ -80,7 +86,7 @@ describe('backup routes', () => {
expect(backup.runBackup).toHaveBeenCalledWith(
'/dest',
undefined,
- { excludePaths: ['node_modules', '.git'] }
+ { excludePaths: ['node_modules', '.git'], disabledDefaultExcludes: [] }
);
});
@@ -91,7 +97,20 @@ describe('backup routes', () => {
expect(backup.runBackup).toHaveBeenCalledWith(
'/dest',
undefined,
- { excludePaths: [] }
+ { excludePaths: [], disabledDefaultExcludes: [] }
+ );
+ });
+
+ it('forwards disabledDefaultExcludes when configured', async () => {
+ getSettings.mockResolvedValue({
+ backup: { destPath: '/dest', disabledDefaultExcludes: ['/loras/*.safetensors'] }
+ });
+ backup.runBackup.mockResolvedValue({ success: true });
+ await request(buildApp()).post('/api/backup/run');
+ expect(backup.runBackup).toHaveBeenCalledWith(
+ '/dest',
+ undefined,
+ { excludePaths: [], disabledDefaultExcludes: ['/loras/*.safetensors'] }
);
});
});
diff --git a/server/routes/settings.js b/server/routes/settings.js
index b7c0b6a1be..0077fe573b 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -7,6 +7,7 @@ import {
CODEX_PARALLEL_DEFAULT,
} from '../services/mediaJobQueue/index.js';
import { asyncHandler } from '../lib/errorHandler.js';
+import { backupConfigSchema, validateRequest } from '../lib/validation.js';
const router = Router();
@@ -38,6 +39,13 @@ router.get('/', asyncHandler(async (req, res) => {
// PUT /api/settings
router.put('/', asyncHandler(async (req, res) => {
+ // Settings is a polymorphic store but the backup sub-object has a known
+ // schema. Validate that slice when it's present so a malformed Backup-tab
+ // save doesn't reach disk (the runtime guards downstream are belt-and-
+ // suspenders, but per project convention all inputs are validated).
+ if (req.body?.backup !== undefined) {
+ validateRequest(backupConfigSchema.partial(), req.body.backup);
+ }
const merged = await updateSettings(req.body);
// The queue caches codex.parallelLimit in-process; sync it from the
// merged value so a save takes effect without a restart and without
diff --git a/server/services/backup.js b/server/services/backup.js
index 42f7f1bd04..ba0de18baa 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -21,21 +21,32 @@ let isRunning = false;
const STATE_PATH = join(PATHS.data, 'backup', 'state.json');
-// Paths under data/ that are always skipped on top of user-configured excludes.
-// Browser profile is a CDP cache that can grow to several GB; worktrees are
-// throwaway agent checkouts of the main repo. When adding a new entry, ensure
-// the path glob covers *every* on-disk location for that class of data —
-// e.g. agent worktrees live under both cos/worktrees/ and
-// cos/feature-agents/*/worktree/; cross-reference worktreeManager.js and
-// agentLifecycle.js if introducing new worktree paths.
+// Paths under data/ that are skipped by default on top of user-configured excludes.
+// Two classes live here: (1) ephemeral/cache data the user almost never wants in a
+// snapshot (browser profile, agent worktrees), and (2) large re-downloadable assets
+// (LoRA model files, cloned repos, browser downloads) that would bloat the backup
+// target — typically iCloud or an external drive with limited capacity. Entries
+// tagged `overridable: true` can be re-enabled from the Backup settings UI via
+// `disabledDefaultExcludes`; non-overridable entries hold no irreplaceable user data
+// and stay off unconditionally. When adding a new entry, ensure the path glob covers
+// *every* on-disk location for that class of data — e.g. agent worktrees live under
+// both cos/worktrees/ and cos/feature-agents/*/worktree/; cross-reference
+// worktreeManager.js and agentLifecycle.js if introducing new worktree paths.
+//
+// All paths are anchored with a leading `/` (rsync filter syntax for "relative to
+// the transfer root"). Without the anchor, a pattern like `loras/*.safetensors`
+// matches any `loras/` directory anywhere under data/ (e.g. a user's
+// brain/.../loras/ collection), which would silently exclude unrelated user data.
export const DEFAULT_EXCLUDES = [
- { path: 'browser-profile/', reason: 'Browser CDP profile — cache/cookies, can be several GB' },
- { path: 'cos/worktrees/', reason: 'Ephemeral agent git worktrees — recreated on demand' },
- { path: 'cos/feature-agents/*/worktree/', reason: 'Per-feature-agent git worktrees — recreated on demand' }
+ { path: '/browser-profile/', reason: 'Browser CDP profile — cache/cookies, can be several GB', overridable: false },
+ { path: '/cos/worktrees/', reason: 'Ephemeral agent git worktrees — recreated on demand', overridable: false },
+ { path: '/cos/feature-agents/*/worktree/', reason: 'Per-feature-agent git worktrees — recreated on demand', overridable: false },
+ { path: '/loras/*.safetensors', reason: 'LoRA adapter weight files — large, re-downloadable. .metadata.json sidecars (Civitai metadata, user-editable name/notes) ARE backed up.', overridable: true },
+ { path: '/repos/', reason: 'Cloned git repositories — large, re-cloneable from origin', overridable: true },
+ { path: '/cos/reference-repos/', reason: 'Reference upstream repos used by agents — re-cloneable', overridable: true },
+ { path: '/browser-downloads/', reason: 'Browser downloads cache — large, re-downloadable', overridable: true }
];
-const DEFAULT_EXCLUDE_PATHS = DEFAULT_EXCLUDES.map(e => e.path);
-
// Snapshots live under snapshots/<hostname>/<snapshotId> so a single shared
// destination (e.g. iCloud) can host backups from multiple machines without
// their snapshot IDs colliding.
@@ -97,12 +108,34 @@ function runRsync(srcDir, destDir, flags = []) {
// EXPORTS
// =============================================================================
+/**
+ * Compute the effective rsync --exclude list for a backup run. Pure function
+ * extracted so the Array.isArray guards + override allow-list can be unit
+ * tested without spawning rsync.
+ *
+ * - Non-overridable defaults stay on regardless of `disabledDefaultExcludes` so
+ * ephemeral/cache paths can never be backed up by mistake (e.g. via a
+ * hand-edited settings.json).
+ * - Array.isArray guards: settings can be hand-edited or sent by a stale
+ * client, so a non-array value here would otherwise throw inside .filter
+ * and abort the backup before the defensive allow-list has a chance to apply.
+ */
+export function computeEffectiveExcludes({ excludePaths, disabledDefaultExcludes } = {}) {
+ const overridablePaths = new Set(DEFAULT_EXCLUDES.filter(e => e.overridable).map(e => e.path));
+ const disabledList = Array.isArray(disabledDefaultExcludes) ? disabledDefaultExcludes : [];
+ const userList = Array.isArray(excludePaths) ? excludePaths : [];
+ const disabledSet = new Set(disabledList.filter(p => overridablePaths.has(p)));
+ const activeDefaults = DEFAULT_EXCLUDES.filter(e => !disabledSet.has(e.path)).map(e => e.path);
+ const userExcludes = userList.filter(Boolean);
+ return [...new Set([...activeDefaults, ...userExcludes])];
+}
+
/**
* Run a full backup snapshot from PATHS.data to destPath.
* @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 = [] } = {}) {
+export async function runBackup(destPath, io = null, { excludePaths = [], disabledDefaultExcludes = [] } = {}) {
if (isRunning) {
console.log('💾 Backup already running — skipping');
return { skipped: true };
@@ -121,9 +154,7 @@ export async function runBackup(destPath, io = null, { excludePaths = [] } = {})
const snapshotDir = join(destPath, 'snapshots', MACHINE_HOST, snapshotId);
const dataDestDir = join(snapshotDir, 'data');
- // Merge user excludes with built-in defaults; dedupe so user can't double-list a default.
- const userExcludes = excludePaths.filter(Boolean);
- const effectiveExcludes = [...new Set([...DEFAULT_EXCLUDE_PATHS, ...userExcludes])];
+ const effectiveExcludes = computeEffectiveExcludes({ excludePaths, disabledDefaultExcludes });
console.log(`💾 Backup starting: snapshot ${snapshotId} (excluding ${effectiveExcludes.length} paths)`);
if (io) io.emit('backup:started', { snapshotId });
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
new file mode 100644
index 0000000000..cc526fc74c
--- /dev/null
+++ b/server/services/backup.test.js
@@ -0,0 +1,105 @@
+/**
+ * Unit tests for computeEffectiveExcludes — the pure function that decides
+ * which paths rsync sees as `--exclude`. Tests the defensive Array.isArray
+ * guards (settings.json is hand-editable, so a non-array value must not
+ * throw) and the overridable allow-list (non-overridable defaults can never
+ * be disabled by user input).
+ */
+
+import { describe, it, expect } from 'vitest';
+import { DEFAULT_EXCLUDES, computeEffectiveExcludes } from './backup.js';
+
+const overridable = DEFAULT_EXCLUDES.filter(e => e.overridable).map(e => e.path);
+const nonOverridable = DEFAULT_EXCLUDES.filter(e => !e.overridable).map(e => e.path);
+
+describe('computeEffectiveExcludes', () => {
+ it('includes every DEFAULT_EXCLUDES path when nothing is disabled', () => {
+ const result = computeEffectiveExcludes({ excludePaths: [], disabledDefaultExcludes: [] });
+ for (const path of DEFAULT_EXCLUDES.map(e => e.path)) {
+ expect(result).toContain(path);
+ }
+ });
+
+ it('honors disabling an overridable default', () => {
+ const target = overridable[0];
+ const result = computeEffectiveExcludes({
+ excludePaths: [],
+ disabledDefaultExcludes: [target]
+ });
+ expect(result).not.toContain(target);
+ });
+
+ it('ignores attempts to disable a non-overridable default', () => {
+ const target = nonOverridable[0];
+ const result = computeEffectiveExcludes({
+ excludePaths: [],
+ disabledDefaultExcludes: [target]
+ });
+ expect(result).toContain(target);
+ });
+
+ it('merges user excludePaths on top of active defaults', () => {
+ const result = computeEffectiveExcludes({
+ excludePaths: ['my/custom/path', 'cache/'],
+ disabledDefaultExcludes: []
+ });
+ expect(result).toContain('my/custom/path');
+ expect(result).toContain('cache/');
+ });
+
+ it('dedupes when a user exclude matches an active default', () => {
+ const target = overridable[0];
+ const result = computeEffectiveExcludes({
+ excludePaths: [target],
+ disabledDefaultExcludes: []
+ });
+ expect(result.filter(p => p === target)).toHaveLength(1);
+ });
+
+ it('drops falsy entries from excludePaths', () => {
+ const result = computeEffectiveExcludes({
+ excludePaths: ['', null, undefined, 'real/path'],
+ disabledDefaultExcludes: []
+ });
+ expect(result).toContain('real/path');
+ expect(result).not.toContain('');
+ expect(result).not.toContain(null);
+ });
+
+ it('tolerates a non-array disabledDefaultExcludes without throwing', () => {
+ // Simulates a hand-edited settings.json with bad shape — should not crash.
+ expect(() => computeEffectiveExcludes({
+ excludePaths: [],
+ disabledDefaultExcludes: 'loras/*.safetensors'
+ })).not.toThrow();
+
+ const result = computeEffectiveExcludes({
+ excludePaths: [],
+ disabledDefaultExcludes: { bogus: true }
+ });
+ // Bogus value is ignored — all defaults stay active.
+ for (const path of DEFAULT_EXCLUDES.map(e => e.path)) {
+ expect(result).toContain(path);
+ }
+ });
+
+ it('tolerates a non-array excludePaths without throwing', () => {
+ expect(() => computeEffectiveExcludes({
+ excludePaths: 'just/one/string',
+ disabledDefaultExcludes: []
+ })).not.toThrow();
+
+ const result = computeEffectiveExcludes({
+ excludePaths: null,
+ disabledDefaultExcludes: []
+ });
+ // Null user list is treated as empty — only defaults remain.
+ expect(result).toEqual(DEFAULT_EXCLUDES.map(e => e.path));
+ });
+
+ it('handles being called with no arguments (defensive)', () => {
+ expect(() => computeEffectiveExcludes()).not.toThrow();
+ const result = computeEffectiveExcludes();
+ expect(result).toEqual(DEFAULT_EXCLUDES.map(e => e.path));
+ });
+});
diff --git a/server/services/backupScheduler.js b/server/services/backupScheduler.js
index 3f9857cb8f..3cedf8a5b2 100644
--- a/server/services/backupScheduler.js
+++ b/server/services/backupScheduler.js
@@ -29,23 +29,37 @@ export async function startBackupScheduler() {
}
const cronExpression = settings.backup?.cronExpression || '0 0 * * *';
- const destPath = settings.backup.destPath;
- const excludePaths = settings.backup?.excludePaths || [];
const timezone = await getUserTimezone();
+ // The cron expression itself is locked in at registration time — changing it
+ // requires a restart. But everything else (destPath, excludePaths,
+ // disabledDefaultExcludes) is re-read inside the handler so toggles saved in
+ // the Settings UI take effect on the next scheduled run without a restart.
schedule({
id: 'backup-daily',
type: 'cron',
cron: cronExpression,
timezone,
handler: async () => {
+ const current = await getSettings();
+ if (current.backup?.enabled === false) {
+ console.log('💾 Backup scheduler: disabled since registration — skipping run');
+ return;
+ }
+ const destPath = current.backup?.destPath;
+ if (!destPath) {
+ console.log('💾 Backup scheduler: destPath cleared since registration — skipping run');
+ return;
+ }
+ const excludePaths = current.backup?.excludePaths || [];
+ const disabledDefaultExcludes = current.backup?.disabledDefaultExcludes || [];
console.log('💾 Backup scheduler: running scheduled backup');
- await runBackup(destPath, null, { excludePaths });
+ await runBackup(destPath, null, { excludePaths, disabledDefaultExcludes });
},
metadata: { source: 'backupScheduler' }
});
- console.log(`💾 Backup scheduler: registered daily backup at cron "${cronExpression}" -> ${destPath}`);
+ console.log(`💾 Backup scheduler: registered daily backup at cron "${cronExpression}" -> ${settings.backup.destPath}`);
}
/**
diff --git a/server/services/backupScheduler.test.js b/server/services/backupScheduler.test.js
new file mode 100644
index 0000000000..7754151370
--- /dev/null
+++ b/server/services/backupScheduler.test.js
@@ -0,0 +1,125 @@
+/**
+ * Tests for backupScheduler — specifically that the cron handler re-reads
+ * settings on each invocation, so toggle changes in the Backup UI take
+ * effect on the next scheduled run without a server restart.
+ *
+ * Prior bug: destPath/excludePaths/disabledDefaultExcludes were closed over
+ * at registration time, so saving a toggle updated settings.json but the
+ * already-scheduled handler kept using the old values until restart.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./eventScheduler.js', () => ({
+ schedule: vi.fn(),
+ cancel: vi.fn()
+}));
+
+vi.mock('./settings.js', () => ({
+ getSettings: vi.fn()
+}));
+
+vi.mock('./backup.js', () => ({
+ runBackup: vi.fn().mockResolvedValue({ success: true })
+}));
+
+vi.mock('../lib/timezone.js', () => ({
+ getUserTimezone: vi.fn().mockResolvedValue('UTC')
+}));
+
+import { schedule } from './eventScheduler.js';
+import { getSettings } from './settings.js';
+import { runBackup } from './backup.js';
+import { startBackupScheduler } from './backupScheduler.js';
+
+describe('startBackupScheduler', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('skips registration when backup is disabled', async () => {
+ getSettings.mockResolvedValue({ backup: { enabled: false, destPath: '/dest' } });
+ await startBackupScheduler();
+ expect(schedule).not.toHaveBeenCalled();
+ });
+
+ it('skips registration when destPath is missing', async () => {
+ getSettings.mockResolvedValue({ backup: { enabled: true } });
+ await startBackupScheduler();
+ expect(schedule).not.toHaveBeenCalled();
+ });
+
+ it('registers a daily cron with the configured expression', async () => {
+ getSettings.mockResolvedValue({
+ backup: { enabled: true, destPath: '/dest', cronExpression: '0 3 * * *' }
+ });
+ await startBackupScheduler();
+ expect(schedule).toHaveBeenCalledTimes(1);
+ expect(schedule.mock.calls[0][0]).toMatchObject({
+ id: 'backup-daily',
+ type: 'cron',
+ cron: '0 3 * * *',
+ timezone: 'UTC'
+ });
+ });
+
+ it('handler re-reads settings on each invocation (no startup-snapshot staleness)', async () => {
+ // First call: registration reads stale settings.
+ getSettings.mockResolvedValueOnce({
+ backup: { enabled: true, destPath: '/dest-original', excludePaths: ['stale/'], disabledDefaultExcludes: [] }
+ });
+ await startBackupScheduler();
+
+ // Second call: scheduled handler fires later, settings have changed.
+ getSettings.mockResolvedValueOnce({
+ backup: {
+ enabled: true,
+ destPath: '/dest-fresh',
+ excludePaths: ['fresh/'],
+ disabledDefaultExcludes: ['/loras/*.safetensors']
+ }
+ });
+
+ // Invoke the registered handler.
+ const handler = schedule.mock.calls[0][0].handler;
+ await handler();
+
+ expect(runBackup).toHaveBeenCalledWith(
+ '/dest-fresh',
+ null,
+ { excludePaths: ['fresh/'], disabledDefaultExcludes: ['/loras/*.safetensors'] }
+ );
+ });
+
+ it('handler skips the run if backup was disabled since registration', async () => {
+ getSettings.mockResolvedValueOnce({
+ backup: { enabled: true, destPath: '/dest', excludePaths: [], disabledDefaultExcludes: [] }
+ });
+ await startBackupScheduler();
+
+ // User toggled "Enabled" off in the UI before the cron fired.
+ getSettings.mockResolvedValueOnce({
+ backup: { enabled: false, destPath: '/dest' }
+ });
+
+ const handler = schedule.mock.calls[0][0].handler;
+ await handler();
+
+ expect(runBackup).not.toHaveBeenCalled();
+ });
+
+ it('handler skips the run if destPath has been cleared since registration', async () => {
+ getSettings.mockResolvedValueOnce({
+ backup: { enabled: true, destPath: '/dest', excludePaths: [], disabledDefaultExcludes: [] }
+ });
+ await startBackupScheduler();
+
+ // User cleared destPath in the UI before the cron fired.
+ getSettings.mockResolvedValueOnce({ backup: { enabled: true } });
+
+ const handler = schedule.mock.calls[0][0].handler;
+ await handler();
+
+ expect(runBackup).not.toHaveBeenCalled();
+ });
+});