Native macOS SwiftUI client for the NestVault self-hosted backup server.
| Item | Minimum |
|---|---|
| macOS | 14.0 (Sonoma) |
| Xcode | 15.0 |
| Swift | 5.9 |
| Server | backup_files v2.6+ (mínimo funcional — batch check) · v7.8+ recomendado (habilita /register/batch) |
NestVault_Xcode/
├── NestVaultClient.xcodeproj/
│ ├── project.pbxproj
│ └── xcshareddata/xcschemes/NestVaultClient.xcscheme
└── NestVaultClient/
│
├── # Entry & Core
├── BackupVaultApp.swift # App entry · MenuBarExtra · Settings scene
├── ContentView.swift # Main window · fixed sidebar · NavigationSplitView
├── Models.swift # All data models — check/register batch, absorb, BackupSchedule
├── APIService.swift # Network layer · backoff-aware checkHealth · batch check/register · Keychain-backed API key
├── ConfigStore.swift # Local profile persistence (UserDefaults)
│
├── # Views
├── DashboardView.swift # Global stats · "On this Mac" section · recent activity · collapsible server backups
├── BackupsView.swift # 3-panel browser: backups → versions → files
├── BackupConfigsView.swift # Profile CRUD · ExcludesEditor · ScheduleEditor
├── CleanupView.swift # Old version cleanup with preview
├── SettingsView.swift # Server URL · API Key · startup · system status
├── ActivityView.swift # Run history: day groups, filters, per-event log excerpt
├── MenuBarView.swift # Compact menu bar panel
├── PlaceholderView.swift # ContentUnavailableView substitute (macOS 13/14)
│
├── # Activity
├── ActivityLog.swift # ActivityEvent model · persisted history (Application Support JSON) · unread tracking
├── RunRecorder.swift # Single completion funnel — persists lastRun, records the event, applies the notification policy
│
├── # Backup Execution
├── BackupRunner.swift # Pipelined backup engine (hash→check→register/upload overlapped) · byte-weighted progress · dock progress
├── BackupRunnerView.swift # Execution sheet with live log and cancel
├── BackupQueue.swift # Sequential queue engine
├── BackupQueueView.swift # Queue sheet with selection UI and per-item progress
│
├── # Restore
├── RestoreRunner.swift # Parallel download engine · SHA-256 verify · zip-slip guard · overwrite policies
├── RestoreView.swift # Restore sheet: destination/policy picker + live log
├── HashUtil.swift # Shared streaming SHA-256 (backup dedup + restore integrity check)
│
├── # Scheduling & System
├── ScheduleManager.swift # Timer-based scheduler · respects power/network
├── ScheduleEditor.swift # Schedule editor (Hourly/Daily/Weekly/Custom)
├── LoginItemManager.swift # SMAppService wrapper for auto-start
├── PowerMonitor.swift # Battery + network interface monitoring
├── DockProgress.swift # Dock tile progress bar during backups
│
├── # Utilities
├── L10n.swift # L("key") helper for non-view contexts
├── LegacyMigration.swift # One-time migration from com.vcm.backupvault.app
│
├── # Localization
├── en.lproj/Localizable.strings
├── pt-BR.lproj/Localizable.strings
│
└── # Resources
├── Info.plist # ATS · NSLocalNetworkUsageDescription
└── Assets.xcassets/AppIcon.appiconset/
- Open
NestVaultClient.xcodeprojin Xcode - In Signing & Capabilities, select your Team
- In Assets.xcassets → AppIcon, enable Single Size and drag a 1024×1024 PNG
- ⌘R to run
Bundle ID: com.vcm.nestvaultclient.app
- Cards: total backups, versions, files, and storage
- On this Mac (first section): every local profile joined with its server counterpart — status glyph from
lastRunStatus, version count and size from the server, last run, next scheduled run, live progress while running, and a Run button (or View, re-attaching to an in-flight run). Profiles with no server counterpart yet, no label, or no source folder are shown explicitly rather than hidden. Run all… opens the existing queue sheet - The local↔server join is the
label, matched trimmed and case-insensitively — the server has no reliable machine identity (client_nameis written once at creation and never updated) - Recent activity: the last three events, with a link into the Activity screen
- Other backups on the server: everything without a matching local profile, collapsed by default (
dashboard.showOthers) - Explanation panel: SHA-256 deduplication, versioning, label isolation, snapshots
- Alert banner when the server is unreachable
- Sidebar section with an unread badge; persisted run history for backups, restores, queue runs and cleanups
- Grouped by day (Today / Yesterday / full date), filterable by outcome, kind, profile and free text
- Each row: status glyph, profile name, label, trigger badge (manual / scheduled / queue), the counters that actually moved, duration and time
- Expanding a row shows the captured log excerpt — every warning and error plus the last lines of the run — selectable and copyable
- Stored as
~/Library/Application Support/NestVaultClient/activity.json, capped at 400 events; a corrupt file is moved aside asactivity.json.bakrather than silently discarded ActivityEventdecodes withdecodeIfPresenton every non-identity field, so adding a field in a later version does not erase existing history
- 3-panel
HStacklayout: backups → versions → files - Filter by backup label and file name
- File table with SHA-256, status, size
- Delete individual version via context menu
- Restore version from the versions context menu, or restore a selection/filtered subset from the files table (multi-select,
.contextMenu(forSelectionType:)) — see Restore below
- Two entry points: "Restore version…" (versions context menu) and per-file/subset restore from the files table (multi-select or currently filtered rows)
- Destination: Original location (resolved from the local profile matching the backup label —
sourcePath+prefix; disabled when no matching profile exists) or Choose folder… (NSOpenPanel); for a partial selection, the destination root is the files' longest common directory so the folder structure isn't recreated from/. Prefixes match whole path components, and paths recorded by Windows clients (C:\...,\\nas\...) restore with the drive letter as a folder - Overwrite policy: Keep existing (never overwrite; local file is SHA-256'd and skipped if identical) / Overwrite changed only (default) / Overwrite everything
- Parallel download (
RestoreRunner, workers from the source profile or 4), each file verified against its catalogued SHA-256 after download before being committed to disk — a hash mismatch is retried, never silently accepted - Retries (3×, exponential backoff) only for transient failures (
503degraded replicas, network errors);404/410(unknown/physically gone content) fail immediately per file without blocking the rest - Zip-slip guard on every destination path; duplicate destination paths in a selection are de-duplicated (last one wins); original file
mtimeis restored on the written file - One failing file never aborts the run — the sheet reports a partial result (restored/skipped/errors) exactly like the backup summary
- Responsive cancellation (
session.invalidateAndCancel()); files already committed before cancelling are kept - No server-side changes required — restore is entirely client-orchestrated against the existing
GET /filesandGET /files/{file_id}/downloadendpoints (decryption, if enabled, happens server-side; the client only ever handles plaintext bytes)
- Create and manage local backup profiles
- Each profile: name, label, source folder, server override, workers, prefix, excludes, schedule
- Native folder picker (
NSOpenPanelviapanel.begin) - 4-tab editor: General / Server / Schedule / Exclusions
- Run individual backup (sheet with live log)
- Run queue with selection UI and per-item progress
- Duplicate-run guard: reopening the runner sheet for a profile already backing up (manual, scheduled, or as the current queue item) re-attaches to the active runner instead of starting a second one; the label stays disabled elsewhere until it finishes
- Delete backup from server (context menu) — on server 9.3+ with a user key it goes to the server trash; the app shows until when an admin can restore it
- Python equivalent command preview
- Optional per-profile toggle: Skip if no changes
- Before running the classify/hash/upload pipeline, compares the local file tree against the hash cache (
mtime+size) - If 0 files changed: skips classify, execute, and sync phases entirely; creates a new version by calling
POST /absorbfrom the previous version — no upload - If any file changed (or was added/deleted): falls back to a full backup automatically
- 1-week safety override: if more than 7 days have elapsed since the last full backup, a full run is forced regardless of change detection, to keep the server verified
lastFullBackupDateis persisted per profile and updated only after a real full backup completes- Recommended for backups maintained by a single client machine (no concurrent writers)
- Optional per-profile toggle: Accumulate (
profile.accumulate) — for archives that are never fully present on the client at once (e.g. a photo library spread across external drives) - On finalize, the client calls
POST /absorbwith the previous done version as source: the server copies everyVersionFileabsent from the current version (byoriginal_path) into it, so deleted-from-client files are preserved instead of dropped - Client-side optimization: unchanged files whose exact content (same server path + sha256) already exists in the previous done version are withheld from the register pipeline entirely and inherited by that same absorb call — zero register round-trips for them, instead of one request each
- Safety guard: once files are withheld this way, absorb becomes structural rather than best-effort — if it fails, or inherits fewer paths than were withheld, the version is marked
failedrather than silently missing files - Profiles without a previous done version, or where the previous version's file cache is unavailable, fall back to registering every file individually (no withholding)
- 5 modes: Disabled / Hourly / Daily / Weekly / Custom (minutes)
- Daily and Weekly respect a configured time-of-day
- Weekly also respects day of week
- Custom supports 5–10080 minutes
ScheduleManagerchecks every 30s with aTimer- Respects network reachability, battery state, and active backup lock
- Shows next run date in editor and last run time in detail view
- A schedule that has never run anchors to the moment it was enabled (not to the distant past), so a freshly configured daily/weekly schedule fires at its configured time instead of immediately
- Local notifications (
UserNotifications) report completion or failure — the only reliable signal while the app runs as a menu-bar accessory, since the Dock bounce is invisible without a Dock icon. Since v5.0 the policy lives inRunRecorder: scheduled runs and queue summaries always notify; manual runs notify on failure, or on success only when the app is not frontmost; per-item queue runs and cancellations never do. Tapping a notification brings the app forward and opens the Activity screen
- Mode: all backups or specific label
- Keep N most recent versions (default: 5)
- Per-label preview table before executing
- Mandatory confirmation alert
- Detailed results: versions removed + storage files freed
- Connection indicator icon
- Compact panel: status, 3 mini-stats, 5 recent backups
- Quick actions: Open NestVault · Settings · Quit
- General tab: Login Item (start with macOS via
SMAppService), network status, power source, backoff info - Server tab: Server URL and API Key, test connection, tips
- About tab: version, links to Swagger UI and GitHub
| Method | Endpoint | Usage |
|---|---|---|
GET |
/health |
Check connection (backoff-aware) |
GET |
/backups |
List backups with version_count, file_count, total_size_bytes |
GET |
/backups/{label}/versions |
List versions |
GET |
/files?backup_label=&version_key= |
List files |
GET |
/files/{file_id}/download |
Download one file's content (decrypted server-side if encryption is enabled) — used by Restore |
POST |
/backups |
Create backup (label, client_name) |
POST |
/backups/{label}/versions |
Create version (version_key) |
POST |
/check |
Check single file: returns needs_upload, content_exists |
POST |
/check/batch |
Check up to 100 files in one request (v2.6+) |
POST |
/register/batch |
Register up to 500 files whose content already exists in one request — one server commit per batch instead of one per file (v7.8+; client batches at 200) |
POST |
/upload |
Upload file (binary) or register (header only) |
POST |
/sync |
Mark absent files as deleted (existing_paths) |
PATCH |
/backups/{label}/versions/{key} |
Finalize version (status: done/failed) — 409 on server 9.3+ means it was already finalized with another status (not retried) |
POST |
/backups/{label}/cleanup |
Remove old versions (keep) — server 9.3+: trashed/purge_after for user keys, scheduled (storage freed in background) for admin keys |
DELETE |
/backups/{label}/versions/{key} |
Delete version — server 9.3+: user keys send it to the server trash (trashed, purge_after) |
DELETE |
/backups/{label} |
Delete entire backup — server 9.3+: user keys send it to the server trash (trashed, purge_after) |
New content (content_exists = false):
POST /upload
Content-Type: application/octet-stream
X-Backup-Label: <label>
X-Version-Key: <version_key>
X-Original-Path: <path base64>
X-Mtime: <epoch float>
<raw file bytes>
Already in storage (content_exists = true):
POST /upload
X-Backup-Label: <label>
X-Version-Key: <version_key>
X-Original-Path: <path base64>
X-Content-Sha256: <sha256>
X-Mtime: <epoch float>
(no body)
The BackupRunner walks the source tree once (BFS over contentsOfDirectory with includingPropertiesForKeys — mtime, size, isDirectory — in a single kernel pass), splits files into cache hits (matching mtime+size against the previous version or the local hash cache) and files needing a hash, then runs the rest as a pipeline instead of strict sequential phases:
- A producer hashes changed files in parallel (SHA-256, streamed in 4 MB chunks) and, as each batch of hashes completes, classifies it against the server (
POST /check/batch) — CPU (hashing) and network (classification) overlap instead of waiting on each other. - Cache hits and classified "register" items are coalesced into
/register/batchrequests (batches of 200) when the server supports it (v7.8+); otherwise they fall back to individualPOST /uploadregister calls. A batch item whose content turns out missing server-side escalates to a full upload; a batch that fails after retries falls back to per-file registers. - Files needing new content upload via
POST /uploadwith a binary body, streamed directly from disk with configurable concurrency (workers) and exponential retry (3 attempts). - Progress is a single pool of byte-equivalent units spanning hashing + classification + transfer (a server round-trip costs a fixed unit; upload cost is the file's actual size). It only moves forward, and is throttled to ~10 updates/sec to stay smooth with tens of thousands of files. Upload progress itself streams in real time via a per-task
URLSessionTaskDelegatereporting bytes sent, so a single large file no longer stalls the bar. - In accumulate mode, files withheld for absorb-inheritance (see Accumulate Mode above) skip this pipeline entirely — no hash, no check, no register.
The RestoreRunner mirrors BackupRunner's structure (published state machine, StatsAccumulator-style actor, throttled progress, cancel() semantics) but runs the inverse direction — server → disk — against the version's already-fetched VersionFile list, with no server-side write:
- Plan phase (synchronous): maps each
original_pathto a destination URL — strips the configured prefix, rejects any path that would resolve outside the destination root (zip-slip guard), skips system files (.DS_Store,Thumbs.db,desktop.ini), de-duplicates by destination path. - Execute phase: sliding-window task group (same pattern as the backup pipeline's executor), concurrency = the matching profile's
workersor 4. Per file: if the destination already exists and the policy isn't overwrite everything, the local file is hashed and the download skipped when it's already byte-identical. - Each download goes through
URLSession.download(for:), is hashed and verified against the catalogued SHA-256 before being committed — content that doesn't match its recorded hash is treated as a failed attempt and retried, never written to disk. - Progress is a single
doneBytes / totalBytesfraction (sizes are known upfront from the file list), throttled the same way as the backup progress bar. - A file's failure (permanent HTTP error, exhausted retries) is recorded and logged but does not stop the run — the final summary reports restored/skipped/error counts, same shape as the backup summary.
Application Support (~/Library/Application Support/NestVaultClient/):
| File | Content |
|---|---|
activity.json |
Run history — up to 400 ActivityEvent records (v5.0+) |
{label}_hashcache.json |
Per-label sha256 cache used to skip re-hashing unchanged files |
UserDefaults:
| Key | Content |
|---|---|
server_url |
Server URL |
activity.lastSeenDate |
Timestamp of the newest event the user has seen — drives the Activity badge |
dashboard.showOthers |
Bool — whether "Other backups on the server" is expanded |
backupProfiles_v1 |
JSON array of BackupProfile (includes BackupSchedule, lastRun, smartSkip, accumulate, lastFullBackupDate) |
schedule.pauseOnBattery |
Bool — pause when on battery |
schedule.minBatteryPercent |
Int — minimum battery level to run |
Keychain (service com.vcm.nestvault):
| Item | Content |
|---|---|
api_key |
API Key — no longer stored in UserDefaults. A one-time migration on first launch of this version moves any existing plaintext key from UserDefaults into the Keychain and clears the old value. |
Declared in Info.plist:
NSLocalNetworkUsageDescription— required on macOS 15+ for local network accessNSAppTransportSecuritywithNSAllowsLocalNetworking— allows HTTP on local IPs
On first connection, macOS will prompt for local network permission — click Allow.
The app automatically uses the system language. Supported: English (default) and Brazilian Portuguese.
Files: en.lproj/Localizable.strings and pt-BR.lproj/Localizable.strings.
cd backup_files/server
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
export BACKUP_API_KEY="your-key"
export STORAGE_DIR="/mnt/external/backups"
export DB_PATH="/mnt/external/backup.db"
uvicorn main:app --host 0.0.0.0 --port 8000Web dashboard: http://<pi-ip>:8000/
Swagger UI: http://<pi-ip>:8000/docs
| Symptom | Cause | Fix |
|---|---|---|
Error -1009 |
Local network permission denied | System Settings → Privacy → Local Network → enable NestVault |
BadRequest on upload |
Server older than v2.1 | Update server to v2.6+ |
Keys shown raw (e.g. menubar.open) |
Localizable.strings not in bundle | Verify Localizable.strings is in target Resources build phase |
| Schedule not running | Battery mode or network | Check Settings → General → System Status |
requiresApproval on Login Item |
macOS needs user consent | Click "Open Settings" in Settings → General |
| Connection refused | Server offline | systemctl status backup-server on the Pi |
Compatibilidade com o servidor NestVault 9.3 — nenhuma mudança quebrava o app, mas várias respostas novas eram ignoradas e a interface mostrava informação errada.
| Componente | Mudança |
|---|---|
| Lixeira do servidor (9.3+) | DELETE de versão/backup e POST /cleanup com chave de usuário passam a ir para a lixeira do servidor. VersionDeletedResponse, BackupDeletedResponse (novo) e CleanupResult leem trashed/purge_after, e o app avisa até quando o admin pode restaurar |
CleanupView.swift |
Limpeza de admin agora roda em background no servidor (scheduled, storage_files_removed = 0): o resultado mostra "Storage em background" em vez de 0 arquivos removidos; limpeza de usuário mostra "Versões na lixeira" |
| Erros de exclusão | Exclusão de versão engolia erros (try?) e a de backup guardava o erro sem nunca exibi-lo — agora ambos aparecem em alerta |
BackupRunner.swift |
PATCH de finalização com 409 (versão já finalizada com outro status, 9.3+) não é mais repetido; upload com 503 (nenhuma cópia legível no servidor) espera 5 s × tentativa em vez de 0,5 s |
RestoreRunner.swift |
Prefixo comparado por componente (/docs não casa mais com /docs2/x) e caminhos gravados por clientes Windows (C:\..., \\nas\...) restaurados com a letra do drive como pasta — paridade com o cliente Python 9.3 |
| Textos | Confirmações de exclusão/limpeza deixam de prometer remoção permanente: explicam o comportamento com chave de admin e de usuário |
| Componente | Mudança |
|---|---|
ActivityLog.swift (novo) — histórico |
Modelo ActivityEvent (backup / restore / fila / limpeza) persistido em ~/Library/Application Support/NestVaultClient/activity.json, cap de 400 eventos com poda por histerese, contagem de não-lidos ancorada em data (activity.lastSeenDate) e não em contador, decoder à mão com decodeIfPresent para não apagar histórico ao evoluir o schema, e arquivo corrompido movido para .bak em vez de sobrescrito |
RunRecorder.swift (novo) — funil de conclusão |
Correção de bug: lastRun/lastRunStatus eram gravados apenas por execuções agendadas — runs manuais e de fila deixavam o perfil parecendo nunca executado. Agora os três caminhos passam por um único ponto, ancorado num defer dentro de BackupRunner.run que cobre os oito pontos de saída (incluindo cancelamento e o sucesso antecipado do smart skip). Um assert em DEBUG impede que um novo call site esqueça de se registrar |
ActivityView.swift (novo) — tela Atividade |
Nova seção na sidebar com badge de não-lidos: histórico agrupado por dia, filtros por resultado/tipo/perfil/texto, e trecho de log por evento (todos os warnings e erros mais as últimas linhas) selecionável e copiável |
DashboardView.swift — foco na máquina |
Dashboard deixa de ser uma lista crua do servidor: "Nesta máquina" vem primeiro, juntando cada perfil local ao seu backup no servidor pelo label (aparado e case-insensitive), com glyph de estado, última e próxima execução, progresso ao vivo e botões Executar / Executar todos. Perfis sem contrapartida no servidor, sem label ou sem origem aparecem explicitamente. Abaixo, atividade recente e "Outros backups no servidor" recolhível |
ScheduleManager.swift |
nextRun(for:) e anyRunner(for:) extraídos para o Dashboard não depender de estado interno; persistência e notificação de execuções agendadas migradas para RunRecorder |
| Notificações | Passam a cobrir runs manuais (só quando o app não está em foco, ou sempre em caso de falha) e restaurações; categoria nv.run e userInfo levam o toque da notificação direto para a tela Atividade, mesmo com a janela principal fechada |
CleanupView.swift |
Limpeza — uma operação destrutiva no servidor — passa a ser registrada no histórico, não só no bloco de resultado transitório da tela |
| Limpeza de código morto | VersionDetailView.swift removido: estava fora do target desde sempre e não compilava (referenciava VersionInfo/FileInfo, tipos que não existem) |
| Componente | Mudança |
|---|---|
BackupRunner.swift — progress model |
Substituído o modelo de pesos fixos (40/60 entre fases) por um pool único de unidades byte-equivalentes; fases visíveis (preparing/scanning/checking/processing/finalizing) com contagens ao vivo; UI throttled a ~10 updates/s |
BackupRunner.swift — pipeline |
Hash → check → register/upload deixaram de ser fases sequenciais estritas: um produtor faz hash em paralelo e classifica em lotes assim que completa, sobrepondo CPU e rede; um executor consome via AsyncStream respeitando o limite de workers |
BackupRunner.swift — upload progress |
Progresso intra-upload via URLSessionTaskDelegate por task (deltas de bytes enviados), eliminando o congelamento da barra durante um único arquivo grande |
ScheduleManager.swift — duplicate-run guard |
Reabrir o sheet de um perfil já em backup (manual, agendado, ou item corrente da fila) reanexa ao runner ativo em vez de iniciar um segundo; o label fica bloqueado em outros pontos de entrada até terminar |
ScheduleManager.swift — schedule anchors |
Um agendamento nunca executado ancora no momento em que foi habilitado, não no passado distante — agendamentos diário/semanal recém-criados disparam no horário configurado, não imediatamente |
ScheduleManager.swift / BackupNotifier |
Notificações locais (UserNotifications) para conclusão/falha de backups agendados e de fila — sinal confiável já que o bounce do Dock é invisível sem ícone no Dock (app como acessório de menu bar) |
APIService.swift — Keychain |
API key migrada de UserDefaults (plaintext) para o Keychain (com.vcm.nestvault), com migração automática de uma vez na primeira execução |
| Limpeza de código morto | Removidos BackoffPolicy.swift, UploadResponse, BackupDeletedResponse, stats.total/stats.skipped não utilizados, PowerMonitor duplicado em SettingsView |
| Performance | Classificação fast/slow e detecção de smart-skip reduzidas de ~2 saltos de actor por arquivo para 1 salto para a lista inteira; cleanupAll coleta erros por label em vez de abortar no primeiro; ForEach com identidade estável em vez de índice posicional |
| Localização e polimento | Strings PT hardcoded movidas para Localizable.strings (pt-BR/en); onChange(of:perform:) migrado para a API de dois parâmetros do macOS 14 |
BackupRunner.swift — Accumulate Mode |
Modo acumulativo passa a herdar arquivos inalterados via /absorb em vez de registrá-los um a um — ver seção Accumulate Mode acima |
APIService.swift, BackupRunner.swift — /register/batch |
Cliente adota o endpoint de registro em lote do servidor (v7.8+) — ver API Contract e Backup Engine acima |
RestoreRunner.swift, RestoreView.swift (novo) — Restore |
Nova feature: restaura uma versão inteira ou uma seleção de arquivos do servidor para o disco local. Download paralelo com verificação SHA-256 pós-download, guard anti zip-slip, 3 políticas de sobrescrita (manter/só alterados/tudo), destino "local original" (via perfil correspondente) ou pasta escolhida, cancelamento responsivo e resultado parcial tolerante a falhas por arquivo. Sem mudanças no servidor — usa GET /files e GET /files/{file_id}/download já existentes — ver Restore e Restore Engine acima |
BackupsView.swift — entradas de restore |
"Restaurar versão…" no menu de contexto das versões; multi-seleção na tabela de arquivos com restore de selecionados ou dos exibidos (filtro ativo) |
HashUtil.swift (novo) |
computeSHA256Streaming extraído de BackupRunner para reuso na verificação de integridade do restore |