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: re-sync the backup cron on settings save so post-boot enablement schedules (#3910)
[._.]/ Adam Eivy0a3c1fb63dca
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 08d14beecf..12bc578041 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,6 +6,7 @@## Fixed+- Turning on scheduled backups now actually schedules them. The daily backup cron was registered once at server start, so if backups were off — or no destination folder was set — when PortOS booted, enabling them in Backup settings did nothing until the server was restarted, and no backup ever ran. The schedule is now kept in sync with your settings: enabling backups or picking a destination registers it immediately, editing the schedule re-registers it, and turning backups off cancels it.- Canon entry cards in a universe bible are usable on a phone again. The card's icon action strip sat as a full-height column beside the entry's content, so on a phone it squeezed the description box and every collapsible editor under it to about a third of the card — the description was clipped after a few words and the "Reveal timing" and "Outfits" headers wrapped into tall centered stacks. The action strip now shares the entry's title row and the content spans the full card width beneath it. Long entry names wrap instead of being cut off mid-word (variation and reference-board rows on the same page too), a collapsed "Outfits" header clips its outfit list to one line, and the character colour rows leave their hex field enough room for the description beside it.- Wrapped labels inside buttons no longer render as a centered ragged stack. Browsers center button text by default, which is invisible while a label fits on one line and only shows up once it wraps — so it surfaced on phones, in section headers across the app, and not on desktop. Buttons that lay their contents out in a row now read left-aligned unless they explicitly ask to be centered.- Voice dictation into the Shell terminal no longer garbles what you said. Apple dictation streams progressively refined guesses and rewrites what it already typed ("determin" → "determine" → "determines"); the terminal forwarded every insertion but none of the matching deletions, so a dictated sentence arrived at the prompt as an accumulating pile-up ("ddedeterdetermindeterminedetermines if any code…"). Dictation edits are now translated into the deletions and insertions a terminal understands, so the prompt shows the sentence you dictated.diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 93dfc3179e..07f6226677 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -30,7 +30,7 @@ A backup run (`runBackup` in `server/services/backup.js`) writes to:- **Non-overridable** (`overridable: false`): browser CDP profile, agent worktrees — caches with no irreplaceable user data; never backed up.- **Overridable** (`overridable: true`): LoRA weight files, cloned repos, reference repos, browser downloads — re-downloadable; the user can opt back in from the Backup settings UI via `disabledDefaultExcludes`.-The effective exclude list is computed by the pure `computeEffectiveExcludes()` helper (unit-tested in `backup.test.js`). The scheduled cron handler in `backupScheduler.js` re-reads settings on every run, so `destPath`, `excludePaths`, `disabledDefaultExcludes`, and `enabled` all take effect on the next run without a restart.+The effective exclude list is computed by the pure `computeEffectiveExcludes()` helper (unit-tested in `backup.test.js`). The scheduled cron handler in `backupScheduler.js` re-reads settings on every run, so `destPath`, `excludePaths`, `disabledDefaultExcludes`, and `enabled` all take effect on the next run without a restart. See [Scheduling & status](#scheduling--status) for how the cron registration itself tracks settings.#### Why every exclude must be anchored with a leading `/`@@ -85,6 +85,7 @@ Separate from snapshot restore: `server/routes/database.js` can copy data **betw## Scheduling & status- Daily backups are driven by `backupScheduler.js` via the `backup-daily` cron event; `getNextRunTime()` reports the next run.+- **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.## See alsodiff --git a/server/services/backupScheduler.js b/server/services/backupScheduler.jsindex 3cedf8a5b2..25741e0be6 100644--- a/server/services/backupScheduler.js+++ b/server/services/backupScheduler.js@@ -2,70 +2,122 @@* Backup Scheduler Service** Registers a daily cron job for automated backups using eventScheduler.- * Mirrors the brainScheduler.js pattern.+ * The registration is re-synced on every settings save (via settings.js's+ * `settingsEvents` bus), so enabling backups — or setting `destPath` — after+ * boot registers the cron immediately instead of waiting for a restart, and+ * disabling backups cancels it.*/import { schedule, cancel } from './eventScheduler.js';-import { getSettings } from './settings.js';+import { getSettings, settingsEvents } from './settings.js';import { runBackup } from './backup.js';import { getUserTimezone } from '../lib/timezone.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.+let registered = false;+let lastSignature = null;+/**- * Start the backup scheduler.- * Reads backup settings and registers a daily cron job with eventScheduler.- * No-ops if backup is disabled or destPath is not configured.+ * The registration-affecting slice of settings: `null` when backup scheduling+ * should be inactive (explicitly disabled, or no destination configured).*/-export async function startBackupScheduler() {- const settings = await getSettings();+function registrationInputs(settings) {+ const backup = settings?.backup;+ if (backup?.enabled === false) return null;+ if (!backup?.destPath) return null;+ return { cron: backup.cronExpression || DEFAULT_CRON, destPath: backup.destPath };+}- if (settings.backup?.enabled === false) {- console.log('💾 Backup scheduler: disabled in settings — skipping');- return;- }+/**+ * (Re)synchronize the backup cron to match the given settings snapshot.+ * Idempotent — safe to call at boot and after every settings save. Registering+ * a cron fires nothing until its expression elapses, so this never triggers a+ * backup by itself.+ * @param {object} [settings] - a settings snapshot; re-read when omitted+ * @returns {Promise<boolean>} whether a cron is registered after the sync+ */+export async function syncBackupSchedule(settings) {+ const current = settings || await getSettings().catch(() => null);+ const inputs = registrationInputs(current);+ const timezone = await getUserTimezone().catch(() => 'UTC');- if (!settings.backup?.destPath) {- console.log('💾 Backup scheduler: no destPath configured — skipping');- return;- }+ // Only `cron` + `timezone` + active/inactive are baked into the registration;+ // destPath and the exclude lists are re-read by the handler on every run.+ const signature = JSON.stringify({ active: Boolean(inputs), cron: inputs?.cron ?? null, tz: timezone });+ if (signature === lastSignature) return registered;+ lastSignature = signature;- const cronExpression = settings.backup?.cronExpression || '0 0 * * *';- const timezone = await getUserTimezone();+ if (!inputs) {+ if (registered) {+ cancel(EVENT_ID);+ registered = false;+ console.log('💾 Backup scheduler: disabled or destPath cleared — cron cancelled');+ } else {+ console.log('💾 Backup scheduler: disabled or no destPath configured — nothing scheduled');+ }+ return false;+ }- // 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()` replaces an event with the same id, so a changed cron+ // expression cleanly re-registers. destPath, excludePaths and+ // disabledDefaultExcludes are re-read inside the handler so toggles saved in+ // the Settings UI take effect on the next scheduled run.schedule({- id: 'backup-daily',+ id: EVENT_ID,type: 'cron',- cron: cronExpression,+ cron: inputs.cron,timezone,handler: async () => {- const current = await getSettings();- if (current.backup?.enabled === false) {+ const fresh = await getSettings();+ if (fresh.backup?.enabled === false) {console.log('💾 Backup scheduler: disabled since registration — skipping run');return;}- const destPath = current.backup?.destPath;+ const destPath = fresh.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 || [];+ const excludePaths = fresh.backup?.excludePaths || [];+ const disabledDefaultExcludes = fresh.backup?.disabledDefaultExcludes || [];console.log('💾 Backup scheduler: running scheduled backup');await runBackup(destPath, null, { excludePaths, disabledDefaultExcludes });},metadata: { source: 'backupScheduler' }});+ registered = true;++ console.log(`💾 Backup scheduler: registered daily backup at cron "${inputs.cron}"`);+ return true;+}++// Re-sync on every settings save rather than from the settings route — keeps+// the HTTP handler decoupled from the backup graph (mirrors+// seriesAutopilotScheduler.js). The signature guard makes unrelated saves free.+settingsEvents.on('settings:updated', (cleaned) => {+ syncBackupSchedule(cleaned).catch(err =>+ console.error(`❌ Backup schedule re-sync failed: ${err.message}`));+});- console.log(`💾 Backup scheduler: registered daily backup at cron "${cronExpression}" -> ${settings.backup.destPath}`);+/**+ * Boot entry point — registers the cron once at startup if backup is+ * configured. Later enable/disable/cron edits are picked up by the+ * `settings:updated` subscription above.+ */+export async function startBackupScheduler() {+ return syncBackupSchedule();}/*** Stop the backup scheduler by cancelling the scheduled event.*/export function stopBackupScheduler() {- cancel('backup-daily');+ cancel(EVENT_ID);+ registered = false;+ lastSignature = null;console.log('💾 Backup scheduler: stopped');}diff --git a/server/services/backupScheduler.test.js b/server/services/backupScheduler.test.jsindex 7754151370..a089554589 100644--- a/server/services/backupScheduler.test.js+++ b/server/services/backupScheduler.test.js@@ -6,6 +6,9 @@* 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.+ *+ * Also covers the registration re-sync (#3910): enabling backups or setting+ * destPath after boot must register the cron without a restart.*/import { describe, it, expect, vi, beforeEach } from 'vitest';@@ -15,8 +18,22 @@ vi.mock('./eventScheduler.js', () => ({cancel: vi.fn()}));+// The scheduler subscribes to `settings:updated` at module load, so the mock+// needs a working emitter the re-sync tests below can fire. `vi.hoisted` runs+// above the import block, so it is built by hand rather than importing+// node:events up there.+const { settingsEvents } = vi.hoisted(() => {+ const listeners = new Map();+ return {+ settingsEvents: {+ on: (event, fn) => { listeners.set(event, [...(listeners.get(event) || []), fn]); },+ emit: (event, payload) => { for (const fn of listeners.get(event) || []) fn(payload); }+ }+ };+});vi.mock('./settings.js', () => ({- getSettings: vi.fn()+ getSettings: vi.fn(),+ settingsEvents}));vi.mock('./backup.js', () => ({@@ -27,13 +44,16 @@ vi.mock('../lib/timezone.js', () => ({getUserTimezone: vi.fn().mockResolvedValue('UTC')}));-import { schedule } from './eventScheduler.js';+import { schedule, cancel } from './eventScheduler.js';import { getSettings } from './settings.js';import { runBackup } from './backup.js';-import { startBackupScheduler } from './backupScheduler.js';+import { startBackupScheduler, stopBackupScheduler } from './backupScheduler.js';describe('startBackupScheduler', () => {beforeEach(() => {+ // Registration state is module-level and persists across tests in this+ // file — reset it (and the mock call log it dirties) before each case.+ stopBackupScheduler();vi.clearAllMocks();});@@ -123,3 +143,76 @@ describe('startBackupScheduler', () => {expect(runBackup).not.toHaveBeenCalled();});});++/**+ * Regression (#3910): before this, registration happened ONCE at boot. A user+ * who enabled backups (or set destPath) afterwards got no scheduled run at all+ * until the server process was restarted.+ */+describe('settings:updated re-sync', () => {+ const emitSettings = async (settings) => {+ settingsEvents.emit('settings:updated', settings);+ // The listener is async (it awaits getUserTimezone) — let it settle.+ await new Promise(resolve => setImmediate(resolve));+ };++ beforeEach(() => {+ stopBackupScheduler();+ vi.clearAllMocks();+ });++ it('registers the cron when backup is enabled after boot', async () => {+ getSettings.mockResolvedValue({ backup: { enabled: false } });+ await startBackupScheduler();+ expect(schedule).not.toHaveBeenCalled();++ await emitSettings({ backup: { enabled: true, destPath: '/dest', cronExpression: '0 4 * * *' } });++ expect(schedule).toHaveBeenCalledTimes(1);+ expect(schedule.mock.calls[0][0]).toMatchObject({ id: 'backup-daily', cron: '0 4 * * *' });+ });++ it('registers the cron when destPath is configured after boot', async () => {+ getSettings.mockResolvedValue({ backup: { enabled: true } });+ await startBackupScheduler();+ expect(schedule).not.toHaveBeenCalled();++ await emitSettings({ backup: { enabled: true, destPath: '/dest' } });++ expect(schedule).toHaveBeenCalledTimes(1);+ expect(schedule.mock.calls[0][0]).toMatchObject({ cron: '0 0 * * *' });+ });++ it('re-registers when the cron expression changes', async () => {+ getSettings.mockResolvedValue({ backup: { enabled: true, destPath: '/dest', cronExpression: '0 1 * * *' } });+ await startBackupScheduler();++ await emitSettings({ backup: { enabled: true, destPath: '/dest', cronExpression: '0 5 * * *' } });++ expect(schedule).toHaveBeenCalledTimes(2);+ expect(schedule.mock.calls[1][0]).toMatchObject({ id: 'backup-daily', cron: '0 5 * * *' });+ });++ it('cancels the cron when backup is disabled after boot', async () => {+ getSettings.mockResolvedValue({ backup: { enabled: true, destPath: '/dest' } });+ await startBackupScheduler();+ expect(schedule).toHaveBeenCalledTimes(1);++ await emitSettings({ backup: { enabled: false, destPath: '/dest' } });++ expect(cancel).toHaveBeenCalledWith('backup-daily');+ });++ it('is a no-op for a save that does not touch backup registration', async () => {+ getSettings.mockResolvedValue({ backup: { enabled: true, destPath: '/dest' } });+ await startBackupScheduler();+ expect(schedule).toHaveBeenCalledTimes(1);++ // destPath and excludes are re-read by the handler, so a change to them+ // must not churn the registration.+ await emitSettings({ backup: { enabled: true, destPath: '/other', excludePaths: ['x/'] } });++ expect(schedule).toHaveBeenCalledTimes(1);+ expect(cancel).not.toHaveBeenCalled();+ });+});