Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

30.7 KB
Raw Blame

Issue 650 desktop scheduled backup implementation scope

简体中文

Problem and outcome

Implement Issue #650 following the scheduled backup and encrypted recovery design. Desktop saves the current account's synchronized knowledge base to a chosen local directory, optionally password-encrypted, and restores it to a new instance without the original instance.

Changes affect desktop background work, shared archives, settings and restore entry points, backup reads, and a new migration. The main risks are write disruption by revision triggers, unreadable archives, plaintext disclosure, and accidental backup deletion. Disabling stops new tasks and keeps files; application rollback retains additive database structures and faulty triggers require a subsequent corrective migration. Validate old-database upgrades, platform directories/credentials, and recovery separately.

When a resource-restore request returns 503, archive consumer errors are rewritten as invalidZip, and desktop IPC then drops the HTTP status. Preserve the real failure and record its request diagnostics through the existing desktop log. The main risks are error-classification regressions and sensitive diagnostic fields. Keep ZIP-reader failures classified as invalid archives and use selected fields plus existing redaction. Reverting this item restores the old error path without changing archives or restored data.

An empty Worker behind local Wrangler 4.112.0 also returned 503 at a fixed five-second cadence. Its development proxy has an idle-connection race and misclassifies the error source. Use the repository's existing Bun dependency-patch mechanism to repair local forwarding without retrying restore writes. The risk is local-proxy compatibility; limit connection changes to plain loopback HTTP, preserve remote/WebSocket behavior, and roll back by removing the patch and its package/lockfile registration. Keep running services unchanged; actual business restore requires user acceptance after restarting the development service.

Desktop has duplicate export/backup entry points, no direct actions on completed archives, and creates redundant archives for unchanged data. Unify backup and restore while retaining one-off plain/encrypted output and separating source checks from actual archive creation. Risks are name collisions, file ownership and incorrect skipping; bind operations to the current backup set and use the existing source-revision protocol plus an available previous archive. Rollback does not migrate or rename old archives. Validate in isolated directories without operating on user instances, processes or files.

Expanding backup settings adds a vertical scrollbar, narrowing the card and rewrapping content; settings below the archive list are also hard to find. Move the collapsed settings below status and above history, and reserve scrollbar space in both wide and narrow settings-page scroll containers. Risk is limited to spacing and narrow-window layout. Reverting these two layout changes restores the previous arrangement without changing collapsed defaults, configuration, backup or restore behavior. Check actual expanded/collapsed widths, keyboard operation and narrow-window rendering.

The contribution branch starts from current official main and carries only this feature, not deployment-fork snapshot history. Give the new backup migration an unused increasing number, retaining every published upstream migration, notebook-appearance field and locale catalog. Integration risks are migration ordering, dropped archive fields and regressions in existing callers. Validate isolated old-database upgrades and old/new export/restore paths; rolling back code must not delete data or additive migration structures. Keep the original development checkout and user instances unchanged. Review B01–B19 for correctness, necessary complexity and actual UI behavior; record each evidence-backed behavior fix before implementing it.

Allowed behavior and acceptance

ID Behavior change Acceptance
B01 New numbered migration adds workspace backup_revision default 0; notebook, note, content, revision, resource and prompt inserts/updates/deletes advance the owning workspace in the original transaction. Resolve ownership before deletion and cover both sides of moves. API revisions are decimal strings; synchronization cursors stay unchanged. Upgrade real pre-migration data, then edit/sync/delete/restore; cover each entity, bulk operations and workspace isolation.
B02 Add /api/v1/backups/state and /api/v1/backups/data, resolving the workspace from existing authenticated backup access. Return protocol, identity, revision and counts; page by stable ID. Check revisions around pages and after attachments; return backup_source_changed on mismatch. Disable caching and lagging replica reads. New automatic backup requests an upgrade on old servers rather than weakening consistency. Actual routes/database/resource reads with concurrent changes, identity, permissions and complete pagination; old endpoints remain usable.
B03 New desktop backups read only current-account synchronized undeleted notes, hierarchy, tags/states, revisions, prompts and active attachments. No sync pushes or cache fallback; exclude Trash, credentials, deployment/share/form settings and unregistered external files. Validate attachment lengths and existing digests, computing missing digests while reading. Missing/mismatched files fail the task. Export and restore one dataset into a fresh instance; verify coverage and files. Offline/missing-resource failure preserves old archives.
B04 Share existing edgeever-zip v2 structure, retaining v1/v2 reads and nullable digests. Add pinned @zip.js/zip.js for ZIP64 with license notices, without unrelated compression replacement. Stream new desktop/large-archive paths with backpressure; retain the 128 MiB manual Web fallback and existing per-file limits. Existing archive tests and plain/ZIP64 round trips; real streams exceeding 4 GiB and ZIP64 entry-count boundaries; targeted memory observation.
B05 .edgeever.enc uses the designed 40-byte EDGB v1 header, AES-256-GCM, PBKDF2-HMAC-SHA256/600000 iterations, 32-byte key, random 16-byte salt/12-byte IV/16-byte tag and header AAD. Accept only the defined suite, preserve UTF-8 password bytes, and abort ZIP input beyond 2^36 - 32 bytes while retaining backups. Interoperability, wrong passwords, modified headers/ciphertext, truncation, unsupported parameters and length boundaries; failed authentication causes no restore writes.
B06 Main-process secure credentials bind to instance/account. No passwords in server requests, ordinary config, localStorage, logs, backup folders or saved-value UI. Pause encrypted automatic work for Linux basic_text or unavailable/locked storage; allow a one-time unsaved password run without plaintext fallback. Password changes affect new files only. Credential adapter and real-platform checks, cross-device password restore, failure and password-change behavior.
B07 Main-process scheduling, separate background execution and narrow IPC independent of the renderer. Initially automatic/encryption off, weekly, retain 5; intervals daily/weekly/biweekly/monthly and retention 3/5/10/20. Restore the account from the saved session in the main process at startup, without requiring renderer IPC. Check at startup/login-ready/resume/hourly, run first enable and catch up once; local-calendar scheduling recalculates on timezone changes. Lifecycle, month end, first enable and success records; settings close, renderer reload, tray and resume paths.
B08 Manual/scheduled runs share exclusion, configuration and validation; manual works with scheduling off. Cancel before configuration edits. Failure preserves success time; network/revision automatic retries wait at least an hour, manual retry is immediate. Action-required errors do not repeat dialogs. App exit cancels. Recheck enabled/due/backoff after acquiring exclusion for scheduled runs; cancel unfinished requests and release the worker when a task ends. Concurrent triggers, cancellation, retry, exit/restart and usable foreground editing.
B09 Scope configuration, immutable task context and records to instance/account, with a random local backupSetId. Switching/sign-out cancels; reject old-account operations during context transitions; late responses cannot publish, record success or prune. Default root is OS Documents/EdgeEver Backups, native directory selection and a backup-set subfolder, with UTC/random-ID automatic names; manual names follow B15. Actual account/instance and folder changes, late responses, other-account/device file preservation.
B10 Stream a unique same-directory .part, validate/flush, atomically publish and persist completion before retention and notification. Pre-publication failure removes only its temporary file, without pruning. Recover interrupted completion records by verification; allow an encrypted pending archive to be verified once using its original password without replacing the currently saved password. Delete only recorded completed files in the current set, not symlink targets or mtime-inferred ownership. Retention errors are separate warnings. Destination changes/disabling/reinstallation retain old files; report local completion only. Disk/permission/interruption/cancel/prune failure, publication recovery, ownership/retention and no plaintext in synchronized folders.
B11 Desktop backup card includes destination, interval, retention, encryption/password confirmation, run/cancel, folder, last-success/next-due/error and history/manual actions as specified in B15–B18, with a verification action for pending publications. Require matching nonempty passwords; show only saved status, synchronized coverage and future-only password changes. Reuse existing UI/Tooltip and all existing locale catalogs. Real settings/backup interactions, keyboard, state/errors and screenshots.
B12 Desktop import identifies ZIP/encrypted headers. The file picker starts in the currently configured actual backup directory (including its backup-set subfolder), while allowing selection elsewhere without creating directories or restricting import sources. Submit the password dialog as a form: Enter matches Unlock and check; empty passwords and pending submissions remain blocked. Keep the unlock dialog until decryption and archive checks succeed; show failures inline with retry, show check progress, disable password editing/repeated submission while checking, and cancel the check when closing the dialog. Isolate import errors and staging-cleanup warnings from automatic-backup state, preserving backup errors, warnings and success records. Classify legacy backup_decrypt_failed records as import errors only when no pending publication exists; retain the backup classification for pending-publication verification. Authenticate completely in a private directory before scanning format/paths/CRC/counts/relationships/files; confirm target instance/account/counts before writes. Preserve ID overwrite/unrelated data, retryable batch failure and final refresh. Unix staging 0700/0600, private Windows ACLs; clean registered plaintext on success/failure/cancel/crash. Preserve ownership registration when old staging/part cleanup fails; do not overwrite it with a new task until cleanup succeeds. Disconnect source and restore plain/encrypted archives to a fresh instance; cancellation/bad-file zero writes, partial restore retry, staging cleanup and old ZIP compatibility; verify the picker receives the current actual backup directory and still accepts native selections from elsewhere; exercise Enter/click with matching unlock inputs, empty/pending submission guards and cancellation in a real browser; exercise inline wrong-password errors, successful retry/confirmation, cancellation while checking, plain invalid archives and restore-error ownership; main-process tests cover preserved backup state, isolated cleanup warnings and legacy classification.
B13 ZIP reads, decompression and CRC failures remain invalidZip; preserve original entry-consumer and target-restore errors instead of treating them as corrupt archives. Desktop IPC/status retain HTTP status and server error code/message, with HTTP status shown beside the actual error. Log failed desktop backup/restore HTTP requests through existing desktop.log, including time, task kind/phase, method, query-free endpoint path, status and server error code/redacted message. For non-JSON failures use the HTTP status text; do not record headers, request bodies, raw response bodies, passwords, tokens or note content. Logging failures must not change task outcomes. Start each attachment upload initialization only when its first data chunk or empty-entry close is consumed, and await it immediately; a fast initialization rejection must follow the restore error path rather than terminate the Node worker as an unhandled rejection. Preserve cancellation, restore batches, existing retries and account isolation; add no retry/fallback and do not change filenames. First reproduce consumer-error misclassification. Real workers receive controlled JSON/non-JSON 503 responses for the third resource initialization, preserving status/message after the first two complete, without uploading the third or leaking staging files. Main-process checks cover selected/redacted log fields, unaffected task results if logging fails and persisted status. Browser shows HTTP 503 rather than invalid ZIP; existing CRC-damage rejection still passes. A real Node regression combines asynchronous archive reads with an immediately rejected upload initialization and retains the original status/code/message without an unhandled rejection.
B14 Use existing Bun patches and pin the current official Wrangler CLI 4.112.0. Forward ordinary loopback HTTP through an existing Miniflare service binding using Wrangler's bundled Undici with pipelining=0 and a fresh connection per request, avoiding the roughly five-second idle-close race; retain native forwarding for remote targets, HTTPS and Upgrade/WebSocket. Set the current Miniflare local loopback server's keepAliveTimeout and headersTimeout to 0 to avoid the same race before reaching the Node adapter; preserve response backpressure and stop reading the upstream stream when the downstream closes; retain its currently locked transitive version 4.20260714.0. Backport upstream PR #14593's origin comparison so unchanged-Worker connection errors are reported rather than disguised as restart 503s or parked GETs; preserve existing queues/503s during actual Worker replacement. Add no restore POST retries or other fallback, restart no running services, and change no business data, deployment commands, version number, archives or filenames. Reproduce current proxy 503s with an empty Worker, then check the same five-second cadence and an isolated instance after correction. Exercise the installed proxy's loopback HTTP behavior, unchanged WebSocket/remote forwarding, same-origin failure versus actual Worker replacement, and no non-idempotent retry; run existing Wrangler runner checks, updating their stale trigger inventory from 12 to 30 to include the added backup migration while retaining every single-line trigger check. Verify frozen-lockfile installation applies the patch automatically.
B15 Unify desktop into Backup and restore with Back up now and Restore from file; remove the standalone desktop ZIP export card, preserving Web export/import. A manual-run dialog defaults to an editable local timestamp name without a UUID; append .zip or .edgeever.enc for the selected format, stripping a supplied recognized extension. Reject empty names, path/control characters and Windows-invalid names; conflicts fail without overwriting. Encryption defaults to saved settings but overrides apply only to this run; request and confirm an unsaved password when needed. Cancel creates no job/file. Pending-publication verification keeps its original flow/name. Named output uses exclusive atomic publication; unsupported filesystem operations fail rather than falling back to overwrite. Tests first for main-process/IPC naming, extensions, invalid paths, preflight/publication conflicts, one-off encryption, cancellation and legacy calls; real plain/encrypted archive recovery. Browser covers Enter, cancel, errors and both formats.
B16 Show registered completed files in the current directory/set with name, time, size, encryption and Restore/Delete actions. Restore selects the registered file directly and reuses one unlock/check/target-confirmation controller without a picker; external archives use Restore from file. Confirm permanent deletion of the selected file, then remove its record; an externally removed file can have its stale record removed. Main process rejects unregistered names, paths, symlinks/replaced directories, stale accounts and busy operations. Failures preserve records with visible errors; other files remain untouched. Isolated file checks cover selection, deletion, missing files, retained records on failure and unknown/cross-account/symlink rejection. Browser covers row targeting, delete confirm/cancel and a single restore controller.
B17 Scheduled runs skip only when source instance/workspace identity and backupRevision, full backup configuration and saved-password generation match and the previous archive remains a registered regular file of the same size in the current directory. Missing comparison metadata, missing files or configuration changes create an archive. Configuration includes directory, interval, retention, enabled and encryption. Manual archives with one-off encryption/password overrides are not automatic-skip baselines. Manual runs always create an archive. Skips persist check time/no-change only, without changing archive success time, retention or archive notifications; a separate scheduling anchor advances to the next interval. Preserve hourly failure backoff and never treat cancellation as success. Revisions conservatively track writes, not semantic deduplication. Real worker reads state only and creates no file on no-change; source changes create an archive. Main-process checks cover legacy records, configuration/password changes, missing files, forced manual work, no skip pruning/success changes, restart scheduling and failure/cancel states.
B18 Above the list, always show the last actual successful archive, latest check time/result (success/no-change/failure/cancelled/running), and automatic-off or next scheduled check. No-change explicitly states that the existing backup is current. Failures retain last success and show their cause; import state remains separate. Account changes clear local dialogs/inputs. Inspect actual browser renders/screenshots for success, no-change, failure and automatic-off; verify persisted check records, account isolation and existing import-error isolation.
B19 Order the backup area as actions, status, initially collapsed backup settings, then local archives; keep the migration guide after the card. Reserve vertical scrollbar space in wide and narrow settings-page content containers so expanding/collapsing does not change card width. Do not fix the card width or change settings persistence, backup/restore/delete behavior, data or defaults. Reuse the isolated real-component browser fixture with settings-page layout. Check expand/collapse, keyboard operation, long names/paths, no narrow-window horizontal overflow, and working save/row actions. Retain dimensions/screenshots and run affected Web typecheck/build.
B20 Move the feature and listed fixes onto official main. Number the backup-revision migration 0080, preserving published migrations 0073–0079. Keep upstream notebook-appearance export/restore behavior and the added Russian catalog, including Russian text for this feature. Exclude deployment-fork history, unrelated version changes and local caches. Check the exact diff against official main; apply the added migration to a real isolated old database and verify reads/writes/restore; check existing archives, locale catalogs and settings/manual-backup/restore UI; include upstream seeded resources in worker totals while limiting controlled 503s and per-file assertions to the three fixture-created attachments; run the three project typecheck/build commands and reuse applicable isolated-module evidence.
B21 After publication, keep only the latest completion record for the same actual file path, including case aliases on the filesystem. Retention must not delete a new archive through an older record. A failed completion commit still restores previous success and leaves a recoverable pending archive, without expanding deletion ownership. In isolation, create A/B/C, externally move A, then reuse A/a; verify the new file survives with one history record. Reuse completion-failure and retention-ownership checks.
B22 Save passwords to separate randomly identified private encrypted credential files, then atomically commit their reference and password generation with configuration. A failed configuration commit preserves previous configuration, credentials and no-change baseline and cleans the uncommitted credential. Read existing standalone .secret credentials; require new references to match the generated identifier format. Retire the old credential only after commit; cleanup failure does not undo a completed save or re-enable the old credential. First reproduce ENOSPC after password-file writing. Before/after restart, verify the old password and configuration/generation survive failure. A successful password change invalidates the previous archive baseline; legacy credentials remain readable.
B23 Before restoring any note in a page, validate ownership of every revision ID. IDs already owned by another note (including another workspace), or assigned to different notes within the page, fail with a conflict before any page writes. Preserve same-ID/same-note restore and never move or overwrite unrelated revisions. Reproduce revision takeover through the real API/SQLite for both same- and cross-workspace owners; verify zero page writes and intact unrelated revisions, reusing idempotent same-owner restore coverage.

Unchanged boundaries

  • Preserve executed migrations, synchronization protocol, note IDs and permissions. Old backups/json, ordinary Web manual ZIP, bounded browser fallback and SQLite recovery keep their existing conditions of use.
  • No WebDAV/S3 uploads, OS service after app exit, encrypted Web entry points, native mobile UI or whole-instance image; no installer/update/version/release changes.
  • Do not operate on existing user instances, production databases, installed desktop apps or users' cloud-drive data. Verify with isolated directories and test instances; commit/push only the contribution branch and create a PR, without a release or deployment.
  • Add only shared components, dependencies, packaging inclusions, fixtures and test adapters needed for the listed behavior. Cloudflare and Docker retain shared business logic.

Completion audit

B01–B23 are implemented. The contribution branch starts from official main and includes only this feature and related fixes. The added migration is 0080_backup_revision.sql; published migrations are unchanged. Actual behavior changes map to the scope above. Shared archives retain existing entry points, upstream notebook-appearance fields and all five locale catalogs.

Decisive results and evidence

  • B01–B05, B20: consistency and archives. Real data created on the preceding schema survives the added migration; API read/write, workspace isolation, legacy backup, archive and Markdown checks passed. Preserve edgeever-zip v1/v2 reads and add ZIP64. The unchanged streaming engine reuses the earlier 4,718,598,326-byte restore: five 900 MiB attachments restored after disconnecting the source, with matching content and peak worker RSS of 444 MiB. A 65,536-entry ZIP64 scan also passed. Existing local Cloudflare D1 read evidence remains separate from native cross-platform acceptance.
  • B06–B10, B17–B18, B21–B22: background work and files. Current main-process tests passed 37 cases and 211 assertions; see results. Fixed old history deleting a newly published file after name reuse, and mismatched passwords/configuration when credential writing succeeded but configuration failed. Keep the latest record per actual path, and commit a new credential reference with configuration while retaining the previous credential on failure. Existing macOS secure-storage, startup without renderer account IPC, and interrupted-publication verification results remain applicable.
  • B11–B13, B15–B16, B23: restore and errors. Current real API/SQLite and Node-worker checks passed 20 cases and 175 assertions; see restore results. They cover plain/encrypted recovery after stopping the source, exact attachment bytes, history restore/deletion, JSON/non-JSON 503 on the third fixture attachment, error identity and staging cleanup. Revision-ID takeover was reproduced before fixing it; conflicting pages now write nothing, unrelated revisions survive, and same-owner repeated restores remain valid. Removed redundant reassigning UPSERT from the delete-then-insert revision path. Current upstream seeded resources count toward totals; controlled 503s target only fixture-created files. Earlier native macOS restore readback remains native evidence.
  • B14: local development proxy. Pin Wrangler/Miniflare and use Bun patches for the local idle-connection race, error attribution and streaming backpressure, without adding restore POST retries. Current proxy/runner checks passed 36 cases and 128 assertions; see results. Frozen installation applied both patches. The same transport versions reuse earlier five-second cadence results, backpressure/cancellation/clean-install results, and real Wrangler D1/R2 restore.
  • B11–B12, B15–B19: interface. Current real components were exercised in a browser for settings save, manual naming/encryption with Enter, history restore, wrong-password retry, target confirmation and delete confirmation/cancellation; see interaction results. The desktop bridge is mocked and no user instance is operated on. The hierarchy remains primary actions, status, initially collapsed settings, then local files; Restore and Delete stay with their file row. Earlier wide/narrow layout measurements remain applicable.

Current interface

Overview · Expanded settings · Manual plain backup · Manual encrypted backup · Unlock error · Restore confirmation

The current contribution branch passed bun run typecheck, bun run typecheck:mobile, and bun run build:web; logs are in the current evidence directory. Versions, installers and automatic-update mechanisms are unchanged.

Reproduction entry points

bun test apps/api/src/backup-consistency.test.mjs apps/api/src/backup-routes.test.mjs apps/api/src/backup-restore.test.mjs
bun test tests/json-backup.test.ts tests/json-backup-zip64.test.ts tests/markdown-export.test.ts
bun test apps/desktop/src/backup/encrypted-archive.test.mjs apps/desktop/src/backup/worker-integration.test.mjs
bun test apps/desktop/src/main/backup-settings.test.mjs apps/desktop/src/main/backup-manager.test.mjs apps/desktop/src/main/backup-ipc.test.mjs
bun test tests/wrangler-proxy.test.mjs tests/wrangler-runner.test.ts scripts/local-dev.test.mjs

Large-archive/runtime entry points are apps/desktop/src/backup/tests/large-archive.mjs, zip64-entry-count.mjs, and docs/changes/evidence/2026-10-23-desktop-backup/wrangler-backup-replay.mjs; build the required workers first. Reuse valid results rather than repeating these runs.

CI status

PR #684 is submitted. The first CI run's feature-related lint issues are fixed: remove an unused Markdown import and replace the filename control-character expression with an equivalent character-code check. Targeted lint and existing naming tests passed; the accepted filename range is unchanged.

The two HTTP 503 worker failures came from starting an attachment upload before asynchronous ZIP reads had attached a rejection handler. A fast rejection terminated Node before the worker could return its structured error. Upload initialization now starts only when immediately awaited by the first chunk or empty-entry close. The real Node reproducer failed before the fix; the existing JSON/non-JSON 503 checks and archive/worker tests now pass (21 cases, 114 assertions), retaining the original assertions, partial-restore state and cleanup. No retries or fallback were added.

Repository-wide bun run lint remains blocked by two unchanged official-baseline locations: no-control-regex in apps/desktop/src/main/picgo.mjs:56 and no-useless-spread in apps/mobile/src/lib/mobile-locale.tsx:805. Both files match official main; upstream maintenance is needed to restore full CI, and this PR leaves them unchanged.

Remaining release acceptance

  • Native Windows/Linux directory permissions, secure storage, publication and restore, plus a real old-to-new packaged application upgrade, require their platform environments.
  • Native macOS file/directory dialogs used controlled selections. Actual OS-picker interaction, tray/sleep/resume, physical disk-full and retry after partially interrupted network restore have not completed native scenario acceptance.
  • Docker image pulling encountered Docker Hub 429, so container acceptance did not run; see the blocking log. Local Bun/SQLite and workerd/D1 results remain separate; no remote Cloudflare instance was deployed.

This delivery is code and a PR, not a release, deployment or replacement of the installed application.