Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: resolve backup schedule defaults once so the Settings tab can't cancel a live schedule (#6632)
[._.]/ Adam Eivy48657c94025f
diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsxindex 301369a1e0..96d4da40e5 100644--- a/client/src/components/settings/BackupTab.jsx+++ b/client/src/components/settings/BackupTab.jsx@@ -42,13 +42,21 @@ export function BackupTab() {const additionalExcludeId = useId();const defaultExcludesPanelId = useId();const [loading, setLoading] = useState(true);+ // A settings response that never resolved is NOT 'the defaults' — the schedule+ // fields stay null and the form is replaced by an error panel, so an unreachable+ // API can't be saved back as invented values (#6632).+ const [loadFailed, setLoadFailed] = useState(false);const [saving, setSaving] = useState(false);const [destPath, setDestPath] = useState('');const [savedDestPath, setSavedDestPath] = useState('');- const [enabled, setEnabled] = useState(false);- const [savedEnabled, setSavedEnabled] = useState(false);- const [cronExpression, setCronExpression] = useState('0 2 * * *');- const [savedCronExpression, setSavedCronExpression] = useState('0 2 * * *');+ // Schedule state is seeded ONLY from the API's resolved values. The server+ // owns how a sparse backup config resolves (server/lib/backupConfig.js); a+ // client-side fallback here would be a second, conflicting interpretation —+ // which is exactly what silently cancelled destination-only schedules (#6632).+ const [enabled, setEnabled] = useState(null);+ const [savedEnabled, setSavedEnabled] = useState(null);+ const [cronExpression, setCronExpression] = useState(null);+ const [savedCronExpression, setSavedCronExpression] = useState(null);const [excludePaths, setExcludePaths] = useState([]);const [savedExcludePaths, setSavedExcludePaths] = useState([]);const [disabledDefaultExcludes, setDisabledDefaultExcludes] = useState([]);@@ -78,8 +86,14 @@ export function BackupTab() {const savedDisabled = asArray(backup.disabledDefaultExcludes);setDestPath(saved);setSavedDestPath(saved);- const savedEnabledValue = backup.enabled ?? false;- const savedCron = backup.cronExpression || '0 2 * * *';+ // The GET projects the effective schedule, so these are always present.+ // Anything else is an unresolved response and is treated as a load failure+ // rather than being papered over with a locally invented default.+ if (typeof backup.enabled !== 'boolean' || !backup.cronExpression) {+ throw new Error('Settings response did not include a resolved backup schedule');+ }+ const savedEnabledValue = backup.enabled;+ const savedCron = backup.cronExpression;setEnabled(savedEnabledValue);setSavedEnabled(savedEnabledValue);setCronExpression(savedCron);@@ -93,7 +107,10 @@ export function BackupTab() {setBackupStatus(status?.status ?? 'never');setSnapshots(Array.isArray(snaps) ? snaps : []);})- .catch(() => toast.error('Failed to load settings'))+ .catch(() => {+ setLoadFailed(true);+ toast.error('Failed to load settings');+ }).finally(() => setLoading(false));}, []);@@ -174,6 +191,15 @@ export function BackupTab() {return <BrailleSpinner text="Loading backup settings" />;}+ if (loadFailed) {+ return (+ <div className="text-sm text-port-error">+ Failed to load backup settings. Reload the page to try again — the form stays hidden so an+ unresolved response can't be saved over your schedule.+ </div>+ );+ }+const dirty = destPath !== savedDestPath|| enabled !== savedEnabled|| cronExpression !== savedCronExpressiondiff --git a/client/src/components/settings/BackupTab.test.jsx b/client/src/components/settings/BackupTab.test.jsxindex bd134aecae..dc0a3ab532 100644--- a/client/src/components/settings/BackupTab.test.jsx+++ b/client/src/components/settings/BackupTab.test.jsx@@ -502,4 +502,34 @@ describe('BackupTab', () => {expect(screen.getByText(/Dump failed: version_mismatch/i)).toBeTruthy();});});++ describe('resolved schedule from the API (#6632)', () => {+ // The regression: editing something unrelated and saving used to write the+ // 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: [] }+ });+ updateSettings.mockResolvedValue({});+ await renderTab();++ fireEvent.change(screen.getByPlaceholderText('repos/'), { target: { value: 'scratch/' } });+ fireEvent.click(screen.getByLabelText('Add exclude path'));+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /^Save$/i })); });++ expect(updateSettings).toHaveBeenCalledWith(+ { backup: expect.objectContaining({ enabled: true, cronExpression: '0 0 * * *', excludePaths: ['scratch/'] }) },+ { silent: true }+ );+ });++ // An unresolved response is not 'the defaults': the form must not render, so+ // nothing can be saved over a live schedule.+ it('refuses to render the form when the response carries no resolved schedule', async () => {+ getSettings.mockResolvedValue({ backup: { destPath: '/example-backups' } });+ render(<BackupTab />);+ await waitFor(() => expect(screen.getByText(/Failed to load backup settings/i)).toBeTruthy());+ expect(screen.queryByRole('button', { name: /^Save$/i })).toBeNull();+ });+ });});diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 07f6226677..3f0f957071 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -88,6 +88,20 @@ Separate from snapshot restore: `server/routes/database.js` can copy data **betw- **The registration tracks settings — no restart needed.** `syncBackupSchedule()` runs at boot *and* on every settings save (subscribed to `settingsEvents`' `settings:updated`), so enabling backups or setting `destPath` when scheduling was previously inactive registers the cron immediately, editing `cronExpression` re-registers it, and disabling backups (or clearing `destPath`) cancels it. A save that doesn't change the registration inputs (cron expression, timezone, active/inactive) is a no-op — `destPath` and the exclude lists are re-read by the handler per run, so changing them never churns the registration.- `GET /api/backup/status` surfaces the persisted state including the last `pgBackup` outcome, so the Backup settings tab shows whether the last DB dump succeeded, its size, and table count.+### Omitted schedule fields++The backup settings slice is stored **sparsely** — an install where the user only ever typed a destination has no `enabled` and no `cronExpression` on disk. `server/lib/backupConfig.js` is the single module that says what those omissions mean, and every consumer resolves through it:++| Stored | Effective |+| --- | --- |+| `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 |++`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.++This is **read-time resolution only**: nothing on disk changes, sparse configurations stay valid, and older clients can keep submitting the same partial shape.+## See also- [Storage Classification Contract](./STORAGE.md) — which data lives in Postgres vs files (and therefore which half of a snapshot captures it).diff --git a/server/lib/README.md b/server/lib/README.mdindex 52a3163637..55c98ccae5 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -499,6 +499,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| 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. || `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. || `cudaCapability.js` | NVIDIA CUDA host probe — the one place that shells to `nvidia-smi`. `detectCudaGpus()` / cached `getCudaCapability()` return `{ available, status, gpus, maxVramGb }` where `status` is three-way: `'available'`, `'absent'` (no driver, or driver present with zero GPUs), or `'unknown'` (nvidia-smi exists but wouldn't answer — `available` is `null`, never `false`, so callers can say "couldn't detect" instead of lying about the hardware). `unknown` is not memoized so a transient driver hiccup retries. `parseNvidiaSmiGpus(stdout)` is the pure CSV parser (a `[N/A]` VRAM column yields `vramGb: null`, not a dropped GPU). Gates the image-to-3D `local-cuda` lane and the Windows FLUX.2 CUDA-torch wheel choice (`pythonSetup.js#hasNvidiaGpu`). `detectCudaComputeCapability()` / cached `getCudaComputeCapability()` are a SEPARATE `nvidia-smi` query (`--query-gpu=name,compute_cap,memory.total`, parsed by `parseNvidiaSmiComputeCaps`) returning `primaryComputeCap` — the arch of the LARGEST card, since a render uses one GPU — for build flags like NATTEN's `NATTEN_CUDA_ARCH` and SGLang provider filtering; kept separate because an older driver rejects `compute_cap` and would fail the whole VRAM query with it. `detectCudaUtilization()` / `getCudaUtilization()` add live per-GPU utilization on a short TTL. |diff --git a/server/lib/backupConfig.js b/server/lib/backupConfig.jsnew file mode 100644index 0000000000..b2f5c15aaf--- /dev/null+++ b/server/lib/backupConfig.js@@ -0,0 +1,37 @@+/**+ * Backup schedule defaults — the SINGLE declaring module (#6632).+ *+ * The backup settings slice is stored sparsely: a user who only ever typed a+ * destination has no `enabled` and no `cronExpression` on disk. Before this+ * module the scheduler and the Settings screen each invented their own answer+ * for those omissions (server: enabled + midnight; client: disabled + 02:00),+ * so a destination-only install ran nightly backups while the screen claimed+ * they were off — and saving any unrelated backup preference wrote the+ * screen's invented values back, cancelling the schedule.+ *+ * The server's interpretation is the compatible one and is preserved here:+ * omitted `enabled` means ENABLED, a missing/blank cron means midnight, and no+ * destination still means nothing is scheduled. This is read-time resolution+ * only — nothing on disk changes, and a sparse stored shape stays valid.+ *+ * Pure and dependency-free so both the scheduler and the settings route can+ * use it without dragging a service graph into leaf suites.+ */++/** Cron expression used when the stored backup settings omit one. */+export const DEFAULT_BACKUP_CRON = '0 0 * * *';++/**+ * 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 }}+ * `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.+ */+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) };+}diff --git a/server/lib/index.js b/server/lib/index.jsindex 06e103bbc3..465b64e1f1 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -485,6 +485,7 @@ export * from './textUtils.js';export * from './vaultCrypto.js';// === Model & config ===+export * from './backupConfig.js';export * from './browserConfig.js';export * from './buildId.js';export * from './buildIdentity.js';diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 91ae169a40..9d9699a189 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1,4 +1,5 @@import { CREDENTIALS } from './credentialRegistry.js';+import { DEFAULT_BACKUP_CRON } from './backupConfig.js';import { z } from 'zod';import { ServerError } from './errorHandler.js';import { partialWithoutDefaults, emptyToUndefined, emptyToNull, optionalBooleanMap } from './zodCompat.js';@@ -870,9 +871,13 @@ export const mediaSketchSaveSchema = z.object({// 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.+// The enabled/cron defaults here are the SAME interpretation `backupConfig.js`+// declares (omitted enabled = enabled, blank cron = midnight) and are sourced+// from it, so the boundary schema can never drift from the module the scheduler+// and the settings GET both resolve through (#6632).export const backupConfigSchema = z.object({destPath: z.string().nullable().optional(),- cronExpression: z.string().optional(),+ cronExpression: z.string().optional().default(DEFAULT_BACKUP_CRON),enabled: z.boolean().optional().default(true),excludePaths: z.array(z.string()).optional().default([]),disabledDefaultExcludes: z.array(z.string()).optional().default([])diff --git a/server/routes/settings.js b/server/routes/settings.jsindex eade9da86d..bca8de3f66 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -19,6 +19,7 @@ import { ensureEidoverseHost } from '../services/eidoverseHost.js';import { isGitHubRepoUrl } from '../lib/repoUrl.js';import { asyncHandler } from '../lib/errorHandler.js';import { isPlainObject } from '../lib/objects.js';+import { resolveBackupConfig } from '../lib/backupConfig.js';import { DEFAULT_UNTRUSTED_CONTENT_POLICY, untrustedContentSettingsSchema } from '../lib/untrustedContent.js';import { agentContextSettingsSchema } from '../lib/agentContextValidation.js';import { EFFORT_LEVELS } from '../lib/providerModels.js';@@ -135,13 +136,32 @@ const mergeFederationSlice = (next, current) => {return next;};+// The backup slice is stored sparsely, so every response projects the EFFECTIVE+// schedule (`server/lib/backupConfig.js`) over the stored values. Without this the+// Settings screen had to guess what an omitted `enabled`/`cronExpression` meant,+// guessed the opposite of the scheduler, and then saved its guess back — silently+// cancelling a destination-only install's nightly backup (#6632). The stored keys+// stay sparse on disk; only the transport carries the resolved view.+const projectEffectiveBackup = (safe) => {+ const effective = resolveBackupConfig(safe.backup);+ return {+ ...safe,+ backup: {+ ...safe.backup,+ destPath: effective.destPath,+ enabled: effective.enabled,+ cronExpression: effective.cronExpression+ }+ };+};+// Single sanitizer every settings response (GET load + PUT save) runs through,// so a leak can't reappear on one path after being closed on the other: strip-// the top-level `secrets` hierarchy, redact external tokens (#1821), then-// decorate server-authoritative bounds.+// the top-level `secrets` hierarchy, redact external tokens (#1821), decorate+// server-authoritative bounds, then resolve the sparse backup schedule.const sanitizeSettingsForResponse = (settings) => {const { secrets, ...safe } = settings;- return decorateBounds(redactExternalTokens(safe));+ return projectEffectiveBackup(decorateBounds(redactExternalTokens(safe)));};// GET /api/settingsdiff --git a/server/routes/settings.test.js b/server/routes/settings.test.jsindex ed201b47fd..400c5fe826 100644--- a/server/routes/settings.test.js+++ b/server/routes/settings.test.js@@ -818,3 +818,54 @@ describe('Settings routes — optional networking preference', () => {expect(store.networkSetupPreference).toBe('none');});});++describe('Settings routes — backup schedule resolution (#6632)', () => {+ beforeEach(() => {+ store = {};+ vi.clearAllMocks();+ });++ // The stored slice is sparse — the user only ever typed a destination. The+ // screen used to read that as "disabled, 02:00" while the scheduler read it as+ // "enabled, midnight", so the screen's next save cancelled a running schedule.+ it('projects the scheduler-compatible effective schedule for a destination-only config', async () => {+ store = { backup: { destPath: '/example-backups' } };+ const res = await request(buildApp()).get('/api/settings');+ expect(res.body.backup).toMatchObject({+ destPath: '/example-backups',+ enabled: true,+ cronExpression: '0 0 * * *'+ });+ });++ it('leaves an explicit disable and a custom cron untouched', async () => {+ store = { backup: { destPath: '/example-backups', enabled: false, cronExpression: '0 3 * * *' } };+ const res = await request(buildApp()).get('/api/settings');+ expect(res.body.backup).toMatchObject({ enabled: false, cronExpression: '0 3 * * *' });+ });++ it('resolves a null destination when none is configured', async () => {+ const res = await request(buildApp()).get('/api/settings');+ expect(res.body.backup).toMatchObject({ destPath: null, enabled: true, cronExpression: '0 0 * * *' });+ });++ // 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 () => {+ store = { backup: { destPath: '/example-backups' } };+ await request(buildApp()).get('/api/settings');+ expect(store.backup).toEqual({ destPath: '/example-backups' });+ });++ // The round trip the bug actually took: read the effective values, edit only an+ // exclusion, save. The saved slice must still register the same schedule.+ it('keeps schedule eligibility when only an exclusion is edited and saved back', async () => {+ store = { backup: { destPath: '/example-backups' } };+ const loaded = await request(buildApp()).get('/api/settings');+ const saved = await request(buildApp())+ .put('/api/settings')+ .send({ backup: { ...loaded.body.backup, excludePaths: ['/scratch'] } });+ expect(saved.status).toBe(200);+ expect(store.backup).toMatchObject({ enabled: true, cronExpression: '0 0 * * *', destPath: '/example-backups' });+ });+});diff --git a/server/services/backupScheduler.js b/server/services/backupScheduler.jsindex e9b3a5e9ec..cb7e3872cc 100644--- a/server/services/backupScheduler.js+++ b/server/services/backupScheduler.js@@ -12,9 +12,9 @@ import { schedule, cancel } from './eventScheduler.js';import { getSettings, settingsEvents } from './settings.js';import { runBackup } from './backup.js';import { getUserTimezone } from './userTimezone.js';+import { resolveBackupConfig } from '../lib/backupConfig.js';const EVENT_ID = 'backup-daily';-const DEFAULT_CRON = '0 0 * * *';// Registration state, so an unrelated settings save is a cheap no-op and a// cancel only fires when a cron is actually registered.@@ -26,10 +26,9 @@ let lastSignature = null;* should be inactive (explicitly disabled, or no destination configured).*/function registrationInputs(settings) {- const backup = settings?.backup;- if (backup?.enabled === false) return null;- if (!backup?.destPath) return null;- return { cron: backup.cronExpression || DEFAULT_CRON };+ const effective = resolveBackupConfig(settings?.backup);+ if (!effective.scheduled) return null;+ return { cron: effective.cronExpression };}/**@@ -82,19 +81,19 @@ export async function syncBackupSchedule(settings) {timezone,handler: async () => {const fresh = await getSettings();- if (fresh.backup?.enabled === false) {+ const effective = resolveBackupConfig(fresh.backup);+ if (!effective.enabled) {console.log('💾 Backup scheduler: disabled since registration — skipping run');return;}- const destPath = fresh.backup?.destPath;- if (!destPath) {+ if (!effective.destPath) {console.log('💾 Backup scheduler: destPath cleared since registration — skipping run');return;}const excludePaths = fresh.backup?.excludePaths || [];const disabledDefaultExcludes = fresh.backup?.disabledDefaultExcludes || [];console.log('💾 Backup scheduler: running scheduled backup');- await runBackup(destPath, null, { excludePaths, disabledDefaultExcludes });+ await runBackup(effective.destPath, null, { excludePaths, disabledDefaultExcludes });},metadata: { source: 'backupScheduler' }});diff --git a/server/services/backupScheduler.test.js b/server/services/backupScheduler.test.jsindex 5a098f1c78..4250c6576d 100644--- a/server/services/backupScheduler.test.js+++ b/server/services/backupScheduler.test.js@@ -245,3 +245,52 @@ describe('settings:updated re-sync', () => {expect(cancel).not.toHaveBeenCalled();});});++describe('backup schedule defaults (#6632)', () => {+ beforeEach(() => {+ stopBackupScheduler();+ vi.clearAllMocks();+ });++ // A destination-only config is the shape a user who never touched the toggle+ // has on disk. It must schedule — that is the behavior the settings GET now+ // reports, and the compatibility contract this change preserves.+ it('registers midnight for a destination-only configuration', async () => {+ getSettings.mockResolvedValue({ backup: { destPath: '/example-backups' } });+ await startBackupScheduler();+ expect(schedule).toHaveBeenCalledTimes(1);+ expect(schedule.mock.calls[0][0]).toMatchObject({ cron: '0 0 * * *' });+ });++ // The regression itself: the Settings screen reads the resolved values and+ // saves them back verbatim when the user edits something unrelated. Feeding+ // that saved slice into registration must not change what is scheduled.+ it('keeps the same registration when the resolved values are saved back', async () => {+ getSettings.mockResolvedValue({ backup: { destPath: '/example-backups' } });+ await startBackupScheduler();+ const first = schedule.mock.calls[0][0].cron;++ // What the settings GET now hands the screen, plus the unrelated edit.+ settingsEvents.emit('settings:updated', {+ backup: { destPath: '/example-backups', enabled: true, cronExpression: '0 0 * * *', excludePaths: ['/scratch'] }+ });+ // The re-sync runs on the event bus, so let its promise settle before asserting.+ await new Promise(resolve => setTimeout(resolve, 0));+ expect(first).toBe('0 0 * * *');+ // Identical registration inputs → the signature guard makes this a no-op.+ // A cancel here is the bug: the screen's save disabling a live schedule.+ expect(cancel).not.toHaveBeenCalled();+ expect(schedule).toHaveBeenCalledTimes(1);+ });++ // The handler re-reads settings, so it needs the same interpretation as+ // registration — otherwise a sparse config registers but never runs.+ it('runs the backup when the re-read settings omit enabled', async () => {+ getSettings.mockResolvedValue({ backup: { destPath: '/example-backups' } });+ await startBackupScheduler();+ await schedule.mock.calls[0][0].handler();+ expect(runBackup).toHaveBeenCalledWith('/example-backups', null, {+ excludePaths: [], disabledDefaultExcludes: []+ });+ });+});