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

test: cover backup getState/saveState default recovery and write-queue serialization (#3916)

[._.]/ Adam Eivy5cf2d091e48e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c8e451037e..a2561a57dd 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -88,3 +88,4 @@
- Unsaved SongBook editor drafts survive a sidebar click, a ⌘K jump, voice nav and the browser Back button. The editor already deferred its own exits — the View toggle and the "All songs" link — behind an inline discard confirm, but anything that left through the router without touching those controls unmounted the editor and dropped the sheet text and practice notes silently, which is the same data loss through a different door. The client now mounts a react-router data router (the existing route tree hangs unchanged under one splat route, so no page needed rewriting), which makes `useBlocker` available, and the guard ships as a shared `useUnsavedChangesGuard(isDirty)` hook: it parks the navigation, hands the page `blocked` / `proceed()` / `reset()` so the page renders its own inline confirm rather than a `window.confirm`, and arms `beforeunload` for tab close and reload. A parked navigation that settles clean — the user hits Save with the confirm up — runs instead of being swallowed, a navigation that only changes search params on the same page is never blocked, and a ⌘-click that opens a second tab still leaves the editor standing untouched.
- Unsaved edits in the pipeline manuscript editor and the writers-room work editor now survive an in-app navigation. Both carried a `beforeunload`-only guard, so a tab close or reload asked before dropping the draft but a sidebar link, a ⌘K jump, a voice `ui_navigate` or the browser Back button unmounted the editor and discarded the work silently — manuscript sections only persist onBlur, so a section typed into and left without blurring was gone. Both now adopt the shared `useUnsavedChangesGuard` hook and render an inline Discard / Keep editing confirm (never a `window.confirm`), with the local `beforeunload` effects dropped in favour of the hook's. The manuscript editor is a splat route where switching issue tabs changes the pathname without leaving the editor, so the hook grew an `isSameView(from, to)` option that exempts an editor's own in-page moves: switching between issues with unsaved text raises nothing, while leaving the manuscript entirely still parks the navigation behind the confirm, and discarding restores each section to its last server-confirmed content before the navigation runs.
- A merge follow-up that successfully lands its PR is no longer recorded as a failure. These runs exist to merge one pull request: they make no commit, are told to exit once the PR reads `MERGED`, and on Antigravity often skip the completion sentinel — so the idle reaper had only proxies to judge them by, and every proxy got it wrong. Their prompt quotes `gh pr checks`, `gh pr merge` and `--delete-branch`, which the TUI echoes back, which latches the swarm merge-queue tracker before any work happens; the finished agent then sat silent for the tracker's 15-minute grace and was reaped as "idled out in the merge queue — it likely died mid-merge", twice retried, and finally blocked on max retries with a high-priority "PR left open" notification naming a PR that had merged fifteen minutes into the first attempt. The reaper now asks the forge the actual question — once a follow-up run has been quiet for its normal idle window, it checks whether its PR merged, and finalises on that answer. A `gh` that cannot be reached still counts as "we could not ask" rather than "not merged", so every existing verdict is untouched when the forge is unavailable, and a follow-up whose PR genuinely did not land still surfaces as needs-manual-finish. The reaper's branch matrix also moved out of the interval body into a pure function the tests now call directly, replacing a hand-maintained copy of that logic inside the test file.
+- The backup service's persisted state file is now covered by tests. `getState` returning the default state when `data/backup/state.json` is missing or truncated mid-write, `saveState` merging a partial patch into what is already on disk, and — the one that actually matters — two concurrent `saveState` calls (a run finishing while the scheduler stamps a status) serializing through the write queue so neither loses the other's fields. The concurrency test fails if the queue is removed, and all of it runs against a real temp directory rather than a mocked filesystem.
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 7149163836..b2deb97310 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -9,9 +9,13 @@
* - dumpPostgres — status classification (ok / skipped / failed) so the
* caller can distinguish "no PG configured" from "configured but the dump
* failed", including the empty-dump verification path.
+ * - getState / saveState — the persisted backup-state read-merge-write cycle:
+ * default-state recovery when state.json is missing or corrupted, patch
+ * merging, and the createFileWriteQueue serialization that keeps two
+ * concurrent saveState() callers from clobbering each other's fields.
*/
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// Mock the DB health check and child_process.spawn before importing backup.js
vi.mock('../lib/db.js', () => ({
@@ -730,3 +734,147 @@ describe('restoreSnapshot subdirFilter guard', () => {
}
});
});
+
+// getState / saveState — the persisted `data/backup/state.json` read-merge-write
+// cycle (issue #3916). Runs against a real temp dir with `PATHS.data` re-pointed,
+// so the assertions cover the ACTUAL bytes on disk (real readJSONFile +
+// atomicWrite), not a mocked persistence layer.
+describe('getState and saveState', () => {
+ let tmpRoot;
+ let backup;
+ let writeLog;
+
+ beforeEach(async () => {
+ // Same spy hygiene as the generateManifest suite: earlier suites leave
+ // persistent fs spies installed, and these tests hit the real filesystem.
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ const realFs = await vi.importActual('fs/promises');
+ fs.stat.mockImplementation(realFs.stat);
+ fs.readFile.mockImplementation(realFs.readFile);
+ vi.resetModules();
+
+ const { mkdtemp } = await import('fs/promises');
+ const { tmpdir } = await import('os');
+ const { join } = await import('path');
+ tmpRoot = await mkdtemp(join(tmpdir(), 'portos-backup-state-'));
+ writeLog = [];
+
+ // `vi.doMock` is NOT hoisted, so the factory can close over `tmpRoot` and
+ // `writeLog`. Only PATHS.data and atomicWrite are overridden — readJSONFile,
+ // ensureDir and the rest stay real.
+ vi.doMock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, data: tmpRoot },
+ // Bracket the real write with log markers and a delay, so an unqueued
+ // read-merge-write would visibly interleave (start/start/end/end).
+ atomicWrite: async (filePath, data) => {
+ writeLog.push(`start:${data?.status}`);
+ await new Promise((r) => setTimeout(r, 10));
+ const result = await actual.atomicWrite(filePath, data);
+ writeLog.push(`end:${data?.status}`);
+ return result;
+ }
+ };
+ });
+ backup = await import('./backup.js');
+ });
+
+ afterEach(async () => {
+ vi.doUnmock('../lib/fileUtils.js');
+ vi.resetModules();
+ const { rm } = await import('fs/promises');
+ if (tmpRoot) await rm(tmpRoot, { recursive: true, force: true });
+ });
+
+ // Read the raw persisted state file (no service helpers) so the assertions
+ // describe what a *restore* or another process would actually see.
+ async function readStateFile() {
+ const { readFile } = await import('fs/promises');
+ const { join } = await import('path');
+ return JSON.parse(await readFile(join(tmpRoot, 'backup', 'state.json'), 'utf-8'));
+ }
+
+ const DEFAULTS = {
+ lastRun: null,
+ status: 'never',
+ lastSnapshotId: null,
+ filesChanged: 0,
+ pgBackup: null,
+ error: null
+ };
+
+ it('returns the default state when state.json does not exist', async () => {
+ expect(await backup.getState()).toEqual(DEFAULTS);
+ });
+
+ it('returns the default state when state.json holds invalid JSON', async () => {
+ const { mkdir, writeFile } = await import('fs/promises');
+ const { join } = await import('path');
+ await mkdir(join(tmpRoot, 'backup'), { recursive: true });
+ // Truncated mid-object — the shape a crash during a non-atomic write leaves.
+ await writeFile(join(tmpRoot, 'backup', 'state.json'), '{"status":"ok","filesChanged":');
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ expect(await backup.getState()).toEqual(DEFAULTS);
+ });
+
+ it('merges a patch into existing state and persists it to disk', async () => {
+ await backup.saveState({ lastRun: '2026-01-01T00:00:00Z', status: 'ok', filesChanged: 7 });
+ const updated = await backup.saveState({ status: 'degraded', error: 'pg dump failed' });
+
+ // The second patch must not drop the first patch's untouched fields.
+ expect(updated).toEqual({
+ ...DEFAULTS,
+ lastRun: '2026-01-01T00:00:00Z',
+ status: 'degraded',
+ filesChanged: 7,
+ error: 'pg dump failed'
+ });
+ expect(await readStateFile()).toEqual(updated);
+ // A fresh read of the file agrees with the returned value.
+ expect(await backup.getState()).toEqual(updated);
+ });
+
+ it('serializes concurrent saveState calls so neither patch is clobbered', async () => {
+ const [first, second] = await Promise.all([
+ backup.saveState({ status: 'running', filesChanged: 10 }),
+ backup.saveState({ status: 'ok', lastSnapshotId: 'snap-2' })
+ ]);
+
+ // Queue order is call order: the first write sees only its own patch...
+ expect(first).toEqual({ ...DEFAULTS, status: 'running', filesChanged: 10 });
+ // ...and the second reads the FIRST one's committed image, not the pre-image.
+ expect(second).toEqual({
+ ...DEFAULTS,
+ status: 'ok',
+ filesChanged: 10,
+ lastSnapshotId: 'snap-2'
+ });
+
+ // No interleaving: each read-merge-write completes before the next starts.
+ expect(writeLog).toEqual(['start:running', 'end:running', 'start:ok', 'end:ok']);
+
+ // Last write wins on disk, with both patches' fields intact.
+ expect(await readStateFile()).toEqual(second);
+ });
+
+ it('keeps a rejected write from poisoning the queue for later callers', async () => {
+ const { writeFile } = await import('fs/promises');
+ const { join } = await import('path');
+ // A pre-existing FILE where the backup dir must go makes ensureDir throw,
+ // so the first saveState rejects mid-queue.
+ await writeFile(join(tmpRoot, 'backup'), 'not a directory');
+
+ await expect(backup.saveState({ status: 'running' })).rejects.toThrow();
+
+ const { rm } = await import('fs/promises');
+ await rm(join(tmpRoot, 'backup'));
+ // The queue tail must still accept work after the rejection.
+ const after = await backup.saveState({ status: 'ok' });
+ expect(after).toEqual({ ...DEFAULTS, status: 'ok' });
+ expect(await readStateFile()).toEqual(after);
+ });
+});