diff --git a/.claude/architecture.md b/.claude/architecture.md deleted file mode 100644 index 897be540..00000000 --- a/.claude/architecture.md +++ /dev/null @@ -1,102 +0,0 @@ -# Architecture - -## Layout (`packages/plugin/src/`) - -- `main.ts` - lifecycle only: onload/onunload, saveSettings, scheduleScopeRefresh -- `plugin/` - composition root: host.ts, bootstrap, one register*() per concern -- `core/` - long-lived services: LogService, PassphraseManager, StatePersister, DeviceName -- `sync/` - the engine: manifest, diff, operations, history, projection. No UI. -- `crypto/` - the vault key and blobs (`index.ts`), live keys, `seal.ts`: everything the relay carries (live frames, cursors, presence), sealed with its space's key, and `device-key.ts`: the key in Obsidian's SecretStorage that seals what stays on the device (the passphrase cache, the settings envelope) -- `hub/` - the relay hub: socket link, one socket per relay (`channels.ts`: the vault and owned shares on the own relay, joined shares on their owner's), a per-space facade (`space(id)`) routing frames by slot; `HubConnection.statusOf` is the relay status every display reads (`status.ts`) -- `presence/` - who is where: each device announces its open file on every space channel it holds, sealed with that space's key (`people.ts`, `channel.ts`, `announcement.ts`); `here.ts` tracks the active file and idleness; `unseen.ts` the files others changed that this device has not opened. Keys and identity per space come from `plugin/space-access.ts`, shared with live editing -- `spaces/` - space records (`settings.spaces`, one object each under `spaces/` in the vault storage), the partition (`spacesOf`, `mountError`), the owner's share (`owner.ts`), invites (`invite.ts`), how a device reaches a share (`access.ts`). No network and no settings: the relay broker client is `storage/adapters/share-broker.ts`, the flows are `ui/shares/share-action.ts` and `ui/shares/invite-action.ts`. `sync/` never imports it; `core/session-factory.ts` opens a share's session from its record -- `live/` - live documents: `session/` (one file's Y.Doc in its space's room: the outbox, the room log, who else is in it, the rotation it asked for), `workspace/` (which open notes are live: `sessions.ts` and each note's `noteState`, `room.ts`, `space.ts`, the join patience, renames, and `editors.ts` pairing each model with the view that edits it), `cold/` (the file sync's `LiveNotes` port, declared in `sync/live-notes.ts` so `sync/` never imports `live/`, and the agreed texts), `doc-id.ts` (a room's id), `doc-types.ts` (what goes live, in which view), and a model per kind (`text/`, `drawing/`, each with the binding that attaches its view) -- `links/` - share links, see [share links](share-links.md): the record in `settings.links`, written only through `SharedLinks` (`plugin.sharedLinks`, subscribable), traded with the vault storage under `links/` (`remote.ts`, at each `host.spaces()` refresh), `note-links.ts` (a note's live links and whether the note changed since), the snapshot (Obsidian's renderer into a hidden attached element, then `sanitize.ts`, `math.ts` and `images.ts`), `publish.ts` (seal with `@mdsync/protocol`'s link format, store through `storage/adapters/link-broker.ts`). No UI: the flows are `ui/links/`. The page a link opens is `packages/viewer`, served by the relay -- `drawing/` - Excalidraw files without Obsidian: reading the scene, its fingerprint, the merge by element. Pure; used by `sync/`, `vault/` and `live/` -- `storage/` - remote backends behind StorageAdapter, plus the registry; `records.ts` keeps records (spaces, links) one sealed object each, with an etag read cache per kind -- `vault/` - Obsidian filesystem access, scanning, ignore rules -- `settings/` - settings model, `envelope.ts` (the secrets of `data.json`, sealed by the device key), transfer, and declarative settings definitions; `page.ts` adapts imperative pages, and `fields.ts` provides field rows and `renderDefinitions` for the wizard. `setup/` is the first-run wizard (one `create*Step` view per step, `steps.ts` computes which are done from the settings, `run-action.ts` is the busy/error wrapper every async button uses) -- `cloudflare/` - the Cloudflare API without UI: `api.ts` envelope client over an injected `Http`, relay deploy (`relay-deploy.ts`, `assets.ts`, `migrations.ts`), `relay-account.ts` (which worker on the account is this device's relay, relay names, the bundled relay version), R2 bucket and S3 keys (`r2.ts`), the token template (`token.ts`). `obsidian-http.ts` is the only file that imports Obsidian -- `ui/` - views and modals at the top; `live/` (note header in `header/`, relay and live status in `status/`, the states both show in `live-state.ts`), `shares/` (share window, share and invite flows), `links/` (share-link window, its list, the menu entries, the note header button), `explorer/` (file tree indicators and presence), `actions/` (menu actions), `common/` (notices, icon buttons, avatars, relay text and fixes, menus, the modal frame, file paths, helpers: whatever two of these use) -- `editor/` - CodeMirror gutter signs, the read-only share lock -- `shared/`, `utils/` - app-aware helpers vs. generic algorithms -- `styles/` - the stylesheet, one slice per feature (see Styles) - -## PluginHost over the plugin class - -Feature modules take `PluginHost` (`plugin/host.ts`), never -`import MdsyncPlugin from "@/main"` - that import direction is what turned -`main.ts` into a proxy dump. A module that also registers something with -Obsidian takes `Plugin & PluginHost`; `MdsyncPlugin` satisfies both. - -## Styles - -`src/styles/` is bundled to `packages/plugin/styles.css` by the same esbuild -config that builds `main.js`. The generated file is gitignored; edit the slices. - -- Slices mirror `ui/`: one file per feature, imported by `index.css`. Import - order is the cascade, so append within a slice rather than reordering imports. -- Phone overrides live next to the component they override; only `mobile.css` - (the cross-cutting touch-target pass) is loaded last. -- Spacing uses Obsidian's 4px grid (`--size-4-*`, `--size-2-*`) directly. Do not - add a parallel scale. `tokens.css` holds only what Obsidian has no variable - for: `--mdsync-icon`, `--mdsync-touch`, `--mdsync-bar`, the pill radius. -- `--mdsync-bar` is a tone-coloured change bar, `--mdsync-bar-strong` the - heavier accent bar for a chosen side. Keep that distinction. -- Raw px is for hairlines (1px borders, outlines) and the few off-grid values - with no token. Row metrics (`min-height` on rows) are a contract with - `virtual-list.ts`, which measures them - don't round them casually. - -## Layering - -`sync/`, `storage/` and `vault/` must not import from `ui/`, -`settings/` (beyond `settings/model`) or `editor/`. An adapter that needs to -tell the user something returns a result for the caller to surface - see -`StorageAuthOutcome`. - -## Imports - -- `@/` for anything outside the file's own directory, relative `./` inside it. -- Tests reach source through `@/` and their own helpers through `@tests/`; a - test imports the module it tests directly. -- Cross-area behaviour goes through the area barrel: `@/ui`, `@/ui/common`, - `@/storage`, `@/live`, `@/hub`, `@/presence`, `@/spaces`, `@/shared`, - `@/utils`; inside `live/`, `@/live/session`. A slice never imports its own - barrel; `ui/index.ts` reaches its folders relatively. Leaf type modules - (`@/storage/types`, `@/sync/types`, `@/hub/status`, `@/spaces/record`, - `@/live/model`, `@/live/session/session-deps`) are imported directly so a - type never drags in its slice. `@/spaces/access` (drags `@/storage`) stays out of its barrel. -- No barrel for `sync/`: `sync` and `vault` import each other, and a barrel - would risk their init order. - -## Conventions - -- TypeScript strict; Node.js current LTS; obsidian type definitions. -- esbuild (`esbuild.config.mjs`) bundles everything into `main.js` - no - unbundled runtime deps, no Node/Electron APIs (mobile compatibility; - `isDesktopOnly` is set accordingly). Mind mobile memory limits. -- Keep the bundled plugin small; prefer browser-compatible packages. -- Split files that exceed ~200-300 lines; one well-defined responsibility per - module; prefer `async/await` over promise chains; handle errors gracefully. -- Constants live with their consumer: a value used by one module is a - module-level `const` there; only genuinely cross-area values belong in - `src/constants.ts`. -- Never commit generated files (`node_modules/`, `main.js`, `styles.css`). - -## Scope rules - -- Vault scanning prunes denied, ignored and disabled config directories via - `ScopePolicy.canDescend()` before listing descendants. Keep that pruning - path in sync with `ScopePolicy.includes()` when changing sync scope rules. -- Symlink skipping lives in `vault/symlinks.ts` and plugs into `ScopePolicy` - through the optional `symlinks` option, so the scanner and the diff filter - both honour it from one place. It is the only part of the - plugin that touches Node (`require("node:fs")`, lazily - mobile gets a - no-op detector). - -## Performance - -- Keep startup light: defer heavy work, lazy-initialise, nothing long-running - in `onload`. -- Batch disk access, avoid excessive vault scans, debounce/throttle expensive - reactions to file system events. diff --git a/.claude/commands-and-settings.md b/.claude/commands-and-settings.md deleted file mode 100644 index 9ec38b94..00000000 --- a/.claude/commands-and-settings.md +++ /dev/null @@ -1,50 +0,0 @@ -# Commands, settings and UI copy - -## Commands - -- **Set up sync** (`open-setup-wizard`) opens the setup wizard; a fresh install opens it once. It also opens from a sync without storage (notice action), from sharing a link without a relay (at the relay step), and from Settings → Connection. Which steps are done is computed from the settings, never stored. The Cloudflare token it keeps (`cloudflareToken`, `cloudflareAccountId`) is device-local and never transferred. -- **Update the relay** (modal, `plugin/relay-update.ts`): once per launch, when the vault's relay connects with an older build than the plugin carries and this device's token reaches its account, MDSync offers to redeploy it in place. Relay versions are `+` (`relayBehind`), so an older plugin never offers a downgrade and an unchanged relay is never redeployed. **Not now** holds until a newer build ships. -- Add user-facing commands via `this.addCommand(...)` with stable IDs; never rename once released. -- Sync is manual by default (`compare`, `push`, `pull`); autosync and push-after-changes are opt-in settings. Push/pull run a compare preflight and must surface conflicts instead of choosing a side silently. -- The `reset-remote-storage` command is destructive and must remain confirmation-gated. It deletes `manifest.json.enc`, `objects/`, `history.json.enc`, and `pins/` in the configured remote prefix (history must not outlive the objects it references), preserves local vault files, clears local `baseline`/`vaultId`, and keeps `salt.bin` and `keys.json` so the current passphrase-derived key remains valid. -- **Share folder** (folder menu; hidden where the folder cannot be shared, disabled with the reason unless the storage is S3; without a relay it still shares and says invites need one) makes the folder a space of its own under `/shares//` with its own key, opens its window and pushes it there meanwhile. The owner's other devices mount it on their next refresh. The vault's next push drops the folder's files from its manifest. -- **The share's window** (**Manage sharing** in the folder menu of a share root or anything inside it, its badge in the file explorer, **Manage** in the settings, command `manage-shared-folder` for the open file's share) holds everything about one share: a head with whose it is, its path and the relay state; one card of the people, **You** first (owner with the relay: everyone with access, else whoever is here): role pill, where they are now, **Follow** and a menu (open their note, revoke) for someone at a note, **Revoke** (owner, with the relay) for the rest; the inline invite (name, access, **Create invite**); **Pause** as segments (Off / On this device / On all my devices); **Stop sharing…** / **Leave…** and **Done** at the foot. On a phone it rises from the bottom as a sheet (`mdsync-drawer` in `styles/modal-frame.css`, as every window and the gutter's change drawer). -- **Invite** (the share's window, owner, needs the relay) registers the share's storage with the relay's broker, issues a token for one person and shows an `obsidian://mdsync-share` link with a generated password to send separately. Opening the link, or pasting it in **Accept an invite** (settings) or the command `accept-shared-folder-invite` (Obsidian opens a link in the vault last used, not always the right one), asks for the password (no vault storage needed: such a guest device syncs only its shares) and a new or empty folder (default `Shared/`), then pulls the share there. The participant never holds storage credentials. A **Read-only** invite is pulled but never auto-pushed; the broker refuses a manual push. Its notes open in source mode follow the others' typing live, locked. Inviting the same name again (any case) replaces that person's link. -- **Shared folders** (settings, Sync page) starts with **Use shared folders on this device** (device-local, on by default): off pauses every share here, arriving ones too, cancels running operations, and hides the rest of the section, the folder menu entries, **Manage sharing** and the Changes tab's paused line; the relay carries only the vault, and opening an invite first asks to turn shares on. The paused badge stays on a share folder that is on disk. On, it has **Your name** once the person owns an open share (how participants see them; empty shows "Owner"; stored on their shares, so it reaches all their devices), and lists this person's open shares under **Your shared folders**, each with **Manage**, so a share whose folder is gone here can still be closed. **Stop sharing** (owner; ends every token at the broker) or **Leave** (participant) closes the record on all of the person's devices; the folder's files stay and sync with the vault again. **Pause** On this device stops syncing the share here, history included; On all my devices puts it on the record, so every device of the person stops at its next refresh, and Off from any of them clears it. The folder stays out of the vault meanwhile, and the Changes tab names it. **Pause shared folders added on other devices** (device-local) pauses a share new to this device in the same save that brings its record, before any pull. **Push shared folders right away** (on by default) pushes a change in a share 2 s after the last file event there (`quietQueue` in `sync/scheduler.ts`), comparing and pushing only that share (`autoPushShares`). Events find their share by the records from launch; before the first refresh, the push refreshes first. Under it **Push only added, moved and deleted files** (on by default) leaves edits for a push, so their gutter marks and the Changes tab show them; open notes still update live. Read-only and paused shares never push, and with it off share paths go to the vault's **Auto-push after change** queue. A push that published nothing signals no one. After a refresh in which an owned share compared fine, the device sends its current S3 credentials to the broker again when they changed, so rotated keys reach participants without a new invite. Renaming a shared folder (or a folder above it) in Obsidian moves it on the person's other devices too, each at its next refresh; where the new path is taken the share keeps syncing at the old one, with a notice. A move into another shared folder or a hidden one is renamed back. -- **Share link** (file menu of a Markdown note, not Excalidraw; disabled with "needs a relay" without one) and `share-note-link` open the window that publishes the open note as a link: expiry, view limit, optional passphrase, images, the note's name. The window shows what the note's copy leaves out; the passphrase is shown once, beside the link, and never stored. **Share links of this note (n)** (file menu, when it has links), `manage-note-links` (named "Manage share links") and **Settings → Sync → Share links** open the list: views left, **Copy link**, **Update** (same link, the note as it is now; views spent stay spent) and **Stop sharing**. A shared note shows a globe badge in the file tree and a header button that open its links, with a dot when the note changed since it was shared; `update-note-links` ("Update share links of this note") updates them. `settings.links` reaches the person's other devices through the vault storage at each refresh, so any of them can copy, update or stop a link; it stays outside device transfer. See [share links](share-links.md). -- **Open source control** (`open-source-control`, ribbon, status menu) opens the view in the right sidebar. On a phone or tablet a leaf waits there once the plugin loads (checked after onload: a reload gets its leaves back from Obsidian only then), so the drawer lists it beside backlinks and the outline; its back arrow on a phone closes the drawer and keeps the leaf. Its tree joins a chain of lone subfolders into one row; a path shows its end when cut. On a phone a row keeps one fixed height: the size goes under the name (none in the tree), and its menu opens with the whole path. -- **Offline** (`snapshot.offline`: the browser reports no network, or the last call to the storage died on the network; classified in `shared/offline.ts`) is shown as a state, but the failed cycle still sets `snapshot.error`, so auto-sync, push and reset keep gating on it and never act on a stale comparison. Displays check `offline` before `error`. The status bar, the status menu and the Changes summary say so in a muted tone, **Push** and **Pull** are off, and History, Timeline and Deleted show an offline state with **Try again** instead of the raw error. When the connection returns, autosync runs its cycle at once; with autosync off MDSync compares once and never pushes or pulls. Interval 0 (one sync after startup) reconnects with a compare only, unless that startup sync never landed. Browser online but a storage unreachable (the vault's, or a shared folder's, shown muted as "offline" apart from a broken one): autosync retries on its heartbeat under the usual backoff. Lists that failed offline load again after the next compare that goes through. -- `refresh` and the Changes tab's refresh button also list the disk, as the first refresh after launch does: Obsidian's watcher misses files copied in bulk from outside the app. Files its index lacks sync anyway, with a notice to restart Obsidian to see them. -- The summary's **ignored** and **not synced** chips open a list of those files (`ui/source-control/excluded-files.ts`): ignored ones grouped by where the rule lives (All devices: `syncignore.md`; This device: the ignore patterns), skipped ones by why (too large, with sizes; name clash; name not allowed; unreadable). A row reveals the file in the file explorer; its menu opens it, copies its path, or for an ignored one **Stop ignoring**. Past 8 files a filter appears; past 200 rows the rest wait for it. -- Every window draws its head, sections, cards and footer with `ui/common/modal-frame.ts` (an icon tile, red for a destructive question; buttons in the footer; a bottom sheet on a phone). The setup wizard keeps its own layout. -- `rebuild-live-note` is available only for the active note bound to a live room. It moves the room into its next generation from the current text, shedding the edit history; attribution survives. -- Presence: each open note's header has a pill with a dot and its state (Live, Joining, Not live, Paused, Not synced; dot only on a phone) and who else has it open, as coloured rings with their initial; tapping it lists them with **follow** (also **Follow** in the share's window): the tab opens each note they open and keeps their cursor in its middle, with a banner under its header naming them and **Stop following**; following ends on that, on a note opened there by hand, on their leaving the space, or on tapping them again. One tab follows at a time, owned by the plugin (`plugin/follows.ts`). A note outside shares shows the mark only with another of your devices in it or relay trouble. The file explorer marks share roots by kind with a headcount of people in its notes and an accent guide down them, and people on the notes they have open (a collapsed folder gathers them); a changed file takes its change's colour (added, edited, moved, deleted) with a dot when made here or an arrow when it waits for a pull, a conflict a red tint and an alert; ignored and skipped rows are dimmed, with an icon on the topmost; the desktop status bar is one item: where sync stands (synced, pending, conflicts, progress, offline, stopped), then the relay dot and who is in shared notes; selecting it opens its menu. The header menu also has **Show who typed what** (shared notes), **Reconnect** (relay down; restarts only that space's socket) or **Open relay settings** (the relay refused this device), **Manage sharing** and **Rebuild live note** (not for a read-only person, who never writes the room). **Real-time sync** switches off presence and live editing together; **Show my open note to others** off keeps the device online but hides its note; **Live editing speed** (device-local, never transferred) sends this device's live edits at once, then at most every 100 ms, 250 ms (default) or 1 s; **File and folder indicators** off keeps the share badge, the tree's way into the share window. Relay state everywhere comes from `realtime.hub.statusOf`. Commands `show-live-status` (named "Show sync and relay status": the status bar item's menu: the sync summary with Resolve, Push, Pull, Compare, then a relay row per space, who is in shared notes; the only way to it on a phone) and `show-note-live-menu` (the note header's menu, **follow** included) reach both without a pointer. On a phone, tapping a mark in the tree (people, the new dot, a change, ignored or skipped) shows its tooltip as a notice. -- `toggle-live-authors` tints, in every live editor, the text people other than this one typed, in their colour, with their name on hover; remembered on this device. Names are the ones the owner invited people by (the owner is "Owner"); in the vault everything is this person's, so nothing is tinted. Attribution is advisory: each client names its own edits. - -## Settings - -- Provide a settings tab with sensible defaults and validation; persist via `this.loadData()` / `this.saveData()`. -- Device transfer exports only the main sync settings as a compact `obsidian://mdsync?d=...` URL/QR. The payload uses short field names, omits default-valued fields, and may compress before encryption when that makes the token smaller. Never include the cached passphrase, passphrase cache settings, or local-only display preferences. Import requires the same passphrase and explicit confirmation. -- An automatic push (autosync push-after-pull, push after changes settle, shares pushed right away) that would publish more deletions than **Deletion limit** (default 5) holds them all back for review, with a notice. **Ask before pushing many deletions** (on by default) turns that off; manual pushes are never held. -- **Change marks beside names** (Interface, under **File and folder indicators**, device-local) drops the dot, arrow or warning sign beside a changed file in the tree; its name keeps the colour. -- Local diagnostics are stored only on the current device in `/plugins/mdsync/logs.json` and surfaced on the Logs page of the plugin settings. They must stay excluded from sync. -- Configuration categories (core settings, hotkeys, plugin list, plugins, snippets, themes) are per device and default to off. A disabled category is invisible to that device: nothing is scanned, diffed, pulled or published for it, and the remote keeps whatever other devices synced. Turning a category off never deletes anything anywhere. MDSync's own plugin folder is never synced. -- **Clear on remote** beside a category is the only way to remove a category from the remote. It bumps that category's reset generation so every device forgets its baseline for it instead of reading the removal as deletions; local files stay everywhere, and enabled devices re-upload on their next push. Confirmation-gated. - -## UI copy - -- Sentence case for headings, buttons, and titles. -- Clear, action-oriented imperatives in step-by-step copy; keep in-app strings short, consistent, free of jargon. -- **Bold** for literal UI labels; prefer "select" for interactions. -- Arrow notation for navigation: **Settings → Community plugins**. - -## Tooltips - -- Never set the `title` attribute. Obsidian already renders its own tooltip from - `aria-label`, so a `title` beside one produces two overlapping tooltips. - `aria-label` is the only tooltip source; write it to read as one, since it is - also the accessible name. -- `appendIconButton` and `makeActivatable` set `aria-label` for you - pass the - text you want shown rather than adding an attribute afterwards. -- A button with visible text needs no `aria-label`: the text already names it, - and adding one only duplicates it in a hover bubble (`appendLabeledButton`). diff --git a/.claude/hunts/data-loss.md b/.claude/hunts/data-loss.md deleted file mode 100644 index e7ae243d..00000000 --- a/.claude/hunts/data-loss.md +++ /dev/null @@ -1,24 +0,0 @@ -# Hunt: silent data loss - -Find where the sync loses, truncates, reverts, resurrects or misplaces content without telling anyone: the bugs users find weeks later. Read `AGENTS.md`, `.claude/sync-invariants.md` and `.claude/platform-contracts.md` first. Breaking a stated invariant or ignoring a platform contract is in scope; an accepted limit listed there is not. - -## What counts - -- Content lost, truncated, reverted or resurrected on any device, or published so. -- A deletion reaching past what the person deleted. -- A file left in a state nobody chose: a step name, half a write, a duplicate. -- A clean status while devices hold different content. - -## Where to look - -Pick an interruption, a platform contract and a sequence, then follow it to the push that publishes the damage. - -- **Interruptions**: the process killed between any two awaits of a pull, push, merge, revert, restore, rename or state persist; one worker failing while others still write; a refresh racing an edit. -- **Platform**: every line of the platform contracts, above all non-atomic writes, mobile `exists()` false on errors, case-blind disks and listings that normalize names. -- **Time**: a device offline for days while peers edit, delete, rename and revert; clock skew; coarse mtimes (FAT, exFAT) hiding a same-size edit from `unchangedSince` and the hash cache. -- **State**: a baseline lagging the disk, a stale comparison reused, a share moved or closed mid-cycle, a journal entry outliving its space. -- **Live**: a room opening on a file the sync is writing, or half wrote; a room's save racing a pull. - -## Proof - -A finding names the trigger sequence and the code path that publishes the damage, best as a failing vitest on `tests/helpers` (`pairedSessions`, `InMemoryAdapter`, `createTestControllerHost`), the way `tests/sync/cut-short.test.ts` kills a write part way. "Could race" without a sequence is no finding. diff --git a/.claude/platform-contracts.md b/.claude/platform-contracts.md deleted file mode 100644 index 657698a8..00000000 --- a/.claude/platform-contracts.md +++ /dev/null @@ -1,14 +0,0 @@ -# Platform contracts - -What Obsidian's `DataAdapter` really does, read from the 1.14.5 app bundle (desktop `FileSystemAdapter`, mobile `CapacitorAdapter` over Capacitor Filesystem). Code that writes, renames or deletes vault files must hold under every line here. The bundle is proprietary: read it outside the repo, never copy it in. - -- **Writes are not atomic.** `write` and `writeBinary` truncate, then write, everywhere: a write cut short leaves a prefix or an empty file. Mobile writes 5 MiB and up as an empty write plus 1 MiB appends, and a failed append deletes the file. No write creates a missing parent folder. See `sync/journal.ts`, `vault/atomic-write.ts`. -- **Rename checks, then renames.** Desktop takes a new case of a name only when it knows its disk is case-blind; mobile never knows, so it refuses every name `exists()` calls taken, the file's own other casing included ("Destination file already exists!"), before touching the disk. See `renameCaseSafe`. -- **`rmdir(path, false)` is no "only if empty".** Mobile always recurses, desktop removes nothing. See `removeEmptyDir`. -- **Mobile `exists()` is false on any error** (permissions, I/O), not only for a missing path: never decide a deletion or an overwrite on it alone. -- **`stat` is null only for a missing path** (ENOENT) and throws on any other error, on both platforms: the way to tell missing from unreadable. -- **Listings lie at the edges.** Desktop `list` rejects a whole folder when one child's stat fails. Mobile `list` turns U+00A0 and U+202F into a plain space and NFC-normalizes, so a listed name may not be the name on disk. -- **Events fire inside the call.** An adapter call's vault events run before its promise resolves: code awaiting the call sees its own events first. -- **Case sensitivity is per disk, not per OS.** Windows, macOS and Android shared storage are case-blind; iOS and Android app-private storage are case-sensitive; Linux depends on the mount. `caseInsensitiveDisk()` only guesses by OS. -- **Local trash** (`.trash`): a taken name gets a number from 2; mobile lowercases the extension. -- **ChromeOS** runs the Android app: no sign of transient ENOENT was found. diff --git a/.claude/releasing.md b/.claude/releasing.md deleted file mode 100644 index 0d64396e..00000000 --- a/.claude/releasing.md +++ /dev/null @@ -1,23 +0,0 @@ -# Releasing - -## Manifest (`manifest.json`) - -- Must include (non-exhaustive): `id` (matches the plugin folder name for local dev), `name`, `version` (SemVer `x.y.z`), `minAppVersion`, `description`, `isDesktopOnly` (boolean). Optional: `author`, `authorUrl`, `fundingUrl` (string or map). -- Never change `id` after release; treat it as stable API. -- Keep `minAppVersion` accurate when using newer APIs. -- Canonical requirements are coded here: https://github.com/obsidianmd/obsidian-releases/blob/master/.github/workflows/validate-plugin-entry.yml - -## Process - -- Add a `## [x.y.z] - YYYY-MM-DD` section at the top of `CHANGELOG.md`: plain sentences for users under `### Important`, `### Features`, `### Improvements` or `### Fixes`, never commit titles. It is the source of truth for release notes. -- Bump `version` (`pnpm version x.y.z`): `version-bump.mjs` refuses a version without a changelog section, then updates `manifest.json`, `packages/plugin/package.json` and `versions.json` (plugin version → minimum app version). -- Push a tag equal to `manifest.json`'s `version` - no leading `v`. The Release workflow checks that tag, manifest and the newest changelog section agree, builds, attests the assets, and creates the GitHub release with that section as its notes. CI runs the same check (`node tools/changelog.mjs check`) on every push. -- The release carries `manifest.json`, `main.js`, and `styles.css` as individual assets. `main.js` and `styles.css` are both build outputs of `pnpm build`. Release artifacts live at the top level of the plugin folder in the vault (`/.obsidian/plugins//`). -- Plugins are submitted at community.obsidian.md (sign in, connect GitHub, Plugins → New plugin); its scan checks the manifest, the release assets, the source and that the build matches it. Fix findings with a new, higher version. - -## References - -- API documentation: https://docs.obsidian.md -- Developer policies: https://docs.obsidian.md/Developer+policies -- Plugin guidelines: https://docs.obsidian.md/Plugins/Releasing/Plugin+guidelines -- Style guide: https://help.obsidian.md/style-guide diff --git a/.claude/rules/history.md b/.claude/rules/history.md new file mode 100644 index 00000000..c6bedbfc --- /dev/null +++ b/.claude/rules/history.md @@ -0,0 +1,69 @@ +--- +paths: + - 'packages/plugin/src/features/sync/history/**' + - 'packages/plugin/src/features/source-control/history/**' + - 'packages/plugin/src/features/source-control/timeline/**' + - 'packages/plugin/src/features/source-control/trash/**' + - 'packages/plugin/src/features/diff/ui/restore-modal.ts' + - 'packages/plugin/src/features/sync/runtime/maintenance*.ts' +--- + +# File history, restore and GC + +History is one encrypted record per push under `history/`, which GC thins into objects per period. Model, publish order, windows and accepted limits: `features/sync/README.md` (History). Engine invariants: `.claude/rules/sync-integrity.md`; hunk restore: `.claude/rules/hunks.md`. + +## Records + +- Every push writes `history/p/.enc` before it publishes (`publishManifestWithHistory` in `features/sync/history/publish.ts`), so a won push always has its record; a lost one leaves a sibling the walk never takes. It holds the diff from the snapshot's parent, which is `compareResult.remote`, not `state.baseline` (they differ whenever another device pushed since the last compare). +- A record write is best-effort: a failure warns and never fails the push; the sealed record waits in memory, keyed by storage identity (a share move or token refresh rebuilds the adapter), and the next push writes it first. A failed publish keeps its record waiting: the manifest may have landed, and a sibling costs only GC. A held-back record lands only under the same data key (it must still decrypt: a re-unlock or rotation builds a new key object) and vault and while every blob it names exists (`stillLands`: a root under `objects/` or `recipes/`, which guards its chunks; past a thousand blobs, checked against one listing of each): a sweep or a reset meanwhile would leave it dangling, so it is dropped as a gap. Records and pins are sealed in space paths, so a retry after a move still names the right files. +- History covers vault files, not the vault's configuration folder: `splitTracked` (`historyTracks(untrackedDir(session))` in `features/sync/history/changes.ts`, any casing) leaves `/` out of the record and puts every hash that side names in `PushRecord.released`. It is cleanup metadata, never shown nor reachable: GC frees it with the record (`freedHashes`), and the sweep keeps whatever HEAD, a pin or a record still names. A config-only push counts no activity, and the Timeline lists no version without a file change unless pinned (`sessionsOf`; the newest shown walked version takes **Latest** when HEAD is hidden, never an off-walk pin; the calendar still shows when no version is listed). A share splits nothing: its scope names the vault's folder too. +- A record carries both sides (`modified.from` / `.to`, the departed entry on `deleted`) and compares every field (`sameEntry`), so a restore never needs a replay and a missing record leaves a detectable gap, not a corrupted chain. +- A merged record (`composeChanges`, used by the GC model in `features/sync/history/model/`) runs from its first parent to its last push: `deleted` keeps the parent's entry for replay, `deletedLast` the content right before the deletion, and `changeEntries` names both. Merge only chain-contiguous runs. +- Readers walk from HEAD only while a record's `parentId` names the next one (`coverOf` in `features/sync/history/model/cover.ts`); past a gap history is not evidence of anything. Order by the walk, never `createdAt` (clock skew). Storage time (the listing's `modified`) dates a record; an undated push takes its parent's listed time, else the newest. +- Storage times run forward along the walk (`forwardTimes` in `coverOf`), so every period is one run of the chain; a stored object is still split into runs (`runsOf`) and every record ends a candidate, so a sibling may fork from inside a run. A GC build replaces an input only with every record the walk took from it: a late parent record re-dates a packed object's records into other groups. Within the horizon only inputs the walk took whole (an off-walk part may be a sibling or lie behind a gap); a counts build takes the rest of its group, off-walk keys included, and is not built when it would replace only earlier counts (rebuilt every run otherwise; the walk still counts what stays). Counts views merge by the larger per hour (`mergeCounts`, `activityOf`), never a sum. +- `readHistory` (`features/sync/history/remote.ts`) lists `history/` once and decodes only keys it has not seen (records never change, objects are named by content); a key gone between listing and GET (a GC retired it) re-lists once. A listed key that does not decode, a newer format included, is `unreadable`: readers show a gap, GC and deep clean must not run on it. + +## Listings + +- `listDeletedFiles` walks deletions, never absences: newest first, a path counts only at its newest change along the walk, so a file deleted, recreated and deleted again reports its latest death, and a lagging walk (starting below HEAD's own deletions) never reports an older one; anything back in HEAD is skipped. A merged record restores `deletedLast`, the content right before the deletion. +- Pins outside the walk are diffed against HEAD separately; those rows are `source: "pinned"` and say "last seen", never "deleted": a pin proves the file existed, not when it went. A pin marks a deleted row `pinned` only for the hash it holds. +- `keptUntil` is the earliest time retention may drop a version: the end of its counts group plus the horizon (`keptUntil` in `features/sync/history/model/periods.ts`), null while pinned or without a horizon; `countsBefore` is the time before which every record is past it, and `stagesOf` the resolutions a record passes through for a horizon (the settings ladder, `ladderOf`). +- HEAD without its record sets `lagging`, a walk stopped at a missing parent `truncated`; the UI warns instead of showing an empty vault as an empty trash (`features/source-control/trash/trash-tab.ts`, `features/source-control/timeline/timeline-tab.ts`). The Trash tab and `listDeletedFiles` skip paths the scope no longer includes. +- `listSnapshots` and `getFileHistory` date a version by `at` (`Dating` in `features/sync/history/types.ts`), the storage time of its newest push, and give `res`, the period its key holds; a pin off the walk has only its own clock and `res` null. `listSnapshots` adds `activityOf`, past the horizon too. +- The vault's last-read activity is kept device-local (`ActivityCache` in `features/sync/history/activity-cache.ts`, Obsidian's local storage `mdsync-activity`), keyed by storage identity so another target never shows it; only reads that happen anyway fill it (`listSnapshots`, GC after a vault push), and a read begun before the kept one is dropped. A remote reset or an adopted vault forgets it (`forget`). The settings overview draws it with no request (`features/settings/activity-card.ts`, `buildCalendar` with versions `null`: no resolutions). +- `getFileHistory` emits a file version at the record that wrote it (its `pushes` are that record's), never at a later snapshot that still holds it; content older than the walk is the oldest record's parent, dated at that record's `firstAt`, and not `replayable` (it cannot be pinned). A version's `pinId` is any pin holding its hash, which may be a later snapshot: pin actions go there. +- Timeline sessions are cut from the walk order with pins still in it (`sessionsOf` in `features/source-control/timeline/sessions.ts`): a pin stands alone, so a session's `composeChanges` never skips a link. +- A snapshot is `restorable` only when replay reaches it from HEAD (`replayTo` in `features/sync/history/replay.ts`) or it is pinned. `replayTo` returns null when lagging or past the walk: a partial replay would invent a state. + +## Restore + +- A restore that puts the vault back is local only: nothing reaches the remote until the person pushes. `planVaultRestore` (`features/sync/history/restore-vault.ts`) is pure, and the confirmation and the operation both run it; the operation re-plans after the confirmation and applies nothing if the plan differs (`sameRestorePlan`). +- It leaves `/` alone, neither writing, removing nor counting it (`planVaultRestore`'s `tracks`): replay keeps HEAD's configuration and a pin may hold an older one. +- It removes only paths the scan actually read (an unreadable directory is unknown, not absent), sends removed files to the trash (`trashPath`), and never touches an ignored, out-of-scope or disk-refused path in either direction. +- Its writes run under a journal claim like a pull's (`restoreVault` in `features/sync/runtime/history-service.ts`) and its target manifest keeps only paths the space owns (`ownedFiles`). Against the plan's own scan, each write asks `coldSince` and each removal `unchangedSince`: an edit saved meanwhile keeps its file. A path the scan skipped (unreadable, or a name this disk cannot hold: `skipUnholdableNames`) is left alone. +- Restore dialogs promise "nothing is pushed until you say so" (`features/diff/ui/restore-modal.ts`); keep that true. Every restore route (file, batch, restore-to, hunks, vault) hands what it leaves to `HistoryServiceDeps.restored` before its first write (a vault restore's removals once its writes landed, its writes under the disk's spelling too); `RestoredFiles` (`features/sync/automation/restored-files.ts`, local storage `mdsync-restored`) keeps those paths out of every automatic push while their local change holds a hash a restore left (null: removed), named inside their space so a moved root keeps them. Every fresh compare settles them (`OperationRunner`'s `onCompared`): a change or conflict at another hash (an edit) or a scanned file with no change (pushed by hand, pulled) ends a hold; a file the compare did not see (ignored, unreadable) keeps it. + +## Pins + +- A pin is one object, `pins/.json.enc` (`features/sync/history/pins.ts`): `{ v: 1, manifest, label?, pinnedAt }` with the snapshot's manifest minus `/`, so it outlives the records it was replayed from. Nothing else flags it: a pin is on exactly while its object reads. +- `setSnapshotPinned` (`features/sync/history/query.ts`) keeps a readable pin's manifest and replays only for a new one; a pin that cannot be read is rewritten, never trusted. Unpinning deletes the object. Both run on the operation queue (`features/sync/runtime/history-service.ts`), in the space of the file whose History asked (`path`), else the vault's. A restore-to reads the version in its source's space (`HistoryDiffRequest.source`, `restoreFileVersion`'s `from`) and writes in the target's. +- A listed pin that does not read (corrupt, or a 1.x bare manifest) is `unreadable` in `readPins`: what it holds is unknown. One gone since the listing was unpinned and is skipped. Decoded pins are cached only by etag: a timestamp may not move on a rewrite. Manifests stay up to `PIN_CACHE_ENTRIES` file entries in all, the info of every listed pin (`readPinInfos`, the Timeline's); both drop pins no longer listed, so a warm read of unchanged pins GETs none. + +## GC and deep clean + +- Never delete an object reachable from HEAD, from any listed push record or history object (every version it names: `changeEntries`, off the walk too), or from a pin (`reachableHashes` in `features/sync/history/sweep.ts`). If any of those cannot be read, delete nothing (deep clean and verify throw): a bounded blob leak is acceptable, a dangling reference is not. +- Sweep only blobs older than any push in flight: `listDated` (`features/sync/remote/uploads.ts`) lists them with their age and `isSettled` decides, `SETTLED_AFTER_MS` is twice `UPLOAD_TRUST_MS`. Another device may have re-uploaded an old hash for a push it has not published. A storage that cannot report object ages cannot be swept (`listDetailed` is required). +- Deep clean and GC's phase 2 share one sweep (`sweepObjects` in `features/sync/history/sweep.ts`; phase 2 passes `freedOnly`): it needs a published HEAD, deletes nothing written in the last day nor any hash a candidate file younger than a day names (one it cannot read fails closed), and bails if HEAD, the pin listing or a new history key (a candidate file too) changed since it listed (neither a pin nor a retried record moves HEAD). It deletes no history record, object or pin; settled candidate files go after the sweep. +- A file's root is `objects/` or `recipes/`, and the sweep takes both as one hash. Chunks (`chunks/`, shared between files) are no hash: a settled one goes only when no surviving recipe names it, every listed recipe the sweep does not delete counting (young and undated too, so a push in flight keeps the chunks it trusted); phase 2 takes only chunks the recipes it deletes named. Doomed roots are judged once, against one clock. When a chunk could go, a surviving recipe that does not read fails the sweep before any delete; a root never needs another recipe's list. Roots go before chunks, and HEAD, pins and history are rechecked after every read, right before the deletes. Recipe reads are kept by etag (`chunksNamed` in `features/sync/content/closure.ts`). +- GC (`collectHistoryGarbage` in `features/sync/history/gc.ts`) runs after a push this device published, at most every 10 min per space, on the quiet queue (`MaintenanceService.afterPush`); a failure only logs. Without object ages (`listDetailed`) it does nothing. +- The horizon is this device's **Keep history for** (`fileHistoryKeep`, a key of `HISTORY_KEEP_MS` in `core/constants.ts`, named by `HISTORY_KEEP_TEXT`; `forever` is `null`), read per session in `app/session-factory.ts`. Each device's GC applies its own, so the shortest wins. +- Phase 1 stops on any unreadable history key: a gap only this run sees would let counts or the horizon take what lies behind it. Each planned object is written under the digest of its whole content, `consumed` included, and read back before anything it replaces goes (`writeHistoryObject`); only keys this run listed are deleted, and what the verified object names in `consumed`, never the plan. Readers recompute every object's key: one whose content does not match is unreadable, never trusted to consume anything. +- Phase 1 deletes no blob: the hashes its retired keys named and the verified objects do not go to `history/g/.enc` before any delete. Phase 2 sweeps a candidate file only once it is settled (`isSettled`, `SETTLED_AFTER_MS`), so a pin or record written around phase 1 is listed by then and keeps its blobs. It runs only once a candidate is a day past settling (`sweepDue` in `gc.ts`) and then takes every settled one: its full listing of `objects/`, `recipes/` and `chunks/` costs a request per thousand blobs, so it runs about once a day, and freed versions stay one to two days. When every freed hash is still reachable it deletes only the settled candidate files and lists nothing. `readHistory` lists `history/g/` in its one call. +- `planGc` deletes only: keys a present object consumes, a settled push that lost the guard (its parent's chain child is another id), another vault's settled keys, and settled keys off the walk whose newest record is past the horizon. +- Maintenance lists only `objects/`, `recipes/`, `chunks/`, `pins/` and `history/` of its own space; a reset deletes chunks after every root. + +## Format fence + +- Every manifest carries `MANIFEST_VERSION` 3 (`buildManifest`), and `fetchRemoteManifest` refuses a higher one: a 1.x client stops at HEAD before any GC or deep clean. Raise it whenever an older client would destroy what the new format keeps. +- 1.x history is deleted, never read: after the first published push of a session per storage and space, history on or off, `clearLegacyHistory` (`features/sync/history/legacy.ts`) deletes every pin that decrypts to a bare manifest, then `history.json.enc`; a failed run is retried at the next push. Pins are scanned even without the log (an interrupted reset can leave them, and one blocks every sweep); a pin it cannot decrypt stays. +- A sweep refuses a HEAD below `MANIFEST_VERSION`: 1.x clients still sync there, and their history names what looks orphaned. diff --git a/.claude/rules/hunks.md b/.claude/rules/hunks.md new file mode 100644 index 00000000..1d2c39bc --- /dev/null +++ b/.claude/rules/hunks.md @@ -0,0 +1,39 @@ +--- +paths: + - 'packages/plugin/src/features/sync/hunks/**' + - 'packages/plugin/src/features/sync/operations/**' + - 'packages/plugin/src/features/diff/**' + - 'packages/plugin/src/features/editor-signs/**' +--- + +# Hunks, diff views and gutter marks + +A view that diffs one pair of texts while the operation recomputes from another applies the wrong hunk. Why, and the flow: `features/sync/README.md`. Engine-wide invariants: `.claude/rules/sync-integrity.md`. + +## Sides and hashes + +- A hunk operation takes both texts from `loadHunkSides` (`features/sync/operations/text-loaders.ts`) with the `EHunkPair` the view used: `Local` is baseline vs local, `Remote` is local vs remote (conflicts too). The projection (`features/sync/hunks/projection.ts`) builds its own sides from the same texts, its baseline through `hunkBaseline`, never `deps.state.baseline` directly. +- Every operation verifies the sha256 of each side against the `expected` hashes the view drew (`assertSidesUnchanged`); a view passes `leftHash` / `rightHash` of its `FileDiffModel`. A file edited since gets an error, never a stale index applied. +- `loadHunkSides` refuses a path outside the sync scope. +- The merge screen's sides come from `getConflictThreeWay` (`features/sync/runtime/file-diff-service.ts`): it refuses a local file whose sha256 is not the compare's, and a `.json` conflict gets base and remote in local's key order and indent (`alignJsonSides`, `features/sync/hunks/json-align.ts`), only when every side is exactly `JSON.stringify` output, so the rewrite loses nothing. + +## Patch order + +- Hunk and segment indices belong to one patch: `computeHunks(left, right)` in `features/sync/hunks/hunks.ts`, called with the same argument order by the view and the operation. `applyHunks` takes the right side for selected segments; keeping the left side of one means selecting the others (`complementSelection`). +- History restore numbers hunks from `computeHunks(version, current)`: `restoreHistoryHunks` (`features/sync/runtime/history-service.ts`) computes in that order, inverts the selection, and checks the working copy's sha256 against the one the view drew (`model.rightHash`). +- Push and revert of one file run in one operation (`localHunksOp`): both derive from the same baseline/local pair, so a revert cannot shift the push's indices. The result keeps the file's line endings (`withEolOf`). +- A hunk push refuses a file with a conflict or a remote change (pull first). A hunk pull advances the baseline for the path only when it takes every segment (`isFullSelection`); a partial pull's baseline would hide the left-behind segments and the next push would overwrite them. +- A diff of a moved file applies no hunks: its sides sit at two paths (`movedFrom`; `hunkHintText` in `features/diff/history-state.ts` says why). Per-hunk actions are off over `HUNK_TEXT_MAX_BYTES`, for a historical change, between two stored versions, and for a history side with no working file. + +## Gutter marks + +- Editor gutter marks are the push/revert segments, never a second diff: `markedChanges` (`features/editor-signs/marks.ts`) runs `computeHunks` and `hunkSegments`, the unit `pushHunk` and `segmentRevert` act on. Blank lines make diffs ambiguous; a mark must show exactly what Push and Revert move. +- `pushHunk` (`features/editor-signs/provider.ts`) sends the baseline hash and the sha256 of the editor's current text as `expected`, so an unsaved buffer never pushes a different hunk. A revert from the popup edits the editor through `segmentRevert` (`features/editor-signs/popup/hunk-revert.ts`), whole lines out of the baseline, terminator included. + +## Size and binary + +- A diff view never loads unshowable content: classify each side from `adapter.stat()`, manifest entry sizes and `KNOWN_BINARY_EXTENSIONS` (`hasKnownBinaryExtension`) before reading or downloading anything (`resolveSide` in `features/sync/hunks/projection.ts`, `localSide` / `decodeRemote` in `features/sync/operations/text-loaders.ts`, `isTextMergeCandidate` in `features/sync/apply/auto-merge.ts`). Only sides that pass are sniffed for NUL bytes. +- Limits are `HUNK_TEXT_MAX_BYTES` (hunk-level actions) and `FORCE_DIFF_MAX_BYTES` (an on-demand "show anyway" diff) in `features/sync/constants.ts`; a known-binary extension is never forceable. Keep this when touching any diff or merge path. +- An absent side reads as empty text: `leftPresent` / `rightPresent` tell absent from an empty file. +- Diff work past `DIFF_BUDGET` falls back to `anchoredHunks` / `changedMiddle`, never an unbounded exact diff (the editor recomputes on every keystroke). +- The diff model cache (`features/sync/hunks/diff-cache.ts`) is bounded by entries and bytes and is keyed by change kind, path, move source and the local, remote and baseline hashes; a new key part is needed for any new input of a model. diff --git a/.claude/rules/links.md b/.claude/rules/links.md new file mode 100644 index 00000000..fecd9da1 --- /dev/null +++ b/.claude/rules/links.md @@ -0,0 +1,60 @@ +--- +paths: + - 'packages/plugin/src/features/links/**' + - 'packages/viewer/src/**' + - 'packages/relay/src/link/**' + - 'packages/protocol/src/link*' +--- + +# Share links + +Flows, snapshot table, trade cases and accepted limits: `features/links/README.md`, `packages/viewer/README.md`. + +## Format and crypto + +- `packages/protocol/src/link.ts` is the only definition of the seal format (plugin seals, viewer opens, relay checks the gate). Never copy it. +- Link `https:///s/#[/]`: key and anchor stay in the fragment, which no server sees. Build and read it with `linkUrl` / `parseLinkLocation`, never by string concat. +- Payload JSON -> deflate -> AES-GCM, AAD `link:`: a blob opens under its own id only. Inflate with a limit (`MAX_PLAINTEXT_BYTES`), deflate ratios reach 1000x. +- Content key and gate are two HKDF outputs of the fragment key (plus PBKDF2 of the trimmed NFC passphrase when protected). Every link has a gate; the relay keeps only its hash, compared in constant time, so the id alone serves and updates nothing. +- The passphrase is never stored: not in settings, records, the vault storage or the viewer. "Remember on this browser" keeps only the derived non-extractable `CryptoKey` and the gate. +- Size, views and ttl caps are `LINK_MAX_*` in the protocol; the relay enforces all, the plugin checks size (`features/links/publish.ts`) and ttl (`features/links/describe.ts`) first. + +## Snapshot (plugin) + +- Everything published passes `features/links/snapshot/sanitize.ts`, then the viewer's DOMPurify. Properties, comments, embedded notes, internal links and vault paths never leave the device. +- Render into an element attached to the document (`.mdsync-link-render`, off screen): detached, callout icons stay empty. Tear down in `finally`: component unload, host removal, MathJax patch restored (`untag`). +- Vault images go only as `data:` URIs: JPEGs always redrawn (drops EXIF/GPS), per-image cap `IMAGE_MAX_BYTES`, total budget; one that fails is dropped and counted, never sent raw. +- Create publishes the exact `Snapshot` the owner previewed; `publishLink` never renders again. The preview frame is `sandbox=""` under its own CSP. + +## Records and trade (plugin) + +- `SharedLinks` (`features/links/shared-links.ts`, `plugin.sharedLinks`) is the only writer of `settings.links`. Every local change goes through `edit`: save, notify, bump `rev` and `author` of each replaced record. Read through `all()` / `of()` (they hide `removed`) and re-read the settings object per call, an import replaces it. +- A record keeps the whole link, key included: the only way to copy or stop it. `parseStoredLink` repairs a record that still has `id` and `url`; never drop one with its key. +- `vault` and `removed` are local-only: `tradedLink` strips them, `parseTradedLink` ignores them. Links never enter a settings transfer. +- Publish: if the record cannot be saved, revoke the link again (live with no key here to stop it); if that fails too the record stays in memory for the next save. +- Revoke at the relay first, then forget; unreachable keeps it listed. Only the relay that made a link manages it (`onRelay`: same origin, no cleartext), asked per call (`adminFor`); otherwise remove from the list only. +- Update keeps id, key, counter, limits and expiry; a protected link needs its passphrase, the relay checks the gate. One update per id at a time (`updating`). +- Rename moves a note's links (`move`); delete detaches them (`detach`, `registerLinkPaths`): live and listed, no Update, a new note at that path starts clean. +- Trade only through `readRecords` / `writeRecord` / `removeRecord` (`features/storage/records.ts`): one `links/.json.enc` per link, vault key, no manifest, no remote tombstones; `isNewer` (rev, then author) decides. +- A removed link is flagged `removed` first, even one never traded (any trade, a failed one too, may have written it), deleted by name (a listing lags), forgotten only after the delete succeeded. +- A copy traded with this storage that it no longer lists was removed elsewhere: drop it, even edited here (removal beats edit). An object that will not decode is never written over or dropped, unless removed here. +- `SharedLinks.sync` replays edits made during a trade (`pending`) above what the trade took in, also those that matched nothing yet. A failed trade warns and never fails the vault refresh (`app/bootstrap.ts`). + +## Relay (`packages/relay/src/link/`) + +- Admin routes call `isAdmin` first. `meta` and `open` are public: missing, expired and spent links all answer 404 `gone`; `open` reads at most 1 KiB of body. +- `LinkStore` is synchronous: a view is counted and a spent link erased in one Durable Object turn, so two opens never share the last view. No `await` between check and count; KV is eventually consistent, not for this. +- A view counts when `open` serves ciphertext, not when the shell loads (preview bots fetch the shell). +- Wrong gates cool down the client (hashed IP, IPv6 as /64), never the link: a per-link lockout lets anyone holding the id lock readers out. +- A creation never inherits a counter (409 if one stands). An update needs a standing link and the same gate (403 `gate`), keeps limits, expiry and counter, never revives a spent link. `ttl` is counted on the relay's clock. +- `handleShellRequest` owns the viewer headers. Never loosen the CSP: no inline script, no `unsafe-eval`, no framing; `style-src-attr 'unsafe-inline'` is the only inline allowance. Link route answers stay `no-store`. +- Only `/s/*` runs the worker first (`packages/relay/wrangler.toml`). A new Durable Object class needs a new migration tag; never edit an old one. + +## Viewer (`packages/viewer/src/`) + +- Payload HTML is attached only through `sanitizeNote` (DOMPurify, `LINK_HREF_ALLOWED`, `LINK_IMAGE_SRC_ALLOWED`); other payload text (the title) goes in as a text node, never as HTML. Buttons and forms are forbidden in notes; the viewer adds its own after sanitizing. +- Never set `location.hash` to a bare `#x`: it replaces the key and kills the link. In-page jumps use `linkUrl(...)` with `replaceState` (`addressOf` in `packages/viewer/src/anchors.ts`) and `preventDefault`. +- Own requests go only to the relay's link routes (`connect-src 'self'`); no analytics, no third-party assets. +- `sessionStorage` holds sealed bytes only, so a reload costs no view; keys and passphrase are never written there. Remembered keys (IndexedDB) expire with the link and are dropped when the relay says gone or refuses the gate. +- Copy as Markdown converts the sanitized page, never the author's file: nothing the snapshot dropped can come back. +- Listeners of a shown state end with its `AbortSignal`; `show` aborts the previous state. diff --git a/.claude/rules/live.md b/.claude/rules/live.md new file mode 100644 index 00000000..4bad948c --- /dev/null +++ b/.claude/rules/live.md @@ -0,0 +1,54 @@ +--- +paths: + - 'packages/plugin/src/features/live/**' + - 'packages/plugin/src/features/sync/live-notes.ts' + - 'packages/plugin/src/features/sync/recovery/**' + - 'packages/plugin/src/features/sync/apply/**' + - 'packages/plugin/tests/features/live/**' +--- + +# Live editing + +Breaking one of these doubles, resurrects or silently drops text typed by someone else. Model, flows and accepted limits: `features/live/README.md`. Hub frames, echo and grants: `.claude/rules/realtime.md`. Paths are relative to `packages/plugin/src/`. + +## Boundary + +- `sync` never imports `live`: the engine owns the `LiveNotes` port (`features/sync/live-notes.ts`), `features/live/cold/cold-sync.ts` implements it, `app/` wires it. Live asks sync for nothing else. +- While a session lives its Y.Doc is authoritative for the note. Live never writes the file: the view that owns it saves. +- Text is LF before the CRDT and the hash, a lone CR included (CodeMirror breaks lines on it), through one normaliser (`toLf` in `core/utils/eol.ts`). + +## Rooms + +- A note is live only in its own space's room: named under that space's keys by the path inside its root (`docIdIn`, `features/live/workspace/space.ts`), its frames only on that space's slot. A note whose space changes (shared, paused, new key) leaves its room; the file sync of one space answers `later` for a note whose room belongs to another. Paused shares stay cold. +- A room is seeded once, only while it has no log: `Seed` from disk only on a `State` with `head == 0`, applied locally only on its `Echo`. An empty room with a log is a deleted note (seeding resurrects it, two seeds double it). An empty room behind what the device knows of it (its agreed seq in that generation, or a successor it was pointed at) lost its log and is never seeded. +- An update leaves the unacked FIFO only on its echo; everything unacked is resent on the next socket's `State`, and frames queued under a dead socket's epoch never act on the new one. A `State` with another log name, or a head behind what the session knows, means the room lost its log: the note rotates onto its next generation from its own text, never refills the old room. +- A room is rebuilt in one hub step or not at all: `Rotate` carries the sender's last seq as `upto`. Only a settled session rotates, a follower of a pointer never seeds, and a pointer other than `docIdFor(path, gen + 1)` leaves the note to the file sync. +- A snapshot comes only from a settled document (nothing pending or unacked), sent only by the lowest writer's client id; compaction after `COMPACT_AFTER` deltas (`features/live/session/room-log.ts`). +- A note reopened while its last session is still closing opens once that one's `Unsub` is out (`features/live/session/closing.ts`). +- A room silent `JOIN_PATIENCE_MS` after its `SUB` leaves the note to the file sync (`features/live/workspace/patience.ts`); a late answer merges in like a reopen. + +## Disk and the file sync + +- Disk enters a room only by three-way merge: `mergeThreeWay(base, disk, room)`, then `patchYText` as inserts and deletes on code points. Never delete-all plus insert, never a diff from room to disk: both overwrite what others wrote meanwhile. A conflict keeps both sides, the room's first. +- The merge base is the note's agreed text (`features/live/cold/agreed-texts.ts`), falling back to the cold baseline; a note whose folder just became a share uses the vault's frozen entry (`shareBases`). +- A `live` mark means the content is exactly that room's text at `seq`: only a hash equal to the agreed text earns it, and an open room with anything pending or unacked marks nothing. Marks `{doc, gen, seq}` are ordered by `(gen, seq)`, never merged, and never replace a remote mark of the same note at an equal or higher order. +- The file sync never writes a note whose room is open: the incoming version goes to the room (`LiveNotes.absorb`), which saves it through the editor before the baseline takes the remote entry. A room behind a snapshot of itself, one that closed or moved during the fetch, a view that could not save, or a note still joining while the hub is up all answer `later`: nothing moves. +- With the hub down a joining note is an ordinary file, and every view showing it is readied for the write (`expectWrite`). A marked version written to a closed note becomes its agreed text, disk first, then the base saved (`putNow`) before the journal lets a room open on it; a merge's base (`grewFrom`) is held the same way. +- Live and cold writes exclude each other: no room opens on a note under an engine write or stays on one cut short (an open marks the note joining before it asks the journal again, a sync claims before its last look for a room). An edit saved meanwhile, or a room come since, keeps the file (`coldSince`). +- Accepting the remote side and revert go the pull's way (`settleLive`, `writeIncoming`), so a room snapshot they put back becomes the base. `LiveNotes.holds` keeps the engine off a note live editing holds. + +## Kinds + +- Live document types are chosen by frontmatter, not suffix (`features/live/doc-types.ts`): a drawing goes live only in the Excalidraw view, never as text. Each kind is a `LiveModel` behind one session (`features/live/model.ts`); `features/live/workspace/editors.ts` pairs it with its view. +- Text binds through a Compartment over the undocumented `editor.cm`. Undo is the room's `Y.UndoManager` on every path (keymap, `beforeinput`, `editor.undo()`): Obsidian's own history would revert what others typed. +- A drawing binds through Excalidraw's undocumented API (`features/live/drawing/excalidraw.ts`, checked against 2.x). Elements go through a staging map drained once per send; remote ones apply with `captureUpdate: NEVER`; the room holds copies (Excalidraw mutates in place). A binding reads and writes only while the view `holds` its file, or one drawing pours into another's room. Excalidraw drops the first write after its own save, so the file sync clears that flag first (`letWriteIn`). +- A read-only person's text note follows its room (`features/live/session/follower-session.ts`): it sends only `Sub`, `Unsub` and `Awareness`, never seeds, rotates or compacts, and joins only when the disk is the room's text, the agreed text or the cold baseline. Drawings stay cold for readers. + +## Renames and deletions + +- A note renamed with its room open takes the room along (`features/live/workspace/rename.ts`): it rotates into the new path's first generation that has no room, probed by `SUB`; meanwhile the note counts as joining, so the file sync waits. Concurrent renames settle on the one the hub took first. +- Another device's deletion of a note open here keeps it as a new file and asks at once (`LiveNotes.kept`, `features/live/ui/deleted-elsewhere.ts`). An unreadable remote text is no deletion. + +## Tests + +- Live sessions run against the relay's own hub and SQLite store in-process (`packages/plugin/tests/helpers/live-hub.ts`) with switches for lost frames and reconnects; prove a lost or doubled edit there before fixing it. diff --git a/.claude/rules/presence.md b/.claude/rules/presence.md new file mode 100644 index 00000000..942aec2d --- /dev/null +++ b/.claude/rules/presence.md @@ -0,0 +1,43 @@ +--- +paths: + - 'packages/plugin/src/features/presence/**' + - 'packages/plugin/src/features/note-header/**' + - 'packages/plugin/src/features/explorer/**' + - 'packages/plugin/src/features/status/**' + - 'packages/plugin/tests/features/{presence,note-header,explorer,status}/**' +--- + +# Presence + +Who is where, the note header, the file tree marks and the status surfaces. Model and accepted limits: `features/presence/README.md`. Paths are relative to `packages/plugin/src/`. + +## Announcements + +- Each device announces `{key, name, device, note, idle}` on every space channel it holds, sealed whole with that space's frame key (`features/presence/announcement.ts`): the relay sees no names or paths. `note` is the path inside the space root, so each mount maps it onto its own. +- `device` is the device's own name in a share (one person's devices share a key), null in the vault (whose keys are devices). Every settings save refreshes presence and rooms, so a device rename reaches both. +- A client can seal any name, not the `who` the hub vouches for its socket: an announcement shows only from a vouched socket whose key is its `who` (`features/presence/channel.ts`), a participant under their invited label. The owner's sockets may carry any key (the vault's devices). +- A file counts only while a tab shows it (Obsidian keeps naming a closed one active); idle after `IDLE_AFTER_MS` without input in any window, popouts included, or with every window hidden (`features/presence/here.ts`). + +## Identity and colour + +- The key groups and colours: the person in a share, the device in the vault. One colour per key everywhere (`personColor` / `personTint` in `core/shared/colors.ts`): cursors, author tint, avatars. Hex, so awareness sends no tint. +- The author tint names a present person by their vouched label; one who left, by their own `users` entry. Attribution is advisory (each client names its own client id); never treat it as proof. + +## Views and caches + +- `People` (`features/presence/people.ts`) caches its per-space and per-note views and drops them at every change of what a channel knows (`onEntriesChange`), a changed partition, or dispose. Returned lists are shared: never edit them. +- `SpaceRecords.partition()` is memoized on the identity of `settings.spaces`, `pausedSpaces` and `localRoots`: replace those fields, never edit them in place, or every reader sees the old partition. +- The tree paints two layers (`features/explorer/row-decorator.ts`): change, link and ignored marks, rebuilt only when the diff, links, partition or ignore state changed; and the presence layer (share badges, people, unseen), recomputed per pass. A people event repaints only rows whose marks changed. The row adapter reads Obsidian's undocumented `fileItems` (`features/explorer/file-explorer-api.ts`). + +## Follow + +- One follow controller on the plugin (`features/presence/follow/follows.ts`), so one tab follows at a time. Following opens the person's presence `note` in the same tab and keeps their cursor in the middle half of the view (`features/presence/follow/follow-scroll.ts`); the watch reads edits too and scrolls a frame later. +- Input never ends following; it ends on **Stop following** (`features/presence/follow/follow-banner.ts`), another note opened there by hand, or the person leaving the space. + +## Header and marks + +- The note header shows its live mark only after the room answers or `SETTLE_MS` passes (`features/note-header/note-presence.ts`), so switching notes never blinks through joining. A vault note shows none unless another device is in it or the relay has trouble. The header is its own button, not `clickable-icon`. +- Scrollbar cursor ticks (`features/live/text/scroll-marks.ts`) scroll there, never follow. +- A read-only share's lock is the editor's (`features/spaces/ui/read-only.ts`: CodeMirror `editable`/`readOnly`), shown in the header; drawings stay in Excalidraw's view mode, and only views put there by the lock are let out. +- The tree's "new" dot (`features/presence/unseen.ts`, vault localStorage): a pull or auto-merge landing content another key published, past the space's first sync, marks those share files unseen unless active; opening clears it, renames and deletions follow it. +- The relay status every display reads is `HubConnection.statusOf` (`features/relay/connection.ts`), worded once in `core/hub/relay-text.ts`: never derive a second status in a surface. Which socket carries a space, and that socket's state, is `HubConnection.relays()`; the status menu groups spaces under it (`relayGroups` in `features/status/live-spaces.ts`) and names a space only where its status differs from its socket's. diff --git a/.claude/rules/realtime.md b/.claude/rules/realtime.md new file mode 100644 index 00000000..292100a6 --- /dev/null +++ b/.claude/rules/realtime.md @@ -0,0 +1,62 @@ +--- +paths: + - 'packages/plugin/src/core/hub/**' + - 'packages/plugin/src/features/relay/connection.ts' + - 'packages/plugin/src/features/relay/channels.ts' + - 'packages/plugin/src/app/realtime.ts' + - 'packages/protocol/src/**' + - 'packages/relay/src/hub/**' +--- + +# Realtime hub and protocol + +Hub model, storage, accepted limits: `packages/relay/README.md`. Wire formats: `packages/protocol/README.md`. Live documents: `.claude/rules/live.md`; presence: `.claude/rules/presence.md`; share broker and tokens: `.claude/rules/spaces.md`. Plugin paths are relative to `packages/plugin/src/`. + +## Formats + +- `packages/protocol/src/frames.ts` and `packages/protocol/src/codec.ts` are the only definition of a frame: plugin, relay and tests import them. A new frame is a `CLIENT` or `SERVER` codec entry; a new field goes last in its body (State's `log`: an older reader stops short); a new `ERefusal` also needs its `ColdCause` in `REFUSED` (`features/live/workspace/room.ts`), or the client cannot say why the note went cold. Plugin and relay deploy apart, so both directions stay tolerant. +- `decodeClient` / `decodeServer` return null for anything malformed, never throw. A text field is at most 255 bytes (one length byte): cut a name before framing it (`MAX_NAME_LENGTH` in `packages/relay/src/hub/access.ts`). +- Limits are protocol constants (`MAX_FRAME_BYTES`, `MAX_SLOTS`, `MAX_DOC_SUBS`, `MAX_DOC_ID_LENGTH`, `MAX_MOVE_NOTE_BYTES`) shared by client and hub. `MAX_DOC_SUBS` follows from the 16 KB socket attachment. +- Every sealed payload names its place as AES-GCM additional data (`SealedFor` in `core/crypto/seal.ts`: `doc:`, `awareness:`, `moved:`, `presence`): the relay cannot move a frame into another document or kind. A rotation is sealed for its target, a rename note for the room it left. A new kind of payload gets its own tag. +- docId = HMAC (`docIds` key) of `#`, 16 bytes (`features/live/doc-id.ts`), so every mount of a share meets in one room. Frame and docId keys are HKDF outputs of the space key, derived where the envelope is unwrapped (`core/crypto/live-keys.ts` over `core/crypto/hkdf.ts`; the content key is not extractable). The chunk naming key is one more (`core/crypto/chunk-ids.ts`). +- The relay sees ciphertext, sizes, timings, a hashed channel and a device id; never a path, file content or key. What else it holds: `.claude/rules/security.md`. + +## Echo and delivery + +- The Echo is the ACK and names the update by the sender's counter `n`. The hub answers a socket in order, so an earlier unacked update was dropped and goes out again at once (`Outbox.ack`, `features/live/session/outbox.ts`); one with no echo for `ACK_PATIENCE_MS`, and all of them after a reconnect, go again (Yjs updates are idempotent). Never ACK before the write is stored. +- A dropped `SUB`, `SEED` or `ROTATE` is not retried: the note turns "unanswered" until the next socket. `SUB` carries `since`: a reconnect gets the tail, not the whole state. +- Over the rate (`FrameLimits`) a frame is dropped unanswered; the echo gap tells the client. A document frame refused for size, too many documents, a read-only grant or failed storage answers `Refused{reason}` to its sender only (`refuse`): unanswered, the client waits forever. A new refusal path answers too; only malformed frames, frames for an unfollowed document and bad `Sub`/`Rotate` fields are dropped silently. +- `Seed` goes only into a document with no log (the loser gets the room to merge into, or text doubles). `Rotate` seeds the target and points the old log at it atomically, only while the log ends at `upto`, else the rotator gets the room: an update after `upto` would be acked here and missing there. A moved document answers every frame with its pointer. +- `LEAVE` drops a socket's awareness at once, but only of clients that socket announced last (a dead socket's `LEAVE` comes after its successor's); every announcement moves the awareness clock on, or a peer that dropped the state never takes it back (`features/live/session/room-awareness.ts`). +- Sends are paced because each update is a hub row (Free: 100k rows a day): at once, then once per `liveSendMs`; cursors per `ANNOUNCE_MS`, and nothing while alone in the room. + +## Hub (`packages/relay/src/hub/`) + +- Admission is the worker's (`handleHubRequest`, `grantFor`): a request with no valid grant never wakes the Durable Object, which accepts only an upgrade carrying `HUB_ADMISSION_HEADER`. An empty `RELAY_SECRET` fails closed. A channel asked twice is admitted once. +- Owner grant: `.` (`deriveChannelGrant`), minted per connection, `GRANT_TTL_S` (a day); refused when expired or minted further ahead than a skewed clock explains (`CLOCK_SKEW_S`). A share token is admitted only while `shareGrantOf` calls it live. A socket outlives its grant. +- The hub is blind: it orders and forwards ciphertext, never merges. Presence is never stored; `JOIN`/`HERE` carry the `who` and `name` of the vouched grant (`vouchedFrame`): nothing a client seals counts as identity. +- Read-only grant: each write answers `Refused(ReadOnly)`; `Signal` is dropped (HTTP 403: it would only wake everyone); awareness has its own ceiling (`READ_ONLY_AWARENESS`, `MAX_READ_ONLY_AWARENESS_BYTES`). +- One SQLite transaction per document frame (`DocStore.atomic`). A throw rolls back, clears the caches and answers `Refused(Unstored)`: unanswered the writer resends forever, and half a seed leaves a row that answers every seed with `State(head 0)`. The echo follows a successful `append` or `seed` in the same run (`logged`): a full log answers `Refused(TooLarge)`, a failed write rolls back and answers `Refused(Unstored)`, never an echo. `Sub` reads before it follows (the attachment is outside the transaction). +- Tails are capped (`MAX_TAIL_DELTAS`, `MAX_TAIL_BYTES`): a log nothing compacts refuses writes with `TooLarge` and the note goes back to the file sync. A snapshot replaces the log only up to `upto` (clamped to the head); an empty or older one is ignored. +- State lives in the socket attachment and SQLite, never in memory beyond caches: the object hibernates between frames, and `ping` is answered without waking it. Sweeps run by alarm only while two or more sockets are open; `leave` announces once. +- Schema: `CREATE TABLE IF NOT EXISTS` plus the settle step in `SqlDocStore`. A new Durable Object class needs a new migration tag in `packages/relay/wrangler.toml`, never an edited one. + +## Refusal and revocation + +- Revoking cuts the hub before it forgets the token (`dropToken` in `packages/relay/src/share/kv.ts`): a failed cut is retried by repeating the revoke. `Hub.dropGrant` keeps the fingerprint `REVOKED_MS` (5 minutes) and refuses it on connect and on HTTP signal, since KV may still admit the token for about a minute. +- A cut slot gets `REVOKED(slot)` and other slots live on; a socket with none left closes `UNAUTHORIZED_CLOSE_CODE`. `purgeChannel` (a share ended) deletes the rows and shuts the channel for good (`closed`): no write can bring it back. +- Client: `HubConnection` marks the slot revoked and ignores its signals; it retries `REVOKED_RETRIES` times (jittered, doubling), a refused socket `UNAUTHORIZED_RETRIES` times (a fresh token can be refused for a minute while KV catches up), then reads `unauthorized` until settings change or the device wakes (`online`, page visible). +- Space channels are `SpaceHub` per space behind `SpaceHubs` (`core/hub/space-hub.ts`); `HubConnection` implements them, live and presence see only the contract. +- Relay state is one answer: `HubConnection.statusOf` -> `relayStatus` (`core/hub/status.ts`). A display never derives its own; the sockets, their state and the spaces on each (full ones apart) are `HubConnection.relays()`. + +## Client socket + +- One `HubLink` per relay, channels addressed by slot = index in `HubRoute.spaces`, the vault first. `hubRoutes` (`features/relay/channels.ts`): vault and owned shares on the own relay, joined shares on their owner's; paused and closed shares get no slot; past `MAX_SLOTS` a space is `full`, never queued. `HubRoute.key` holds everything the socket depends on: a change reconnects that socket only. +- Vault channel = `sha256(storageIdentity)`, share channel = `shareChannel(id)`: the relay never sees an endpoint or bucket. Grants are asked per connection (`channels()`), never reused past their day. +- Grant and token ride in the URL (a browser WebSocket sends no `Authorization`; `Sec-WebSocket-Protocol` is logged unredacted): never log the hub URL. +- `HubLink.send` drops while down: callers resend on reconnect. A send after `PROBE_AFTER_MS` of quiet pings first and a missing answer in `PROBE_MS` drops the link; `KEEPALIVE_SILENCE_MS` of quiet drops it too. Backoff is jittered and restarts on the first message, not on open. +- Listeners outlive socket rebuilds; `onConnectionChange(false)` fires on every restart so state tied to the old link is dropped. `HubLink.signal` posts `/hub/signal` when the socket is down: best effort. + +## Tests + +- Hub logic runs in-process (`packages/relay/tests/hub/`, `packages/relay/tests/helpers/hub.ts`); protocol round trips in `packages/protocol/tests/codec.test.ts`; `pnpm e2e:hub` against `wrangler dev`. diff --git a/.claude/rules/releasing.md b/.claude/rules/releasing.md new file mode 100644 index 00000000..1af720e7 --- /dev/null +++ b/.claude/rules/releasing.md @@ -0,0 +1,32 @@ +--- +paths: + - 'manifest.json' + - 'versions.json' + - 'version-bump.mjs' + - 'CHANGELOG.md' + - '.github/workflows/**' + - 'packages/plugin/package.json' + - 'packages/plugin/esbuild*.mjs' +--- + +# Releasing + +## Manifest (`manifest.json`) + +- Required: `id`, `name`, `version` (SemVer `x.y.z`), `minAppVersion`, `description`, `isDesktopOnly` (boolean, false here: the plugin runs on mobile). Optional: `author`, `authorUrl`, `fundingUrl`. Canonical checks: obsidianmd/obsidian-releases `validate-plugin-entry.yml`. +- Never change `id` (`mdsync`) after release: it is the plugin folder name and stable API. +- Keep `minAppVersion` accurate when using newer Obsidian APIs; `versions.json` maps each plugin version to its minimum app version. + +## Process + +- Add a `## [x.y.z] - YYYY-MM-DD` section at the top of `CHANGELOG.md`: plain sentences for users under `### Important`, `### Features`, `### Improvements` or `### Fixes`, never commit titles. It is the source of truth for release notes. +- Bump with `pnpm version x.y.z`: `version-bump.mjs` refuses a version without a changelog section, then updates `manifest.json`, `packages/plugin/package.json` and `versions.json`. +- Push a tag equal to `manifest.json`'s `version`, no leading `v`. `.github/workflows/release.yml` checks that tag, manifest and newest changelog section agree (`node tools/changelog.mjs check`), builds with `pnpm --filter mdsync run build`, attests the assets and creates the GitHub release with that section as notes. `lint.yml` (CI) runs the same check on every push, then build, lint, typecheck, `pnpm arch` and tests; `.husky/pre-commit` runs lint, typecheck and `pnpm arch`. +- The release carries `manifest.json`, `packages/plugin/main.js` and `packages/plugin/styles.css` as individual assets; the last two are build outputs of the build, never committed. +- The relay ships inside the plugin: `packages/plugin/esbuild.relay-bundle.mjs` bundles `packages/relay` as `mdsync:relay-bundle`, version `+`. It is built in the same run, so a release deploys the relay of its own commit, and relay versions order releases (an older plugin never offers a downgrade). +- `.github/workflows/deploy-relay.yml` is a manual deploy of the relay to a Cloudflare account from repository secrets (`CLOUDFLARE_*`, `RELAY_SECRET`, optional `GDRIVE_*`); it does not touch the plugin release. +- Plugins are submitted at community.obsidian.md (sign in, connect GitHub, Plugins, New plugin); its scan checks the manifest, the release assets, the source and that the build matches it. Fix findings with a new, higher version. + +## References + +- https://docs.obsidian.md, Developer policies, Plugin guidelines (`docs.obsidian.md/Plugins/Releasing/Plugin+guidelines`), Style guide (`help.obsidian.md/style-guide`). diff --git a/.claude/rules/security.md b/.claude/rules/security.md new file mode 100644 index 00000000..c48f7e2d --- /dev/null +++ b/.claude/rules/security.md @@ -0,0 +1,60 @@ +--- +paths: + - 'packages/plugin/src/core/crypto/**' + - 'packages/plugin/src/app/settings/**' + - 'packages/plugin/src/features/transfer/**' + - 'packages/plugin/src/features/links/**' + - 'packages/plugin/src/features/storage/**' + - 'packages/relay/src/**' + - 'packages/protocol/src/**' +--- + +# Security, privacy and compliance + +Follows Obsidian's Developer Policies and Plugin Guidelines. Link model and limits: `features/links/README.md`. + +## Policy + +- No telemetry, ads or deceptive patterns. Offline by default: a request needs a feature that asks for it and a reason the user can see. Analytics, if ever, are opt-in and documented in `README.md` and settings. +- Every service the plugin reaches is listed under "Privacy and network" in `README.md` (the user's storage, their own relay, the Cloudflare API from the wizard only, one GitHub clip on demand). A new endpoint or kind of data sent updates it in the same change. +- Never execute remote code: no `eval`, `new Function`, fetched scripts, self-update. The relay the plugin deploys is the bundle built from the same commit (`packages/plugin/esbuild.relay-bundle.mjs`). +- Read and write only inside the vault. Notes, names and personal data leave the device only for a feature the user turned on (sync, shared folder, share link). +- Consent comes first: publishing a link is the Create button after a preview, deploying or updating the relay is an explicit button, stopping a link or any destructive step asks (`openConfirmModal`). + +## Secrets on the device + +- Secret settings live in one AES-GCM envelope under `secrets` in the plugin's data.json (`app/settings/envelope.ts`, the `SEALED` list); the other settings stay readable. A new secret field joins `SEALED` in the same change or it is written in the clear. +- One blob on purpose: storage credentials and share records (each share's key, a participant's broker token) are kept or lost together; storage without share records would read shared folders as vault files. The vault key also opens share records through the space records in the vault storage. +- The envelope's key, and the passphrase cache's, is the device key (`core/crypto/device-key.ts`) in Obsidian's SecretStorage (`mdsync-device-key`): per vault id, outside the vault, never synced, never a file. A copy of the vault folder opens nothing. +- `DeviceKey.readOrCreate` yields one key however many callers ask (a second would orphan what the first sealed); `read` never creates. The legacy `device.key` file moves into SecretStorage and is deleted. +- An envelope this device cannot open is held and written back untouched until the sealed settings change; a transient keychain failure must not destroy the credentials. The user is told once to import a setup link or set up again. +- Secrets of an earlier build found in the clear are sealed at load (`inTheClear`), not at the next change. +- Passphrase cache: `passphrase.enc` sealed with the device key, bound to the storage identity (`core/crypto/passphrase-cache.ts`); `cachePassphrase` off (`PassphraseManager.applyCachePreference`) or Forget clears it from disk (`clearCachedPassphrase`). +- A settings transfer (setup link, `features/transfer/`) is sealed under the vault passphrase and carries only what the user ticked (storage credentials, scope, automation, relay URL and secret). Never share records, links or the Cloudflare token. +- Recovery after a lost device key: a setup link from another device (storage, passphrase, relay); share records and links return from the vault storage (`spaces/`, `links/`); a guest with no vault storage needs new invites. +- The plugin's own folder is outside the sync scope (`features/sync/scope/scope.ts`), and syncing it with another tool is unsupported: the other device cannot open this device's envelope. +- Other plugins can read SecretStorage as they can read data.json: the envelope defends against copies of the folder, not against code running on the device. + +## Blob envelopes + +- Version byte `0x01` AES-GCM, `0x02` gzip then AES-GCM, `0x03` described (`BLOB_VERSION_DESCRIBED`): gzip-sealed like `0x02`, its plaintext a length-prefixed JSON header then a payload (`encryptDescribed`). `0x02` and `0x03` bind the version as additional data, so a relabelled blob fails; padding hides compressed length. +- `decryptBytes` refuses `0x03` on purpose: it also opens JSON, keys and links, and described content is only for file content (`features/sync/content/`). Only `decryptDescribed` opens it, and its header is validated there before anything is rebuilt. + +## What the relay may see + +- Ciphertext, sizes, timings, a hash of the storage identity, a device id per connection. Never file contents, names or keys: frames and presence are sealed under the space's key with the frame's place as additional data (`core/crypto/seal.ts`). +- For a shared folder with participants it keeps the owner's S3 credentials (KV) to presign and the names invited; with Google Drive it sees the refresh token. For a link: id, size, expiry, view limit and count, protected yes/no, a SHA-256 of the gate. Never title, text or key. +- The relay's operator is the owner (one trust domain, `RELAY_SECRET`) and serves the viewer script, so a hostile operator could read link notes. A relay can also withhold, replay or reorder frames (additional data binds place, not time). +- Admin checks go through `isAdmin` / `secretsEqual` (digests, constant time); an empty `RELAY_SECRET` fails closed. A link's gate is stored as a `fingerprint` hash, and the hub keeps a grant fingerprint per socket, not the token. +- The secret rides every request: a relay over plain http is refused unless local (`isCleartextRemote`). +- `packages/relay/src/share/key.ts` is the whole boundary between a participant's object name and the bucket key. It fails closed (escapes are rejected, not cleaned); every change needs traversal tests. +- A participant with write access can delete the share's objects; history, not revocation, repairs that. A link revoke is immediate. + +## Share links + +- Creating one sends a rendered copy of one note, sealed on the device, to the user's own relay (disclosed in `README.md`). The envelope keeps each link whole, key included; the vault storage carries it sealed under the vault key. The passphrase is never stored. + +## Cleanup + +- Register every DOM, app and interval listener with `registerEvent`, `registerDomEvent`, `registerInterval` or `plugin.register(...)`; a subscription that returns an unsubscribe goes through `plugin.register`. A modal removes its own listeners and timers in `onClose`. +- Teardown is idempotent, and each `onunload` step is isolated (`safely` in `main.ts`) so one throw leaves nothing running. diff --git a/.claude/rules/settings-setup.md b/.claude/rules/settings-setup.md new file mode 100644 index 00000000..735d4841 --- /dev/null +++ b/.claude/rules/settings-setup.md @@ -0,0 +1,56 @@ +--- +paths: + - 'packages/plugin/src/features/{settings,setup,transfer,relay}/**' + - 'packages/plugin/src/core/settings/**' + - 'packages/plugin/src/app/settings/**' + - 'packages/plugin/src/features/*/settings.ts' + - 'packages/plugin/src/app/commands.ts' +--- + +# Commands, settings, setup, relay deploy + +Paths are relative to `packages/plugin/src/`. Wizard steps and modules: `features/setup/README.md`. + +## Commands + +- User commands are `addCommand` calls in `app/commands.ts` with stable ids: never rename or remove one once released. Hidden-when-unavailable commands use `checkCallback`. +- Sync is manual by default (`compare`, `push`, `pull`); autosync and push-after-change are opt-in. Push and pull run a compare preflight and surface conflicts, never choose a side silently. With autosync off the scheduler still compares once after startup (`compareAtStartup`: moves nothing, skipped unless the entered or saved passphrase opens the vault key without asking (`passphrase.unlock()`), so none, or one rotated on another device, waits for the first sync action: launch never prompts). +- `reset-remote-storage` stays confirmation-gated (`confirmRemoteReset`, `features/sync/ui/reset-modal.ts`). It deletes `manifest.json.enc`, `objects/`, `history/`, the 1.x `history.json.enc` and `pins/` under the prefix (history must not outlive its objects), keeps local files, clears local `baseline` and `vaultId`, and keeps the salt and key file so the passphrase-derived key stays valid. +- An automatic push (autosync push-after-pull, after changes settle, shares right away) publishing more than `bulkDeleteLimit` deletions (default 5) holds all of them for review with a notice; `confirmBulkDeletes` turns that off. Manual pushes are never held. +- Slow files (`slowFileSuffixes`; a drawing by its front matter counts as `.excalidraw.md`) saved in the active view, where their edit would queue a push, stay out of the quiet queue and every automatic push, both ends of a move with them (`SlowFiles` in `features/sync/automation/slow-files.ts`, read by `createAutoPushSelector`) until `slowFileSettleSeconds` of quiet, a leave of the view, or 10 min after the first held save; then they queue as any edit. A save while its push is queued holds it again once that push ends. + +## Settings + +- Every write goes through `plugin.saveSettings()`; the plugin's saved settings file is read and written, one write at a time, by `SettingsStore` (`app/settings/store.ts`) and sealed by `SettingsEnvelope` (`app/settings/envelope.ts`). A new secret field joins its `SEALED` list, or it is stored in the clear. +- `MdsyncSettings` is declared in `core/settings/model.ts` (`CoreSettings`: defaults `DEFAULT_CORE_SETTINGS`, bounds `NUMERIC_BOUNDS`, `mergeCoreSettings`). A field typed by a feature is added by that feature through module augmentation of `@/core/settings`, next to its parser: `storageConfigs`, `activeStorageKind` (`features/storage/settings.ts`), `spaces` (`features/spaces/record.ts`), `links` (`features/links/record.ts`). `mergeSettings` and `DEFAULT_SETTINGS` (`app/settings/index.ts`) compose them; a new parsed field joins there, or `tsc` fails. A value from a file or token is clamped by its parser. A removed setting goes in `RETIRED_KEYS` (secrets are deleted, not kept). +- Selectors live with their owner: `activeStorage`, `isStorageConfigured` (storage), `canSync`, `isGuest` (sync), `ownerStorage`, `relayAdmin` (spaces), `isRelayConfigured` (core). A transfer re-parses only what it carries (`mergeTransferredSettings`). +- Rows are declarative fields (`fieldRow`, `group`, `checkRow`, `renderDefinitions`, `EFieldKind` in `core/settings/fields.ts`); a setting stored as is spreads `...bind("key")` for its get/set, type-checked against the key (a Toggle takes a boolean key, Text, Password and Choice a string, Slider a number), and a get/set that normalises or patches more than one key is written out. A Number field with `min`/`max` is a native number input. A failed save shows a notice. Storage's fields are `SettingsFieldSpec`s adapted to fields by `storageRows` (`features/storage/ui/storage-fields.ts`), patching a fresh `storageConfigs[kind]`. Text that applies on typing goes through `onSettled` (a relay URL typed letter by letter must not open a socket per prefix); closing the tab flushes it (`settleTyping`). A scope-affecting field sets `refreshScope`. +- Sections belong to the feature they configure (`links/ui`, `relay/ui`, `spaces/ui`, `sync/ui` with Automatic sync and History (`automation-section.ts`, `history/history-section.ts`, typed by `SettingsHost` and `HistorySectionHost`), `sync/scope`, `transfer/ui`, `storage/ui`); `features/settings/sections/` holds only cross-cutting ones, and `features/settings/tab.ts` orders them (the History page's `loadHistory` and its per-visit cache stay there). +- Never transferred (not in `TRANSFER_FIELDS`): `cloudflareToken`, `cloudflareAccountId`, `liveSendMs`, `showChangeMarks`, `showLiveAuthors`, `cachePassphrase`, `spaces`, `links`, the cached passphrase. Also never published to the vault storage: `useSharedFolders`, `pausedSpaces`, `pauseArrivingShares`, `localRoots`; `spaces` and `links` are traded sealed through it. +- Logs are device-local in `/plugins/mdsync/logs.json` (`core/logs/store.ts`), under the plugin folder `ScopePolicy` never syncs. +- Config categories (core settings, hotkeys, plugin list, plugins, snippets, themes) are per device, default off. A disabled category is invisible: nothing scanned, diffed, pulled or published, and the remote keeps what other devices synced. Turning one off never deletes anything. While `pluginConfigs` is on, `pluginLevel` (`EPluginLevel` Settings, Code or Data; default Settings) is every plugin's level; `pluginLevels` holds device-local overrides for single plugins, only those that differ from it, and they apply with the category off too. Choosing the default in Settings prunes overrides equal to it. Both are transferred with the scope (`p`, `o`); `a` (old plugin code) is retired. +- **Clear on remote** is the only way to remove a category from the remote: it bumps `resetGenerations` so every device forgets that category's baseline instead of reading deletions (`features/sync/operations/config-reset.ts`). Local files stay, enabled devices re-upload, it is confirmation-gated, and older clients refuse the cleared remote by its manifest version, as every publish. + +## Device transfer (`features/transfer/`) + +- `TRANSFER_FIELDS` in `features/transfer/transfer.ts` is an allowlist: a setting not listed there is not exported. Payload uses short keys, omits default-valued fields, deflates only when that is smaller. A retired short key is never reused: older links still carry it. +- Import needs the same passphrase and explicit consent: the import modal asks for typed `IMPORT` after listing the sections it replaces (`importedSections`); the wizard's `importWith` has the passphrase typed beside the link and its button is the consent, with the step saying what it replaces. +- An imported section replaces every field in it: one left default on the other device resets here. In the wizard import the passphrase becomes this device's only when the link carried storage; without storage it opens nothing here. + +## Setup wizard (`features/setup/`) + +- Which steps are done is computed (`isStepDone`, `firstStep` in `features/setup/step-state.ts`), never stored, so the wizard cannot disagree with the settings tab. A fresh install (`loadData()` returned null) starts with history on (`FRESH_INSTALL` in `app/settings/store.ts`; the default stays off, since a setup link leaves defaults out and older links would flip), saves settings first, then opens it on layout ready, so closing it does not bring it back. +- Other entries open it through `plugin.openSetup(step?)`: command `open-setup-wizard`, settings, the Changes tab prompt, the relay section, the link menu without a relay. A background sync without storage shows a notice with **Set up** (`onNoStorage`), never a modal. +- Consent before action: nothing irreversible (R2 bucket, relay deploy, import over settings, replacing a relay) runs without a button that says what it does. A relay that is not this device's, or whose secret is unknown, is updated only after the user types its secret or picks a new name. +- Late results: an async step moves on only while its view is still on screen (`wizard.isShowing(view)`; `isLive()` for a closed wizard), and rechecks before saving settings, since a reopened wizard may hold other input. Async buttons use `runAction` (`features/setup/run-action.ts`); the storage step ignores Back while a connect runs (it would apply to the choice left behind). +- Add a step as `create*Step` in `steps/` plus a `STEPS` entry in `features/setup/wizard.ts`; reuse `choiceCard`, `actionRow`, `busyButton`, `busyLine`, `renderTokenForm`. + +## Relay deploy and update (`features/relay/`, `features/storage/cloudflare/`) + +- The deployed secret is saved the moment the worker holds it (`onUploaded` in `features/relay/deploy/deploy-flow.ts`), not when the wizard closes: closing mid-deploy must not lose a live relay's secret. +- One deploy at a time, module-level and outliving the wizard: a reopened wizard attaches (`runningRelayDeploy`) instead of starting a second. A deploy whose answer was lost is remembered (`failedRelay`) and retried with its own secret, only while no relay is configured (a stale secret must not replace a working relay). +- `planRelay` updates in place only when this device's relay is on the account and answers; a silent relay proves nothing (another device may have changed its secret). A new relay takes `RELAY_NAME` or the first free `mdsync-relay-N`; an existing relay keeps its KV namespace (a new one orphans every share token). +- `activateRelay` is one shared wait that survives a closed wizard, stops on unload (`plugin.unloaded`), and turns `realtimeSync` on once the relay answers with this plugin's build (`useRelay`), unless Manual or Automatic was picked on the wizard's Features step (`enablesRealtime(wizard.syncMode, settings)`, asked when the relay answers; the pick is shared by every wizard of the launch, so a reopened wizard's Manual holds, and a picked Instant lapses once the settings turn Manual). Without a choice, as for an update (`relay-update-modal.ts`), real-time sync stays as it is. +- Relay versions are `+`: `relayBehind` never offers a downgrade and never redeploys an unchanged relay. `mdsync:relay-bundle` is imported only inside `features/relay/deploy/`. +- Update offer (`features/relay/update/relay-update.ts`): once per relay per launch, on hub connect, when this device's token reaches the relay's account. **Not now** holds until a newer build ships (`mdsync-relay-update-skipped`). State is read at use: a forgotten token, a switched relay or an edited, untested secret must not deploy (it would lock other devices out). +- The Cloudflare token is verified before it is kept (`connectCloudflare`); one that R2 refuses is forgotten so the token form returns (`isRefusedToken`). R2 keys derive from it: deleting it stops sync, so the wizard says so; `rekeyR2` and the storage-refused modal repair it. diff --git a/.claude/rules/spaces.md b/.claude/rules/spaces.md new file mode 100644 index 00000000..1881beba --- /dev/null +++ b/.claude/rules/spaces.md @@ -0,0 +1,55 @@ +--- +paths: + - 'packages/plugin/src/features/spaces/**' + - 'packages/plugin/src/app/session-factory.ts' + - 'packages/plugin/src/app/bootstrap.ts' + - 'packages/relay/src/share/**' +--- + +# Shared folders (spaces) + +Model, flows, accepted limits: `features/spaces/README.md`. What the engine does with the partition (frozen entries, `SpaceGoneError`, relative remote paths, vault-wide listings): "Spaces" in `.claude/rules/sync-integrity.md`. Hub and grants: `.claude/rules/realtime.md`. Share links are not spaces: `.claude/rules/links.md`. Plugin paths below are relative to `packages/plugin/src/`. + +## Identity and records + +- A person is a vault's owner (`OWNER`) or a broker token's `participantId`; attribution, presence and revocation work per person (`shareIdentity` in `features/spaces/record.ts`). The relay vouches only the `owner` key: a participant's name is the label the owner invited them by, the owner's is **Your name**, kept on every open owner share (`renameOwner`) so all their devices read one. +- One object per record, `spaces/.json.enc` under the vault key, through `readRecords` / `writeRecord` (`features/storage/records.ts`): concurrent adds never race, one record edited on two devices is last-writer-wins (`isNewer`: `rev`, then `author`). Every edit bumps `rev` and sets `author`. Never in `manifest.json.enc`: the state file (`features/sync/state.ts`) keeps the manifest in plain text. +- A listing etag decides re-reads (a quiet cycle is one list, no GETs); a record that will not decode is never written over (`syncRecords` in `features/spaces/remote.ts`): it may be newer or of a newer format. +- A share's location (endpoint, bucket, prefix) is pinned at creation (`ShareLocation`): re-deriving it from settings orphans its objects. Credentials never enter a record: each owner device signs with its vault's current S3 credentials (`ownerStorageConfig`). Owning needs S3 (`ownerStorage` in `features/spaces/owner.ts`): WebDAV and Drive cannot presign. +- Records belong to the vault storage they were traded with (`settings.spacesVault`, `bindTo`): pointed at another vault the device drops them, never publishes share keys into it. +- Device-local, never published: `useSharedFolders`, `pausedSpaces`, `pauseArrivingShares`, `localRoots`. Replace `settings.spaces`, `pausedSpaces`, `localRoots`, never edit in place: `SpaceRecords.partition()` memoizes on their identity. + +## Partition and pause + +- `spacesOf` (`features/spaces/partition.ts`) is the one partition builder: vault first, then open records by id; a root overlapping one already held is skipped (lower id wins, the other is inert and warned once, `SpaceRecords.inert`). `mountError` refuses the vault root, hidden folders, nested and re-shared roots. Only the owner invites. +- Pause has one rule, `pauseOf`: shares off here (`useSharedFolders`), `record.paused` (published, every device of the person), `pausedSpaces` (this device). Ask it; never read those fields to decide. A paused share stays in the partition (marked `paused`) or the vault would publish its folder; records still trade while shares are off. +- `openShare` and `localShareStorage` (`app/session-factory.ts`) refuse a paused record; a share opens with the key in its record, never the vault passphrase. A guest (`isGuest`) has no vault storage: `openVault` returns null silently, its records stay in settings. +- `admitJoined` throws when a joined share's root holds vault files or another share: the refresh stops until the folder is renamed (a guest's first trade with a new vault). +- `spaces()` in `app/bootstrap.ts` keeps its order: vault session, `admitJoined`, `spaces.sync`, `links.sync` (a failed links trade warns, never fails the refresh), `forgetSpace` of closed and left shares, `followMoves`, `warnInert`, then the partition. Following moves before the partition is what keeps an old root from becoming vault content. + +## Close, leave, revoke + +- Closing is a record edit: `closeRecord` tombstones it (`rev` + `CLOSE_REV_STEP`), the folder returns to the vault. Never delete files, never delete a record. `closeHere` (`features/spaces/ui/share-action.ts`): close, refresh, then `forgetSpace`; `deleteRemote` only for the owner. +- Stop sharing ends the broker's tokens first (relay configured) and aborts when that fails: live tokens would keep writing where nobody reads. An unreachable relay never stops a Leave. A vault whose relay is not the one invites went through warns first (`strandedInvites`). +- A participant's share closes on revocation only when the broker's `unauthorized` still holds `RECHECK_MS` (90 s) later (`createAccessEnded`): broker KV lags ~60 s, a fresh token reads as revoked, and a false close reaches every device of that person. Never shorten it. +- `reset-remote-storage` leaves `shares/`, `spaces/` and `links/`. + +## Moves, invites, ignore + +- A rename of a share root (or a folder above it) is a record edit (`registerShareRenames`: `moveRoot`, cancel, `scheduleScopeRefresh`); into another share or a hidden folder it is renamed back. Other devices follow in `createMoveFollower`, before the partition; `localRoots` holds the old root until followed, a closed share's folder is never moved. +- `createInvite` registers the storage at the broker on every invite (current credentials), issues one token per person (same name, trimmed and case-folded, keeps `participantId`; the old link dies, older duplicates are revoked), remembers `access.relayUrl`, seals under a 60-bit password (`invitePassword`) sent apart. The password is never stored. +- `mountShare` needs a new or empty folder (a full one would ship its files into someone else's share) and refuses an owner's own share, closed too. A link to a share already here replaces its access in place (`renew`): the storage identity is `broker|`, not the relay. Accepting runs `forgetSpace` so no old baseline is read. +- `syncRecords` `unbound` (records made before this device knew the vault): an owner record beats a participant's, an open join outranks the vault's older close. +- Every space reads its own ignore note (`IGNORE_FILE_NAME` in `core/constants.ts`) in its root (`ignoreNoteOf` in `features/sync/scope/ignore.ts`); the vault's rules stop at a share's root, device-local patterns apply everywhere. **Share folder** first writes one exact rule per vault-ignored path into the share's note (`carryVaultIgnores`), or those files reach every participant. + +## Broker (`features/spaces/broker/`, `packages/relay/src/share/`) + +- A participant never holds storage credentials: the broker presigns under their share token (`createBrokerAdapter`); the owner registers the storage (`registerShareStorage`) and issues tokens. `PARTICIPANT_REFUSALS` errors are about the share, never retried. +- `packages/relay/src/share/key.ts` is the whole boundary between a participant's object name and the bucket key: a participant reaches `shares//` only, escapes are rejected (fails closed), every change needs traversal tests (`packages/relay/tests/share/key.test.ts`). Vault GC lists only `objects/`, `recipes/`, `chunks/`, `pins/` and `history/`. +- A token is live only while its participant's pointer names it (`shareGrantOf` in `packages/relay/src/share/kv.ts`). Revoking cuts the hub first (`dropToken`), then forgets the token, so a failed cut is retried by repeating the revoke. Read-only tokens get `read_only` on `put` and `delete`. +- Signing: URLs live `PRESIGN_TTL_SECONDS` (120 s), the client drops its own after 60 s (`SIGNED_URL_TTL_MS`); batches take 1 to `SIGN_BATCH_MAX` keys, `get` or `put` only, one unsafe key rejects the batch; failures fall back to single signing (`prepareReads` / `prepareWrites` hint keys, separate GET and PUT caches). `saveStorage` writes KV only when the registration changed (free tier: 1k writes a day). +- `createShareRegistration` resends credentials hourly, only after the share compared fine (dead keys never overwrite good ones) and only where an invite went before. + +## Tests + +- `packages/plugin/tests/features/spaces/` mirrors the slice (`packages/plugin/tests/helpers/space-records.ts` builds records); the broker is `packages/relay/tests/share/`; real flows: `pnpm e2e:shares`, `e2e:invite`, `e2e:guest`. diff --git a/.claude/rules/structure.md b/.claude/rules/structure.md new file mode 100644 index 00000000..dbe6de11 --- /dev/null +++ b/.claude/rules/structure.md @@ -0,0 +1,60 @@ +--- +paths: + - 'packages/plugin/src/**' + - 'packages/plugin/tests/**' +--- + +# Plugin structure + +Paths in this file are relative to `packages/plugin/src/`. + +## Layout + +- `main.ts` - lifecycle only: onload, one `teardown()` shared by onunload and an onload that finds itself unloaded, and the host methods that delegate to `app/` (`saveSettings`, `scheduleScopeRefresh`). `styles.css` - the cascade order of every stylesheet. +- `app/` - composition root: the host container (`app/host.ts`), bootstrap, commands, events, protocol handlers, runtime hooks (what the sync runtime tells the plugin), realtime coordinator, session factory, scope refresh debounce, settings (`app/settings/index.ts`), its store and envelope, views. It holds only what spans slices: their order (menus in `app/events.ts`, the vault refresh in `app/bootstrap.ts`) and wiring; a slice's own flow lives in the slice. Only `app/` and `main.ts` call a feature's `register*()`. +- `core/` - infra that knows no feature: `chunking cloudflare crypto drawing hub logs settings shared ui utils vault`, plus `core/constants.ts`. `core/drawing` holds the Excalidraw format, scene fingerprint, merge and codec (`codec.ts`, pure: a `compressed-json` scene stored as plain JSON and rebuilt byte for byte). Code moves here when a second feature needs it and it knows no feature. +- `features/` - one slice per feature. **Domain** (state, logic, own flows and modals), lowest first: `storage < sync < live < presence < spaces < links < relay < transfer`. **Surface** (where domains meet in Obsidian): `diff editor-signs explorer note-header settings setup source-control status`. +- A domain imports only lower domains, types included (`domain-order-` in `pnpm arch`). What a lower slice needs from a higher one it declares structurally (`LiveAccess` in `features/live/register.ts`, `PresenceAccess` in `features/presence/people.ts`); a contract several slices share and that knows no feature goes to `core/` (space channels: `SpaceHub`, `SpaceHubs` in `core/hub/space-hub.ts`). + +## Slice shape (`features//`) + +- `features//index.ts` - facade, exports only what other slices import. A slice never imports its own facade. +- `features//register.ts` - Obsidian wiring for the plugin lifetime (commands, events, menus, views), called from `app/`. Teardown goes through `register*` helpers. +- `features//host.ts` - `Host`, what the slice reads from the plugin (see Imports). +- `*.ts` logic: `obsidian` as `import type` where possible, testable without DOM. Obsidian adapters sit in a named sub-area (`links/snapshot/`, `live/text/`). +- `ui/` DOM, modals, menus, settings sections. `*.css` next to what it styles. `README.md` flows, rationale, accepted limits. +- Create a file only when the slice needs it. Past 12 modules in a folder, group by sub-area, never by kind. + +## Imports + +- Another slice only through its facade `@/features/`, another core area through `@/core/`; `@/core/constants` directly. Inside a slice and inside a core area, relative paths. +- New code adds no deep import into another slice: export what is needed from its facade. A facade loads its whole slice, so a test that reaches one may need `importOriginal` in its `obsidian` mock. +- esbuild emits CJS: a facade must not create a runtime cycle. `import type` edges are ignored by the cycle rule. +- What a slice needs from the plugin is its `Host` in `features//host.ts` (`SyncHost`, `SpacesHost`, ...), exported by its facade; `MdsyncPlugin` satisfies it structurally, and only `app/` and `main.ts` see the whole `PluginHost` (`app/host.ts`). A surface that offers a domain's actions extends that domain's host (`ExplorerHost extends SpacesHost, LinksHost`); a member typed above the slice is declared structurally (`SpacesHost.realtime.hub`). Settings sections type their `FieldContext<...Host>`, rows need only `SettingsHost` (`core/settings/fields.ts`). Wiring hosts stay with what they wire (`SyncControllerHost`, `LiveHost`, `SchedulerHost`, `SpaceAccessHost`, `SettingsTransferDeps`); a single module may declare its own (`DeletedElsewhereHost`). +- Navigation into another surface is a host callback, not an import: `openSetup(step)` with the step's literal (`"relay"`), `openSourceControl()`, `openChanges()`, `openTimeline(day?)`; `openDiffView` is the diff slice's. +- Settings: a slice adds the fields typed by its own types to `MdsyncSettings` by module augmentation where it parses them, and `app/settings/index.ts` composes the parsers (`.claude/rules/settings-setup.md`). + +## `pnpm arch` (`packages/plugin/.dependency-cruiser.cjs`) + +- Rules: `no-circular` (runtime), `slice-via-facade`, `root-via-facade` (`app/`, `main.ts`), `core-independent` (core imports no feature or app), `features-not-app`, `domain-order-`, `domain-not-surface`, `surface-`. +- Surface -> surface only: `setup` -> `settings`; `source-control` -> `diff`, `setup`; `status` -> `diff`, `source-control`. `diff`, `editor-signs`, `explorer`, `note-header`, `settings` reach no other surface. +- No baseline: a violation fails `pnpm arch`; fix the import, never add an exception. +- Folder cap: at most 12 `.ts` modules per source folder, css excluded (`packages/plugin/tests/arch/folders.test.ts`, runs in `pnpm test`). + +## Styles + +`styles.css` is bundled to `packages/plugin/styles.css` by `packages/plugin/esbuild.config.mjs`; the output is gitignored, edit the slices. + +- A stylesheet sits in its feature (`features//styles/` or `ui/`), shared ones in `core/ui/styles/`. Each is imported from `styles.css`: core first, features lowest first, then `core/ui/styles/utilities.css` (the shared spinner and `.mdsync-hidden`, late so hiding beats a feature's own display), `core/ui/styles/mobile.css` last. Import order is the cascade: append within a slice, never reorder. +- Phone overrides live next to the component they override; `core/ui/styles/mobile.css` is only the cross-cutting touch-target pass. +- Spacing is Obsidian's 4px grid (`--size-4-*`, `--size-2-*`), never a parallel scale. `core/ui/styles/tokens.css` holds only what Obsidian lacks (`--mdsync-icon`, `--mdsync-touch`, `--mdsync-bar`, `--mdsync-bar-strong`, `--mdsync-radius-pill`, the change-state palette). The bar is the tone change bar, the strong one the accent bar of a chosen side. +- Raw px only for hairlines and off-grid values with no token. Row `min-height` is a contract with `features/source-control/virtual-list.ts`, which measures it and sets `--mdsync-row-height`: do not round it. + +## Conventions + +- TypeScript strict. esbuild bundles everything into `main.js`: no unbundled runtime deps, no Node or Electron APIs (mobile, `isDesktopOnly` is false). The one exception is the symlink detector `core/vault/symlinks.ts`: lazy `import("node:fs")` in `loadNodeFs`, desktop only, a no-op detector on mobile. +- Keep the bundle small, prefer browser-compatible packages, mind mobile memory. Never commit `node_modules/`, `main.js`, `styles.css`. +- One responsibility per module, split past ~200-300 lines, `async/await` over chains, handle errors gracefully. +- A constant lives with its one consumer; only cross-area values go in `core/constants.ts`. +- Scope: the scanner prunes denied, ignored and disabled config directories through `ScopePolicy.canDescend()` before listing. Keep it in step with `includes()` (`features/sync/scope/scope.ts`). Symlinks plug in through the `symlinks` option of `ScopePolicy`, so scanner and diff filter share one place. +- Startup stays light: nothing long-running in `onload`, lazy-initialise heavy work. Batch disk access, avoid vault scans, debounce reactions to file events. diff --git a/.claude/rules/sync-integrity.md b/.claude/rules/sync-integrity.md new file mode 100644 index 00000000..dd3a7f47 --- /dev/null +++ b/.claude/rules/sync-integrity.md @@ -0,0 +1,74 @@ +--- +paths: + - 'packages/plugin/src/features/sync/**' + - 'packages/plugin/tests/features/sync/**' + - 'packages/plugin/src/app/session-factory.ts' +--- + +# Sync integrity + +Breaking one of these silently corrupts user data or publishes remote deletions; every change here needs a test. Map, flows and accepted limits: `features/sync/README.md`. Hunks: `.claude/rules/hunks.md`; history and GC: `.claude/rules/history.md`; platform behavior: `.claude/rules/vault-io.md`; live editing: `.claude/rules/live.md`. + +## Baseline and remote reads + +- The baseline moves only for paths an operation actually wrote (`advanceBaselineForPaths` in `features/sync/remote/baseline.ts`). Adopting a whole published or remote manifest claims every file this device never downloaded, and the next push publishes them as deletions. +- A pull advances the baseline for `written`, never for the asked paths (an undownloaded conflict would turn into a local edit pushed over the remote); a hunk pull only on a full selection (`isFullSelection`). +- A batch stopped by an error keeps what landed: pull and auto-merge save the baseline, then throw (`PullResult.failed`), as a cancel stops; moves record each as it lands. On the old baseline a landed file reads as this device's edit, and a change made elsewhere meanwhile is pushed back. +- A remote read is complete: equal snapshot ids do not make a partial baseline a remote manifest. A 304 serves only the complete cached response of the same storage adapter, key and root (`fetchRemoteManifest`); a stale read is replaced only by a head this session published, never by the baseline (`reconcileRemoteAgainstBaseline`). +- Every file content read and write goes through `features/sync/content/` (`loadContent`, `storeContent`): the owner of the object format. Bytes it rebuilds (a described blob, a decoded drawing, joined chunks) are checked against the file hash, and a header it does not know makes the content unreadable, never guessed. A root is `objects/` or `recipes/` (`readOrder` looks where the size says first); a missing chunk throws, never reads as an absent file. A pull takes a chunk from the file's copy on disk only by its id (a MAC of its bytes), and the joined file is still checked against its hash. +- Upload before publish: a manifest naming objects never uploaded dangles, so a cancelled push publishes nothing (`pushPaths`; uploaded blobs stay). + +## Scope and unreadable + +- Unreadable is not absent: a file or directory the scan could not read goes to `snapshot.skipped` / `unreadableDirs` and out of the diff (`diff` in `features/sync/changes/diff.ts`, `safeList` in `features/sync/scope/scanner.ts`). Read as missing, a locked file is published as a deletion. +- Empty folders merge three-way (`mergeFolderArrays`): one the baseline knew stays published only while both sides have it, so a deletion on either side propagates; a pull never recreates one deleted here since the baseline (`syncFolders`); one in or under an unreadable directory, or this disk cannot open or name, is kept (`foldersToPublish`); another space's leave the manifest (`scope.owns`). +- Disabled scope is untouched: excluded configuration files and empty folders stay in the remote manifest and baseline during ordinary operations; only an explicit category reset forgets their baseline. +- A plugin's level is a filter, not a category: `EPluginLevel` (`core/settings/model.ts`) is Off < Settings (`data.json`) < Code (+ `manifest.json`, `main.js`, `styles.css`) < Data (everything else in the folder, and stray files directly in `plugins/`). A plugin part above its plugin's level stays frozen like a disabled category: on the remote and in the baseline, never read as a deletion (`isConfigAllowed`, `canDescendConfigDir` in `features/sync/scope/scope.ts`). `pluginLevels` (device-local overrides) win over `pluginLevel` and apply with `pluginConfigs` off, so `plugins/` is descended when any level is above Off, `plugins//` at Settings, deeper at Data. `getCategory` still files every plugin path under `pluginConfigs`: an older client resets by that key, and a category of its own would read as remote deletions there. **Clear on remote** therefore clears all plugins whatever their level. +- Obsidian reads plugin code and `community-plugins.json` only at startup: a pull that wrote one (`ScopePolicy.loadsOnStartup`, first sync included) calls the host hook `onPluginsPulled` (`OperationRunner`), which shows the restart notice. +- Configuration resets are not file deletions: generations are scoped by `/`; a newer one makes every device forget that category's baseline files and folders (`reconcileBaselineResetGenerations`) and keep its local files. Ordinary publishes retain generations; every manifest carries `MANIFEST_VERSION` (3), so a client from before resets refuses one (`features/sync/operations/config-reset.ts`). +- A name this disk refuses is skipped, never written (`diskRefuses`): one failed write would stop every pull. Such remote files go to `snapshot.skipped` (`features/sync/changes/remote-names.ts`), such folders are not claimed on disk, a restore leaves them out. +- A drawing is its scene: the scanner fingerprints an Excalidraw file into `scene` (`core/drawing/scene.ts`) and the diff takes equal scenes for equal content (`sameContent`), or every save pushes. Conflicts merge by element (`mergeDrawings` in `core/drawing/merge.ts`, called from `features/sync/apply/conflict-merge.ts`), never by lines: that yields a scene that no longer opens. Notes above the data changed on both sides stay a conflict. +- Auto-merge takes only notes (`.md`) by line and settings JSON by key (`autoMergerFor` in `features/sync/apply/conflict-merge.ts`): a line merge of JSON or plugin code can be clean by lines and broken as a file, silently mixing two plugin versions. Every other conflict waits for a person. +- Settings JSON is Obsidian's own configuration files and a plugin's `data.json` (`ScopePolicy.isSettingsJson`), never plugin code. `mergeJsonByKey` (`features/sync/hunks/json-merge.ts`) merges objects by key and takes arrays and scalars whole; absent is not `null`. A key changed differently on both sides, or a side that is not exactly `JSON.stringify` output (a rewrite would change it, big integers included), stays a conflict. The result keeps local's key order, indent and ending. + +## Publishing + +- A push is done only when its own id reads back: `publishManifestWithGuard` re-reads while it sees a head it replaced; anything but our snapshot id is a `ConcurrentPushError`, so the baseline stays put and the runner re-compares. Taking a replaced head as a stale read lets a sibling's overwrite turn our files into remote deletions. +- Only the head vouches for a blob: a push skips an upload when the head names the hash, or when this device uploaded it for a push never published (`features/sync/remote/uploads.ts`, `UPLOAD_TRUST_MS` 12 h, still probed). Anything else may be swept between probe and publish, so it is uploaded again. A chunk is skipped when the compared HEAD's recipe for the path names it, or this device uploaded it (probed); a recipe is always PUT, after its chunks, so a root present means its chunks landed (`storeContent`). A root that leans on HEAD's chunks stands only under that HEAD, so it stays out of the upload log and a resumed push stores it again; the log keeps the newest `UPLOAD_LOG_MAX` (20 000) entries. +- No automatic push publishes a bulk deletion: more local deletions than `bulkDeleteLimit` (moves excluded) are all held back from every automatic push, logged and reported once per set (`createAutoPushSelector` in `features/sync/automation/auto-push.ts`); the rest still pushes. Only a push by hand, or **Ask before pushing many deletions** (`confirmBulkDeletes`) off, publishes them. The selector also leaves out slow files being edited and files a history restore left (`RestoredFiles`), both ends of a move with them. +- Authorship is set only at publish: `publishFileMap` runs `attribute` (`features/sync/identity/authors.ts`): a changed hash takes the publisher, anything else keeps its parent's `by`. The `authors` table only grows, so an index from any earlier manifest or baseline names the same key; `by` is never content, so equality checks ignore it (`sameEntry`). + +## Spaces + +- Every path belongs to exactly one space: `spaceOf` picks the deepest root holding it, else the vault. A scope owns its root's subtree minus nested roots (`nestedRoots`). A share's root folder is its mount point, in no space: never published, never removed. +- The vault treats share roots like a local ignore: its entries there stay frozen until its next push leaves them out of the manifest (`ownedFiles` in `features/sync/remote/foreign.ts`); frozen, they would hold the folder's blobs for good. The push record still lists them `deleted`, so history GC sweeps the blobs once no record names them; the Trash tab and a vault restore skip paths the vault no longer owns. +- A baseline forgets frozen entries the remote no longer has (`forgetDroppedForeign`, every refresh), so closing a share never reads them as remote deletions; entries the remote still lists stay, so an edit made before closing is a plain modify. A forgotten entry whose share has no baseline of the path yet moves to the vault slot's `shareBases` (`heldShareBases`): never part of the baseline, gone once the share holds the path or the folder is the vault's again. +- The partition is fixed per refresh: a full refresh asks `host.spaces()` once inside the queue, pulling records first; a targeted share refresh keeps the previous partition; vault signals always ask for a full one. `openSession(space, partition)` builds scopes from that list alone (`sessionFiles` in `app/session-factory.ts`): a record arriving mid-cycle must not turn a root into unscanned vault content that a push publishes as deleted. +- Automatic operations reuse a comparison only inside that serialized cycle, with a matching scope epoch and local-file revision (`runOperationNow`). Hidden configuration files are rescanned every time: their writes emit no vault events. +- A share never publishes the loss of all its files: when its scan holds none of the files its baseline does (folder deleted or moved away here, or back holding only new files; a skipped file counts as there), `compare` throws `SpaceGoneError` (`assertSpacePresent` in `features/sync/remote/space.ts`): the share is that device's error, never an empty folder for everyone. `controller.settleGone` settles it, asked by `features/spaces/ui/space-gone.ts`: Restore forgets the share's state, Delete pushes with `Space.goneAccepted` for that one operation. The vault is not guarded. +- Closing a share is a record edit, never a deletion of files: the record is tombstoned (`closeRecord`: `closed`, rev raised by `CLOSE_REV_STEP`) so no device republishes it, and its root returns to the vault scope with its files from the next refresh. Stop sharing then empties the share's own storage through the operation queue (`deleteShareObjects` refuses the vault). +- Every close (here or seen elsewhere) and leaving shares with the vault storage forget the share's state by its id (`forgetShare`, `StorageState.space`), needing no session: a participant's slot keeps one identity across re-accepts, and a later reopen at any root would read the old baseline as deleted files. Stop sharing refreshes before it deletes (`closeHere` in `features/spaces/ui/share-action.ts`), so an operation queued for the share is refused instead of pushing its objects back. +- A paused share stays in the partition: `spacesOf` marks it `paused` (device-local `settings.pausedSpaces`, `record.paused` published for every device, or shared folders off); the refresh skips it and every session refuses it, reads such as history too (`OperationRunner.openSession`, `openShare`), but its root stays out of the vault scope. Dropping it from the partition would hand the folder to the vault and publish it there. +- A moved root moves on every device before any scan: renaming a share root (or a folder above it) edits the record (`moveRoot`, rev + 1), cancels the running operation and invalidates in the same tick (`scheduleScopeRefresh`); results begun before are dropped (refresh epoch), so auto-push never acts on the old partition. A device that learns of the move keeps the folder where it is (`settings.localRoots`) and `createMoveFollower` (`features/spaces/share-moves.ts`) moves it inside `host.spaces()`, before the partition is fixed. A blocked move keeps the share syncing at the old root; a closed share's folder is the vault's and never moved. An old root must never turn into vault content that holds the share's files. +- A space's remote paths are relative to its root; local ones never are: manifests, history records and pins are translated only in `features/sync/remote/space-paths.ts`, called from `features/sync/remote/manifest.ts`, `features/sync/history/remote.ts`, and `features/sync/history/pins.ts`; every read and write of those blobs goes through it, hash-only readers included. Each scan carries forward the hash-cache entries its space does not own, so one space's persist never drops another's. A share's slot of the state file records its root (`StorageState.root`); `projectSession` re-roots a baseline once after a move (`manifestMoved`), and an unmoved baseline keeps its reference so the persister still debounces. +- Vault-wide listings stay inside `objects/`, `recipes/`, `chunks/`, `pins/` and `history/`: shares live under `/shares//`, records under `/spaces/` and `/links/`, inside the vault's prefix. GC, verify and reset never list or delete beyond their own folders. + +## Moves + +- A rename carries its hashes: the scanner trusts a cached hash while size and mtime match, so a rename moves the entry with the file (`StatePersister.carry`, fed by `registerHashCarry` in `app/events.ts`, applied before any read of the state). +- A move acts whole: `pairMoves` (`features/sync/changes/moves.ts`) pairs a gone path with a new one of the same baseline hash in one space (else by file name, only where one to one); anything unclear stays a delete plus an add. The other side's edit of the old path follows the file instead of conflicting. +- Push, pull and revert take both paths when asked for one (`withMoves`, `pullMoves`). A pull renames (`renameLocal`), never over a file that appeared at the new path since the compare; folders it emptied go (`removeEmptied`), never the space root nor one the remote keeps. A revert restores the source and trashes the destination, each only if unedited since the compare. Diff views of a move apply no hunks (`.claude/rules/hunks.md`). +- A rename the disk refuses leaves the move waiting with a warning and the rest of the pull lands; a file left under its step name stops the pull (`StrandedRenameError`; `.claude/rules/vault-io.md`). + +## Writes cut short + +- Every engine content write of vault files goes through the journal (`features/sync/recovery/journal.ts`, entry `writeContent` in `features/sync/changes/content.ts`): Obsidian truncates before it writes, so a killed write leaves a prefix that auto-merge takes as a deletion and pushes everywhere. Order: claim (one per pull or vault-restore batch; a pull leaves out new files that are no room snapshot), stage the content, ask `ready` again (an edit saved meanwhile keeps the file: `coldSince`), write, `landed`, release. +- A write cut short is finished, never read as an edit: the plugin's load puts back what was cut short before anything waits on the network (`restoreCutShort`); `compare` finishes pending ones right after the scan, before it waits for the remote (`finishCutShort`). A prefix of the staged copy, or a missing file in a folder that stays, is rewritten; what cannot be finished yet (anything unreadable) leaves the diff as unreadable. +- A download finished or found landed gives the baseline its entry (`BaseStep`), and the diff is taken against that (`withLanded`): on the old baseline it would read as this device's edit and a change made elsewhere since would be pushed back. The step names the storage and vault it was claimed under, which alone take it, and only while their baseline still holds what it held then; adopting the write never moves it. +- A landed write with a step stays in the journal (`land`: never rewritten, staged copy gone) until the baseline holding its step is saved: by its operation (`acknowledge`) or, that save lost, by the runner after its next compare (`settleLanded`). Dropped first, a lost save leaves the old baseline with no record. The runner saves the journal as every operation ends, so an edit before the next compare still finds the write landed. +- A claim over an unfinished write is refused (`UnfinishedWriteError`); writes follow their share's moves and pass to whichever space holds their path (`adopt`). +- A journal that cannot be read stops the plugin loading: read as empty, its writes would pass for edits. Unloaded (`dispose`), it saves nothing more and refuses claims: an operation still running has its state save dropped, so its releases must not reach the file the next instance reads. A concurrency run rejects only once its workers settle (`runWithConcurrency`), so nothing writes behind the error. + +## Tests + +- Prove a data-loss path with a failing test on the shared harness: `pairedSessions` (`packages/plugin/tests/helpers/session.ts`), `InMemoryAdapter`, `killNextWrite` and `failIo` (`packages/plugin/tests/helpers/faults.ts`), as `packages/plugin/tests/features/sync/recovery/cut-short.test.ts` kills a write part way. diff --git a/.claude/rules/testing.md b/.claude/rules/testing.md new file mode 100644 index 00000000..3f4d8727 --- /dev/null +++ b/.claude/rules/testing.md @@ -0,0 +1,44 @@ +--- +paths: + - 'packages/plugin/tests/**' + - 'packages/*/tests/**' + - 'tests/**' + - 'packages/*/vitest.config.ts' +--- + +# Testing + +Plugin source paths are relative to `packages/plugin/src/`. Run `pnpm test` (all packages) or `pnpm --filter mdsync test:watch`. Scenarios against real processes: `tests/e2e/README.md`. + +## Placement + +- Tests mirror the source tree under `packages/plugin/tests/` and are never colocated: `features/sync/remote/baseline.ts` is tested by `packages/plugin/tests/features/sync/remote/baseline.test.ts`, `core/crypto/seal.ts` by `packages/plugin/tests/core/crypto/seal.test.ts`, `app/` by `packages/plugin/tests/app/`. The Obsidian linter skips `tests/`, not `src/`. +- Other packages keep their tests in their own `tests/` (`packages/{relay,viewer,protocol}/tests`); relay and viewer have their own `packages/relay/vitest.config.ts` and `packages/viewer/vitest.config.ts` (the viewer runs in jsdom). e2e code is `tests/e2e/`, typechecked by `tests/tsconfig.json`. +- Shared helpers in `packages/plugin/tests/helpers/`, the Obsidian runtime stub in `packages/plugin/tests/stubs/obsidian.ts` (`obsidian` resolves to it), the relay bundle stub in `packages/plugin/tests/stubs/relay-bundle.ts`, global setup in `packages/plugin/tests/setup.ts` (window, crypto, localStorage, `navigator.onLine`). A needed Obsidian API is added to the stub, not mocked per test file. +- A file that needs a DOM starts with `// @vitest-environment jsdom` and installs Obsidian's element helpers (`packages/plugin/tests/helpers/obsidian-dom.ts`, `packages/plugin/tests/helpers/element-methods.ts`); the default environment is node. +- Imports: the code under test through `@/`, helpers through `@tests/`, a test imports the module it tests directly (a test may reach slice internals, `pnpm arch` covers `src/` only). + +## What must be covered + +- All domain logic needs unit tests: diffs, merging, concurrency, hunk matching, baseline cache, history, scope, crypto and wire formats. A bug fix lands with the test that fails without it. +- Test behavior through the module's public function, not private helpers. Randomized tests are seeded (`seeded` in `packages/plugin/tests/helpers/seeded.ts`) so a failure replays. +- Data-safety paths are tested by killing them part way: `packages/plugin/tests/helpers/faults.ts` (`killNextWrite`) and `packages/plugin/tests/helpers/cut-short.ts` cut a write at a prefix or at nothing, `packages/plugin/tests/features/sync/recovery/cut-short.test.ts` shows the shape. + +## Harnesses + +- Two devices: `pairedSessions()` and `TestSession` (`packages/plugin/tests/helpers/session.ts`) over `InMemoryAdapter` and `FakeStorage`; `createTestControllerHost` (`packages/plugin/tests/helpers/controller.ts`) for a controller. `useEncryptionKey()` derives the key once. +- Live sessions run against the relay's own hub logic and SQLite store in-process: `LiveHub` (`packages/plugin/tests/helpers/live-hub.ts`, via the `mdsync-relay` devDependency, `memorySql` from the relay's test helpers) with switches for lost frames (`dropIncoming`, `dropUpdates`, `dropOutgoing` on a `connection()`), a stranded socket (`strand`) and wiped logs (`LiveHub.wipe`). `packages/plugin/tests/core/crypto/chaos.test.ts` runs three devices through seeded edits, drops and half-open sockets and demands one text with every edit. A new live behavior gets a case here, not a mock of the hub. +- Cloudflare: `packages/plugin/tests/helpers/fake-cloudflare.ts` routes. Relay and link tests in `packages/relay/tests` use `tests/helpers/` there (`cloudflare:workers` is aliased to a stub). + +## Mocking + +- Mock the module that defines the thing, by its file path: `vi.mock("@/core/ui/notices")`. A mock of a facade (`@/features/spaces`) misses same-slice leaf imports that bypass it; a mock of the leaf also covers every facade that re-exports it. +- Keep what the test does not replace: `vi.mock("obsidian", async (importOriginal) => ({ ...(await importOriginal()), ... }))`. +- Prefer a fake that implements the real interface (`FakeStorage`, `InMemoryAdapter`, `LiveHub`) over `vi.fn` returning canned data. + +## Real Obsidian + +- `tools/obsidian.mjs` (`pnpm obsidian `) drives a running instance over CDP: `launch`, `shot`, `click`, `fill`, `text`, `cmd `, `commands`, `eval` (runs in the renderer, where `app.plugins.plugins.mdsync` is reachable). Obsidian must be started with the port open (`launch`); a normally launched instance exposes nothing. +- `tools/measure-history/` (`pnpm measure:history`) runs `measure.ts` in that instance through `openApp` from `tools/obsidian.mjs`: what each changed version of the unlocked vault costs today, sealed whole and chunked. Read-only, prints sizes only. +- After copying a new build in, reload with `app.plugins.disablePlugin('mdsync')` then `enablePlugin`: `styles.css` is re-injected only on reload. Both `main.js` and `styles.css` are build outputs; run `pnpm build` first. +- Test on iOS and Android where feasible; do not assume desktop-only behavior. diff --git a/.claude/rules/ui.md b/.claude/rules/ui.md new file mode 100644 index 00000000..e8befe56 --- /dev/null +++ b/.claude/rules/ui.md @@ -0,0 +1,57 @@ +--- +paths: + - 'packages/plugin/src/features/**/ui/**' + - 'packages/plugin/src/features/{diff,source-control,explorer,status,note-header,editor-signs,setup,settings}/**' + - 'packages/plugin/src/core/ui/**' + - 'packages/plugin/src/**/*.css' +--- + +# UI + +Paths are relative to `packages/plugin/src/`. Stylesheet order, tokens and row metrics: the structure rule. + +## Reuse `core/ui` (`@/core/ui`) before building + +| Need | Use | +|---|---| +| a message | `notifyInfo`, `notifyError`, `notifyAction` (one button, for what a background task cannot open a modal for), `reportError`, `runWithNotice`, `attempt`, `tapTooltip` (`core/ui/notices.ts`); copying, `copyText` (`core/ui/controls/copyable.ts`). Never `new Notice` | +| a window | `renderModalHead` + `modalSection`, `modalCard`, `modalHint`, `modalWarning`, `modalFooter` (`core/ui/modal-frame.ts`): icon tile (red `tone: "danger"` for a destructive question), footer buttons, bottom sheet on a phone (`asDrawer`). The setup wizard keeps its own layout and is a sheet too (`asDrawer`, its sticky footer flush with the safe area) | +| a question | `openConfirmModal`, `openChoiceModal`, `openPromptModal`, `askPassphrase`, `askNewPassphrase`; a custom modal that returns a value uses `openPromiseModal` | +| icon button, labeled button | `appendIconButton`, `appendLabeledButton` | +| clickable non-button | `makeActivatable` (role, tabindex, Enter and Space) | +| one choice of a few | `renderSegments` (native radios, locks while saving) | +| inline state, warning | `callout`, `alertLine`, `copyable`, `renderPath`, `slideWhenCut` / `measureSlide` (cut paths slide) | +| redraw keeping focus | `renderKeepingFocus`, `focusKey`, `onEnter`, `onLongPress` | +| an element's size | `observeResize`: the observer of the element's own window (settings and popouts are windows of their own), rebuilt when Obsidian moves the tab. Never `new ResizeObserver` | +| wizard-only parts | `choiceCard`, `actionRow`, `busyButton` (error line and accent button of a `runAction` step), `busyLine`, `renderTokenForm` (`features/setup/`) | + +When one falls short, extend it in `core/ui` instead of writing a second. + +## Copy + +- Sentence case for headings, buttons and titles. Short, action-oriented imperatives, no jargon, consistent words across windows (the code says `spaces`, the UI says shared folders). +- **Bold** for literal UI labels, "select" for interactions, arrow notation for navigation: **Settings → Community plugins**. +- A destructive or irreversible action says what it deletes and what it keeps, and is confirmation-gated. +- A guard on a feature says why and what to do (needs a relay, read-only, paused), never a bare disabled control. + +## Tooltips + +- Never set `title`: Obsidian renders its own tooltip from `aria-label`, so both would overlap. `aria-label` (or `setTooltip` on a component) is the only source, worded as one since it is also the accessible name. +- `appendIconButton` and `makeActivatable` set `aria-label`; pass the text, do not add the attribute after. A button with visible text needs none (`appendLabeledButton`). +- On a phone a mark with a tooltip shows it as a notice on tap (`tapTooltip`: file tree marks, activity calendar days). + +## Style + +- Change states use one palette per theme, not the theme's accents: `--mdsync-added`, `--mdsync-modified`, `--mdsync-deleted` (`-rgb` for tints) in `core/ui/styles/tokens.css`, for letters, chips, size deltas, explorer marks, editor change bars and diff lines. Conflicts, warnings, errors and success stay on theme colours. +- Obsidian variables and tokens first: colors `--color-*`, `--text-*`, `--background-*`; spacing, radii and fonts from Obsidian's scales. A fixed colour is only a fallback inside `var(--color-x, #hex)`, one fixed on-color text (`features/presence/ui/presence.css`), or the change-state palette. +- Class names start `mdsync-`. Obsidian's own classes (`.modal`, `.nav-file-title`, `.cm-line`) appear only as the target of an override. +- A changed file shows its change by colour and a mark (dot, arrow or warning sign); `showChangeMarks` turns only the mark off, the name keeps the colour. + +## Phone + +- Check `Platform.isPhone` in script, `body.is-phone` / `body.is-tablet` in css. Touch targets are at least `--mdsync-touch`; the pass is `core/ui/styles/mobile.css`, other phone rules sit beside their component. The activity calendar (`features/sync/ui/history/activity-calendar.ts`) is the one exception: larger cells on a phone, and a tap shows the day as a notice. +- A view that renders differently on a phone redraws when the class changes: `redrawOnPhoneChange`. +- Windows rise as a bottom sheet (`mdsync-drawer`); while a field is typed in, the sheet scrolls whole (`is-typing`), the keyboard leaves little room. +- A row keeps one fixed height on a phone: the size goes under the name, the menu shows the whole path, a cut path shows its end. +- A phone has no hover: what lives only behind a pointer or a hover also gets a command (`show-live-status`, `show-note-live-menu` in `app/commands.ts`). +- A source-control leaf waits in the right sidebar on mobile (`keepInRightSidebar`, after onload: a reload gets its leaves back only then). Its back arrow closes the drawer and keeps the leaf. diff --git a/.claude/rules/vault-io.md b/.claude/rules/vault-io.md new file mode 100644 index 00000000..713378cd --- /dev/null +++ b/.claude/rules/vault-io.md @@ -0,0 +1,46 @@ +--- +paths: + - 'packages/plugin/src/core/vault/**' + - 'packages/plugin/src/features/sync/**' + - 'packages/plugin/src/features/live/workspace/**' + - 'packages/plugin/src/features/spaces/share-moves.ts' +--- + +# Vault I/O and platform contracts + +What Obsidian's `DataAdapter` really does, read from the 1.14.5 app bundle (desktop `FileSystemAdapter`, mobile `CapacitorAdapter` over Capacitor Filesystem). Code that writes, renames or deletes vault files holds under every line here. The bundle is proprietary: read it outside the repo, never copy it in. Wrappers live in `core/vault/` (`packages/plugin/src/core/vault/io.ts`); use them, never the raw adapter call. Engine consequences: `.claude/rules/sync-integrity.md`; the journal's flow: `features/sync/README.md`. + +## Writes + +- Writes are not atomic: `write` and `writeBinary` truncate, then write, everywhere, so a write cut short leaves a prefix or an empty file. Mobile writes 5 MiB and up as an empty write plus 1 MiB appends, and a failed append deletes the file. Engine content writes go through the journal (`features/sync/recovery/journal.ts`); the plugin's own state files through `writeAtomic` (`core/vault/atomic-write.ts`: `.new` temp file and `.bak` backup, never missing). +- No write creates a missing parent folder: `writeBinary` ensures the parent (`ensureDir`), and retries once only when a cached "folder exists" proves stale. `ensureParent` before any other write. +- Every reader of a file `writeAtomic` wrote also tries `.new` and `.bak` (`loadState` in `features/sync/state.ts`, `WriteJournal.load`); state nobody can parse is kept as `state.json.unreadable` before a fresh one is written, and a journal whose read throws stops the plugin loading. +- A name the disk refuses is never written (`diskRefuses`: Windows and Android refuse U+0000-U+001F, DEL and `\/:*?"<>|`): `writeBinary` throws. Windows would put `a:b.md` in a hidden stream, Android fails with `FILE_NOTCREATED`. +- Events fire inside the call: an adapter call's vault events run before its promise resolves, so code awaiting the call sees its own events first. + +## Existence, stat and listings + +- Mobile `exists()` is false on any error (permissions, I/O), not only for a missing path: never decide a deletion or an overwrite on it alone. +- `stat` is null only for a missing path (ENOENT) and throws on any other error, on both platforms: the way to tell missing from unreadable (`staged` in the journal, `folderStays` in `features/sync/recovery/cut-short.ts`). +- `unchangedSince(adapter, path, seen)` guards every overwrite or delete of a file the engine did not just write: a later edit must not be lost. Coarse mtimes (FAT, exFAT) can hide a same-size edit from it and from the hash cache. +- Listings lie at the edges: desktop `list` rejects a whole folder when one child's stat fails; mobile `list` turns U+00A0 and U+202F into a plain space and NFC-normalizes, so a listed name may not be the name on disk. A failed listing is "unknown" (`safeList` in `features/sync/scope/scanner.ts`), never "empty". +- A deletion the engine mirrors counts only when the file is gone afterwards (`deletePath` rethrows while `exists`); a person's deletion of work maybe only here goes to the trash (`trashPath`: system trash, else `.trash`). + +## Folders + +- `rmdir(path, false)` is no "only if empty": mobile always recurses, desktop removes nothing. Remove a folder only through `removeEmptyDir` (list, then `rmdir(path, true)`); relying on the flag wiped every folder above a pulled deletion or move on phones. +- Empty folders are listed by the scanner only for candidates the index shows empty (the index hides dotfiles, so a folder holding only a `.DS_Store` looks empty); `emptyFolders` holds the ones the listing confirms. +- A share's root folder is moved only by `createMoveFollower` (`features/spaces/share-moves.ts`) and `renameInVault`; `following` marks the follower's own rename events. + +## Renames and case + +- Rename checks, then renames: desktop takes a new case of a name only when it knows its disk is case-blind; mobile never knows, so it refuses every name `exists()` calls taken, the file's own other casing included ("Destination file already exists!"), before touching the disk. +- Every rename route goes through `renameCaseSafe` (`renameInVault` in `core/vault/file-index.ts`, `renameLocal` in `features/sync/apply/pull-moves.ts`): a recasing steps through a free `.mdsync-recase.` name (extension kept so a view stays open), tries the target, and puts the file back when the target is taken. Return false means the move did not happen. +- A put-back that fails too throws `StrandedRenameError` ("rename it back"); the pull stops there. Anything that follows renames (live rooms, views) asks `isRecaseStep(path)` and ignores a step in flight. +- `caseInsensitiveDisk()` only guesses by OS. Case sensitivity is per disk: Windows, macOS and Android shared storage are case-blind; iOS and Android app-private storage are case-sensitive; Linux depends on the mount. Never rely on the guess for safety: two remote spellings of one path are skipped as `case-clash` where it says blind (`features/sync/changes/remote-names.ts`). +- `.trash` (local trash): a taken name gets a number from 2; mobile lowercases the extension. ChromeOS runs the Android app: no sign of transient ENOENT was found. + +## Symlinks and Node + +- Symlinks and junctions look like folders to Obsidian but belong to one machine: the scope skips them like device-local ignores (`createSymlinkDetector` in `core/vault/symlinks.ts`), so they are never pushed or read as deletions. Mobile has no Node, so detection is a no-op there. +- `node:fs` is loaded once, lazily, through `import("node:fs")` in `loadNodeFs`, desktop only, before any detector (detection is synchronous). Never `require` it, never import it statically. diff --git a/.claude/security.md b/.claude/security.md deleted file mode 100644 index 27278afb..00000000 --- a/.claude/security.md +++ /dev/null @@ -1,15 +0,0 @@ -# Security, privacy and compliance - -Follow Obsidian's Developer Policies and Plugin Guidelines: - -- Default to local/offline operation; make network requests only when essential to the feature, with an obvious user-facing reason and documentation. -- No hidden telemetry. Optional analytics require explicit opt-in, documented clearly in README.md and settings. -- Never execute remote code, fetch and eval scripts, or auto-update plugin code outside normal releases. -- Minimize scope: read/write only what's necessary inside the vault; do not access files outside it. -- Do not collect vault contents, filenames, or personal information unless strictly necessary and explicitly consented; store or transmit vault contents only when essential and consented. -- Clearly disclose any external services used, data sent, and risks. Features requiring cloud services need explicit opt-in. -- No deceptive patterns, ads, or spammy notifications. -- Secrets on the device: `data.json` keeps the storage credentials, relay secret, Cloudflare token, share records (keys, broker tokens, roots) and share links in one AES-GCM envelope (`secrets`, `settings/envelope.ts`); the other settings stay readable. Its key, and the passphrase cache's, is the device key (`crypto/device-key.ts`) in Obsidian's SecretStorage (`mdsync-device-key`): per vault id, outside the vault, sealed by the OS keychain where Electron's safeStorage works (1.13.7 desktop does), never synced. A copy of the vault folder (backup, git, a cloud folder) opens nothing; earlier builds' plain files and `device.key` are migrated at launch. An envelope this device cannot open is written back untouched until storage is set up again, and a notice says to import a setup link. Other plugins can read SecretStorage, as they can read `data.json`. -- Shared folders: each share's key and a participant's broker token sit in that envelope, like the storage credentials; the vault key also opens them through the space records. To presign for participants the relay keeps the owner's S3 credentials (its KV), so its operator is trusted with them. A participant with write access can delete the share's objects; history, not revocation, repairs that. -- Share links: creating one sends a rendered copy of one note, sealed on the device, to the user's own relay (disclosed in README). The envelope keeps each link whole, its key included, so the owner can copy it again, and the person's other devices get it through the vault storage, sealed under the vault key (`links/`); the passphrase is never stored. A reader who ticks **Remember on this browser** keeps the derived non-extractable key and gate in that browser's IndexedDB until the link expires or is gone, never the passphrase. The relay holds ciphertext, a SHA-256 of the link's gate (derived from the key in the fragment, and the passphrase if any: the id alone serves and updates nothing), the view limit and expiry. Everything published passes `links/sanitize.ts` (no properties, comments, embedded notes or paths) and the viewer's DOMPurify; the viewer page runs under a CSP with no inline script, no `unsafe-eval` and no framing, and the key stays in the URL fragment, which in-page jumps must not replace. The relay's operator serves the viewer script, so they are trusted as the owner. -- Register and clean up all DOM, app, and interval listeners with the provided `register*` helpers so the plugin unloads safely; teardown is idempotent so reload/unload leaks nothing. diff --git a/.claude/share-links.md b/.claude/share-links.md deleted file mode 100644 index d9ed18e8..00000000 --- a/.claude/share-links.md +++ /dev/null @@ -1,279 +0,0 @@ -# Share links - -Status: built (protocol, relay, viewer, plugin), tested in-process and end to -end (`pnpm e2e:links` against `wrangler dev` and Chrome, `pnpm -e2e:links-obsidian` through a real Obsidian). Share one note by a link that opens in any -browser, with optional passphrase, view limit and expiry. Not the same as a -shared folder ([shares](shares.md)): no accounts, no sync, a read-only snapshot. - -## Decisions - -| Decision | Why | -| --- | --- | -| The plugin renders the note to HTML (`MarkdownRenderer`) and uploads that, sealed | callouts, math, mermaid, code, tasks and other plugins' blocks come free and keep following Obsidian; the viewer needs no markdown parser | -| End to end: random key in the URL `#fragment`, the relay stores ciphertext | same zero-knowledge as the rest; the fragment never reaches a server | -| The viewer is a static package served by the relay worker (Workers Static Assets) | one deploy, one origin, no CORS, no third-party host | -| One `Link` Durable Object per link holds blob, counter, gate, expiry | view limit must be atomic; KV is eventually consistent (a fresh blob could miss, a spent link could re-serve) | -| A view is counted when the ciphertext is served, not when the page loads | link-preview bots fetch only the shell | -| Every link has a gate derived from the fragment key (plus the passphrase when there is one), checked by the relay before it serves or updates | the id alone burns no view and yields no ciphertext; a wrong guess burns no view; operator alone cannot decrypt | -| Seal format lives in `packages/protocol` | plugin and viewer share one source of truth | -| Link list travels through the vault storage (`links/.json.enc`, vault key), LWW, no tombstones | any of the person's devices can copy, update or stop a link; the link itself (with its key) must be re-copyable | - -## Link format - -`https:///s/#[/]`: `id` 16 random bytes base64url, `key` -16 random bytes base64url, `anchor` an optional heading slug, URI-encoded -(base64url has no `/`, so it cannot run into the key). The whole fragment stays -in the browser. - -Payload: `{title, html, createdAt}` (`createdAt` is the snapshot time) -> JSON --> deflate -> AES-GCM. Content key = HKDF(`key` [+ PBKDF2(trimmed passphrase, -salt) when protected]); AAD `link:`. A second HKDF output (other `info`) is -the **gate**, with or without a passphrase; the relay stores only its hash and -compares it in constant time. A salt is stored exactly for protected links. - -The relay knows: id, size, expiry, view limit and count, protected yes/no, -timings. Not the title, text or key. - -## Relay (`packages/relay/src/link/`) - -| Route | Auth | Does | -| --- | --- | --- | -| `PUT /link/` | admin | body is the sealed bytes; query `maxViews`, `ttl` (seconds, counted on the relay's clock, so a wrong device clock cannot misdate it); headers `X-Mdsync-Gate` (required), `X-Mdsync-Salt` (protected links). Creates (409 if one stands) and answers `{expires}`; `?update=1` replaces only the blob of a standing link (404 when gone) and needs the same gate (403 `gate` otherwise, so a mistyped passphrase cannot re-key it), keeping limits, expiry and counter: an update never brings a spent link back and a creation never inherits a counter | -| `DELETE /link/` | admin | revoke: `deleteAll` | -| `GET /link//status` | admin | `{views, maxViews, expires, protected, size}` for the plugin's list | -| `GET /link//meta` | none | `{protected, salt}`; counts nothing; 404 when gone | -| `POST /link//open` | none | `{gate}` (body capped at 1 KiB) -> sealed bytes, `X-Mdsync-Views-Left` when limited, `X-Mdsync-Expires` when it expires; counts a view; 401 wrong gate; 429 in cooldown; 404 for missing, expired, spent alike | -| `GET /s/` | none | viewer shell from `ASSETS` | - -- `Link` DO (SQLite, migration `v3` in `wrangler.toml`): blob in rows of at - most 1 MiB (a SQLite value caps at 2 MB), total cap 6 MiB sealed. `open` - runs in one DO turn: expiry, cooldown, gate, `views++`, delete everything - when `views >= maxViews`. An alarm at `expiresAt` deletes too. -- Gate failures cool down the client, never the link (anyone holding only - the id could lock the readers out otherwise): after 5 in a row from one - client (`CF-Connecting-IP`, an IPv6 reduced to its /64, hashed) a cooldown of - 1 min, doubling, capped at 1 h, during which even the right gate is refused - for that client. The gate is checked in the Durable Object's synchronous - turn on a hash the worker computed, so counting stays atomic. 128 clients - are remembered per link, the least recent first. -- Response headers on the shell: CSP `default-src 'none'; script-src 'self'; - style-src 'self'; style-src-attr 'unsafe-inline'; img-src data: https:; - connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors - 'none'`, `Referrer-Policy: no-referrer`, `X-Robots-Tag: noindex`, `Cache-Control: - no-store` on `open`. -- `wrangler.toml`: `[assets] directory = "../viewer/dist"`, `binding = "ASSETS"`, - `run_worker_first` so `/hub`, `/share`, `/link`, `/auth` keep going to code. - -## Viewer (`packages/viewer`) - -Vanilla TS, esbuild to `dist/`. States: loading, passphrase form, content, -gone ("expired or reached its view limit"), error. - -- Reads `id` and `#key`, `GET meta`, asks the passphrase if protected, `POST - open`, decrypts with `@mdsync/protocol`, inflates (`DecompressionStream`), - sanitizes with DOMPurify (SVG on, scripts and handlers off), injects. -- Caches the sealed blob in `sessionStorage` per id: a reload decrypts locally - and costs no view. Views count opens, not people: another tab or browser - spends one. -- **Remember on this browser** (passphrase form, off by default: a shared - computer must not keep a note by accident) keeps the derived keys in - IndexedDB (`keys.ts`, `idb-keyval`): the non-extractable AES `CryptoKey` and - the gate, never the passphrase. Kept until the link's expiry (each visit - erases every expired entry), or until the relay says it is gone; a kept gate - the relay refuses is dropped. -- A passphrase is trimmed before it is stretched (`protocol`), so a pasted - trailing space is no wrong attempt. -- CSS written once (`viewer.css` page and layout, `note.css` the note, - `sidebar.css`), on Obsidian's variable names (`--code-keyword`, `--h2-size`, - `--color-blue-rgb`...) so its SVG reads them and a theme could set them: - typography, callout colour per type, Prism tokens, checkboxes, tables, - footnotes; light and dark by `prefers-color-scheme`; print styles. -- The reading view's behaviour is the viewer's, since the snapshot carries no - script: `sections.ts` nests the flat top-level blocks under their headings - (footnotes stay out); a click on the heading or its chevron folds it. - `anchors.ts` gives each heading a `#` button: it copies the link with the - heading's slug, puts it in the address (`replaceState`, key kept) and - scrolls there; a load or `hashchange` with an anchor jumps to it, unfolding. - `code.ts` puts a **Copy** button on each code block. A note opening with an - H1 equal to its name shows the name once. -- `sidebar.ts`: a column left of the note (a panel behind a menu button on a - narrow screen) with a card (views left, expiry from `X-Mdsync-Expires`, - **Copy as Markdown**, **Wide text** kept in `localStorage`) and `outline.ts`, - the headings (3 or more) marking the one being read. **Wide text** only - applies from 66rem up (below it the toggle is hidden); a paragraph holding - only an image (`images.ts`, `lone-image`) is centered while wide. -- **Copy as Markdown** (`markdown.ts`, turndown + GFM) converts the sanitized - page, not the author's file, so nothing the snapshot dropped can come back. - Callouts become `> [!type]` blocks (fold kept), tasks `- [x]`, tables GFM; - a formula is written back as TeX from `data-tex` on its `` (set by the - plugin's `math.ts`); vault images (`data:`) and drawings are left out. -- The tab icon is an inline SVG data URI in `index.html`: the CSP allows images - from `data:` and `https:` only, so a file served by the relay would be blocked. -- Footer text only, no analytics, no external requests of its own. - -## Plugin (`packages/plugin/src/links/`) - -- Entry: note file menu **Share link** and command `share-note-link` (stable - ID); hidden for non-markdown and Excalidraw files; disabled with the reason - when no relay is set (`RELAY_TEXT["no-relay"]`). -- Modal (`ui/links/share-link-modal.ts`): **Expires** (5 minutes, 15 minutes, - 1 hour, 1 day, 7 days default, 30 days, never, or **Pick a date…** with an - exact local date and time, 1 minute to 365 days ahead), **Views** (1, 5, 25, - unlimited), **Passphrase** - (optional, at least 8 characters, **Generate** uses the invite password - generator), **Include images** (on), **Show the note's name** (on), and a - line saying what was left out (counts from the snapshot, rerun when images - toggle). **Create link** then shows the link and the passphrase with - **Copy**; the passphrase is never stored, so the modal does not close while - the link is being made. -- Snapshot (`snapshot.ts`): `MarkdownRenderer.render` into an element - **attached** to the document (hidden off screen) with a throwaway `Component`: - detached, callout icons stay empty ``s, which Obsidian fills on insert. - Wait until it settles (images loaded, math rendered; 5 s cap). Then - `sanitize.ts`, a pure DOM pass. What the renderer really emits (spike on - Obsidian 1.13, `temp/spike-render.ts`) and what it becomes: - -| In the rendered DOM | Becomes | -| --- | --- | -| `pre.frontmatter` (raw YAML, hidden by an inline style) | removed: it holds every property, secrets included | -| `a.internal-link` (any vault link, also `[x](Other.md)`) | its text (alias or `Note > Heading`), no element | -| `a.tag` (`href="#tag"`) | its text in `span.tag` | -| `a.external-link` | kept; the viewer adds `rel` and `target` | -| footnote `a[href^="#"]` | kept, its `target` and `rel` dropped | -| `span.internal-embed.markdown-embed` (the other note's whole body inlined) | removed, counted; never published | -| `span.internal-embed` that is audio, video, pdf, missing (`mod-empty-attachment`) | removed, counted | -| `span.image-embed > img[src=app://...]` | `img` with a `data:` URI read from the vault by the span's `src` link text; width kept; over 1600 px re-encoded smaller; per image 1.5 MiB, total within the cap, else dropped and counted | -| external `img` | kept (the viewer's IP goes to that host; `no-referrer` is set) | -| `%%comment%%`, `` | dropped by the renderer, leaving an empty `

`: empty paragraphs removed | -| `button.copy-code-button` | removed | -| `.callout-content[style="display: none"]` (folded) | style removed; `is-collapsed` on the callout and the viewer's CSS fold it | -| `.mermaid-wrapper.is-guarded` (the vault has not allowed Mermaid) | replaced by its source as a code block; a rendered `svg` is kept | -| `mjx-container` (MathJax CHTML: per-glyph rules in a runtime stylesheet, fonts loaded from `app://`, no TeX kept) | replaced by MathML. `math.ts` patches `window.MathJax.tex2chtml` (the main window's global; `activeWindow` is not it) while a snapshot runs, tagging each node with its TeX and display mode, then converts with `MathJax.tex2mml`. The viewer's browser draws MathML itself: no stylesheet, fonts or payload field travel. A formula MathJax cannot convert stays as its TeX in `code`. | -| `node-insert-event`, `data-href`, `dir`, `contenteditable`, `draggable`, handlers | removed; other `class` and `data-*` kept | -| task checkboxes | disabled | - -Properties are never published (no option): the renderer does not draw them. - -- Publish: seal (protocol), then `PUT /link/` through - `storage/adapters/link-broker.ts` (beside `share-broker.ts`, `requestUrl`, - admin header); `relayAdmin` moves from `ui/shares/share-action.ts` to - `settings/model.ts` beside `RelayConfig`, so links never import `ui/shares`. - Then record `LinkRecord` (`links/record.ts`: id, url with key, path, - showTitle, createdAt, publishedAt, expiry as the relay set it, view limit, - salt, images, detached, `rev`, `author`) in `settings.links` (never in device - transfer). If the record cannot be saved the link is revoked again, or it - would be live with no key here to stop it. Loading keeps any record with an - id and a link (`parseStoredLink` repairs the rest, a record of the first - builds starts at `rev` 0): a record is never dropped with its key. An older - relay answers `not_found`: the error says to redeploy it. -- `SharedLinks` (`links/shared-links.ts`, `plugin.sharedLinks`) is the only - writer of `settings.links`: add, remove, `published` (Update), `move` - (rename), `detach` (the note was deleted: its links stay live and listed - under Manage, with no Update, and a new note at that path starts clean); - each change saves, notifies subscribers and signs the records it replaced - (`rev + 1`, this device). Add and remove also refresh the vault, so the - other devices hear soon. -- Trade (`links/remote.ts`, `sync` inside `host.spaces()`, after the space - records): one object per link under `/links/`, read through - `storage/records.ts`. Local-only fields `vault` (storage identity last traded - with) and `removed` never leave the device. A removed link is deleted by name - (a lagging listing must not keep it), then forgotten; a failed delete keeps - it for the next trade. A copy traded with this storage that it no longer - lists was removed elsewhere and is dropped, even if edited here: removal - beats edit. One that will not decode is never written over or dropped, - unless removed here. Edits made while a trade runs are replayed onto its - outcome, above what it took in, also those that matched nothing yet. A - removed link is always flagged first, even one never traded: any trade, a - failed one too, may have written it. Known risk: two devices that each still hold a link removed on a - third can bring it back as a list entry; its relay payload stays gone. -- Shared-note marks: `noteLinks` (`links/note-links.ts`) gives a note's - unexpired links and `stale` (`file.stat.mtime > publishedAt`; `publishedAt` - is taken just before the note is read, and a pulled write gets a local - mtime). A `globe` badge in the file tree (`mdsync-published-badge`, shown - even with file indicators off; not `link-2`, which marks a symlinked path) - and a header button on the open note (`ui/links/note-link-action.ts`) open - the note's links; a dot marks stale. The list starts a stale row with - "Changed since it was shared." Command `update-note-links` updates the - active note's links. -- Management (`ui/links/manage-links-modal.ts`, opened by the command **Manage - share links**, the settings Sync tab's **Share links**, or the note menu's - **Share links of this note (n)**): a row per link with views left (status - call), expiry, **Copy link**, **Update** (re-render, same id and key, - counter, limits and expiry kept; a protected link asks for its passphrase - and the relay refuses one that is not the link's) and **Stop sharing** (revoke at the relay, then forget). An ended - link, or one made through another relay than the vault's current one, can - only be removed from the list: nothing here can stop it. A rename (of the - note or a folder above it) updates the stored path (`plugin/links.ts`). -- `data.json` keeps the link with its key in the device key's envelope, like - share keys (see [security](security.md)); the vault storage keeps it sealed - under the vault key. - -## Steps - -Each step ships green (`pnpm lint`, `typecheck`, `test`) on its own. - -1. **Protocol**: `packages/protocol/src/link.ts` (keys, gate, seal, open); - vectors, wrong key, wrong AAD, tamper. -2. **Relay**: `Link` DO, routes, admin and public auth, migration `v3`, caps, - cooldown, alarm. Tests in-process like the hub's (`memory-sql`): one-view - link with N concurrent opens serves exactly one, expiry, gate and - cooldown, update keeps the counter, revoke, oversize, admin-only routes. -3. **Viewer + serving**: package, build, `[assets]`, `/s/`, headers; the - `pnpm build`, `typecheck`, `lint` and the Deploy Relay workflow build it - first. Tested with `wrangler dev` and a fixed payload (`pnpm e2e:links`, - a headless browser over CDP: text, passphrase, limit gone, reload costs no - view). -4. **Spike, in a real Obsidian over CDP** (done): the table above comes from - it. `require("obsidian")` is not reachable from the console, so the spike - loads a two-line plugin that exposes it. -5. **Snapshot**: `sanitize.ts` with unit tests on the spike's HTML as a - fixture (`tests/links/fixtures/rendered-note.html`; jsdom as a plugin - devDependency, per test file; tests run in `node` by default), `images.ts` - (budget), `math.ts` (MathML), `snapshot.ts`. -6. **Create flow**: modal, publish, copy, `settings.links`, commands, file - menu, no-relay and old-relay messages, `styles/links.css`. -7. **Manage**: list with status, update, stop, rename tracking. - `pnpm e2e:links-obsidian` runs the whole loop in a real Obsidian: menu, - modal, passphrase, view count, update, stop. -8. **Docs and release**: README, `security.md`, `commands-and-settings.md`, - `architecture.md`, `testing.md`, `CHANGELOG.md`. - -Deploying: run the Deploy Relay workflow again (it builds the viewer; the -relay gains the `Link` Durable Object, migration `v3`, and static assets). - -## Open checks - -- `run_worker_first` array and negation syntax in wrangler ^4.131 (step 3). -- `MarkdownRenderer.render` is current for `minAppVersion` 1.13 (step 4). -- Settled in steps 1 and 2: the passphrase stretch is its own PBKDF2 (600k) in - `packages/protocol/src/link.ts`, not the vault's `deriveKey`; a blob is - chunked at 1 MiB and checked in workerd up to the 6 MiB cap - (`pnpm e2e:links`); `deleteAll` then a new link on the same id works. - -## Accepted limitations - -- A view limit and a passphrase deter, they are not DRM: a reader can copy or - screenshot. -- Without a passphrase the link is the capability: a leaked full URL opens - until the limit or expiry. Revoke is immediate. -- The relay serves the viewer script, so a hostile operator could read a - note. The operator here is the owner of the deployment (one trust domain). -- No link previews: the content is sealed, the shell is generic. -- A closed tab after the response, or a failed decrypt, still counts a view. -- A sealed note over about 3.9 MiB does not fit the tab's `sessionStorage`, so a - reload of it spends another view. -- Pasted HTML with `style` attributes can still position or overlay parts of - the page (the CSP allows inline style attributes for the note's own layout). - The author is the link's owner. -- Every random id asked of the public routes wakes a Durable Object; only the - relay's own cost limits that. -- "Changed since it was shared" compares file times, so a touch, a sync rewrite - or an autosave after sharing an unsaved note can show it falsely. -- A heading link opened in another tab counts a view: the cache is per tab. -- The snapshot is static until **Update**; it looks as the owner's Obsidian, - theme-independent, rendered. Other plugins' output (Dataview) is published - as rendered, which can include data from other notes: the preview is the - check. -- The link list is per device: another device does not list or revoke it. -- Markdown notes only: drawings, canvases and bases are not offered. diff --git a/.claude/shares.md b/.claude/shares.md deleted file mode 100644 index 16958ad3..00000000 --- a/.claude/shares.md +++ /dev/null @@ -1,493 +0,0 @@ -# Spaces, shares and live editing - -How shared folders and live editing are built, and why. The rules that keep -data safe are in [sync invariants](sync-invariants.md). - -## Decisions - -| Decision | Why | -| --- | --- | -| The relay stores and fans out ciphertext and never merges | zero-knowledge; hibernation has nothing to lose | -| The relay is never the source of truth, for data or config | losing its Durable Object loses only an unsaved live tail | -| No accounts: a person is a vault (storage + passphrase), their bucket is their control plane | serverless, no third-party service | -| A space is the unit of sync; the vault and a share run one engine | one history, one live path, no parallel share cycle | -| Every path belongs to exactly one space; a share's data lives once | two writers on one path corrupt it | -| A share mounts itself on all of a person's devices; pause is per device or on all of them, and a device can turn shares off | otherwise the folder freezes: out of the vault, not in the share; paused, it stays out of the vault while nothing of it syncs | -| Leaving, closing or revocation never deletes files | they return to that person's vault | -| One socket per relay with channels in slots; one hub object per deployment | fewer sockets, handshakes and wake-ups; one `RELAY_SECRET` is one trust domain | -| Owning a share needs S3-compatible storage | WebDAV and Google Drive cannot presign | -| No integration with the Relay plugin | paid past 3 participants, closed control plane; its MIT code may be borrowed with its header and a `NOTICE` | - -## Identity - -A **person** is a vault's owner (`owner` on the hub) or a broker token's -`participantId`; a **device** syncing that vault is the person's, anything -else joins by invite. Attribution, presence and revocation work per person. A -participant is named as the owner invited them (`personName`); the owner by -**Your name** (Settings, Shared folders), kept on each of their open shares' -owner access so every device of theirs reads one through the records' trade, -"Owner" while empty. A new share takes the name the others carry. The relay -vouches only the `owner` key, so peers read that name from the owner's own -announcement (`ChannelPresence.nameOf`). - -## Spaces and records - -| | root | key | storage | hub grant | -| --- | --- | --- | --- | --- | -| vault | `/` minus share roots | vault data key | bucket root | `deriveChannelGrant(RELAY_SECRET, channel)` | -| own share | a folder | share key | `/shares//` | same | -| joined share | own folder | share key | broker, presigned URLs | share token | - -- Records (`settings.spaces`, `spaces/record.ts`) are published one object each - as `/spaces/.json.enc` under the vault key, so concurrent adds - never race; one record edited on two devices is LWW (`rev`, then author). - Never in `manifest.json.enc`: `state.json` keeps the manifest in plain text. - A record is re-read only when its listing etag differs from the etag of the - bytes last read (`listDetailed`, cached per storage, key and prefix in - `storage/records.ts`; one it just published, or one that will not decode, is - read again next cycle): a quiet cycle is one list and no GETs. A backend - that lists no etags reads every record. -- A share's location (endpoint, bucket, prefix) is pinned once: re-deriving it - from current settings orphans its objects. Credentials never enter a record; - each owner device uses its vault's current S3 credentials. -- A share is paused on a device by one rule (`pauseOf` in `spaces/partition.ts`, - read by the partition, the hub's routes and status, and `openShare`): - `useSharedFolders` off there pauses every share, arriving ones too; the - record's `paused` pauses it on every device of the person (published, LWW - like any record edit; a resume from any device clears it); `pausedSpaces` - on this device alone. Records still trade while shares are off, or the - device would read a share's folder as vault files the vault no longer lists. -- Device-local, never published: `useSharedFolders`, `pausedSpaces`, `pauseArrivingShares`, - `localRoots` (a move not yet followed here). -- Every space ignores by its own `syncignore.md` in its root, rules relative to - it (`vault/ignore.ts`); the vault's rules stop at a share's root. **Share - folder** first writes one exact rule per path the vault's rules kept out, or - those files would reach every participant. Device-local patterns apply - everywhere. -- Roots never overlap; nested shares and re-sharing someone else's are refused; - only the owner invites. Two offline devices sharing one folder: the lower id - wins, the other record is inert. -- The broker lets a participant into `shares//` only (`share/key.ts`); vault - GC lists only `objects/` and `pins/`. Keep both so. -- Participant pulls and pushes hint their object keys (`prepareReads`, - `prepareWrites`). `share-signed-urls.ts` lazily signs up to `SIGN_BATCH_MAX` - (32) GET or PUT URLs when the first is needed. Expired URLs and failed - batches fall back to single signing; an older relay costs one refused batch - per transfer. GET and PUT caches are separate. The relay checks the token - once, derives one signing key, rejects an unsafe key's whole batch, and - refuses PUT batches from read-only grants. Existence probes remain listings. - Measured 2026-09-29 on 1000 files with modelled round trips: one sign per - object made the pull 2-7.7x slower than direct S3, batches 1.1x. - -## Lifecycle - -- **Share folder** writes the record; the next refresh publishes and pushes it, - and the push's signal wakes the owner's other devices, which mount it. -- **Invite** registers the share's location with the broker, remembers that - relay in the owner's record (`access.relayUrl`), issues one token per person - and seals `{id, name, key, relayUrl, token, participantId, - personName, readOnly}` under a 60-bit password (`sealLink`), sent apart. -- **Accept** needs a new or empty folder (a full one would ship its files into - someone else's share). A link to a share already here replaces its access - in place: same folder and baseline, since the broker's storage identity is - `broker|`, not the relay. That is the way back after a re-invite or a - move of the owner's relay; the owner's share window names the old relay. -- **Guest**: accepting needs no vault storage. A device without one - (`isGuest`) syncs its joined shares and never opens the vault; its records - stay in its settings. Once the vault is set up, the first trade admits them - as an accept there would (`admitJoined`: no vault file and no other share at - the root, else the refresh stops until the folder is renamed). In that trade - (`syncRecords`, `unbound`) an open record outranks the vault's older close - of it, and a share the vault owns stays its owner's whatever this device - joined or left of it (its folder moves to the owner's root). -- **Move** is a record edit; the person's other devices move the folder. Paths - inside the share and docIds do not change. -- **A root gone on one device** detaches that device; it never deletes for all. -- **Stop sharing / Leave** tombstone the record; the folder returns to the vault. - Stop sharing then deletes `shares//` through the operation queue, so no - refresh mounts the share again meanwhile; a failure only leaves orphans. - Leave revokes the participant's own token at the broker (`DELETE - /share/token`), never one issued after it; an unreachable relay does not - stop the leave. Stop sharing from a vault whose relay is not the one the - invites went through warns that their tokens live on there. - -## Relay hub - -- One `Hub` Durable Object per deployment. `/hub?c=&t=&…&d=` - opens up to 32 slots; the worker checks every grant before waking it. The - vault's channel is `sha256(storageIdentity)`, so the relay never sees the - endpoint or bucket. An owner grant is `.:")>`, minted per connection for a day; the relay refuses - one expired or minted over a day further ahead. A socket outlives its grant. A read-only share token follows documents but never - writes: each write is answered `Refused(ReadOnly)`. It never signals (the - hub drops it, HTTP answers 403: it would only wake everyone into a sync), - and its awareness runs under its own ceiling (20 a second, bursts of 40, 4 KB). - Every socket's frames run under one more (32 a second, bursts of 256, excess - dropped unanswered). The burst takes an update and a cursor from all 64 - documents a socket may follow; sustained bulk edits can pass the rate, and the - client resends what was dropped (see the echo below). -- Per-socket state (slot -> channel, grant fingerprint, `who`, `name`) lives - in the 16 KB WebSocket attachment, not in tags (at most 10). `name` is the - label the owner invited a participant by, from the broker token, cut to 64 - UTF-16 units so its UTF-8 fits a frame's one-byte text length. -- `JOIN {from, who, name}` goes to the channel as a socket arrives; before - it, the newcomer gets `HERE` with the same fields for everyone already on - that channel, since presence is never stored. -- `ping` is auto-answered without waking the object; while two or more sockets exist, an - alarm every half window (37 s of 75) closes those silent past the window and announces `LEAVE` once. - Each alarm is a request and a row, and a lone ghost misleads no one: the next arrival sweeps first. -- The client drops a link silent 90 s. A network change leaves a socket half-open, so `online`, turning - visible and a send after 10 s of quiet ping first; no answer in 5 s drops it sooner. -- A share token is live while its participant's pointer names it - (`share/kv.ts`): two re-invites at once leave one live token, not an - orphan no revoke finds. -- Revocation: broker -> `dropGrant` -> `REVOKED(slot)` (cut first, then the token - and pointer go, so a failed cut is retried by repeating the revoke); other slots live on, a - socket with none left closes with 4001. The client retries a refused socket - six times (a fresh share token can be refused for a minute while KV catches - up) and then reads `unauthorized` until the settings change or the device - wakes (`online`, page visible); its backoff is jittered and restarts on the - first message, not on open. The hub keeps a revoked fingerprint 5 minutes - (`hub/revoked.ts`) and refuses it on connect, while KV may still let it in. -- Storage is SQLite per `(channel, doc)`, both tables WITHOUT ROWID: a document row (snapshot, - forwarding pointer, log name; changes on compaction and rotation) and chunks of consecutive - deltas, each after its 4-byte length. An update joins the last chunk while it stays within 4 KB, - else starts one: a row written either way, and a compaction deletes a row per chunk, so ~1.03 - rows an update (a row per delta cost ~2). The head is the last chunk's last seq, or the - snapshot's when compaction left none; a chunk the snapshot covers part of stays, reads skip what - it covers. Ending a share deletes its rows (`purgeChannel`) and shuts the channel for good - (`closed`). A frame is at most 1 MiB; live notes are markdown up to 256 KB, so a snapshot fits - one frame and one row. -- A 1.3 relay kept a row per delta (`deltas`). The store packs each log into chunks in one - transaction, a row per chunk; while the day's writes cannot cover it, document frames get - `Refused(Unstored)` and retry it, the rest of the hub runs. `deltas` beside `chunks` means a - rollback appended under seqs the chunks hold: the logs start over as if lost, pointers kept. -- A room row created again gets a new log name, sent in `STATE`: a client - that sees another name, or a head behind what it knows, rotates the note on. -- A frame past 1 MiB, a document past a socket's 64, or a write from a - read-only grant is answered `Refused{reason}` to its sender only; that note - stays with the file sync until it is closed, and its status says why. -- Each document frame runs in one SQLite transaction (`DocStore.atomic`); a throw (past Free's 100k - rows a day, the next write throws until 00:00 UTC) rolls it back and answers `Refused(Unstored)`. - Unanswered, the writer would resend forever and its notes stay out of every push; half a seed would - leave a row with no delta that answers each seed with `State(head 0)` again. 1.3.0 clients go cold - under a generic status. - -## Protocol (`packages/protocol`) - -Frames are `[type][slot][docLen][doc][body]`. Choices that would cost three -places to change later: - -- The echo is the ack and names the update by the sender's counter (`n`). The - hub answers a socket in order, so an earlier update still unacked was - dropped and goes out again at once; one with no echo for 15 s goes out - again too, and all of them after a reconnect (Yjs updates are idempotent). - A dropped `SUB`, `SEED` or `ROTATE` is not retried: the note turns - "unanswered" until the next socket. -- `SUB` carries `since`: a reconnect gets the tail, not the whole state. -- `LEAVE` drops a socket's awareness at once, without y-protocols' 30 s timeout, - but only clients that socket announced last: a silently dead socket's comes - after its successor's. Every announcement moves the clock on, since - y-protocols ignores a clock it has seen and a peer that dropped the state - would not take it back. -- docId = HMAC(docId key, path inside the space root + `#` + generation), 16 - bytes: every mount of a share meets in one room. -- `MOVED` / `ROTATE` carry the target docId: rename and rebuild are one - operation. A rename adds a note of the new path, sealed, which the hub - keeps with the pointer. -- Frame and docId keys come from the space key by HKDF, derived when the - envelope is unwrapped (the content key is not extractable). -- A sealed payload names what it is for as AES-GCM additional data - (`doc:`, `awareness:`, `moved:`, `presence`): the relay - cannot move a frame into another document or kind. A rotation is sealed for - its target, a rename note for the room it left. -- Edits go out at once, then at most once an interval of the device's **Live editing speed** (100 ms, 250 ms by default, 1 s): each is a hub row. - Cursors likewise per 100 ms, and only while someone else is in the room: their Join, or the first frame of - one already there, asks for them, so a lone note sends no cursor or heartbeat. - -## Live layer - -- While a session lives its Y.Doc is authoritative for the note; live never - writes the file, the view that owns it does. -- Text is LF before the CRDT and the hash, a lone CR included (CodeMirror - breaks lines on it), through one normaliser (`utils/eol.ts`). -- The merge base is the note's agreed text (per docId, in the plugin folder), - falling back to the cold baseline; the baseline as the main base duplicated - lines not yet pushed. A note whose folder just became a share has no share - baseline yet: the base is the vault's frozen entry. A real conflict keeps - both sides, the room's first, and lines both open or close with come once - (git's zealous merge), since two inserts at one spot often share them. -- A note reopened while its last session is still closing opens once that - one's `Unsub` is out (`live/session/closing.ts`): after the new `Sub` it would drop - the socket's subscription. -- Live document types are chosen by frontmatter, not suffix - (`excalidraw-plugin: parsed` also sits in plain `.md`): a drawing goes live - only in the Excalidraw view, never as text. -- Each kind is a `LiveModel` behind one session (`live/model.ts`): a note is one - Y.Text, a drawing a Y.Map of whole elements settled by Excalidraw's own rule - (`live/drawing/`). `live/workspace/editors.ts` pairs each with the view that edits it. -- A drawing binds through the Excalidraw plugin's undocumented `excalidrawAPI` - and `window.ExcalidrawLib` (checked against 2.x). `onChange` pushes elements - whose version moved into a staging map; the session drains it into the room - once per send (`LiveSession.stage`, also on dispose, `absorb`, a - rebuild and detach; `settled` is false meanwhile), because `mergeUpdates` - keeps every overwritten frame of a stroke. Remote elements come in through - `reconcileElements` and `updateScene` with `captureUpdate: NEVER`, so undo - stays local; only the event's `keysChanged` are reconciled (the whole room - after an event missed while the view did not `holds` its file). Y.Map settles - concurrent sets by client id, so the element a view kept goes back into the - map; an edit made over a newer version is bumped past it. The room holds - copies: Excalidraw mutates elements in place. -- Drawing pointers travel in awareness as scene coordinates from `pointermove`, - one per animation frame (the API has no `onPointerUpdate`), and render as - Excalidraw collaborators. - The view loads its API after `file-open`, so binding retries every 500 ms. -- A view switched to another file names it a moment before it shows its - scene (`excalidrawData.file` lags `file`): a binding reads, takes and gives - elements only while the view `holds` its file, or one drawing pours into the - other's room. -- The editor binding is a Compartment over the undocumented `editor.cm`, as - Peerdraft and Relay do. -- Undo in a live note is the room's `Y.UndoManager` on every path: the - keymap, `beforeinput` history inputs (Edit menu, system gestures) and - `editor.undo()`/`redo()` (the phone toolbar), routed while bound. - Obsidian's own history would revert what others typed. -- A write under an open note (git, another sync) needs nothing from live: - Obsidian merges it three-way with the editor, and the binding carries the - change. Excalidraw drops the first write after its own save as that save's - (2.27), so the file sync clears the flag first (`letWriteIn`). -- A drawing view that reloads replaces its `excalidrawAPI`; its binding then - asks for a new one (`stale`). -- Another device's deletion leaves a note open here be: it stays as a new - file, and `LiveNotes.kept` asks the person at once to delete it here too or - push it back (`ui/live/deleted-elsewhere.ts`). A remote text that is not - readable is not a deletion and asks nothing. -- A room silent 15 s after its `SUB` leaves the note to the file sync, as a - dead hub does; if it answers later, the session merges in like a reopen. -- A note renamed with its room open takes the room along (`live/workspace/rename.ts`, - spotted by its TFile's new path): the room rotates into the new path's - first generation with no room, probed by `SUB`, since readers step past - every pointer; meanwhile the note counts as joining, so the file sync - waits. A device in the room renames its file (`vault.rename`: the - links are the renamer's edits, and they sync) and follows with the merge - base. A device that never joined steps past as a new note. Concurrent - renames settle on the one the hub took first. -- The lowest writer's client id compacts once 200 deltas pile up; **Rebuild - live note** sheds tombstones (a note's document reached 3x its text after an - hour). A snapshot past a frame makes the leader rebuild the room itself; a - rebuild past a frame too sends the note back to the file sync ("too-large"), - and past the tail cap the hub refuses its updates the same way. -- A read-only person's text note follows its room (`live/session/follower-session.ts`): - it sends only `Sub`, `Unsub` and `Awareness`, never seeds, rotates or - compacts. It joins only when the disk is the room's text, the agreed text or - the cold baseline, since the bound view shows the room over it. A change - made there, an incoming version the room lacks, an empty room or a lost log - leave the note to the file sync until it closes, or until the share turns - writable. The view saves the room's text, a pending local change until the - writers' push of it is pulled. Drawings stay cold for readers. -- Attribution is advisory: each client names its own client id in `users`, in - the ciphertext, so a client may type under another's key. Checking it - against the hub's `who` needs signatures, since compaction snapshots come - from clients; only the names shown for present people are the relay's. Deletions name no - one: a Yjs delete set carries no client, and tracking it would keep the - tombstones Rebuild sheds. - -## Presence - -- Each device announces `{key, name, device, note, idle}` on every space channel - it holds, sealed whole with that space's frame key: a device with no note of - a share open still sees who is in which one, and the relay sees no names or - paths. `note` is the path inside the root, so each mount maps it onto its own. - `device` is the device's own name in a share, where one person's devices - share a key: a person's entry lists theirs ("Owner · Laptop, Phone") and each - cursor carries its own; null in the vault, whose keys are devices. A device - rename reaches both, as every settings save refreshes presence and rooms. -- A client can seal any name, not the `who` the hub vouches for its socket - (`JOIN`/`HERE`): an announcement shows only from a vouched socket whose key - is its `who`, and a participant under their invited label (the owner's - sockets may carry any key: the vault's devices). The author tint names a - present person by it; one who left, by their own `users` entry. -- The key groups and colours: the person in a share, the device in the vault - (one person). One colour per key everywhere (`shared/colors.ts`): cursors, - author tint, avatars. Hex, so awareness sends no tint: y-codemirror derives - it as `color + "33"`, as the author tint does. -- A file counts only while a tab shows it (Obsidian keeps naming a closed one - active); away after 5 minutes without input in any window, popouts - included, or with every window hidden. -- The header menu's "follow" and the share window's **Follow** - (`ui/live/header/cursor-follow.ts`, one instance on the plugin, so one tab - follows at a time) follow a space's person: their presence `note` opens in - the same tab (one not on - this device yet waits), and there the doc awareness `user.key` cursor is - kept in the middle half of the view, centred again once it leaves it - (`follow-scroll.ts`). The cursor watch reads edits too, since a relative - cursor moves without a new awareness state, and scrolls a frame later, - since y-codemirror changes awareness inside an editor update. A banner under - the tab's header (`follow-banner.ts`) names them with **Stop following**; - input never ends it, a stray key would by surprise. It ends on that - button, on another note opened there by hand, or once they leave the space. -- A note header shows its live mark only after the room answers or a second - passes (`note-presence.ts`), so switching notes never blinks through - joining. A vault note shows none unless another device is in it or the - relay has trouble: it is live only between this person's devices, and a - mark there read as shared. The header is its own button, not - `clickable-icon`, which themes size to one icon. -- Each manifest entry names its publisher: `by` indexes the manifest's - `authors` (`{key, name}`: the person in a share, the device in the vault). - The table only grows, so an unchanged entry stays byte-identical; the merged - UI result drops it, each space indexing its own. -- A live note marks others' cursors on its scrollbar (`live/text/scroll-marks.ts`); - a tick scrolls there, never follows. -- A read-only share's notes take no typing (`editor/read-only.ts`: CodeMirror - `editable`/`readOnly` by the editor's file), with a lock in the note header. - Its drawings stay in Excalidraw's view mode, set again if switched off; only - views put there by the lock are let out. -- The tree's "new" dot: a pull (or auto-merge) that lands content another key - published, past the space's first sync, marks those share files unseen on - this device (`presence/unseen.ts`, vault localStorage) unless active; opening - clears it, renames and deletions follow. -- `People` caches its per-space and per-note views and drops them at every - change of what a channel knows (`ChannelPresence`'s `onEntriesChange`, a - changed partition, dispose); the returned lists are shared, never edited. - `SpaceRecords.partition()` is memoized on the identity of `settings.spaces`, - `pausedSpaces` and `localRoots`: replace those fields, never edit them in - place, or every reader sees the old partition. -- The tree paints two layers (`ui/explorer/row-decorator.ts`): change, link and - ignored marks, rebuilt only when the diff, links, partition or ignore state - changed, and the presence layer (share badges, people, unseen), recomputed - per pass. A people event repaints only the rows whose marks changed. - -## Accepted limitations - -- Every share owner is the key `owner`: two shares of unnamed owners show them - alike. A remote cursor moves only while its window has - focus (y-codemirror), so "follow" goes where they last were there. -- The read-only lock is the editor's: Properties, renames and other plugins - still change files there, which then wait unpushed as before. A note moved - into a read-only root while open locks on reopening. A drawing locks once - its view loaded (up to 500 ms), and scripts can still edit it. -- A writer that started from a file older than the editor's last save (a - stale checkout) replaces what came between: Obsidian merges against that - save, and nothing knows the writer's base. Git or another sync writing under - an open drawing after its save is still dropped by Excalidraw. -- A session that seeded a room learns the log's name from its next `STATE`: a - log lost before that shows only once the head falls behind. -- A rename leaves the room where it is when another note's room holds the new - path or the room stays busy for 10 s: the others type on in the old room and - the sync ends with both files, as before. So does a device that opens a - stale copy of the old path before its file sync caught up. -- A file moved elsewhere waits here while an open room holds its note: the - file sync renames it once the room closes, carrying what was typed in it. -- A note whose folder becomes a share leaves its vault room in the hub (rooms - are never trimmed); other devices type there until the record's signal moves - them, then fold those edits into the share's room. -- Excalidraw colours a drawing's pointers itself, from the person's key, so - they do not match that person's avatar. -- The "new" dot knows only what this device pulled: a file changed and seen - on another of the same person's devices is still new here. Deletions mark - nothing. -- The vault's device list needs the vault key: until a sync knows the - passphrase, settings say so instead of listing devices. -- Revocation closes the share on the participant's devices: a broker - `unauthorized` that still holds for the same token 90 s later tombstones the - record as Leave does (no broker call, the token is dead) and asks at once - whether to keep its files or trash the folder (`ui/shares/access-ended.ts`). - The wait is because the broker's KV is eventually consistent (~60 s, negative - answers cached): a fresh or renewed token looks revoked at first, and a false - close would reach every device of that person. A hub `REVOKED` pulls, so the - broker is asked soon. People may lag an invite; a revoke shows at once, as - the list reads each pointer. -- A revoked writer keeps file storage for up to about three minutes: the broker - signs by the KV grant (cached ~60 s), never the hub's revoked table, and a - presigned URL lives 120 s. They held the same rights a moment before; asking - the hub on every signature costs a Durable Object round trip per object. -- Re-inviting recognises a person by name, case-insensitively: one name is one - participant, a renamed person is a new one, an unnamed invite is always new. -- `reset-remote-storage` leaves `shares/`, `spaces/` and `links/`: resetting the - vault does not end shares others depend on, nor forget live share links. -- Mounting over one's own copy: identical files converge; an edit made before - the record arrived is a conflict with no base in the share. -- The vault drops a share folder's frozen entries at its next push, so they - stop holding the folder's blobs (`sync/foreign.ts`); history keeps them until - it rolls off. The baseline forgets them at the next refresh; until the - share's baseline on this device takes a path, its entry stays in - `shareBases` as the live merge base. Until that push the vault lists them. A device whose refresh - read the records just before the share was created, or that skipped the - share's whole open period and first refreshes after Stop sharing before the - owner pushes the folder back, reads them as deletions of unchanged files; - the share or the owner's push brings them back. A share kept paused while - it is edited and closed gives that device conflicts, not a clean pull. -- Closing where the folder is gone returns an empty root: entries the vault - still lists (no vault push since the share opened) read as deletions (files - edited since give a conflict). A share empties only by closing; deleting - every file also hits `SpaceGoneError`. -- A root move rehashes the moved files once, deletes the vault's frozen copy at - the old path on the next push if one is still listed (history keeps it), and - two offline moves converge by LWW (the loser moves again). -- A failed share is retried on every refresh (one broker request), not backed - off; an explicit operation on its paths shows its error, which the scheduler - does not count. -- A read-only participant's local changes in the share stay pending: auto-push - skips them, an explicit push holding any of them is refused, **Revert this - file** drops them. -- Records belong to the vault storage they were traded with - (`settings.spacesVault`): pointed at another vault, a device drops them - rather than publish share keys into it, and their folders stay as plain files. - It says so and forgets its state of them, so back at the first vault they - mount afresh; a folder moved elsewhere meanwhile stays behind as vault - content. Credentials are not the location: new keys to the same bucket keep - every owned share. -- A folder moved outside Obsidian, or while it was closed, is a vanished root - (`SpaceGoneError`) plus new vault content. A rename in Obsidian cancels the - running operation, so a pull stops writing under the old path. -- An owner device resends its S3 credentials to the broker hourly after a good - compare: another device's older keys lose within the hour once deleted. -- A closed share's `syncignore.md` stays as a plain file: the vault's rules - govern the folder again. A read-only participant ignores only on their device. -- A new own share restarts the vault's socket, so live sessions resubscribe. -- A participant's other devices hear of an accepted share by signal only with - a relay of their own. -- A guest has no vault socket: the ribbon's relay dot and the vault's relay - line read offline while its shares' channels are live. A guest's shares - reach the person's other devices only once it sets up the vault; files - another device has in that folder but never pushed are pushed into the share - there, as with any record arriving over one's own copy. -- The manifest caches (`validators`, `publishedHeads`) live as long as their - storage adapter; a share's root is in its adapter memo, so a new root is a - new adapter. -- Grants ride in the hub URL: a browser WebSocket cannot send - `Authorization`, and `Sec-WebSocket-Protocol` would be logged unredacted, - while Cloudflare's logs redact hex and base64 ids in URLs by heuristics. A - leaked owner grant admits for up to a day. -- An unauthenticated upgrade can cost up to 2 KV reads per slot before the hub - is reached; a Cloudflare rate-limiting rule on `/hub` is the remedy. -- A writable token can fill one document's log up to the tail cap (2,000 deltas - or 8 MiB since its snapshot), and open as many documents as it likes; the hub - caps frames and tails, not a channel's document count. -- A relay rolled back to 1.3 and forward again restarts every live log (devices rotate from their - text); the plugin never deploys an older relay, only a manual rollback does this. -- Open: the cursor heartbeat is y-protocols' own renewal, timed by the wall clock: set back (say an - hour), an idle device sends none, and others drop its cursor after 30 s until it moves or someone - joins. A monotonic heartbeat of our own, announcing only real changes otherwise, would close it. -- Open: with the day's Durable Object writes used up (Free: 100k rows), a revocation throws in - `Hub.dropGrant` / `purgeChannel` before it cuts a socket; the owner sees the error, and the participant - keeps access until a retry succeeds after 00:00 UTC. Cutting first would not help: KV still admits the token. -- Open: the hub keeps every room (snapshot, tail, pointer) until its share - ends, in one Durable Object capped at 10 GB. Deleting idle rooms is not - enough: a deleted id is seedable again, so a device returning with a stale - disk takes the regrown log for a lost one and rotates over newer edits, and - an expired pointer splits a note from its live successor. Retiring needs a - tombstone the hub answers with a new signal, clients moving to the next - generation (join it, else seed it), and a backfill batched within the - Workers Free write budget. -- A rebuild (automatic, manual, or a lost log moving on) that lands while a - rename waits for its workspace refresh leaves the renamed note in a fresh - room apart from the others (`carryRenamed` skips a moved session): live - edits stop crossing until it reopens, and the file sync reconciles it. -- The relay can still withhold, replay or reorder a document's frames: - additional data binds a frame to where it belongs, not to when. -- The broker presigns DELETE too: a writer can remove a share's objects; - history, not revocation, repairs that. `share/key.ts` is the whole boundary: - it fails closed, and every change needs traversal tests. -- A faster **Live editing speed** starts from a note's next send: edits already - waiting keep the slower deadline, under 1 s once. Not worth tracking it. diff --git a/.claude/skills/hunt-data-loss/SKILL.md b/.claude/skills/hunt-data-loss/SKILL.md new file mode 100644 index 00000000..6993ca4d --- /dev/null +++ b/.claude/skills/hunt-data-loss/SKILL.md @@ -0,0 +1,29 @@ +--- +name: hunt-data-loss +description: Hunt silent data loss in the MDSync sync engine - content lost, truncated, reverted, resurrected or misplaced without telling anyone, or remote deletions that reach past what the person deleted. Use when asked to audit, review or hunt bugs in packages/plugin/src/features/sync (pull, push, merge, revert, restore, rename, state persist, history GC), or when a report says files vanished, came back or differ between devices. +--- + +# Hunt: silent data loss + +Find where the sync loses, truncates, reverts, resurrects or misplaces content without telling anyone: the bugs users find weeks later. Read `.claude/rules/sync-integrity.md`, `.claude/rules/vault-io.md` and `packages/plugin/src/features/sync/README.md` first (`.claude/rules/hunks.md`, `.claude/rules/history.md` and `.claude/rules/live.md` for those areas). Breaking a stated invariant or ignoring a platform contract is in scope; an accepted limit listed in the README or a rule is not. + +## What counts + +- Content lost, truncated, reverted or resurrected on any device, or published so. +- A deletion reaching past what the person deleted. +- A file left in a state nobody chose: a step name, half a write, a duplicate. +- A clean status while devices hold different content. + +## Where to look + +Pick an interruption, a platform contract and a sequence, then follow it to the push that publishes the damage. + +- **Interruptions**: the process killed between any two awaits of a pull, push, merge, revert, restore, rename or state persist (`features/sync/apply/`, `features/sync/operations/`, `features/sync/recovery/`, `features/sync/runtime/history-service.ts`); one worker failing while others still write; a refresh racing an edit. +- **Platform**: every line of `.claude/rules/vault-io.md`, above all non-atomic writes, mobile `exists()` false on errors, case-blind disks and listings that normalize names. +- **Time**: a device offline for days while peers edit, delete, rename and revert; clock skew; coarse mtimes (FAT, exFAT) hiding a same-size edit from `unchangedSince` and the hash cache (`features/sync/scope/scanner.ts`). +- **State**: a baseline lagging the disk, a stale comparison reused (`runOperationNow` in `features/sync/runtime/operation-runner.ts`), a share moved, paused or closed mid-cycle, a journal entry outliving its space. +- **Live**: a room opening on a file the sync is writing, or half wrote; a room's save racing a pull (`features/sync/live-notes.ts`, `features/live/workspace/`). + +## Proof + +A finding names the trigger sequence and the code path that publishes the damage, best as a failing vitest on the shared harness in `packages/plugin/tests/helpers/`: `pairedSessions` (`packages/plugin/tests/helpers/session.ts`), `InMemoryAdapter` (`packages/plugin/tests/helpers/in-memory-adapter.ts`), `createTestControllerHost` (`packages/plugin/tests/helpers/controller.ts`), faults from `packages/plugin/tests/helpers/faults.ts` (`killNextWrite`, `failIo`), as `packages/plugin/tests/features/sync/recovery/cut-short.test.ts` kills a write part way. "Could race" without a sequence is no finding. diff --git a/.claude/skills/new-feature/SKILL.md b/.claude/skills/new-feature/SKILL.md new file mode 100644 index 00000000..dd6cc56a --- /dev/null +++ b/.claude/skills/new-feature/SKILL.md @@ -0,0 +1,39 @@ +--- +name: new-feature +description: Place and scaffold a new feature slice in packages/plugin (a domain area or Obsidian surface no existing slice owns). Use before creating a slice under packages/plugin/src/features/. Not for changes inside an existing slice. +--- + +# New feature + +The rules in `.claude/rules/` (structure, ui, testing) load as you touch files; this skill is the order of work. Paths are relative to `packages/plugin/src/`. + +## 1. Find an owner + +- List `features/*/index.ts` and read the README of the closest slice. Extending an existing slice beats a new one: a new slice needs a domain or a surface nobody owns. +- Name it after the domain term the code uses (`spaces`, not "shared folders"), not after the screen. + +## 2. Pick the tier and its place + +- **Domain** (owns state, logic, its own flows and modals) or **surface** (a place in Obsidian where domains meet: a view, the gutter, the file tree, a header, the status bar, the wizard, the settings tab). +- Domain order, lowest first: `storage < sync < live < presence < spaces < links < relay < transfer`. A slice imports only downward, types included (`pnpm arch` checks it; a new domain also joins `DOMAINS` in `packages/plugin/.dependency-cruiser.cjs`); a domain never imports a surface. Surface -> surface only along the allow list in the structure rule and `packages/plugin/.dependency-cruiser.cjs`; extending that list is a design decision, not part of this task. +- Anything the slice needs from another slice comes through that slice's facade (`@/features/`) or `@/core/`. If two slices need code and it knows no feature, it belongs in `core/`. +- Do not take `PluginHost` (`app/host.ts`): declare what the slice reads from the plugin in `host.ts` as `Host`, export it from the facade; `MdsyncPlugin` satisfies it structurally. A way into another surface is a callback in it. + +## 3. Create only the files it needs + +1. Logic `*.ts` at the slice root, `obsidian` as `import type` where possible so it tests without a DOM. Group by sub-area past 12 modules, never by kind. +2. `features//register.ts` - Obsidian wiring for the plugin lifetime (commands with stable ids, events, menus, views), called from `app/` (`app/commands.ts`, `app/views.ts`, `app/events.ts`, or `main.ts` for services). Only `app/` and `main.ts` call it. +3. `ui/` - DOM, modals, menus, settings sections, built from `core/ui` primitives (the ui rule). A settings section is exported through the facade and ordered by `features/settings/tab.ts`. +4. `*.css` next to what it styles, imported from `styles.css` at its place in the cascade (lowest feature first, `core/ui/styles/mobile.css` stays last). +5. `features//index.ts` - the facade: export only what other slices or `app/` import; never import it from inside the slice. +6. `README.md` - what it does, flows, rationale, accepted limits. Constraints that must hold go to a rule in `.claude/rules/` with `paths:` for the slice. + +## 4. Tests + +Mirror the tree under `packages/plugin/tests/features//` (the testing rule): never colocated. All domain logic gets unit tests; reuse `tests/helpers/` before adding a helper. + +## 5. Finish + +- `pnpm lint && pnpm typecheck && pnpm test && pnpm arch`, all green, and no folder over 12 modules. +- Grep `.claude/` and `features/*/README.md` for what the change renames or retires and update every mention in the same commit (`CLAUDE.md` rules table when a rule is added). +- Report the files created and anything left out on purpose. diff --git a/.claude/sync-invariants.md b/.claude/sync-invariants.md deleted file mode 100644 index f495aa9e..00000000 --- a/.claude/sync-invariants.md +++ /dev/null @@ -1,45 +0,0 @@ -# Sync invariants - -Hard data-integrity rules of the engine. Breaking one silently corrupts user -data or publishes remote deletions. Every change in these areas needs tests. - -- **Hunk source of truth**: a hunk operation must take both texts from `loadHunkSides` and must verify the sha256 of each side before it applies an index. The projection builds its own sides from the same texts, the baseline through `hunkBaseline`. A view that diffs one pair of texts while the operation recomputes from another will apply the wrong hunk. Editor gutter marks are those segments too (`markedChanges` in `editor/signs/helpers.ts`), never a second diff: blank lines make diffs ambiguous, and a mark must show exactly what Push and Revert move. -- **Baseline advance**: the baseline may only move for paths an operation actually wrote. Adopting a whole published or remote manifest silently claims every file this device has not downloaded, and the next push publishes them as deletions. -- **Remote reads are complete**: matching snapshot ids do not make a partial baseline a remote manifest. HTTP 304 must use the complete cached response under the same storage adapter and encryption key. Stale reads may use a complete head actually published by this session, never the baseline. -- **Configuration resets are not file deletions**: reset generations are scoped by configuration directory and category. A newer generation forgets that category's baseline files and folders, preserving local files on every device. Ordinary publishes retain generations. Reset manifests require version 2 so older clients refuse them. -- **Disabled scope is untouched**: excluded configuration files and empty folders remain in the remote manifest and baseline during ordinary operations. Only an explicit category reset forgets their baseline. -- **Empty folders merge three-way** (`mergeFolderArrays`): one the baseline knew stays published only while both sides still have it, so a deletion on either side propagates; a pull never recreates one deleted here since the baseline; one in or under an unreadable directory is kept, not deleted; another space's leave the manifest (`scope.owns`). -- **History is a change log, not an archive.** `history.json.enc` holds one record per push, each the diff from that snapshot's *parent* - which is `compareResult.remote`, not `state.baseline`; the two differ whenever another device pushed since the last compare. Records carry both sides (`modified.from`/`.to`, and the departed entry on `deleted`) so a restore never needs a replay and a lost update leaves a detectable gap instead of a corrupted chain. Walk the chain only while `entry.parentId === next.id` (`contiguousLength`); past a gap the log is not evidence of anything. -- **Deleted-file listing walks deletions, never absences.** `listDeletedFiles` collects `changes[snapshot].deleted` newest first and keeps the first hit per path, so a file deleted, recreated and deleted again reports its latest death; anything back in HEAD is skipped. Pinned snapshots outside the walked chain are diffed against HEAD separately, and those rows say "last seen", not "deleted" - a pin proves the file existed, not when it went. A log that lags HEAD sets `lagging` rather than reporting an empty vault as an empty trash. -- **Hunk indices belong to one patch.** The history diff numbers its hunks from `computeHunks(version, current)`, so `restoreHistoryHunks` must compute in that same order and invert the selection (`applyHunks` takes the right side for selected hunks, so keeping one hunk on the version's side means selecting all the others). It also verifies the working copy's sha256 against the one the view drew, or a file edited since then gets a stale index applied. -- **A restore that puts the vault back is local only.** `planVaultRestore` is pure and both the confirmation and the operation run it, the operation re-planning after the user confirms. It only removes paths the scan actually read - an unreadable directory means unknown, not absent - and never touches an ignored path in either direction. Nothing reaches the remote until the user pushes. -- **GC reachability under the change log**: never delete an object reachable from HEAD, from a retained change record, or from a pinned snapshot's manifest. If any of those cannot be read, set `skippedObjectSweep` and delete no objects at all - a bounded blob leak is acceptable, a dangling reference is not. Sweep only blobs `settledKeys` lists as older than any push in flight: another device may have re-uploaded an old hash for a push it has not published. Accepted limit: a re-upload landing between the listing and its delete is still lost (Drive has no conditional delete); deep clean shares that window. Pins keep their own full manifest under `pins/` precisely so they outlive the chain; write that manifest *before* setting the flag, or GC will believe objects are protected that nothing references. -- **Only the head vouches for a blob.** A push skips an upload when the head names the hash, or when this device uploaded it for a push that never published (`sync/uploads.ts`, 12 h, still probed); anything else may be swept by GC or deep clean between a probe and the publish, so it is uploaded again. Deep clean deletes nothing written in the last day: another device's push uploads before it publishes, and a pin's manifest lands before its flag. Still open, narrow: GC evicting the record of an own unpublished upload at that moment, another device's reset between the probe and the publish, clock skew over 12 h. -- **A push is done only when its own id reads back.** `publishManifestWithGuard` re-reads while it sees a head it replaced; anything but our snapshot id is a `ConcurrentPushError`, so the baseline stays put and the runner re-compares. Taking the replaced head as a stale read lets a sibling's overwrite turn our files into remote deletions. Accepted limit: a backend hiding our own write past the retries (WebDAV behind a cache) leaves a landed push unconfirmed, so peers are not pinged, a partial push shows an auto-merged conflict, and that snapshot gets no history record. -- **Unreadable is not absent**: a file or directory the scan could not read is reported in `snapshot.skipped` and excluded from the diff. Treating it as missing turns a locked file into a remote deletion. -- **A write cut short is finished, never read as an edit.** Obsidian truncates before it writes (mobile drops a file whose append fails), so a killed write leaves a prefix that auto-merge takes as a deletion and pushes everywhere. Engine content writes go through `sync/journal.ts`: a durable claim (one per pull or vault restore batch; a pull leaves out new files that are no room snapshot), the content staged, `ready` asked again (an edit saved meanwhile, or a room come since, keeps the file: `coldSince`), the write, what ends it (`landed`: a room snapshot's merge base), the release. The plugin's load puts back what was cut short before anything waits on the network (`restoreCutShort`); `compare` finishes pending ones right after the scan, before it waits for the remote (`finishCutShort`), and a start with one pending refreshes at once: a prefix of the staged copy, or a missing file in a folder that stays, is rewritten; one that landed still gives its room the merge base, judged by its bytes when the scan left it out; what it cannot finish yet (anything unreadable, an open room) leaves the diff as unreadable. A download finished or found landed so gives the baseline its entry (`BaseStep`), and the diff is taken against that (`withLanded`): on the old baseline it would read as this device's edit, and a change made elsewhere since would be pushed back. The step names the storage and vault it was claimed under, which alone take it, and only while their baseline holds what it held then; adopting the write never moves it. Any write with a step stays in the journal once it lands (`land`: never rewritten again, in no room's way, its staged copy gone) until the baseline holding its step is saved: by its operation (`acknowledge`), or, that save lost, by the runner after its next compare (`settleLanded`). Dropped first, a lost save would leave the old baseline with no record. The runner saves the journal as every operation ends, so an edit before the next compare still finds the write landed. No room opens on a note under an engine write or stays on one cut short: an open marks the note joining before it asks the journal again, and a sync claims before its last look for a room, so one sees the other. A claim over an unfinished write is refused (`UnfinishedWriteError`), and writes follow their share's moves and pass to whichever space holds their path, a share closed or opened (`adopt`). A journal that cannot be read stops the plugin loading: read as empty, its writes would pass for edits. Unloaded, it saves nothing more and refuses claims: an operation still running has its state save dropped, so its releases must not reach the file the next instance reads. A concurrency run rejects only once its workers settle. Accepted limits: garbage that is no prefix reads as an edit; an edit since that leaves a prefix of the staged copy, or deletes the file, is undone; a pulled new file that is no room snapshot, cut short, stays a conflict, and gives no step; so does a file a pull moves here and edits there; a step of a storage switched away from is dropped; a write landed in a run the app died in, edited before the next compare, loses its step; a first sync's download has none (no baseline yet), so a note deleted elsewhere before it is finished comes back. -- **A batch stopped by an error keeps what landed.** Pull and auto-merge save the baseline for it, then throw, as a cancel stops (`PullResult.failed`); moves record each as it lands. On the old baseline a landed file reads as this device's edit until a compare finds it matching the remote, and a change made there elsewhere meanwhile is pushed back or merged against the wrong base. -- **A folder goes only when a listing shows it empty.** Obsidian's `rmdir(path, false)` never means "only if empty": mobile always recurses, desktop removes no folder. `removeEmptyDir` lists, then removes recursively. Relying on the flag wiped every folder above a pulled deletion or move on phones, and auto-push published it (issue #9). Accepted limit: a file created there between the two calls goes too. -- **No automatic push publishes a bulk deletion.** More local deletions than `bulkDeleteLimit` (moves excluded) are all held back from every automatic push, logged and reported once per set (`createAutoPushSelector`, `sync/auto-push.ts`); the rest still pushes. Only a push by hand, or **Ask before pushing many deletions** turned off, publishes them. -- **A name this disk refuses is skipped, never written** (`diskRefuses`: Windows and Android refuse U+0000-U+001F, DEL and `\/:*?"<>|`). One failed write would stop every pull. Such remote files go to `snapshot.skipped` (`sync/remote-names.ts`), such folders are not claimed on disk, a restore leaves them out. Accepted limit: a remote rename into such a name reads here as the deletion of its source. -- **Diff views must never load unshowable content**: classify sides from `adapter.stat()`, manifest entry sizes, and `KNOWN_BINARY_EXTENSIONS` before reading or downloading anything (see `src/sync/projection.ts`). Keep this invariant when touching diff/merge code paths. -- **A drawing is its scene.** An Excalidraw file (front matter `excalidraw-plugin`) also holds the saving device's zoom, scroll and tool, so two devices save one drawing as different bytes. The scanner fingerprints the scene into `scene` (`drawing/scene.ts`: the text outside the drawing block plus each live element's `id:version:versionNonce`) and the diff takes equal scenes for equal content; otherwise every save pushes. Conflicts merge by element (`mergeDrawings`: the higher version wins, then the lower nonce; an element one side dropped goes unless the other changed it), never by lines, which yields a scene that no longer opens. Notes above the data changed on both sides stay a conflict. A drawing never earns a `live` mark: its file may lag its room. -- **Authorship is set only at publish.** `publishFileMap` runs `attribute` (`sync/authors.ts`): a changed hash takes the publisher, anything else keeps its parent's `by`. The `authors` table only grows, so an index read from any earlier manifest or baseline still names the same key; `by` is never content, so equality checks ignore it (`sameEntry`). -- **Every path belongs to exactly one space.** `spaceOf` picks the deepest root holding the path, else the vault. A space's scope owns its root's subtree minus the roots nested in it (`nestedRoots`); the vault treats share roots like a local ignore, so its entries there stay frozen until the vault's next push, which leaves them out of the manifest (`sync/foreign.ts`): frozen, they would hold the folder's blobs for good. The change record still lists them as `deleted`, so history GC sweeps the blobs once it rolls off; the Trash tab and a vault restore skip paths the vault no longer owns. A baseline forgets frozen entries the remote no longer has (`forgetDroppedForeign`, each refresh) so closing the share never reads them as remote deletions; entries the remote still lists stay, so an edit made before closing is a plain modify. A forgotten entry whose share here has no baseline of the path yet moves to the vault slot's `shareBases`, the live merge base of a note that just became a share (`baseTextOf`), never part of the baseline; it leaves once the share holds the path or the folder is the vault's again. A share's root folder is its mount point and belongs to no space: never published, never removed. -- **The partition is fixed per refresh.** A full refresh asks `host.spaces()` once inside the queue, pulling records before fixing the partition. A targeted share refresh keeps the previous partition; vault signals always request full discovery. `openSession(space, partition)` builds scopes from that list alone: a record arriving mid-cycle must not turn a root into unscanned vault content that a push publishes as deleted. Automatic operations reuse comparisons only inside that serialized cycle, with matching scope epoch and local-file revision. Hidden configuration files are rescanned because their writes emit no vault events. -- **A share never publishes the loss of all its files.** When a share's scan holds none of the files its baseline does (its folder was deleted or moved away on this device, or came back holding only new files; a file the scan left out counts as there), `compare` throws `SpaceGoneError` (`assertSpacePresent` in `sync/space.ts`): the share is that device's error, detached there, never an empty folder for everyone. The person settles it (`controller.settleGone`, asked by `ui/shares/space-gone.ts`): Restore forgets the share's state so it mounts afresh and pulls its files back; Delete pushes with the guard lifted for that one operation (`Space.goneAccepted`). The vault itself is not guarded. -- **Closing a share is a record edit, never a deletion of files.** Records are tombstoned (`closed`, `rev + 1`) so no device republishes them; a closed record leaves the partition from the next refresh, and its root returns to the vault scope with its files. Stop sharing then empties the share's own storage through the operation queue (`deleteShareObjects` refuses the vault). Every close, here or seen from elsewhere, and leaving shares with the vault storage forget the share's state by its id (`StorageState.space`), needing no session: a participant's slot keeps one identity across re-accepts, so a later reopen at any root would otherwise read the old baseline as deleted files. Stop sharing refreshes before it deletes, so an operation queued for the share is refused instead of pushing its objects back. -- **A paused share stays in the partition.** Pause is device-local (`settings.pausedSpaces`, never published); `spacesOf` marks the space `paused`, the refresh skips it and every session refuses it, reads such as history too (`OperationRunner.openSession`), but its root stays out of the vault scope. Dropping it from the partition would hand the folder to the vault and publish it there. -- **A moved root moves on every device before any scan.** A rename of a share root (or a folder above it) edits the record (`moveRoot`, `rev + 1`) and invalidates in the same tick; results begun before the invalidation are dropped (refresh epoch), so auto-push never acts on the old partition. A device that learns of the move keeps the folder where it is (`settings.localRoots`, saved with the records) and `plugin/share-moves.ts` moves it inside `host.spaces()`, before the partition is fixed; a blocked move keeps the share syncing at the old root. A closed share's folder is the vault's and is never moved. An old root must never turn into vault content that holds the share's files. -- **Vault-wide listings stay inside `objects/` and `pins/`.** Shares live under `/shares//` and records under `/spaces/` and `/links/`, inside the vault's prefix; GC, verify and reset must never list or delete beyond their own folders. -- **A space's remote paths are relative to its root; local ones never are.** Manifest, history log and pin manifests are translated only in their codec functions (`sync/space-paths.ts`, called from `sync/manifest.ts` and `sync/history/store.ts`); every read and write of those blobs goes through them, hash-only readers included. Each scan carries forward the hash-cache entries its space does not own, so one space's persist never drops another's. A share's `state.json` slot records the root its baseline sits under (`StorageState.root`); `projectSession` re-roots it once after a move (`manifestMoved`), and an unmoved baseline keeps its reference so the persister still debounces. -- **A note is live only in its own space's room.** The room is named under that space's keys by the path inside its root (`docIdIn`), and its frames go only on that space's slot (`HubConnection.space`). A note whose space changes (shared, paused, new key) leaves its room; the file sync of one space answers `later` for a note whose room belongs to another. Paused shares stay cold. A read-only person's notes follow their room and never write it (`FollowerSession`): a change made there, or an incoming version the room lacks, leaves the note to the file sync; the hub refuses every write from a read-only grant (`Refused`). -- **A live room is seeded once, and only while it has no log.** The session sends `Seed` from disk only on a `State` with `head == 0`; the hub appends it only into an empty log and answers a losing seed with the whole room, and the seed is applied locally only on its `Echo`. An empty room *with* a log is a deleted note: seeding it would resurrect it, two seeds would double it. An empty room behind what the device knows of it (its agreed seq in that generation, or a successor it was pointed at) lost its log and is never seeded. -- **Disk enters a live room only by three-way merge.** `mergeThreeWay(base, disk, room)`, then `patchYText` as inserts and deletes on code points; a shared run under 10 characters between two changes is re-inserted with them only when that saves an op, so a rewritten sentence is one replacement, not an item per shared letter (a device that edits inside such a run in the same moment lands beside the re-inserted copy). Never delete-all + insert and never a diff from room to disk: both overwrite what others wrote meanwhile. A conflict keeps both sides, the room's first; only overlapping hunks (or inserts at one point) conflict, neighbouring lines merge. A drawing merges by element against its agreed stamps; what the file dropped unchanged becomes a tombstone in the room, since a saved file leaves deleted elements out. -- **A `live` mark means the content is exactly that room's text at `seq`.** Only a hash equal to the note's agreed text earns it, and an open room with anything pending or unacked marks nothing: the path waits for the next push. Marks are `{doc, gen, seq}` with `doc` the note's generation-0 docId, ordered by `(gen, seq)`: a rebuilt room follows every snapshot of the one before. A mark never replaces the remote's mark of the same note at an equal or higher order. Two marks of one note are settled by that order, never merged (`sync/live-notes.ts`). -- **The file sync never writes a note whose room is open.** The incoming version goes to the room (`LiveNotes.absorb`: its own snapshot is already there, anything else is merged three-way against the baseline). The room saves the result through the note's editor before the baseline takes the remote entry, so the baseline never claims a version the disk lacks. A room behind a snapshot of itself answers `later`: nothing moves. So does a room that closed or moved while the incoming text was fetched, and a view that could not save. So does a note still joining its room while the hub is up; with the hub down it is an ordinary file, and every view showing it is readied for the write (`expectWrite`): Excalidraw takes the first write after its own save for that save's. A marked version written to a closed note becomes its agreed text, disk first, then the base, saved (`putNow`) before the journal lets a room open on it or releases it; a base not saved leaves the write cut short, for the next compare to save. Lost, the room would merge against an older base and bring back what it deleted. A merge's base (`grewFrom`) is held the same way; one cut short is redone from its step's remote entry, which needs the remote, so offline the note stays unfinished. Accepting the remote side goes the pull's way (`settleLive`: an open room takes it in, one not ready leaves the conflict), and revert leaves a note live editing holds; both write through `writeIncoming`, so a room snapshot they put back becomes the base. A revert to an unmarked version under a newer agreed base still replays into the room at its next open. Reconcile reads the base first, so it never pairs a newer base with an older disk. -- **A live snapshot is taken only from a settled document.** With nothing pending or unacked the Y.Doc is exactly the room at `lastSeq`; a snapshot holding an unacked edit would hand newcomers text the current followers never got. Only the lowest writer's client id sends it (a reader's awareness says `follows`), and the hub refuses one not newer than the snapshot it holds. -- **A room is rebuilt in one hub step, or not at all.** `Rotate` carries the sender's `lastSeq` as `upto`; the hub seeds the successor and seals the old room only if the log is still at `upto`, the room is not moved and the successor has no log. Otherwise an edit could be acked in the old room and missing from the new one. Only a settled session rotates, a follower of a pointer never seeds, and a pointer other than `docIdFor(path, gen + 1)` leaves the note to the file sync. -- **An update leaves the unacked FIFO only on its echo.** Everything unacked is resent on the next socket's `State`; frames queued under a dead socket's epoch never act on the new one. `State` names its log: another name, or a head behind what the session knows, means the room lost it. The note then rotates onto its next generation from its own text, never refills the old room: seqs would restart under marks, and a log regrown from another device's disk would double the text. -- **A rename carries its hashes.** The scanner trusts a cached hash while size and mtime match, so a rename moves the entry with the file (`StatePersister.carry`, applied before any read of the state). Accepted limit: an operation persists the cache its scan saw, so two files of equal size and mtime swapped while it runs keep each other's hashes until one is edited. -- **A move acts whole.** `pairMoves` (`sync/moves.ts`) pairs a gone path with a new one of the same baseline hash in one space (else by file name, only where one to one); anything unclear stays a delete plus an add. The other side's edit of the old path follows the file instead of conflicting. Push, pull and revert take both paths when asked for one (`withMoves`, `pullMoves`). A pull renames (`renameLocal`), never over a file that appeared at the new path since the compare, and never a note an open room holds; folders it emptied go (`removeEmptied`), never the space root nor one the remote keeps. Diff views of a move apply no hunks: their sides sit at two paths. A revert restores the source and trashes the destination, each only if unedited since the compare. A recasing the disk refuses steps through a free name (`renameCaseSafe`, every rename route, live's too): Obsidian mobile refuses a new case of a name as taken. Live editing never moves a room to a step in flight (`isRecaseStep`). A rename the disk refuses leaves the move waiting with a warning, the rest of the pull lands; a file left under its step name stops the pull (`StrandedRenameError`). Accepted limits: a destination edited while the source downloads keeps both files, nothing lost; a recasing whose rename back fails too stays under its step name, said in the error, and a push may publish it so; an open live room waits there as joining, holding the move back, until the next refresh or the rename back. diff --git a/.claude/testing.md b/.claude/testing.md deleted file mode 100644 index 72a1d093..00000000 --- a/.claude/testing.md +++ /dev/null @@ -1,106 +0,0 @@ -# Testing - -- vitest covers core logic (diff, hunks, concurrency, ignore, etc.). Run with `pnpm test`, or `pnpm --filter mdsync test:watch` while iterating. -- ALL domain logic (diffs, merging, concurrency, hunks matching, baseline cache) must have complete unit-test coverage. -- Tests mirror `src/`: `tests//.test.ts`, helpers in `tests/helpers/`. -- Live sessions run against the relay's own hub logic and SQLite store in-process (`tests/helpers/live-hub.ts`, via the `mdsync-relay` devDependency), with switches for lost frames and reconnects. `tests/live/chaos.test.ts` runs three devices through seeded edits, drops and half-open sockets and demands one text with every edit in it. -- Hunting silent data loss: the brief is `.claude/hunts/data-loss.md`. - -## Driving a real Obsidian - -`tools/obsidian.mjs` attaches to a running instance over CDP, so plugin UI can -be exercised without a human clicking. Obsidian must be started with the port -open (`node tools/obsidian.mjs launch`) - a normally launched instance exposes -nothing. Then `shot`, `click`, `text`, `cmd ` and `eval` drive it; -`eval` runs in the renderer, where `app` and `app.plugins.plugins.mdsync` are -reachable. After copying a new build in, reload with -`app.plugins.disablePlugin('mdsync')` then `enablePlugin` - `styles.css` is -re-injected only on reload. - -## End to end - -`tests/e2e/` runs scenarios against real processes and tears them down: - -- `pnpm exec jiti tests/e2e/optimization-ui.ts` - a real Obsidian renders synthetic 20,000-file Timeline and Trash lists in 100-row pages; page navigation and full-list selection are checked. Build first. Uses ports 8832 and 9233. -- `pnpm e2e:settings` - an isolated Obsidian checks passphrase and toggle scroll retention, device-only ignore rules, and phone layouts at 320, 390 and 600 px. Uses port 9235; `E2E_SHOTS=1` saves screenshots. -- `pnpm e2e:links` - share links under `wrangler dev` and headless Chrome: the Link Durable Object (chunks, erase, expiry, a restart), the routes, the viewer page (passphrase, one view, reload costs none, a hostile note runs nothing, outline on desktop and phone, heading folds, heading anchors, wide text, code copy). Port 8799. -- `pnpm e2e:links-obsidian` - builds, then shares a note from a real Obsidian through the file menu and opens the link in Chrome: properties, comments and embedded notes absent, math as MathML, callout, task and image kept, outline from the real render, passphrase, view count, update and stop. Ports 8799 and 9246; `E2E_SHOTS=1` saves `link-viewer.png`. -- `pnpm e2e:hub` - the relay hub under `wrangler dev`, driven by scripted peers; - ending a share cuts its channel for good (across a restart too); its last run - sets `HUB_STALE_MS` low to watch the stale-socket sweep. -- `pnpm e2e:realtime` - builds, then runs the plugin in a throwaway Obsidian - (own `--user-data-dir` and temp vault, trust modal clicked) against the relay; - a scripted peer reads and writes its sealed presence under a handed-in key. - `E2E_SOAK_MS=130000` adds an idle stretch past the link's silence timeout. -- `pnpm e2e:live` - two Obsidians type into one note through the relay; the - shared key lives on an in-memory WebDAV (`startWebDav`). Undo through the - phone toolbar's path and the Edit menu's takes back only the device's own - typing. A file written under the open note from outside Obsidian joins the - room; ends with a rename of the open note that the other device follows. -- `pnpm e2e:shares` - two Obsidians of one owner on an in-memory S3 - (`startS3`): one shares a folder through its menu, the other mounts it, - pauses and resumes it; the first renames the folder and the other follows. -- `pnpm e2e:invite` - an owner and a participant with separate vaults: invite - through the relay's broker, accept through the protocol handler; each - side's edit reaches the other on the share channel's signal alone, and a - change or rename in the share pushes by itself (a rename lands as a rename). -- `pnpm e2e:guest` - a participant with no vault storage joins and syncs the - share alone, then sets up a vault: the record goes there, the share's files - do not. -- `pnpm e2e:people` - a read-only participant (its editor locked, following - the owner's typing live), a re-invite - that kills the old link and whose new one takes over the folder in place, - the owner's rotated S3 key (`s3.revoke`) reaching the broker, who has - access and Revoke in the share's window. -- `pnpm e2e:live-share` - an owner and a participant type into one note of a - share, in the share's room on the owner's relay; the cursor carries the - invited name, authors tint the other's text, and the sync after is clean; - presence reaches a device with no note open, the tree and the share's window - show who is where (a collapsed folder too), the header shows the other person - live, its cursor marks the scrollbar, "follow cursor" jumps there and - scrolls down a long insert until the owner's own wheel ends it, and - closing the note leaves it; a note the other changed shows as new until - opened. -- `pnpm e2e:live-into-share` - two devices of one owner type into a live note - while one shares its folder; both end in the share's room, every edit once. -- `pnpm e2e:live-drawing` - two Obsidians with the Excalidraw plugin (latest - release, fetched once into `temp/e2e-plugins/`) draw into one drawing: shapes, - concurrent edits and a deletion reach the other, the pointer shows, and the - file sync of drawings saved with different zoom settles clean; with live - off, a drawing view that saved takes what the sync writes under it. - `E2E_SHOTS=1` saves screenshots of these under `artifacts/e2e-shots/`. -- `pnpm e2e:note-switch` - one leaf switches between two live notes of a - share with a slow disk read and a focus change mid-load: no moment shows - one note's change signs on the other's text, the header's live mark never - drops, and each note keeps its own text. - -On Windows the Obsidians run on a desktop of their own (`hidden-desktop.ps1`), -so they never show or take focus; `E2E_VISIBLE=1` puts them on screen. - -`tests/e2e/device.ts` drives a device: sync, files, folder menus, modals. -`tests/e2e/sharing.ts` holds the owner-and-participant setup and share steps. -`tests/e2e/editor.ts` opens, types into and reads a device's editor. -Obsidian 1.13 mounts modals in `activeDocument`, not `document`, and keeps -protocol handlers in `app.workspace.protocolHandler.handlers`; never open an -`obsidian://` URL through the OS, it would reach the user's own Obsidian. -Settings stay open under later modals, so helpers search the topmost first; -close buttons ignore synthetic clicks, `closeModals` sends Escape. - -Ports 8799 (relay), 8801 (WebDAV), 8802 (S3), 9223 and 9224 (CDP) must be free. A run -killed midway can leave `wrangler dev` holding 8799: kill that tree. The relay -keeps its storage in `packages/relay/.wrangler/e2e-state`, wiped when a run -starts it first: tables an older build left would break the hub. New -scenarios reuse `launchObsidian`, `startRelay`, `startWebDav`, `startS3` and -`connectPeer`; several Obsidians need distinct CDP ports. - -## Manual install for testing - -Copy `main.js`, `manifest.json`, `styles.css` to -`/.obsidian/plugins//`, reload Obsidian and enable the -plugin in **Settings → Community plugins**. Both `main.js` and `styles.css` are -build outputs, so run `pnpm build` (or `pnpm dev`) first - neither is in git. - -## Mobile - -- Where feasible, test on iOS and Android. -- Don't assume desktop-only behaviour unless `isDesktopOnly` is `true`. diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 396312fb..aa48f26c 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -23,4 +23,5 @@ jobs: - run: pnpm -r --if-present run build - run: pnpm run lint - run: pnpm run typecheck + - run: pnpm run arch - run: pnpm -r --if-present run test diff --git a/.husky/pre-commit b/.husky/pre-commit index ec1470b7..db758b1b 100644 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,2 +1,3 @@ pnpm run lint -pnpm -r --if-present run typecheck +pnpm run typecheck +pnpm run arch diff --git a/AGENTS.md b/AGENTS.md index 25a87827..342fbd7a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,36 +1 @@ -# MDSync - -An Obsidian community plugin that syncs a vault between devices over -user-configured remote storage (S3-compatible, WebDAV, Google Drive). -TypeScript, bundled to `main.js` by esbuild. - -pnpm workspace: `packages/plugin` (the plugin), `packages/relay` (one -Cloudflare worker: realtime relay over PartyServer Durable Objects, share -broker, Google OAuth proxy; deployed by the Deploy Relay workflow). - -## Commands - -- `pnpm install` - dependencies -- `pnpm dev` - esbuild watch -- `pnpm build` - production bundle -- `pnpm lint` / `pnpm lint:fix` - Biome over the whole repo -- `pnpm typecheck` - `tsc -noEmit` in every package -- `pnpm test` - all vitest suites (`pnpm --filter mdsync test:watch` while iterating) - -## Read before touching sync code - -Breaking an engine invariant silently corrupts user data or publishes remote -deletions. Read [sync invariants](.claude/sync-invariants.md) before changing -diff, hunk, baseline, history or GC code, and [platform contracts](.claude/platform-contracts.md) -before code that writes, renames or deletes vault files. - -## Guidelines - -- [Architecture](.claude/architecture.md) - layout, layering, imports, conventions -- [Sync invariants](.claude/sync-invariants.md) - data-integrity rules of the engine -- [Platform contracts](.claude/platform-contracts.md) - what Obsidian's adapter really does on each platform -- [Spaces, shares and live](.claude/shares.md) - the model, relay hub, protocol and live layer, and why -- [Commands & settings](.claude/commands-and-settings.md) - commands, settings, transfer, UI copy -- [Testing](.claude/testing.md) - vitest, CDP driver, manual install -- [Releasing](.claude/releasing.md) - manifest, versioning, release assets -- [Security](.claude/security.md) - privacy, compliance, listener cleanup +The instructions for this repository live in CLAUDE.md, read that file. diff --git a/CHANGELOG.md b/CHANGELOG.md index 7be9dec1..cc61d904 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,66 @@ This file is the source of truth for release notes: the section of a version becomes the notes of its GitHub release. The newest section must match `version` in `manifest.json`. Headings are `## [x.y.z] - YYYY-MM-DD`, then `### Important`, `### Features`, `### Improvements` and `### Fixes` as needed. Write for users, in plain sentences, not commit titles. +## Unreleased + +### Important + +- **Update MDSync on every device.** Once a device with this version pushes, devices still on an older version stop syncing with that storage until they are updated. +- **File history starts over.** History from earlier versions is not carried over: after the first push, its versions and pinned versions are deleted. +- **Plugins sync only their settings by default.** Each plugin's settings (`data.json`) sync, existing setups included, and nothing is deleted. Install and update plugins on each device yourself, or choose **Code** or **All** for **Plugins** in **Settings → MDSync → Sync** to sync the plugin itself too. + +### Features + +- **New file history.** Every push is kept for an hour, then one version per 10 minutes, hour, day and week. Past that, only how busy each day was remains. Pinned versions stay. **Keep history for** in **Settings → MDSync → History** replaces **Versions to keep**; with several devices, the shortest choice among them applies. +- **Timeline** groups pushes into sessions, with an activity calendar and a filter by path and day. **History** lists a file's versions by age, dated by their push. **Deleted** has a path filter and says until when each file is kept. +- **What history holds** in **Settings → MDSync → History** shows pushes per day across your devices; select a day to open it in Timeline. An **Activity** card on the settings page shows the same at a glance. +- **Big files sync in parts.** Only the parts that changed are uploaded, and a pull downloads only the parts the copy on disk lacks. +- **Slow files.** Drawings and canvases save every few seconds while you work on them, so an automatic push waits until you stop or leave the file, at most 10 minutes. Set the list and its quiet period under **Slow files** in **Settings → MDSync → Sync**. Pushing by hand sends them at once. +- **Search in compare and merge.** Each pane has a search icon in its header, and Ctrl/Cmd+F opens and closes search in the pane you are in. Find works with match case, whole word and regular expressions, folded lines included, and Result also replaces. Ctrl/Cmd+Alt+G goes to a line. +- **Merge from the keyboard.** **Take local in merge**, **Take remote in merge**, **Take both in merge, local first**, **Go to next merge conflict** and **Save merge result** act on the change at the cursor; give them hotkeys in **Settings → Hotkeys**. +- **Choose per plugin.** Under **Plugins** in **Settings → MDSync → Sync**, **Per plugin** sets a level for single plugins on this device: **Off**, **Settings**, **Code** (also the plugin itself) or **All** (also the rest of its folder, such as caches). Plugins that only your other devices have are listed too. A plugin set on its own also syncs while **Plugins** is off, so you can sync just one private plugin. The choice is not shared between devices, but it travels with a device transfer link. +- **Restart notice.** When a sync brings plugin code or the list of enabled plugins from another device, MDSync says "Plugins changed on another device. Restart Obsidian to load them.", because Obsidian reads them only at startup. +- **Settings merge by key.** When two devices change different settings of Obsidian or of a plugin, autosync merges the settings file instead of leaving a conflict. +- **Setup asks what you want.** A new step in the setup wizard chooses when to sync (**Manual**, **Automatic** or **Instant** with a relay), whether to keep history, and which parts of Obsidian sync, plugins one by one included. On a device joining by a setup link it shows what the link brought, to change for this device. +- **First sync shows what it will do.** The last step of the wizard compares first and lists what would be uploaded, downloaded or is in conflict, before **Sync N files** moves anything. When it is done, a short guide says where the status bar, panel, file tree marks and editor margin are. + +### Improvements + +- The setup wizard rises as a bottom sheet on a phone, with its buttons always in reach. +- A new install keeps file history from the start. Sync stays manual until you choose otherwise. +- With manual sync, MDSync compares once after startup, so the file tree, status bar and **Changes** show what waits right away. Nothing moves until you push or pull, and it never asks for the passphrase on launch. +- **History** has its own page in **Settings → MDSync**. On the **Sync** page, **Automatic sync** and **Real time** are separate groups, and **Interval** is a list of choices. +- **Turn on history** in the History, Timeline and Deleted tabs, where history is off, instead of a pointer to settings. +- While a conflict is open, Push and Pull in the Changes panel look disabled, and pushing a file says which conflict to resolve first instead of failing. +- A conflict with no earlier version to merge from (a file added on two devices, or a binary file) offers **Compare…** instead of **Merge…**, and its card says it was added on both sides. +- Compare in a narrow pane keeps the file name and its buttons in view: the hint gets its own line and the buttons wrap. +- The status bar menu no longer says nobody is in a shared note when no shared folder is connected. +- The status bar menu groups the vault and shared folders under the relay that carries them, since folders on one relay share one connection. A folder whose state differs from its relay's says so, one with no room left on its relay too, and selecting a shared folder opens its window. +- On a phone, settings that do nothing there (**Status bar indicator**, **Ignore symlinks**) are hidden. +- Autosync merges conflicts on its own only in notes (`.md`) and in settings files. Everything else, plugin code and other JSON included, waits for you: a merge by lines can break such files. +- In a JSON file written by Obsidian or a plugin, keys that only moved show no change in merge, and a merged result that is not valid JSON is not saved. +- Unsaved merge edits come back when you close the tab and open **Merge…** again, as long as neither version changed. +- **Merge…** says why it is unavailable, refuses a file changed since the compare, and the merge bar says when the file changed while you merge. +- The tab menu of compare and merge copies the file's path or the whole text of either side. +- Change cards show how many lines each change adds and removes. +- Leaving a file with picked but unapplied changes asks first. +- A restored version stays out of automatic pushes until you edit, push or pull it. +- Changes to the configuration folder are kept out of file history and Timeline. +- Files are compressed in storage when that makes them smaller. Excalidraw drawings saved compressed are stored unpacked, so they compress better and sync in parts, and they come back exactly as saved. +- History, Timeline and Deleted load faster, and old versions are cleaned up in the background after pushes. +- The default **Max file size** is now 25 MB. + +### Fixes + +- **Keep both versions** no longer creates a copy that would never sync, such as a plugin code file while only plugin settings sync. +- On a phone, the back arrow in a diff keeps the sidebar open. +- A deleted file opened from the Timeline shows the same diff as in **Deleted**, not a plain text view. +- The activity calendar in settings opens scrolled to today. +- A diff or source control tab moved to its own window follows that window's size: the diff turns Inline when narrow, long lists fill as the pane grows. +- A diff or merge moved to its own window keeps line numbers beside the text. +- Stepping through changes rings the change at once, without a flash at the top, and Inline rings a removed line's card. +- In merge, the connectors of a conflict where both sides added lines reach its whole card instead of a thin tail hidden behind **Take**. + ## [1.4.1] - 2026-10-27 ### Improvements diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..fca541df --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,55 @@ +# MDSync + +An Obsidian community plugin that syncs a vault between devices, end-to-end encrypted, over storage the user owns (S3-compatible, WebDAV, Google Drive), with an optional self-deployed Cloudflare relay for live editing, shared folders and share links. pnpm 10 workspace, Node 24, TypeScript strict, Biome. + +| Package | Holds | +|---|---| +| `packages/plugin` | `mdsync`: the plugin, bundled to `main.js` and `styles.css` by esbuild. Feature slices under `src/features/`, shared infra in `src/core/`, composition root in `src/app/` | +| `packages/relay` | `mdsync-relay`: one Cloudflare worker (Durable Objects, no PartyServer): relay hub, share broker, link storage, Google OAuth proxy. The plugin deploys it from its own bundle | +| `packages/protocol` | `@mdsync/protocol`: wire formats and signing shared by plugin, relay and viewer (hub frames, sealed link format, SigV4 helpers) | +| `packages/viewer` | `mdsync-viewer`: the page a share link opens, built and served by the relay | +| `tests/e2e/` | end-to-end scenarios against real Obsidian, `wrangler dev` and in-memory S3/WebDAV: `tests/e2e/README.md` | + +## Commands + +- `pnpm install` - dependencies +- `pnpm dev` - esbuild watch of the plugin +- `pnpm build` - typecheck, then the production bundle (`main.js`, `styles.css`; the relay is bundled into it) +- `pnpm lint` / `pnpm lint:fix` - Biome over the repo +- `pnpm typecheck` - `tsc` in every package and in `tests/` +- `pnpm test` - every vitest suite (`pnpm --filter mdsync test:watch` while iterating) +- `pnpm arch` - plugin dependency boundaries (`packages/plugin/.dependency-cruiser.cjs`); the folder cap runs in `pnpm test` +- `pnpm e2e:` - real-process scenarios (list and prerequisites in `tests/e2e/README.md`); on macOS set `OBSIDIAN_EXE=/Applications/Obsidian.app/Contents/MacOS/Obsidian` + +## Rules + +`.claude/rules/` holds the working rules; Claude Code loads each when you touch a file matching its `paths`. Other agents read the ones that match the files in their task. A rule holds constraints and mechanisms; explanations, flows and accepted limits live in the README next to the code (`packages/plugin/src/features/*/README.md`, `packages/viewer/README.md`, `tests/e2e/README.md`). + +| Rule (`.claude/rules/.md`) | Covers | +|---|---| +| `structure` | plugin layout, feature slices, imports, `pnpm arch`, styles, bundle and mobile constraints (`packages/plugin/src/**`, `tests/**`) | +| `sync-integrity` | engine invariants: baseline, manifest, push and pull, deletions, conflicts (`features/sync/**`) | +| `hunks` | hunk anchoring, diff, merge, change signs, partial operations | +| `history` | history log, pins, timeline, trash, restore, GC | +| `vault-io` | what Obsidian's adapter does on each platform: non-atomic writes, renames, case, symlinks | +| `spaces` | shared folders: records, owner and participant flows, broker, moves, pause | +| `realtime` | hub protocol, channels, grants, frames, relay worker | +| `live` | live documents: sessions, rooms, cold sync, drawings, authors | +| `presence` | who is where: announcements, header pill, follow, file tree marks | +| `links` | share links: snapshot, sealed format, broker, viewer | +| `security` | secrets, envelope, device key, privacy, listener cleanup | +| `settings-setup` | commands, settings and transfer, setup wizard, relay deploy and update | +| `ui` | `core/ui` primitives, copy, tooltips, tokens, phone behavior | +| `testing` | test placement, helpers, mocks, live hub harness, real-Obsidian driving | +| `releasing` | manifest, versioning, changelog, release workflow | + +Rules describe the code as it is. A change that adds, renames or retires a mechanism, convention or path updates every rule, skill and README that names it, in the same commit: grep `.claude/` and `features/*/README.md` for the old name before finishing. + +## Skills + +- `new-feature` (`.claude/skills/new-feature/SKILL.md`) - before creating a slice under `packages/plugin/src/features/` +- `hunt-data-loss` - the brief for hunting silent data loss in the sync engine + +## Comments + +Explain only a non-obvious reason, invariant, compatibility constraint or platform quirk, in 1-2 lines. Never narrate names, types or the code below. Use `-`, not a long dash. diff --git a/README.md b/README.md index 83b9ddf5..ff9c86fd 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ MDSync syncs your vault through an S3 bucket, a WebDAV server or Google Drive. T ## Quick start 1. Install [MDSync](https://community.obsidian.md/plugins/mdsync) from **Settings → Community plugins** and enable it. The setup wizard opens on its own; later, run **MDSync: Set up sync**. -2. On the first device, choose **Start syncing this vault**: pick a storage, choose a passphrase (12 characters or more) and, if you want real time, deploy the relay. **Sync now** on the last step does the first upload. +2. On the first device, choose **Start syncing this vault**: pick a storage, choose a passphrase (12 characters or more), choose when to sync and what of Obsidian syncs and, if you want real time, deploy the relay. The last step shows what the first sync would move; **Sync N files** runs it. 3. On every other device, choose **Connect to a vault set up on another device** and paste a [setup link](#device-transfer) from the first one. Give each vault its own bucket prefix. MDSync refuses a prefix that already holds another vault. @@ -91,7 +91,7 @@ Set up the first device alone and let its first sync finish. That sync creates t The panel has four tabs: **Changes**, **History**, **Timeline** and **Deleted**. -**Changes** lists local changes, remote changes and conflicts, with a path filter. Open any file for a side-by-side diff (combined on narrow screens or on request). In a text file you can revert a single local change or accept a single remote one, then apply your choices. Binary files show the size change instead, with **Show differences anyway** where the file can be read as text. +**Changes** lists local changes, remote changes and conflicts, with a path filter. Open any file for a side-by-side diff (combined on narrow screens or on request). In a text file you can revert a single local change or accept a single remote one, then apply your choices; leaving the file before you apply them asks first. The search icon on each pane (in the toolbar when combined), or Ctrl/Cmd+F, toggles a find bar over the text of a diff or merge, folded lines included, with match case, whole word and regular expressions; in a merge's result it also replaces. Ctrl/Cmd+Alt+G goes to a line. The tab's menu copies the file's path or the whole text of either side. Binary files show the size change instead, with **Show differences anyway** where the file can be read as text.

Demo @@ -102,17 +102,22 @@ The panel has four tabs: **Changes**, **History**, **Timeline** and **Deleted**. ### Automatic sync -In **Settings → MDSync → Sync** you can turn on: +With everything here off, sync is manual: after startup MDSync only compares, so the file tree, the status bar and **Changes** show what waits, and nothing moves until you push or pull. It skips that compare when it would have to ask for your passphrase. -- **Autosync**: compare, pull and push every few minutes. +Under **Automatic sync** in **Settings → MDSync → Sync** you can turn on: + +- **Autosync**: compare, pull and push after startup and then at the **Interval** you choose. - **Push after changes settle**: push once the vault has been quiet for a set delay. It never pulls, so conflicts and incoming changes wait for you. +- **Slow files**: drawings and canvases save every few seconds while you work. A push after changes leaves them until you pause, leave the file or 10 minutes pass, so your notes still go out on time. A push by hand sends them at once. - **Push after successful pull**. ### Conflicts -A conflict is a file changed both here and on the remote. For each one you can **Keep local**, **Accept remote**, **Keep both versions** (the remote copy lands next to yours as `todo (conflict from Phone 2026-07-05).md`) or **Merge…**. +A conflict is a file changed both here and on the remote. For each one you can **Keep local**, **Accept remote**, **Keep both versions** (the remote copy lands next to yours as `todo (conflict from Phone 2026-07-05).md`) or **Merge…**. A file added on both devices with different contents has no earlier version to merge from, nor has a binary file: **Compare…** shows the two side by side to keep one, or both. While a conflict is open, nothing else in the vault (or in that shared folder) pushes or pulls. + +**Merge…** opens a three-way editor: your version, the result and the remote version side by side. Changes that do not overlap are merged up front, and you review and save. Autosync merges such conflicts in notes (`.md`) on its own, and in Obsidian's and plugins' settings when each device changed different settings. It leaves the rest to you, plugin code and other JSON included: a merge by lines can break them. In a JSON file written by Obsidian or a plugin, keys that only moved show no change, and a result that is not valid JSON is not saved. Unsaved merge edits come back when you close the tab and open **Merge…** again, as long as neither version changed. -**Merge…** opens a three-way editor: your version, the result and the remote version side by side. Changes that do not overlap are merged up front, and you review and save. Autosync merges such conflicts on its own and leaves the rest to you. +From the keyboard, **Take local in merge**, **Take remote in merge**, **Take both in merge, local first**, **Go to next merge conflict** and **Save merge result** act on the change at the cursor; give them hotkeys in **Settings → Hotkeys**.
Demo @@ -147,15 +152,15 @@ README.md Ignoring never deletes anything: a matching file stops syncing, and copies on the remote and other devices stay. To remove a file everywhere, delete it first and then ignore it. -**Ignore symlinks** (on by default) skips symbolic links and Windows junctions, which Obsidian shows as ordinary folders. **Max file size** skips anything larger. +**Ignore symlinks** (on by default, desktop only) skips symbolic links and Windows junctions, which Obsidian shows as ordinary folders. **Max file size** skips anything larger. ### Obsidian settings sync -Under **Obsidian configuration scope** you choose what else to sync: core settings, hotkeys, the list of enabled plugins, plugins with their settings, CSS snippets and themes. Every category is off by default and chosen per device. Turning one off deletes nothing. **Clear on remote** removes a category from the remote without touching local files. MDSync's own plugin folder never syncs. +Under **Obsidian configuration scope** you choose what else to sync: core settings, hotkeys, the list of enabled plugins, plugins, CSS snippets and themes. Every category is off by default and chosen per device. **Plugins** syncs each plugin's settings by default; choose **Code** to sync the plugins themselves (install and update everywhere) or **All** for the rest of their folders too, such as caches. **Per plugin** sets a level for single plugins on this device, and one set that way syncs even while **Plugins** is off. After a sync brings plugin code or the enabled list from another device, restart Obsidian to load it. Turning one off deletes nothing. **Clear on remote** removes a category from the remote without touching local files. MDSync's own plugin folder never syncs. ## History -Every push records what it changed. **Versions to keep** sets how many pushes history holds; pinned versions are kept until you unpin them. +Every push records what it changed (history is on for a new install; turn it off with **Keep history** in **Settings → MDSync → History**). History keeps every push for an hour, then fewer as they age: one per 10 minutes, hour, day and then week. **Keep history for** (3 months by default) sets how long versions stay; past it only how busy each day was remains. Pinned versions are kept until you unpin them. Every device thins the same history, so the shortest choice among your devices applies. ### File history @@ -216,7 +221,7 @@ A note open on two devices edits together, keystroke by keystroke, with the othe ### Presence -The note header shows who else has the note open, as coloured initials. Click one, or **Follow** in the shared folder's window, to follow that person: your tab opens the notes they open and keeps their cursor in view, with a banner to stop. The file explorer colours changed files with a mark for each (a dot for your changes, an arrow for ones to pull, an alert for conflicts), shows headcounts on shared folders and a dot on files others changed that you have not opened yet. On desktop, one status bar item shows where sync stands and the relay state; select it for a menu with Push, Pull and Compare. +The note header shows who else has the note open, as coloured initials. Click one, or **Follow** in the shared folder's window, to follow that person: your tab opens the notes they open and keeps their cursor in view, with a banner to stop. The file explorer colours changed files with a mark for each (a dot for your changes, an arrow for ones to pull, an alert for conflicts), shows headcounts on shared folders and a dot on files others changed that you have not opened yet. On desktop, one status bar item shows where sync stands and the relay state; select it for a menu with Push, Pull and Compare, and each relay with the folders it carries over its one connection. Select a shared folder there to open its window. Turn off **Show my open note to others** to stay online without showing where you are. @@ -336,7 +341,7 @@ Storage credentials, share keys, share links, the relay secret and the Cloudflar ```text /manifest.json.enc encrypted file list -/history.json.enc encrypted change log, one entry per push +/history/... encrypted change records, one per push, thinned over time /salt.bin /keys.json vault key wrapped by your passphrase /objects/.enc encrypted file contents @@ -377,10 +382,9 @@ While the OAuth consent screen is in testing mode, Google expires refresh tokens What comes next, in this order: -1. **Big files.** Today a file is read and encrypted whole, so anything over **Max file size** (100 MB by default) is skipped. Large files will sync in parts, so videos and big PDFs go through without holding the whole file in memory. -2. **History that thins out.** **Versions to keep** holds the last pushes, so a busy afternoon of pushes drops last week. History will keep every recent push and fewer as they age, down to one a day and then one a week, so older days stay reachable. -3. **Canvas sync.** Obsidian Canvas boards merge card by card and edit live, as Excalidraw drawings do. -4. **Relay on your own server.** The relay will run outside Cloudflare too, for when the Workers free tier runs short, and as a home for features that need more than it gives. +1. **Big files.** Today a file is read whole into memory, so anything over **Max file size** (25 MB by default) is skipped. Large files will stream in parts, so videos and big PDFs go through without holding the whole file in memory. +2. **Canvas sync.** Obsidian Canvas boards merge card by card and edit live, as Excalidraw drawings do. +3. **Relay on your own server.** The relay will run outside Cloudflare too, for when the Workers free tier runs short, and as a home for features that need more than it gives. ## Development diff --git a/package.json b/package.json index 4637a2e3..e9fe2460 100644 --- a/package.json +++ b/package.json @@ -11,9 +11,11 @@ "test": "pnpm -r --if-present run test", "lint": "biome check .", "lint:fix": "biome check --write .", - "typecheck": "pnpm -r --if-present run typecheck && tsc -p tests", + "typecheck": "pnpm -r --if-present run typecheck && tsc -p tests && tsc -p tools/measure-history", + "arch": "pnpm --filter mdsync run arch", "version": "node version-bump.mjs", "obsidian": "node tools/obsidian.mjs", + "measure:history": "node tools/measure-history/run.mjs", "e2e:hub": "jiti tests/e2e/hub.ts", "e2e:links": "jiti tests/e2e/links.ts", "e2e:links-obsidian": "pnpm build && jiti tests/e2e/links-obsidian.ts", @@ -29,6 +31,7 @@ "e2e:people": "pnpm build && jiti tests/e2e/people.ts", "e2e:live-drawing": "pnpm build && jiti tests/e2e/live-drawing.ts", "e2e:note-switch": "pnpm build && jiti tests/e2e/note-switch.ts", + "e2e:history": "pnpm build && jiti tests/e2e/history.ts", "prepare": "husky" }, "devDependencies": { diff --git a/packages/plugin/.dependency-cruiser.cjs b/packages/plugin/.dependency-cruiser.cjs new file mode 100644 index 00000000..7488c970 --- /dev/null +++ b/packages/plugin/.dependency-cruiser.cjs @@ -0,0 +1,101 @@ +/** Lowest first: a domain imports only those before it, types included. */ +const DOMAINS = [ + "storage", + "sync", + "live", + "presence", + "spaces", + "links", + "relay", + "transfer", +]; +const SURFACES = { + diff: [], + "editor-signs": [], + explorer: [], + "note-header": [], + settings: [], + setup: ["settings"], + "source-control": ["diff", "setup"], + status: ["diff", "source-control"], +}; +const SLICE = "^src/(features|core)/[^/]+/"; +const FACADE = "^src/(features|core)/[^/]+/index\\.ts$"; + +const domainOrderRules = DOMAINS.slice(0, -1).map((from, i) => ({ + name: `domain-order-${from}`, + comment: `${from} never imports ${DOMAINS.slice(i + 1).join(", ")}`, + severity: "error", + from: { path: `^src/features/${from}/` }, + to: { path: `^src/features/(${DOMAINS.slice(i + 1).join("|")})/` }, +})); + +const surfaceRules = Object.entries(SURFACES).map(([from, allowed]) => ({ + name: `surface-${from}`, + comment: `${from} may reach other surfaces only: ${allowed.join(", ") || "none"}`, + severity: "error", + from: { path: `^src/features/${from}/` }, + to: { + path: `^src/features/(${Object.keys(SURFACES).join("|")})/`, + pathNot: [ + `^src/features/${from}/`, + ...allowed.map((s) => `^src/features/${s}/`), + ], + }, +})); + +/** @type {import('dependency-cruiser').IConfiguration} */ +module.exports = { + forbidden: [ + { + name: "no-circular", + severity: "error", + from: {}, + to: { circular: true, viaOnly: { dependencyTypesNot: ["type-only"] } }, + }, + { + name: "slice-via-facade", + comment: "Another slice is reached through its index.ts only", + severity: "error", + from: { path: "^src/(features|core)/([^/]+)/" }, + to: { path: SLICE, pathNot: ["^src/$1/$2/", FACADE] }, + }, + { + name: "root-via-facade", + comment: "app/ and main.ts reach slices through their index.ts only", + severity: "error", + from: { path: "^src/", pathNot: SLICE }, + to: { path: SLICE, pathNot: FACADE }, + }, + { + name: "core-independent", + comment: "core/ knows no feature and no app", + severity: "error", + from: { path: "^src/core/" }, + to: { path: "^src/(features|app)/" }, + }, + { + name: "features-not-app", + comment: + "A feature declares its deps instead of importing the composition root", + severity: "error", + from: { path: "^src/features/" }, + to: { path: "^src/(app/|main\\.ts$)" }, + }, + { + name: "domain-not-surface", + severity: "error", + from: { path: `^src/features/(${DOMAINS.join("|")})/` }, + to: { path: `^src/features/(${Object.keys(SURFACES).join("|")})/` }, + }, + ...domainOrderRules, + ...surfaceRules, + ], + options: { + doNotFollow: { path: "node_modules" }, + exclude: { path: "\\.d\\.ts$" }, + tsPreCompilationDeps: true, + tsConfig: { fileName: "tsconfig.json" }, + enhancedResolveOptions: { extensions: [".ts", ".js"] }, + }, +}; diff --git a/packages/plugin/esbuild.config.mjs b/packages/plugin/esbuild.config.mjs index 3727fa60..166ef453 100644 --- a/packages/plugin/esbuild.config.mjs +++ b/packages/plugin/esbuild.config.mjs @@ -57,7 +57,7 @@ const cssContext = await esbuild.context({ banner: { css: banner, }, - entryPoints: ["src/styles/index.css"], + entryPoints: ["src/styles.css"], bundle: true, target: ["chrome111", "safari16.4"], logLevel: "info", diff --git a/packages/plugin/esbuild.relay-bundle.mjs b/packages/plugin/esbuild.relay-bundle.mjs index 65487e3d..c551b3d1 100644 --- a/packages/plugin/esbuild.relay-bundle.mjs +++ b/packages/plugin/esbuild.relay-bundle.mjs @@ -1,18 +1,23 @@ import { execSync } from "node:child_process"; -import { readFileSync } from "node:fs"; +import { readdirSync, readFileSync, statSync } from "node:fs"; +import { join } from "node:path"; import { fileURLToPath } from "node:url"; const BUNDLE = fileURLToPath( new URL("../relay/dist/relay-bundle.json", import.meta.url), ); const PACKAGE = fileURLToPath(new URL("./package.json", import.meta.url)); +// What the bundle is built from: the worker, the viewer it serves, and the protocol both import. +const SOURCES = ["relay", "viewer", "protocol"].map((name) => + fileURLToPath(new URL(`../${name}/src`, import.meta.url)), +); /** * Serves `mdsync:relay-bundle`: the relay built in the same run, so a release deploys the relay of - * its own commit. Built once per process; a watch picks up relay changes on restart. + * its own commit. A watch rebuilds it when the sources above change, and only then. */ export function relayBundle() { - let contents; + let built; return { name: "relay-bundle", setup(build) { @@ -21,19 +26,60 @@ export function relayBundle() { namespace: "relay-bundle", })); build.onLoad({ filter: /.*/, namespace: "relay-bundle" }, () => { - if (!contents) { - // Through the shell: pnpm is a .cmd shim on Windows. - execSync("pnpm --filter mdsync-relay run bundle", { - stdio: ["ignore", "ignore", "inherit"], - }); - const bundle = JSON.parse(readFileSync(BUNDLE, "utf8")); - const { version } = JSON.parse(readFileSync(PACKAGE, "utf8")); - // The release orders relays, so an older plugin never offers a downgrade. - bundle.version = `${version}+${bundle.version}`; - contents = JSON.stringify(bundle); + const { files, dirs } = sourceTree(); + // watchDirs sees only entries added or removed, not subfolders or edits: files cover those. + const watch = { watchFiles: files, watchDirs: dirs }; + // onLoad runs on every rebuild, also those caused by the plugin's own sources. + let stamp = stampOf(files); + // A save during the build is already in the watch's baseline and would never rebuild: build again. + while (built?.stamp !== stamp) { + try { + built = { stamp, contents: buildRelay() }; + } catch (error) { + built = undefined; + // A throw would end the watch for good: esbuild keeps no watch list of a failed load. + return { errors: [{ text: error.message }], ...watch }; + } + stamp = stampOf(files); } - return { contents, loader: "json" }; + return { contents: built.contents, loader: "json", ...watch }; }); }, }; } + +function buildRelay() { + // Through the shell: pnpm is a .cmd shim on Windows. + execSync("pnpm --filter mdsync-relay run bundle", { + stdio: ["ignore", "ignore", "inherit"], + }); + const bundle = JSON.parse(readFileSync(BUNDLE, "utf8")); + const { version } = JSON.parse(readFileSync(PACKAGE, "utf8")); + // The release orders relays, so an older plugin never offers a downgrade. + bundle.version = `${version}+${bundle.version}`; + return JSON.stringify(bundle); +} + +function stampOf(files) { + return files + .map( + (file) => `${file}:${statSync(file, { throwIfNoEntry: false })?.mtimeMs}`, + ) + .join("\n"); +} + +function sourceTree() { + const files = []; + const dirs = [...SOURCES]; + for (const root of SOURCES) { + for (const entry of readdirSync(root, { + recursive: true, + withFileTypes: true, + })) { + (entry.isDirectory() ? dirs : files).push( + join(entry.parentPath, entry.name), + ); + } + } + return { files, dirs }; +} diff --git a/packages/plugin/package.json b/packages/plugin/package.json index a49471b1..29a736f7 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -10,7 +10,8 @@ "dev": "node esbuild.config.mjs", "test": "vitest run", "test:watch": "vitest", - "typecheck": "tsc -noEmit" + "typecheck": "tsc -noEmit", + "arch": "depcruise src --config .dependency-cruiser.cjs" }, "dependencies": { "@jest/diff-sequences": "^30.5.0", @@ -25,8 +26,10 @@ }, "devDependencies": { "@codemirror/commands": "^6.8.1", + "@codemirror/search": "^6.7.2", "@types/node": "^22.20.1", "@types/qrcode": "^1.5.6", + "dependency-cruiser": "^18.7.0", "esbuild": "^0.25.12", "jsdom": "^30.1.2", "mdsync-relay": "workspace:*", @@ -34,6 +37,7 @@ }, "peerDependencies": { "@codemirror/commands": "^6.8.1", + "@codemirror/search": "^6.5.0", "@codemirror/state": "^6.5.0", "@codemirror/view": "^6.38.6" } diff --git a/packages/plugin/src/plugin/bootstrap.ts b/packages/plugin/src/app/bootstrap.ts similarity index 74% rename from packages/plugin/src/plugin/bootstrap.ts rename to packages/plugin/src/app/bootstrap.ts index 17fdbcce..2e8daa51 100644 --- a/packages/plugin/src/plugin/bootstrap.ts +++ b/packages/plugin/src/app/bootstrap.ts @@ -1,25 +1,31 @@ import type { App } from "obsidian"; - +import type { DeviceKey } from "@/core/crypto"; +import { LogService } from "@/core/logs"; +import type { MdsyncSettings } from "@/core/settings"; +import { reportWarning } from "@/core/shared"; +import { askPassphrase, notifyError, notifyInfo } from "@/core/ui"; +import type { SharedLinks } from "@/features/links"; +import { + createInertWarning, + createMoveFollower, + SpaceRecords, +} from "@/features/spaces"; +import { isStorageConfigured } from "@/features/storage"; +import type { LiveNotes } from "@/features/sync"; import { - createSessionOpeners, - LogService, + fetchRemoteManifest, PassphraseManager, + restoreCutShort, + type Space, StatePersister, -} from "@/core"; -import type { DeviceKey } from "@/crypto/device-key"; -import type { SharedLinks } from "@/links"; -import { isStorageConfigured, type MdsyncSettings } from "@/settings/model"; -import { reportWarning } from "@/shared"; -import { SpaceRecords } from "@/spaces"; -import { SyncController } from "@/sync/controller"; -import { restoreCutShort } from "@/sync/cut-short"; -import { WriteJournal } from "@/sync/journal"; -import type { LiveNotes } from "@/sync/live-notes"; -import { fetchRemoteManifest } from "@/sync/manifest"; -import { type Space, VAULT_SPACE } from "@/sync/space"; -import { askPassphrase, notifyError, notifyInfo } from "@/ui"; + SyncController, + VAULT_SPACE, + WriteJournal, +} from "@/features/sync"; +import { createSessionOpeners } from "./session-factory"; -import { createMoveFollower } from "./share-moves"; +const ACTIVITY_KEY = "mdsync-activity"; +const RESTORED_KEY = "mdsync-restored"; export interface PluginRuntime { controller: SyncController; @@ -30,7 +36,7 @@ export interface PluginRuntime { journal: WriteJournal; } -interface BootstrapPluginRuntimeOptions { +export interface BootstrapPluginRuntimeOptions { app: App; settings: MdsyncSettings; deviceKey: DeviceKey; @@ -43,6 +49,7 @@ interface BootstrapPluginRuntimeOptions { onStorageRefused?: (space: Space) => void; onSpaceGone?: (space: Space) => void; onUnindexed?: (count: number) => void; + onPluginsPulled?: () => void; onDeletionsHeld?: (space: Space, paths: readonly string[]) => void; onTheirsPulled?: (space: Space, paths: readonly string[]) => void; onNoStorage: () => void; @@ -132,6 +139,14 @@ export async function bootstrapPluginRuntime( }, openSession, openLocal, + activityStore: { + load: () => app.loadLocalStorage(ACTIVITY_KEY) as unknown, + save: (value) => app.saveLocalStorage(ACTIVITY_KEY, value), + }, + restoredStore: { + load: () => app.loadLocalStorage(RESTORED_KEY) as unknown, + save: (value) => app.saveLocalStorage(RESTORED_KEY, value), + }, persistState: (state) => statePersister.persist(state), getState: () => statePersister.state, logInfo: (op, msg, details) => logs.info(op, msg, details), @@ -143,6 +158,7 @@ export async function bootstrapPluginRuntime( onStorageRefused: options.onStorageRefused, onSpaceGone: options.onSpaceGone, onUnindexed: options.onUnindexed, + onPluginsPulled: options.onPluginsPulled, autoDeleteLimit: () => settings.confirmBulkDeletes ? settings.bulkDeleteLimit : null, onDeletionsHeld: options.onDeletionsHeld, @@ -158,26 +174,3 @@ export async function bootstrapPluginRuntime( journal, }; } - -/** For an onload that has to abandon what it built, see `MdsyncPlugin.onload`. */ -export function disposePluginRuntime(runtime: PluginRuntime): void { - runtime.statePersister.dispose(); - runtime.journal.dispose(); - runtime.controller.dispose(); - runtime.passphraseManager.dispose(); - runtime.logs.dispose(); -} - -/** Once per record and session: two devices shared one folder offline, and this one lost. */ -function createInertWarning(spaces: SpaceRecords): () => void { - const warned = new Set(); - return () => { - for (const { id, name, root } of spaces.inert()) { - if (warned.has(id)) continue; - warned.add(id); - notifyError( - `"${name}" is not syncing: another shared folder already holds "${root}". Stop sharing it in the Sync settings.`, - ); - } - }; -} diff --git a/packages/plugin/src/commands/index.ts b/packages/plugin/src/app/commands.ts similarity index 80% rename from packages/plugin/src/commands/index.ts rename to packages/plugin/src/app/commands.ts index a6b66eb3..914128e7 100644 --- a/packages/plugin/src/commands/index.ts +++ b/packages/plugin/src/app/commands.ts @@ -1,32 +1,54 @@ import { MarkdownView, type Plugin } from "obsidian"; - -import { SOURCE_CONTROL_VIEW_TYPE } from "@/constants"; -import { noteLinks, onRelay } from "@/links"; -import type { PluginHost } from "@/plugin/host"; -import { spaceOf } from "@/sync/space"; +import { SOURCE_CONTROL_VIEW_TYPE } from "@/core/constants"; +import { notifyInfo } from "@/core/ui"; +import { type ActiveMerge, DiffView, openDiffView } from "@/features/diff"; import { - canRebuild, - deepCleanOrphanedObjects, isLinkable, - notifyInfo, - openDiffView, - openInvite, + noteLinks, + onRelay, openManageLinks, openShareLink, - openShareWindow, + updateSharedLinks, +} from "@/features/links"; +import { + canRebuild, + rebuildLiveNote, + toggleAuthors, +} from "@/features/note-header"; +import { openSourceControlDeleted, openSourceControlHistory, openSourceControlView, - openStatusMenu, - rebuildLiveNote, +} from "@/features/source-control"; +import { openInvite, openShareWindow } from "@/features/spaces"; +import { openStatusMenu } from "@/features/status"; +import { + deepCleanOrphanedObjects, resetRemoteStorage, runCompare, runPullAll, runPushAll, - toggleAuthors, - updateSharedLinks, + spaceOf, verifyRemoteIntegrity, -} from "@/ui"; +} from "@/features/sync"; +import type { PluginHost } from "./host"; + +/** Shown only while the active view merges; the change is the one at the cursor. */ +const MERGE_COMMANDS: readonly [ + string, + string, + (merge: ActiveMerge) => void, +][] = [ + ["merge-take-local", "Take local in merge", (m) => m.take(["local"])], + ["merge-take-remote", "Take remote in merge", (m) => m.take(["remote"])], + [ + "merge-take-both", + "Take both in merge, local first", + (m) => m.take(["local", "remote"]), + ], + ["merge-next-conflict", "Go to next merge conflict", (m) => m.nextConflict()], + ["merge-save", "Save merge result", (m) => m.save()], +]; export function registerCommands( plugin: Plugin & PluginHost, @@ -206,6 +228,19 @@ export function registerCommands( callback: () => void openInvite(plugin), }); + for (const [id, name, run] of MERGE_COMMANDS) { + plugin.addCommand({ + id, + name, + checkCallback: (checking) => { + const merge = plugin.app.workspace.getActiveViewOfType(DiffView)?.merge; + if (!merge) return false; + if (!checking) run(merge); + return true; + }, + }); + } + plugin.addCommand({ id: "open-diff-active-file", name: "Open diff for active file", diff --git a/packages/plugin/src/app/events.ts b/packages/plugin/src/app/events.ts new file mode 100644 index 00000000..e3e83da6 --- /dev/null +++ b/packages/plugin/src/app/events.ts @@ -0,0 +1,64 @@ +import { type Plugin, TFile, TFolder } from "obsidian"; +import { reportWarning } from "@/core/shared"; +import { addLinkMenuItems } from "@/features/links"; +import { addHistoryMenuItems } from "@/features/source-control"; +import { addShareMenuItem } from "@/features/spaces"; +import type { StatePersister } from "@/features/sync"; +import { addIgnoreMenuItem, addPushMenuItem } from "@/features/sync"; +import type { PluginHost } from "./host"; + +/** The menus' order is the slices' order here. */ +export function registerWorkspaceMenus(plugin: Plugin & PluginHost): void { + plugin.registerEvent( + plugin.app.workspace.on("file-menu", (menu, file) => { + const folder = file instanceof TFolder; + addIgnoreMenuItem(menu, plugin, file.path, folder, "MDSync: "); + addPushMenuItem(menu, plugin, file.path, folder); + addLinkMenuItems(menu, plugin, file); + if (folder && !file.isRoot()) addShareMenuItem(menu, plugin, file.path); + addHistoryMenuItems( + menu, + plugin, + file instanceof TFile ? file.path : null, + ); + }), + ); + plugin.registerEvent( + plugin.app.workspace.on("editor-menu", (menu, _editor, view) => { + const path = view.file?.path ?? null; + if (path) addPushMenuItem(menu, plugin, path, false); + addHistoryMenuItems(menu, plugin, path); + }), + ); +} + +export function registerHashCarry( + plugin: Plugin, + statePersister: StatePersister, +): void { + plugin.registerEvent( + plugin.app.vault.on("rename", (file, oldPath) => + statePersister.carry({ + from: oldPath, + to: file.path, + folder: file instanceof TFolder, + }), + ), + ); +} + +export function registerStatePersistenceFlush( + plugin: Plugin & PluginHost, + statePersister: StatePersister, +): void { + const flush = (): void => { + statePersister + .flush() + .catch((err) => reportWarning("Could not save the sync state.", err)); + }; + + plugin.registerDomEvent(document, "visibilitychange", () => { + if (document.visibilityState === "hidden") flush(); + }); + plugin.registerDomEvent(window, "beforeunload", flush); +} diff --git a/packages/plugin/src/plugin/host.ts b/packages/plugin/src/app/host.ts similarity index 59% rename from packages/plugin/src/plugin/host.ts rename to packages/plugin/src/app/host.ts index 72a8109c..a6ed78da 100644 --- a/packages/plugin/src/plugin/host.ts +++ b/packages/plugin/src/app/host.ts @@ -1,18 +1,19 @@ import type { App } from "obsidian"; - -import type { DeviceName, LogService, PassphraseManager } from "@/core"; -import type { SharedLinks } from "@/links"; -import type { Unseen } from "@/presence"; -import type { MdsyncSettings } from "@/settings/model"; -import type { ESetupStep } from "@/settings/setup/steps"; -import type { SettingsTransferController } from "@/settings/transfer-controller"; -import type { SpaceRecords } from "@/spaces"; -import type { SyncController } from "@/sync/controller"; -import type { CursorFollow } from "@/ui"; - -import type { IgnoreStateHandle } from "./ignore-state"; +import type { LogService } from "@/core/logs"; +import type { MdsyncSettings } from "@/core/settings"; +import type { SharedLinks } from "@/features/links"; +import type { CursorFollow, Unseen } from "@/features/presence"; +import type { RelayUpdate } from "@/features/relay"; +import type { ESetupStep } from "@/features/setup"; +import type { SpaceRecords } from "@/features/spaces"; +import type { + DeviceName, + IgnoreStateHandle, + PassphraseManager, + SyncController, +} from "@/features/sync"; +import type { SettingsTransferController } from "@/features/transfer"; import type { Realtime } from "./realtime"; -import type { RelayUpdate } from "./relay-update"; /** * The plugin surface feature modules may use; Obsidian's registration API stays on the Plugin, so registering @@ -41,7 +42,11 @@ export interface PluginHost { resetLocalState(): Promise; refreshEditorSigns(enabled: boolean): void; refreshFileIndicators(enabled: boolean): void; - refreshSourceControlView(): void; + refreshSourceControlView(history?: boolean): void; /** The setup wizard, at `step` or where this device's setup stopped. */ openSetup(step?: ESetupStep): void; + openSourceControl(): Promise; + openChanges(): Promise; + /** The Timeline on the local day starting at `day`, else as it was left. */ + openTimeline(day?: number): Promise; } diff --git a/packages/plugin/src/app/protocols.ts b/packages/plugin/src/app/protocols.ts new file mode 100644 index 00000000..bc6a283b --- /dev/null +++ b/packages/plugin/src/app/protocols.ts @@ -0,0 +1,24 @@ +import type { Plugin } from "obsidian"; + +import { LINK_PARAM } from "@/core/crypto"; +import { INVITE_ACTION, openInvite } from "@/features/spaces"; +import { authorizeStorage } from "@/features/storage"; +import { TRANSFER_ACTION } from "@/features/transfer"; + +import type { PluginHost } from "./host"; + +/** obsidian:// entry points owned by the plugin itself. */ +export function registerProtocolHandlers( + plugin: Plugin & PluginHost, + onStorageAuthorized: () => void, +): void { + plugin.registerObsidianProtocolHandler(TRANSFER_ACTION, (params) => { + void plugin.transfer.handleProtocol(params); + }); + plugin.registerObsidianProtocolHandler("mdsync-auth", (params) => { + void authorizeStorage(plugin, params, onStorageAuthorized); + }); + plugin.registerObsidianProtocolHandler(INVITE_ACTION, (params) => { + void openInvite(plugin, params[LINK_PARAM] ?? ""); + }); +} diff --git a/packages/plugin/src/plugin/realtime.ts b/packages/plugin/src/app/realtime.ts similarity index 81% rename from packages/plugin/src/plugin/realtime.ts rename to packages/plugin/src/app/realtime.ts index 7aa47455..1ed6e94f 100644 --- a/packages/plugin/src/plugin/realtime.ts +++ b/packages/plugin/src/app/realtime.ts @@ -1,13 +1,11 @@ import { debounce } from "obsidian"; - -import { HubConnection } from "@/hub"; -import type { LiveSessions } from "@/live"; -import { People, watchHere } from "@/presence"; -import type { LiveNotes } from "@/sync/live-notes"; -import { type Space, VAULT_SPACE } from "@/sync/space"; - -import { createLive, type LiveHost } from "./live"; -import { createSpaceAccess } from "./space-access"; +import type { LiveSessions } from "@/features/live"; +import { createLive, type LiveHost } from "@/features/live"; +import { People, watchHere } from "@/features/presence"; +import { HubConnection } from "@/features/relay"; +import { createSpaceAccess, type SpaceAccessHost } from "@/features/spaces"; +import type { LiveNotes } from "@/features/sync"; +import { type Space, VAULT_SPACE } from "@/features/sync"; const REALTIME_SYNC_DEBOUNCE_MS = 2_000; /** How long an unload waits for the rooms' last edits before closing the sockets. */ @@ -24,7 +22,7 @@ export interface Realtime { } /** The hub sockets, who is where, live notes, and a pull when another device pushed into any space. */ -export function createRealtime(host: LiveHost): Realtime { +export function createRealtime(host: LiveHost & SpaceAccessHost): Realtime { const { controller, settings } = host; const hub = new HubConnection({ settings, diff --git a/packages/plugin/src/app/runtime-hooks.ts b/packages/plugin/src/app/runtime-hooks.ts new file mode 100644 index 00000000..d594d79b --- /dev/null +++ b/packages/plugin/src/app/runtime-hooks.ts @@ -0,0 +1,55 @@ +import type { Plugin } from "obsidian"; +import { notifyAction, notifyInfo } from "@/core/ui"; +import { markTheirs } from "@/features/presence"; +import { refreshHistoryAfterPush } from "@/features/source-control"; +import { + createAccessEnded, + createShareRegistration, + createSpaceGone, +} from "@/features/spaces"; +import type { BootstrapPluginRuntimeOptions } from "./bootstrap"; +import type { PluginHost } from "./host"; +import { createStorageRefused } from "./storage-refused"; + +export type RuntimeHooks = Omit< + BootstrapPluginRuntimeOptions, + "app" | "settings" | "deviceKey" | "links" +>; + +/** What the sync runtime tells the rest of the plugin; read at call time, as the host is complete only after bootstrap. */ +export function createRuntimeHooks(plugin: Plugin & PluginHost): RuntimeHooks { + const registerShare = createShareRegistration(plugin); + return { + onPushComplete: (space) => { + plugin.realtime.hub.signal(space.id); + refreshHistoryAfterPush(plugin); + }, + onSpaceRefreshed: (space) => void registerShare(space), + onShareRefused: createAccessEnded(plugin), + onStorageRefused: createStorageRefused(plugin), + onSpaceGone: createSpaceGone(plugin), + onUnindexed: (count) => + notifyInfo( + `Obsidian has not loaded ${count} files that are on disk. MDSync syncs them; restart Obsidian to see them.`, + ), + onPluginsPulled: () => + notifyInfo( + "Plugins changed on another device. Restart Obsidian to load them.", + ), + onDeletionsHeld: (space, paths) => + notifyAction( + `Auto-push held back ${paths.length} deleted files${space.root ? ` in "${space.root}"` : ""}. Review them before they sync.`, + "Review", + () => void plugin.openChanges(), + ), + onTheirsPulled: (space, paths) => + markTheirs(plugin, plugin.unseen, space, paths), + onNoStorage: () => + notifyAction("Set up storage to sync.", "Set up", () => + plugin.openSetup(), + ), + persistSettings: () => plugin.saveSettings(), + // The first refresh can precede the realtime coordinator. + liveNotes: (space) => plugin.realtime?.liveNotes(space), + }; +} diff --git a/packages/plugin/src/app/scope-refresh.ts b/packages/plugin/src/app/scope-refresh.ts new file mode 100644 index 00000000..c9c93eca --- /dev/null +++ b/packages/plugin/src/app/scope-refresh.ts @@ -0,0 +1,44 @@ +import type { MdsyncSettings } from "@/core/settings"; +import { canSync, type SyncController } from "@/features/sync"; + +const SCOPE_REFRESH_DEBOUNCE_MS = 800; + +export interface ScopeRefresh { + schedule(reason?: string): void; + cancel(): void; +} + +/** A scope change drops the comparison at once and compares again once the changes settle. */ +export function createScopeRefresh( + controller: () => SyncController, + settings: () => MdsyncSettings, +): ScopeRefresh { + let timer: number | null = null; + const cancel = (): void => { + if (timer === null) return; + window.clearTimeout(timer); + timer = null; + }; + return { + cancel, + schedule(reason = "Sync scope changed.") { + const sync = controller(); + const snapshot = sync.getSnapshot(); + // A first refresh still running read the old scope: drop it too. + if ( + !snapshot.result && + snapshot.lastCompareAt === null && + !snapshot.busy + ) { + return; + } + sync.invalidate(reason); + if (!canSync(settings())) return; + cancel(); + timer = window.setTimeout(() => { + timer = null; + void sync.refresh(); + }, SCOPE_REFRESH_DEBOUNCE_MS); + }, + }; +} diff --git a/packages/plugin/src/core/session-factory.ts b/packages/plugin/src/app/session-factory.ts similarity index 74% rename from packages/plugin/src/core/session-factory.ts rename to packages/plugin/src/app/session-factory.ts index a618fdf9..aa565bbe 100644 --- a/packages/plugin/src/core/session-factory.ts +++ b/packages/plugin/src/app/session-factory.ts @@ -1,38 +1,48 @@ import { type App, TFile } from "obsidian"; -import type { EncryptionKey } from "@/crypto"; -import { ESyncLogOperation } from "@/logs/store"; +import { HISTORY_KEEP_MS } from "@/core/constants"; +import type { EncryptionKey } from "@/core/crypto"; +import type { LogService } from "@/core/logs"; +import { ESyncLogOperation } from "@/core/logs"; +import type { MdsyncSettings } from "@/core/settings"; +import { reportWarning } from "@/core/shared"; +import { createSymlinkDetector, createVaultIndex } from "@/core/vault"; +import type { SpaceRecords } from "@/features/spaces"; +import { + pauseOf, + shareChunkIds, + shareIdentity, + shareKey, + shareStorage, +} from "@/features/spaces"; import { activeStorage, - isGuest, + createStorageAdapter, isStorageConfigured, - type MdsyncSettings, -} from "@/settings/model"; -import { reportWarning } from "@/shared"; -import type { SpaceRecords } from "@/spaces"; -import { pauseOf } from "@/spaces"; -import { shareKey, shareStorage } from "@/spaces/access"; -import { shareIdentity } from "@/spaces/record"; -import { createStorageAdapter, type StorageAdapter } from "@/storage"; -import { clearRemoteTextCache } from "@/sync/content"; -import type { EngineDependencies } from "@/sync/engine"; -import type { WriteJournal } from "@/sync/journal"; -import { PassphraseRotatedError } from "@/sync/keyfile"; -import type { LiveNotes } from "@/sync/live-notes"; -import { projectSession } from "@/sync/session-state"; -import { nestedRoots, type Space, VAULT_SPACE } from "@/sync/space"; -import type { ManifestAuthor } from "@/sync/types"; -import { createVaultIndex } from "@/vault/file-index"; + type StorageAdapter, +} from "@/features/storage"; +import type { + EngineDependencies, + LiveNotes, + LocalOpener, + ManifestAuthor, + PassphraseManager, + SessionFiles, + StatePersister, + WriteJournal, +} from "@/features/sync"; import { + clearRemoteTextCache, createIgnoreMatcher, + createScopePolicy, type IgnoreMatcher, ignoreNoteOf, + isGuest, loadSharedIgnoreMatcher, -} from "@/vault/ignore"; -import { createScopePolicy } from "@/vault/scope"; -import { createSymlinkDetector } from "@/vault/symlinks"; -import type { LogService } from "./log-service"; -import type { PassphraseManager } from "./passphrase-manager"; -import type { StatePersister } from "./state-persister"; + nestedRoots, + projectSession, + type Space, + VAULT_SPACE, +} from "@/features/sync"; export interface SessionFactoryDeps { app: App; @@ -56,22 +66,6 @@ export type SessionOpener = ( partition: readonly Space[], ) => Promise; -type SessionFiles = Pick< - EngineDependencies, - "space" | "adapter" | "scope" | "state" | "maxFileBytes" ->; - -/** What a display-only look at one space's files needs: no storage, no key. */ -export type LocalSession = SessionFiles & { - /** The storage `state` belongs to. */ - identity: string; -}; - -export type LocalOpener = ( - space: Space, - partition: readonly Space[], -) => Promise; - /** One adapter and scope cache for both: a local look reuses the session's adapter. */ export function createSessionOpeners(deps: SessionFactoryDeps): { openSession: SessionOpener; @@ -104,9 +98,10 @@ function sessionOpener( storage: opened.storage, index: createVaultIndex(app.vault), key: opened.key, + chunkIds: opened.chunkIds, concurrency: opened.concurrency, history: settings.fileHistoryEnabled - ? { maxSnapshots: settings.fileHistoryMaxSnapshots } + ? { horizon: HISTORY_KEEP_MS[settings.fileHistoryKeep] } : undefined, live: deps.liveNotes?.(space), author: opened.author, @@ -160,6 +155,8 @@ async function sessionFiles( adapter, scope: createScopePolicy({ settingsSync: settings.settingsSync, + pluginLevel: settings.pluginLevel, + pluginLevels: settings.pluginLevels, configDir: app.vault.configDir, sharedIgnore, localIgnore, @@ -175,6 +172,7 @@ async function sessionFiles( interface OpenedStorage { storage: StorageAdapter; key: EncryptionKey; + chunkIds?: CryptoKey; concurrency: number; /** Unset in the vault, which publishes as the device. */ author?: ManifestAuthor; @@ -232,10 +230,17 @@ async function openVault( return null; } const storage = vaultStorage(deps, getStorage); - const key = await resolveKeyWithRotationRetry(deps, storage); - return key - ? { storage, key, concurrency: activeStorage(deps.settings).concurrency } - : null; + const key = await deps.passphrase.resolveKeyRecovering(storage, { + warn: (message) => deps.logs.warn(ESyncLogOperation.Session, message), + notify: deps.notify, + }); + if (!key) return null; + return { + storage, + key, + chunkIds: deps.passphrase.chunkIds() ?? undefined, + concurrency: activeStorage(deps.settings).concurrency, + }; } function vaultStorage( @@ -278,6 +283,7 @@ async function openShare( return { storage: getStorage(space.id, storage.memo, storage.create), key: await shareKey(record), + chunkIds: await shareChunkIds(record), concurrency: storage.concurrency, author: { key: person, name }, }; @@ -329,34 +335,3 @@ function createScopeMatchers( return matchers; }; } - -/** Recovers from a passphrase rotated on another device: forget it, re-prompt once, retry; a second failure aborts. */ -async function resolveKeyWithRotationRetry( - deps: SessionFactoryDeps, - storage: StorageAdapter, -): Promise { - const { passphrase, logs, notify } = deps; - try { - return await passphrase.resolveKey(storage); - } catch (err) { - if (!(err instanceof PassphraseRotatedError)) throw err; - await logs.warn( - ESyncLogOperation.Session, - "Passphrase no longer matches the remote (rotated elsewhere); re-prompting.", - ); - notify("Passphrase changed on another device. Enter the new one."); - await passphrase.forget(); - if (!(await passphrase.prompt(true))) return null; - try { - return await passphrase.resolveKey(storage); - } catch (retryErr) { - if (!(retryErr instanceof PassphraseRotatedError)) throw retryErr; - await logs.warn( - ESyncLogOperation.Session, - "Session blocked: passphrase still does not match after re-prompt.", - ); - notify("Passphrase still incorrect."); - return null; - } - } -} diff --git a/packages/plugin/src/settings/envelope.ts b/packages/plugin/src/app/settings/envelope.ts similarity index 91% rename from packages/plugin/src/settings/envelope.ts rename to packages/plugin/src/app/settings/envelope.ts index 11cf263b..0d211a3c 100644 --- a/packages/plugin/src/settings/envelope.ts +++ b/packages/plugin/src/app/settings/envelope.ts @@ -1,8 +1,8 @@ -import { decryptJson, encryptJson } from "@/crypto"; -import type { DeviceKey } from "@/crypto/device-key"; -import { base64ToBytes, bytesToBase64 } from "@/utils"; - -import { type MdsyncSettings, mergeSettings } from "./model"; +import type { DeviceKey } from "@/core/crypto"; +import { decryptJson, encryptJson } from "@/core/crypto"; +import type { MdsyncSettings } from "@/core/settings"; +import { base64ToBytes, bytesToBase64 } from "@/core/utils"; +import { mergeSettings } from "./index"; /** The secrets, and the share state that means nothing without them: kept or lost as one. */ const SEALED = [ diff --git a/packages/plugin/src/app/settings/index.ts b/packages/plugin/src/app/settings/index.ts new file mode 100644 index 00000000..722fb2cc --- /dev/null +++ b/packages/plugin/src/app/settings/index.ts @@ -0,0 +1,18 @@ +import { type MdsyncSettings, mergeCoreSettings } from "@/core/settings"; +import { parseStoredLinks } from "@/features/links"; +import { parseSpaceRecords } from "@/features/spaces"; +import { parseStorageSettings } from "@/features/storage"; + +/** Each slice parses the fields it declares over the core ones. */ +export function mergeSettings( + stored: Partial | null | undefined, +): MdsyncSettings { + return { + ...mergeCoreSettings(stored), + ...parseStorageSettings(stored), + spaces: parseSpaceRecords(stored?.spaces), + links: parseStoredLinks(stored?.links), + }; +} + +export const DEFAULT_SETTINGS: MdsyncSettings = mergeSettings(null); diff --git a/packages/plugin/src/app/settings/store.ts b/packages/plugin/src/app/settings/store.ts new file mode 100644 index 00000000..b4b881e3 --- /dev/null +++ b/packages/plugin/src/app/settings/store.ts @@ -0,0 +1,58 @@ +import type { Plugin } from "obsidian"; +import type { DeviceKey } from "@/core/crypto"; +import type { MdsyncSettings } from "@/core/settings"; +import { SettingsEnvelope } from "./envelope"; +import { mergeSettings } from "./index"; + +/** + * Where a new install starts beyond the defaults. Not the defaults themselves: a setup link leaves + * default values out, so a changed default would flip the setting for links made before. + */ +const FRESH_INSTALL: Partial = { fileHistoryEnabled: true }; + +/** `data.json` through the envelope, one write at a time. */ +export class SettingsStore { + private readonly envelope: SettingsEnvelope; + /** Two writes in flight may land the older one last. */ + private saving: Promise = Promise.resolve(); + private fresh = false; + + constructor( + private readonly plugin: Pick, + deviceKey: DeviceKey, + ) { + this.envelope = new SettingsEnvelope(deviceKey); + } + + /** Set by {@link load}: there was no `data.json` yet. */ + get freshInstall(): boolean { + return this.fresh; + } + + unreadable(): boolean { + return this.envelope.unreadable(); + } + + async load(): Promise { + const data = (await this.plugin.loadData()) as Record< + string, + unknown + > | null; + this.fresh = data === null; + const { stored, inTheClear } = await this.envelope.open(data); + const settings = mergeSettings( + this.fresh ? { ...stored, ...FRESH_INSTALL } : stored, + ); + // Sealed now, not at the next change: the secrets of an earlier build must not linger in the clear. + if (inTheClear) await this.write(settings); + return settings; + } + + write(settings: MdsyncSettings): Promise { + const save = this.saving.then(async () => + this.plugin.saveData(await this.envelope.seal(settings)), + ); + this.saving = save.catch(() => undefined); + return save; + } +} diff --git a/packages/plugin/src/app/storage-refused.ts b/packages/plugin/src/app/storage-refused.ts new file mode 100644 index 00000000..49721f1c --- /dev/null +++ b/packages/plugin/src/app/storage-refused.ts @@ -0,0 +1,16 @@ +import { createStorageRefusedPrompt } from "@/features/storage"; +import { type Space, VAULT_SPACE } from "@/features/sync"; +import type { PluginHost } from "./host"; + +/** The vault and owned shares reach the storage with this device's keys; a participant's are the owner's to fix. */ +export function createStorageRefused( + plugin: PluginHost, +): (space: Space) => void { + const ask = createStorageRefusedPrompt(plugin); + return (space) => { + const own = + space.root === VAULT_SPACE.root || + plugin.spaces.get(space.id)?.access.kind === "owner"; + if (own) ask(); + }; +} diff --git a/packages/plugin/src/plugin/ui.ts b/packages/plugin/src/app/views.ts similarity index 65% rename from packages/plugin/src/plugin/ui.ts rename to packages/plugin/src/app/views.ts index fa4392c5..ea68fdae 100644 --- a/packages/plugin/src/plugin/ui.ts +++ b/packages/plugin/src/app/views.ts @@ -1,20 +1,21 @@ import { Platform, type Plugin } from "obsidian"; -import { DIFF_VIEW_TYPE, SOURCE_CONTROL_VIEW_TYPE } from "@/constants"; -import type { PluginHost } from "@/plugin/host"; -import { MdsyncSettingTab } from "@/settings/tab"; -import type { SyncController } from "@/sync/controller"; +import { DIFF_VIEW_TYPE, SOURCE_CONTROL_VIEW_TYPE } from "@/core/constants"; +import { DiffView } from "@/features/diff"; import { - DiffView, type IndicatorHandle, - keepInRightSidebar, registerFileContextIndicators, registerFileExplorerIndicators, - registerNoteLinkActions, - registerNotePresence, - registerRibbon, - registerStatusBar, +} from "@/features/explorer"; +import { registerNoteLinkActions } from "@/features/links"; +import { registerNotePresence } from "@/features/note-header"; +import { MdsyncSettingTab } from "@/features/settings"; +import { + keepInRightSidebar, SourceControlView, -} from "@/ui"; +} from "@/features/source-control"; +import { registerRibbon, registerStatusBar } from "@/features/status"; +import type { SyncController } from "@/features/sync"; +import type { PluginHost } from "./host"; interface RegisteredPluginUi { settingsTab: MdsyncSettingTab; @@ -63,28 +64,3 @@ export function registerPluginUi( return { settingsTab, fileIndicators, openNoteMenu, refreshStatusBar }; } - -export function refreshOpenHistoryViewsAfterPush( - plugin: Plugin & PluginHost, -): void { - if (!plugin.settings.historyAutoRefresh) return; - for (const leaf of plugin.app.workspace.getLeavesOfType( - SOURCE_CONTROL_VIEW_TYPE, - )) { - if (leaf.view instanceof SourceControlView) { - leaf.view.refreshHistory(); - } - } -} - -export function refreshOpenSourceControlViews( - plugin: Plugin & PluginHost, -): void { - for (const leaf of plugin.app.workspace.getLeavesOfType( - SOURCE_CONTROL_VIEW_TYPE, - )) { - if (leaf.view instanceof SourceControlView) { - leaf.view.refreshDisplaySettings(); - } - } -} diff --git a/packages/plugin/src/cloudflare/index.ts b/packages/plugin/src/cloudflare/index.ts deleted file mode 100644 index 0a979780..00000000 --- a/packages/plugin/src/cloudflare/index.ts +++ /dev/null @@ -1,43 +0,0 @@ -export { - type CloudflareApi, - cloudflareApi, - type Http, - type HttpRequest, - hasCode, - isRefusedToken, -} from "./api"; -export type { RelayBundle } from "./bundle"; -export { - ensureBucket, - R2NotEnabledError, - type R2Storage, - r2AccountOf, - r2DashboardUrl, - r2Keys, - r2Storage, -} from "./r2"; -export { - type AccountRelays, - accountRelays, - freeRelayName, - ownRelayName, - RELAY_NAME, - RELAY_VERSION, - type RelayTarget, - relayBehind, - relayNameError, - relayUrlOf, -} from "./relay-account"; -export { - deployRelay, - ERelayDeployStep, - workerNames, - workersSubdomain, - workerUrl, -} from "./relay-deploy"; -export { - type CloudflareAccount, - listAccounts, - tokenTemplateUrl, - verifyToken, -} from "./token"; diff --git a/packages/plugin/src/core/chunking/fastcdc.ts b/packages/plugin/src/core/chunking/fastcdc.ts new file mode 100644 index 00000000..5a371a79 --- /dev/null +++ b/packages/plugin/src/core/chunking/fastcdc.ts @@ -0,0 +1,74 @@ +/** Chunk sizes in bytes: no chunk below `min` (but the last) or above `max`, `avg` a power of two. */ +export interface ChunkParams { + min: number; + avg: number; + max: number; +} + +/** Bits the cut masks move off the average: FastCDC's normalization level 2. */ +const NORMALIZATION = 2; + +/** + * Where FastCDC cuts `bytes`: the end offset of every chunk, the last at `bytes.length`. An edit moves only + * the cuts near it, so the chunks around it keep their content and dedup. + */ +export function chunkEnds( + bytes: Uint8Array, + params: ChunkParams, + gear: Uint32Array, +): number[] { + const bits = Math.log2(params.avg); + // Top bits: a left-shifted gear hash mixes the last 32 bytes only there. + const strict = topBits(bits + NORMALIZATION); + const loose = topBits(bits - NORMALIZATION); + const ends: number[] = []; + let start = 0; + while (start < bytes.length) { + start = cutAfter(bytes, start, params, strict, loose, gear); + ends.push(start); + } + return ends; +} + +/** 256 words drawn from `seed`: the same seed cuts the same content at the same places. */ +export function gearTable(seed: number): Uint32Array { + const gear = new Uint32Array(256); + let state = seed >>> 0; + for (let index = 0; index < gear.length; index++) { + // mulberry32 + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + gear[index] = (t ^ (t >>> 14)) >>> 0; + } + return gear; +} + +function cutAfter( + bytes: Uint8Array, + start: number, + { min, avg, max }: ChunkParams, + strict: number, + loose: number, + gear: Uint32Array, +): number { + const end = Math.min(start + max, bytes.length); + if (end - start <= min) return end; + const normal = Math.min(start + avg, end); + let hash = 0; + let at = start + min; + // A harder mask before the average and an easier one after it keep sizes close to `avg`. + for (; at < normal; at++) { + hash = ((hash << 1) + (gear[bytes[at] as number] as number)) >>> 0; + if ((hash & strict) === 0) return at + 1; + } + for (; at < end; at++) { + hash = ((hash << 1) + (gear[bytes[at] as number] as number)) >>> 0; + if ((hash & loose) === 0) return at + 1; + } + return end; +} + +function topBits(count: number): number { + return (0xffffffff << (32 - count)) >>> 0; +} diff --git a/packages/plugin/src/core/chunking/index.ts b/packages/plugin/src/core/chunking/index.ts new file mode 100644 index 00000000..edb38693 --- /dev/null +++ b/packages/plugin/src/core/chunking/index.ts @@ -0,0 +1 @@ +export { type ChunkParams, chunkEnds, gearTable } from "./fastcdc"; diff --git a/packages/plugin/src/cloudflare/api.ts b/packages/plugin/src/core/cloudflare/api.ts similarity index 100% rename from packages/plugin/src/cloudflare/api.ts rename to packages/plugin/src/core/cloudflare/api.ts diff --git a/packages/plugin/src/core/cloudflare/index.ts b/packages/plugin/src/core/cloudflare/index.ts new file mode 100644 index 00000000..41ffb7d9 --- /dev/null +++ b/packages/plugin/src/core/cloudflare/index.ts @@ -0,0 +1,14 @@ +export { + type CloudflareApi, + cloudflareApi, + hasCode, + isRefusedToken, +} from "./api"; +export { encodeForm } from "./multipart"; +export { obsidianHttp } from "./obsidian-http"; +export { + type CloudflareAccount, + listAccounts, + tokenTemplateUrl, + verifyToken, +} from "./token"; diff --git a/packages/plugin/src/cloudflare/multipart.ts b/packages/plugin/src/core/cloudflare/multipart.ts similarity index 100% rename from packages/plugin/src/cloudflare/multipart.ts rename to packages/plugin/src/core/cloudflare/multipart.ts diff --git a/packages/plugin/src/cloudflare/obsidian-http.ts b/packages/plugin/src/core/cloudflare/obsidian-http.ts similarity index 100% rename from packages/plugin/src/cloudflare/obsidian-http.ts rename to packages/plugin/src/core/cloudflare/obsidian-http.ts diff --git a/packages/plugin/src/cloudflare/token.ts b/packages/plugin/src/core/cloudflare/token.ts similarity index 100% rename from packages/plugin/src/cloudflare/token.ts rename to packages/plugin/src/core/cloudflare/token.ts diff --git a/packages/plugin/src/constants.ts b/packages/plugin/src/core/constants.ts similarity index 52% rename from packages/plugin/src/constants.ts rename to packages/plugin/src/core/constants.ts index 0bf24fef..b3827edd 100644 --- a/packages/plugin/src/constants.ts +++ b/packages/plugin/src/core/constants.ts @@ -1,5 +1,8 @@ export const PLUGIN_ID = "mdsync"; +/** The vault storage's head: sync publishes it, storage probes it to tell an empty remote from a vault. */ +export const REMOTE_MANIFEST_KEY = "manifest.json.enc"; + export const IGNORE_FILE_NAME = "syncignore.md"; export const DEFAULT_CONCURRENCY = 4; @@ -12,13 +15,33 @@ export const AUTO_PUSH_SETTLE_MIN_SECONDS = 3; export const AUTO_PUSH_SETTLE_MAX_SECONDS = 60; +export const SLOW_FILE_SETTLE_MIN_SECONDS = 10; + +export const SLOW_FILE_SETTLE_MAX_SECONDS = 300; + export const BULK_DELETE_LIMIT_MIN = 0; export const BULK_DELETE_LIMIT_MAX = 1000; -export const FILE_HISTORY_MIN_SNAPSHOTS = 1; +const DAY_MS = 24 * 60 * 60_000; + +/** **Keep history for**: past it only activity counts remain; `null` keeps every version tier forever. */ +export const HISTORY_KEEP_MS = { + week: 7 * DAY_MS, + month: 30 * DAY_MS, + quarter: 91 * DAY_MS, + year: 365 * DAY_MS, + forever: null, +} as const; -export const FILE_HISTORY_MAX_SNAPSHOTS = 1000; +/** How **Keep history for** names each choice; the Deleted tab says it too. */ +export const HISTORY_KEEP_TEXT = { + week: "1 week", + month: "1 month", + quarter: "3 months", + year: "1 year", + forever: "Forever", +} as const satisfies Record; export const SOURCE_CONTROL_VIEW_TYPE = "mdsync-source-control"; diff --git a/packages/plugin/src/core/crypto/chunk-ids.ts b/packages/plugin/src/core/crypto/chunk-ids.ts new file mode 100644 index 00000000..cfe43143 --- /dev/null +++ b/packages/plugin/src/core/crypto/chunk-ids.ts @@ -0,0 +1,27 @@ +import { toHex } from "@mdsync/protocol"; +import { deriveFromDataKey } from "./hkdf"; + +const CHUNK_IDS_INFO = "mdsync/chunks/ids/v1"; + +/** HMAC-SHA-256 naming chunks, so the storage never learns their plain hashes. */ +export function deriveChunkIds(dataKey: Uint8Array): Promise { + return deriveFromDataKey( + dataKey, + CHUNK_IDS_INFO, + { name: "HMAC", hash: "SHA-256", length: 256 }, + ["sign"], + ); +} + +/** Equal bytes get one name under one data key, so versions of a file share their unchanged chunks. */ +export async function chunkId( + key: CryptoKey, + bytes: Uint8Array, +): Promise { + const mac = await window.crypto.subtle.sign( + "HMAC", + key, + bytes as BufferSource, + ); + return toHex(mac); +} diff --git a/packages/plugin/src/crypto/index.ts b/packages/plugin/src/core/crypto/cipher.ts similarity index 56% rename from packages/plugin/src/crypto/index.ts rename to packages/plugin/src/core/crypto/cipher.ts index 4d28f245..acfa1526 100644 --- a/packages/plugin/src/crypto/index.ts +++ b/packages/plugin/src/core/crypto/cipher.ts @@ -1,16 +1,25 @@ import { toHex } from "@mdsync/protocol"; +import { + bytesToBase64Url, + deflateBytes, + GZIP, + inflateBytes, +} from "@/core/utils"; import { BLOB_VERSION, + BLOB_VERSION_DESCRIBED, BLOB_VERSION_GZIP, + DESCRIBED_HEADER_BYTES, GZIP_LENGTH_BYTES, GZIP_PAD_BYTES, + GZIP_SAMPLE_BYTES, + GZIP_SAMPLE_MAX_RATIO, IV_BYTES, JSON_GZIP_MIN_BYTES, KDF_ITERATIONS, KDF_SALT_LABEL, MIN_PASSPHRASE_LENGTH, -} from "@/crypto/constants"; -import { bytesToBase64Url, deflateBytes, GZIP, inflateBytes } from "@/utils"; +} from "./constants"; const subtle = window.crypto.subtle; const encoder = new TextEncoder(); @@ -112,18 +121,29 @@ function versionAad(version: number): Uint8Array | undefined { export async function decryptBytes( key: EncryptionKey, blob: Uint8Array, +): Promise { + const plaintext = await open(key, blob, [BLOB_VERSION, BLOB_VERSION_GZIP]); + if (blob[0] !== BLOB_VERSION_GZIP) return plaintext; + return inflatePadded(plaintext); +} + +/** The authenticated plaintext of a blob whose version is one of `versions`. */ +async function open( + key: EncryptionKey, + blob: Uint8Array, + versions: readonly number[], ): Promise { if (blob.length < 1 + IV_BYTES + 16) { throw new Error("Encrypted blob is too short"); } - const version = blob[0]; - if (version !== BLOB_VERSION && version !== BLOB_VERSION_GZIP) { + const version = blob[0] ?? 0; + if (!versions.includes(version)) { throw new Error(`Unsupported blob version: ${version}`); } const iv = blob.subarray(1, 1 + IV_BYTES); const ciphertext = blob.subarray(1 + IV_BYTES); const aad = versionAad(version); - const plaintext = new Uint8Array( + return new Uint8Array( await subtle.decrypt( { name: "AES-GCM", @@ -134,19 +154,26 @@ export async function decryptBytes( toBufferSource(ciphertext), ), ); - if (version !== BLOB_VERSION_GZIP) return plaintext; +} + +async function inflatePadded(padded: Uint8Array): Promise { if (typeof DecompressionStream !== "function") { throw new Error( "This remote is compressed and this device cannot decompress it. Update Obsidian, or sync this vault from another device.", ); } - return inflateBytes(unpad(plaintext), GZIP); + return inflateBytes(unpad(padded), GZIP); +} + +function paddedLength(gzipLength: number): number { + return ( + Math.ceil((GZIP_LENGTH_BYTES + gzipLength) / GZIP_PAD_BYTES) * + GZIP_PAD_BYTES + ); } function pad(gzipped: Uint8Array): Uint8Array { - const framed = GZIP_LENGTH_BYTES + gzipped.length; - const size = Math.ceil(framed / GZIP_PAD_BYTES) * GZIP_PAD_BYTES; - const out = new Uint8Array(size); + const out = new Uint8Array(paddedLength(gzipped.length)); new DataView(out.buffer).setUint32(0, gzipped.length, true); out.set(gzipped, GZIP_LENGTH_BYTES); return out; @@ -170,30 +197,115 @@ export async function encryptJson( key: EncryptionKey, value: unknown, ): Promise { - const json = encoder.encode(JSON.stringify(value)); - const gzipped = await gzipJson(json); - if (!gzipped) return encryptBytes(key, json); + return sealSmallest( + key, + encoder.encode(JSON.stringify(value)), + JSON_GZIP_MIN_BYTES, + ); +} + +/** File content: gzipped when that makes the blob smaller. Every release since 1.0.0 reads both. */ +export async function encryptCompressible( + key: EncryptionKey, + bytes: Uint8Array, +): Promise { + // Below one pad unit the sealed blob cannot shrink. + return sealSmallest(key, bytes, GZIP_PAD_BYTES); +} + +async function sealSmallest( + key: EncryptionKey, + plaintext: Uint8Array, + minBytes: number, +): Promise { + const gzipped = await gzipIfSmaller(plaintext, minBytes); + if (!gzipped) return encryptBytes(key, plaintext); return sealBytes(key, pad(gzipped), BLOB_VERSION_GZIP); } /** - * Null keeps the document at {@link BLOB_VERSION}, so a device without CompressionStream still writes a + * Null keeps the blob at {@link BLOB_VERSION}, so a device without CompressionStream still writes a * remote its peers can read. */ -async function gzipJson(json: Uint8Array): Promise { - if (json.length < JSON_GZIP_MIN_BYTES) return null; +async function gzipIfSmaller( + bytes: Uint8Array, + minBytes: number, +): Promise { + if (bytes.length < minBytes) return null; try { - const out = await deflateBytes(json, GZIP); + if (!(await compressible(bytes))) return null; + const out = await deflateBytes(bytes, GZIP); if (!out) return null; - const framed = - Math.ceil((GZIP_LENGTH_BYTES + out.length) / GZIP_PAD_BYTES) * - GZIP_PAD_BYTES; - return framed < json.length ? out : null; + return paddedLength(out.length) < bytes.length ? out : null; } catch { return null; } } +/** A sample decides for large inputs, so media and archives are not compressed whole for nothing. */ +async function compressible(bytes: Uint8Array): Promise { + if (bytes.length <= GZIP_SAMPLE_BYTES) return true; + const sample = await deflateBytes(bytes.subarray(0, GZIP_SAMPLE_BYTES), GZIP); + return ( + sample !== null && sample.length < GZIP_SAMPLE_BYTES * GZIP_SAMPLE_MAX_RATIO + ); +} + +export function isDescribed(blob: Uint8Array): boolean { + return blob[0] === BLOB_VERSION_DESCRIBED; +} + +/** + * File content with a JSON `header` describing how `payload` maps to it. Always gzipped (a build without + * CompressionStream throws, so the caller stores the plain form), padded like {@link BLOB_VERSION_GZIP}. + */ +export async function encryptDescribed( + key: EncryptionKey, + header: object, + payload: Uint8Array, +): Promise { + const head = encoder.encode(JSON.stringify(header)); + const plaintext = new Uint8Array( + DESCRIBED_HEADER_BYTES + head.length + payload.length, + ); + new DataView(plaintext.buffer).setUint32(0, head.length, true); + plaintext.set(head, DESCRIBED_HEADER_BYTES); + plaintext.set(payload, DESCRIBED_HEADER_BYTES + head.length); + const gzipped = await deflateBytes(plaintext, GZIP); + if (!gzipped) { + throw new Error( + "This device cannot compress, so it cannot seal a described blob", + ); + } + return sealBytes(key, pad(gzipped), BLOB_VERSION_DESCRIBED); +} + +/** The header is unchecked: the caller validates its shape. */ +export async function decryptDescribed( + key: EncryptionKey, + blob: Uint8Array, +): Promise<{ header: unknown; payload: Uint8Array }> { + const plaintext = await inflatePadded( + await open(key, blob, [BLOB_VERSION_DESCRIBED]), + ); + if (plaintext.length < DESCRIBED_HEADER_BYTES) { + throw new Error("Described blob is too short"); + } + const length = new DataView( + plaintext.buffer, + plaintext.byteOffset, + plaintext.byteLength, + ).getUint32(0, true); + const end = DESCRIBED_HEADER_BYTES + length; + if (end > plaintext.length) throw new Error("Described blob is truncated"); + return { + header: JSON.parse( + decoder.decode(plaintext.subarray(DESCRIBED_HEADER_BYTES, end)), + ), + payload: plaintext.subarray(end), + }; +} + export async function decryptJson( key: EncryptionKey, blob: Uint8Array, diff --git a/packages/plugin/src/crypto/constants.ts b/packages/plugin/src/core/crypto/constants.ts similarity index 66% rename from packages/plugin/src/crypto/constants.ts rename to packages/plugin/src/core/crypto/constants.ts index f992bff5..714e6f8a 100644 --- a/packages/plugin/src/crypto/constants.ts +++ b/packages/plugin/src/core/crypto/constants.ts @@ -11,6 +11,15 @@ export const BLOB_VERSION = 0x01; /** Same envelope, plaintext gzipped; an older build rejects it by version instead of failing in JSON.parse. */ export const BLOB_VERSION_GZIP = 0x02; +/** + * Gzip-sealed like 0x02, its plaintext a length-prefixed JSON header and then a payload. The one blob that + * `decryptBytes` refuses: it is file content only, never JSON, a key or a link. + */ +export const BLOB_VERSION_DESCRIBED = 0x03; + +/** uint32 little-endian length of the header JSON, ahead of it in a described plaintext. */ +export const DESCRIBED_HEADER_BYTES = 4; + /** * Below this gzip framing costs more than it saves and any build can read the document (a 20k-file manifest * gzips 3.4 MB to 1.0 MB). @@ -23,6 +32,11 @@ export const JSON_GZIP_MIN_BYTES = 16 * 1024; */ export const GZIP_PAD_BYTES = 4 * 1024; +/** Larger inputs are compressed only when this much of their start shrinks below the ratio. */ +export const GZIP_SAMPLE_BYTES = 64 * 1024; + +export const GZIP_SAMPLE_MAX_RATIO = 0.9; + /** uint32 little-endian gzip length, ahead of the padding. */ export const GZIP_LENGTH_BYTES = 4; diff --git a/packages/plugin/src/crypto/device-key.ts b/packages/plugin/src/core/crypto/device-key.ts similarity index 91% rename from packages/plugin/src/crypto/device-key.ts rename to packages/plugin/src/core/crypto/device-key.ts index 6aea40ca..c363a9ff 100644 --- a/packages/plugin/src/crypto/device-key.ts +++ b/packages/plugin/src/core/crypto/device-key.ts @@ -1,12 +1,11 @@ import type { DataAdapter, SecretStorage } from "obsidian"; -import { PLUGIN_ID } from "@/constants"; -import { reportWarning } from "@/shared"; -import { base64ToBytes, bytesToBase64 } from "@/utils"; -import { deletePath, readBinary } from "@/vault/io"; - +import { PLUGIN_ID } from "@/core/constants"; +import { reportWarning } from "@/core/shared"; +import { base64ToBytes, bytesToBase64 } from "@/core/utils"; +import { deletePath, readBinary } from "@/core/vault"; +import { type EncryptionKey, importAesKey, randomBytes } from "./cipher"; import { DEVICE_KEY_BYTES, DEVICE_KEY_FILE_NAME } from "./constants"; -import { type EncryptionKey, importAesKey, randomBytes } from "./index"; const SECRET_ID = `${PLUGIN_ID}-device-key`; diff --git a/packages/plugin/src/core/crypto/hkdf.ts b/packages/plugin/src/core/crypto/hkdf.ts new file mode 100644 index 00000000..3c4678bc --- /dev/null +++ b/packages/plugin/src/core/crypto/hkdf.ts @@ -0,0 +1,29 @@ +/** A key for one purpose, derived from the raw data key where its bytes exist: the content key is non-extractable. */ +export async function deriveFromDataKey( + dataKey: Uint8Array, + info: string, + algorithm: AesKeyGenParams | HmacImportParams, + usages: KeyUsage[], +): Promise { + const subtle = window.crypto.subtle; + const material = await subtle.importKey( + "raw", + dataKey as BufferSource, + "HKDF", + false, + ["deriveKey"], + ); + return subtle.deriveKey( + { + name: "HKDF", + hash: "SHA-256", + // The data key is uniformly random, so HKDF needs no salt to extract. + salt: new Uint8Array(), + info: new TextEncoder().encode(info), + }, + material, + algorithm, + false, + usages, + ); +} diff --git a/packages/plugin/src/core/crypto/index.ts b/packages/plugin/src/core/crypto/index.ts new file mode 100644 index 00000000..3ea4c54f --- /dev/null +++ b/packages/plugin/src/core/crypto/index.ts @@ -0,0 +1,29 @@ +export { chunkId, deriveChunkIds } from "./chunk-ids"; +export { + decryptBytes, + decryptDescribed, + decryptJson, + deriveKey, + type EncryptionKey, + encryptBytes, + encryptCompressible, + encryptDescribed, + encryptJson, + importAesKey, + isDescribed, + randomBytes, + randomId, + randomSecret, + sha256Hex, + weakPassphrase, +} from "./cipher"; +export { MIN_PASSPHRASE_LENGTH } from "./constants"; +export { DeviceKey } from "./device-key"; +export { deriveLiveKeys, type LiveKeys } from "./live-keys"; +export { + clearCachedPassphrase, + loadCachedPassphrase, + saveCachedPassphrase, +} from "./passphrase-cache"; +export { type SealedFor, seal, unseal } from "./seal"; +export { LINK_PARAM, openLink, sealLink } from "./sealed-link"; diff --git a/packages/plugin/src/core/crypto/live-keys.ts b/packages/plugin/src/core/crypto/live-keys.ts new file mode 100644 index 00000000..01c63bdc --- /dev/null +++ b/packages/plugin/src/core/crypto/live-keys.ts @@ -0,0 +1,28 @@ +import { deriveFromDataKey } from "./hkdf"; + +/** One key per live-layer purpose. */ +export interface LiveKeys { + /** AES-GCM-256 over every live frame the hub stores or forwards. */ + frames: CryptoKey; + /** HMAC-SHA-256 naming documents, so the hub never learns a path. */ + docIds: CryptoKey; +} + +const FRAMES_INFO = "mdsync/live/frames/v1"; +const DOC_IDS_INFO = "mdsync/live/doc-ids/v1"; + +export async function deriveLiveKeys(dataKey: Uint8Array): Promise { + const [frames, docIds] = await Promise.all([ + deriveFromDataKey(dataKey, FRAMES_INFO, { name: "AES-GCM", length: 256 }, [ + "encrypt", + "decrypt", + ]), + deriveFromDataKey( + dataKey, + DOC_IDS_INFO, + { name: "HMAC", hash: "SHA-256", length: 256 }, + ["sign"], + ), + ]); + return { frames, docIds }; +} diff --git a/packages/plugin/src/crypto/passphrase-cache.ts b/packages/plugin/src/core/crypto/passphrase-cache.ts similarity index 86% rename from packages/plugin/src/crypto/passphrase-cache.ts rename to packages/plugin/src/core/crypto/passphrase-cache.ts index 3e6bab64..28f5f0c2 100644 --- a/packages/plugin/src/crypto/passphrase-cache.ts +++ b/packages/plugin/src/core/crypto/passphrase-cache.ts @@ -1,10 +1,9 @@ import type { DataAdapter } from "obsidian"; -import { PLUGIN_ID } from "@/constants"; -import { PASSPHRASE_CACHE_FILE_NAME } from "@/crypto/constants"; -import { deletePath, readBinary, writeBinary } from "@/vault/io"; - +import { PLUGIN_ID } from "@/core/constants"; +import { deletePath, readBinary, writeBinary } from "@/core/vault"; +import { decryptJson, encryptJson } from "./cipher"; +import { PASSPHRASE_CACHE_FILE_NAME } from "./constants"; import type { DeviceKey } from "./device-key"; -import { decryptJson, encryptJson } from "./index"; interface CachedPayload { version: 1; diff --git a/packages/plugin/src/crypto/seal.ts b/packages/plugin/src/core/crypto/seal.ts similarity index 100% rename from packages/plugin/src/crypto/seal.ts rename to packages/plugin/src/core/crypto/seal.ts diff --git a/packages/plugin/src/crypto/sealed-link.ts b/packages/plugin/src/core/crypto/sealed-link.ts similarity index 98% rename from packages/plugin/src/crypto/sealed-link.ts rename to packages/plugin/src/core/crypto/sealed-link.ts index b52fc3b8..3f7067a8 100644 --- a/packages/plugin/src/crypto/sealed-link.ts +++ b/packages/plugin/src/core/crypto/sealed-link.ts @@ -5,9 +5,9 @@ import { bytesToBase64Url, deflateBytes, inflateBytes, -} from "@/utils"; +} from "@/core/utils"; -import { decryptBytes, deriveKey, encryptBytes, randomBytes } from "./index"; +import { decryptBytes, deriveKey, encryptBytes, randomBytes } from "./cipher"; const LINK_VERSION = 5; const LINK_SALT_BYTES = 16; diff --git a/packages/plugin/src/core/drawing/codec.ts b/packages/plugin/src/core/drawing/codec.ts new file mode 100644 index 00000000..77a754db --- /dev/null +++ b/packages/plugin/src/core/drawing/codec.ts @@ -0,0 +1,114 @@ +/** + * Excalidraw's `compressed-json` scene is one LZString stream: any edit rewrites all of it, so neither gzip nor + * chunking can share bytes between versions. The stored form carries the scene as plain JSON instead; the wrap + * the plugin applied to the base64 is kept so the original bytes come back. + */ + +import { compressToBase64, decompressFromBase64 } from "lz-string"; + +import { HEAD_BYTES, isDrawing, SCENE_BLOCK } from "./format"; + +export interface DrawingCodec { + name: "excalidraw-lz"; + /** Base64 characters per line. */ + width: number; + /** What follows each full line. */ + gap: string; +} + +const NAME = "excalidraw-lz"; +const MAX_GAP = 16; +/** A bigger scene is stored as it is: rebuilding it on every read would hold the main thread for seconds. */ +const MAX_SCENE_CHARS = 2 * 1024 * 1024; + +const decoder = new TextDecoder("utf-8", { ignoreBOM: true }); +const encoder = new TextEncoder(); + +export function isDrawingCodec(value: unknown): value is DrawingCodec { + if (typeof value !== "object" || value === null) return false; + const { name, width, gap } = value as Partial; + return ( + Object.keys(value).length === 3 && + name === NAME && + typeof width === "number" && + Number.isInteger(width) && + width > 0 && + typeof gap === "string" && + gap.length <= MAX_GAP && + /^\s*$/.test(gap) + ); +} + +/** + * Null for anything but a drawing whose scene is `compressed-json` and whose decoded form rebuilds the very + * same bytes: a file this cannot reproduce is stored as it is. + */ +export function encodeDrawing( + bytes: Uint8Array, +): { stored: Uint8Array; codec: DrawingCodec } | null { + try { + if (!isDrawing(decoder.decode(bytes.subarray(0, HEAD_BYTES)))) return null; + const text = decoder.decode(bytes); + const match = SCENE_BLOCK.exec(text); + if (match?.[2] !== "compressed-json") return null; + const [whole = "", heading = "", , lineBreak = "", body = "", close = ""] = + match; + const json = decompressFromBase64(body.replace(/\s+/g, "")); + if (!json || json.length > MAX_SCENE_CHARS) return null; + const codec: DrawingCodec = { name: NAME, ...wrapOf(body) }; + if (!isDrawingCodec(codec)) return null; + const stored = encoder.encode( + `${text.slice(0, match.index)}${heading}\`\`\`json${lineBreak}${json}${close}\`\`\`${text.slice(match.index + whole.length)}`, + ); + return same(decodeDrawing(stored, codec), bytes) ? { stored, codec } : null; + } catch { + return null; + } +} + +/** Throws when `stored` holds no scene block; the caller's hash check is the guard on what it returns. */ +export function decodeDrawing( + stored: Uint8Array, + codec: DrawingCodec, +): Uint8Array { + if (!isDrawingCodec(codec)) throw new Error("Unknown drawing codec"); + const text = decoder.decode(stored); + const match = SCENE_BLOCK.exec(text); + if (match?.[2] !== "json") throw new Error("Stored drawing has no scene"); + const [whole = "", heading = "", , lineBreak = "", json = "", close = ""] = + match; + const packed = wrap(compressToBase64(json), codec); + return encoder.encode( + `${text.slice(0, match.index)}${heading}\`\`\`compressed-json${lineBreak}${packed}${close}\`\`\`${text.slice(match.index + whole.length)}`, + ); +} + +/** + * The first line's length and the whitespace after it, as the writer chose them (the Excalidraw plugin: 256 + * and a blank line). One line with no break is its own width and no gap. + */ +function wrapOf(body: string): { width: number; gap: string } { + const width = body.search(/\s/); + if (width < 0) return { width: body.length, gap: "" }; + const run = /\s+/y; + run.lastIndex = width; + return { width, gap: run.exec(body)?.[0] ?? "" }; +} + +/** `base64.replace(/(.{width})/g, "$1" + gap)`, without building a pattern from the width. */ +function wrap(base64: string, { width, gap }: DrawingCodec): string { + const lines: string[] = []; + for (let at = 0; at < base64.length; at += width) { + const line = base64.slice(at, at + width); + lines.push(line.length === width ? line + gap : line); + } + return lines.join(""); +} + +function same(a: Uint8Array, b: Uint8Array): boolean { + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false; + } + return true; +} diff --git a/packages/plugin/src/drawing/format.ts b/packages/plugin/src/core/drawing/format.ts similarity index 82% rename from packages/plugin/src/drawing/format.ts rename to packages/plugin/src/core/drawing/format.ts index 7442ed26..11b3e60b 100644 --- a/packages/plugin/src/drawing/format.ts +++ b/packages/plugin/src/core/drawing/format.ts @@ -28,21 +28,28 @@ export interface Drawing { end: number; } -const BLOCK = - /(## Drawing[ \t]*\r?\n)```(compressed-json|json)\r?\n([\s\S]*?)\r?\n```/; +/** Heading, kind, line break, body, closing line break: the codec rebuilds the block from them byte for byte. */ +export const SCENE_BLOCK = + /(## Drawing[ \t]*\r?\n)```(compressed-json|json)(\r?\n)([\s\S]*?)(\r?\n)```/; const EMBEDDED = "## Embedded Files"; +/** Front matter sits at the top; a drawing names itself well before this. */ +export const HEAD_BYTES = 1024; + +/** The front matter key that makes a note a drawing, whatever its name. */ +export const DRAWING_KEY = "excalidraw-plugin"; +const DRAWING_LINE = new RegExp(`^${DRAWING_KEY}:`, "m"); export function isDrawing(text: string): boolean { if (!text.startsWith("---")) return false; const end = text.indexOf("\n---", 3); - return /^excalidraw-plugin:/m.test(end < 0 ? text : text.slice(0, end)); + return DRAWING_LINE.test(end < 0 ? text : text.slice(0, end)); } export function readDrawing(text: string): Drawing | null { if (!isDrawing(text)) return null; - const match = BLOCK.exec(text); + const match = SCENE_BLOCK.exec(text); if (!match) return null; - const [whole, heading = "", kind, body = ""] = match; + const [whole, heading = "", kind, , body = ""] = match; const json = kind === "json" ? body : decompressFromBase64(body.replace(/\s+/g, "")); try { diff --git a/packages/plugin/src/core/drawing/index.ts b/packages/plugin/src/core/drawing/index.ts new file mode 100644 index 00000000..e1736346 --- /dev/null +++ b/packages/plugin/src/core/drawing/index.ts @@ -0,0 +1,15 @@ +export { + type DrawingCodec, + decodeDrawing, + encodeDrawing, + isDrawingCodec, +} from "./codec"; +export { + DRAWING_KEY, + isDrawing, + isElement, + readDrawing, + type SceneElement, +} from "./format"; +export { mergeDrawings, mergeElements, wins } from "./merge"; +export { sceneOfBytes } from "./scene"; diff --git a/packages/plugin/src/drawing/merge.ts b/packages/plugin/src/core/drawing/merge.ts similarity index 100% rename from packages/plugin/src/drawing/merge.ts rename to packages/plugin/src/core/drawing/merge.ts diff --git a/packages/plugin/src/drawing/scene.ts b/packages/plugin/src/core/drawing/scene.ts similarity index 79% rename from packages/plugin/src/drawing/scene.ts rename to packages/plugin/src/core/drawing/scene.ts index de609deb..4b90c318 100644 --- a/packages/plugin/src/drawing/scene.ts +++ b/packages/plugin/src/core/drawing/scene.ts @@ -1,11 +1,14 @@ -import { sha256Hex } from "@/crypto"; +import { sha256Hex } from "@/core/crypto"; -import { isDrawing, readDrawing, type SceneElement } from "./format"; +import { + HEAD_BYTES, + isDrawing, + readDrawing, + type SceneElement, +} from "./format"; const decoder = new TextDecoder(); const encoder = new TextEncoder(); -/** Front matter sits at the top; a drawing names itself well before this. */ -const HEAD_BYTES = 1024; /** * A drawing's identity regardless of view state: its text outside the scene plus element versions. Undefined @@ -35,6 +38,6 @@ export async function sceneOfBytes( } /** An element at one version: any edit gives it a new nonce. */ -export function stamp({ id, version, versionNonce }: SceneElement): string { +function stamp({ id, version, versionNonce }: SceneElement): string { return `${id}:${version}:${versionNonce}`; } diff --git a/packages/plugin/src/core/hub/index.ts b/packages/plugin/src/core/hub/index.ts new file mode 100644 index 00000000..31e807a6 --- /dev/null +++ b/packages/plugin/src/core/hub/index.ts @@ -0,0 +1,24 @@ +export { type HubChannel, HubLink } from "./link"; +export { + FULL_SHORT_TEXT, + LINK_TEXT, + RELAY_TEXT, + type RelayFix, + relayFixOf, + relaySummary, + UNREADABLE_TEXT, +} from "./relay-text"; +export type { + HubListener, + SpaceFrame, + SpaceHub, + SpaceHubs, + SpaceListener, +} from "./space-hub"; +export { + isConnected, + isLinkState, + type LinkState, + type RelayStatus, + relayStatus, +} from "./status"; diff --git a/packages/plugin/src/hub/link.ts b/packages/plugin/src/core/hub/link.ts similarity index 100% rename from packages/plugin/src/hub/link.ts rename to packages/plugin/src/core/hub/link.ts diff --git a/packages/plugin/src/ui/common/relay.ts b/packages/plugin/src/core/hub/relay-text.ts similarity index 80% rename from packages/plugin/src/ui/common/relay.ts rename to packages/plugin/src/core/hub/relay-text.ts index 9f5a6a06..fd1ddd49 100644 --- a/packages/plugin/src/ui/common/relay.ts +++ b/packages/plugin/src/core/hub/relay-text.ts @@ -1,8 +1,5 @@ import { MAX_SLOTS } from "@mdsync/protocol"; -import type { App } from "obsidian"; - -import { PLUGIN_ID } from "@/constants"; -import { isConnected, type LinkState, type RelayStatus } from "@/hub/status"; +import { isConnected, type LinkState, type RelayStatus } from "./status"; export const RELAY_TEXT: Record = { off: "Real-time sync is off", @@ -16,6 +13,16 @@ export const RELAY_TEXT: Record = { offline: "Relay unreachable: changes sync on the schedule", }; +/** A socket's state in a word, beside the relay it goes to. */ +export const LINK_TEXT: Record = { + connecting: "Connecting…", + connected: "Connected", + unauthorized: "Refused", + offline: "Unreachable", +}; + +export const FULL_SHORT_TEXT = "No room on this relay: syncs on the schedule"; + export const UNREADABLE_TEXT = "Can't read everyone here: a different passphrase or access"; @@ -46,14 +53,3 @@ export function relayFixOf(status: RelayStatus): RelayFix | null { if (status === "offline") return "reconnect"; return status === "unauthorized" ? "settings" : null; } - -interface SettingsDialog { - open(): void; - openTabById(id: string): void; -} - -export function openPluginSettings(app: App): void { - const { setting } = app as App & { setting?: SettingsDialog }; - setting?.open(); - setting?.openTabById(PLUGIN_ID); -} diff --git a/packages/plugin/src/core/hub/space-hub.ts b/packages/plugin/src/core/hub/space-hub.ts new file mode 100644 index 00000000..0bc8c45d --- /dev/null +++ b/packages/plugin/src/core/hub/space-hub.ts @@ -0,0 +1,37 @@ +import type { ClientFrame, ServerFrame } from "@mdsync/protocol"; + +/** The relay's own state and the cold-sync ping; frames go to `SpaceListener`s. */ +export interface HubListener { + /** Another device pushed into any space this device holds. */ + onSignal?(spaceId: string): void; + /** The relay cut a space's grant: revoked, or a token too new for it yet. */ + onRevoked?(): void; + /** The vault's socket; also reported on every restart, so listeners drop state tied to the old link. */ + onConnectionChange?(connected: boolean): void; +} + +export interface SpaceListener { + onFrame?(frame: ServerFrame): void; + /** False on every restart of its socket and when the relay revokes the channel. */ + onConnectionChange?(connected: boolean): void; +} + +/** A client frame before its socket's slot is known. */ +export type SpaceFrame = ClientFrame extends infer F + ? F extends ClientFrame + ? Omit + : never + : never; + +/** A space's channel on whichever socket holds it; frames sent while it is down are dropped. */ +export interface SpaceHub { + send(frame: SpaceFrame): void; + isConnected(): boolean; + listen(listener: SpaceListener): () => void; +} + +/** The hub as live editing and presence see it: one channel per space. */ +export interface SpaceHubs { + space(spaceId: string): SpaceHub; + listen(listener: HubListener): () => void; +} diff --git a/packages/plugin/src/hub/status.ts b/packages/plugin/src/core/hub/status.ts similarity index 100% rename from packages/plugin/src/hub/status.ts rename to packages/plugin/src/core/hub/status.ts diff --git a/packages/plugin/src/core/index.ts b/packages/plugin/src/core/index.ts deleted file mode 100644 index 150cb29f..00000000 --- a/packages/plugin/src/core/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export { DeviceName } from "./device-name"; -export { LogService } from "./log-service"; -export { PassphraseManager } from "./passphrase-manager"; -export { createSessionOpeners } from "./session-factory"; -export { StatePersister } from "./state-persister"; diff --git a/packages/plugin/src/core/logs/index.ts b/packages/plugin/src/core/logs/index.ts new file mode 100644 index 00000000..1fb3936b --- /dev/null +++ b/packages/plugin/src/core/logs/index.ts @@ -0,0 +1,2 @@ +export { LogService } from "./log-service"; +export { ESyncLogLevel, ESyncLogOperation, type SyncLogEntry } from "./store"; diff --git a/packages/plugin/src/core/log-service.ts b/packages/plugin/src/core/logs/log-service.ts similarity index 97% rename from packages/plugin/src/core/log-service.ts rename to packages/plugin/src/core/logs/log-service.ts index a14f0849..56e5f834 100644 --- a/packages/plugin/src/core/log-service.ts +++ b/packages/plugin/src/core/logs/log-service.ts @@ -1,5 +1,5 @@ import type { DataAdapter } from "obsidian"; - +import { setDiagnosticsSink } from "@/core/shared"; import { appendSyncLog, createSyncLogEntry, @@ -8,8 +8,7 @@ import { loadSyncLogs, type SyncLogEntry, saveSyncLogs, -} from "@/logs/store"; -import { setDiagnosticsSink } from "@/shared"; +} from "./store"; /** A push logs many lines in a burst: one file write after they settle. */ const WRITE_QUIET_MS = 1000; diff --git a/packages/plugin/src/logs/store.ts b/packages/plugin/src/core/logs/store.ts similarity index 94% rename from packages/plugin/src/logs/store.ts rename to packages/plugin/src/core/logs/store.ts index 89d765c9..581defcc 100644 --- a/packages/plugin/src/logs/store.ts +++ b/packages/plugin/src/core/logs/store.ts @@ -1,9 +1,8 @@ import type { DataAdapter } from "obsidian"; -import { PLUGIN_ID } from "@/constants"; -import { randomId } from "@/crypto"; -import { writeAtomic } from "@/vault/atomic-write"; -import { ensureParent } from "@/vault/io"; +import { PLUGIN_ID } from "@/core/constants"; +import { randomId } from "@/core/crypto"; +import { ensureParent, writeAtomic } from "@/core/vault"; const LOG_FILE_NAME = "logs.json"; const MAX_LOG_ENTRIES = 200; diff --git a/packages/plugin/src/settings/fields.ts b/packages/plugin/src/core/settings/fields.ts similarity index 59% rename from packages/plugin/src/settings/fields.ts rename to packages/plugin/src/core/settings/fields.ts index f64758e3..de51cec4 100644 --- a/packages/plugin/src/settings/fields.ts +++ b/packages/plugin/src/core/settings/fields.ts @@ -6,12 +6,26 @@ import { type SettingGroupItem, } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import { EFieldKind } from "@/storage"; +import { notifyError } from "@/core/ui"; -import type { ConnectionTestResult } from "./connection-test"; import type { MdsyncSettings } from "./model"; +export const EFieldKind = { + Text: "text", + Password: "password", + Toggle: "toggle", + Number: "number", + Slider: "slider", + Choice: "choice", +} as const; +export type EFieldKind = (typeof EFieldKind)[keyof typeof EFieldKind]; + +/** What a Test button reports in its row. */ +export interface CheckResult { + ok: boolean; + message: string; +} + export const SUB_SETTING_CLASS = "mdsync-sub-setting"; const ERROR_DESC_CLASS = "mdsync-settings-error"; /** A relay URL typed letter by letter must not open a socket, or send a grant, per prefix. */ @@ -44,12 +58,19 @@ export function settleTyping(): void { for (const flush of [...settling]) flush(); } -export interface FieldContext { - plugin: PluginHost; +/** What a settings row needs from the plugin; a section that needs more widens it. */ +export interface SettingsHost { + settings: MdsyncSettings; + saveSettings(): Promise; + scheduleScopeRefresh(reason?: string): void; +} + +export interface FieldContext { + plugin: H; rerender: () => void; } -interface FieldBase { +interface FieldBase { name: string; desc?: string; when?: (settings: MdsyncSettings) => boolean; @@ -57,58 +78,79 @@ interface FieldBase { /** For scope-affecting settings. */ refreshScope?: boolean; rerender?: boolean; - after?: (plugin: PluginHost) => void; + after?: (plugin: H) => void; } -export interface ToggleField extends FieldBase { +export interface ToggleField extends FieldBase { kind: typeof EFieldKind.Toggle; get: (settings: MdsyncSettings) => boolean; - set: (value: boolean, plugin: PluginHost) => Partial; + set: (value: boolean, plugin: H) => Partial; } -export interface TextField extends FieldBase { +export interface TextField extends FieldBase { kind: typeof EFieldKind.Text | typeof EFieldKind.Password; placeholder?: string; get: (settings: MdsyncSettings) => string; - set: (value: string, plugin: PluginHost) => Partial; + set: (value: string, plugin: H) => Partial; } -export interface NumberField extends FieldBase { +export interface NumberField extends FieldBase { kind: typeof EFieldKind.Number; + /** Native bounds: either one makes the input a number input. */ + min?: number; + max?: number; get: (settings: MdsyncSettings) => string; parse: (raw: string) => number; - set: (value: number, plugin: PluginHost) => Partial; + set: (value: number, plugin: H) => Partial; } -export interface SliderField extends FieldBase { +export interface SliderField extends FieldBase { kind: typeof EFieldKind.Slider; min: number; max: number; step?: number; get: (settings: MdsyncSettings) => number; - set: (value: number, plugin: PluginHost) => Partial; + set: (value: number, plugin: H) => Partial; } -export interface ChoiceField extends FieldBase { +export interface ChoiceField extends FieldBase { kind: typeof EFieldKind.Choice; - /** Value to label. */ - options: Record; + /** Value to label; a function when the list depends on the current value. */ + options: + | Record + | ((settings: MdsyncSettings) => Record); get: (settings: MdsyncSettings) => string; - set: (value: string, plugin: PluginHost) => Partial; + set: (value: string, plugin: H) => Partial; } -export type SettingsField = - | ToggleField - | TextField - | NumberField - | SliderField - | ChoiceField; +export type SettingsField = + | ToggleField + | TextField + | NumberField + | SliderField + | ChoiceField; + +/** The get/set pair of a setting stored as is; spread it into a field, whose value type must match the key's. */ +export function bind( + key: K, +): { + get: (settings: MdsyncSettings) => MdsyncSettings[K]; + set: (value: MdsyncSettings[K]) => Pick; +} { + return { + get: (s) => s[key], + set: (v) => ({ [key]: v }) as Pick, + }; +} export type SettingsRow = Omit & { render: (setting: Setting) => ReturnType; }; -export function fieldRow(ctx: FieldContext, field: SettingsField): SettingsRow { +export function fieldRow( + ctx: FieldContext, + field: SettingsField, +): SettingsRow { const { when } = field; return { name: field.name, @@ -120,20 +162,22 @@ export function fieldRow(ctx: FieldContext, field: SettingsField): SettingsRow { }; } -function applyControl( +function applyControl( setting: Setting, - ctx: FieldContext, - field: SettingsField, + ctx: FieldContext, + field: SettingsField, ): Setting { if (field.sub) setting.settingEl.addClass(SUB_SETTING_CLASS); const apply = (patch: Partial): void => { - applyPatch(ctx, patch, field); + Object.assign(ctx.plugin.settings, patch); + persist(ctx, field); }; - const applyTyped = onSettled(apply); + // Typed edits are in the settings at once: a patch replayed later could revert another field's. + const persistTyped = onSettled(() => persist(ctx, field)); const type = (patch: Partial): void => { Object.assign(ctx.plugin.settings, patch); - applyTyped(patch); + persistTyped(); }; if (field.kind === EFieldKind.Toggle) { @@ -147,19 +191,28 @@ function applyControl( if (field.kind === EFieldKind.Choice) { return setting.addDropdown((dropdown) => dropdown - .addOptions(field.options) + .addOptions( + typeof field.options === "function" + ? field.options(ctx.plugin.settings) + : field.options, + ) .setValue(field.get(ctx.plugin.settings)) .onChange((value) => apply(field.set(value, ctx.plugin))), ); } if (field.kind === EFieldKind.Number) { - return setting.addText((text) => + return setting.addText((text) => { + if (field.min !== undefined || field.max !== undefined) { + text.inputEl.type = "number"; + if (field.min !== undefined) text.inputEl.min = String(field.min); + if (field.max !== undefined) text.inputEl.max = String(field.max); + } text.setValue(field.get(ctx.plugin.settings)).onChange((raw) => { if (!WHOLE_NUMBER.test(raw)) return; type(field.set(field.parse(raw), ctx.plugin)); - }), - ); + }); + }); } if (field.kind === EFieldKind.Slider) { @@ -184,7 +237,7 @@ function applyControl( export function checkRow( name: string, desc: string, - run: () => Promise, + run: () => Promise, ): SettingsRow { return { name, @@ -245,17 +298,18 @@ export function renderDefinitions( } } -function applyPatch( - ctx: FieldContext, - patch: Partial, - field: SettingsField, +function persist( + ctx: FieldContext, + field: SettingsField, ): void { - Object.assign(ctx.plugin.settings, patch); - void ctx.plugin.saveSettings().then(() => { - if (field.refreshScope) { - ctx.plugin.scheduleScopeRefresh("Sync scope settings changed."); - } - field.after?.(ctx.plugin); - if (field.rerender) ctx.rerender(); - }); + void ctx.plugin.saveSettings().then( + () => { + if (field.refreshScope) { + ctx.plugin.scheduleScopeRefresh("Sync scope settings changed."); + } + field.after?.(ctx.plugin); + if (field.rerender) ctx.rerender(); + }, + (err: unknown) => notifyError("Could not save settings", err), + ); } diff --git a/packages/plugin/src/core/settings/index.ts b/packages/plugin/src/core/settings/index.ts new file mode 100644 index 00000000..b6cd577e --- /dev/null +++ b/packages/plugin/src/core/settings/index.ts @@ -0,0 +1,32 @@ +export { + bind, + type CheckResult, + checkRow, + EFieldKind, + type FieldContext, + fieldRow, + group, + introRow, + onSettled, + renderDefinitions, + type SettingsField, + type SettingsHost, + type SettingsRow, + SUB_SETTING_CLASS, + settleTyping, +} from "./fields"; +export { + type CoreSettings, + clamp, + DEFAULT_CORE_SETTINGS, + DEFAULT_SETTINGS_SYNC, + EPluginLevel, + type HistoryKeep, + isRelayConfigured, + type MdsyncSettings, + mergeCoreSettings, + NUMERIC_BOUNDS, + type RelayConfig, + type SettingsSyncCategories, +} from "./model"; +export { imperativePage } from "./page"; diff --git a/packages/plugin/src/settings/model.ts b/packages/plugin/src/core/settings/model.ts similarity index 60% rename from packages/plugin/src/settings/model.ts rename to packages/plugin/src/core/settings/model.ts index 6f40c414..9c2bda40 100644 --- a/packages/plugin/src/settings/model.ts +++ b/packages/plugin/src/core/settings/model.ts @@ -5,28 +5,16 @@ import { AUTO_SYNC_MIN_MINUTES, BULK_DELETE_LIMIT_MAX, BULK_DELETE_LIMIT_MIN, - FILE_HISTORY_MAX_SNAPSHOTS, - FILE_HISTORY_MIN_SNAPSHOTS, + HISTORY_KEEP_MS, LIVE_SEND_MS, -} from "@/constants"; -import { parseStoredLink, type StoredLink } from "@/links/record"; -import { isCleartextRemote } from "@/shared"; -import { isSpaceRecord, type SpaceRecord } from "@/spaces/record"; -import { - type BrokerAdmin, - CONCURRENCY_FIELD, - defaultS3Config, - EStorageBackend, - getDescriptor, - isAdapterConfigured, - isKnownBackend, - type S3StorageConfig, - type StorageAdapterConfig, -} from "@/storage"; + SLOW_FILE_SETTLE_MAX_SECONDS, + SLOW_FILE_SETTLE_MIN_SECONDS, +} from "@/core/constants"; +import { isCleartextRemote } from "@/core/shared"; -const DEFAULT_MAX_FILE_BYTES = 100 * 1024 * 1024; +const DEFAULT_MAX_FILE_BYTES = 25 * 1024 * 1024; -const DEFAULT_FILE_HISTORY_MAX_SNAPSHOTS = 50; +export type HistoryKeep = keyof typeof HISTORY_KEEP_MS; export interface SettingsSyncCategories { coreSettings: boolean; @@ -37,6 +25,10 @@ export interface SettingsSyncCategories { themes: boolean; } +/** How much of a plugin's folder syncs; each level adds to the one before. */ +export const EPluginLevel = { Off: 0, Settings: 1, Code: 2, Data: 3 } as const; +export type EPluginLevel = (typeof EPluginLevel)[keyof typeof EPluginLevel]; + export const DEFAULT_SETTINGS_SYNC: SettingsSyncCategories = { coreSettings: false, hotkeys: false, @@ -46,10 +38,13 @@ export const DEFAULT_SETTINGS_SYNC: SettingsSyncCategories = { themes: false, }; -export interface MdsyncSettings { - storageConfigs: Record; - activeStorageKind: EStorageBackend; +/** What core parses. A field typed by a feature joins `MdsyncSettings` by module augmentation where that feature parses it. */ +export interface CoreSettings { settingsSync: SettingsSyncCategories; + /** Every plugin's level while `pluginConfigs` is on; never Off. */ + pluginLevel: EPluginLevel; + /** Plugins whose level differs from the default, Off included: they apply with `pluginConfigs` off too. */ + pluginLevels: Record; ignorePatterns: string; /** Skip symlinks and directory links pointing outside the vault. */ ignoreSymlinks: boolean; @@ -62,11 +57,15 @@ export interface MdsyncSettings { autoPushAfterChange: boolean; autoPushSettleSeconds: number; autoPushChangedFilesOnly: boolean; + /** Name endings, comma or space separated: files saved every few seconds, pushed after their own quiet period. */ + slowFileSuffixes: string; + slowFileSettleSeconds: number; /** An automatic push publishing more than `bulkDeleteLimit` deletions holds them all for review. */ confirmBulkDeletes: boolean; bulkDeleteLimit: number; fileHistoryEnabled: boolean; - fileHistoryMaxSnapshots: number; + fileHistoryKeep: HistoryKeep; + fileHistoryActivity: boolean; historyAutoRefresh: boolean; realtimeSync: boolean; /** Notes open in the editor edit together across devices, over the relay. */ @@ -76,8 +75,6 @@ export interface MdsyncSettings { /** Others' text in live notes tinted by author, on this device. */ showLiveAuthors: boolean; showOpenNote: boolean; - /** This device's copy of the shared folders it syncs; see `spaces/`. */ - spaces: SpaceRecord[]; /** Off: every share is paused here and kept out of sight. Never published. */ useSharedFolders: boolean; /** Shares this device holds out of sync; never published, unlike `spaces`. */ @@ -92,8 +89,6 @@ export interface MdsyncSettings { localRoots: Record; /** The vault storage (identity) the records were traded with: another vault's never reach this one. */ spacesVault: string | null; - /** This person's share links, keys included: traded sealed through the vault storage, never transferred. */ - links: StoredLink[]; /** Self-hosted worker (packages/relay): realtime signals. */ relayUrl: string; /** The worker's RELAY_SECRET; relay room tokens derive from it. */ @@ -112,12 +107,12 @@ export interface MdsyncSettings { uiLayout: "tree" | "flat"; } -const DEFAULT_STORAGE = defaultS3Config(); +export interface MdsyncSettings extends CoreSettings {} -export const DEFAULT_SETTINGS: MdsyncSettings = { - storageConfigs: { [DEFAULT_STORAGE.kind]: DEFAULT_STORAGE }, - activeStorageKind: DEFAULT_STORAGE.kind, +export const DEFAULT_CORE_SETTINGS: CoreSettings = { settingsSync: DEFAULT_SETTINGS_SYNC, + pluginLevel: EPluginLevel.Settings, + pluginLevels: {}, ignorePatterns: "", ignoreSymlinks: true, maxFileBytes: DEFAULT_MAX_FILE_BYTES, @@ -127,17 +122,19 @@ export const DEFAULT_SETTINGS: MdsyncSettings = { autoPushAfterChange: false, autoPushSettleSeconds: 10, autoPushChangedFilesOnly: false, + slowFileSuffixes: ".excalidraw.md, .canvas", + slowFileSettleSeconds: 60, confirmBulkDeletes: true, bulkDeleteLimit: 5, fileHistoryEnabled: false, - fileHistoryMaxSnapshots: DEFAULT_FILE_HISTORY_MAX_SNAPSHOTS, + fileHistoryKeep: "quarter", + fileHistoryActivity: true, historyAutoRefresh: true, realtimeSync: false, liveEditing: true, liveSendMs: LIVE_SEND_MS.balanced, showLiveAuthors: false, showOpenNote: true, - spaces: [], useSharedFolders: true, pausedSpaces: [], pauseArrivingShares: false, @@ -145,7 +142,6 @@ export const DEFAULT_SETTINGS: MdsyncSettings = { shareEditsWait: true, localRoots: {}, spacesVault: null, - links: [], relayUrl: "", relaySecret: "", cloudflareToken: "", @@ -160,38 +156,7 @@ export const DEFAULT_SETTINGS: MdsyncSettings = { uiLayout: "tree", }; -export function activeStorage(settings: MdsyncSettings): StorageAdapterConfig { - return ( - settings.storageConfigs[settings.activeStorageKind] ?? defaultS3Config() - ); -} - -export function isStorageConfigured(settings: MdsyncSettings): boolean { - return isAdapterConfigured(activeStorage(settings)); -} - -/** No vault storage, only shares joined by invite: those sync, the vault stays on this device. */ -export function isGuest(settings: MdsyncSettings): boolean { - return ( - !isStorageConfigured(settings) && - settings.spaces.some( - (record) => !record.closed && record.access.kind === "participant", - ) - ); -} - -export function canSync(settings: MdsyncSettings): boolean { - return isStorageConfigured(settings) || isGuest(settings); -} - -/** A share pins its location for good, so only a complete S3 setup may own one. */ -export function ownerStorage(settings: MdsyncSettings): S3StorageConfig | null { - const storage = activeStorage(settings); - if (storage.kind !== EStorageBackend.S3) return null; - return isStorageConfigured(settings) ? storage : null; -} - -export type RelayConfig = Pick; +export type RelayConfig = Pick; /** Both or nothing: the URL alone opens no room and signs nothing. A relay that takes the secret in the clear is none. */ export function isRelayConfigured(relay: RelayConfig): boolean { @@ -201,14 +166,6 @@ export function isRelayConfigured(relay: RelayConfig): boolean { ); } -/** The owner's side of the relay: shares and links both speak to it with the secret. */ -export function relayAdmin({ - relayUrl, - relaySecret, -}: RelayConfig): BrokerAdmin { - return { relayUrl, secret: relaySecret }; -} - /** Dropped settings. Several held secrets - share keys among them - so they are deleted, not kept. */ const RETIRED_KEYS = [ "realtimeServerUrl", @@ -217,6 +174,7 @@ const RETIRED_KEYS = [ "shareBrokerAdminSecret", "sharedFolders", "shareStorageKind", + "fileHistoryMaxSnapshots", ] as const; /** Bounds for numeric settings. Clamping here prevents invalid values from files or tokens. */ @@ -230,28 +188,27 @@ export const NUMERIC_BOUNDS = { min: AUTO_PUSH_SETTLE_MIN_SECONDS, max: AUTO_PUSH_SETTLE_MAX_SECONDS, }, + slowFileSettleSeconds: { + min: SLOW_FILE_SETTLE_MIN_SECONDS, + max: SLOW_FILE_SETTLE_MAX_SECONDS, + }, bulkDeleteLimit: { min: BULK_DELETE_LIMIT_MIN, max: BULK_DELETE_LIMIT_MAX, }, - fileHistoryMaxSnapshots: { - min: FILE_HISTORY_MIN_SNAPSHOTS, - max: FILE_HISTORY_MAX_SNAPSHOTS, - }, -} as const satisfies Partial>; - -const CONCURRENCY_BOUNDS: Bounds = { - min: CONCURRENCY_FIELD.min, - max: CONCURRENCY_FIELD.max, -}; +} as const satisfies Partial>; -interface Bounds { +export interface Bounds { min: number; max: number; } /** Returns fallback if below minimum; caps if above maximum. */ -function clamp(value: unknown, bounds: Bounds, fallback: number): number { +export function clamp( + value: unknown, + bounds: Bounds, + fallback: number, +): number { if (typeof value !== "number" || !Number.isFinite(value)) return fallback; if (value < bounds.min) return fallback; return Math.min(bounds.max, Math.round(value)); @@ -268,68 +225,59 @@ function stringValues(value: unknown): Record { ); } -type StoredSettings = Partial; +function isPluginLevel(value: unknown): value is EPluginLevel { + return Object.values(EPluginLevel).includes(value); +} -export function mergeSettings( - stored: StoredSettings | null | undefined, -): MdsyncSettings { - const storageConfigs: Record = { - ...(stored?.storageConfigs ?? {}), - }; - // Backfill fields added after initial save from backend defaults. - for (const [kind, config] of Object.entries(storageConfigs)) { - if (!isKnownBackend(kind) || !config || typeof config !== "object") { - delete storageConfigs[kind]; - continue; - } - config.concurrency = clamp( - config.concurrency, - CONCURRENCY_BOUNDS, - getDescriptor(kind).defaults().concurrency, - ); - } - if (Object.keys(storageConfigs).length === 0) { - storageConfigs[DEFAULT_STORAGE.kind] = DEFAULT_STORAGE; - } - const requested = stored?.activeStorageKind; - const activeStorageKind = - requested && storageConfigs[requested] - ? requested - : (Object.keys(storageConfigs)[0] as EStorageBackend); +function pluginLevelValues(value: unknown): Record { + if (typeof value !== "object" || value === null) return {}; + return Object.fromEntries( + Object.entries(value).filter((entry): entry is [string, EPluginLevel] => + isPluginLevel(entry[1]), + ), + ); +} - const merged: MdsyncSettings = { - ...DEFAULT_SETTINGS, +/** Keeps unknown stored keys: the slices parse theirs over this. */ +export function mergeCoreSettings( + stored: Partial | null | undefined, +): CoreSettings { + const merged: CoreSettings = { + ...DEFAULT_CORE_SETTINGS, ...(stored ?? {}), - storageConfigs, - activeStorageKind, // A preset only: the dropdown shows nothing else. liveSendMs: Object.values(LIVE_SEND_MS).includes( stored?.liveSendMs, ) ? (stored?.liveSendMs as number) - : DEFAULT_SETTINGS.liveSendMs, + : DEFAULT_CORE_SETTINGS.liveSendMs, + fileHistoryKeep: Object.keys(HISTORY_KEEP_MS).includes( + stored?.fileHistoryKeep as string, + ) + ? (stored?.fileHistoryKeep as HistoryKeep) + : DEFAULT_CORE_SETTINGS.fileHistoryKeep, settingsSync: { ...DEFAULT_SETTINGS_SYNC, ...((stored?.settingsSync as | Partial | undefined) ?? {}), }, - spaces: Array.isArray(stored?.spaces) - ? stored.spaces.filter(isSpaceRecord) - : [], + pluginLevel: + isPluginLevel(stored?.pluginLevel) && + stored.pluginLevel !== EPluginLevel.Off + ? stored.pluginLevel + : DEFAULT_CORE_SETTINGS.pluginLevel, + pluginLevels: pluginLevelValues(stored?.pluginLevels), pausedSpaces: Array.isArray(stored?.pausedSpaces) ? stored.pausedSpaces.filter((id) => typeof id === "string") : [], localRoots: stringValues(stored?.localRoots), - links: Array.isArray(stored?.links) - ? stored.links.flatMap((link) => parseStoredLink(link) ?? []) - : [], spacesVault: typeof stored?.spacesVault === "string" ? stored.spacesVault : null, }; for (const [key, bounds] of Object.entries(NUMERIC_BOUNDS)) { const field = key as keyof typeof NUMERIC_BOUNDS; - merged[field] = clamp(merged[field], bounds, DEFAULT_SETTINGS[field]); + merged[field] = clamp(merged[field], bounds, DEFAULT_CORE_SETTINGS[field]); } for (const key of RETIRED_KEYS) Reflect.deleteProperty(merged, key); return merged; diff --git a/packages/plugin/src/settings/page.ts b/packages/plugin/src/core/settings/page.ts similarity index 100% rename from packages/plugin/src/settings/page.ts rename to packages/plugin/src/core/settings/page.ts diff --git a/packages/plugin/src/shared/colors.ts b/packages/plugin/src/core/shared/colors.ts similarity index 100% rename from packages/plugin/src/shared/colors.ts rename to packages/plugin/src/core/shared/colors.ts diff --git a/packages/plugin/src/shared/diagnostics.ts b/packages/plugin/src/core/shared/diagnostics.ts similarity index 100% rename from packages/plugin/src/shared/diagnostics.ts rename to packages/plugin/src/core/shared/diagnostics.ts diff --git a/packages/plugin/src/shared/errors.ts b/packages/plugin/src/core/shared/errors.ts similarity index 100% rename from packages/plugin/src/shared/errors.ts rename to packages/plugin/src/core/shared/errors.ts diff --git a/packages/plugin/src/shared/format.ts b/packages/plugin/src/core/shared/format.ts similarity index 68% rename from packages/plugin/src/shared/format.ts rename to packages/plugin/src/core/shared/format.ts index cc9e46b7..bb42806e 100644 --- a/packages/plugin/src/shared/format.ts +++ b/packages/plugin/src/core/shared/format.ts @@ -1,5 +1,3 @@ -import type { ManifestEntry } from "@/sync/types"; - const BYTES_PER_KB = 1024; const BYTES_PER_MB = 1024 * 1024; @@ -23,7 +21,7 @@ export function formatTimestamp(ms: number): string { export function sumBytes( paths: ReadonlyArray, - fileMap: Record, + fileMap: Record, ): number { let total = 0; for (const p of paths) { @@ -49,7 +47,7 @@ export function formatRelativeTime( if (delta < RELATIVE_DAY_LIMIT * MS_PER_DAY) { return agoText(delta / MS_PER_DAY, "day"); } - return new Date(ms).toLocaleDateString(); + return formatDay(ms, now, false); } /** Heading for a day of rows: recent days read better by name than by date. */ @@ -57,24 +55,50 @@ export function formatDayLabel(ms: number, now: number = Date.now()): string { const days = Math.round((startOfDay(now) - startOfDay(ms)) / MS_PER_DAY); if (days <= 0) return "Today"; if (days === 1) return "Yesterday"; - if (days < 7) { - return new Date(ms).toLocaleDateString(undefined, { weekday: "long" }); - } - return new Date(ms).toLocaleDateString(); + return formatDay(ms, now); +} + +/** "Wed 14 Oct", with the year once it is not this one. */ +export function formatDay( + ms: number, + now: number = Date.now(), + weekday = true, +): string { + const date = new Date(ms); + const year = + date.getFullYear() === new Date(now).getFullYear() ? undefined : "numeric"; + return date.toLocaleDateString(undefined, { + weekday: weekday ? "short" : undefined, + day: "numeric", + month: "short", + year, + }); } -function startOfDay(ms: number): number { +export function startOfDay(ms: number): number { const date = new Date(ms); date.setHours(0, 0, 0, 0); return date.getTime(); } +/** Local Monday, as history's weeks run Monday to Sunday. */ +export function startOfWeek(ms: number): number { + const date = new Date(ms); + // Monday first, then its midnight: a DST switch can skip the Sunday's. + date.setDate(date.getDate() - ((date.getDay() + 6) % 7)); + return startOfDay(date.getTime()); +} + function agoText(value: number, unit: string): string { const count = Math.floor(value); return `${count} ${unit}${count === 1 ? "" : "s"} ago`; } /** "1 file" / "3 files". Counts read wrong without it in the restore warnings. */ -export function pluralize(count: number, noun: string): string { - return `${count} ${noun}${count === 1 ? "" : "s"}`; +export function pluralize( + count: number, + noun: string, + plural = `${noun}s`, +): string { + return `${count} ${count === 1 ? noun : plural}`; } diff --git a/packages/plugin/src/core/shared/index.ts b/packages/plugin/src/core/shared/index.ts new file mode 100644 index 00000000..d1fa52ae --- /dev/null +++ b/packages/plugin/src/core/shared/index.ts @@ -0,0 +1,32 @@ +export { personColor, personTint } from "./colors"; +export { reportWarning, setDiagnosticsSink } from "./diagnostics"; +export { asError, errorMessage } from "./errors"; +export { + formatBytes, + formatDay, + formatDayLabel, + formatRelativeTime, + formatTimestamp, + pluralize, + startOfDay, + startOfWeek, + sumBytes, + withDevices, +} from "./format"; +export { + isNetworkError, + isOffline, + OFFLINE_MESSAGE, + userMessage, +} from "./offline"; +export { + folderName, + hasDotSegment, + hasReservedChar, + isCleartextRemote, + normalizeKeyPrefix, + normalizePath, + relayBase, + stripTrailingSlash, +} from "./path"; +export { StorageHttpError, StorageTimeoutError } from "./transport-errors"; diff --git a/packages/plugin/src/shared/offline.ts b/packages/plugin/src/core/shared/offline.ts similarity index 82% rename from packages/plugin/src/shared/offline.ts rename to packages/plugin/src/core/shared/offline.ts index 3f16ddf3..110b522e 100644 --- a/packages/plugin/src/shared/offline.ts +++ b/packages/plugin/src/core/shared/offline.ts @@ -1,4 +1,5 @@ import { errorMessage } from "./errors"; +import { StorageHttpError, StorageTimeoutError } from "./transport-errors"; export const OFFLINE_MESSAGE = "No connection to the storage."; @@ -6,12 +7,13 @@ export const OFFLINE_MESSAGE = "No connection to the storage."; const NETWORK_FAILURE = /network\s*(?:connection|request|error)\b|network is unreachable|failed to fetch|load failed|stream closed|socket hang up|unknown\s*host|unable to resolve host|internet connection|ECONNRESET|ECONNREFUSED|ECONNABORTED|ETIMEDOUT|EPIPE|ENOTFOUND|EAI_AGAIN|ENETUNREACH|EHOSTUNREACH|ENETRESET|ERR_(?:NETWORK|CONNECTION|INTERNET|NAME_NOT_RESOLVED)/i; -/** A request that got no answer. By name, not class: `storage/` imports this module. */ +/** A request that got no answer. */ export function isNetworkError(err: unknown): boolean { if (!err || typeof err !== "object") return false; + if (err instanceof StorageHttpError) return false; + if (err instanceof StorageTimeoutError) return true; const { name, message } = err as { name?: string; message?: string }; - if (name === "StorageHttpError") return false; - if (name === "StorageTimeoutError" || name === "TimeoutError") return true; + if (name === "TimeoutError") return true; return typeof message === "string" && NETWORK_FAILURE.test(message); } diff --git a/packages/plugin/src/shared/path.ts b/packages/plugin/src/core/shared/path.ts similarity index 100% rename from packages/plugin/src/shared/path.ts rename to packages/plugin/src/core/shared/path.ts diff --git a/packages/plugin/src/core/shared/transport-errors.ts b/packages/plugin/src/core/shared/transport-errors.ts new file mode 100644 index 00000000..ae34d0d1 --- /dev/null +++ b/packages/plugin/src/core/shared/transport-errors.ts @@ -0,0 +1,21 @@ +/** Owned by core because `offline.ts` classifies them: a rename in a feature must not silently change what counts as offline. */ + +export class StorageHttpError extends Error { + constructor( + readonly status: number, + message: string, + ) { + super(message); + this.name = "StorageHttpError"; + } +} + +export class StorageTimeoutError extends Error { + constructor( + ms: number, + readonly bytes = 0, + ) { + super(`Storage operation timed out after ${ms}ms`); + this.name = "StorageTimeoutError"; + } +} diff --git a/packages/plugin/src/ui/source-control/action-button.ts b/packages/plugin/src/core/ui/controls/action-button.ts similarity index 100% rename from packages/plugin/src/ui/source-control/action-button.ts rename to packages/plugin/src/core/ui/controls/action-button.ts diff --git a/packages/plugin/src/ui/common/alert-line.ts b/packages/plugin/src/core/ui/controls/alert-line.ts similarity index 100% rename from packages/plugin/src/ui/common/alert-line.ts rename to packages/plugin/src/core/ui/controls/alert-line.ts diff --git a/packages/plugin/src/ui/common/callout.ts b/packages/plugin/src/core/ui/controls/callout.ts similarity index 100% rename from packages/plugin/src/ui/common/callout.ts rename to packages/plugin/src/core/ui/controls/callout.ts diff --git a/packages/plugin/src/ui/common/copyable.ts b/packages/plugin/src/core/ui/controls/copyable.ts similarity index 93% rename from packages/plugin/src/ui/common/copyable.ts rename to packages/plugin/src/core/ui/controls/copyable.ts index c86a30b2..958fd934 100644 --- a/packages/plugin/src/ui/common/copyable.ts +++ b/packages/plugin/src/core/ui/controls/copyable.ts @@ -1,6 +1,6 @@ import { Setting } from "obsidian"; -import { runWithNotice } from "./notices"; +import { runWithNotice } from "../notices"; /** A read-only field with a copy button. */ export function copyable(el: HTMLElement, name: string, value: string): void { diff --git a/packages/plugin/src/ui/common/file-path.ts b/packages/plugin/src/core/ui/controls/file-path.ts similarity index 100% rename from packages/plugin/src/ui/common/file-path.ts rename to packages/plugin/src/core/ui/controls/file-path.ts diff --git a/packages/plugin/src/ui/common/icon-button.ts b/packages/plugin/src/core/ui/controls/icon-button.ts similarity index 100% rename from packages/plugin/src/ui/common/icon-button.ts rename to packages/plugin/src/core/ui/controls/icon-button.ts diff --git a/packages/plugin/src/ui/common/marquee.ts b/packages/plugin/src/core/ui/controls/marquee.ts similarity index 100% rename from packages/plugin/src/ui/common/marquee.ts rename to packages/plugin/src/core/ui/controls/marquee.ts diff --git a/packages/plugin/src/ui/common/segments.ts b/packages/plugin/src/core/ui/controls/segments.ts similarity index 100% rename from packages/plugin/src/ui/common/segments.ts rename to packages/plugin/src/core/ui/controls/segments.ts diff --git a/packages/plugin/src/core/ui/index.ts b/packages/plugin/src/core/ui/index.ts new file mode 100644 index 00000000..0b465b4d --- /dev/null +++ b/packages/plugin/src/core/ui/index.ts @@ -0,0 +1,46 @@ +export { actionButton, textButton } from "./controls/action-button"; +export { alertLine } from "./controls/alert-line"; +export { callout } from "./controls/callout"; +export { copyable, copyText } from "./controls/copyable"; +export { renderPath } from "./controls/file-path"; +export { appendIconButton, appendLabeledButton } from "./controls/icon-button"; +export { measureSlide, slideWhenCut } from "./controls/marquee"; +export { renderSegments, type Segments } from "./controls/segments"; +export { makeActivatable } from "./input/activatable"; +export { onEnter } from "./input/enter-key"; +export { focusKey, renderKeepingFocus } from "./input/focus"; +export { onLongPress } from "./input/long-press"; +export { infoTitle, showMenuAt } from "./menu"; +export { + asDrawer, + type ModalHead, + modalCard, + modalFooter, + modalHint, + modalSection, + modalWarning, + renderModalHead, +} from "./modal-frame"; +export { openChoiceModal, openConfirmModal } from "./modals/confirm-modal"; +export { askNewPassphrase, askPassphrase } from "./modals/passphrase-modal"; +export { openPromiseModal } from "./modals/promise-modal"; +export { openPromptModal } from "./modals/prompt-modal"; +export { + attempt, + notifyAction, + notifyError, + notifyInfo, + reportError, + runWithNotice, + tapTooltip, +} from "./notices"; +export { observeResize } from "./observe-resize"; +export { + closePluginSettings, + openInEditor, + openPluginSettings, + revealInFileExplorer, +} from "./obsidian-helpers"; +export { openNote } from "./open-note"; +export { redrawOnPhoneChange } from "./phone-change"; +export { serial } from "./serial"; diff --git a/packages/plugin/src/ui/common/activatable.ts b/packages/plugin/src/core/ui/input/activatable.ts similarity index 100% rename from packages/plugin/src/ui/common/activatable.ts rename to packages/plugin/src/core/ui/input/activatable.ts diff --git a/packages/plugin/src/ui/common/enter-key.ts b/packages/plugin/src/core/ui/input/enter-key.ts similarity index 88% rename from packages/plugin/src/ui/common/enter-key.ts rename to packages/plugin/src/core/ui/input/enter-key.ts index a759158f..c6edfc5c 100644 --- a/packages/plugin/src/ui/common/enter-key.ts +++ b/packages/plugin/src/core/ui/input/enter-key.ts @@ -1,5 +1,5 @@ -import { reportError } from "./notices"; -import { serial } from "./serial"; +import { reportError } from "../notices"; +import { serial } from "../serial"; function isPlainEnter(event: KeyboardEvent): boolean { return ( diff --git a/packages/plugin/src/ui/common/focus.ts b/packages/plugin/src/core/ui/input/focus.ts similarity index 100% rename from packages/plugin/src/ui/common/focus.ts rename to packages/plugin/src/core/ui/input/focus.ts diff --git a/packages/plugin/src/ui/common/long-press.ts b/packages/plugin/src/core/ui/input/long-press.ts similarity index 100% rename from packages/plugin/src/ui/common/long-press.ts rename to packages/plugin/src/core/ui/input/long-press.ts diff --git a/packages/plugin/src/ui/common/menu.ts b/packages/plugin/src/core/ui/menu.ts similarity index 65% rename from packages/plugin/src/ui/common/menu.ts rename to packages/plugin/src/core/ui/menu.ts index 8a243220..88947fa1 100644 --- a/packages/plugin/src/ui/common/menu.ts +++ b/packages/plugin/src/core/ui/menu.ts @@ -1,10 +1,5 @@ import type { Menu } from "obsidian"; -import type { Person } from "@/presence"; -import { withDevices } from "@/shared"; - -import { renderAvatar } from "./avatars"; - export function infoTitle(text: string, state?: string): DocumentFragment { const title = createFragment(); title.createSpan({ cls: "mdsync-menu-info", text }); @@ -12,14 +7,6 @@ export function infoTitle(text: string, state?: string): DocumentFragment { return title; } -export function personTitle(person: Person, state: string): DocumentFragment { - const title = createFragment(); - renderAvatar(title, person); - title.createSpan({ text: withDevices(person.name, person.devices) }); - title.createSpan({ cls: "mdsync-person-state", text: state }); - return title; -} - export function showMenuAt( menu: Menu, anchor: HTMLElement | null | undefined, diff --git a/packages/plugin/src/ui/common/modal-frame.ts b/packages/plugin/src/core/ui/modal-frame.ts similarity index 100% rename from packages/plugin/src/ui/common/modal-frame.ts rename to packages/plugin/src/core/ui/modal-frame.ts diff --git a/packages/plugin/src/ui/modals/confirm-modal.ts b/packages/plugin/src/core/ui/modals/confirm-modal.ts similarity index 97% rename from packages/plugin/src/ui/modals/confirm-modal.ts rename to packages/plugin/src/core/ui/modals/confirm-modal.ts index 9de88f0b..b070501d 100644 --- a/packages/plugin/src/ui/modals/confirm-modal.ts +++ b/packages/plugin/src/core/ui/modals/confirm-modal.ts @@ -1,12 +1,11 @@ import { type App, ButtonComponent, Modal } from "obsidian"; - +import { renderPath } from "../controls/file-path"; import { modalCard, modalFooter, modalHint, renderModalHead, - renderPath, -} from "@/ui/common"; +} from "../modal-frame"; import { openPromiseModal } from "./promise-modal"; type ButtonClass = "mod-cta" | "mod-warning"; diff --git a/packages/plugin/src/core/ui/modals/passphrase-modal.ts b/packages/plugin/src/core/ui/modals/passphrase-modal.ts new file mode 100644 index 00000000..64c5407c --- /dev/null +++ b/packages/plugin/src/core/ui/modals/passphrase-modal.ts @@ -0,0 +1,122 @@ +import { type App, ButtonComponent, Modal, Setting } from "obsidian"; + +import { weakPassphrase } from "@/core/crypto"; +import { alertLine } from "../controls/alert-line"; +import { onEnter } from "../input/enter-key"; +import { type ModalHead, modalFooter, renderModalHead } from "../modal-frame"; + +import { openPromiseModal } from "./promise-modal"; + +type Answer = (value: string | null) => void; + +function openFrame( + app: App, + answer: Answer, + head: ModalHead, + text: string, +): { modal: Modal; finish: Answer } { + const modal = new Modal(app); + renderModalHead(modal, head); + modal.contentEl.createEl("p", { text }); + return { + modal, + finish: (value) => { + answer(value); + modal.close(); + }, + }; +} + +function passwordField( + modal: Modal, + label: string, + onChange: (value: string) => void, + onSubmit: () => void, +): HTMLInputElement { + let input!: HTMLInputElement; + new Setting(modal.contentEl).setName(label).addText((t) => { + input = t.inputEl; + t.inputEl.type = "password"; + t.inputEl.setAttr("aria-label", label); + t.onChange(onChange); + onEnter(t.inputEl, onSubmit); + }); + return input; +} + +function cancelAndConfirm( + modal: Modal, + confirmLabel: string, + cancel: () => void, + submit: () => void, +): void { + const footer = modalFooter(modal); + new ButtonComponent(footer).setButtonText("Cancel").onClick(cancel); + new ButtonComponent(footer) + .setButtonText(confirmLabel) + .setCta() + .onClick(submit); +} + +export function askPassphrase(app: App): Promise { + return openPromiseModal((answer) => { + const { modal, finish } = openFrame( + app, + answer, + { icon: "lock", title: "MDSync passphrase" }, + "Enter the encryption passphrase for this vault. It is never sent to the remote storage.", + ); + let value = ""; + const submit = (): void => { + if (!value) { + error.setText("Enter the passphrase, or cancel."); + return; + } + finish(value); + }; + passwordField(modal, "Passphrase", (v) => (value = v), submit); + const error = alertLine(modal.contentEl); + cancelAndConfirm(modal, "Continue", () => finish(null), submit); + return modal; + }, null); +} + +export function askNewPassphrase(app: App): Promise { + return openPromiseModal((answer) => { + const { modal, finish } = openFrame( + app, + answer, + { icon: "key-round", title: "Change passphrase" }, + "Re-wraps the vault's data key under a new passphrase. Your notes are not re-encrypted, so this is instant. Every device must switch to the new passphrase afterwards.", + ); + let next = ""; + let confirm = ""; + const submit = (): void => { + const problem = + weakPassphrase(next) ?? + (next === confirm ? null : "Passphrases do not match."); + if (problem) { + error.setText(problem); + error.hidden = false; + return; + } + finish(next); + }; + passwordField( + modal, + "New passphrase", + (v) => (next = v), + () => (next ? confirmField.focus() : submit()), + ); + const confirmField = passwordField( + modal, + "Confirm passphrase", + (v) => (confirm = v), + submit, + ); + const error = alertLine(modal.contentEl); + error.hidden = true; + cancelAndConfirm(modal, "Change", () => finish(null), submit); + return modal; + }, null); +} diff --git a/packages/plugin/src/ui/modals/promise-modal.ts b/packages/plugin/src/core/ui/modals/promise-modal.ts similarity index 100% rename from packages/plugin/src/ui/modals/promise-modal.ts rename to packages/plugin/src/core/ui/modals/promise-modal.ts diff --git a/packages/plugin/src/ui/modals/prompt-modal.ts b/packages/plugin/src/core/ui/modals/prompt-modal.ts similarity index 94% rename from packages/plugin/src/ui/modals/prompt-modal.ts rename to packages/plugin/src/core/ui/modals/prompt-modal.ts index d1e0fd36..f867ee0a 100644 --- a/packages/plugin/src/ui/modals/prompt-modal.ts +++ b/packages/plugin/src/core/ui/modals/prompt-modal.ts @@ -1,6 +1,6 @@ import { type App, ButtonComponent, Modal } from "obsidian"; - -import { modalFooter, onEnter, renderModalHead } from "@/ui/common"; +import { onEnter } from "../input/enter-key"; +import { modalFooter, renderModalHead } from "../modal-frame"; import { openPromiseModal } from "./promise-modal"; diff --git a/packages/plugin/src/ui/common/notices.ts b/packages/plugin/src/core/ui/notices.ts similarity index 79% rename from packages/plugin/src/ui/common/notices.ts rename to packages/plugin/src/core/ui/notices.ts index 23ca4529..84d7088c 100644 --- a/packages/plugin/src/ui/common/notices.ts +++ b/packages/plugin/src/core/ui/notices.ts @@ -1,9 +1,9 @@ import { ButtonComponent, Notice } from "obsidian"; -import { errorMessage } from "@/shared"; -import type { SyncOperationResult } from "@/sync/controller"; +import { errorMessage } from "@/core/shared"; const NOTICE_DURATION_MS = 8000; +const TIP_MS = 4000; export function notifyError(messagePrompt: string, err?: unknown): void { const details = err === undefined ? "" : ` - ${errorMessage(err)}`; @@ -33,6 +33,15 @@ export function notifyAction( }); } +/** A phone has no hover: a tap shows the element's tooltip as a notice, the newest replacing the last. */ +export function tapTooltip(): (el: Element) => void { + let tip: Notice | null = null; + return (el) => { + tip?.hide(); + tip = new Notice(el.getAttribute("aria-label") ?? "", TIP_MS); + }; +} + /** Shows a caught error as a notice and logs the original to the console. */ export function reportError(err: unknown): void { notifyError(errorMessage(err)); @@ -44,7 +53,9 @@ export function attempt(task: Promise, failureLabel: string): void { } export async function runWithNotice( - action: () => Promise | Promise, + action: () => + | Promise + | Promise, successMessage: string, failureLabel = "Operation failed", ): Promise { diff --git a/packages/plugin/src/core/ui/observe-resize.ts b/packages/plugin/src/core/ui/observe-resize.ts new file mode 100644 index 00000000..d79b086a --- /dev/null +++ b/packages/plugin/src/core/ui/observe-resize.ts @@ -0,0 +1,18 @@ +/** An observer never reports another window's element, so it comes from the element's own and is rebuilt when Obsidian moves the tab to a popout. */ +export function observeResize( + el: HTMLElement, + onResize: () => void, +): () => void { + let observer: ResizeObserver | null = null; + const bind = (): void => { + observer?.disconnect(); + observer = new (el.win as typeof window).ResizeObserver(onResize); + observer.observe(el); + }; + bind(); + const unmigrated = el.onWindowMigrated(bind); + return () => { + unmigrated(); + observer?.disconnect(); + }; +} diff --git a/packages/plugin/src/ui/common/obsidian-helpers.ts b/packages/plugin/src/core/ui/obsidian-helpers.ts similarity index 75% rename from packages/plugin/src/ui/common/obsidian-helpers.ts rename to packages/plugin/src/core/ui/obsidian-helpers.ts index 1c4bb20b..5b1ee2ed 100644 --- a/packages/plugin/src/ui/common/obsidian-helpers.ts +++ b/packages/plugin/src/core/ui/obsidian-helpers.ts @@ -1,6 +1,23 @@ import { type App, TFile, type View } from "obsidian"; +import { PLUGIN_ID } from "@/core/constants"; import { notifyInfo } from "./notices"; +interface SettingsDialog { + open(): void; + close(): void; + openTabById(id: string): void; +} + +export function openPluginSettings(app: App): void { + const { setting } = app as App & { setting?: SettingsDialog }; + setting?.open(); + setting?.openTabById(PLUGIN_ID); +} + +export function closePluginSettings(app: App): void { + (app as App & { setting?: SettingsDialog }).setting?.close(); +} + interface FileExplorerReveal extends View { revealInFolder?: (file: unknown) => void; } diff --git a/packages/plugin/src/ui/common/open-note.ts b/packages/plugin/src/core/ui/open-note.ts similarity index 100% rename from packages/plugin/src/ui/common/open-note.ts rename to packages/plugin/src/core/ui/open-note.ts diff --git a/packages/plugin/src/ui/common/phone-change.ts b/packages/plugin/src/core/ui/phone-change.ts similarity index 100% rename from packages/plugin/src/ui/common/phone-change.ts rename to packages/plugin/src/core/ui/phone-change.ts diff --git a/packages/plugin/src/ui/common/serial.ts b/packages/plugin/src/core/ui/serial.ts similarity index 100% rename from packages/plugin/src/ui/common/serial.ts rename to packages/plugin/src/core/ui/serial.ts diff --git a/packages/plugin/src/styles/base/callout.css b/packages/plugin/src/core/ui/styles/callout.css similarity index 100% rename from packages/plugin/src/styles/base/callout.css rename to packages/plugin/src/core/ui/styles/callout.css diff --git a/packages/plugin/src/styles/base/file-path.css b/packages/plugin/src/core/ui/styles/file-path.css similarity index 100% rename from packages/plugin/src/styles/base/file-path.css rename to packages/plugin/src/core/ui/styles/file-path.css diff --git a/packages/plugin/src/styles/base/icon-button.css b/packages/plugin/src/core/ui/styles/icon-button.css similarity index 100% rename from packages/plugin/src/styles/base/icon-button.css rename to packages/plugin/src/core/ui/styles/icon-button.css diff --git a/packages/plugin/src/styles/base/marquee.css b/packages/plugin/src/core/ui/styles/marquee.css similarity index 100% rename from packages/plugin/src/styles/base/marquee.css rename to packages/plugin/src/core/ui/styles/marquee.css diff --git a/packages/plugin/src/styles/mobile.css b/packages/plugin/src/core/ui/styles/mobile.css similarity index 100% rename from packages/plugin/src/styles/mobile.css rename to packages/plugin/src/core/ui/styles/mobile.css diff --git a/packages/plugin/src/styles/modal-frame.css b/packages/plugin/src/core/ui/styles/modal-frame.css similarity index 96% rename from packages/plugin/src/styles/modal-frame.css rename to packages/plugin/src/core/ui/styles/modal-frame.css index b7832f88..548d340d 100644 --- a/packages/plugin/src/styles/modal-frame.css +++ b/packages/plugin/src/core/ui/styles/modal-frame.css @@ -253,6 +253,13 @@ body.is-phone .mdsync-drawer :is(.modal-close-button, .modal-header-button) { display: none; } +/* Obsidian keeps a phone title clear of header buttons a sheet does not show. */ +body.is-phone .modal.mdsync-drawer .mdsync-modal-head { + flex: 1 1 auto; + max-width: none; + padding-inline-end: 0; +} + body.is-phone .modal.mdsync-modal { .mdsync-modal-footer { margin-bottom: 0; diff --git a/packages/plugin/src/styles/modals.css b/packages/plugin/src/core/ui/styles/modals.css similarity index 100% rename from packages/plugin/src/styles/modals.css rename to packages/plugin/src/core/ui/styles/modals.css diff --git a/packages/plugin/src/styles/base/notice.css b/packages/plugin/src/core/ui/styles/notice.css similarity index 100% rename from packages/plugin/src/styles/base/notice.css rename to packages/plugin/src/core/ui/styles/notice.css diff --git a/packages/plugin/src/styles/base/segments.css b/packages/plugin/src/core/ui/styles/segments.css similarity index 100% rename from packages/plugin/src/styles/base/segments.css rename to packages/plugin/src/core/ui/styles/segments.css diff --git a/packages/plugin/src/styles/tokens.css b/packages/plugin/src/core/ui/styles/tokens.css similarity index 69% rename from packages/plugin/src/styles/tokens.css rename to packages/plugin/src/core/ui/styles/tokens.css index ef822066..95fe576f 100644 --- a/packages/plugin/src/styles/tokens.css +++ b/packages/plugin/src/core/ui/styles/tokens.css @@ -1,5 +1,5 @@ /* - * MDSync's own design tokens: only values Obsidian has no variable for. + * MDSync's own design tokens: only values Obsidian has no variable for, plus the change-state palette. * Spacing uses Obsidian's 4px grid directly; a parallel scale would duplicate a source of truth we do not own. */ @@ -29,6 +29,25 @@ body.is-mobile { --mdsync-status-bar-clearance: 0px; } +/* Change states, one palette in every view whatever the theme's accents; `-rgb` for tints. */ +body.theme-dark { + --mdsync-added-rgb: 68, 207, 110; + --mdsync-modified-rgb: 233, 151, 63; + --mdsync-deleted-rgb: 255, 138, 142; +} + +body.theme-light { + --mdsync-added-rgb: 26, 127, 55; + --mdsync-modified-rgb: 188, 76, 0; + --mdsync-deleted-rgb: 207, 34, 46; +} + +body { + --mdsync-added: rgb(var(--mdsync-added-rgb)); + --mdsync-modified: rgb(var(--mdsync-modified-rgb)); + --mdsync-deleted: rgb(var(--mdsync-deleted-rgb)); +} + /* * Set from TypeScript, listed so a reader knows the contract exists: * --mdsync-depth tree indent level source-control/change-rows.ts diff --git a/packages/plugin/src/core/ui/styles/utilities.css b/packages/plugin/src/core/ui/styles/utilities.css new file mode 100644 index 00000000..3ba1103b --- /dev/null +++ b/packages/plugin/src/core/ui/styles/utilities.css @@ -0,0 +1,20 @@ +.mdsync-status-spinner { + display: inline-block; + width: 0.75rem; + height: 0.75rem; + border: 2px solid var(--background-modifier-border); + border-top-color: var(--interactive-accent); + border-radius: 50%; + animation: mdsync-spin 0.65s linear infinite; +} + +@keyframes mdsync-spin { + to { + transform: rotate(360deg); + } +} + +.mdsync-status-spinner.mdsync-hidden, +.mdsync-hidden { + display: none; +} diff --git a/packages/plugin/src/utils/base64.ts b/packages/plugin/src/core/utils/base64.ts similarity index 85% rename from packages/plugin/src/utils/base64.ts rename to packages/plugin/src/core/utils/base64.ts index 38e0b6b3..802411c1 100644 --- a/packages/plugin/src/utils/base64.ts +++ b/packages/plugin/src/core/utils/base64.ts @@ -1,3 +1,5 @@ +export { toBase64Url as bytesToBase64Url } from "@mdsync/protocol"; + const BTOA_CHUNK_SIZE = 0x8000; export function bytesToBase64(bytes: Uint8Array): string { @@ -18,13 +20,6 @@ export function base64ToBytes(value: string): Uint8Array { return bytes; } -export function bytesToBase64Url(bytes: Uint8Array): string { - return bytesToBase64(bytes) - .replace(/\+/g, "-") - .replace(/\//g, "_") - .replace(/=+$/g, ""); -} - export function base64UrlToBytes(value: string): Uint8Array { // Strip non-base64url first: a pasted trailing newline would pad to an invalid length and throw. const normalized = value diff --git a/packages/plugin/src/utils/bytes.ts b/packages/plugin/src/core/utils/bytes.ts similarity index 100% rename from packages/plugin/src/utils/bytes.ts rename to packages/plugin/src/core/utils/bytes.ts diff --git a/packages/plugin/src/utils/compress.ts b/packages/plugin/src/core/utils/compress.ts similarity index 100% rename from packages/plugin/src/utils/compress.ts rename to packages/plugin/src/core/utils/compress.ts diff --git a/packages/plugin/src/utils/concurrency.ts b/packages/plugin/src/core/utils/concurrency.ts similarity index 100% rename from packages/plugin/src/utils/concurrency.ts rename to packages/plugin/src/core/utils/concurrency.ts diff --git a/packages/plugin/src/utils/diff.ts b/packages/plugin/src/core/utils/diff.ts similarity index 100% rename from packages/plugin/src/utils/diff.ts rename to packages/plugin/src/core/utils/diff.ts diff --git a/packages/plugin/src/utils/eol.ts b/packages/plugin/src/core/utils/eol.ts similarity index 100% rename from packages/plugin/src/utils/eol.ts rename to packages/plugin/src/core/utils/eol.ts diff --git a/packages/plugin/src/core/utils/index.ts b/packages/plugin/src/core/utils/index.ts new file mode 100644 index 00000000..1b3081f6 --- /dev/null +++ b/packages/plugin/src/core/utils/index.ts @@ -0,0 +1,12 @@ +export { + base64ToBytes, + base64UrlToBytes, + bytesToBase64, + bytesToBase64Url, +} from "./base64"; +export { toArrayBuffer } from "./bytes"; +export { deflateBytes, GZIP, inflateBytes } from "./compress"; +export { runWithConcurrency } from "./concurrency"; +export { changedMiddle, commonEnds, type DiffRange, diffRanges } from "./diff"; +export { eolOf, toLf, withEolOf } from "./eol"; +export { isNewer, type Revised } from "./revision"; diff --git a/packages/plugin/src/utils/revision.ts b/packages/plugin/src/core/utils/revision.ts similarity index 100% rename from packages/plugin/src/utils/revision.ts rename to packages/plugin/src/core/utils/revision.ts diff --git a/packages/plugin/src/vault/atomic-write.ts b/packages/plugin/src/core/vault/atomic-write.ts similarity index 100% rename from packages/plugin/src/vault/atomic-write.ts rename to packages/plugin/src/core/vault/atomic-write.ts diff --git a/packages/plugin/src/vault/file-index.ts b/packages/plugin/src/core/vault/file-index.ts similarity index 100% rename from packages/plugin/src/vault/file-index.ts rename to packages/plugin/src/core/vault/file-index.ts diff --git a/packages/plugin/src/core/vault/index.ts b/packages/plugin/src/core/vault/index.ts new file mode 100644 index 00000000..e1ea7c25 --- /dev/null +++ b/packages/plugin/src/core/vault/index.ts @@ -0,0 +1,28 @@ +export { writeAtomic } from "./atomic-write"; +export { + createVaultIndex, + type IndexedFile, + type IndexedFolder, + renameInVault, + type VaultIndex, +} from "./file-index"; +export { + caseInsensitiveDisk, + deletePath, + diskRefuses, + ensureDir, + ensureParent, + isRecaseStep, + readBinary, + removeEmptyDir, + renameCaseSafe, + StrandedRenameError, + trashPath, + unchangedSince, + writeBinary, +} from "./io"; +export { + createSymlinkDetector, + loadNodeFs, + type SymlinkDetector, +} from "./symlinks"; diff --git a/packages/plugin/src/vault/io.ts b/packages/plugin/src/core/vault/io.ts similarity index 98% rename from packages/plugin/src/vault/io.ts rename to packages/plugin/src/core/vault/io.ts index 38528839..45dd9c80 100644 --- a/packages/plugin/src/vault/io.ts +++ b/packages/plugin/src/core/vault/io.ts @@ -1,7 +1,7 @@ import { type DataAdapter, Platform } from "obsidian"; -import { errorMessage, hasReservedChar } from "@/shared"; -import { toArrayBuffer } from "@/utils"; +import { errorMessage, hasReservedChar } from "@/core/shared"; +import { toArrayBuffer } from "@/core/utils"; /** * Folders {@link writeBinary} already wrote into: a 20k-file pull otherwise pays 60k `exists` round trips. diff --git a/packages/plugin/src/vault/symlinks.ts b/packages/plugin/src/core/vault/symlinks.ts similarity index 100% rename from packages/plugin/src/vault/symlinks.ts rename to packages/plugin/src/core/vault/symlinks.ts diff --git a/packages/plugin/src/crypto/live-keys.ts b/packages/plugin/src/crypto/live-keys.ts deleted file mode 100644 index 4332e6c4..00000000 --- a/packages/plugin/src/crypto/live-keys.ts +++ /dev/null @@ -1,48 +0,0 @@ -/** - * One key per live-layer purpose, derived where the raw data key is unwrapped, since the content key is - * non-extractable. - */ - -export interface LiveKeys { - /** AES-GCM-256 over every live frame the hub stores or forwards. */ - frames: CryptoKey; - /** HMAC-SHA-256 naming documents, so the hub never learns a path. */ - docIds: CryptoKey; -} - -const FRAMES_INFO = "mdsync/live/frames/v1"; -const DOC_IDS_INFO = "mdsync/live/doc-ids/v1"; - -export async function deriveLiveKeys(dataKey: Uint8Array): Promise { - const subtle = window.crypto.subtle; - const material = await subtle.importKey( - "raw", - dataKey as BufferSource, - "HKDF", - false, - ["deriveKey"], - ); - const purpose = (info: string): HkdfParams => ({ - name: "HKDF", - hash: "SHA-256", - // The data key is uniformly random, so HKDF needs no salt to extract. - salt: new Uint8Array(), - info: new TextEncoder().encode(info), - }); - return { - frames: await subtle.deriveKey( - purpose(FRAMES_INFO), - material, - { name: "AES-GCM", length: 256 }, - false, - ["encrypt", "decrypt"], - ), - docIds: await subtle.deriveKey( - purpose(DOC_IDS_INFO), - material, - { name: "HMAC", hash: "SHA-256", length: 256 }, - false, - ["sign"], - ), - }; -} diff --git a/packages/plugin/src/drawing/index.ts b/packages/plugin/src/drawing/index.ts deleted file mode 100644 index 27ecef40..00000000 --- a/packages/plugin/src/drawing/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -export { - type Drawing, - isDrawing, - isElement, - readDrawing, - type Scene, - type SceneElement, - withScene, -} from "./format"; -export { mergeDrawings, mergeElements, wins } from "./merge"; -export { sceneOf, sceneOfBytes, stamp } from "./scene"; diff --git a/packages/plugin/src/editor/signs/index.ts b/packages/plugin/src/editor/signs/index.ts deleted file mode 100644 index 79d4d900..00000000 --- a/packages/plugin/src/editor/signs/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { registerEditorSigns, type SignsHandle } from "./integration"; diff --git a/packages/plugin/src/ui/diff/action-bar.ts b/packages/plugin/src/features/diff/action-bar.ts similarity index 97% rename from packages/plugin/src/ui/diff/action-bar.ts rename to packages/plugin/src/features/diff/action-bar.ts index 6f1ba694..28dd078b 100644 --- a/packages/plugin/src/ui/diff/action-bar.ts +++ b/packages/plugin/src/features/diff/action-bar.ts @@ -1,5 +1,5 @@ import { ButtonComponent } from "obsidian"; -import { EDiffDirection } from "@/sync/projection"; +import { EDiffDirection } from "@/features/sync"; import type { DiffHeaderActions, DiffHeaderState } from "./header"; /** Between the bar and the panes: what Apply will do, why per-change actions are off, whole-file actions. */ @@ -35,6 +35,8 @@ export function renderActionBar( .setButtonText("Keep both versions") .onClick(actions.keepBothVersions); } + } + if (state.mergeable) { new ButtonComponent(buttons) .setButtonText("Merge…") .setCta() diff --git a/packages/plugin/src/ui/diff/choices.ts b/packages/plugin/src/features/diff/choices.ts similarity index 96% rename from packages/plugin/src/ui/diff/choices.ts rename to packages/plugin/src/features/diff/choices.ts index 79651de0..9864e344 100644 --- a/packages/plugin/src/ui/diff/choices.ts +++ b/packages/plugin/src/features/diff/choices.ts @@ -1,5 +1,5 @@ -import type { HunkSelection } from "@/sync/hunks"; -import { EDiffDirection } from "@/sync/projection"; +import type { HunkSelection } from "@/features/sync"; +import { EDiffDirection } from "@/features/sync"; import type { RailAction } from "./rail"; export const EChoiceKind = { diff --git a/packages/plugin/src/ui/diff/binary-view.ts b/packages/plugin/src/features/diff/compare/binary-view.ts similarity index 89% rename from packages/plugin/src/ui/diff/binary-view.ts rename to packages/plugin/src/features/diff/compare/binary-view.ts index a3326fce..16f4dadc 100644 --- a/packages/plugin/src/ui/diff/binary-view.ts +++ b/packages/plugin/src/features/diff/compare/binary-view.ts @@ -1,5 +1,5 @@ -import { formatBytes } from "@/shared"; -import type { FileDiffModel } from "@/sync/projection"; +import { formatBytes } from "@/core/shared"; +import type { FileDiffModel } from "@/features/sync"; export function renderBinaryDiff( parent: HTMLElement, diff --git a/packages/plugin/src/ui/diff/compare-controls.ts b/packages/plugin/src/features/diff/compare/compare-controls.ts similarity index 70% rename from packages/plugin/src/ui/diff/compare-controls.ts rename to packages/plugin/src/features/diff/compare/compare-controls.ts index 9d07fead..7aad05d8 100644 --- a/packages/plugin/src/ui/diff/compare-controls.ts +++ b/packages/plugin/src/features/diff/compare/compare-controls.ts @@ -1,15 +1,15 @@ import { ButtonComponent, setIcon } from "obsidian"; -import type { EDiffDirection } from "@/sync/projection"; -import { appendIconButton } from "@/ui/common"; +import { appendIconButton } from "@/core/ui"; +import { EDiffDirection } from "@/features/sync"; import { CHOICE_ICON, choiceVerb, EChoiceKind, type HunkChoices, -} from "./choices"; -import type { PanelHosts } from "./header"; -import { renderChangeNav } from "./rail"; -import { renderCounters } from "./source-widget"; +} from "../choices"; +import type { PanelHosts } from "../header"; +import { type LineCounters, renderCounters } from "../lines/source-widget"; +import { renderChangeNav } from "../rail"; const CONTEXT: Record = { local: "since the last sync", @@ -24,6 +24,18 @@ const HINT: Record = { conflict: "Select a change to accept it, or settle the whole file.", history: "Select a change to restore it. Nothing changes until you apply.", }; +const NO_MERGE_HINT = + "No earlier version to merge from: select a change to accept it, or settle the whole file."; + +export interface CompareControlsOptions { + direction: EDiffDirection; + actionable: boolean; + /** A conflict **Merge…** can open; one that cannot says why. */ + mergeable: boolean; + choices: HunkChoices; + discard(): void; + apply(): void; +} /** Detached panel-owned content survives shell re-renders. */ export class CompareControls { @@ -34,12 +46,20 @@ export class CompareControls { null; private pin: HTMLButtonElement | null = null; + constructor(private readonly options: CompareControlsOptions) {} + mount(hosts: PanelHosts): void { hosts.info.appendChild(this.info); hosts.controls.appendChild(this.controls); hosts.pending.appendChild(this.pending); } + remove(): void { + this.info.remove(); + this.controls.remove(); + this.pending.remove(); + } + /** Keeps the buttons of chosen changes on the strip; off leaves only the selected change's. */ pinToggle(enabled: boolean, change: (enabled: boolean) => void): void { const pin = appendIconButton( @@ -69,20 +89,15 @@ export class CompareControls { this.showPosition = renderChangeNav(this.controls, jump); } - update( - counts: { - added: number; - removed: number; - changes: number; - current: number; - }, - direction: EDiffDirection, - actionable: boolean, - choices: HunkChoices, - discard: () => void, - apply: () => void, - ): void { - const { added, removed, changes, current } = counts; + update(segments: readonly LineCounters[], current: number): void { + const { direction, actionable, mergeable, choices } = this.options; + let added = 0; + let removed = 0; + for (const segment of segments) { + added += segment.added; + removed += segment.removed; + } + const changes = segments.length; const changeText = `${changes} ${changes === 1 ? "change" : "changes"}`; this.info.empty(); renderCounters(this.info, { added, removed }); @@ -105,7 +120,10 @@ export class CompareControls { if (actionable) this.pending.createSpan({ cls: "mdsync-diff-hint", - text: HINT[direction], + text: + direction === EDiffDirection.Conflict && !mergeable + ? NO_MERGE_HINT + : HINT[direction], }); if (choices.size === 0) return; const buttons = this.pending.createDiv({ @@ -113,12 +131,12 @@ export class CompareControls { }); new ButtonComponent(buttons) .setButtonText("Discard choices") - .onClick(discard); + .onClick(() => this.options.discard()); new ButtonComponent(buttons) .setButtonText( `Apply ${choices.size} ${choices.size === 1 ? "change" : "changes"}`, ) .setCta() - .onClick(apply); + .onClick(() => this.options.apply()); } } diff --git a/packages/plugin/src/ui/diff/compare-decorations.ts b/packages/plugin/src/features/diff/compare/compare-decorations.ts similarity index 91% rename from packages/plugin/src/ui/diff/compare-decorations.ts rename to packages/plugin/src/features/diff/compare/compare-decorations.ts index 6eda3b24..da99fc3b 100644 --- a/packages/plugin/src/ui/diff/compare-decorations.ts +++ b/packages/plugin/src/features/diff/compare/compare-decorations.ts @@ -11,22 +11,26 @@ import { type ViewUpdate, WidgetType, } from "@codemirror/view"; -import { hunkSegments, type LineRange } from "@/sync/hunks"; -import type { Span } from "@/sync/merge-model"; -import type { EDiffDirection, FileDiffModel } from "@/sync/projection"; -import { choiceVerb, type HunkChoices } from "./choices"; -import { addCodeMarks, type LineMarks, lineMarks } from "./code-lines"; +import type { EDiffDirection, FileDiffModel, Span } from "@/features/sync"; +import { hunkSegments, type LineRange } from "@/features/sync"; +import { choiceVerb, type HunkChoices } from "../choices"; +import { combinedModeField } from "../layout-mode"; +import { addCodeMarks, type LineMarks, lineMarks } from "../lines/code-lines"; import { addUnchangedGaps, gapGutter, gapRow, numberUnchangedLines, -} from "./gap-widgets"; -import { forEachVisibleRange, rangeLabel, sideSpan } from "./geometry"; -import { markLine, type Tints, tintLine, viewportTints } from "./line-tints"; -import { combinedModeField } from "./merge-decorations"; -import type { RailAction } from "./rail"; -import { type SourceBlock, SourceBlockWidget } from "./source-widget"; +} from "../lines/gap-widgets"; +import { forEachVisibleRange, rangeLabel, sideSpan } from "../lines/geometry"; +import { + markLine, + type Tints, + tintLine, + viewportTints, +} from "../lines/line-tints"; +import { type SourceBlock, SourceBlockWidget } from "../lines/source-widget"; +import type { RailAction } from "../rail"; export type CompareSide = "left" | "right"; @@ -315,14 +319,21 @@ function changeCard( const where = `${to - from > 1 ? "Lines" : "Line"} ${rangeLabel(from + 1, to)}`; const actions = config.combined.actions(segment); const kind = segmentKind(segment); + const counters = { added: segment.added, removed: segment.removed }; return { key: String(segment.key), tone: "removed", head: chosen === undefined - ? { mark: kind, text: `${where} · ${KIND_TEXT[kind]}`, actions } + ? { + mark: kind, + text: `${where} · ${KIND_TEXT[kind]}`, + counters, + actions, + } : { mark: "chosen", + counters, // Regular verbs: push, revert, pull, accept, restore. text: `${where} · will be ${choiceVerb(config.combined.direction, chosen).replace(/e?$/, "ed")}`, actions: actions diff --git a/packages/plugin/src/ui/diff/compare-panel.ts b/packages/plugin/src/features/diff/compare/compare-panel.ts similarity index 88% rename from packages/plugin/src/ui/diff/compare-panel.ts rename to packages/plugin/src/features/diff/compare/compare-panel.ts index 95d82266..5a120687 100644 --- a/packages/plugin/src/ui/diff/compare-panel.ts +++ b/packages/plugin/src/features/diff/compare/compare-panel.ts @@ -1,8 +1,30 @@ import { EditorState } from "@codemirror/state"; import { EditorView, lineNumbers } from "@codemirror/view"; -import { EDiffDirection, type FileDiffModel } from "@/sync/projection"; -import { ChangeOverlay } from "./change-overlay"; -import { choiceActions, type EChoiceKind, HunkChoices } from "./choices"; +import { EDiffDirection, type FileDiffModel } from "@/features/sync"; +import { choiceActions, type EChoiceKind, HunkChoices } from "../choices"; +import type { PanelHosts } from "../header"; +import { LayoutMode, setCombinedMode } from "../layout-mode"; +import { + LineWrappingControl, + type LineWrappingOptions, +} from "../line-wrapping-control"; +import { ChangeOverlay } from "../lines/change-overlay"; +import { Divider, type DividerItem } from "../lines/divider"; +import { followWindow } from "../lines/follow-window"; +import { foldedBands } from "../lines/gap-widgets"; +import { + sideSpan, + spanBounds, + updatePaneViewportWidth, +} from "../lines/geometry"; +import { PanelSearch } from "../lines/pane-search"; +import { + NO_ANCHORS, + PaneScrollSync, + type ScrollAnchors, + spanAnchors, +} from "../lines/scroll-sync"; +import { changeNavigation, type RailAction, stepIndex } from "../rail"; import { CompareControls } from "./compare-controls"; import { buildSegments, @@ -12,27 +34,11 @@ import { segmentKind, segmentsChanged, } from "./compare-decorations"; -import { Divider, type DividerItem } from "./divider"; -import { foldedBands } from "./gap-widgets"; -import { sideSpan, spanBounds, updatePaneViewportWidth } from "./geometry"; -import type { PanelHosts } from "./header"; -import { LayoutMode } from "./layout-mode"; -import { - LineWrappingControl, - type LineWrappingOptions, -} from "./line-wrapping-control"; -import { setCombinedMode } from "./merge-decorations"; -import { changeNavigation, type RailAction } from "./rail"; -import { - NO_ANCHORS, - PaneScrollSync, - type ScrollAnchors, - spanAnchors, -} from "./scroll-sync"; export interface ComparePanelOptions extends LineWrappingOptions { direction: EDiffDirection; actionable: boolean; + mergeable: boolean; pinChosen: boolean; onPinChosenChange(enabled: boolean): void; onApply(choices: HunkChoices): void; @@ -63,7 +69,10 @@ export function renderTextDiff( * carries all picks out. */ export class ComparePanel { - private readonly choices = new HunkChoices(); + readonly choices = new HunkChoices(); + readonly search = new PanelSearch("right", () => + this.unfoldAll(), + ); /** Keys of the segments folded to one row in both panes. */ private readonly folded = new Set(); /** Unchanged runs opened in both panes, by index. */ @@ -187,9 +196,7 @@ export class ComparePanel { this.leftView = null; this.rightView = null; this.rootEl = null; - this.controls?.info.remove(); - this.controls?.controls.remove(); - this.controls?.pending.remove(); + this.controls?.remove(); this.controls = null; this.current = -1; this.choices.clear(); @@ -221,10 +228,11 @@ export class ComparePanel { side: CompareSide, first: boolean, ): EditorView { - heads.createDiv({ + const head = heads.createDiv({ cls: `mdsync-compare-head is-${side}`, text: side === "left" ? model.leftLabel : model.rightLabel, }); + this.search.appendToggle(head, side); const host = body.createDiv({ cls: `mdsync-compare-host is-${side}${first ? " is-first" : ""}`, }); @@ -266,6 +274,8 @@ export class ComparePanel { }, }), lineNumbers(), + followWindow(parent), + this.search.extension(side), EditorView.domEventHandlers({ // A click on a change's lines selects it, as one on its connector does. click: (event, view) => { @@ -373,7 +383,14 @@ export class ComparePanel { } private renderToolbar(root: HTMLElement): void { - this.controls = new CompareControls(); + this.controls = new CompareControls({ + ...this.options, + choices: this.choices, + discard: () => this.discardChoices(), + apply: () => { + if (this.choices.size > 0) this.options.onApply(this.choices); + }, + }); const toolbar = this.controls.controls; this.layoutMode = new LayoutMode(root, toolbar, (combined, changed) => { if (changed) { @@ -382,6 +399,7 @@ export class ComparePanel { } } this.controls?.showPin(!combined); + this.search.setInline(combined); this.scheduleLayout(); }); this.wrapping.mount(toolbar); @@ -393,25 +411,20 @@ export class ComparePanel { }); } this.controls.navigation((delta) => this.jump(delta)); + this.search.appendInlineToggle(toolbar); } - private updateToolbar(): void { - let added = 0; - let removed = 0; - for (const segment of this.segments) { - added += segment.added; - removed += segment.removed; + /** Search reads every line: folded runs and changes open. */ + private unfoldAll(): void { + this.folded.clear(); + for (let index = 0; index <= this.segments.length; index++) { + this.opened.add(index); } - this.controls?.update( - { added, removed, changes: this.segments.length, current: this.current }, - this.options.direction, - this.options.actionable, - this.choices, - () => this.discardChoices(), - () => { - if (this.choices.size > 0) this.options.onApply(this.choices); - }, - ); + this.redrawSegments(); + } + + private updateToolbar(): void { + this.controls?.update(this.segments, this.current); } private discardChoices(): void { @@ -443,7 +456,8 @@ export class ComparePanel { } private jump(delta: number): void { - const segment = this.segments[this.nextIndex(delta)]; + this.current = stepIndex(this.current, delta, this.segments.length); + const segment = this.segments[this.current]; if (!segment) return; this.divider?.select(segment.key); this.updateToolbar(); @@ -469,18 +483,6 @@ export class ComparePanel { }); } - private nextIndex(delta: number): number { - const count = this.segments.length; - if (count === 0) return -1; - this.current = - this.current < 0 - ? delta > 0 - ? 0 - : count - 1 - : (this.current + delta + count) % count; - return this.current; - } - private scheduleLayout(): void { if (this.layoutFrame !== null) return; this.layoutFrame = window.requestAnimationFrame(() => { diff --git a/packages/plugin/src/ui/diff/hunk-renderer.ts b/packages/plugin/src/features/diff/compare/hunk-renderer.ts similarity index 88% rename from packages/plugin/src/ui/diff/hunk-renderer.ts rename to packages/plugin/src/features/diff/compare/hunk-renderer.ts index 6c04f1b8..6ecf6d12 100644 --- a/packages/plugin/src/ui/diff/hunk-renderer.ts +++ b/packages/plugin/src/features/diff/compare/hunk-renderer.ts @@ -1,6 +1,6 @@ -import type { SyncHunk } from "@/sync/hunks"; -import { renderCodeLine } from "./code-lines"; -import { renderCounters } from "./source-widget"; +import type { SyncHunk } from "@/features/sync"; +import { renderCodeLine } from "../lines/code-lines"; +import { renderCounters } from "../lines/source-widget"; /** Read-only hunk preview for restore confirmations; lines are numbered by the side they belong to. */ export function renderHunkPreview( diff --git a/packages/plugin/src/ui/diff/file-navigation.ts b/packages/plugin/src/features/diff/file-navigation.ts similarity index 95% rename from packages/plugin/src/ui/diff/file-navigation.ts rename to packages/plugin/src/features/diff/file-navigation.ts index 2fcf1981..f83f9526 100644 --- a/packages/plugin/src/ui/diff/file-navigation.ts +++ b/packages/plugin/src/features/diff/file-navigation.ts @@ -1,4 +1,4 @@ -import type { DiffResult } from "@/sync/types"; +import type { DiffResult } from "@/features/sync"; export interface FilePosition { index: number; diff --git a/packages/plugin/src/ui/diff/header.ts b/packages/plugin/src/features/diff/header.ts similarity index 90% rename from packages/plugin/src/ui/diff/header.ts rename to packages/plugin/src/features/diff/header.ts index 7e5e4980..99f44ee6 100644 --- a/packages/plugin/src/ui/diff/header.ts +++ b/packages/plugin/src/features/diff/header.ts @@ -1,15 +1,15 @@ import { ButtonComponent, Platform } from "obsidian"; -import type { - EDiffDirection, - FileDiffModel, - HistoryVersionRef, -} from "@/sync/projection"; import { appendIconButton, measureSlide, renderPath, slideWhenCut, -} from "@/ui/common"; +} from "@/core/ui"; +import { + EDiffDirection, + type FileDiffModel, + type HistoryVersionRef, +} from "@/features/sync"; import { renderActionBar } from "./action-bar"; import { type FilePosition, getFilePosition } from "./file-navigation"; import { type HistoryChange, hunkHintText } from "./history-state"; @@ -20,6 +20,8 @@ export interface DiffHeaderState { isBinary: boolean; /** A remote deletion leaves no version to keep beside the local one. */ remotePresent: boolean; + /** A conflict whose two versions grew from one earlier, readable version. */ + mergeable: boolean; isEditing: boolean; position: FilePosition | null; /** Names the side a history restore would take, when that is ambiguous. */ @@ -82,6 +84,7 @@ export function renderDiffFrame( direction: model?.direction ?? null, isBinary: model?.isBinary ?? false, remotePresent: model?.rightPresent ?? false, + mergeable: isMergeable(model), isEditing, position: getFilePosition(paths, path), restoreLabel: against ? `Restore ${historyLabel}` : "Restore this version", @@ -121,7 +124,7 @@ export function refitDiffTitle(root: HTMLElement): void { if (name) measureSlide(name); } -export function renderDiffHeader( +function renderDiffHeader( parent: HTMLElement, state: DiffHeaderState, actions: DiffHeaderActions, @@ -194,3 +197,12 @@ function renderResolution( .setCta() .onClick(actions.saveResolution).buttonEl; } + +/** Merge needs the version both sides started from: none for a file added on both, or one that is not text. */ +export function isMergeable(model: FileDiffModel | null): boolean { + return ( + model?.direction === EDiffDirection.Conflict && + !model.isBinary && + model.baseText !== null + ); +} diff --git a/packages/plugin/src/ui/diff/history-state.ts b/packages/plugin/src/features/diff/history-state.ts similarity index 50% rename from packages/plugin/src/ui/diff/history-state.ts rename to packages/plugin/src/features/diff/history-state.ts index ba1ea19b..9f5ce977 100644 --- a/packages/plugin/src/ui/diff/history-state.ts +++ b/packages/plugin/src/features/diff/history-state.ts @@ -1,10 +1,12 @@ -import { HUNK_TEXT_MAX_BYTES } from "@/sync/constants"; +import { DIFF_VIEW_TYPE } from "@/core/constants"; import { EDiffDirection, type FileDiffModel, type HistoryDiffRequest, type HistoryVersionRef, -} from "@/sync/projection"; + HUNK_TEXT_MAX_BYTES, +} from "@/features/sync"; +import type { DiffHost } from "./host"; export interface HistoryChange { before: HistoryVersionRef | null; @@ -21,36 +23,108 @@ export interface DiffViewState { againstLabel?: string; againstSize?: number; historyChange?: HistoryChange; - historyPreviewIfMissing?: boolean; /** Open directly in merge; never stored. */ merge?: boolean; } -export type HistoryMode = "change" | "preview" | "diff"; +export interface HistoryDiffTarget extends HistoryVersionRef { + /** Right side. Without it the version is diffed against the file on disk. */ + against?: { hash: string; label: string; size?: number }; + change?: HistoryChange; +} + +/** `merge` goes straight into the conflict's merge, as the diff's Merge… does. */ +export async function openDiffView( + plugin: DiffHost, + path: string, + history?: HistoryDiffTarget, + merge = false, +): Promise { + const existing = plugin.app.workspace.getLeavesOfType(DIFF_VIEW_TYPE); + const leaf = existing[0] ?? plugin.app.workspace.getLeaf(true); + const state: DiffViewState = { + path, + historyHash: history?.hash, + historyLabel: history?.label, + historySize: history?.size, + againstHash: history?.against?.hash, + againstLabel: history?.against?.label, + againstSize: history?.against?.size, + historyChange: history?.change, + merge: merge || undefined, + }; + await leaf.setViewState({ + type: DIFF_VIEW_TYPE, + active: true, + state: { ...state }, + }); + await plugin.app.workspace.revealLeaf(leaf); +} -export interface HistoryModeInput { +/** What a diff tab shows: a file, or stored versions of it. */ +export interface DiffTarget { + path: string | null; historyHash: string | null; - historyChange: HistoryChange | null; - historyPreviewIfMissing: boolean; + historyLabel: string; + historySize: number | undefined; against: HistoryVersionRef | null; - localExists: boolean; + historyChange: HistoryChange | null; } -export function selectHistoryMode(input: HistoryModeInput): HistoryMode { - if (!input.historyHash) return "diff"; - if (input.historyChange) return "change"; - if (input.against) return "diff"; - if (input.historyPreviewIfMissing && !input.localExists) return "preview"; - return "diff"; +/** A state without a path keeps `path`; every other field it leaves out resets. */ +export function readTarget( + state: DiffViewState, + path: string | null, +): DiffTarget { + return { + path: state.path ?? path, + historyHash: state.historyHash ?? null, + historyLabel: state.historyLabel ?? "Version", + historySize: state.historySize, + against: state.againstHash + ? { + hash: state.againstHash, + label: state.againstLabel ?? "Other version", + size: state.againstSize, + } + : null, + historyChange: state.historyChange ?? null, + }; } -export interface HistoryRequestInput { +export const fileTarget = (path: string | null): DiffTarget => + readTarget({}, path); + +/** History fields are stored too, so a restored workspace keeps a version diff. */ +export function targetState(target: DiffTarget): DiffViewState { + const { path, historyHash, against } = target; + return { + path: path ?? undefined, + historyHash: historyHash ?? undefined, + historyLabel: historyHash ? target.historyLabel : undefined, + historySize: target.historySize, + againstHash: against?.hash, + againstLabel: against?.label, + againstSize: against?.size, + historyChange: target.historyChange ?? undefined, + }; +} + +/** A size alone never reloads; a pin rename changes only the label, which the header reads. */ +export function sameTarget(a: DiffTarget, b: DiffTarget): boolean { + return ( + a.path === b.path && + a.historyHash === b.historyHash && + a.against?.hash === b.against?.hash && + (a.historyHash === null || a.historyLabel === b.historyLabel) && + !changesDiffer(a.historyChange, b.historyChange) + ); +} + +export interface HistoryRequestInput + extends Omit { path: string; historyHash: string; - historyLabel: string; - historySize: number | undefined; - historyChange: HistoryChange | null; - against: HistoryVersionRef | null; forceText: boolean; } diff --git a/packages/plugin/src/features/diff/host.ts b/packages/plugin/src/features/diff/host.ts new file mode 100644 index 00000000..5af43c10 --- /dev/null +++ b/packages/plugin/src/features/diff/host.ts @@ -0,0 +1,9 @@ +import type { App } from "obsidian"; +import type { SyncController } from "@/features/sync"; + +/** What the diff view needs from the plugin. */ +export interface DiffHost { + readonly app: App; + readonly controller: SyncController; + openSourceControl(): Promise; +} diff --git a/packages/plugin/src/features/diff/index.ts b/packages/plugin/src/features/diff/index.ts new file mode 100644 index 00000000..16837ab0 --- /dev/null +++ b/packages/plugin/src/features/diff/index.ts @@ -0,0 +1,8 @@ +export { + type HistoryChange, + type HistoryDiffTarget, + openDiffView, +} from "./history-state"; +export type { DiffHost } from "./host"; +export { confirmBulkRestore, confirmRestore } from "./ui/restore-modal"; +export { type ActiveMerge, DiffView } from "./view"; diff --git a/packages/plugin/src/ui/diff/layout-mode.ts b/packages/plugin/src/features/diff/layout-mode.ts similarity index 65% rename from packages/plugin/src/ui/diff/layout-mode.ts rename to packages/plugin/src/features/diff/layout-mode.ts index 0b7e5e4a..8e2a41a4 100644 --- a/packages/plugin/src/ui/diff/layout-mode.ts +++ b/packages/plugin/src/features/diff/layout-mode.ts @@ -1,12 +1,24 @@ -import { randomId } from "@/crypto"; -import { renderSegments, type Segments } from "@/ui/common"; +import { StateEffect, StateField } from "@codemirror/state"; +import { randomId } from "@/core/crypto"; +import { observeResize, renderSegments, type Segments } from "@/core/ui"; const COMBINED_BELOW_PX = 900; +export const setCombinedMode = StateEffect.define(); +export const combinedModeField = StateField.define({ + create: () => false, + update: (combined, transaction) => { + for (const effect of transaction.effects) { + if (effect.is(setCombinedMode)) return effect.value; + } + return combined; + }, +}); + /** Automatic below a width, or forced from a toolbar button while there is room for both layouts. */ export class LayoutMode { private readonly control: Segments; - private readonly observer: ResizeObserver; + private readonly stopResize: () => void; private forceCombined = false; private current = false; @@ -29,8 +41,7 @@ export class LayoutMode { }, ); this.control.el.addClasses(["is-compact", "mdsync-layout-btn"]); - this.observer = new ResizeObserver(() => this.refresh()); - this.observer.observe(root); + this.stopResize = observeResize(root, () => this.refresh()); } get combined(): boolean { @@ -49,6 +60,6 @@ export class LayoutMode { } destroy(): void { - this.observer.disconnect(); + this.stopResize(); } } diff --git a/packages/plugin/src/ui/diff/line-wrapping-control.ts b/packages/plugin/src/features/diff/line-wrapping-control.ts similarity index 96% rename from packages/plugin/src/ui/diff/line-wrapping-control.ts rename to packages/plugin/src/features/diff/line-wrapping-control.ts index 730990ba..56f174a4 100644 --- a/packages/plugin/src/ui/diff/line-wrapping-control.ts +++ b/packages/plugin/src/features/diff/line-wrapping-control.ts @@ -1,6 +1,6 @@ import { Compartment, type Extension } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; -import { appendIconButton } from "@/ui/common"; +import { appendIconButton } from "@/core/ui"; export interface LineWrappingOptions { lineWrapping: boolean; diff --git a/packages/plugin/src/ui/diff/change-overlay.ts b/packages/plugin/src/features/diff/lines/change-overlay.ts similarity index 82% rename from packages/plugin/src/ui/diff/change-overlay.ts rename to packages/plugin/src/features/diff/lines/change-overlay.ts index db0d43b1..520ab948 100644 --- a/packages/plugin/src/ui/diff/change-overlay.ts +++ b/packages/plugin/src/features/diff/lines/change-overlay.ts @@ -1,8 +1,11 @@ import type { EditorView } from "@codemirror/view"; -import { firstIndex } from "@/utils"; -import type { CompareSegment, CompareSide } from "./compare-decorations"; +import type { + CompareSegment, + CompareSide, +} from "../compare/compare-decorations"; +import { renderRailButton } from "../rail"; import { type Bounds, shiftBounds, sideSpan, spanBounds } from "./geometry"; -import { renderRailButton } from "./rail"; +import { firstIndex } from "./search"; /** A shorter change is cheaper to scroll past than to fold. */ const MIN_FOLD_LINES = 10; @@ -12,7 +15,9 @@ export class ChangeOverlay { private readonly layer: HTMLElement; private readonly buttons = new Map(); private buttonHeight = 0; - private ring: { segment: CompareSegment; el: HTMLElement } | null = null; + /** Its element comes with its first place: unplaced, it shows as a line at the top. */ + private ring: { segment: CompareSegment; el: HTMLElement | null } | null = + null; constructor( private readonly host: HTMLElement, @@ -25,16 +30,11 @@ export class ChangeOverlay { /** Rings a change until its fade ends; the next layout places it. */ flash(segment: CompareSegment): void { - this.ring?.el.remove(); + this.ring?.el?.remove(); this.ring = null; // A hidden pane never runs the fade, so its ring would wait there for the next layout switch. if (this.host.clientHeight === 0) return; - const el = this.layer.createDiv({ cls: "mdsync-change-ring" }); - el.addEventListener("animationend", () => { - el.remove(); - if (this.ring?.el === el) this.ring = null; - }); - this.ring = { segment, el }; + this.ring = { segment, el: null }; } layout( @@ -76,17 +76,27 @@ export class ChangeOverlay { } private placeRing(segments: readonly CompareSegment[], shift: number): void { - if (!this.ring) return; - const { segment, el } = this.ring; + const ring = this.ring; + if (!ring) return; // A refresh rebuilds the segments; the ring must not move onto whatever took its index. - if (segments[segment.key] !== segment) { - el.remove(); + if (segments[ring.segment.key] !== ring.segment) { + ring.el?.remove(); this.ring = null; return; } - const { top, bottom } = this.place(segment, shift); - el.style.transform = `translateY(${Math.round(top)}px)`; - el.style.height = `${Math.round(bottom - top)}px`; + ring.el ??= this.ringElement(); + const { top, bottom } = this.place(ring.segment, shift); + ring.el.style.transform = `translateY(${Math.round(top)}px)`; + ring.el.style.height = `${Math.round(bottom - top)}px`; + } + + private ringElement(): HTMLElement { + const el = this.layer.createDiv({ cls: "mdsync-change-ring" }); + el.addEventListener("animationend", () => { + el.remove(); + if (this.ring?.el === el) this.ring = null; + }); + return el; } private place(segment: CompareSegment, shift: number): Bounds { diff --git a/packages/plugin/src/ui/diff/code-lines.ts b/packages/plugin/src/features/diff/lines/code-lines.ts similarity index 96% rename from packages/plugin/src/ui/diff/code-lines.ts rename to packages/plugin/src/features/diff/lines/code-lines.ts index e6dc1c2e..2e0c8b59 100644 --- a/packages/plugin/src/ui/diff/code-lines.ts +++ b/packages/plugin/src/features/diff/lines/code-lines.ts @@ -1,7 +1,7 @@ import type { Range } from "@codemirror/state"; import { Decoration } from "@codemirror/view"; -import type { Span } from "@/sync/merge-model"; -import { type DiffRange, diffRanges } from "@/utils"; +import { type DiffRange, diffRanges } from "@/core/utils"; +import type { Span } from "@/features/sync"; /** Past these, word marks cost more than they tell; the line tint still shows the change. */ const MARK_MAX_LINE_CHARS = 10_000; diff --git a/packages/plugin/src/ui/diff/divider.ts b/packages/plugin/src/features/diff/lines/divider.ts similarity index 98% rename from packages/plugin/src/ui/diff/divider.ts rename to packages/plugin/src/features/diff/lines/divider.ts index 79db95a3..47b7aba9 100644 --- a/packages/plugin/src/ui/diff/divider.ts +++ b/packages/plugin/src/features/diff/lines/divider.ts @@ -1,8 +1,8 @@ import type { EditorView } from "@codemirror/view"; -import type { Span } from "@/sync/merge-model"; -import { firstIndex } from "@/utils"; +import type { Span } from "@/features/sync"; +import { type RailAction, renderRailButton } from "../rail"; import { type Bounds, shiftBounds, spanBounds } from "./geometry"; -import { type RailAction, renderRailButton } from "./rail"; +import { firstIndex } from "./search"; /** One change as the strip sees it: where it sits in each pane, how to draw it, what it offers. */ export interface DividerItem { diff --git a/packages/plugin/src/features/diff/lines/follow-window.ts b/packages/plugin/src/features/diff/lines/follow-window.ts new file mode 100644 index 00000000..34612946 --- /dev/null +++ b/packages/plugin/src/features/diff/lines/follow-window.ts @@ -0,0 +1,10 @@ +import { ViewPlugin } from "@codemirror/view"; + +/** + * Obsidian moves a tab's DOM to a popout as is, and CodeMirror mounts its styles only in the document it started in. + * Watched on the host: Obsidian marks a watched node with a class, and CodeMirror rewrites its own root's. + */ +export const followWindow = (host: HTMLElement) => + ViewPlugin.define((view) => ({ + destroy: host.onWindowMigrated(() => view.setRoot(host.doc)), + })); diff --git a/packages/plugin/src/ui/diff/gap-widgets.ts b/packages/plugin/src/features/diff/lines/gap-widgets.ts similarity index 97% rename from packages/plugin/src/ui/diff/gap-widgets.ts rename to packages/plugin/src/features/diff/lines/gap-widgets.ts index a01dd750..6a459188 100644 --- a/packages/plugin/src/ui/diff/gap-widgets.ts +++ b/packages/plugin/src/features/diff/lines/gap-widgets.ts @@ -7,9 +7,8 @@ import { WidgetType, } from "@codemirror/view"; import { setIcon } from "obsidian"; -import type { LineRange } from "@/sync/hunks"; -import type { Span } from "@/sync/merge-model"; -import { firstIndex } from "@/utils"; +import type { LineRange, Span } from "@/features/sync"; +import { firstIndex } from "./search"; const CONTEXT_LINES = 3; /** A shorter run costs less to show than the row that would hide it. */ diff --git a/packages/plugin/src/ui/diff/geometry.ts b/packages/plugin/src/features/diff/lines/geometry.ts similarity index 79% rename from packages/plugin/src/ui/diff/geometry.ts rename to packages/plugin/src/features/diff/lines/geometry.ts index a1071d1d..3d271066 100644 --- a/packages/plugin/src/ui/diff/geometry.ts +++ b/packages/plugin/src/features/diff/lines/geometry.ts @@ -1,8 +1,8 @@ import type { Text } from "@codemirror/state"; import type { EditorView } from "@codemirror/view"; -import type { LineRange } from "@/sync/hunks"; -import type { Span } from "@/sync/merge-model"; -import { firstIndex } from "@/utils"; +import type { LineRange, Span } from "@/features/sync"; +import { firstIndex } from "./search"; +import { SourceBlockWidget } from "./source-widget"; export interface Bounds { top: number; @@ -29,7 +29,7 @@ export function sideSpan(doc: Text, [start, end]: LineRange): Span { return { from: lineStart(doc, start), to: lineStart(doc, end) }; } -/** Vertical extent of a span in document pixels; an empty span is a point. */ +/** Vertical extent of a span in document pixels; an empty span is a point, or the card standing in its place. */ export function spanBounds(view: EditorView, span: Span): Bounds { if (span.to > span.from) { return { @@ -38,6 +38,16 @@ export function spanBounds(view: EditorView, span: Span): Bounds { }; } const block = view.lineBlockAt(span.from); + // Lines this side lacks show as a card at that very place (Inline, a conflict in Result): the change is + // the card. The line block holds any card on its line, one closing the file at its end too. + const cards = Array.isArray(block.type) + ? block.type.filter( + (part) => + part.from === span.from && part.widget instanceof SourceBlockWidget, + ) + : []; + const [first, last] = [cards[0], cards[cards.length - 1]]; + if (first && last) return { top: first.top, bottom: last.bottom }; const y = span.from === block.from ? block.top : block.bottom; return { top: y, bottom: y }; } diff --git a/packages/plugin/src/ui/diff/line-tints.ts b/packages/plugin/src/features/diff/lines/line-tints.ts similarity index 100% rename from packages/plugin/src/ui/diff/line-tints.ts rename to packages/plugin/src/features/diff/lines/line-tints.ts diff --git a/packages/plugin/src/features/diff/lines/pane-search.ts b/packages/plugin/src/features/diff/lines/pane-search.ts new file mode 100644 index 00000000..ecc6dc46 --- /dev/null +++ b/packages/plugin/src/features/diff/lines/pane-search.ts @@ -0,0 +1,97 @@ +import { + closeSearchPanel, + gotoLine, + openSearchPanel, + search, + searchKeymap, + searchPanelOpen, +} from "@codemirror/search"; +import type { Extension } from "@codemirror/state"; +import { EditorView, keymap, ViewPlugin } from "@codemirror/view"; +import { appendIconButton } from "@/core/ui"; +import { SearchBar } from "./search-bar"; + +/** + * A panel's find and go to line, one per pane, toggled from the pane's head, from the toolbar while Inline + * hides the heads, or by Mod+F. `onOpen` opens what folding hides, or a match could land inside a fold. + */ +export class PanelSearch { + private readonly views = new Map(); + private readonly toggles: { key: K; button: HTMLElement }[] = []; + private inline: HTMLElement | null = null; + + constructor( + private readonly main: K, + private readonly onOpen: (key: K, view: EditorView) => void, + ) {} + + extension(key: K): Extension { + return [ + search({ createPanel: (view) => new SearchBar(view) }), + keymap.of([ + // Go to line opens no search panel. + { + key: "Mod-Alt-g", + run: (view) => { + this.onOpen(key, view); + return gotoLine(view); + }, + }, + ...searchKeymap, + ]), + ViewPlugin.define((view) => { + this.views.set(key, view); + return { destroy: () => this.views.delete(key) }; + }), + EditorView.updateListener.of(({ state, startState, view }) => { + const open = searchPanelOpen(state); + if (open === searchPanelOpen(startState)) return; + for (const toggle of this.toggles) { + if (toggle.key !== key) continue; + toggle.button.toggleClass("is-active", open); + toggle.button.setAttr("aria-pressed", String(open)); + } + // After this update ends: unfolding dispatches. + if (open) queueMicrotask(() => this.onOpen(key, view)); + }), + ]; + } + + appendToggle(parent: HTMLElement, key: K): HTMLElement { + const button = appendIconButton(parent, "search", "Search", () => + this.toggle(key), + ); + button.addClass("mdsync-search-toggle"); + button.setAttr("aria-pressed", "false"); + this.toggles.push({ key, button }); + return button; + } + + appendInlineToggle(toolbar: HTMLElement): void { + this.inline = this.appendToggle(toolbar, this.main); + } + + setInline(inline: boolean): void { + if (this.inline) this.inline.hidden = !inline; + } + + /** Mod+F: the pane holding the focus, else the main one. */ + toggleFocused(): void { + const focused = [...this.views].find(([, view]) => + view.dom.contains(view.root.activeElement), + ); + this.toggle(focused?.[0] ?? this.main); + } + + private toggle(key: K): void { + const view = this.views.get(key); + if (!view) return; + if (!searchPanelOpen(view.state)) { + openSearchPanel(view); + return; + } + closeSearchPanel(view); + // A toggle in a head keeps the focus CodeMirror would hand back to the text. + view.focus(); + } +} diff --git a/packages/plugin/src/ui/diff/scroll-sync.ts b/packages/plugin/src/features/diff/lines/scroll-sync.ts similarity index 98% rename from packages/plugin/src/ui/diff/scroll-sync.ts rename to packages/plugin/src/features/diff/lines/scroll-sync.ts index 0dcc2418..81f83d56 100644 --- a/packages/plugin/src/ui/diff/scroll-sync.ts +++ b/packages/plugin/src/features/diff/lines/scroll-sync.ts @@ -1,7 +1,7 @@ import type { EditorView } from "@codemirror/view"; -import type { Span } from "@/sync/merge-model"; -import { firstIndex } from "@/utils"; +import type { Span } from "@/features/sync"; import { docBottom, spanBounds } from "./geometry"; +import { firstIndex } from "./search"; /** IntelliJ keeps the line a third of the way down the viewport aligned. */ const ANCHOR_RATIO = 1 / 3; diff --git a/packages/plugin/src/features/diff/lines/search-bar.ts b/packages/plugin/src/features/diff/lines/search-bar.ts new file mode 100644 index 00000000..f6cf9f9e --- /dev/null +++ b/packages/plugin/src/features/diff/lines/search-bar.ts @@ -0,0 +1,178 @@ +import { + findNext, + findPrevious, + getSearchQuery, + replaceAll, + replaceNext, + SearchQuery, + setSearchQuery, +} from "@codemirror/search"; +import { + type EditorView, + type Panel, + runScopeHandlers, + type ViewUpdate, +} from "@codemirror/view"; +import { SearchComponent, TextComponent } from "obsidian"; +import { appendIconButton, appendLabeledButton } from "@/core/ui"; + +/** Counted on every edit while open: past this the count says "+". */ +const COUNT_MAX = 1000; + +type Flag = "caseSensitive" | "wholeWord" | "regexp"; + +const FLAGS: readonly { flag: Flag; icon: string; label: string }[] = [ + { flag: "caseSensitive", icon: "case-sensitive", label: "Match case" }, + { flag: "wholeWord", icon: "whole-word", label: "Match whole word" }, + { flag: "regexp", icon: "regex", label: "Use regular expression" }, +]; + +/** CodeMirror's search in Obsidian's look: its query, matching and commands, our bar. Replace only where the pane is editable; closed by its toggle, Mod+F or Escape. */ +export class SearchBar implements Panel { + readonly dom = createDiv({ cls: "mdsync-search-bar" }); + readonly top = true; + private query: SearchQuery; + private readonly find: SearchComponent; + private readonly replace: TextComponent | null = null; + private readonly count: HTMLElement; + private readonly flags: { flag: Flag; button: HTMLButtonElement }[]; + + constructor(private readonly view: EditorView) { + this.query = getSearchQuery(view.state); + const row = this.dom.createDiv({ cls: "mdsync-search-row" }); + this.find = new SearchComponent( + row.createDiv({ cls: "mdsync-search-field" }), + ) + .setPlaceholder("Find") + .onChange(() => this.commit({})); + // `openSearchPanel` focuses and selects the field marked so. + this.find.inputEl.setAttr("main-field", "true"); + this.find.inputEl.setAttr("aria-label", "Find"); + // Inside the field, before Obsidian's clear button. + this.count = createSpan({ cls: "mdsync-search-count" }); + this.find.inputEl.after(this.count); + // One block, so a narrow pane wraps every button together. + const tools = row.createDiv({ cls: "mdsync-search-tools" }); + appendIconButton(tools, "arrow-up", "Previous match", () => + findPrevious(view), + ); + appendIconButton(tools, "arrow-down", "Next match", () => findNext(view)); + this.flags = FLAGS.map(({ flag, icon, label }) => ({ + flag, + button: appendIconButton(tools, icon, label, () => + this.commit({ [flag]: !this.query[flag] }), + ), + })); + if (!view.state.readOnly) this.replace = this.renderReplace(tools); + this.dom.addEventListener("keydown", (event) => this.onKey(event)); + this.show(); + } + + /** The first open focuses here; `openSearchPanel` refocuses only an open bar. */ + mount(): void { + this.find.inputEl.focus(); + this.find.inputEl.select(); + } + + update(update: ViewUpdate): void { + const query = getSearchQuery(update.state); + const changed = !query.eq(this.query); + if (changed) { + this.query = query; + this.show(); + } else if (update.docChanged || update.selectionSet) { + this.recount(); + } + } + + private renderReplace(tools: HTMLElement): TextComponent { + const line = this.dom.createDiv({ cls: "mdsync-search-row" }); + line.hidden = true; + const replace = new TextComponent( + line.createDiv({ cls: "mdsync-search-field" }), + ) + .setPlaceholder("Replace") + .onChange(() => this.commit({})); + replace.inputEl.setAttr("aria-label", "Replace"); + appendLabeledButton(line, "replace", "Replace", () => + replaceNext(this.view), + ); + appendLabeledButton(line, "replace-all", "Replace all", () => + replaceAll(this.view), + ); + const toggle = appendIconButton(tools, "replace", "Show replace", () => { + line.hidden = !line.hidden; + toggle.toggleClass("is-active", !line.hidden); + toggle.setAttr("aria-pressed", String(!line.hidden)); + if (!line.hidden) replace.inputEl.focus(); + }); + return replace; + } + + /** The scoped search keys (Esc, F3) first; Enter in a field steps, or replaces in the replace field. Buttons keep their own Enter. */ + private onKey(event: KeyboardEvent): void { + if (runScopeHandlers(this.view, event, "search-panel")) { + event.preventDefault(); + return; + } + if (event.key !== "Enter" || !(event.target instanceof HTMLInputElement)) + return; + event.preventDefault(); + if (event.target === this.replace?.inputEl) replaceNext(this.view); + else if (event.shiftKey) findPrevious(this.view); + else findNext(this.view); + } + + private commit(flags: Partial>): void { + const { query } = this; + const next = new SearchQuery({ + search: this.find.getValue(), + replace: this.replace?.getValue() ?? query.replace, + literal: query.literal, + caseSensitive: flags.caseSensitive ?? query.caseSensitive, + wholeWord: flags.wholeWord ?? query.wholeWord, + regexp: flags.regexp ?? query.regexp, + }); + if (!next.eq(query)) + this.view.dispatch({ effects: setSearchQuery.of(next) }); + } + + /** A query set elsewhere (opening on a selection) shows here; the field being typed in keeps its caret. */ + private show(): void { + const { query } = this; + if (this.find.getValue() !== query.search) this.find.setValue(query.search); + if (this.replace && this.replace.getValue() !== query.replace) { + this.replace.setValue(query.replace); + } + for (const { flag, button } of this.flags) { + button.toggleClass("is-active", query[flag]); + button.setAttr("aria-pressed", String(query[flag])); + } + this.recount(); + } + + private recount(): void { + const [text, missing] = this.matches(); + this.count.setText(text); + this.count.toggleClass("is-empty", missing); + } + + /** The count's text, and whether nothing matches; an invalid pattern matches nothing. */ + private matches(): [string, boolean] { + const { query } = this; + if (!query.search) return ["", false]; + if (!query.valid) return ["0", true]; + const { from, to } = this.view.state.selection.main; + const cursor = query.getCursor(this.view.state); + let total = 0; + let current = 0; + for (let next = cursor.next(); !next.done; next = cursor.next()) { + total++; + if (next.value.from === from && next.value.to === to) current = total; + if (total === COUNT_MAX) break; + } + if (total === 0) return ["0", true]; + const all = `${total}${total === COUNT_MAX ? "+" : ""}`; + return [current > 0 ? `${current}/${all}` : all, false]; + } +} diff --git a/packages/plugin/src/utils/search.ts b/packages/plugin/src/features/diff/lines/search.ts similarity index 100% rename from packages/plugin/src/utils/search.ts rename to packages/plugin/src/features/diff/lines/search.ts diff --git a/packages/plugin/src/ui/diff/source-widget.ts b/packages/plugin/src/features/diff/lines/source-widget.ts similarity index 98% rename from packages/plugin/src/ui/diff/source-widget.ts rename to packages/plugin/src/features/diff/lines/source-widget.ts index 61e66921..01f327b7 100644 --- a/packages/plugin/src/ui/diff/source-widget.ts +++ b/packages/plugin/src/features/diff/lines/source-widget.ts @@ -1,9 +1,9 @@ import { type EditorView, WidgetType } from "@codemirror/view"; import { setIcon } from "obsidian"; -import { type Span, sameLines } from "@/sync/merge-model"; +import { type Span, sameLines } from "@/features/sync"; +import { type RailAction, renderRailButton } from "../rail"; import { renderCodeLine } from "./code-lines"; import { gapRow } from "./gap-widgets"; -import { type RailAction, renderRailButton } from "./rail"; /** A widget is drawn whole, never windowed; past this a block shows its start and offers the rest. */ const BLOCK_MAX_LINES = 300; diff --git a/packages/plugin/src/features/diff/merge/edit-plan.ts b/packages/plugin/src/features/diff/merge/edit-plan.ts new file mode 100644 index 00000000..89c9dbfc --- /dev/null +++ b/packages/plugin/src/features/diff/merge/edit-plan.ts @@ -0,0 +1,226 @@ +import { + type EMergeSide, + type ESideStatus, + MERGE_SIDES, + type MergeChange, + type SideStatus, + type Span, + type Taken, +} from "@/features/sync"; + +export type StatusPatch = Partial>; +/** `null` withdraws a side's contribution. */ +export type TakenPatch = Partial>; + +export interface EditPlan { + from: number; + to: number; + insert: string; + /** Where the change sits once the edit is in; absent when mapping alone places it. */ + result?: Span; + taken: TakenPatch; +} + +/** The subset of a CodeMirror `Text` the model needs, so it stays free of the editor. */ +export interface LineDoc { + length: number; + lineAt(pos: number): { from: number; to: number }; +} + +interface LineEdit { + from: number; + to: number; + insert: string; + result: Span; +} + +function otherSide(side: EMergeSide): EMergeSide { + return side === "local" ? "remote" : "local"; +} + +export function sameStatus(a: SideStatus, b: SideStatus | undefined): boolean { + return b !== undefined && MERGE_SIDES.every((side) => a[side] === b[side]); +} + +export function patchTaken(taken: Taken, patch: TakenPatch): Taken { + const next: Partial> = { ...taken }; + for (const side of MERGE_SIDES) { + const span = patch[side]; + if (span === undefined) continue; + if (span === null) delete next[side]; + else next[side] = span; + } + return next; +} + +/** Widens a span to whole lines: from a line start to the next line start or the doc end. */ +export function snapToLines(doc: LineDoc, span: Span): Span { + if (span.to <= span.from) { + // An empty span sits before a line, or after the last line of a file without a final newline; + // mid-line it moves to the next line. + const line = doc.lineAt(span.from); + const at = + span.from === line.from || span.from === doc.length + ? span.from + : Math.min(line.to + 1, doc.length); + return { from: at, to: at }; + } + const from = doc.lineAt(span.from).from; + const endLine = doc.lineAt(span.to); + const to = + endLine.from === span.to ? span.to : Math.min(endLine.to + 1, doc.length); + return { from, to }; +} + +/** A conflict whose other side is already in gets this side appended below it, so click order is line order. */ +export function applyPlan( + doc: LineDoc, + change: MergeChange, + side: EMergeSide, + sideLines: readonly string[], +): EditPlan { + const span = snapToLines(doc, change.result); + const otherSideName = otherSide(side); + const otherApplied = change.status[otherSideName] === "applied"; + + if (!change.conflict && otherApplied) { + const otherPart = change.taken[otherSideName]; + if (otherPart) { + return { + from: otherPart.from, + to: otherPart.from, + insert: "", + result: change.result, + taken: { [side]: otherPart }, + }; + } + } + + const append = otherApplied; + if (append && sideLines.length === 0) { + return { + from: span.to, + to: span.to, + insert: "", + result: span, + taken: { [side]: { from: span.to, to: span.to } }, + }; + } + const edit = replaceLines( + doc, + append ? { from: span.to, to: span.to } : span, + sideLines, + change.endsAtEof, + append || emptyResult(change), + ); + return { + ...edit, + // An emptied span at the end of the file sits before the line break the new lines bring, not at a + // line start: they are the whole result, or reverting would snap it onto the line above. + result: + append && doc.lineAt(span.from).from === span.from + ? { from: span.from, to: edit.result.to } + : edit.result, + taken: { [side]: edit.result }, + }; +} + +/** With the other side still in, only this side's lines go; otherwise the base lines return. */ +export function revertPlan( + doc: LineDoc, + change: MergeChange, + side: EMergeSide, + baseLines: readonly string[], +): EditPlan { + const part = change.taken[side]; + const otherSideName = otherSide(side); + const otherApplied = change.status[otherSideName] === "applied"; + + if (!change.conflict && otherApplied) { + const otherPart = change.taken[otherSideName]; + if ( + part && + otherPart && + part.from === otherPart.from && + part.to === otherPart.to + ) { + return { + from: part.from, + to: part.from, + insert: "", + taken: { [side]: null }, + }; + } + } + + if (part && otherApplied) { + if (part.from === part.to && change[side][0] === change[side][1]) + return { + from: part.from, + to: part.from, + insert: "", + taken: { [side]: null }, + }; + const edit = replaceLines( + doc, + snapToLines(doc, part), + [], + change.endsAtEof, + ); + return { + from: edit.from, + to: edit.to, + insert: "", + taken: { [side]: null }, + }; + } + const edit = replaceLines( + doc, + snapToLines(doc, change.result), + baseLines, + change.endsAtEof, + emptyResult(change), + ); + return { ...edit, taken: { [side]: null } }; +} + +function replaceLines( + doc: LineDoc, + target: Span, + lines: readonly string[], + endsAtEof: boolean, + afterLastLine = false, +): LineEdit { + let { from } = target; + const { to } = target; + const atEnd = endsAtEof && to === doc.length; + let insert = ""; + let prefix = ""; + if (lines.length === 0) { + // The final empty line is significant too: removing it removes the final newline. + if (atEnd && from > 0 && (from < to || doc.lineAt(from).from === from)) + from -= 1; + } else { + if ( + from === to && + ((atEnd && afterLastLine) || doc.lineAt(from).from !== from) + ) + prefix = "\n"; + insert = `${prefix}${lines.join("\n")}${atEnd ? "" : "\n"}`; + } + return { + from, + to, + insert, + result: { from: from + prefix.length, to: from + insert.length }, + }; +} + +function emptyResult(change: MergeChange): boolean { + const applied = MERGE_SIDES.filter( + (side) => change.status[side] === "applied", + ); + return applied.length > 0 + ? applied.every((side) => change[side][0] === change[side][1]) + : change.base[0] === change.base[1]; +} diff --git a/packages/plugin/src/ui/diff/merge-actions.ts b/packages/plugin/src/features/diff/merge/merge-actions.ts similarity index 87% rename from packages/plugin/src/ui/diff/merge-actions.ts rename to packages/plugin/src/features/diff/merge/merge-actions.ts index 9005a226..3dbdbce8 100644 --- a/packages/plugin/src/ui/diff/merge-actions.ts +++ b/packages/plugin/src/features/diff/merge/merge-actions.ts @@ -2,16 +2,18 @@ import { isolateHistory } from "@codemirror/commands"; import { ChangeSet, type EditorState } from "@codemirror/state"; import type { EditorView } from "@codemirror/view"; import { - applyPlan, - type EditPlan, type EMergeSide, type ESideStatus, MERGE_SIDES, type MergeChange, +} from "@/features/sync"; +import { + applyPlan, + type EditPlan, revertPlan, type StatusPatch, sameStatus, -} from "@/sync/merge-model"; +} from "./edit-plan"; import { fullTaken, mergeChangesField, setChangeState } from "./merge-state"; export interface MergeActions { @@ -101,6 +103,25 @@ function takeSides( "ignored", ); } + const asked = state.field(mergeChangesField)[index]; + // No side asked for changed this region: its base lines are the answer, over anything typed there. + if ( + mode === "settle" && + asked && + sides.every((side) => asked.status[side] === "none") + ) { + const plan = revertPlan( + state.doc, + asked, + sides[0] ?? "local", + base.slice(...asked.base), + ); + if (state.sliceDoc(plan.from, plan.to) !== plan.insert) { + const tr = state.update(planSpec(index, plan, {})); + changes = changes.compose(tr.changes); + state = tr.state; + } + } for (const side of sides) { step( side, diff --git a/packages/plugin/src/ui/diff/merge-cards.ts b/packages/plugin/src/features/diff/merge/merge-cards.ts similarity index 87% rename from packages/plugin/src/ui/diff/merge-cards.ts rename to packages/plugin/src/features/diff/merge/merge-cards.ts index c8428def..7c0c9336 100644 --- a/packages/plugin/src/ui/diff/merge-cards.ts +++ b/packages/plugin/src/features/diff/merge/merge-cards.ts @@ -5,23 +5,38 @@ import { StateField, type Text, } from "@codemirror/state"; -import { Decoration, type DecorationSet } from "@codemirror/view"; -import type { LineRange } from "@/sync/hunks"; +import { + Decoration, + type DecorationSet, + type EditorView, +} from "@codemirror/view"; +import type { LineRange } from "@/features/sync"; import { type EMergeSide, isResolved, MERGE_SIDES, type MergeChange, - snapToLines, -} from "@/sync/merge-model"; -import { addUnchangedGaps } from "./gap-widgets"; -import { rangeLabel } from "./geometry"; +} from "@/features/sync"; +import { addUnchangedGaps } from "../lines/gap-widgets"; +import { rangeLabel } from "../lines/geometry"; +import { type SourceBlock, SourceBlockWidget } from "../lines/source-widget"; +import type { RailAction } from "../rail"; +import { snapToLines } from "./edit-plan"; import type { MergeActions } from "./merge-actions"; import { settleActions } from "./merge-controls"; import type { SideMarks } from "./merge-marks"; import { mergeChangesField } from "./merge-state"; -import type { RailAction } from "./rail"; -import { type SourceBlock, SourceBlockWidget } from "./source-widget"; + +/** Search reads every line: each run folded between cards opens. */ +export function openAllMergeGaps(view: EditorView): void { + const opened = view.state.field(openedGapsField); + const effects: StateEffect[] = []; + const count = view.state.field(mergeChangesField).length; + for (let index = 0; index <= count; index++) { + if (!opened.has(index)) effects.push(toggleMergeGap.of(index)); + } + if (effects.length > 0) view.dispatch({ effects }); +} export interface CombinedMergeConfig { actions: MergeActions; diff --git a/packages/plugin/src/ui/diff/merge-controls.ts b/packages/plugin/src/features/diff/merge/merge-controls.ts similarity index 90% rename from packages/plugin/src/ui/diff/merge-controls.ts rename to packages/plugin/src/features/diff/merge/merge-controls.ts index cafff4e1..b04e9d1b 100644 --- a/packages/plugin/src/ui/diff/merge-controls.ts +++ b/packages/plugin/src/features/diff/merge/merge-controls.ts @@ -1,18 +1,15 @@ import type { Text } from "@codemirror/state"; -import { - type EMergeSide, - type MergeChange, - snapToLines, -} from "@/sync/merge-model"; -import type { DividerItem } from "./divider"; -import { sideSpan } from "./geometry"; +import type { EMergeSide, MergeChange } from "@/features/sync"; +import type { DividerItem } from "../lines/divider"; +import { sideSpan } from "../lines/geometry"; +import type { RailAction } from "../rail"; +import { snapToLines } from "./edit-plan"; import type { MergeActions } from "./merge-actions"; -import type { RailAction } from "./rail"; export type MergeTone = "conflict" | EMergeSide | "base" | "shared"; /** On the strips an open conflict is only taken: it is settled from its head in Result. */ -export function sideActions( +function sideActions( change: MergeChange, side: EMergeSide, handlers: MergeActions, diff --git a/packages/plugin/src/ui/diff/merge-decorations.ts b/packages/plugin/src/features/diff/merge/merge-decorations.ts similarity index 89% rename from packages/plugin/src/ui/diff/merge-decorations.ts rename to packages/plugin/src/features/diff/merge/merge-decorations.ts index 05ba1ca3..bc5fdda8 100644 --- a/packages/plugin/src/ui/diff/merge-decorations.ts +++ b/packages/plugin/src/features/diff/merge/merge-decorations.ts @@ -11,13 +11,20 @@ import { isResolved, MERGE_SIDES, type MergeChange, - snapToLines, -} from "@/sync/merge-model"; -import { firstIndex } from "@/utils"; -import { addCodeMarks } from "./code-lines"; -import { numberUnchangedLines } from "./gap-widgets"; -import { forEachVisibleRange, rangeLabel, sideSpan } from "./geometry"; -import { markLine, type Tints, tintLine, viewportTints } from "./line-tints"; +} from "@/features/sync"; +import { combinedModeField } from "../layout-mode"; +import { addCodeMarks } from "../lines/code-lines"; +import { numberUnchangedLines } from "../lines/gap-widgets"; +import { forEachVisibleRange, rangeLabel, sideSpan } from "../lines/geometry"; +import { + markLine, + type Tints, + tintLine, + viewportTints, +} from "../lines/line-tints"; +import { firstIndex } from "../lines/search"; +import { type SourceBlock, SourceBlockWidget } from "../lines/source-widget"; +import { snapToLines } from "./edit-plan"; import type { MergeActions } from "./merge-actions"; import { type CombinedMergeConfig, @@ -28,18 +35,6 @@ import { import { type MergeTone, settleActions, toneOf } from "./merge-controls"; import type { SideMarks } from "./merge-marks"; import { mergeChangesField, rememberChangeState } from "./merge-state"; -import { type SourceBlock, SourceBlockWidget } from "./source-widget"; - -export const setCombinedMode = StateEffect.define(); -export const combinedModeField = StateField.define({ - create: () => false, - update: (combined, transaction) => { - for (const effect of transaction.effects) { - if (effect.is(setCombinedMode)) return effect.value; - } - return combined; - }, -}); export function mergeResultState(combined?: CombinedMergeConfig): Extension { const cards = combined && mergeCards(combined); diff --git a/packages/plugin/src/features/diff/merge/merge-drafts.ts b/packages/plugin/src/features/diff/merge/merge-drafts.ts new file mode 100644 index 00000000..95bdb8f7 --- /dev/null +++ b/packages/plugin/src/features/diff/merge/merge-drafts.ts @@ -0,0 +1,74 @@ +import type { MergeChange } from "@/features/sync"; + +export interface MergeDraft { + text: string; + changes: readonly MergeChange[]; + expected: { localHash: string; remoteHash: string }; +} + +/** Each holds a whole file: only the latest few stay. */ +const MAX_DRAFTS = 5; + +// Plugin lifetime: a draft outlives its closed tab, not a reload. +const drafts = new Map(); + +export function keepMergeDraft(path: string, draft: MergeDraft): void { + drafts.delete(path); + drafts.set(path, draft); + for (const oldest of drafts.keys()) { + if (drafts.size <= MAX_DRAFTS) break; + drafts.delete(oldest); + } +} + +export interface MergeStart { + text: string; + changes: readonly MergeChange[]; + /** From a draft: its edits count before any undo step exists. */ + restored: boolean; + notice: string | null; +} + +/** A kept draft of these versions, else the fresh session; the notice says which. */ +export function startMerge( + path: string, + expected: MergeDraft["expected"], + session: { text: string; changes: readonly MergeChange[] }, +): MergeStart { + const draft = takeMergeDraft(path, expected); + if (draft && draft !== "stale") { + const { text, changes } = draft; + return { + text, + changes, + restored: true, + notice: "Restored your unsaved merge.", + }; + } + const notice = + draft === "stale" + ? "This file changed since you left its merge, so your unsaved edits were dropped." + : session.changes.some((change) => change.conflict) + ? null + : "No overlapping changes - auto-merged. Review and save."; + return { + text: session.text, + changes: session.changes, + restored: false, + notice, + }; +} + +/** Takes the draft for `path` off the store; `stale` when either side changed since it was kept. */ +export function takeMergeDraft( + path: string, + expected: MergeDraft["expected"], +): MergeDraft | "stale" | null { + const draft = drafts.get(path); + if (!draft) return null; + drafts.delete(path); + const same = + draft.expected.localHash === expected.localHash && + draft.expected.remoteHash === expected.remoteHash; + return same ? draft : "stale"; +} diff --git a/packages/plugin/src/ui/diff/merge-editor.ts b/packages/plugin/src/features/diff/merge/merge-editor.ts similarity index 64% rename from packages/plugin/src/ui/diff/merge-editor.ts rename to packages/plugin/src/features/diff/merge/merge-editor.ts index 3a27fad0..c28a8c23 100644 --- a/packages/plugin/src/ui/diff/merge-editor.ts +++ b/packages/plugin/src/features/diff/merge/merge-editor.ts @@ -9,46 +9,52 @@ import { import { EditorState } from "@codemirror/state"; import { EditorView, keymap, lineNumbers } from "@codemirror/view"; import { setIcon } from "obsidian"; -import { randomId } from "@/crypto"; -import type { PluginHost } from "@/plugin/host"; +import { randomId } from "@/core/crypto"; +import { notifyError, notifyInfo } from "@/core/ui"; +import { eolOf } from "@/core/utils"; import { buildMergeSession, countUnresolved, type EMergeSide, - isResolved, MERGE_SIDES, type MergeChange, - snapToLines, -} from "@/sync/merge-model"; -import { notifyError, notifyInfo, runWithNotice } from "@/ui/common"; -import { eolOf } from "@/utils"; -import { Divider } from "./divider"; -import { sideSpan, spanBounds, updatePaneViewportWidth } from "./geometry"; -import type { PanelHosts } from "./header"; -import { LayoutMode } from "./layout-mode"; +} from "@/features/sync"; +import type { PanelHosts } from "../header"; +import type { DiffHost } from "../host"; +import { LayoutMode, setCombinedMode } from "../layout-mode"; import { LineWrappingControl, type LineWrappingOptions, -} from "./line-wrapping-control"; +} from "../line-wrapping-control"; +import { Divider } from "../lines/divider"; +import { followWindow } from "../lines/follow-window"; +import { sideSpan, updatePaneViewportWidth } from "../lines/geometry"; +import { PanelSearch } from "../lines/pane-search"; +import { + NO_ANCHORS, + PaneScrollSync, + type ScrollAnchors, + spanAnchors, +} from "../lines/scroll-sync"; +import { changeNavigation } from "../rail"; +import { snapToLines } from "./edit-plan"; import { mergeActions } from "./merge-actions"; -import { toggleMergeGap } from "./merge-cards"; +import { openAllMergeGaps, toggleMergeGap } from "./merge-cards"; import { dividerItems } from "./merge-controls"; import { mergeResultState, - setCombinedMode, showSideChanges, sideDecorations, } from "./merge-decorations"; +import { keepMergeDraft, type MergeDraft, startMerge } from "./merge-drafts"; import { type SideMarks, sideMarks } from "./merge-marks"; -import { initialMergeChanges, mergeChangesField } from "./merge-state"; -import { MergeToolbar } from "./merge-toolbar"; -import { changeNavigation } from "./rail"; +import { MergeNavigation } from "./merge-navigation"; import { - NO_ANCHORS, - PaneScrollSync, - type ScrollAnchors, - spanAnchors, -} from "./scroll-sync"; + changeAt, + initialMergeChanges, + mergeChangesField, +} from "./merge-state"; +import { MergeToolbar } from "./merge-toolbar"; export class MergeEditorPanel { private text = ""; @@ -62,12 +68,16 @@ export class MergeEditorPanel { private dividers: Partial> = {}; private scrollSync: PaneScrollSync | null = null; private toolbar: MergeToolbar | null = null; - /** The selected change, or -1. */ - private current = -1; private layoutFrame: number | null = null; private layoutMode: LayoutMode | null = null; private wrapping: LineWrappingControl | null = null; + /** New per render: its toggles are the heads and toolbar drawn with it. */ + private paneSearch = mergeSearch(); private active = false; + /** Opened from a draft: its edits count before any undo step exists. */ + private restored = false; + /** A compare since opening saw other versions: Save will be refused. */ + private versionsChanged = false; private readonly dividerActions = mergeActions(() => ({ view: this.resultView, @@ -75,6 +85,22 @@ export class MergeEditorPanel { base: this.base, })); + private readonly nav = new MergeNavigation({ + result: () => this.resultView, + changes: () => this.currentChanges(), + paneSync: () => (this.layoutMode?.combined ? null : this.scrollSync), + onSelect: (index) => { + for (const side of MERGE_SIDES) { + this.dividers[side]?.select(index < 0 ? null : index); + } + this.updateStatus(); + }, + }); + + get search(): PanelSearch { + return this.paneSearch; + } + get isEditing(): boolean { return this.active; } @@ -82,17 +108,57 @@ export class MergeEditorPanel { /** Undoing every step back counts as none: nothing would be lost. */ get hasEdits(): boolean { return ( - this.active && !!this.resultView && undoDepth(this.resultView.state) > 0 + this.active && + !!this.resultView && + (this.restored || undoDepth(this.resultView.state) > 0) ); } reset(): void { this.active = false; + this.restored = false; + } + + /** Obsidian cannot cancel a tab close: the edits wait for the next Merge of the same versions. */ + keepDraft(path: string): void { + const view = this.resultView; + if (!this.hasEdits || !view || !this.expected) return; + keepMergeDraft(path, { + text: view.state.doc.toString(), + changes: view.state.field(mergeChangesField), + expected: this.expected, + }); + } + + /** Says it as soon as a compare finds the conflict at other versions, not only when Save fails. */ + checkVersions(current: MergeDraft["expected"] | undefined): void { + const { expected } = this; + if (!this.active || !current || !expected) return; + const changed = + current.localHash !== expected.localHash || + current.remoteHash !== expected.remoteHash; + if (changed === this.versionsChanged) return; + this.versionsChanged = changed; + this.updateStatus(); + if (!changed) return; + notifyInfo( + "This file changed since its merge opened, so Save will be refused. Copy what you need from Result, then cancel and merge again.", + ); + } + + /** Settles the change at the cursor, else the selected one, with these sides in order. */ + take(sides: readonly EMergeSide[]): void { + const view = this.resultView; + if (!view) return; + const at = changeAt(view.state, view.state.selection.main.head); + const index = at >= 0 ? at : this.nav.current; + if (index >= 0) this.dividerActions.settle(index, sides); + else notifyInfo("Put the cursor in a change first."); } /** `stillOn` says the view still shows `path` once the three versions arrive. */ async enter( - plugin: PluginHost, + plugin: DiffHost, path: string, stillOn: () => boolean, onEntered: () => void, @@ -101,15 +167,16 @@ export class MergeEditorPanel { const texts = await plugin.controller.fileDiffs.getConflictThreeWay(path); // Another file opened meanwhile, or a merge began: this one would replace it unasked. if (!stillOn() || this.active) return; - if (!texts) { - notifyError( - "Cannot three-way merge this file (binary or no common ancestor). Use Keep local / Accept remote.", - ); + if (typeof texts === "string") { + notifyError(`Cannot merge this file: ${texts}`); return; } const session = buildMergeSession(texts.base, texts.local, texts.remote); - this.text = session.text; - this.changes = session.changes; + const start = startMerge(path, texts.expected, session); + this.text = start.text; + this.changes = start.changes; + this.restored = start.restored; + this.versionsChanged = false; this.base = session.baseLines; this.sides = { local: session.localLines, @@ -119,9 +186,7 @@ export class MergeEditorPanel { this.expected = texts.expected; this.active = true; onEntered(); - if (!session.changes.some((change) => change.conflict)) { - notifyInfo("No overlapping changes - auto-merged. Review and save."); - } + if (start.notice) notifyInfo(start.notice); } catch (err) { notifyError("Merge failed", err); } @@ -129,6 +194,7 @@ export class MergeEditorPanel { render(parent: HTMLElement, options: LineWrappingOptions): void { this.destroy(); + this.paneSearch = mergeSearch(); this.wrapping = new LineWrappingControl( options, () => [...Object.values(this.sideViews), this.resultView], @@ -147,7 +213,7 @@ export class MergeEditorPanel { } private renderToolbar(root: HTMLElement): void { - const toolbar = new MergeToolbar(() => this.jumpToConflict()); + const toolbar = new MergeToolbar(() => this.nextConflict()); this.toolbar = toolbar; this.layoutMode = new LayoutMode( root, @@ -156,6 +222,7 @@ export class MergeEditorPanel { if (changed) { this.resultView?.dispatch({ effects: setCombinedMode.of(combined) }); } + this.paneSearch.setInline(combined); this.scheduleLayout(); }, ); @@ -164,43 +231,45 @@ export class MergeEditorPanel { () => this.resultView && undo(this.resultView), () => this.resultView && redo(this.resultView), ); - toolbar.navigation((delta) => this.jump(delta)); + toolbar.navigation((delta) => this.nav.jump(delta)); + this.paneSearch.appendInlineToggle(toolbar.controls); } private renderDesktop(root: HTMLElement): void { const heads = root.createDiv({ cls: "mdsync-merge-pane-heads" }); const body = root.createDiv({ cls: "mdsync-merge-body" }); - const pane = (cls: string, name: string, note: string, id?: string) => { - const head = heads.createDiv({ cls: `mdsync-merge-pane-head ${cls}` }); + const pane = (key: MergePane, name: string, note: string, id?: string) => { + const head = heads.createDiv({ cls: `mdsync-merge-pane-head is-${key}` }); if (id) head.id = id; const mark = head.createSpan({ cls: "mdsync-merge-pane-mark" }); - if (cls === "is-result") setIcon(mark, "pencil"); + if (key === "result") setIcon(mark, "pencil"); head.createSpan({ cls: "mdsync-merge-pane-name", text: name }); head.createSpan({ cls: "mdsync-merge-pane-note", text: note }); - return body.createDiv({ cls: `mdsync-merge-editor-host ${cls}` }); + this.paneSearch.appendToggle(head, key); + return body.createDiv({ cls: `mdsync-merge-editor-host is-${key}` }); }; const strip = (cls: string) => { heads.createDiv({ cls: "mdsync-merge-divider-head" }); return body.createDiv({ cls: `mdsync-merge-divider ${cls}` }); }; const resultLabel = randomId(); - const localHost = pane("is-local", "Local", "this device"); + const localHost = pane("local", "Local", "this device"); const leftEl = strip("is-local"); const resultHost = pane( - "is-result", + "result", "Result", "you can type here", resultLabel, ); const rightEl = strip("is-remote"); - const remoteHost = pane("is-remote", "Remote", "incoming"); + const remoteHost = pane("remote", "Remote", "incoming"); const marks = sideMarks(this.base, this.sides); const local = this.makeSideEditor(localHost, "local", marks); const result = this.makeResultEditor(resultHost, marks, resultLabel); const remote = this.makeSideEditor(remoteHost, "remote", marks); this.sideViews = { local, remote }; - const select = (key: number | null) => this.select(key ?? -1); + const select = (key: number | null) => this.nav.select(key ?? -1); this.dividers = { local: new Divider(leftEl, local, result, "left", select), remote: new Divider(rightEl, remote, result, "right", select), @@ -239,8 +308,10 @@ export class MergeEditorPanel { doc: this.sides[side].join("\n"), extensions: [ EditorState.readOnly.of(true), - changeNavigation((delta) => this.jump(delta)), + changeNavigation((delta) => this.nav.jump(delta)), lineNumbers(), + followWindow(parent), + this.paneSearch.extension(side), this.wrapping?.extension() ?? [], sideDecorations(side, marks), EditorView.updateListener.of((update) => { @@ -275,9 +346,11 @@ export class MergeEditorPanel { history(), // Labelled by the pane head: an aria-label shows Obsidian's tooltip over the whole editor. EditorView.contentAttributes.of({ "aria-labelledby": labelId }), - changeNavigation((delta) => this.jump(delta)), + changeNavigation((delta) => this.nav.jump(delta)), keymap.of(historyKeymap), lineNumbers(), + followWindow(parent), + this.paneSearch.extension("result"), this.wrapping?.extension() ?? [], EditorView.updateListener.of((update) => { const modelChanged = @@ -339,93 +412,31 @@ export class MergeEditorPanel { this.toolbar?.update({ unresolved: countUnresolved(changes), total: changes.length, - current: this.current, + current: this.nav.current, canUndo: undoDepth(view.state) > 0, canRedo: redoDepth(view.state) > 0, + versionsChanged: this.versionsChanged, }); } - /** Raises the change on both strips and shows its position. */ - private select(index: number): void { - this.current = index; - for (const side of MERGE_SIDES) { - this.dividers[side]?.select(index < 0 ? null : index); - } - this.updateStatus(); - } - - private jump(delta: number): void { - const total = this.currentChanges().length; - if (total === 0) return; - let next = (this.current + delta + total) % total; - if (this.current < 0) next = delta > 0 ? 0 : total - 1; - this.reveal(next); - } - - /** The next unresolved change after the selected one, wrapping round. */ - private jumpToConflict(): void { - const changes = this.currentChanges(); - const total = changes.length; - for (let step = 1; step <= total; step++) { - const index = (Math.max(this.current, -1) + step) % total; - const change = changes[index]; - if (change && !isResolved(change)) { - this.reveal(index); - return; - } - } - } - - private reveal(index: number): void { - const view = this.resultView; - const target = this.currentChanges()[index]; - if (!view || !target) return; - // The strips show its buttons, so the keyboard reaches them with Tab. - this.select(index); - const combined = this.layoutMode?.combined ?? false; - view.dispatch({ - selection: { anchor: target.result.from }, - effects: - this.scrollSync && !combined - ? [] - : EditorView.scrollIntoView(target.result.from, { y: "center" }), - }); - if (!combined && this.scrollSync) { - const top = spanBounds( - view, - snapToLines(view.state.doc, target.result), - ).top; - this.scrollSync.revealIn(view, top); - } - view.focus(); + nextConflict(): void { + this.nav.nextConflict(); } - async save( - plugin: PluginHost, - path: string, - onSaved: (resolvedPath: string) => Promise, - ): Promise { + /** The text to save and the versions it was merged from, once no conflict is left open. */ + merged(): { text: string; expected: MergeDraft["expected"] } | null { const view = this.resultView; - if (!view) return; + if (!view) return null; if (countUnresolved(this.currentChanges()) > 0) { notifyError("Resolve every conflict before saving."); - return; + return null; } const { expected } = this; - if (!expected) return; - const text = view.state.doc.toString().replace(/\n/g, this.eol); - try { - const saved = await runWithNotice( - () => plugin.controller.resolveConflictMerged(path, text, expected), - "Conflict resolved with merged content.", - "Save resolution failed", - ); - if (!saved) return; - this.active = false; - await onSaved(path); - } catch (err) { - notifyError("Save resolution failed", err); - } + if (!expected) return null; + return { + text: view.state.doc.toString().replace(/\n/g, this.eol), + expected, + }; } destroy(): void { @@ -447,6 +458,15 @@ export class MergeEditorPanel { this.toolbar?.controls.remove(); this.toolbar = null; this.wrapping = null; - this.current = -1; + this.nav.current = -1; } } + +type MergePane = EMergeSide | "result"; + +function mergeSearch(): PanelSearch { + return new PanelSearch("result", (pane, view) => { + // Only Result folds unchanged runs into gaps. + if (pane === "result") openAllMergeGaps(view); + }); +} diff --git a/packages/plugin/src/ui/diff/merge-marks.ts b/packages/plugin/src/features/diff/merge/merge-marks.ts similarity index 88% rename from packages/plugin/src/ui/diff/merge-marks.ts rename to packages/plugin/src/features/diff/merge/merge-marks.ts index d8174321..498d2acf 100644 --- a/packages/plugin/src/ui/diff/merge-marks.ts +++ b/packages/plugin/src/features/diff/merge/merge-marks.ts @@ -1,5 +1,5 @@ -import type { EMergeSide, MergeChange, Span } from "@/sync/merge-model"; -import { type LineMarks, lineMarks } from "./code-lines"; +import type { EMergeSide, MergeChange, Span } from "@/features/sync"; +import { type LineMarks, lineMarks } from "../lines/code-lines"; /** Word marks of a side's lines against the base lines of the same change; none where the side did not change. */ export type SideMarks = ( diff --git a/packages/plugin/src/features/diff/merge/merge-navigation.ts b/packages/plugin/src/features/diff/merge/merge-navigation.ts new file mode 100644 index 00000000..011cd480 --- /dev/null +++ b/packages/plugin/src/features/diff/merge/merge-navigation.ts @@ -0,0 +1,66 @@ +import { EditorView } from "@codemirror/view"; +import { isResolved, type MergeChange } from "@/features/sync"; +import { spanBounds } from "../lines/geometry"; +import type { PaneScrollSync } from "../lines/scroll-sync"; +import { stepIndex } from "../rail"; +import { snapToLines } from "./edit-plan"; + +export interface NavigationHost { + result(): EditorView | null; + changes(): readonly MergeChange[]; + /** Side by side the panes scroll together; inline, null, and Result scrolls alone. */ + paneSync(): PaneScrollSync | null; + /** Raises the change on both strips and shows its position. */ + onSelect(index: number): void; +} + +/** Which change is selected, and moving between changes. */ +export class MergeNavigation { + /** The selected change, or -1. */ + current = -1; + + constructor(private readonly host: NavigationHost) {} + + select(index: number): void { + this.current = index; + this.host.onSelect(index); + } + + jump(delta: number): void { + this.reveal(stepIndex(this.current, delta, this.host.changes().length)); + } + + /** The next unresolved change after the selected one, wrapping round. */ + nextConflict(): void { + const changes = this.host.changes(); + const total = changes.length; + for (let step = 1; step <= total; step++) { + const index = (Math.max(this.current, -1) + step) % total; + const change = changes[index]; + if (change && !isResolved(change)) { + this.reveal(index); + return; + } + } + } + + private reveal(index: number): void { + const view = this.host.result(); + const target = this.host.changes()[index]; + if (!view || !target) return; + // The strips show its buttons, so the keyboard reaches them with Tab. + this.select(index); + const sync = this.host.paneSync(); + view.dispatch({ + selection: { anchor: target.result.from }, + effects: sync + ? [] + : EditorView.scrollIntoView(target.result.from, { y: "center" }), + }); + if (sync) { + const span = snapToLines(view.state.doc, target.result); + sync.revealIn(view, spanBounds(view, span).top); + } + view.focus(); + } +} diff --git a/packages/plugin/src/ui/diff/merge-state.ts b/packages/plugin/src/features/diff/merge/merge-state.ts similarity index 88% rename from packages/plugin/src/ui/diff/merge-state.ts rename to packages/plugin/src/features/diff/merge/merge-state.ts index f1a23070..6dcbcd9d 100644 --- a/packages/plugin/src/ui/diff/merge-state.ts +++ b/packages/plugin/src/features/diff/merge/merge-state.ts @@ -1,6 +1,7 @@ import { invertedEffects } from "@codemirror/commands"; import { type ChangeDesc, + type EditorState, Facet, StateEffect, StateField, @@ -9,13 +10,16 @@ import { type EMergeSide, MERGE_SIDES, type MergeChange, - patchTaken, type Span, + type Taken, +} from "@/features/sync"; +import { + patchTaken, type StatusPatch, sameStatus, - type Taken, + snapToLines, type TakenPatch, -} from "@/sync/merge-model"; +} from "./edit-plan"; export interface ChangeStateUpdate { index: number; @@ -90,6 +94,19 @@ export const mergeChangesField = StateField.define({ }, }); +/** The change whose lines hold `pos`, or -1. */ +export function changeAt(state: EditorState, pos: number): number { + const { doc } = state; + return state.field(mergeChangesField).findIndex((change) => { + const { from, to } = snapToLines(doc, change.result); + // A last line with no line break after it ends at the doc end, still inside. + const lastLine = to === doc.length && doc.lineAt(pos).from < pos; + return ( + pos === from || (pos > from && (pos < to || (pos === to && lastLine))) + ); + }); +} + /** Records the pre-transaction change state so undo restores spans and statuses. */ export const rememberChangeState = invertedEffects.of((tr) => { const before = tr.startState.field(mergeChangesField); diff --git a/packages/plugin/src/ui/diff/merge-toolbar.ts b/packages/plugin/src/features/diff/merge/merge-toolbar.ts similarity index 83% rename from packages/plugin/src/ui/diff/merge-toolbar.ts rename to packages/plugin/src/features/diff/merge/merge-toolbar.ts index f57a47cf..c2259276 100644 --- a/packages/plugin/src/ui/diff/merge-toolbar.ts +++ b/packages/plugin/src/features/diff/merge/merge-toolbar.ts @@ -1,6 +1,6 @@ -import { appendIconButton, appendLabeledButton } from "@/ui/common"; -import type { PanelHosts } from "./header"; -import { renderChangeNav } from "./rail"; +import { appendIconButton, appendLabeledButton } from "@/core/ui"; +import type { PanelHosts } from "../header"; +import { renderChangeNav } from "../rail"; export interface MergeProgress { /** Changes still waiting for a side. */ @@ -10,6 +10,7 @@ export interface MergeProgress { current: number; canUndo: boolean; canRedo: boolean; + versionsChanged: boolean; } /** The merge's parts of the diff frame; built once per render and moved into each new frame. */ @@ -23,10 +24,20 @@ export class MergeToolbar { private save: HTMLButtonElement | null = null; private unresolved = 0; + private readonly changed: HTMLElement; + constructor(nextConflict: () => void) { this.status = appendLabeledButton(this.info, "", "", nextConflict); this.status.addClasses(["mdsync-diff-status", "mdsync-merge-status"]); this.status.setAttr("aria-description", "Goes to the next conflict"); + this.changed = this.info.createSpan({ + cls: "mdsync-merge-changed", + text: "File changed", + attr: { + "aria-label": + "This file changed since the merge opened, so Save will be refused", + }, + }); } mount(hosts: PanelHosts): void { @@ -63,6 +74,7 @@ export class MergeToolbar { if (undo) undo.disabled = !progress.canUndo; if (redo) redo.disabled = !progress.canRedo; this.showPosition?.(current, total); + this.changed.hidden = !progress.versionsChanged; this.unresolved = unresolved; this.showSave(); } diff --git a/packages/plugin/src/ui/diff/operations.ts b/packages/plugin/src/features/diff/operations.ts similarity index 83% rename from packages/plugin/src/ui/diff/operations.ts rename to packages/plugin/src/features/diff/operations.ts index 8b757bae..0aac3737 100644 --- a/packages/plugin/src/ui/diff/operations.ts +++ b/packages/plugin/src/features/diff/operations.ts @@ -1,11 +1,15 @@ -import type { PluginHost } from "@/plugin/host"; -import { EConflictStrategy, type SyncOperationResult } from "@/sync/controller"; -import { EDiffDirection, type FileDiffModel } from "@/sync/projection"; -import { notifyError, runWithNotice } from "@/ui/common"; -import { openConfirmModal } from "@/ui/modals"; -import { confirmRestore } from "@/ui/source-control/restore-modal"; +import { notifyError, openConfirmModal, runWithNotice } from "@/core/ui"; +import { + EConflictStrategy, + EDiffDirection, + type FileDiffModel, + type SyncOperationResult, +} from "@/features/sync"; import { EChoiceKind, type HunkChoices } from "./choices"; import type { HistoryChange } from "./history-state"; +import type { DiffHost } from "./host"; +import type { MergeDraft } from "./merge/merge-drafts"; +import { confirmRestore } from "./ui/restore-modal"; export interface DiffOperationState { path: string | null; @@ -24,7 +28,7 @@ export class DiffOperations { private hunkOpInFlight = false; constructor( - private readonly plugin: PluginHost, + private readonly plugin: DiffHost, private readonly callbacks: DiffOperationCallbacks, ) {} @@ -153,10 +157,26 @@ export class DiffOperations { ); } + /** `saved` runs before the next file opens, so leaving the merge asks nothing. */ + async saveMerge( + text: string, + expected: MergeDraft["expected"], + saved: () => void, + ): Promise { + await this.resolve( + (path) => + this.plugin.controller.resolveConflictMerged(path, text, expected), + "Conflict resolved with merged content.", + "Save resolution failed", + saved, + ); + } + private async resolve( action: (path: string) => Promise, okMessage: string, failureLabel: string, + resolved: () => void = () => {}, ): Promise { const { path } = this.callbacks.state(); if (!path) return; @@ -164,7 +184,10 @@ export class DiffOperations { () => action(path), okMessage, failureLabel, - () => this.callbacks.advance(path), + () => { + resolved(); + return this.callbacks.advance(path); + }, ); } @@ -184,10 +207,7 @@ export class DiffOperations { } /** Reverted lines exist nowhere else: the remote never had them. */ -function confirmHunkRevert( - plugin: PluginHost, - count: number, -): Promise { +function confirmHunkRevert(plugin: DiffHost, count: number): Promise { return openConfirmModal({ app: plugin.app, title: `Revert ${count} change(s)?`, diff --git a/packages/plugin/src/ui/diff/rail.ts b/packages/plugin/src/features/diff/rail.ts similarity index 86% rename from packages/plugin/src/ui/diff/rail.ts rename to packages/plugin/src/features/diff/rail.ts index 2aed2248..68d5691b 100644 --- a/packages/plugin/src/ui/diff/rail.ts +++ b/packages/plugin/src/features/diff/rail.ts @@ -1,6 +1,6 @@ import { keymap } from "@codemirror/view"; import { setIcon } from "obsidian"; -import { appendIconButton } from "@/ui/common"; +import { appendIconButton } from "@/core/ui"; export function changeNavigation(jump: (delta: number) => void) { return keymap.of( @@ -14,6 +14,13 @@ export function changeNavigation(jump: (delta: number) => void) { ); } +/** The change `delta` away, wrapping round; from none selected (-1), forward is the first and back the last. */ +export function stepIndex(current: number, delta: number, total: number) { + if (total === 0) return -1; + if (current < 0) return delta > 0 ? 0 : total - 1; + return (current + delta + total) % total; +} + /** Arrows with the position between them, in one box so a narrow bar can drop it whole. */ export function renderChangeNav( parent: HTMLElement, diff --git a/packages/plugin/src/styles/diff/cards.css b/packages/plugin/src/features/diff/styles/cards.css similarity index 100% rename from packages/plugin/src/styles/diff/cards.css rename to packages/plugin/src/features/diff/styles/cards.css diff --git a/packages/plugin/src/styles/diff/cm-lines.css b/packages/plugin/src/features/diff/styles/cm-lines.css similarity index 100% rename from packages/plugin/src/styles/diff/cm-lines.css rename to packages/plugin/src/features/diff/styles/cm-lines.css diff --git a/packages/plugin/src/styles/diff/code-lines.css b/packages/plugin/src/features/diff/styles/code-lines.css similarity index 100% rename from packages/plugin/src/styles/diff/code-lines.css rename to packages/plugin/src/features/diff/styles/code-lines.css diff --git a/packages/plugin/src/styles/diff/divider.css b/packages/plugin/src/features/diff/styles/divider.css similarity index 100% rename from packages/plugin/src/styles/diff/divider.css rename to packages/plugin/src/features/diff/styles/divider.css diff --git a/packages/plugin/src/styles/diff/gaps.css b/packages/plugin/src/features/diff/styles/gaps.css similarity index 100% rename from packages/plugin/src/styles/diff/gaps.css rename to packages/plugin/src/features/diff/styles/gaps.css diff --git a/packages/plugin/src/features/diff/styles/hunk-preview.css b/packages/plugin/src/features/diff/styles/hunk-preview.css new file mode 100644 index 00000000..d1a7678a --- /dev/null +++ b/packages/plugin/src/features/diff/styles/hunk-preview.css @@ -0,0 +1,15 @@ +.mdsync-hunk-preview { + margin-bottom: var(--size-4-2); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-s); + overflow: hidden; + background: var(--background-primary); + font-family: var(--font-monospace); + font-size: var(--font-ui-smaller); +} + +@media (max-width: 700px) { + .mdsync-layout-btn { + display: none; + } +} diff --git a/packages/plugin/src/styles/diff/merge.css b/packages/plugin/src/features/diff/styles/merge.css similarity index 98% rename from packages/plugin/src/styles/diff/merge.css rename to packages/plugin/src/features/diff/styles/merge.css index 4bc67365..ae89efff 100644 --- a/packages/plugin/src/styles/diff/merge.css +++ b/packages/plugin/src/features/diff/styles/merge.css @@ -29,6 +29,12 @@ body.is-phone .mdsync-diff-header button.mdsync-merge-status { min-height: 32px; } +.mdsync-merge-changed { + margin-inline-start: var(--size-4-2); + color: var(--text-warning); + font-size: var(--font-ui-small); +} + .mdsync-merge-status .mdsync-labeled-btn-icon { width: 6px; height: 6px; diff --git a/packages/plugin/src/styles/diff/pane-grid.css b/packages/plugin/src/features/diff/styles/pane-grid.css similarity index 95% rename from packages/plugin/src/styles/diff/pane-grid.css rename to packages/plugin/src/features/diff/styles/pane-grid.css index cd59c621..6712269f 100644 --- a/packages/plugin/src/styles/diff/pane-grid.css +++ b/packages/plugin/src/features/diff/styles/pane-grid.css @@ -109,4 +109,9 @@ body.is-phone .mdsync-diff-view .mdsync-compare-host .cm-content { .mdsync-compare-host .cm-content { caret-color: transparent; } + +/* CodeMirror's light theme paints the caret black. */ +.mdsync-merge-editor-host.is-result .cm-content { + caret-color: var(--caret-color); +} /* biome-ignore-end lint/style/noDescendingSpecificity: see above */ diff --git a/packages/plugin/src/styles/diff/phone.css b/packages/plugin/src/features/diff/styles/phone.css similarity index 100% rename from packages/plugin/src/styles/diff/phone.css rename to packages/plugin/src/features/diff/styles/phone.css diff --git a/packages/plugin/src/styles/diff/rail.css b/packages/plugin/src/features/diff/styles/rail.css similarity index 100% rename from packages/plugin/src/styles/diff/rail.css rename to packages/plugin/src/features/diff/styles/rail.css diff --git a/packages/plugin/src/features/diff/styles/search.css b/packages/plugin/src/features/diff/styles/search.css new file mode 100644 index 00000000..049a7f68 --- /dev/null +++ b/packages/plugin/src/features/diff/styles/search.css @@ -0,0 +1,128 @@ +/* CodeMirror paints its panels and matches light unless the editor is marked dark. */ +.mdsync-diff-view .cm-panels { + background-color: var(--background-primary); + color: var(--text-normal); +} + +/* Find floats over the text, as in VS Code: opening it moves no line. CodeMirror pins `top: 0` inline. */ +.mdsync-diff-view .cm-editor .cm-panels-top { + position: absolute; + left: auto; + right: var(--size-4-4); + width: min(30em, calc(100% - var(--size-4-8))); + margin-top: var(--size-4-1); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); + background-color: var(--background-secondary); + box-shadow: var(--shadow-s); +} + +.mdsync-compare-head .mdsync-search-toggle, +.mdsync-merge-pane-head .mdsync-search-toggle { + margin-inline-start: auto; +} + +.mdsync-diff-view .cm-panels-bottom { + border-top: 1px solid var(--background-modifier-border); +} + +/* Go to line is CodeMirror's own dialog: Obsidian's field and button. */ +.mdsync-diff-view .cm-editor .cm-dialog { + padding: var(--size-4-1) var(--size-4-8) var(--size-4-1) var(--size-4-2); +} + +.mdsync-diff-view .cm-editor .cm-dialog label { + font-size: var(--font-ui-small); + color: var(--text-muted); +} + +.mdsync-diff-view .cm-editor .cm-textfield { + background-color: var(--background-modifier-form-field); + border-color: var(--background-modifier-border); + font-size: var(--font-ui-small); + margin-inline-start: var(--size-4-1); +} + +.mdsync-diff-view .cm-editor .cm-button { + background-image: none; + border: none; + font-size: var(--font-ui-small); +} + +.mdsync-diff-view .cm-editor .cm-dialog-close { + top: 50%; + transform: translateY(-50%); + right: var(--size-4-2); + color: var(--text-muted); + box-shadow: none; +} + +/* As Obsidian's own note search: every match highlighted, the current one ringed. Older Obsidian names the highlight `--text-highlight-bg`. */ +.mdsync-diff-view .cm-editor .cm-searchMatch { + background-color: var( + --highlight-background, + var(--text-highlight-bg, rgba(255, 208, 0, 0.4)) + ); + border-radius: 2px; +} + +.mdsync-diff-view .cm-editor .cm-searchMatch-selected { + box-shadow: 0 0 0 2px var(--text-accent); +} + +.mdsync-search-bar { + display: flex; + flex-direction: column; + gap: var(--size-4-1); + padding: var(--size-4-1) var(--size-4-2); +} + +/* A narrow pane wraps the buttons under the field rather than clipping them. */ +.mdsync-search-row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--size-2-1); +} + +.mdsync-search-row[hidden] { + display: none; +} + +.mdsync-search-field { + flex: 1 1 8em; + min-width: 6em; +} + +.mdsync-search-tools { + display: flex; + align-items: center; + gap: var(--size-2-1); +} + +.mdsync-search-field .search-input-container, +.mdsync-search-field input { + width: 100%; + margin: 0; +} + +/* The count sits in the field, left of Obsidian's clear button (28px, 2px from the edge); the text stops short of both. */ +.mdsync-search-field .search-input-container input { + padding-inline-end: calc(30px + 7ch); +} + +.mdsync-search-count { + position: absolute; + top: 50%; + right: 30px; + transform: translateY(-50%); + pointer-events: none; + color: var(--text-muted); + font-size: var(--font-ui-smaller); + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.mdsync-search-count.is-empty { + color: var(--text-error); +} diff --git a/packages/plugin/src/styles/diff/source-blocks.css b/packages/plugin/src/features/diff/styles/source-blocks.css similarity index 97% rename from packages/plugin/src/styles/diff/source-blocks.css rename to packages/plugin/src/features/diff/styles/source-blocks.css index 0fbd513c..2b1dffe8 100644 --- a/packages/plugin/src/styles/diff/source-blocks.css +++ b/packages/plugin/src/features/diff/styles/source-blocks.css @@ -111,11 +111,11 @@ body.is-phone } .mdsync-counters .is-added { - color: var(--color-green); + color: var(--mdsync-added); } .mdsync-counters .is-removed { - color: var(--color-red); + color: var(--mdsync-deleted); } .mdsync-source-lines.is-empty { diff --git a/packages/plugin/src/styles/diff/tones.css b/packages/plugin/src/features/diff/styles/tones.css similarity index 88% rename from packages/plugin/src/styles/diff/tones.css rename to packages/plugin/src/features/diff/styles/tones.css index 8606e646..425e350d 100644 --- a/packages/plugin/src/styles/diff/tones.css +++ b/packages/plugin/src/features/diff/styles/tones.css @@ -7,9 +7,9 @@ --mdsync-tone-remote: var(--color-purple-rgb, 157, 105, 220); --mdsync-tone-shared: var(--color-cyan-rgb, 0, 191, 188); --mdsync-tone-base: var(--mono-rgb-100, 0, 0, 0); - --mdsync-tone-added: var(--color-green-rgb, 44, 153, 115); - --mdsync-tone-removed: var(--color-red-rgb, 233, 49, 71); - --mdsync-tone-modified: var(--color-orange-rgb, 236, 117, 0); + --mdsync-tone-added: var(--mdsync-added-rgb); + --mdsync-tone-removed: var(--mdsync-deleted-rgb); + --mdsync-tone-modified: var(--mdsync-modified-rgb); --mdsync-tone: var(--mdsync-tone-base); } diff --git a/packages/plugin/src/styles/diff/toolbars.css b/packages/plugin/src/features/diff/styles/toolbars.css similarity index 77% rename from packages/plugin/src/styles/diff/toolbars.css rename to packages/plugin/src/features/diff/styles/toolbars.css index d2fe1872..f9418b57 100644 --- a/packages/plugin/src/styles/diff/toolbars.css +++ b/packages/plugin/src/features/diff/styles/toolbars.css @@ -77,8 +77,13 @@ --mdsync-kind: var(--color-purple-rgb, 157, 105, 220); } -/* The bar's buttons are ghosts, like the editor's own header. */ -.mdsync-diff-header .mdsync-icon-btn { +/* Header, pane head and find bar buttons are ghosts, like the editor's own header. */ +:is( + .mdsync-diff-header, + .mdsync-compare-head, + .mdsync-merge-pane-head, + .mdsync-search-bar +) .mdsync-icon-btn { width: 28px; min-width: 28px; height: 28px; @@ -89,17 +94,35 @@ color: var(--text-muted); } -.mdsync-diff-header .mdsync-icon-btn:hover { +:is( + .mdsync-diff-header, + .mdsync-compare-head, + .mdsync-merge-pane-head, + .mdsync-search-bar + ) + .mdsync-icon-btn:hover { background: var(--background-modifier-hover); color: var(--text-normal); } -.mdsync-diff-header .mdsync-icon-btn.is-active { +:is( + .mdsync-diff-header, + .mdsync-compare-head, + .mdsync-merge-pane-head, + .mdsync-search-bar + ) + .mdsync-icon-btn.is-active { background: var(--background-modifier-hover); color: var(--text-accent); } -.mdsync-diff-header .mdsync-icon-btn:disabled { +:is( + .mdsync-diff-header, + .mdsync-compare-head, + .mdsync-merge-pane-head, + .mdsync-search-bar + ) + .mdsync-icon-btn:disabled { background: transparent; opacity: 0.4; } diff --git a/packages/plugin/src/styles/diff/view.css b/packages/plugin/src/features/diff/styles/view.css similarity index 82% rename from packages/plugin/src/styles/diff/view.css rename to packages/plugin/src/features/diff/styles/view.css index ffa5d271..63d9d5a9 100644 --- a/packages/plugin/src/styles/diff/view.css +++ b/packages/plugin/src/features/diff/styles/view.css @@ -188,6 +188,36 @@ flex-shrink: 0; } +/* A narrow pane: the hint takes the row and the buttons go under it, not a column of seven lines. */ +@container mdsync-diff (max-width: 640px) { + body:not(.is-phone) .mdsync-diff-action-bar { + flex-wrap: wrap; + } + + body:not(.is-phone) .mdsync-diff-pending-host, + body:not(.is-phone) .mdsync-diff-action-bar > .mdsync-diff-hint { + flex-basis: 100%; + } + + body:not(.is-phone) .mdsync-diff-file-actions { + flex-shrink: 1; + justify-content: flex-end; + min-width: 0; + } +} + +/* The name first: the arrows keep their labels, and each change card counts its own lines. */ +@container mdsync-diff (max-width: 480px) { + body:not(.is-phone) .mdsync-diff-header { + gap: var(--size-4-1); + } + + body:not(.is-phone) .mdsync-diff-file-position, + body:not(.is-phone) .mdsync-diff-header .mdsync-diff-info { + display: none; + } +} + .mdsync-diff-action-bar:not(.has-button, .has-hint), .mdsync-diff-file-actions:empty, .mdsync-diff-action-bar:not(.has-pending-items) .mdsync-diff-pending-host, diff --git a/packages/plugin/src/features/diff/ui/copy-menu.ts b/packages/plugin/src/features/diff/ui/copy-menu.ts new file mode 100644 index 00000000..e5d1e3d6 --- /dev/null +++ b/packages/plugin/src/features/diff/ui/copy-menu.ts @@ -0,0 +1,39 @@ +import type { Menu } from "obsidian"; +import { copyText } from "@/core/ui"; +import type { FileDiffModel } from "@/features/sync"; + +/** The tab menu copies the path and each side whole; a selection in a pane copies part of one. */ +export function addCopyItems( + menu: Menu, + path: string, + model: FileDiffModel | null, +): void { + menu.addItem((item) => + item + .setTitle("Copy path") + .setIcon("copy") + .onClick(() => void copyText("Path", path)), + ); + if (!model || model.isBinary) return; + const sides = [ + { + label: model.leftLabel, + text: model.leftText, + present: model.leftPresent, + }, + { + label: model.rightLabel, + text: model.rightText, + present: model.rightPresent, + }, + ]; + for (const { label, text, present } of sides) { + if (!present) continue; + menu.addItem((item) => + item + .setTitle(`Copy text (${label})`) + .setIcon("copy") + .onClick(() => void copyText("Text", text)), + ); + } +} diff --git a/packages/plugin/src/features/diff/ui/leave-guard.ts b/packages/plugin/src/features/diff/ui/leave-guard.ts new file mode 100644 index 00000000..7321e453 --- /dev/null +++ b/packages/plugin/src/features/diff/ui/leave-guard.ts @@ -0,0 +1,31 @@ +import type { App } from "obsidian"; +import { openConfirmModal } from "@/core/ui"; + +/** False when the person keeps unsaved work on screen: merge edits, or changes picked and not applied. */ +export function confirmLeave( + app: App, + work: { mergeEdits: boolean; picked: number }, +): Promise { + if (work.mergeEdits) { + return openConfirmModal({ + app, + title: "Discard this merge?", + body: ["The merged result is not saved. Leaving drops your edits to it."], + confirmLabel: "Discard", + cancelLabel: "Keep merging", + confirmClass: "mod-warning", + }); + } + if (work.picked === 0) return Promise.resolve(true); + const one = work.picked === 1; + return openConfirmModal({ + app, + title: "Discard your choices?", + body: [ + `${work.picked} picked ${one ? "change is" : "changes are"} not applied yet. Leaving drops ${one ? "it" : "them"}.`, + ], + confirmLabel: "Discard", + cancelLabel: "Keep choosing", + confirmClass: "mod-warning", + }); +} diff --git a/packages/plugin/src/ui/source-control/restore-modal.ts b/packages/plugin/src/features/diff/ui/restore-modal.ts similarity index 93% rename from packages/plugin/src/ui/source-control/restore-modal.ts rename to packages/plugin/src/features/diff/ui/restore-modal.ts index 571bbe35..7c737d03 100644 --- a/packages/plugin/src/ui/source-control/restore-modal.ts +++ b/packages/plugin/src/features/diff/ui/restore-modal.ts @@ -1,20 +1,20 @@ import { ButtonComponent, Modal } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import { errorMessage, formatBytes } from "@/shared"; -import type { FileDiffModel, HistoryVersionRef } from "@/sync/projection"; +import { errorMessage, formatBytes } from "@/core/shared"; import { + actionButton, modalCard, modalFooter, modalWarning, + openPromiseModal, renderModalHead, renderPath, -} from "@/ui/common"; -import { renderHunkPreview } from "@/ui/diff"; -import { openPromiseModal } from "@/ui/modals"; -import { actionButton } from "./action-button"; +} from "@/core/ui"; +import type { FileDiffModel, HistoryVersionRef } from "@/features/sync"; +import { renderHunkPreview } from "../compare/hunk-renderer"; +import type { DiffHost } from "../host"; export interface RestoreConfirmOptions { - plugin: PluginHost; + plugin: DiffHost; /** File the version belongs to; also the diff's other side. */ path: string; version: HistoryVersionRef; @@ -91,6 +91,7 @@ async function loadPreview( return options.plugin.controller.history.getHistoryDiff({ // Diff against the target, not the original path: that is what gets replaced. path: options.target, + source: options.path, // Current on the left, so "+" is what the restore brings back. left: { current: true }, right: { version: options.version }, @@ -99,7 +100,7 @@ async function loadPreview( /** Names every file a bulk restore would bring back; no diff preview, as the trash rows offer Preview per file. */ export function confirmBulkRestore( - plugin: PluginHost, + plugin: DiffHost, entries: readonly BulkRestoreEntry[], ): Promise { return openPromiseModal((answer) => { diff --git a/packages/plugin/src/ui/diff-view.ts b/packages/plugin/src/features/diff/view.ts similarity index 60% rename from packages/plugin/src/ui/diff-view.ts rename to packages/plugin/src/features/diff/view.ts index 77b3accf..d6f75f39 100644 --- a/packages/plugin/src/ui/diff-view.ts +++ b/packages/plugin/src/features/diff/view.ts @@ -1,50 +1,52 @@ -import { ItemView, type ViewStateResult, type WorkspaceLeaf } from "obsidian"; -import { DIFF_VIEW_TYPE, SOURCE_CONTROL_VIEW_TYPE } from "@/constants"; -import type { PluginHost } from "@/plugin/host"; -import { userMessage } from "@/shared"; -import type { CompareResult } from "@/sync/engine"; import { - EDiffDirection, - type FileDiffModel, - type HistoryVersionRef, -} from "@/sync/projection"; -import { notifyError, redrawOnPhoneChange } from "@/ui/common"; -import { openConfirmModal } from "@/ui/modals"; -import { type ComparePanel, MergeEditorPanel, renderBinaryDiff } from "./diff"; -import { watchDiffChrome } from "./diff/action-bar"; -import { renderTextDiff } from "./diff/compare-panel"; + ItemView, + type Menu, + Scope, + type ViewStateResult, + type WorkspaceLeaf, +} from "obsidian"; +import { DIFF_VIEW_TYPE } from "@/core/constants"; +import { userMessage } from "@/core/shared"; +import { notifyError, redrawOnPhoneChange } from "@/core/ui"; +import type { CompareResult, EMergeSide, FileDiffModel } from "@/features/sync"; +import { watchDiffChrome } from "./action-bar"; +import { renderBinaryDiff } from "./compare/binary-view"; +import { type ComparePanel, renderTextDiff } from "./compare/compare-panel"; import { getAdjacentPath, getNextConflictPath, getOrderedPaths, -} from "./diff/file-navigation"; -import { refitDiffTitle, renderDiffFrame } from "./diff/header"; +} from "./file-navigation"; +import { isMergeable, refitDiffTitle, renderDiffFrame } from "./header"; import { buildHistoryRequest, - changesDiffer, compareActionable, type DiffViewState, - type HistoryChange, - selectHistoryMode, -} from "./diff/history-state"; -import { DiffOperations } from "./diff/operations"; -import { PreviewPanel } from "./diff/preview-panel"; -import { openSourceControlView } from "./source-control-view"; + fileTarget, + readTarget, + sameTarget, + targetState, +} from "./history-state"; +import type { DiffHost } from "./host"; +import { MergeEditorPanel } from "./merge/merge-editor"; +import { DiffOperations } from "./operations"; +import { addCopyItems } from "./ui/copy-menu"; +import { confirmLeave } from "./ui/leave-guard"; + +/** A merge open in a diff view, as commands reach it. */ +export interface ActiveMerge { + take(sides: readonly EMergeSide[]): void; + nextConflict(): void; + save(): void; +} export class DiffView extends ItemView { - private readonly plugin: PluginHost; + private readonly plugin: DiffHost; private readonly operations: DiffOperations; - private path: string | null = null; - private historyHash: string | null = null; - private historyLabel = "Version"; - private historySize: number | undefined; - private against: HistoryVersionRef | null = null; - private historyChange: HistoryChange | null = null; - private historyPreviewIfMissing = false; + private target = fileTarget(null); private model: FileDiffModel | null = null; private readonly mergePanel = new MergeEditorPanel(); private comparePanel: ComparePanel | null = null; - private previewPanel: PreviewPanel | null = null; private forceText = false; private lineWrapping = true; private pinChosen = true; @@ -59,19 +61,24 @@ export class DiffView extends ItemView { /** Monotonic generation counter; async loads discard results from older generations. */ private loadGeneration = 0; - constructor(leaf: WorkspaceLeaf, plugin: PluginHost) { + constructor(leaf: WorkspaceLeaf, plugin: DiffHost) { super(leaf); this.plugin = plugin; this.operations = new DiffOperations(plugin, { - state: () => ({ - path: this.path, - historyHash: this.historyHash, - historyChange: this.historyChange, - model: this.model, - }), + state: () => ({ ...this.target, model: this.model }), refresh: () => this.refreshModel(), advance: (path) => this.advanceAfterResolve(path), }); + // Obsidian's own Mod+F (search in a note) runs before the panes' CodeMirror keys. + // Uppercase matches the key's position, so any keyboard layout. + this.scope = new Scope(this.app.scope); + this.scope.register(["Mod"], "F", () => { + const panel = this.mergePanel.isEditing + ? this.mergePanel + : this.comparePanel; + panel?.search.toggleFocused(); + return false; + }); } getViewType(): string { @@ -79,55 +86,31 @@ export class DiffView extends ItemView { } getDisplayText(): string { - if (!this.path) return "MDSync diff"; - return this.historyHash ? `History: ${this.path}` : `Diff: ${this.path}`; + const { path, historyHash } = this.target; + if (!path) return "MDSync diff"; + return historyHash ? `History: ${path}` : `Diff: ${path}`; } getIcon(): string { return "git-compare"; } + onPaneMenu(menu: Menu, source: string): void { + super.onPaneMenu(menu, source); + const { path } = this.target; + if (path) addCopyItems(menu, path, this.model); + } + getState(): Record { - // History fields belong here so a restored workspace preserves version diffs. - return { - path: this.path, - historyHash: this.historyHash ?? undefined, - historyLabel: this.historyHash ? this.historyLabel : undefined, - historySize: this.historySize, - againstHash: this.against?.hash, - againstLabel: this.against?.label, - againstSize: this.against?.size, - historyChange: this.historyChange ?? undefined, - historyPreviewIfMissing: this.historyPreviewIfMissing || undefined, - }; + return { ...targetState(this.target) }; } async setState(state: DiffViewState, result: ViewStateResult): Promise { - this.mergeRequested = state.merge ? (state.path ?? this.path) : null; - const changed = - (state.path && state.path !== this.path) || - (state.historyHash ?? null) !== this.historyHash || - (state.againstHash ?? null) !== (this.against?.hash ?? null) || - // A pin rename changes the label alone, and the header reads it. - (state.historyHash !== undefined && - (state.historyLabel ?? "Version") !== this.historyLabel) || - changesDiffer(state.historyChange ?? null, this.historyChange) || - (state.historyPreviewIfMissing ?? false) !== this.historyPreviewIfMissing; - if (changed) { - if (!(await this.leaveMerge())) return; - this.path = state.path ?? this.path; - this.historyHash = state.historyHash ?? null; - this.historyLabel = state.historyLabel ?? "Version"; - this.historySize = state.historySize; - this.against = state.againstHash - ? { - hash: state.againstHash, - label: state.againstLabel ?? "Other version", - size: state.againstSize, - } - : null; - this.historyChange = state.historyChange ?? null; - this.historyPreviewIfMissing = state.historyPreviewIfMissing ?? false; + const next = readTarget(state, this.target.path); + this.mergeRequested = state.merge ? next.path : null; + if (!sameTarget(next, this.target)) { + if (!(await this.mayLeave())) return; + this.target = next; this.model = null; this.mergePanel.reset(); this.forceText = false; @@ -142,20 +125,13 @@ export class DiffView extends ItemView { /** Once the requested path's model is in: a load still queued behind another finishes later. */ private async enterRequestedMerge(): Promise { const model = this.model; - if (!this.path || this.mergeRequested !== this.path || !model) return; + const { path } = this.target; + if (!path || this.mergeRequested !== path || !model) return; this.mergeRequested = null; - if ( - model.direction !== EDiffDirection.Conflict || - model.isBinary || - this.mergePanel.isEditing - ) { - return; - } - await this.mergePanel.enter( - this.plugin, - this.path, - this.stillShowing(), - () => this.renderShell(), + // Without a version to merge from, the diff and its whole-file choices are the answer, not an error. + if (!isMergeable(model) || this.mergePanel.isEditing) return; + await this.mergePanel.enter(this.plugin, path, this.stillShowing(), () => + this.renderShell(), ); } @@ -188,8 +164,13 @@ export class DiffView extends ItemView { this.seenBusy = busy; if (result === this.seenResult && !settled) return; this.seenResult = result; + const { path, against, historyChange } = this.target; + if (result && path && this.mergePanel.isEditing) { + const status = this.plugin.controller.fileDiffs.getStatusForPath(path); + this.mergePanel.checkVersions(status?.conflict); + } // Stored versions are immutable: a compare cannot change them. - if (this.against || this.historyChange) return; + if (against || historyChange) return; this.stale = true; this.onResize(); }); @@ -201,7 +182,7 @@ export class DiffView extends ItemView { /** Obsidian resizes a tab when it is shown again: the reload a hidden tab skipped. */ onResize(): void { refitDiffTitle(this.containerEl); - if (!this.stale || !this.path || this.mergePanel.isEditing) return; + if (!this.stale || !this.target.path || this.mergePanel.isEditing) return; if (!this.containerEl.isShown()) return; this.stale = false; void this.refreshModel(); @@ -216,6 +197,7 @@ export class DiffView extends ItemView { this.chrome?.disconnect(); this.chrome = null; this.refreshPending = false; + if (this.target.path) this.mergePanel.keepDraft(this.target.path); this.destroyViews(); this.contentEl.empty(); this.bodyEl = null; @@ -224,7 +206,9 @@ export class DiffView extends ItemView { } private async refreshModel(): Promise { - if (!this.path) return; + const target = this.target; + const { path, historyHash } = target; + if (!path) return; if (this.rendering) { this.refreshPending = true; return; @@ -233,18 +217,15 @@ export class DiffView extends ItemView { const gen = this.loadGeneration; try { if (!this.model) this.renderLoading(); - if (this.historyHash) { - const request = buildHistoryRequest({ - path: this.path, - historyHash: this.historyHash, - historyLabel: this.historyLabel, - historySize: this.historySize, - historyChange: this.historyChange, - against: this.against, - forceText: this.forceText, - }); - const model = - await this.plugin.controller.history.getHistoryDiff(request); + if (historyHash) { + const model = await this.plugin.controller.history.getHistoryDiff( + buildHistoryRequest({ + ...target, + path, + historyHash, + forceText: this.forceText, + }), + ); if (gen !== this.loadGeneration) return; this.model = model; if (!this.model) { @@ -255,8 +236,8 @@ export class DiffView extends ItemView { return; } const model = this.forceText - ? await this.plugin.controller.fileDiffs.getForcedFileDiff(this.path) - : await this.plugin.controller.fileDiffs.getFileDiff(this.path); + ? await this.plugin.controller.fileDiffs.getForcedFileDiff(path) + : await this.plugin.controller.fileDiffs.getFileDiff(path); if (gen !== this.loadGeneration) return; this.model = model; @@ -319,7 +300,8 @@ export class DiffView extends ItemView { const header = this.headerEl; const actionBar = this.actionBarEl; if (!header || !actionBar) return; - const path = this.path ?? ""; + const { against, historyChange, historyLabel } = this.target; + const path = this.target.path ?? ""; renderDiffFrame( header, actionBar, @@ -330,17 +312,14 @@ export class DiffView extends ItemView { ), model: this.model, isEditing: this.mergePanel.isEditing, - against: this.against, - historyChange: this.historyChange, - historyLabel: this.historyLabel, + against, + historyChange, + historyLabel, }, { - saveResolution: () => - void this.mergePanel.save(this.plugin, path, (resolved: string) => - this.advanceAfterResolve(resolved), - ), + saveResolution: () => this.saveMerge(), cancelResolution: () => - void this.leaveMerge().then((leave) => { + void this.mayLeave().then((leave) => { if (!leave) return; this.mergePanel.reset(); this.renderShell(); @@ -359,8 +338,11 @@ export class DiffView extends ItemView { goPrevFile: () => void this.navigateFile(-1), goNextFile: () => void this.navigateFile(1), goBack: () => - void this.leaveMerge().then((leave) => { - if (leave) void this.returnToSourceControl(); + void this.mayLeave().then((leave) => { + if (!leave) return; + // Discarded here, so closing the tab keeps no draft of it. + this.mergePanel.reset(); + void this.returnToSourceControl(); }), }, this.mergePanel.isEditing ? this.mergePanel : this.comparePanel, @@ -371,18 +353,8 @@ export class DiffView extends ItemView { const body = this.bodyEl; if (!body) return; const model = this.model; - const preview = - model && - selectHistoryMode({ - historyHash: this.historyHash, - historyChange: this.historyChange, - historyPreviewIfMissing: this.historyPreviewIfMissing, - against: this.against, - localExists: model.rightPresent, - }) === "preview"; if ( model && - !preview && !model.isBinary && !this.mergePanel.isEditing && this.comparePanel && @@ -412,14 +384,10 @@ export class DiffView extends ItemView { }); return; } - if (preview) { - this.previewPanel = new PreviewPanel(); - this.previewPanel.render(body, model.leftText, this.historyLabel); - return; - } this.comparePanel = renderTextDiff(body, model, { direction: model.direction, actionable: this.compareActionable(model), + mergeable: isMergeable(model), lineWrapping: this.lineWrapping, onLineWrappingChange: (enabled) => { this.lineWrapping = enabled; @@ -433,11 +401,7 @@ export class DiffView extends ItemView { } private compareActionable(model: FileDiffModel): boolean { - return compareActionable({ - model, - against: this.against, - historyChange: this.historyChange, - }); + return compareActionable({ ...this.target, model }); } private async advanceAfterResolve(resolvedPath: string): Promise { @@ -457,42 +421,49 @@ export class DiffView extends ItemView { // Detached first: the leaf Obsidian activates after it, a tick later, closes a phone's drawer. this.leaf.detach(); await sleep(0); - await openSourceControlView(this.app, SOURCE_CONTROL_VIEW_TYPE); + await this.plugin.openSourceControl(); } private async navigateFile(delta: number): Promise { // Re-read at click time: the list captured at render goes stale once anything syncs. const target = getAdjacentPath( getOrderedPaths(this.plugin.controller.getSnapshot().result?.diff), - this.path, + this.target.path, delta, ); - if (!target || !(await this.leaveMerge())) return; + if (!target || !(await this.mayLeave())) return; this.showFile(target); await this.refreshModel(); } - /** False when the user keeps an unsaved merge on screen. */ - private async leaveMerge(): Promise { - if (!this.mergePanel.hasEdits) return true; - return openConfirmModal({ - app: this.app, - title: "Discard this merge?", - body: ["The merged result is not saved. Leaving drops your edits to it."], - confirmLabel: "Discard", - cancelLabel: "Keep merging", - confirmClass: "mod-warning", + /** What merge commands act on; null unless this view is merging. */ + get merge(): ActiveMerge | null { + const { path } = this.target; + if (!this.mergePanel.isEditing || !path) return null; + return { + take: (sides) => this.mergePanel.take(sides), + nextConflict: () => this.mergePanel.nextConflict(), + save: () => this.saveMerge(), + }; + } + + private saveMerge(): void { + const merged = this.mergePanel.merged(); + if (!merged) return; + void this.operations.saveMerge(merged.text, merged.expected, () => + this.mergePanel.reset(), + ); + } + + private mayLeave(): Promise { + return confirmLeave(this.app, { + mergeEdits: this.mergePanel.hasEdits, + picked: this.comparePanel?.choices.size ?? 0, }); } private showFile(path: string): void { - this.path = path; - this.historyHash = null; - this.historyLabel = "Version"; - this.historySize = undefined; - this.against = null; - this.historyChange = null; - this.historyPreviewIfMissing = false; + this.target = fileTarget(path); this.model = null; this.forceText = false; this.loadGeneration++; @@ -505,7 +476,5 @@ export class DiffView extends ItemView { this.mergePanel.destroy(); this.comparePanel?.destroy(); this.comparePanel = null; - this.previewPanel?.destroy(); - this.previewPanel = null; } } diff --git a/packages/plugin/src/editor/signs/compute.ts b/packages/plugin/src/features/editor-signs/compute.ts similarity index 98% rename from packages/plugin/src/editor/signs/compute.ts rename to packages/plugin/src/features/editor-signs/compute.ts index 58f39586..3ff055b1 100644 --- a/packages/plugin/src/editor/signs/compute.ts +++ b/packages/plugin/src/features/editor-signs/compute.ts @@ -2,7 +2,7 @@ import type { ChangeDesc } from "@codemirror/state"; import { type EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view"; import { debounce } from "obsidian"; -import { markedChanges } from "./helpers"; +import { markedChanges } from "./marks"; import { changesField, compareTextField, diff --git a/packages/plugin/src/editor/signs/extension.ts b/packages/plugin/src/features/editor-signs/extension.ts similarity index 100% rename from packages/plugin/src/editor/signs/extension.ts rename to packages/plugin/src/features/editor-signs/extension.ts diff --git a/packages/plugin/src/editor/signs/focus.ts b/packages/plugin/src/features/editor-signs/focus.ts similarity index 97% rename from packages/plugin/src/editor/signs/focus.ts rename to packages/plugin/src/features/editor-signs/focus.ts index ed37ff97..71db296c 100644 --- a/packages/plugin/src/editor/signs/focus.ts +++ b/packages/plugin/src/features/editor-signs/focus.ts @@ -5,7 +5,7 @@ import { StateField, } from "@codemirror/state"; import { Decoration, EditorView } from "@codemirror/view"; -import type { ChangeMark } from "./helpers"; +import type { ChangeMark } from "./marks"; /** The change under the pointer and the one whose popup is open: their marks widen, the open one tints its lines. */ export interface HunkFocus { diff --git a/packages/plugin/src/editor/signs/gutter.ts b/packages/plugin/src/features/editor-signs/gutter.ts similarity index 89% rename from packages/plugin/src/editor/signs/gutter.ts rename to packages/plugin/src/features/editor-signs/gutter.ts index f0a69004..75febccf 100644 --- a/packages/plugin/src/editor/signs/gutter.ts +++ b/packages/plugin/src/features/editor-signs/gutter.ts @@ -7,8 +7,8 @@ import { import { type EditorView, GutterMarker, gutter } from "@codemirror/view"; import { focusHunk, hunkFocusField, sameMark } from "./focus"; -import { type ChangeMark, findChangeForLine } from "./helpers"; -import { showHunkPopupAt } from "./hunk-popup"; +import { type ChangeMark, findChangeForLine } from "./marks"; +import { showHunkPopupAt } from "./popup/hunk-popup"; import type { SignsProvider } from "./provider"; import { type ChangesData, @@ -18,6 +18,7 @@ import { setCompareTextEffect, } from "./state"; +/** Each value is the suffix of its `mdsync-sign-` class in signs.css. */ const ESignKind = { Add: "add", Change: "change", @@ -27,14 +28,6 @@ const ESignKind = { } as const; type ESignKind = (typeof ESignKind)[keyof typeof ESignKind]; -const KIND_CLASS: Record = { - [ESignKind.Add]: "mdsync-sign-add", - [ESignKind.Change]: "mdsync-sign-change", - [ESignKind.Delete]: "mdsync-sign-delete", - [ESignKind.TopDelete]: "mdsync-sign-topdelete", - [ESignKind.ChangeDelete]: "mdsync-sign-changedelete", -}; - class SignMarker extends GutterMarker { constructor( private readonly kind: ESignKind, @@ -52,7 +45,7 @@ class SignMarker extends GutterMarker { } override toDOM(): HTMLElement { - const cls = `mdsync-sign ${KIND_CLASS[this.kind]}`; + const cls = `mdsync-sign mdsync-sign-${this.kind}`; return createDiv({ cls: this.wide ? `${cls} is-wide` : cls }); } } @@ -168,10 +161,7 @@ function buildMarkers(state: EditorState): RangeSet { /** One colour down a change, so a block reads as one stroke; its last line may also mark lines removed below. */ function signKind(mark: ChangeMark, line: number): ESignKind { - if (mark.kind === "add") return ESignKind.Add; - if (mark.kind === "delete") return ESignKind.Delete; - if (mark.kind === "topdelete") return ESignKind.TopDelete; return mark.removesBelow && line === mark.to ? ESignKind.ChangeDelete - : ESignKind.Change; + : mark.kind; } diff --git a/packages/plugin/src/features/editor-signs/host.ts b/packages/plugin/src/features/editor-signs/host.ts new file mode 100644 index 00000000..8c612358 --- /dev/null +++ b/packages/plugin/src/features/editor-signs/host.ts @@ -0,0 +1,10 @@ +import type { App } from "obsidian"; +import type { MdsyncSettings } from "@/core/settings"; +import type { SyncController } from "@/features/sync"; + +/** What the editor's change signs need from the plugin. */ +export interface EditorSignsHost { + readonly app: App; + settings: MdsyncSettings; + readonly controller: SyncController; +} diff --git a/packages/plugin/src/styles/editor/hunk-popup.css b/packages/plugin/src/features/editor-signs/hunk-popup.css similarity index 94% rename from packages/plugin/src/styles/editor/hunk-popup.css rename to packages/plugin/src/features/editor-signs/hunk-popup.css index eadfac61..e867faa2 100644 --- a/packages/plugin/src/styles/editor/hunk-popup.css +++ b/packages/plugin/src/features/editor-signs/hunk-popup.css @@ -23,7 +23,7 @@ /* A tile with the kind of change: + added, − removed, M both. */ .mdsync-hunk-popup-glyph { - --mdsync-hunk: var(--color-orange, #e9973f); + --mdsync-hunk: var(--mdsync-modified); display: inline-flex; flex: 0 0 24px; align-items: center; @@ -38,11 +38,11 @@ } .mdsync-hunk-popup-glyph.is-add { - --mdsync-hunk: var(--color-green, #2bb673); + --mdsync-hunk: var(--mdsync-added); } .mdsync-hunk-popup-glyph.is-delete { - --mdsync-hunk: var(--color-red, #d04a4a); + --mdsync-hunk: var(--mdsync-deleted); } .mdsync-hunk-popup-heading { @@ -123,11 +123,11 @@ } .mdsync-hunk-popup-line-removed { - background: rgba(var(--color-red-rgb), 0.14); + background: rgba(var(--mdsync-deleted-rgb), 0.14); } .mdsync-hunk-popup-line-added { - background: rgba(var(--color-green-rgb), 0.13); + background: rgba(var(--mdsync-added-rgb), 0.13); } .mdsync-hunk-popup-prefix { @@ -138,11 +138,11 @@ } .mdsync-hunk-popup-line-removed .mdsync-hunk-popup-prefix { - color: var(--color-red, #d04a4a); + color: var(--mdsync-deleted); } .mdsync-hunk-popup-line-added .mdsync-hunk-popup-prefix { - color: var(--color-green, #2bb673); + color: var(--mdsync-added); } .mdsync-hunk-popup-text { diff --git a/packages/plugin/src/features/editor-signs/index.ts b/packages/plugin/src/features/editor-signs/index.ts new file mode 100644 index 00000000..edc32850 --- /dev/null +++ b/packages/plugin/src/features/editor-signs/index.ts @@ -0,0 +1,2 @@ +export type { EditorSignsHost } from "./host"; +export { registerEditorSigns, type SignsHandle } from "./register"; diff --git a/packages/plugin/src/editor/signs/helpers.ts b/packages/plugin/src/features/editor-signs/marks.ts similarity index 97% rename from packages/plugin/src/editor/signs/helpers.ts rename to packages/plugin/src/features/editor-signs/marks.ts index 0c33d21b..9ceb9e57 100644 --- a/packages/plugin/src/editor/signs/helpers.ts +++ b/packages/plugin/src/features/editor-signs/marks.ts @@ -1,12 +1,11 @@ import { Text } from "@codemirror/state"; - +import { commonEnds } from "@/core/utils"; import { computeHunks, type HunkSegment, hunkSegments, type SyncHunk, -} from "@/sync/hunks"; -import { commonEnds } from "@/utils"; +} from "@/features/sync"; /** One change a gutter mark stands for: a segment of a sync hunk, the unit push and revert act on. */ export interface SyncChange { @@ -77,7 +76,7 @@ export function markedChanges(baseline: Text, current: Text): MarkedChange[] { } /** A change's lines here, less those that differ only by the note's final newline. */ -export function changeMark(change: SyncChange): ChangeMark { +function changeMark(change: SyncChange): ChangeMark { const { removedLines, addedLines } = presentSyncChange(change); const { head, tail } = commonEnds(removedLines, addedLines); const removed = removedLines.slice(head, removedLines.length - tail); diff --git a/packages/plugin/src/editor/signs/hunk-popup.ts b/packages/plugin/src/features/editor-signs/popup/hunk-popup.ts similarity index 91% rename from packages/plugin/src/editor/signs/hunk-popup.ts rename to packages/plugin/src/features/editor-signs/popup/hunk-popup.ts index 7f415fa7..78ee7845 100644 --- a/packages/plugin/src/editor/signs/hunk-popup.ts +++ b/packages/plugin/src/features/editor-signs/popup/hunk-popup.ts @@ -1,14 +1,14 @@ import type { EditorView } from "@codemirror/view"; import { type App, Modal, Platform } from "obsidian"; -import { asDrawer } from "@/ui/common"; +import { asDrawer } from "@/core/ui"; -import { focusHunk } from "./focus"; -import { findChangeForLine } from "./helpers"; +import { focusHunk } from "../focus"; +import { findChangeForLine } from "../marks"; +import type { SignsProvider } from "../provider"; +import { changesField, compareTextField } from "../state"; import { installDismissHandlers } from "./popup-dismiss"; import { positionPopup } from "./popup-placement"; import { buildPopup, type HunkTarget } from "./popup-view"; -import type { SignsProvider } from "./provider"; -import { changesField, compareTextField } from "./state"; let activePopup: { element: HTMLElement; cleanup: () => void } | null = null; let activeDrawer: HunkDrawer | null = null; diff --git a/packages/plugin/src/editor/signs/hunk-revert.ts b/packages/plugin/src/features/editor-signs/popup/hunk-revert.ts similarity index 93% rename from packages/plugin/src/editor/signs/hunk-revert.ts rename to packages/plugin/src/features/editor-signs/popup/hunk-revert.ts index 571f29a3..0d5b05ae 100644 --- a/packages/plugin/src/editor/signs/hunk-revert.ts +++ b/packages/plugin/src/features/editor-signs/popup/hunk-revert.ts @@ -1,6 +1,6 @@ import type { Text } from "@codemirror/state"; -import type { HunkSegment } from "@/sync/hunks"; +import type { HunkSegment } from "@/features/sync"; export interface TextChange { from: number; diff --git a/packages/plugin/src/editor/signs/popup-dismiss.ts b/packages/plugin/src/features/editor-signs/popup/popup-dismiss.ts similarity index 100% rename from packages/plugin/src/editor/signs/popup-dismiss.ts rename to packages/plugin/src/features/editor-signs/popup/popup-dismiss.ts diff --git a/packages/plugin/src/editor/signs/popup-placement.ts b/packages/plugin/src/features/editor-signs/popup/popup-placement.ts similarity index 92% rename from packages/plugin/src/editor/signs/popup-placement.ts rename to packages/plugin/src/features/editor-signs/popup/popup-placement.ts index 6fdce5d3..adfe84e4 100644 --- a/packages/plugin/src/editor/signs/popup-placement.ts +++ b/packages/plugin/src/features/editor-signs/popup/popup-placement.ts @@ -10,7 +10,7 @@ interface Size { height: number; } -export function placePopup(click: Point, size: Size, viewport: Size): Point { +function placePopup(click: Point, size: Size, viewport: Size): Point { let x = click.x + MARGIN; let y = click.y + MARGIN; if (x + size.width > viewport.width - MARGIN) { diff --git a/packages/plugin/src/editor/signs/popup-view.ts b/packages/plugin/src/features/editor-signs/popup/popup-view.ts similarity index 96% rename from packages/plugin/src/editor/signs/popup-view.ts rename to packages/plugin/src/features/editor-signs/popup/popup-view.ts index e13b7cd5..c294a354 100644 --- a/packages/plugin/src/editor/signs/popup-view.ts +++ b/packages/plugin/src/features/editor-signs/popup/popup-view.ts @@ -2,8 +2,8 @@ import type { Text } from "@codemirror/state"; import type { EditorView } from "@codemirror/view"; import { ButtonComponent, Platform } from "obsidian"; -import { pluralize } from "@/shared"; -import { appendIconButton, appendLabeledButton, notifyInfo } from "@/ui/common"; +import { pluralize } from "@/core/shared"; +import { appendIconButton, appendLabeledButton, notifyInfo } from "@/core/ui"; import { type ChangeMark, @@ -11,9 +11,9 @@ import { markPlace, presentSyncChange, type SyncChange, -} from "./helpers"; +} from "../marks"; +import type { SignsProvider } from "../provider"; import { segmentRevert } from "./hunk-revert"; -import type { SignsProvider } from "./provider"; const MAX_LINES = 30; diff --git a/packages/plugin/src/editor/signs/provider.ts b/packages/plugin/src/features/editor-signs/provider.ts similarity index 94% rename from packages/plugin/src/editor/signs/provider.ts rename to packages/plugin/src/features/editor-signs/provider.ts index 617f2e2f..3cf73d26 100644 --- a/packages/plugin/src/editor/signs/provider.ts +++ b/packages/plugin/src/features/editor-signs/provider.ts @@ -2,14 +2,14 @@ import type { Text } from "@codemirror/state"; import type { EditorView } from "@codemirror/view"; import type { App } from "obsidian"; -import { sha256Hex } from "@/crypto"; -import { reportWarning } from "@/shared"; -import { textToBytes } from "@/sync/content"; -import type { SyncController } from "@/sync/controller"; -import { notifyError, runWithNotice } from "@/ui"; - -import { type SyncChange, toCmText } from "./helpers"; -import { dismissPopupIn } from "./hunk-popup"; +import { sha256Hex } from "@/core/crypto"; +import { reportWarning } from "@/core/shared"; +import { notifyError, runWithNotice } from "@/core/ui"; +import type { SyncController } from "@/features/sync"; +import { textToBytes } from "@/features/sync"; + +import { type SyncChange, toCmText } from "./marks"; +import { dismissPopupIn } from "./popup/hunk-popup"; import { compareTextField, setCompareTextEffect } from "./state"; const BASELINE_CACHE_MAX = 64; diff --git a/packages/plugin/src/editor/signs/integration.ts b/packages/plugin/src/features/editor-signs/register.ts similarity index 89% rename from packages/plugin/src/editor/signs/integration.ts rename to packages/plugin/src/features/editor-signs/register.ts index 4dc03946..d495619c 100644 --- a/packages/plugin/src/editor/signs/integration.ts +++ b/packages/plugin/src/features/editor-signs/register.ts @@ -1,11 +1,9 @@ import type { Extension } from "@codemirror/state"; import type { Plugin, TAbstractFile } from "obsidian"; import { TFile } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; - import { buildSignsExtensions } from "./extension"; -import { dismissPopup } from "./hunk-popup"; +import type { EditorSignsHost } from "./host"; +import { dismissPopup } from "./popup/hunk-popup"; import { SignsProvider } from "./provider"; export interface SignsHandle { @@ -18,7 +16,9 @@ interface ActiveSignsRuntime { dispose(): void; } -export function registerEditorSigns(plugin: Plugin & PluginHost): SignsHandle { +export function registerEditorSigns( + plugin: Plugin & EditorSignsHost, +): SignsHandle { const mutable: Extension[] = []; let runtime: ActiveSignsRuntime | null = null; plugin.registerEditorExtension(mutable); @@ -52,7 +52,9 @@ export function registerEditorSigns(plugin: Plugin & PluginHost): SignsHandle { }; } -function createActiveRuntime(plugin: Plugin & PluginHost): ActiveSignsRuntime { +function createActiveRuntime( + plugin: Plugin & EditorSignsHost, +): ActiveSignsRuntime { const provider = new SignsProvider(plugin.controller, plugin.app); // Progress broadcasts arrive every frame during an operation; invalidating on each re-downloads every // open baseline. A baseline moves only with an installed or cleared result, which a saved-file patch is @@ -86,7 +88,7 @@ function createActiveRuntime(plugin: Plugin & PluginHost): ActiveSignsRuntime { } function onRename( - plugin: Plugin & PluginHost, + plugin: Plugin & EditorSignsHost, handler: (oldPath: string, newPath: string) => void, ): () => void { const ref = plugin.app.vault.on( @@ -108,7 +110,7 @@ function onRename( } function onFileOpen( - plugin: Plugin & PluginHost, + plugin: Plugin & EditorSignsHost, handler: () => void, ): () => void { const ref = plugin.app.workspace.on("file-open", () => handler()); diff --git a/packages/plugin/src/styles/editor/signs.css b/packages/plugin/src/features/editor-signs/signs.css similarity index 82% rename from packages/plugin/src/styles/editor/signs.css rename to packages/plugin/src/features/editor-signs/signs.css index 2786fc21..2b54c3ff 100644 --- a/packages/plugin/src/styles/editor/signs.css +++ b/packages/plugin/src/features/editor-signs/signs.css @@ -13,8 +13,8 @@ /* Square ends, so a block of changed lines reads as one stroke. */ .mdsync-sign { - --mdsync-sign-change: var(--color-orange, #e9973f); - --mdsync-sign-delete: var(--color-red, #d04a4a); + --mdsync-sign-change: var(--mdsync-modified); + --mdsync-sign-delete: var(--mdsync-deleted); position: absolute; top: 0; bottom: 0; @@ -30,7 +30,7 @@ } .mdsync-sign-add { - background-color: var(--color-green, #2bb673); + background-color: var(--mdsync-added); } .mdsync-sign-change { @@ -63,16 +63,16 @@ /* The lines of the change whose popup is open. */ .cm-line.mdsync-hunk-open { - --mdsync-hunk: var(--color-orange, #e9973f); + --mdsync-hunk: var(--mdsync-modified); background-color: color-mix(in srgb, var(--mdsync-hunk) 8%, transparent); } .cm-line.mdsync-hunk-open.is-add { - --mdsync-hunk: var(--color-green, #2bb673); + --mdsync-hunk: var(--mdsync-added); } .cm-line.mdsync-hunk-open:is(.is-delete, .is-topdelete) { - --mdsync-hunk: var(--color-red, #d04a4a); + --mdsync-hunk: var(--mdsync-deleted); } @media (prefers-reduced-motion: reduce) { diff --git a/packages/plugin/src/editor/signs/state.ts b/packages/plugin/src/features/editor-signs/state.ts similarity index 97% rename from packages/plugin/src/editor/signs/state.ts rename to packages/plugin/src/features/editor-signs/state.ts index c5df2243..79979207 100644 --- a/packages/plugin/src/editor/signs/state.ts +++ b/packages/plugin/src/features/editor-signs/state.ts @@ -6,7 +6,7 @@ import { } from "@codemirror/state"; import { editorInfoField } from "obsidian"; -import type { MarkedChange } from "./helpers"; +import type { MarkedChange } from "./marks"; export interface ChangesData { changes: readonly MarkedChange[]; diff --git a/packages/plugin/src/editor/signs/subscriber.ts b/packages/plugin/src/features/editor-signs/subscriber.ts similarity index 95% rename from packages/plugin/src/editor/signs/subscriber.ts rename to packages/plugin/src/features/editor-signs/subscriber.ts index 346b9a83..e4c1d504 100644 --- a/packages/plugin/src/editor/signs/subscriber.ts +++ b/packages/plugin/src/features/editor-signs/subscriber.ts @@ -1,6 +1,6 @@ import { type EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view"; -import { shouldRedeliverBaseline } from "./helpers"; +import { shouldRedeliverBaseline } from "./marks"; import type { SignsProvider } from "./provider"; import { compareTextField, pathFromState } from "./state"; diff --git a/packages/plugin/src/styles/explorer.css b/packages/plugin/src/features/explorer/explorer.css similarity index 95% rename from packages/plugin/src/styles/explorer.css rename to packages/plugin/src/features/explorer/explorer.css index 7655893c..89b97668 100644 --- a/packages/plugin/src/styles/explorer.css +++ b/packages/plugin/src/features/explorer/explorer.css @@ -1,17 +1,21 @@ /* One colour per kind of change, shared by the name and its mark. */ .nav-file-title.mdsync-changed-add { - --mdsync-change: var(--color-green); + --mdsync-change: var(--mdsync-added); } .nav-file-title.mdsync-changed-modify { - --mdsync-change: var(--color-orange); + --mdsync-change: var(--mdsync-modified); } .nav-file-title.mdsync-changed-move { --mdsync-change: var(--color-blue); } -.nav-file-title:is(.mdsync-changed-delete, .mdsync-changed-conflict) { +.nav-file-title.mdsync-changed-delete { + --mdsync-change: var(--mdsync-deleted); +} + +.nav-file-title.mdsync-changed-conflict { --mdsync-change: var(--color-red); } diff --git a/packages/plugin/src/ui/explorer/file-context-indicators.ts b/packages/plugin/src/features/explorer/file-context-indicators.ts similarity index 93% rename from packages/plugin/src/ui/explorer/file-context-indicators.ts rename to packages/plugin/src/features/explorer/file-context-indicators.ts index 89065929..cd7f4f87 100644 --- a/packages/plugin/src/ui/explorer/file-context-indicators.ts +++ b/packages/plugin/src/features/explorer/file-context-indicators.ts @@ -1,12 +1,11 @@ import { MarkdownView, type Plugin, setIcon } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; -import { makeActivatable, revealInFileExplorer } from "@/ui/common"; -import { createSymlinkDetector, type SymlinkDetector } from "@/vault/symlinks"; +import { makeActivatable, revealInFileExplorer } from "@/core/ui"; +import { createSymlinkDetector, type SymlinkDetector } from "@/core/vault"; +import type { ExplorerHost } from "./host"; import type { IndicatorHandle } from "./indicator-handle"; export function registerFileContextIndicators( - plugin: Plugin & PluginHost, + plugin: Plugin & ExplorerHost, ): IndicatorHandle { const root = plugin.addStatusBarItem(); root.addClass("mdsync-file-context", "mdsync-hidden"); @@ -151,7 +150,7 @@ export function registerFileContextIndicators( }; } -function createDetector(plugin: Plugin & PluginHost): SymlinkDetector { +function createDetector(plugin: Plugin & ExplorerHost): SymlinkDetector { return createSymlinkDetector( plugin.app.vault.adapter, plugin.settings.ignoreSymlinks, diff --git a/packages/plugin/src/ui/explorer/file-explorer-api.ts b/packages/plugin/src/features/explorer/file-explorer-api.ts similarity index 100% rename from packages/plugin/src/ui/explorer/file-explorer-api.ts rename to packages/plugin/src/features/explorer/file-explorer-api.ts diff --git a/packages/plugin/src/ui/explorer/file-explorer-badges.ts b/packages/plugin/src/features/explorer/file-explorer-badges.ts similarity index 88% rename from packages/plugin/src/ui/explorer/file-explorer-badges.ts rename to packages/plugin/src/features/explorer/file-explorer-badges.ts index dd9eeedb..f7025d47 100644 --- a/packages/plugin/src/ui/explorer/file-explorer-badges.ts +++ b/packages/plugin/src/features/explorer/file-explorer-badges.ts @@ -1,10 +1,8 @@ -import { Notice, Platform, setIcon } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; -import { describePeople, lastEditLabel, renderAvatarStack } from "@/ui/common"; -import { openManageLinks } from "@/ui/links"; -import { openShareWindow } from "@/ui/shares/share-window"; - +import { Platform, setIcon } from "obsidian"; +import { tapTooltip } from "@/core/ui"; +import { openManageLinks } from "@/features/links"; +import { describePeople, renderAvatarStack } from "@/features/presence"; +import { lastEditLabel, openShareWindow } from "@/features/spaces"; import type { PresenceMarks, PublishedMark, @@ -12,6 +10,7 @@ import type { ShareMark, UnseenMark, } from "./file-explorer-marks"; +import type { ExplorerHost } from "./host"; const SHARE_ICONS: Record = { owned: "share-2", @@ -30,13 +29,12 @@ const SHARE_BADGE = ".mdsync-share-badge"; const PUBLISHED_BADGE = ".mdsync-published-badge"; const TAP_BADGES = ".mdsync-people-badge, .mdsync-unseen-dot, .mdsync-skip-badge, .mdsync-ignore-badge, .mdsync-change-mark"; -const TIP_MS = 4000; /** Read here, not while computing marks: a pass runs on every sync event. */ export function renderPresenceMarks( target: HTMLElement, marks: PresenceMarks, - plugin: PluginHost, + plugin: ExplorerHost, ): void { if (marks.unseen) { target.createSpan({ @@ -60,9 +58,9 @@ export function renderPresenceMarks( /** Action badges open management; other badges show a tooltip on phones. */ export function badgeActivation( - plugin: PluginHost, + plugin: ExplorerHost, ): (event: MouseEvent | KeyboardEvent) => void { - let tip: Notice | null = null; + const showTip = tapTooltip(); return (event) => { if ("key" in event && event.key !== "Enter" && event.key !== " ") return; if (!(event.target instanceof Element)) return; @@ -76,8 +74,7 @@ export function badgeActivation( event.preventDefault(); event.stopPropagation(); if (mark) { - tip?.hide(); - tip = new Notice(mark.getAttribute("aria-label") ?? "", TIP_MS); + showTip(mark); return; } if (published) { @@ -92,7 +89,7 @@ export function badgeActivation( } function unseenTooltip( - plugin: PluginHost, + plugin: ExplorerHost, { count, file }: UnseenMark, ): string { if (file) return lastEditLabel(plugin, file) ?? "Changed by someone else"; diff --git a/packages/plugin/src/ui/explorer/file-explorer-decorations.ts b/packages/plugin/src/features/explorer/file-explorer-decorations.ts similarity index 94% rename from packages/plugin/src/ui/explorer/file-explorer-decorations.ts rename to packages/plugin/src/features/explorer/file-explorer-decorations.ts index 4051163a..e4a2bffc 100644 --- a/packages/plugin/src/ui/explorer/file-explorer-decorations.ts +++ b/packages/plugin/src/features/explorer/file-explorer-decorations.ts @@ -1,17 +1,14 @@ import { setIcon } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; -import type { SyncController } from "@/sync/controller"; -import type { EChangeType } from "@/sync/types"; +import type { EChangeType, SyncController } from "@/features/sync"; import { type ChangeAction, changeActionOf, skippedFiles, skippedText, -} from "@/ui/common"; - +} from "@/features/sync"; import { renderPresenceMarks } from "./file-explorer-badges"; import type { PresenceMarks } from "./file-explorer-marks"; +import type { ExplorerHost } from "./host"; type ChangeKind = ChangeAction | "move" | "conflict"; @@ -60,9 +57,9 @@ const TARGET_CLASSES = [ ]; export function computeBase( - plugin: PluginHost, + plugin: ExplorerHost, controller: SyncController, - directLinks: ReadonlyMap, + directLinks: ReadonlySet, ): Map { const out = new Map(); const statuses = controller.fileDiffs.getChangedPathStatuses(); @@ -77,8 +74,8 @@ export function computeBase( if (statuses.get(path) === "conflict") continue; patchDecoration(out, path, { change: { kind: "move", incoming } }); } - for (const [path, linkRoot] of directLinks) { - patchDecoration(out, path, { linkRoot }); + for (const path of directLinks) { + patchDecoration(out, path, { linkRoot: path }); } const ignored = plugin.ignoreState.ignoredPaths(); for (const path of ignored) { @@ -121,7 +118,7 @@ export function sameDecoration( export function renderDecoration( target: HTMLElement, decoration: PathDecoration, - plugin: PluginHost, + plugin: ExplorerHost, ): void { const { change, ignored, skipped, linkRoot, share } = decoration; if (change) { diff --git a/packages/plugin/src/ui/explorer/file-explorer-indicators.ts b/packages/plugin/src/features/explorer/file-explorer-indicators.ts similarity index 97% rename from packages/plugin/src/ui/explorer/file-explorer-indicators.ts rename to packages/plugin/src/features/explorer/file-explorer-indicators.ts index eb009d66..745638e6 100644 --- a/packages/plugin/src/ui/explorer/file-explorer-indicators.ts +++ b/packages/plugin/src/features/explorer/file-explorer-indicators.ts @@ -1,19 +1,17 @@ import type { Plugin, TAbstractFile } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; -import type { SyncController } from "@/sync/controller"; - +import type { SyncController } from "@/features/sync"; import { readFileExplorer, readFileExplorerContainer, } from "./file-explorer-api"; import { badgeActivation } from "./file-explorer-badges"; +import type { ExplorerHost } from "./host"; import type { IndicatorHandle } from "./indicator-handle"; import { LinkScan } from "./link-scan"; import { RowDecorator } from "./row-decorator"; export function registerFileExplorerIndicators( - plugin: Plugin & PluginHost, + plugin: Plugin & ExplorerHost, controller: SyncController, ): IndicatorHandle { const decorator = new RowDecorator(plugin, controller); diff --git a/packages/plugin/src/ui/explorer/file-explorer-marks.ts b/packages/plugin/src/features/explorer/file-explorer-marks.ts similarity index 88% rename from packages/plugin/src/ui/explorer/file-explorer-marks.ts rename to packages/plugin/src/features/explorer/file-explorer-marks.ts index 194319af..0dad231b 100644 --- a/packages/plugin/src/ui/explorer/file-explorer-marks.ts +++ b/packages/plugin/src/features/explorer/file-explorer-marks.ts @@ -1,7 +1,7 @@ -import { type LinkRecord, noteLinks, noteLinksText } from "@/links"; -import type { PluginHost } from "@/plugin/host"; -import { isAtNote, mergePeople, type Person } from "@/presence"; -import { type Space, spaceOf, VAULT_SPACE } from "@/sync/space"; +import { type LinkRecord, noteLinks, noteLinksText } from "@/features/links"; +import { isAtNote, mergePeople, type Person } from "@/features/presence"; +import { type Space, spaceOf, VAULT_SPACE } from "@/features/sync"; +import type { ExplorerHost } from "./host"; export type ShareKind = "owned" | "joined" | "read-only" | "paused"; @@ -33,7 +33,7 @@ export interface PresenceMarks { } export function shareMarks( - plugin: PluginHost, + plugin: ExplorerHost, spaces: readonly Space[] = plugin.spaces.partition(), ): Map { const out = new Map(); @@ -76,7 +76,7 @@ export function shareMarks( /** A note inside a collapsed folder hands its marks to the outermost collapsed folder above it, the row that shows. */ export function presenceMarks( - plugin: PluginHost, + plugin: ExplorerHost, collapsed: (folder: string) => boolean, ): Map { const spaces = plugin.spaces.partition(); @@ -98,7 +98,7 @@ export function presenceMarks( return out; } -function shareKind(plugin: PluginHost, space: Space): ShareKind { +function shareKind(plugin: ExplorerHost, space: Space): ShareKind { if (space.paused) return "paused"; if (space.readOnly) return "read-only"; return plugin.spaces.get(space.id)?.access.kind === "participant" @@ -108,7 +108,7 @@ function shareKind(plugin: PluginHost, space: Space): ShareKind { /** Files, not rows: a stale path of a file deleted while closed shows nowhere. */ function unseenRows( - plugin: PluginHost, + plugin: ExplorerHost, collapsed: (folder: string) => boolean, ): Map { const rows = new Map(); diff --git a/packages/plugin/src/features/explorer/host.ts b/packages/plugin/src/features/explorer/host.ts new file mode 100644 index 00000000..e36c8bfa --- /dev/null +++ b/packages/plugin/src/features/explorer/host.ts @@ -0,0 +1,8 @@ +import type { LinksHost } from "@/features/links"; +import type { Unseen } from "@/features/presence"; +import type { SpacesHost } from "@/features/spaces"; + +/** What the file tree marks need from the plugin: they offer share and link actions. */ +export interface ExplorerHost extends SpacesHost, LinksHost { + readonly unseen: Unseen; +} diff --git a/packages/plugin/src/features/explorer/index.ts b/packages/plugin/src/features/explorer/index.ts new file mode 100644 index 00000000..f39c8870 --- /dev/null +++ b/packages/plugin/src/features/explorer/index.ts @@ -0,0 +1,4 @@ +export { registerFileContextIndicators } from "./file-context-indicators"; +export { registerFileExplorerIndicators } from "./file-explorer-indicators"; +export type { ExplorerHost } from "./host"; +export type { IndicatorHandle } from "./indicator-handle"; diff --git a/packages/plugin/src/ui/explorer/indicator-handle.ts b/packages/plugin/src/features/explorer/indicator-handle.ts similarity index 100% rename from packages/plugin/src/ui/explorer/indicator-handle.ts rename to packages/plugin/src/features/explorer/indicator-handle.ts diff --git a/packages/plugin/src/ui/explorer/link-scan.ts b/packages/plugin/src/features/explorer/link-scan.ts similarity index 74% rename from packages/plugin/src/ui/explorer/link-scan.ts rename to packages/plugin/src/features/explorer/link-scan.ts index 52edfc23..d3dfedf6 100644 --- a/packages/plugin/src/ui/explorer/link-scan.ts +++ b/packages/plugin/src/features/explorer/link-scan.ts @@ -1,10 +1,10 @@ import type { DataAdapter } from "obsidian"; -import { createSymlinkDetector, type SymlinkDetector } from "@/vault/symlinks"; +import { createSymlinkDetector, type SymlinkDetector } from "@/core/vault"; import type { FileExplorerRows } from "./file-explorer-api"; const BATCH = 64; -const NO_LINKS: ReadonlyMap = new Map(); +const NO_LINKS: ReadonlySet = new Set(); interface LinkScanHost { enabled(): boolean; @@ -29,7 +29,7 @@ export class LinkScan { this.detector = createSymlinkDetector(adapter, this.enabled); } - get links(): ReadonlyMap { + get links(): ReadonlySet { return this.found; } @@ -57,9 +57,9 @@ export class LinkScan { this.checked.delete(checked); } this.publish( - new Map( + new Set( [...this.found].filter( - ([found]) => found !== path && !found.startsWith(`${path}/`), + (found) => found !== path && !found.startsWith(`${path}/`), ), ), ); @@ -85,14 +85,12 @@ export class LinkScan { const paths = explorer.paths(); const pending = paths.filter((path) => !this.checked.has(path)); const visible = new Set(paths); - const found = new Map( - [...this.found].filter(([path]) => visible.has(path)), - ); + const found = new Set([...this.found].filter((path) => visible.has(path))); if (pending.length === 0) this.publish(found); else this.check(pending, found); } - private check(pending: string[], found: Map): void { + private check(pending: string[], found: Set): void { const generation = ++this.generation; let index = 0; const batch = (): void => { @@ -102,9 +100,9 @@ export class LinkScan { const path = pending[index]; if (!path) continue; this.checked.add(path); - if (this.detector.findLink(path) === path) found.set(path, path); + if (this.detector.findLink(path) === path) found.add(path); } - this.publish(new Map(found)); + this.publish(new Set(found)); if (index < pending.length) { this.frame = window.requestAnimationFrame(batch); return; @@ -118,20 +116,16 @@ export class LinkScan { this.frame = window.requestAnimationFrame(batch); } - private publish(found: ReadonlyMap): void { - if (sameStringMap(found, this.found)) return; + private publish(found: ReadonlySet): void { + if (sameStringSet(found, this.found)) return; this.found = found; this.host.linksChanged(); } } -function sameStringMap( - left: ReadonlyMap, - right: ReadonlyMap, +function sameStringSet( + left: ReadonlySet, + right: ReadonlySet, ): boolean { - if (left.size !== right.size) return false; - for (const [key, value] of left) { - if (right.get(key) !== value) return false; - } - return true; + return left.size === right.size && [...left].every((path) => right.has(path)); } diff --git a/packages/plugin/src/ui/explorer/row-decorator.ts b/packages/plugin/src/features/explorer/row-decorator.ts similarity index 90% rename from packages/plugin/src/ui/explorer/row-decorator.ts rename to packages/plugin/src/features/explorer/row-decorator.ts index f22f1b76..bf05d46c 100644 --- a/packages/plugin/src/ui/explorer/row-decorator.ts +++ b/packages/plugin/src/features/explorer/row-decorator.ts @@ -1,6 +1,5 @@ -import type { PluginHost } from "@/plugin/host"; -import type { SyncController } from "@/sync/controller"; -import { skippedFiles } from "@/ui/common"; +import type { SyncController } from "@/features/sync"; +import { skippedFiles } from "@/features/sync"; import type { FileExplorerRows } from "./file-explorer-api"; import { type AppliedDecoration, @@ -17,6 +16,7 @@ import { presenceMarks, shareMarks, } from "./file-explorer-marks"; +import type { ExplorerHost } from "./host"; const NO_BASE: ReadonlyMap = new Map(); const NO_MARKS: ReadonlyMap = new Map(); @@ -32,7 +32,7 @@ export class RowDecorator { private ignoreVersion = 0; constructor( - private readonly plugin: PluginHost, + private readonly plugin: ExplorerHost, private readonly controller: SyncController, ) {} @@ -42,7 +42,7 @@ export class RowDecorator { apply( explorer: FileExplorerRows, - directLinks: ReadonlyMap, + directLinks: ReadonlySet, indicators: boolean, rowsChanged: boolean, ): void { @@ -73,7 +73,7 @@ export class RowDecorator { } private baseMarks( - directLinks: ReadonlyMap, + directLinks: ReadonlySet, ): ReadonlyMap { const inputs = [ this.controller.fileDiffs.getChangedPathStatuses(), diff --git a/packages/plugin/src/features/links/README.md b/packages/plugin/src/features/links/README.md new file mode 100644 index 00000000..8048e194 --- /dev/null +++ b/packages/plugin/src/features/links/README.md @@ -0,0 +1,116 @@ +# Share links + +Share one note by a link that opens in any browser, with an optional passphrase, view limit and expiry. The plugin renders the note to HTML, seals it on the device and uploads the ciphertext to the owner's relay; the page a link opens is `packages/viewer` (`packages/viewer/README.md`), served by the relay. Not a shared folder (`features/spaces`): no accounts, no sync, a read-only snapshot. Constraints: `.claude/rules/links.md`. + +## Decisions + +| Decision | Why | +| --- | --- | +| The plugin renders the note (`MarkdownRenderer`) and uploads that HTML, sealed | callouts, math, mermaid, code, tasks and other plugins' blocks come free and follow Obsidian; the viewer needs no Markdown parser | +| Random key in the URL `#fragment`; the relay stores ciphertext | zero knowledge; the fragment never reaches a server | +| The viewer is a static package served by the relay worker (Workers Static Assets) | one deploy, one origin, no CORS, no third-party host | +| One `Link` Durable Object per link holds blob, counter, gate, expiry | the view limit must be atomic; KV is eventually consistent (a spent link could be served again) | +| A view counts when the ciphertext is served, not when the page loads | link-preview bots fetch only the shell | +| Every link has a gate derived from the fragment key (plus the passphrase), checked by the relay before it serves or updates | the id alone burns no view and yields no ciphertext; a wrong guess burns no view; without the fragment the operator cannot test a guess, even offline | +| Link records travel through the vault storage (`links/.json.enc`, vault key), last writer wins, no tombstones | any device of the person can copy, update or stop a link; the link, key included, must be re-copyable | + +## Format + +`https:///s/#[/]`: `id` 16 random bytes base64url, `key` 16 random bytes base64url, `anchor` an optional heading slug, URI-encoded (base64url has no `/`, so it cannot run into the key). Payload `{title, html, createdAt}` (`createdAt` = snapshot time; `title` is empty when **Show the note's name** is off) -> JSON -> deflate -> AES-GCM. Content key and gate are two HKDF outputs; a protected link also mixes in PBKDF2 (600k) of the trimmed passphrase and a stored salt. Defined once in `packages/protocol/src/link.ts`. + +The relay knows: id, size, expiry, view limit and count, protected yes/no, salt, timings. Not the title, text or key. + +## Entry points + +- Note file menu **MDSync: Share link** (`features/links/ui/link-menu.ts`), command `share-note-link`; hidden for non-Markdown and Excalidraw files. Without a configured relay the item reads "(set up a relay)" and opens the setup wizard's relay step. +- Commands `update-note-links` (the active note's links) and `manage-note-links` (**Manage share links**); settings Sync tab **Share links**; menu item **Share links of this note (n)**. Ids are in `app/commands.ts` and never change. +- A `globe` badge in the file tree (`features/explorer/file-explorer-badges.ts`, shown even with file indicators off; `link-2` marks a symlinked path) and a header button on the open note (`features/links/ui/note-link-action.ts`) open the note's links; a dot marks stale. +- **Share a link** modal (`features/links/ui/share-link-modal.ts`): Expires (5 minutes to 30 days, never, or an exact date 1 minute to 365 days ahead), Views (1, 5, 25, unlimited), Passphrase (optional, 8+ characters, **Generate**), Include images, Show the note's name, and a "Left out of the link" line from the snapshot. Create is disabled until the preview exists; the modal cannot close while the upload runs, because the passphrase is shown once in the result and never stored. +- **Manage** modal (`features/links/ui/manage-links-modal.ts`): a row per link with views left (status call), expiry, **Copy link**, **Update**, **Stop sharing**. An ended link, or one made through another relay than the current one, can only be removed from the list. + +## Snapshot + +`features/links/snapshot/snapshot.ts` renders with `MarkdownRenderer.render` into an element attached to the document and hidden off screen (`.mdsync-link-render`, `features/links/ui/links.css`) with a throwaway `Component`; detached, callout icons stay empty. It waits until images and math settle (5 s cap; `complete: false` warns that the preview may be unfinished), swaps math, then runs `features/links/snapshot/sanitize.ts`, a DOM pass. Properties are never published: the renderer does not draw them, and `pre.frontmatter` is removed anyway. + +| In the rendered DOM | Becomes | +| --- | --- | +| `pre.frontmatter` (raw YAML) | removed: it holds every property, secrets included | +| `a.internal-link` (any vault link) and any `href` that is not http(s), mailto or `#` | its text, no element | +| `a.tag` | its text in `span.tag` | +| external `a` | kept; the viewer adds `rel` and `target` | +| `a[href^="#"]` (footnotes) | kept, `target` and `rel` dropped | +| `.internal-embed` of a note, audio, video, pdf or a missing file | removed, counted | +| `.internal-embed` with an `img` (image embed) | the `img`, its `src` and path-like `alt` removed, then inlined as a `data:` URI read from the vault by the embed's link text (`features/links/snapshot/images.ts`), or dropped and counted | +| external `img` | kept (the viewer's IP goes to that host; `no-referrer` is set) | +| `img` with a `src` that is not `data:image/` or `https://` | removed, counted | +| `audio video iframe object embed script style button` (incl. copy-code buttons) | removed | +| `%%comment%%`, `` | dropped by the renderer, leaving an empty `

`: empty paragraphs removed | +| `.callout-content` with `style` (folded) | style removed; Obsidian's `is-collapsed` class stays, the viewer folds | +| `.mermaid-wrapper.is-guarded` (the vault has not allowed Mermaid) | its source as a code block, counted; a rendered `svg` is kept | +| `mjx-container` (MathJax CHTML, no TeX kept) | MathML (`features/links/snapshot/math.ts`): patches `window.MathJax.tex2chtml` (the main window's global, not `activeWindow`) while a snapshot runs, tags each node with its TeX, converts with `tex2mml`, sets `data-tex`. One MathJax cannot convert stays as TeX in `code` | +| `data-href`, `contenteditable`, `draggable`, `on*`, class `node-insert-event` | removed; other `class` and `data-*` kept | +| task checkboxes | disabled | + +Images: JPEGs are always redrawn (drops EXIF and GPS); other flat images over 300 KB are re-encoded to WebP at 1600 px on the long edge when that is smaller; GIF and SVG are kept whole. Per image 1.5 MiB, total 4 MiB of data URIs, then dropped and counted. + +## Flows + +- **Preview**: `previewLink` reads the note (`features/links/snapshot/note-text.ts`: an open editor's text wins over the file) and takes the snapshot; `takenAt` is read just before. **Create** publishes that exact `Snapshot`. +- **Publish** (`features/links/publish.ts`): new id, key and salt, seal, `PUT /link/` through `features/links/link-broker.ts` (`requestUrl`, admin header), then `SharedLinks.add`. An older relay answers `not_found`, or a creation without `expires` (it ignores `ttl`, so the link is revoked again): the error says to redeploy the relay. If the record cannot be saved the link is revoked again; if that fails too the record stays in memory for the next save. +- **Update**: render again (links of one note share at most two renders: with and without images), seal with the same id, key and passphrase (asked for a protected link), `PUT ?update=1`, then `published`. The relay keeps counter, limits and expiry, so an update never revives a spent link; a wrong passphrase is refused (403 `gate`) and cannot re-key it. +- **Stop**: `DELETE /link/`, then `SharedLinks.remove`. Unreachable keeps it listed to try again. +- **Moves**: `registerLinkPaths` (`features/links/register.ts`): rename moves the stored path (also under a renamed folder), delete detaches (the links stay live and listed under Manage with no Update; a new note at that path starts clean). +- **Stale**: `file.stat.mtime > publishedAt` (`noteLinks`, `isStale`); a pulled write gets a local mtime. The list starts such a row with "Changed since it was shared." + +## Records and trading + +`settings.links` holds `StoredLink`s: the published `LinkRecord` (`id`, `url` with key, `path`, `showTitle`, `createdAt`, `publishedAt`, `expires` as the relay set it, `maxViews`, `salt`, `images`, `detached`, `rev`, `author`) plus local-only `vault` (storage identity last traded with) and `removed`. In the plugin data file they sit in the device-key envelope (`app/settings/envelope.ts`); in the vault storage each is sealed under the vault key. + +`SharedLinks.sync` runs from the `spaces()` hook in `app/bootstrap.ts` after the space records, only with vault storage; a write or delete there signals the person's other devices. `add` and `remove` ask for a refresh (`announce`). `tradeLinks` (`features/links/remote.ts`) per local link: + +| Case | Result | +| --- | --- | +| `removed` | delete the object by name (listed or not), forget; a failed delete throws and is retried | +| object listed but unreadable | keep local, never write over | +| not listed, `vault` = this storage | removed elsewhere: dropped, even if edited here | +| not listed otherwise, or local `isNewer` | write, `vault` = this storage (a copy last traded with another storage is published to this one) | +| remote newer | take remote | +| same revision, `vault` = this storage | keep local, so a trade that brought nothing saves nothing | +| listed remotely only | added | + +Edits made while a trade runs are replayed onto its outcome with a fresh revision above what it took in, also those that matched nothing yet (a rename of a link the trade brings in). + +## Relay (`packages/relay/src/link/`) + +| Route | Auth | Does | +| --- | --- | --- | +| `PUT /link/` | admin | body = sealed bytes; query `maxViews`, `ttl` (seconds on the relay's clock); headers `X-Mdsync-Gate` (required), `X-Mdsync-Salt` (protected). Creates (409 if one stands) and answers `{stored, size, expires}`; `?update=1` replaces only the blob of a standing link (404 `gone` if not, 403 `gate` on another gate). 400 bad settings, 413 over 6 MiB | +| `DELETE /link/` | admin | revoke: erase everything | +| `GET /link//status` | admin | `{views, maxViews, expires, protected, size}`; 404 when gone | +| `GET /link//meta` | none | `{protected, salt}`; counts nothing | +| `POST /link//open` | none | `{gate}` (body 1 KiB max) -> sealed bytes with `X-Mdsync-Views-Left` / `X-Mdsync-Expires`; counts a view; 401 wrong gate, 429 cooldown (`Retry-After`), 404 missing, expired and spent alike | +| `GET /s/` | none | viewer shell from `ASSETS` with the CSP | + +- `Link` DO (SQLite, migration `v3` in `packages/relay/wrangler.toml`): blob in 1 MiB rows (a SQLite value caps at 2 MB), 6 MiB sealed in total. `open` runs in one synchronous turn: expiry, cooldown, gate, `views++`, erase when spent. An alarm at the expiry erases too and `deleteAll` frees the file. +- Cooldown per client (`CF-Connecting-IP` hashed, IPv6 reduced to its /64): 5 misses in a row, then 1 min doubling up to 1 h, even the right gate refused meanwhile; 128 clients remembered per link, a locked one ranks by when its lock ends. +- Shell headers: CSP (`default-src 'none'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; img-src data: https:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`), `Referrer-Policy: no-referrer`, `X-Robots-Tag: noindex, nofollow`, `nosniff`. `open`, `meta` and `status` answer `Cache-Control: no-store`. +- Deploying: the Deploy Relay workflow builds the viewer first; an older relay lacks the `Link` DO and assets. + +## Tests + +`packages/plugin/tests/features/links/` (the sanitizer runs on the real renderer's output, `packages/plugin/tests/features/links/snapshot/fixtures/rendered-note.html`, under jsdom), `packages/relay/tests/link/` (in-process DO store, one-view link with concurrent opens), `pnpm e2e:links` (`wrangler dev` and headless Chrome), `pnpm e2e:links-obsidian` (a real Obsidian: menu, modal, passphrase, view count, update, stop). + +## Accepted limitations + +- A view limit and a passphrase deter, they are not DRM: a reader can copy or screenshot. Stopping a link is immediate, but whoever opened it keeps what they saw. +- Without a passphrase the link is the capability: a leaked full URL opens until the limit or expiry. +- The relay serves the viewer script, so a hostile operator could read a note. The operator is the owner of the deployment (one trust domain). +- A closed tab after the response, or a failed decrypt, still counts a view. Readers behind one address share a cooldown. +- No link previews: the content is sealed, the shell is generic. +- Pasted HTML with `style` attributes can position or overlay parts of the page (the CSP allows inline style attributes); the author is the link's owner. External images tell their host the reader's IP. +- The snapshot is static until **Update**, rendered as the owner's Obsidian. Other plugins' output (Dataview) is published as rendered and can include data from other notes: the preview is the check. +- "Changed since it was shared" compares file times, so a touch, a sync rewrite or an autosave of an unsaved note can show it falsely. +- Every random id asked of the public routes wakes a Durable Object; only the relay's own cost limits that. +- No remote tombstones. Known risk: two devices that each still hold a link removed on a third can bring it back as a list entry (a copy never traded, or last traded with another storage, is published to the current one). Its relay payload stays gone; remove it again. A lagging listing only drops a copy the storage still holds, and the next trade restores it. Other devices list a removed link until their next refresh. +- Ended links stay listed until someone removes them; a link made through another relay is manageable only after setting that relay again. +- Markdown notes only: drawings, canvases and bases are not offered. diff --git a/packages/plugin/src/links/describe.ts b/packages/plugin/src/features/links/describe.ts similarity index 100% rename from packages/plugin/src/links/describe.ts rename to packages/plugin/src/features/links/describe.ts diff --git a/packages/plugin/src/links/errors.ts b/packages/plugin/src/features/links/errors.ts similarity index 69% rename from packages/plugin/src/links/errors.ts rename to packages/plugin/src/features/links/errors.ts index 1883ee29..f1338583 100644 --- a/packages/plugin/src/links/errors.ts +++ b/packages/plugin/src/features/links/errors.ts @@ -1,5 +1,5 @@ -import { asError } from "@/shared"; -import { StorageRequestError } from "@/storage"; +import { asError } from "@/core/shared"; +import { StorageRequestError } from "@/features/storage"; /** A relay refusal in the owner's words; any other error as it came. */ export function linkError(err: unknown): Error { diff --git a/packages/plugin/src/features/links/host.ts b/packages/plugin/src/features/links/host.ts new file mode 100644 index 00000000..ba51b4f2 --- /dev/null +++ b/packages/plugin/src/features/links/host.ts @@ -0,0 +1,10 @@ +import type { App } from "obsidian"; +import type { SettingsHost } from "@/core/settings"; +import type { SharedLinks } from "./shared-links"; + +/** What share links need from the plugin. */ +export interface LinksHost extends SettingsHost { + readonly app: App; + readonly sharedLinks: SharedLinks; + openSetup(step: "relay"): void; +} diff --git a/packages/plugin/src/features/links/index.ts b/packages/plugin/src/features/links/index.ts new file mode 100644 index 00000000..d946e9be --- /dev/null +++ b/packages/plugin/src/features/links/index.ts @@ -0,0 +1,19 @@ +export type { LinksHost } from "./host"; +export { noteLinks, noteLinksText } from "./note-links"; +export { + type LinkRecord, + onRelay, + parseStoredLinks, + type StoredLink, +} from "./record"; +export { registerLinkPaths } from "./register"; +export { SharedLinks } from "./shared-links"; +export { updateSharedLinks } from "./ui/link-actions"; +export { + addLinkMenuItems, + isLinkable, + openManageLinks, + openShareLink, +} from "./ui/link-menu"; +export { linksSection } from "./ui/links-section"; +export { registerNoteLinkActions } from "./ui/note-link-action"; diff --git a/packages/plugin/src/storage/adapters/link-broker.ts b/packages/plugin/src/features/links/link-broker.ts similarity index 92% rename from packages/plugin/src/storage/adapters/link-broker.ts rename to packages/plugin/src/features/links/link-broker.ts index 40c7368b..5313e037 100644 --- a/packages/plugin/src/storage/adapters/link-broker.ts +++ b/packages/plugin/src/features/links/link-broker.ts @@ -1,12 +1,10 @@ -import { LINK_HEADERS, type LinkStatus } from "@mdsync/protocol"; +import { ADMIN_HEADER, LINK_HEADERS, type LinkStatus } from "@mdsync/protocol"; import { requestUrl } from "obsidian"; -import { relayBase } from "@/shared"; -import { StorageRequestError } from "@/storage/types"; -import { toArrayBuffer } from "@/utils"; - -import { ADMIN_HEADER, type BrokerAdmin } from "./share-broker"; -import { errorCode, StorageHttpError } from "./util"; +import { relayBase, StorageHttpError } from "@/core/shared"; +import { toArrayBuffer } from "@/core/utils"; +import type { BrokerAdmin } from "@/features/spaces"; +import { errorCode, StorageRequestError } from "@/features/storage"; const OUTDATED_RELAY = "This relay is out of date for share links. Redeploy it with the Deploy Relay workflow."; diff --git a/packages/plugin/src/links/note-links.ts b/packages/plugin/src/features/links/note-links.ts similarity index 94% rename from packages/plugin/src/links/note-links.ts rename to packages/plugin/src/features/links/note-links.ts index cee39829..beeff49d 100644 --- a/packages/plugin/src/links/note-links.ts +++ b/packages/plugin/src/features/links/note-links.ts @@ -1,6 +1,5 @@ -import type { PluginHost } from "@/plugin/host"; - import { expiryLine } from "./describe"; +import type { LinksHost } from "./host"; import { isExpired, isStale, type LinkRecord } from "./record"; /** A note's live links, and whether one still shows a copy older than the note. */ @@ -11,7 +10,7 @@ export interface NoteLinks { /** Null when the note has no links, or only expired ones. */ export function noteLinks( - plugin: PluginHost, + plugin: LinksHost, path: string, /** The note's links when the caller already grouped them. */ of: readonly LinkRecord[] = plugin.sharedLinks.of(path), diff --git a/packages/plugin/src/links/publish.ts b/packages/plugin/src/features/links/publish.ts similarity index 89% rename from packages/plugin/src/links/publish.ts rename to packages/plugin/src/features/links/publish.ts index 6f540102..25c49dd9 100644 --- a/packages/plugin/src/links/publish.ts +++ b/packages/plugin/src/features/links/publish.ts @@ -11,21 +11,16 @@ import { toBase64Url, } from "@mdsync/protocol"; import type { TFile } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; -import { isRelayConfigured, relayAdmin } from "@/settings/model"; -import { relayBase } from "@/shared"; -import { - type BrokerAdmin, - createLink, - linkStatus, - replaceLink, - revokeLink, -} from "@/storage"; -import { noteText } from "./note-text"; +import { isRelayConfigured } from "@/core/settings"; +import { relayBase } from "@/core/shared"; +import type { BrokerAdmin } from "@/features/spaces"; +import { relayAdmin } from "@/features/spaces"; +import type { LinksHost } from "./host"; +import { createLink, linkStatus, replaceLink, revokeLink } from "./link-broker"; import { type LinkRecord, onRelay } from "./record"; import type { NewLink } from "./shared-links"; -import { type Snapshot, takeSnapshot } from "./snapshot"; +import { noteText } from "./snapshot/note-text"; +import { type Snapshot, takeSnapshot } from "./snapshot/snapshot"; export interface ShareOptions { /** Seconds from now, counted by the relay; null never expires. */ @@ -37,7 +32,7 @@ export interface ShareOptions { } export const TOO_LARGE = "This note is too large to share as a link."; -export const NO_RELAY = "Set up the relay under Connection to share links."; +const NO_RELAY = "Set up the relay under Connection to share links."; const OTHER_RELAY = "This link was made through another relay: set that relay again to manage it."; /** Ids of the links being updated now. */ @@ -45,7 +40,7 @@ const updating = new Set(); /** What would be published, for the owner to look at first. */ export async function previewLink( - plugin: PluginHost, + plugin: LinksHost, file: TFile, images: boolean, ): Promise { @@ -57,7 +52,7 @@ export async function previewLink( /** The `snapshot` the owner looked at is exactly what goes out. */ export async function publishLink( - plugin: PluginHost, + plugin: LinksHost, file: TFile, options: ShareOptions, snapshot: Snapshot, @@ -117,7 +112,7 @@ export type RenderedNote = Map>; * links of one note can share `rendered`. */ export async function updateLink( - plugin: PluginHost, + plugin: LinksHost, shown: LinkRecord, passphrase: string | null, rendered: RenderedNote = new Map(), @@ -158,19 +153,19 @@ export async function updateLink( /** Ends the link at the relay, then forgets it here; unreachable, it stays listed to try again. */ export async function revokeLinkRecord( - plugin: PluginHost, + plugin: LinksHost, record: LinkRecord, ): Promise { await revokeLink(adminFor(plugin, record), record.id); await plugin.sharedLinks.remove(record.id); } -export async function linkStatusOf(plugin: PluginHost, record: LinkRecord) { +export async function linkStatusOf(plugin: LinksHost, record: LinkRecord) { return linkStatus(adminFor(plugin, record), record.id); } /** Asked again at each call: the relay in the settings may have changed since the list was drawn. */ -function adminFor(plugin: PluginHost, record: LinkRecord): BrokerAdmin { +function adminFor(plugin: LinksHost, record: LinkRecord): BrokerAdmin { if (!onRelay(record, plugin.settings)) throw new Error(OTHER_RELAY); return relayAdmin(plugin.settings); } diff --git a/packages/plugin/src/links/record.ts b/packages/plugin/src/features/links/record.ts similarity index 92% rename from packages/plugin/src/links/record.ts rename to packages/plugin/src/features/links/record.ts index da74e44f..e92f782e 100644 --- a/packages/plugin/src/links/record.ts +++ b/packages/plugin/src/features/links/record.ts @@ -1,7 +1,7 @@ import { isLinkId } from "@mdsync/protocol"; -import { isCleartextRemote, relayBase } from "@/shared"; -import type { Revised } from "@/utils"; +import { isCleartextRemote, relayBase } from "@/core/shared"; +import type { Revised } from "@/core/utils"; const MS_PER_S = 1000; @@ -37,6 +37,19 @@ export interface StoredLink extends LinkRecord { removed?: true; } +declare module "@/core/settings" { + interface MdsyncSettings { + /** This person's share links, keys included: traded sealed through the vault storage, never transferred. */ + links: StoredLink[]; + } +} + +export function parseStoredLinks(value: unknown): StoredLink[] { + return Array.isArray(value) + ? value.flatMap((link) => parseStoredLink(link) ?? []) + : []; +} + /** A record of the first builds, made before links were traded, starts at revision 0. */ export function parseStoredLink(value: unknown): StoredLink | null { const record = parseLinkRecord(value); diff --git a/packages/plugin/src/plugin/links.ts b/packages/plugin/src/features/links/register.ts similarity index 78% rename from packages/plugin/src/plugin/links.ts rename to packages/plugin/src/features/links/register.ts index b3fbcc99..3c145f77 100644 --- a/packages/plugin/src/plugin/links.ts +++ b/packages/plugin/src/features/links/register.ts @@ -1,11 +1,9 @@ import type { Plugin } from "obsidian"; - -import { reportWarning } from "@/shared"; - -import type { PluginHost } from "./host"; +import { reportWarning } from "@/core/shared"; +import type { LinksHost } from "./host"; /** A renamed note keeps its links; a deleted one lets go of them, so a new note at its path starts clean. */ -export function registerLinkPaths(plugin: Plugin & PluginHost): void { +export function registerLinkPaths(plugin: Plugin & LinksHost): void { const { vault } = plugin.app; plugin.registerEvent( vault.on("rename", (file, oldPath) => { diff --git a/packages/plugin/src/links/remote.ts b/packages/plugin/src/features/links/remote.ts similarity index 91% rename from packages/plugin/src/links/remote.ts rename to packages/plugin/src/features/links/remote.ts index a62defb1..30627c3c 100644 --- a/packages/plugin/src/links/remote.ts +++ b/packages/plugin/src/features/links/remote.ts @@ -1,12 +1,12 @@ -import type { EncryptionKey } from "@/crypto"; +import type { EncryptionKey } from "@/core/crypto"; +import { isNewer } from "@/core/utils"; +import type { StorageAdapter } from "@/features/storage"; import { type RecordKind, readRecords, removeRecord, writeRecord, -} from "@/storage/records"; -import type { StorageAdapter } from "@/storage/types"; -import { isNewer } from "@/utils"; +} from "@/features/storage"; import { type LinkRecord, diff --git a/packages/plugin/src/links/shared-links.ts b/packages/plugin/src/features/links/shared-links.ts similarity index 98% rename from packages/plugin/src/links/shared-links.ts rename to packages/plugin/src/features/links/shared-links.ts index b2d43a5a..98b3d10d 100644 --- a/packages/plugin/src/links/shared-links.ts +++ b/packages/plugin/src/features/links/shared-links.ts @@ -1,5 +1,5 @@ -import type { EncryptionKey } from "@/crypto"; -import type { StorageAdapter } from "@/storage/types"; +import type { EncryptionKey } from "@/core/crypto"; +import type { StorageAdapter } from "@/features/storage"; import { detachedLinks, diff --git a/packages/plugin/src/links/images.ts b/packages/plugin/src/features/links/snapshot/images.ts similarity index 100% rename from packages/plugin/src/links/images.ts rename to packages/plugin/src/features/links/snapshot/images.ts diff --git a/packages/plugin/src/links/math.ts b/packages/plugin/src/features/links/snapshot/math.ts similarity index 100% rename from packages/plugin/src/links/math.ts rename to packages/plugin/src/features/links/snapshot/math.ts diff --git a/packages/plugin/src/links/note-text.ts b/packages/plugin/src/features/links/snapshot/note-text.ts similarity index 100% rename from packages/plugin/src/links/note-text.ts rename to packages/plugin/src/features/links/snapshot/note-text.ts diff --git a/packages/plugin/src/links/sanitize.ts b/packages/plugin/src/features/links/snapshot/sanitize.ts similarity index 100% rename from packages/plugin/src/links/sanitize.ts rename to packages/plugin/src/features/links/snapshot/sanitize.ts diff --git a/packages/plugin/src/links/snapshot.ts b/packages/plugin/src/features/links/snapshot/snapshot.ts similarity index 100% rename from packages/plugin/src/links/snapshot.ts rename to packages/plugin/src/features/links/snapshot/snapshot.ts diff --git a/packages/plugin/src/ui/links/link-actions.ts b/packages/plugin/src/features/links/ui/link-actions.ts similarity index 77% rename from packages/plugin/src/ui/links/link-actions.ts rename to packages/plugin/src/features/links/ui/link-actions.ts index c9a9956b..028b0f2a 100644 --- a/packages/plugin/src/ui/links/link-actions.ts +++ b/packages/plugin/src/features/links/ui/link-actions.ts @@ -1,16 +1,12 @@ -import { - type LinkRecord, - linkError, - type RenderedNote, - updateLink, -} from "@/links"; -import type { PluginHost } from "@/plugin/host"; -import { notifyError, notifyInfo } from "@/ui/common"; -import { openPromptModal } from "@/ui/modals"; +import { notifyError, notifyInfo, openPromptModal } from "@/core/ui"; +import { linkError } from "../errors"; +import type { LinksHost } from "../host"; +import { type RenderedNote, updateLink } from "../publish"; +import type { LinkRecord } from "../record"; /** Updates each link in turn, asking a protected one for its passphrase; one notice says how it went. */ export async function updateSharedLinks( - plugin: PluginHost, + plugin: LinksHost, records: readonly LinkRecord[], ): Promise { const rendered: RenderedNote = new Map(); @@ -36,7 +32,7 @@ export async function updateSharedLinks( notifyInfo(`${shows} the note as it is.${spent}`); } -function askPassphrase(plugin: PluginHost): Promise { +function askPassphrase(plugin: LinksHost): Promise { return openPromptModal({ app: plugin.app, title: "Passphrase", diff --git a/packages/plugin/src/ui/links/link-menu.ts b/packages/plugin/src/features/links/ui/link-menu.ts similarity index 76% rename from packages/plugin/src/ui/links/link-menu.ts rename to packages/plugin/src/features/links/ui/link-menu.ts index 7297bc05..8029e117 100644 --- a/packages/plugin/src/ui/links/link-menu.ts +++ b/packages/plugin/src/features/links/ui/link-menu.ts @@ -1,8 +1,7 @@ import { type App, type Menu, type TAbstractFile, TFile } from "obsidian"; -import { docKindOf } from "@/live"; -import type { PluginHost } from "@/plugin/host"; -import { isRelayConfigured } from "@/settings/model"; -import { ESetupStep } from "@/settings/setup/steps"; +import { isRelayConfigured } from "@/core/settings"; +import { docKindOf } from "@/features/live"; +import type { LinksHost } from "../host"; import { ManageLinksModal } from "./manage-links-modal"; import { ShareLinkModal } from "./share-link-modal"; @@ -20,21 +19,21 @@ export function isLinkable( ); } -export function openShareLink(plugin: PluginHost, file: TFile): void { +export function openShareLink(plugin: LinksHost, file: TFile): void { if (isRelayConfigured(plugin.settings)) { new ShareLinkModal(plugin, file).open(); } else { - plugin.openSetup(ESetupStep.Relay); + plugin.openSetup("relay"); } } -export function openManageLinks(plugin: PluginHost, path?: string): void { +export function openManageLinks(plugin: LinksHost, path?: string): void { new ManageLinksModal(plugin, path).open(); } export function addLinkMenuItems( menu: Menu, - plugin: PluginHost, + plugin: LinksHost, file: TAbstractFile, ): void { if (!isLinkable(plugin.app, file)) return; diff --git a/packages/plugin/src/settings/sections/links.ts b/packages/plugin/src/features/links/ui/links-section.ts similarity index 70% rename from packages/plugin/src/settings/sections/links.ts rename to packages/plugin/src/features/links/ui/links-section.ts index deb5463f..d085fc7b 100644 --- a/packages/plugin/src/settings/sections/links.ts +++ b/packages/plugin/src/features/links/ui/links-section.ts @@ -1,9 +1,11 @@ import type { SettingDefinitionGroup } from "obsidian"; +import { type FieldContext, group } from "@/core/settings"; +import type { LinksHost } from "../host"; +import { openManageLinks } from "./link-menu"; -import { type FieldContext, group } from "@/settings/fields"; -import { openManageLinks } from "@/ui"; - -export function linksSection({ plugin }: FieldContext): SettingDefinitionGroup { +export function linksSection({ + plugin, +}: FieldContext): SettingDefinitionGroup { return group("Share links", [ { name: "Notes shared by link", diff --git a/packages/plugin/src/styles/links.css b/packages/plugin/src/features/links/ui/links.css similarity index 100% rename from packages/plugin/src/styles/links.css rename to packages/plugin/src/features/links/ui/links.css diff --git a/packages/plugin/src/ui/links/manage-links-modal.ts b/packages/plugin/src/features/links/ui/manage-links-modal.ts similarity index 95% rename from packages/plugin/src/ui/links/manage-links-modal.ts rename to packages/plugin/src/features/links/ui/manage-links-modal.ts index c88383a2..4ebe45d0 100644 --- a/packages/plugin/src/ui/links/manage-links-modal.ts +++ b/packages/plugin/src/features/links/ui/manage-links-modal.ts @@ -6,29 +6,28 @@ import { Setting, type TFile, } from "obsidian"; -import { - isExpired, - isStale, - type LinkRecord, - linkError, - linkStatusOf, - linkStatusText, - noteName, - onRelay, - revokeLinkRecord, -} from "@/links"; -import type { PluginHost } from "@/plugin/host"; import { copyText, modalCard, modalFooter, modalHint, notifyError, + openConfirmModal, renderModalHead, serial, -} from "@/ui/common"; -import { openConfirmModal } from "@/ui/modals"; -import { runWithConcurrency } from "@/utils"; +} from "@/core/ui"; +import { runWithConcurrency } from "@/core/utils"; +import { linkStatusText } from "../describe"; +import { linkError } from "../errors"; +import type { LinksHost } from "../host"; +import { linkStatusOf, revokeLinkRecord } from "../publish"; +import { + isExpired, + isStale, + type LinkRecord, + noteName, + onRelay, +} from "../record"; import { updateSharedLinks } from "./link-actions"; @@ -48,7 +47,7 @@ export class ManageLinksModal extends Modal { private modifyRef: EventRef | null = null; constructor( - private readonly plugin: PluginHost, + private readonly plugin: LinksHost, /** Only this note's links; all of them without it. */ private readonly path?: string, ) { diff --git a/packages/plugin/src/ui/links/note-link-action.ts b/packages/plugin/src/features/links/ui/note-link-action.ts similarity index 91% rename from packages/plugin/src/ui/links/note-link-action.ts rename to packages/plugin/src/features/links/ui/note-link-action.ts index 5e793a00..1e86bfaf 100644 --- a/packages/plugin/src/ui/links/note-link-action.ts +++ b/packages/plugin/src/features/links/ui/note-link-action.ts @@ -1,7 +1,6 @@ import { FileView, type Plugin, type WorkspaceLeaf } from "obsidian"; - -import { noteLinks, noteLinksText } from "@/links"; -import type { PluginHost } from "@/plugin/host"; +import type { LinksHost } from "../host"; +import { noteLinks, noteLinksText } from "../note-links"; import { openManageLinks } from "./link-menu"; @@ -11,7 +10,7 @@ interface Shown { el: HTMLElement; } -export function registerNoteLinkActions(plugin: Plugin & PluginHost): void { +export function registerNoteLinkActions(plugin: Plugin & LinksHost): void { const { workspace, vault } = plugin.app; const shown = new Map(); let disposed = false; diff --git a/packages/plugin/src/ui/links/preview-frame.ts b/packages/plugin/src/features/links/ui/preview-frame.ts similarity index 100% rename from packages/plugin/src/ui/links/preview-frame.ts rename to packages/plugin/src/features/links/ui/preview-frame.ts diff --git a/packages/plugin/src/ui/links/share-link-modal.ts b/packages/plugin/src/features/links/ui/share-link-modal.ts similarity index 96% rename from packages/plugin/src/ui/links/share-link-modal.ts rename to packages/plugin/src/features/links/ui/share-link-modal.ts index 48f62ce8..1681ad3c 100644 --- a/packages/plugin/src/ui/links/share-link-modal.ts +++ b/packages/plugin/src/features/links/ui/share-link-modal.ts @@ -6,31 +6,29 @@ import { type TextComponent, type TFile, } from "obsidian"; - +import { + alertLine, + copyable, + modalFooter, + renderModalHead, + serial, +} from "@/core/ui"; +import { invitePassword } from "@/features/spaces"; import { DEFAULT_EXPIRY, DEFAULT_VIEWS, EXPIRY_CHOICES, expiryLine, - type LinkRecord, leftOutText, - linkError, PICK_DATE, - previewLink, - publishLink, resolveExpiry, - type Snapshot, VIEW_CHOICES, -} from "@/links"; -import type { PluginHost } from "@/plugin/host"; -import { invitePassword } from "@/spaces"; -import { - alertLine, - copyable, - modalFooter, - renderModalHead, - serial, -} from "@/ui/common"; +} from "../describe"; +import { linkError } from "../errors"; +import type { LinksHost } from "../host"; +import { previewLink, publishLink } from "../publish"; +import type { LinkRecord } from "../record"; +import type { Snapshot } from "../snapshot/snapshot"; import { renderPreviewFrame } from "./preview-frame"; const MIN_PASSPHRASE = 8; @@ -63,7 +61,7 @@ export class ShareLinkModal extends Modal { private footer: HTMLElement | null = null; constructor( - private readonly plugin: PluginHost, + private readonly plugin: LinksHost, private readonly file: TFile, ) { super(plugin.app); diff --git a/packages/plugin/src/features/live/README.md b/packages/plugin/src/features/live/README.md new file mode 100644 index 00000000..cdcf8d4b --- /dev/null +++ b/packages/plugin/src/features/live/README.md @@ -0,0 +1,45 @@ +# Live editing + +Open notes and drawings of a space are edited together through that space's room on the relay hub: one Y.Doc per file, sealed frames, the hub stores ciphertext only. When no room answers, the note falls back to the file sync. Constraints: `.claude/rules/live.md`; hub frames: `.claude/rules/realtime.md`; wire formats: `packages/protocol/README.md`. + +## Map + +| Area | Holds | +|---|---| +| `features/live/session/` | one file's session in its room: the state machine (`session.ts`), the unacked FIFO (`outbox.ts`), the room log and compaction (`room-log.ts`), rotation (`rotation.ts`), who else is there (`room-awareness.ts`), close before reopen (`closing.ts`), read-only followers (`follower-session.ts`), its ports (`session-deps.ts`) | +| `features/live/workspace/` | which open notes are live: `sessions.ts` and each note's state, joining a room (`room.ts`), join patience, renames (`rename.ts`), the space a note is in (`space.ts`), `editors.ts` pairing each model with the view that edits it | +| `features/live/cold/` | the file sync's `LiveNotes` port (`cold-sync.ts`, declared in `features/sync/live-notes.ts`) and the agreed texts (`agreed-texts.ts`) | +| `features/live/text/` | Y.Text model, CodeMirror binding and undo, disk-to-CRDT patch, three-way merge, rebuild, author tint, cursors, scrollbar marks | +| `features/live/drawing/` | Y.Map of Excalidraw elements, its binding and the undocumented host adapter (`excalidraw.ts`) | +| `features/live/register.ts` | workspace events, rooms, agreed texts and the sync port, wired from `app/` | +| `doc-id.ts`, `doc-types.ts`, `model.ts`, `authors.ts`, `live-state.ts` | room ids, what goes live in which view, the `LiveModel` contract, CRDT attribution, the states the header and status show | + +## Flow + +1. A note opens in a view that can edit it live; `sessions.ts` asks `room.ts` for its room id: HMAC of the path inside its space root plus the generation (`doc-id.ts`), so every mount of a share meets in one room. +2. The session sends `Sub` with what it knows. `State` answers with the room's head and log name. An empty room with no log gets one `Seed` from disk; anything else is merged in: `mergeThreeWay(agreed text, disk, room)`, then patched into the Y.Text. +3. Local edits go out through the outbox (paced by **Live editing speed**), each kept until its `Echo`. Remote updates apply to the doc, the binding carries them into the editor, and the view saves the file. +4. Once settled (nothing pending or unacked), the lowest writer snapshots the room; past `COMPACT_AFTER` deltas it compacts. **Rebuild live note** rotates into the next generation, shedding tombstones. +5. The file sync meets live notes only through `LiveNotes`: an open room takes incoming versions (`absorb`), a closed note's agreed text moves with each marked version, and a push marks a note `{doc, gen, seq}` only when its content equals the room's text. + +## Notes + +- Merge base: the note's agreed text per docId, kept in the plugin folder, falling back to the cold baseline (the baseline alone duplicated lines not yet pushed). Lines both sides open or close with come once (git's zealous merge). +- Drawings: `onChange` stages elements whose version moved; the session drains the stage once per send (also on dispose, absorb, rebuild, detach) because `mergeUpdates` keeps every overwritten frame of a stroke. Only an event's `keysChanged` are reconciled. Pointers travel in awareness as scene coordinates, one per animation frame. The view loads its API after `file-open`, so binding retries every 500 ms; a reloaded view replaces its API and the binding asks again (`stale`). +- A write under an open note (git, another sync) needs nothing from live: Obsidian merges it with the editor and the binding carries the change. +- A rename with the room open rotates the room to the new path's first free generation; a device in the room renames its file and follows with the merge base; one that never joined steps past as a new note. +- A snapshot past a frame makes the leader rebuild; a rebuild past a frame sends the note back to the file sync ("too-large"), as does the hub's tail cap. +- Attribution is advisory: each client names its own client id in `users`; deletions name no one (a Yjs delete set carries no client). + +## Accepted limitations + +- A writer that started from a file older than the editor's last save replaces what came between: Obsidian merges against that save. Git or another sync writing under an open drawing right after its save is still dropped by Excalidraw. +- A session that seeded a room learns the log's name from its next `STATE`: a log lost before that shows only once the head falls behind. +- A rename leaves the room in place when another note's room holds the new path or the room stays busy for 10 s; the sync then ends with both files. So does a device that opens a stale copy of the old path before its file sync caught up. +- A file moved elsewhere waits here while an open room holds its note; the file sync renames it once the room closes. +- A note whose folder becomes a share leaves its vault room in the hub (rooms are never trimmed); others type there until the record's signal moves them, then fold those edits into the share's room. +- A rebuild landing while a rename waits for its workspace refresh leaves the renamed note in a fresh room apart (`carryRenamed` skips a moved session) until it reopens; the file sync reconciles it. +- A revert to an unmarked version under a newer agreed base still replays into the room at its next open. +- Excalidraw colours pointers itself from the person's key, so they do not match the avatar. +- A faster **Live editing speed** applies from a note's next send. +- Open: the hub keeps every room until its share ends, in one Durable Object capped at 10 GB. Retiring rooms needs a tombstone, clients moving generation, and a backfill within the Workers Free write budget; deleting idle rooms alone makes ids seedable again. diff --git a/packages/plugin/src/live/authors.ts b/packages/plugin/src/features/live/authors.ts similarity index 100% rename from packages/plugin/src/live/authors.ts rename to packages/plugin/src/features/live/authors.ts diff --git a/packages/plugin/src/live/cold/agreed-texts.ts b/packages/plugin/src/features/live/cold/agreed-texts.ts similarity index 97% rename from packages/plugin/src/live/cold/agreed-texts.ts rename to packages/plugin/src/features/live/cold/agreed-texts.ts index 89a27deb..bac067d2 100644 --- a/packages/plugin/src/live/cold/agreed-texts.ts +++ b/packages/plugin/src/features/live/cold/agreed-texts.ts @@ -5,9 +5,9 @@ import type { DataAdapter } from "obsidian"; -import { PLUGIN_ID } from "@/constants"; -import { reportWarning } from "@/shared"; -import { ensureDir } from "@/vault/io"; +import { PLUGIN_ID } from "@/core/constants"; +import { reportWarning } from "@/core/shared"; +import { ensureDir } from "@/core/vault"; export interface AgreedText { text: string; diff --git a/packages/plugin/src/live/cold/cold-sync.ts b/packages/plugin/src/features/live/cold/cold-sync.ts similarity index 89% rename from packages/plugin/src/live/cold/cold-sync.ts rename to packages/plugin/src/features/live/cold/cold-sync.ts index e44af5ad..2d148c03 100644 --- a/packages/plugin/src/live/cold/cold-sync.ts +++ b/packages/plugin/src/features/live/cold/cold-sync.ts @@ -3,20 +3,20 @@ * and an open room takes incoming text itself. */ -import { sha256Hex } from "@/crypto"; -import { hasLiveExtension } from "@/live/doc-types"; -import type { LiveSession } from "@/live/session"; -import type { LiveSessions } from "@/live/workspace/sessions"; -import { docIdIn, type LiveSpace } from "@/live/workspace/space"; -import { textToBytes } from "@/sync/content"; +import { sha256Hex } from "@/core/crypto"; +import { toLf } from "@/core/utils"; +import type { LiveMark } from "@/features/sync"; import { type IncomingText, isNewerMark, type LiveNotes, type LiveTake, -} from "@/sync/live-notes"; -import type { LiveMark } from "@/sync/types"; -import { toLf } from "@/utils"; + textToBytes, +} from "@/features/sync"; +import { hasLiveExtension } from "../doc-types"; +import type { LiveSession } from "../session/session"; +import type { LiveSessions } from "../workspace/sessions"; +import { docIdIn, type LiveSpace } from "../workspace/space"; import type { AgreedTexts } from "./agreed-texts"; export interface LiveColdSyncDeps { diff --git a/packages/plugin/src/live/doc-id.ts b/packages/plugin/src/features/live/doc-id.ts similarity index 95% rename from packages/plugin/src/live/doc-id.ts rename to packages/plugin/src/features/live/doc-id.ts index 79864612..6d803789 100644 --- a/packages/plugin/src/live/doc-id.ts +++ b/packages/plugin/src/features/live/doc-id.ts @@ -1,6 +1,6 @@ import { toHex } from "@mdsync/protocol"; -import type { LiveKeys } from "@/crypto/live-keys"; +import type { LiveKeys } from "@/core/crypto"; /** 16 bytes of HMAC: collision-free at any vault size, short on the wire. */ const DOC_ID_BYTES = 16; diff --git a/packages/plugin/src/live/doc-types.ts b/packages/plugin/src/features/live/doc-types.ts similarity index 92% rename from packages/plugin/src/live/doc-types.ts rename to packages/plugin/src/features/live/doc-types.ts index ade329bf..95230df1 100644 --- a/packages/plugin/src/live/doc-types.ts +++ b/packages/plugin/src/features/live/doc-types.ts @@ -1,4 +1,5 @@ import type { App, TFile } from "obsidian"; +import { DRAWING_KEY } from "@/core/drawing"; export type LiveDocKind = "text" | "drawing"; @@ -28,7 +29,7 @@ export function docKindOf(app: App, file: TFile): LiveDocKind | null { if (file.extension !== LIVE_EXTENSION) return null; const cache = app.metadataCache.getFileCache(file); if (!cache) return null; - return cache.frontmatter && "excalidraw-plugin" in cache.frontmatter + return cache.frontmatter && DRAWING_KEY in cache.frontmatter ? "drawing" : "text"; } diff --git a/packages/plugin/src/live/drawing/binding.ts b/packages/plugin/src/features/live/drawing/binding.ts similarity index 96% rename from packages/plugin/src/live/drawing/binding.ts rename to packages/plugin/src/features/live/drawing/binding.ts index ecec4b4a..28ab228a 100644 --- a/packages/plugin/src/live/drawing/binding.ts +++ b/packages/plugin/src/features/live/drawing/binding.ts @@ -1,9 +1,10 @@ import type * as Y from "yjs"; -import { type SceneElement, wins } from "@/drawing"; +import { type SceneElement, wins } from "@/core/drawing"; -import type { BoundEditor } from "@/live/model"; -import { type LiveSession, LOCAL_AWARENESS } from "@/live/session"; +import type { BoundEditor } from "../model"; +import { LOCAL_AWARENESS } from "../session/room-awareness"; +import type { LiveSession } from "../session/session"; import { type Collaborator, type ExcalidrawView, diff --git a/packages/plugin/src/live/drawing/excalidraw.ts b/packages/plugin/src/features/live/drawing/excalidraw.ts similarity index 97% rename from packages/plugin/src/live/drawing/excalidraw.ts rename to packages/plugin/src/features/live/drawing/excalidraw.ts index 52fb730c..4522d327 100644 --- a/packages/plugin/src/live/drawing/excalidraw.ts +++ b/packages/plugin/src/features/live/drawing/excalidraw.ts @@ -5,9 +5,9 @@ import type { TextFileView, TFile, View } from "obsidian"; -import type { SceneElement } from "@/drawing"; +import type { SceneElement } from "@/core/drawing"; -import { LIVE_VIEWS } from "@/live/doc-types"; +import { LIVE_VIEWS } from "../doc-types"; export interface Collaborator { pointer: { x: number; y: number; tool: "pointer" }; diff --git a/packages/plugin/src/live/drawing/model.ts b/packages/plugin/src/features/live/drawing/model.ts similarity index 97% rename from packages/plugin/src/live/drawing/model.ts rename to packages/plugin/src/features/live/drawing/model.ts index e3ace1aa..fd0a419f 100644 --- a/packages/plugin/src/live/drawing/model.ts +++ b/packages/plugin/src/features/live/drawing/model.ts @@ -6,9 +6,9 @@ import { readDrawing, type SceneElement, wins, -} from "@/drawing"; +} from "@/core/drawing"; -import type { LiveKind, LiveModel } from "@/live/model"; +import type { LiveKind, LiveModel } from "../model"; const ELEMENTS = "elements"; diff --git a/packages/plugin/src/features/live/index.ts b/packages/plugin/src/features/live/index.ts new file mode 100644 index 00000000..d7e7190b --- /dev/null +++ b/packages/plugin/src/features/live/index.ts @@ -0,0 +1,19 @@ +export { docKindOf, LIVE_VIEWS, liveKindOf } from "./doc-types"; +export { + type ExcalidrawApi, + type ExcalidrawView, + isViewMode, + setViewMode, +} from "./drawing/excalidraw"; +export { + LINK_LIVE_STATE, + type LiveState, + STATE_ICONS, + STATE_TEXT, +} from "./live-state"; +export { createLive, type LiveHost } from "./register"; +export { LiveSession } from "./session/session"; +export type { Rotation } from "./session/session-deps"; +export { watchCursor } from "./text/cursors"; +export { createDeletedElsewhere } from "./ui/deleted-elsewhere"; +export { type ColdCause, LiveSessions } from "./workspace/sessions"; diff --git a/packages/plugin/src/ui/live/live-state.ts b/packages/plugin/src/features/live/live-state.ts similarity index 93% rename from packages/plugin/src/ui/live/live-state.ts rename to packages/plugin/src/features/live/live-state.ts index 0b7f5782..b3db19a7 100644 --- a/packages/plugin/src/ui/live/live-state.ts +++ b/packages/plugin/src/features/live/live-state.ts @@ -1,4 +1,4 @@ -import type { LinkState } from "@/hub/status"; +import type { LinkState } from "@/core/hub"; export type LiveState = "live" | "joining" | "offline" | "cold" | "warning"; diff --git a/packages/plugin/src/live/model.ts b/packages/plugin/src/features/live/model.ts similarity index 100% rename from packages/plugin/src/live/model.ts rename to packages/plugin/src/features/live/model.ts diff --git a/packages/plugin/src/plugin/live.ts b/packages/plugin/src/features/live/register.ts similarity index 81% rename from packages/plugin/src/plugin/live.ts rename to packages/plugin/src/features/live/register.ts index 7b697c30..da276b0b 100644 --- a/packages/plugin/src/plugin/live.ts +++ b/packages/plugin/src/features/live/register.ts @@ -1,35 +1,41 @@ import type { App, FileView, TFile, Vault, Workspace } from "obsidian"; +import type { LiveKeys } from "@/core/crypto"; +import type { SpaceHubs } from "@/core/hub"; +import type { MdsyncSettings } from "@/core/settings"; +import { personColor, reportWarning } from "@/core/shared"; +import { renameInVault } from "@/core/vault"; +import type { LiveNotes, SyncController, WriteJournal } from "@/features/sync"; +import { type Space, spaceOf, VAULT_SPACE } from "@/features/sync"; +import { AgreedTexts } from "./cold/agreed-texts"; +import { LiveColdSync } from "./cold/cold-sync"; +import { LIVE_VIEWS } from "./doc-types"; +import { LiveSessions } from "./workspace/sessions"; +import type { LiveSpace } from "./workspace/space"; -import type { HubConnection } from "@/hub"; -import { - AgreedTexts, - LIVE_VIEWS, - LiveColdSync, - LiveSessions, - type LiveSpace, -} from "@/live"; -import { personColor, reportWarning } from "@/shared"; -import type { SpaceRecords } from "@/spaces"; -import type { WriteJournal } from "@/sync/journal"; -import type { LiveNotes } from "@/sync/live-notes"; -import { type Space, spaceOf, VAULT_SPACE } from "@/sync/space"; -import { renameInVault } from "@/vault/file-index"; - -import type { SpaceAccess, SpaceAccessHost } from "./space-access"; - -export interface LiveHost extends SpaceAccessHost { +export interface LiveHost { app: App; - /** Its partition is the spaces as the records have them now, ahead of the next refresh. */ - spaces: Pick; + controller: SyncController; + settings: () => MdsyncSettings; + /** The spaces as the records have them now, ahead of the next refresh. */ + spaces: { partition(): readonly Space[] }; journal: Pick; onDeletedElsewhere(path: string): void; } +/** This device's keys and identity in a space's room, as the spaces slice grants them. */ +export interface LiveAccess { + keys: LiveKeys; + person: string; + key: string; + name: string; + device: string | null; +} + /** Live editing wired to the workspace: which notes are open decides which rooms are joined. */ export function createLive( host: LiveHost, - hub: HubConnection, - access: (space: Space) => Promise, + hub: SpaceHubs, + access: (space: Space) => Promise, nameOf: (space: string, person: string) => string | null, ): { sessions: LiveSessions; @@ -82,7 +88,7 @@ export function createLive( function refreshOnChanges( { workspace, vault, metadataCache }: App, - hub: HubConnection, + hub: SpaceHubs, sessions: LiveSessions, ): () => void { const refresh = () => void sessions.refresh(); @@ -128,7 +134,7 @@ function flushAgreedWhenLeaving(agreed: AgreedTexts): () => void { /** Live editing on top of the space's access. Paused shares stay cold; a read-only one's notes follow the room. */ function createLiveSpaces( host: LiveHost, - access: (space: Space) => Promise, + access: (space: Space) => Promise, ): (space: Space) => Promise { return async (space) => { if (!host.settings().liveEditing || space.paused) return null; diff --git a/packages/plugin/src/live/session/closing.ts b/packages/plugin/src/features/live/session/closing.ts similarity index 100% rename from packages/plugin/src/live/session/closing.ts rename to packages/plugin/src/features/live/session/closing.ts diff --git a/packages/plugin/src/live/session/follower-session.ts b/packages/plugin/src/features/live/session/follower-session.ts similarity index 96% rename from packages/plugin/src/live/session/follower-session.ts rename to packages/plugin/src/features/live/session/follower-session.ts index 8e45a5af..6d0f3f82 100644 --- a/packages/plugin/src/live/session/follower-session.ts +++ b/packages/plugin/src/features/live/session/follower-session.ts @@ -4,8 +4,8 @@ */ import { EFrame } from "@mdsync/protocol"; -import type { LiveModel } from "@/live/model"; -import { toLf } from "@/utils"; +import { toLf } from "@/core/utils"; +import type { LiveModel } from "../model"; import { FOLLOWS } from "./room-awareness"; import { LiveSession, type Unaddressed } from "./session"; import type { Follower, LiveSessionDeps, Rotation } from "./session-deps"; diff --git a/packages/plugin/src/live/session/outbox.ts b/packages/plugin/src/features/live/session/outbox.ts similarity index 98% rename from packages/plugin/src/live/session/outbox.ts rename to packages/plugin/src/features/live/session/outbox.ts index 1fe5bfce..5aa3c731 100644 --- a/packages/plugin/src/live/session/outbox.ts +++ b/packages/plugin/src/features/live/session/outbox.ts @@ -1,6 +1,6 @@ import * as Y from "yjs"; -import { reportWarning } from "@/shared"; +import { reportWarning } from "@/core/shared"; /** Silent this long, the hub dropped the last update and no later echo will tell. */ const ACK_PATIENCE_MS = 15_000; diff --git a/packages/plugin/src/live/session/room-awareness.ts b/packages/plugin/src/features/live/session/room-awareness.ts similarity index 97% rename from packages/plugin/src/live/session/room-awareness.ts rename to packages/plugin/src/features/live/session/room-awareness.ts index a904ce16..c465cfd0 100644 --- a/packages/plugin/src/live/session/room-awareness.ts +++ b/packages/plugin/src/features/live/session/room-awareness.ts @@ -11,8 +11,8 @@ import { } from "y-protocols/awareness"; import type * as Y from "yjs"; -import type { LiveKeys } from "@/crypto/live-keys"; -import { type SealedFor, seal, unseal } from "@/crypto/seal"; +import type { LiveKeys } from "@/core/crypto"; +import { type SealedFor, seal, unseal } from "@/core/crypto"; /** Own changes go at most this often: a drag or a drawing's pointer moves 10 times a second. */ export const ANNOUNCE_MS = 100; diff --git a/packages/plugin/src/live/session/room-log.ts b/packages/plugin/src/features/live/session/room-log.ts similarity index 100% rename from packages/plugin/src/live/session/room-log.ts rename to packages/plugin/src/features/live/session/room-log.ts diff --git a/packages/plugin/src/live/session/rotation.ts b/packages/plugin/src/features/live/session/rotation.ts similarity index 92% rename from packages/plugin/src/live/session/rotation.ts rename to packages/plugin/src/features/live/session/rotation.ts index f4b65c0c..d74b19a4 100644 --- a/packages/plugin/src/live/session/rotation.ts +++ b/packages/plugin/src/features/live/session/rotation.ts @@ -1,8 +1,7 @@ import { EFrame } from "@mdsync/protocol"; - -import type { LiveKeys } from "@/crypto/live-keys"; -import { seal } from "@/crypto/seal"; -import type { SpaceFrame } from "@/hub"; +import type { LiveKeys } from "@/core/crypto"; +import { seal } from "@/core/crypto"; +import type { SpaceFrame } from "@/core/hub"; import type { Rotation } from "./session-deps"; type RotateFrame = Omit< diff --git a/packages/plugin/src/live/session/session-deps.ts b/packages/plugin/src/features/live/session/session-deps.ts similarity index 89% rename from packages/plugin/src/live/session/session-deps.ts rename to packages/plugin/src/features/live/session/session-deps.ts index 8a4eab32..256fabad 100644 --- a/packages/plugin/src/live/session/session-deps.ts +++ b/packages/plugin/src/features/live/session/session-deps.ts @@ -1,10 +1,9 @@ import type { Refusal } from "@mdsync/protocol"; +import type { LiveKeys } from "@/core/crypto"; +import type { SpaceHub } from "@/core/hub"; -import type { LiveKeys } from "@/crypto/live-keys"; -import type { SpaceHub } from "@/hub"; - -import type { Author } from "@/live/authors"; -import type { LiveKind, LiveModel } from "@/live/model"; +import type { Author } from "../authors"; +import type { LiveKind, LiveModel } from "../model"; /** "busy": not now - edits still staged or unacked, offline, or the answer was lost. */ export type Rotation = "moved" | "refused" | "busy"; diff --git a/packages/plugin/src/live/session/session.ts b/packages/plugin/src/features/live/session/session.ts similarity index 97% rename from packages/plugin/src/live/session/session.ts rename to packages/plugin/src/features/live/session/session.ts index 435fe17b..df9c5539 100644 --- a/packages/plugin/src/live/session/session.ts +++ b/packages/plugin/src/features/live/session/session.ts @@ -10,13 +10,13 @@ import { type ServerFrame, } from "@mdsync/protocol"; import * as Y from "yjs"; -import { LIVE_SEND_MS } from "@/constants"; -import { type SealedFor, seal, unseal } from "@/crypto/seal"; -import type { SpaceFrame, SpaceListener } from "@/hub"; -import { attribute } from "@/live/authors"; -import type { LiveModel } from "@/live/model"; -import { reportWarning } from "@/shared"; -import { runWithConcurrency } from "@/utils"; +import { LIVE_SEND_MS } from "@/core/constants"; +import { type SealedFor, seal, unseal } from "@/core/crypto"; +import type { SpaceFrame, SpaceListener } from "@/core/hub"; +import { reportWarning } from "@/core/shared"; +import { runWithConcurrency } from "@/core/utils"; +import { attribute } from "../authors"; +import type { LiveModel } from "../model"; import { closingUntil } from "./closing"; import { Outbox } from "./outbox"; import { RoomAwareness } from "./room-awareness"; diff --git a/packages/plugin/src/live/text/author-marks.ts b/packages/plugin/src/features/live/text/author-marks.ts similarity index 96% rename from packages/plugin/src/live/text/author-marks.ts rename to packages/plugin/src/features/live/text/author-marks.ts index 34e56b0a..693aa5ca 100644 --- a/packages/plugin/src/live/text/author-marks.ts +++ b/packages/plugin/src/features/live/text/author-marks.ts @@ -12,8 +12,8 @@ import { type ViewUpdate, } from "@codemirror/view"; import type * as Y from "yjs"; -import { type Author, authorRanges } from "@/live/authors"; -import { personTint } from "@/shared"; +import { personTint } from "@/core/shared"; +import { type Author, authorRanges } from "../authors"; /** Typing and scrolling recompute the tint at most this often; in between it is only mapped. */ const REDRAW_MS = 250; diff --git a/packages/plugin/src/live/text/binding.ts b/packages/plugin/src/features/live/text/binding.ts similarity index 96% rename from packages/plugin/src/live/text/binding.ts rename to packages/plugin/src/features/live/text/binding.ts index 6390ce9d..d6978884 100644 --- a/packages/plugin/src/live/text/binding.ts +++ b/packages/plugin/src/features/live/text/binding.ts @@ -12,9 +12,9 @@ import { yUndoManagerKeymap, } from "y-codemirror.next"; import type * as Y from "yjs"; -import { USERS } from "@/live/authors"; -import type { BoundEditor } from "@/live/model"; -import type { LiveSession } from "@/live/session"; +import { USERS } from "../authors"; +import type { BoundEditor } from "../model"; +import type { LiveSession } from "../session/session"; import { authorMarks } from "./author-marks"; import type { TextModel } from "./model"; import { remoteSelections } from "./remote-selections"; diff --git a/packages/plugin/src/live/text/cursors.ts b/packages/plugin/src/features/live/text/cursors.ts similarity index 97% rename from packages/plugin/src/live/text/cursors.ts rename to packages/plugin/src/features/live/text/cursors.ts index 036b71cc..3b240d12 100644 --- a/packages/plugin/src/live/text/cursors.ts +++ b/packages/plugin/src/features/live/text/cursors.ts @@ -1,6 +1,6 @@ import * as Y from "yjs"; -import type { LiveSession } from "@/live/session"; +import type { LiveSession } from "../session/session"; import { TextModel } from "./model"; interface CursorState { diff --git a/packages/plugin/src/live/text/merge.ts b/packages/plugin/src/features/live/text/merge.ts similarity index 92% rename from packages/plugin/src/live/text/merge.ts rename to packages/plugin/src/features/live/text/merge.ts index 23f5855d..8fb5873a 100644 --- a/packages/plugin/src/live/text/merge.ts +++ b/packages/plugin/src/features/live/text/merge.ts @@ -1,5 +1,5 @@ -import { sameLines, threeWayRegions, toLines } from "@/sync/merge-model"; -import { commonEnds } from "@/utils"; +import { commonEnds } from "@/core/utils"; +import { sameLines, threeWayRegions, toLines } from "@/features/sync"; /** * The room's text with this device's offline changes folded in, on the regions the merge editor shows. A diff --git a/packages/plugin/src/live/text/model.ts b/packages/plugin/src/features/live/text/model.ts similarity index 93% rename from packages/plugin/src/live/text/model.ts rename to packages/plugin/src/features/live/text/model.ts index 191b6550..05715317 100644 --- a/packages/plugin/src/live/text/model.ts +++ b/packages/plugin/src/features/live/text/model.ts @@ -1,6 +1,6 @@ import * as Y from "yjs"; -import type { LiveKind, LiveModel } from "@/live/model"; -import { toLf } from "@/utils"; +import { toLf } from "@/core/utils"; +import type { LiveKind, LiveModel } from "../model"; import { mergeThreeWay } from "./merge"; import { patchYText } from "./patch"; import { BODY, rebuild } from "./rebuild"; diff --git a/packages/plugin/src/live/text/patch.ts b/packages/plugin/src/features/live/text/patch.ts similarity index 93% rename from packages/plugin/src/live/text/patch.ts rename to packages/plugin/src/features/live/text/patch.ts index 1597d9ca..986fc031 100644 --- a/packages/plugin/src/live/text/patch.ts +++ b/packages/plugin/src/features/live/text/patch.ts @@ -1,7 +1,6 @@ import type * as Y from "yjs"; - -import { DIFF_BUDGET } from "@/sync/hunks"; -import { changedMiddle, diffRanges } from "@/utils"; +import { changedMiddle, diffRanges } from "@/core/utils"; +import { DIFF_BUDGET } from "@/features/sync"; const MIN_ANCHOR = 10; diff --git a/packages/plugin/src/live/text/rebuild.ts b/packages/plugin/src/features/live/text/rebuild.ts similarity index 96% rename from packages/plugin/src/live/text/rebuild.ts rename to packages/plugin/src/features/live/text/rebuild.ts index 5fcb732c..448f71aa 100644 --- a/packages/plugin/src/live/text/rebuild.ts +++ b/packages/plugin/src/features/live/text/rebuild.ts @@ -5,7 +5,7 @@ import * as Y from "yjs"; -import { USERS } from "@/live/authors"; +import { USERS } from "../authors"; export const BODY = "body"; diff --git a/packages/plugin/src/live/text/remote-selections.ts b/packages/plugin/src/features/live/text/remote-selections.ts similarity index 100% rename from packages/plugin/src/live/text/remote-selections.ts rename to packages/plugin/src/features/live/text/remote-selections.ts diff --git a/packages/plugin/src/live/text/scroll-marks.ts b/packages/plugin/src/features/live/text/scroll-marks.ts similarity index 95% rename from packages/plugin/src/live/text/scroll-marks.ts rename to packages/plugin/src/features/live/text/scroll-marks.ts index faff812d..2211b458 100644 --- a/packages/plugin/src/live/text/scroll-marks.ts +++ b/packages/plugin/src/features/live/text/scroll-marks.ts @@ -1,6 +1,7 @@ import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view"; -import { type LiveSession, LOCAL_AWARENESS } from "@/live/session"; -import { personColor } from "@/shared"; +import { personColor } from "@/core/shared"; +import { LOCAL_AWARENESS } from "../session/room-awareness"; +import type { LiveSession } from "../session/session"; import { cursorsIn, type RoomCursor } from "./cursors"; import type { TextModel } from "./model"; diff --git a/packages/plugin/src/ui/live/deleted-elsewhere.ts b/packages/plugin/src/features/live/ui/deleted-elsewhere.ts similarity index 74% rename from packages/plugin/src/ui/live/deleted-elsewhere.ts rename to packages/plugin/src/features/live/ui/deleted-elsewhere.ts index 71d69d8f..33d240c9 100644 --- a/packages/plugin/src/ui/live/deleted-elsewhere.ts +++ b/packages/plugin/src/features/live/ui/deleted-elsewhere.ts @@ -1,11 +1,16 @@ -import type { PluginHost } from "@/plugin/host"; -import { spaceOf } from "@/sync/space"; -import { notifyError, runWithNotice } from "@/ui/common"; -import { openChoiceModal } from "@/ui/modals"; +import type { App } from "obsidian"; +import { notifyError, openChoiceModal, runWithNotice } from "@/core/ui"; +import { type Space, type SyncController, spaceOf } from "@/features/sync"; + +interface DeletedElsewhereHost { + readonly app: App; + readonly controller: SyncController; + readonly spaces: { partition(): readonly Space[] }; +} /** Another device deleted a note open here: the person decides whether it goes here too or comes back everywhere. */ export function createDeletedElsewhere( - plugin: PluginHost, + plugin: DeletedElsewhereHost, ): (path: string) => void { const asking = new Set(); return (path) => { @@ -15,7 +20,7 @@ export function createDeletedElsewhere( }; } -async function ask(plugin: PluginHost, path: string): Promise { +async function ask(plugin: DeletedElsewhereHost, path: string): Promise { const { app, controller, spaces } = plugin; const { readOnly } = spaceOf(spaces.partition(), path); const name = app.vault.getFileByPath(path)?.basename ?? path; diff --git a/packages/plugin/src/live/workspace/editors.ts b/packages/plugin/src/features/live/workspace/editors.ts similarity index 90% rename from packages/plugin/src/live/workspace/editors.ts rename to packages/plugin/src/features/live/workspace/editors.ts index b08949cf..ad58a7f2 100644 --- a/packages/plugin/src/live/workspace/editors.ts +++ b/packages/plugin/src/features/live/workspace/editors.ts @@ -11,20 +11,21 @@ import { type View, type WorkspaceLeaf, } from "obsidian"; -import { LIVE_VIEWS, type LiveDocKind, liveKindOf } from "@/live/doc-types"; -import { bindDrawing } from "@/live/drawing/binding"; +import { LIVE_VIEWS, type LiveDocKind, liveKindOf } from "../doc-types"; +import { bindDrawing } from "../drawing/binding"; import { drawingView, letWriteIn, readDrawing, saveDrawing, -} from "@/live/drawing/excalidraw"; -import { DRAWING } from "@/live/drawing/model"; -import type { BoundEditor, LiveKind, LiveModel } from "@/live/model"; -import { FollowerSession, LiveSession } from "@/live/session"; -import type { LiveSessionDeps } from "@/live/session/session-deps"; -import { bindEditor } from "@/live/text/binding"; -import { TEXT } from "@/live/text/model"; +} from "../drawing/excalidraw"; +import { DRAWING } from "../drawing/model"; +import type { BoundEditor, LiveKind, LiveModel } from "../model"; +import { FollowerSession } from "../session/follower-session"; +import { LiveSession } from "../session/session"; +import type { LiveSessionDeps } from "../session/session-deps"; +import { bindEditor } from "../text/binding"; +import { TEXT } from "../text/model"; import type { LiveSpace } from "./space"; export interface LiveRoom { diff --git a/packages/plugin/src/live/workspace/patience.ts b/packages/plugin/src/features/live/workspace/patience.ts similarity index 100% rename from packages/plugin/src/live/workspace/patience.ts rename to packages/plugin/src/features/live/workspace/patience.ts diff --git a/packages/plugin/src/live/workspace/rename.ts b/packages/plugin/src/features/live/workspace/rename.ts similarity index 91% rename from packages/plugin/src/live/workspace/rename.ts rename to packages/plugin/src/features/live/workspace/rename.ts index 7b050a32..c7224ac8 100644 --- a/packages/plugin/src/live/workspace/rename.ts +++ b/packages/plugin/src/features/live/workspace/rename.ts @@ -4,14 +4,18 @@ */ import { EFrame } from "@mdsync/protocol"; -import { seal, unseal } from "@/crypto/seal"; -import type { SpaceHub } from "@/hub"; -import { hasLiveExtension } from "@/live/doc-types"; -import type { LiveSession } from "@/live/session"; -import type { Rotation } from "@/live/session/session-deps"; -import { hasDotSegment, normalizePath } from "@/shared"; -import { bytesToText, textToBytes } from "@/sync/content"; -import { insideOf, vaultPathOf } from "@/sync/space"; +import { seal, unseal } from "@/core/crypto"; +import type { SpaceHub } from "@/core/hub"; +import { hasDotSegment, normalizePath } from "@/core/shared"; +import { + bytesToText, + insideOf, + textToBytes, + vaultPathOf, +} from "@/features/sync"; +import { hasLiveExtension } from "../doc-types"; +import type { LiveSession } from "../session/session"; +import type { Rotation } from "../session/session-deps"; import { docIdIn, type LiveSpace } from "./space"; /** Generations one path may have gone through; past this the rename is left to the file sync. */ diff --git a/packages/plugin/src/live/workspace/room.ts b/packages/plugin/src/features/live/workspace/room.ts similarity index 95% rename from packages/plugin/src/live/workspace/room.ts rename to packages/plugin/src/features/live/workspace/room.ts index e6c34a04..cb34300a 100644 --- a/packages/plugin/src/live/workspace/room.ts +++ b/packages/plugin/src/features/live/workspace/room.ts @@ -1,12 +1,11 @@ import { ERefusal } from "@mdsync/protocol"; import type { App, TFile } from "obsidian"; - -import type { HubConnection } from "@/hub"; -import type { AgreedTexts } from "@/live/cold/agreed-texts"; -import { closedBefore } from "@/live/session"; -import type { Refused, Unfollowed } from "@/live/session/session-deps"; -import { reportWarning, withDevices } from "@/shared"; -import { toLf } from "@/utils"; +import type { SpaceHubs } from "@/core/hub"; +import { reportWarning, withDevices } from "@/core/shared"; +import { toLf } from "@/core/utils"; +import type { AgreedTexts } from "../cold/agreed-texts"; +import { closedBefore } from "../session/closing"; +import type { Refused, Unfollowed } from "../session/session-deps"; import { type LiveEditor, type LiveRoom, readOpen } from "./editors"; import { type MoveNote, movedWith } from "./rename"; import { docIdIn, type LiveSpace, sameSpace } from "./space"; @@ -48,7 +47,7 @@ export interface OpenAt { export interface RoomDeps { app: App; - hub: Pick; + hub: Pick; /** Where the note goes live; null keeps it cold: live off, no key yet, a paused share. */ liveSpace: (path: string) => Promise; agreed: AgreedTexts; diff --git a/packages/plugin/src/live/workspace/sessions.ts b/packages/plugin/src/features/live/workspace/sessions.ts similarity index 97% rename from packages/plugin/src/live/workspace/sessions.ts rename to packages/plugin/src/features/live/workspace/sessions.ts index 4fc3ba9c..5d21a0d6 100644 --- a/packages/plugin/src/live/workspace/sessions.ts +++ b/packages/plugin/src/features/live/workspace/sessions.ts @@ -4,11 +4,12 @@ */ import type { WorkspaceLeaf } from "obsidian"; -import type { BoundEditor } from "@/live/model"; -import { closedBefore, type LiveSession } from "@/live/session"; -import type { Rotation } from "@/live/session/session-deps"; -import { reportWarning } from "@/shared"; -import { isRecaseStep } from "@/vault/io"; +import { reportWarning } from "@/core/shared"; +import { isRecaseStep } from "@/core/vault"; +import type { BoundEditor } from "../model"; +import { closedBefore } from "../session/closing"; +import type { LiveSession } from "../session/session"; +import type { Rotation } from "../session/session-deps"; import { EDITORS, type OpenNote, openNotes } from "./editors"; import { JoinPatience, type Waiting, waitingSince } from "./patience"; import { moveRoom } from "./rename"; diff --git a/packages/plugin/src/live/workspace/space.ts b/packages/plugin/src/features/live/workspace/space.ts similarity index 89% rename from packages/plugin/src/live/workspace/space.ts rename to packages/plugin/src/features/live/workspace/space.ts index 8aa54e5c..b2ca16c2 100644 --- a/packages/plugin/src/live/workspace/space.ts +++ b/packages/plugin/src/features/live/workspace/space.ts @@ -1,6 +1,6 @@ -import type { LiveKeys } from "@/crypto/live-keys"; -import { docIdFor } from "@/live/doc-id"; -import { insideOf } from "@/sync/space"; +import type { LiveKeys } from "@/core/crypto"; +import { insideOf } from "@/features/sync"; +import { docIdFor } from "../doc-id"; export interface LiveUser { /** The presence key: whose cursor this is, for a jump to it. */ diff --git a/packages/plugin/src/ui/live/header/header-state.ts b/packages/plugin/src/features/note-header/header-state.ts similarity index 82% rename from packages/plugin/src/ui/live/header/header-state.ts rename to packages/plugin/src/features/note-header/header-state.ts index 920b5a36..37248dba 100644 --- a/packages/plugin/src/ui/live/header/header-state.ts +++ b/packages/plugin/src/features/note-header/header-state.ts @@ -1,10 +1,14 @@ import { FileView, type TFile, type WorkspaceLeaf } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; -import type { Person } from "@/presence"; -import { type Space, spaceOf, VAULT_SPACE } from "@/sync/space"; -import { skippedFiles, skippedText } from "@/ui/common"; -import type { LiveState } from "@/ui/live/live-state"; +import type { LiveState } from "@/features/live"; +import type { Person } from "@/features/presence"; +import { + type Space, + skippedFiles, + skippedText, + spaceOf, + VAULT_SPACE, +} from "@/features/sync"; +import type { NoteHeaderHost } from "./host"; import { type LiveStatus, liveStatusOf } from "./live-status"; @@ -25,7 +29,7 @@ interface Header { } export function headerOf( - plugin: PluginHost, + plugin: NoteHeaderHost, leaf: WorkspaceLeaf, ): Header | null { const { view } = leaf; @@ -50,7 +54,7 @@ export function headerOf( } /** Left out of the sync outranks how it would go live. */ -function skippedStatus(plugin: PluginHost, file: TFile): LiveStatus | null { +function skippedStatus(plugin: NoteHeaderHost, file: TFile): LiveStatus | null { const skipped = skippedFiles(plugin.controller).find( ({ path }) => path === file.path, ); diff --git a/packages/plugin/src/features/note-header/host.ts b/packages/plugin/src/features/note-header/host.ts new file mode 100644 index 00000000..13f8c5c3 --- /dev/null +++ b/packages/plugin/src/features/note-header/host.ts @@ -0,0 +1,13 @@ +import type { LiveSessions } from "@/features/live"; +import type { People } from "@/features/presence"; +import type { HubConnection } from "@/features/relay"; +import type { SpacesHost } from "@/features/spaces"; + +/** What the note header needs from the plugin. */ +export interface NoteHeaderHost extends SpacesHost { + readonly realtime: { + readonly hub: HubConnection; + readonly people: People; + readonly live: LiveSessions; + }; +} diff --git a/packages/plugin/src/features/note-header/index.ts b/packages/plugin/src/features/note-header/index.ts new file mode 100644 index 00000000..1ec8dbd1 --- /dev/null +++ b/packages/plugin/src/features/note-header/index.ts @@ -0,0 +1,4 @@ +export type { NoteHeaderHost } from "./host"; +export { rebuildLiveNote, toggleAuthors } from "./live-actions"; +export { canRebuild } from "./note-menu-items"; +export { registerNotePresence } from "./note-presence"; diff --git a/packages/plugin/src/ui/live/header/live-actions.ts b/packages/plugin/src/features/note-header/live-actions.ts similarity index 66% rename from packages/plugin/src/ui/live/header/live-actions.ts rename to packages/plugin/src/features/note-header/live-actions.ts index 8370d6bc..347dd828 100644 --- a/packages/plugin/src/ui/live/header/live-actions.ts +++ b/packages/plugin/src/features/note-header/live-actions.ts @@ -1,6 +1,6 @@ -import type { Rotation } from "@/live/session/session-deps"; -import type { PluginHost } from "@/plugin/host"; -import { notifyInfo, reportError } from "@/ui/common"; +import { notifyInfo, reportError } from "@/core/ui"; +import type { Rotation } from "@/features/live"; +import type { NoteHeaderHost } from "./host"; const REBUILT: Record = { moved: "Live note rebuilt from its text.", @@ -8,7 +8,7 @@ const REBUILT: Record = { busy: "Still sending edits. Try again in a moment.", }; -export function toggleAuthors(plugin: PluginHost): void { +export function toggleAuthors(plugin: NoteHeaderHost): void { const shown = !plugin.settings.showLiveAuthors; plugin.settings.showLiveAuthors = shown; plugin.realtime.live.repaintAuthors(); @@ -20,7 +20,7 @@ export function toggleAuthors(plugin: PluginHost): void { ); } -export function rebuildLiveNote(plugin: PluginHost, path: string): void { +export function rebuildLiveNote(plugin: NoteHeaderHost, path: string): void { void plugin.realtime.live .rotate(path) .then((outcome) => notifyInfo(REBUILT[outcome])) diff --git a/packages/plugin/src/ui/live/header/live-status.ts b/packages/plugin/src/features/note-header/live-status.ts similarity index 87% rename from packages/plugin/src/ui/live/header/live-status.ts rename to packages/plugin/src/features/note-header/live-status.ts index 5536d1ce..b1f7b386 100644 --- a/packages/plugin/src/ui/live/header/live-status.ts +++ b/packages/plugin/src/features/note-header/live-status.ts @@ -1,11 +1,20 @@ import { type FileView, MarkdownView, type TFile } from "obsidian"; - -import { isLinkState, type RelayStatus } from "@/hub/status"; -import { type ColdCause, docKindOf, LIVE_VIEWS, liveKindOf } from "@/live"; -import type { PluginHost } from "@/plugin/host"; -import type { Space } from "@/sync/space"; -import { RELAY_TEXT, UNREADABLE_TEXT } from "@/ui/common"; -import { LINK_LIVE_STATE, type LiveState } from "@/ui/live/live-state"; +import { + isLinkState, + RELAY_TEXT, + type RelayStatus, + UNREADABLE_TEXT, +} from "@/core/hub"; +import { + type ColdCause, + docKindOf, + LINK_LIVE_STATE, + LIVE_VIEWS, + type LiveState, + liveKindOf, +} from "@/features/live"; +import type { Space } from "@/features/sync"; +import type { NoteHeaderHost } from "./host"; const ARRIVES_ON_SYNC = "Changes arrive as they sync"; @@ -34,7 +43,7 @@ const NOT_CARRIED: Partial> = { /** Null where no relay carries `space`, the file's. */ export function liveStatusOf( - plugin: PluginHost, + plugin: NoteHeaderHost, view: FileView, file: TFile, space: Space, @@ -68,7 +77,7 @@ export function liveStatusOf( } function coldReason( - plugin: PluginHost, + plugin: NoteHeaderHost, view: FileView, file: TFile, space: Space, diff --git a/packages/plugin/src/ui/live/header/note-menu-items.ts b/packages/plugin/src/features/note-header/note-menu-items.ts similarity index 95% rename from packages/plugin/src/ui/live/header/note-menu-items.ts rename to packages/plugin/src/features/note-header/note-menu-items.ts index 559038a6..9c0c216f 100644 --- a/packages/plugin/src/ui/live/header/note-menu-items.ts +++ b/packages/plugin/src/features/note-header/note-menu-items.ts @@ -1,5 +1,5 @@ -import type { RelayFix } from "@/ui/common"; -import { STATE_ICONS } from "@/ui/live/live-state"; +import type { RelayFix } from "@/core/hub"; +import { STATE_ICONS } from "@/features/live"; import type { LiveStatus } from "./live-status"; export const LOCKED = "Read-only: shared with you to read"; diff --git a/packages/plugin/src/ui/live/header/note-menu.ts b/packages/plugin/src/features/note-header/note-menu.ts similarity index 89% rename from packages/plugin/src/ui/live/header/note-menu.ts rename to packages/plugin/src/features/note-header/note-menu.ts index 296725b6..0567447c 100644 --- a/packages/plugin/src/ui/live/header/note-menu.ts +++ b/packages/plugin/src/features/note-header/note-menu.ts @@ -1,16 +1,10 @@ import { MarkdownView, Menu, type WorkspaceLeaf } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; -import { - infoTitle, - lastEditLabel, - openPluginSettings, - personTitle, - relayFixOf, - showMenuAt, -} from "@/ui/common"; -import { openShareWindow } from "@/ui/shares/share-window"; +import { relayFixOf } from "@/core/hub"; +import { infoTitle, openPluginSettings, showMenuAt } from "@/core/ui"; +import { personTitle } from "@/features/presence"; +import { lastEditLabel, openShareWindow } from "@/features/spaces"; import { headerOf, showsHeader } from "./header-state"; +import type { NoteHeaderHost } from "./host"; import { rebuildLiveNote, toggleAuthors } from "./live-actions"; import { actionItems, @@ -22,7 +16,7 @@ import { } from "./note-menu-items"; export function openActiveNoteMenu( - plugin: PluginHost, + plugin: NoteHeaderHost, checking: boolean, ): boolean { const leaf = plugin.app.workspace.getMostRecentLeaf(); @@ -34,7 +28,7 @@ export function openActiveNoteMenu( /** Read when opened: the header may be a frame behind. */ export function openNoteMenu( - plugin: PluginHost, + plugin: NoteHeaderHost, leaf: WorkspaceLeaf, anchor?: HTMLElement, ): void { diff --git a/packages/plugin/src/ui/live/header/note-presence.ts b/packages/plugin/src/features/note-header/note-presence.ts similarity index 93% rename from packages/plugin/src/ui/live/header/note-presence.ts rename to packages/plugin/src/features/note-header/note-presence.ts index 1ea4ca56..b6bb0d17 100644 --- a/packages/plugin/src/ui/live/header/note-presence.ts +++ b/packages/plugin/src/features/note-header/note-presence.ts @@ -1,14 +1,10 @@ import { type Plugin, setIcon, type WorkspaceLeaf } from "obsidian"; - -import { watchReadOnlyRoots } from "@/editor/read-only"; -import type { PluginHost } from "@/plugin/host"; -import { - describePeople, - makeActivatable, - renderAvatarStack, -} from "@/ui/common"; -import { STATE_TEXT } from "@/ui/live/live-state"; +import { makeActivatable } from "@/core/ui"; +import { STATE_TEXT } from "@/features/live"; +import { describePeople, renderAvatarStack } from "@/features/presence"; +import { watchReadOnlyRoots } from "@/features/spaces"; import { type HeaderState, headerOf, showsHeader } from "./header-state"; +import type { NoteHeaderHost } from "./host"; import type { LiveStatus } from "./live-status"; import { openActiveNoteMenu, openNoteMenu } from "./note-menu"; import { LOCKED } from "./note-menu-items"; @@ -28,7 +24,7 @@ interface Shown { /** Returns the active note's menu opener, as a command's check callback. */ export function registerNotePresence( - plugin: Plugin & PluginHost, + plugin: Plugin & NoteHeaderHost, ): (checking: boolean) => boolean { const { workspace } = plugin.app; const { people, live } = plugin.realtime; @@ -108,7 +104,7 @@ export function registerNotePresence( } function createHeader( - plugin: PluginHost, + plugin: NoteHeaderHost, leaf: WorkspaceLeaf, actions: HTMLElement, ): HTMLElement { diff --git a/packages/plugin/src/features/presence/README.md b/packages/plugin/src/features/presence/README.md new file mode 100644 index 00000000..122da0c9 --- /dev/null +++ b/packages/plugin/src/features/presence/README.md @@ -0,0 +1,34 @@ +# Presence + +Who is where: each device announces the note it shows on every space channel it holds, and the plugin turns those into avatars in the note header, people in the file tree and share window, cursor following and the tree's "new" dot. Constraints: `.claude/rules/presence.md`; the channel and its frames: `.claude/rules/realtime.md`. + +## Map + +| File | Holds | +|---|---| +| `announcement.ts` | the sealed payload `{key, name, device, note, idle}` | +| `channel.ts` | one space channel's entries, shown only from sockets the hub vouches for | +| `people.ts` | per-space, per-note and per-device views over all channels, cached until a channel changes | +| `views.ts` | grouping and sorting people for display | +| `here.ts` | the active file and idleness of this device | +| `unseen.ts`, `register.ts` | files others changed that this device has not opened, kept in vault localStorage; open, rename and delete hooks | +| `follow/` | following a person: the controller, scrolling to their cursor, the banner | +| `ui/avatars.ts`, `ui/presence.css` | avatars and stacks; header, lock and following styles | + +Keys and identity per space come from `features/spaces/space-access.ts`, shared with live editing. The note header itself is `features/note-header/`, the tree marks `features/explorer/`, the relay dot and menus `features/status/`. + +## Model + +- The key groups people: the person in a share (their devices share a key), the device in the vault (one person). One colour per key everywhere. +- `note` is the path inside the space root, so each mount of a share maps it onto its own folder. A device with no note of a share open still sees who is in which. +- A person's entry lists their devices ("Owner · Laptop, Phone"); each cursor carries its own device name. +- Manifest entries name their publisher (`by` into the manifest's `authors`), which the explorer and history show as last editor; the table only grows, so unchanged entries stay byte-identical. + +## Accepted limitations + +- Every share owner is the key `owner`: two shares of unnamed owners show them alike. +- A remote cursor moves only while its window has focus (y-codemirror), so following goes where they last were there. +- The read-only lock is the editor's: Properties, renames and other plugins still change files there, which then wait unpushed. A note moved into a read-only root while open locks on reopening; a drawing locks once its view loaded (up to 500 ms), and scripts can still edit it. +- The "new" dot knows only what this device pulled: a file seen on another of the same person's devices is still new here. Deletions mark nothing. +- The vault's device list needs the vault key: until a sync knows the passphrase, settings say so instead of listing devices. +- Open: the cursor heartbeat is y-protocols' own, timed by the wall clock. Set back, an idle device sends none and others drop its cursor after 30 s until it moves or someone joins. diff --git a/packages/plugin/src/presence/announcement.ts b/packages/plugin/src/features/presence/announcement.ts similarity index 95% rename from packages/plugin/src/presence/announcement.ts rename to packages/plugin/src/features/presence/announcement.ts index d06a5f3e..cd0a6771 100644 --- a/packages/plugin/src/presence/announcement.ts +++ b/packages/plugin/src/features/presence/announcement.ts @@ -1,5 +1,5 @@ -import type { LiveKeys } from "@/crypto/live-keys"; -import { seal, unseal } from "@/crypto/seal"; +import type { LiveKeys } from "@/core/crypto"; +import { seal, unseal } from "@/core/crypto"; /** One device's place in a space, sealed whole: the relay learns no names or paths. */ export interface Announcement { diff --git a/packages/plugin/src/presence/channel.ts b/packages/plugin/src/features/presence/channel.ts similarity index 98% rename from packages/plugin/src/presence/channel.ts rename to packages/plugin/src/features/presence/channel.ts index 78d07bd3..24d62f9b 100644 --- a/packages/plugin/src/presence/channel.ts +++ b/packages/plugin/src/features/presence/channel.ts @@ -1,6 +1,6 @@ import { EFrame, OWNER, type ServerFrame } from "@mdsync/protocol"; -import type { LiveKeys } from "@/crypto/live-keys"; +import type { LiveKeys } from "@/core/crypto"; import { type Announcement, openAnnouncement } from "./announcement"; diff --git a/packages/plugin/src/ui/live/header/cursor-follow.ts b/packages/plugin/src/features/presence/follow/cursor-follow.ts similarity index 94% rename from packages/plugin/src/ui/live/header/cursor-follow.ts rename to packages/plugin/src/features/presence/follow/cursor-follow.ts index 5338eb61..70301b95 100644 --- a/packages/plugin/src/ui/live/header/cursor-follow.ts +++ b/packages/plugin/src/features/presence/follow/cursor-follow.ts @@ -1,9 +1,8 @@ import { FileView, MarkdownView, type WorkspaceLeaf } from "obsidian"; - -import type { LiveSession } from "@/live"; -import type { PluginHost } from "@/plugin/host"; -import type { Person } from "@/presence"; -import { openNote } from "@/ui/common"; +import { openNote } from "@/core/ui"; +import type { LiveSession } from "@/features/live"; +import type { PresenceHost } from "../host"; +import type { Person } from "../views"; import { showFollowBanner } from "./follow-banner"; import { trackCursor } from "./follow-scroll"; @@ -25,7 +24,7 @@ interface Following { export class CursorFollow { private current: Following | null = null; - constructor(private readonly plugin: PluginHost) {} + constructor(private readonly plugin: PresenceHost) {} of(leaf: WorkspaceLeaf): string | null { return this.current?.leaf === leaf ? this.current.key : null; diff --git a/packages/plugin/src/ui/live/header/follow-banner.ts b/packages/plugin/src/features/presence/follow/follow-banner.ts similarity index 87% rename from packages/plugin/src/ui/live/header/follow-banner.ts rename to packages/plugin/src/features/presence/follow/follow-banner.ts index 9268e432..a132984d 100644 --- a/packages/plugin/src/ui/live/header/follow-banner.ts +++ b/packages/plugin/src/features/presence/follow/follow-banner.ts @@ -1,8 +1,7 @@ import { ButtonComponent } from "obsidian"; - -import type { Person } from "@/presence"; -import { personColor } from "@/shared"; -import { renderAvatar } from "@/ui/common"; +import { personColor } from "@/core/shared"; +import { renderAvatar } from "../ui/avatars"; +import type { Person } from "../views"; /** The strip under a following tab's header: whom it follows, and the way out. */ export function showFollowBanner( diff --git a/packages/plugin/src/ui/live/header/follow-scroll.ts b/packages/plugin/src/features/presence/follow/follow-scroll.ts similarity index 93% rename from packages/plugin/src/ui/live/header/follow-scroll.ts rename to packages/plugin/src/features/presence/follow/follow-scroll.ts index 797b8ba4..7abe55b7 100644 --- a/packages/plugin/src/ui/live/header/follow-scroll.ts +++ b/packages/plugin/src/features/presence/follow/follow-scroll.ts @@ -1,7 +1,8 @@ import type { EditorView } from "@codemirror/view"; import type { MarkdownView } from "obsidian"; -import { type LiveSession, watchCursor } from "@/live"; +import type { LiveSession } from "@/features/live"; +import { watchCursor } from "@/features/live"; /** Their cursor moves freely inside the middle half of the view; past it, it is centred again. */ const MARGIN = 0.25; diff --git a/packages/plugin/src/plugin/follows.ts b/packages/plugin/src/features/presence/follow/follows.ts similarity index 57% rename from packages/plugin/src/plugin/follows.ts rename to packages/plugin/src/features/presence/follow/follows.ts index 2273582b..5c5604c3 100644 --- a/packages/plugin/src/plugin/follows.ts +++ b/packages/plugin/src/features/presence/follow/follows.ts @@ -1,10 +1,9 @@ import type { Plugin } from "obsidian"; - -import { CursorFollow } from "@/ui"; -import type { PluginHost } from "./host"; +import type { PresenceHost } from "../host"; +import { CursorFollow } from "./cursor-follow"; /** One for the plugin: the note header's menu and the share window both start following. */ -export function registerFollows(plugin: Plugin & PluginHost): CursorFollow { +export function registerFollows(plugin: Plugin & PresenceHost): CursorFollow { const follows = new CursorFollow(plugin); plugin.register(() => follows.stop()); return follows; diff --git a/packages/plugin/src/presence/here.ts b/packages/plugin/src/features/presence/here.ts similarity index 100% rename from packages/plugin/src/presence/here.ts rename to packages/plugin/src/features/presence/here.ts diff --git a/packages/plugin/src/features/presence/host.ts b/packages/plugin/src/features/presence/host.ts new file mode 100644 index 00000000..27bdd8da --- /dev/null +++ b/packages/plugin/src/features/presence/host.ts @@ -0,0 +1,9 @@ +import type { App } from "obsidian"; +import type { LiveSessions } from "@/features/live"; +import type { People } from "./people"; + +/** What presence needs from the plugin. */ +export interface PresenceHost { + readonly app: App; + readonly realtime: { readonly live: LiveSessions; readonly people: People }; +} diff --git a/packages/plugin/src/features/presence/index.ts b/packages/plugin/src/features/presence/index.ts new file mode 100644 index 00000000..7457e9bf --- /dev/null +++ b/packages/plugin/src/features/presence/index.ts @@ -0,0 +1,14 @@ +export { CursorFollow } from "./follow/cursor-follow"; +export { registerFollows } from "./follow/follows"; +export { watchHere } from "./here"; +export type { PresenceHost } from "./host"; +export { People } from "./people"; +export { markTheirs, registerUnseen } from "./register"; +export { + describePeople, + personTitle, + renderAvatar, + renderAvatarStack, +} from "./ui/avatars"; +export { Unseen } from "./unseen"; +export { isAtNote, mergePeople, type Person } from "./views"; diff --git a/packages/plugin/src/presence/people.ts b/packages/plugin/src/features/presence/people.ts similarity index 97% rename from packages/plugin/src/presence/people.ts rename to packages/plugin/src/features/presence/people.ts index c008ed2b..aaae7bc4 100644 --- a/packages/plugin/src/presence/people.ts +++ b/packages/plugin/src/features/presence/people.ts @@ -2,16 +2,16 @@ import { CHANNEL_DOC, EFrame } from "@mdsync/protocol"; -import type { LiveKeys } from "@/crypto/live-keys"; -import type { HubConnection, SpaceHub } from "@/hub"; -import { reportWarning } from "@/shared"; +import type { LiveKeys } from "@/core/crypto"; +import type { SpaceHub, SpaceHubs } from "@/core/hub"; +import { reportWarning } from "@/core/shared"; import { insideOf, type Space, spaceOf, VAULT_SPACE, vaultPathOf, -} from "@/sync/space"; +} from "@/features/sync"; import { type Announcement, sealAnnouncement } from "./announcement"; import { ChannelPresence } from "./channel"; @@ -32,7 +32,7 @@ export interface PresenceAccess { } export interface PeopleDeps { - hub: Pick; + hub: Pick; /** Paused spaces flagged; the same array until the partition changes. */ spaces(): readonly Space[]; access(space: Space): Promise; diff --git a/packages/plugin/src/plugin/unseen.ts b/packages/plugin/src/features/presence/register.ts similarity index 92% rename from packages/plugin/src/plugin/unseen.ts rename to packages/plugin/src/features/presence/register.ts index de2a8cd8..f585c22d 100644 --- a/packages/plugin/src/plugin/unseen.ts +++ b/packages/plugin/src/features/presence/register.ts @@ -1,7 +1,6 @@ import type { Plugin } from "obsidian"; - -import { Unseen } from "@/presence"; -import { type Space, VAULT_SPACE } from "@/sync/space"; +import { type Space, VAULT_SPACE } from "@/features/sync"; +import { Unseen } from "./unseen"; const STORAGE_KEY = "mdsync-unseen"; diff --git a/packages/plugin/src/ui/common/avatars.ts b/packages/plugin/src/features/presence/ui/avatars.ts similarity index 76% rename from packages/plugin/src/ui/common/avatars.ts rename to packages/plugin/src/features/presence/ui/avatars.ts index 1c3efcef..ea9d3812 100644 --- a/packages/plugin/src/ui/common/avatars.ts +++ b/packages/plugin/src/features/presence/ui/avatars.ts @@ -1,5 +1,5 @@ -import type { Person } from "@/presence"; -import { personColor, withDevices } from "@/shared"; +import { personColor, withDevices } from "@/core/shared"; +import type { Person } from "../views"; /** More faces than this collapse into a "+N". */ const STACK_MAX = 3; @@ -18,6 +18,14 @@ export function renderAvatar( return avatar; } +export function personTitle(person: Person, state: string): DocumentFragment { + const title = createFragment(); + renderAvatar(title, person); + title.createSpan({ text: withDevices(person.name, person.devices) }); + title.createSpan({ cls: "mdsync-person-state", text: state }); + return title; +} + export function renderAvatarStack( parent: HTMLElement, people: readonly Person[], diff --git a/packages/plugin/src/styles/presence.css b/packages/plugin/src/features/presence/ui/presence.css similarity index 100% rename from packages/plugin/src/styles/presence.css rename to packages/plugin/src/features/presence/ui/presence.css diff --git a/packages/plugin/src/presence/unseen.ts b/packages/plugin/src/features/presence/unseen.ts similarity index 100% rename from packages/plugin/src/presence/unseen.ts rename to packages/plugin/src/features/presence/unseen.ts diff --git a/packages/plugin/src/presence/views.ts b/packages/plugin/src/features/presence/views.ts similarity index 100% rename from packages/plugin/src/presence/views.ts rename to packages/plugin/src/features/presence/views.ts diff --git a/packages/plugin/src/hub/channels.ts b/packages/plugin/src/features/relay/channels.ts similarity index 88% rename from packages/plugin/src/hub/channels.ts rename to packages/plugin/src/features/relay/channels.ts index dee467b5..676eb5ab 100644 --- a/packages/plugin/src/hub/channels.ts +++ b/packages/plugin/src/features/relay/channels.ts @@ -5,20 +5,18 @@ import { deriveChannelGrant, MAX_SLOTS, shareChannel } from "@mdsync/protocol"; -import { sha256Hex } from "@/crypto"; +import { sha256Hex } from "@/core/crypto"; +import type { HubChannel } from "@/core/hub"; +import { isRelayConfigured, type MdsyncSettings } from "@/core/settings"; +import { relayBase } from "@/core/shared"; +import type { SpaceRecord } from "@/features/spaces"; +import { pauseOf } from "@/features/spaces"; import { activeStorage, - isRelayConfigured, isStorageConfigured, - type MdsyncSettings, -} from "@/settings/model"; -import { relayBase } from "@/shared"; -import { pauseOf } from "@/spaces"; -import type { SpaceRecord } from "@/spaces/record"; -import { storageIdentity } from "@/storage"; -import { VAULT_SPACE } from "@/sync/space"; - -import type { HubChannel } from "./link"; + storageIdentity, +} from "@/features/storage"; +import { VAULT_SPACE } from "@/features/sync"; export interface HubRoute { serverUrl: string; diff --git a/packages/plugin/src/hub/connection.ts b/packages/plugin/src/features/relay/connection.ts similarity index 82% rename from packages/plugin/src/hub/connection.ts rename to packages/plugin/src/features/relay/connection.ts index 035dda14..55d39984 100644 --- a/packages/plugin/src/hub/connection.ts +++ b/packages/plugin/src/features/relay/connection.ts @@ -3,45 +3,20 @@ * credentials change; listeners outlive the rebuilds. */ -import { type ClientFrame, EFrame, type ServerFrame } from "@mdsync/protocol"; - -import type { MdsyncSettings } from "@/settings/model"; -import { pauseOf } from "@/spaces"; -import { VAULT_SPACE } from "@/sync/space"; - +import { EFrame, type ServerFrame } from "@mdsync/protocol"; +import { + HubLink, + type HubListener, + type LinkState, + type RelayStatus, + relayStatus, + type SpaceHub, + type SpaceListener, +} from "@/core/hub"; +import type { MdsyncSettings } from "@/core/settings"; +import { pauseOf } from "@/features/spaces"; +import { VAULT_SPACE } from "@/features/sync"; import { type HubRoute, hubRoutes } from "./channels"; -import { HubLink } from "./link"; -import { type RelayStatus, relayStatus } from "./status"; - -/** The relay's own state and the cold-sync ping; frames go to `SpaceListener`s. */ -export interface HubListener { - /** Another device pushed into any space this device holds. */ - onSignal?(spaceId: string): void; - /** The relay cut a space's grant: revoked, or a token too new for it yet. */ - onRevoked?(): void; - /** The vault's socket; also reported on every restart, so listeners drop state tied to the old link. */ - onConnectionChange?(connected: boolean): void; -} - -export interface SpaceListener { - onFrame?(frame: ServerFrame): void; - /** False on every restart of its socket and when the relay revokes the channel. */ - onConnectionChange?(connected: boolean): void; -} - -/** A client frame before its socket's slot is known. */ -export type SpaceFrame = ClientFrame extends infer F - ? F extends ClientFrame - ? Omit - : never - : never; - -/** A space's channel on whichever socket holds it; frames sent while it is down are dropped. */ -export interface SpaceHub { - send(frame: SpaceFrame): void; - isConnected(): boolean; - listen(listener: SpaceListener): () => void; -} export interface HubConnectionOptions { settings(): MdsyncSettings; @@ -51,6 +26,15 @@ export interface HubConnectionOptions { const REVOKED_RETRY_MS = 15_000; const REVOKED_RETRIES = 3; +/** One socket: the relay it goes to, the state its spaces share, and those spaces in slot order. */ +export interface RelaySocket { + url: string; + state: LinkState; + spaces: readonly string[]; + /** Spaces this relay had no slot left for: they sync on the schedule. */ + full: readonly string[]; +} + interface OpenLink { route: HubRoute; link: HubLink; @@ -89,6 +73,16 @@ export class HubConnection { }); } + /** The sockets this device holds, in the routes' order: its own relay first. */ + relays(): RelaySocket[] { + return hubRoutes(this.options.settings()).flatMap(({ serverUrl }) => { + const open = this.links.get(serverUrl); + if (!open) return []; + const { spaces, full } = open.route; + return [{ url: serverUrl, state: open.link.state, spaces, full }]; + }); + } + listen(listener: HubListener): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener); diff --git a/packages/plugin/src/cloudflare/assets.ts b/packages/plugin/src/features/relay/deploy/assets.ts similarity index 91% rename from packages/plugin/src/cloudflare/assets.ts rename to packages/plugin/src/features/relay/deploy/assets.ts index 26ae20a8..5d47d691 100644 --- a/packages/plugin/src/cloudflare/assets.ts +++ b/packages/plugin/src/features/relay/deploy/assets.ts @@ -1,8 +1,7 @@ -import { bytesToBase64 } from "@/utils"; - -import type { CloudflareApi } from "./api"; +import type { CloudflareApi } from "@/core/cloudflare"; +import { encodeForm } from "@/core/cloudflare"; +import { bytesToBase64 } from "@/core/utils"; import type { RelayAsset } from "./bundle"; -import { encodeForm } from "./multipart"; const encoder = new TextEncoder(); diff --git a/packages/plugin/src/cloudflare/bundle.ts b/packages/plugin/src/features/relay/deploy/bundle.ts similarity index 100% rename from packages/plugin/src/cloudflare/bundle.ts rename to packages/plugin/src/features/relay/deploy/bundle.ts diff --git a/packages/plugin/src/settings/setup/relay.ts b/packages/plugin/src/features/relay/deploy/deploy-flow.ts similarity index 78% rename from packages/plugin/src/settings/setup/relay.ts rename to packages/plugin/src/features/relay/deploy/deploy-flow.ts index 2da749bf..7f8bec13 100644 --- a/packages/plugin/src/settings/setup/relay.ts +++ b/packages/plugin/src/features/relay/deploy/deploy-flow.ts @@ -1,20 +1,18 @@ import bundle from "mdsync:relay-bundle"; import { toHex } from "@mdsync/protocol"; - +import { randomBytes, randomSecret } from "@/core/crypto"; +import { isRelayConfigured, type RelayConfig } from "@/core/settings"; +import type { CloudflareLogin } from "@/features/storage"; +import type { RelayHost } from "../host"; +import { testRelay } from "../relay-test"; import { type AccountRelays, - deployRelay, - type ERelayDeployStep, ownRelayName, RELAY_NAME, RELAY_VERSION, type RelayTarget, -} from "@/cloudflare"; -import { randomBytes, randomSecret } from "@/crypto"; -import type { PluginHost } from "@/plugin/host"; -import type { CloudflareLogin } from "@/settings/cloudflare-login"; -import { testRelay } from "@/settings/connection-test"; -import { isRelayConfigured, type RelayConfig } from "@/settings/model"; +} from "./relay-account"; +import { deployRelay, type ERelayDeployStep } from "./relay-deploy"; const POLL_MS = 3000; /** A workers.dev name registered just now can take minutes to answer. */ @@ -64,7 +62,7 @@ export function failedRelay(accountId: string): RelayTarget | null { * never loses the secret of a live relay. */ export function deployOwnRelay( - plugin: PluginHost, + plugin: RelayHost, login: CloudflareLogin, target: RelayTarget, onStep: (step: ERelayDeployStep) => void, @@ -90,7 +88,7 @@ export function deployOwnRelay( } async function deployTo( - plugin: PluginHost, + plugin: RelayHost, login: CloudflareLogin, target: RelayTarget, onStep: (step: ERelayDeployStep) => void, @@ -129,15 +127,22 @@ export async function waitForRelay( let activating: Promise | null = null; -/** One wait however many wizards ask: the relay is switched on once, when it answers. Survives a closed wizard, stops on unload. */ -export function activateRelay(plugin: PluginHost): Promise { +/** + * One wait however many wizards ask: the relay is switched on once, when it answers. Survives a closed wizard, stops on unload. + * `realtime` is asked when the relay answers, not before: the choice may change while it is awaited. + * Without it real-time sync stays as it is, as an update needs. + */ +export function activateRelay( + plugin: RelayHost, + realtime: () => boolean = () => false, +): Promise { activating ??= (async () => { try { const answered = await waitForRelay( plugin.settings, () => !plugin.unloaded, ); - if (answered) await useRelay(plugin); + if (answered) await useRelay(plugin, realtime()); return answered; } finally { activating = null; @@ -146,9 +151,12 @@ export function activateRelay(plugin: PluginHost): Promise { return activating; } -/** Real-time sync is what a relay is for: on once it answers. */ -export async function useRelay(plugin: PluginHost): Promise { - plugin.settings.realtimeSync = true; +/** Real-time sync is what a relay is for: on once it answers, unless the person chose otherwise (`realtime` false). */ +export async function useRelay( + plugin: RelayHost, + realtime = true, +): Promise { + if (realtime) plugin.settings.realtimeSync = true; await plugin.saveSettings(); plugin.realtime.hub.restart(); } diff --git a/packages/plugin/src/cloudflare/migrations.ts b/packages/plugin/src/features/relay/deploy/migrations.ts similarity index 100% rename from packages/plugin/src/cloudflare/migrations.ts rename to packages/plugin/src/features/relay/deploy/migrations.ts diff --git a/packages/plugin/src/cloudflare/relay-account.ts b/packages/plugin/src/features/relay/deploy/relay-account.ts similarity index 98% rename from packages/plugin/src/cloudflare/relay-account.ts rename to packages/plugin/src/features/relay/deploy/relay-account.ts index 93fe5ca0..abe1f824 100644 --- a/packages/plugin/src/cloudflare/relay-account.ts +++ b/packages/plugin/src/features/relay/deploy/relay-account.ts @@ -1,6 +1,6 @@ import bundle from "mdsync:relay-bundle"; -import type { CloudflareApi } from "./api"; +import type { CloudflareApi } from "@/core/cloudflare"; import { workerNames, workersSubdomain, workerUrl } from "./relay-deploy"; /** The relay build this plugin carries, `+`; `/status` of a relay running it says the same. */ diff --git a/packages/plugin/src/cloudflare/relay-bundle.d.ts b/packages/plugin/src/features/relay/deploy/relay-bundle.d.ts similarity index 73% rename from packages/plugin/src/cloudflare/relay-bundle.d.ts rename to packages/plugin/src/features/relay/deploy/relay-bundle.d.ts index 5e0dc236..5daf10f5 100644 --- a/packages/plugin/src/cloudflare/relay-bundle.d.ts +++ b/packages/plugin/src/features/relay/deploy/relay-bundle.d.ts @@ -1,6 +1,6 @@ /** The relay this build deploys, built from packages/relay by esbuild.relay-bundle.mjs. */ declare module "mdsync:relay-bundle" { - import type { RelayBundle } from "@/cloudflare/bundle"; + import type { RelayBundle } from "@/features/relay/deploy/bundle"; const bundle: RelayBundle; export default bundle; diff --git a/packages/plugin/src/cloudflare/relay-deploy.ts b/packages/plugin/src/features/relay/deploy/relay-deploy.ts similarity index 98% rename from packages/plugin/src/cloudflare/relay-deploy.ts rename to packages/plugin/src/features/relay/deploy/relay-deploy.ts index 68f0b7c5..28fe9545 100644 --- a/packages/plugin/src/cloudflare/relay-deploy.ts +++ b/packages/plugin/src/features/relay/deploy/relay-deploy.ts @@ -1,8 +1,7 @@ -import { type CloudflareApi, hasCode } from "./api"; +import { type CloudflareApi, encodeForm, hasCode } from "@/core/cloudflare"; import { uploadAssets } from "./assets"; import type { RelayBundle } from "./bundle"; import { type MigrationUpload, pendingMigrations } from "./migrations"; -import { encodeForm } from "./multipart"; export const ERelayDeployStep = { Subdomain: "subdomain", diff --git a/packages/plugin/src/features/relay/host.ts b/packages/plugin/src/features/relay/host.ts new file mode 100644 index 00000000..e0a35b67 --- /dev/null +++ b/packages/plugin/src/features/relay/host.ts @@ -0,0 +1,12 @@ +import type { App } from "obsidian"; +import type { SettingsHost } from "@/core/settings"; +import type { HubConnection } from "./connection"; + +/** What the relay needs from the plugin. */ +export interface RelayHost extends SettingsHost { + readonly app: App; + readonly realtime: { readonly hub: HubConnection }; + /** Work that outlives its view, like a relay deploy, stops here. */ + readonly unloaded: boolean; + openSetup(step: "relay"): void; +} diff --git a/packages/plugin/src/features/relay/index.ts b/packages/plugin/src/features/relay/index.ts new file mode 100644 index 00000000..a4e44a0a --- /dev/null +++ b/packages/plugin/src/features/relay/index.ts @@ -0,0 +1,24 @@ +export { HubConnection, type RelaySocket } from "./connection"; +export { + activateRelay, + deployOwnRelay, + failedRelay, + planRelay, + runningRelayDeploy, + useRelay, +} from "./deploy/deploy-flow"; +export { + type AccountRelays, + accountRelays, + freeRelayName, + RELAY_NAME, + type RelayTarget, + relayBehind, + relayNameError, + relayUrlOf, +} from "./deploy/relay-account"; +export { ERelayDeployStep } from "./deploy/relay-deploy"; +export type { RelayHost } from "./host"; +export { type RelayTestResult, testRelay } from "./relay-test"; +export { relaySection } from "./ui/relay-section"; +export { type RelayUpdate, registerRelayUpdate } from "./update/relay-update"; diff --git a/packages/plugin/src/features/relay/relay-test.ts b/packages/plugin/src/features/relay/relay-test.ts new file mode 100644 index 00000000..b9d6b4b4 --- /dev/null +++ b/packages/plugin/src/features/relay/relay-test.ts @@ -0,0 +1,64 @@ +import { ADMIN_HEADER } from "@mdsync/protocol"; +import { requestUrl } from "obsidian"; + +import { + type CheckResult, + isRelayConfigured, + type RelayConfig, +} from "@/core/settings"; +import { errorMessage, isCleartextRemote, relayBase } from "@/core/shared"; + +export interface RelayTestResult extends CheckResult { + /** The build the relay runs; null for one deployed outside MDSync. */ + version?: string | null; +} + +/** Tells a wrong URL (unreachable, HTTP 404) apart from a wrong secret. */ +export async function testRelay(relay: RelayConfig): Promise { + if (isCleartextRemote(relay.relayUrl)) { + return { + ok: false, + message: + "Use an https:// relay URL: the secret is sent with every request.", + }; + } + if (!isRelayConfigured(relay)) { + return { ok: false, message: "Enter the relay URL and secret first." }; + } + try { + const res = await requestUrl({ + url: `${relayBase(relay.relayUrl)}/status`, + method: "GET", + headers: { [ADMIN_HEADER]: relay.relaySecret }, + throw: false, + }); + const body = jsonOf(res) as { + message?: string; + version?: string | null; + } | null; + return res.status === 200 + ? { + ok: true, + message: "Connected. The relay accepts this secret.", + version: body?.version ?? null, + } + : { + ok: false, + message: `Relay error: ${body?.message ?? `HTTP ${res.status}`}`, + }; + } catch (err) { + return { ok: false, message: errorMessage(err) }; + } +} + +/** + * An edge error page is HTML and Obsidian parses `.json` lazily: reading it would throw a SyntaxError over + * the status the caller needs. + */ +function jsonOf(res: { json?: unknown }): unknown { + try { + return res.json ?? null; + } catch { + return null; + } +} diff --git a/packages/plugin/src/settings/sections/relay.ts b/packages/plugin/src/features/relay/ui/relay-section.ts similarity index 75% rename from packages/plugin/src/settings/sections/relay.ts rename to packages/plugin/src/features/relay/ui/relay-section.ts index 0e0c440b..4310b580 100644 --- a/packages/plugin/src/settings/sections/relay.ts +++ b/packages/plugin/src/features/relay/ui/relay-section.ts @@ -1,25 +1,26 @@ import type { SettingDefinitionGroup } from "obsidian"; - -import { randomSecret } from "@/crypto"; -import { forgetCloudflare } from "@/settings/cloudflare-login"; -import { testRelay } from "@/settings/connection-test"; +import { randomSecret } from "@/core/crypto"; import { checkRow, + EFieldKind, type FieldContext, fieldRow, group, -} from "@/settings/fields"; -import { isRelayConfigured } from "@/settings/model"; -import { ESetupStep } from "@/settings/setup/steps"; -import { relayBase } from "@/shared"; -import { EFieldKind } from "@/storage"; -import { runWithNotice } from "@/ui/common"; + isRelayConfigured, +} from "@/core/settings"; +import { relayBase } from "@/core/shared"; +import { copyText } from "@/core/ui"; +import { forgetCloudflare } from "@/features/storage"; +import type { RelayHost } from "../host"; +import { testRelay } from "../relay-test"; function secretButtonLabel(secret: string): string { return secret ? "Copy" : "Generate"; } -export function relaySection(ctx: FieldContext): SettingDefinitionGroup { +export function relaySection( + ctx: FieldContext, +): SettingDefinitionGroup { const { plugin } = ctx; const secretRow = fieldRow(ctx, { kind: EFieldKind.Password, @@ -38,7 +39,7 @@ export function relaySection(ctx: FieldContext): SettingDefinitionGroup { setting.addButton((button) => button .setButtonText(configured ? "Update" : "Deploy") - .onClick(() => plugin.openSetup(ESetupStep.Relay)), + .onClick(() => plugin.openSetup("relay")), ); }, }, @@ -69,12 +70,7 @@ export function relaySection(ctx: FieldContext): SettingDefinitionGroup { await plugin.saveSettings(); ctx.rerender(); } - const { relaySecret } = plugin.settings; - await runWithNotice( - () => navigator.clipboard.writeText(relaySecret), - "Relay secret copied.", - "Could not copy the relay secret", - ); + await copyText("Relay secret", plugin.settings.relaySecret); }); }); }, diff --git a/packages/plugin/src/ui/modals/relay-update-modal.ts b/packages/plugin/src/features/relay/update/relay-update-modal.ts similarity index 86% rename from packages/plugin/src/ui/modals/relay-update-modal.ts rename to packages/plugin/src/features/relay/update/relay-update-modal.ts index 92a825ff..f7f4fa3c 100644 --- a/packages/plugin/src/ui/modals/relay-update-modal.ts +++ b/packages/plugin/src/features/relay/update/relay-update-modal.ts @@ -1,26 +1,24 @@ import { ButtonComponent, Modal } from "obsidian"; - -import type { RelayTarget } from "@/cloudflare"; -import type { PluginHost } from "@/plugin/host"; -import { - type CloudflareLogin, - cloudflareErrorMessage, -} from "@/settings/cloudflare-login"; -import { activateRelay, deployOwnRelay } from "@/settings/setup/relay"; import { alertLine, modalFooter, modalHint, notifyError, notifyInfo, + openPromiseModal, renderModalHead, -} from "@/ui/common"; - -import { openPromiseModal } from "./promise-modal"; +} from "@/core/ui"; +import { + type CloudflareLogin, + cloudflareErrorMessage, +} from "@/features/storage"; +import { activateRelay, deployOwnRelay } from "../deploy/deploy-flow"; +import type { RelayTarget } from "../deploy/relay-account"; +import type { RelayHost } from "../host"; /** True once the relay is updated; any other close is "not now". */ export function openRelayUpdateModal( - plugin: PluginHost, + plugin: RelayHost, login: CloudflareLogin, target: RelayTarget, ): Promise { diff --git a/packages/plugin/src/plugin/relay-update.ts b/packages/plugin/src/features/relay/update/relay-update.ts similarity index 89% rename from packages/plugin/src/plugin/relay-update.ts rename to packages/plugin/src/features/relay/update/relay-update.ts index eea5865e..637025b8 100644 --- a/packages/plugin/src/plugin/relay-update.ts +++ b/packages/plugin/src/features/relay/update/relay-update.ts @@ -1,19 +1,17 @@ import type { Plugin } from "obsidian"; - +import { reportWarning } from "@/core/shared"; +import { cloudflareOf } from "@/features/storage"; +import { runningRelayDeploy } from "../deploy/deploy-flow"; import { accountRelays, ownRelayName, RELAY_VERSION, type RelayTarget, relayBehind, -} from "@/cloudflare"; -import { cloudflareOf } from "@/settings/cloudflare-login"; -import { testRelay } from "@/settings/connection-test"; -import { runningRelayDeploy } from "@/settings/setup/relay"; -import { reportWarning } from "@/shared"; -import { openRelayUpdateModal } from "@/ui"; - -import type { PluginHost } from "./host"; +} from "../deploy/relay-account"; +import type { RelayHost } from "../host"; +import { testRelay } from "../relay-test"; +import { openRelayUpdateModal } from "./relay-update-modal"; const SKIPPED_KEY = "mdsync-relay-update-skipped"; @@ -29,7 +27,7 @@ export interface RelayUpdate { * update once per relay per launch; "not now" holds until a newer build ships. A deploy reconnects the * socket, so a relay found outdated is checked again on every connect. */ -export function registerRelayUpdate(plugin: Plugin & PluginHost): RelayUpdate { +export function registerRelayUpdate(plugin: Plugin & RelayHost): RelayUpdate { const checked = new Set(); const listeners = new Set<() => void>(); /** The relays found outdated, by account and URL, with the secret they answered to. */ diff --git a/packages/plugin/src/features/settings/activity-card.ts b/packages/plugin/src/features/settings/activity-card.ts new file mode 100644 index 00000000..3d86e793 --- /dev/null +++ b/packages/plugin/src/features/settings/activity-card.ts @@ -0,0 +1,42 @@ +import { ButtonComponent } from "obsidian"; +import { formatRelativeTime, pluralize } from "@/core/shared"; +import { closePluginSettings } from "@/core/ui"; +import { + activeStorage, + isStorageConfigured, + storageIdentity, +} from "@/features/storage"; +import { buildCalendar, renderActivityCalendar } from "@/features/sync"; +import type { SettingsTabHost } from "./host"; + +/** A year of the vault's pushes as this device last read them: no request, so nothing until history is read once. */ +export function renderActivityCard( + parent: HTMLElement, + plugin: SettingsTabHost, +): void { + const { settings } = plugin; + if (!settings.fileHistoryEnabled || !isStorageConfigured(settings)) return; + const cached = plugin.controller.activity.recall( + storageIdentity(activeStorage(settings)), + ); + if (!cached) return; + const open = (day?: number): void => { + closePluginSettings(plugin.app); + void plugin.openTimeline(day); + }; + const calendar = buildCalendar(cached.activity, null); + const card = parent.createDiv({ + cls: "mdsync-overview-card mdsync-overview-activity", + }); + const head = card.createDiv({ cls: "mdsync-overview-activity-head" }); + const text = head.createDiv(); + text.createDiv({ cls: "mdsync-overview-card-title", text: "Activity" }); + text.createDiv({ + cls: "mdsync-overview-card-lines", + text: `${pluralize(calendar.pushes, "push", "pushes")} in the last year · updated ${formatRelativeTime(cached.at)}`, + }); + new ButtonComponent(head) + .setButtonText("Open timeline") + .onClick(() => open()); + renderActivityCalendar(card, calendar, { onPick: (day) => open(day.start) }); +} diff --git a/packages/plugin/src/features/settings/host.ts b/packages/plugin/src/features/settings/host.ts new file mode 100644 index 00000000..93e29c9d --- /dev/null +++ b/packages/plugin/src/features/settings/host.ts @@ -0,0 +1,29 @@ +import type { LogService } from "@/core/logs"; +import type { LinksHost } from "@/features/links"; +import type { LiveSessions } from "@/features/live"; +import type { RelayHost, RelayUpdate } from "@/features/relay"; +import type { SpacesHost } from "@/features/spaces"; +import type { + DeviceName, + HistorySectionHost, + PassphraseManager, +} from "@/features/sync"; +import type { TransferHost } from "@/features/transfer"; + +/** What the settings tab needs from the plugin: every section's host. */ +export interface SettingsTabHost + extends HistorySectionHost, + SpacesHost, + LinksHost, + RelayHost, + TransferHost { + readonly logs: LogService; + readonly passphrase: PassphraseManager; + readonly device: DeviceName; + readonly relayUpdate: RelayUpdate; + readonly realtime: SpacesHost["realtime"] & + RelayHost["realtime"] & { readonly live: LiveSessions }; + openSetup(step?: "relay"): void; + refreshEditorSigns(enabled: boolean): void; + refreshFileIndicators(enabled: boolean): void; +} diff --git a/packages/plugin/src/features/settings/index.ts b/packages/plugin/src/features/settings/index.ts new file mode 100644 index 00000000..9c7bec1a --- /dev/null +++ b/packages/plugin/src/features/settings/index.ts @@ -0,0 +1,3 @@ +export type { SettingsTabHost } from "./host"; +export { SETUP_FIELDS } from "./sections/realtime"; +export { MdsyncSettingTab } from "./tab"; diff --git a/packages/plugin/src/settings/logs-view.ts b/packages/plugin/src/features/settings/logs-view.ts similarity index 92% rename from packages/plugin/src/settings/logs-view.ts rename to packages/plugin/src/features/settings/logs-view.ts index c6cab6ce..653f352e 100644 --- a/packages/plugin/src/settings/logs-view.ts +++ b/packages/plugin/src/features/settings/logs-view.ts @@ -7,11 +7,11 @@ import { ESyncLogLevel, ESyncLogOperation, type SyncLogEntry, -} from "@/logs/store"; -import type { PluginHost } from "@/plugin/host"; -import { formatTimestamp, pluralize } from "@/shared"; -import { copyText } from "@/ui/common"; -import { imperativePage } from "./page"; +} from "@/core/logs"; +import { imperativePage } from "@/core/settings"; +import { formatTimestamp, pluralize } from "@/core/shared"; +import { copyText } from "@/core/ui"; +import type { SettingsTabHost } from "./host"; const LOG_LEVEL_LABELS: Record = { [ESyncLogLevel.Info]: "Info", @@ -35,7 +35,7 @@ const OPERATION_LABELS: Record = { const RECENT_ERRORS_MS = 24 * 60 * 60 * 1000; -export function logsPage(plugin: PluginHost): SettingDefinitionPage { +export function logsPage(plugin: SettingsTabHost): SettingDefinitionPage { const recentErrors = (): number => { const since = Date.now() - RECENT_ERRORS_MS; return plugin.logs @@ -61,7 +61,7 @@ export function logsPage(plugin: PluginHost): SettingDefinitionPage { function renderLogsView( parent: HTMLElement, - plugin: PluginHost, + plugin: SettingsTabHost, onRefresh: () => void, ): void { parent.createEl("p", { diff --git a/packages/plugin/src/styles/settings/overview.css b/packages/plugin/src/features/settings/overview.css similarity index 89% rename from packages/plugin/src/styles/settings/overview.css rename to packages/plugin/src/features/settings/overview.css index 0876c726..407db5f3 100644 --- a/packages/plugin/src/styles/settings/overview.css +++ b/packages/plugin/src/features/settings/overview.css @@ -94,7 +94,7 @@ overflow-wrap: anywhere; } -.mdsync-overview-card button { +.mdsync-overview-card > button { align-self: flex-start; margin-top: var(--size-2-2); } @@ -146,7 +146,7 @@ } /* Logs shows a value only for errors: the red pill says it, Obsidian's warning sign would say it twice. */ -.mdsync-settings-sections .setting-item:nth-child(5) .setting-item-value { +.mdsync-settings-sections .setting-item:nth-child(6) .setting-item-value { background: rgba(var(--color-red-rgb), 0.15); color: var(--text-error); } @@ -166,16 +166,32 @@ } .mdsync-settings-sections .setting-item:nth-child(3) { + /* History */ + --mdsync-section-icon: url("data:image/svg+xml,"); +} + +.mdsync-settings-sections .setting-item:nth-child(4) { /* Interface */ --mdsync-section-icon: url("data:image/svg+xml,"); } -.mdsync-settings-sections .setting-item:nth-child(4) { +.mdsync-settings-sections .setting-item:nth-child(5) { /* Maintenance */ --mdsync-section-icon: url("data:image/svg+xml,"); } -.mdsync-settings-sections .setting-item:nth-child(5) { +.mdsync-settings-sections .setting-item:nth-child(6) { /* Logs */ --mdsync-section-icon: url("data:image/svg+xml,"); } + +.mdsync-overview-activity { + margin-top: var(--size-4-3); +} + +.mdsync-overview-activity-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: var(--size-4-3); +} diff --git a/packages/plugin/src/settings/overview.ts b/packages/plugin/src/features/settings/overview.ts similarity index 86% rename from packages/plugin/src/settings/overview.ts rename to packages/plugin/src/features/settings/overview.ts index 0b40db14..fb215d5c 100644 --- a/packages/plugin/src/settings/overview.ts +++ b/packages/plugin/src/features/settings/overview.ts @@ -3,22 +3,20 @@ import { type SettingDefinitionGroup, setIcon, } from "obsidian"; - -import type { RelayStatus } from "@/hub/status"; -import type { PluginHost } from "@/plugin/host"; -import { formatRelativeTime, pluralize } from "@/shared"; -import { describeStorageTarget, storageIdentity } from "@/storage"; -import { VAULT_SPACE } from "@/sync/space"; -import { RELAY_TEXT } from "@/ui/common"; - -import type { FieldContext } from "./fields"; +import type { RelayStatus } from "@/core/hub"; +import { RELAY_TEXT } from "@/core/hub"; +import type { FieldContext } from "@/core/settings"; +import { isRelayConfigured } from "@/core/settings"; +import { formatRelativeTime, pluralize } from "@/core/shared"; import { activeStorage, - canSync, - isGuest, - isRelayConfigured, + describeStorageTarget, isStorageConfigured, -} from "./model"; + storageIdentity, +} from "@/features/storage"; +import { canSync, isGuest, VAULT_SPACE } from "@/features/sync"; +import { renderActivityCard } from "./activity-card"; +import type { SettingsTabHost } from "./host"; type Tone = "ok" | "muted" | "warning" | "error"; @@ -43,7 +41,9 @@ const RELAY_STATE: Record = { }; /** The root page's head: the setup wizard and where storage, encryption and the relay stand, live. */ -export function overviewGroup(ctx: FieldContext): SettingDefinitionGroup { +export function overviewGroup( + ctx: FieldContext, +): SettingDefinitionGroup { const { plugin } = ctx; return { type: "group", @@ -69,6 +69,7 @@ export function overviewGroup(ctx: FieldContext): SettingDefinitionGroup { renderCard(grid, relayCard(plugin)); }; draw(); + renderActivityCard(root, plugin); const { hub, people } = plugin.realtime; const stops = [ plugin.controller.subscribe(draw), @@ -103,7 +104,7 @@ function renderCard(grid: HTMLElement, card: Card): void { } } -function storageCard(plugin: PluginHost): Card { +function storageCard(plugin: SettingsTabHost): Card { const { settings } = plugin; const base = { icon: "hard-drive", title: "Storage" }; if (!isStorageConfigured(settings)) { @@ -143,7 +144,7 @@ function storageCard(plugin: PluginHost): Card { }; } -function encryptionCard(plugin: PluginHost, redraw: () => void): Card { +function encryptionCard(plugin: SettingsTabHost, redraw: () => void): Card { const { settings, passphrase } = plugin; const base = { icon: "lock", title: "Encryption" }; if (!isStorageConfigured(settings)) { @@ -178,7 +179,7 @@ function encryptionCard(plugin: PluginHost, redraw: () => void): Card { }; } -function relayCard(plugin: PluginHost): Card { +function relayCard(plugin: SettingsTabHost): Card { const base = { icon: "radio-tower", title: "Relay" }; if (!isRelayConfigured(plugin.settings)) { return { @@ -213,7 +214,7 @@ function relayCard(plugin: PluginHost): Card { function devicesText({ locked, devices, -}: ReturnType): string { +}: ReturnType): string { if (locked) return "Sync once to see your other devices."; if (devices.length === 0) return "No other device online."; return `${pluralize(devices.length, "other device")} online.`; diff --git a/packages/plugin/src/settings/sections/advanced.ts b/packages/plugin/src/features/settings/sections/advanced.ts similarity index 69% rename from packages/plugin/src/settings/sections/advanced.ts rename to packages/plugin/src/features/settings/sections/advanced.ts index 95c02c6a..e98168df 100644 --- a/packages/plugin/src/settings/sections/advanced.ts +++ b/packages/plugin/src/features/settings/sections/advanced.ts @@ -1,11 +1,11 @@ import type { SettingDefinitionGroup } from "obsidian"; - -import { type FieldContext, group, onSettled } from "@/settings/fields"; -import { defaultDeviceName } from "@/sync/device"; +import { type FieldContext, group, onSettled } from "@/core/settings"; +import { defaultDeviceName } from "@/features/sync"; +import type { SettingsTabHost } from "../host"; export function advancedSection({ plugin, -}: FieldContext): SettingDefinitionGroup { +}: FieldContext): SettingDefinitionGroup { return group("Advanced", [ { name: "Device name", diff --git a/packages/plugin/src/settings/sections/interface.ts b/packages/plugin/src/features/settings/sections/interface.ts similarity index 58% rename from packages/plugin/src/settings/sections/interface.ts rename to packages/plugin/src/features/settings/sections/interface.ts index 64e2680c..fcee9c7c 100644 --- a/packages/plugin/src/settings/sections/interface.ts +++ b/packages/plugin/src/features/settings/sections/interface.ts @@ -1,34 +1,33 @@ -import type { SettingDefinitionGroup } from "obsidian"; - +import { Platform, type SettingDefinitionGroup } from "obsidian"; import { + bind, + EFieldKind, type FieldContext, fieldRow, group, type SettingsField, -} from "@/settings/fields"; -import { EFieldKind } from "@/storage"; +} from "@/core/settings"; +import type { SettingsTabHost } from "../host"; -const INTERFACE_FIELDS: ReadonlyArray = [ - { - kind: EFieldKind.Toggle, - name: "Status bar indicator", - desc: "Applies after Obsidian restarts.", - get: (s) => s.showStatusBar, - set: (v) => ({ showStatusBar: v }), - }, +const STATUS_BAR_FIELD: SettingsField = { + kind: EFieldKind.Toggle, + name: "Status bar indicator", + desc: "Applies after Obsidian restarts.", + ...bind("showStatusBar"), +}; + +const INTERFACE_FIELDS: ReadonlyArray> = [ { kind: EFieldKind.Toggle, name: "Ribbon icon", desc: "Applies after Obsidian restarts.", - get: (s) => s.showRibbonIcon, - set: (v) => ({ showRibbonIcon: v }), + ...bind("showRibbonIcon"), }, { kind: EFieldKind.Toggle, name: "File and folder indicators", desc: "Show change marks, linked and ignored paths, who is in a note and new-note dots in the file tree, and a linked or ignored label for the open note. Share badges always stay: they open the share window.", - get: (s) => s.showFileExplorerIndicators, - set: (v) => ({ showFileExplorerIndicators: v }), + ...bind("showFileExplorerIndicators"), after: (plugin) => plugin.refreshFileIndicators(plugin.settings.showFileExplorerIndicators), rerender: true, @@ -39,8 +38,7 @@ const INTERFACE_FIELDS: ReadonlyArray = [ desc: "A dot, arrow or warning sign beside a changed file. Its name keeps its colour either way.", when: (s) => s.showFileExplorerIndicators, sub: true, - get: (s) => s.showChangeMarks, - set: (v) => ({ showChangeMarks: v }), + ...bind("showChangeMarks"), after: (plugin) => plugin.refreshFileIndicators(plugin.settings.showFileExplorerIndicators), }, @@ -48,8 +46,7 @@ const INTERFACE_FIELDS: ReadonlyArray = [ kind: EFieldKind.Toggle, name: "Editor change signs", desc: "Show per-line gutter marks for changes since the last sync.", - get: (s) => s.showEditorChangeSigns, - set: (v) => ({ showEditorChangeSigns: v }), + ...bind("showEditorChangeSigns"), after: (plugin) => plugin.refreshEditorSigns(plugin.settings.showEditorChangeSigns), }, @@ -57,15 +54,20 @@ const INTERFACE_FIELDS: ReadonlyArray = [ kind: EFieldKind.Toggle, name: "File sizes in changes", desc: "Show current sizes and size changes in the Changes list.", - get: (s) => s.showFileSizes, - set: (v) => ({ showFileSizes: v }), + ...bind("showFileSizes"), after: (plugin) => plugin.refreshSourceControlView(), }, ]; -export function interfaceSection(ctx: FieldContext): SettingDefinitionGroup { +export function interfaceSection( + ctx: FieldContext, +): SettingDefinitionGroup { + // Obsidian mobile has no status bar. Left out, not hidden: a hidden first row leaves its separator on the next. + const fields = Platform.isMobile + ? INTERFACE_FIELDS + : [STATUS_BAR_FIELD, ...INTERFACE_FIELDS]; return group( undefined, - INTERFACE_FIELDS.map((field) => fieldRow(ctx, field)), + fields.map((field) => fieldRow(ctx, field)), ); } diff --git a/packages/plugin/src/features/settings/sections/realtime.ts b/packages/plugin/src/features/settings/sections/realtime.ts new file mode 100644 index 00000000..8d6a14a5 --- /dev/null +++ b/packages/plugin/src/features/settings/sections/realtime.ts @@ -0,0 +1,121 @@ +import type { Setting, SettingDefinitionGroup } from "obsidian"; +import { LIVE_SEND_MS } from "@/core/constants"; +import type { RelayStatus } from "@/core/hub"; +import { RELAY_TEXT } from "@/core/hub"; +import { + bind, + EFieldKind, + type FieldContext, + fieldRow, + group, + type SettingsField, + type SettingsHost, + SUB_SETTING_CLASS, +} from "@/core/settings"; +import type { People } from "@/features/presence"; +import { VAULT_SPACE } from "@/features/sync"; +import type { SettingsTabHost } from "../host"; + +const REALTIME_FIELD: SettingsField = { + kind: EFieldKind.Toggle, + name: "Real-time sync", + desc: "Other devices pull the moment you push, and you see who is in which note. Turning it off also stops live editing. Your devices use the relay server (Connection tab), shared folders their owner's.", + ...bind("realtimeSync"), + rerender: true, +}; + +const LIVE_EDITING_FIELD: SettingsField = { + kind: EFieldKind.Toggle, + name: "Live editing", + desc: "Notes open in the editor edit together, keystroke by keystroke, across your devices and with the people in shared folders, through the relay.", + when: (s) => s.realtimeSync, + sub: true, + ...bind("liveEditing"), + rerender: true, +}; + +const LIVE_SPEED_FIELD: SettingsField = { + kind: EFieldKind.Choice, + name: "Live editing speed", + desc: "How often your typing reaches others. Each send is a write on the relay, and Cloudflare's free plan allows 100,000 a day. Set per device.", + when: (s) => s.realtimeSync && s.liveEditing, + sub: true, + options: { + [LIVE_SEND_MS.instant]: "Instant", + [LIVE_SEND_MS.balanced]: "Balanced", + [LIVE_SEND_MS.economical]: "Economical: once a second", + }, + get: (s) => String(s.liveSendMs), + set: (v) => ({ liveSendMs: Number(v) }), +}; + +const SHOW_OPEN_NOTE_FIELD: SettingsField = { + kind: EFieldKind.Toggle, + name: "Show my open note to others", + desc: "Off, others see only that you are online. Live editing still shows you in a note you both have open.", + when: (s) => s.realtimeSync, + sub: true, + ...bind("showOpenNote"), +}; + +/** What the setup wizard's Features step shows under real-time sync, which its sync mode turns on. */ +export const SETUP_FIELDS: ReadonlyArray> = [ + LIVE_EDITING_FIELD, + SHOW_OPEN_NOTE_FIELD, +]; + +const REALTIME_FIELDS: ReadonlyArray> = [ + REALTIME_FIELD, + LIVE_EDITING_FIELD, + LIVE_SPEED_FIELD, + SHOW_OPEN_NOTE_FIELD, +]; + +export function realtimeSection( + ctx: FieldContext, +): SettingDefinitionGroup { + return group("Real time", [ + ...REALTIME_FIELDS.map((field) => fieldRow(ctx, field)), + { + name: "Connected devices", + visible: () => ctx.plugin.settings.realtimeSync, + render: (setting) => renderConnectedDevices(setting, ctx.plugin), + }, + ]); +} + +function renderConnectedDevices( + devicesSetting: Setting, + plugin: SettingsTabHost, +): () => void { + devicesSetting.settingEl.addClass(SUB_SETTING_CLASS); + const { hub, people } = plugin.realtime; + const render = (): void => { + devicesSetting.setDesc( + describeConnectedDevices( + plugin.realtime.hub.statusOf(VAULT_SPACE.id), + people.devices(), + ), + ); + }; + render(); + + const unsubscribeStatus = hub.listen({ onConnectionChange: render }); + const unsubscribeDevices = people.subscribe(render); + return () => { + unsubscribeStatus(); + unsubscribeDevices(); + }; +} + +function describeConnectedDevices( + status: RelayStatus, + { locked, devices }: ReturnType, +): string { + if (status !== "connected") return RELAY_TEXT[status]; + if (locked) return "Sync once to unlock the device list."; + if (devices.length === 0) { + return "No other devices connected."; + } + return devices.map((device) => device.name).join(", "); +} diff --git a/packages/plugin/src/features/settings/tab.ts b/packages/plugin/src/features/settings/tab.ts new file mode 100644 index 00000000..41160a13 --- /dev/null +++ b/packages/plugin/src/features/settings/tab.ts @@ -0,0 +1,136 @@ +import { + type App, + type Plugin, + PluginSettingTab, + type SettingDefinitionItem, +} from "obsidian"; +import { type FieldContext, settleTyping } from "@/core/settings"; +import { linksSection } from "@/features/links"; +import { relaySection } from "@/features/relay"; +import { sharesSection } from "@/features/spaces"; +import { + activeStorage, + backendSection, + storageIdentity, +} from "@/features/storage"; +import { + automationSection, + configurationScopeSection, + encryptionSection, + exclusionsSection, + historySection, + historyValue, + maintenanceSection, + type SnapshotListResult, +} from "@/features/sync"; +import { deviceTransferSection } from "@/features/transfer"; +import type { SettingsTabHost } from "./host"; +import { logsPage } from "./logs-view"; +import { overviewGroup } from "./overview"; +import { advancedSection } from "./sections/advanced"; +import { interfaceSection } from "./sections/interface"; +import { realtimeSection } from "./sections/realtime"; + +export class MdsyncSettingTab extends PluginSettingTab { + private readonly plugin: Plugin & SettingsTabHost; + /** One history read per visit and compare: a toggle that redraws the tab must not read it again. */ + private history: { + storage: string; + checked: number; + load: Promise; + } | null = null; + + constructor(app: App, plugin: Plugin & SettingsTabHost) { + super(app, plugin); + this.plugin = plugin; + } + + override hide(): void { + settleTyping(); + this.history = null; + super.hide(); + } + + private loadHistory(): Promise { + const storage = storageIdentity(activeStorage(this.plugin.settings)); + // A compare since the last read may have seen a push. + const checked = this.plugin.controller.getSnapshot().vaultCheck?.at ?? 0; + if (this.history?.storage !== storage || this.history.checked !== checked) { + const load = this.plugin.controller.history.listSnapshots(); + // A failed read is not kept: the next redraw tries again. + load.catch(() => { + if (this.history?.load === load) this.history = null; + }); + this.history = { storage, checked, load }; + } + return this.history.load; + } + + getSettingDefinitions(): SettingDefinitionItem[] { + const ctx: FieldContext = { + plugin: this.plugin, + rerender: () => this.update(), + }; + return [ + overviewGroup(ctx), + { + type: "group", + // The row order picks each page's icon in CSS. + cls: "mdsync-settings-sections", + items: [ + { + type: "page", + name: "Connection", + desc: "Storage, encryption, relay and device transfer.", + items: [ + backendSection(ctx), + encryptionSection(ctx), + relaySection(ctx), + deviceTransferSection(ctx), + advancedSection(ctx), + ], + }, + { + type: "page", + name: "Sync", + desc: "When to sync, real time, shared folders, share links, Obsidian configuration and exclusions.", + displayValue: () => { + const open = this.plugin.spaces + .list() + .filter((record) => !record.closed).length; + return open ? `${open} shared` : ""; + }, + items: [ + automationSection(ctx), + realtimeSection(ctx), + sharesSection(ctx), + linksSection(ctx), + configurationScopeSection(ctx), + exclusionsSection(ctx), + ], + }, + { + type: "page", + name: "History", + desc: "Past versions, how long they stay, and pushes per day.", + displayValue: () => historyValue(this.plugin), + items: [historySection(ctx, () => this.loadHistory())], + }, + { + type: "page", + name: "Interface", + desc: "Status bar, ribbon, file indicators and editor signs.", + items: [interfaceSection(ctx)], + }, + { + type: "page", + name: "Maintenance", + desc: "Local state, remote integrity and storage cleanup.", + items: [maintenanceSection(ctx)], + }, + logsPage(this.plugin), + ], + }, + ]; + } +} diff --git a/packages/plugin/src/styles/settings/tabs-and-logs.css b/packages/plugin/src/features/settings/tabs-and-logs.css similarity index 89% rename from packages/plugin/src/styles/settings/tabs-and-logs.css rename to packages/plugin/src/features/settings/tabs-and-logs.css index d7254632..b36fd5c2 100644 --- a/packages/plugin/src/styles/settings/tabs-and-logs.css +++ b/packages/plugin/src/features/settings/tabs-and-logs.css @@ -62,17 +62,18 @@ color: var(--text-error); } -.mdsync-settings .mdsync-ignore-patterns { +/* The control under its description, across the row: in settings and in the setup wizard. */ +.setting-item.mdsync-stacked-setting { flex-direction: column; align-items: stretch; gap: var(--size-4-2); } -.mdsync-ignore-patterns .setting-item-info { +.mdsync-stacked-setting .setting-item-info { margin-inline-end: 0; } -.mdsync-ignore-patterns .setting-item-control { +.mdsync-stacked-setting .setting-item-control { width: 100%; } diff --git a/packages/plugin/src/features/setup/README.md b/packages/plugin/src/features/setup/README.md new file mode 100644 index 00000000..7c2a215d --- /dev/null +++ b/packages/plugin/src/features/setup/README.md @@ -0,0 +1,59 @@ +# Setup wizard + +One modal stepper takes a fresh install to a syncing vault: storage (Cloudflare R2 from a token by default), passphrase, features (when to sync, history, what of Obsidian syncs), relay (deployed from the plugin) and first sync. It replaces "configure first" toasts with a way into the right step. Constraints: `.claude/rules/settings-setup.md`. + +## Entry points + +- `openSetupWizard(plugin, step, onClosed)` (`features/setup/wizard.ts`), reached through `plugin.openSetup(step?)` in `main.ts`; the callback refreshes the settings tab, the Changes tab and the status bar the wizard changed under. One wizard at a time: asking again moves the open one to `step`. `closeSetupWizard()` runs on unload. +- Without a step it opens where this device stands (`firstStep` in `features/setup/step-state.ts`): no storage -> Start; otherwise the first step of the `new` path not done; else Ready. Never stored: `isStepDone` reads the settings, so the wizard agrees with the settings tab. +- Callers: a fresh install (`main.ts`: `loadData()` returned null, settings saved first so closing it does not bring it back, then on layout ready); command `open-setup-wizard` ("Set up sync", `app/commands.ts`); the **Setup wizard** button of the settings overview (`features/settings/overview.ts`); the status menu; the notice **Set up** when a sync has no storage or the saved connection cannot be read; the relay section (`ESetupStep.Relay`); the link menu and `openShareLink` without a relay (`ESetupStep.Relay`); the Changes tab prompt (`features/source-control/setup-prompt.ts`, also `ESetupStep.Import`). + +## Paths and steps + +`features/setup/step-state.ts` holds `ESetupStep`, `ESetupPath` and `PATH_STEPS`. + +- Start (no stepper, `features/setup/steps/start-step.ts`): **Start syncing this vault** (path `new`), **Connect to a vault set up on another device** (path `join`, first and highlighted on a phone, which is rarely the first device), **Accept an invite to a shared folder** (hands off to `openInvite` of spaces, closes), **Not now**. +- `new`: Storage -> Passphrase -> Features -> Relay -> Ready. `join`: Import -> Features -> Relay -> Ready (the setup link usually brings the relay; a done step shows its summary and **Next**). +- Back walks the path; a step may undo inside itself first (`StepView.back`). **Skip** shows on the optional Relay step while it is not done. **Next** shows only once the step is done and `blocksNext()` is false; until then the step's own button moves on, so no bare disabled Next. + +| Step | File | What it does | +|---|---|---| +| Storage | `features/setup/steps/storage-step.ts` | **Cloudflare R2** (recommended) or **Other storage**. R2: token form, then `useR2` (`features/storage/cloudflare/r2-select.ts`): bucket `mdsync-vaults` via `ensureBucket`, S3 keys derived from the token (`r2Keys`), `prefix` = vault-name slug plus a hash so two vaults on one account stay apart, active kind S3, then `testConnection`. `R2NotEnabledError` shows **Open R2** and **Try again**. A refused token (`isRefusedToken`) is forgotten so the form returns, and the new token lands in the same prefix. Warns that deleting the token in Cloudflare stops sync. Other: `backendSection` as in settings; **Continue** runs `testConnection` and blocks on failure | +| Passphrase | `features/setup/steps/passphrase-step.ts` | `passphrase.unlock()` first: a saved one that opens the vault moves on by itself (`wizard.moveOn()`: to where the device stands when the wizard opened on this step, else the next one), unless the step was entered by Back after it was done, else `vaultHasKey()`: none -> new passphrase and confirm held to `weakPassphrase` ("nobody can reset it"); present -> "enter the passphrase from your other device". A wrong one (`PassphraseRotatedError`) is dropped and shown inline. Storage unreachable offers **Try again**, and **Update keys** (`openStorageRefusedModal`) when the storage refused R2 keys | +| Import | `features/setup/steps/import-step.ts` | setup link and passphrase, then `transfer.importWith(link, passphrase)`. No prompt modal and no typed `IMPORT`: the step says what it replaces (storage, what syncs, automation and history, the relay) and the button is the consent | +| Features | `features/setup/steps/features-step.ts` | always done: its values are the settings. **When to sync** presets (`ESyncMode` in `features/setup/feature-choices.ts`, read by `syncModeOf`, written by `syncModePatch`): Manual turns autosync, push after change and real-time sync off; Automatic turns the first two on with a 5 minute interval when it was 0; Instant adds real-time sync, which without a relay waits for the relay step (`useRelay`) and lapses, shown and on activation alike, once the settings turn Manual (`shownSyncMode`, `enablesRealtime`). The pick is kept on the wizard (`Wizard.syncMode`), one for every wizard of the launch since a deploy outlives its wizard: a relay connected or deployed after Manual or Automatic leaves real-time sync off (`enablesRealtime`); a mode never picked counts as Instant. Push after change alone reads as Automatic. **Keep history** and **Keep for**; core settings, hotkeys, themes and snippets, enabled plugins, and the Plugins level and **Per plugin** rows of the settings tab (`pluginLevelRows`, without **Clear on remote**); live editing and the open note (`SETUP_FIELDS` of `features/settings/sections/realtime.ts`) once real-time sync is on. On `join` it says the values came with the link and apply to this device only | +| Relay | `features/setup/steps/relay-step.ts`, `features/setup/steps/relay-deploy-view.ts` | see Relay below | +| Ready | `features/setup/steps/ready-step.ts` | with storage, the first sync (`features/setup/steps/first-sync.ts`): a compare (`controller.refresh()`) that moves nothing (one that ends with no result, as when the passphrase prompt was cancelled, says so and offers **Try again**, never "all set"), then counts to upload, to download and in conflict, **See the files** (Changes) and **Sync N files** = `controller.refreshAndAutoSync(true)`, the scheduled cycle: it merges notes whose changes do not overlap, and a conflict left holds the whole sync, as Push all and Pull all refuse to run past one. Conflicts with no `baselineHash` (both sides added the file, as on a second device's first sync) can never merge on their own: the step names them and offers only **Choose in Changes**. After a held sync it says what waits (**Waiting for your choice**). Below, the summary rows (storage, encryption, relay, when to sync, history). While something is left to move or choose the footer's **Done** is not the accent button (`quietFooter`). Nothing left to move -> the done guide (`features/setup/steps/done-tour.ts`): where the status bar (desktop), panel, file tree marks and editor margin are, the words push, pull, compare and conflict, **Show setup link** (`showSettingsTransferExport`) and, without a relay, **Add a relay** | + +## Modules + +- `features/setup/wizard.ts` - modal shell, `STEPS` table (label, icon, `create*Step`), stepper header, Back, Skip and Next footer. `Wizard` is what steps get: `redraw(fromTop?)` (`fromTop` when the content was replaced whole), `next`, `moveOn`, `choose(path)`, `close`, `isShowing(view)`, `isLive()`, `currentPath()`. +- `features/setup/feature-choices.ts` - the Features step's sync mode presets over the automation settings, pure. +- `features/setup/steps/first-sync.ts`, `features/setup/steps/done-tour.ts` - the Ready step's first sync preview and the guide it ends on. +- `features/setup/stepper.ts`, `features/setup/choice-card.ts`, `features/setup/form.ts` (`actionRow`, `busyButton`, `busyLine`), `features/setup/passphrase-meter.ts`, `features/setup/run-action.ts` (busy and error wrapper for every async button), `features/setup/styles/`. +- `features/setup/steps/cloudflare-token.ts` - the token form shared by the Storage and Relay steps: **Open Cloudflare** (`tokenTemplateUrl`, permissions preselected), paste, account picker when the token reaches several accounts, then `connectCloudflare`. +- Non-UI logic lives with its domain: Cloudflare login and R2 in `features/storage/cloudflare/`, deploy and update in `features/relay/deploy/` and `features/relay/update/`, `importWith` in `features/transfer/`, `unlock` and `vaultHasKey` in `PassphraseManager` (`features/sync/remote/passphrase-manager.ts`). + +## Relay step + +- Choices: **Deploy to my Cloudflare** (recommended), **I already have a relay** (URL and secret, **Connect** runs `testRelay`, settings saved only on success and only while that manual view is still showing), or **Skip**, which lists what stays off (instant sync, live editing, invites, share links). With a relay already set the step shows its version against the bundled one and **Update**. +- Deploy (`relayDeployView`): token form if none, then the account's workers and workers.dev subdomain (`accountRelays`). `planRelay` decides: this device's relay on the account that answers -> update in place with its secret; no relay and the default name free -> new relay with a random secret; otherwise ask. Asking offers **Update it** (type the existing relay's secret, checked with `testRelay` before deploying), **Use another token** when this device's relay is not on the account, and **Deploy new** with a name (first free `mdsync-relay-N` proposed, `relayNameError` validates). +- Progress is the `ERelayDeployStep` checklist (workers address, storage, share page files, relay code, public address) plus **Answering**, then `activateRelay` polls `/status` until `version === RELAY_VERSION`, about 3 minutes (`WAIT_MS`), then **Check again**. On success `relayUrl`, `relaySecret` are saved at upload and `realtimeSync` turns on once it answers (`useRelay`), unless Manual or Automatic was picked in Features. + +## Lifetime and races + +- The deploy outlives the wizard: `deploying` in `features/relay/deploy/deploy-flow.ts` is module-level. A wizard closed mid-deploy leaves it running; a reopened one shows "still deploying from earlier" and attaches (`runningRelayDeploy`) instead of starting a second. The URL and secret are saved the moment the worker holds the secret (`onUploaded`), so a closed wizard never loses a live relay's secret. +- A deploy that broke off is remembered with its secret (`failedRelay`); **Try again** repeats it with that secret. It is used only while no relay is configured, so a stale secret cannot replace a working relay. +- Late results move on only from the step still on screen (`wizard.isShowing(view)`); `isLive()` guards redraws after a close. An edited token or secret is compared with what was sent before the result is applied. +- The settings tab is its own document: a wizard left in another one is hidden or went away with it, so `openSetupWizard` closes it and opens anew. + +## Recovery + +- No storage when sync runs: notice **Set up** (`onNoStorage` from `app/bootstrap.ts`), never a modal from a background sync. +- Saved connection unreadable (vault copied, keychain reset): notice **Set up** on layout ready; the sealed envelope is kept untouched until storage is set up again (`app/settings/envelope.ts`). +- Storage refused the keys: Passphrase step **Update keys**, or the settings storage fields for other backends. R2 keys derive from the Cloudflare token, so a rolled token needs `rekeyR2`; the saved login is replaced when it was that token. +- Relay refused or lost: the Relay step, or **Settings → MDSync → Connection → Update relay**, which opens the wizard at Relay and updates in place. + +## Tests + +`packages/plugin/tests/features/setup/` (`step-state`, `stepper`, `run-action`, `passphrase-meter`, `steps/relay-step`), `packages/plugin/tests/features/storage/cloudflare/`, `packages/plugin/tests/features/relay/deploy/` (fake Cloudflare: existing relay, new name, R2 not enabled, version wait), `packages/plugin/tests/features/transfer/transfer-controller.test.ts`. Real processes: `pnpm e2e:setup` (`tests/e2e/setup.ts`). Real Cloudflare is checked by hand: R2 plus a deploy over an existing relay name. diff --git a/packages/plugin/src/settings/setup/choice-card.ts b/packages/plugin/src/features/setup/choice-card.ts similarity index 100% rename from packages/plugin/src/settings/setup/choice-card.ts rename to packages/plugin/src/features/setup/choice-card.ts diff --git a/packages/plugin/src/features/setup/feature-choices.ts b/packages/plugin/src/features/setup/feature-choices.ts new file mode 100644 index 00000000..d7da0e58 --- /dev/null +++ b/packages/plugin/src/features/setup/feature-choices.ts @@ -0,0 +1,77 @@ +import { isRelayConfigured, type MdsyncSettings } from "@/core/settings"; + +/** The Features step's presets over the automation settings; read from them, never stored. */ +export const ESyncMode = { + Manual: "manual", + Automatic: "automatic", + /** Automatic plus real-time sync, over a relay. */ + Instant: "instant", +} as const; +export type ESyncMode = (typeof ESyncMode)[keyof typeof ESyncMode]; + +/** What Automatic schedules when the interval was left at 0 (one sync after startup). */ +export const AUTOMATIC_INTERVAL_MINUTES = 5; + +export function syncModeOf(settings: MdsyncSettings): ESyncMode { + if (settings.realtimeSync && isRelayConfigured(settings)) { + return ESyncMode.Instant; + } + // Push after change uploads on its own, so it is not Manual. + return settings.autoSyncEnabled || settings.autoPushAfterChange + ? ESyncMode.Automatic + : ESyncMode.Manual; +} + +/** Instant without a relay is a wish over Automatic's settings; turning them Manual elsewhere drops it. */ +function standingPick( + picked: ESyncMode | null, + settings: MdsyncSettings, +): ESyncMode | null { + return picked === ESyncMode.Instant && + syncModeOf(settings) === ESyncMode.Manual + ? ESyncMode.Manual + : picked; +} + +export function shownSyncMode( + picked: ESyncMode | null, + settings: MdsyncSettings, +): ESyncMode { + return standingPick(picked, settings) === ESyncMode.Instant && + !isRelayConfigured(settings) + ? ESyncMode.Instant + : syncModeOf(settings); +} + +/** The relay step turns real-time sync on for a relay unless Manual or Automatic was picked on purpose. */ +export function enablesRealtime( + picked: ESyncMode | null, + settings: MdsyncSettings, +): boolean { + const standing = standingPick(picked, settings); + return standing === null || standing === ESyncMode.Instant; +} + +/** + * Real-time sync turns on only with a relay to carry it; without one the relay step turns it on + * once a relay answers (`useRelay`). + */ +export function syncModePatch( + settings: MdsyncSettings, + mode: ESyncMode, +): Partial { + if (mode === ESyncMode.Manual) { + return { + autoSyncEnabled: false, + autoPushAfterChange: false, + realtimeSync: false, + }; + } + return { + autoSyncEnabled: true, + autoPushAfterChange: true, + autoSyncIntervalMinutes: + settings.autoSyncIntervalMinutes || AUTOMATIC_INTERVAL_MINUTES, + realtimeSync: mode === ESyncMode.Instant && isRelayConfigured(settings), + }; +} diff --git a/packages/plugin/src/features/setup/form.ts b/packages/plugin/src/features/setup/form.ts new file mode 100644 index 00000000..47496a7f --- /dev/null +++ b/packages/plugin/src/features/setup/form.ts @@ -0,0 +1,37 @@ +import { Setting } from "obsidian"; + +import { alertLine } from "@/core/ui"; + +import type { ActionState } from "./run-action"; + +/** Buttons that belong to the fields above them: no separator, so they read as part of the form. */ +export function actionRow(parent: HTMLElement): Setting { + const row = new Setting(parent); + row.settingEl.addClass("mdsync-button-row"); + return row; +} + +/** The error of a `runAction` step and its accent button, disabled with `busyLabel` while it runs. */ +export function busyButton( + parent: HTMLElement, + state: ActionState, + label: string, + busyLabel: string, + act: () => Promise, +): void { + if (state.error) alertLine(parent).setText(state.error); + actionRow(parent).addButton((b) => + b + .setButtonText(state.busy ? busyLabel : label) + .setCta() + .setDisabled(state.busy) + .onClick(() => void act()), + ); +} + +/** A line for work that is still going. */ +export function busyLine(parent: HTMLElement, text: string): void { + const line = parent.createDiv({ cls: "mdsync-setup-busy" }); + line.createSpan({ cls: "mdsync-status-spinner" }); + line.createSpan({ text }); +} diff --git a/packages/plugin/src/features/setup/host.ts b/packages/plugin/src/features/setup/host.ts new file mode 100644 index 00000000..b97d9c8f --- /dev/null +++ b/packages/plugin/src/features/setup/host.ts @@ -0,0 +1,13 @@ +import type { LiveSessions } from "@/features/live"; +import type { RelayHost } from "@/features/relay"; +import type { SpacesHost } from "@/features/spaces"; +import type { PassphraseManager } from "@/features/sync"; +import type { SettingsTransferController } from "@/features/transfer"; + +/** What the setup wizard needs from the plugin. */ +export interface SetupHost extends SpacesHost, RelayHost { + readonly passphrase: PassphraseManager; + readonly transfer: SettingsTransferController; + readonly realtime: SpacesHost["realtime"] & + RelayHost["realtime"] & { readonly live: LiveSessions }; +} diff --git a/packages/plugin/src/features/setup/index.ts b/packages/plugin/src/features/setup/index.ts new file mode 100644 index 00000000..ddf4fbca --- /dev/null +++ b/packages/plugin/src/features/setup/index.ts @@ -0,0 +1,3 @@ +export type { SetupHost } from "./host"; +export { ESetupStep } from "./step-state"; +export { closeSetupWizard, openSetupWizard } from "./wizard"; diff --git a/packages/plugin/src/settings/setup/passphrase-meter.ts b/packages/plugin/src/features/setup/passphrase-meter.ts similarity index 96% rename from packages/plugin/src/settings/setup/passphrase-meter.ts rename to packages/plugin/src/features/setup/passphrase-meter.ts index 1fb61f24..a148ba99 100644 --- a/packages/plugin/src/settings/setup/passphrase-meter.ts +++ b/packages/plugin/src/features/setup/passphrase-meter.ts @@ -1,4 +1,4 @@ -import { MIN_PASSPHRASE_LENGTH } from "@/crypto/constants"; +import { MIN_PASSPHRASE_LENGTH } from "@/core/crypto"; export const METER_BARS = 4; diff --git a/packages/plugin/src/settings/setup/run-action.ts b/packages/plugin/src/features/setup/run-action.ts similarity index 92% rename from packages/plugin/src/settings/setup/run-action.ts rename to packages/plugin/src/features/setup/run-action.ts index 23cd93f1..7b4432fe 100644 --- a/packages/plugin/src/settings/setup/run-action.ts +++ b/packages/plugin/src/features/setup/run-action.ts @@ -1,4 +1,4 @@ -import { errorMessage } from "@/shared"; +import { errorMessage } from "@/core/shared"; import type { Wizard } from "./wizard"; diff --git a/packages/plugin/src/settings/setup/steps.ts b/packages/plugin/src/features/setup/step-state.ts similarity index 70% rename from packages/plugin/src/settings/setup/steps.ts rename to packages/plugin/src/features/setup/step-state.ts index 420cda37..7a738dc8 100644 --- a/packages/plugin/src/settings/setup/steps.ts +++ b/packages/plugin/src/features/setup/step-state.ts @@ -1,15 +1,15 @@ -import type { PluginHost } from "@/plugin/host"; -import { - canSync, - isRelayConfigured, - isStorageConfigured, -} from "@/settings/model"; +import { isRelayConfigured } from "@/core/settings"; +import { isStorageConfigured } from "@/features/storage"; +import { canSync } from "@/features/sync"; +import type { SetupHost } from "./host"; export const ESetupStep = { Start: "start", Storage: "storage", Passphrase: "passphrase", Import: "import", + /** Presets for what syncs and when; always done, its values are the settings. */ + Features: "features", Relay: "relay", Ready: "ready", } as const; @@ -27,14 +27,20 @@ export const PATH_STEPS: Record = { [ESetupPath.New]: [ ESetupStep.Storage, ESetupStep.Passphrase, + ESetupStep.Features, + ESetupStep.Relay, + ESetupStep.Ready, + ], + [ESetupPath.Join]: [ + ESetupStep.Import, + ESetupStep.Features, ESetupStep.Relay, ESetupStep.Ready, ], - [ESetupPath.Join]: [ESetupStep.Import, ESetupStep.Relay, ESetupStep.Ready], }; /** Computed, never stored, so the wizard always agrees with the settings. */ -export function isStepDone(plugin: PluginHost, step: ESetupStep): boolean { +export function isStepDone(plugin: SetupHost, step: ESetupStep): boolean { switch (step) { case ESetupStep.Storage: return isStorageConfigured(plugin.settings); @@ -50,7 +56,7 @@ export function isStepDone(plugin: PluginHost, step: ESetupStep): boolean { } /** Where the wizard opens: the first step this device still lacks. */ -export function firstStep(plugin: PluginHost): ESetupStep { +export function firstStep(plugin: SetupHost): ESetupStep { if (!isStorageConfigured(plugin.settings)) return ESetupStep.Start; return ( PATH_STEPS[ESetupPath.New].find((step) => !isStepDone(plugin, step)) ?? diff --git a/packages/plugin/src/settings/setup/stepper.ts b/packages/plugin/src/features/setup/stepper.ts similarity index 100% rename from packages/plugin/src/settings/setup/stepper.ts rename to packages/plugin/src/features/setup/stepper.ts diff --git a/packages/plugin/src/settings/setup/cloudflare-token.ts b/packages/plugin/src/features/setup/steps/cloudflare-token.ts similarity index 86% rename from packages/plugin/src/settings/setup/cloudflare-token.ts rename to packages/plugin/src/features/setup/steps/cloudflare-token.ts index d9476c3a..37c42071 100644 --- a/packages/plugin/src/settings/setup/cloudflare-token.ts +++ b/packages/plugin/src/features/setup/steps/cloudflare-token.ts @@ -1,12 +1,12 @@ import { Setting } from "obsidian"; -import { type CloudflareAccount, tokenTemplateUrl } from "@/cloudflare"; -import { accountsOf, connectCloudflare } from "@/settings/cloudflare-login"; -import { alertLine, focusKey, onEnter } from "@/ui/common"; +import { type CloudflareAccount, tokenTemplateUrl } from "@/core/cloudflare"; +import { focusKey, onEnter } from "@/core/ui"; +import { accountsOf, connectCloudflare } from "@/features/storage"; -import { actionRow } from "./form"; -import { type ActionState, runAction } from "./run-action"; -import type { Wizard } from "./wizard"; +import { busyButton } from "../form"; +import { type ActionState, runAction } from "../run-action"; +import type { Wizard } from "../wizard"; /** Fetched only when the person opens "Show me how"; disclosed in the README. */ const TOKEN_DEMO_URL = @@ -135,12 +135,5 @@ export function renderTokenForm( }); }); } - if (form.error) alertLine(el).setText(form.error); - actionRow(el).addButton((b) => - b - .setButtonText(form.busy ? "Connecting…" : "Connect") - .setCta() - .setDisabled(form.busy) - .onClick(() => void connect()), - ); + busyButton(el, form, "Connect", "Connecting…", connect); } diff --git a/packages/plugin/src/features/setup/steps/done-tour.ts b/packages/plugin/src/features/setup/steps/done-tour.ts new file mode 100644 index 00000000..3830b9b5 --- /dev/null +++ b/packages/plugin/src/features/setup/steps/done-tour.ts @@ -0,0 +1,127 @@ +import { Platform, Setting, setIcon } from "obsidian"; +import { isRelayConfigured } from "@/core/settings"; +import { showSettingsTransferExport } from "@/features/transfer"; +import { ESyncMode, syncModeOf } from "../feature-choices"; +import { actionRow } from "../form"; +import type { Wizard } from "../wizard"; + +const WORDS: ReadonlyArray<[string, string]> = [ + ["Push", "Send this device's changes to the storage."], + ["Pull", "Take what your other devices sent."], + ["Compare", "Check both sides without moving anything."], + [ + "Conflict", + "A file changed on two devices. Notes merge when the changes do not overlap; otherwise you choose.", + ], +]; + +/** Where things live once the vault syncs: the last thing the wizard shows. */ +export function renderDoneTour(el: HTMLElement, wizard: Wizard): void { + const { plugin } = wizard; + const { settings } = plugin; + const hero = el.createDiv({ cls: "mdsync-hero" }); + const icon = hero.createDiv({ cls: "mdsync-hero-icon is-success" }); + setIcon(icon, "party-popper"); + const text = hero.createDiv({ cls: "mdsync-hero-text" }); + text.createEl("h3", { text: "You're all set" }); + text.createEl("p", { + text: + syncModeOf(settings) === ESyncMode.Manual + ? "This vault is in sync. It syncs again when you push and pull, through your storage, encrypted on this device." + : "This vault is in sync and keeps itself in sync, through your storage, encrypted on this device.", + }); + + el.createEl("h4", { + cls: "mdsync-setup-heading", + text: "Where to find things", + }); + const list = el.createEl("ul", { cls: "mdsync-summary mdsync-tour" }); + // Obsidian's mobile app has no status bar. + if (!Platform.isMobile && settings.showStatusBar) { + place( + list, + "cloud-check", + "Status bar", + "Where sync stands, bottom right. Select it to compare, push or pull.", + ); + } + place( + list, + "refresh-cw", + "MDSync panel", + Platform.isMobile + ? "In the right sidebar: what changed, past versions, deleted files and every push." + : "What changed, past versions, deleted files and every push. The ribbon icon opens it.", + ); + if (settings.showFileExplorerIndicators) { + place( + list, + "folder-tree", + "File tree", + "A colour and a mark beside files changed since the last sync.", + ); + } + if (settings.showEditorChangeSigns) { + place( + list, + "align-left", + "Editor margin", + "A bar beside lines changed since the last sync. Select it to see the change, push it or undo it.", + ); + } + + el.createEl("h4", { + cls: "mdsync-setup-heading", + text: "Words you will see", + }); + const words = el.createEl("dl", { cls: "mdsync-tour-words" }); + for (const [term, meaning] of WORDS) { + words.createEl("dt", { text: term }); + words.createEl("dd", { text: meaning }); + } + + el.createEl("h4", { cls: "mdsync-setup-heading", text: "Next" }); + new Setting(el) + .setName("Set up another device") + .setDesc( + "A link and QR code that bring this setup to your phone or another computer.", + ) + .addButton((b) => + b.setButtonText("Show setup link").onClick(() => + showSettingsTransferExport(plugin.app, { + createPackage: (options) => plugin.transfer.createPackage(options), + }), + ), + ); + if (!isRelayConfigured(settings)) { + new Setting(el) + .setName("Live editing and sharing") + .setDesc( + "Add a relay when you want instant sync, live editing, shared folders or share links.", + ) + .addButton((b) => + b.setButtonText("Add a relay").onClick(() => plugin.openSetup("relay")), + ); + } + actionRow(el).addButton((b) => + b.setButtonText("Open MDSync panel").onClick(() => { + wizard.close(); + void plugin.openSourceControl(); + }), + ); +} + +function place( + list: HTMLElement, + icon: string, + name: string, + text: string, +): void { + const row = list.createEl("li", { + cls: "mdsync-summary-row mdsync-tour-row", + }); + setIcon(row.createSpan({ cls: "mdsync-summary-icon" }), icon); + const body = row.createDiv({ cls: "mdsync-summary-text" }); + body.createDiv({ cls: "mdsync-tour-name", text: name }); + body.createDiv({ cls: "mdsync-tour-text", text }); +} diff --git a/packages/plugin/src/features/setup/steps/features-step.ts b/packages/plugin/src/features/setup/steps/features-step.ts new file mode 100644 index 00000000..47d6d344 --- /dev/null +++ b/packages/plugin/src/features/setup/steps/features-step.ts @@ -0,0 +1,185 @@ +import { HISTORY_KEEP_TEXT } from "@/core/constants"; +import { + bind, + EFieldKind, + fieldRow, + type HistoryKeep, + isRelayConfigured, + type MdsyncSettings, + renderDefinitions, + type SettingsField, +} from "@/core/settings"; +import { pluralize } from "@/core/shared"; +import { callout, renderSegments } from "@/core/ui"; +import { SETUP_FIELDS } from "@/features/settings"; +import { categoryField, pluginLevelRows } from "@/features/sync"; +import { ESyncMode, shownSyncMode, syncModePatch } from "../feature-choices"; +import type { SetupHost } from "../host"; +import { ESetupPath } from "../step-state"; +import type { StepView, Wizard } from "../wizard"; + +const MODES = [ + { value: ESyncMode.Manual, text: "Manual" }, + { value: ESyncMode.Automatic, text: "Automatic" }, + { value: ESyncMode.Instant, text: "Instant" }, +]; + +const WITHOUT_RELAY = + "Live editing, shared folders and share links need a relay, a small server in your own Cloudflare account. The next step sets one up; you can skip it."; + +const HISTORY_FIELDS: ReadonlyArray> = [ + { + kind: EFieldKind.Toggle, + name: "Keep history", + desc: "Past versions of every file, deleted files and a timeline of each push, encrypted. Without it a file deleted on any device cannot be brought back.", + ...bind("fileHistoryEnabled"), + rerender: true, + }, + { + kind: EFieldKind.Choice, + name: "Keep for", + desc: "Your devices share one history, so the shortest choice among them applies.", + when: (s) => s.fileHistoryEnabled, + sub: true, + options: HISTORY_KEEP_TEXT, + get: (s) => s.fileHistoryKeep, + set: (v) => ({ fileHistoryKeep: v as HistoryKeep }), + }, +]; + +const CONFIG_FIELDS: ReadonlyArray> = [ + categoryField( + "coreSettings", + "Core settings", + "App, appearance, core plugins, bookmarks and templates.", + ), + categoryField("hotkeys", "Hotkeys", "Your keyboard shortcuts."), + { + kind: EFieldKind.Toggle, + name: "Themes and snippets", + desc: "Installed themes and CSS snippets.", + get: (s) => s.settingsSync.themes && s.settingsSync.snippets, + set: (v, plugin) => ({ + settingsSync: { + ...plugin.settings.settingsSync, + themes: v, + snippets: v, + }, + }), + refreshScope: true, + }, + categoryField( + "pluginList", + "Enabled plugins", + "Which community plugins are switched on. Without it a plugin whose code syncs arrives switched off.", + ), +]; + +export function createFeaturesStep(wizard: Wizard): StepView { + const { plugin } = wizard; + const ctx = { plugin, rerender: () => wizard.redraw() }; + + const shownMode = (): ESyncMode => + shownSyncMode(wizard.syncMode, plugin.settings); + + const save = async (patch: Partial): Promise => { + Object.assign(plugin.settings, patch); + await plugin.saveSettings(); + wizard.redraw(); + }; + + const heading = (el: HTMLElement, name: string): void => { + el.createEl("h4", { cls: "mdsync-setup-heading", text: name }); + }; + + const renderMode = (el: HTMLElement): void => { + heading(el, "When to sync"); + const box = el.createDiv({ cls: "mdsync-setup-choice" }); + renderSegments(box, "mdsync-sync-mode", MODES, shownMode, (mode) => { + wizard.syncMode = mode; + return save(syncModePatch(plugin.settings, mode)); + }); + box.createDiv({ + cls: "mdsync-setup-choice-desc", + text: modeText(plugin.settings, shownMode()), + }); + }; + + const renderConfig = (el: HTMLElement): void => { + heading(el, "Obsidian settings and plugins"); + el.createDiv({ + cls: "mdsync-setup-note", + text: "Chosen per device: a phone often keeps its own hotkeys and theme. Turning one off here deletes nothing.", + }); + renderDefinitions( + el, + CONFIG_FIELDS.map((field) => fieldRow(ctx, field)), + ); + renderDefinitions(el, pluginLevelRows(ctx)); + }; + + const renderTogether = (el: HTMLElement): void => { + heading(el, "Work with others"); + if (!isRelayConfigured(plugin.settings)) { + el.createDiv({ cls: "mdsync-setup-note", text: WITHOUT_RELAY }); + return; + } + if (!plugin.settings.realtimeSync) { + el.createDiv({ + cls: "mdsync-setup-note", + text: "Live editing and showing others which note you have open come with Instant.", + }); + return; + } + renderDefinitions( + el, + SETUP_FIELDS.map((field) => fieldRow(ctx, field)), + ); + }; + + const view: StepView = { + render(el) { + el.createEl("h3", { text: "Choose how MDSync works" }); + el.createEl("p", { + cls: "mdsync-setup-lead", + text: "Pick what you need now. You can change any of it later in Settings → MDSync.", + }); + if (wizard.currentPath() === ESetupPath.Join) { + callout( + el, + "info", + "These came with the setup link. Change anything for this device; your other device keeps its own.", + ); + } + renderMode(el); + heading(el, "History"); + renderDefinitions( + el, + HISTORY_FIELDS.map((field) => fieldRow(ctx, field)), + ); + renderConfig(el); + renderTogether(el); + }, + }; + return view; +} + +function modeText(settings: MdsyncSettings, mode: ESyncMode): string { + if (mode === ESyncMode.Manual) { + return "Nothing leaves this device until you push, and nothing arrives until you pull."; + } + const when = ["at startup"]; + if (settings.autoSyncIntervalMinutes > 0) { + when.push(`every ${pluralize(settings.autoSyncIntervalMinutes, "minute")}`); + } + if (settings.autoPushAfterChange) { + when.push("a few seconds after you stop typing"); + } + const last = when.pop(); + const automatic = `Syncs ${when.length > 0 ? `${when.join(", ")} and ${last}` : last}.`; + if (mode === ESyncMode.Automatic) return automatic; + const instant = `${automatic} Your other devices get each change the moment it is pushed.`; + return isRelayConfigured(settings) + ? instant + : `${instant} Needs a relay: the next step sets one up.`; +} diff --git a/packages/plugin/src/features/setup/steps/first-sync.ts b/packages/plugin/src/features/setup/steps/first-sync.ts new file mode 100644 index 00000000..1ddfc49d --- /dev/null +++ b/packages/plugin/src/features/setup/steps/first-sync.ts @@ -0,0 +1,240 @@ +import { setIcon } from "obsidian"; +import { pluralize } from "@/core/shared"; +import { alertLine, callout } from "@/core/ui"; +import type { Conflict, DiffResult, SyncStatusSnapshot } from "@/features/sync"; +import { actionRow, busyLine } from "../form"; +import type { Wizard } from "../wizard"; + +const EPhase = { + Idle: "idle", + Comparing: "comparing", + Compared: "compared", + Syncing: "syncing", + Synced: "synced", +} as const; +type EPhase = (typeof EPhase)[keyof typeof EPhase]; + +export interface FirstSync { + /** Compares once: moves nothing, so the step can show what a sync would do. */ + start(): void; + /** Compared or synced with nothing left to move. */ + done(): boolean; + /** Its own button leads: something is left to move or to choose. */ + leads(): boolean; + render(el: HTMLElement): void; +} + +export function createFirstSync(wizard: Wizard): FirstSync { + const { plugin } = wizard; + const { controller } = plugin; + let phase: EPhase = EPhase.Idle; + + const track = async (next: EPhase, run: () => Promise) => { + const unsubscribe = controller.subscribe(() => wizard.redraw()); + try { + await run(); + } finally { + unsubscribe(); + phase = next; + wizard.redraw(true); + } + }; + + const compare = (): void => { + phase = EPhase.Comparing; + wizard.redraw(); + void track(EPhase.Compared, () => controller.refresh()); + }; + + /** The scheduled sync's own cycle: merges what it can, pulls, pushes, and leaves the rest for Changes. */ + const sync = (): void => { + phase = EPhase.Syncing; + wizard.redraw(); + void track(EPhase.Synced, () => controller.refreshAndAutoSync(true)); + }; + + const openChanges = (): void => { + wizard.close(); + void plugin.openChanges(); + }; + + const renderFailed = (el: HTMLElement, snapshot: SyncStatusSnapshot) => { + if (snapshot.error) alertLine(el).setText(snapshot.error); + for (const { root, message } of snapshot.spaceErrors) { + alertLine(el).setText(`Error in "${root}": ${message}`); + } + // A cancelled passphrase prompt ends the compare with neither an error nor a result. + if (!snapshot.error && snapshot.spaceErrors.length === 0) { + alertLine(el).setText("The comparison did not finish."); + } + actionRow(el).addButton((b) => + b.setButtonText("Try again").onClick(compare), + ); + }; + + const renderPreview = (el: HTMLElement, snapshot: SyncStatusSnapshot) => { + const { pendingLocal, pendingRemote, conflicts } = snapshot; + const open = snapshot.result?.diff.conflicts ?? []; + const synced = phase === EPhase.Synced; + const held = + snapshot.result !== null && + syncHeld(snapshot.result.diff, (path) => controller.spaceFor(path).id); + el.createDiv({ + cls: "mdsync-setup-note", + text: !synced + ? "MDSync compared this vault with the storage. Nothing has moved yet." + : conflicts > 0 + ? "Files changed on both sides hold the sync until you choose." + : "What is left waits for you in Changes.", + }); + const counts = el.createEl("ul", { cls: "mdsync-sync-counts" }); + count(counts, "arrow-up", pendingLocal, "to upload", "changed only here"); + count( + counts, + "arrow-down", + pendingRemote, + "to download", + "from your other devices", + ); + count( + counts, + "triangle-alert", + conflicts, + conflicts === 1 ? "conflict" : "conflicts", + "changed on both sides", + ).toggleClass("is-conflict", conflicts > 0); + if (open.length > 0) { + callout(el, "warning", conflictText(open, synced || held)); + } + const actions = actionRow(el); + if (synced || held) { + actions.addButton((b) => + b + .setButtonText(conflicts > 0 ? "Choose in Changes" : "Open changes") + .setCta() + .onClick(openChanges), + ); + return; + } + actions.addButton((b) => + b.setButtonText("See the files").onClick(openChanges), + ); + const files = pendingLocal + pendingRemote + conflicts; + actions.addButton((b) => + b + .setButtonText(`Sync ${pluralize(files, "file")}`) + .setCta() + .onClick(sync), + ); + }; + + return { + start() { + if (phase !== EPhase.Idle) return; + // Called while the step renders: the busy line is drawn by that render, not a nested one. + phase = EPhase.Comparing; + void track(EPhase.Compared, () => controller.refresh()); + }, + done() { + if (phase !== EPhase.Compared && phase !== EPhase.Synced) return false; + const snapshot = controller.getSnapshot(); + return ( + !failed(snapshot) && + snapshot.pendingLocal + snapshot.pendingRemote + snapshot.conflicts === + 0 + ); + }, + leads() { + return phase !== EPhase.Idle && !this.done(); + }, + render(el) { + const snapshot = controller.getSnapshot(); + el.createEl("h3", { text: headingOf(phase, snapshot) }); + if (phase === EPhase.Idle || phase === EPhase.Comparing) { + busyLine(el, "Comparing this vault with the storage…"); + return; + } + if (phase === EPhase.Syncing) { + busyLine(el, snapshot.progressText ?? "Syncing…"); + return; + } + if (failed(snapshot)) { + renderFailed(el, snapshot); + return; + } + renderPreview(el, snapshot); + }, + }; +} + +/** + * Nothing a sync would move: a conflict holds its own space only (`sync/runtime/auto-cycle.ts`), and one + * without a common version never merges, so every pending file sits in a space held that way. + */ +export function syncHeld( + diff: DiffResult, + spaceOf: (path: string) => string, +): boolean { + const held = new Set(); + for (const { path, baselineHash } of diff.conflicts) { + if (baselineHash !== null) return false; + held.add(spaceOf(path)); + } + return ( + held.size > 0 && + [...diff.localChanges, ...diff.remoteChanges].every(({ path }) => + held.has(spaceOf(path)), + ) + ); +} + +/** No result without an error means the compare never ran, as when the passphrase prompt was cancelled. */ +function failed(snapshot: SyncStatusSnapshot): boolean { + return ( + Boolean(snapshot.error) || + snapshot.spaceErrors.length > 0 || + snapshot.result === null + ); +} + +function count( + list: HTMLElement, + icon: string, + value: number, + label: string, + hint: string, +): HTMLElement { + const item = list.createEl("li", { cls: "mdsync-sync-count" }); + item.toggleClass("is-zero", value === 0); + const head = item.createDiv({ cls: "mdsync-sync-count-value" }); + setIcon(head.createSpan({ cls: "mdsync-sync-count-icon" }), icon); + head.createSpan({ text: String(value) }); + item.createDiv({ cls: "mdsync-sync-count-label", text: label }); + item.createDiv({ cls: "mdsync-sync-count-hint", text: hint }); + return item; +} + +function headingOf(phase: EPhase, snapshot: SyncStatusSnapshot): string { + if (phase !== EPhase.Synced) return "First sync"; + return snapshot.conflicts > 0 + ? "Waiting for your choice" + : "Not everything synced"; +} + +/** `final`: nothing merges them on its own any more, so only a choice moves the sync on. */ +function conflictText(conflicts: readonly Conflict[], final: boolean): string { + const names = namesOf(conflicts); + const verb = conflicts.length === 1 ? "is" : "are"; + return final + ? `${names} ${verb} different here and in the storage. Choose which version to keep in Changes; nothing syncs until then.` + : `${names} changed here and in the storage. Notes whose changes do not overlap merge on their own; anything else holds the sync until you choose in Changes.`; +} + +/** Up to three paths, then how many more. */ +function namesOf(conflicts: readonly Conflict[]): string { + const shown = conflicts.slice(0, 3).map(({ path }) => path); + const rest = conflicts.length - shown.length; + if (rest > 0) return `${shown.join(", ")} and ${rest} more`; + if (shown.length === 1) return shown[0] ?? ""; + return `${shown.slice(0, -1).join(", ")} and ${shown.at(-1)}`; +} diff --git a/packages/plugin/src/settings/setup/import-step.ts b/packages/plugin/src/features/setup/steps/import-step.ts similarity index 76% rename from packages/plugin/src/settings/setup/import-step.ts rename to packages/plugin/src/features/setup/steps/import-step.ts index db46d411..3f725a2f 100644 --- a/packages/plugin/src/settings/setup/import-step.ts +++ b/packages/plugin/src/features/setup/steps/import-step.ts @@ -1,10 +1,9 @@ import { Setting } from "obsidian"; - -import { canSync } from "@/settings/model"; -import { alertLine, callout, focusKey, onEnter } from "@/ui/common"; -import { actionRow } from "./form"; -import { runAction } from "./run-action"; -import type { StepView, Wizard } from "./wizard"; +import { callout, focusKey, onEnter } from "@/core/ui"; +import { canSync } from "@/features/sync"; +import { busyButton } from "../form"; +import { runAction } from "../run-action"; +import type { StepView, Wizard } from "../wizard"; export function createImportStep(wizard: Wizard): StepView { const { plugin } = wizard; @@ -36,7 +35,7 @@ export function createImportStep(wizard: Wizard): StepView { callout( el, "warning", - "Importing replaces this device's storage and relay settings.", + "Importing replaces the settings the link carries: storage, what syncs, automation and history, and the relay.", ); } const linkRow = new Setting(el).setName("Setup link").addTextArea((t) => { @@ -63,14 +62,7 @@ export function createImportStep(wizard: Wizard): StepView { }); onEnter(t.inputEl, () => void submit()); }); - if (state.error) alertLine(el).setText(state.error); - actionRow(el).addButton((b) => - b - .setButtonText(state.busy ? "Importing…" : "Import") - .setCta() - .setDisabled(state.busy) - .onClick(() => void submit()), - ); + busyButton(el, state, "Import", "Importing…", submit); }, }; return view; diff --git a/packages/plugin/src/settings/setup/passphrase-step.ts b/packages/plugin/src/features/setup/steps/passphrase-step.ts similarity index 80% rename from packages/plugin/src/settings/setup/passphrase-step.ts rename to packages/plugin/src/features/setup/steps/passphrase-step.ts index 3d96417c..88aa8958 100644 --- a/packages/plugin/src/settings/setup/passphrase-step.ts +++ b/packages/plugin/src/features/setup/steps/passphrase-step.ts @@ -1,16 +1,18 @@ import { Setting } from "obsidian"; -import { weakPassphrase } from "@/crypto"; -import { r2StorageOf } from "@/settings/r2"; -import { errorMessage } from "@/shared"; -import { isRefusedCredentials } from "@/storage"; -import { PassphraseRotatedError } from "@/sync/keyfile"; -import { openStorageRefusedModal } from "@/ui"; -import { alertLine, callout, focusKey, onEnter } from "@/ui/common"; -import { actionRow, busyLine } from "./form"; -import { passphraseMeter } from "./passphrase-meter"; -import { runAction } from "./run-action"; -import type { StepView, Wizard } from "./wizard"; +import { weakPassphrase } from "@/core/crypto"; +import { errorMessage } from "@/core/shared"; +import { alertLine, callout, focusKey, onEnter } from "@/core/ui"; +import { + isRefusedCredentials, + openStorageRefusedModal, + r2StorageOf, +} from "@/features/storage"; +import { PassphraseRotatedError } from "@/features/sync"; +import { actionRow, busyButton, busyLine } from "../form"; +import { passphraseMeter } from "../passphrase-meter"; +import { runAction } from "../run-action"; +import type { StepView, Wizard } from "../wizard"; type Phase = "checking" | "new" | "existing" | "unlocked" | "unreachable"; @@ -24,6 +26,8 @@ export function createPassphraseStep(wizard: Wizard): StepView { /** Unreachable because the storage turned the keys away, not the network. */ let refused = false; const state = { busy: false, error: "" }; + /** Entered by Back after it was done: it stays to be looked at. */ + const wasUnlocked = passphrase.isUnlocked(); /** A passphrase entered or saved earlier is tried first, so a set-up device just moves on. */ const check = async (): Promise => { @@ -31,8 +35,13 @@ export function createPassphraseStep(wizard: Wizard): StepView { state.error = ""; wizard.redraw(); try { - if (await passphrase.unlock()) phase = "unlocked"; - else phase = (await passphrase.vaultHasKey()) ? "existing" : "new"; + if (await passphrase.unlock()) { + phase = "unlocked"; + if (!wasUnlocked && wizard.isShowing(view)) { + wizard.moveOn(); + return; + } + } else phase = (await passphrase.vaultHasKey()) ? "existing" : "new"; } catch (err) { if (err instanceof PassphraseRotatedError) { phase = "existing"; @@ -151,19 +160,12 @@ export function createPassphraseStep(wizard: Wizard): StepView { value = v; }); } - if (state.error) alertLine(el).setText(state.error); - actionRow(el).addButton((b) => - b - .setButtonText( - state.busy - ? "Checking…" - : phase === "new" - ? "Set passphrase" - : "Unlock", - ) - .setCta() - .setDisabled(state.busy) - .onClick(() => void submit()), + busyButton( + el, + state, + phase === "new" ? "Set passphrase" : "Unlock", + "Checking…", + submit, ); }, }; diff --git a/packages/plugin/src/features/setup/steps/ready-step.ts b/packages/plugin/src/features/setup/steps/ready-step.ts new file mode 100644 index 00000000..0f91970a --- /dev/null +++ b/packages/plugin/src/features/setup/steps/ready-step.ts @@ -0,0 +1,115 @@ +import { setIcon } from "obsidian"; +import { HISTORY_KEEP_TEXT } from "@/core/constants"; +import { isRelayConfigured } from "@/core/settings"; +import { + activeStorage, + describeStorageTarget, + isStorageConfigured, +} from "@/features/storage"; +import { canSync } from "@/features/sync"; +import { ESyncMode, syncModeOf } from "../feature-choices"; +import type { StepView, Wizard } from "../wizard"; +import { renderDoneTour } from "./done-tour"; +import { createFirstSync } from "./first-sync"; + +const MODE_TEXT: Record = { + [ESyncMode.Manual]: "Manual: when you push and pull", + [ESyncMode.Automatic]: "Automatic", + [ESyncMode.Instant]: "Instant, over the relay", +}; + +function summaryRow( + list: HTMLElement, + icon: string, + label: string, + value: string, + on: boolean, +): void { + const row = list.createEl("li", { cls: "mdsync-summary-row" }); + row.toggleClass("is-off", !on); + setIcon(row.createSpan({ cls: "mdsync-summary-icon" }), icon); + const text = row.createDiv({ cls: "mdsync-summary-text" }); + text.createDiv({ cls: "mdsync-summary-label", text: label }); + text.createDiv({ cls: "mdsync-summary-value", text: value }); + setIcon( + row.createSpan({ cls: "mdsync-summary-state" }), + on ? "check" : "minus", + ); +} + +export function createReadyStep(wizard: Wizard): StepView { + const { plugin } = wizard; + const firstSync = createFirstSync(wizard); + + const renderSummary = (el: HTMLElement): void => { + const { settings } = plugin; + const list = el.createEl("ul", { cls: "mdsync-summary" }); + const storage = isStorageConfigured(settings); + summaryRow( + list, + "hard-drive", + "Storage", + storage ? describeStorageTarget(activeStorage(settings)) : "Not set up", + storage, + ); + summaryRow( + list, + "key-round", + "Encryption", + !plugin.passphrase.has() + ? "No passphrase yet" + : settings.cachePassphrase + ? "Passphrase saved on this device" + : "Passphrase unlocked for this session", + plugin.passphrase.has(), + ); + const relay = isRelayConfigured(settings); + summaryRow( + list, + "radio-tower", + "Relay", + relay ? settings.relayUrl : "Not set up (optional)", + relay, + ); + const mode = syncModeOf(settings); + summaryRow(list, "refresh-cw", "When to sync", MODE_TEXT[mode], true); + summaryRow( + list, + "history", + "History", + !settings.fileHistoryEnabled + ? "Off" + : settings.fileHistoryKeep === "forever" + ? "Kept forever" + : `Kept for ${HISTORY_KEEP_TEXT[settings.fileHistoryKeep]}`, + settings.fileHistoryEnabled, + ); + }; + + const view: StepView = { + render(el) { + if (!canSync(plugin.settings)) { + const hero = el.createDiv({ cls: "mdsync-hero" }); + setIcon(hero.createDiv({ cls: "mdsync-hero-icon" }), "sparkles"); + const text = hero.createDiv({ cls: "mdsync-hero-text" }); + text.createEl("h3", { text: "Almost there" }); + text.createEl("p", { text: "Set up a storage to start syncing." }); + renderSummary(el); + return; + } + firstSync.start(); + if (firstSync.done()) { + renderDoneTour(el, wizard); + return; + } + firstSync.render(el); + el.createEl("h4", { + cls: "mdsync-setup-heading", + text: "On this device", + }); + renderSummary(el); + }, + quietFooter: () => canSync(plugin.settings) && firstSync.leads(), + }; + return view; +} diff --git a/packages/plugin/src/settings/setup/relay-deploy-view.ts b/packages/plugin/src/features/setup/steps/relay-deploy-view.ts similarity index 94% rename from packages/plugin/src/settings/setup/relay-deploy-view.ts rename to packages/plugin/src/features/setup/steps/relay-deploy-view.ts index 5b9999eb..f05bd9d1 100644 --- a/packages/plugin/src/settings/setup/relay-deploy-view.ts +++ b/packages/plugin/src/features/setup/steps/relay-deploy-view.ts @@ -1,34 +1,32 @@ import { Setting, setIcon } from "obsidian"; - +import { randomSecret } from "@/core/crypto"; +import { isRelayConfigured } from "@/core/settings"; +import { alertLine, callout, focusKey, serial } from "@/core/ui"; import { type AccountRelays, accountRelays, + activateRelay, + deployOwnRelay, ERelayDeployStep, + failedRelay, freeRelayName, + planRelay, RELAY_NAME, type RelayTarget, relayNameError, relayUrlOf, -} from "@/cloudflare"; -import { randomSecret } from "@/crypto"; + runningRelayDeploy, + testRelay, +} from "@/features/relay"; import { cloudflareErrorMessage, cloudflareOf, forgetCloudflare, -} from "@/settings/cloudflare-login"; -import { testRelay } from "@/settings/connection-test"; -import { isRelayConfigured } from "@/settings/model"; -import { alertLine, callout, focusKey, serial } from "@/ui/common"; +} from "@/features/storage"; +import { enablesRealtime } from "../feature-choices"; +import { actionRow, busyLine } from "../form"; +import type { Wizard } from "../wizard"; import { renderTokenForm, tokenForm } from "./cloudflare-token"; -import { actionRow, busyLine } from "./form"; -import { - activateRelay, - deployOwnRelay, - failedRelay, - planRelay, - runningRelayDeploy, -} from "./relay"; -import type { Wizard } from "./wizard"; type Phase = | "token" @@ -151,7 +149,8 @@ export function relayDeployView( const wait = async (): Promise => { phase = "waiting"; wizard.redraw(); - if (!(await activateRelay(plugin))) { + const realtime = () => enablesRealtime(wizard.syncMode, plugin.settings); + if (!(await activateRelay(plugin, realtime))) { phase = "silent"; wizard.redraw(); return; diff --git a/packages/plugin/src/settings/setup/relay-step.ts b/packages/plugin/src/features/setup/steps/relay-step.ts similarity index 85% rename from packages/plugin/src/settings/setup/relay-step.ts rename to packages/plugin/src/features/setup/steps/relay-step.ts index 1b7c5f43..af4dc5ce 100644 --- a/packages/plugin/src/settings/setup/relay-step.ts +++ b/packages/plugin/src/features/setup/steps/relay-step.ts @@ -1,16 +1,19 @@ import { Setting } from "obsidian"; - -import { relayBehind } from "@/cloudflare"; -import { type RelayTestResult, testRelay } from "@/settings/connection-test"; -import { isRelayConfigured } from "@/settings/model"; -import { relayBase } from "@/shared"; -import { alertLine, callout, focusKey, onEnter } from "@/ui/common"; -import { choiceCard } from "./choice-card"; -import { actionRow, busyLine } from "./form"; -import { useRelay } from "./relay"; +import { isRelayConfigured } from "@/core/settings"; +import { relayBase } from "@/core/shared"; +import { callout, focusKey, onEnter } from "@/core/ui"; +import { + type RelayTestResult, + relayBehind, + testRelay, + useRelay, +} from "@/features/relay"; +import { choiceCard } from "../choice-card"; +import { enablesRealtime } from "../feature-choices"; +import { busyButton, busyLine } from "../form"; +import { runAction } from "../run-action"; +import type { StepView, Wizard } from "../wizard"; import { relayDeployView } from "./relay-deploy-view"; -import { runAction } from "./run-action"; -import type { StepView, Wizard } from "./wizard"; type Mode = "choose" | "deploy" | "manual"; @@ -48,7 +51,7 @@ export function createRelayStep(wizard: Wizard): StepView { // A wizard closed meanwhile may be reopened with another relay typed in. if (mode !== "manual" || !wizard.isShowing(view)) return; Object.assign(plugin.settings, relay); - await useRelay(plugin); + await useRelay(plugin, enablesRealtime(wizard.syncMode, plugin.settings)); }); if (connected && mode === "manual") moveOn(); }; @@ -138,14 +141,7 @@ export function createRelayStep(wizard: Wizard): StepView { manual.secret = v.trim(); }); }); - if (manual.error) alertLine(el).setText(manual.error); - actionRow(el).addButton((b) => - b - .setButtonText(manual.busy ? "Connecting…" : "Connect") - .setCta() - .setDisabled(manual.busy) - .onClick(() => void connect()), - ); + busyButton(el, manual, "Connect", "Connecting…", connect); }; if (isRelayConfigured(plugin.settings)) void checkStatus(); diff --git a/packages/plugin/src/features/setup/steps/start-step.ts b/packages/plugin/src/features/setup/steps/start-step.ts new file mode 100644 index 00000000..0177777d --- /dev/null +++ b/packages/plugin/src/features/setup/steps/start-step.ts @@ -0,0 +1,53 @@ +import { Platform, setIcon } from "obsidian"; + +import { openInvite } from "@/features/spaces"; + +import { choiceCard } from "../choice-card"; +import { ESetupPath } from "../step-state"; +import type { StepView, Wizard } from "../wizard"; + +export function createStartStep(wizard: Wizard): StepView { + return { + render(el) { + const hero = el.createDiv({ cls: "mdsync-hero" }); + setIcon(hero.createDiv({ cls: "mdsync-hero-icon" }), "refresh-cw"); + const text = hero.createDiv({ cls: "mdsync-hero-text" }); + text.createEl("h3", { text: "Sync your vault, privately" }); + text.createEl("p", { + text: "MDSync keeps this vault in sync through storage you own. Everything is encrypted on this device with a passphrase only you know.", + }); + const choices = el.createDiv({ cls: "mdsync-choices" }); + // A phone is rarely the first device: joining leads there. + const joinFirst = Platform.isPhone; + const start = () => + choiceCard(choices, { + icon: "sparkles", + title: "Start syncing this vault", + desc: "The first device: choose a storage and set a passphrase.", + primary: !joinFirst, + onClick: () => wizard.choose(ESetupPath.New), + }); + const join = () => + choiceCard(choices, { + icon: "link", + title: "Connect to a vault set up on another device", + desc: "Use the setup link or QR code from that device.", + primary: joinFirst, + onClick: () => wizard.choose(ESetupPath.Join), + }); + if (joinFirst) { + join(); + start(); + } else { + start(); + join(); + } + choiceCard(choices, { + icon: "folder-input", + title: "Accept an invite to a shared folder", + desc: "Someone shared a folder with you. No storage of your own is needed.", + onClick: () => void openInvite(wizard.plugin, "", () => wizard.close()), + }); + }, + }; +} diff --git a/packages/plugin/src/settings/setup/storage-step.ts b/packages/plugin/src/features/setup/steps/storage-step.ts similarity index 81% rename from packages/plugin/src/settings/setup/storage-step.ts rename to packages/plugin/src/features/setup/steps/storage-step.ts index 113a7740..f700cea6 100644 --- a/packages/plugin/src/settings/setup/storage-step.ts +++ b/packages/plugin/src/features/setup/steps/storage-step.ts @@ -1,25 +1,24 @@ +import { isRefusedToken } from "@/core/cloudflare"; +import { renderDefinitions } from "@/core/settings"; +import { alertLine, callout } from "@/core/ui"; import { - isRefusedToken, - R2NotEnabledError, - r2DashboardUrl, -} from "@/cloudflare"; -import { + activeStorage, + backendSection, cloudflareErrorMessage, cloudflareOf, + describeStorageTarget, forgetCloudflare, -} from "@/settings/cloudflare-login"; -import { testConnection } from "@/settings/connection-test"; -import { renderDefinitions } from "@/settings/fields"; -import { activeStorage, isStorageConfigured } from "@/settings/model"; -import { useR2 } from "@/settings/r2"; -import { backendSection } from "@/settings/sections/backend"; -import { describeStorageTarget } from "@/storage"; -import { alertLine, callout } from "@/ui/common"; -import { choiceCard } from "./choice-card"; + isStorageConfigured, + R2NotEnabledError, + r2DashboardUrl, + testConnection, + useR2, +} from "@/features/storage"; +import { choiceCard } from "../choice-card"; +import { actionRow, busyButton } from "../form"; +import { runAction } from "../run-action"; +import type { StepView, Wizard } from "../wizard"; import { renderTokenForm, tokenForm } from "./cloudflare-token"; -import { actionRow } from "./form"; -import { runAction } from "./run-action"; -import type { StepView, Wizard } from "./wizard"; type Mode = "choose" | "r2" | "other"; @@ -133,13 +132,8 @@ export function createStorageStep(wizard: Wizard): StepView { renderDefinitions(el, [ backendSection({ plugin, rerender: () => wizard.redraw() }), ]); - if (state.error) alertLine(el).setText(state.error); - actionRow(el).addButton((b) => - b - .setButtonText(state.busy ? "Checking…" : "Continue") - .setCta() - .setDisabled(state.busy) - .onClick(() => void finish(async () => undefined)), + busyButton(el, state, "Continue", "Checking…", () => + finish(async () => undefined), ); }; diff --git a/packages/plugin/src/styles/settings/setup-cards.css b/packages/plugin/src/features/setup/styles/setup-cards.css similarity index 83% rename from packages/plugin/src/styles/settings/setup-cards.css rename to packages/plugin/src/features/setup/styles/setup-cards.css index b9bfdb09..7f175b9a 100644 --- a/packages/plugin/src/styles/settings/setup-cards.css +++ b/packages/plugin/src/features/setup/styles/setup-cards.css @@ -27,7 +27,7 @@ background: color-mix( in srgb, var(--text-success) 16%, - var(--background-primary) + var(--modal-background, var(--background-primary)) ); box-shadow: 0 6px 18px color-mix(in srgb, var(--text-success) 25%, transparent); @@ -62,10 +62,10 @@ box-sizing: border-box; width: 100%; height: auto; - padding: var(--size-4-3) var(--size-4-4); + padding: var(--size-4-3) var(--size-4-4) var(--size-4-3) var(--size-4-3); border: 1px solid var(--background-modifier-border); border-radius: var(--radius-m); - background: var(--background-primary); + background: var(--modal-background, var(--background-primary)); box-shadow: none; text-align: left; cursor: pointer; @@ -80,7 +80,7 @@ background: color-mix( in srgb, var(--interactive-accent) 6%, - var(--background-primary) + var(--modal-background, var(--background-primary)) ); box-shadow: none; } @@ -128,6 +128,8 @@ flex-direction: column; gap: 2px; min-width: 0; + /* A button keeps its text on one line; a long title runs off a phone's card. */ + white-space: normal; } .mdsync-choice-title { @@ -152,7 +154,6 @@ color: var(--text-muted); font-size: var(--font-ui-small); line-height: var(--line-height-tight); - white-space: normal; } .mdsync-choice-arrow { @@ -176,10 +177,16 @@ } } -.is-phone .mdsync-hero { - align-items: flex-start; +/* A sheet is narrow: the tile would only squeeze the text into more lines. */ +.is-phone .mdsync-hero-icon { + display: none; } .is-phone .mdsync-choice { min-height: var(--mdsync-touch); } + +/* Obsidian's mobile button padding outranks the card's: the tile would sit 20px from the edge and 4px from the top. */ +.is-mobile .mdsync-choices .mdsync-choice { + padding: var(--size-4-3) var(--size-4-4) var(--size-4-3) var(--size-4-3); +} diff --git a/packages/plugin/src/styles/settings/setup-forms.css b/packages/plugin/src/features/setup/styles/setup-forms.css similarity index 100% rename from packages/plugin/src/styles/settings/setup-forms.css rename to packages/plugin/src/features/setup/styles/setup-forms.css diff --git a/packages/plugin/src/styles/settings/setup-progress.css b/packages/plugin/src/features/setup/styles/setup-progress.css similarity index 58% rename from packages/plugin/src/styles/settings/setup-progress.css rename to packages/plugin/src/features/setup/styles/setup-progress.css index 39f814fd..a44b04d8 100644 --- a/packages/plugin/src/styles/settings/setup-progress.css +++ b/packages/plugin/src/features/setup/styles/setup-progress.css @@ -151,6 +151,12 @@ white-space: nowrap; } +/* A cut value says too little on a phone; it wraps instead. */ +.is-phone .mdsync-summary-value { + overflow-wrap: anywhere; + white-space: normal; +} + .mdsync-summary-state { display: grid; flex: none; @@ -166,3 +172,125 @@ .mdsync-summary-row.is-off .mdsync-summary-state { color: var(--text-faint); } + +/* First sync: what a sync would move, before it does. */ +.mdsync-sync-counts { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: var(--size-4-2); + margin: var(--size-4-3) 0; + padding: 0; + list-style: none; +} + +.mdsync-sync-count { + display: flex; + flex-direction: column; + gap: var(--size-2-1); + min-width: 0; + padding: var(--size-4-3); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); +} + +.mdsync-sync-count-value { + display: flex; + align-items: center; + gap: var(--size-4-2); + color: var(--text-normal); + font-size: var(--font-ui-large); + font-weight: var(--font-semibold); +} + +.mdsync-sync-count-icon { + display: grid; + color: var(--text-accent); +} + +.mdsync-sync-count.is-conflict .mdsync-sync-count-icon { + color: var(--text-warning); +} + +.mdsync-sync-count.is-zero + :is(.mdsync-sync-count-value, .mdsync-sync-count-icon) { + color: var(--text-faint); +} + +.mdsync-sync-count-label { + color: var(--text-normal); + font-size: var(--font-ui-small); +} + +.mdsync-sync-count-hint { + color: var(--text-muted); + font-size: var(--font-ui-smaller); + line-height: var(--line-height-tight); +} + +/* Three columns are too narrow on a phone: one bordered list, a count per row. */ +.is-phone .mdsync-sync-counts { + grid-template-columns: minmax(0, 1fr); + gap: 0; + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); +} + +.is-phone .mdsync-sync-count { + display: grid; + grid-template-areas: "value label" "value hint"; + grid-template-columns: 4em minmax(0, 1fr); + column-gap: var(--size-4-2); + align-items: center; + padding: var(--size-4-2) var(--size-4-3); + border: 0; + border-radius: 0; +} + +.is-phone .mdsync-sync-count + .mdsync-sync-count { + border-top: 1px solid var(--background-modifier-border); +} + +.is-phone .mdsync-sync-count-value { + grid-area: value; +} + +.is-phone .mdsync-sync-count-label { + grid-area: label; +} + +.is-phone .mdsync-sync-count-hint { + grid-area: hint; +} + +/* Done: where things live. */ +.mdsync-tour-row .mdsync-summary-icon { + background: color-mix(in srgb, var(--interactive-accent) 14%, transparent); + color: var(--text-accent); +} + +.mdsync-tour-name { + font-weight: var(--font-medium); +} + +.mdsync-tour-text { + color: var(--text-muted); + font-size: var(--font-ui-small); + line-height: var(--line-height-tight); +} + +.mdsync-tour-words { + display: grid; + grid-template-columns: max-content 1fr; + gap: var(--size-4-2) var(--size-4-4); + margin: 0; + font-size: var(--font-ui-small); +} + +.mdsync-tour-words dt { + font-weight: var(--font-medium); +} + +.mdsync-tour-words dd { + margin: 0; + color: var(--text-muted); +} diff --git a/packages/plugin/src/styles/settings/setup-stepper.css b/packages/plugin/src/features/setup/styles/setup-stepper.css similarity index 82% rename from packages/plugin/src/styles/settings/setup-stepper.css rename to packages/plugin/src/features/setup/styles/setup-stepper.css index 78a2841f..4342299e 100644 --- a/packages/plugin/src/styles/settings/setup-stepper.css +++ b/packages/plugin/src/features/setup/styles/setup-stepper.css @@ -12,13 +12,14 @@ display: none; } +/* Edge to edge: the first step is just its dot, each later one fills the space up to its own dot. */ .mdsync-step { position: relative; display: flex; flex: 1 1 0; flex-direction: column; min-width: 0; - align-items: center; + align-items: flex-end; gap: var(--size-4-2); color: var(--text-faint); font-size: var(--font-ui-smaller); @@ -27,13 +28,19 @@ animation-delay: calc(var(--mdsync-step-index, 0) * 70ms); } +.mdsync-step:first-child { + flex: none; + width: var(--mdsync-step-dot); + align-items: flex-start; +} + /* The line into a step: empty until the step is reached, then filled left to right. */ .mdsync-step + .mdsync-step::before { content: ""; position: absolute; top: calc(var(--mdsync-step-dot) / 2 - 1px); - right: calc(50% + var(--mdsync-step-dot) / 2 + var(--mdsync-step-gap)); - left: calc(-50% + var(--mdsync-step-dot) / 2 + var(--mdsync-step-gap)); + right: calc(var(--mdsync-step-dot) + var(--mdsync-step-gap)); + left: var(--mdsync-step-gap); height: 2px; border-radius: 1px; background-color: var(--background-modifier-border); @@ -50,6 +57,7 @@ background-size: 100% 100%; } +/* The sheet's own colour: a phone's dark theme paints --background-primary black under a grey sheet. */ .mdsync-step-dot { position: relative; z-index: 1; @@ -60,7 +68,7 @@ height: var(--mdsync-step-dot); border: 2px solid var(--background-modifier-border); border-radius: var(--mdsync-radius-pill); - background-color: var(--background-primary); + background-color: var(--modal-background, var(--background-primary)); color: var(--text-faint); transition: background-color 0.3s ease, @@ -90,11 +98,15 @@ } .mdsync-step-label { - max-width: 100%; - overflow-wrap: anywhere; + white-space: nowrap; transition: color 0.3s ease; } +/* Centred under its dot; the end labels line up with the edges instead. */ +.mdsync-step:not(:first-child, :last-child) .mdsync-step-label { + transform: translateX(calc(50% - var(--mdsync-step-dot) / 2)); +} + .mdsync-step.is-reached .mdsync-step-dot { border-color: var(--interactive-accent); color: var(--interactive-accent); diff --git a/packages/plugin/src/styles/settings/setup.css b/packages/plugin/src/features/setup/styles/setup.css similarity index 56% rename from packages/plugin/src/styles/settings/setup.css rename to packages/plugin/src/features/setup/styles/setup.css index ffcceaee..2da10dda 100644 --- a/packages/plugin/src/styles/settings/setup.css +++ b/packages/plugin/src/features/setup/styles/setup.css @@ -23,6 +23,23 @@ box-shadow: 0 var(--size-4-4) 0 var(--mdsync-footer-bg); } +/* + * A sheet ends at the screen's edge: the footer sits flush and clears the home indicator. + * On mobile the content scrolls, not the modal, so its padding is the strip to close. + */ +body.is-phone .modal.mdsync-setup, +body.is-phone .modal.mdsync-setup .modal-content { + padding-bottom: 0; +} + +body.is-phone .modal.mdsync-setup .setting-item.mdsync-setup-footer { + padding-bottom: max( + var(--size-4-3), + var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px)) + ); + box-shadow: none; +} + .mdsync-setup-footer .setting-item-info { display: none; } @@ -52,3 +69,34 @@ flex-basis: 100%; width: 100%; } + +.mdsync-setup-lead { + margin-top: 0; + color: var(--text-muted); +} + +.mdsync-setup-choice { + display: flex; + flex-direction: column; + gap: var(--size-4-2); + width: 100%; + padding-bottom: var(--size-4-2); + text-align: start; +} + +.mdsync-setup-choice-desc, +.mdsync-setup-note { + color: var(--text-muted); + font-size: var(--font-ui-small); + line-height: var(--line-height-tight); +} + +.mdsync-setup-note { + padding-bottom: var(--size-4-2); +} + +.mdsync-setup-heading { + margin: var(--size-4-6) 0 var(--size-4-2); + font-size: var(--font-ui-medium); + font-weight: var(--font-semibold); +} diff --git a/packages/plugin/src/settings/setup/wizard.ts b/packages/plugin/src/features/setup/wizard.ts similarity index 67% rename from packages/plugin/src/settings/setup/wizard.ts rename to packages/plugin/src/features/setup/wizard.ts index 083a99b3..724c8755 100644 --- a/packages/plugin/src/settings/setup/wizard.ts +++ b/packages/plugin/src/features/setup/wizard.ts @@ -1,13 +1,14 @@ import { Modal, Setting } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; -import { renderKeepingFocus } from "@/ui/common"; - -import { createImportStep } from "./import-step"; -import { createPassphraseStep } from "./passphrase-step"; -import { createReadyStep } from "./ready-step"; -import { createRelayStep } from "./relay-step"; -import { createStartStep } from "./start-step"; +import { asDrawer, renderKeepingFocus } from "@/core/ui"; +import type { ESyncMode } from "./feature-choices"; +import type { SetupHost } from "./host"; +import { + ESetupPath, + ESetupStep, + firstStep, + isStepDone, + PATH_STEPS, +} from "./step-state"; import { createStepper, EStepState, @@ -15,23 +16,29 @@ import { type StepperItem, stepStates, } from "./stepper"; -import { - ESetupPath, - ESetupStep, - firstStep, - isStepDone, - PATH_STEPS, -} from "./steps"; -import { createStorageStep } from "./storage-step"; +import { createFeaturesStep } from "./steps/features-step"; +import { createImportStep } from "./steps/import-step"; +import { createPassphraseStep } from "./steps/passphrase-step"; +import { createReadyStep } from "./steps/ready-step"; +import { createRelayStep } from "./steps/relay-step"; +import { createStartStep } from "./steps/start-step"; +import { createStorageStep } from "./steps/storage-step"; export interface Wizard { - readonly plugin: PluginHost; + readonly plugin: SetupHost; /** A late result moves on only from the step that is still on screen. */ isShowing(view: StepView): boolean; /** Not `isOpen`: Obsidian's Modal already has that as a boolean field. */ isLive(): boolean; - redraw(): void; + /** The preset picked on the Features step, null until then; one for every wizard of the launch. The Relay step reads it. */ + syncMode: ESyncMode | null; + /** Join shows what the setup link brought; New, what this device starts with. */ + currentPath(): ESetupPath | null; + /** `fromTop` when the step's content was replaced whole, not updated in place. */ + redraw(fromTop?: boolean): void; next(): void; + /** Leaves a step found done with nothing asked: where this device stands if the wizard opened on it, else the next. */ + moveOn(): void; choose(path: ESetupPath): void; close(): void; } @@ -41,6 +48,8 @@ export interface StepView { /** Goes back inside the step; false when it has nothing to undo. */ back?(): boolean; blocksNext?(): boolean; + /** The step's own button leads, so the footer's is not the accent one. */ + quietFooter?(): boolean; } interface StepSpec { @@ -71,6 +80,11 @@ const STEPS: Record = { icon: "link", create: createImportStep, }, + [ESetupStep.Features]: { + label: "Features", + icon: "sliders-horizontal", + create: createFeaturesStep, + }, [ESetupStep.Relay]: { label: "Relay", icon: "radio-tower", @@ -84,21 +98,34 @@ const STEPS: Record = { }, }; +/** Shared by every wizard of a launch: a relay deploy outlives its wizard and asks the latest pick when it answers. */ +let pickedSyncMode: ESyncMode | null = null; + class SetupWizardModal extends Modal implements Wizard { + get syncMode(): ESyncMode | null { + return pickedSyncMode; + } + set syncMode(mode: ESyncMode | null) { + pickedSyncMode = mode; + } private path: ESetupPath | null; private step: ESetupStep; private view: StepView; private opened = false; + /** The step chosen by where this device stands, until the person moves. */ + private landing: ESetupStep | null; private stepper: Stepper | null = null; private bodyEl: HTMLElement | null = null; constructor( - readonly plugin: PluginHost, + readonly plugin: SetupHost, step: ESetupStep, + landed: boolean, private readonly onClosed: () => void, ) { super(plugin.app); this.step = step; + this.landing = landed ? step : null; this.path = pathOf(step, null); this.view = STEPS[step].create(this); } @@ -107,6 +134,7 @@ class SetupWizardModal extends Modal implements Wizard { this.opened = true; this.titleEl.setText("Set up MDSync"); this.modalEl.addClass("mdsync-setup"); + asDrawer(this); this.stepper = createStepper(this.contentEl); this.bodyEl = this.contentEl.createDiv(); this.redraw(); @@ -129,11 +157,21 @@ class SetupWizardModal extends Modal implements Wizard { return this.opened; } - redraw(): void { + currentPath(): ESetupPath | null { + return this.path; + } + + redraw(fromTop = false): void { if (!this.opened || !this.stepper || !this.bodyEl) return; const body = this.bodyEl; this.stepper.update(this.stepperItems()); renderKeepingFocus(body, () => this.draw(body)); + if (fromTop) this.contentEl.scrollTop = 0; + } + + moveOn(): void { + if (this.landing === this.step) this.go(firstStep(this.plugin)); + else this.next(); } next(): void { @@ -149,11 +187,11 @@ class SetupWizardModal extends Modal implements Wizard { } go(step: ESetupStep): void { + this.landing = null; this.path = pathOf(step, this.path); this.step = step; this.view = STEPS[step].create(this); - this.contentEl.scrollTop = 0; - this.redraw(); + this.redraw(true); } private steps(): readonly ESetupStep[] { @@ -209,13 +247,12 @@ class SetupWizardModal extends Modal implements Wizard { b.setButtonText("Skip").onClick(() => this.next()), ); } - footer.addButton((b) => - b - .setButtonText(last ? "Done" : "Next") - .setCta() - .setDisabled(!done || this.view.blocksNext?.() === true) - .onClick(() => this.next()), - ); + // Until the step is done its own button moves on; a bare disabled Next would not say why. + if (!done || this.view.blocksNext?.() === true) return; + footer.addButton((b) => { + b.setButtonText(last ? "Done" : "Next").onClick(() => this.next()); + if (!this.view.quietFooter?.()) b.setCta(); + }); } } @@ -234,7 +271,7 @@ export function closeSetupWizard(): void { /** One wizard at a time: asking again moves the open one to `step`. */ export function openSetupWizard( - plugin: PluginHost, + plugin: SetupHost, step: ESetupStep | undefined, onClosed: () => void, ): void { @@ -245,6 +282,11 @@ export function openSetupWizard( return; } current?.close(); - current = new SetupWizardModal(plugin, step ?? firstStep(plugin), onClosed); + current = new SetupWizardModal( + plugin, + step ?? firstStep(plugin), + step === undefined, + onClosed, + ); current.open(); } diff --git a/packages/plugin/src/ui/source-control/actions.ts b/packages/plugin/src/features/source-control/actions/actions.ts similarity index 78% rename from packages/plugin/src/ui/source-control/actions.ts rename to packages/plugin/src/features/source-control/actions/actions.ts index 38f812ed..e63c9096 100644 --- a/packages/plugin/src/ui/source-control/actions.ts +++ b/packages/plugin/src/features/source-control/actions/actions.ts @@ -1,22 +1,25 @@ -import { Menu, Platform } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; -import { EConflictStrategy } from "@/sync/controller"; -import { EChangeType } from "@/sync/types"; -import { addIgnoreMenuItem } from "@/ui/actions/ignore-action"; +import { type App, Menu, Platform } from "obsidian"; import { attempt, + copyText, + notifyError, + notifyInfo, openInEditor, revealInFileExplorer, runWithNotice, -} from "@/ui/common"; -import { isIgnoreNote } from "@/vault/ignore"; +} from "@/core/ui"; import { + addIgnoreMenuItem, confirmAdoptNewVault, confirmBatchResolve, confirmRevert, -} from "./modals"; -import { ESection } from "./types"; + EChangeType, + EConflictStrategy, + heldByConflicts, + isIgnoreNote, +} from "@/features/sync"; +import type { SourceControlHost } from "../host"; +import { ESection } from "../types"; const BATCH_RESOLVE_CONFIRM_THRESHOLD = 5; @@ -32,14 +35,29 @@ function pathMenu(path: string): Menu { return menu; } +function addLocateItems(menu: Menu, app: App, path: string): void { + menu.addItem((item) => + item + .setTitle("Reveal in file explorer") + .setIcon("folder") + .onClick(() => void revealInFileExplorer(app, path)), + ); + menu.addItem((item) => + item + .setTitle("Copy path") + .setIcon("clipboard") + .onClick(() => void copyText("Path", path)), + ); +} + interface SourceControlActionDeps { - plugin: PluginHost; + plugin: SourceControlHost; showHistory: (path: string) => void; openDiff: (path: string) => Promise; } export class SourceControlActions { - private readonly plugin: PluginHost; + private readonly plugin: SourceControlHost; private readonly showHistory: (path: string) => void; private readonly openDiff: (path: string) => Promise; @@ -67,25 +85,7 @@ export class SourceControlActions { .setIcon("file-text") .onClick(() => void openInEditor(this.plugin.app, path)), ); - menu.addItem((item) => - item - .setTitle("Reveal in file explorer") - .setIcon("folder") - .onClick(() => void revealInFileExplorer(this.plugin.app, path)), - ); - menu.addItem((item) => - item - .setTitle("Copy path") - .setIcon("clipboard") - .onClick( - () => - void runWithNotice( - () => navigator.clipboard.writeText(path), - "Path copied.", - "Could not copy the path", - ), - ), - ); + addLocateItems(menu, this.plugin.app, path); if (this.plugin.settings.fileHistoryEnabled) { menu.addItem((item) => item @@ -127,25 +127,7 @@ export class SourceControlActions { showFolderContextMenu(event: MouseEvent, path: string): void { const menu = pathMenu(path); - menu.addItem((item) => - item - .setTitle("Reveal in file explorer") - .setIcon("folder") - .onClick(() => void revealInFileExplorer(this.plugin.app, path)), - ); - menu.addItem((item) => - item - .setTitle("Copy path") - .setIcon("clipboard") - .onClick( - () => - void runWithNotice( - () => navigator.clipboard.writeText(path), - "Path copied.", - "Could not copy the path", - ), - ), - ); + addLocateItems(menu, this.plugin.app, path); menu.addSeparator(); addIgnoreMenuItem(menu, this.plugin, path, true); menu.showAtMouseEvent(event); @@ -220,7 +202,7 @@ export class SourceControlActions { } async pushPaths(paths: string[]): Promise { - if (paths.length === 0) return false; + if (paths.length === 0 || (await this.held(paths))) return false; return runWithNotice( () => this.plugin.controller.pushPaths(paths), `Pushed ${paths.length} file(s).`, @@ -229,7 +211,7 @@ export class SourceControlActions { } async pullPaths(paths: string[]): Promise { - if (paths.length === 0) return false; + if (paths.length === 0 || (await this.held(paths))) return false; return runWithNotice( () => this.plugin.controller.pullPaths(paths), `Pulled ${paths.length} file(s).`, @@ -237,6 +219,22 @@ export class SourceControlActions { ); } + /** The engine refuses these while a conflict waits: say so, not "Push failed". */ + private async held(paths: ReadonlyArray): Promise { + const { controller } = this.plugin; + if (!heldByConflicts(controller, paths)) return false; + // The cached conflict may have been resolved elsewhere since; a fresh compare decides. + try { + await controller.refresh(); + } catch (err) { + notifyError("Could not compare", err); + return true; + } + const held = heldByConflicts(controller, paths); + if (held) notifyInfo(held); + return held !== null; + } + async adoptNewVault(): Promise { const ok = await confirmAdoptNewVault(this.plugin.app); if (!ok) return; diff --git a/packages/plugin/src/ui/source-control/section-actions.ts b/packages/plugin/src/features/source-control/actions/section-actions.ts similarity index 96% rename from packages/plugin/src/ui/source-control/section-actions.ts rename to packages/plugin/src/features/source-control/actions/section-actions.ts index bcfe8587..39c2135a 100644 --- a/packages/plugin/src/ui/source-control/section-actions.ts +++ b/packages/plugin/src/features/source-control/actions/section-actions.ts @@ -1,5 +1,5 @@ +import { ESection } from "../types"; import type { SourceControlActions } from "./actions"; -import { ESection } from "./types"; /** What a section's files can be sent to: one file from its row, many from the selection bar. */ export interface SectionAction { diff --git a/packages/plugin/src/ui/source-control/selection-bar.ts b/packages/plugin/src/features/source-control/actions/selection-bar.ts similarity index 94% rename from packages/plugin/src/ui/source-control/selection-bar.ts rename to packages/plugin/src/features/source-control/actions/selection-bar.ts index 91f0adaa..5f3d6569 100644 --- a/packages/plugin/src/ui/source-control/selection-bar.ts +++ b/packages/plugin/src/features/source-control/actions/selection-bar.ts @@ -1,5 +1,9 @@ -import { appendIconButton, focusKey, renderKeepingFocus } from "@/ui/common"; -import { textButton } from "./action-button"; +import { + appendIconButton, + focusKey, + renderKeepingFocus, + textButton, +} from "@/core/ui"; export interface SelectionCommand { text: string; diff --git a/packages/plugin/src/ui/source-control/change-rows.ts b/packages/plugin/src/features/source-control/changes/change-rows.ts similarity index 93% rename from packages/plugin/src/ui/source-control/change-rows.ts rename to packages/plugin/src/features/source-control/changes/change-rows.ts index 6a3c6688..4ee873cb 100644 --- a/packages/plugin/src/ui/source-control/change-rows.ts +++ b/packages/plugin/src/features/source-control/changes/change-rows.ts @@ -4,13 +4,13 @@ import { makeActivatable, onLongPress, renderPath, -} from "@/ui/common"; -import { textButton } from "./action-button"; -import type { SourceControlActions } from "./actions"; + textButton, +} from "@/core/ui"; +import type { SourceControlActions } from "../actions/actions"; +import { SECTION_ACTIONS } from "../actions/section-actions"; +import { renderSize } from "../row-parts"; +import { ESection, type FileRow, type VisualRow } from "../types"; import type { ConflictPreviewManager } from "./conflict-preview-manager"; -import { renderSize } from "./row-parts"; -import { SECTION_ACTIONS } from "./section-actions"; -import { ESection, type FileRow, type VisualRow } from "./types"; export type CheckState = "all" | "some" | "none"; @@ -194,7 +194,9 @@ export function renderConflictCard( const who = ctx.editor(row.path) ?? "remotely"; card.createDiv({ cls: "mdsync-conflict-note", - text: `Changed here and ${who} since the last sync.`, + text: row.hasBase + ? `Changed here and ${who} since the last sync.` + : `Added here and ${who}, with different contents.`, }); const choices = card.createDiv({ cls: "mdsync-conflict-choices" }); textButton(choices, "Keep local").onClick( @@ -203,7 +205,10 @@ export function renderConflictCard( textButton(choices, "Accept remote").onClick( () => void ctx.actions.resolveAcceptRemote(row.path), ); - textButton(choices, "Merge…").onClick(() => ctx.openMerge(row.path)); + // Without a base or as binary, the merge request opens the side-by-side diff with its choices. + textButton(choices, row.mergeable ? "Merge…" : "Compare…").onClick(() => + ctx.openMerge(row.path), + ); if (ctx.previews.isExpanded(row.path)) ctx.previews.render(card, row.path); return card; } diff --git a/packages/plugin/src/ui/source-control/changes-section.ts b/packages/plugin/src/features/source-control/changes/changes-section.ts similarity index 96% rename from packages/plugin/src/ui/source-control/changes-section.ts rename to packages/plugin/src/features/source-control/changes/changes-section.ts index 98ef59d8..c4365e1c 100644 --- a/packages/plugin/src/ui/source-control/changes-section.ts +++ b/packages/plugin/src/features/source-control/changes/changes-section.ts @@ -1,6 +1,14 @@ import { Menu, setIcon } from "obsidian"; -import { EConflictStrategy } from "@/sync/controller"; -import { appendIconButton, makeActivatable } from "@/ui/common"; +import { appendIconButton, makeActivatable } from "@/core/ui"; +import { EConflictStrategy } from "@/features/sync"; +import { SECTION_ACTIONS } from "../actions/section-actions"; +import type { + SelectionCommand, + SelectionSource, +} from "../actions/selection-bar"; +import { RowPager } from "../history/row-pager"; +import { ESection, type FileRow, type VisualRow } from "../types"; +import { mountVirtualList, type VirtualListHandle } from "../virtual-list"; import { type CheckState, type RowContext, @@ -11,12 +19,7 @@ import { renderFolderRow, setCheck, } from "./change-rows"; -import { RowPager } from "./row-pager"; -import { SECTION_ACTIONS } from "./section-actions"; -import type { SelectionCommand, SelectionSource } from "./selection-bar"; import { buildTree, flattenRows, flattenTree } from "./tree-builder"; -import { ESection, type FileRow, type VisualRow } from "./types"; -import { mountVirtualList, type VirtualListHandle } from "./virtual-list"; export interface ChangesSectionDeps extends Pick< diff --git a/packages/plugin/src/ui/source-control/changes-tab.ts b/packages/plugin/src/features/source-control/changes/changes-tab.ts similarity index 94% rename from packages/plugin/src/ui/source-control/changes-tab.ts rename to packages/plugin/src/features/source-control/changes/changes-tab.ts index f0be8fc3..d6549202 100644 --- a/packages/plugin/src/ui/source-control/changes-tab.ts +++ b/packages/plugin/src/features/source-control/changes/changes-tab.ts @@ -1,24 +1,22 @@ import { Platform, SearchComponent } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import { canSync } from "@/settings/model"; -import type { SyncStatusSnapshot } from "@/sync/controller"; -import type { DiffResult, ManifestEntry } from "@/sync/types"; -import { - appendIconButton, - appendLabeledButton, - lastEditLabel, - lastEditor, - notifyError, -} from "@/ui/common"; -import type { SourceControlActions } from "./actions"; +import { appendIconButton, appendLabeledButton, notifyError } from "@/core/ui"; +import { lastEditLabel, lastEditor } from "@/features/spaces"; +import type { + DiffResult, + ManifestEntry, + SyncStatusSnapshot, +} from "@/features/sync"; +import { canSync } from "@/features/sync"; +import type { SourceControlActions } from "../actions/actions"; +import { SelectionBar } from "../actions/selection-bar"; +import type { SourceControlHost } from "../host"; +import { renderSetupPrompt } from "../setup-prompt"; +import { SummaryCard } from "../summary-card"; +import { ESection, type FileRow } from "../types"; import { ChangesSection, type ChangesSectionDeps } from "./changes-section"; import type { ConflictPreviewManager } from "./conflict-preview-manager"; import { diffEquals } from "./diff-identity"; import { foldMoves, rowFromChange, rowFromConflict } from "./row-formatter"; -import { SelectionBar } from "./selection-bar"; -import { renderSetupPrompt } from "./setup-prompt"; -import { SummaryCard } from "./summary-card"; -import { ESection, type FileRow } from "./types"; /** Summary, filter, the three change sections and the selection bar; owns selection and layout so the view above only picks a tab. */ export class ChangesTab { @@ -45,7 +43,7 @@ export class ChangesTab { private openGeneration = 0; constructor( - private readonly plugin: PluginHost, + private readonly plugin: SourceControlHost, private readonly previews: ConflictPreviewManager, private readonly actions: SourceControlActions, private readonly rerender: () => void, diff --git a/packages/plugin/src/ui/source-control/conflict-preview-manager.ts b/packages/plugin/src/features/source-control/changes/conflict-preview-manager.ts similarity index 98% rename from packages/plugin/src/ui/source-control/conflict-preview-manager.ts rename to packages/plugin/src/features/source-control/changes/conflict-preview-manager.ts index 1511ffc1..d727dc07 100644 --- a/packages/plugin/src/ui/source-control/conflict-preview-manager.ts +++ b/packages/plugin/src/features/source-control/changes/conflict-preview-manager.ts @@ -1,4 +1,4 @@ -import type { FileDiffModel } from "@/sync/projection"; +import type { FileDiffModel } from "@/features/sync"; import { type ConflictPreview, renderConflictPreview, diff --git a/packages/plugin/src/ui/source-control/conflict-preview.ts b/packages/plugin/src/features/source-control/changes/conflict-preview.ts similarity index 96% rename from packages/plugin/src/ui/source-control/conflict-preview.ts rename to packages/plugin/src/features/source-control/changes/conflict-preview.ts index eb744854..70396d54 100644 --- a/packages/plugin/src/ui/source-control/conflict-preview.ts +++ b/packages/plugin/src/features/source-control/changes/conflict-preview.ts @@ -1,4 +1,4 @@ -import type { FileDiffModel } from "@/sync/projection"; +import type { FileDiffModel } from "@/features/sync"; const CONFLICT_PREVIEW_LINES = 10; diff --git a/packages/plugin/src/ui/source-control/diff-identity.ts b/packages/plugin/src/features/source-control/changes/diff-identity.ts similarity index 94% rename from packages/plugin/src/ui/source-control/diff-identity.ts rename to packages/plugin/src/features/source-control/changes/diff-identity.ts index a46fdff9..b284ee0e 100644 --- a/packages/plugin/src/ui/source-control/diff-identity.ts +++ b/packages/plugin/src/features/source-control/changes/diff-identity.ts @@ -1,4 +1,4 @@ -import type { DiffResult } from "@/sync/types"; +import type { DiffResult } from "@/features/sync"; /** The fields every row is drawn from, walked rather than described: short-circuits on the first difference. */ export function diffEquals( diff --git a/packages/plugin/src/ui/source-control/excluded-files.ts b/packages/plugin/src/features/source-control/changes/excluded-files.ts similarity index 91% rename from packages/plugin/src/ui/source-control/excluded-files.ts rename to packages/plugin/src/features/source-control/changes/excluded-files.ts index 6e161119..73582bef 100644 --- a/packages/plugin/src/ui/source-control/excluded-files.ts +++ b/packages/plugin/src/features/source-control/changes/excluded-files.ts @@ -1,14 +1,13 @@ import { TFolder } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; -import { formatBytes } from "@/shared"; -import type { SkippedFile } from "@/sync/types"; -import { stopIgnoring } from "@/ui/actions/ignore-action"; +import { formatBytes } from "@/core/shared"; +import type { SkippedFile } from "@/features/sync"; +import { stopIgnoring } from "@/features/sync"; +import type { SourceControlHost } from "../host"; import { type FileGroup, FileListModal } from "./file-list-modal"; /** What the vault's and this device's ignore rules keep out, by where the rule lives. */ export function showIgnoredFiles( - plugin: PluginHost, + plugin: SourceControlHost, paths: readonly string[], ): void { const { ignoreState } = plugin; @@ -57,7 +56,7 @@ export function showIgnoredFiles( /** Files this device cannot sync, by why. */ export function showSkippedFiles( - plugin: PluginHost, + plugin: SourceControlHost, skipped: readonly SkippedFile[], ): void { const of = (reason: R) => diff --git a/packages/plugin/src/ui/source-control/file-list-modal.ts b/packages/plugin/src/features/source-control/changes/file-list-modal.ts similarity index 99% rename from packages/plugin/src/ui/source-control/file-list-modal.ts rename to packages/plugin/src/features/source-control/changes/file-list-modal.ts index f51a917a..5daccfbb 100644 --- a/packages/plugin/src/ui/source-control/file-list-modal.ts +++ b/packages/plugin/src/features/source-control/changes/file-list-modal.ts @@ -21,7 +21,7 @@ import { renderPath, revealInFileExplorer, showMenuAt, -} from "@/ui/common"; +} from "@/core/ui"; export interface ListedFile { path: string; diff --git a/packages/plugin/src/ui/source-control/row-formatter.ts b/packages/plugin/src/features/source-control/changes/row-formatter.ts similarity index 81% rename from packages/plugin/src/ui/source-control/row-formatter.ts rename to packages/plugin/src/features/source-control/changes/row-formatter.ts index 5a155be9..de69b740 100644 --- a/packages/plugin/src/ui/source-control/row-formatter.ts +++ b/packages/plugin/src/features/source-control/changes/row-formatter.ts @@ -1,8 +1,12 @@ -import { deviceLabel } from "@/sync/device"; -import { movesByPath } from "@/sync/moves"; -import type { Conflict, FileChange, Move } from "@/sync/types"; -import { type ChangeAction, changeActionOf } from "@/ui/common"; -import type { FileRow } from "./types"; +import type { Conflict, FileChange, Move } from "@/features/sync"; +import { + type ChangeAction, + changeActionOf, + deviceLabel, + hasKnownBinaryExtension, + movesByPath, +} from "@/features/sync"; +import type { FileRow } from "../types"; export const STATUS_LETTERS: Record = { add: "A", @@ -65,12 +69,16 @@ export function foldMoves( } export function rowFromConflict(conflict: Conflict, size?: number): FileRow { + const hasBase = conflict.baselineHash !== null; return { path: conflict.path, size, statusLetter: "C", statusClass: "mdsync-status-conflict", isConflict: true, + hasBase, + // The diff view decides for sure once it reads both sides; this only names the button. + mergeable: hasBase && !hasKnownBinaryExtension(conflict.path), }; } diff --git a/packages/plugin/src/ui/source-control/tree-builder.ts b/packages/plugin/src/features/source-control/changes/tree-builder.ts similarity index 99% rename from packages/plugin/src/ui/source-control/tree-builder.ts rename to packages/plugin/src/features/source-control/changes/tree-builder.ts index feded650..d1752324 100644 --- a/packages/plugin/src/ui/source-control/tree-builder.ts +++ b/packages/plugin/src/features/source-control/changes/tree-builder.ts @@ -1,4 +1,4 @@ -import type { FileRow, MutableTreeNode, TreeNode, VisualRow } from "./types"; +import type { FileRow, MutableTreeNode, TreeNode, VisualRow } from "../types"; export function buildTree(rows: ReadonlyArray): TreeNode { const root = createFolderNode("", ""); diff --git a/packages/plugin/src/features/source-control/history/age-groups.ts b/packages/plugin/src/features/source-control/history/age-groups.ts new file mode 100644 index 00000000..530b9b7e --- /dev/null +++ b/packages/plugin/src/features/source-control/history/age-groups.ts @@ -0,0 +1,104 @@ +import { + formatDay, + formatDayLabel, + pluralize, + startOfWeek, +} from "@/core/shared"; +import { RESOLUTIONS, type Resolution } from "@/features/sync"; + +const HOUR_MS = 3_600_000; + +export const PINNED_LABEL = "Pinned"; + +export interface Aged { + at: number; + /** Null off the walk, dated by its own clock like a single push. */ + res: Resolution | null; + pinned: boolean; +} + +export interface AgeGroup { + label: string; + /** The coarsest resolution kept in it, where it differs from the group above. */ + chip: Resolution | null; + rows: T[]; +} + +/** Pinned rows lead; the rest group as finely as history keeps them: the last hour, days, weeks, months. */ +export function groupByAge( + rows: readonly T[], + now: number = Date.now(), +): AgeGroup[] { + const pinned = rows.filter((row) => row.pinned); + const groups: AgeGroup[] = + pinned.length > 0 + ? [{ label: PINNED_LABEL, chip: null, rows: pinned }] + : []; + const aged: Array<{ label: string; res: Resolution; rows: T[] }> = []; + for (const row of rows) { + if (row.pinned) continue; + const label = ageLabel(row, now); + const res = row.res ?? "push"; + const last = aged[aged.length - 1]; + if (last?.label !== label) aged.push({ label, res, rows: [row] }); + else { + last.rows.push(row); + if (RESOLUTIONS.indexOf(res) > RESOLUTIONS.indexOf(last.res)) + last.res = res; + } + } + let above: Resolution | null = null; + for (const { label, res, rows } of aged) { + groups.push({ label, chip: res === above ? null : res, rows }); + above = res; + } + return groups; +} + +export function ageLabel( + { at, res }: Pick, + now: number = Date.now(), +): string { + if (res === "1w") + return new Date(at).toLocaleDateString(undefined, { + month: "long", + year: "numeric", + }); + if (res === "1d") { + const monday = new Date(startOfWeek(at)); + const sunday = new Date(monday); + sunday.setDate(monday.getDate() + 6); + return new Intl.DateTimeFormat(undefined, { + month: "short", + day: "numeric", + }).formatRange(monday, sunday); + } + if ((res ?? "push") === "push" && inLastHour(at, now)) return "Last hour"; + return formatDayLabel(at, now); +} + +export function inLastHour(at: number, now: number): boolean { + return now - at < HOUR_MS; +} + +/** A row's title under its group: the time in a day, the day in a week, the week in a month. */ +export function ageTitle( + { at, res }: Pick, + now: number = Date.now(), +): string { + if (res === "1w") return `Week of ${formatDay(startOfWeek(at), now, false)}`; + if (res === "1d") return formatDay(at, now); + return clockTime(at); +} + +/** "last of 3 pushes" for a version that stands for several. */ +export function lastOf(pushes: number): string | null { + return pushes > 1 ? `last of ${pluralize(pushes, "push", "pushes")}` : null; +} + +export function clockTime(ms: number): string { + return new Date(ms).toLocaleTimeString(undefined, { + hour: "2-digit", + minute: "2-digit", + }); +} diff --git a/packages/plugin/src/ui/source-control/history-list.ts b/packages/plugin/src/features/source-control/history/history-list.ts similarity index 95% rename from packages/plugin/src/ui/source-control/history-list.ts rename to packages/plugin/src/features/source-control/history/history-list.ts index 384329b3..7725b8b1 100644 --- a/packages/plugin/src/ui/source-control/history-list.ts +++ b/packages/plugin/src/features/source-control/history/history-list.ts @@ -1,4 +1,4 @@ -import { OFFLINE_MESSAGE, userMessage } from "@/shared"; +import { OFFLINE_MESSAGE, userMessage } from "@/core/shared"; /** A list read from history: one load at a time, and one started before `clear` never lands. */ export class HistoryList { diff --git a/packages/plugin/src/ui/source-control/history-rows.ts b/packages/plugin/src/features/source-control/history/history-rows.ts similarity index 57% rename from packages/plugin/src/ui/source-control/history-rows.ts rename to packages/plugin/src/features/source-control/history/history-rows.ts index acb8f3b4..4294198c 100644 --- a/packages/plugin/src/ui/source-control/history-rows.ts +++ b/packages/plugin/src/features/source-control/history/history-rows.ts @@ -1,7 +1,7 @@ -import { formatRelativeTime, formatTimestamp } from "@/shared"; -import type { FileVersion } from "@/sync/history"; -import { timeInDay } from "./day-groups"; -import { deviceText } from "./row-formatter"; +import { formatDay, formatRelativeTime, formatTimestamp } from "@/core/shared"; +import type { FileVersion, Resolution } from "@/features/sync"; +import { deviceText } from "../changes/row-formatter"; +import { ageTitle, lastOf } from "./age-groups"; export interface HistoryRowVersion { hash: string; @@ -12,16 +12,21 @@ export interface HistoryRowVersion { export interface HistoryRow { snapshotId: string; createdAt: number; + at: number; + res: Resolution | null; hash: string; size: number; /** Bytes gained or lost against the next older version. Absent on the oldest. */ sizeDelta?: number; - /** The pin's name, else the age of a pin or a version from today, else the clock time. */ + /** The pin's name, else what its group leaves to say (`ageTitle`). */ title: string; meta: string; /** Absolute timestamp; the title is relative, which alone is not precise. */ tooltip: string; pinned: boolean; + /** Where pin actions go: the pin holding this content may sit on a later snapshot. */ + pinId: string | null; + replayable: boolean; /** The pin's own name, empty when it has none. Distinct from the displayed title. */ label: string; isLatest: boolean; @@ -34,6 +39,8 @@ export interface HistoryRow { export interface HistoryRowOptions { now?: number; currentDevice?: { id: string; name: string } | null; + /** Positions in `versions` to build, in this order; each still compares with its next older version. */ + only?: readonly number[]; } export function buildHistoryRows( @@ -41,7 +48,9 @@ export function buildHistoryRows( options: HistoryRowOptions = {}, ): HistoryRow[] { const now = options.now ?? Date.now(); - return versions.map((version, index) => { + const positions = options.only ?? versions.map((_, index) => index); + return positions.map((index) => { + const version = versions[index] as FileVersion; const older = versions[index + 1]; const relative = formatRelativeTime(version.createdAt, now); const label = version.label?.trim() ?? ""; @@ -49,16 +58,25 @@ export function buildHistoryRows( return { snapshotId: version.snapshotId, createdAt: version.createdAt, + at: version.at, + res: version.res, hash: version.hash, size: version.size, sizeDelta: older ? version.size - older.size : undefined, - title: - label || - (version.pinned ? relative : timeInDay(version.createdAt, now)), - // A pin's name replaces the age in the title, and pins sit apart from their day. - meta: label ? `${relative} · ${device}` : device, - tooltip: formatTimestamp(version.createdAt), - pinned: version.pinned, + title: label || ageTitle(version, now), + meta: [ + // Pins sit apart from their day, so they carry it. + version.pinId ? formatDay(version.at, now) : null, + device, + lastOf(version.pushes), + version.first ? "first version" : null, + ] + .filter(Boolean) + .join(" · "), + tooltip: formatTimestamp(version.at), + pinned: version.pinId !== null, + pinId: version.pinId, + replayable: version.replayable, label, isLatest: index === 0, version: { hash: version.hash, label: relative, size: version.size }, diff --git a/packages/plugin/src/ui/source-control/history-tab.ts b/packages/plugin/src/features/source-control/history/history-tab.ts similarity index 71% rename from packages/plugin/src/ui/source-control/history-tab.ts rename to packages/plugin/src/features/source-control/history/history-tab.ts index 87c13983..a8ae998e 100644 --- a/packages/plugin/src/ui/source-control/history-tab.ts +++ b/packages/plugin/src/features/source-control/history/history-tab.ts @@ -1,28 +1,29 @@ import { Menu, setIcon } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import { pluralize } from "@/shared"; -import type { FileVersion } from "@/sync/history"; +import { HISTORY_KEEP_MS } from "@/core/constants"; +import { formatDay, pluralize } from "@/core/shared"; import { appendIconButton, appendLabeledButton, attempt, makeActivatable, - notifyError, - notifyInfo, -} from "@/ui/common"; -import type { HistoryDiffTarget } from "@/ui/source-control-view"; -import { groupRows } from "./day-groups"; -import { HistoryList } from "./history-list"; -import { buildHistoryRows, type HistoryRow } from "./history-rows"; -import { confirmRestore } from "./restore-modal"; -import { renderSize } from "./row-parts"; -import { addSnapshotPinItems } from "./snapshot-menu"; + openPluginSettings, +} from "@/core/ui"; +import type { HistoryDiffTarget } from "@/features/diff"; +import { countsBefore, type FileVersion } from "@/features/sync"; +import type { SourceControlHost } from "../host"; +import { confirmAndRestoreFile } from "../restore-file"; +import { renderAgeHeader, renderSize } from "../row-parts"; import { renderEmptyState, renderHistoryOff, renderLoadError, renderLoading, -} from "./tab-states"; +} from "../tab-states"; +import { addSnapshotPinItems } from "../timeline/snapshot-menu"; +import { groupByAge } from "./age-groups"; +import { HistoryList } from "./history-list"; +import { buildHistoryRows, type HistoryRow } from "./history-rows"; +import { RowPager } from "./row-pager"; export class HistoryTab { private explicitPath: string | null = null; @@ -32,9 +33,10 @@ export class HistoryTab { /** The version whose diff was opened last. */ private selected: string | null = null; private loadedPath: string | null = null; + private pager = new RowPager(); constructor( - private readonly plugin: PluginHost, + private readonly plugin: SourceControlHost, private readonly onRerender: () => void, private readonly openDiff: ( path: string, @@ -60,6 +62,8 @@ export class HistoryTab { clearVersions(): void { this.versions.clear(); this.loadedPath = null; + // A new path or result always follows a clear. + this.pager = new RowPager(); } clearOffline(): boolean { @@ -73,8 +77,9 @@ export class HistoryTab { if (!this.plugin.settings.fileHistoryEnabled) { renderHistoryOff( pane, - this.plugin.app, - "File version history is disabled. Enable it in settings.", + this.plugin, + "Keep past versions of your files to view or restore any of them. Each push saves what it changed, encrypted.", + this.onRerender, ); return; } @@ -132,14 +137,45 @@ export class HistoryTab { }); return; } + // Pinned lead, as groupByAge orders them, so a page break never splits the pinned group. + const ordered = [ + ...versions.flatMap((v, index) => (v.pinId !== null ? [index] : [])), + ...versions.flatMap((v, index) => (v.pinId === null ? [index] : [])), + ]; const rows = buildHistoryRows(versions, { currentDevice: this.plugin.controller.currentDevice(), + only: this.pager.slice(ordered), }); - for (const group of groupRows(rows)) { - body.createDiv({ cls: "mdsync-timeline-day", text: group.label }); + for (const group of groupByAge(rows)) { + renderAgeHeader(body, group); const list = body.createDiv({ cls: "mdsync-history-rows" }); for (const row of group.rows) this.renderRow(list, path, row); } + this.pager.render(body, ordered.length, this.onRerender); + this.renderFooter(body); + } + + /** Where the list ends and why: this device's **Keep history for**. */ + private renderFooter(body: HTMLElement): void { + const horizon = HISTORY_KEEP_MS[this.plugin.settings.fileHistoryKeep]; + const note = body.createDiv({ cls: "mdsync-history-footer" }); + if (horizon === null) { + note.setText( + "Older versions thin to one per week and are kept for good.", + ); + return; + } + const now = Date.now(); + const cutoff = countsBefore(now, horizon); + note.appendText( + `Older versions thin out with age; before ${formatDay(cutoff, now, false)} only pinned versions and activity counts remain. `, + ); + note + .createEl("a", { text: "Keep history for", href: "#" }) + .addEventListener("click", (event) => { + event.preventDefault(); + openPluginSettings(this.plugin.app); + }); } private renderFileCard(parent: HTMLElement, path: string): void { @@ -168,7 +204,10 @@ export class HistoryTab { const item = list.createDiv({ cls: "mdsync-history-row" }); item.toggleClass("is-latest", row.isLatest); item.toggleClass("is-active", this.selected === row.snapshotId); - makeActivatable(item, `${row.title} · ${row.tooltip}`, () => { + const label = [row.title, row.tooltip, row.meta] + .filter(Boolean) + .join(" · "); + makeActivatable(item, label, () => { this.selected = row.snapshotId; // In place: a re-render would lose the list's scroll. item.parentElement?.parentElement @@ -185,7 +224,7 @@ export class HistoryTab { mark.addClass("has-pin"); const pin = mark.createSpan({ cls: "mdsync-history-pin" }); setIcon(pin, "pin"); - pin.setAttr("aria-label", "Pinned snapshot"); + pin.setAttr("aria-label", "Pinned version"); } else mark.createSpan({ cls: "mdsync-history-dot" }); const copy = item.createDiv({ cls: "mdsync-timeline-copy" }); const title = copy.createDiv({ cls: "mdsync-timeline-title" }); @@ -230,7 +269,13 @@ export class HistoryTab { ); } menu.addSeparator(); - addSnapshotPinItems(menu, this.plugin, row, this.onSnapshotsChanged); + addSnapshotPinItems( + menu, + this.plugin, + { ...row, snapshotId: row.pinId ?? row.snapshotId, path }, + this.onSnapshotsChanged, + row.replayable, + ); menu.showAtMouseEvent(event); } @@ -259,20 +304,16 @@ export class HistoryTab { path: string, row: HistoryRow, ): Promise { - const confirmed = await confirmRestore({ - plugin: this.plugin, - path, - target: path, - // The title is a clock time under its day; the dialog has no day. - version: { ...row.version, label: row.label || row.version.label }, - }); - if (!confirmed) return; - try { - await this.plugin.controller.history.restoreFileVersion(path, row.hash); + await confirmAndRestoreFile( + this.plugin, + { + path, + target: path, + // The title is a clock time under its day; the dialog has no day. + version: { ...row.version, label: row.label || row.version.label }, + }, // The list describes the remote, which a local restore does not touch. - notifyInfo("Restored. Review and push the change when ready."); - } catch (err) { - notifyError("Restore failed", err); - } + "Restored. Review and push the change when ready.", + ); } } diff --git a/packages/plugin/src/styles/source-control/history.css b/packages/plugin/src/features/source-control/history/history.css similarity index 81% rename from packages/plugin/src/styles/source-control/history.css rename to packages/plugin/src/features/source-control/history/history.css index 39a27f83..2366f05b 100644 --- a/packages/plugin/src/styles/source-control/history.css +++ b/packages/plugin/src/features/source-control/history/history.css @@ -204,6 +204,17 @@ } /* Deleted files: a box to tick, the file, what history says of it. */ +.mdsync-deleted-panel .mdsync-timeline-filter { + margin-bottom: var(--size-4-2); +} + +.mdsync-deleted-list { + display: flex; + flex: 0 0 auto; + flex-direction: column; + gap: var(--size-2-1); +} + .mdsync-deleted-head { display: flex; flex: 0 0 auto; @@ -224,7 +235,7 @@ cursor: pointer; } -.mdsync-deleted-count { +.mdsync-deleted-kept { margin-left: auto; color: var(--text-faint); font-size: var(--font-ui-smaller); @@ -233,10 +244,11 @@ .mdsync-deleted-row { display: grid; flex: 0 0 auto; - grid-template-columns: 24px minmax(0, 1fr) auto; + position: relative; + grid-template-columns: 20px minmax(0, 1fr) auto; align-items: start; - gap: 6px; - padding: var(--size-4-2) 6px var(--size-4-2) var(--size-4-1); + gap: var(--size-4-2); + padding: var(--size-4-2) 6px var(--size-4-2) var(--size-4-2); border-radius: var(--radius-m); } @@ -303,4 +315,42 @@ .mdsync-deleted-row:not(:hover, :focus-within) .mdsync-row-actions { display: none; } + + /* Over the name's end in the row's own tint, so showing them reflows nothing. */ + .mdsync-deleted-row .mdsync-row-actions { + --mdsync-tint: var(--background-modifier-hover); + position: absolute; + top: var(--size-4-1); + right: 6px; + padding-left: var(--size-4-2); + background: + linear-gradient(var(--mdsync-tint), var(--mdsync-tint)), + var(--mdsync-view-bg); + } + + .mdsync-deleted-row.is-selected .mdsync-row-actions { + --mdsync-tint: color-mix( + in srgb, + var(--interactive-accent) 12%, + transparent + ); + } +} + +/* Size first, its change under it in the state colour. */ +.mdsync-history-row .mdsync-file-size.has-delta .mdsync-file-size-delta { + order: 1; +} + +.mdsync-history-row .mdsync-file-size-current { + color: var(--text-muted); +} + +.mdsync-history-footer { + margin: var(--size-4-3) var(--size-4-1) 0; + padding: var(--size-4-2) var(--size-4-3); + border: 1px dashed var(--background-modifier-border); + border-radius: var(--radius-m); + color: var(--text-muted); + font-size: var(--font-ui-smaller); } diff --git a/packages/plugin/src/ui/source-control/row-pager.ts b/packages/plugin/src/features/source-control/history/row-pager.ts similarity index 67% rename from packages/plugin/src/ui/source-control/row-pager.ts rename to packages/plugin/src/features/source-control/history/row-pager.ts index 6e79ab93..0271c891 100644 --- a/packages/plugin/src/ui/source-control/row-pager.ts +++ b/packages/plugin/src/features/source-control/history/row-pager.ts @@ -4,6 +4,8 @@ const PAGE_SIZE = 100; export class RowPager { private page = 0; + /** The button just used: the controls are redrawn with the page, so focus moves to the new ones. */ + private refocus: string | null = null; slice(rows: readonly T[]): readonly T[] { this.page = Math.min(this.page, lastPage(rows.length)); @@ -17,19 +19,30 @@ export class RowPager { render(parent: HTMLElement, count: number, changed: () => void): void { if (count <= PAGE_SIZE) return; const controls = parent.createDiv({ cls: "mdsync-history-row-actions" }); + const buttons = new Map(); for (const [label, delta] of [ ["Previous page", -1], ["Next page", 1], ] as const) { - new ButtonComponent(controls) + const button = new ButtonComponent(controls) .setButtonText(label) .setDisabled( delta < 0 ? this.page === 0 : this.page === lastPage(count), ) .onClick(() => { this.move(delta, count); + this.refocus = label; changed(); }); + buttons.set(label, button); + } + if (this.refocus) { + const used = buttons.get(this.refocus); + const target = used?.disabled + ? [...buttons.values()].find((button) => !button.disabled) + : used; + target?.buttonEl.focus({ preventScroll: true }); + this.refocus = null; } controls.createSpan({ cls: "mdsync-history-row-meta", diff --git a/packages/plugin/src/features/source-control/host.ts b/packages/plugin/src/features/source-control/host.ts new file mode 100644 index 00000000..97ae8af5 --- /dev/null +++ b/packages/plugin/src/features/source-control/host.ts @@ -0,0 +1,8 @@ +import type { DiffHost } from "@/features/diff"; +import type { ESetupStep } from "@/features/setup"; +import type { SpacesHost } from "@/features/spaces"; + +/** What the source control view needs from the plugin. */ +export interface SourceControlHost extends SpacesHost, DiffHost { + openSetup(step?: ESetupStep): void; +} diff --git a/packages/plugin/src/features/source-control/index.ts b/packages/plugin/src/features/source-control/index.ts new file mode 100644 index 00000000..068fd019 --- /dev/null +++ b/packages/plugin/src/features/source-control/index.ts @@ -0,0 +1,13 @@ +export type { SourceControlHost } from "./host"; +export { SourceControlView } from "./view"; +export { + addHistoryMenuItems, + keepInRightSidebar, + openSourceControlChanges, + openSourceControlDeleted, + openSourceControlHistory, + openSourceControlTimeline, + openSourceControlView, + refreshHistoryAfterPush, + refreshSourceControlViews, +} from "./workspace"; diff --git a/packages/plugin/src/features/source-control/restore-file.ts b/packages/plugin/src/features/source-control/restore-file.ts new file mode 100644 index 00000000..2fa482b0 --- /dev/null +++ b/packages/plugin/src/features/source-control/restore-file.ts @@ -0,0 +1,26 @@ +import { notifyError, notifyInfo } from "@/core/ui"; +import { confirmRestore } from "@/features/diff"; +import type { SourceControlHost } from "./host"; + +type RestoreConfirm = Omit[0], "plugin">; + +/** Asks, then writes one stored version of a file into the vault; nothing is pushed. */ +export async function confirmAndRestoreFile( + plugin: SourceControlHost, + confirm: RestoreConfirm, + success: string, + afterRestore?: () => void, +): Promise { + if (!(await confirmRestore({ ...confirm, plugin }))) return; + try { + await plugin.controller.history.restoreFileVersion( + confirm.target, + confirm.version.hash, + confirm.path, + ); + notifyInfo(success); + afterRestore?.(); + } catch (error) { + notifyError("Restore failed", error); + } +} diff --git a/packages/plugin/src/ui/source-control/row-parts.ts b/packages/plugin/src/features/source-control/row-parts.ts similarity index 65% rename from packages/plugin/src/ui/source-control/row-parts.ts rename to packages/plugin/src/features/source-control/row-parts.ts index 979dbed0..80ed3a3a 100644 --- a/packages/plugin/src/ui/source-control/row-parts.ts +++ b/packages/plugin/src/features/source-control/row-parts.ts @@ -1,4 +1,19 @@ -import { formatBytes } from "@/shared"; +import { formatBytes } from "@/core/shared"; +import { RESOLUTION_TEXT, type Resolution } from "@/features/sync"; + +/** A group's heading, with the resolution its versions are kept at where that changes. */ +export function renderAgeHeader( + parent: HTMLElement, + { label, chip }: { label: string; chip: Resolution | null }, +): void { + const header = parent.createDiv({ cls: "mdsync-timeline-day" }); + header.createSpan({ text: label }); + if (chip) + header.createSpan({ + cls: "mdsync-timeline-res", + text: RESOLUTION_TEXT[chip], + }); +} /** The compact size badge: signed delta stacked over the current size. */ export function renderSize( diff --git a/packages/plugin/src/ui/source-control/setup-prompt.ts b/packages/plugin/src/features/source-control/setup-prompt.ts similarity index 71% rename from packages/plugin/src/ui/source-control/setup-prompt.ts rename to packages/plugin/src/features/source-control/setup-prompt.ts index c808819e..1845f773 100644 --- a/packages/plugin/src/ui/source-control/setup-prompt.ts +++ b/packages/plugin/src/features/source-control/setup-prompt.ts @@ -1,16 +1,16 @@ -import type { PluginHost } from "@/plugin/host"; -import { ESetupStep } from "@/settings/setup/steps"; +import { ESetupStep } from "@/features/setup"; +import type { SourceControlHost } from "./host"; import { renderEmptyState } from "./tab-states"; /** The Changes tab of a device that syncs nothing yet. */ export function renderSetupPrompt( parent: HTMLElement, - plugin: PluginHost, + plugin: SourceControlHost, ): void { const el = renderEmptyState(parent, { icon: "hard-drive", title: "Connect storage to sync", - text: "Pick S3, WebDAV or Google Drive and set a passphrase. Files are encrypted on this device.", + text: "Use Cloudflare R2, S3, WebDAV or Google Drive and set a passphrase. Files are encrypted on this device.", action: { text: "Set up sync", cta: true, run: () => plugin.openSetup() }, }); const join = el.createEl("a", { diff --git a/packages/plugin/src/styles/source-control/containers.css b/packages/plugin/src/features/source-control/styles/containers.css similarity index 100% rename from packages/plugin/src/styles/source-control/containers.css rename to packages/plugin/src/features/source-control/styles/containers.css diff --git a/packages/plugin/src/styles/source-control/file-list.css b/packages/plugin/src/features/source-control/styles/file-list.css similarity index 100% rename from packages/plugin/src/styles/source-control/file-list.css rename to packages/plugin/src/features/source-control/styles/file-list.css diff --git a/packages/plugin/src/styles/source-control/file-rows.css b/packages/plugin/src/features/source-control/styles/file-rows.css similarity index 82% rename from packages/plugin/src/styles/source-control/file-rows.css rename to packages/plugin/src/features/source-control/styles/file-rows.css index a8720c1d..8f635789 100644 --- a/packages/plugin/src/styles/source-control/file-rows.css +++ b/packages/plugin/src/features/source-control/styles/file-rows.css @@ -34,9 +34,23 @@ background: var(--background-primary-alt); } +/* The status spinner's look: a pseudo-element cannot take its class. */ .mdsync-file-row.is-opening::after { content: ""; flex: 0 0 auto; + display: inline-block; + width: 0.75rem; + height: 0.75rem; + border: 2px solid var(--background-modifier-border); + border-top-color: var(--interactive-accent); + border-radius: 50%; + animation: mdsync-spin 0.65s linear infinite; +} + +@media (prefers-reduced-motion: reduce) { + .mdsync-file-row.is-opening::after { + animation: none; + } } /* A tinted letter tile: the colour comes from the status class. */ @@ -82,11 +96,11 @@ } .mdsync-size-delta.is-positive { - color: var(--color-green); + color: var(--mdsync-added); } .mdsync-size-delta.is-negative { - color: var(--color-red); + color: var(--mdsync-deleted); } .mdsync-size-delta.is-neutral { @@ -98,15 +112,15 @@ } .mdsync-status-add { - color: var(--color-green); + color: var(--mdsync-added); } .mdsync-status-modify { - color: var(--color-orange); + color: var(--mdsync-modified); } .mdsync-status-delete { - color: var(--color-red); + color: var(--mdsync-deleted); } .mdsync-status-move { @@ -268,16 +282,18 @@ font-size: var(--font-ui-smaller); } +/* Sized by their labels, wrapping in a narrow sidebar: equal thirds cut "Accept remote" short. */ .mdsync-conflict-choices { display: flex; - gap: var(--size-2-3); + flex-wrap: wrap; + gap: var(--size-2-2); } .mdsync-conflict-choices > button { - flex: 1 1 0; + flex: 1 1 auto; min-width: 0; height: 26px; - padding: 0 var(--size-2-3); + padding: 0 var(--size-2-2); font-size: var(--font-ui-smaller); } @@ -306,3 +322,26 @@ margin: 0; padding: var(--size-2-2) var(--size-4-2); } + +.mdsync-unified-line { + display: block; +} + +.mdsync-line-prefix { + display: inline-block; + width: 1.5em; + text-align: center; + user-select: none; + opacity: 0.6; +} + +/* Tint from the theme's own hue, not `--background-modifier-error/success`: solid fills make same-hue text invisible. */ +.mdsync-unified-line.is-add { + background-color: rgba(var(--mdsync-added-rgb), 0.15); + color: var(--text-normal); +} + +.mdsync-unified-line.is-del { + background-color: rgba(var(--mdsync-deleted-rgb), 0.15); + color: var(--text-normal); +} diff --git a/packages/plugin/src/styles/source-control/phone.css b/packages/plugin/src/features/source-control/styles/phone.css similarity index 94% rename from packages/plugin/src/styles/source-control/phone.css rename to packages/plugin/src/features/source-control/styles/phone.css index 9fff1439..9550bb04 100644 --- a/packages/plugin/src/styles/source-control/phone.css +++ b/packages/plugin/src/features/source-control/styles/phone.css @@ -242,3 +242,17 @@ body.is-phone .mdsync-source-control .mdsync-timeline-file { white-space: normal; overflow-wrap: anywhere; } + +/* Beside the tools the pill is too narrow for a whole name: the active tab is then its icon on the accent. */ +body.is-phone .mdsync-source-control .mdsync-source-tabs { + container: mdsync-source-tabs / inline-size; +} + +@container mdsync-source-tabs (max-width: 229px) { + body.is-phone + .mdsync-source-control + .mdsync-settings-tab-button.is-active + .mdsync-source-tab-label { + display: none; + } +} diff --git a/packages/plugin/src/styles/source-control/sections.css b/packages/plugin/src/features/source-control/styles/sections.css similarity index 100% rename from packages/plugin/src/styles/source-control/sections.css rename to packages/plugin/src/features/source-control/styles/sections.css diff --git a/packages/plugin/src/styles/source-control/shell.css b/packages/plugin/src/features/source-control/styles/shell.css similarity index 100% rename from packages/plugin/src/styles/source-control/shell.css rename to packages/plugin/src/features/source-control/styles/shell.css diff --git a/packages/plugin/src/styles/source-control/states.css b/packages/plugin/src/features/source-control/styles/states.css similarity index 100% rename from packages/plugin/src/styles/source-control/states.css rename to packages/plugin/src/features/source-control/styles/states.css diff --git a/packages/plugin/src/styles/source-control/summary.css b/packages/plugin/src/features/source-control/styles/summary.css similarity index 95% rename from packages/plugin/src/styles/source-control/summary.css rename to packages/plugin/src/features/source-control/styles/summary.css index 5cf381a9..49b4756f 100644 --- a/packages/plugin/src/styles/source-control/summary.css +++ b/packages/plugin/src/features/source-control/styles/summary.css @@ -131,6 +131,23 @@ background: rgba(0, 0, 0, 0.2); } +/* Off while conflicts or a pull wait: an accent fill at Obsidian's disabled opacity still reads as the next step. */ +.mdsync-sync-summary-buttons > button:disabled { + opacity: 0.6; + cursor: default; +} + +.mdsync-sync-summary-buttons > button.mod-cta:disabled { + background-color: var(--interactive-normal); + color: var(--text-muted); +} + +.mdsync-sync-summary-buttons + > button.mod-cta:disabled + .mdsync-sync-summary-count { + background: rgba(var(--mono-rgb-100), 0.1); +} + /* Set apart from the buttons: what is left out, not what to do. */ .mdsync-sync-summary-extras { display: flex; diff --git a/packages/plugin/src/styles/source-control/toolbar.css b/packages/plugin/src/features/source-control/styles/toolbar.css similarity index 100% rename from packages/plugin/src/styles/source-control/toolbar.css rename to packages/plugin/src/features/source-control/styles/toolbar.css diff --git a/packages/plugin/src/styles/source-control/tree.css b/packages/plugin/src/features/source-control/styles/tree.css similarity index 100% rename from packages/plugin/src/styles/source-control/tree.css rename to packages/plugin/src/features/source-control/styles/tree.css diff --git a/packages/plugin/src/ui/source-control/summary-card.ts b/packages/plugin/src/features/source-control/summary-card.ts similarity index 92% rename from packages/plugin/src/ui/source-control/summary-card.ts rename to packages/plugin/src/features/source-control/summary-card.ts index 15e6835c..4005df2e 100644 --- a/packages/plugin/src/ui/source-control/summary-card.ts +++ b/packages/plugin/src/features/source-control/summary-card.ts @@ -1,14 +1,20 @@ import { ButtonComponent, setIcon } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import { formatRelativeTime } from "@/shared"; -import { type SyncStatusSnapshot, splitSpaceErrors } from "@/sync/controller"; -import { deviceLabel } from "@/sync/device"; -import type { Manifest } from "@/sync/types"; -import { askSpaceGone } from "@/ui/shares/space-gone"; -import { actionButton, textButton } from "./action-button"; -import type { SourceControlActions } from "./actions"; -import { showIgnoredFiles, showSkippedFiles } from "./excluded-files"; -import { canPullAll, canPushAll } from "./sync-gates"; +import { formatRelativeTime } from "@/core/shared"; +import { actionButton, textButton } from "@/core/ui"; +import { askSpaceGone } from "@/features/spaces"; +import type { Manifest } from "@/features/sync"; +import { + canPullAll, + canPushAll, + conflictsFirst, + deviceLabel, + isVaultMismatch, + type SyncStatusSnapshot, + splitSpaceErrors, +} from "@/features/sync"; +import type { SourceControlActions } from "./actions/actions"; +import { showIgnoredFiles, showSkippedFiles } from "./changes/excluded-files"; +import type { SourceControlHost } from "./host"; /** * The head of the Changes tab: what is pending, Push and Pull, what keeps files out and what stops a sync. @@ -37,7 +43,7 @@ export class SummaryCard { /** `dock` takes Push and Pull out of the card, to the bottom of a phone screen. */ constructor( parent: HTMLElement, - private readonly plugin: PluginHost, + private readonly plugin: SourceControlHost, private readonly actions: Pick< SourceControlActions, "adoptNewVault" | "pushPaths" | "pullPaths" @@ -105,7 +111,7 @@ export class SummaryCard { pending === 0; // Nothing but the connection to say, so the card is an empty state with a retry. const parked = offline || (waiting && pending === 0); - const mismatch = isVaultMismatch(snapshot); + const mismatch = isVaultMismatch(snapshot.error); this.el.toggleClass("is-error", Boolean(error) && !snapshot.offline); this.el.toggleClass("is-warning", failed && !error); this.el.toggleClass("is-offline", parked); @@ -231,7 +237,7 @@ export class SummaryCard { const plugin = this.plugin; const extras = this.extrasEl; extras.empty(); - if (isVaultMismatch(snapshot)) { + if (isVaultMismatch(snapshot.error)) { actionButton(extras, "warning") .setButtonText("Resolve vault mismatch") .onClick(() => void this.actions.adoptNewVault()) @@ -324,12 +330,6 @@ function spaceErrorText({ return { title: `"${root}" did not compare`, desc: message }; } -function isVaultMismatch(snapshot: SyncStatusSnapshot): boolean { - return ( - snapshot.error?.includes("Remote vault id does not match local") ?? false - ); -} - function note(parent: HTMLElement, text: string): void { parent.createDiv({ cls: "mdsync-sync-summary-note", text }); } @@ -350,14 +350,15 @@ function chip( badge.addEventListener("click", open); } -/** Why Push or Pull of everything is off while there is something to sync; selected files still go. */ +/** Why Push or Pull of everything is off while there is something to sync. */ function blockedHint(snapshot: SyncStatusSnapshot): string | null { const diff = snapshot.result?.diff; if (snapshot.busy || !diff) return null; const { conflicts, localChanges, remoteChanges } = diff; if (conflicts.length > 0 && localChanges.length + remoteChanges.length > 0) { - return "Resolve the conflicts to push or pull everything."; + return conflictsFirst(conflicts.map((c) => c.path)); } + // Selected files without a remote change still go. if (remoteChanges.length > 0 && localChanges.length > 0) { return "Pull first to push everything."; } diff --git a/packages/plugin/src/ui/source-control/tab-states.ts b/packages/plugin/src/features/source-control/tab-states.ts similarity index 79% rename from packages/plugin/src/ui/source-control/tab-states.ts rename to packages/plugin/src/features/source-control/tab-states.ts index 11b0f407..421c474d 100644 --- a/packages/plugin/src/ui/source-control/tab-states.ts +++ b/packages/plugin/src/features/source-control/tab-states.ts @@ -1,6 +1,7 @@ -import { type App, ButtonComponent, setIcon } from "obsidian"; -import { OFFLINE_MESSAGE } from "@/shared"; -import { callout, openPluginSettings } from "@/ui/common"; +import { ButtonComponent, setIcon } from "obsidian"; +import type { SettingsHost } from "@/core/settings"; +import { OFFLINE_MESSAGE } from "@/core/shared"; +import { callout } from "@/core/ui"; interface StateAction { text: string; @@ -61,17 +62,26 @@ export function renderLoading(parent: HTMLElement): void { for (let i = 0; i < 5; i++) el.createDiv({ cls: "mdsync-skeleton-row" }); } +/** Records from the next push on: nothing from before comes back. */ export function renderHistoryOff( parent: HTMLElement, - app: App, + plugin: SettingsHost, text: string, + onEnabled: () => void, ): void { renderEmptyState(parent, { icon: "timer-off", tone: "muted", title: "History is off", text, - action: { text: "Open settings", run: () => openPluginSettings(app) }, + action: { + text: "Turn on history", + cta: true, + run: () => { + Object.assign(plugin.settings, { fileHistoryEnabled: true }); + void plugin.saveSettings().then(onEnabled); + }, + }, }); } diff --git a/packages/plugin/src/styles/source-control/restore.css b/packages/plugin/src/features/source-control/timeline/restore.css similarity index 100% rename from packages/plugin/src/styles/source-control/restore.css rename to packages/plugin/src/features/source-control/timeline/restore.css diff --git a/packages/plugin/src/features/source-control/timeline/session-card.ts b/packages/plugin/src/features/source-control/timeline/session-card.ts new file mode 100644 index 00000000..f2479db5 --- /dev/null +++ b/packages/plugin/src/features/source-control/timeline/session-card.ts @@ -0,0 +1,236 @@ +import { setIcon } from "obsidian"; +import { formatBytes, pluralize } from "@/core/shared"; +import { + appendIconButton, + appendLabeledButton, + makeActivatable, + onLongPress, + renderPath, +} from "@/core/ui"; +import type { Resolution } from "@/features/sync"; +import { STATUS_CLASSES, STATUS_LETTERS } from "../changes/row-formatter"; +import type { RowPager } from "../history/row-pager"; +import { renderDelta } from "../row-parts"; +import { type SessionRow, touches } from "./session-rows"; +import type { TimelineFileRow, TimelineRow } from "./timeline-rows"; + +const PERIOD_CAPTION: Partial> = { + "10m": "Last version of every 10 minutes", + "1h": "Last version of each hour", + "1d": "Last version of each day", + "1w": "Last version of each week", +}; + +export interface CardContext { + /** Lowercase path filter, empty for none. */ + query: string; + selected: string | null; + opening: string | null; + isOpen(key: string): boolean; + toggle(key: string): void; + pager(key: string): RowPager; + rerender(): void; + sessionMenu(event: MouseEvent, row: SessionRow): void; + versionMenu(event: MouseEvent, row: TimelineRow): void; + fileMenu(event: MouseEvent, owner: string, file: TimelineFileRow): void; + openFile(owner: string, file: TimelineFileRow): void; +} + +interface Heading { + title: string; + meta: string | null; + tooltip: string; + counts: string | null; + tally: TimelineRow["tally"]; + netDelta: number | null; + pinned: boolean; + isHead: boolean; +} + +export function renderSessionCard( + parent: HTMLElement, + row: SessionRow, + ctx: CardContext, +): void { + const card = parent.createDiv({ cls: "mdsync-timeline-card" }); + renderHead(card, row.key, row, ctx, (event) => ctx.sessionMenu(event, row)); + if (!ctx.isOpen(row.key)) return; + const body = card.createDiv({ cls: "mdsync-timeline-files" }); + const versions = ctx.query + ? row.versions.filter((version) => touches(version, ctx.query)) + : row.versions; + if (!row.everyPush) { + body.createDiv({ + cls: "mdsync-timeline-caption", + text: (row.res && PERIOD_CAPTION[row.res]) ?? "", + }); + renderVersions(body, row.key, versions, ctx); + return; + } + renderFiles(body, row.key, row.files, ctx); + if (row.versions.length < 2) return; + const allKey = `all:${row.key}`; + const all = ctx.isOpen(allKey); + const more = appendLabeledButton( + body, + all ? "chevron-up" : "chevron-down", + all + ? "Hide pushes" + : `Show all ${pluralize(row.versions.length, "push", "pushes")}`, + () => ctx.toggle(allKey), + ); + more.addClass("mdsync-timeline-more"); + more.setAttr("data-timeline-focus", allKey); + if (all) renderVersions(body, row.key, versions, ctx); +} + +function renderVersions( + parent: HTMLElement, + owner: string, + versions: readonly TimelineRow[], + ctx: CardContext, +): void { + const pager = ctx.pager(`versions:${owner}`); + for (const version of pager.slice(versions)) + renderVersion(parent, version, ctx); + pager.render(parent, versions.length, ctx.rerender); +} + +function renderVersion( + parent: HTMLElement, + row: TimelineRow, + ctx: CardContext, +): void { + const key = `v:${row.snapshotId}`; + const item = parent.createDiv({ cls: "mdsync-timeline-version" }); + renderHead(item, key, row, ctx, (event) => ctx.versionMenu(event, row)); + if (ctx.isOpen(key)) renderFiles(item, key, row.files, ctx); +} + +function renderHead( + parent: HTMLElement, + key: string, + row: Heading, + ctx: CardContext, + menu: (event: MouseEvent) => void, +): void { + const open = ctx.isOpen(key); + const head = parent.createDiv({ cls: "mdsync-timeline-head" }); + head.setAttr("data-timeline-focus", key); + head.setAttr("aria-expanded", String(open)); + // The meta is cut short in a narrow pane; the tooltip keeps all of it. + const label = [row.title, row.tooltip, row.meta].filter(Boolean).join(" · "); + makeActivatable(head, label, () => ctx.toggle(key)); + setIcon( + head.createSpan({ cls: "mdsync-timeline-icon" }), + open ? "chevron-down" : "chevron-right", + ); + const copy = head.createDiv({ cls: "mdsync-timeline-copy" }); + const title = copy.createDiv({ cls: "mdsync-timeline-title" }); + title.createSpan({ cls: "mdsync-history-row-title", text: row.title }); + if (row.isHead) title.createSpan({ cls: "mdsync-pill", text: "Latest" }); + if (row.pinned) { + const pin = title.createSpan({ cls: "mdsync-history-pin" }); + setIcon(pin, "pin"); + pin.setAttr("aria-label", "Pinned version"); + } + const meta = copy.createDiv({ + cls: "mdsync-history-row-meta mdsync-timeline-meta", + }); + if (row.meta) + meta.createSpan({ cls: "mdsync-timeline-device", text: row.meta }); + if (!row.tally) meta.createSpan({ text: "Change record unavailable" }); + else { + const chips = meta.createSpan({ cls: "mdsync-timeline-chips" }); + if (row.counts) chips.setAttr("aria-label", row.counts); + for (const [action, count] of row.tally) { + chips.createSpan({ + cls: `mdsync-count-chip ${STATUS_CLASSES[action]}`, + text: `${STATUS_LETTERS[action]} ${count}`, + }); + } + } + if (row.netDelta) renderDelta(meta, row.netDelta, "mdsync-timeline-net"); + const actions = head.createDiv({ cls: "mdsync-timeline-actions" }); + const more = appendIconButton(actions, "ellipsis", "Actions", (event) => { + event.stopPropagation(); + menu(event); + }); + more.setAttr("data-timeline-focus", `${key}:menu`); + head.addEventListener("contextmenu", (event) => { + event.preventDefault(); + menu(event); + }); +} + +function renderFiles( + parent: HTMLElement, + owner: string, + all: TimelineFileRow[] | null, + ctx: CardContext, +): void { + const list = parent.createDiv({ cls: "mdsync-timeline-file-list" }); + const files = all?.filter((file) => + file.path.toLowerCase().includes(ctx.query), + ); + if (!files || files.length === 0) { + list.createDiv({ + cls: "mdsync-status-line", + text: files + ? "No file changes here." + : "The change record for this push is unavailable.", + }); + return; + } + const pager = ctx.pager(owner); + for (const file of pager.slice(files)) renderFile(list, owner, file, ctx); + pager.render(list, files.length, ctx.rerender); +} + +function renderFile( + parent: HTMLElement, + owner: string, + file: TimelineFileRow, + ctx: CardContext, +): void { + const key = JSON.stringify([owner, file.path]); + const item = parent.createDiv({ + cls: "mdsync-file-row mdsync-timeline-file", + }); + item.toggleClass("is-deleted", file.action === "delete"); + item.setAttr("data-timeline-focus", key); + item.toggleClass("is-active", ctx.selected === key); + item.toggleClass("is-opening", ctx.opening === key); + if (ctx.selected === key) item.setAttr("aria-current", "true"); + if (ctx.opening === key) item.setAttr("aria-busy", "true"); + // Before makeActivatable: the hold has to swallow its own trailing click. + onLongPress(item, (event) => ctx.fileMenu(event, owner, file)); + makeActivatable(item, file.path, () => ctx.openFile(owner, file)); + renderPath(item, file.path); + // What a change moved; an addition, a deletion or an even change shows its size. + if (file.sizeDelta) renderDelta(item, file.sizeDelta, "mdsync-timeline-size"); + else + item.createSpan({ + cls: "mdsync-timeline-size", + text: formatBytes(file.size), + }); + item.createSpan({ + cls: `mdsync-file-status ${STATUS_CLASSES[file.action]}`, + text: STATUS_LETTERS[file.action], + }); + const actions = item.createDiv({ cls: "mdsync-timeline-actions" }); + const more = appendIconButton( + actions, + "ellipsis", + `Actions for ${file.path}`, + (event) => { + event.stopPropagation(); + ctx.fileMenu(event, owner, file); + }, + ); + more.setAttr("data-timeline-focus", `${key}:menu`); + item.addEventListener("contextmenu", (event) => { + event.preventDefault(); + ctx.fileMenu(event, owner, file); + }); +} diff --git a/packages/plugin/src/features/source-control/timeline/session-rows.ts b/packages/plugin/src/features/source-control/timeline/session-rows.ts new file mode 100644 index 00000000..744ab652 --- /dev/null +++ b/packages/plugin/src/features/source-control/timeline/session-rows.ts @@ -0,0 +1,115 @@ +import { + formatDay, + formatTimestamp, + pluralize, + startOfWeek, +} from "@/core/shared"; +import type { Resolution, SnapshotSummary } from "@/features/sync"; +import { deviceText } from "../changes/row-formatter"; +import { type Session, sessionsOf } from "./sessions"; +import { + buildTimelineRows, + type ChangeSummary, + fileRowsOf, + summaryOf, + type TimelineFileRow, + type TimelineRow, +} from "./timeline-rows"; + +export interface SessionRow extends ChangeSummary { + key: string; + at: number; + firstAt: number; + res: Resolution | null; + pinned: boolean; + title: string; + meta: string; + tooltip: string; + isHead: boolean; + /** Every push kept: the files lead and the pushes wait behind **Show all**. */ + everyPush: boolean; + versions: TimelineRow[]; + files: TimelineFileRow[] | null; +} + +export interface SessionRowOptions { + now?: number; + currentDevice?: { id: string; name: string } | null; +} + +export function buildSessionRows( + snapshots: readonly SnapshotSummary[], + { now = Date.now(), currentDevice = null }: SessionRowOptions = {}, +): SessionRow[] { + return sessionsOf(snapshots, now).map((session) => { + const newest = session.versions[0] as SnapshotSummary; + const label = newest.label?.trim() ?? ""; + const device = deviceText(newest, currentDevice); + const everyPush = (session.res ?? "push") === "push"; + const { changes } = session; + const summary = summaryOf(changes); + // Pins sit apart from their day, so they carry it instead of counts. + const meta = session.pinned + ? [formatDay(session.at, now), label ? device : null] + : [ + everyPush ? null : pluralize(session.versions.length, "version"), + pluralize(session.pushes, "push", "pushes"), + summary.fileCount === null + ? null + : pluralize(summary.fileCount, "file"), + ]; + return { + key: newest.id, + at: session.at, + firstAt: session.firstAt, + res: session.res, + pinned: session.pinned, + title: label || `${device} · ${spanText(session)}`, + meta: meta.filter(Boolean).join(" · "), + tooltip: + session.firstAt === session.at + ? formatTimestamp(session.at) + : `${formatTimestamp(session.firstAt)} – ${formatTimestamp(session.at)}`, + ...summary, + isHead: session.versions.some((version) => version.isHead), + everyPush, + versions: buildTimelineRows(session.versions, now), + get files() { + return changes ? fileRowsOf(changes, session.at) : null; + }, + }; + }); +} + +/** A version touched a path containing `query`, lowercase. */ +export function touches(row: TimelineRow, query: string): boolean { + const { changes } = row; + if (!changes) return false; + return [changes.added, changes.modified, changes.deleted].some((group) => + Object.keys(group).some((path) => path.toLowerCase().includes(query)), + ); +} + +/** "08:40 – 12:10", or the days or weeks a packed session spans. */ +function spanText({ firstAt, at, res }: Session): string { + if (res === "1w") + return range({ day: "numeric", month: "short" }, startOfWeek(firstAt), at); + if (res === "1d") + return range( + { weekday: "short", day: "numeric", month: "short" }, + firstAt, + at, + ); + return range({ hour: "2-digit", minute: "2-digit" }, firstAt, at); +} + +function range( + options: Intl.DateTimeFormatOptions, + from: number, + to: number, +): string { + return new Intl.DateTimeFormat(undefined, options).formatRange( + Math.min(from, to), + to, + ); +} diff --git a/packages/plugin/src/features/source-control/timeline/sessions.ts b/packages/plugin/src/features/source-control/timeline/sessions.ts new file mode 100644 index 00000000..ff60ebfd --- /dev/null +++ b/packages/plugin/src/features/source-control/timeline/sessions.ts @@ -0,0 +1,99 @@ +import { + composeChanges, + keepSize, + type Resolution, + type SnapshotChanges, + type SnapshotSummary, +} from "@/features/sync"; +import { ageLabel } from "../history/age-groups"; + +/** Pushes further apart than this, or than one kept period, start a new sitting. */ +const SESSION_GAP_MS = 10 * 60_000; + +export interface Session { + /** Newest first, as the walk lists them. */ + versions: SnapshotSummary[]; + at: number; + firstAt: number; + res: Resolution | null; + pinned: boolean; + pushes: number; + /** From the oldest version's parent to the newest version; null when a version has no record. */ + changes: SnapshotChanges | null; +} + +/** + * Splits the walk into sittings: consecutive versions of one device and resolution under one heading, each + * close to the next. A pin stands alone, so a session never skips a link of the chain it composes. + */ +export function sessionsOf( + versions: readonly SnapshotSummary[], + now: number = Date.now(), +): Session[] { + const runs: SnapshotSummary[][] = []; + for (const version of listed(versions)) { + const run = runs[runs.length - 1]; + const newer = run?.[run.length - 1]; + if (run && newer && continues(newer, version, now)) run.push(version); + else runs.push([version]); + } + return runs.map(sessionOf); +} + +/** A version that changed only what history leaves out (the configuration folder) is not listed. */ +function listed(versions: readonly SnapshotSummary[]): SnapshotSummary[] { + const shown = versions.filter( + ({ pinned, files }) => + pinned || + !files || + Object.keys({ ...files.added, ...files.modified, ...files.deleted }) + .length > 0, + ); + // Everything above the newest shown version changed no vault file, so it still holds what HEAD does; an + // off-walk pin (no files) is another state. + const [newest] = shown; + if (newest?.files && newest !== versions[0] && versions[0]?.isHead) + shown[0] = { ...newest, isHead: true }; + return shown; +} + +function continues( + newer: SnapshotSummary, + older: SnapshotSummary, + now: number, +): boolean { + if (newer.pinned || older.pinned) return false; + if (newer.deviceId !== older.deviceId || newer.res !== older.res) + return false; + const gap = Math.max(SESSION_GAP_MS, (older.res && keepSize(older.res)) ?? 0); + return ( + newer.firstAt - older.at < gap && + ageLabel(newer, now) === ageLabel(older, now) + ); +} + +function sessionOf(versions: SnapshotSummary[]): Session { + const newest = versions[0] as SnapshotSummary; + const oldest = versions[versions.length - 1] as SnapshotSummary; + return { + versions, + at: newest.at, + firstAt: oldest.firstAt, + res: newest.res, + pinned: newest.pinned, + pushes: versions.reduce((sum, version) => sum + version.pushes, 0), + changes: composed(versions), + }; +} + +function composed( + versions: readonly SnapshotSummary[], +): SnapshotChanges | null { + if (versions.length === 1) return versions[0]?.files ?? null; + const run: SnapshotChanges[] = []; + for (const version of [...versions].reverse()) { + if (!version.files) return null; + run.push(version.files); + } + return composeChanges(run); +} diff --git a/packages/plugin/src/ui/source-control/snapshot-menu.ts b/packages/plugin/src/features/source-control/timeline/snapshot-menu.ts similarity index 77% rename from packages/plugin/src/ui/source-control/snapshot-menu.ts rename to packages/plugin/src/features/source-control/timeline/snapshot-menu.ts index c0bd79d0..0f7969c0 100644 --- a/packages/plugin/src/ui/source-control/snapshot-menu.ts +++ b/packages/plugin/src/features/source-control/timeline/snapshot-menu.ts @@ -1,17 +1,18 @@ import type { Menu } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import { notifyError, notifyInfo } from "@/ui/common"; -import { openPromptModal } from "@/ui/modals"; +import { notifyError, notifyInfo, openPromptModal } from "@/core/ui"; +import type { SourceControlHost } from "../host"; interface SnapshotPin { snapshotId: string; pinned: boolean; label: string; + /** A file of the snapshot's space, from its History; the vault's without one. */ + path?: string; } export function addSnapshotPinItems( menu: Menu, - plugin: PluginHost, + plugin: SourceControlHost, snapshot: SnapshotPin, onChanged: () => void, canPin = true, @@ -22,9 +23,10 @@ export function addSnapshotPinItems( snapshot.snapshotId, pinned, label, + snapshot.path, ); onChanged(); - notifyInfo(pinned ? "Snapshot pinned." : "Snapshot unpinned."); + notifyInfo(pinned ? "Version pinned." : "Version unpinned."); } catch (error) { notifyError("Could not update pin", error); } @@ -32,7 +34,7 @@ export function addSnapshotPinItems( if (!snapshot.pinned) { menu.addItem((item) => item - .setTitle("Pin this snapshot") + .setTitle("Pin this version") .setIcon("pin") .setDisabled(!canPin) .onClick(() => void update(true)), diff --git a/packages/plugin/src/ui/source-control/timeline-actions.ts b/packages/plugin/src/features/source-control/timeline/timeline-actions.ts similarity index 67% rename from packages/plugin/src/ui/source-control/timeline-actions.ts rename to packages/plugin/src/features/source-control/timeline/timeline-actions.ts index 5ab7861b..ceaa97d3 100644 --- a/packages/plugin/src/ui/source-control/timeline-actions.ts +++ b/packages/plugin/src/features/source-control/timeline/timeline-actions.ts @@ -1,8 +1,8 @@ import { Menu } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import { notifyError, notifyInfo } from "@/ui/common"; -import { openConfirmModal } from "@/ui/modals"; -import { confirmRestore } from "./restore-modal"; +import { notifyError, notifyInfo, openConfirmModal } from "@/core/ui"; +import type { SourceControlHost } from "../host"; +import { confirmAndRestoreFile } from "../restore-file"; +import type { SessionRow } from "./session-rows"; import { addSnapshotPinItems } from "./snapshot-menu"; import { describeRestorePlan, @@ -13,22 +13,39 @@ import { export class TimelineActions { constructor( - private readonly plugin: PluginHost, + private readonly plugin: SourceControlHost, private readonly refresh: () => void, private readonly openFile: ( - row: TimelineRow, + owner: string, file: TimelineFileRow, mode: "current" | "change", ) => void, ) {} - showSnapshotMenu(event: MouseEvent, row: TimelineRow): void { + /** A session acts through its newest version: pinning it, or the vault as the session left it. */ + showSessionMenu(event: MouseEvent, session: SessionRow): void { + const newest = session.versions[0]; + if (newest) + this.showVersionMenu( + event, + newest, + session.versions.length > 1 + ? "Restore vault to end of session…" + : undefined, + ); + } + + showVersionMenu( + event: MouseEvent, + row: TimelineRow, + restoreTitle = "Restore vault to this version…", + ): void { const menu = new Menu(); addSnapshotPinItems(menu, this.plugin, row, this.refresh, row.restorable); menu.addSeparator(); menu.addItem((item) => item - .setTitle("Restore vault to this snapshot…") + .setTitle(restoreTitle) .setIcon("rotate-ccw") .setDisabled(!row.restorable) .onClick(() => void this.restoreVault(row)), @@ -36,23 +53,19 @@ export class TimelineActions { menu.showAtMouseEvent(event); } - showFileMenu( - event: MouseEvent, - row: TimelineRow, - file: TimelineFileRow, - ): void { + showFileMenu(event: MouseEvent, owner: string, file: TimelineFileRow): void { const menu = new Menu(); menu.addItem((item) => item .setTitle("Compare with current") .setIcon("git-compare") - .onClick(() => this.openFile(row, file, "current")), + .onClick(() => this.openFile(owner, file, "current")), ); menu.addItem((item) => item - .setTitle("Show changes in this push") + .setTitle("Show changes") .setIcon("history") - .onClick(() => this.openFile(row, file, "change")), + .onClick(() => this.openFile(owner, file, "change")), ); menu.addSeparator(); menu.addItem((item) => @@ -69,22 +82,11 @@ export class TimelineActions { } async restoreFile(file: TimelineFileRow): Promise { - const confirmed = await confirmRestore({ - plugin: this.plugin, - path: file.path, - target: file.path, - version: file.version, - }); - if (!confirmed) return; - try { - await this.plugin.controller.history.restoreFileVersion( - file.path, - file.version.hash, - ); - notifyInfo("Restored. Review and push the change when ready."); - } catch (error) { - notifyError("Restore failed", error); - } + await confirmAndRestoreFile( + this.plugin, + { path: file.path, target: file.path, version: file.version }, + "Restored. Review and push the change when ready.", + ); } private async restoreVault(row: TimelineRow): Promise { @@ -99,7 +101,7 @@ export class TimelineActions { } const confirmed = await openConfirmModal({ app: this.plugin.app, - title: `Restore the vault to ${row.title}?`, + title: `Restore the vault to ${row.label || row.tooltip}?`, body: [ ...(moved ? ["The vault changed while you decided. Here is the new plan."] diff --git a/packages/plugin/src/ui/source-control/timeline-rows.ts b/packages/plugin/src/features/source-control/timeline/timeline-rows.ts similarity index 64% rename from packages/plugin/src/ui/source-control/timeline-rows.ts rename to packages/plugin/src/features/source-control/timeline/timeline-rows.ts index becf5075..babcb72a 100644 --- a/packages/plugin/src/ui/source-control/timeline-rows.ts +++ b/packages/plugin/src/features/source-control/timeline/timeline-rows.ts @@ -1,15 +1,15 @@ -import { formatRelativeTime, formatTimestamp, pluralize } from "@/shared"; +import { formatTimestamp, pluralize } from "@/core/shared"; +import type { HistoryDiffTarget } from "@/features/diff"; import type { + ChangeAction, + HistoryVersionRef, + ManifestEntry, + Resolution, SnapshotChanges, SnapshotSummary, VaultRestorePlan, -} from "@/sync/history"; -import type { HistoryVersionRef } from "@/sync/projection"; -import type { ManifestEntry } from "@/sync/types"; -import type { ChangeAction } from "@/ui/common"; -import type { HistoryDiffTarget } from "@/ui/source-control-view"; -import { timeInDay } from "./day-groups"; -import { deviceText } from "./row-formatter"; +} from "@/features/sync"; +import { ageTitle, lastOf } from "../history/age-groups"; export interface TimelineFileRow { path: string; @@ -23,73 +23,82 @@ export interface TimelineFileRow { sizeDelta?: number; } -export interface TimelineRow { - snapshotId: string; - createdAt: number; - title: string; - meta: string; - tooltip: string; +/** What a card says of its changes; all null without a change record. */ +export interface ChangeSummary { counts: string | null; - /** Files per kind of change, the non-zero ones; null without a change record. */ + /** Files per kind of change, the non-zero ones. */ tally: Array<[ChangeAction, number]> | null; - /** Net bytes the push moved, signed. Null when it moved none, or is unknown. */ + /** Net bytes moved, signed; null when none moved. */ netDelta: number | null; + fileCount: number | null; +} + +/** One version: a push, or the last push of a period. */ +export interface TimelineRow extends ChangeSummary { + snapshotId: string; + at: number; + res: Resolution | null; + title: string; + /** "last of 3 pushes" where the version stands for several. */ + meta: string | null; + tooltip: string; pinned: boolean; isHead: boolean; restorable: boolean; label: string; + changes: SnapshotChanges | null; files: TimelineFileRow[] | null; } -export interface TimelineRowOptions { - now?: number; - currentDevice?: { id: string; name: string } | null; -} - export function buildTimelineRows( snapshots: readonly SnapshotSummary[], - options: TimelineRowOptions = {}, + now: number = Date.now(), ): TimelineRow[] { - const now = options.now ?? Date.now(); return snapshots.map((snapshot) => { - const relative = formatRelativeTime(snapshot.createdAt, now); const label = snapshot.label?.trim() ?? ""; - const device = deviceText(snapshot, options.currentDevice); + const changes = snapshot.files; return { snapshotId: snapshot.id, - createdAt: snapshot.createdAt, - title: - label || - (snapshot.pinned ? relative : timeInDay(snapshot.createdAt, now)), - // A pin's name replaces the age in the title, and pins sit apart from their day. - meta: label ? `${relative} · ${device}` : device, - tooltip: formatTimestamp(snapshot.createdAt), - counts: countsText(snapshot), - tally: snapshot.files ? tallyOf(snapshot.files) : null, - netDelta: (snapshot.files && netBytes(snapshot.files)) || null, + at: snapshot.at, + res: snapshot.res, + title: label || ageTitle(snapshot, now), + meta: lastOf(snapshot.pushes), + tooltip: formatTimestamp(snapshot.at), + ...summaryOf(changes), pinned: snapshot.pinned, isHead: snapshot.isHead, restorable: snapshot.restorable, label, + changes, // Only expanded cards read it, so the rows of a collapsed push are never built. get files() { - return snapshot.files - ? fileRowsOf(snapshot.files, snapshot.createdAt) - : null; + return changes ? fileRowsOf(changes, snapshot.at) : null; }, }; }); } +export function summaryOf(changes: SnapshotChanges | null): ChangeSummary { + if (!changes) + return { counts: null, tally: null, netDelta: null, fileCount: null }; + const tally = tallyOf(changes); + return { + counts: tallyText(tally), + tally, + netDelta: netBytes(changes) || null, + fileCount: tally.reduce((sum, [, count]) => sum + count, 0), + }; +} + const fileRowCache = new WeakMap(); -function fileRowsOf( +export function fileRowsOf( changes: SnapshotChanges, - createdAt: number, + at: number, ): TimelineFileRow[] { let rows = fileRowCache.get(changes); if (!rows) { - rows = buildFileRows(changes, createdAt); + rows = buildFileRows(changes, at); fileRowCache.set(changes, rows); } return rows; @@ -97,11 +106,12 @@ function fileRowsOf( function buildFileRows( changes: SnapshotChanges, - createdAt: number, + at: number, ): TimelineFileRow[] { const rows: TimelineFileRow[] = []; + const stamp = formatTimestamp(at); for (const [path, entry] of Object.entries(changes.added)) { - const after = versionRef(entry, createdAt, "after push"); + const after = versionRef(entry, stamp, "after push"); rows.push({ path, action: "add", @@ -112,8 +122,8 @@ function buildFileRows( }); } for (const [path, change] of Object.entries(changes.modified)) { - const before = versionRef(change.from, createdAt, "before push"); - const after = versionRef(change.to, createdAt, "after push"); + const before = versionRef(change.from, stamp, "before push"); + const after = versionRef(change.to, stamp, "after push"); rows.push({ path, action: "modify", @@ -125,14 +135,20 @@ function buildFileRows( }); } for (const [path, entry] of Object.entries(changes.deleted)) { - const before = versionRef(entry, createdAt, "before push"); + // A merged record keeps the parent's entry for replay; the content right before the deletion is `deletedLast`. + const last = + (changes.deletedLast && + Object.hasOwn(changes.deletedLast, path) && + changes.deletedLast[path]) || + entry; + const before = versionRef(last, stamp, "before push"); rows.push({ path, action: "delete", version: before, before, after: null, - size: entry.size, + size: last.size, }); } return rows.sort((a, b) => a.path.localeCompare(b.path)); @@ -150,13 +166,13 @@ function netBytes(changes: SnapshotChanges): number { function versionRef( entry: ManifestEntry, - createdAt: number, + stamp: string, suffix: string, ): HistoryVersionRef { return { hash: entry.hash, size: entry.size, - label: `${formatTimestamp(createdAt)} (${suffix})`, + label: `${stamp} (${suffix})`, }; } @@ -170,11 +186,12 @@ function tallyOf(changes: SnapshotChanges): Array<[ChangeAction, number]> { } /** "+3 new · 2 changed · 1 removed", dropping the parts that are zero. */ -export function countsText(snapshot: SnapshotSummary): string | null { - if (!snapshot.files) return null; - const parts = tallyOf(snapshot.files).map(([action, count]) => - COUNT_WORDS[action](count), - ); +export function countsText(changes: SnapshotChanges | null): string | null { + return changes ? tallyText(tallyOf(changes)) : null; +} + +function tallyText(tally: ReadonlyArray<[ChangeAction, number]>): string { + const parts = tally.map(([action, count]) => COUNT_WORDS[action](count)); return parts.length > 0 ? parts.join(" · ") : "no file changes"; } @@ -188,20 +205,10 @@ export function timelineDiffTarget( file: TimelineFileRow, mode: "current" | "change" = "current", ): HistoryDiffTarget { - if (mode === "change") { - return { - hash: file.version.hash, - label: file.version.label, - size: file.version.size, - change: { before: file.before, after: file.after }, - }; - } - return { - hash: file.version.hash, - label: file.version.label, - size: file.version.size, - previewIfMissing: true, - }; + const { hash, label, size } = file.version; + return mode === "change" + ? { hash, label, size, change: { before: file.before, after: file.after } } + : { hash, label, size }; } /** Lines for the confirmation, ordered so the destructive count is not buried. */ diff --git a/packages/plugin/src/features/source-control/timeline/timeline-tab.ts b/packages/plugin/src/features/source-control/timeline/timeline-tab.ts new file mode 100644 index 00000000..5152d5e9 --- /dev/null +++ b/packages/plugin/src/features/source-control/timeline/timeline-tab.ts @@ -0,0 +1,477 @@ +import { SearchComponent, setIcon } from "obsidian"; +import { formatDay, pluralize, startOfDay } from "@/core/shared"; +import { + appendIconButton, + appendLabeledButton, + callout, + makeActivatable, + notifyError, +} from "@/core/ui"; +import type { HistoryDiffTarget } from "@/features/diff"; +import { + type ActivityCalendar, + buildCalendar, + type CalendarDay, + renderActivityCalendar, + type SnapshotListResult, +} from "@/features/sync"; +import { ageTitle, groupByAge, inLastHour } from "../history/age-groups"; +import { HistoryList } from "../history/history-list"; +import { RowPager } from "../history/row-pager"; +import type { SourceControlHost } from "../host"; +import { renderAgeHeader } from "../row-parts"; +import { + renderEmptyState, + renderHistoryOff, + renderLoadError, + renderLoading, +} from "../tab-states"; +import { type CardContext, renderSessionCard } from "./session-card"; +import { buildSessionRows, type SessionRow, touches } from "./session-rows"; +import { TimelineActions } from "./timeline-actions"; +import { type TimelineFileRow, timelineDiffTarget } from "./timeline-rows"; + +export class TimelineTab { + private readonly snapshots = new HistoryList(() => { + const loaded = this.snapshots.value; + if (loaded) this.prune(loaded); + this.onRerender(); + }); + private openGeneration = 0; + private readonly open = new Set(); + private readonly pages = new Map(); + /** Rows survive UI-only rerenders, so composed changes keep the identity the file-row cache is keyed by. */ + private sessionMemo: { + snapshots: SnapshotListResult["snapshots"]; + key: string; + rows: SessionRow[]; + } | null = null; + /** The calendar scans every snapshot per day, so UI-only rerenders reuse it until the result or the day changes. */ + private calendarMemo: { + result: SnapshotListResult; + today: number; + calendar: ActivityCalendar; + } | null = null; + private query = ""; + private sessionPager = new RowPager(); + /** What the session pager counts pages of: another result, filter or day starts it over. */ + private pagedFor: { + result: SnapshotListResult; + query: string; + day: number | null; + } | null = null; + private picked: CalendarDay | null = null; + private activityOpen = true; + private selected: string | null = null; + private opening: string | null = null; + private list: HTMLElement | null = null; + /** Typing redraws only the list, so the filter keeps its focus and an IME its composition. */ + private redrawSessions: () => void = () => {}; + private scrollTop = 0; + private focusKey: string | null = null; + private readonly actions: TimelineActions; + + constructor( + private readonly plugin: SourceControlHost, + private readonly onRerender: () => void, + private readonly openDiff: ( + path: string, + history: HistoryDiffTarget, + ) => Promise, + onSnapshotsChanged: () => void, + ) { + this.actions = new TimelineActions( + plugin, + onSnapshotsChanged, + (owner, file, mode) => void this.openFile(owner, file, mode), + ); + } + + captureState(): void { + if ( + !this.list?.isConnected || + this.list.hasClass("is-loading") || + !this.snapshots.value + ) + return; + this.scrollTop = this.list.scrollTop; + const active = this.list.ownerDocument.activeElement; + this.focusKey = + active && this.list.contains(active) + ? active.getAttribute("data-timeline-focus") + : null; + } + + clear(): void { + this.captureState(); + this.snapshots.clear(); + } + + clearOffline(): boolean { + if (!this.snapshots.offline) return false; + this.clear(); + return true; + } + + dispose(): void { + this.snapshots.clear(); + this.openGeneration++; + this.list = null; + this.redrawSessions = () => {}; + } + + render(parent: HTMLElement, tools: HTMLElement): void { + const pane = parent.createDiv({ + cls: "mdsync-history-pane mdsync-timeline", + }); + if (!this.plugin.settings.fileHistoryEnabled) { + renderHistoryOff( + pane, + this.plugin, + "The timeline shows what each push changed, day by day. It starts with the next push.", + this.onRerender, + ); + return; + } + appendIconButton(tools, "refresh-cw", "Refresh timeline", () => + this.reload(), + ); + this.list = pane.createDiv({ + cls: "mdsync-history-list mdsync-timeline-list", + }); + this.list.toggleClass("is-loading", this.snapshots.value === null); + this.renderBody(this.list); + if (!this.snapshots.value) return; + this.list.scrollTop = this.scrollTop; + if (this.focusKey) { + const target = Array.from( + this.list.querySelectorAll("[data-timeline-focus]"), + ).find((el) => el.getAttribute("data-timeline-focus") === this.focusKey); + target?.focus({ preventScroll: true }); + this.focusKey = null; + } + } + + private reload(): void { + this.clear(); + this.onRerender(); + } + + private renderBody(body: HTMLElement): void { + const { value: result, error } = this.snapshots; + if (error) { + renderLoadError(body, "Could not load the timeline", error, () => + this.reload(), + ); + return; + } + if (!result) { + renderLoading(body); + this.snapshots.load(() => this.plugin.controller.history.listSnapshots()); + return; + } + if (result.lagging) { + callout( + body, + "warning", + "History has not caught up with the latest push yet, so the newest version is missing.", + ); + } + const rows = this.sessionRows(result); + // A packed version whose changes cancel out is no row, yet its pushes are activity. + const empty = rows.length === 0 && !Object.keys(result.activity).length; + if (empty && !result.lagging) { + renderEmptyState(body, { + icon: "clock-3", + title: "No pushes yet", + text: "No pushes recorded yet. The timeline fills up as you push.", + }); + return; + } + // Built while hidden too: a day picked in settings filters by it. + const calendar = this.calendarOf(result); + // A reload may have thinned the picked day, or moved it off the calendar. + const picked = this.picked?.start; + this.picked = + calendar.weeks + .flatMap((week) => week.days) + .find((day) => day.start === picked) ?? null; + if (this.plugin.settings.fileHistoryActivity) + this.renderActivity(body, calendar); + this.renderFilter(body); + const sessions = body.createDiv({ cls: "mdsync-timeline-sessions" }); + this.redrawSessions = () => { + sessions.empty(); + this.renderSessions(sessions, rows, result, calendar); + }; + this.redrawSessions(); + } + + private calendarOf(result: SnapshotListResult): ActivityCalendar { + const today = startOfDay(Date.now()); + if ( + this.calendarMemo?.result !== result || + this.calendarMemo.today !== today + ) + this.calendarMemo = { + result, + today, + calendar: buildCalendar(result.activity, result.snapshots), + }; + return this.calendarMemo.calendar; + } + + private sessionRows({ snapshots }: SnapshotListResult): SessionRow[] { + const currentDevice = this.plugin.controller.currentDevice(); + const now = Date.now(); + // Sessions and titles read the clock: the minute, and each push's own hour mark. + const key = JSON.stringify([ + Math.floor(now / 60_000), + snapshots.filter(({ at }) => inLastHour(at, now)).length, + currentDevice.id, + currentDevice.name, + ]); + if ( + this.sessionMemo?.snapshots !== snapshots || + this.sessionMemo.key !== key + ) + this.sessionMemo = { + snapshots, + key, + rows: buildSessionRows(snapshots, { currentDevice }), + }; + return this.sessionMemo.rows; + } + + private renderActivity(body: HTMLElement, calendar: ActivityCalendar): void { + const card = body.createDiv({ cls: "mdsync-timeline-activity" }); + const head = card.createDiv({ cls: "mdsync-timeline-activity-head" }); + head.setAttr("aria-expanded", String(this.activityOpen)); + head.setAttr("data-timeline-focus", "activity"); + makeActivatable(head, "Activity", () => { + this.activityOpen = !this.activityOpen; + this.onRerender(); + }); + setIcon( + head.createSpan({ cls: "mdsync-timeline-icon" }), + this.activityOpen ? "chevron-down" : "chevron-right", + ); + head.createSpan({ + cls: "mdsync-timeline-activity-title", + text: "Activity", + }); + head.createSpan({ + cls: "mdsync-timeline-activity-sum", + text: `${pluralize(calendar.pushes, "push", "pushes")} since ${formatDay(calendar.since, Date.now(), false)}`, + }); + if (!this.activityOpen) return; + renderActivityCalendar(card, calendar, { + picked: this.picked?.start ?? null, + onPick: (day) => { + this.picked = this.picked?.start === day.start ? null : day; + this.onRerender(); + }, + }); + // A pick redraws the pane; the focus follows the day. + card.querySelectorAll("[data-day]").forEach((cell) => { + cell.setAttr("data-timeline-focus", `day:${cell.dataset.day}`); + }); + } + + private renderFilter(body: HTMLElement): void { + const bar = body.createDiv({ cls: "mdsync-timeline-filter" }); + const search = new SearchComponent(bar) + .setPlaceholder("Filter by path or folder") + .setValue(this.query); + search.inputEl.setAttr("aria-label", "Filter pushes by path"); + search.inputEl.setAttr("data-timeline-focus", "filter"); + search.onChange((value) => { + this.query = value; + this.redrawSessions(); + }); + if (!this.picked) return; + const chip = bar.createSpan({ cls: "mdsync-timeline-day-chip" }); + chip.createSpan({ text: formatDay(this.picked.start) }); + appendIconButton(chip, "x", "Show every day", () => { + this.picked = null; + this.onRerender(); + }); + } + + private renderSessions( + el: HTMLElement, + rows: readonly SessionRow[], + result: SnapshotListResult, + calendar: ActivityCalendar, + ): void { + const picked = this.picked; + const query = this.query.trim().toLowerCase(); + const pager = this.pagerFor(result, query, picked?.start ?? null); + if (picked?.res === "counts") { + this.renderCountsDay(el, picked, result, calendar); + return; + } + const day = picked && new Date(picked.start); + // From the date, never by adding a day to the start: a DST switch can skip the midnight. + const dayEnd = + day && new Date(day.getFullYear(), day.getMonth(), day.getDate() + 1); + const shown = rows.filter( + (row) => + (!query || row.versions.some((version) => touches(version, query))) && + (!dayEnd || row.firstAt < dayEnd.getTime()), + ); + if (shown.length === 0 && query) { + renderEmptyState(el, { + icon: "search-x", + tone: "muted", + title: `No pushes touch ${this.query.trim()}`, + text: result.truncated + ? "Nothing under this path changed in the history that can be read." + : "Nothing under this path changed in the kept history.", + action: { text: "Clear filter", run: () => this.clearQuery() }, + }); + } + const ctx = this.cardContext(query); + // Pinned lead, as groupByAge orders them, so a page break never splits the pinned group. + const ordered = [ + ...shown.filter((row) => row.pinned), + ...shown.filter((row) => !row.pinned), + ]; + for (const group of groupByAge(pager.slice(ordered))) { + renderAgeHeader(el, group); + for (const row of group.rows) renderSessionCard(el, row, ctx); + } + pager.render(el, ordered.length, () => { + this.redrawSessions(); + // The button sat at the foot of the old page; the next one reads from its top. + el.scrollIntoView({ block: "start" }); + }); + if (result.truncated) + callout( + el, + "warning", + "A push record is missing, so the versions before it are hidden.", + "Older history is out of reach", + ); + } + + private pagerFor( + result: SnapshotListResult, + query: string, + day: number | null, + ): RowPager { + const paged = this.pagedFor; + if ( + paged?.result !== result || + paged.query !== query || + paged.day !== day + ) { + this.sessionPager = new RowPager(); + this.pagedFor = { result, query, day }; + } + return this.sessionPager; + } + + /** Past the horizon a day kept only its counts; the nearest version is the oldest still walked. */ + private renderCountsDay( + el: HTMLElement, + day: CalendarDay, + result: SnapshotListResult, + calendar: ActivityCalendar, + ): void { + const card = el.createDiv({ cls: "mdsync-timeline-counts" }); + const title = card.createDiv({ cls: "mdsync-timeline-counts-title" }); + setIcon(title.createSpan(), "bar-chart-2"); + title.createSpan({ + text: `${formatDay(day.start)}: ${pluralize(day.pushes, "push", "pushes")}`, + }); + const nearest = result.snapshots.filter((version) => version.res).pop(); + card.createDiv({ + cls: "mdsync-history-row-meta", + text: nearest + ? `Only counts are kept for this day. The nearest version is from ${ageTitle(nearest)}.` + : "Only counts are kept for this day.", + }); + const start = nearest && startOfDay(nearest.at); + const target = calendar.weeks + .flatMap((week) => week.days) + .find((candidate) => candidate.start === start); + if (!target) return; + appendLabeledButton(card, "arrow-right", "Show nearest version", () => { + this.picked = target; + this.onRerender(); + }); + } + + /** Fresh history from the top; the day is rebound to the calendar's own once it loads. */ + showDay(start: number): void { + this.snapshots.clear(); + this.picked = { start, pushes: 0, level: 0, res: null }; + this.query = ""; + this.scrollTop = 0; + this.focusKey = null; + } + + private clearQuery(): void { + this.query = ""; + this.onRerender(); + } + + private cardContext(query: string): CardContext { + return { + query, + selected: this.selected, + opening: this.opening, + isOpen: (key) => this.open.has(key), + toggle: (key) => { + if (!this.open.delete(key)) this.open.add(key); + this.onRerender(); + }, + pager: (key) => { + let pager = this.pages.get(key); + if (!pager) { + pager = new RowPager(); + this.pages.set(key, pager); + } + return pager; + }, + rerender: this.onRerender, + sessionMenu: (event, row) => this.actions.showSessionMenu(event, row), + versionMenu: (event, row) => this.actions.showVersionMenu(event, row), + fileMenu: (event, owner, file) => + this.actions.showFileMenu(event, owner, file), + openFile: (owner, file) => void this.openFile(owner, file), + }; + } + + /** Rows gone from the new list take their open state with them. */ + private prune({ snapshots }: SnapshotListResult): void { + const ids = new Set(snapshots.map((row) => row.id)); + // Keys are an id, or an id after a "v:", "all:" or "versions:" prefix. + const live = (key: string) => ids.has(key.slice(key.indexOf(":") + 1)); + for (const key of this.open) if (!live(key)) this.open.delete(key); + for (const key of this.pages.keys()) if (!live(key)) this.pages.delete(key); + } + + private async openFile( + owner: string, + file: TimelineFileRow, + mode: "current" | "change" = "current", + ): Promise { + const generation = ++this.openGeneration; + this.selected = JSON.stringify([owner, file.path]); + this.opening = this.selected; + this.onRerender(); + try { + await this.openDiff(file.path, timelineDiffTarget(file, mode)); + } catch (error) { + if (generation === this.openGeneration) + notifyError("Could not open historical file", error); + } finally { + if (generation === this.openGeneration) { + this.opening = null; + this.onRerender(); + } + } + } +} diff --git a/packages/plugin/src/styles/source-control/timeline.css b/packages/plugin/src/features/source-control/timeline/timeline.css similarity index 65% rename from packages/plugin/src/styles/source-control/timeline.css rename to packages/plugin/src/features/source-control/timeline/timeline.css index 942a8485..4085bb03 100644 --- a/packages/plugin/src/styles/source-control/timeline.css +++ b/packages/plugin/src/features/source-control/timeline/timeline.css @@ -231,22 +231,137 @@ height: var(--mdsync-icon); } -.mdsync-diff-preview-header { +/* The resolution chip sits after the rule that fills the header. */ +.mdsync-timeline-res { + order: 2; + padding: 0 var(--size-4-1); + border: 1px solid var(--background-modifier-border); + border-radius: var(--mdsync-radius-pill); + font-weight: var(--font-normal); + text-transform: none; + letter-spacing: 0; +} + +.mdsync-timeline-day::after { + order: 1; +} + +.mdsync-timeline-activity { + flex: 0 0 auto; padding: var(--size-4-2); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); + background: var(--background-primary); +} + +.mdsync-timeline-activity-head { + display: flex; + align-items: center; + gap: var(--size-4-1); + margin-bottom: var(--size-4-1); + cursor: pointer; +} + +.mdsync-timeline-activity-title { + font-weight: var(--font-semibold); +} + +.mdsync-timeline-activity-sum { + margin-left: auto; color: var(--text-muted); font-size: var(--font-ui-smaller); } -.mdsync-diff-preview-body { +.mdsync-timeline-filter { + display: flex; + flex: 0 0 auto; + align-items: center; + gap: var(--size-4-2); +} + +.mdsync-timeline-filter .search-input-container { flex: 1; - min-height: 0; - overflow: hidden; + min-width: 0; +} + +.mdsync-timeline-day-chip { + display: inline-flex; + flex: 0 0 auto; + align-items: center; + gap: var(--size-2-1); + padding-left: var(--size-4-2); + border-radius: var(--mdsync-radius-pill); + background: var(--background-modifier-hover); + font-size: var(--font-ui-smaller); +} + +.mdsync-timeline-sessions { + display: flex; + flex-direction: column; + gap: var(--size-2-2); +} + +.mdsync-timeline-caption { + padding: var(--size-2-2) 0; + color: var(--text-faint); + font-size: var(--font-ui-smaller); +} + +/* A version inside a session: a lighter card head, its files under it. */ +.mdsync-timeline-version .mdsync-timeline-head { + padding: var(--size-2-1) 6px var(--size-2-1) var(--size-2-2); +} + +/* One line: time, chips, size. */ +.mdsync-timeline-version .mdsync-timeline-head .mdsync-timeline-copy { + flex-direction: row; + align-items: center; + gap: 6px; +} + +.mdsync-timeline-version .mdsync-timeline-meta { + flex: 1; + min-width: 0; +} + +.mdsync-timeline-version .mdsync-history-row-title { + font-size: var(--font-ui-small); +} + +body:not(.is-phone) + .mdsync-timeline-version + .mdsync-timeline-actions + .clickable-icon { + padding: var(--size-2-1) var(--size-2-2); +} + +/* A link, not a button: it only unfolds the list. */ +.mdsync-timeline-more.mdsync-labeled-btn { + align-self: flex-start; + margin: var(--size-2-2) 0; + padding: 0; + color: var(--text-accent); + background: transparent; + box-shadow: none; } -.mdsync-diff-preview-body .cm-editor { - height: 100%; +.mdsync-timeline-counts { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: var(--size-4-2); + padding: var(--size-4-3); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); +} + +.mdsync-timeline-counts-title { + display: flex; + align-items: center; + gap: var(--size-4-2); + font-weight: var(--font-semibold); } -.mdsync-diff-preview-body .cm-scroller { - overflow: auto; +.mdsync-timeline-more.mdsync-labeled-btn:hover { + text-decoration: underline; } diff --git a/packages/plugin/src/ui/source-control/trash-rows.ts b/packages/plugin/src/features/source-control/trash/trash-rows.ts similarity index 63% rename from packages/plugin/src/ui/source-control/trash-rows.ts rename to packages/plugin/src/features/source-control/trash/trash-rows.ts index 2b9c0ba9..413675a2 100644 --- a/packages/plugin/src/ui/source-control/trash-rows.ts +++ b/packages/plugin/src/features/source-control/trash/trash-rows.ts @@ -1,6 +1,11 @@ -import { formatBytes, formatRelativeTime, normalizePath } from "@/shared"; -import type { DeletedFile } from "@/sync/history"; -import { deviceText } from "./row-formatter"; +import { + formatBytes, + formatDay, + formatRelativeTime, + normalizePath, +} from "@/core/shared"; +import type { DeletedFile } from "@/features/sync"; +import { deviceText } from "../changes/row-formatter"; export interface TrashRow { path: string; @@ -12,7 +17,7 @@ export interface TrashRow { /** Short enough to head a diff pane: "deleted 3 days ago". */ label: string; meta: string; - /** Back in the vault but unpushed, else how much longer the record survives. */ + /** Back in the vault but unpushed, else how long history keeps it. */ note: TrashNote | null; pinned: boolean; } @@ -23,12 +28,10 @@ export interface TrashNote { icon: string; } -/** Pushes left at which a record's end is worth a colour. */ -const SOON_PUSHES = 3; +/** Time left at which a version's end is worth a colour. */ +const SOON_MS = 7 * 24 * 60 * 60_000; export interface TrashRowOptions { - /** Non-pinned snapshots kept before eviction, from settings. */ - maxSnapshots: number; now?: number; /** Lets rows name this device instead of showing a raw id. */ currentDevice?: { id: string; name: string } | null; @@ -55,10 +58,11 @@ export function buildTrashRows( age, title: file.path, label, + // Size before the device: a narrow pane cuts the end. meta: [ label, - deviceText(file, options.currentDevice), formatBytes(file.entry.size), + deviceText(file, options.currentDevice), ].join(" · "), note: options.inVault?.(file.path) ? { @@ -66,20 +70,17 @@ export function buildTrashRows( tone: "restored", icon: "check", } - : retentionNote(file.rank, options.maxSnapshots), - pinned: file.rank === null, + : retentionNote(file, now), + pinned: file.pinned, }; }); } -function retentionNote( - rank: number | null, - maxSnapshots: number, -): TrashNote | null { - const text = retentionText(rank, maxSnapshots); +function retentionNote(file: DeletedFile, now: number): TrashNote | null { + const text = retentionText(file, now); if (text === null) return null; - if (rank === null) return { text, tone: "pinned", icon: "pin" }; - const soon = maxSnapshots - rank <= SOON_PUSHES; + if (file.pinned) return { text, tone: "pinned", icon: "pin" }; + const soon = file.keptUntil !== null && file.keptUntil - now <= SOON_MS; return { text, tone: soon ? "soon" : "plain", icon: "hourglass" }; } @@ -102,17 +103,12 @@ export function resolveRestoreTarget(input: string): string | null { return normalized; } -/** - * Remaining lifetime in pushes, which is what retention counts; amortised GC can leave a record listed past - * the limit. - */ +/** Retention promises "at least": GC may keep a version past this date, never drops it before. */ export function retentionText( - rank: number | null, - maxSnapshots: number, + file: Pick, + now: number, ): string | null { - if (rank === null) return "Kept by a pinned snapshot"; - const remaining = maxSnapshots - rank; - if (remaining <= 0) return "Drops out of history at the next cleanup"; - if (remaining === 1) return "Drops out of history after 1 more push"; - return `Drops out of history after ${remaining} more pushes`; + if (file.pinned) return "Kept by a pinned snapshot"; + if (file.keptUntil === null) return null; + return `Kept until ${formatDay(file.keptUntil, now, false)}`; } diff --git a/packages/plugin/src/ui/source-control/trash-tab.ts b/packages/plugin/src/features/source-control/trash/trash-tab.ts similarity index 69% rename from packages/plugin/src/ui/source-control/trash-tab.ts rename to packages/plugin/src/features/source-control/trash/trash-tab.ts index 157893cc..3b7b5de1 100644 --- a/packages/plugin/src/ui/source-control/trash-tab.ts +++ b/packages/plugin/src/features/source-control/trash/trash-tab.ts @@ -1,7 +1,12 @@ -import { Menu, Platform, setIcon, TFile, TFolder } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import { pluralize } from "@/shared"; -import type { DeletedFilesResult } from "@/sync/history"; +import { + Menu, + Platform, + SearchComponent, + setIcon, + TFile, + TFolder, +} from "obsidian"; +import { HISTORY_KEEP_TEXT } from "@/core/constants"; import { appendIconButton, attempt, @@ -9,23 +14,26 @@ import { notifyError, notifyInfo, onLongPress, + openPromptModal, renderPath, -} from "@/ui/common"; -import { openPromptModal } from "@/ui/modals"; -import { HistoryList } from "./history-list"; -import { confirmBulkRestore, confirmRestore } from "./restore-modal"; -import { RowPager } from "./row-pager"; +} from "@/core/ui"; +import { confirmBulkRestore } from "@/features/diff"; +import type { DeletedFilesResult } from "@/features/sync"; import { SelectionBar, type SelectionCommand, type SelectionSource, -} from "./selection-bar"; +} from "../actions/selection-bar"; +import { HistoryList } from "../history/history-list"; +import { RowPager } from "../history/row-pager"; +import type { SourceControlHost } from "../host"; +import { confirmAndRestoreFile } from "../restore-file"; import { renderEmptyState, renderHistoryOff, renderLoadError, renderLoading, -} from "./tab-states"; +} from "../tab-states"; import { buildTrashRows, resolveRestoreTarget, @@ -39,13 +47,15 @@ export class TrashTab implements SelectionSource { ); /** Selected row paths; pruned to the rows the latest render produced. */ private readonly selected = new Set(); + /** The rows the filter shows: Select all and restore act on these alone. */ private rows: TrashRow[] = []; + private query = ""; private readonly pager = new RowPager(); private bar: SelectionBar | null = null; private selectAll: HTMLInputElement | null = null; constructor( - private readonly plugin: PluginHost, + private readonly plugin: SourceControlHost, private readonly onRerender: () => void, private readonly openDiff: ( path: string, @@ -71,8 +81,9 @@ export class TrashTab implements SelectionSource { if (!this.plugin.settings.fileHistoryEnabled) { renderHistoryOff( pane, - this.plugin.app, - "File version history is disabled, so deleted files are not recoverable. Enable it in settings.", + this.plugin, + "Without history, deleted files cannot be recovered. Files deleted after you turn it on can be.", + this.onRerender, ); return; } @@ -144,28 +155,84 @@ export class TrashTab implements SelectionSource { ); } const rows = buildTrashRows(deleted.files, { - maxSnapshots: this.plugin.settings.fileHistoryMaxSnapshots, currentDevice: this.plugin.controller.currentDevice(), inVault: (path) => this.plugin.app.vault.getAbstractFileByPath(path) instanceof TFile, }); - this.rows = rows; - this.pruneSelection(); if (rows.length === 0) { + this.rows = rows; + this.pruneSelection(); // The warnings above already say why the list is short; do not contradict them. if (!incomplete) { renderEmptyState(body, { icon: "circle-check", tone: "success", title: "Nothing to restore", - text: `Nothing deleted in the last ${this.plugin.settings.fileHistoryMaxSnapshots} snapshots. Older deletions are dropped from history unless their snapshot is pinned.`, + text: this.isKeptForGood() + ? "Nothing deleted in the kept history." + : `Nothing deleted in the last ${this.keepText()}. Older deletions drop out unless a pinned snapshot holds them.`, }); } return; } - this.renderListHead(body); - for (const row of this.pager.slice(rows)) this.renderRow(body, row); - this.pager.render(body, rows.length, this.onRerender); + const bar = body.createDiv({ cls: "mdsync-timeline-filter" }); + const list = body.createDiv({ cls: "mdsync-deleted-list" }); + // Typing redraws the list alone, so the field keeps its focus. + const redraw = (): void => { + list.empty(); + this.renderRows(list, rows, incomplete); + }; + new SearchComponent(bar) + .setPlaceholder("Filter by path or folder") + .setValue(this.query) + .onChange((value) => { + this.query = value; + redraw(); + }) + .inputEl.setAttr("aria-label", "Filter deleted files by path"); + redraw(); + } + + /** A filter drops the rows it hides from the selection. */ + private renderRows( + list: HTMLElement, + rows: readonly TrashRow[], + incomplete: boolean, + ): void { + const query = this.query.trim().toLowerCase(); + this.rows = rows.filter((row) => row.path.toLowerCase().includes(query)); + this.pruneSelection(); + this.selectAll = null; + if (this.rows.length === 0) { + renderEmptyState(list, { + icon: "search-x", + tone: "muted", + title: `No deleted files match ${this.query.trim()}`, + text: incomplete + ? "Nothing under this path was deleted in the history that can be read." + : "Nothing under this path was deleted in the kept history.", + action: { + text: "Clear filter", + run: () => { + this.query = ""; + this.onRerender(); + }, + }, + }); + } else { + this.renderListHead(list); + for (const row of this.pager.slice(this.rows)) this.renderRow(list, row); + this.pager.render(list, this.rows.length, this.onRerender); + } + this.selectionChanged(); + } + + private isKeptForGood(): boolean { + return this.plugin.settings.fileHistoryKeep === "forever"; + } + + private keepText(): string { + return HISTORY_KEEP_TEXT[this.plugin.settings.fileHistoryKeep]; } private renderListHead(body: HTMLElement): void { @@ -183,8 +250,10 @@ export class TrashTab implements SelectionSource { }); this.selectAll = box; head.createSpan({ - cls: "mdsync-deleted-count", - text: `${pluralize(this.rows.length, "file")} history still holds`, + cls: "mdsync-deleted-kept", + text: this.isKeptForGood() + ? "Kept for good" + : `Kept ${this.keepText()} after deletion`, }); } @@ -319,21 +388,17 @@ export class TrashTab implements SelectionSource { private async restore(row: TrashRow, target: string): Promise { if (!this.targetIsWritable(target)) return; // The diff modal is the confirmation: it names the target and shows the change. - const confirmed = await confirmRestore({ - plugin: this.plugin, - path: row.path, - target, - version: { hash: row.hash, label: row.age, size: row.size }, - }); - if (!confirmed) return; - try { - await this.plugin.controller.history.restoreFileVersion(target, row.hash); + await confirmAndRestoreFile( + this.plugin, + { + path: row.path, + target, + version: { hash: row.hash, label: row.age, size: row.size }, + }, + `Restored ${target}. Review and push the change when ready.`, // The row stays, marked: the remote still has the file deleted until this is pushed. - notifyInfo(`Restored ${target}. Review and push the change when ready.`); - this.onRerender(); - } catch (err) { - notifyError("Restore failed", err); - } + this.onRerender, + ); } /** A folder at the target cannot take file bytes, so stop before the preview. */ @@ -363,28 +428,34 @@ export class TrashTab implements SelectionSource { })), ); if (!confirmed) return; + // Same guard as a single restore, collected instead of one notice each. + const folders = new Set( + rows + .filter( + (row) => + this.plugin.app.vault.getAbstractFileByPath(row.path) instanceof + TFolder, + ) + .map((row) => row.path), + ); + const items = rows + .filter((row) => !folders.has(row.path)) + .map(({ path, hash }) => ({ path, hash })); + // A rejection is the closing refresh and loses which paths failed, so all stay selected, as a refresh per file did. + const failed = new Set([ + ...folders, + ...(await this.plugin.controller.history + .restoreFileVersions(items) + .catch(() => items.map((item) => item.path))), + ]); let restored = 0; - const failures: string[] = []; - for (const row of rows) { - // Same guard as a single restore, collected instead of one notice each. - if ( - this.plugin.app.vault.getAbstractFileByPath(row.path) instanceof TFolder - ) { - failures.push(row.path); - continue; - } - try { - await this.plugin.controller.history.restoreFileVersion( - row.path, - row.hash, - ); - // Failures stay selected so the user can retry them. - this.selected.delete(row.path); - restored++; - } catch { - failures.push(row.path); - } + for (const { path } of items) { + if (failed.has(path)) continue; + // Failures stay selected so the user can retry them. + this.selected.delete(path); + restored++; } + const failures = rows.map((row) => row.path).filter((p) => failed.has(p)); if (restored > 0) { notifyInfo(`Restored ${restored} file(s). Review and push when ready.`); } diff --git a/packages/plugin/src/ui/source-control/types.ts b/packages/plugin/src/features/source-control/types.ts similarity index 81% rename from packages/plugin/src/ui/source-control/types.ts rename to packages/plugin/src/features/source-control/types.ts index 79452759..366c5c45 100644 --- a/packages/plugin/src/ui/source-control/types.ts +++ b/packages/plugin/src/features/source-control/types.ts @@ -14,6 +14,10 @@ export interface FileRow { statusLetter: string; statusClass: string; isConflict: boolean; + /** A conflict over an earlier version both sides changed; without one, both sides added the file. */ + hasBase?: boolean; + /** A conflict **Merge…** can open: a base, and text. */ + mergeable?: boolean; } export interface TreeNode { diff --git a/packages/plugin/src/ui/source-control-view.ts b/packages/plugin/src/features/source-control/view.ts similarity index 74% rename from packages/plugin/src/ui/source-control-view.ts rename to packages/plugin/src/features/source-control/view.ts index 7cf487b8..e121d180 100644 --- a/packages/plugin/src/ui/source-control-view.ts +++ b/packages/plugin/src/features/source-control/view.ts @@ -1,29 +1,19 @@ +import { ItemView, Platform, setIcon, type WorkspaceLeaf } from "obsidian"; import { - type App, - ItemView, - Platform, - setIcon, - type WorkspaceLeaf, -} from "obsidian"; -import { - DIFF_VIEW_TYPE, RELATIVE_TIME_REFRESH_MS, SOURCE_CONTROL_VIEW_TYPE, -} from "@/constants"; -import type { PluginHost } from "@/plugin/host"; -import { canSync } from "@/settings/model"; -import type { SyncStatusSnapshot } from "@/sync/controller"; -import type { HistoryVersionRef } from "@/sync/projection"; -import { redrawOnPhoneChange } from "@/ui/common"; -import type { HistoryChange } from "./diff/history-state"; -import { - ChangesTab, - ConflictPreviewManager, - HistoryTab, - SourceControlActions, - TimelineTab, - TrashTab, -} from "./source-control"; +} from "@/core/constants"; +import { redrawOnPhoneChange } from "@/core/ui"; +import { openDiffView } from "@/features/diff"; +import type { SyncStatusSnapshot } from "@/features/sync"; +import { canSync } from "@/features/sync"; +import { SourceControlActions } from "./actions/actions"; +import { ChangesTab } from "./changes/changes-tab"; +import { ConflictPreviewManager } from "./changes/conflict-preview-manager"; +import { HistoryTab } from "./history/history-tab"; +import type { SourceControlHost } from "./host"; +import { TimelineTab } from "./timeline/timeline-tab"; +import { TrashTab } from "./trash/trash-tab"; const ESourceTab = { Changes: "changes", @@ -46,67 +36,8 @@ const SOURCE_TABS: ReadonlyArray<{ { tab: ESourceTab.Timeline, label: "Timeline", icon: "clock-3" }, ]; -export function openSourceControlHistory( - plugin: PluginHost, - path?: string, -): Promise { - return openSourceControlOn(plugin, (view) => view.showHistory(path ?? null)); -} - -export function openSourceControlDeleted(plugin: PluginHost): Promise { - return openSourceControlOn(plugin, (view) => view.showDeleted()); -} - -/** An open view keeps its tab; conflicts are only on Changes. */ -export function openSourceControlChanges(plugin: PluginHost): Promise { - return openSourceControlOn(plugin, (view) => view.showChanges()); -} - -async function openSourceControlOn( - plugin: PluginHost, - show: (view: SourceControlView) => void, -): Promise { - // The leaf it showed: an older one in a main tab may sit beside the sidebar's. - const { view } = await openSourceControlView( - plugin.app, - SOURCE_CONTROL_VIEW_TYPE, - ); - if (view instanceof SourceControlView) show(view); -} - -export async function openSourceControlView( - app: App, - viewType: string, -): Promise { - const { workspace } = app; - const existing = workspace.getLeavesOfType(viewType); - const shown = - existing.find((leaf) => leaf.getRoot() === workspace.rightSplit) ?? - existing[0]; - if (shown) { - await workspace.revealLeaf(shown); - return shown; - } - const leaf = workspace.getRightLeaf(false) ?? workspace.getLeaf(true); - await leaf.setViewState({ type: viewType, active: true }); - await workspace.revealLeaf(leaf); - return leaf; -} - -/** A mobile's right sidebar lists only the views it holds: one waits there beside backlinks and the outline. */ -export function keepInRightSidebar(app: App): void { - const { workspace } = app; - const held = workspace - .getLeavesOfType(SOURCE_CONTROL_VIEW_TYPE) - .some((leaf) => leaf.getRoot() === workspace.rightSplit); - if (held) return; - void workspace - .getRightLeaf(false) - ?.setViewState({ type: SOURCE_CONTROL_VIEW_TYPE, active: false }); -} - export class SourceControlView extends ItemView { - private readonly plugin: PluginHost; + private readonly plugin: SourceControlHost; private readonly previews: ConflictPreviewManager; private readonly actions: SourceControlActions; private readonly changes: ChangesTab; @@ -120,7 +51,7 @@ export class SourceControlView extends ItemView { private historyStale = false; private comparedOnce = false; - constructor(leaf: WorkspaceLeaf, plugin: PluginHost) { + constructor(leaf: WorkspaceLeaf, plugin: SourceControlHost) { super(leaf); this.plugin = plugin; this.previews = new ConflictPreviewManager({ @@ -261,6 +192,17 @@ export class SourceControlView extends ItemView { this.render(this.plugin.controller.getSnapshot(), true); } + /** On `day`, else as it was left. */ + showTimeline(day?: number): void { + if (day === undefined) { + this.activateTab(ESourceTab.Timeline); + return; + } + this.tab = ESourceTab.Timeline; + this.timelineTab.showDay(day); + this.render(this.plugin.controller.getSnapshot(), true); + } + showChanges(): void { this.activateTab(ESourceTab.Changes); } @@ -409,38 +351,3 @@ export class SourceControlView extends ItemView { ?.focus(); } } - -export interface HistoryDiffTarget extends HistoryVersionRef { - /** Right side. Without it the version is diffed against the file on disk. */ - against?: { hash: string; label: string; size?: number }; - change?: HistoryChange; - previewIfMissing?: boolean; -} - -/** `merge` goes straight into the conflict's merge, as the diff's Merge… does. */ -export async function openDiffView( - plugin: PluginHost, - path: string, - history?: HistoryDiffTarget, - merge = false, -): Promise { - const existing = plugin.app.workspace.getLeavesOfType(DIFF_VIEW_TYPE); - const leaf = existing[0] ?? plugin.app.workspace.getLeaf(true); - await leaf.setViewState({ - type: DIFF_VIEW_TYPE, - active: true, - state: { - path, - historyHash: history?.hash, - historyLabel: history?.label, - historySize: history?.size, - againstHash: history?.against?.hash, - againstLabel: history?.against?.label, - againstSize: history?.against?.size, - historyChange: history?.change, - historyPreviewIfMissing: history?.previewIfMissing, - merge: merge || undefined, - }, - }); - await plugin.app.workspace.revealLeaf(leaf); -} diff --git a/packages/plugin/src/ui/source-control/virtual-list.ts b/packages/plugin/src/features/source-control/virtual-list.ts similarity index 97% rename from packages/plugin/src/ui/source-control/virtual-list.ts rename to packages/plugin/src/features/source-control/virtual-list.ts index 47e8a063..778f2f1a 100644 --- a/packages/plugin/src/ui/source-control/virtual-list.ts +++ b/packages/plugin/src/features/source-control/virtual-list.ts @@ -1,3 +1,5 @@ +import { observeResize } from "@/core/ui"; + /** * Windows a long list against a scroll container that is not the list itself: the whole pane scrolls. * Fixed-pitch absolute rows give the list its full height from the first frame, so the scrollbar never jumps. @@ -89,8 +91,7 @@ export function mountVirtualList( }; scroller.addEventListener("scroll", schedule, { passive: true }); - const resize = new ResizeObserver(schedule); - resize.observe(scroller); + const stopResize = observeResize(scroller, schedule); container.style.height = `${count * pitch}px`; update(); @@ -112,7 +113,7 @@ export function mountVirtualList( destroy(): void { if (frame) window.cancelAnimationFrame(frame); scroller.removeEventListener("scroll", schedule); - resize.disconnect(); + stopResize(); container.removeClass("is-virtual"); container.style.removeProperty("height"); container.style.removeProperty("--mdsync-row-height"); diff --git a/packages/plugin/src/features/source-control/workspace.ts b/packages/plugin/src/features/source-control/workspace.ts new file mode 100644 index 00000000..bf76bb4d --- /dev/null +++ b/packages/plugin/src/features/source-control/workspace.ts @@ -0,0 +1,119 @@ +import type { App, Menu, WorkspaceLeaf } from "obsidian"; +import { SOURCE_CONTROL_VIEW_TYPE } from "@/core/constants"; +import type { SourceControlHost } from "./host"; +import { SourceControlView } from "./view"; + +export function openSourceControlHistory( + plugin: SourceControlHost, + path?: string, +): Promise { + return openSourceControlOn(plugin, (view) => view.showHistory(path ?? null)); +} + +export function openSourceControlDeleted( + plugin: SourceControlHost, +): Promise { + return openSourceControlOn(plugin, (view) => view.showDeleted()); +} + +/** The Timeline filtered to the local day starting at `day`. */ +export function openSourceControlTimeline( + plugin: SourceControlHost, + day?: number, +): Promise { + return openSourceControlOn(plugin, (view) => view.showTimeline(day)); +} + +/** An open view keeps its tab; conflicts are only on Changes. */ +export function openSourceControlChanges( + plugin: SourceControlHost, +): Promise { + return openSourceControlOn(plugin, (view) => view.showChanges()); +} + +async function openSourceControlOn( + plugin: SourceControlHost, + show: (view: SourceControlView) => void, +): Promise { + // The leaf it showed: an older one in a main tab may sit beside the sidebar's. + const { view } = await openSourceControlView( + plugin.app, + SOURCE_CONTROL_VIEW_TYPE, + ); + if (view instanceof SourceControlView) show(view); +} + +export async function openSourceControlView( + app: App, + viewType: string, +): Promise { + const { workspace } = app; + const existing = workspace.getLeavesOfType(viewType); + const shown = + existing.find((leaf) => leaf.getRoot() === workspace.rightSplit) ?? + existing[0]; + if (shown) { + await workspace.revealLeaf(shown); + return shown; + } + const leaf = workspace.getRightLeaf(false) ?? workspace.getLeaf(true); + await leaf.setViewState({ type: viewType, active: true }); + await workspace.revealLeaf(leaf); + return leaf; +} + +/** A mobile's right sidebar lists only the views it holds: one waits there beside backlinks and the outline. */ +export function keepInRightSidebar(app: App): void { + const { workspace } = app; + const held = workspace + .getLeavesOfType(SOURCE_CONTROL_VIEW_TYPE) + .some((leaf) => leaf.getRoot() === workspace.rightSplit); + if (held) return; + void workspace + .getRightLeaf(false) + ?.setViewState({ type: SOURCE_CONTROL_VIEW_TYPE, active: false }); +} + +/** History is otherwise only in the side panel and a deleted file has no menu, so both ride on any file menu. */ +export function addHistoryMenuItems( + menu: Menu, + plugin: SourceControlHost, + path: string | null, +): void { + if (!plugin.settings.fileHistoryEnabled) return; + if (path) { + menu.addItem((item) => + item + .setTitle("MDSync: File history") + .setIcon("history") + .onClick(() => void openSourceControlHistory(plugin, path)), + ); + } + menu.addItem((item) => + item + .setTitle("MDSync: Restore deleted files") + .setIcon("trash-2") + .onClick(() => void openSourceControlDeleted(plugin)), + ); +} + +export function refreshHistoryAfterPush(plugin: SourceControlHost): void { + if (!plugin.settings.historyAutoRefresh) return; + for (const view of openViews(plugin.app)) view.refreshHistory(); +} + +/** `history` also drops loaded history: a new horizon changes every date it computed. */ +export function refreshSourceControlViews(app: App, history = false): void { + for (const view of openViews(app)) { + if (history) view.refreshHistory(); + else view.refreshDisplaySettings(); + } +} + +function openViews(app: App): SourceControlView[] { + return app.workspace + .getLeavesOfType(SOURCE_CONTROL_VIEW_TYPE) + .flatMap((leaf) => + leaf.view instanceof SourceControlView ? [leaf.view] : [], + ); +} diff --git a/packages/plugin/src/features/spaces/README.md b/packages/plugin/src/features/spaces/README.md new file mode 100644 index 00000000..463577e9 --- /dev/null +++ b/packages/plugin/src/features/spaces/README.md @@ -0,0 +1,74 @@ +# Shared folders (spaces) + +A shared folder is a **space**: a vault folder with its own storage, key and history, synced by the same engine as the vault (`features/sync/README.md`). This slice holds the records that describe spaces, the partition built from them, how a device reaches a share (own S3 or the owner's relay broker), invites, moves, pause and the share window. It does no networking of its own except the broker client in `features/spaces/broker/`. The relay side is `packages/relay/src/share/` (`packages/relay/README.md`). Constraints: `.claude/rules/spaces.md`; engine side of the partition: `.claude/rules/sync-integrity.md`. + +## Decisions + +| Decision | Why | +|---|---| +| A space is the unit of sync; the vault and a share run one engine | one history, one live path, no parallel share cycle | +| Every path belongs to exactly one space; a share's data lives once | two writers on one path corrupt it | +| No accounts: a person is a vault (storage + passphrase), their bucket is their control plane | serverless, no third-party service | +| A share mounts itself on all of a person's devices; pause is per device or on all of them, and a device can turn shares off | otherwise the folder freezes: out of the vault, not in the share; paused, it stays out of the vault while nothing of it syncs | +| Leaving, closing or revocation never deletes files | they return to that person's vault | +| Owning a share needs S3-compatible storage | WebDAV and Google Drive cannot presign | +| A participant gets presigned URLs from the owner's relay, never credentials | the owner's keys stay in the owner's KV; revoking a token is one broker call | +| No integration with the Relay plugin (No-Instructions/Relay) | paid past 3 participants, closed control plane. Its MIT code may be borrowed with attribution in the source header, as `features/sync/hunks/anchored-hunks.ts` does; there is no NOTICE file | + +## Model + +A **person** is a vault's owner (`owner` on the hub) or a broker token's `participantId`; a **device** syncing that vault is the person's, anything else joins by invite. Attribution, presence and revocation work per person. A participant is named as the owner invited them (`personName`); the owner by **Your name** (Settings, Shared folders), kept on each of their open shares' owner access so every device of theirs reads one through the records' trade, "Owner" while empty (`features/spaces/record.ts`, `features/spaces/owner.ts`). A new share takes the name the others carry. The relay vouches only the `owner` key, so peers read that name from the owner's own announcement (`ChannelPresence.nameOf`). + +| | root | key | storage | hub grant | +|---|---|---|---|---| +| vault | `/` minus share roots | vault data key | bucket root | `deriveChannelGrant(RELAY_SECRET, channel)` | +| own share | a folder | share key | `/shares//` | same | +| joined share | own folder | share key | broker, presigned URLs | share token | + +**Records** (`settings.spaces`, `features/spaces/record.ts`) are published one object each as `/spaces/.json.enc` under the vault key (`features/spaces/remote.ts` over `features/storage/records.ts`), so concurrent adds never race; one record edited on two devices is last-writer-wins (`rev`, then author). They are never in `manifest.json.enc` because the state file (`features/sync/state.ts`) keeps the manifest in plain text. A record is re-read only when its listing etag differs from the etag of the bytes last read (cached per storage, key and prefix; one it just published, or one that will not decode, is read again next cycle): a quiet cycle is one list and no GETs. A backend that lists no etags reads every record. + +A share's location (endpoint, bucket, prefix) is pinned once: re-deriving it from current settings orphans its objects. Credentials never enter a record; each owner device uses its vault's current S3 credentials. Records belong to the vault storage they were traded with (`settings.spacesVault`). + +**Pause** is one rule (`pauseOf` in `features/spaces/partition.ts`, read by the partition, the hub's routes and status, and `openShare`): `useSharedFolders` off pauses every share on that device, arriving ones too; the record's `paused` pauses it on every device of the person (published, LWW like any record edit; a resume from any device clears it); `pausedSpaces` on this device alone. Records still trade while shares are off, or the device would read a share's folder as vault files the vault no longer lists. Device-local, never published: `useSharedFolders`, `pausedSpaces`, `pauseArrivingShares`, `localRoots` (a move not yet followed here). + +**Ignore.** Every space ignores by its own ignore note (`IGNORE_FILE_NAME`, `core/constants.ts`) in its root, rules relative to it; the vault's rules stop at a share's root. **Share folder** first writes one exact rule per path the vault's rules kept out, or those files would reach every participant. Device-local patterns apply everywhere. + +**Roots** never overlap; nested shares and re-sharing someone else's are refused; only the owner invites. Two offline devices sharing one folder: the lower id wins, the other record is inert (`SpaceRecords.inert`, warned once). + +**Broker signing.** The broker lets a participant into `shares//` only (`packages/relay/src/share/key.ts`); vault GC lists only `objects/`, `recipes/`, `chunks/`, `pins/` and `history/`. Pulls and pushes hint their object keys (`prepareReads`, `prepareWrites`); `features/spaces/broker/share-signed-urls.ts` lazily signs up to `SIGN_BATCH_MAX` GET or PUT URLs when the first is needed, because signing every object alone made a pull several times slower than direct S3. Expired URLs and failed batches fall back to single signing; an older relay costs one refused batch per transfer. The relay checks the token once, derives one signing key, rejects an unsafe key's whole batch and refuses PUT batches from read-only grants. Existence probes remain listings. + +## Lifecycle + +- **Share folder** (`shareFolder`) writes the record; the next refresh publishes and pushes it, and the push's signal wakes the owner's other devices, which mount it. Without a configured relay the share works across the owner's own devices; the notice says a relay is needed to invite people. +- **Invite** (`createInvite`) registers the share's location with the broker, remembers that relay in the owner's record (`access.relayUrl`), issues one token per person and seals `{id, name, key, relayUrl, token, participantId, personName, readOnly}` under a 60-bit password (`sealLink`), sent apart. +- **Accept** (`mountShare`) needs a new or empty folder (a full one would ship its files into someone else's share). A link to a share already here replaces its access in place: same folder and baseline, since the broker's storage identity is `broker|`, not the relay. That is the way back after a re-invite or a move of the owner's relay; the owner's share window names the old relay. +- **Guest**: accepting needs no vault storage. A device without one (`isGuest`) syncs its joined shares and never opens the vault; its records stay in its settings. Once the vault is set up, the first trade admits them as an accept there would (`admitJoined`: no vault file and no other share at the root, else the refresh stops until the folder is renamed). In that trade (`syncRecords`, `unbound`) an open record outranks the vault's older close of it, and a share the vault owns stays its owner's whatever this device joined or left of it (its folder moves to the owner's root). +- **Move** is a record edit; the person's other devices move the folder (`features/spaces/share-moves.ts`). Paths inside the share and docIds do not change. A root gone on one device detaches that device (`SpaceGoneError`, `features/spaces/ui/space-gone.ts`); it never deletes for all. +- **Stop sharing / Leave** tombstone the record; the folder returns to the vault. Stop sharing then deletes `shares//` through the operation queue, so no refresh mounts the share again meanwhile; a failure only leaves orphans. Leave revokes the participant's own token at the broker (`DELETE /share/token`), never one issued after it; an unreachable relay does not stop the leave. Stop sharing from a vault whose relay is not the one the invites went through warns that their tokens live on there. +- **Revocation** closes the share on the participant's devices: a broker `unauthorized` that still holds for the same token 90 s later tombstones the record as Leave does (no broker call, the token is dead) and asks at once whether to keep its files or trash the folder (`features/spaces/ui/access-ended.ts`). The wait is because the broker's KV is eventually consistent (about 60 s, negative answers cached): a fresh or renewed token looks revoked at first, and a false close would reach every device of that person. A hub `REVOKED` pulls, so the broker is asked soon. People may lag an invite; a revoke shows at once, as the list reads each pointer. +- **Owner credentials**: after a good compare the owner device resends its S3 credentials to the broker (`createShareRegistration`), hourly, only where an invite went before. + +## Accepted limitations + +- Every share owner is the key `owner`: two shares of unnamed owners show them alike. +- The read-only lock (`features/spaces/ui/read-only.ts`) is the editor's: Properties, renames and other plugins still change files there, which then wait unpushed. A note moved into a read-only root while open locks on reopening. A drawing locks once its view loaded (up to 500 ms), and scripts can still edit it. +- A read-only participant's local changes in the share stay pending: auto-push skips them, an explicit push holding any of them is refused, **Revert this file** drops them. A read-only participant ignores only on their device. +- A revoked writer keeps file storage for up to about three minutes: the broker signs by the KV grant (cached about 60 s), never the hub's revoked table, and a presigned URL lives 120 s. They held the same rights a moment before; asking the hub on every signature costs a Durable Object round trip per object. +- The broker presigns DELETE too: a writer can remove a share's objects; history, not revocation, repairs that. `packages/relay/src/share/key.ts` is the whole boundary: it fails closed, and every change needs traversal tests. +- Re-inviting recognises a person by name, case-insensitively: one name is one participant, a renamed person is a new one, an unnamed invite is always new. +- `reset-remote-storage` leaves `shares/`, `spaces/` and `links/`: resetting the vault does not end shares others depend on, nor forget live share links. +- Mounting over one's own copy: identical files converge; an edit made before the record arrived is a conflict with no base in the share. +- The vault drops a share folder's frozen entries at its next push, so they stop holding the folder's blobs (`features/sync/remote/foreign.ts`); history keeps them until it rolls off. The baseline forgets them at the next refresh; until the share's baseline on this device takes a path, its entry stays in `shareBases` as the live merge base. Until that push the vault lists them. A device whose refresh read the records just before the share was created, or that skipped the share's whole open period and first refreshes after Stop sharing before the owner pushes the folder back, reads them as deletions of unchanged files; the share or the owner's push brings them back. A share kept paused while it is edited and closed gives that device conflicts, not a clean pull. +- Closing where the folder is gone returns an empty root: entries the vault still lists (no vault push since the share opened) read as deletions (files edited since give a conflict). A share empties only by closing; deleting every file also hits `SpaceGoneError`. +- A root move rehashes the moved files once, deletes the vault's frozen copy at the old path on the next push if one is still listed (history keeps it), and two offline moves converge by LWW (the loser moves again). A folder moved outside Obsidian, or while it was closed, is a vanished root (`SpaceGoneError`) plus new vault content. A rename in Obsidian cancels the running operation, so a pull stops writing under the old path. +- Pointed at another vault storage, a device drops the records rather than publish share keys into it, and their folders stay as plain files. It says so and forgets its state of them, so back at the first vault they mount afresh; a folder moved elsewhere meanwhile stays behind as vault content. Credentials are not the location: new keys to the same bucket keep every owned share. +- A failed share is retried on every refresh (one broker request), not backed off; an explicit operation on its paths shows its error, which the scheduler does not count. +- A closed share's ignore note stays as a plain file: the vault's rules govern the folder again. +- A new own share restarts the vault's socket, so live sessions resubscribe. A note whose folder becomes a share leaves its vault room in the hub (rooms are never trimmed); other devices type there until the record's signal moves them, then fold those edits into the share's room. +- A participant's other devices hear of an accepted share by signal only with a relay of their own. +- A guest has no vault socket: the ribbon's relay dot and the vault's relay line read offline while its shares' channels are live. A guest's shares reach the person's other devices only once it sets up the vault; files another device has in that folder but never pushed are pushed into the share there, as with any record arriving over one's own copy. +- The manifest caches (`validators`, `publishedHeads` in `features/sync/remote/manifest.ts`) live as long as their storage adapter; a share's root is in its adapter memo (`ShareStorage.memo`), so a new root is a new adapter. + +## Tests + +`packages/plugin/tests/features/spaces/` mirrors the slice; `packages/plugin/tests/helpers/space-records.ts` builds records; the broker is covered by `packages/relay/tests/share/`. Real flows: `pnpm e2e:shares`, `pnpm e2e:invite`, `pnpm e2e:guest` (`tests/e2e/README.md`). diff --git a/packages/plugin/src/spaces/access.ts b/packages/plugin/src/features/spaces/access.ts similarity index 83% rename from packages/plugin/src/spaces/access.ts rename to packages/plugin/src/features/spaces/access.ts index b69f4c52..0ad0b3de 100644 --- a/packages/plugin/src/spaces/access.ts +++ b/packages/plugin/src/features/spaces/access.ts @@ -1,12 +1,17 @@ -import { type EncryptionKey, importAesKey } from "@/crypto"; -import { deriveLiveKeys, type LiveKeys } from "@/crypto/live-keys"; import { - createBrokerAdapter, + deriveChunkIds, + deriveLiveKeys, + type EncryptionKey, + importAesKey, + type LiveKeys, +} from "@/core/crypto"; +import { base64ToBytes } from "@/core/utils"; +import { createStorageAdapter, type StorageAdapter, type StorageAdapterConfig, -} from "@/storage"; -import { base64ToBytes } from "@/utils"; +} from "@/features/storage"; +import { createBrokerAdapter } from "./broker/share-broker"; import { ownerStorageConfig } from "./owner"; import type { SpaceRecord } from "./record"; @@ -62,6 +67,10 @@ export function shareKey(record: SpaceRecord): Promise { return key; } +export function shareChunkIds(record: SpaceRecord): Promise { + return deriveChunkIds(base64ToBytes(record.key)); +} + export function shareLiveKeys(record: SpaceRecord): Promise { return deriveLiveKeys(base64ToBytes(record.key)); } diff --git a/packages/plugin/src/storage/adapters/share-broker.ts b/packages/plugin/src/features/spaces/broker/share-broker.ts similarity index 94% rename from packages/plugin/src/storage/adapters/share-broker.ts rename to packages/plugin/src/features/spaces/broker/share-broker.ts index 6f946886..4664f2a3 100644 --- a/packages/plugin/src/storage/adapters/share-broker.ts +++ b/packages/plugin/src/features/spaces/broker/share-broker.ts @@ -4,25 +4,24 @@ * lives and issues the tokens. */ +import { ADMIN_HEADER } from "@mdsync/protocol"; import { requestUrl } from "obsidian"; -import { relayBase } from "@/shared"; -import type { S3StorageConfig } from "@/storage/config"; -import { - ShareRefusedError, - type StorageAdapter, - StorageRequestError, -} from "@/storage/types"; - +import type { RelayConfig } from "@/core/settings"; +import { relayBase, StorageHttpError } from "@/core/shared"; +import type { S3StorageConfig } from "@/features/storage"; import { + createS3Store, endpointUrl, + errorCode, type S3Method, type S3RequestInput, + ShareRefusedError, + type StorageAdapter, + StorageRequestError, signingRegion, -} from "./s3-signer"; -import { createS3Store } from "./s3-store"; +} from "@/features/storage"; import { ShareSignedUrls } from "./share-signed-urls"; -import { errorCode, StorageHttpError } from "./util"; export interface BrokerAccess { relayUrl: string; @@ -35,13 +34,20 @@ export interface BrokerAdmin { secret: string; } +/** Shares and links both speak to the relay with its secret. */ +export function relayAdmin({ + relayUrl, + relaySecret, +}: RelayConfig): BrokerAdmin { + return { relayUrl, secret: relaySecret }; +} + const SIGN_OPS: Record = { GET: "get", PUT: "put", DELETE: "delete", HEAD: "head", }; -export const ADMIN_HEADER = "X-Mdsync-Admin"; /** Refusals that say something about the share, not the network: never retried. */ const PARTICIPANT_REFUSALS: Record = { unauthorized: "This shared folder's invite is no longer valid.", diff --git a/packages/plugin/src/storage/adapters/share-signed-urls.ts b/packages/plugin/src/features/spaces/broker/share-signed-urls.ts similarity index 100% rename from packages/plugin/src/storage/adapters/share-signed-urls.ts rename to packages/plugin/src/features/spaces/broker/share-signed-urls.ts diff --git a/packages/plugin/src/features/spaces/host.ts b/packages/plugin/src/features/spaces/host.ts new file mode 100644 index 00000000..7f8b4a8c --- /dev/null +++ b/packages/plugin/src/features/spaces/host.ts @@ -0,0 +1,14 @@ +import type { RelayStatus } from "@/core/hub"; +import type { CursorFollow, People } from "@/features/presence"; +import type { SyncHost } from "@/features/sync"; +import type { SpaceRecords } from "./records"; + +/** What shared folders need from the plugin. */ +export interface SpacesHost extends SyncHost { + readonly spaces: SpaceRecords; + readonly follows: CursorFollow; + readonly realtime: { + readonly people: People; + readonly hub: { statusOf(spaceId: string): RelayStatus }; + }; +} diff --git a/packages/plugin/src/features/spaces/index.ts b/packages/plugin/src/features/spaces/index.ts new file mode 100644 index 00000000..64c42181 --- /dev/null +++ b/packages/plugin/src/features/spaces/index.ts @@ -0,0 +1,26 @@ +export { shareChunkIds, shareKey, shareStorage } from "./access"; +export { type BrokerAdmin, relayAdmin } from "./broker/share-broker"; +export type { SpacesHost } from "./host"; +export { INVITE_ACTION, invitePassword } from "./invite"; +export { pauseOf } from "./partition"; +export { + parseSpaceRecords, + type SpaceRecord, + shareIdentity, +} from "./record"; +export { SpaceRecords } from "./records"; +export { createMoveFollower, registerShareRenames } from "./share-moves"; +export { createShareRegistration } from "./share-registration"; +export { + createSpaceAccess, + type SpaceAccess, + type SpaceAccessHost, +} from "./space-access"; +export { createAccessEnded } from "./ui/access-ended"; +export { createInertWarning } from "./ui/inert-warning"; +export { openInvite } from "./ui/invites/invite-action"; +export { lastEditLabel, lastEditor } from "./ui/last-edit"; +export { registerReadOnlyLock, watchReadOnlyRoots } from "./ui/read-only"; +export { sharesSection } from "./ui/shares-section"; +export { askSpaceGone, createSpaceGone } from "./ui/space-gone"; +export { addShareMenuItem, openShareWindow } from "./ui/window/share-window"; diff --git a/packages/plugin/src/spaces/invite.ts b/packages/plugin/src/features/spaces/invite.ts similarity index 96% rename from packages/plugin/src/spaces/invite.ts rename to packages/plugin/src/features/spaces/invite.ts index ef761074..cde72402 100644 --- a/packages/plugin/src/spaces/invite.ts +++ b/packages/plugin/src/features/spaces/invite.ts @@ -4,9 +4,7 @@ */ import { isShareId } from "@mdsync/protocol"; - -import { randomBytes } from "@/crypto"; -import { LINK_PARAM, openLink, sealLink } from "@/crypto/sealed-link"; +import { LINK_PARAM, openLink, randomBytes, sealLink } from "@/core/crypto"; import type { ShareAccess, SpaceRecord } from "./record"; diff --git a/packages/plugin/src/spaces/owner.ts b/packages/plugin/src/features/spaces/owner.ts similarity index 81% rename from packages/plugin/src/spaces/owner.ts rename to packages/plugin/src/features/spaces/owner.ts index 24ae94ed..a233ba34 100644 --- a/packages/plugin/src/spaces/owner.ts +++ b/packages/plugin/src/features/spaces/owner.ts @@ -1,12 +1,15 @@ import { sharePrefix } from "@mdsync/protocol"; -import { randomBytes, randomId } from "@/crypto"; +import { randomBytes, randomId } from "@/core/crypto"; +import type { MdsyncSettings } from "@/core/settings"; +import { bytesToBase64, isNewer } from "@/core/utils"; import { + activeStorage, EStorageBackend, + isStorageConfigured, type S3StorageConfig, type StorageAdapterConfig, -} from "@/storage"; -import { bytesToBase64, isNewer } from "@/utils"; +} from "@/features/storage"; import type { ShareLocation, SpaceRecord } from "./record"; @@ -70,6 +73,13 @@ function ownShares(records: readonly SpaceRecord[]): SpaceRecord[] { } /** The share's storage under this device's own credentials; null off S3. */ +/** A share pins its location for good, so only a complete S3 setup may own one. */ +export function ownerStorage(settings: MdsyncSettings): S3StorageConfig | null { + const storage = activeStorage(settings); + if (storage.kind !== EStorageBackend.S3) return null; + return isStorageConfigured(settings) ? storage : null; +} + export function ownerStorageConfig( shareId: string, location: ShareLocation, diff --git a/packages/plugin/src/spaces/partition.ts b/packages/plugin/src/features/spaces/partition.ts similarity index 94% rename from packages/plugin/src/spaces/partition.ts rename to packages/plugin/src/features/spaces/partition.ts index 0e464a16..4467a0e1 100644 --- a/packages/plugin/src/spaces/partition.ts +++ b/packages/plugin/src/features/spaces/partition.ts @@ -1,5 +1,5 @@ -import { hasDotSegment } from "@/shared"; -import { isUnder, type Space, VAULT_SPACE } from "@/sync/space"; +import { hasDotSegment } from "@/core/shared"; +import { isUnder, type Space, VAULT_SPACE } from "@/features/sync"; import type { SpaceRecord } from "./record"; diff --git a/packages/plugin/src/spaces/record.ts b/packages/plugin/src/features/spaces/record.ts similarity index 93% rename from packages/plugin/src/spaces/record.ts rename to packages/plugin/src/features/spaces/record.ts index d355d2e5..77990d49 100644 --- a/packages/plugin/src/spaces/record.ts +++ b/packages/plugin/src/features/spaces/record.ts @@ -1,6 +1,6 @@ import { isShareId, OWNER } from "@mdsync/protocol"; -import { isNewer } from "@/utils"; +import { isNewer } from "@/core/utils"; /** * Where a share's objects live: its owner's S3 location when it was created. Pinned for good; re-deriving @@ -90,6 +90,17 @@ export function mergeRecords( return [...byId.values()].sort((a, b) => (a.id < b.id ? -1 : 1)); } +declare module "@/core/settings" { + interface MdsyncSettings { + /** This device's copy of the shared folders it syncs; see `spaces/`. */ + spaces: SpaceRecord[]; + } +} + +export function parseSpaceRecords(value: unknown): SpaceRecord[] { + return Array.isArray(value) ? value.filter(isSpaceRecord) : []; +} + export function isSpaceRecord(value: unknown): value is SpaceRecord { if (typeof value !== "object" || value === null) return false; const record = value as Record; diff --git a/packages/plugin/src/spaces/records.ts b/packages/plugin/src/features/spaces/records.ts similarity index 98% rename from packages/plugin/src/spaces/records.ts rename to packages/plugin/src/features/spaces/records.ts index 30cf5693..bfc1d462 100644 --- a/packages/plugin/src/spaces/records.ts +++ b/packages/plugin/src/features/spaces/records.ts @@ -1,6 +1,6 @@ -import type { EncryptionKey } from "@/crypto"; -import type { StorageAdapter } from "@/storage/types"; -import { isUnder, type Space, VAULT_SPACE } from "@/sync/space"; +import type { EncryptionKey } from "@/core/crypto"; +import type { StorageAdapter } from "@/features/storage"; +import { isUnder, type Space, VAULT_SPACE } from "@/features/sync"; import { mountError, type PauseKind, pauseOf, spacesOf } from "./partition"; import { diff --git a/packages/plugin/src/spaces/remote.ts b/packages/plugin/src/features/spaces/remote.ts similarity index 88% rename from packages/plugin/src/spaces/remote.ts rename to packages/plugin/src/features/spaces/remote.ts index 9a51898b..423f7284 100644 --- a/packages/plugin/src/spaces/remote.ts +++ b/packages/plugin/src/features/spaces/remote.ts @@ -1,7 +1,7 @@ -import type { EncryptionKey } from "@/crypto"; -import { type RecordKind, readRecords, writeRecord } from "@/storage/records"; -import type { ObjectStorage } from "@/storage/types"; -import { isNewer } from "@/utils"; +import type { EncryptionKey } from "@/core/crypto"; +import { isNewer } from "@/core/utils"; +import type { ObjectStorage } from "@/features/storage"; +import { type RecordKind, readRecords, writeRecord } from "@/features/storage"; import { isSpaceRecord, mergeRecords, type SpaceRecord } from "./record"; diff --git a/packages/plugin/src/plugin/share-moves.ts b/packages/plugin/src/features/spaces/share-moves.ts similarity index 89% rename from packages/plugin/src/plugin/share-moves.ts rename to packages/plugin/src/features/spaces/share-moves.ts index 90c9feaa..0099bca8 100644 --- a/packages/plugin/src/plugin/share-moves.ts +++ b/packages/plugin/src/features/spaces/share-moves.ts @@ -1,16 +1,11 @@ import { type Plugin, TFolder, type Vault } from "obsidian"; -import { reportWarning } from "@/shared"; -import { - mountError, - type PendingMove, - type SpaceRecords, - spacesOf, -} from "@/spaces"; -import { isUnder } from "@/sync/space"; -import { notifyError, notifyInfo } from "@/ui"; -import { removeEmptyDir } from "@/vault/io"; - -import type { PluginHost } from "./host"; +import { reportWarning } from "@/core/shared"; +import { notifyError, notifyInfo } from "@/core/ui"; +import { removeEmptyDir } from "@/core/vault"; +import { isUnder } from "@/features/sync"; +import type { SpacesHost } from "./host"; +import { mountError, spacesOf } from "./partition"; +import type { PendingMove, SpaceRecords } from "./records"; type MoveVault = Pick< Vault, @@ -45,7 +40,7 @@ export function createMoveFollower( } /** A shared folder renamed here, or one it is in, moves on the person's other devices too. */ -export function registerShareRenames(plugin: Plugin & PluginHost): void { +export function registerShareRenames(plugin: Plugin & SpacesHost): void { const movingBack = new Set(); plugin.register(() => { for (const timer of movingBack) window.clearTimeout(timer); @@ -93,7 +88,7 @@ async function follow( } async function onFolderRenamed( - plugin: Plugin & PluginHost, + plugin: Plugin & SpacesHost, folder: TFolder, oldPath: string, movingBack: Set, diff --git a/packages/plugin/src/plugin/share-registration.ts b/packages/plugin/src/features/spaces/share-registration.ts similarity index 81% rename from packages/plugin/src/plugin/share-registration.ts rename to packages/plugin/src/features/spaces/share-registration.ts index 9fda0d4d..2ce68215 100644 --- a/packages/plugin/src/plugin/share-registration.ts +++ b/packages/plugin/src/features/spaces/share-registration.ts @@ -1,14 +1,11 @@ -import type { LogService } from "@/core"; -import { ESyncLogOperation } from "@/logs/store"; -import { - isRelayConfigured, - type MdsyncSettings, - ownerStorage, -} from "@/settings/model"; -import { errorMessage } from "@/shared"; -import { brokerStorage, type SpaceRecords } from "@/spaces"; -import { listParticipants, registerShareStorage } from "@/storage"; -import type { Space } from "@/sync/space"; +import type { LogService } from "@/core/logs"; +import { ESyncLogOperation } from "@/core/logs"; +import { isRelayConfigured, type MdsyncSettings } from "@/core/settings"; +import { errorMessage } from "@/core/shared"; +import type { Space } from "@/features/sync"; +import { listParticipants, registerShareStorage } from "./broker/share-broker"; +import { brokerStorage, ownerStorage } from "./owner"; +import type { SpaceRecords } from "./records"; /** Another owner device may have sent older keys: resent this often, so working ones win back. */ const RESEND_MS = 60 * 60_000; diff --git a/packages/plugin/src/plugin/space-access.ts b/packages/plugin/src/features/spaces/space-access.ts similarity index 86% rename from packages/plugin/src/plugin/space-access.ts rename to packages/plugin/src/features/spaces/space-access.ts index bf449c47..ce7cad57 100644 --- a/packages/plugin/src/plugin/space-access.ts +++ b/packages/plugin/src/features/spaces/space-access.ts @@ -1,14 +1,13 @@ import { OWNER } from "@mdsync/protocol"; - -import type { PassphraseManager } from "@/core"; -import type { LiveKeys } from "@/crypto/live-keys"; -import { isStorageConfigured, type MdsyncSettings } from "@/settings/model"; -import { reportWarning } from "@/shared"; -import type { SpaceRecords } from "@/spaces"; -import { shareLiveKeys } from "@/spaces/access"; -import { type SpaceRecord, shareIdentity } from "@/spaces/record"; -import type { SyncController } from "@/sync/controller"; -import { type Space, VAULT_SPACE } from "@/sync/space"; +import type { LiveKeys } from "@/core/crypto"; +import type { MdsyncSettings } from "@/core/settings"; +import { reportWarning } from "@/core/shared"; +import { isStorageConfigured } from "@/features/storage"; +import type { PassphraseManager, SyncController } from "@/features/sync"; +import { type Space, VAULT_SPACE } from "@/features/sync"; +import { shareLiveKeys } from "./access"; +import { type SpaceRecord, shareIdentity } from "./record"; +import type { SpaceRecords } from "./records"; const VAULT_UNLOCK_RETRY_MS = 30_000; diff --git a/packages/plugin/src/ui/shares/access-ended.ts b/packages/plugin/src/features/spaces/ui/access-ended.ts similarity index 88% rename from packages/plugin/src/ui/shares/access-ended.ts rename to packages/plugin/src/features/spaces/ui/access-ended.ts index 4dab96c5..c8690e20 100644 --- a/packages/plugin/src/ui/shares/access-ended.ts +++ b/packages/plugin/src/features/spaces/ui/access-ended.ts @@ -1,9 +1,8 @@ import type { Plugin } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; -import type { SpaceRecord } from "@/spaces/record"; -import type { Space } from "@/sync/space"; -import { openConfirmModal } from "@/ui/modals"; +import { openConfirmModal } from "@/core/ui"; +import type { Space } from "@/features/sync"; +import type { SpacesHost } from "../host"; +import type { SpaceRecord } from "../record"; import { closeHere } from "./share-action"; @@ -12,7 +11,7 @@ const RECHECK_MS = 90_000; /** The owner ended this link: the share closes as on Leave and the person chooses what happens to its files. */ export function createAccessEnded( - plugin: Plugin & PluginHost, + plugin: Plugin & SpacesHost, ): (space: Space) => void { const refusedSince = new Map(); const rechecks = new Set(); @@ -41,7 +40,7 @@ export function createAccessEnded( } async function endAccess( - plugin: PluginHost, + plugin: SpacesHost, record: SpaceRecord, ): Promise { // Its token is dead: no leave call to the broker, which would only refuse it. diff --git a/packages/plugin/src/features/spaces/ui/inert-warning.ts b/packages/plugin/src/features/spaces/ui/inert-warning.ts new file mode 100644 index 00000000..47cf9dd0 --- /dev/null +++ b/packages/plugin/src/features/spaces/ui/inert-warning.ts @@ -0,0 +1,16 @@ +import { notifyError } from "@/core/ui"; +import type { SpaceRecords } from "../records"; + +/** Once per record and session: two devices shared one folder offline, and this one lost. */ +export function createInertWarning(spaces: SpaceRecords): () => void { + const warned = new Set(); + return () => { + for (const { id, name, root } of spaces.inert()) { + if (warned.has(id)) continue; + warned.add(id); + notifyError( + `"${name}" is not syncing: another shared folder already holds "${root}". Stop sharing it in the Sync settings.`, + ); + } + }; +} diff --git a/packages/plugin/src/ui/shares/invite-action.ts b/packages/plugin/src/features/spaces/ui/invites/invite-action.ts similarity index 86% rename from packages/plugin/src/ui/shares/invite-action.ts rename to packages/plugin/src/features/spaces/ui/invites/invite-action.ts index 1b7dcd48..815884d2 100644 --- a/packages/plugin/src/ui/shares/invite-action.ts +++ b/packages/plugin/src/features/spaces/ui/invites/invite-action.ts @@ -1,29 +1,28 @@ import { TFile, TFolder } from "obsidian"; - -import { randomId } from "@/crypto"; -import type { PluginHost } from "@/plugin/host"; -import { ownerStorage, relayAdmin } from "@/settings/model"; -import { normalizePath, stripTrailingSlash } from "@/shared"; +import { randomId } from "@/core/crypto"; +import { normalizePath, stripTrailingSlash } from "@/core/shared"; +import { notifyInfo, openConfirmModal, runWithNotice } from "@/core/ui"; +import { scopedPaths } from "@/features/sync"; +import { + issueShareToken, + listParticipants, + registerShareStorage, + relayAdmin, + revokeParticipant, +} from "../../broker/share-broker"; +import type { SpacesHost } from "../../host"; import { acceptInvite, - brokerStorage, type Invite, inviteAccess, inviteLink, invitePassword, - mountError, readInvite, -} from "@/spaces"; -import type { SpaceRecord } from "@/spaces/record"; -import { - issueShareToken, - listParticipants, - registerShareStorage, - revokeParticipant, -} from "@/storage"; -import { scopedPaths } from "@/ui/actions/push-action"; -import { notifyInfo, runWithNotice } from "@/ui/common"; -import { AcceptInviteModal, openConfirmModal } from "@/ui/modals"; +} from "../../invite"; +import { brokerStorage, ownerStorage } from "../../owner"; +import { mountError } from "../../partition"; +import type { SpaceRecord } from "../../record"; +import { AcceptInviteModal } from "./invite-modal"; export interface CreatedInvite { link: string; @@ -32,7 +31,7 @@ export interface CreatedInvite { /** Opens an `obsidian://mdsync-share` link, or asks for one when `link` is empty. `accepted` runs once the share is in. */ export async function openInvite( - plugin: PluginHost, + plugin: SpacesHost, link = "", accepted?: () => void, ): Promise { @@ -58,7 +57,7 @@ export async function openInvite( ).open(); } -async function turnOnShares(plugin: PluginHost): Promise { +async function turnOnShares(plugin: SpacesHost): Promise { const confirmed = await openConfirmModal({ app: plugin.app, title: "Shared folders are off on this device", @@ -77,7 +76,7 @@ async function turnOnShares(plugin: PluginHost): Promise { /** Registered again on every invite, so the relay signs with current credentials. */ export async function createInvite( - plugin: PluginHost, + plugin: SpacesHost, record: SpaceRecord, person: string, readOnly: boolean, @@ -127,7 +126,7 @@ export async function createInvite( /** What is wrong with mounting at `root`, or null once the share is in. */ export async function mountShare( - plugin: PluginHost, + plugin: SpacesHost, invite: Invite, root: string, ): Promise { @@ -163,7 +162,7 @@ export async function mountShare( return null; } -async function pullFolder(plugin: PluginHost, root: string): Promise { +async function pullFolder(plugin: SpacesHost, root: string): Promise { await plugin.controller.refresh(); const diff = plugin.controller.getSnapshot().result?.diff; const paths = scopedPaths(diff?.remoteChanges ?? [], root, true); @@ -175,7 +174,7 @@ async function pullFolder(plugin: PluginHost, root: string): Promise { ); } -function recordOf(plugin: PluginHost, invite: Invite): SpaceRecord | undefined { +function recordOf(plugin: SpacesHost, invite: Invite): SpaceRecord | undefined { return plugin.spaces.list().find((record) => record.id === invite.id); } diff --git a/packages/plugin/src/ui/modals/invite-modal.ts b/packages/plugin/src/features/spaces/ui/invites/invite-modal.ts similarity index 97% rename from packages/plugin/src/ui/modals/invite-modal.ts rename to packages/plugin/src/features/spaces/ui/invites/invite-modal.ts index 4592d127..0d7cde5b 100644 --- a/packages/plugin/src/ui/modals/invite-modal.ts +++ b/packages/plugin/src/features/spaces/ui/invites/invite-modal.ts @@ -1,13 +1,13 @@ import { type App, ButtonComponent, Modal, Setting } from "obsidian"; -import { errorMessage, folderName } from "@/shared"; -import type { Invite } from "@/spaces"; +import { errorMessage, folderName } from "@/core/shared"; import { alertLine, modalFooter, onEnter, renderModalHead, serial, -} from "@/ui/common"; +} from "@/core/ui"; +import type { Invite } from "../../invite"; const NO_LINK = "Paste the invite link."; const NO_PASSWORD = "Enter the password."; diff --git a/packages/plugin/src/ui/shares/invite-section.ts b/packages/plugin/src/features/spaces/ui/invites/invite-section.ts similarity index 97% rename from packages/plugin/src/ui/shares/invite-section.ts rename to packages/plugin/src/features/spaces/ui/invites/invite-section.ts index 8987c984..36ce3e77 100644 --- a/packages/plugin/src/ui/shares/invite-section.ts +++ b/packages/plugin/src/features/spaces/ui/invites/invite-section.ts @@ -1,7 +1,7 @@ import { ButtonComponent, DropdownComponent, TextComponent } from "obsidian"; -import { errorMessage } from "@/shared"; -import { alertLine, copyable, modalHint, onEnter, serial } from "@/ui/common"; +import { errorMessage } from "@/core/shared"; +import { alertLine, copyable, modalHint, onEnter, serial } from "@/core/ui"; import type { CreatedInvite } from "./invite-action"; /** Name, access and the button on one line; the link and its password appear under it, once. */ diff --git a/packages/plugin/src/ui/common/last-edit.ts b/packages/plugin/src/features/spaces/ui/last-edit.ts similarity index 69% rename from packages/plugin/src/ui/common/last-edit.ts rename to packages/plugin/src/features/spaces/ui/last-edit.ts index 923dea31..ac8ac5c5 100644 --- a/packages/plugin/src/ui/common/last-edit.ts +++ b/packages/plugin/src/features/spaces/ui/last-edit.ts @@ -1,10 +1,10 @@ -import type { PluginHost } from "@/plugin/host"; -import { formatRelativeTime } from "@/shared"; -import { shareIdentity } from "@/spaces/record"; -import { type Space, spaceOf, VAULT_SPACE } from "@/sync/space"; +import { formatRelativeTime } from "@/core/shared"; +import { type Space, spaceOf, VAULT_SPACE } from "@/features/sync"; +import type { SpacesHost } from "../host"; +import { shareIdentity } from "../record"; /** "Changed by Alex, 5 minutes ago": people in a share, devices in the vault. */ -export function lastEditLabel(plugin: PluginHost, path: string): string | null { +export function lastEditLabel(plugin: SpacesHost, path: string): string | null { const edit = plugin.controller.lastEdit(path); return edit ? `Changed ${editorOf(plugin, path, edit.key, edit.name)}, ${formatRelativeTime(edit.at)}` @@ -12,13 +12,13 @@ export function lastEditLabel(plugin: PluginHost, path: string): string | null { } /** "on Laptop" in the vault, "by Alex" in a share. */ -export function lastEditor(plugin: PluginHost, path: string): string | null { +export function lastEditor(plugin: SpacesHost, path: string): string | null { const edit = plugin.controller.lastEdit(path); return edit ? editorOf(plugin, path, edit.key, edit.name) : null; } function editorOf( - plugin: PluginHost, + plugin: SpacesHost, path: string, key: string, name: string, @@ -30,7 +30,7 @@ function editorOf( : `by ${mine ? "you" : name}`; } -function isMine(plugin: PluginHost, space: Space, key: string): boolean { +function isMine(plugin: SpacesHost, space: Space, key: string): boolean { if (space.id === VAULT_SPACE.id) { return key === plugin.controller.currentDevice().id; } diff --git a/packages/plugin/src/editor/read-only.ts b/packages/plugin/src/features/spaces/ui/read-only.ts similarity index 96% rename from packages/plugin/src/editor/read-only.ts rename to packages/plugin/src/features/spaces/ui/read-only.ts index 41308aaa..19c17f52 100644 --- a/packages/plugin/src/editor/read-only.ts +++ b/packages/plugin/src/features/spaces/ui/read-only.ts @@ -7,13 +7,13 @@ import { isViewMode, LIVE_VIEWS, setViewMode, -} from "@/live"; -import type { PluginHost } from "@/plugin/host"; +} from "@/features/live"; +import type { SpacesHost } from "../host"; const LOADING_RETRY_MS = 500; /** Notes and drawings of a read-only share take no edits: nothing made there could sync. */ -export function registerReadOnlyLock(plugin: Plugin & PluginHost): void { +export function registerReadOnlyLock(plugin: Plugin & SpacesHost): void { const { vault, workspace } = plugin.app; const mutable: Extension[] = []; plugin.registerEditorExtension(mutable); @@ -44,7 +44,7 @@ export function registerReadOnlyLock(plugin: Plugin & PluginHost): void { /** Calls `onChange` with the read-only share roots whenever they change; returns the stop. */ export function watchReadOnlyRoots( - plugin: PluginHost, + plugin: SpacesHost, onChange: (roots: readonly string[]) => void, ): () => void { let shown = ""; diff --git a/packages/plugin/src/ui/shares/share-action.ts b/packages/plugin/src/features/spaces/ui/share-action.ts similarity index 87% rename from packages/plugin/src/ui/shares/share-action.ts rename to packages/plugin/src/features/spaces/ui/share-action.ts index e826997c..1fda3083 100644 --- a/packages/plugin/src/ui/shares/share-action.ts +++ b/packages/plugin/src/features/spaces/ui/share-action.ts @@ -1,18 +1,19 @@ -import type { PluginHost } from "@/plugin/host"; -import { isRelayConfigured, ownerStorage, relayAdmin } from "@/settings/model"; -import { relayBase } from "@/shared"; -import { createShare, mountError, ownerNameOf } from "@/spaces"; -import type { SpaceRecord } from "@/spaces/record"; +import { RELAY_TEXT } from "@/core/hub"; +import { isRelayConfigured } from "@/core/settings"; +import { relayBase } from "@/core/shared"; +import { notifyError, notifyInfo, openConfirmModal } from "@/core/ui"; +import { carryVaultIgnores, pushScope } from "@/features/sync"; import { endShare, leaveShare, type Participant, + relayAdmin, revokeParticipant, -} from "@/storage"; -import { carryVaultIgnores } from "@/ui/actions/ignore-action"; -import { pushScope } from "@/ui/actions/push-action"; -import { notifyError, notifyInfo, RELAY_TEXT } from "@/ui/common"; -import { openConfirmModal } from "@/ui/modals"; +} from "../broker/share-broker"; +import type { SpacesHost } from "../host"; +import { createShare, ownerNameOf, ownerStorage } from "../owner"; +import { mountError } from "../partition"; +import type { SpaceRecord } from "../record"; export function closeLabel({ access }: SpaceRecord): string { return access.kind === "owner" ? "Stop sharing" : "Leave"; @@ -20,7 +21,7 @@ export function closeLabel({ access }: SpaceRecord): string { /** The folder becomes a space of its own, beside the vault; null when it cannot. */ export async function shareFolder( - plugin: PluginHost, + plugin: SpacesHost, root: string, ): Promise { const storage = ownerStorage(plugin.settings); @@ -52,7 +53,7 @@ export async function shareFolder( /** The relay an owner's invites went through, when this vault cannot reach it to end their tokens. */ export function strandedInvites( - plugin: PluginHost, + plugin: SpacesHost, record: SpaceRecord, ): string | null { const { access } = record; @@ -65,7 +66,7 @@ export function strandedInvites( /** The owner stops sharing, or a participant leaves; true once it is closed. */ export async function closeShare( - plugin: PluginHost, + plugin: SpacesHost, record: SpaceRecord, ): Promise { const { access } = record; @@ -112,7 +113,7 @@ export async function closeShare( /** Tombstones the record; `deleteRemote` empties the owner's copy too. */ export async function closeHere( - plugin: PluginHost, + plugin: SpacesHost, record: SpaceRecord, deleteRemote: boolean, ): Promise { @@ -129,7 +130,7 @@ export async function closeHere( /** False when the owner backed out. */ export async function revokeAccess( - plugin: PluginHost, + plugin: SpacesHost, record: SpaceRecord, person: Participant, ): Promise { diff --git a/packages/plugin/src/settings/sections/shares.ts b/packages/plugin/src/features/spaces/ui/shares-section.ts similarity index 83% rename from packages/plugin/src/settings/sections/shares.ts rename to packages/plugin/src/features/spaces/ui/shares-section.ts index 6ee3e937..dab12a42 100644 --- a/packages/plugin/src/settings/sections/shares.ts +++ b/packages/plugin/src/features/spaces/ui/shares-section.ts @@ -1,18 +1,23 @@ import { Setting, type SettingDefinitionGroup } from "obsidian"; - import { + bind, + EFieldKind, type FieldContext, fieldRow, group, + imperativePage, introRow, -} from "@/settings/fields"; -import { imperativePage } from "@/settings/page"; -import { ownerNameOf, renameOwner } from "@/spaces"; -import { EFieldKind } from "@/storage"; -import { openInvite, openShareWindow, shareSummary } from "@/ui"; +} from "@/core/settings"; +import type { SpacesHost } from "../host"; +import { ownerNameOf, renameOwner } from "../owner"; +import { openInvite } from "./invites/invite-action"; +import { shareSummary } from "./window/share-summary"; +import { openShareWindow } from "./window/share-window"; /** This person's open shares, each managed in its window, even on a device where the folder is gone. */ -export function sharesSection(ctx: FieldContext): SettingDefinitionGroup { +export function sharesSection( + ctx: FieldContext, +): SettingDefinitionGroup { const { plugin } = ctx; const open = () => plugin.spaces.list().filter((record) => !record.closed); const enabled = () => plugin.settings.useSharedFolders; @@ -21,8 +26,7 @@ export function sharesSection(ctx: FieldContext): SettingDefinitionGroup { kind: EFieldKind.Toggle, name: "Use shared folders on this device", desc: "Off, none of them syncs or shows up here, and the relay carries only the vault. Their folders already here stay as they are. This device only.", - get: (s) => s.useSharedFolders, - set: (v) => ({ useSharedFolders: v }), + ...bind("useSharedFolders"), after: (host) => { // A pull or push running now would go on writing into a share. if (!host.settings.useSharedFolders) host.controller.cancel(); @@ -51,8 +55,7 @@ export function sharesSection(ctx: FieldContext): SettingDefinitionGroup { kind: EFieldKind.Toggle, name: "Push shared folders right away", desc: "A change in a shared folder reaches the others a couple of seconds after you stop, whatever the vault's auto-push says. Read-only folders never push.", - get: (s) => s.pushSharesRightAway, - set: (v) => ({ pushSharesRightAway: v }), + ...bind("pushSharesRightAway"), rerender: true, }), fieldRow(ctx, { @@ -61,16 +64,14 @@ export function sharesSection(ctx: FieldContext): SettingDefinitionGroup { name: "Push only added, moved and deleted files", desc: "Edits wait for your push, so their gutter marks show what changed. Open notes still update live.", sub: true, - get: (s) => s.shareEditsWait, - set: (v) => ({ shareEditsWait: v }), + ...bind("shareEditsWait"), }), fieldRow(ctx, { when: enabled, kind: EFieldKind.Toggle, name: "Pause shared folders added on other devices", desc: "They arrive here paused, before anything is pulled, until you resume them. This device only.", - get: (s) => s.pauseArrivingShares, - set: (v) => ({ pauseArrivingShares: v }), + ...bind("pauseArrivingShares"), }), { name: "Accept an invite", diff --git a/packages/plugin/src/styles/shares.css b/packages/plugin/src/features/spaces/ui/shares.css similarity index 100% rename from packages/plugin/src/styles/shares.css rename to packages/plugin/src/features/spaces/ui/shares.css diff --git a/packages/plugin/src/ui/shares/space-gone.ts b/packages/plugin/src/features/spaces/ui/space-gone.ts similarity index 82% rename from packages/plugin/src/ui/shares/space-gone.ts rename to packages/plugin/src/features/spaces/ui/space-gone.ts index 8ae0cb6e..97e2ebf1 100644 --- a/packages/plugin/src/ui/shares/space-gone.ts +++ b/packages/plugin/src/features/spaces/ui/space-gone.ts @@ -1,7 +1,6 @@ -import type { PluginHost } from "@/plugin/host"; -import type { Space } from "@/sync/space"; -import { runWithNotice } from "@/ui/common"; -import { openChoiceModal } from "@/ui/modals"; +import { openChoiceModal, runWithNotice } from "@/core/ui"; +import type { Space } from "@/features/sync"; +import type { SpacesHost } from "../host"; const RESTORE = { key: "restore", @@ -15,7 +14,7 @@ const DELETE = { } as const; /** Asks once per share and launch; the Changes tab asks again on demand. */ -export function createSpaceGone(plugin: PluginHost): (space: Space) => void { +export function createSpaceGone(plugin: SpacesHost): (space: Space) => void { const asked = new Set(); return (space) => { if (asked.has(space.id)) return; @@ -26,7 +25,7 @@ export function createSpaceGone(plugin: PluginHost): (space: Space) => void { /** A share lost every file it had here: they come back, or their loss reaches everyone in it. */ export async function askSpaceGone( - plugin: PluginHost, + plugin: SpacesHost, space: Space, ): Promise { const choice = await openChoiceModal<"restore" | "delete">({ diff --git a/packages/plugin/src/ui/shares/pause-control.ts b/packages/plugin/src/features/spaces/ui/window/pause-control.ts similarity index 88% rename from packages/plugin/src/ui/shares/pause-control.ts rename to packages/plugin/src/features/spaces/ui/window/pause-control.ts index 30027e64..e1f497f2 100644 --- a/packages/plugin/src/ui/shares/pause-control.ts +++ b/packages/plugin/src/features/spaces/ui/window/pause-control.ts @@ -1,5 +1,5 @@ -import type { PauseKind } from "@/spaces"; -import { renderSegments } from "@/ui/common"; +import { renderSegments } from "@/core/ui"; +import type { PauseKind } from "../../partition"; export type Pause = Exclude; diff --git a/packages/plugin/src/ui/shares/people-list.ts b/packages/plugin/src/features/spaces/ui/window/people-list.ts similarity index 93% rename from packages/plugin/src/ui/shares/people-list.ts rename to packages/plugin/src/features/spaces/ui/window/people-list.ts index 1efe2e33..320c896e 100644 --- a/packages/plugin/src/ui/shares/people-list.ts +++ b/packages/plugin/src/features/spaces/ui/window/people-list.ts @@ -1,14 +1,13 @@ import { ButtonComponent, Menu } from "obsidian"; - -import type { Person } from "@/presence"; -import type { Participant } from "@/storage"; import { appendIconButton, appendLabeledButton, focusKey, - renderAvatar, showMenuAt, -} from "@/ui/common"; +} from "@/core/ui"; +import type { Person } from "@/features/presence"; +import { renderAvatar } from "@/features/presence"; +import type { Participant } from "../../broker/share-broker"; import type { ShareRow } from "./share-people"; export interface PeopleActions { diff --git a/packages/plugin/src/ui/shares/share-head.ts b/packages/plugin/src/features/spaces/ui/window/share-head.ts similarity index 90% rename from packages/plugin/src/ui/shares/share-head.ts rename to packages/plugin/src/features/spaces/ui/window/share-head.ts index 36bd1c0d..584edbb6 100644 --- a/packages/plugin/src/ui/shares/share-head.ts +++ b/packages/plugin/src/features/spaces/ui/window/share-head.ts @@ -1,7 +1,6 @@ import type { Modal } from "obsidian"; - -import type { SpaceRecord } from "@/spaces/record"; -import { renderModalHead } from "@/ui/common"; +import { renderModalHead } from "@/core/ui"; +import type { SpaceRecord } from "../../record"; export interface RelayState { live: boolean; diff --git a/packages/plugin/src/ui/shares/share-modal.ts b/packages/plugin/src/features/spaces/ui/window/share-modal.ts similarity index 92% rename from packages/plugin/src/ui/shares/share-modal.ts rename to packages/plugin/src/features/spaces/ui/window/share-modal.ts index b2c3b3ff..53a6758d 100644 --- a/packages/plugin/src/ui/shares/share-modal.ts +++ b/packages/plugin/src/features/spaces/ui/window/share-modal.ts @@ -1,17 +1,7 @@ import { ButtonComponent, Modal } from "obsidian"; - -import { isLinkState } from "@/hub/status"; -import type { PluginHost } from "@/plugin/host"; -import type { Person } from "@/presence"; -import { isRelayConfigured, relayAdmin } from "@/settings/model"; -import { errorMessage } from "@/shared"; -import { type SpaceRecord, shareIdentity } from "@/spaces/record"; -import { - type BrokerAdmin, - listParticipants, - type Participant, -} from "@/storage"; -import { isUnder } from "@/sync/space"; +import { isLinkState, RELAY_TEXT, relaySummary } from "@/core/hub"; +import { isRelayConfigured } from "@/core/settings"; +import { errorMessage } from "@/core/shared"; import { alertLine, modalCard, @@ -21,21 +11,29 @@ import { modalWarning, notifyError, openNote, - RELAY_TEXT, - relaySummary, renderKeepingFocus, serial, -} from "@/ui/common"; -import { createInvite } from "./invite-action"; -import { renderInviteForm } from "./invite-section"; -import { type Pause, renderPauseControl } from "./pause-control"; -import { renderPeople } from "./people-list"; +} from "@/core/ui"; +import type { Person } from "@/features/presence"; +import { isUnder } from "@/features/sync"; +import { + type BrokerAdmin, + listParticipants, + type Participant, + relayAdmin, +} from "../../broker/share-broker"; +import type { SpacesHost } from "../../host"; +import { type SpaceRecord, shareIdentity } from "../../record"; +import { createInvite } from "../invites/invite-action"; +import { renderInviteForm } from "../invites/invite-section"; import { closeLabel, closeShare, revokeAccess, strandedInvites, -} from "./share-action"; +} from "../share-action"; +import { type Pause, renderPauseControl } from "./pause-control"; +import { renderPeople } from "./people-list"; import { renderShareHead } from "./share-head"; import { presenceNote, selfRow, shareRows } from "./share-people"; @@ -50,7 +48,7 @@ export class ShareModal extends Modal { private readonly admin: BrokerAdmin | null; constructor( - private readonly plugin: PluginHost, + private readonly plugin: SpacesHost, private readonly record: SpaceRecord, private readonly onClosed?: () => void, ) { diff --git a/packages/plugin/src/ui/shares/share-people.ts b/packages/plugin/src/features/spaces/ui/window/share-people.ts similarity index 90% rename from packages/plugin/src/ui/shares/share-people.ts rename to packages/plugin/src/features/spaces/ui/window/share-people.ts index 2983a56f..5a283c38 100644 --- a/packages/plugin/src/ui/shares/share-people.ts +++ b/packages/plugin/src/features/spaces/ui/window/share-people.ts @@ -1,10 +1,10 @@ import { OWNER } from "@mdsync/protocol"; -import type { RelayStatus } from "@/hub/status"; -import type { Person } from "@/presence"; -import { type SpaceRecord, shareIdentity } from "@/spaces/record"; -import type { Participant } from "@/storage"; -import { RELAY_TEXT, UNREADABLE_TEXT } from "@/ui/common"; +import type { RelayStatus } from "@/core/hub"; +import { RELAY_TEXT, UNREADABLE_TEXT } from "@/core/hub"; +import type { Person } from "@/features/presence"; +import type { Participant } from "../../broker/share-broker"; +import { type SpaceRecord, shareIdentity } from "../../record"; export interface ShareRow { key: string; diff --git a/packages/plugin/src/ui/shares/share-summary.ts b/packages/plugin/src/features/spaces/ui/window/share-summary.ts similarity index 84% rename from packages/plugin/src/ui/shares/share-summary.ts rename to packages/plugin/src/features/spaces/ui/window/share-summary.ts index e738dc04..c358771e 100644 --- a/packages/plugin/src/ui/shares/share-summary.ts +++ b/packages/plugin/src/features/spaces/ui/window/share-summary.ts @@ -1,5 +1,6 @@ -import type { PauseKind, SpaceRecords } from "@/spaces"; -import type { SpaceRecord } from "@/spaces/record"; +import type { PauseKind } from "../../partition"; +import type { SpaceRecord } from "../../record"; +import type { SpaceRecords } from "../../records"; const PAUSED: Record = { here: ", paused on this device", diff --git a/packages/plugin/src/ui/shares/share-window.ts b/packages/plugin/src/features/spaces/ui/window/share-window.ts similarity index 78% rename from packages/plugin/src/ui/shares/share-window.ts rename to packages/plugin/src/features/spaces/ui/window/share-window.ts index 8a4b1aeb..516befe2 100644 --- a/packages/plugin/src/ui/shares/share-window.ts +++ b/packages/plugin/src/features/spaces/ui/window/share-window.ts @@ -1,18 +1,17 @@ import type { Menu } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; -import { ownerStorage } from "@/settings/model"; -import { mountError } from "@/spaces"; -import type { SpaceRecord } from "@/spaces/record"; -import { isUnder } from "@/sync/space"; -import { notifyError } from "@/ui/common"; -import { shareFolder } from "./share-action"; +import { notifyError } from "@/core/ui"; +import { isUnder } from "@/features/sync"; +import type { SpacesHost } from "../../host"; +import { ownerStorage } from "../../owner"; +import { mountError } from "../../partition"; +import type { SpaceRecord } from "../../record"; +import { shareFolder } from "../share-action"; import { ShareModal } from "./share-modal"; /** Folder menu entry: the window of the share the folder is or is in, else sharing it. */ export function addShareMenuItem( menu: Menu, - plugin: PluginHost, + plugin: SpacesHost, root: string, ): void { if (!plugin.settings.useSharedFolders) return; @@ -52,7 +51,7 @@ export function addShareMenuItem( /** The share's window, for its owner and for whoever it was shared with. */ export function openShareWindow( - plugin: PluginHost, + plugin: SpacesHost, record: SpaceRecord, onClosed?: () => void, ): void { diff --git a/packages/plugin/src/features/status/host.ts b/packages/plugin/src/features/status/host.ts new file mode 100644 index 00000000..fb0b6d91 --- /dev/null +++ b/packages/plugin/src/features/status/host.ts @@ -0,0 +1,9 @@ +import type { People, Unseen } from "@/features/presence"; +import type { HubConnection } from "@/features/relay"; +import type { SourceControlHost } from "@/features/source-control"; + +/** What the status bar and its menus need from the plugin. */ +export interface StatusHost extends SourceControlHost { + readonly unseen: Unseen; + readonly realtime: { readonly hub: HubConnection; readonly people: People }; +} diff --git a/packages/plugin/src/features/status/index.ts b/packages/plugin/src/features/status/index.ts new file mode 100644 index 00000000..ea6882da --- /dev/null +++ b/packages/plugin/src/features/status/index.ts @@ -0,0 +1,4 @@ +export type { StatusHost } from "./host"; +export { registerRibbon } from "./ribbon"; +export { registerStatusBar } from "./status-bar"; +export { openStatusMenu } from "./status-menu"; diff --git a/packages/plugin/src/features/status/live-spaces.ts b/packages/plugin/src/features/status/live-spaces.ts new file mode 100644 index 00000000..a3704649 --- /dev/null +++ b/packages/plugin/src/features/status/live-spaces.ts @@ -0,0 +1,71 @@ +import { isConnected, isLinkState, type LinkState } from "@/core/hub"; +import { isRelayConfigured } from "@/core/settings"; +import { relayBase } from "@/core/shared"; +import { isAtNote, type Person } from "@/features/presence"; +import { VAULT_SPACE } from "@/features/sync"; +import type { StatusHost } from "./host"; + +export interface CarriedSpace { + id: string; + status: LinkState; +} + +/** One socket and the spaces riding it: several shared folders on one relay share it. */ +export interface RelayGroup { + /** "Your relay", or the host of the relay a share was joined through. */ + name: string; + state: LinkState; + spaces: CarriedSpace[]; + /** On this relay, but past its slots. */ + full: string[]; +} + +export function carried(plugin: StatusHost): CarriedSpace[] { + return plugin.spaces.partition().flatMap(({ id }) => { + const status = plugin.realtime.hub.statusOf(id); + return isLinkState(status) ? [{ id, status }] : []; + }); +} + +/** The carried spaces by the socket that carries them, this device's own relay first. */ +export function relayGroups(plugin: StatusHost): RelayGroup[] { + const shown = new Set(plugin.spaces.partition().map(({ id }) => id)); + const all = carried(plugin); + const { settings } = plugin; + const own = isRelayConfigured(settings) ? relayBase(settings.relayUrl) : null; + return plugin.realtime.hub + .relays() + .flatMap(({ url, state, spaces, full }) => { + const riding = all.filter(({ id }) => spaces.includes(id)); + const left = full.filter((id) => shown.has(id)); + if (riding.length === 0 && left.length === 0) return []; + const name = url === own ? "Your relay" : hostOf(url); + return [{ name, state, spaces: riding, full: left }]; + }); +} + +/** Only a connected shared folder shows who is in it; without one, "nobody" would be a guess. */ +export function sharesConnected(spaces: readonly CarriedSpace[]): boolean { + return spaces.some( + ({ id, status }) => id !== VAULT_SPACE.id && isConnected(status), + ); +} + +export function inSharedNotes(plugin: StatusHost): Person[] { + return carried(plugin) + .filter(({ id }) => id !== VAULT_SPACE.id) + .flatMap(({ id }) => plugin.realtime.people.online(id).filter(isAtNote)); +} + +export function spaceName(plugin: StatusHost, id: string): string { + if (id === VAULT_SPACE.id) return "Vault"; + return plugin.spaces.get(id)?.name ?? id; +} + +function hostOf(url: string): string { + try { + return new URL(url).host; + } catch { + return url; + } +} diff --git a/packages/plugin/src/ui/live/status/relay-status.ts b/packages/plugin/src/features/status/relay-status.ts similarity index 90% rename from packages/plugin/src/ui/live/status/relay-status.ts rename to packages/plugin/src/features/status/relay-status.ts index 1b98a3e8..81840971 100644 --- a/packages/plugin/src/ui/live/status/relay-status.ts +++ b/packages/plugin/src/features/status/relay-status.ts @@ -1,20 +1,19 @@ import type { Plugin } from "obsidian"; - -import { isConnected, type LinkState } from "@/hub/status"; -import type { PluginHost } from "@/plugin/host"; -import type { Person } from "@/presence"; import { - describePeople, + isConnected, + type LinkState, RELAY_TEXT, relaySummary, - renderAvatarStack, UNREADABLE_TEXT, -} from "@/ui/common"; +} from "@/core/hub"; +import type { Person } from "@/features/presence"; +import { describePeople, renderAvatarStack } from "@/features/presence"; +import type { StatusHost } from "./host"; import { carried, inSharedNotes } from "./live-spaces"; /** The status bar's relay half: one dot for the link of every space it carries, and who is in shared notes. */ export function mountRelayStatus( - plugin: Plugin & PluginHost, + plugin: Plugin & StatusHost, el: HTMLElement, onChange: () => void, ): void { diff --git a/packages/plugin/src/styles/ribbon.css b/packages/plugin/src/features/status/ribbon.css similarity index 100% rename from packages/plugin/src/styles/ribbon.css rename to packages/plugin/src/features/status/ribbon.css diff --git a/packages/plugin/src/ui/ribbon.ts b/packages/plugin/src/features/status/ribbon.ts similarity index 68% rename from packages/plugin/src/ui/ribbon.ts rename to packages/plugin/src/features/status/ribbon.ts index e0f3a427..12a4a6c6 100644 --- a/packages/plugin/src/ui/ribbon.ts +++ b/packages/plugin/src/features/status/ribbon.ts @@ -1,12 +1,14 @@ import type { App, Plugin } from "obsidian"; -import { SOURCE_CONTROL_VIEW_TYPE } from "@/constants"; -import type { HubConnection } from "@/hub"; -import type { SyncController, SyncStatusSnapshot } from "@/sync/controller"; -import { openSourceControlView } from "./source-control-view"; +import { SOURCE_CONTROL_VIEW_TYPE } from "@/core/constants"; +import type { HubConnection } from "@/features/relay"; +import { openSourceControlView } from "@/features/source-control"; +import type { SyncController, SyncStatusSnapshot } from "@/features/sync"; +import type { StatusHost } from "./host"; +import { syncHeadline } from "./status-menu"; export function registerRibbon( - plugin: Plugin, + plugin: Plugin & StatusHost, controller: SyncController, hub: Pick, ): void { @@ -27,7 +29,8 @@ export function registerRibbon( const hasConflict = snapshot.conflicts > 0; icon.toggleClass("is-pending", pending > 0 || hasConflict); icon.toggleClass("is-conflict", hasConflict); - icon.setAttr("aria-label", buildLabel(snapshot)); + // The status bar's words, so the two never disagree. + icon.setAttr("aria-label", `MDSync: ${syncHeadline(plugin, snapshot)}`); }; // A CSS class, not an element: `setIcon` removes the first child and appends a new one, so an element of ours @@ -45,11 +48,3 @@ export function registerRibbon( unlisten(); }); } - -function buildLabel(snapshot: SyncStatusSnapshot): string { - if (snapshot.conflicts > 0) - return `MDSync — ${snapshot.conflicts} conflict(s)`; - const pending = snapshot.pendingLocal + snapshot.pendingRemote; - if (pending === 0) return "MDSync — no changes"; - return `MDSync — ${snapshot.pendingLocal} to push, ${snapshot.pendingRemote} to pull`; -} diff --git a/packages/plugin/src/features/status/status-bar.css b/packages/plugin/src/features/status/status-bar.css new file mode 100644 index 00000000..52a297b6 --- /dev/null +++ b/packages/plugin/src/features/status/status-bar.css @@ -0,0 +1,142 @@ +.mdsync-status-bar, +.mdsync-status-sync, +.mdsync-status-relay { + display: inline-flex; + gap: var(--size-4-2); + align-items: center; +} + +.mdsync-status-bar:focus-visible { + outline: 2px solid var(--interactive-accent); + outline-offset: -2px; +} + +.mdsync-status-sync { + font-variant-numeric: tabular-nums; +} + +.mdsync-status-part { + display: inline-flex; + gap: var(--size-2-1); + align-items: center; +} + +.mdsync-status-part svg { + width: var(--icon-xs); + height: var(--icon-xs); +} + +.mdsync-status-sync.is-error, +.mdsync-status-part.is-conflict { + color: var(--color-red); +} + +/* Mutually exclusive with is-error (see status-bar.ts), so order is free. */ +.mdsync-status-sync.is-offline, +.mdsync-status-part.is-offline { + color: var(--text-muted); +} + +.mdsync-status-relay { + --mdsync-avatar: 16px; +} + +/* A hairline between where sync stands and the relay. */ +.mdsync-status-relay::before { + content: ""; + width: 1px; + height: 12px; + background: var(--background-modifier-border); +} + +.mdsync-status-relay.mdsync-hidden { + display: none; +} + +.mdsync-menu-headline { + color: var(--text-normal); + font-weight: var(--font-semibold); +} + +.mdsync-menu-detail { + color: var(--text-muted); + font-size: var(--font-ui-smaller); +} + +/* The folders on one relay hang from its icon: an icon-less label's title starts under the icon's middle. */ +.mdsync-relay-member { + position: relative; + display: block; + padding-left: var(--size-4-4); +} + +/* The rail overshoots and the item clips it, so stacked items join whatever padding a platform gives them. */ +.menu-item:has(.mdsync-relay-member) { + overflow: hidden; +} + +/* A share is a button, the vault a label: both set like the relay above them, the title unclipped for the rail. */ +.menu .menu-item:has(.mdsync-relay-member) .menu-item-title { + display: block; + overflow: visible; + white-space: normal; + -webkit-line-clamp: none; +} + +body:not(.is-phone) .menu-item:has(.mdsync-relay-member) { + font-size: var(--font-ui-small); +} + +/* A phone sets tappable items in a card with dividers, which would cut the rail into pieces. */ +body.is-phone .menu-item:has(.mdsync-relay-member) { + border-radius: 0; + background-color: transparent; +} + +body.is-phone .menu-item:has(.mdsync-relay-member):active { + background-color: var(--background-modifier-hover); +} + +body.is-phone .menu-group .menu-item:has(.mdsync-relay-member)::after { + display: none; +} + +.mdsync-relay-member::before, +.mdsync-relay-member::after { + content: ""; + position: absolute; + left: 0; + border-color: var(--background-modifier-border-hover); + border-style: solid; + border-width: 0; +} + +.mdsync-relay-member::before { + top: -100px; + bottom: -100px; + border-left-width: 1px; +} + +.mdsync-relay-member::after { + top: 0.5lh; + width: var(--size-4-2); + border-top-width: 1px; +} + +.mdsync-relay-member.is-last::before { + bottom: calc(100% - 0.5lh); +} + +.mdsync-relay-member.is-trouble .mdsync-person-state { + color: var(--color-orange); +} + +/* A host breaks at its hyphens: the state goes under it instead. */ +.mdsync-relay-name { + display: inline-block; + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + vertical-align: bottom; +} diff --git a/packages/plugin/src/ui/status-bar.ts b/packages/plugin/src/features/status/status-bar.ts similarity index 89% rename from packages/plugin/src/ui/status-bar.ts rename to packages/plugin/src/features/status/status-bar.ts index d9f29ff7..7d642630 100644 --- a/packages/plugin/src/ui/status-bar.ts +++ b/packages/plugin/src/features/status/status-bar.ts @@ -1,19 +1,21 @@ import { type Plugin, setIcon } from "obsidian"; - -import { RELATIVE_TIME_REFRESH_MS } from "@/constants"; -import type { PluginHost } from "@/plugin/host"; -import { canSync } from "@/settings/model"; -import { formatRelativeTime, OFFLINE_MESSAGE, pluralize } from "@/shared"; -import { type SyncStatusSnapshot, splitSpaceErrors } from "@/sync/controller"; -import { makeActivatable } from "./common/activatable"; -import { mountRelayStatus } from "./live/status/relay-status"; +import { RELATIVE_TIME_REFRESH_MS } from "@/core/constants"; +import { formatRelativeTime, OFFLINE_MESSAGE, pluralize } from "@/core/shared"; +import { makeActivatable } from "@/core/ui"; +import { + canSync, + type SyncStatusSnapshot, + splitSpaceErrors, +} from "@/features/sync"; +import type { StatusHost } from "./host"; +import { mountRelayStatus } from "./relay-status"; import { openStatusMenu, syncHeadline } from "./status-menu"; /** * One item: where sync stands, then the relay and who is in shared notes; selecting it opens their menu. * Returns a repaint for what no snapshot announces, such as finishing setup. */ -export function registerStatusBar(plugin: Plugin & PluginHost): () => void { +export function registerStatusBar(plugin: Plugin & StatusHost): () => void { const { controller } = plugin; const root = plugin.addStatusBarItem(); root.addClass("mdsync-status-bar", "mod-clickable"); @@ -96,7 +98,7 @@ function renderSync( ).addClass("is-offline"); } if (!snapshot.result) { - part(el, "cloud", "Not compared"); + part(el, "cloud", "Not compared yet"); return; } if (conflicts > 0) { @@ -117,7 +119,7 @@ function part(parent: HTMLElement, icon: string, text: string): HTMLElement { } function tooltip( - plugin: PluginHost, + plugin: StatusHost, snapshot: SyncStatusSnapshot, offline: boolean, ): string { diff --git a/packages/plugin/src/ui/status-menu.ts b/packages/plugin/src/features/status/status-menu.ts similarity index 84% rename from packages/plugin/src/ui/status-menu.ts rename to packages/plugin/src/features/status/status-menu.ts index d4c4212f..e3f4c00a 100644 --- a/packages/plugin/src/ui/status-menu.ts +++ b/packages/plugin/src/features/status/status-menu.ts @@ -1,22 +1,26 @@ import { Menu } from "obsidian"; - -import { SOURCE_CONTROL_VIEW_TYPE } from "@/constants"; -import type { PluginHost } from "@/plugin/host"; -import { canSync } from "@/settings/model"; -import { formatRelativeTime, pluralize } from "@/shared"; -import { type SyncStatusSnapshot, splitSpaceErrors } from "@/sync/controller"; -import { runPullAll, runPushAll } from "./actions/sync-actions"; -import { showMenuAt } from "./common"; -import { addRelaySections } from "./live/status/where-menu"; -import { canPullAll, canPushAll } from "./source-control/sync-gates"; +import { SOURCE_CONTROL_VIEW_TYPE } from "@/core/constants"; +import { formatRelativeTime, pluralize } from "@/core/shared"; +import { showMenuAt } from "@/core/ui"; +import { openDiffView } from "@/features/diff"; import { - openDiffView, openSourceControlChanges, openSourceControlView, -} from "./source-control-view"; +} from "@/features/source-control"; +import { + canPullAll, + canPushAll, + canSync, + runPullAll, + runPushAll, + type SyncStatusSnapshot, + splitSpaceErrors, +} from "@/features/sync"; +import type { StatusHost } from "./host"; +import { addRelaySections } from "./where-menu"; /** The status bar item's menu, and on a phone the command's: where sync stands, what to do next, the relay. */ -export function openStatusMenu(plugin: PluginHost, anchor?: HTMLElement): void { +export function openStatusMenu(plugin: StatusHost, anchor?: HTMLElement): void { const menu = new Menu(); const snapshot = plugin.controller.getSnapshot(); menu.addItem((item) => @@ -40,7 +44,7 @@ export function openStatusMenu(plugin: PluginHost, anchor?: HTMLElement): void { function addSyncActions( menu: Menu, - plugin: PluginHost, + plugin: StatusHost, snapshot: SyncStatusSnapshot, ): void { if (!canSync(plugin.settings)) { @@ -106,7 +110,7 @@ function addSyncActions( } function summaryTitle( - plugin: PluginHost, + plugin: StatusHost, snapshot: SyncStatusSnapshot, ): DocumentFragment { const title = createFragment(); @@ -125,7 +129,7 @@ function summaryTitle( /** "3 to push · 1 conflict": the menu's head, and what the status bar item announces. */ export function syncHeadline( - plugin: PluginHost, + plugin: StatusHost, snapshot: SyncStatusSnapshot, ): string { if (!canSync(plugin.settings)) return "Sync is not set up"; @@ -149,6 +153,6 @@ export function syncHeadline( return parts.length > 0 ? parts.join(" · ") : "Everything is in sync"; } -async function openSourceControl(plugin: PluginHost): Promise { +async function openSourceControl(plugin: StatusHost): Promise { await openSourceControlView(plugin.app, SOURCE_CONTROL_VIEW_TYPE); } diff --git a/packages/plugin/src/features/status/where-menu.ts b/packages/plugin/src/features/status/where-menu.ts new file mode 100644 index 00000000..44a32c96 --- /dev/null +++ b/packages/plugin/src/features/status/where-menu.ts @@ -0,0 +1,171 @@ +import type { Menu } from "obsidian"; +import { + FULL_SHORT_TEXT, + isConnected, + LINK_TEXT, + type LinkState, + RELAY_TEXT, + relayFixOf, + UNREADABLE_TEXT, +} from "@/core/hub"; +import { infoTitle, openNote, openPluginSettings } from "@/core/ui"; +import { LINK_LIVE_STATE, STATE_ICONS } from "@/features/live"; +import { personTitle } from "@/features/presence"; +import { lastEditLabel, openShareWindow } from "@/features/spaces"; +import { VAULT_SPACE } from "@/features/sync"; +import type { StatusHost } from "./host"; +import { + type CarriedSpace, + carried, + inSharedNotes, + type RelayGroup, + relayGroups, + sharesConnected, + spaceName, +} from "./live-spaces"; + +/** The relay of every space, its fixes, who is in shared notes and what others changed. */ +export function addRelaySections(menu: Menu, plugin: StatusHost): void { + const spaces = carried(plugin); + addStatuses(menu, plugin, spaces); + addRelayFixes(menu, plugin, spaces); + menu.addSeparator(); + const here = inSharedNotes(plugin); + if (here.length === 0 && sharesConnected(spaces)) { + menu.addItem((item) => + item.setTitle(infoTitle("Nobody is in a shared note")).setIsLabel(true), + ); + } + for (const person of here) { + const note = person.note ?? ""; + menu.addItem((item) => + item + .setTitle(personTitle(person, note)) + .onClick(() => void openNote(plugin.app, note)), + ); + } + addUnseen(menu, plugin); +} + +function addStatuses( + menu: Menu, + plugin: StatusHost, + spaces: readonly CarriedSpace[], +): void { + const groups = relayGroups(plugin); + if (spaces.length === 0 || groups.length === 0) { + menu.addItem((item) => + item + .setTitle( + infoTitle(RELAY_TEXT[plugin.realtime.hub.statusOf(VAULT_SPACE.id)]), + ) + .setIcon(STATE_ICONS.cold) + .setIsLabel(true), + ); + return; + } + for (const group of groups) addGroup(menu, plugin, group); +} + +/** The relay, then the folders on its one socket, hung from its icon by a rail; a share opens its window. */ +function addGroup(menu: Menu, plugin: StatusHost, group: RelayGroup): void { + const { name, state, spaces, full } = group; + const head = createFragment(); + head.createSpan({ cls: "mdsync-menu-info mdsync-relay-name", text: name }); + head.createSpan({ cls: "mdsync-person-state", text: LINK_TEXT[state] }); + menu.addItem((item) => + item + .setTitle(head) + .setIcon(STATE_ICONS[LINK_LIVE_STATE[state]]) + .setIsLabel(true), + ); + const members = [ + ...spaces.map(({ id, status }) => ({ + id, + note: memberNote(plugin, id, status, state), + })), + ...full.map((id) => ({ id, note: FULL_SHORT_TEXT })), + ]; + members.forEach(({ id, note }, at) => { + const title = createFragment(); + const row = title.createSpan({ cls: "mdsync-relay-member" }); + row.toggleClass("is-last", at === members.length - 1); + row.toggleClass("is-trouble", note !== null); + row.createSpan({ cls: "mdsync-menu-info", text: spaceName(plugin, id) }); + if (note) row.createSpan({ cls: "mdsync-person-state", text: note }); + const record = id === VAULT_SPACE.id ? undefined : plugin.spaces.get(id); + menu.addItem((item) => { + item.setTitle(title); + if (record) item.onClick(() => openShareWindow(plugin, record)); + else item.setIsLabel(true); + }); + }); +} + +/** Said only where a folder differs from its relay: the socket's word covers the rest. */ +function memberNote( + plugin: StatusHost, + id: string, + status: LinkState, + socket: LinkState, +): string | null { + if (status !== socket) return LINK_TEXT[status]; + if (isConnected(status) && plugin.realtime.people.unreadable(id)) { + return UNREADABLE_TEXT; + } + return null; +} + +function addRelayFixes( + menu: Menu, + plugin: StatusHost, + spaces: readonly CarriedSpace[], +): void { + const unreachable = spaces.filter( + ({ status }) => relayFixOf(status) === "reconnect", + ); + const refused = spaces.some( + ({ status }) => relayFixOf(status) === "settings", + ); + if (unreachable.length === 0 && !refused) return; + menu.addSeparator(); + if (unreachable.length > 0) { + menu.addItem((item) => + item + .setTitle("Reconnect") + .setIcon("refresh-cw") + .onClick(() => { + for (const { id } of unreachable) plugin.realtime.hub.reconnect(id); + }), + ); + } + if (refused) { + menu.addItem((item) => + item + .setTitle("Open relay settings") + .setIcon("settings") + .onClick(() => openPluginSettings(plugin.app)), + ); + } +} + +function addUnseen(menu: Menu, plugin: StatusHost): void { + const notes = [...plugin.unseen.all()].filter((path) => + plugin.app.vault.getFileByPath(path), + ); + const latest = notes.at(-1); + if (latest === undefined) return; + menu.addSeparator(); + menu.addItem((item) => + item + .setTitle(infoTitle(`${notes.length} changed by others`)) + .setIcon("dot") + .setIsLabel(true), + ); + const edited = lastEditLabel(plugin, latest); + if (edited) { + menu.addItem((item) => + item.setTitle(infoTitle(edited)).setIcon("pencil").setIsLabel(true), + ); + } +} diff --git a/packages/plugin/src/storage/adapters/google-drive-auth.ts b/packages/plugin/src/features/storage/backends/google-drive-auth.ts similarity index 92% rename from packages/plugin/src/storage/adapters/google-drive-auth.ts rename to packages/plugin/src/features/storage/backends/google-drive-auth.ts index e99cb541..132eb17e 100644 --- a/packages/plugin/src/storage/adapters/google-drive-auth.ts +++ b/packages/plugin/src/features/storage/backends/google-drive-auth.ts @@ -1,17 +1,11 @@ import { toHex } from "@mdsync/protocol"; import type { ObsidianProtocolData } from "obsidian"; -import { randomBytes } from "@/crypto"; -import { relayBase } from "@/shared"; -import { - EStorageBackend, - type GoogleDriveStorageConfig, -} from "@/storage/config"; -import { - CONCURRENCY_FIELD, - EFieldKind, - type SettingsFieldSpec, -} from "@/storage/field-spec"; -import type { StorageAuthOutcome } from "@/storage/types"; +import { randomBytes } from "@/core/crypto"; +import { EFieldKind } from "@/core/settings"; +import { relayBase } from "@/core/shared"; +import { EStorageBackend, type GoogleDriveStorageConfig } from "../config"; +import { CONCURRENCY_FIELD, type SettingsFieldSpec } from "../field-spec"; +import type { StorageAuthOutcome } from "../types"; export function googleAuthUrl( config: Pick, diff --git a/packages/plugin/src/storage/adapters/google-drive-request.ts b/packages/plugin/src/features/storage/backends/google-drive-request.ts similarity index 93% rename from packages/plugin/src/storage/adapters/google-drive-request.ts rename to packages/plugin/src/features/storage/backends/google-drive-request.ts index 00428804..013f6a75 100644 --- a/packages/plugin/src/storage/adapters/google-drive-request.ts +++ b/packages/plugin/src/features/storage/backends/google-drive-request.ts @@ -1,12 +1,12 @@ import { type RequestUrlParam, requestUrl } from "obsidian"; -import { StorageRequestError } from "@/storage/types"; +import { StorageHttpError } from "@/core/shared"; +import { StorageRequestError } from "../types"; import { isRetryableStatus, - StorageHttpError, transferBytes, withDeadline, withRetry, -} from "./util"; +} from "./http"; const FORBIDDEN = 403; const TOO_MANY_REQUESTS = 429; diff --git a/packages/plugin/src/storage/adapters/google-drive-upload.ts b/packages/plugin/src/features/storage/backends/google-drive-upload.ts similarity index 97% rename from packages/plugin/src/storage/adapters/google-drive-upload.ts rename to packages/plugin/src/features/storage/backends/google-drive-upload.ts index b00ac86f..cdde9ee8 100644 --- a/packages/plugin/src/storage/adapters/google-drive-upload.ts +++ b/packages/plugin/src/features/storage/backends/google-drive-upload.ts @@ -1,6 +1,6 @@ -import { toArrayBuffer } from "@/utils"; +import { toArrayBuffer } from "@/core/utils"; import { type AuthorizedRequest, driveRequest } from "./google-drive-request"; -import { assertOk } from "./util"; +import { assertOk } from "./http"; const DRIVE_UPLOAD_API = "https://www.googleapis.com/upload/drive/v3/files"; /** Multipart max; larger files go resumable. */ diff --git a/packages/plugin/src/storage/adapters/google-drive.ts b/packages/plugin/src/features/storage/backends/google-drive.ts similarity index 90% rename from packages/plugin/src/storage/adapters/google-drive.ts rename to packages/plugin/src/features/storage/backends/google-drive.ts index 8326e1ab..6885ca59 100644 --- a/packages/plugin/src/storage/adapters/google-drive.ts +++ b/packages/plugin/src/features/storage/backends/google-drive.ts @@ -1,10 +1,7 @@ import type { RequestUrlParam } from "obsidian"; -import type { GoogleDriveStorageConfig } from "@/storage/config"; -import type { - ConditionalRead, - ListedObject, - StorageAdapter, -} from "@/storage/types"; +import { StorageHttpError } from "@/core/shared"; +import type { GoogleDriveStorageConfig } from "../config"; +import type { ConditionalRead, ListedObject, StorageAdapter } from "../types"; import { computeExpiresAt, googleAuthUrl, @@ -12,7 +9,7 @@ import { } from "./google-drive-auth"; import { type AuthorizedRequest, driveRequest } from "./google-drive-request"; import { sendUpload } from "./google-drive-upload"; -import { assertOk, dateOf, StorageHttpError } from "./util"; +import { assertOk, dateOf } from "./http"; const DRIVE_API = "https://www.googleapis.com/drive/v3/files"; const DRIVE_PAGE_SIZE = "1000"; @@ -22,6 +19,14 @@ const PREPARE_READS_MIN = 256; const PRIME_PAGE_SLACK = 2; const NOT_FOUND = 404; +interface Hint { + keys: Set; + prefix: string; + ready?: Promise; + // Write hints: keys the listing did not find. Only put() may create them unlooked: exists() and putIfAbsent() must ask. + absent?: Set; +} + interface GoogleDriveListResponse { files?: { id?: string; @@ -52,18 +57,8 @@ export function createGoogleDriveAdapter( // name -> file id. Only positive entries are cached: a negative one would keep reporting a file another // device uploaded this session as missing, failing the pull. const fileIdCache = new Map(); - let readHint: { - keys: Set; - prefix: string; - ready?: Promise; - } | null = null; - let writeHint: { - keys: Set; - prefix: string; - ready?: Promise; - // Hinted keys the listing did not find. Only put() may create them unlooked: exists() and putIfAbsent() must ask. - absent?: Set; - } | null = null; + let readHints: Hint[] = []; + let writeHints: Hint[] = []; const refreshAccessToken = async (): Promise => { const res = await driveRequest({ @@ -250,16 +245,17 @@ export function createGoogleDriveAdapter( return res.json as { md5Checksum?: string; headRevisionId?: string }; }; - /** A hint is worth one listing when many uncached keys share a prefix. */ - const hintOf = (keys: string[]) => { - const missing = keys.filter((key) => !fileIdCache.has(key)); - const first = missing[0]; - const prefix = first?.slice(0, first.lastIndexOf("/") + 1) ?? ""; - return missing.length >= PREPARE_READS_MIN && - prefix !== "" && - missing.every((key) => key.startsWith(prefix)) - ? { keys: new Set(missing), prefix } - : null; + /** A folder is worth one listing when many uncached keys share it; a batch may span several. */ + const hintsOf = (keys: string[]): Hint[] => { + const byPrefix = new Map>(); + for (const key of keys) { + const prefix = key.slice(0, key.lastIndexOf("/") + 1); + if (prefix === "" || fileIdCache.has(key)) continue; + byPrefix.set(prefix, (byPrefix.get(prefix) ?? new Set()).add(key)); + } + return [...byPrefix] + .filter(([, group]) => group.size >= PREPARE_READS_MIN) + .map(([prefix, group]) => ({ keys: group, prefix })); }; /** @@ -338,22 +334,22 @@ export function createGoogleDriveAdapter( }, prepareReads(keys) { - readHint = hintOf(keys); + readHints = hintsOf(keys); }, prepareWrites(keys) { - writeHint = hintOf(keys); + writeHints = hintsOf(keys); }, async get(key: string, size?: number): Promise { - if (readHint?.keys.has(key) && !fileIdCache.has(key)) { - const hint = readHint; + const hint = readHints.find((each) => each.keys.has(key)); + if (hint && !fileIdCache.has(key)) { hint.ready ??= listObjects(hint.prefix, false, hint).then( () => undefined, () => undefined, ); await hint.ready; - if (readHint === hint) readHint = null; + readHints = readHints.filter((each) => each !== hint); } const cached = fileIdCache.has(key); const body = await download(key, size); @@ -383,8 +379,8 @@ export function createGoogleDriveAdapter( }, async put(key, body, contentType) { - const hint = writeHint; - if (hint?.keys.has(key) && !fileIdCache.has(key)) { + const hint = writeHints.find((each) => each.keys.has(key)); + if (hint && !fileIdCache.has(key)) { hint.ready ??= listObjects(hint.prefix, false, hint).then( ({ complete }) => { // A cut-short listing proves nothing absent: the rest are looked up exactly. diff --git a/packages/plugin/src/storage/adapters/util.ts b/packages/plugin/src/features/storage/backends/http.ts similarity index 91% rename from packages/plugin/src/storage/adapters/util.ts rename to packages/plugin/src/features/storage/backends/http.ts index 983756ad..5ff0a8bf 100644 --- a/packages/plugin/src/storage/adapters/util.ts +++ b/packages/plugin/src/features/storage/backends/http.ts @@ -1,4 +1,8 @@ -import { isNetworkError } from "@/shared"; +import { + isNetworkError, + StorageHttpError, + StorageTimeoutError, +} from "@/core/shared"; const RETRY_DELAYS_MS: ReadonlyArray = [500, 2_000, 5_000]; @@ -8,26 +12,6 @@ const FLOOR_BYTES_PER_SECOND = 128 * 1024; /** A timeout past this size is not retried in place: requestUrl cannot be cancelled, so the first request is still running. */ const RETRY_MAX_BYTES = 1024 * 1024; -export class StorageHttpError extends Error { - constructor( - readonly status: number, - message: string, - ) { - super(message); - this.name = "StorageHttpError"; - } -} - -export class StorageTimeoutError extends Error { - constructor( - ms: number, - readonly bytes = 0, - ) { - super(`Storage operation timed out after ${ms}ms`); - this.name = "StorageTimeoutError"; - } -} - function delay(ms: number): Promise { return new Promise((resolve) => window.setTimeout(resolve, ms)); } diff --git a/packages/plugin/src/storage/adapters/s3-signer.ts b/packages/plugin/src/features/storage/backends/s3-signer.ts similarity index 72% rename from packages/plugin/src/storage/adapters/s3-signer.ts rename to packages/plugin/src/features/storage/backends/s3-signer.ts index d3b6f2b6..c7cde2eb 100644 --- a/packages/plugin/src/storage/adapters/s3-signer.ts +++ b/packages/plugin/src/features/storage/backends/s3-signer.ts @@ -1,27 +1,29 @@ -import { toHex } from "@mdsync/protocol"; - -import { sha256Hex } from "@/crypto"; -import type { S3StorageConfig } from "@/storage/config"; +import { + amzTimestamp, + canonicalizeQuery, + decodePath, + deriveSigningKey, + encodePath, + hmac, + SIGV4_ALGORITHM, + SIGV4_SERVICE, + toHex, + UNSIGNED_PAYLOAD, +} from "@mdsync/protocol"; + +import { sha256Hex } from "@/core/crypto"; +import type { S3StorageConfig } from "../config"; /** * SigV4 signing for S3-compatible storage, so requests go through Obsidian's `requestUrl` instead of * `fetch`: at origin `app://obsidian.md` fetch is subject to CORS, which most backends reject until the * user hand-writes a bucket CORS policy. */ -const ALGORITHM = "AWS4-HMAC-SHA256"; -const SERVICE = "s3"; /** SHA-256 of the empty string: the payload hash of a request with no body. */ const EMPTY_PAYLOAD_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; -/** - * Hashing an upload is a second full pass over every blob on the UI thread. Over HTTPS TLS protects the - * body and AWS documents this option; a plain-HTTP endpoint (a LAN MinIO) has no transport integrity, so - * there the body is hashed. - */ -const UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; - const AWS_DEFAULT_REGION = "us-east-1"; const encoder = new TextEncoder(); @@ -54,12 +56,11 @@ export function createS3Signer(config: S3StorageConfig): S3Signer { const signingKey = async (dateStamp: string): Promise => { if (cached?.dateStamp === dateStamp) return cached.key; - let key = await importHmacKey( - encoder.encode(`AWS4${config.secretAccessKey}`), + const key = await deriveSigningKey( + config.secretAccessKey, + dateStamp, + region, ); - for (const part of [dateStamp, region, SERVICE, "aws4_request"]) { - key = await importHmacKey(await hmac(key, part)); - } cached = { dateStamp, key }; return key; }; @@ -68,7 +69,7 @@ export function createS3Signer(config: S3StorageConfig): S3Signer { const canonicalUri = objectUri(config, endpoint.basePath, input.key); const canonicalQuery = canonicalizeQuery(input.query ?? {}); const payloadHash = await payloadDigest(input.body, endpoint.protocol); - const amzDate = timestamp(); + const amzDate = amzTimestamp(); const dateStamp = amzDate.slice(0, 8); const signed: Record = { host: endpoint.host }; @@ -94,9 +95,9 @@ export function createS3Signer(config: S3StorageConfig): S3Signer { payloadHash, ].join("\n"); - const scope = `${dateStamp}/${region}/${SERVICE}/aws4_request`; + const scope = `${dateStamp}/${region}/${SIGV4_SERVICE}/aws4_request`; const stringToSign = [ - ALGORITHM, + SIGV4_ALGORITHM, amzDate, scope, await sha256Hex(encoder.encode(canonicalRequest)), @@ -114,7 +115,7 @@ export function createS3Signer(config: S3StorageConfig): S3Signer { "x-amz-content-sha256": payloadHash, "x-amz-date": amzDate, Authorization: - `${ALGORITHM} Credential=${config.accessKeyId}/${scope}, ` + + `${SIGV4_ALGORITHM} Credential=${config.accessKeyId}/${scope}, ` + `SignedHeaders=${signedHeaders}, Signature=${signature}`, }, }; @@ -161,6 +162,11 @@ function resolveEndpoint(config: S3StorageConfig): ResolvedEndpoint { }; } +/** + * Hashing an upload is a second full pass over every blob on the UI thread. Over HTTPS TLS protects the + * body and AWS documents UNSIGNED-PAYLOAD; a plain-HTTP endpoint (a LAN MinIO) has no transport integrity, + * so there the body is hashed. + */ async function payloadDigest( body: Uint8Array | undefined, protocol: string, @@ -186,58 +192,3 @@ function objectUri( : `/${key}`; return encodePath(`${basePath}${path}`) || "/"; } - -function canonicalizeQuery(query: Record): string { - return Object.keys(query) - .sort() - .map((name) => `${encodeRfc3986(name)}=${encodeRfc3986(query[name] ?? "")}`) - .join("&"); -} - -/** `20260907T101530Z`, the only format SigV4 accepts. */ -function timestamp(): string { - return new Date() - .toISOString() - .replace(/[:-]/g, "") - .replace(/\.\d{3}/, ""); -} - -function importHmacKey(raw: BufferSource): Promise { - return crypto.subtle.importKey( - "raw", - raw, - { name: "HMAC", hash: "SHA-256" }, - false, - ["sign"], - ); -} - -function hmac(key: CryptoKey, data: string): Promise { - return crypto.subtle.sign("HMAC", key, encoder.encode(data)); -} - -/** `encodeURIComponent` leaves these, and SigV4 requires them encoded. */ -function encodeRfc3986(value: string): string { - return encodeURIComponent(value).replace( - /[!'()*]/g, - (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`, - ); -} - -/** Percent-encodes each path segment, leaving the separators intact. */ -function encodePath(path: string): string { - return path.split("/").map(encodeRfc3986).join("/"); -} - -function decodePath(path: string): string { - return path - .split("/") - .map((segment) => { - try { - return decodeURIComponent(segment); - } catch { - return segment; - } - }) - .join("/"); -} diff --git a/packages/plugin/src/storage/adapters/s3-store.ts b/packages/plugin/src/features/storage/backends/s3-store.ts similarity index 98% rename from packages/plugin/src/storage/adapters/s3-store.ts rename to packages/plugin/src/features/storage/backends/s3-store.ts index 64ba4336..86d7c523 100644 --- a/packages/plugin/src/storage/adapters/s3-store.ts +++ b/packages/plugin/src/features/storage/backends/s3-store.ts @@ -1,25 +1,23 @@ import { requestUrl } from "obsidian"; - +import { StorageHttpError } from "@/core/shared"; +import { toArrayBuffer } from "@/core/utils"; import { type ConditionalRead, type ListedObject, type StorageAdapter, StorageRequestError, -} from "@/storage/types"; -import { toArrayBuffer } from "@/utils"; - -import type { S3RequestInput, S3Signer } from "./s3-signer"; -import { parseErrorCode, parseListObjects } from "./s3-xml"; +} from "../types"; import { assertOk, headerValue, isRetryableError, isRetryableStatus, - StorageHttpError, transferBytes, withDeadline, withRetry, -} from "./util"; +} from "./http"; +import type { S3RequestInput, S3Signer } from "./s3-signer"; +import { parseErrorCode, parseListObjects } from "./s3-xml"; const HTTP_NOT_FOUND = 404; const HTTP_NOT_MODIFIED = 304; diff --git a/packages/plugin/src/storage/adapters/s3-xml.ts b/packages/plugin/src/features/storage/backends/s3-xml.ts similarity index 97% rename from packages/plugin/src/storage/adapters/s3-xml.ts rename to packages/plugin/src/features/storage/backends/s3-xml.ts index 81a9c7c7..94d85a1b 100644 --- a/packages/plugin/src/storage/adapters/s3-xml.ts +++ b/packages/plugin/src/features/storage/backends/s3-xml.ts @@ -4,8 +4,8 @@ * match is exact for well-formed documents. */ -import type { ListedObject } from "@/storage/types"; -import { dateOf } from "./util"; +import type { ListedObject } from "../types"; +import { dateOf } from "./http"; export interface ListPage { objects: ListedObject[]; diff --git a/packages/plugin/src/storage/adapters/s3.ts b/packages/plugin/src/features/storage/backends/s3.ts similarity index 87% rename from packages/plugin/src/storage/adapters/s3.ts rename to packages/plugin/src/features/storage/backends/s3.ts index 38d04056..5dcd95ae 100644 --- a/packages/plugin/src/storage/adapters/s3.ts +++ b/packages/plugin/src/features/storage/backends/s3.ts @@ -1,12 +1,9 @@ -import { DEFAULT_CONCURRENCY } from "@/constants"; -import { normalizeKeyPrefix } from "@/shared"; -import { EStorageBackend, type S3StorageConfig } from "@/storage/config"; -import { - CONCURRENCY_FIELD, - EFieldKind, - type SettingsFieldSpec, -} from "@/storage/field-spec"; -import type { StorageAdapter } from "@/storage/types"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { EFieldKind } from "@/core/settings"; +import { normalizeKeyPrefix } from "@/core/shared"; +import { EStorageBackend, type S3StorageConfig } from "../config"; +import { CONCURRENCY_FIELD, type SettingsFieldSpec } from "../field-spec"; +import type { StorageAdapter } from "../types"; import { createS3Signer } from "./s3-signer"; import { createS3Store } from "./s3-store"; diff --git a/packages/plugin/src/storage/adapters/webdav.ts b/packages/plugin/src/features/storage/backends/webdav.ts similarity index 96% rename from packages/plugin/src/storage/adapters/webdav.ts rename to packages/plugin/src/features/storage/backends/webdav.ts index a664f47f..fa9109b5 100644 --- a/packages/plugin/src/storage/adapters/webdav.ts +++ b/packages/plugin/src/features/storage/backends/webdav.ts @@ -1,29 +1,20 @@ import { type RequestUrlParam, requestUrl } from "obsidian"; - -import { DEFAULT_CONCURRENCY } from "@/constants"; -import { normalizeKeyPrefix } from "@/shared"; -import { EStorageBackend, type WebDAVStorageConfig } from "@/storage/config"; -import { - CONCURRENCY_FIELD, - EFieldKind, - type SettingsFieldSpec, -} from "@/storage/field-spec"; -import type { - ConditionalRead, - ListedObject, - StorageAdapter, -} from "@/storage/types"; -import { bytesToBase64, toArrayBuffer } from "@/utils"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { EFieldKind } from "@/core/settings"; +import { normalizeKeyPrefix, StorageHttpError } from "@/core/shared"; +import { bytesToBase64, toArrayBuffer } from "@/core/utils"; +import { EStorageBackend, type WebDAVStorageConfig } from "../config"; +import { CONCURRENCY_FIELD, type SettingsFieldSpec } from "../field-spec"; +import type { ConditionalRead, ListedObject, StorageAdapter } from "../types"; import { assertOk, dateOf, headerValue, isRetryableStatus, - StorageHttpError, transferBytes, withDeadline, withRetry, -} from "./util"; +} from "./http"; const PROPFIND_BODY = ''; diff --git a/packages/plugin/src/settings/cloudflare-login.ts b/packages/plugin/src/features/storage/cloudflare/cloudflare-login.ts similarity index 83% rename from packages/plugin/src/settings/cloudflare-login.ts rename to packages/plugin/src/features/storage/cloudflare/cloudflare-login.ts index 4600ec24..15476583 100644 --- a/packages/plugin/src/settings/cloudflare-login.ts +++ b/packages/plugin/src/features/storage/cloudflare/cloudflare-login.ts @@ -4,12 +4,12 @@ import { cloudflareApi, hasCode, listAccounts, + obsidianHttp, verifyToken, -} from "@/cloudflare"; -import { obsidianHttp } from "@/cloudflare/obsidian-http"; -import type { PluginHost } from "@/plugin/host"; -import type { MdsyncSettings } from "@/settings/model"; -import { errorMessage } from "@/shared"; +} from "@/core/cloudflare"; +import type { MdsyncSettings } from "@/core/settings"; +import { errorMessage } from "@/core/shared"; +import type { StorageHost } from "../host"; /** A per-Worker token or a role without the legacy Workers Scripts permission. */ const AUTH_ERROR = 10000; @@ -43,7 +43,7 @@ export async function accountsOf(token: string): Promise { /** Verified before it is kept: a revoked or expired token would fail every later step. */ export async function connectCloudflare( - plugin: PluginHost, + plugin: StorageHost, token: string, accountId: string, ): Promise { @@ -55,7 +55,7 @@ export async function connectCloudflare( await plugin.saveSettings(); } -export async function forgetCloudflare(plugin: PluginHost): Promise { +export async function forgetCloudflare(plugin: StorageHost): Promise { Object.assign(plugin.settings, { cloudflareToken: "", cloudflareAccountId: "", diff --git a/packages/plugin/src/settings/r2.ts b/packages/plugin/src/features/storage/cloudflare/r2-select.ts similarity index 82% rename from packages/plugin/src/settings/r2.ts rename to packages/plugin/src/features/storage/cloudflare/r2-select.ts index d93aa9b5..eafd6168 100644 --- a/packages/plugin/src/settings/r2.ts +++ b/packages/plugin/src/features/storage/cloudflare/r2-select.ts @@ -1,32 +1,22 @@ -import { - cloudflareApi, - ensureBucket, - r2AccountOf, - r2Keys, - r2Storage, - verifyToken, -} from "@/cloudflare"; -import { obsidianHttp } from "@/cloudflare/obsidian-http"; -import { STORAGE_CHANGED_REASON } from "@/constants"; -import { sha256Hex } from "@/crypto"; -import type { PluginHost } from "@/plugin/host"; -import { cloudflareOf } from "@/settings/cloudflare-login"; -import { activeStorage, type MdsyncSettings } from "@/settings/model"; -import { - createStorageAdapter, - defaultS3Config, - EStorageBackend, - isRefusedCredentials, - type S3StorageConfig, -} from "@/storage"; -import { REMOTE_MANIFEST_KEY } from "@/sync/constants"; +import { cloudflareApi, obsidianHttp, verifyToken } from "@/core/cloudflare"; +import { REMOTE_MANIFEST_KEY, STORAGE_CHANGED_REASON } from "@/core/constants"; +import { sha256Hex } from "@/core/crypto"; +import type { MdsyncSettings } from "@/core/settings"; +import { isRefusedCredentials } from "../backends/http"; +import { defaultS3Config } from "../backends/s3"; +import { EStorageBackend, type S3StorageConfig } from "../config"; +import type { StorageHost } from "../host"; +import { createStorageAdapter } from "../registry"; +import { activeStorage } from "../settings"; +import { cloudflareOf } from "./cloudflare-login"; +import { ensureBucket, r2AccountOf, r2Keys, r2Storage } from "./r2"; const BUCKET = "mdsync-vaults"; /** What R2 shows as the Secret Access Key: the hex SHA-256 of the token's value. */ const R2_SECRET = /^[0-9a-f]{64}$/i; /** Makes the bucket (or finds it) and points the vault's S3 storage at it, under this vault's prefix. */ -export async function useR2(plugin: PluginHost): Promise { +export async function useR2(plugin: StorageHost): Promise { const login = cloudflareOf(plugin.settings); if (!login) throw new Error("Connect your Cloudflare account first."); const { api, accountId } = login; @@ -64,7 +54,7 @@ export function r2StorageOf(settings: MdsyncSettings): S3StorageConfig | null { * value or the Secret Access Key shown beside it; the keys must open the storage before anything is saved. */ export async function rekeyR2( - plugin: PluginHost, + plugin: StorageHost, value: string, ): Promise { const { settings } = plugin; diff --git a/packages/plugin/src/cloudflare/r2.ts b/packages/plugin/src/features/storage/cloudflare/r2.ts similarity index 92% rename from packages/plugin/src/cloudflare/r2.ts rename to packages/plugin/src/features/storage/cloudflare/r2.ts index 172ea7c8..6c4f57a9 100644 --- a/packages/plugin/src/cloudflare/r2.ts +++ b/packages/plugin/src/features/storage/cloudflare/r2.ts @@ -1,7 +1,6 @@ -import { sha256Hex } from "@/crypto"; -import type { S3StorageConfig } from "@/storage/config"; - -import { type CloudflareApi, hasCode } from "./api"; +import { type CloudflareApi, hasCode } from "@/core/cloudflare"; +import { sha256Hex } from "@/core/crypto"; +import type { S3StorageConfig } from "../config"; const BUCKET_OWNED = 10004; const R2_NOT_ENABLED = 10042; diff --git a/packages/plugin/src/storage/config.ts b/packages/plugin/src/features/storage/config.ts similarity index 100% rename from packages/plugin/src/storage/config.ts rename to packages/plugin/src/features/storage/config.ts diff --git a/packages/plugin/src/storage/field-spec.ts b/packages/plugin/src/features/storage/field-spec.ts similarity index 76% rename from packages/plugin/src/storage/field-spec.ts rename to packages/plugin/src/features/storage/field-spec.ts index 979d10f6..b8c077de 100644 --- a/packages/plugin/src/storage/field-spec.ts +++ b/packages/plugin/src/features/storage/field-spec.ts @@ -1,14 +1,5 @@ -import { DEFAULT_CONCURRENCY } from "@/constants"; - -export const EFieldKind = { - Text: "text", - Password: "password", - Toggle: "toggle", - Number: "number", - Slider: "slider", - Choice: "choice", -} as const; -export type EFieldKind = (typeof EFieldKind)[keyof typeof EFieldKind]; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { EFieldKind } from "@/core/settings"; export interface BaseFieldSpec { key: string; diff --git a/packages/plugin/src/features/storage/host.ts b/packages/plugin/src/features/storage/host.ts new file mode 100644 index 00000000..88b51e97 --- /dev/null +++ b/packages/plugin/src/features/storage/host.ts @@ -0,0 +1,7 @@ +import type { App } from "obsidian"; +import type { SettingsHost } from "@/core/settings"; + +/** What storage needs from the plugin. */ +export interface StorageHost extends SettingsHost { + readonly app: App; +} diff --git a/packages/plugin/src/features/storage/index.ts b/packages/plugin/src/features/storage/index.ts new file mode 100644 index 00000000..9db4cacf --- /dev/null +++ b/packages/plugin/src/features/storage/index.ts @@ -0,0 +1,57 @@ +export { errorCode, isRefusedCredentials } from "./backends/http"; +export { + endpointUrl, + type S3Method, + type S3RequestInput, + signingRegion, +} from "./backends/s3-signer"; +export { createS3Store } from "./backends/s3-store"; +export { + accountsOf, + type CloudflareLogin, + cloudflareErrorMessage, + cloudflareOf, + connectCloudflare, + forgetCloudflare, +} from "./cloudflare/cloudflare-login"; +export { R2NotEnabledError, r2DashboardUrl } from "./cloudflare/r2"; +export { r2StorageOf, useR2 } from "./cloudflare/r2-select"; +export { + EStorageBackend, + type S3StorageConfig, + type StorageAdapterConfig, +} from "./config"; +export type { StorageHost } from "./host"; +export { listEntries } from "./listing"; +export { + type RecordKind, + readRecords, + removeRecord, + writeRecord, +} from "./records"; +export { createStorageRefusedPrompt } from "./refused-prompt"; +export { + type CompactStorageConfig, + compactStorageConfig, + createStorageAdapter, + describeStorageTarget, + storageDefaults, + storageIdentity, +} from "./registry"; +export { + activeStorage, + isStorageConfigured, + parseStorageSettings, +} from "./settings"; +export { + type ConditionalRead, + type ListedObject, + type ObjectStorage, + ShareRefusedError, + type StorageAdapter, + StorageRequestError, +} from "./types"; +export { authorizeStorage } from "./ui/authorize"; +export { backendSection } from "./ui/backend-section"; +export { testConnection } from "./ui/connection-test"; +export { openStorageRefusedModal } from "./ui/storage-refused-modal"; diff --git a/packages/plugin/src/features/storage/listing.ts b/packages/plugin/src/features/storage/listing.ts new file mode 100644 index 00000000..da523654 --- /dev/null +++ b/packages/plugin/src/features/storage/listing.ts @@ -0,0 +1,14 @@ +import type { ListedObject, ObjectStorage } from "./types"; + +/** Every key under `prefix`, with its etag and write time where the backend reports them. */ +export async function listEntries( + storage: ObjectStorage, + prefix: string, +): Promise { + if (storage.listDetailed) return storage.listDetailed(prefix); + return (await storage.list(prefix)).map((key) => ({ + key, + etag: null, + modified: null, + })); +} diff --git a/packages/plugin/src/storage/records.ts b/packages/plugin/src/features/storage/records.ts similarity index 89% rename from packages/plugin/src/storage/records.ts rename to packages/plugin/src/features/storage/records.ts index 1e099962..4dbb3a5a 100644 --- a/packages/plugin/src/storage/records.ts +++ b/packages/plugin/src/features/storage/records.ts @@ -3,12 +3,13 @@ * and no compare-and-set is needed. */ -import { DEFAULT_CONCURRENCY } from "@/constants"; -import { decryptJson, type EncryptionKey, encryptJson } from "@/crypto"; -import { reportWarning } from "@/shared"; -import { runWithConcurrency } from "@/utils"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { decryptJson, type EncryptionKey, encryptJson } from "@/core/crypto"; +import { reportWarning } from "@/core/shared"; +import { runWithConcurrency } from "@/core/utils"; -import type { ListedObject, ObjectStorage } from "./types"; +import { listEntries } from "./listing"; +import type { ObjectStorage } from "./types"; /** One kind of record: `.json.enc`, sealed with the vault key. */ export interface RecordKind { @@ -37,7 +38,7 @@ export async function readRecords( kind: RecordKind, ): Promise<{ records: T[]; unreadable: Set }> { const cache = cacheFor(storage, key, kind); - const listed = (await listRecords(storage, kind.prefix)).filter( + const listed = (await listEntries(storage, kind.prefix)).filter( ({ key: name }) => name.endsWith(RECORD_SUFFIX), ); const names = new Set(listed.map(({ key: name }) => name)); @@ -115,18 +116,6 @@ function cacheFor( return records; } -async function listRecords( - storage: ObjectStorage, - prefix: string, -): Promise { - if (storage.listDetailed) return storage.listDetailed(prefix); - return (await storage.list(prefix)).map((name) => ({ - key: name, - etag: null, - modified: null, - })); -} - /** A backend that cannot name the version it served leaves the listing's word as the only one. */ async function readObject( storage: ObjectStorage, diff --git a/packages/plugin/src/features/storage/refused-prompt.ts b/packages/plugin/src/features/storage/refused-prompt.ts new file mode 100644 index 00000000..68b23ff1 --- /dev/null +++ b/packages/plugin/src/features/storage/refused-prompt.ts @@ -0,0 +1,20 @@ +import type { StorageHost } from "./host"; +import { activeStorage } from "./settings"; +import { openStorageRefusedModal } from "./ui/storage-refused-modal"; + +/** Drive replaces its access token hourly; the keys are what the person set. */ +const VOLATILE = new Set(["accessToken", "expiresAt"]); + +/** Asks once per set of keys: every sync run hits the same refusal until they change, here or in the settings. */ +export function createStorageRefusedPrompt(plugin: StorageHost): () => void { + let askedFor: string | null = null; + return () => { + const keys = JSON.stringify( + activeStorage(plugin.settings), + (key, value: unknown) => (VOLATILE.has(key) ? undefined : value), + ); + if (keys === askedFor) return; + askedFor = keys; + void openStorageRefusedModal(plugin); + }; +} diff --git a/packages/plugin/src/storage/registry.ts b/packages/plugin/src/features/storage/registry.ts similarity index 96% rename from packages/plugin/src/storage/registry.ts rename to packages/plugin/src/features/storage/registry.ts index 138012f3..c24bb90c 100644 --- a/packages/plugin/src/storage/registry.ts +++ b/packages/plugin/src/features/storage/registry.ts @@ -1,6 +1,6 @@ import type { ObsidianProtocolData } from "obsidian"; -import { createGoogleDriveAdapter } from "./adapters/google-drive"; +import { createGoogleDriveAdapter } from "./backends/google-drive"; import { defaultGoogleDriveConfig, describeGoogleDriveTarget, @@ -8,7 +8,7 @@ import { googleDriveIdentity, handleGoogleDriveProtocol, isGoogleDriveConfigured, -} from "./adapters/google-drive-auth"; +} from "./backends/google-drive-auth"; import { createS3Adapter, defaultS3Config, @@ -16,7 +16,7 @@ import { isS3Configured, S3_FIELDS, s3Identity, -} from "./adapters/s3"; +} from "./backends/s3"; import { createWebDAVAdapter, defaultWebDAVConfig, @@ -24,7 +24,7 @@ import { isWebDAVConfigured, WEBDAV_FIELDS, webdavIdentity, -} from "./adapters/webdav"; +} from "./backends/webdav"; import { EStorageBackend, type StorageAdapterConfig } from "./config"; import type { SettingsFieldSpec } from "./field-spec"; import type { StorageAdapter, StorageAuthOutcome } from "./types"; diff --git a/packages/plugin/src/features/storage/settings.ts b/packages/plugin/src/features/storage/settings.ts new file mode 100644 index 00000000..f2bcd646 --- /dev/null +++ b/packages/plugin/src/features/storage/settings.ts @@ -0,0 +1,58 @@ +import { clamp, type MdsyncSettings } from "@/core/settings"; + +import { defaultS3Config } from "./backends/s3"; +import type { EStorageBackend, StorageAdapterConfig } from "./config"; +import { CONCURRENCY_FIELD } from "./field-spec"; +import { getDescriptor, isAdapterConfigured, isKnownBackend } from "./registry"; + +declare module "@/core/settings" { + interface MdsyncSettings { + storageConfigs: Record; + activeStorageKind: EStorageBackend; + } +} + +type StorageSettings = Pick< + MdsyncSettings, + "storageConfigs" | "activeStorageKind" +>; + +export function parseStorageSettings( + stored: Partial | null | undefined, +): StorageSettings { + const storageConfigs: Record = { + ...(stored?.storageConfigs ?? {}), + }; + // Backfill fields added after initial save from backend defaults. + for (const [kind, config] of Object.entries(storageConfigs)) { + if (!isKnownBackend(kind) || !config || typeof config !== "object") { + delete storageConfigs[kind]; + continue; + } + config.concurrency = clamp( + config.concurrency, + CONCURRENCY_FIELD, + getDescriptor(kind).defaults().concurrency, + ); + } + if (Object.keys(storageConfigs).length === 0) { + const fallback = defaultS3Config(); + storageConfigs[fallback.kind] = fallback; + } + const requested = stored?.activeStorageKind; + const activeStorageKind = + requested && storageConfigs[requested] + ? requested + : (Object.keys(storageConfigs)[0] as EStorageBackend); + return { storageConfigs, activeStorageKind }; +} + +export function activeStorage(settings: StorageSettings): StorageAdapterConfig { + return ( + settings.storageConfigs[settings.activeStorageKind] ?? defaultS3Config() + ); +} + +export function isStorageConfigured(settings: StorageSettings): boolean { + return isAdapterConfigured(activeStorage(settings)); +} diff --git a/packages/plugin/src/storage/types.ts b/packages/plugin/src/features/storage/types.ts similarity index 100% rename from packages/plugin/src/storage/types.ts rename to packages/plugin/src/features/storage/types.ts diff --git a/packages/plugin/src/features/storage/ui/authorize.ts b/packages/plugin/src/features/storage/ui/authorize.ts new file mode 100644 index 00000000..ace534e1 --- /dev/null +++ b/packages/plugin/src/features/storage/ui/authorize.ts @@ -0,0 +1,27 @@ +import type { ObsidianProtocolData } from "obsidian"; +import { notifyError, notifyInfo } from "@/core/ui"; +import type { StorageHost } from "../host"; +import { handleStorageProtocol } from "../registry"; + +/** A backend's sign-in callback. A failure must be visible: it fires once and never retries. */ +export async function authorizeStorage( + plugin: StorageHost, + params: ObsidianProtocolData, + onAuthorized: () => void, +): Promise { + try { + const outcome = await handleStorageProtocol( + params, + (kind) => plugin.settings.storageConfigs[kind], + async () => { + await plugin.saveSettings(); + onAuthorized(); + }, + ); + if (!outcome) return; + if (outcome.ok) notifyInfo(outcome.message); + else notifyError(outcome.message, outcome.detail); + } catch (err) { + notifyError("Storage authorization failed", err); + } +} diff --git a/packages/plugin/src/settings/sections/backend.ts b/packages/plugin/src/features/storage/ui/backend-section.ts similarity index 77% rename from packages/plugin/src/settings/sections/backend.ts rename to packages/plugin/src/features/storage/ui/backend-section.ts index ab268e04..8664a250 100644 --- a/packages/plugin/src/settings/sections/backend.ts +++ b/packages/plugin/src/features/storage/ui/backend-section.ts @@ -1,18 +1,15 @@ import type { SettingDefinitionGroup } from "obsidian"; - -import { STORAGE_CHANGED_REASON } from "@/constants"; -import { testConnection } from "@/settings/connection-test"; -import { - checkRow, - type FieldContext, - group, - introRow, -} from "@/settings/fields"; -import type { EStorageBackend } from "@/storage"; -import { getDescriptor, listBackends } from "@/storage"; +import { STORAGE_CHANGED_REASON } from "@/core/constants"; +import { checkRow, type FieldContext, group, introRow } from "@/core/settings"; +import type { EStorageBackend } from "../config"; +import type { StorageHost } from "../host"; +import { getDescriptor, listBackends } from "../registry"; +import { testConnection } from "./connection-test"; import { storageRows } from "./storage-fields"; -export function backendSection(ctx: FieldContext): SettingDefinitionGroup { +export function backendSection( + ctx: FieldContext, +): SettingDefinitionGroup { const { plugin } = ctx; return group("Backend", [ introRow( @@ -48,7 +45,7 @@ export function backendSection(ctx: FieldContext): SettingDefinitionGroup { }, }, ...listBackends().flatMap(({ kind }) => - storageRows(plugin, kind).map((row) => ({ + storageRows(ctx, kind).map((row) => ({ ...row, visible: () => plugin.settings.activeStorageKind === kind, })), diff --git a/packages/plugin/src/features/storage/ui/connection-test.ts b/packages/plugin/src/features/storage/ui/connection-test.ts new file mode 100644 index 00000000..281e37a7 --- /dev/null +++ b/packages/plugin/src/features/storage/ui/connection-test.ts @@ -0,0 +1,44 @@ +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; +import type { CheckResult } from "@/core/settings"; +import { errorMessage, reportWarning } from "@/core/shared"; +import type { StorageHost } from "../host"; +import { + createStorageAdapter, + describeStorageTarget, + isAdapterConfigured, +} from "../registry"; +import { activeStorage } from "../settings"; + +/** + * Reaches the remote without a passphrase, so credentials can be checked before anything is encrypted. + * Reads only the manifest key: absent is a healthy empty remote, anything else a real connection problem. + */ +export async function testConnection( + plugin: StorageHost, +): Promise { + const config = activeStorage(plugin.settings); + if (!isAdapterConfigured(config)) { + return { ok: false, message: "This backend is not fully configured yet." }; + } + const target = describeStorageTarget(config); + try { + // A test may refresh a Drive token: saved, or a rotated one is lost on restart. + const adapter = createStorageAdapter(config, () => { + plugin + .saveSettings() + .catch((err) => reportWarning("Could not save the settings.", err)); + }); + const found = await adapter.exists(REMOTE_MANIFEST_KEY); + return { + ok: true, + message: found + ? `Connected to ${target}. A vault is already published there.` + : `Connected to ${target}. No vault published yet - your first push will create one.`, + }; + } catch (err) { + return { + ok: false, + message: `Could not reach ${target}: ${errorMessage(err)}`, + }; + } +} diff --git a/packages/plugin/src/features/storage/ui/storage-fields.ts b/packages/plugin/src/features/storage/ui/storage-fields.ts new file mode 100644 index 00000000..bf7ec9a5 --- /dev/null +++ b/packages/plugin/src/features/storage/ui/storage-fields.ts @@ -0,0 +1,152 @@ +import type { Setting } from "obsidian"; +import { + EFieldKind, + type FieldContext, + fieldRow, + type MdsyncSettings, + type SettingsField, + type SettingsRow, +} from "@/core/settings"; +import { notifyInfo } from "@/core/ui"; +import { googleLoginUrl } from "../backends/google-drive-auth"; +import { + EStorageBackend, + type GoogleDriveStorageConfig, + type StorageAdapterConfig, +} from "../config"; +import type { SettingsFieldSpec } from "../field-spec"; +import type { StorageHost } from "../host"; +import { getDescriptor } from "../registry"; + +export function storageRows( + ctx: FieldContext, + kind: EStorageBackend, +): SettingsRow[] { + const rows: SettingsRow[] = getDescriptor(kind).fields.map((spec) => + fieldRow(ctx, storageField(kind, spec)), + ); + if (kind === EStorageBackend.GoogleDrive) { + rows.push({ + name: "Google account", + render: (setting) => renderGoogleDriveAuth(setting, ctx.plugin, kind), + }); + } + return rows; +} + +function configOf( + settings: MdsyncSettings, + kind: EStorageBackend, +): Record { + const config = + settings.storageConfigs[kind] ?? getDescriptor(kind).defaults(); + return config as unknown as Record; +} + +/** Patches a fresh config: another field may have replaced it since this row drew. */ +function patchConfig( + plugin: StorageHost, + kind: EStorageBackend, + key: string, + value: unknown, +): Partial { + const next = { ...configOf(plugin.settings, kind), [key]: value }; + return { + storageConfigs: { + ...plugin.settings.storageConfigs, + [kind]: next as unknown as StorageAdapterConfig, + }, + }; +} + +function storageField( + kind: EStorageBackend, + spec: SettingsFieldSpec, +): SettingsField { + const { key, name, desc } = spec; + const set = (value: unknown, plugin: StorageHost) => + patchConfig(plugin, kind, key, value); + const text = (settings: MdsyncSettings): string => { + const raw = configOf(settings, kind)[key]; + return typeof raw === "string" ? raw : ""; + }; + + switch (spec.kind) { + case EFieldKind.Toggle: + return { + kind: EFieldKind.Toggle, + name, + desc, + get: (s) => Boolean(configOf(s, kind)[key]), + set, + }; + case EFieldKind.Number: + return { + kind: EFieldKind.Number, + name, + desc, + min: spec.min, + max: spec.max, + get: (s) => { + const raw = configOf(s, kind)[key]; + return String(typeof raw === "number" ? raw : spec.fallback); + }, + parse: (raw) => + Math.min(spec.max, Math.max(spec.min, Number.parseInt(raw, 10))), + set, + }; + case EFieldKind.Password: + // Trailing spaces in a password are part of it. + return { + kind: EFieldKind.Password, + name, + desc, + placeholder: spec.placeholder, + get: text, + set, + }; + case EFieldKind.Text: + return { + kind: EFieldKind.Text, + name, + desc, + placeholder: spec.placeholder, + get: text, + set: (value, plugin) => set(value.trim(), plugin), + }; + } +} + +function renderGoogleDriveAuth( + setting: Setting, + plugin: StorageHost, + kind: EStorageBackend, +): void { + // Read on click too: editing a field replaces the config object. + const config = () => + configOf(plugin.settings, kind) as unknown as GoogleDriveStorageConfig; + const isAuth = Boolean(config().refreshToken); + + setting + .setDesc( + isAuth + ? "Authenticated. Tokens are stored on this device." + : createFragment((f) => { + f.appendText("Not authenticated. Select "); + f.createEl("strong", { text: "Log in" }); + f.appendText(" to authorize."); + }), + ) + .addButton((b) => + b + .setButtonText(isAuth ? "Re-authenticate" : "Log in") + .setCta() + .onClick(() => { + if (!config().authServerUrl) { + notifyInfo("Set the auth server URL first."); + return; + } + window.open(googleLoginUrl(config())); + }), + ); +} diff --git a/packages/plugin/src/ui/modals/storage-refused-modal.ts b/packages/plugin/src/features/storage/ui/storage-refused-modal.ts similarity index 84% rename from packages/plugin/src/ui/modals/storage-refused-modal.ts rename to packages/plugin/src/features/storage/ui/storage-refused-modal.ts index 029bde4b..05322930 100644 --- a/packages/plugin/src/ui/modals/storage-refused-modal.ts +++ b/packages/plugin/src/features/storage/ui/storage-refused-modal.ts @@ -1,25 +1,23 @@ import { ButtonComponent, Modal, Setting } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; -import { cloudflareErrorMessage } from "@/settings/cloudflare-login"; -import { activeStorage } from "@/settings/model"; -import { r2StorageOf, rekeyR2 } from "@/settings/r2"; -import { describeStorageTarget } from "@/storage"; import { alertLine, modalFooter, onEnter, openPluginSettings, + openPromiseModal, renderModalHead, -} from "@/ui/common"; - -import { openPromiseModal } from "./promise-modal"; +} from "@/core/ui"; +import { cloudflareErrorMessage } from "../cloudflare/cloudflare-login"; +import { r2StorageOf, rekeyR2 } from "../cloudflare/r2-select"; +import type { StorageHost } from "../host"; +import { describeStorageTarget } from "../registry"; +import { activeStorage } from "../settings"; const FIELD = "Token value or secret access key"; const UPDATE = "Update keys"; /** True once new keys open the storage; R2 takes them here, any other storage in the settings. */ -export function openStorageRefusedModal(plugin: PluginHost): Promise { +export function openStorageRefusedModal(plugin: StorageHost): Promise { return openPromiseModal((answer) => { const modal = new Modal(plugin.app); const { contentEl } = modal; diff --git a/packages/plugin/src/features/sync/README.md b/packages/plugin/src/features/sync/README.md new file mode 100644 index 00000000..c01ca992 --- /dev/null +++ b/packages/plugin/src/features/sync/README.md @@ -0,0 +1,103 @@ +# Sync engine + +File sync of the vault and of each shared folder (a "space") against object storage. One slice, kept whole: history is called by publish and hunks by operations, so splitting them out would create cycles; the sub-areas carry the navigation. Constraints live in `.claude/rules/sync-integrity.md`, `.claude/rules/hunks.md`, `.claude/rules/history.md`, `.claude/rules/vault-io.md`; this file holds the map, the flows and the reasons behind them. + +## Map + +| Folder | Holds | +|---|---| +| `changes/` | scan -> diff: `features/sync/changes/diff.ts` (local, remote, conflict, converged), `features/sync/changes/moves.ts` (`pairMoves`), `features/sync/changes/content.ts` (load and write content), `features/sync/changes/remote-names.ts`, `features/sync/changes/binary-extensions.ts` | +| `remote/` | the remote side: `features/sync/remote/manifest.ts` (fetch, build, guarded publish), `features/sync/remote/baseline.ts`, `features/sync/remote/space.ts`, `features/sync/remote/space-paths.ts`, `features/sync/remote/foreign.ts`, `features/sync/remote/config-reset.ts`, `features/sync/remote/uploads.ts`, `features/sync/remote/reset.ts`, `features/sync/remote/keyfile.ts`, `features/sync/remote/passphrase-manager.ts` | +| `scope/` | what syncs: `features/sync/scope/scope.ts` (policy), `features/sync/scope/scanner.ts`, ignore matcher, rules and state, the scope and exclusions settings sections, `features/sync/scope/plugin-levels-modal.ts` (per-plugin levels) | +| `apply/` | landing remote content: `features/sync/apply/pull.ts`, `features/sync/apply/pull-moves.ts`, `features/sync/apply/auto-merge.ts`, `features/sync/apply/conflict-merge.ts`, `features/sync/apply/conflict-copy.ts` | +| `recovery/` | `features/sync/recovery/journal.ts`, `features/sync/recovery/cut-short.ts`, `features/sync/recovery/state-persister.ts` | +| `hunks/` | `features/sync/hunks/hunks.ts`, `features/sync/hunks/projection.ts`, `features/sync/hunks/diff-cache.ts`, `features/sync/hunks/merge-model.ts`, `features/sync/hunks/anchored-hunks.ts` | +| `operations/` | what a person or the auto cycle runs over one compare: push, pull, revert, resolve, hunks, config reset, flows, `features/sync/operations/text-loaders.ts` | +| `automation/` | `features/sync/automation/scheduler.ts` (timer, backoff; with autosync off, one compare after startup when the passphrase needs no prompt), `features/sync/automation/auto-push.ts` (bulk-deletion hold), `features/sync/automation/slow-files.ts` (slow files held while edited), `features/sync/automation/restored-files.ts` (restored files held until pushed by hand) | +| `identity/` | `features/sync/identity/authors.ts`, `features/sync/identity/device.ts`, `features/sync/identity/device-name.ts` | +| `runtime/` | what `features/sync/controller.ts` is built from: `features/sync/runtime/operation-runner.ts`, `features/sync/runtime/refresh-queue.ts`, `features/sync/runtime/auto-cycle.ts`, `features/sync/runtime/scan-cycle.ts`, `features/sync/runtime/controller-state.ts`, `features/sync/runtime/file-diff-service.ts`, `features/sync/runtime/history-service.ts`, `features/sync/runtime/maintenance.ts`, `features/sync/runtime/saved-refresh.ts`, `features/sync/runtime/merged-result.ts` | +| `content/` | the one owner of file content on the remote: `features/sync/content/load.ts` (`loadContent`, `openContent`, `prepareContent`), `features/sync/content/store.ts` (`storeContent`), `features/sync/content/header.ts`, `features/sync/content/keys.ts` (root and chunk keys), `features/sync/content/closure.ts` (chunks recipes name) | +| `history/` | push records, queries, replay, pins, vault restore plan, GC and sweep | +| `ui/` | menu items, modals, the settings sections (Automatic sync, encryption, maintenance, History) | + +Top level: `features/sync/engine.ts` (`compare`, `pushPaths`, `publishFileMap`), `features/sync/session-state.ts`, `features/sync/state.ts` (the state file), `features/sync/types.ts`, `features/sync/constants.ts` (remote layout, size limits), `features/sync/live-notes.ts` (the seam to live editing: the file sync never imports `features/live`), `features/sync/index.ts` (facade). + +## One refresh + +1. `RefreshQueue` coalesces requests into one cycle on the single operation chain (`SyncControllerRuntimeState.enqueue`); `runRefreshCycle` (`features/sync/runtime/auto-cycle.ts`) runs `refreshNow`, then the automatic steps. +2. A full `refreshNow` asks `host.spaces()` once (records traded with the vault storage, moves followed) and keeps that partition for the cycle; a targeted share refresh reuses the previous one. For each unpaused space it opens a session (`app/session-factory.ts`, scope built from that partition alone) and runs `compare`. +3. `compare`: scan the disk while the remote head downloads, `finishCutShort`, take the baseline `withLanded`, check the vault id and `assertSpacePresent`, reconcile the head against the baseline, mark unholdable names skipped, then `diffWithin`. A refresh then forgets reset categories and dropped frozen entries from the baseline, advances it for `converged` paths (both sides reached equal content: no phantom conflict), and saves state and hash cache once. +4. Automatic steps, per space: conflicts go to `autoMergeOp` (notes by line, settings JSON by key; a line merge of JSON or plugin code can be clean by lines and broken as a file), remote changes to `pullPathsOp`, local changes chosen by the auto-push selector to `pushPathsOp`. The first failing step ends the cycle. +5. `runOperationNow` re-checks that the space is still mounted, reuses the refresh's comparison only for the same scope epoch and local revision (else compares again), runs the operation, then patches the result from what it wrote (`recomputeAfterWrite`) instead of rescanning. `ConcurrentPushError` clears the result and refreshes; a cancel says nothing on the remote changed; the journal is saved as every operation ends. +6. `invalidate` bumps the epoch: results begun before it are dropped, so a stale partition or scope never settles state auto-push could act on. + +## Baseline + +The baseline is the manifest this device last agreed with, per storage identity slot of the state file (`features/sync/state.ts`) (`LocalState.storages`; `projectSession` flattens one slot for one space and re-roots it after a share move). Local change = disk differs from baseline; remote change = head differs from baseline; both = conflict, unless equal (converged). + +It moves only through `advanceBaselineForPaths`: converged paths at refresh, `written` after a pull, the published delta after a push, one path for a hunk operation. Adopting a whole manifest would claim files this device never downloaded; the next push would publish them as deletions. Empty folders advance by majority of baseline, remote and disk (`majorityFolders`): a folder on one side only is not agreed yet. + +A push publishes the remote's file map (`result.remote`) plus this push's changes, never the local snapshot: files the device has not pulled stay. Authorship (`attribute`) is stamped there and only there. + +## Publication guard + +`publishManifestWithGuard`: seal first (gzip after the precheck would widen the race window), precheck the head equals the expected parent, `put`, then read back. A head this push replaced is a stale read or a lost push, so it re-reads (`VERIFY_DELAYS_MS`); only our own snapshot id proves it landed. Taking the replaced head as stale would let a sibling's overwrite turn our files into remote deletions. History is recorded only for the guard's winner. + +Accepted limit: a backend hiding our own write past the retries (WebDAV behind a cache) leaves a landed push unconfirmed: peers are not pinged, a partial push shows an auto-merged conflict, that snapshot gets no history record. + +Uploads: the head vouches for a blob; this device's own unpublished uploads count for 12 h (`UPLOAD_TRUST_MS`, still probed). Anything else may be swept by GC or deep clean between probe and publish. Still open, narrow: another device's reset between the probe and the publish, clock skew over 12 h. + +A blob is gzipped when that makes it smaller (`encryptCompressible` in `core/crypto/cipher.ts`, padded like the JSON documents), else sealed as is; every release since 1.0.0 reads both. A large file is judged by its first 64 KB, so media is not compressed whole for nothing. + +Every file content read and write goes through `content/`: `loadContent` (`changes/content.ts` `loadRemoteBytes` calls it; deep verify fetches the root itself (`fetchRoot`) and opens it with `openContent`, the same unseal and hash check; a failed read, a chunk's too, is no `ContentError`, so an outage aborts instead of reading as corrupt) and `storeContent` (`pushPaths`, `storeObject`); whether a file needs uploading stays in `engine.ts`, which of its chunks does in `storeContent`. `objects/` holds either the file (0x01/0x02) or a described blob (0x03): a JSON header, then a payload. A drawing whose `## Drawing` block is `compressed-json` is stored with that block decoded to plain JSON (`core/drawing/codec.ts`), because an LZString stream changes whole on every edit and so neither gzip nor chunking can share bytes between versions; the header carries the base64 wrap width and gap. It is kept only when decoding reproduces the file byte for byte at write time, and a read checks SHA-256 against the file hash again. A header this build does not know (an unknown codec, `chunks` outside a recipe) makes the content unreadable, never wrong bytes. A device without CompressionStream stores such a drawing whole. + +With a chunk key (`EngineDependencies.chunkIds`, HKDF of the data key: the keyfile's for the vault, the record's for a share) a file of `CHUNK_THRESHOLD` (256 KB) or more is stored in chunks, cut by FastCDC (`core/chunking`) at 16/64/256 KB, past 16 MB at 256 KB/1/4 MB, and named by HMAC so the storage never sees their plain hashes: `recipes/` is a described blob with an empty payload whose header lists `chunks: [id, size][]`, each `chunks/` a 0x01/0x02 blob of that part of the stored form (a decoded drawing included). Readers look where the size says first (`readOrder`: a big file under `recipes/`, then `objects/` for one uploaded whole; an unknown size the other way). `prepareContent` hints every root a batch may read, reads its recipes once (kept for the batch's loads) and hints their chunks with the roots, since a hint replaces the one before. A write of a pulled file (`writeIncoming`) hands its copy on disk to `loadContent` (`loadLocalCopy`: only one no bigger than the remote file or below `LARGE_FILE_BYTES`, so a file that shrank does not bring large-file work into a transfer admitted as small): cut as the remote file (the size picks the chunk sizes, `content/cut.ts`) and named with the same key, its chunks the recipe names are not downloaded; the joined file is still checked against its hash. The copy, the downloaded chunks and the joined file are in memory at once, about three times the file. + +## Writes and the journal + +Obsidian truncates before it writes (mobile drops a file whose append fails), so a killed write leaves a prefix. `features/sync/recovery/journal.ts` makes every engine content write recoverable: a durable claim, the whole content staged under the plugin folder, the write, release. Recovery (`features/sync/recovery/cut-short.ts`) runs at load (`restoreCutShort`) and in every `compare` right after the scan: a prefix of the staged copy, or a missing file in a folder that stays, is rewritten; one that landed still gives its room its merge base (judged by its bytes when the scan left it out); what cannot be finished yet (unreadable, open room) leaves the diff as unreadable. A start with one pending refreshes at once (`main.ts`). + +A finished download gives the baseline its entry (`BaseStep`, taken only by the storage and vault it was claimed under, only while the baseline still holds what it held then); `withLanded` applies it in the diff, because on the old baseline the write would read as this device's edit. Landed writes stay in the journal until the baseline holding their step is saved (`acknowledge`, else `settleLanded`). + +Live editing meets this in `features/sync/live-notes.ts` (`coldSince`, `writeIncoming`, `LiveNotes.holds`); its rules are in the live rule: a room never opens on a note under an engine write, the engine never writes a note whose room is open. + +Accepted limits: garbage that is no prefix reads as an edit; an edit since that leaves a prefix of the staged copy, or deletes the file, is undone; a pulled new file that is no room snapshot, cut short, stays a conflict and gives no step; so does a file a pull moves here and edits there; a step of a storage switched away from is dropped; a write landed in a run the app died in, edited before the next compare, loses its step; a first sync's download has none (no baseline yet), so a note deleted elsewhere before it finished comes back. + +## Spaces + +A `Space` is the vault or a shared folder with its own storage and key. The partition (`spacesOf`, built by `features/spaces/records.ts`) lists the vault first, then each open record whose root is free. Scopes own a root's subtree minus nested roots. The vault treats share roots like a local ignore: entries there are frozen in its manifest (so a share opened or closed never reads as a deletion), dropped from the next vault push, and swept from storage by history GC once no history record names them. A frozen entry the baseline forgot but whose share has no baseline yet is kept in `shareBases`, the merge base of a note that just became a share. + +Remote blobs hold paths relative to the space root (`features/sync/remote/space-paths.ts`), so participants mounting at different folders agree; locally everything is vault paths. A move of a share root edits the record; every device moves its folder before the next partition (`features/spaces/share-moves.ts`). + +Failure modes the rules guard: a share whose scan lost every file (`SpaceGoneError`) is the device's error, settled by the person; closing is a tombstone, never file deletion; pausing keeps the folder out of the vault. + +## Moves, folders and names + +`pairMoves` pairs a gone path with a new one of the same baseline hash in one space, else by file name where one to one; the empty hash pairs nothing. A pull renames locally (`features/sync/apply/pull-moves.ts`), so a local edit goes with the file. Recasing on a case-blind disk steps through a free name (`renameCaseSafe`). + +A folder is removed only after a listing shows it empty. Accepted limits: a file created between the listing and the removal goes too; a destination edited while its source downloads keeps both files; a recasing whose rename back fails stays under its step name, said in the error, and a push may publish it so; an open live room waits as joining, holding the move back, until the next refresh or the rename back; two files of equal size and mtime swapped while an operation runs keep each other's hashes until one is edited (the persister saves the cache its scan saw); a remote rename into a name this disk refuses reads here as the deletion of its source. + +## Hunks + +A hunk index means nothing without its two texts. The diff view, the gutter marks and the operation must agree on the pair, the order and the baseline, or "apply hunk 3" hits another region. So the operation loads sides from one function, hashes them against what the view drew, and the editor's marks are built from the same segments push and revert move (blank lines make diffs ambiguous). History restore numbers hunks version-to-current, so it inverts the selection instead of recomputing the other way. Size gates run before any read so a large video never loads into a diff. + +## History + +Every push writes one encrypted record, `history/p/.enc`, before it publishes: the diff from that snapshot's parent (`added`, `modified {from, to}`, `deleted`). History covers vault files only: the configuration folder syncs but keeps no versions (plugin updates would hold every old bundle for the whole horizon), so its hashes go to the record's `released` list, which GC frees with the record; restore and new pins leave it alone. Both sides are stored so one version restores without replaying, and a record that never landed shows as a parent/child gap the walk from HEAD stops at (`coverOf`). A failed record write is retried before the next push. Readers list `history/` once and keep what they decoded in memory (`features/sync/history/remote.ts`); every query walks from HEAD (`features/sync/history/query.ts`). Pins are their own objects under `pins/` holding a full manifest, so they outlive the records. GC (`features/sync/history/gc.ts`) runs after a push this device published, at most every 10 minutes per space: it packs aged records into one object per period (every push for the last hour, then per 10 minutes, hour, day and week, then activity counts past the horizon, **Keep history for**), planned by the pure model in `features/sync/history/model/`, and sweeps the file versions they stopped naming one to two days later (the sweep lists every blob, so it runs about once a day). The activity those reads see is kept on the device (`features/sync/history/activity-cache.ts`) for the settings overview, which never reads history itself. + +Every manifest carries `MANIFEST_VERSION` 3, so a 1.x client refuses the remote from the first new push and never runs its GC or deep clean over this layout. 1.x history is not imported: the first push of a session deletes `history.json.enc` and the bare-manifest pins (`features/sync/history/legacy.ts`); the versions only they named stay until a deep clean, which refuses to run until a v3 HEAD fences the old clients out. + +Windows: a blob younger than `SETTLED_AFTER_MS` (24 h) is never swept, GC sweeps what it freed only a day after freeing it, deep clean deletes nothing written in the last day. Accepted limits: a re-upload landing between the listing and its delete is still lost (Drive has no conditional delete); a push by another device that re-uploaded an old hash is covered only by those windows; a cold read decodes every listed record, and a vault never thinned by GC reads all of its pushes; a push stalled between its guard's precheck and its put while another push and its GC complete (the guard race, where that other push's files already leave HEAD) may find its parent merged away, so its history starts at a gap; a push that outlasts the 10-minute GC interval can queue a second, empty run behind the first; the horizon is a device setting, so the device with the shortest one thins history for all; a 1.x client stalled mid-push across the first v3 publish can land one v2 HEAD and rewrite the old log, until the next push publishes v3 and deletes it again; a packed version's push count still includes pushes that changed only the configuration folder, which the activity calendar leaves out; a restored file in a shared folder closed elsewhere returns to the vault without its hold, so an automatic push may publish it there. + +## Other flows + +- Reset and adopt (`features/sync/operations/flows.ts`): reset deletes the vault storage's manifest, history, objects and pins and clears the baseline; adopt re-aims this device at a remote vault whose id changed. Category resets (`features/sync/operations/config-reset.ts`) bump a generation in the manifest. +- Maintenance (`features/sync/runtime/maintenance.ts`): verify checks every reachable object exists, a recipe's chunks against one listing of `chunks/` (`deep` also rebuilds and hashes it); deep clean removes unreachable settled roots and the settled chunks no remaining recipe names. +- Saved-file refresh (`features/sync/runtime/saved-refresh.ts`): display only, patches the last compare after an editor save; nothing persists, the next refresh reconciles. +- Credentials: `features/sync/remote/keyfile.ts` wraps one constant data key under the passphrase (rotation re-wraps only); `features/sync/remote/passphrase-manager.ts` caches keys per epoch. +- Plugin levels (`EPluginLevel`: Off, Settings, Code, Data; each adds to the one before): Settings is a plugin's `data.json`, Code adds `manifest.json`, `main.js`, `styles.css` (what Obsidian's installer writes), Data adds the rest of the folder (caches, indexes, subfolders). `pluginLevel` (default Settings, so code stays where each device put it) is every plugin's level while **Plugins** is on; `pluginLevels` holds overrides for single plugins, set in **Choose per plugin** (`features/sync/scope/plugin-levels-modal.ts`, which also lists plugins only the remote holds, named from the local `manifest.json`). Overrides are device-local and apply with **Plugins** off, to sync one private plugin only. A plugin at Off on a device is frozen there: its remote files stay and are never read as deletions, and nothing of it is read or published. A part above its plugin's level is frozen the same way. Accepted limits: a plugin missing here gets a folder holding only its `data.json` until it is installed by hand (Obsidian's installer keeps an existing `data.json`, so the synced settings are picked up); two devices on different plugin versions trade one settings file; a plugin removed on a device whose level covers its code takes its settings off every device, while devices below Code keep the plugin and start from its defaults; **Keep both** on a `data.json` is refused, since a copy beside it is out of scope (`keepBothConflictOp` refuses any copy the scope would not publish); **Clear on remote** clears every plugin part whatever its level, and devices whose level covers it upload it again; a plugin enabled in the synced list but missing here stays in the list (Obsidian reads and writes `community-plugins.json` whole). +- Restart notice: Obsidian 1.14.5 reads plugin manifests and the enabled list only at startup, and watches only an enabled plugin's `data.json`. So after a pull that wrote plugin code or `community-plugins.json`, first sync included, `OperationRunner` calls the host hook `onPluginsPulled` and `app/runtime-hooks.ts` shows "Plugins changed on another device. Restart Obsidian to load them." The plugin never reloads another plugin itself. Accepted limit: a pull stopped by an error shows no notice for the code it landed, as with marks of others' edits. + +## Tests + +`packages/plugin/tests/features/sync/` mirrors the folders. Two devices share one `FakeStorage` through `pairedSessions` (`packages/plugin/tests/helpers/session.ts`); faults come from `packages/plugin/tests/helpers/faults.ts`; `packages/plugin/tests/features/sync/chaos.test.ts` runs seeded rounds of edits and killed writes across three devices. diff --git a/packages/plugin/src/sync/auto-merge.ts b/packages/plugin/src/features/sync/apply/auto-merge.ts similarity index 86% rename from packages/plugin/src/sync/auto-merge.ts rename to packages/plugin/src/features/sync/apply/auto-merge.ts index 019daa10..89c22146 100644 --- a/packages/plugin/src/sync/auto-merge.ts +++ b/packages/plugin/src/features/sync/apply/auto-merge.ts @@ -1,23 +1,24 @@ -import { DEFAULT_CONCURRENCY } from "@/constants"; -import { ESyncLogOperation } from "@/logs/store"; -import { asError, sortedByPath } from "@/shared"; -import { - advanceBaselineForPaths, - mergeWrittenIntoCache, -} from "@/sync/baseline"; -import { HUNK_TEXT_MAX_BYTES, LOG_PATH_LIMIT } from "@/sync/constants"; -import { runWithConcurrency } from "@/utils"; -import { tryAutoMergeConflict } from "./conflict-merge"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { ESyncLogOperation } from "@/core/logs"; +import { asError } from "@/core/shared"; +import { runWithConcurrency } from "@/core/utils"; import { hasKnownBinaryExtension, textToBytes, writeLocalFile, -} from "./content"; -import { baseStep } from "./cut-short"; -import type { CompareResult, EngineDependencies } from "./engine"; -import { coldSince, grewFrom, settleLive, writeIncoming } from "./live-notes"; -import type { OperationContext, OperationOutcome } from "./operations"; -import type { Conflict, Manifest, ManifestEntry, SessionState } from "./types"; +} from "../changes/content"; +import { sortedByPath } from "../changes/records"; +import { HUNK_TEXT_MAX_BYTES, LOG_PATH_LIMIT } from "../constants"; +import type { CompareResult, EngineDependencies } from "../engine"; +import { coldSince, grewFrom, settleLive, writeIncoming } from "../live-notes"; +import type { OperationContext, OperationOutcome } from "../operations/types"; +import { baseStep } from "../recovery/cut-short"; +import { + advanceBaselineForPaths, + mergeWrittenIntoCache, +} from "../remote/baseline"; +import type { Conflict, Manifest, ManifestEntry, SessionState } from "../types"; +import { autoMergerFor, tryAutoMergeConflict } from "./conflict-merge"; export async function autoMergeOp( deps: EngineDependencies, @@ -141,6 +142,8 @@ async function settleConflict( } // No common ancestor: nothing to merge against, and no reason to stat. if (!conflict.baselineHash) return undefined; + const merge = autoMergerFor(deps.scope, conflict.path); + if (!merge) return undefined; // Rules out binary/oversized files by path and manifest size without downloading them. const mergeable = await isTextMergeCandidate( deps, @@ -149,7 +152,7 @@ async function settleConflict( deps.state.baseline, ); if (!mergeable) return undefined; - const text = await tryAutoMergeConflict(deps, conflict); + const text = await tryAutoMergeConflict(deps, conflict, merge); if (text === null) return undefined; const landed = remote && (() => grewFrom(deps, conflict.path, remote)); const bytes = textToBytes(text); diff --git a/packages/plugin/src/sync/conflict-copy.ts b/packages/plugin/src/features/sync/apply/conflict-copy.ts similarity index 95% rename from packages/plugin/src/sync/conflict-copy.ts rename to packages/plugin/src/features/sync/apply/conflict-copy.ts index 6797678f..13196ba4 100644 --- a/packages/plugin/src/sync/conflict-copy.ts +++ b/packages/plugin/src/features/sync/apply/conflict-copy.ts @@ -1,11 +1,11 @@ import type { DataAdapter } from "obsidian"; -import { folderName } from "@/shared"; +import { folderName } from "@/core/shared"; /** Guard against an endless "(conflict from X) N" chain on one file. */ const CONFLICT_COPY_LIMIT = 100; /** "notes/todo.md" → "notes/todo (conflict from Phone 2026-07-05).md" */ -export function conflictCopyPath( +function conflictCopyPath( path: string, deviceName: string | undefined, now = new Date(), diff --git a/packages/plugin/src/features/sync/apply/conflict-merge.ts b/packages/plugin/src/features/sync/apply/conflict-merge.ts new file mode 100644 index 00000000..692469e7 --- /dev/null +++ b/packages/plugin/src/features/sync/apply/conflict-merge.ts @@ -0,0 +1,62 @@ +import type { DataAdapter } from "obsidian"; + +import { isDrawing, mergeDrawings } from "@/core/drawing"; +import { withEolOf } from "@/core/utils"; +import { loadLocalText, loadRemoteText } from "../changes/content"; +import type { ContentSource } from "../content/load"; +import { mergeJsonByKey } from "../hunks/json-merge"; +import { buildMergeSession, countUnresolved } from "../hunks/merge-model"; +import type { ScopePolicy } from "../scope/scope"; +import type { Conflict } from "../types"; + +/** Base, local, remote to the settled text, or null for a real conflict. */ +export type TextMerge = ( + base: string, + local: string, + remote: string, +) => string | null; + +/** + * How a conflict merges unattended: notes by line, settings JSON by key. Null for anything else, as a line + * merge of plugin code or other JSON can be valid by lines and broken as a file; those go to the merge screen. + */ +export function autoMergerFor( + scope: ScopePolicy, + path: string, +): TextMerge | null { + if (scope.isSettingsJson(path)) return mergeJsonByKey; + return /\.md$/i.test(path) ? mergeNote : null; +} + +/** + * Null, leaving the file untouched, when a side is binary or missing, there is no ancestor, or the conflict + * is real. The caller writes the result and should gate on `isTextMergeCandidate` to skip needless downloads. + */ +export async function tryAutoMergeConflict( + deps: ContentSource & { adapter: DataAdapter }, + conflict: Conflict, + merge: TextMerge, +): Promise { + if (!conflict.baselineHash || !conflict.localHash || !conflict.remoteHash) { + return null; + } + const [baseText, remoteText, localText] = await Promise.all([ + loadRemoteText(deps, conflict.baselineHash), + loadRemoteText(deps, conflict.remoteHash), + loadLocalText(deps.adapter, conflict.path), + ]); + if (baseText === null || remoteText === null || localText === null) { + return null; + } + return merge(baseText, localText, remoteText); +} + +function mergeNote(base: string, local: string, remote: string): string | null { + if ([base, remote, local].some(isDrawing)) { + return mergeDrawings(base, local, remote); + } + // The same regions the merge editor shows, so a file it calls clean opens without conflicts. + const { text, changes } = buildMergeSession(base, local, remote); + if (countUnresolved(changes) > 0) return null; + return withEolOf(local, text); +} diff --git a/packages/plugin/src/sync/pull-moves.ts b/packages/plugin/src/features/sync/apply/pull-moves.ts similarity index 93% rename from packages/plugin/src/sync/pull-moves.ts rename to packages/plugin/src/features/sync/apply/pull-moves.ts index 3d3e39e6..c7390622 100644 --- a/packages/plugin/src/sync/pull-moves.ts +++ b/packages/plugin/src/features/sync/apply/pull-moves.ts @@ -3,7 +3,7 @@ * re-downloaded, and a local edit goes with it. Each move lands whole or waits. */ -import { entryAt, reportWarning } from "@/shared"; +import { reportWarning } from "@/core/shared"; import { diskRefuses, ensureDir, @@ -12,12 +12,13 @@ import { renameCaseSafe, StrandedRenameError, unchangedSince, -} from "@/vault/io"; +} from "@/core/vault"; -import type { CompareResult, EngineDependencies } from "./engine"; -import { coldSince, writeIncoming } from "./live-notes"; -import { isUnder } from "./space"; -import type { Manifest, ManifestEntry } from "./types"; +import { entryAt } from "../changes/records"; +import type { CompareResult, EngineDependencies } from "../engine"; +import { coldSince, writeIncoming } from "../live-notes"; +import { isUnder } from "../remote/space"; +import type { Manifest, ManifestEntry } from "../types"; /** * Records each move in `written` as it lands, so one that stops the pull keeps those before it. Returns both diff --git a/packages/plugin/src/sync/pull.ts b/packages/plugin/src/features/sync/apply/pull.ts similarity index 85% rename from packages/plugin/src/sync/pull.ts rename to packages/plugin/src/features/sync/apply/pull.ts index b644d12b..31fdcbdc 100644 --- a/packages/plugin/src/sync/pull.ts +++ b/packages/plugin/src/features/sync/apply/pull.ts @@ -1,17 +1,19 @@ /** The pull: moves, downloads and deletions land, then the baseline follows what did. */ -import { DEFAULT_CONCURRENCY } from "@/constants"; -import { asError, entryAt } from "@/shared"; -import { runWithConcurrency, runWithFileConcurrency } from "@/utils"; -import { deletePath, unchangedSince } from "@/vault/io"; -import { advanceBaselineForPaths } from "./baseline"; -import { baseStep } from "./cut-short"; -import type { CompareResult, EngineDependencies } from "./engine"; -import type { Target } from "./journal"; -import { coldSince, settleLive, writeIncoming } from "./live-notes"; -import { objectKey } from "./manifest"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { asError } from "@/core/shared"; +import { runWithConcurrency } from "@/core/utils"; +import { deletePath, unchangedSince } from "@/core/vault"; +import { runWithFileConcurrency } from "../changes/file-concurrency"; +import { entryAt } from "../changes/records"; +import { prepareContent } from "../content/load"; +import type { CompareResult, EngineDependencies } from "../engine"; +import { coldSince, settleLive, writeIncoming } from "../live-notes"; +import { baseStep } from "../recovery/cut-short"; +import type { Target } from "../recovery/journal"; +import { advanceBaselineForPaths } from "../remote/baseline"; +import { EChangeType, type Manifest, type ManifestEntry } from "../types"; import { pullMoves, syncFolders } from "./pull-moves"; -import { EChangeType, type Manifest, type ManifestEntry } from "./types"; export interface PullResult { baseline: Manifest; @@ -86,20 +88,23 @@ async function land( const total = downloads.length + deletions.length; let done = 0; - const hashes = new Set(); + const sizes = new Map(); // Overwrites, and room snapshots for their merge base: any other new file cut short has no base, so it is // never merged. const targets = new Map(); for (const change of downloads) { const entry = entryAt(remote.files, change.path); if (!entry) continue; - hashes.add(entry.hash); + sizes.set(entry.hash, entry.size); if (entry.live || entryAt(compareResult.snapshot.files, change.path)) { const base = baseStep(deps, change.path, entry); targets.set(change.path, { hash: entry.hash, live: entry.live, base }); } } - deps.storage.prepareReads?.([...hashes].map(objectKey)); + await prepareContent( + deps, + [...sizes].map(([hash, size]) => ({ hash, size })), + ); // One durable claim for the batch, not one per file. const claims = await deps.journal?.claim(deps.space, targets); /** True when live editing settled the path: an open room keeps its file. */ diff --git a/packages/plugin/src/sync/auto-push.ts b/packages/plugin/src/features/sync/automation/auto-push.ts similarity index 73% rename from packages/plugin/src/sync/auto-push.ts rename to packages/plugin/src/features/sync/automation/auto-push.ts index 7d5c7277..6ec33236 100644 --- a/packages/plugin/src/sync/auto-push.ts +++ b/packages/plugin/src/features/sync/automation/auto-push.ts @@ -1,5 +1,5 @@ -import type { Space } from "./space"; -import { type DiffResult, EChangeType } from "./types"; +import type { Space } from "../remote/space"; +import { type DiffResult, EChangeType } from "../types"; export interface AutoPushSelection { paths: string[]; @@ -43,10 +43,14 @@ export type AutoPushSelector = ( only?: ReadonlySet, ) => string[]; -/** Held deletions go to `report` once per set, not on every cycle that holds the same ones. */ +/** + * Held deletions go to `report` once per set, not on every cycle that holds the same ones. `waiting` names + * what a later push takes: a slow file still being edited, a restored one not pushed by hand yet. + */ export function createAutoPushSelector( deleteLimit: () => number | null, report: (space: Space, held: readonly string[]) => void, + waiting: (space: Space, diff: DiffResult) => (path: string) => boolean, ): AutoPushSelector { const reported = new Map(); return (space, diff, only) => { @@ -59,7 +63,16 @@ export function createAutoPushSelector( reported.set(space.id, key); report(space, held); } - return paths; + const waits = waiting(space, diff); + const later = new Set(paths.filter(waits)); + // A push takes both ends of a move, so a held end holds the other. + for (const { from, to, side } of diff.moves) { + if (side === "local" && (waits(from) || waits(to))) { + later.add(from); + later.add(to); + } + } + return paths.filter((path) => !later.has(path)); }; } diff --git a/packages/plugin/src/features/sync/automation/restored-files.ts b/packages/plugin/src/features/sync/automation/restored-files.ts new file mode 100644 index 00000000..86e5063b --- /dev/null +++ b/packages/plugin/src/features/sync/automation/restored-files.ts @@ -0,0 +1,97 @@ +import type { CompareResult } from "../engine"; +import { insideOf, type Space, vaultPathOf } from "../remote/space"; +import type { DiffResult, LocalStore } from "../types"; + +/** Per space id, per path inside its root (a moved root keeps them): each hash a restore left, null: removed. */ +type Holds = Map>; + +/** + * Files a history restore wrote or removed, kept out of automatic pushes while they hold what it left: its + * dialogs promise nothing is pushed until the person says so. Kept on the device, so a restart keeps the promise. + */ +export class RestoredFiles { + private holds: Holds; + + constructor(private readonly store: LocalStore) { + this.holds = parse(store.load()); + } + + /** Before the write: one cut short must neither reach a push nor end an earlier restore's hold. */ + hold(space: Space, left: ReadonlyMap): void { + if (left.size === 0) return; + const kept = new Map(this.holds.get(space.id)); + for (const [path, hash] of left) { + const inside = insideOf(space, path); + kept.set(inside, [...new Set([...(kept.get(inside) ?? []), hash])]); + } + this.save(space, kept); + } + + /** Local changes that still hold what a restore left. */ + waiting(space: Space, diff: DiffResult): Set { + const kept = this.holds.get(space.id); + if (!kept) return new Set(); + return new Set( + diff.localChanges + .filter(({ path, localHash }) => + kept.get(insideOf(space, path))?.includes(localHash), + ) + .map(({ path }) => path), + ); + } + + /** + * After every compare: a change to another hash (an edit) or a scanned file with no change (pushed, pulled) + * ends a hold. Unseen is unknown (ignored, unreadable, another spelling) and keeps it. + */ + settle(space: Space, { snapshot, diff }: CompareResult): void { + const kept = this.holds.get(space.id); + if (!kept) return; + const changed = new Map( + [...diff.localChanges, ...diff.conflicts].map(({ path, localHash }) => [ + insideOf(space, path), + localHash, + ]), + ); + const still = new Map(); + for (const [inside, hashes] of kept) { + const local = changed.get(inside); + if (local === undefined) { + if (!Object.hasOwn(snapshot.files, vaultPathOf(space, inside))) { + still.set(inside, hashes); + } + } else if (hashes.includes(local)) { + still.set(inside, hashes.length > 1 ? [local] : hashes); + } + } + if ([...kept].some(([inside, hashes]) => still.get(inside) !== hashes)) { + this.save(space, still); + } + } + + private save(space: Space, kept: Map): void { + this.holds = new Map(this.holds); + if (kept.size > 0) this.holds.set(space.id, kept); + else this.holds.delete(space.id); + this.store.save( + Object.fromEntries( + [...this.holds].map(([id, paths]) => [id, Object.fromEntries(paths)]), + ), + ); + } +} + +function parse(value: unknown): Holds { + const holds: Holds = new Map(); + if (typeof value !== "object" || value === null) return holds; + for (const [space, paths] of Object.entries(value)) { + if (typeof paths !== "object" || paths === null) continue; + const valid = Object.entries(paths).filter( + (entry): entry is [string, (string | null)[]] => + Array.isArray(entry[1]) && + entry[1].every((hash) => typeof hash === "string" || hash === null), + ); + if (valid.length > 0) holds.set(space, new Map(valid)); + } + return holds; +} diff --git a/packages/plugin/src/sync/scheduler.ts b/packages/plugin/src/features/sync/automation/scheduler.ts similarity index 71% rename from packages/plugin/src/sync/scheduler.ts rename to packages/plugin/src/features/sync/automation/scheduler.ts index 0ff241d3..e14d18c7 100644 --- a/packages/plugin/src/sync/scheduler.ts +++ b/packages/plugin/src/features/sync/automation/scheduler.ts @@ -1,8 +1,11 @@ import type { Plugin, TAbstractFile } from "obsidian"; - -import { canSync, type MdsyncSettings } from "@/settings/model"; -import type { SyncController, SyncStatusSnapshot } from "./controller"; -import { type Space, spaceOf, VAULT_SPACE } from "./space"; +import type { MdsyncSettings } from "@/core/settings"; +import { isStorageConfigured } from "@/features/storage"; +import type { SyncController, SyncStatusSnapshot } from "../controller"; +import type { PassphraseManager } from "../remote/passphrase-manager"; +import { type Space, spaceOf, VAULT_SPACE } from "../remote/space"; +import { canSync } from "../settings"; +import { isSlowFile, type QueueEdit } from "./slow-files"; const AUTO_PULL_STARTUP_DELAY_MS = 3_000; @@ -27,6 +30,7 @@ export interface SchedulerHost extends Plugin { settings: MdsyncSettings; /** The records' partition: known from launch, before any refresh partitions. */ spaces: { partition(): readonly Space[] }; + passphrase: Pick; } export function registerScheduler( @@ -98,6 +102,8 @@ export function registerScheduler( // Interval 0 with the toggle on is deliberate: sync once after startup, then stay quiet until reload. if (host.settings.autoSyncEnabled) { scheduleFirstRun(host, () => void tick()); + } else { + scheduleFirstRun(host, () => void compareAtStartup(host, controller)); } // Read the interval on every wake-up so setting changes apply without restart. @@ -155,12 +161,18 @@ export function registerScheduler( } }); const backingOff = (): boolean => Date.now() < backoffUntil; + const slow = controller.slowFiles; + host.register(() => slow.clear()); + const slowQuietMs = (): number => host.settings.slowFileSettleSeconds * 1000; + const settle = (paths: ReadonlySet) => (): void => + slow.settled(paths, slowQuietMs(), queueEdit); const queueVaultPush = quietQueue( host, () => host.settings.autoPushSettleSeconds * 1000, backingOff, onOnline, - (paths) => void runQueuedPush(host, controller, paths), + (paths) => + void runQueuedPush(host, controller, paths).finally(settle(paths)), ); // One per share: typing in one must not hold back another's push. const shareQueues = new Map void>(); @@ -173,40 +185,94 @@ export function registerScheduler( backingOff, onOnline, (paths) => { - if (host.settings.pushSharesRightAway && canSync(host.settings)) { - void controller.autoPushShares(paths); - } + const push = + host.settings.pushSharesRightAway && canSync(host.settings) + ? controller.autoPushShares(paths) + : Promise.resolve(); + void push.finally(settle(paths)); }, ); shareQueues.set(space, queue); } queue(path); }; + /** Where an event of `path` queues; null when nothing there pushes on its own. */ + const queueOf = ( + path: string, + edit: boolean, + ): ((path: string) => void) | null => { + const { id, paused, readOnly } = spaceOf(host.spaces.partition(), path); + // Nothing there pushes: queued, it would only refresh. + if (paused || readOnly) return null; + const rightAway = + id !== VAULT_SPACE.id && host.settings.pushSharesRightAway; + // A waiting edit keeps its gutter marks until someone pushes it. + if (rightAway && !(edit && host.settings.shareEditsWait)) { + return (queued) => queueSharePush(id, queued); + } + return !rightAway && host.settings.autoPushAfterChange + ? queueVaultPush + : null; + }; + const queueEdit: QueueEdit = (path) => { + const queue = queueOf(path, true); + queue?.(path); + return queue !== null; + }; + const activePath = (): string | null => + host.app.workspace.getActiveFile()?.path ?? null; const onVaultEvent = (edit: boolean) => (file: TAbstractFile, oldPath?: string): void => { controller.noteLocalChange(); if (edit) controller.refreshSaved(file.path); for (const path of oldPath ? [file.path, oldPath] : [file.path]) { - const { id, paused, readOnly } = spaceOf(host.spaces.partition(), path); - // Nothing there pushes: queued, it would only refresh. - if (paused || readOnly) continue; - const rightAway = - id !== VAULT_SPACE.id && host.settings.pushSharesRightAway; - // A waiting edit keeps its gutter marks until someone pushes it. - if (rightAway && !(edit && host.settings.shareEditsWait)) { - queueSharePush(id, path); - } else if (!rightAway && host.settings.autoPushAfterChange) { - queueVaultPush(path); + if (!edit) slow.forget(path); + const queue = queueOf(path, edit); + if (!queue) continue; + // Held only where its edit queues: nothing else would ever release it to an automatic push. + if ( + edit && + path === activePath() && + isSlowFile(host.app, path, host.settings.slowFileSuffixes) + ) { + slow.saved(path, slowQuietMs(), queueEdit); + } else { + queue(path); } } }; + const leave = (): void => slow.left(activePath(), queueEdit); + host.registerEvent(host.app.workspace.on("active-leaf-change", leave)); + host.registerEvent(host.app.workspace.on("file-open", leave)); host.registerEvent(host.app.vault.on("modify", onVaultEvent(true))); host.registerEvent(host.app.vault.on("create", onVaultEvent(false))); host.registerEvent(host.app.vault.on("delete", onVaultEvent(false))); host.registerEvent(host.app.vault.on("rename", onVaultEvent(false))); } +/** + * Manual sync still shows where things stand after a launch: one compare, which moves nothing. Never a + * passphrase prompt on launch: the key is opened first from the entered or saved passphrase alone, and + * without one that opens the vault (none, or rotated on another device) the first sync action asks. + */ +async function compareAtStartup( + host: SchedulerHost, + controller: SyncController, +): Promise { + const { settings } = host; + // Autosync turned on since launch runs its own cycle; an open Changes panel may have compared already. + if (settings.autoSyncEnabled || !navigator.onLine || !canSync(settings)) { + return; + } + if (controller.getSnapshot().result) return; + if (isStorageConfigured(settings)) { + const unlocked = await host.passphrase.unlock().catch(() => false); + if (!unlocked) return; + } + await controller.refresh(); +} + /** * Starting before the metadata cache resolves costs 3x, as the scan competes with Obsidian's indexing. An * already-settled cache never re-fires `resolved`, so it uses the fixed delay. diff --git a/packages/plugin/src/features/sync/automation/slow-files.ts b/packages/plugin/src/features/sync/automation/slow-files.ts new file mode 100644 index 00000000..d357a18a --- /dev/null +++ b/packages/plugin/src/features/sync/automation/slow-files.ts @@ -0,0 +1,99 @@ +import type { App } from "obsidian"; +import { DRAWING_KEY } from "@/core/drawing"; + +/** Nonstop editing still pushes this often. */ +export const SLOW_FILE_CAP_MS = 10 * 60_000; + +const DRAWING_SUFFIX = ".excalidraw.md"; + +/** Named by one of `suffixes` (the setting); a drawing named as a plain note counts as `.excalidraw.md`. */ +export function isSlowFile(app: App, path: string, suffixes: string): boolean { + const name = path.toLowerCase(); + const listed = suffixes + .toLowerCase() + .split(/[\s,]+/) + .filter(Boolean); + if (listed.some((suffix) => name.endsWith(suffix))) return true; + return ( + listed.includes(DRAWING_SUFFIX) && + name.endsWith(".md") && + DRAWING_KEY in (app.metadataCache.getCache(path)?.frontmatter ?? {}) + ); +} + +/** Routes a due file as any edit; false when nothing queued it. */ +export type QueueEdit = (path: string) => boolean; + +interface Entry { + since: number; + /** Null once due: it waits for the push it was queued for. */ + timer: number | null; + /** Saved while due: the push may have read it before, so it is held again after. */ + again?: boolean; +} + +/** + * Files saved every few seconds while open (drawings, canvases), held out of automatic pushes while edited: + * they would push on every save and keep the vault's quiet queue from ever firing. A held file is due after its + * own quiet period, once its view is left, or {@link SLOW_FILE_CAP_MS} after its first held save. + */ +export class SlowFiles { + private readonly entries = new Map(); + + holds(path: string): boolean { + return (this.entries.get(path)?.timer ?? null) !== null; + } + + /** A save of `path` in the active view. */ + saved(path: string, quietMs: number, queue: QueueEdit): void { + const entry = this.entries.get(path); + if (entry && entry.timer === null) { + entry.again = true; + return; + } + const since = entry?.since ?? Date.now(); + if (entry?.timer != null) window.clearTimeout(entry.timer); + const wait = Math.min(quietMs, since + SLOW_FILE_CAP_MS - Date.now()); + const timer = window.setTimeout( + () => this.release(path, queue), + Math.max(0, wait), + ); + this.entries.set(path, { since, timer }); + } + + /** The active view shows `open` now: every other held file was left. */ + left(open: string | null, queue: QueueEdit): void { + for (const path of [...this.entries.keys()]) { + if (path !== open) this.release(path, queue); + } + } + + /** The push queued for `paths` ended, landed or not: the next save holds again. */ + settled(paths: Iterable, quietMs: number, queue: QueueEdit): void { + for (const path of paths) { + const entry = this.entries.get(path); + if (!entry || entry.timer !== null) continue; + this.entries.delete(path); + if (entry.again) this.saved(path, quietMs, queue); + } + } + + /** Deleted or renamed: its own event routes it. */ + forget(path: string): void { + const timer = this.entries.get(path)?.timer; + if (timer != null) window.clearTimeout(timer); + this.entries.delete(path); + } + + clear(): void { + for (const path of [...this.entries.keys()]) this.forget(path); + } + + private release(path: string, queue: QueueEdit): void { + const entry = this.entries.get(path); + if (!entry || entry.timer === null) return; + window.clearTimeout(entry.timer); + entry.timer = null; + if (!queue(path)) this.entries.delete(path); + } +} diff --git a/packages/plugin/src/sync/cancel.ts b/packages/plugin/src/features/sync/cancel.ts similarity index 100% rename from packages/plugin/src/sync/cancel.ts rename to packages/plugin/src/features/sync/cancel.ts diff --git a/packages/plugin/src/sync/binary-extensions.ts b/packages/plugin/src/features/sync/changes/binary-extensions.ts similarity index 100% rename from packages/plugin/src/sync/binary-extensions.ts rename to packages/plugin/src/features/sync/changes/binary-extensions.ts diff --git a/packages/plugin/src/sync/content.ts b/packages/plugin/src/features/sync/changes/content.ts similarity index 83% rename from packages/plugin/src/sync/content.ts rename to packages/plugin/src/features/sync/changes/content.ts index 47be1d45..7dfad507 100644 Binary files a/packages/plugin/src/sync/content.ts and b/packages/plugin/src/features/sync/changes/content.ts differ diff --git a/packages/plugin/src/sync/diff.ts b/packages/plugin/src/features/sync/changes/diff.ts similarity index 96% rename from packages/plugin/src/sync/diff.ts rename to packages/plugin/src/features/sync/changes/diff.ts index cebdad1c..f44c79a6 100644 --- a/packages/plugin/src/sync/diff.ts +++ b/packages/plugin/src/features/sync/changes/diff.ts @@ -1,6 +1,5 @@ -import type { ScopePolicy } from "@/vault/scope"; -import { reconcileBaselineResetGenerations } from "./config-reset"; -import { pairMoves } from "./moves"; +import { reconcileBaselineResetGenerations } from "../remote/config-reset"; +import type { ScopePolicy } from "../scope/scope"; import { type Conflict, type DiffResult, @@ -9,7 +8,8 @@ import { type LocalSnapshot, type Manifest, type ManifestEntry, -} from "./types"; +} from "../types"; +import { pairMoves } from "./moves"; export interface DiffInput { local: LocalSnapshot; diff --git a/packages/plugin/src/utils/file-concurrency.ts b/packages/plugin/src/features/sync/changes/file-concurrency.ts similarity index 94% rename from packages/plugin/src/utils/file-concurrency.ts rename to packages/plugin/src/features/sync/changes/file-concurrency.ts index 1ba4712f..948116ed 100644 --- a/packages/plugin/src/utils/file-concurrency.ts +++ b/packages/plugin/src/features/sync/changes/file-concurrency.ts @@ -1,4 +1,4 @@ -import { runWithConcurrency } from "./concurrency"; +import { runWithConcurrency } from "@/core/utils"; export const LARGE_FILE_BYTES = 8 * 1024 * 1024; diff --git a/packages/plugin/src/sync/moves.ts b/packages/plugin/src/features/sync/changes/moves.ts similarity index 99% rename from packages/plugin/src/sync/moves.ts rename to packages/plugin/src/features/sync/changes/moves.ts index e40d8bd2..4eb55c2a 100644 --- a/packages/plugin/src/sync/moves.ts +++ b/packages/plugin/src/features/sync/changes/moves.ts @@ -5,7 +5,7 @@ import { type FileChange, type ManifestEntry, type Move, -} from "./types"; +} from "../types"; type Unpaired = Omit; diff --git a/packages/plugin/src/shared/records.ts b/packages/plugin/src/features/sync/changes/records.ts similarity index 100% rename from packages/plugin/src/shared/records.ts rename to packages/plugin/src/features/sync/changes/records.ts diff --git a/packages/plugin/src/sync/remote-names.ts b/packages/plugin/src/features/sync/changes/remote-names.ts similarity index 92% rename from packages/plugin/src/sync/remote-names.ts rename to packages/plugin/src/features/sync/changes/remote-names.ts index 69566702..0b9fcb17 100644 --- a/packages/plugin/src/sync/remote-names.ts +++ b/packages/plugin/src/features/sync/changes/remote-names.ts @@ -1,6 +1,6 @@ -import { caseInsensitiveDisk, diskRefuses } from "@/vault/io"; -import type { ScopePolicy } from "@/vault/scope"; -import type { LocalSnapshot, Manifest, SkippedFile } from "./types"; +import { caseInsensitiveDisk, diskRefuses } from "@/core/vault"; +import type { ScopePolicy } from "../scope/scope"; +import type { LocalSnapshot, Manifest, SkippedFile } from "../types"; /** Remote paths this disk cannot hold, skipped so nothing pulls them or deletes them. */ export function skipUnholdableNames( diff --git a/packages/plugin/src/sync/constants.ts b/packages/plugin/src/features/sync/constants.ts similarity index 56% rename from packages/plugin/src/sync/constants.ts rename to packages/plugin/src/features/sync/constants.ts index 043c57b9..a18e6435 100644 --- a/packages/plugin/src/sync/constants.ts +++ b/packages/plugin/src/features/sync/constants.ts @@ -1,12 +1,16 @@ /** Remote object layout and engine-wide limits. */ -export const REMOTE_MANIFEST_KEY = "manifest.json.enc"; - export const REMOTE_OBJECTS_PREFIX = "objects/"; +/** A chunked file's root: its list of chunks (`features/sync/content/`). */ +export const REMOTE_RECIPES_PREFIX = "recipes/"; +export const REMOTE_CHUNKS_PREFIX = "chunks/"; -/** Single change log: snapshot metadata plus one parent-relative delta per snapshot. */ +/** The 1.x change log: deleted after the first v3 push (`clearLegacyHistory`), never read. */ export const REMOTE_HISTORY_LOG_KEY = "history.json.enc"; +/** Push records (`p/`) and the objects GC packs them into (`b/`). */ +export const REMOTE_HISTORY_PREFIX = "history/"; + /** Full manifests for pinned snapshots, so a pin survives its chain being evicted. */ export const REMOTE_PINS_PREFIX = "pins/"; @@ -14,7 +18,8 @@ export const REMOTE_SALT_KEY = "salt.bin"; export const REMOTE_KEYFILE_KEY = "keys.json"; -export const MANIFEST_VERSION = 2; +/** Every publish carries it, and a client refuses a higher one: 3 is the history layout under `history/`. */ +export const MANIFEST_VERSION = 3; /** Max paths attached to a single log entry, so one big sync cannot flood the log. */ export const LOG_PATH_LIMIT = 50; diff --git a/packages/plugin/src/features/sync/content/closure.ts b/packages/plugin/src/features/sync/content/closure.ts new file mode 100644 index 00000000..6ebee36b --- /dev/null +++ b/packages/plugin/src/features/sync/content/closure.ts @@ -0,0 +1,65 @@ +import type { EncryptionKey } from "@/core/crypto"; +import { runWithConcurrency } from "@/core/utils"; +import type { ListedObject, ObjectStorage } from "@/features/storage"; +import { chunkKey } from "./keys"; +import { recipeChunks } from "./load"; + +export interface ChunksNamed { + /** `chunks/` keys. */ + chunks: Set; + /** Recipes that did not read: what they name is unknown. */ + unreadable: string[]; +} + +// Chunk keys per recipe and etag: a recipe changes only by a re-put of the same file, so a sweep re-reads +// none it read before. +const memo = new WeakMap>(); + +interface Read { + etag: string; + chunks: string[]; +} + +/** Forgets recipes `listed` (every recipe) no longer holds: a sweep deletes them, a session would keep them. */ +export function forgetUnlistedRecipes( + storage: ObjectStorage, + listed: readonly ListedObject[], +): void { + const known = memo.get(storage); + if (!known) return; + const keys = new Set(listed.map(({ key }) => key)); + for (const at of known.keys()) if (!keys.has(at)) known.delete(at); +} + +/** The chunks `recipes` name; one gone since its listing names nothing. */ +export async function chunksNamed( + storage: ObjectStorage, + key: EncryptionKey, + recipes: readonly ListedObject[], + concurrency: number, +): Promise { + const known = memo.get(storage) ?? new Map(); + memo.set(storage, known); + const named: ChunksNamed = { chunks: new Set(), unreadable: [] }; + await runWithConcurrency(recipes, concurrency, async ({ key: at, etag }) => { + const hit = known.get(at); + const chunks = hit && hit.etag === etag ? hit.chunks : await read(at); + if (!chunks) { + named.unreadable.push(at); + return; + } + if (etag !== null) known.set(at, { etag, chunks }); + for (const chunk of chunks) named.chunks.add(chunk); + }); + return named; + + async function read(recipeKey: string): Promise { + const blob = await storage.get(recipeKey); + if (!blob) return []; + try { + return (await recipeChunks(key, blob)).map(([id]) => chunkKey(id)); + } catch { + return null; + } + } +} diff --git a/packages/plugin/src/features/sync/content/cut.ts b/packages/plugin/src/features/sync/content/cut.ts new file mode 100644 index 00000000..a12ff626 --- /dev/null +++ b/packages/plugin/src/features/sync/content/cut.ts @@ -0,0 +1,48 @@ +import { type ChunkParams, chunkEnds, gearTable } from "@/core/chunking"; +import { chunkId } from "@/core/crypto"; +import { encodeDrawing } from "@/core/drawing"; + +// Every device cuts with the same seed and sizes, or one file would be cut two ways and share nothing. +const GEAR = gearTable(0x6d64); +const KB = 1024; +const SMALL_CHUNKS: ChunkParams = { min: 16 * KB, avg: 64 * KB, max: 256 * KB }; +/** Past it, bigger chunks keep a file's recipe and request count small. */ +const LARGE_FILE = 16 * KB * KB; +const LARGE_CHUNKS: ChunkParams = { + min: 256 * KB, + avg: 1024 * KB, + max: 4096 * KB, +}; + +/** The stored form of a file of `size` bytes, cut into chunks: views of `stored`, no copies. */ +export function cut(stored: Uint8Array, size: number): Uint8Array[] { + const params = size > LARGE_FILE ? LARGE_CHUNKS : SMALL_CHUNKS; + let start = 0; + return chunkEnds(stored, params, GEAR).map((end) => { + const part = stored.subarray(start, end); + start = end; + return part; + }); +} + +/** + * The chunks of `local`, a file's copy on this disk, that are among `wanted`: cut as a file of `size` bytes, + * the remote one's, since the size picks the chunk sizes. None when it does not read. + */ +export async function chunksOf( + chunkIds: CryptoKey, + local: () => Promise, + size: number, + wanted: ReadonlySet, +): Promise> { + const bytes = await local().catch(() => null); + const found = new Map(); + if (!bytes) return found; + const parts = cut(encodeDrawing(bytes)?.stored ?? bytes, size); + const ids = await Promise.all(parts.map((part) => chunkId(chunkIds, part))); + parts.forEach((part, index) => { + const id = ids[index] as string; + if (wanted.has(id)) found.set(id, part); + }); + return found; +} diff --git a/packages/plugin/src/features/sync/content/header.ts b/packages/plugin/src/features/sync/content/header.ts new file mode 100644 index 00000000..e7b46ac2 --- /dev/null +++ b/packages/plugin/src/features/sync/content/header.ts @@ -0,0 +1,44 @@ +import { type DrawingCodec, isDrawingCodec } from "@/core/drawing"; + +/** A chunk's id and its plain size. */ +export type ChunkRef = [id: string, size: number]; + +/** What a described root (`BLOB_VERSION_DESCRIBED`) says about how its payload maps to the file. */ +export interface ContentHeader { + /** Absent: the stored form is the file. */ + codec?: DrawingCodec; + /** The stored form, in order; only a `recipes/` root names them, with an empty payload. */ + chunks?: ChunkRef[]; +} + +/** Anything this build does not know makes the content unreadable: guessing could only give wrong bytes. */ +export function readHeader(header: unknown, recipe: boolean): ContentHeader { + if (typeof header !== "object" || header === null || Array.isArray(header)) { + throw new Error("Unreadable content header"); + } + const { codec, chunks, ...rest } = header as Record; + if (Object.keys(rest).length > 0) throw new Error("Unknown content header"); + if (codec !== undefined && !isDrawingCodec(codec)) { + throw new Error("Unknown content codec"); + } + if (chunks === undefined) { + if (recipe) throw new Error("A recipe names no chunks"); + return codec ? { codec } : {}; + } + if (!recipe || !Array.isArray(chunks) || !chunks.every(isChunkRef)) { + throw new Error("Unreadable chunk list"); + } + return codec ? { codec, chunks } : { chunks }; +} + +function isChunkRef(value: unknown): value is ChunkRef { + if (!Array.isArray(value) || value.length !== 2) return false; + const [id, size] = value; + return ( + typeof id === "string" && + id.length > 0 && + !id.includes("/") && + Number.isInteger(size) && + size >= 0 + ); +} diff --git a/packages/plugin/src/features/sync/content/keys.ts b/packages/plugin/src/features/sync/content/keys.ts new file mode 100644 index 00000000..7d2e3aaf --- /dev/null +++ b/packages/plugin/src/features/sync/content/keys.ts @@ -0,0 +1,41 @@ +import { + REMOTE_CHUNKS_PREFIX, + REMOTE_OBJECTS_PREFIX, + REMOTE_RECIPES_PREFIX, +} from "../constants"; + +/** A file this size or more is stored as chunks, judged by the file itself so a manifest entry tells. */ +export const CHUNK_THRESHOLD = 256 * 1024; + +export function objectKey(hash: string): string { + return `${REMOTE_OBJECTS_PREFIX}${hash}`; +} + +export function recipeKey(hash: string): string { + return `${REMOTE_RECIPES_PREFIX}${hash}`; +} + +export function chunkKey(id: string): string { + return `${REMOTE_CHUNKS_PREFIX}${id}`; +} + +export function isRecipeKey(storageKey: string): boolean { + return storageKey.startsWith(REMOTE_RECIPES_PREFIX); +} + +/** The file hash a `objects/` or `recipes/` key names. */ +export function rootHash(storageKey: string): string { + return storageKey.slice(storageKey.indexOf("/") + 1); +} + +/** Every key a file's root may sit under: a hash alone does not say which. */ +export function rootKeys(hash: string): [string, string] { + return [objectKey(hash), recipeKey(hash)]; +} + +/** Likeliest first: a big file uploaded before chunking sits whole under `objects/`. */ +export function readOrder(hash: string, size?: number): string[] { + const [whole, recipe] = rootKeys(hash); + if (size === undefined) return [whole, recipe]; + return size >= CHUNK_THRESHOLD ? [recipe, whole] : [whole]; +} diff --git a/packages/plugin/src/features/sync/content/load.ts b/packages/plugin/src/features/sync/content/load.ts new file mode 100644 index 00000000..6b9d8b1b --- /dev/null +++ b/packages/plugin/src/features/sync/content/load.ts @@ -0,0 +1,201 @@ +import { + decryptBytes, + decryptDescribed, + type EncryptionKey, + isDescribed, + sha256Hex, +} from "@/core/crypto"; +import { decodeDrawing } from "@/core/drawing"; +import { runWithConcurrency } from "@/core/utils"; +import type { ObjectStorage } from "@/features/storage"; +import { chunksOf } from "./cut"; +import { type ChunkRef, type ContentHeader, readHeader } from "./header"; +import { chunkKey, isRecipeKey, readOrder } from "./keys"; + +export interface ContentSource { + storage: ObjectStorage; + key: EncryptionKey; + /** Names chunks; absent stores every file whole. */ + chunkIds?: CryptoKey; +} + +const CHUNK_READS = 4; + +/** The stored form cannot give the file; a failed read never is one, so deep verify tells them apart. */ +export class ContentError extends Error {} + +// Recipes `prepareContent` read for its hints, each taken once by the load that needs it. A root names its +// file's hash, so one re-put meanwhile can only give the same file. +const prefetched = new WeakMap>(); + +/** A copy of the file on this disk, an older version, whose unchanged chunks need no download. */ +export interface LocalCopy { + read(): Promise; + /** The remote file's bytes: they pick the chunk sizes. */ + size: number; +} + +/** + * The file `hash` names, or null only when no root of it exists; anything else, a missing chunk too, throws. + * `size`: the file's bytes, which pick where to look first and stretch the transfer deadline. + */ +export async function loadContent( + source: ContentSource, + hash: string, + size?: number, + local?: () => Promise, +): Promise { + const root = await fetchRoot(source.storage, hash, size); + const copy = local && size !== undefined ? { read: local, size } : undefined; + return root && openContent(source, root.blob, hash, root.storageKey, copy); +} + +/** The first root of `hash` that exists, looked for in {@link readOrder}. */ +export async function fetchRoot( + storage: ObjectStorage, + hash: string, + size?: number, +): Promise<{ storageKey: string; blob: Uint8Array } | null> { + for (const storageKey of readOrder(hash, size)) { + const blob = + take(storage, storageKey) ?? (await storage.get(storageKey, size)); + if (blob) return { storageKey, blob }; + } + return null; +} + +/** + * The bytes the root at `storageKey` holds for `hash`, checked against it: a rebuilt file that does not hash to + * its name is refused. For a caller that fetches the root itself and must tell a failed read from a bad blob. + */ +export async function openContent( + source: ContentSource, + blob: Uint8Array, + hash: string, + storageKey: string, + local?: LocalCopy, +): Promise { + const { codec, chunks, payload } = await content(() => + openRoot(source.key, blob, isRecipeKey(storageKey)), + ); + const stored = chunks ? await readChunks(source, chunks, local) : payload; + const bytes = await content(async () => + codec ? decodeDrawing(stored, codec) : stored, + ); + if ((await sha256Hex(bytes)) !== hash) { + throw new ContentError(`Hash mismatch for remote object ${hash}`); + } + return bytes; +} + +/** The chunks a `recipes/` root names; throws when it is not one this build reads. */ +export function recipeChunks( + key: EncryptionKey, + blob: Uint8Array, +): Promise { + return content(async () => { + const { chunks } = await openRoot(key, blob, true); + return chunks as ChunkRef[]; + }); +} + +/** + * Hints the reads a batch will make: every root it may read, then the chunks big ones name. A hint replaces + * the one before, so the batch is hinted whole; the recipes read for it are kept for its loads. + */ +export async function prepareContent( + source: ContentSource, + entries: readonly { hash: string; size: number }[], +): Promise { + const { storage } = source; + prefetched.delete(storage); + if (!storage.prepareReads) return; + const roots = entries.flatMap(({ hash, size }) => readOrder(hash, size)); + storage.prepareReads(roots); + const recipes = roots.filter(isRecipeKey); + if (recipes.length === 0) return; + const kept = new Map(); + prefetched.set(storage, kept); + const chunks = new Set(); + // Best effort: a read that fails here fails again in its own load, which reports it. + await runWithConcurrency(recipes, CHUNK_READS, async (storageKey) => { + const blob = await storage.get(storageKey).catch(() => null); + if (!blob) return; + kept.set(storageKey, blob); + const named = await recipeChunks(source.key, blob).catch(() => []); + for (const [id] of named) chunks.add(chunkKey(id)); + }); + storage.prepareReads([...roots, ...chunks]); +} + +async function openRoot( + key: EncryptionKey, + blob: Uint8Array, + recipe: boolean, +): Promise { + if (!isDescribed(blob)) { + if (recipe) throw new Error("Unreadable recipe"); + return { payload: await decryptBytes(key, blob) }; + } + const { header, payload } = await decryptDescribed(key, blob); + const read = readHeader(header, recipe); + if (read.chunks && payload.length > 0) throw new Error("Unreadable recipe"); + return { ...read, payload }; +} + +async function readChunks( + source: ContentSource, + chunks: readonly ChunkRef[], + local: LocalCopy | undefined, +): Promise { + // An id is a MAC of the bytes, so a local chunk of the same id is the same chunk; the hash check stays. + const onDisk = + local && source.chunkIds + ? await chunksOf( + source.chunkIds, + local.read, + local.size, + new Set(chunks.map(([id]) => id)), + ) + : new Map(); + const parts: Uint8Array[] = new Array(chunks.length); + await runWithConcurrency(chunks, CHUNK_READS, async ([id, size], index) => { + const kept = onDisk.get(id); + if (kept) { + parts[index] = kept; + return; + } + const blob = await source.storage.get(chunkKey(id), size); + if (!blob) throw new ContentError(`A chunk of this file is missing: ${id}`); + const part = await content(() => decryptBytes(source.key, blob)); + if (part.length !== size) { + throw new ContentError(`Chunk ${id} has the wrong size`); + } + parts[index] = part; + }); + const bytes = new Uint8Array(chunks.reduce((sum, [, size]) => sum + size, 0)); + let at = 0; + for (const part of parts) { + bytes.set(part, at); + at += part.length; + } + return bytes; +} + +async function content(open: () => Promise): Promise { + try { + return await open(); + } catch (error) { + if (error instanceof ContentError) throw error; + throw new ContentError( + error instanceof Error ? error.message : String(error), + ); + } +} + +function take(storage: ObjectStorage, storageKey: string): Uint8Array | null { + const kept = prefetched.get(storage); + const blob = kept?.get(storageKey) ?? null; + kept?.delete(storageKey); + return blob; +} diff --git a/packages/plugin/src/features/sync/content/store.ts b/packages/plugin/src/features/sync/content/store.ts new file mode 100644 index 00000000..89e7025c --- /dev/null +++ b/packages/plugin/src/features/sync/content/store.ts @@ -0,0 +1,144 @@ +import { chunkId, encryptCompressible, encryptDescribed } from "@/core/crypto"; +import { type DrawingCodec, encodeDrawing } from "@/core/drawing"; +import { runWithConcurrency } from "@/core/utils"; +import type { ObjectStorage } from "@/features/storage"; +import { rememberUpload, uploadedHere } from "../remote/uploads"; +import { cut } from "./cut"; +import type { ChunkRef } from "./header"; +import { + CHUNK_THRESHOLD, + chunkKey, + objectKey, + readOrder, + recipeKey, +} from "./keys"; +import { type ContentSource, recipeChunks } from "./load"; + +const CHUNK_WRITES = 4; + +interface Stored { + bytes: Uint8Array; + codec?: DrawingCodec; +} + +/** + * PUTs `bytes` as the file named `hash`: whole, or from {@link CHUNK_THRESHOLD} as a recipe plus the chunks + * the storage may lack. Whether it holds the root already is the caller's call. `previous`: HEAD's entry at + * the path, whose chunks HEAD vouches for. False when the root leans on them: it stands only under that HEAD, + * so a resumed push must store it again rather than trust it. + */ +export async function storeContent( + source: ContentSource, + hash: string, + bytes: Uint8Array, + previous?: { hash: string; size: number } | null, +): Promise { + const drawing = encodeDrawing(bytes); + const stored: Stored = drawing + ? { bytes: drawing.stored, codec: drawing.codec } + : { bytes }; + if (source.chunkIds && bytes.length >= CHUNK_THRESHOLD) { + const chunked = await storeChunked( + source, + source.chunkIds, + hash, + bytes.length, + stored, + previous, + ); + if (chunked !== null) return !chunked.leans; + } + await source.storage.put(objectKey(hash), await seal(source, bytes, stored)); + return true; +} + +/** True when a root of `hash` exists, looked for where its size says first. */ +export async function isStored( + storage: ObjectStorage, + hash: string, + size?: number, +): Promise { + for (const storageKey of readOrder(hash, size)) { + if (await storage.exists(storageKey)) return true; + } + return false; +} + +async function storeChunked( + source: ContentSource, + chunkIds: CryptoKey, + hash: string, + size: number, + stored: Stored, + previous: { hash: string; size: number } | null | undefined, +): Promise<{ leans: boolean } | null> { + const parts = cut(stored.bytes, size); + const ids = await Promise.all(parts.map((part) => chunkId(chunkIds, part))); + const chunks = parts.map( + (part, index): ChunkRef => [ids[index] as string, part.length], + ); + let recipe: Uint8Array; + try { + recipe = await encryptDescribed( + source.key, + stored.codec ? { codec: stored.codec, chunks } : { chunks }, + new Uint8Array(0), + ); + } catch { + // No CompressionStream here: a whole blob is one every peer reads. + return null; + } + const vouched = await vouchedBy(source, previous); + const fresh = new Map(); + parts.forEach((part, index) => { + const id = ids[index] as string; + if (!vouched.has(id)) fresh.set(id, part); + }); + const { storage } = source; + await runWithConcurrency([...fresh], CHUNK_WRITES, async ([id, part]) => { + const storageKey = chunkKey(id); + // Chunk keys share the upload log with file hashes: neither can be the other. + if ( + uploadedHere(storage, storageKey) && + (await storage.exists(storageKey)) + ) { + return; + } + await storage.put(storageKey, await encryptCompressible(source.key, part)); + rememberUpload(storage, storageKey); + }); + // Last: a recipe present means its chunks landed, so a resumed push may skip the file. + await storage.put(recipeKey(hash), recipe); + return { leans: ids.some((id) => vouched.has(id)) }; +} + +/** Chunk ids `previous`'s recipe names; none when it was stored whole or does not read. */ +async function vouchedBy( + source: ContentSource, + previous: { hash: string; size: number } | null | undefined, +): Promise> { + if (!previous || previous.size < CHUNK_THRESHOLD) return new Set(); + const blob = await source.storage.get(recipeKey(previous.hash)); + if (!blob) return new Set(); + const named = await recipeChunks(source.key, blob).catch(() => []); + return new Set(named.map(([id]) => id)); +} + +async function seal( + source: ContentSource, + bytes: Uint8Array, + stored: Stored, +): Promise { + if (stored.codec) { + try { + return await encryptDescribed( + source.key, + { codec: stored.codec }, + stored.bytes, + ); + } catch { + // No CompressionStream here: a plain blob is one every peer reads. + } + } + return encryptCompressible(source.key, bytes); +} diff --git a/packages/plugin/src/sync/controller.ts b/packages/plugin/src/features/sync/controller.ts similarity index 81% rename from packages/plugin/src/sync/controller.ts rename to packages/plugin/src/features/sync/controller.ts index 9f2a6ef3..886a68f3 100644 --- a/packages/plugin/src/sync/controller.ts +++ b/packages/plugin/src/features/sync/controller.ts @@ -1,31 +1,41 @@ -import type { LocalOpener } from "@/core/session-factory"; -import { ESyncLogOperation } from "@/logs/store"; -import type { SettingsSyncCategories } from "@/settings/model"; -import { authorOf, type LastEdit } from "./authors"; -import { type AutoPushSelector, createAutoPushSelector } from "./auto-push"; -import { clearRemoteTextCache } from "./content"; -import { defaultDeviceName } from "./device"; +import { ESyncLogOperation } from "@/core/logs"; +import type { SettingsSyncCategories } from "@/core/settings"; +import { + type AutoPushSelector, + createAutoPushSelector, +} from "./automation/auto-push"; +import { RestoredFiles } from "./automation/restored-files"; +import { SlowFiles } from "./automation/slow-files"; +import { clearRemoteTextCache } from "./changes/content"; import type { EngineDependencies } from "./engine"; -import type { HunkSelection } from "./hunks"; +import { ActivityCache } from "./history/activity-cache"; +import type { Activity } from "./history/model/types"; +import type { HunkSelection } from "./hunks/hunks"; +import { authorOf, type LastEdit } from "./identity/authors"; +import { defaultDeviceName } from "./identity/device"; +import { runCategoryResetFlow } from "./operations/config-reset"; +import { + runAdoptNewVaultFlow, + runResetRemoteStorageFlow, +} from "./operations/flows"; +import { + type LocalHunksArgs, + localHunksOp, + pullHunksOp, +} from "./operations/hunks"; +import { pullPathsOp } from "./operations/pull"; +import { pushPathsOp } from "./operations/push"; import { batchAcceptRemoteOp, batchKeepLocalOp, - type HunkSidesHash, keepBothConflictOp, - type LocalHunksArgs, - localHunksOp, type MergedSaveArgs, - type Operation, - pullHunksOp, - pullPathsOp, - pushPathsOp, - revertPathsOp, - runAdoptNewVaultFlow, - runResetRemoteStorageFlow, - type SyncOperationResult, saveMergedOp, -} from "./operations"; -import { runCategoryResetFlow } from "./operations/config-reset"; +} from "./operations/resolve"; +import { revertPathsOp } from "./operations/revert"; +import type { HunkSidesHash } from "./operations/text-loaders"; +import type { Operation, SyncOperationResult } from "./operations/types"; +import { pathsBySpace, type Space, spaceOf, VAULT_SPACE } from "./remote/space"; import { runRefreshCycle } from "./runtime/auto-cycle"; import { SyncControllerRuntimeState, @@ -41,8 +51,7 @@ import { } from "./runtime/operation-runner"; import { RefreshQueue } from "./runtime/refresh-queue"; import { SavedRefresh } from "./runtime/saved-refresh"; -import { pathsBySpace, type Space, spaceOf, VAULT_SPACE } from "./space"; -import type { LocalState } from "./types"; +import type { LocalState, LocalStore } from "./types"; export const EConflictStrategy = { KeepLocal: "keep-local", @@ -51,6 +60,22 @@ export const EConflictStrategy = { export type EConflictStrategy = (typeof EConflictStrategy)[keyof typeof EConflictStrategy]; +export type SessionFiles = Pick< + EngineDependencies, + "space" | "adapter" | "scope" | "state" | "maxFileBytes" +>; + +/** What a display-only look at one space's files needs: no storage, no key. */ +export type LocalSession = SessionFiles & { + /** The storage `state` belongs to. */ + identity: string; +}; + +export type LocalOpener = ( + space: Space, + partition: readonly Space[], +) => Promise; + export interface SyncControllerHost { /** * The vault first. Asked once per refresh; the partition holds until the next. Null when the vault cannot @@ -62,6 +87,10 @@ export interface SyncControllerHost { space: Space, partition: readonly Space[], ): Promise; + /** Where the vault's last-read activity is kept on this device; without it nothing is. */ + activityStore?: LocalStore; + /** Where restored files wait for a push by hand; without it they wait for this session only. */ + restoredStore?: LocalStore; /** A quick local look at the space's files; null where a session would need a prompt. Never reaches the network. */ openLocal?: LocalOpener; persistState(state: LocalState): Promise; @@ -80,6 +109,8 @@ export interface SyncControllerHost { onSpaceGone?(space: Space): void; /** A disk walk found files Obsidian's index lacks: synced, shown after a restart. */ onUnindexed?(count: number): void; + /** A pull wrote what Obsidian reads only when it starts (`ScopePolicy.loadsOnStartup`). */ + onPluginsPulled?(): void; /** How many deletions one automatic push may publish; null for any number. */ autoDeleteLimit?(): number | null; /** An automatic push left these deletions for the person: more than `autoDeleteLimit`. */ @@ -122,6 +153,9 @@ const CONFLICT_STRATEGY_OPS: Record< }, }; +/** Without a host store, kept for this session only. */ +const NO_STORE: LocalStore = { load: () => null, save: () => {} }; + export class SyncController { private readonly host: SyncControllerHost; private readonly runtimeState: SyncControllerRuntimeState; @@ -133,10 +167,18 @@ export class SyncController { private localRevision = 0; readonly history: HistoryService; readonly maintenance: MaintenanceService; + readonly activity: ActivityCache; + /** Driven by the scheduler, read by every automatic push. */ + readonly slowFiles = new SlowFiles(); + private readonly restored: RestoredFiles; constructor(host: SyncControllerHost) { this.host = host; this.runtimeState = new SyncControllerRuntimeState(); + this.activity = new ActivityCache(host.activityStore ?? NO_STORE); + this.restored = new RestoredFiles(host.restoredStore ?? NO_STORE); + const remember = (storage: string, activity: Activity, since: number) => + this.activity.remember(storage, activity, since); const open = (space: Space) => this.operations.openSession(space); this.fileDiffs = new FileDiffService({ openSession: (path, space) => open(space ?? this.spaceFor(path)), @@ -149,6 +191,8 @@ export class SyncController { runtimeState: this.runtimeState, clearFileDiffs: () => this.fileDiffs.clear(), localRevision: () => this.localRevision, + onPublished: (space) => this.maintenance.afterPush(space), + onCompared: (space, result) => this.restored.settle(space, result), }); this.autoPushPaths = createAutoPushSelector( () => host.autoDeleteLimit?.() ?? null, @@ -160,6 +204,10 @@ export class SyncController { ); host.onDeletionsHeld?.(space, held); }, + (space, diff) => { + const restored = this.restored.waiting(space, diff); + return (path) => this.slowFiles.holds(path) || restored.has(path); + }, ); this.refreshes = new RefreshQueue( (run) => this.runtimeState.enqueue(run), @@ -178,12 +226,18 @@ export class SyncController { open(path === undefined ? VAULT_SPACE : this.spaceFor(path)), enqueue: (task) => this.runtimeState.enqueue(task), refresh: () => this.operations.refreshNow(), + remember, + restored: (space, left) => this.restored.hold(space, left), }); this.maintenance = new MaintenanceService({ - openSession: () => open(VAULT_SPACE), + openSession: open, enqueue: (task) => this.runtimeState.enqueue(task), + enqueueQuiet: (task) => this.runtimeState.enqueueQuiet(task), logInfo: (operation, message, details) => this.host.logInfo(operation, message, details), + logWarn: (operation, message, details) => + this.host.logWarn(operation, message, details), + remember, }); } @@ -225,6 +279,7 @@ export class SyncController { dispose(): void { this.saved.dispose(); + this.maintenance.dispose(); this.runtimeState.dispose(); this.fileDiffs.clear(); clearRemoteTextCache(); @@ -314,9 +369,12 @@ export class SyncController { } async resetRemoteStorage(): Promise { - return this.operations.runFlow(ESyncLogOperation.Reset, (deps, ctx) => - runResetRemoteStorageFlow(deps, ctx), + const reset = await this.operations.runFlow( + ESyncLogOperation.Reset, + (deps, ctx) => runResetRemoteStorageFlow(deps, ctx), ); + if (reset) this.activity.forget(); + return reset; } async resetCategory( @@ -328,9 +386,12 @@ export class SyncController { } async adoptNewVault(): Promise { - return this.operations.runFlow(ESyncLogOperation.Compare, (deps, ctx) => - runAdoptNewVaultFlow(deps, ctx), + const adopted = await this.operations.runFlow( + ESyncLogOperation.Compare, + (deps, ctx) => runAdoptNewVaultFlow(deps, ctx), ); + if (adopted) this.activity.forget(); + return adopted; } /** Runs between operations: none still running persists over what `task` writes. */ diff --git a/packages/plugin/src/sync/engine.ts b/packages/plugin/src/features/sync/engine.ts similarity index 77% rename from packages/plugin/src/sync/engine.ts rename to packages/plugin/src/features/sync/engine.ts index a60c98e1..d177ed3b 100644 --- a/packages/plugin/src/sync/engine.ts +++ b/packages/plugin/src/features/sync/engine.ts @@ -1,32 +1,38 @@ import type { DataAdapter } from "obsidian"; -import { DEFAULT_CONCURRENCY } from "@/constants"; -import { type EncryptionKey, encryptBytes, sha256Hex } from "@/crypto"; -import { sceneOfBytes } from "@/drawing"; -import { entryAt, reportWarning, sortedByPath } from "@/shared"; -import type { StorageAdapter } from "@/storage/types"; -import { REMOTE_OBJECTS_PREFIX } from "@/sync/constants"; -import { runWithFileConcurrency } from "@/utils"; -import type { VaultIndex } from "@/vault/file-index"; -import { readBinary } from "@/vault/io"; -import { scanVault } from "@/vault/scanner"; -import type { ScopePolicy } from "@/vault/scope"; -import { attribute, publisher } from "./authors"; -import { foldersToPublish } from "./baseline"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { type EncryptionKey, sha256Hex } from "@/core/crypto"; +import { sceneOfBytes } from "@/core/drawing"; +import { reportWarning } from "@/core/shared"; +import type { VaultIndex } from "@/core/vault"; +import { readBinary } from "@/core/vault"; +import type { StorageAdapter } from "@/features/storage"; import { throwIfCancelled } from "./cancel"; -import { finishCutShort, withLanded } from "./cut-short"; -import { diffWithin } from "./diff"; -import { ownedFiles } from "./foreign"; -import { type HistoryConfig, publishManifestWithHistory } from "./history"; -import type { WriteJournal } from "./journal"; +import { diffWithin } from "./changes/diff"; +import { runWithFileConcurrency } from "./changes/file-concurrency"; +import { entryAt, sortedByPath } from "./changes/records"; +import { skipUnholdableNames } from "./changes/remote-names"; +import { REMOTE_OBJECTS_PREFIX, REMOTE_RECIPES_PREFIX } from "./constants"; +import { readOrder, rootHash } from "./content/keys"; +import { isStored, storeContent } from "./content/store"; +import { untrackedDir } from "./history/changes"; +import { publishManifestWithHistory } from "./history/publish"; +import type { HistoryConfig } from "./history/types"; +import { attribute, publisher } from "./identity/authors"; +import { VAULT_MISMATCH_MESSAGE } from "./identity/vault-mismatch"; import type { LiveNotes } from "./live-notes"; +import { finishCutShort, withLanded } from "./recovery/cut-short"; +import type { WriteJournal } from "./recovery/journal"; +import { foldersToPublish } from "./remote/baseline"; +import { ownedFiles } from "./remote/foreign"; import { buildManifest, fetchRemoteManifest, - objectKey, reconcileRemoteAgainstBaseline, -} from "./manifest"; -import { skipUnholdableNames } from "./remote-names"; -import { assertSpacePresent, type Space } from "./space"; +} from "./remote/manifest"; +import { assertSpacePresent, type Space } from "./remote/space"; +import { forgetUploads, rememberUpload, uploadedHere } from "./remote/uploads"; +import { scanVault } from "./scope/scanner"; +import type { ScopePolicy } from "./scope/scope"; import { type DiffResult, EChangeType, @@ -39,7 +45,6 @@ import { type ManifestEntry, type SessionState, } from "./types"; -import { forgetUploads, rememberUpload, uploadedHere } from "./uploads"; export interface EngineDependencies { space: Space; @@ -49,6 +54,8 @@ export interface EngineDependencies { /** Absent falls the scanner back to walking the adapter. */ index?: VaultIndex; key: EncryptionKey; + /** Names chunks; absent stores every file whole. */ + chunkIds?: CryptoKey; state: SessionState; maxFileBytes: number; concurrency?: number; @@ -163,7 +170,7 @@ export async function pushPaths( deps.storage.prepareWrites?.( uploads .filter((entry) => !knownHashes.has(entry.hash)) - .map((entry) => objectKey(entry.hash)), + .flatMap((entry) => readOrder(entry.hash, entry.size)), ); let done = 0; await runWithFileConcurrency( @@ -176,7 +183,8 @@ export async function pushPaths( const probe = resumed.has(entry.hash) && (listed === null || listed.has(entry.hash)); - await uploadObject(deps, entry, probe); + const previous = entryAt(compareResult.remote?.files ?? {}, entry.path); + await uploadObject(deps, entry, probe, previous); } onProgress?.(++done, uploads.length); }, @@ -195,21 +203,24 @@ export async function pushPaths( return manifest; } +/** `previous`: HEAD's entry at the path the bytes go to, whose chunks HEAD vouches for. */ export async function storeObject( deps: EngineDependencies, known: ReadonlySet, bytes: Uint8Array, + previous?: ManifestEntry, ): Promise { const hash = await sha256Hex(bytes); if (known.has(hash)) return hash; if ( uploadedHere(deps.storage, hash) && - (await deps.storage.exists(objectKey(hash))) + (await isStored(deps.storage, hash, bytes.length)) ) { return hash; } - await deps.storage.put(objectKey(hash), await encryptBytes(deps.key, bytes)); - rememberUpload(deps.storage, hash); + if (await storeContent(deps, hash, bytes, previous)) { + rememberUpload(deps.storage, hash); + } return hash; } @@ -221,7 +232,12 @@ export async function pushSingleFile( ): Promise { if (!deps.scope.includes(path)) throw new Error("File is outside this device's sync scope."); - const hash = await storeObject(deps, knownRemoteHashes(compareResult), bytes); + const hash = await storeObject( + deps, + knownRemoteHashes(compareResult), + bytes, + entryAt(compareResult.remote?.files ?? {}, path), + ); const kind: EFileKind = deps.scope.classify(path); const entry: ManifestEntry = { hash, @@ -271,6 +287,7 @@ export async function publishFileMap( compareResult.remote, deps.history, deps.state.baseline, + untrackedDir(deps), ); forgetUploads( deps.storage, @@ -321,8 +338,12 @@ async function listStoredHashes( ): Promise | null> { if (probes < UPLOAD_LIST_THRESHOLD) return null; try { - const keys = await storage.list(REMOTE_OBJECTS_PREFIX); - return new Set(keys.map((key) => key.slice(REMOTE_OBJECTS_PREFIX.length))); + const listed = await Promise.all( + [REMOTE_OBJECTS_PREFIX, REMOTE_RECIPES_PREFIX].map((prefix) => + storage.list(prefix), + ), + ); + return new Set(listed.flat().map(rootHash)); } catch { // Listing is only an optimisation; the per-object probe still gives a correct push. return null; @@ -331,18 +352,19 @@ async function listStoredHashes( async function uploadObject( deps: EngineDependencies, - entry: { path: string; hash: string }, + entry: { path: string; hash: string; size: number }, probe: boolean, + previous: ManifestEntry | undefined, ): Promise { - if (probe && (await deps.storage.exists(objectKey(entry.hash)))) return; + if (probe && (await isStored(deps.storage, entry.hash, entry.size))) return; const plaintext = await readBinary(deps.adapter, entry.path); const verifyHash = await sha256Hex(plaintext); if (verifyHash !== entry.hash) { throw new Error(`Hash mismatch while uploading ${entry.path}`); } - const blob = await encryptBytes(deps.key, plaintext); - await deps.storage.put(objectKey(entry.hash), blob); - rememberUpload(deps.storage, entry.hash); + if (await storeContent(deps, entry.hash, plaintext, previous)) { + rememberUpload(deps.storage, entry.hash); + } } function collectUploads( @@ -373,8 +395,6 @@ function assertVaultCompatibility( ): void { if (!remote) return; if (state.vaultId && state.vaultId !== remote.vaultId) { - throw new Error( - "Remote vault id does not match local. Refusing to sync to a different vault.", - ); + throw new Error(VAULT_MISMATCH_MESSAGE); } } diff --git a/packages/plugin/src/features/sync/history/activity-cache.ts b/packages/plugin/src/features/sync/history/activity-cache.ts new file mode 100644 index 00000000..605160ae --- /dev/null +++ b/packages/plugin/src/features/sync/history/activity-cache.ts @@ -0,0 +1,52 @@ +import type { LocalStore } from "../types"; +import type { Activity } from "./model/types"; + +export interface CachedActivity { + activity: Activity; + /** When the read it came from began. */ + at: number; +} + +interface Entry extends CachedActivity { + /** Null once forgotten. */ + storage: string | null; +} + +/** The vault's activity as last read from history, so the settings overview draws it without the network. */ +export class ActivityCache { + constructor(private readonly store: LocalStore) {} + + /** Null for another storage target: it holds another vault. */ + recall(storage: string): CachedActivity | null { + const entry = this.store.load(); + if (!isEntry(entry) || entry.storage !== storage) return null; + return { activity: entry.activity, at: entry.at }; + } + + /** A read begun before the kept one or a `forget` is stale: it may predate a push or a reset. */ + remember(storage: string, activity: Activity, since: number): void { + const kept = this.store.load(); + if (isEntry(kept) && kept.at > since) return; + this.store.save({ storage, activity, at: since } satisfies Entry); + } + + /** After the remote's history went: a reset or another vault adopted at the same target. */ + forget(): void { + this.store.save({ + storage: null, + activity: {}, + at: Date.now(), + } satisfies Entry); + } +} + +function isEntry(value: unknown): value is Entry { + if (typeof value !== "object" || value === null) return false; + const { storage, at, activity } = value as Partial; + return ( + (typeof storage === "string" || storage === null) && + typeof at === "number" && + typeof activity === "object" && + activity !== null + ); +} diff --git a/packages/plugin/src/features/sync/history/changes.ts b/packages/plugin/src/features/sync/history/changes.ts new file mode 100644 index 00000000..38d72d95 --- /dev/null +++ b/packages/plugin/src/features/sync/history/changes.ts @@ -0,0 +1,175 @@ +import { entryAt } from "../changes/records"; +import type { Manifest, ManifestEntry } from "../types"; + +import type { SnapshotChanges } from "./types"; + +function sameEntry(a: ManifestEntry, b: ManifestEntry): boolean { + return ( + a.hash === b.hash && + a.size === b.size && + a.mtime === b.mtime && + a.kind === b.kind + ); +} + +/** Every differing field counts, not just the hash, so replaying backwards reproduces the parent exactly. */ +export function diffManifests( + parent: Manifest | null, + next: Manifest, +): SnapshotChanges { + const changes: SnapshotChanges = { added: {}, modified: {}, deleted: {} }; + const parentFiles = parent?.files ?? {}; + for (const [path, entry] of Object.entries(next.files)) { + const before = entryAt(parentFiles, path); + if (!before) { + changes.added[path] = entry; + } else if (!sameEntry(before, entry)) { + changes.modified[path] = { from: before, to: entry }; + } + } + for (const [path, entry] of Object.entries(parentFiles)) { + if (!entryAt(next.files, path)) changes.deleted[path] = entry; + } + return changes; +} + +/** History keeps vault files; the vault's configuration folder only syncs. A share's scope still names it. */ +export function untrackedDir(session: { + space: { root: string }; + scope: { configDir?: string }; +}): string | undefined { + return session.space.root === "" ? session.scope.configDir : undefined; +} + +/** No `configDir`: every path. Any casing, as a case-blind disk takes `Config/` for `config/`. */ +export function historyTracks( + configDir: string | undefined, +): (path: string) => boolean { + const prefix = configDir === undefined ? null : `${configDir}/`.toLowerCase(); + return (path) => prefix === null || !path.toLowerCase().startsWith(prefix); +} + +/** The record's side, and every hash the untracked side names: GC frees them when it retires the record. */ +export function splitTracked( + changes: SnapshotChanges, + tracks: (path: string) => boolean, +): { changes: SnapshotChanges; released: string[] } { + const side = (kept: boolean): SnapshotChanges => { + const keep = (path: string) => tracks(path) === kept; + return { + added: pickPaths(changes.added, keep), + modified: pickPaths(changes.modified, keep), + deleted: pickPaths(changes.deleted, keep), + }; + }; + const released = changeEntries(side(false)).map(({ hash }) => hash); + return { changes: side(true), released: [...new Set(released)] }; +} + +export function pickPaths( + map: Record, + keep: (path: string) => boolean, +): Record { + return Object.fromEntries(Object.entries(map).filter(([path]) => keep(path))); +} + +/** Undoes one snapshot's changes in place, mutating the given file map into its parent's. */ +export function undoChanges( + files: Record, + changes: SnapshotChanges, +): void { + for (const path of Object.keys(changes.added)) delete files[path]; + for (const [path, change] of Object.entries(changes.modified)) { + files[path] = change.from; + } + for (const [path, entry] of Object.entries(changes.deleted)) { + files[path] = entry; + } +} + +/** Undoes one snapshot for a single path. `null` means the path did not exist. */ +export function undoChangesForPath( + entry: ManifestEntry | null, + changes: SnapshotChanges, + path: string, +): ManifestEntry | null { + if (entryAt(changes.added, path)) return null; + const modified = entryAt(changes.modified, path); + if (modified) return modified.from; + return entryAt(changes.deleted, path) ?? entry; +} + +/** Every version a record names, so all it can restore stays reachable. */ +export function changeEntries(changes: SnapshotChanges): ManifestEntry[] { + return [ + ...Object.values(changes.added), + ...Object.values(changes.modified).flatMap(({ from, to }) => [from, to]), + ...Object.values(changes.deleted), + ...Object.values(changes.deletedLast ?? {}), + ]; +} + +/** + * One record for a contiguous run, oldest first: the first parent's state to the last record's. A path back + * where it started drops out, and a file added and deleted inside the run leaves no trace. + */ +export function composeChanges( + run: readonly SnapshotChanges[], +): SnapshotChanges { + const merged: SnapshotChanges = { added: {}, modified: {}, deleted: {} }; + const deletedLast: Record = {}; + for (const changes of run) { + for (const path of touchedPaths(changes)) { + const start = touches(merged, path) + ? startOf(merged, path) + : startOf(changes, path); + delete merged.added[path]; + delete merged.modified[path]; + delete merged.deleted[path]; + delete deletedLast[path]; + const end = endOf(changes, path); + if (end) { + if (!start) merged.added[path] = end; + else if (!sameEntry(start, end)) { + merged.modified[path] = { from: start, to: end }; + } + } else if (start) { + merged.deleted[path] = start; + const last = + entryAt(changes.deletedLast ?? {}, path) ?? + entryAt(changes.deleted, path); + if (last && !sameEntry(last, start)) deletedLast[path] = last; + } + } + } + if (Object.keys(deletedLast).length > 0) merged.deletedLast = deletedLast; + return merged; +} + +function touchedPaths(changes: SnapshotChanges): string[] { + return [ + ...Object.keys(changes.added), + ...Object.keys(changes.modified), + ...Object.keys(changes.deleted), + ]; +} + +function touches(changes: SnapshotChanges, path: string): boolean { + return ( + entryAt(changes.added, path) !== undefined || + entryAt(changes.modified, path) !== undefined || + entryAt(changes.deleted, path) !== undefined + ); +} + +/** A touched path before the record; null when it did not exist. */ +function startOf(changes: SnapshotChanges, path: string): ManifestEntry | null { + return undoChangesForPath(null, changes, path); +} + +/** A touched path after the record; null when it is gone. */ +function endOf(changes: SnapshotChanges, path: string): ManifestEntry | null { + return ( + entryAt(changes.added, path) ?? entryAt(changes.modified, path)?.to ?? null + ); +} diff --git a/packages/plugin/src/features/sync/history/gc.ts b/packages/plugin/src/features/sync/history/gc.ts new file mode 100644 index 00000000..8c6b992d --- /dev/null +++ b/packages/plugin/src/features/sync/history/gc.ts @@ -0,0 +1,131 @@ +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import type { EncryptionKey } from "@/core/crypto"; +import { runWithConcurrency } from "@/core/utils"; +import type { ListedObject, ObjectStorage } from "@/features/storage"; +import { fetchRemoteManifest } from "../remote/manifest"; +import { SETTLED_AFTER_MS } from "../remote/uploads"; +import type { Manifest } from "../types"; +import { activityOf } from "./model/activity"; +import { coverOf, type HistoryView } from "./model/cover"; +import { freedHashes, planGc } from "./model/plan"; +import type { Activity } from "./model/types"; +import { + type HistoryRead, + readHistory, + writeCandidates, + writeHistoryObject, +} from "./remote"; +import { sweepObjects } from "./sweep"; +import type { HistoryConfig, SnapshotChanges } from "./types"; + +export interface GcResult { + /** History objects written. */ + written: number; + /** Push records and objects deleted. */ + retired: number; + /** File blobs deleted. */ + swept: number; + /** Pushes per hour as this run read them; null without a HEAD. */ + activity: Activity | null; +} + +/** + * Phase 1 thins history now; phase 2 sweeps what an earlier run freed, once that is a day old. Needs object + * ages: without them nothing ever looks old enough to pack or sweep. + */ +export async function collectHistoryGarbage( + storage: ObjectStorage, + key: EncryptionKey, + root: string, + history: HistoryConfig, +): Promise { + const head = storage.listDetailed + ? await fetchRemoteManifest(storage, key, root) + : null; + if (!head) return { written: 0, retired: 0, swept: 0, activity: null }; + const read = await readHistory(storage, key, root); + const thinned = await thinHistory(storage, key, root, history, head, read); + const swept = read.candidates.some(sweepDue) + ? await sweepObjects(storage, key, root, { freedOnly: true }) + : 0; + return { ...thinned, swept }; +} + +/** + * A day past settling: the sweep then takes every settled file at once, so its full listing of `objects/` + * runs about once a day, not after every run. + */ +function sweepDue({ modified }: ListedObject): boolean { + return modified !== null && modified < Date.now() - 2 * SETTLED_AFTER_MS; +} + +/** Writes and verifies the planned objects, records what they freed, then retires what they replace. */ +async function thinHistory( + storage: ObjectStorage, + key: EncryptionKey, + root: string, + history: HistoryConfig, + head: Manifest, + { view, unreadable, now }: HistoryRead, +): Promise> { + // A gap only this run sees would let a counts group or the horizon take what lies behind it. + if (unreadable.length > 0) { + throw new Error( + `File history cleanup stopped: ${unreadable.length} history object(s) could not be read.`, + ); + } + const cover = coverOf(view, { + id: head.snapshotId, + parentId: head.parentSnapshotId, + vaultId: head.vaultId, + }); + const plan = planGc({ + view, + cover, + vaultId: head.vaultId, + now, + horizon: history.horizon, + settledBefore: now - SETTLED_AFTER_MS, + }); + const retire = new Set(plan.deletes); + const written = new Set(); + const kept: { changes: SnapshotChanges }[] = []; + // Every build is written and read back before the first delete: the run rejects only once its workers settle. + await runWithConcurrency(plan.builds, DEFAULT_CONCURRENCY, async (build) => { + const stored = await writeHistoryObject(storage, key, root, build); + written.add(stored.key); + kept.push(...stored.object.records); + for (const named of stored.object.consumed) retire.add(named); + }); + // Only what this run listed: a key named but gone was retired by an earlier run. + const gone = [...retire].filter( + (storageKey) => + !written.has(storageKey) && + (view.pushes.has(storageKey) || view.objects.has(storageKey)), + ); + const freed = freedHashes(changesOf(view, gone), kept); + // Recorded first: a crash after it leaves candidates still named, which the sweep keeps. + if (freed.size > 0) await writeCandidates(storage, key, [...freed]); + await runWithConcurrency(gone, DEFAULT_CONCURRENCY, (storageKey) => + storage.delete(storageKey), + ); + return { + written: written.size, + retired: gone.length, + activity: activityOf(view, cover, head.vaultId), + }; +} + +function changesOf( + view: HistoryView, + keys: readonly string[], +): { changes: SnapshotChanges; released?: string[] }[] { + return keys.flatMap( + (storageKey): { changes: SnapshotChanges; released?: string[] }[] => { + const push = view.pushes.get(storageKey)?.push; + return push + ? [push] + : (view.objects.get(storageKey)?.object.records ?? []); + }, + ); +} diff --git a/packages/plugin/src/features/sync/history/legacy.ts b/packages/plugin/src/features/sync/history/legacy.ts new file mode 100644 index 00000000..6e4f0dee --- /dev/null +++ b/packages/plugin/src/features/sync/history/legacy.ts @@ -0,0 +1,43 @@ +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { decryptJson, type EncryptionKey } from "@/core/crypto"; +import { runWithConcurrency } from "@/core/utils"; +import type { ObjectStorage } from "@/features/storage"; +import { REMOTE_HISTORY_LOG_KEY, REMOTE_PINS_PREFIX } from "../constants"; + +/** + * Deletes 1.x history, which nothing reads past the v3 fence: its pins, then the `history.json.enc` log. Pins + * are scanned even without the log: an interrupted reset can leave them, and one blocks every sweep. + */ +export async function clearLegacyHistory( + storage: ObjectStorage, + key: EncryptionKey, +): Promise { + let removed = 0; + await runWithConcurrency( + await storage.list(REMOTE_PINS_PREFIX), + DEFAULT_CONCURRENCY, + async (pin) => { + if (!(await isLegacyPin(storage, key, pin))) return; + await storage.delete(pin); + removed++; + }, + ); + if (await storage.exists(REMOTE_HISTORY_LOG_KEY)) { + await storage.delete(REMOTE_HISTORY_LOG_KEY); + removed++; + } + return removed; +} + +/** A 1.x pin is a bare manifest, a current one wraps it; one that does not decrypt is unknown and stays. */ +async function isLegacyPin( + storage: ObjectStorage, + key: EncryptionKey, + pin: string, +): Promise { + const blob = await storage.get(pin); + const raw = + blob && + (await decryptJson<{ snapshotId?: unknown }>(key, blob).catch(() => null)); + return typeof raw?.snapshotId === "string"; +} diff --git a/packages/plugin/src/features/sync/history/model/activity.ts b/packages/plugin/src/features/sync/history/model/activity.ts new file mode 100644 index 00000000..cbe03066 --- /dev/null +++ b/packages/plugin/src/features/sync/history/model/activity.ts @@ -0,0 +1,42 @@ +import type { Cover, HistoryView } from "./cover"; +import type { Activity } from "./types"; + +const sum = (a: number, b: number): number => a + b; + +export function mergeActivity( + into: Activity, + add: Activity, + combine = sum, +): void { + for (const [hour, [pushes, paths]] of Object.entries(add)) { + const was = into[Number(hour)]; + into[Number(hour)] = was + ? [combine(was[0], pushes), combine(was[1], paths)] + : [pushes, paths]; + } +} + +/** The walk's records plus what counts objects outlived. */ +export function activityOf( + view: HistoryView, + cover: Cover, + vaultId: string, +): Activity { + const activity: Activity = {}; + for (const { record } of cover.chain) { + mergeActivity(activity, record.activity); + } + for (const [key, { object }] of view.objects) { + if (object.res !== "counts" || object.vaultId !== vaultId) continue; + if (!cover.consumed.has(key)) mergeCounts(activity, object.activity ?? {}); + } + return activity; +} + +/** + * Counts hold hours past the horizon: another counts of them, or a record walked there until GC folds it in, + * is another view of the same pushes. Per hour the larger stands, never the sum. + */ +export function mergeCounts(into: Activity, other: Activity): void { + mergeActivity(into, other, Math.max); +} diff --git a/packages/plugin/src/features/sync/history/model/cover.ts b/packages/plugin/src/features/sync/history/model/cover.ts new file mode 100644 index 00000000..87f1d539 --- /dev/null +++ b/packages/plugin/src/features/sync/history/model/cover.ts @@ -0,0 +1,260 @@ +import { RESOLUTIONS } from "./periods"; +import { runsOf, storedRecord } from "./records"; +import type { + HistoryObject, + PushRecord, + Resolution, + StoredRecord, +} from "./types"; + +/** What storage holds, decoded; `at` is the listing's write time. */ +export interface HistoryView { + pushes: ReadonlyMap; + objects: ReadonlyMap; +} + +export interface WalkedRecord { + record: StoredRecord; + /** The key it was read from. */ + source: string; + /** What its key holds: every push, or the period GC packed it to. */ + res: Resolution; +} + +export interface Cover { + /** Newest first, contiguous from HEAD, or from its parent when `lagging`. */ + chain: WalkedRecord[]; + /** HEAD's own record is not there yet. */ + lagging: boolean; + /** The walk stopped at a missing record, not at the first push. */ + truncated: boolean; + /** Keys a present object replaces: readers skip them, GC deletes them. */ + consumed: ReadonlySet; +} + +export interface Head { + id: string; + parentId: string | null; + vaultId: string; +} + +/** The first `length` records of a chain-contiguous run of one key. */ +interface Segment { + key: string; + res: Resolution; + /** Index in {@link RESOLUTIONS}. */ + rank: number; + /** Oldest first. */ + run: readonly StoredRecord[]; + length: number; + parentId: string | null; + pushes: number; +} + +interface Best { + segment: Segment | null; + root: boolean; + pushes: number; +} + +const DEAD_END: Best = { segment: null, root: false, pushes: 0 }; + +/** + * Walks back from HEAD through whichever objects reach furthest; among equals the coarser, then the one + * with more records, then the smaller key. Pushes merge without loss of count, so equal reach means equal coverage. + */ +export function coverOf(view: HistoryView, head: Head | null): Cover { + const consumed = consumedKeys(view); + if (!head) return { chain: [], lagging: false, truncated: false, consumed }; + const byLast = new Map(); + for (const segment of segmentsOf(view, head.vaultId, consumed)) { + const lastId = segment.run[segment.length - 1]?.id; + if (lastId === undefined) continue; + byLast.set(lastId, [...(byLast.get(lastId) ?? []), segment]); + } + const retired = retiredIds(view, head.vaultId, consumed); + const lagging = !byLast.has(head.id); + const start = lagging ? head.parentId : head.id; + const chain: WalkedRecord[] = []; + let at = start; + const memo = solve(start, byLast, retired); + const seen = new Set(); + while (at !== null && !seen.has(at)) { + seen.add(at); + const segment = memo.get(at)?.segment; + if (!segment) break; + for (const record of segment.run.slice(0, segment.length).reverse()) { + chain.push({ record, source: segment.key, res: segment.res }); + } + at = segment.parentId; + } + return { + chain: forwardTimes(chain, view), + lagging, + truncated: at !== null && !retired.has(at), + consumed, + }; +} + +/** Where retention ended the chain: the newest record each counts object dropped. */ +function retiredIds( + view: HistoryView, + vaultId: string, + consumed: ReadonlySet, +): Set { + const ids = new Set(); + for (const [key, { object }] of view.objects) { + if (consumed.has(key) || object.vaultId !== vaultId) continue; + if (object.lastId !== undefined) ids.add(object.lastId); + } + return ids; +} + +/** + * Only a later write replaces an earlier one, so two objects naming each other (a rewrite after a failed + * delete) cannot both go. + */ +function consumedKeys(view: HistoryView): Set { + const writtenAt = new Map(); + for (const [key, { at }] of view.pushes) writtenAt.set(key, at); + for (const [key, { at }] of view.objects) writtenAt.set(key, at); + const consumed = new Set(); + for (const [key, { object, at }] of view.objects) { + for (const named of object.consumed) { + const namedAt = writtenAt.get(named); + if (namedAt === undefined || named === key) continue; + if (namedAt < at || (namedAt === at && named < key)) consumed.add(named); + } + } + return consumed; +} + +function segmentsOf( + view: HistoryView, + vaultId: string, + consumed: ReadonlySet, +): Segment[] { + const segments: Segment[] = []; + // Every record ends a segment: a sibling may fork from inside a packed run. + const add = (key: string, res: Resolution, run: StoredRecord[]): void => { + const parentId = run[0]?.parentId ?? null; + const rank = RESOLUTIONS.indexOf(res); + let pushes = 0; + for (const [index, record] of run.entries()) { + pushes += record.pushes; + segments.push({ + key, + res, + rank, + run, + length: index + 1, + parentId, + pushes, + }); + } + }; + for (const [key, { push, at }] of view.pushes) { + if (consumed.has(key) || push.vaultId !== vaultId) continue; + add(key, "push", [storedRecord(push, at)]); + } + for (const [key, { object }] of view.objects) { + if (consumed.has(key) || object.vaultId !== vaultId) continue; + // Objects stored by an older walk need not be one run; split rather than trust them. + for (const run of runsOf(object.records)) { + add(key, object.res, run); + } + } + return segments; +} + +/** + * Storage clocks straggle: a time never runs back along the chain, so every period is one run of it. A push + * moved forward is dated anew, its activity with it. + */ +function forwardTimes( + chain: readonly WalkedRecord[], + view: HistoryView, +): WalkedRecord[] { + let floor = Number.NEGATIVE_INFINITY; + const forward = [...chain].reverse().map((walked) => { + if (walked.record.at >= floor) { + floor = walked.record.at; + return walked; + } + const push = view.pushes.get(walked.source)?.push; + const record = push + ? storedRecord(push, floor) + : { ...walked.record, at: floor }; + return { ...walked, record }; + }); + return forward.reverse(); +} + +/** Best choice per id reachable from `start`, iteratively: a long unpacked chain must not overflow the stack. */ +function solve( + start: string | null, + byLast: ReadonlyMap, + retired: ReadonlySet, +): Map { + const memo = new Map(); + if (start === null) return memo; + const stack = [start]; + const open = new Set(); + while (stack.length > 0) { + const id = stack.at(-1) as string; + if (memo.has(id)) { + stack.pop(); + continue; + } + const candidates = byLast.get(id) ?? []; + if (!open.has(id)) { + open.add(id); + for (const { parentId } of candidates) { + if (parentId !== null && !memo.has(parentId) && !open.has(parentId)) { + stack.push(parentId); + } + } + continue; + } + stack.pop(); + open.delete(id); + // A parent still open is a cycle in corrupt data: a dead end. + memo.set(id, pick(candidates, memo, retired)); + } + return memo; +} + +function pick( + candidates: readonly Segment[], + memo: Map, + retired: ReadonlySet, +): Best { + let best = DEAD_END; + for (const segment of candidates) { + const parent = segment.parentId; + const below = parent === null ? undefined : memo.get(parent); + const tail = + parent === null || (!below?.segment && retired.has(parent)) + ? { root: true, pushes: 0 } + : (below ?? DEAD_END); + const option: Best = { + segment, + root: tail.root, + pushes: segment.pushes + tail.pushes, + }; + if (better(option, best)) best = option; + } + return best; +} + +function better(a: Best, b: Best): boolean { + if (!b.segment) return true; + if (!a.segment) return false; + if (a.root !== b.root) return a.root; + if (a.pushes !== b.pushes) return a.pushes > b.pushes; + if (a.segment.rank !== b.segment.rank) return a.segment.rank > b.segment.rank; + if (a.segment.length !== b.segment.length) { + return a.segment.length > b.segment.length; + } + return a.segment.key < b.segment.key; +} diff --git a/packages/plugin/src/features/sync/history/model/periods.ts b/packages/plugin/src/features/sync/history/model/periods.ts new file mode 100644 index 00000000..4e5426b8 --- /dev/null +++ b/packages/plugin/src/features/sync/history/model/periods.ts @@ -0,0 +1,131 @@ +import type { Resolution } from "./types"; + +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; +const WEEK = 7 * DAY; +/** 1970-01-05 was a Monday, where ISO weeks start. */ +const MONDAY = 4 * DAY; + +interface Span { + size: number; + offset: number; +} + +interface Rung { + /** One merged record per span; null keeps every record. */ + keep: Span | null; + /** What one object holds. */ + group: Span; + /** How long past its end a group waits before it is built. */ + settle: number | "horizon"; +} + +const every = (size: number): Span => ({ size, offset: 0 }); +const weeks = (count: number): Span => ({ size: count * WEEK, offset: MONDAY }); + +/** Groups nest (slot < hour < day < week < 4 weeks), so an object is built from finer ones inside it. */ +const RUNGS: Record = { + push: { keep: null, group: every(10 * MINUTE), settle: 10 * MINUTE }, + "10m": { keep: every(10 * MINUTE), group: every(HOUR), settle: HOUR }, + "1h": { keep: every(HOUR), group: every(DAY), settle: DAY }, + "1d": { keep: every(DAY), group: weeks(1), settle: WEEK }, + "1w": { keep: weeks(1), group: weeks(4), settle: 30 * DAY }, + counts: { keep: null, group: weeks(4), settle: "horizon" }, +}; + +export const RESOLUTIONS: readonly Resolution[] = [ + "push", + "10m", + "1h", + "1d", + "1w", + "counts", +]; + +function floorTo(at: number, span: Span): number { + return Math.floor((at - span.offset) / span.size) * span.size + span.offset; +} + +export function hourOf(at: number): number { + return Math.floor(at / HOUR); +} + +export function groupStart(res: Resolution, at: number): number { + return floorTo(at, RUNGS[res].group); +} + +export function groupEnd(res: Resolution, start: number): number { + return start + RUNGS[res].group.size; +} + +/** The span `at` merges into at this resolution; null when every record stays its own. */ +export function keepStart(res: Resolution, at: number): number | null { + const keep = RUNGS[res].keep; + return keep ? floorTo(at, keep) : null; +} + +/** How much time one kept version stands for; null while every push stays. */ +export function keepSize(res: Resolution): number | null { + return RUNGS[res].keep?.size ?? null; +} + +/** `horizon` in ms, null to keep forever. */ +export function isDue( + res: Resolution, + start: number, + now: number, + horizon: number | null, +): boolean { + const settle = RUNGS[res].settle; + if (settle === "horizon" && horizon === null) return false; + const wait = settle === "horizon" ? (horizon ?? 0) : settle; + return groupEnd(res, start) + wait <= now; +} + +/** When a record dated `at` may go to counts: retention keeps its versions at least until then. */ +export function keptUntil(at: number, horizon: number | null): number | null { + return horizon === null + ? null + : groupEnd("counts", groupStart("counts", at)) + horizon; +} + +export interface Stage { + res: Resolution; + from: number; +} + +/** + * What a record thins through with age, each from the youngest age it may reach it at. A rung due no sooner + * than counts never shows: the coarsest due wins. + */ +export function stagesOf(horizon: number | null): Stage[] { + const counts = RUNGS.counts.group.size; + return RESOLUTIONS.flatMap((res): Stage[] => { + const { settle, group } = RUNGS[res]; + if (res === "push") return [{ res, from: 0 }]; + if (settle === "horizon") + return horizon === null ? [] : [{ res, from: horizon }]; + return horizon !== null && settle >= horizon + counts - group.size + ? [] + : [{ res, from: settle }]; + }); +} + +/** Records before this are past `keptUntil`: once GC runs, only counts and pins hold them. */ +export function countsBefore(now: number, horizon: number): number { + return groupStart("counts", now - horizon); +} + +/** The coarsest resolution whose group around `at` is due; null while it is too fresh to pack. */ +export function dueResolution( + at: number, + now: number, + horizon: number | null, +): Resolution | null { + for (let index = RESOLUTIONS.length - 1; index >= 0; index--) { + const res = RESOLUTIONS[index] as Resolution; + if (isDue(res, groupStart(res, at), now, horizon)) return res; + } + return null; +} diff --git a/packages/plugin/src/features/sync/history/model/plan.ts b/packages/plugin/src/features/sync/history/model/plan.ts new file mode 100644 index 00000000..4e0198ea --- /dev/null +++ b/packages/plugin/src/features/sync/history/model/plan.ts @@ -0,0 +1,276 @@ +import { changeEntries } from "../changes"; +import { mergeActivity, mergeCounts } from "./activity"; +import type { Cover, HistoryView, WalkedRecord } from "./cover"; +import { dueResolution, groupStart, RESOLUTIONS } from "./periods"; +import { thin } from "./records"; +import type { + Activity, + HistoryObject, + PushRecord, + Resolution, + StoredRecord, +} from "./types"; + +/** A group counts as complete only once the walk reaches this far before it: storage clocks straggle a little. */ +const COMPLETE_MARGIN_MS = 10 * 60_000; + +export interface PlanInput { + view: HistoryView; + cover: Cover; + vaultId: string; + /** Storage time: the newest write in the listing. */ + now: number; + /** ms, null to keep forever. */ + horizon: number | null; + /** Storage time before which nothing can belong to a push still in flight. */ + settledBefore: number; +} + +/** The store drops the key it writes a build under from `consumed`: an object never replaces itself. */ +export type Build = Omit; + +export interface GcPlan { + /** Each written, read back and checked before its `consumed` go. */ + builds: Build[]; + /** Safe to delete now: replaced by a present object, a lost push, another vault's. */ + deletes: string[]; +} + +interface Target { + res: Resolution; + group: number; + walked: WalkedRecord[]; +} + +interface GroupedObject { + key: string; + object: HistoryObject; +} + +export function planGc(input: PlanInput): GcPlan { + const { view, cover } = input; + const present = new Set([...view.pushes.keys(), ...view.objects.keys()]); + const deletes = new Set( + [...cover.consumed].filter((key) => present.has(key)), + ); + for (const key of lostPushes(input)) deletes.add(key); + for (const key of foreign(input)) deletes.add(key); + for (const key of expired(input)) deletes.add(key); + + const taken = countBySource(input.cover.chain); + const grouped = objectsByGroup(input); + const builds: Build[] = []; + for (const target of targets(input)) { + const build = buildOf(input, target, taken, grouped); + if (build) builds.push(build); + } + return { builds, deletes: [...deletes] }; +} + +function countBySource(walked: readonly WalkedRecord[]): Map { + const counts = new Map(); + for (const { source } of walked) { + counts.set(source, (counts.get(source) ?? 0) + 1); + } + return counts; +} + +/** Versions the replaced records named that the new object no longer does: phase 1's sweep candidates. */ +export function freedHashes( + replaced: readonly (Pick & + Pick)[], + kept: readonly Pick[], +): Set { + const keptHashes = new Set( + kept.flatMap((record) => changeEntries(record.changes).map((e) => e.hash)), + ); + const freed = new Set(); + for (const record of replaced) { + const named = changeEntries(record.changes).map(({ hash }) => hash); + for (const hash of [...named, ...(record.released ?? [])]) { + if (!keptHashes.has(hash)) freed.add(hash); + } + } + return freed; +} + +function targets(input: PlanInput): Target[] { + const byGroup = new Map(); + // Oldest first, so each group's records come in chain order. + for (const walked of [...input.cover.chain].reverse()) { + const due = dueResolution(walked.record.at, input.now, input.horizon); + if (!due) continue; + // Never finer than the object it sits in: that object's records would spill out of the group. + const packed = input.view.objects.get(walked.source)?.object.res; + const res = + packed && RESOLUTIONS.indexOf(packed) > RESOLUTIONS.indexOf(due) + ? packed + : due; + const group = groupStart(res, walked.record.at); + const id = `${res} ${group}`; + const target = byGroup.get(id) ?? { res, group, walked: [] }; + target.walked.push(walked); + byGroup.set(id, target); + } + const reach = oldestReached(input.cover); + // Counts keep no versions, so a group past the horizon goes whole or not. + return [...byGroup.values()].filter( + (target) => + target.res === "counts" || target.group - COMPLETE_MARGIN_MS > reach, + ); +} + +/** Storage time the walk reaches back to; anything newer is fully on it. */ +function oldestReached(cover: Cover): number { + if (!cover.truncated) return Number.NEGATIVE_INFINITY; + const oldest = cover.chain.at(-1)?.record; + return oldest ? oldest.firstAt : Number.POSITIVE_INFINITY; +} + +/** Live objects of this vault by the group they fall in at each resolution at or coarser than their own. */ +function objectsByGroup(input: PlanInput): Map { + const grouped = new Map(); + for (const [key, { object }] of input.view.objects) { + if (input.cover.consumed.has(key) || object.vaultId !== input.vaultId) { + continue; + } + for (const res of RESOLUTIONS.slice(RESOLUTIONS.indexOf(object.res))) { + const id = `${res} ${groupStart(res, object.group)}`; + const bucket = grouped.get(id) ?? []; + bucket.push({ key, object }); + grouped.set(id, bucket); + } + } + return grouped; +} + +function buildOf( + input: PlanInput, + target: Target, + taken: ReadonlyMap, + grouped: ReadonlyMap, +): Build | null { + const { res, group } = target; + const own = countBySource(target.walked); + const walked = new Set(own.keys()); + const inputs = new Set(walked); + const sameGroup: HistoryObject[] = []; + for (const { key, object } of grouped.get(`${res} ${group}`) ?? []) { + inputs.add(key); + if (object.res === res) sameGroup.push(object); + } + // An input goes only with every walked record of it: a late parent re-dates records into other groups. + // Within the horizon it must be whole too, as an off-walk part may hold a sibling or lie behind a gap. + const replaced = [...inputs].filter( + (key) => + (own.get(key) ?? 0) === + (res === "counts" + ? (taken.get(key) ?? 0) + : (input.view.objects.get(key)?.object.records.length ?? 1)), + ); + const [only] = walked; + const built = + walked.size === 1 && + only !== undefined && + input.view.objects.get(only)?.object.res === res; + if (built && replaced.every((key) => key === only)) return null; + // Counts retire sources: one replacing only earlier counts is rebuilt every run; the walk counts what stays. + if ( + res === "counts" && + replaced.every( + (key) => input.view.objects.get(key)?.object.res === "counts", + ) + ) { + return null; + } + + const records = target.walked.map((walked) => walked.record); + const consumed = new Set(replaced); + for (const key of replaced) { + for (const named of input.view.objects.get(key)?.object.consumed ?? []) { + if (input.view.pushes.has(named) || input.view.objects.has(named)) { + consumed.add(named); + } + } + } + const build: Build = { + vaultId: input.vaultId, + res, + group, + records: res === "counts" ? [] : thin(records, res), + consumed: [...consumed].sort(), + }; + if (res === "counts") { + build.activity = countsOf(records, sameGroup); + const newest = target.walked.at(-1)?.record.id; + if (newest !== undefined) build.lastId = newest; + } + return build; +} + +function countsOf( + records: readonly StoredRecord[], + earlier: readonly HistoryObject[], +): Activity { + const activity: Activity = {}; + for (const record of records) mergeActivity(activity, record.activity); + for (const object of earlier) mergeCounts(activity, object.activity ?? {}); + return activity; +} + +/** + * A push whose parent's next record on the chain is another push lost the publication guard and can never + * join; a parent merged out of sight proves nothing, so that push stays. + */ +function lostPushes(input: PlanInput): string[] { + const childOf = new Map(); + const onChain = new Set(); + for (const { record } of input.cover.chain) { + onChain.add(record.id); + if (record.parentId !== null) childOf.set(record.parentId, record.id); + } + const lost: string[] = []; + for (const [key, { push, at }] of input.view.pushes) { + if (input.cover.consumed.has(key) || onChain.has(push.id)) continue; + if (push.vaultId !== input.vaultId || at >= input.settledBefore) continue; + if (push.parentId === null || !onChain.has(push.parentId)) continue; + const child = childOf.get(push.parentId); + if (child !== undefined && child !== push.id) lost.push(key); + } + return lost; +} + +/** Off the walk, behind a gap, past the horizon and settled: retention lets them go, never counted. */ +function expired(input: PlanInput): string[] { + const walked = new Set(input.cover.chain.map(({ source }) => source)); + const gone = (key: string, at: number, newest: number): boolean => + !walked.has(key) && + at < input.settledBefore && + dueResolution(newest, input.now, input.horizon) === "counts"; + const keys: string[] = []; + for (const [key, { push, at }] of input.view.pushes) { + if (push.vaultId === input.vaultId && gone(key, at, at)) keys.push(key); + } + for (const [key, { object, at }] of input.view.objects) { + if (object.vaultId !== input.vaultId || object.records.length === 0) { + continue; + } + const newest = Math.max(...object.records.map((record) => record.at)); + if (gone(key, at, newest)) keys.push(key); + } + return keys; +} + +/** Left by a reset: another vault id. */ +function foreign(input: PlanInput): string[] { + const keys: string[] = []; + for (const [key, { push, at }] of input.view.pushes) { + if (push.vaultId !== input.vaultId && at < input.settledBefore) + keys.push(key); + } + for (const [key, { object, at }] of input.view.objects) { + if (object.vaultId !== input.vaultId && at < input.settledBefore) + keys.push(key); + } + return keys; +} diff --git a/packages/plugin/src/features/sync/history/model/records.ts b/packages/plugin/src/features/sync/history/model/records.ts new file mode 100644 index 00000000..d5f1a15c --- /dev/null +++ b/packages/plugin/src/features/sync/history/model/records.ts @@ -0,0 +1,84 @@ +import { composeChanges } from "../changes"; +import type { SnapshotChanges } from "../types"; +import { mergeActivity } from "./activity"; +import { hourOf, keepStart } from "./periods"; +import type { Activity, PushRecord, Resolution, StoredRecord } from "./types"; + +/** A push as stored once storage has dated it. */ +export function storedRecord(push: PushRecord, at: number): StoredRecord { + const paths = pathsChanged(push.changes); + return { + id: push.id, + parentId: push.parentId, + createdAt: push.createdAt, + deviceId: push.deviceId, + deviceName: push.deviceName, + changes: push.changes, + at, + firstAt: at, + pushes: 1, + // A push of only the configuration folder is no activity in the vault. + activity: paths === 0 && push.released ? {} : { [hourOf(at)]: [1, paths] }, + }; +} + +/** Splits records, in order, wherever `joins` fails; by default at every break in the chain. */ +export function runsOf( + records: readonly StoredRecord[], + joins = (previous: StoredRecord, record: StoredRecord): boolean => + record.parentId === previous.id, +): StoredRecord[][] { + const runs: StoredRecord[][] = []; + for (const record of records) { + const run = runs.at(-1); + const previous = run?.at(-1); + if (run && previous && joins(previous, record)) run.push(record); + else runs.push([record]); + } + return runs; +} + +/** Chain order, oldest first, as `records` are: one record per span, over contiguous runs only. */ +export function thin( + records: readonly StoredRecord[], + res: Resolution, +): StoredRecord[] { + return runsOf(records, (previous, record) => { + const span = keepStart(res, record.at); + return ( + span !== null && + span === keepStart(res, previous.at) && + record.parentId === previous.id + ); + }).map(mergeRecords); +} + +/** `run` is contiguous, oldest first. */ +export function mergeRecords(run: readonly StoredRecord[]): StoredRecord { + const [first] = run; + const last = run.at(-1); + if (!first || !last) throw new Error("Cannot merge an empty run."); + if (run.length === 1) return first; + const activity: Activity = {}; + for (const record of run) mergeActivity(activity, record.activity); + return { + id: last.id, + parentId: first.parentId, + createdAt: last.createdAt, + deviceId: last.deviceId, + deviceName: last.deviceName, + changes: composeChanges(run.map((record) => record.changes)), + at: Math.max(...run.map((record) => record.at)), + firstAt: Math.min(...run.map((record) => record.firstAt)), + pushes: run.reduce((sum, record) => sum + record.pushes, 0), + activity, + }; +} + +function pathsChanged(changes: SnapshotChanges): number { + return ( + Object.keys(changes.added).length + + Object.keys(changes.modified).length + + Object.keys(changes.deleted).length + ); +} diff --git a/packages/plugin/src/features/sync/history/model/types.ts b/packages/plugin/src/features/sync/history/model/types.ts new file mode 100644 index 00000000..33f0411c --- /dev/null +++ b/packages/plugin/src/features/sync/history/model/types.ts @@ -0,0 +1,52 @@ +import type { SnapshotChanges } from "../types"; + +/** Finest first: each one's groups nest inside the next one's. */ +export type Resolution = "push" | "10m" | "1h" | "1d" | "1w" | "counts"; + +/** UTC hours since the epoch -> [pushes, paths changed]. */ +export type Activity = Record; + +/** What a pushing device writes, before storage has dated it. */ +export interface PushRecord { + v: 1; + vaultId: string; + id: string; + parentId: string | null; + createdAt: number; + deviceId: string; + deviceName?: string; + changes: SnapshotChanges; + /** Versions this push named outside history (the configuration folder): freed with the record, never shown. */ + released?: string[]; +} + +/** What GC writes: one resolution over one group. Immutable; a new content is a new object. */ +export interface HistoryObject { + v: 1; + vaultId: string; + res: Resolution; + group: number; + /** Chain order, oldest first; empty for counts. */ + records: StoredRecord[]; + /** Counts only: the activity of records it outlived. */ + activity?: Activity; + /** Counts only: the newest record it dropped, where the chain now ends by retention, not by a gap. */ + lastId?: string; + /** Keys this object replaces. */ + consumed: string[]; +} + +/** A push, or a merged run of pushes: the last one's id and device, the first one's parent. */ +export interface StoredRecord { + id: string; + parentId: string | null; + createdAt: number; + deviceId: string; + deviceName?: string; + changes: SnapshotChanges; + /** Storage time of the newest push in it: periods and retention go by it, never by a device clock. */ + at: number; + firstAt: number; + pushes: number; + activity: Activity; +} diff --git a/packages/plugin/src/features/sync/history/pins.ts b/packages/plugin/src/features/sync/history/pins.ts new file mode 100644 index 00000000..c9a8a3ea --- /dev/null +++ b/packages/plugin/src/features/sync/history/pins.ts @@ -0,0 +1,222 @@ +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { decryptJson, type EncryptionKey, encryptJson } from "@/core/crypto"; +import { reportWarning } from "@/core/shared"; +import { runWithConcurrency } from "@/core/utils"; +import { listEntries, type ObjectStorage } from "@/features/storage"; +import { REMOTE_PINS_PREFIX } from "../constants"; +import { trimOldest } from "../hunks/bounded-map"; +import { manifestToSpace, manifestToVault } from "../remote/space-paths"; +import type { Manifest } from "../types"; + +/** A pin is its own full manifest, so it outlives the records it was replayed from. */ +export interface Pin { + id: string; + manifest: Manifest; + label?: string; + pinnedAt: number; +} + +interface StoredPin { + v: 1; + manifest: Manifest; + label?: string; + pinnedAt: number; +} + +/** A pin without its manifest: what a row shows. */ +export interface PinInfo { + id: string; + label?: string; + createdAt: number; + deviceId: string; + deviceName?: string; +} + +export interface PinsRead { + /** Newest snapshot first, each as `pick` reduced it. */ + pins: { info: PinInfo; picked: T }[]; + /** Listed pins that could not be read: what they hold is unknown. */ + unreadable: string[]; +} + +/** Manifests are big, so the cache holds this many file entries at most (four 50k-file manifests), oldest read first out. */ +const PIN_CACHE_ENTRIES = 200_000; + +interface CachedPin { + etag: string; + pin: Pin; + /** Files in the manifest: what the cache is bounded by. */ + entries: number; +} + +// A relabel rewrites the object, and only its etag proves it unchanged: a timestamp may not move within its resolution. +// Infos are a few strings each, so every listed pin keeps one and a warm Timeline refresh downloads no manifest. +const pinCache = new WeakMap< + ObjectStorage, + { + key: EncryptionKey; + root: string; + pins: Map; + infos: Map; + } +>(); + +export function pinKey(snapshotId: string): string { + return `${REMOTE_PINS_PREFIX}${snapshotId}.json.enc`; +} + +export async function writePin( + storage: ObjectStorage, + key: EncryptionKey, + root: string, + pin: Pin, +): Promise { + const stored: StoredPin = { + v: 1, + manifest: manifestToSpace(pin.manifest, root), + label: pin.label, + pinnedAt: pin.pinnedAt, + }; + await storage.put( + pinKey(pin.id), + await encryptJson(key, stored), + "application/octet-stream", + ); +} + +export function deletePin( + storage: ObjectStorage, + snapshotId: string, +): Promise { + return storage.delete(pinKey(snapshotId)); +} + +/** Every listed pin, reduced by `pick` as it is read so no more than the cache's manifests are held at once. */ +export function readPins( + storage: ObjectStorage, + key: EncryptionKey, + root: string, + pick: (pin: Pin, info: PinInfo) => T, +): Promise> { + return scanPins(storage, key, root, pick); +} + +/** Every listed pin's info, newest first; a pin whose etag is unchanged costs no GET. */ +export async function readPinInfos( + storage: ObjectStorage, + key: EncryptionKey, + root: string, +): Promise<{ pins: PinInfo[]; unreadable: string[] }> { + const read = await scanPins( + storage, + key, + root, + () => null, + () => null, + ); + return { + pins: read.pins.map(({ info }) => info), + unreadable: read.unreadable, + }; +} + +/** `fromInfo` answers a pin whose cached info is current, so it is not read at all. */ +async function scanPins( + storage: ObjectStorage, + key: EncryptionKey, + root: string, + pick: (pin: Pin, info: PinInfo) => T, + fromInfo?: (info: PinInfo) => T, +): Promise> { + let cache = pinCache.get(storage); + if (cache?.key !== key || cache.root !== root) { + cache = { key, root, pins: new Map(), infos: new Map() }; + pinCache.set(storage, cache); + } + const { pins, infos } = cache; + const listed = await listEntries(storage, REMOTE_PINS_PREFIX); + const listedKeys = new Set(listed.map((object) => object.key)); + for (const cached of [pins, infos]) { + for (const storageKey of cached.keys()) { + if (!listedKeys.has(storageKey)) cached.delete(storageKey); + } + } + const read: PinsRead["pins"] = []; + const unreadable: string[] = []; + await runWithConcurrency(listed, DEFAULT_CONCURRENCY, async (object) => { + const { etag } = object; + const known = infos.get(object.key); + if (fromInfo && etag !== null && known?.etag === etag) { + read.push({ info: known.info, picked: fromInfo(known.info) }); + return; + } + const hit = pins.get(object.key); + let pin: Pin | null | undefined = + etag !== null && hit?.etag === etag ? hit.pin : null; + if (!pin) { + pin = await readPin(storage, key, root, object.key); + // Unpinned since the listing: it holds nothing now. + if (pin === undefined) return; + if (!pin) { + unreadable.push(object.key); + return; + } + if (etag !== null) { + const entries = Object.keys(pin.manifest.files).length; + remember(pins, object.key, { etag, pin, entries }); + } + } + const { id, label, manifest } = pin; + const { createdAt, deviceId, deviceName } = manifest; + const info = { id, label, createdAt, deviceId, deviceName }; + if (etag !== null) infos.set(object.key, { etag, info }); + read.push({ info, picked: pick(pin, info) }); + }); + read.sort((a, b) => b.info.createdAt - a.info.createdAt); + return { pins: read, unreadable }; +} + +/** One pin, null when absent or unreadable. */ +export async function readPinById( + storage: ObjectStorage, + key: EncryptionKey, + root: string, + snapshotId: string, +): Promise { + return (await readPin(storage, key, root, pinKey(snapshotId))) ?? null; +} + +/** Undefined when absent, null when unreadable. */ +async function readPin( + storage: ObjectStorage, + key: EncryptionKey, + root: string, + storageKey: string, +): Promise { + const blob = await storage.get(storageKey); + if (!blob) return undefined; + const id = storageKey.slice(REMOTE_PINS_PREFIX.length, -".json.enc".length); + try { + const stored = await decryptJson(key, blob); + if (stored.v !== 1 || stored.manifest?.snapshotId !== id) return null; + return { + id, + manifest: manifestToVault(stored.manifest, root), + label: stored.label, + pinnedAt: stored.pinnedAt, + }; + } catch (err) { + reportWarning(`Pinned snapshot "${id}" is unreadable.`, err); + return null; + } +} + +function remember( + pins: Map, + storageKey: string, + entry: CachedPin, +): void { + pins.delete(storageKey); + pins.set(storageKey, entry); + trimOldest(pins, PIN_CACHE_ENTRIES, ({ entries }) => entries); +} diff --git a/packages/plugin/src/features/sync/history/publish.ts b/packages/plugin/src/features/sync/history/publish.ts new file mode 100644 index 00000000..ab1bab60 --- /dev/null +++ b/packages/plugin/src/features/sync/history/publish.ts @@ -0,0 +1,145 @@ +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { decryptBytes, type EncryptionKey } from "@/core/crypto"; +import { reportWarning } from "@/core/shared"; +import { runWithConcurrency } from "@/core/utils"; +import type { StorageAdapter } from "@/features/storage"; +import { REMOTE_OBJECTS_PREFIX, REMOTE_RECIPES_PREFIX } from "../constants"; +import { rootKeys } from "../content/keys"; +import { publishManifestWithGuard } from "../remote/manifest"; +import type { Manifest } from "../types"; +import { + changeEntries, + diffManifests, + historyTracks, + splitTracked, +} from "./changes"; +import { pushKey, sealPushRecord } from "./remote"; +import type { HistoryConfig } from "./types"; + +/** A sealed record whose write failed, with what decides whether it may still land. */ +interface Unwritten { + blob: Uint8Array; + vaultId: string; + hashes: string[]; +} + +// A gap in the chain until a later push writes them. Keyed by identity, as a share move or a token refresh +// rebuilds the adapter. +const unwritten = new Map>(); + +// One listing page: past it, listing `objects/` once takes fewer requests than a probe per blob. +const PROBE_LIMIT = 1000; + +/** + * The record lands before the publish, so a won push always has one; a lost push leaves a sibling GC removes. + * Best-effort: a failed write warns and never fails the push. + */ +export async function publishManifestWithHistory( + storage: StorageAdapter, + key: EncryptionKey, + root: string, + manifest: Manifest, + parent: Manifest | null, + history: HistoryConfig | undefined, + baseline: Manifest | null = null, + configDir?: string, +): Promise { + if (history) { + const waiting = unwritten.get(storage.identity()) ?? new Map(); + unwritten.set(storage.identity(), waiting); + const { changes, released } = splitTracked( + diffManifests(parent, manifest), + historyTracks(configDir), + ); + const own: Unwritten = { + blob: await sealPushRecord(key, root, { + v: 1, + vaultId: manifest.vaultId, + id: manifest.snapshotId, + parentId: manifest.parentSnapshotId, + createdAt: manifest.createdAt, + deviceId: manifest.deviceId, + deviceName: manifest.deviceName, + changes, + ...(released.length > 0 && { released }), + }), + vaultId: manifest.vaultId, + hashes: [...new Set(changeEntries(changes).map(({ hash }) => hash))], + }; + waiting.set(pushKey(manifest.snapshotId), own); + await writeWaiting(storage, key, waiting, own); + } + // A failed publish keeps its record waiting: the manifest may have landed, and a sibling costs only GC. + await publishManifestWithGuard( + storage, + key, + root, + manifest, + parent?.snapshotId ?? null, + baseline, + ); +} + +/** Oldest first; stops at the first failure, as the rest would likely fail the same way. */ +async function writeWaiting( + storage: StorageAdapter, + key: EncryptionKey, + waiting: Map, + own: Unwritten, +): Promise { + for (const [storageKey, record] of waiting) { + try { + if (record === own || (await stillLands(storage, record, own, key))) { + await storage.put(storageKey, record.blob, "application/octet-stream"); + } + waiting.delete(storageKey); + } catch (err) { + reportWarning( + "A file history record could not be written; the next push retries it.", + err, + ); + return; + } + } +} + +/** + * A held-back record lands only under the same data key and vault, and while every blob it names survived a + * sweep or a reset. Asked of its ciphertext: a re-unlock or a rotation builds a new key object of the same key. + */ +async function stillLands( + storage: StorageAdapter, + record: Unwritten, + own: Unwritten, + key: EncryptionKey, +): Promise { + if (record.vaultId !== own.vaultId) return false; + if ( + !(await decryptBytes(key, record.blob).then( + () => true, + () => false, + )) + ) { + return false; + } + // A root guards its chunks: a sweep deletes them only after it, a reset after every root. + if (record.hashes.length > PROBE_LIMIT) { + const listed = await Promise.all( + [REMOTE_OBJECTS_PREFIX, REMOTE_RECIPES_PREFIX].map((prefix) => + storage.list(prefix), + ), + ); + const stored = new Set(listed.flat()); + return record.hashes.every((hash) => + rootKeys(hash).some((storageKey) => stored.has(storageKey)), + ); + } + let missing = false; + await runWithConcurrency(record.hashes, DEFAULT_CONCURRENCY, async (hash) => { + for (const storageKey of rootKeys(hash)) { + if (await storage.exists(storageKey)) return; + } + missing = true; + }); + return !missing; +} diff --git a/packages/plugin/src/features/sync/history/query.ts b/packages/plugin/src/features/sync/history/query.ts new file mode 100644 index 00000000..e3eccc41 --- /dev/null +++ b/packages/plugin/src/features/sync/history/query.ts @@ -0,0 +1,404 @@ +import type { EncryptionKey } from "@/core/crypto"; +import type { ObjectStorage } from "@/features/storage"; +import { loadRemoteBytes } from "../changes/content"; +import { entryAt } from "../changes/records"; +import { fetchRemoteManifest } from "../remote/manifest"; +import type { Manifest, ManifestEntry } from "../types"; +import { historyTracks, pickPaths, undoChangesForPath } from "./changes"; +import { activityOf } from "./model/activity"; +import { + type Cover, + coverOf, + type HistoryView, + type WalkedRecord, +} from "./model/cover"; +import { keptUntil } from "./model/periods"; +import { + deletePin, + type PinInfo, + readPinById, + readPinInfos, + readPins, + writePin, +} from "./pins"; +import { readHistory } from "./remote"; +import { replayTo } from "./replay"; +import type { + Dating, + DeletedFile, + DeletedFilesResult, + FileVersion, + SnapshotListResult, + SnapshotSummary, +} from "./types"; + +export interface HistoryQuery { + storage: ObjectStorage; + key: EncryptionKey; + root: string; + /** See `HistoryConfig.horizon`. */ + horizon: number | null; + /** Left out of history (`historyTracks`). */ + configDir?: string; +} + +type Source = Pick; + +/** Who made a snapshot and when, as a row shows it. */ +type Meta = Pick; + +/** HEAD and the walk back from it: the one read every query starts from. */ +export async function readTimeline( + source: Source, +): Promise<{ head: Manifest | null; cover: Cover; view: HistoryView }> { + const { storage, key, root } = source; + const [head, history] = await Promise.all([ + fetchRemoteManifest(storage, key, root), + readHistory(storage, key, root), + ]); + const cover = coverOf( + history.view, + head && { + id: head.snapshotId, + parentId: head.parentSnapshotId, + vaultId: head.vaultId, + }, + ); + return { head, cover, view: history.view }; +} + +/** + * Distinct versions of one path, newest first, each dated by the record that wrote it; pins the walk does not + * reach follow. A pin marks every version whose content it holds. + */ +export async function getFileHistory( + query: Source & Pick & { path: string }, +): Promise { + const { path } = query; + // Records leave it out, so walking them would pass HEAD's entry off as the oldest version. + if (!historyTracks(query.configDir)(path)) return []; + const { head, cover } = await readTimeline(query); + if (!head) return []; + const pins = await readPins( + query.storage, + query.key, + query.root, + (pin) => entryAt(pin.manifest.files, path) ?? null, + ); + const pinOf: PinsByHash = new Map( + pins.pins.flatMap(({ info, picked }) => + picked ? [[picked.hash, info] as const] : [], + ), + ); + const versions: FileVersion[] = []; + let entry = entryAt(head.files, path) ?? null; + // Without HEAD's own record nothing older can be anchored to HEAD's files. + const chain = cover.lagging ? [] : cover.chain; + if (chain.length === 0 && entry) { + versions.push(toVersion(metaOf(head), undated(head), entry, pinOf)); + } + for (const walked of chain) { + const before = undoChangesForPath(entry, walked.record.changes, path); + // A merged deletion replays to its parent's entry; the content right before it is kept apart. + const last = + entry === null && entryAt(walked.record.changes.deletedLast ?? {}, path); + if (last && last.hash !== before?.hash) { + versions.push(toVersion(walked.record, datingOf(walked), last, pinOf)); + } + if (entry && before?.hash !== entry.hash) { + versions.push({ + ...toVersion(walked.record, datingOf(walked), entry, pinOf), + first: before === null, + replayable: true, + }); + } + entry = before; + } + // Written before the walk's end: its snapshot is the oldest record's parent, known only to precede it. + const oldest = chain[chain.length - 1]?.record; + if (entry && oldest) { + const { firstAt } = oldest; + const meta = { ...oldest, id: oldest.parentId ?? oldest.id }; + versions.push( + toVersion( + meta, + { + at: firstAt, + firstAt, + pushes: 1, + res: chain[chain.length - 1]?.res ?? null, + }, + entry, + pinOf, + ), + ); + } + const listed = new Set(versions.map((version) => version.hash)); + for (const { info, picked } of pins.pins) { + if (!picked || listed.has(picked.hash)) continue; + listed.add(picked.hash); + versions.push(toVersion(info, undated(info), picked, pinOf)); + } + return versions; +} + +/** + * Files gone from HEAD but restorable, newest death first: a path deleted, recreated and deleted again + * reports its latest. Pins are folded in after. + */ +export async function listDeletedFiles( + query: HistoryQuery, +): Promise { + const { head, cover } = await readTimeline(query); + if (!head) return { files: [], lagging: false, truncated: false }; + const found = new Map(); + // Only a path's newest change can be its latest death: a lagging walk starts below HEAD's own deletions. + const touched = new Set(); + for (const { record } of cover.chain) { + const { added, modified, deleted } = record.changes; + for (const [path, from] of Object.entries(deleted)) { + if (touched.has(path) || entryAt(head.files, path)) continue; + found.set(path, { + path, + entry: entryAt(record.changes.deletedLast ?? {}, path) ?? from, + snapshotId: record.id, + source: "deleted", + createdAt: record.createdAt, + deviceId: record.deviceId, + deviceName: record.deviceName, + pinned: false, + keptUntil: keptUntil(record.at, query.horizon), + }); + } + for (const changed of [added, modified, deleted]) { + for (const path of Object.keys(changed)) touched.add(path); + } + } + await applyPins(query, head, found); + return { + files: [...found.values()], + lagging: cover.lagging, + truncated: cover.truncated, + }; +} + +/** + * A pin proves a file existed, not when it went: its rows say "last seen". It holds only its own hash, so it + * clears the retention of that version alone. + */ +async function applyPins( + source: Source, + head: Manifest, + found: Map, +): Promise { + // Reduced as each pin is read, so the absent files of every pin are never held at once. + const newest = new Map< + string, + { info: PinInfo; entry: ManifestEntry; order: number } + >(); + let order = 0; + await readPins(source.storage, source.key, source.root, (pin, info) => { + for (const [path, entry] of Object.entries(pin.manifest.files)) { + order++; + if (entryAt(head.files, path)) continue; + // `found` holds only the walk's rows here: a pin's own row is added below. + const existing = found.get(path); + if (existing) { + if (existing.entry.hash === entry.hash) { + existing.pinned = true; + existing.keptUntil = null; + } + continue; + } + // Pins finish in any order: the newest wins, a tie going to the one read first. + const held = newest.get(path); + if (held && held.info.createdAt >= info.createdAt) continue; + newest.set(path, { info, entry, order }); + } + }); + // Rows as one pass over the pins newest first would add them. + const rows = [...newest].sort( + ([, a], [, b]) => b.info.createdAt - a.info.createdAt || a.order - b.order, + ); + for (const [path, { info, entry }] of rows) { + found.set(path, { + path, + entry, + snapshotId: info.id, + source: "pinned", + label: info.label, + createdAt: info.createdAt, + deviceId: info.deviceId, + deviceName: info.deviceName, + pinned: true, + keptUntil: null, + }); + } +} + +/** The vault's push timeline, newest first; a pin no longer on the walk follows. */ +export async function listSnapshots( + query: HistoryQuery, +): Promise { + const { head, cover, view } = await readTimeline(query); + if (!head) + return { snapshots: [], lagging: false, truncated: false, activity: {} }; + const { pins } = await readPinInfos(query.storage, query.key, query.root); + const pinned = new Map(pins.map((info) => [info.id, info])); + const summary = ( + meta: Meta, + dating: Dating, + files: SnapshotSummary["files"], + kept: number | null, + ): SnapshotSummary => { + const pin = pinned.get(meta.id); + return { + ...dating, + id: meta.id, + createdAt: meta.createdAt, + deviceId: meta.deviceId, + deviceName: meta.deviceName, + pinned: pin !== undefined, + label: pin?.label, + files, + keptUntil: pin ? null : kept, + restorable: !cover.lagging || pin !== undefined, + isHead: meta.id === head.snapshotId, + }; + }; + const snapshots = cover.chain.map((walked) => + summary( + walked.record, + datingOf(walked), + walked.record.changes, + keptUntil(walked.record.at, query.horizon), + ), + ); + const onChain = new Set(snapshots.map((snapshot) => snapshot.id)); + for (const info of pins) { + if (!onChain.has(info.id)) + snapshots.push(summary(info, undated(info), null, null)); + } + return { + snapshots, + lagging: cover.lagging, + truncated: cover.truncated, + activity: activityOf(view, cover, head.vaultId), + }; +} + +/** Replay first; a pin's stored manifest covers snapshots the walk no longer reaches. */ +export async function resolveSnapshotManifest( + source: Source, + snapshotId: string, +): Promise { + const replayed = await replaySnapshot(source, snapshotId); + if (replayed) return replayed; + const pin = await readPinById( + source.storage, + source.key, + source.root, + snapshotId, + ); + return pin?.manifest ?? null; +} + +async function replaySnapshot( + source: Source, + snapshotId: string, +): Promise { + const { head, cover } = await readTimeline(source); + return head ? replayTo(head, cover, snapshotId) : null; +} + +/** + * Pinning stores the snapshot's manifest without the configuration folder; a readable pin keeps its manifest and + * takes the new label. `label` undefined keeps the pin's name, "" clears it. + */ +export async function setSnapshotPinned( + source: Source & Pick, + snapshotId: string, + pinned: boolean, + label?: string, +): Promise { + const { storage, key, root } = source; + if (!pinned) { + await deletePin(storage, snapshotId); + return; + } + const existing = await readPinById(storage, key, root, snapshotId); + const replayed = existing ? null : await replaySnapshot(source, snapshotId); + const manifest = + existing?.manifest ?? + (replayed && { + ...replayed, + files: pickPaths(replayed.files, historyTracks(source.configDir)), + }); + if (!manifest) { + throw new Error( + "That snapshot can no longer be rebuilt from history, so it cannot be pinned.", + ); + } + await writePin(storage, key, root, { + id: snapshotId, + manifest, + label: label === undefined ? existing?.label : label || undefined, + pinnedAt: existing?.pinnedAt ?? Date.now(), + }); +} + +export async function loadVersionBytes( + storage: ObjectStorage, + key: EncryptionKey, + hash: string, +): Promise { + const plaintext = await loadRemoteBytes({ storage, key }, hash); + if (!plaintext) { + throw new Error(`Version content is no longer available (${hash})`); + } + return plaintext; +} + +function metaOf(manifest: Manifest): Meta { + return { + id: manifest.snapshotId, + createdAt: manifest.createdAt, + deviceId: manifest.deviceId, + deviceName: manifest.deviceName, + }; +} + +function datingOf({ record, res }: WalkedRecord): Dating { + const { at, firstAt, pushes } = record; + return { at, firstAt, pushes, res }; +} + +/** Off the walk only the device's clock dates it. */ +function undated({ createdAt }: Pick): Dating { + return { at: createdAt, firstAt: createdAt, pushes: 1, res: null }; +} + +type PinsByHash = ReadonlyMap>; + +function toVersion( + meta: Meta, + dating: Dating, + entry: ManifestEntry, + pinOf: PinsByHash, +): FileVersion { + return { + ...dating, + snapshotId: meta.id, + hash: entry.hash, + size: entry.size, + mtime: entry.mtime, + kind: entry.kind, + createdAt: meta.createdAt, + deviceId: meta.deviceId, + deviceName: meta.deviceName, + pinId: pinOf.get(entry.hash)?.id ?? null, + label: pinOf.get(entry.hash)?.label, + first: false, + replayable: false, + }; +} diff --git a/packages/plugin/src/features/sync/history/remote.ts b/packages/plugin/src/features/sync/history/remote.ts new file mode 100644 index 00000000..4ad36567 --- /dev/null +++ b/packages/plugin/src/features/sync/history/remote.ts @@ -0,0 +1,288 @@ +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { + decryptJson, + type EncryptionKey, + encryptJson, + randomId, + sha256Hex, +} from "@/core/crypto"; +import { runWithConcurrency } from "@/core/utils"; +import { + type ListedObject, + listEntries, + type ObjectStorage, +} from "@/features/storage"; +import { REMOTE_HISTORY_PREFIX } from "../constants"; +import { changesToSpace, changesToVault } from "../remote/space-paths"; +import type { HistoryView } from "./model/cover"; +import { RESOLUTIONS } from "./model/periods"; +import type { HistoryObject, PushRecord } from "./model/types"; + +const PUSHES = `${REMOTE_HISTORY_PREFIX}p/`; +const OBJECTS = `${REMOTE_HISTORY_PREFIX}b/`; +/** Blobs a GC run stopped naming: held for a day, then swept. */ +const CANDIDATES = `${REMOTE_HISTORY_PREFIX}g/`; + +interface Candidates { + v: 1; + hashes: string[]; +} + +type Decoded = { push: PushRecord } | { object: HistoryObject }; + +export interface HistoryRead { + view: HistoryView; + /** Listed but undecodable (corrupt, newer format): readers show a gap, GC must not run on it. */ + unreadable: string[]; + /** Storage time: the newest record or object listed. */ + now: number; + /** Candidate files, listed in the same call. */ + candidates: ListedObject[]; +} + +// Push records never change and objects are named by their content, so a decoded key stays valid. +const caches = new WeakMap< + ObjectStorage, + { key: EncryptionKey; root: string; entries: Map } +>(); + +function cacheOf( + storage: ObjectStorage, + key: EncryptionKey, + root: string, +): Map { + let cache = caches.get(storage); + if (cache?.key !== key || cache.root !== root) { + cache = { key, root, entries: new Map() }; + caches.set(storage, cache); + } + return cache.entries; +} + +export function pushKey(id: string): string { + return `${PUSHES}${id}.enc`; +} + +/** Sealed with space paths, so a write retried after the space moved still names the right files. */ +export function sealPushRecord( + key: EncryptionKey, + root: string, + record: PushRecord, +): Promise { + return encryptJson(key, { + ...record, + changes: changesToSpace(record.changes, root), + }); +} + +/** + * Named by its whole content, `consumed` included, so a key never changes meaning and a decoded object stays + * valid; only a read-back under the same key proves the write. Returns the stored object, in space paths. + */ +export async function writeHistoryObject( + storage: ObjectStorage, + key: EncryptionKey, + root: string, + build: Omit, +): Promise<{ key: string; object: HistoryObject }> { + const stored: HistoryObject = { + v: 1, + ...build, + records: build.records.map((record) => ({ + ...record, + changes: changesToSpace(record.changes, root), + })), + }; + const storageKey = await objectKeyOf(stored); + await storage.put( + storageKey, + await encryptJson(key, stored), + "application/octet-stream", + ); + const blob = await storage.get(storageKey); + const read = blob && (await decryptJson(key, blob)); + // decodeRaw recomputes the key from the read-back, so a null is one that is not what was written. + const decoded = read && (await decodeRaw(root, storageKey, read)); + if (!read || !decoded) { + throw new Error( + `History object ${storageKey} did not read back as written.`, + ); + } + // Seeded from the read-back only, so the next read of this key costs no GET. + cacheOf(storage, key, root).set(storageKey, decoded); + return { key: storageKey, object: read }; +} + +async function objectKeyOf(object: HistoryObject): Promise { + const { records, activity, lastId, consumed } = object; + const json = JSON.stringify({ records, activity, lastId, consumed }); + const digest = (await sha256Hex(new TextEncoder().encode(json))).slice(0, 16); + return `${OBJECTS}${object.res}-${object.group}-${digest}.enc`; +} + +export async function writeCandidates( + storage: ObjectStorage, + key: EncryptionKey, + hashes: readonly string[], +): Promise { + const candidates: Candidates = { v: 1, hashes: [...hashes] }; + await storage.put( + `${CANDIDATES}${randomId()}.enc`, + await encryptJson(key, candidates), + "application/octet-stream", + ); +} + +/** A file gone meanwhile was swept by another run; one that does not decode is `unreadable`. */ +export async function readCandidates( + storage: ObjectStorage, + key: EncryptionKey, + files: readonly ListedObject[], +): Promise<{ hashes: Set; unreadable: string[] }> { + const hashes = new Set(); + const unreadable: string[] = []; + await runWithConcurrency( + files, + DEFAULT_CONCURRENCY, + async ({ key: file }) => { + const blob = await storage.get(file); + if (!blob) return; + const read = await decryptJson(key, blob).catch(() => null); + if (read?.v !== 1 || !Array.isArray(read.hashes)) unreadable.push(file); + else for (const hash of read.hashes) hashes.add(hash); + }, + ); + return { hashes, unreadable }; +} + +/** Lists `history/` once and decodes only what this session has not seen. */ +export async function readHistory( + storage: ObjectStorage, + key: EncryptionKey, + root: string, +): Promise { + const entries = cacheOf(storage, key, root); + let all = await listEntries(storage, REMOTE_HISTORY_PREFIX); + let listed = all.filter(isRecordOrObject); + let read = await decodeNew(storage, key, root, listed, entries); + // Retired by a GC after our listing: what replaced it is listed now. + if (read.gone > 0) { + all = await listEntries(storage, REMOTE_HISTORY_PREFIX); + listed = all.filter(isRecordOrObject); + read = await decodeNew(storage, key, root, listed, entries); + } + const times = new Map(listed.map((object) => [object.key, object.modified])); + // Reduced, not spread: a long listing would overflow the argument stack. + const now = listed.reduce( + (max, { modified }) => + modified === null || (max !== null && max >= modified) ? max : modified, + null, + ); + const newest = now ?? Date.now(); + const pushes = new Map(); + const objects = new Map(); + for (const [storageKey, modified] of times) { + const decoded = entries.get(storageKey); + if (!decoded) continue; + if ("push" in decoded) { + const { parentId } = decoded.push; + // Undated: its parent's time, else "now"; as "now" it never packs and holds up its successors. + const parentAt = parentId === null ? null : times.get(pushKey(parentId)); + const at = modified ?? parentAt ?? newest; + pushes.set(storageKey, { push: decoded.push, at }); + } else { + objects.set(storageKey, { + object: decoded.object, + at: modified ?? newest, + }); + } + } + for (const storageKey of entries.keys()) { + if (!times.has(storageKey)) entries.delete(storageKey); + } + return { + view: { pushes, objects }, + unreadable: read.unreadable, + now: newest, + candidates: all.filter(({ key }) => key.startsWith(CANDIDATES)), + }; +} + +function isRecordOrObject({ key }: ListedObject): boolean { + return key.startsWith(PUSHES) || key.startsWith(OBJECTS); +} + +async function decodeNew( + storage: ObjectStorage, + key: EncryptionKey, + root: string, + listed: readonly ListedObject[], + entries: Map, +): Promise<{ gone: number; unreadable: string[] }> { + const todo = listed + .map((object) => object.key) + .filter((storageKey) => !entries.has(storageKey)); + // An empty hint would replace one a running transfer gave. + if (todo.length > 0) storage.prepareReads?.(todo); + let gone = 0; + const unreadable: string[] = []; + await runWithConcurrency(todo, DEFAULT_CONCURRENCY, async (storageKey) => { + const blob = await storage.get(storageKey); + if (!blob) { + gone++; + return; + } + const decoded = await decode(key, root, storageKey, blob).catch(() => null); + if (decoded) entries.set(storageKey, decoded); + else unreadable.push(storageKey); + }); + return { gone, unreadable }; +} + +async function decode( + key: EncryptionKey, + root: string, + storageKey: string, + blob: Uint8Array, +): Promise { + return decodeRaw( + root, + storageKey, + await decryptJson>(key, blob), + ); +} + +/** Validates a decrypted record or object and moves its paths from space to vault. */ +async function decodeRaw( + root: string, + storageKey: string, + raw: { v?: unknown; vaultId?: unknown }, +): Promise { + if (raw.v !== 1 || typeof raw.vaultId !== "string") return null; + if (storageKey.startsWith(PUSHES)) { + const push = raw as unknown as PushRecord; + if (typeof push.id !== "string" || !push.changes) return null; + return { + push: { ...push, changes: changesToVault(push.changes, root) }, + }; + } + const object = raw as unknown as HistoryObject; + if ( + !RESOLUTIONS.includes(object.res) || + !Array.isArray(object.records) || + !Array.isArray(object.consumed) || + // A key that does not match its content cannot vouch for what it consumes. + (await objectKeyOf(object)) !== storageKey + ) { + return null; + } + return { + object: { + ...object, + records: object.records.map((record) => ({ + ...record, + changes: changesToVault(record.changes, root), + })), + }, + }; +} diff --git a/packages/plugin/src/features/sync/history/replay.ts b/packages/plugin/src/features/sync/history/replay.ts new file mode 100644 index 00000000..e8386907 --- /dev/null +++ b/packages/plugin/src/features/sync/history/replay.ts @@ -0,0 +1,36 @@ +import type { Manifest } from "../types"; +import { undoChanges } from "./changes"; +import type { Cover } from "./model/cover"; + +/** + * Null when the walk does not start at HEAD or never reaches the target: a partial replay would invent a state. + * Empty folders are not tracked per snapshot, so the result carries none. + */ +export function replayTo( + head: Manifest, + cover: Cover, + snapshotId: string, +): Manifest | null { + if ( + cover.lagging || + !cover.chain.some(({ record }) => record.id === snapshotId) + ) + return null; + const files = { ...head.files }; + for (const { record } of cover.chain) { + if (record.id === snapshotId) { + return { + version: head.version, + vaultId: head.vaultId, + snapshotId: record.id, + parentSnapshotId: record.parentId, + createdAt: record.createdAt, + deviceId: record.deviceId, + deviceName: record.deviceName, + files, + }; + } + undoChanges(files, record.changes); + } + return null; +} diff --git a/packages/plugin/src/sync/history/restore-vault.ts b/packages/plugin/src/features/sync/history/restore-vault.ts similarity index 70% rename from packages/plugin/src/sync/history/restore-vault.ts rename to packages/plugin/src/features/sync/history/restore-vault.ts index 7cbdee39..0eb55c9f 100644 --- a/packages/plugin/src/sync/history/restore-vault.ts +++ b/packages/plugin/src/features/sync/history/restore-vault.ts @@ -1,5 +1,5 @@ -import { entryAt } from "@/shared"; -import type { LocalSnapshot, Manifest, ManifestEntry } from "@/sync/types"; +import { entryAt } from "../changes/records"; +import type { LocalSnapshot, Manifest, ManifestEntry } from "../types"; export interface VaultRestoreWrite { path: string; @@ -12,7 +12,7 @@ export interface VaultRestorePlan { /** Vault files the target snapshot does not have. */ remove: string[]; unchanged: number; - /** Paths the sync scope excludes: left untouched in either direction, so history never overrides an ignore rule. */ + /** Paths the sync scope excludes or the scan skipped: left untouched in either direction, so history never overrides an ignore rule. */ ignored: string[]; } @@ -24,8 +24,14 @@ export function planVaultRestore( target: Manifest, local: LocalSnapshot, inScope: (path: string) => boolean = () => true, + /** Paths history keeps: the rest is neither written, removed nor counted. */ + tracks: (path: string) => boolean = () => true, ): VaultRestorePlan { - const ignored = new Set(local.ignoredPaths); + // A skipped path (unreadable, or a name this disk cannot hold) is unknown here: left alone like an ignored one. + const ignored = new Set([ + ...local.ignoredPaths, + ...local.skipped.map(({ path }) => path), + ]); const plan: VaultRestorePlan = { write: [], remove: [], @@ -33,6 +39,7 @@ export function planVaultRestore( ignored: [], }; for (const [path, entry] of Object.entries(target.files)) { + if (!tracks(path)) continue; if (ignored.has(path) || !inScope(path)) { plan.ignored.push(path); continue; @@ -46,7 +53,8 @@ export function planVaultRestore( } const written = new Set(plan.write.map(({ path }) => path.toLowerCase())); for (const path of Object.keys(local.files)) { - if (ignored.has(path) || entryAt(target.files, path)) continue; + if (!tracks(path) || ignored.has(path) || entryAt(target.files, path)) + continue; if (written.has(path.toLowerCase())) continue; plan.remove.push(path); } diff --git a/packages/plugin/src/features/sync/history/sweep.ts b/packages/plugin/src/features/sync/history/sweep.ts new file mode 100644 index 00000000..228df73e --- /dev/null +++ b/packages/plugin/src/features/sync/history/sweep.ts @@ -0,0 +1,248 @@ +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import type { EncryptionKey } from "@/core/crypto"; +import { runWithConcurrency } from "@/core/utils"; +import type { ListedObject, ObjectStorage } from "@/features/storage"; +import { + MANIFEST_VERSION, + REMOTE_CHUNKS_PREFIX, + REMOTE_OBJECTS_PREFIX, + REMOTE_PINS_PREFIX, + REMOTE_RECIPES_PREFIX, +} from "../constants"; +import { chunksNamed, forgetUnlistedRecipes } from "../content/closure"; +import { rootHash } from "../content/keys"; +import { fetchRemoteManifest } from "../remote/manifest"; +import { listDated, SETTLED_AFTER_MS } from "../remote/uploads"; +import type { Manifest, ManifestEntry } from "../types"; +import { changeEntries } from "./changes"; +import { pinKey, readPins } from "./pins"; +import { type HistoryRead, readCandidates, readHistory } from "./remote"; + +export interface SweepOptions { + concurrency?: number; + onProgress?: (done: number, total: number) => void; + /** Sweep only what settled candidate files name: GC's phase 2. */ + freedOnly?: boolean; +} + +export interface ReachableSet { + /** Each reachable hash with its largest known size. */ + hashes: Map; + head: Manifest | null; + /** Pin keys listed when the set was read. */ + pinned: string; + /** History keys listed when the set was read, candidate files included. */ + history: ReadonlySet; + candidates: readonly ListedObject[]; + /** False when a history record or pin could not be read, so the live set is unknown. */ + complete: boolean; +} + +/** Every hash HEAD, any listed history record (off the walk too: a superset only keeps more) or any pin names. */ +export async function reachableHashes( + storage: ObjectStorage, + key: EncryptionKey, + root: string, +): Promise { + const hashes = new Map(); + const reach = (entries: Iterable): void => { + for (const { hash, size } of entries) { + hashes.set(hash, Math.max(hashes.get(hash) ?? 0, size)); + } + }; + const [head, history, pins] = await Promise.all([ + fetchRemoteManifest(storage, key, root), + readHistory(storage, key, root), + // Reached as each pin is read, so no more than a few manifests are held at once. + readPins(storage, key, root, (pin) => + reach(Object.values(pin.manifest.files)), + ), + ]); + if (head) reach(Object.values(head.files)); + for (const { push } of history.view.pushes.values()) { + reach(changeEntries(push.changes)); + } + for (const { object } of history.view.objects.values()) { + for (const record of object.records) reach(changeEntries(record.changes)); + } + return { + hashes, + head, + pinned: pins.pins + .map(({ info }) => pinKey(info.id)) + .sort() + .join(","), + history: new Set(historyKeys(history)), + candidates: history.candidates, + complete: history.unreadable.length === 0 && pins.unreadable.length === 0, + }; +} + +/** A candidate file a day old: every listing shows what was written around the run that freed its hashes. */ +function isSettled({ modified }: ListedObject): boolean { + return modified !== null && modified < Date.now() - SETTLED_AFTER_MS; +} + +/** + * Deletes settled roots nothing reaches (HEAD, a history record, a pin), never one a GC run freed within the + * last day, then settled chunks no remaining recipe names; needs a backend that can list. + */ +export async function sweepObjects( + storage: ObjectStorage, + key: EncryptionKey, + root: string, + options: SweepOptions = {}, +): Promise { + const reachable = await reachableHashes(storage, key, root); + // Without head, objects from an in-progress upload would look like orphans. + if (!reachable.head) { + throw new Error( + "No manifest is published on this remote, so nothing can be identified as an orphan.", + ); + } + // Below the fence 1.x clients still sync, and their history names what looks orphaned here. + if (reachable.head.version < MANIFEST_VERSION) { + throw new Error( + "This remote still uses the old file history format. Push once with this version, then try again.", + ); + } + // An unreadable record means the live set is unknown, so we cannot safely delete. + if (!reachable.complete) { + throw new Error( + "Some history records could not be read, so orphans cannot be identified safely. Try again later.", + ); + } + + // Split once, before the listing: a file settling during it stays young, so its blobs stay held. + const due: ListedObject[] = []; + const young: ListedObject[] = []; + for (const file of reachable.candidates) { + (isSettled(file) ? due : young).push(file); + } + // An unreadable settled file only leaks its blobs to the next deep clean. + const freed = options.freedOnly + ? (await readCandidates(storage, key, due)).hashes + : null; + const kept = new Set(reachable.hashes.keys()); + // Nothing but candidate files goes then, so the listing, young files and rechecks guard nothing. + if (freed && [...freed].every((hash) => kept.has(hash))) { + await deleteFiles(storage, due); + return 0; + } + + const [objects, recipes, chunks] = await Promise.all([ + listDated(storage, REMOTE_OBJECTS_PREFIX), + listDated(storage, REMOTE_RECIPES_PREFIX), + listDated(storage, REMOTE_CHUNKS_PREFIX), + ]); + forgetUnlistedRecipes(storage, recipes); + + const held = await readCandidates(storage, key, young); + if (held.unreadable.length > 0) { + throw new Error( + "Some history records could not be read, so orphans cannot be identified safely. Try again later.", + ); + } + for (const hash of held.hashes) kept.add(hash); + // Judged once: a recipe settling during the reads below must not drop out of both sides. + const orphans = new Set( + [...objects, ...recipes] + .filter((root) => { + const hash = rootHash(root.key); + return ( + isSettled(root) && + !kept.has(hash) && + (freed === null || freed.has(hash)) + ); + }) + .map((root) => root.key), + ); + const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY; + const named = (doomed: boolean) => + chunksNamed( + storage, + key, + recipes.filter((recipe) => orphans.has(recipe.key) === doomed), + concurrency, + ); + // Phase 2 takes only the chunks of the recipes it deletes; deep clean any settled one. + const freedChunks = freed && (await named(true)).chunks; + let loose = chunks + .filter( + (chunk) => isSettled(chunk) && (freedChunks?.has(chunk.key) ?? true), + ) + .map((chunk) => chunk.key); + if (loose.length > 0) { + // Young and undated recipes survive too, so a push in flight keeps the chunks it trusted. + const surviving = await named(false); + if (surviving.unreadable.length > 0) { + throw new Error( + "Some stored files could not be read, so their parts cannot be identified safely. Try again later.", + ); + } + loose = loose.filter((chunkKey) => !surviving.chunks.has(chunkKey)); + } + // Checked last, so every read since the listing is guarded too. + await assertUnchanged(storage, key, root, reachable); + const total = orphans.size + loose.length; + let done = 0; + // Roots first: a chunk goes only once nothing names it. + for (const batch of [[...orphans], loose]) { + await runWithConcurrency(batch, concurrency, async (storageKey) => { + await storage.delete(storageKey); + options.onProgress?.(++done, total); + }); + } + await deleteFiles(storage, due); + return total; +} + +async function assertUnchanged( + storage: ObjectStorage, + key: EncryptionKey, + root: string, + reachable: ReachableSet, +): Promise { + // Another device publishing since the listing makes its new objects look like orphans: bail. + const headNow = await fetchRemoteManifest(storage, key, root); + if ((headNow?.snapshotId ?? null) !== reachable.head?.snapshotId) { + throw new Error( + "Another device pushed while cleaning; nothing was deleted. Try again.", + ); + } + // Pinning does not move HEAD, so a pin created since the listing needs its own check. + const pinnedNow = (await storage.list(REMOTE_PINS_PREFIX)).sort().join(","); + if (pinnedNow !== reachable.pinned) { + throw new Error( + "Another device changed a pinned snapshot while cleaning; nothing was deleted. Try again.", + ); + } + // A record retried meanwhile does not move HEAD either, and may name what looks orphaned. + const historyNow = await readHistory(storage, key, root); + if ( + historyKeys(historyNow).some((listed) => !reachable.history.has(listed)) + ) { + throw new Error( + "Another device wrote file history while cleaning; nothing was deleted. Try again.", + ); + } +} + +function deleteFiles( + storage: ObjectStorage, + files: readonly ListedObject[], +): Promise { + return runWithConcurrency(files, DEFAULT_CONCURRENCY, (file) => + storage.delete(file.key), + ); +} + +/** Candidate files too: one written meanwhile names versions a run just stopped naming. */ +function historyKeys(read: HistoryRead): string[] { + return [ + ...read.view.pushes.keys(), + ...read.view.objects.keys(), + ...read.unreadable, + ...read.candidates.map(({ key }) => key), + ]; +} diff --git a/packages/plugin/src/sync/history/types.ts b/packages/plugin/src/features/sync/history/types.ts similarity index 55% rename from packages/plugin/src/sync/history/types.ts rename to packages/plugin/src/features/sync/history/types.ts index 312b2f64..fede001d 100644 --- a/packages/plugin/src/sync/history/types.ts +++ b/packages/plugin/src/features/sync/history/types.ts @@ -1,18 +1,9 @@ -import type { EFileKind, ManifestEntry } from "@/sync/types"; +import type { EFileKind, ManifestEntry } from "../types"; +import type { Activity, Resolution } from "./model/types"; export interface HistoryConfig { - maxSnapshots: number; -} - -export interface SnapshotEntry { - id: string; - parentId: string | null; - createdAt: number; - deviceId: string; - deviceName?: string; - /** Pinned snapshots are never evicted and keep a full manifest under `pins/`. */ - pinned?: boolean; - label?: string; + /** ms past which only activity counts are kept; null keeps every tier forever. */ + horizon: number | null; } export interface FileChange { @@ -24,17 +15,23 @@ export interface FileChange { export interface SnapshotChanges { added: Record; modified: Record; + /** The parent's entry, which replay restores. */ deleted: Record; + /** A merged record's content right before the deletion, where it differs from `deleted`. */ + deletedLast?: Record; } -export interface HistoryLog { - version: number; - /** Newest first. */ - snapshots: SnapshotEntry[]; - changes: Record; +/** Where a version sits in retention; a pin the walk no longer reaches is a single push of its own. */ +export interface Dating { + /** Storage time of its newest push: retention and the history views date by it. */ + at: number; + firstAt: number; + pushes: number; + /** The period it is kept at; null off the walk. */ + res: Resolution | null; } -export interface FileVersion { +export interface FileVersion extends Dating { snapshotId: string; hash: string; size: number; @@ -43,9 +40,14 @@ export interface FileVersion { createdAt: number; deviceId: string; deviceName?: string; - pinned: boolean; + /** The pin holding this content, maybe a later snapshot than the one that wrote it; null when none. */ + pinId: string | null; /** Name the user gave the pin, if any. */ label?: string; + /** Nothing older holds the path: this version created it. */ + first: boolean; + /** Replay rebuilds `snapshotId`, so it can be pinned; false past the walk's end. */ + replayable: boolean; } export interface DeletedFile { @@ -60,11 +62,10 @@ export interface DeletedFile { createdAt: number; deviceId: string; deviceName?: string; - /** - * Position among non-pinned snapshots, newest first: survives `retentionLimit - rank` more pushes. `null` - * when a pin holds the file. - */ - rank: number | null; + /** A pin holds this content, so retention never drops it. */ + pinned: boolean; + /** The earliest time retention may drop this content; null while pinned or nothing expires. */ + keptUntil: number | null; } export interface DeletedFilesResult { @@ -78,7 +79,7 @@ export interface DeletedFilesResult { truncated: boolean; } -export interface SnapshotSummary { +export interface SnapshotSummary extends Dating { id: string; createdAt: number; deviceId: string; @@ -87,8 +88,8 @@ export interface SnapshotSummary { label?: string; /** Null when no change record explains this snapshot, so its contents are unknown. */ files: SnapshotChanges | null; - /** Rank among non-pinned snapshots; see `DeletedFile.rank`. Null when pinned. */ - rank: number | null; + /** See `DeletedFile.keptUntil`; null when pinned. */ + keptUntil: number | null; /** Reachable by replay from HEAD, which a restore needs. */ restorable: boolean; /** True when this snapshot is the actual remote HEAD, determined by snapshotId. */ @@ -99,4 +100,8 @@ export interface SnapshotListResult { snapshots: SnapshotSummary[]; /** The log does not describe HEAD yet, so the newest push is missing here. */ lagging: boolean; + /** The walk stopped at a missing record: older versions are unknown. */ + truncated: boolean; + /** Pushes per UTC hour, past the horizon too. */ + activity: Activity; } diff --git a/packages/plugin/src/features/sync/host.ts b/packages/plugin/src/features/sync/host.ts new file mode 100644 index 00000000..9bbd3740 --- /dev/null +++ b/packages/plugin/src/features/sync/host.ts @@ -0,0 +1,26 @@ +import type { App } from "obsidian"; +import type { SettingsHost } from "@/core/settings"; +import type { SyncController } from "./controller"; +import type { PassphraseManager } from "./remote/passphrase-manager"; +import type { Space } from "./remote/space"; +import type { IgnoreStateHandle } from "./scope/ignore-state"; + +/** What sync's commands, menus and sections need from the plugin. */ +export interface SyncHost extends SettingsHost { + readonly app: App; + readonly controller: SyncController; + readonly ignoreState: IgnoreStateHandle; + readonly passphrase: PassphraseManager; + /** The records' partition, ahead of the next refresh. */ + readonly spaces: { partition(): readonly Space[] }; + resetLocalState(): Promise; + openSourceControl(): Promise; + openChanges(): Promise; +} + +/** What the History page reads from the plugin. */ +export interface HistorySectionHost extends SettingsHost { + readonly app: App; + refreshSourceControlView(history?: boolean): void; + openTimeline(day?: number): Promise; +} diff --git a/packages/plugin/src/sync/anchored-hunks.ts b/packages/plugin/src/features/sync/hunks/anchored-hunks.ts similarity index 98% rename from packages/plugin/src/sync/anchored-hunks.ts rename to packages/plugin/src/features/sync/hunks/anchored-hunks.ts index 6624fb14..65aec014 100644 --- a/packages/plugin/src/sync/anchored-hunks.ts +++ b/packages/plugin/src/features/sync/hunks/anchored-hunks.ts @@ -1,4 +1,4 @@ -import { commonEnds, type DiffRange, diffRanges } from "@/utils"; +import { commonEnds, type DiffRange, diffRanges } from "@/core/utils"; import { DIFF_BUDGET } from "./hunks"; diff --git a/packages/plugin/src/features/sync/hunks/bounded-map.ts b/packages/plugin/src/features/sync/hunks/bounded-map.ts new file mode 100644 index 00000000..4d8a42eb --- /dev/null +++ b/packages/plugin/src/features/sync/hunks/bounded-map.ts @@ -0,0 +1,16 @@ +/** Drops the oldest entries until the rest fits; the newest stays even alone over `max`, its reader still needs it. */ +export function trimOldest( + entries: Map, + max: number, + weight: (value: V) => number = () => 1, + maxEntries = Number.POSITIVE_INFINITY, +): void { + let total = 0; + for (const value of entries.values()) total += weight(value); + for (const [key, value] of entries) { + if (entries.size === 1) break; + if (total <= max && entries.size <= maxEntries) break; + entries.delete(key); + total -= weight(value); + } +} diff --git a/packages/plugin/src/sync/diff-cache.ts b/packages/plugin/src/features/sync/hunks/diff-cache.ts similarity index 71% rename from packages/plugin/src/sync/diff-cache.ts rename to packages/plugin/src/features/sync/hunks/diff-cache.ts index 805e8515..5b453be4 100644 --- a/packages/plugin/src/sync/diff-cache.ts +++ b/packages/plugin/src/features/sync/hunks/diff-cache.ts @@ -1,5 +1,7 @@ -import type { EngineDependencies } from "./engine"; -import { hunkBaseline } from "./operations/text-loaders"; +import type { EngineDependencies } from "../engine"; +import { hunkBaseline } from "../operations/text-loaders"; +import type { Conflict, FileChange, Move } from "../types"; +import { trimOldest } from "./bounded-map"; import { buildConflictDiff, buildLocalChangeDiff, @@ -7,9 +9,8 @@ import { type FileDiffModel, type ProjectionDeps, } from "./projection"; -import type { Conflict, FileChange, Move } from "./types"; -/** Total text bytes the in-memory diff model cache may retain. */ +/** Total text the cache may retain: forced diffs must not pin megabytes of strings. */ const DIFF_CACHE_MAX_BYTES = 8 * 1024 * 1024; export interface PathStatusInput { @@ -30,11 +31,9 @@ const DIFF_CACHE_MAX_ENTRIES = 64; export class DiffCache { private readonly entries = new Map(); - private retainedBytes = 0; clear(): void { this.entries.clear(); - this.retainedBytes = 0; } async get(input: DiffCacheInput): Promise { @@ -56,33 +55,18 @@ export class DiffCache { }; const model = await buildModel(projection, input.status, forceText); if (model) { - // A concurrent miss on the same key already charged for its own model. - const raced = this.entries.get(cacheKey); - if (raced) { - this.retainedBytes -= modelBytes(raced); - this.entries.delete(cacheKey); - } + // A concurrent miss may have stored the key: delete first so this model is the newest. + this.entries.delete(cacheKey); this.entries.set(cacheKey, model); - this.retainedBytes += modelBytes(model); - this.evict(); + trimOldest( + this.entries, + DIFF_CACHE_MAX_BYTES, + modelBytes, + DIFF_CACHE_MAX_ENTRIES, + ); } return model; } - - /** Evicts LRU entries past the count or byte budget so forced diffs do not pin megabytes of strings. */ - private evict(): void { - for (const [key, model] of this.entries) { - if ( - this.entries.size <= DIFF_CACHE_MAX_ENTRIES && - this.retainedBytes <= DIFF_CACHE_MAX_BYTES - ) { - break; - } - if (this.entries.size === 1) break; // Always keep the newest model. - this.entries.delete(key); - this.retainedBytes -= modelBytes(model); - } - } } function modelBytes(model: FileDiffModel): number { diff --git a/packages/plugin/src/sync/hunks.ts b/packages/plugin/src/features/sync/hunks/hunks.ts similarity index 95% rename from packages/plugin/src/sync/hunks.ts rename to packages/plugin/src/features/sync/hunks/hunks.ts index b1356a9f..c4aa244b 100644 --- a/packages/plugin/src/sync/hunks.ts +++ b/packages/plugin/src/features/sync/hunks/hunks.ts @@ -1,4 +1,4 @@ -import { changedMiddle, type DiffRange, diffRanges, toLf } from "@/utils"; +import { changedMiddle, type DiffRange, diffRanges, toLf } from "@/core/utils"; export const EHunkKind = { Added: "added", @@ -280,23 +280,20 @@ export function applyHunks( cursor++; } const taken = selected.get(hunk.index); - let segment = -1; - let inSegment = false; - for (const [offset, line] of hunk.lines.entries()) { - const prefix = line[0]; - if (prefix !== " " && prefix !== "-" && prefix !== "+") continue; - if (prefix === " ") { - inSegment = false; - } else if (!inSegment) { - inSegment = true; - segment++; - } - const keep = taken?.has(segment) ? "+" : "-"; - if (prefix === " " || prefix === keep) { + let offset = 0; + const emit = (to: number, keep: string): void => { + for (; offset < to; offset++) { + const line = hunk.lines[offset] as string; + if (line[0] !== " " && line[0] !== keep) continue; const ending = hunk.lines[offset + 1]?.startsWith("\\") ? "" : "\n"; out.push(line.slice(1) + ending); } + }; + for (const segment of hunkSegments(hunk)) { + emit(segment.from, " "); + emit(segment.to, taken?.has(segment.index) ? "+" : "-"); } + emit(hunk.lines.length, " "); cursor = startIndex + hunk.oldLines; } while (cursor < baseLines.length) { diff --git a/packages/plugin/src/features/sync/hunks/json-align.ts b/packages/plugin/src/features/sync/hunks/json-align.ts new file mode 100644 index 00000000..8a16f3bd --- /dev/null +++ b/packages/plugin/src/features/sync/hunks/json-align.ts @@ -0,0 +1,69 @@ +export type Json = unknown; + +/** + * Base and remote rewritten in local's key order and indent, so a merge shows only real changes. Only for JSON + * exactly as `JSON.stringify` writes it on every side (Obsidian's config, plugin `data.json`): rewriting such a + * text loses nothing. Null otherwise. + */ +export function alignJsonSides( + base: string, + local: string, + remote: string, +): { base: string; remote: string } | null { + const [baseSide, localSide, remoteSide] = [base, local, remote].map( + canonical, + ); + if (!baseSide || !localSide || !remoteSide) return null; + const write = ({ value }: Canonical) => + JSON.stringify(ordered(value, localSide.value), null, localSide.indent) + + localSide.tail; + return { base: write(baseSide), remote: write(remoteSide) }; +} + +interface Canonical { + value: Json; + indent: string; + tail: string; +} + +/** The text's value, indent and ending, or null unless it is exactly what `JSON.stringify` writes for it. */ +export function canonical(text: string): Canonical | null { + let value: Json; + try { + value = JSON.parse(text); + } catch { + return null; + } + const indent = /\n([\t ]+)/.exec(text)?.[1] ?? ""; + const tail = text.endsWith("\n") ? "\n" : ""; + // Also refuses what parsing alone would change: big integers, number forms, key order JS reorders. + if (JSON.stringify(value, null, indent) + tail !== text) return null; + return { value, indent, tail }; +} + +/** Template's keys first in its order, then the rest in their own. */ +export function ordered(value: Json, template: Json): Json { + if (Array.isArray(value)) { + return value.map((item, i) => + ordered(item, Array.isArray(template) ? template[i] : undefined), + ); + } + if (!isRecord(value)) return value; + const own = new Set(Object.keys(value)); + const first = isRecord(template) + ? Object.keys(template).filter((key) => own.has(key)) + : []; + // Null prototype: a "__proto__" key stays a key. + const out: Record = Object.create(null); + for (const key of new Set([...first, ...own])) { + out[key] = ordered( + value[key], + isRecord(template) ? template[key] : undefined, + ); + } + return out; +} + +export function isRecord(value: Json): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/packages/plugin/src/features/sync/hunks/json-merge.ts b/packages/plugin/src/features/sync/hunks/json-merge.ts new file mode 100644 index 00000000..b6a14419 --- /dev/null +++ b/packages/plugin/src/features/sync/hunks/json-merge.ts @@ -0,0 +1,68 @@ +import { canonical, isRecord, type Json, ordered } from "./json-align"; + +/** A key one side does not have: absent is not `null`. */ +const ABSENT = Symbol("absent"); +const CLASH = Symbol("clash"); +type Slot = Json | typeof ABSENT; + +/** + * Settings JSON merged three-way by key: a key changed on one side takes that side, equal edits converge, and + * two different edits of one key clash. Arrays and scalars are whole values. Written in local's key order, indent + * and ending. Null on a clash, or when a side is not exactly `JSON.stringify` output: rewriting it could change it. + */ +export function mergeJsonByKey( + base: string, + local: string, + remote: string, +): string | null { + const [baseSide, localSide, remoteSide] = [base, local, remote].map( + canonical, + ); + if (!baseSide || !localSide || !remoteSide) return null; + const merged = mergeValue(baseSide.value, localSide.value, remoteSide.value); + if (merged === CLASH || merged === ABSENT) return null; + return ( + JSON.stringify(ordered(merged, localSide.value), null, localSide.indent) + + localSide.tail + ); +} + +function mergeValue( + base: Slot, + local: Slot, + remote: Slot, +): Slot | typeof CLASH { + if (same(local, remote) || same(base, remote)) return local; + if (same(base, local)) return remote; + if (!isRecord(base) || !isRecord(local) || !isRecord(remote)) return CLASH; + // Null prototype: a "__proto__" key stays a key. + const out: Record = Object.create(null); + for (const key of new Set([...Object.keys(local), ...Object.keys(remote)])) { + const value = mergeValue( + slot(base, key), + slot(local, key), + slot(remote, key), + ); + if (value === CLASH) return CLASH; + if (value !== ABSENT) out[key] = value; + } + return out; +} + +function slot(record: Record, key: string): Slot { + return Object.hasOwn(record, key) ? record[key] : ABSENT; +} + +/** Deep equality in which key order does not count. */ +function same(a: Slot, b: Slot): boolean { + if (a === b) return true; + if (Array.isArray(a) && Array.isArray(b)) { + return a.length === b.length && a.every((item, i) => same(item, b[i])); + } + if (!isRecord(a) || !isRecord(b)) return false; + const keys = Object.keys(a); + return ( + keys.length === Object.keys(b).length && + keys.every((key) => Object.hasOwn(b, key) && same(a[key], b[key])) + ); +} diff --git a/packages/plugin/src/sync/merge-model.ts b/packages/plugin/src/features/sync/hunks/merge-model.ts similarity index 54% rename from packages/plugin/src/sync/merge-model.ts rename to packages/plugin/src/features/sync/hunks/merge-model.ts index 5d033f82..123f838f 100644 --- a/packages/plugin/src/sync/merge-model.ts +++ b/packages/plugin/src/features/sync/hunks/merge-model.ts @@ -1,4 +1,4 @@ -import { diffRanges, toLf } from "@/utils"; +import { diffRanges, toLf } from "@/core/utils"; import { anchoredHunks } from "./anchored-hunks"; import { DIFF_BUDGET } from "./hunks"; @@ -14,11 +14,8 @@ export type EMergeSide = "local" | "remote"; /** How one side of a change stands: not a change there, still to decide, taken, or dismissed. */ export type ESideStatus = "none" | "open" | "applied" | "ignored"; export type SideStatus = Readonly>; -export type StatusPatch = Partial>; /** The lines each side has contributed to the Result. */ export type Taken = Partial>>; -/** `null` withdraws a side's contribution. */ -export type TakenPatch = Partial>; /** One region where a side differs from the base; the IntelliJ "TextMergeChange". */ export interface MergeChange { @@ -41,21 +38,6 @@ export interface MergeSession { remoteLines: string[]; } -export interface EditPlan { - from: number; - to: number; - insert: string; - /** Where the change sits once the edit is in; absent when mapping alone places it. */ - result?: Span; - taken: TakenPatch; -} - -/** The subset of a CodeMirror `Text` the model needs, so it stays free of the editor. */ -export interface LineDoc { - length: number; - lineAt(pos: number): { from: number; to: number }; -} - interface MergeRegion { base: LineRange; local: LineRange; @@ -69,19 +51,8 @@ interface SideHunk { lines: LineRange; } -interface LineEdit { - from: number; - to: number; - insert: string; - result: Span; -} - export const MERGE_SIDES: readonly EMergeSide[] = ["local", "remote"]; -function otherSide(side: EMergeSide): EMergeSide { - return side === "local" ? "remote" : "local"; -} - export function isResolved(change: MergeChange): boolean { return MERGE_SIDES.every((side) => change.status[side] !== "open"); } @@ -90,21 +61,6 @@ export function countUnresolved(changes: readonly MergeChange[]): number { return changes.filter((change) => !isResolved(change)).length; } -export function sameStatus(a: SideStatus, b: SideStatus | undefined): boolean { - return b !== undefined && MERGE_SIDES.every((side) => a[side] === b[side]); -} - -export function patchTaken(taken: Taken, patch: TakenPatch): Taken { - const next: Partial> = { ...taken }; - for (const side of MERGE_SIDES) { - const span = patch[side]; - if (span === undefined) continue; - if (span === null) delete next[side]; - else next[side] = span; - } - return next; -} - /** * Groups both sides' hunks by overlapping-or-touching base lines, as diff3 does; an unchanged side still owns * the base-equal lines of the region. @@ -247,178 +203,6 @@ export function buildMergeSession( return { text, changes, baseLines, localLines, remoteLines }; } -/** Widens a span to whole lines: from a line start to the next line start or the doc end. */ -export function snapToLines(doc: LineDoc, span: Span): Span { - if (span.to <= span.from) { - // An empty span sits before a line, or after the last line of a file without a final newline; - // mid-line it moves to the next line. - const line = doc.lineAt(span.from); - const at = - span.from === line.from || span.from === doc.length - ? span.from - : Math.min(line.to + 1, doc.length); - return { from: at, to: at }; - } - const from = doc.lineAt(span.from).from; - const endLine = doc.lineAt(span.to); - const to = - endLine.from === span.to ? span.to : Math.min(endLine.to + 1, doc.length); - return { from, to }; -} - -/** A conflict whose other side is already in gets this side appended below it, so click order is line order. */ -export function applyPlan( - doc: LineDoc, - change: MergeChange, - side: EMergeSide, - sideLines: readonly string[], -): EditPlan { - const span = snapToLines(doc, change.result); - const otherSideName = otherSide(side); - const otherApplied = change.status[otherSideName] === "applied"; - - if (!change.conflict && otherApplied) { - const otherPart = change.taken[otherSideName]; - if (otherPart) { - return { - from: otherPart.from, - to: otherPart.from, - insert: "", - result: change.result, - taken: { [side]: otherPart }, - }; - } - } - - const append = otherApplied; - if (append && sideLines.length === 0) { - return { - from: span.to, - to: span.to, - insert: "", - result: span, - taken: { [side]: { from: span.to, to: span.to } }, - }; - } - const edit = replaceLines( - doc, - append ? { from: span.to, to: span.to } : span, - sideLines, - change.endsAtEof, - append || emptyResult(change), - ); - return { - ...edit, - // An emptied span at the end of the file sits before the line break the new lines bring, not at a - // line start: they are the whole result, or reverting would snap it onto the line above. - result: - append && doc.lineAt(span.from).from === span.from - ? { from: span.from, to: edit.result.to } - : edit.result, - taken: { [side]: edit.result }, - }; -} - -/** With the other side still in, only this side's lines go; otherwise the base lines return. */ -export function revertPlan( - doc: LineDoc, - change: MergeChange, - side: EMergeSide, - baseLines: readonly string[], -): EditPlan { - const part = change.taken[side]; - const otherSideName = otherSide(side); - const otherApplied = change.status[otherSideName] === "applied"; - - if (!change.conflict && otherApplied) { - const otherPart = change.taken[otherSideName]; - if ( - part && - otherPart && - part.from === otherPart.from && - part.to === otherPart.to - ) { - return { - from: part.from, - to: part.from, - insert: "", - taken: { [side]: null }, - }; - } - } - - if (part && otherApplied) { - if (part.from === part.to && change[side][0] === change[side][1]) - return { - from: part.from, - to: part.from, - insert: "", - taken: { [side]: null }, - }; - const edit = replaceLines( - doc, - snapToLines(doc, part), - [], - change.endsAtEof, - ); - return { - from: edit.from, - to: edit.to, - insert: "", - taken: { [side]: null }, - }; - } - const edit = replaceLines( - doc, - snapToLines(doc, change.result), - baseLines, - change.endsAtEof, - emptyResult(change), - ); - return { ...edit, taken: { [side]: null } }; -} - -function replaceLines( - doc: LineDoc, - target: Span, - lines: readonly string[], - endsAtEof: boolean, - afterLastLine = false, -): LineEdit { - let { from } = target; - const { to } = target; - const atEnd = endsAtEof && to === doc.length; - let insert = ""; - let prefix = ""; - if (lines.length === 0) { - // The final empty line is significant too: removing it removes the final newline. - if (atEnd && from > 0 && (from < to || doc.lineAt(from).from === from)) - from -= 1; - } else { - if ( - from === to && - ((atEnd && afterLastLine) || doc.lineAt(from).from !== from) - ) - prefix = "\n"; - insert = `${prefix}${lines.join("\n")}${atEnd ? "" : "\n"}`; - } - return { - from, - to, - insert, - result: { from: from + prefix.length, to: from + insert.length }, - }; -} - -function emptyResult(change: MergeChange): boolean { - const applied = MERGE_SIDES.filter( - (side) => change.status[side] === "applied", - ); - return applied.length > 0 - ? applied.every((side) => change[side][0] === change[side][1]) - : change.base[0] === change.base[1]; -} - function sideHunks( base: string[], lines: string[], diff --git a/packages/plugin/src/sync/projection.ts b/packages/plugin/src/features/sync/hunks/projection.ts similarity index 94% rename from packages/plugin/src/sync/projection.ts rename to packages/plugin/src/features/sync/hunks/projection.ts index fb07e0c4..8fd7bd46 100644 --- a/packages/plugin/src/sync/projection.ts +++ b/packages/plugin/src/features/sync/hunks/projection.ts @@ -1,7 +1,6 @@ import type { DataAdapter } from "obsidian"; -import { type EncryptionKey, sha256Hex } from "@/crypto"; -import type { ObjectStorage } from "@/storage/types"; -import { FORCE_DIFF_MAX_BYTES, HUNK_TEXT_MAX_BYTES } from "@/sync/constants"; +import { type EncryptionKey, sha256Hex } from "@/core/crypto"; +import type { ObjectStorage } from "@/features/storage"; import { bytesToText, hasBinaryBytes, @@ -10,16 +9,18 @@ import { loadLocalBytes, loadRemoteBytes, textToBytes, -} from "./content"; -import { type ComputedHunks, computeHunks } from "./hunks"; -import { sidesOf } from "./moves"; +} from "../changes/content"; +import { sidesOf } from "../changes/moves"; +import { FORCE_DIFF_MAX_BYTES, HUNK_TEXT_MAX_BYTES } from "../constants"; import type { Conflict, EChangeType, FileChange, Manifest, Move, -} from "./types"; +} from "../types"; +import { trimOldest } from "./bounded-map"; +import { type ComputedHunks, computeHunks } from "./hunks"; export const EDiffDirection = { Local: "local", @@ -289,6 +290,8 @@ export type HistoryDiffSide = export interface HistoryDiffRequest { path: string; + /** Whose space holds the version, when it lands elsewhere (a restore-to); `path` by default. */ + source?: string; /** Removed lines come from here. */ left: HistoryDiffSide; /** Added lines come from here. */ @@ -345,14 +348,7 @@ async function loadVersion( const bytes = await loadRemoteBytes(deps, hash); if (!bytes) return null; cache.set(hash, bytes); - let total = 0; - for (const held of cache.values()) total += held.length; - for (const [oldest, held] of cache) { - // The newest stays even alone over the cap: the open diff refreshes it. - if (total <= VERSION_CACHE_MAX_BYTES || cache.size === 1) break; - cache.delete(oldest); - total -= held.length; - } + trimOldest(cache, VERSION_CACHE_MAX_BYTES, (held) => held.length); return bytes; } diff --git a/packages/plugin/src/sync/authors.ts b/packages/plugin/src/features/sync/identity/authors.ts similarity index 99% rename from packages/plugin/src/sync/authors.ts rename to packages/plugin/src/features/sync/identity/authors.ts index b41079de..0567314d 100644 --- a/packages/plugin/src/sync/authors.ts +++ b/packages/plugin/src/features/sync/identity/authors.ts @@ -1,10 +1,10 @@ -import { defaultDeviceName } from "./device"; import type { Manifest, ManifestAuthor, ManifestEntry, SessionState, -} from "./types"; +} from "../types"; +import { defaultDeviceName } from "./device"; export interface LastEdit extends ManifestAuthor { /** The file's mtime as published. */ diff --git a/packages/plugin/src/core/device-name.ts b/packages/plugin/src/features/sync/identity/device-name.ts similarity index 81% rename from packages/plugin/src/core/device-name.ts rename to packages/plugin/src/features/sync/identity/device-name.ts index 7b89ed9a..c884efb6 100644 --- a/packages/plugin/src/core/device-name.ts +++ b/packages/plugin/src/features/sync/identity/device-name.ts @@ -1,6 +1,5 @@ -import { defaultDeviceName } from "@/sync/device"; - -import type { StatePersister } from "./state-persister"; +import type { StatePersister } from "../recovery/state-persister"; +import { defaultDeviceName } from "./device"; /** The device name lives in local state only - it is never synced. */ export class DeviceName { diff --git a/packages/plugin/src/sync/device.ts b/packages/plugin/src/features/sync/identity/device.ts similarity index 100% rename from packages/plugin/src/sync/device.ts rename to packages/plugin/src/features/sync/identity/device.ts diff --git a/packages/plugin/src/features/sync/identity/vault-mismatch.ts b/packages/plugin/src/features/sync/identity/vault-mismatch.ts new file mode 100644 index 00000000..84dba566 --- /dev/null +++ b/packages/plugin/src/features/sync/identity/vault-mismatch.ts @@ -0,0 +1,8 @@ +const MISMATCH = "Remote vault id does not match local"; + +export const VAULT_MISMATCH_MESSAGE = `${MISMATCH}. Refusing to sync to a different vault.`; + +/** The refusal reaches consumers as snapshot text, so this is the only place that reads it. */ +export function isVaultMismatch(error: string | null | undefined): boolean { + return error?.includes(MISMATCH) ?? false; +} diff --git a/packages/plugin/src/features/sync/index.ts b/packages/plugin/src/features/sync/index.ts new file mode 100644 index 00000000..130e91ac --- /dev/null +++ b/packages/plugin/src/features/sync/index.ts @@ -0,0 +1,165 @@ +export { registerScheduler } from "./automation/scheduler"; +export { + bytesToText, + clearRemoteTextCache, + hasKnownBinaryExtension, + textToBytes, +} from "./changes/content"; +export { movesByPath } from "./changes/moves"; +export { HUNK_TEXT_MAX_BYTES } from "./constants"; +export { + EConflictStrategy, + type LocalOpener, + type LocalSession, + type SessionFiles, + SyncController, + type SyncOperationResult, + type SyncStatusSnapshot, + splitSpaceErrors, +} from "./controller"; +export type { CompareResult, EngineDependencies } from "./engine"; +export { composeChanges } from "./history/changes"; +export { + countsBefore, + keepSize, + RESOLUTIONS, +} from "./history/model/periods"; +export type { Activity, Resolution } from "./history/model/types"; +export type { VaultRestorePlan } from "./history/restore-vault"; +export type { + Dating, + DeletedFile, + DeletedFilesResult, + FileVersion, + SnapshotChanges, + SnapshotListResult, + SnapshotSummary, +} from "./history/types"; +export type { HistorySectionHost, SyncHost } from "./host"; +export { + computeHunks, + DIFF_BUDGET, + type HunkSegment, + type HunkSelection, + hunkSegments, + type LineRange, + type SyncHunk, +} from "./hunks/hunks"; +export { + buildMergeSession, + countUnresolved, + type EMergeSide, + type ESideStatus, + isResolved, + MERGE_SIDES, + type MergeChange, + type SideStatus, + type Span, + sameLines, + type Taken, + threeWayRegions, + toLines, +} from "./hunks/merge-model"; +export { + EDiffDirection, + type FileDiffModel, + type HistoryDiffRequest, + type HistoryVersionRef, +} from "./hunks/projection"; +export { defaultDeviceName, deviceLabel } from "./identity/device"; +export { DeviceName } from "./identity/device-name"; +export { isVaultMismatch } from "./identity/vault-mismatch"; +export { + type IncomingText, + isNewerMark, + type LiveNotes, + type LiveTake, +} from "./live-notes"; +export { restoreCutShort } from "./recovery/cut-short"; +export { WriteJournal } from "./recovery/journal"; +export { StatePersister } from "./recovery/state-persister"; +export { PassphraseRotatedError } from "./remote/keyfile"; +export { fetchRemoteManifest } from "./remote/manifest"; +export { PassphraseManager } from "./remote/passphrase-manager"; +export { + insideOf, + isUnder, + nestedRoots, + type Space, + spaceOf, + VAULT_SPACE, + vaultPathOf, +} from "./remote/space"; +export { canPullAll, canPushAll } from "./runtime/sync-gates"; +export { + categoryField, + configurationScopeSection, + pluginLevelRows, +} from "./scope/configuration-scope-section"; +export { exclusionsSection } from "./scope/exclusions-section"; +export { + createIgnoreMatcher, + type IgnoreMatcher, + ignoreNoteOf, + isIgnoreNote, + loadSharedIgnoreMatcher, +} from "./scope/ignore"; +export { + type IgnoreStateHandle, + registerIgnoreState, +} from "./scope/ignore-state"; +export { createScopePolicy } from "./scope/scope"; +export { projectSession } from "./session-state"; +export { canSync, isGuest } from "./settings"; +export { + type Conflict, + type DiffResult, + EChangeType, + type FileChange, + type LiveMark, + type Manifest, + type ManifestAuthor, + type ManifestEntry, + type Move, + type SkippedFile, +} from "./types"; +export { automationSection } from "./ui/automation-section"; +export { type ChangeAction, changeActionOf } from "./ui/change-action"; +export { encryptionSection } from "./ui/encryption-section"; +export { renderActivityCalendar } from "./ui/history/activity-calendar"; +export { + type ActivityCalendar, + buildCalendar, + type CalendarDay, + RESOLUTION_TEXT, +} from "./ui/history/calendar"; +export { + historySection, + historyValue, +} from "./ui/history/history-section"; +export { + addIgnoreMenuItem, + carryVaultIgnores, + stopIgnoring, +} from "./ui/ignore-action"; +export { + deepCleanOrphanedObjects, + resetRemoteStorage, + verifyRemoteIntegrity, +} from "./ui/maintenance-actions"; +export { maintenanceSection } from "./ui/maintenance-section"; +export { + confirmAdoptNewVault, + confirmBatchResolve, + confirmRevert, +} from "./ui/modals"; +export { addPushMenuItem, pushScope, scopedPaths } from "./ui/push-action"; +export { skippedFiles, skippedText } from "./ui/skipped"; +export { + conflictsFirst, + heldByConflicts, + runCompare, + runPullAll, + runPushAll, +} from "./ui/sync-actions"; +export { registerVaultAdoptionPrompt } from "./ui/vault-adoption"; diff --git a/packages/plugin/src/sync/live-notes.ts b/packages/plugin/src/features/sync/live-notes.ts similarity index 97% rename from packages/plugin/src/sync/live-notes.ts rename to packages/plugin/src/features/sync/live-notes.ts index 445633cd..ffb7b01d 100644 --- a/packages/plugin/src/sync/live-notes.ts +++ b/packages/plugin/src/features/sync/live-notes.ts @@ -3,17 +3,17 @@ * room snapshot; a note with an open room is never written. */ -import { entryAt } from "@/shared"; - import { bytesToText, loadBaselineText, + loadLocalCopy, loadRemoteBytes, loadRemoteText, untouchedSince, type WriteOptions, writeFetched, -} from "./content"; +} from "./changes/content"; +import { entryAt } from "./changes/records"; import type { CompareResult, EngineDependencies } from "./engine"; import type { LiveMark, ManifestEntry } from "./types"; @@ -152,7 +152,9 @@ export async function writeIncoming( entry: ManifestEntry, options: Omit = {}, ): Promise { - const bytes = await loadRemoteBytes(deps, entry.hash, entry.size); + const bytes = await loadRemoteBytes(deps, entry.hash, entry.size, () => + loadLocalCopy(deps.adapter, path, entry.size), + ); if (!bytes) throw new Error(`Missing remote object for ${path}`); const { live: notes } = deps; const { live } = entry; diff --git a/packages/plugin/src/sync/operations/config-reset.ts b/packages/plugin/src/features/sync/operations/config-reset.ts similarity index 78% rename from packages/plugin/src/sync/operations/config-reset.ts rename to packages/plugin/src/features/sync/operations/config-reset.ts index 332d43a4..ddd84298 100644 --- a/packages/plugin/src/sync/operations/config-reset.ts +++ b/packages/plugin/src/features/sync/operations/config-reset.ts @@ -1,14 +1,14 @@ -import { ESyncLogOperation } from "@/logs/store"; -import type { SettingsSyncCategories } from "@/settings/model"; -import { reconcileBaselineResetGenerations } from "@/sync/config-reset"; -import { MANIFEST_VERSION } from "@/sync/constants"; +import { ESyncLogOperation } from "@/core/logs"; +import type { SettingsSyncCategories } from "@/core/settings"; import { type CompareResult, compare, type EngineDependencies, -} from "@/sync/engine"; -import { publishManifestWithHistory } from "@/sync/history"; -import { buildManifest } from "@/sync/manifest"; +} from "../engine"; +import { untrackedDir } from "../history/changes"; +import { publishManifestWithHistory } from "../history/publish"; +import { reconcileBaselineResetGenerations } from "../remote/config-reset"; +import { buildManifest } from "../remote/manifest"; import type { OperationContext } from "./types"; export async function runCategoryResetFlow( @@ -42,8 +42,6 @@ export async function runCategoryResetFlow( remote, { files, emptyFolders: folders }, ); - // Older clients must refuse a reset instead of propagating it as local deletions. - manifest.version = MANIFEST_VERSION; const categoryKey = `${deps.scope.configDir}/${category}`; manifest.resetGenerations = { ...remote.resetGenerations, @@ -58,6 +56,7 @@ export async function runCategoryResetFlow( remote, deps.history, deps.state.baseline, + untrackedDir(deps), ); const state = { ...deps.state, diff --git a/packages/plugin/src/sync/operations/flows.ts b/packages/plugin/src/features/sync/operations/flows.ts similarity index 87% rename from packages/plugin/src/sync/operations/flows.ts rename to packages/plugin/src/features/sync/operations/flows.ts index 19efc748..56147cae 100644 --- a/packages/plugin/src/sync/operations/flows.ts +++ b/packages/plugin/src/features/sync/operations/flows.ts @@ -1,12 +1,12 @@ -import { ESyncLogOperation } from "@/logs/store"; -import { resetSessionState } from "@/sync/baseline"; -import { LOG_PATH_LIMIT } from "@/sync/constants"; +import { ESyncLogOperation } from "@/core/logs"; +import { LOG_PATH_LIMIT } from "../constants"; import { type CompareResult, compare, type EngineDependencies, -} from "@/sync/engine"; -import { resetRemoteStorage as resetStorageObjects } from "@/sync/reset"; +} from "../engine"; +import { resetSessionState } from "../remote/baseline"; +import { resetRemoteStorage as resetStorageObjects } from "../remote/reset"; import type { OperationContext } from "./types"; export interface FlowResult { diff --git a/packages/plugin/src/sync/operations/hunks.ts b/packages/plugin/src/features/sync/operations/hunks.ts similarity index 77% rename from packages/plugin/src/sync/operations/hunks.ts rename to packages/plugin/src/features/sync/operations/hunks.ts index 7fa7d7d4..c4a45e33 100644 --- a/packages/plugin/src/sync/operations/hunks.ts +++ b/packages/plugin/src/features/sync/operations/hunks.ts @@ -1,16 +1,13 @@ -import { ESyncLogOperation } from "@/logs/store"; -import { - advanceBaselineForPaths, - buildSessionState, - mergeWrittenIntoCache, -} from "@/sync/baseline"; -import { textToBytes, writeLocalFile } from "@/sync/content"; +import { ESyncLogOperation } from "@/core/logs"; +import { withEolOf } from "@/core/utils"; +import { trashPath } from "@/core/vault"; +import { textToBytes, writeLocalFile } from "../changes/content"; import { type CompareResult, type EngineDependencies, publishFileMap, pushSingleFile, -} from "@/sync/engine"; +} from "../engine"; import { applyHunks, complementSelection, @@ -18,10 +15,9 @@ import { type HunkSelection, isFullSelection, selectionSize, -} from "@/sync/hunks"; -import type { Manifest, ManifestEntry } from "@/sync/types"; -import { withEolOf } from "@/utils"; -import { trashPath } from "@/vault/io"; +} from "../hunks/hunks"; +import { mergeWrittenIntoCache, stateAfterWrites } from "../remote/baseline"; +import type { Manifest, ManifestEntry } from "../types"; import { assertSidesUnchanged, EHunkPair, @@ -85,13 +81,9 @@ export const localHunksOp: Operation = async ( } } // Only a revert wrote the file; otherwise the scanned cache already holds it. - const hashCache = - reverting > 0 - ? mergeWrittenIntoCache( - new Map([[path, localEntry]]), - result.updatedCache, - ) - : result.updatedCache; + const written = new Map( + reverting > 0 ? [[path, localEntry]] : [], + ); let manifest = result.remote; if (pushing > 0) { @@ -101,18 +93,13 @@ export const localHunksOp: Operation = async ( manifest = deleted ? await publishWithoutPath(deps, result, path) : await pushSingleFile(deps, result, path, textToBytes(merged)); - const baseline = advanceBaselineForPaths( - deps.state.baseline, - manifest, - new Set([path]), - result.snapshot.emptyFolders, - deps.scope, + await ctx.persistState( + stateAfterWrites(deps, result, manifest, new Set([path]), written), ); - await ctx.persistState(buildSessionState(deps.state, baseline, hashCache)); } else { // A revert moves no baseline; only the hash cache learns the written file. - const fresh = ctx.getFreshState(); - await ctx.persistState({ ...fresh, hashCache }); + const hashCache = mergeWrittenIntoCache(written, result.updatedCache); + await ctx.persistState({ ...ctx.getFreshState(), hashCache }); } const parts = [ pushing > 0 ? `pushed ${pushing}` : "", @@ -155,22 +142,18 @@ export const pullHunksOp: Operation = async ( await assertSidesUnchanged(sides, args.expected); const { hunks } = computeHunks(sides.left, sides.right); const merged = withEolOf(sides.left, applyHunks(sides.left, hunks, selected)); - const localEntry = await writeLocalFile(deps, path, textToBytes(merged)); + const written = new Map([ + [path, await writeLocalFile(deps, path, textToBytes(merged))], + ]); // Only a pull taking every segment acknowledges the remote; a partial pull's baseline would hide // left-behind segments and let the next push overwrite them. - const baseline = advanceBaselineForPaths( - deps.state.baseline, - result.remote, - isFullSelection(hunks, selected) ? new Set([path]) : new Set(), - result.snapshot.emptyFolders, - deps.scope, + const acknowledged = isFullSelection(hunks, selected) + ? new Set([path]) + : new Set(); + await ctx.persistState( + stateAfterWrites(deps, result, result.remote, acknowledged, written), ); - const hashCache = mergeWrittenIntoCache( - new Map([[path, localEntry]]), - result.updatedCache, - ); - await ctx.persistState(buildSessionState(deps.state, baseline, hashCache)); await ctx.logInfo( ESyncLogOperation.Pull, `Pulled ${pulling} hunk(s) of ${path}.`, @@ -178,7 +161,7 @@ export const pullHunksOp: Operation = async ( return { newRemote: result.remote, touchedPaths: new Set([path]), - localEntries: new Map([[path, localEntry]]), + localEntries: written, }; }; diff --git a/packages/plugin/src/sync/operations/pull.ts b/packages/plugin/src/features/sync/operations/pull.ts similarity index 86% rename from packages/plugin/src/sync/operations/pull.ts rename to packages/plugin/src/features/sync/operations/pull.ts index 277dd88f..3d6acfb1 100644 --- a/packages/plugin/src/sync/operations/pull.ts +++ b/packages/plugin/src/features/sync/operations/pull.ts @@ -1,8 +1,9 @@ -import { ESyncLogOperation } from "@/logs/store"; -import { entryAt, formatBytes, sumBytes } from "@/shared"; -import { buildSessionState, mergeWrittenIntoCache } from "@/sync/baseline"; -import { LOG_PATH_LIMIT } from "@/sync/constants"; -import { pullPaths } from "@/sync/pull"; +import { ESyncLogOperation } from "@/core/logs"; +import { formatBytes, sumBytes } from "@/core/shared"; +import { pullPaths } from "../apply/pull"; +import { entryAt } from "../changes/records"; +import { LOG_PATH_LIMIT } from "../constants"; +import { buildSessionState, mergeWrittenIntoCache } from "../remote/baseline"; import type { Operation } from "./types"; export const pullPathsOp: Operation> = async ( diff --git a/packages/plugin/src/sync/operations/push.ts b/packages/plugin/src/features/sync/operations/push.ts similarity index 84% rename from packages/plugin/src/sync/operations/push.ts rename to packages/plugin/src/features/sync/operations/push.ts index f81a9d0a..d20cf3f1 100644 --- a/packages/plugin/src/sync/operations/push.ts +++ b/packages/plugin/src/features/sync/operations/push.ts @@ -1,10 +1,10 @@ -import { ESyncLogOperation } from "@/logs/store"; -import { formatBytes, sumBytes } from "@/shared"; -import { advanceSessionAfterPush } from "@/sync/baseline"; -import { LOG_PATH_LIMIT } from "@/sync/constants"; -import { pushPaths } from "@/sync/engine"; -import { liveMarks } from "@/sync/live-notes"; -import { withMoves } from "@/sync/moves"; +import { ESyncLogOperation } from "@/core/logs"; +import { formatBytes, sumBytes } from "@/core/shared"; +import { withMoves } from "../changes/moves"; +import { LOG_PATH_LIMIT } from "../constants"; +import { pushPaths } from "../engine"; +import { liveMarks } from "../live-notes"; +import { advanceSessionAfterPush } from "../remote/baseline"; import type { Operation } from "./types"; export const pushPathsOp: Operation> = async ( diff --git a/packages/plugin/src/sync/operations/resolve.ts b/packages/plugin/src/features/sync/operations/resolve.ts similarity index 81% rename from packages/plugin/src/sync/operations/resolve.ts rename to packages/plugin/src/features/sync/operations/resolve.ts index bb97ec1d..b765773e 100644 --- a/packages/plugin/src/sync/operations/resolve.ts +++ b/packages/plugin/src/features/sync/operations/resolve.ts @@ -1,33 +1,30 @@ -import { DEFAULT_CONCURRENCY } from "@/constants"; -import { sceneOfBytes } from "@/drawing"; -import { ESyncLogOperation } from "@/logs/store"; -import { entryAt } from "@/shared"; -import { - advanceBaselineForPaths, - buildSessionState, - mergeWrittenIntoCache, -} from "@/sync/baseline"; -import { freeConflictCopyPath } from "@/sync/conflict-copy"; -import { LOG_PATH_LIMIT } from "@/sync/constants"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { sceneOfBytes } from "@/core/drawing"; +import { ESyncLogOperation } from "@/core/logs"; +import { asError } from "@/core/shared"; +import { trashPath, unchangedSince } from "@/core/vault"; +import { freeConflictCopyPath } from "../apply/conflict-copy"; import { loadLocalBytes, loadRemoteBytes, textToBytes, withLocalMtime, writeLocalFile, -} from "@/sync/content"; -import { baseStep } from "@/sync/cut-short"; +} from "../changes/content"; +import { runWithFileConcurrency } from "../changes/file-concurrency"; +import { entryAt } from "../changes/records"; +import { LOG_PATH_LIMIT } from "../constants"; import { type CompareResult, type EngineDependencies, knownRemoteHashes, publishFileMap, storeObject, -} from "@/sync/engine"; -import { coldSince, settleLive, writeIncoming } from "@/sync/live-notes"; -import type { ManifestEntry } from "@/sync/types"; -import { runWithFileConcurrency } from "@/utils"; -import { trashPath, unchangedSince } from "@/vault/io"; +} from "../engine"; +import { coldSince, settleLive, writeIncoming } from "../live-notes"; +import { baseStep } from "../recovery/cut-short"; +import { stateAfterWrites } from "../remote/baseline"; +import type { ManifestEntry } from "../types"; import type { Operation, OperationContext, OperationOutcome } from "./types"; const EDITED_SINCE = @@ -84,18 +81,13 @@ export const batchAcceptRemoteOp: Operation> = async ( if (conflictPaths.length === 0) { throw new Error(held.length > 0 ? LIVE_HELD : EDITED_SINCE); } - const baseline = advanceBaselineForPaths( - deps.state.baseline, - remote, - new Set(conflictPaths), - result.snapshot.emptyFolders, - deps.scope, - ); await ctx.persistState( - buildSessionState( - deps.state, - baseline, - mergeWrittenIntoCache(localEntries, result.updatedCache), + stateAfterWrites( + deps, + result, + remote, + new Set(conflictPaths), + localEntries, ), ); await deps.journal?.acknowledge(deps.space); @@ -134,7 +126,12 @@ export const batchKeepLocalOp: Operation> = async ( return null; } const entry = await withLocalMtime(deps.adapter, path, { - hash: await storeObject(deps, known, bytes), + hash: await storeObject( + deps, + known, + bytes, + entryAt(result.remote?.files ?? {}, path), + ), size: bytes.length, kind: deps.scope.classify(path), scene: await sceneOfBytes(path, bytes), @@ -144,18 +141,13 @@ export const batchKeepLocalOp: Operation> = async ( }, ); const manifest = await publishFileMap(deps, result, files); - const baseline = advanceBaselineForPaths( - deps.state.baseline, - manifest, - new Set(conflictPaths), - result.snapshot.emptyFolders, - deps.scope, - ); await ctx.persistState( - buildSessionState( - deps.state, - baseline, - mergeWrittenIntoCache(localEntries, result.updatedCache), + stateAfterWrites( + deps, + result, + manifest, + new Set(conflictPaths), + localEntries, ), ); await ctx.logInfo( @@ -188,6 +180,17 @@ export const keepBothConflictOp: Operation = async ( `"${path}" was deleted remotely: there is no version to keep beside it.`, ); } + const copyPath = await freeConflictCopyPath( + deps.adapter, + path, + result.remote?.deviceName, + ); + // Plugin settings without code, or an ignore rule, can leave the copy's name out: it would never publish. + if (!deps.scope.includes(copyPath)) { + throw new Error( + `Cannot keep both versions of "${path}": a copy beside it would not sync. Use Keep local, Accept remote or Merge.`, + ); + } const bytes = await loadRemoteBytes( { storage: deps.storage, key: deps.key }, conflict.remoteHash, @@ -197,11 +200,6 @@ export const keepBothConflictOp: Operation = async ( `Cannot keep the remote version of "${path}": its object is missing`, ); } - const copyPath = await freeConflictCopyPath( - deps.adapter, - path, - result.remote?.deviceName, - ); await writeLocalFile(deps, copyPath, bytes); await ctx.logInfo( ESyncLogOperation.Push, @@ -231,6 +229,16 @@ export const saveMergedOp: Operation = async ( "This file changed since the merge was opened, so saving it would overwrite that change. Reopen the merge.", ); } + // Published at once: broken JSON would reach every device's plugin or canvas. + if (/\.(json|canvas)$/.test(path)) { + try { + JSON.parse(content); + } catch (err) { + throw new Error( + `The merged result is not valid JSON, so it was not saved: ${asError(err).message}`, + ); + } + } await writeLocalFile(deps, path, textToBytes(content)); return batchKeepLocalOp(deps, result, new Set([path]), ctx); }; diff --git a/packages/plugin/src/sync/operations/revert.ts b/packages/plugin/src/features/sync/operations/revert.ts similarity index 87% rename from packages/plugin/src/sync/operations/revert.ts rename to packages/plugin/src/features/sync/operations/revert.ts index 6e5d56a3..5e056838 100644 --- a/packages/plugin/src/sync/operations/revert.ts +++ b/packages/plugin/src/features/sync/operations/revert.ts @@ -1,13 +1,14 @@ -import { DEFAULT_CONCURRENCY } from "@/constants"; -import { ESyncLogOperation } from "@/logs/store"; -import { mergeWrittenIntoCache } from "@/sync/baseline"; -import { LOG_PATH_LIMIT } from "@/sync/constants"; -import { coldSince, writeIncoming } from "@/sync/live-notes"; -import { withMoves } from "@/sync/moves"; -import { renameLocal } from "@/sync/pull-moves"; -import { EChangeType, type ManifestEntry } from "@/sync/types"; -import { runWithConcurrency, runWithFileConcurrency } from "@/utils"; -import { trashPath } from "@/vault/io"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { ESyncLogOperation } from "@/core/logs"; +import { runWithConcurrency } from "@/core/utils"; +import { trashPath } from "@/core/vault"; +import { renameLocal } from "../apply/pull-moves"; +import { runWithFileConcurrency } from "../changes/file-concurrency"; +import { withMoves } from "../changes/moves"; +import { LOG_PATH_LIMIT } from "../constants"; +import { coldSince, writeIncoming } from "../live-notes"; +import { mergeWrittenIntoCache } from "../remote/baseline"; +import { EChangeType, type ManifestEntry } from "../types"; import type { Operation } from "./types"; const LIVE_HELD = diff --git a/packages/plugin/src/sync/operations/text-loaders.ts b/packages/plugin/src/features/sync/operations/text-loaders.ts similarity index 92% rename from packages/plugin/src/sync/operations/text-loaders.ts rename to packages/plugin/src/features/sync/operations/text-loaders.ts index 1863658d..2625a016 100644 --- a/packages/plugin/src/sync/operations/text-loaders.ts +++ b/packages/plugin/src/features/sync/operations/text-loaders.ts @@ -1,6 +1,4 @@ -import { sha256Hex } from "@/crypto"; -import { reconcileBaselineResetGenerations } from "@/sync/config-reset"; -import { HUNK_TEXT_MAX_BYTES } from "@/sync/constants"; +import { sha256Hex } from "@/core/crypto"; import { bytesToText, hasKnownBinaryExtension, @@ -8,9 +6,11 @@ import { loadLocalBytes, loadRemoteBytes, textToBytes, -} from "@/sync/content"; -import type { CompareResult, EngineDependencies } from "@/sync/engine"; -import type { Manifest } from "@/sync/types"; +} from "../changes/content"; +import { HUNK_TEXT_MAX_BYTES } from "../constants"; +import type { CompareResult, EngineDependencies } from "../engine"; +import { reconcileBaselineResetGenerations } from "../remote/config-reset"; +import type { Manifest } from "../types"; const NOT_TEXT = "Hunk-level actions are only supported for text files"; diff --git a/packages/plugin/src/sync/operations/types.ts b/packages/plugin/src/features/sync/operations/types.ts similarity index 84% rename from packages/plugin/src/sync/operations/types.ts rename to packages/plugin/src/features/sync/operations/types.ts index fb00a919..a8147105 100644 --- a/packages/plugin/src/sync/operations/types.ts +++ b/packages/plugin/src/features/sync/operations/types.ts @@ -1,6 +1,6 @@ -import type { ESyncLogOperation } from "@/logs/store"; -import type { CompareResult, EngineDependencies } from "@/sync/engine"; -import type { Manifest, ManifestEntry, SessionState } from "@/sync/types"; +import type { ESyncLogOperation } from "@/core/logs"; +import type { CompareResult, EngineDependencies } from "../engine"; +import type { Manifest, ManifestEntry, SessionState } from "../types"; export type SyncOperationResult = { ok: true } | { ok: false; error?: string }; diff --git a/packages/plugin/src/sync/cut-short.ts b/packages/plugin/src/features/sync/recovery/cut-short.ts similarity index 94% rename from packages/plugin/src/sync/cut-short.ts rename to packages/plugin/src/features/sync/recovery/cut-short.ts index f6ee469b..081ca4f9 100644 --- a/packages/plugin/src/sync/cut-short.ts +++ b/packages/plugin/src/features/sync/recovery/cut-short.ts @@ -4,21 +4,22 @@ */ import type { DataAdapter } from "obsidian"; -import { sha256Hex } from "@/crypto"; -import { sceneOfBytes } from "@/drawing"; -import { entryAt, reportWarning } from "@/shared"; -import { readBinary, writeBinary } from "@/vault/io"; -import { bytesToText, withLocalMtime } from "./content"; -import type { EngineDependencies } from "./engine"; -import type { BaseStep, Intent, WriteJournal } from "./journal"; -import { grewFrom } from "./live-notes"; -import type { Space } from "./space"; +import { sha256Hex } from "@/core/crypto"; +import { sceneOfBytes } from "@/core/drawing"; +import { reportWarning } from "@/core/shared"; +import { readBinary, writeBinary } from "@/core/vault"; +import { bytesToText, withLocalMtime } from "../changes/content"; +import { entryAt } from "../changes/records"; +import type { EngineDependencies } from "../engine"; +import { grewFrom } from "../live-notes"; +import type { Space } from "../remote/space"; import type { LocalSnapshot, Manifest, ManifestEntry, SessionState, -} from "./types"; +} from "../types"; +import type { BaseStep, Intent, WriteJournal } from "./journal"; const UNFINISHED = "An interrupted write is still being finished."; diff --git a/packages/plugin/src/sync/journal.ts b/packages/plugin/src/features/sync/recovery/journal.ts similarity index 96% rename from packages/plugin/src/sync/journal.ts rename to packages/plugin/src/features/sync/recovery/journal.ts index 859f3b6f..7105c223 100644 --- a/packages/plugin/src/sync/journal.ts +++ b/packages/plugin/src/features/sync/recovery/journal.ts @@ -5,12 +5,16 @@ */ import type { DataAdapter } from "obsidian"; -import { PLUGIN_ID } from "@/constants"; -import { randomId, sha256Hex } from "@/crypto"; -import { writeAtomic } from "@/vault/atomic-write"; -import { ensureParent, readBinary, writeBinary } from "@/vault/io"; -import { insideOf, type Space, spaceOf, vaultPathOf } from "./space"; -import type { LiveMark, ManifestEntry } from "./types"; +import { PLUGIN_ID } from "@/core/constants"; +import { randomId, sha256Hex } from "@/core/crypto"; +import { + ensureParent, + readBinary, + writeAtomic, + writeBinary, +} from "@/core/vault"; +import { insideOf, type Space, spaceOf, vaultPathOf } from "../remote/space"; +import type { LiveMark, ManifestEntry } from "../types"; /** What the baseline of the storage and vault it was claimed under takes once a download is finished on recovery. */ export interface BaseStep { diff --git a/packages/plugin/src/core/state-persister.ts b/packages/plugin/src/features/sync/recovery/state-persister.ts similarity index 98% rename from packages/plugin/src/core/state-persister.ts rename to packages/plugin/src/features/sync/recovery/state-persister.ts index 0babcc1e..0511dc98 100644 --- a/packages/plugin/src/core/state-persister.ts +++ b/packages/plugin/src/features/sync/recovery/state-persister.ts @@ -1,7 +1,7 @@ import type { DataAdapter } from "obsidian"; -import { carryHashes, type HashMove } from "@/sync/session-state"; -import { loadState, resetState, saveState, serializeState } from "@/sync/state"; -import type { LocalState } from "@/sync/types"; +import { carryHashes, type HashMove } from "../session-state"; +import { loadState, resetState, saveState, serializeState } from "../state"; +import type { LocalState } from "../types"; const PERSIST_STATE_DEBOUNCE_MS = 500; // Obsidian awaits each rename of a burst, so only a timer batches them into one cache copy. diff --git a/packages/plugin/src/sync/baseline.ts b/packages/plugin/src/features/sync/remote/baseline.ts similarity index 84% rename from packages/plugin/src/sync/baseline.ts rename to packages/plugin/src/features/sync/remote/baseline.ts index c93c8079..06459971 100644 --- a/packages/plugin/src/sync/baseline.ts +++ b/packages/plugin/src/features/sync/remote/baseline.ts @@ -1,16 +1,16 @@ -import { randomId } from "@/crypto"; -import { entryAt, sortedByPath } from "@/shared"; -import { diskRefuses } from "@/vault/io"; -import type { ScopePolicy } from "@/vault/scope"; -import { reconcileBaselineResetGenerations } from "./config-reset"; -import { isUnderUnreadableDir } from "./diff"; -import type { CompareResult } from "./engine"; +import { randomId } from "@/core/crypto"; +import { diskRefuses } from "@/core/vault"; +import { isUnderUnreadableDir } from "../changes/diff"; +import { entryAt, sortedByPath } from "../changes/records"; +import type { CompareResult, EngineDependencies } from "../engine"; +import type { ScopePolicy } from "../scope/scope"; import type { HashCacheEntry, Manifest, ManifestEntry, SessionState, -} from "./types"; +} from "../types"; +import { reconcileBaselineResetGenerations } from "./config-reset"; export function buildSessionState( previous: SessionState, @@ -49,6 +49,27 @@ export function advanceSessionAfterPush( }; } +/** The state once an operation acknowledged `paths` of `published` and wrote `written` to disk. */ +export function stateAfterWrites( + deps: Pick, + result: CompareResult, + published: Manifest, + paths: ReadonlySet, + written: ReadonlyMap, +): SessionState { + return buildSessionState( + deps.state, + advanceBaselineForPaths( + deps.state.baseline, + published, + paths, + result.snapshot.emptyFolders, + deps.scope, + ), + mergeWrittenIntoCache(written, result.updatedCache), + ); +} + /** * Only `paths` advance; `onDisk` holds the empty folders on disk afterwards. * Adopting the whole manifest would adopt never-pulled remote changes, which a push then overwrites. diff --git a/packages/plugin/src/sync/config-reset.ts b/packages/plugin/src/features/sync/remote/config-reset.ts similarity index 90% rename from packages/plugin/src/sync/config-reset.ts rename to packages/plugin/src/features/sync/remote/config-reset.ts index 758d5cde..914c0949 100644 --- a/packages/plugin/src/sync/config-reset.ts +++ b/packages/plugin/src/features/sync/remote/config-reset.ts @@ -1,5 +1,5 @@ -import type { ScopePolicy } from "@/vault/scope"; -import type { Manifest } from "./types"; +import type { ScopePolicy } from "../scope/scope"; +import type { Manifest } from "../types"; // A reset forgets synchronization history for the category, never its local files. export function reconcileBaselineResetGenerations( diff --git a/packages/plugin/src/sync/foreign.ts b/packages/plugin/src/features/sync/remote/foreign.ts similarity index 92% rename from packages/plugin/src/sync/foreign.ts rename to packages/plugin/src/features/sync/remote/foreign.ts index 1af15c0a..4e620c7b 100644 --- a/packages/plugin/src/sync/foreign.ts +++ b/packages/plugin/src/features/sync/remote/foreign.ts @@ -1,6 +1,6 @@ -import { entryAt } from "@/shared"; -import type { ScopePolicy } from "@/vault/scope"; -import type { Manifest, ManifestEntry } from "./types"; +import { entryAt } from "../changes/records"; +import type { ScopePolicy } from "../scope/scope"; +import type { Manifest, ManifestEntry } from "../types"; /** * Paths another space owns are frozen in a manifest; left there they hold the blobs of a folder this space no diff --git a/packages/plugin/src/sync/keyfile.ts b/packages/plugin/src/features/sync/remote/keyfile.ts similarity index 92% rename from packages/plugin/src/sync/keyfile.ts rename to packages/plugin/src/features/sync/remote/keyfile.ts index 75e560e3..f8fc9284 100644 --- a/packages/plugin/src/sync/keyfile.ts +++ b/packages/plugin/src/features/sync/remote/keyfile.ts @@ -1,18 +1,20 @@ import { decryptBytes, + deriveChunkIds, deriveKey, + deriveLiveKeys, type EncryptionKey, encryptBytes, importAesKey, + type LiveKeys, randomBytes, weakPassphrase, -} from "@/crypto"; -import { deriveLiveKeys, type LiveKeys } from "@/crypto/live-keys"; -import { errorMessage } from "@/shared"; -import type { ObjectStorage } from "@/storage/types"; -import { REMOTE_KEYFILE_KEY } from "@/sync/constants"; -import { base64ToBytes, bytesToBase64 } from "@/utils"; -import { loadOrCreateSalt } from "./session"; +} from "@/core/crypto"; +import { errorMessage } from "@/core/shared"; +import { base64ToBytes, bytesToBase64 } from "@/core/utils"; +import type { ObjectStorage } from "@/features/storage"; +import { REMOTE_KEYFILE_KEY } from "../constants"; +import { loadOrCreateSalt } from "./salt"; const KEYFILE_VERSION = 1; @@ -40,6 +42,7 @@ export interface Keyfile { export interface ResolvedContentKey { contentKey: EncryptionKey; liveKeys: LiveKeys; + chunkIds: CryptoKey; epoch: number; } @@ -147,11 +150,12 @@ async function resolvedFrom( raw: Uint8Array, epoch: number, ): Promise { - const [contentKey, liveKeys] = await Promise.all([ + const [contentKey, liveKeys, chunkIds] = await Promise.all([ importAesKey(raw), deriveLiveKeys(raw), + deriveChunkIds(raw), ]); - return { contentKey, liveKeys, epoch }; + return { contentKey, liveKeys, chunkIds, epoch }; } /** Re-wraps the data key under a new passphrase without re-encrypting content. Returns the new epoch. */ diff --git a/packages/plugin/src/sync/manifest.ts b/packages/plugin/src/features/sync/remote/manifest.ts similarity index 92% rename from packages/plugin/src/sync/manifest.ts rename to packages/plugin/src/features/sync/remote/manifest.ts index fabf17df..b73c94c1 100644 --- a/packages/plugin/src/sync/manifest.ts +++ b/packages/plugin/src/features/sync/remote/manifest.ts @@ -1,18 +1,15 @@ +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; import { decryptJson, type EncryptionKey, encryptJson, randomId, -} from "@/crypto"; -import type { ConditionalRead, ObjectStorage } from "@/storage/types"; -import { - MANIFEST_VERSION, - REMOTE_MANIFEST_KEY, - REMOTE_OBJECTS_PREFIX, -} from "@/sync/constants"; -import { defaultDeviceName } from "./device"; +} from "@/core/crypto"; +import type { ConditionalRead, ObjectStorage } from "@/features/storage"; +import { MANIFEST_VERSION } from "../constants"; +import { defaultDeviceName } from "../identity/device"; +import type { LocalSnapshot, Manifest } from "../types"; import { manifestToSpace, manifestToVault } from "./space-paths"; -import type { LocalSnapshot, Manifest } from "./types"; // A per-path baseline can share a snapshot id with HEAD without holding all its files. const validators = new WeakMap< @@ -73,7 +70,7 @@ export async function fetchRemoteManifest( } /** A conditional read where the backend has validators, else a plain one. */ -export function readIfChanged( +function readIfChanged( storage: ObjectStorage, name: string, etag: string | null, @@ -193,7 +190,7 @@ export function buildManifest( snapshot: Pick, ): Manifest { return { - version: parent?.version ?? 1, + version: MANIFEST_VERSION, vaultId, snapshotId: randomId(), parentSnapshotId: parent?.snapshotId ?? null, @@ -207,7 +204,3 @@ export function buildManifest( snapshot.emptyFolders.length > 0 ? snapshot.emptyFolders : undefined, }; } - -export function objectKey(hash: string): string { - return `${REMOTE_OBJECTS_PREFIX}${hash}`; -} diff --git a/packages/plugin/src/core/passphrase-manager.ts b/packages/plugin/src/features/sync/remote/passphrase-manager.ts similarity index 77% rename from packages/plugin/src/core/passphrase-manager.ts rename to packages/plugin/src/features/sync/remote/passphrase-manager.ts index 9754d62b..f3e5c424 100644 --- a/packages/plugin/src/core/passphrase-manager.ts +++ b/packages/plugin/src/features/sync/remote/passphrase-manager.ts @@ -1,33 +1,36 @@ import type { DataAdapter } from "obsidian"; - -import type { EncryptionKey } from "@/crypto"; -import type { DeviceKey } from "@/crypto/device-key"; -import type { LiveKeys } from "@/crypto/live-keys"; +import type { DeviceKey, EncryptionKey, LiveKeys } from "@/core/crypto"; import { clearCachedPassphrase, loadCachedPassphrase, saveCachedPassphrase, -} from "@/crypto/passphrase-cache"; +} from "@/core/crypto"; +import type { MdsyncSettings } from "@/core/settings"; +import { reportWarning } from "@/core/shared"; import { activeStorage, - isStorageConfigured, - type MdsyncSettings, -} from "@/settings/model"; -import { reportWarning } from "@/shared"; -import { createStorageAdapter, + isStorageConfigured, type ObjectStorage, storageIdentity, -} from "@/storage"; +} from "@/features/storage"; import { + PassphraseRotatedError, readKeyfile, resolveContentKey, rotatePassphrase, -} from "@/sync/keyfile"; +} from "./keyfile"; + +/** How {@link PassphraseManager.resolveKeyRecovering} tells the log and the person what it is doing. */ +export interface RotationFeedback { + warn(message: string): void | Promise; + notify(message: string): void; +} interface CachedKey { key: EncryptionKey; liveKeys: LiveKeys; + chunkIds: CryptoKey; signature: string; epoch: number; } @@ -82,6 +85,10 @@ export class PassphraseManager { this.setPassphrase(null); this.unverified = false; this.cachedKey = null; + await this.dropDiskCopy(); + } + + private async dropDiskCopy(): Promise { try { await clearCachedPassphrase(this.adapter, this.configDir); } catch (err) { @@ -89,6 +96,12 @@ export class PassphraseManager { } } + /** After `cachePassphrase` changed: turning it on saves the verified passphrase, off removes the saved copy. */ + async applyCachePreference(): Promise { + if (this.settings.cachePassphrase) await this.persistIfEnabled(); + else await this.dropDiskCopy(); + } + dispose(): void { this.setPassphrase(null); this.cachedKey = null; @@ -222,18 +235,46 @@ export class PassphraseManager { return key; } + /** Recovers from a passphrase rotated on another device: forget it, ask once more, retry; a second mismatch gives up. */ + async resolveKeyRecovering( + storage: ObjectStorage, + say: RotationFeedback, + ): Promise { + try { + return await this.resolveKey(storage); + } catch (err) { + if (!(err instanceof PassphraseRotatedError)) throw err; + await say.warn( + "Passphrase no longer matches the remote (rotated elsewhere); re-prompting.", + ); + say.notify("Passphrase changed on another device. Enter the new one."); + await this.forget(); + if (!(await this.prompt(true))) return null; + try { + return await this.resolveKey(storage); + } catch (retryErr) { + if (!(retryErr instanceof PassphraseRotatedError)) throw retryErr; + await say.warn( + "Session blocked: passphrase still does not match after re-prompt.", + ); + say.notify("Passphrase still incorrect."); + return null; + } + } + } + private async derive( storage: ObjectStorage, passphrase: string, signature: string, ): Promise { - const { contentKey, liveKeys, epoch } = await resolveContentKey( + const { contentKey, liveKeys, chunkIds, epoch } = await resolveContentKey( storage, passphrase, ); // Forgotten or replaced meanwhile: the old key must not come back. if (this.passphrase !== passphrase) return contentKey; - this.cachedKey = { key: contentKey, liveKeys, signature, epoch }; + this.cachedKey = { key: contentKey, liveKeys, chunkIds, signature, epoch }; if (this.unverified) { this.unverified = false; await this.persistIfEnabled(); @@ -248,10 +289,17 @@ export class PassphraseManager { /** Live-layer keys of the current storage, once a sync session resolved the key. */ liveKeys(): LiveKeys | null { + return this.bound()?.liveKeys ?? null; + } + + /** The chunk naming key of the current storage, once a sync session resolved the key. */ + chunkIds(): CryptoKey | null { + return this.bound()?.chunkIds ?? null; + } + + private bound(): CachedKey | null { const cached = this.cachedKey; - return cached?.signature === this.bindingSignature() - ? cached.liveKeys - : null; + return cached?.signature === this.bindingSignature() ? cached : null; } private bindingSignature(): string { diff --git a/packages/plugin/src/sync/reset.ts b/packages/plugin/src/features/sync/remote/reset.ts similarity index 50% rename from packages/plugin/src/sync/reset.ts rename to packages/plugin/src/features/sync/remote/reset.ts index 03f2dff8..59107c07 100644 --- a/packages/plugin/src/sync/reset.ts +++ b/packages/plugin/src/features/sync/remote/reset.ts @@ -1,13 +1,15 @@ -import { DEFAULT_CONCURRENCY } from "@/constants"; -import type { StorageAdapter } from "@/storage/types"; +import { DEFAULT_CONCURRENCY, REMOTE_MANIFEST_KEY } from "@/core/constants"; +import { runWithConcurrency } from "@/core/utils"; +import type { StorageAdapter } from "@/features/storage"; import { + REMOTE_CHUNKS_PREFIX, REMOTE_HISTORY_LOG_KEY, - REMOTE_MANIFEST_KEY, + REMOTE_HISTORY_PREFIX, REMOTE_OBJECTS_PREFIX, REMOTE_PINS_PREFIX, -} from "@/sync/constants"; -import type { EngineDependencies } from "@/sync/engine"; -import { runWithConcurrency } from "@/utils"; + REMOTE_RECIPES_PREFIX, +} from "../constants"; +import type { EngineDependencies } from "../engine"; export interface RemoteResetResult { deletedKeys: string[]; @@ -18,24 +20,26 @@ export async function resetRemoteStorage( concurrency = DEFAULT_CONCURRENCY, onProgress?: (done: number, total: number) => void, ): Promise { - // History must go with its objects; leaving pins behind breaks the log. - const [objectKeys, pinKeys] = await Promise.all([ + // History must go with its objects: records and pins left behind would name what is gone. + const [chunkKeys, ...listed] = await Promise.all([ + storage.list(REMOTE_CHUNKS_PREFIX), storage.list(REMOTE_OBJECTS_PREFIX), + storage.list(REMOTE_RECIPES_PREFIX), storage.list(REMOTE_PINS_PREFIX), + storage.list(REMOTE_HISTORY_PREFIX), ]); - const keys = Array.from( - new Set([ - REMOTE_MANIFEST_KEY, - REMOTE_HISTORY_LOG_KEY, - ...objectKeys, - ...pinKeys, - ]), + const rest = Array.from( + new Set([REMOTE_MANIFEST_KEY, REMOTE_HISTORY_LOG_KEY, ...listed.flat()]), ); + const keys = [...rest, ...chunkKeys]; let done = 0; - await runWithConcurrency(keys, concurrency, async (key) => { - await storage.delete(key); - onProgress?.(++done, keys.length); - }); + // Chunks last: a root still standing guards its chunks (`stillLands`). + for (const batch of [rest, chunkKeys]) { + await runWithConcurrency(batch, concurrency, async (key) => { + await storage.delete(key); + onProgress?.(++done, keys.length); + }); + } return { deletedKeys: keys }; } diff --git a/packages/plugin/src/sync/session.ts b/packages/plugin/src/features/sync/remote/salt.ts similarity index 82% rename from packages/plugin/src/sync/session.ts rename to packages/plugin/src/features/sync/remote/salt.ts index cb9c7b30..c66deec9 100644 --- a/packages/plugin/src/sync/session.ts +++ b/packages/plugin/src/features/sync/remote/salt.ts @@ -1,6 +1,6 @@ -import { randomBytes } from "@/crypto"; -import type { ObjectStorage } from "@/storage/types"; -import { REMOTE_SALT_KEY } from "@/sync/constants"; +import { randomBytes } from "@/core/crypto"; +import type { ObjectStorage } from "@/features/storage"; +import { REMOTE_SALT_KEY } from "../constants"; const SALT_BYTES = 16; diff --git a/packages/plugin/src/sync/space-paths.ts b/packages/plugin/src/features/sync/remote/space-paths.ts similarity index 64% rename from packages/plugin/src/sync/space-paths.ts rename to packages/plugin/src/features/sync/remote/space-paths.ts index 65e7353f..ed8f523f 100644 --- a/packages/plugin/src/sync/space-paths.ts +++ b/packages/plugin/src/features/sync/remote/space-paths.ts @@ -3,8 +3,8 @@ * everything is vault paths. */ -import type { HistoryLog } from "./history/types"; -import type { Manifest } from "./types"; +import type { SnapshotChanges } from "../history/types"; +import type { Manifest } from "../types"; type Rekey = (path: string) => string; @@ -27,14 +27,6 @@ export function manifestMoved( : manifestToVault(manifestToSpace(manifest, from), to); } -export function historyLogToSpace(log: HistoryLog, root: string): HistoryLog { - return root === "" ? log : rekeyLog(log, stripRoot(root)); -} - -export function historyLogToVault(log: HistoryLog, root: string): HistoryLog { - return root === "" ? log : rekeyLog(log, addRoot(root)); -} - function rekeyManifest(manifest: Manifest, rekey: Rekey): Manifest { return { ...manifest, @@ -43,18 +35,30 @@ function rekeyManifest(manifest: Manifest, rekey: Rekey): Manifest { }; } -function rekeyLog(log: HistoryLog, rekey: Rekey): HistoryLog { - const changes: HistoryLog["changes"] = {}; - for (const [id, { added, modified, deleted }] of Object.entries( - log.changes, - )) { - changes[id] = { - added: rekeyRecord(added, rekey), - modified: rekeyRecord(modified, rekey), - deleted: rekeyRecord(deleted, rekey), - }; +export function changesToSpace( + changes: SnapshotChanges, + root: string, +): SnapshotChanges { + return root === "" ? changes : rekeyChanges(changes, stripRoot(root)); +} + +export function changesToVault( + changes: SnapshotChanges, + root: string, +): SnapshotChanges { + return root === "" ? changes : rekeyChanges(changes, addRoot(root)); +} + +function rekeyChanges(changes: SnapshotChanges, rekey: Rekey): SnapshotChanges { + const rekeyed: SnapshotChanges = { + added: rekeyRecord(changes.added, rekey), + modified: rekeyRecord(changes.modified, rekey), + deleted: rekeyRecord(changes.deleted, rekey), + }; + if (changes.deletedLast) { + rekeyed.deletedLast = rekeyRecord(changes.deletedLast, rekey); } - return { ...log, changes }; + return rekeyed; } function rekeyRecord( diff --git a/packages/plugin/src/sync/space.ts b/packages/plugin/src/features/sync/remote/space.ts similarity index 100% rename from packages/plugin/src/sync/space.ts rename to packages/plugin/src/features/sync/remote/space.ts diff --git a/packages/plugin/src/sync/uploads.ts b/packages/plugin/src/features/sync/remote/uploads.ts similarity index 60% rename from packages/plugin/src/sync/uploads.ts rename to packages/plugin/src/features/sync/remote/uploads.ts index 329e7eb4..0e56f272 100644 --- a/packages/plugin/src/sync/uploads.ts +++ b/packages/plugin/src/features/sync/remote/uploads.ts @@ -1,4 +1,5 @@ -import type { ObjectStorage } from "@/storage/types"; +import type { ListedObject, ObjectStorage } from "@/features/storage"; +import { trimOldest } from "../hunks/bounded-map"; /** * Blobs uploaded here but not yet in a published manifest, so an unpublished push resumes. Any other non-head @@ -6,6 +7,10 @@ import type { ObjectStorage } from "@/storage/types"; */ export const UPLOAD_TRUST_MS = 12 * 60 * 60 * 1000; +/** Chunk keys join the log and no publish forgets them; past this, the oldest go, as a miss only re-uploads. */ +const UPLOAD_LOG_MAX = 20_000; + +// Oldest first: an entry is re-inserted on each upload. const uploads = new WeakMap>(); export function rememberUpload(storage: ObjectStorage, hash: string): void { @@ -14,7 +19,9 @@ export function rememberUpload(storage: ObjectStorage, hash: string): void { byHash = new Map(); uploads.set(storage, byHash); } + byHash.delete(hash); byHash.set(hash, Date.now()); + trimOldest(byHash, UPLOAD_LOG_MAX); } /** Still worth a probe; the probe decides. */ @@ -37,32 +44,17 @@ export function forgetUploads( export const SETTLED_AFTER_MS = 2 * UPLOAD_TRUST_MS; /** - * Keys old enough to be no push's: another device's push uploads before it - * publishes, and a pin's manifest lands before its flag. Undated ones are kept. + * Every object under `prefix`, dated: another device's push uploads before it publishes, and a pin's manifest + * lands before its flag, so only one older than {@link SETTLED_AFTER_MS} may be no push's. Undated ones are kept. */ -export async function settledKeys( - storage: ObjectStorage, - prefix: string, -): Promise { - return [...(await keysByAge(storage, prefix)).settled]; -} - -/** {@link settledKeys}, and the present keys a push may still be using; an absent key is in neither. */ -export async function keysByAge( +export async function listDated( storage: ObjectStorage, prefix: string, -): Promise<{ settled: Set; settling: Set }> { +): Promise { if (!storage.listDetailed) { throw new Error( "This storage does not report when objects were written, so a running upload cannot be told from an orphan.", ); } - const settledBefore = Date.now() - SETTLED_AFTER_MS; - const settled = new Set(); - const settling = new Set(); - for (const object of await storage.listDetailed(prefix)) { - const old = object.modified !== null && object.modified < settledBefore; - (old ? settled : settling).add(object.key); - } - return { settled, settling }; + return storage.listDetailed(prefix); } diff --git a/packages/plugin/src/sync/runtime/auto-cycle.ts b/packages/plugin/src/features/sync/runtime/auto-cycle.ts similarity index 89% rename from packages/plugin/src/sync/runtime/auto-cycle.ts rename to packages/plugin/src/features/sync/runtime/auto-cycle.ts index 848cfffb..f3d7f8a9 100644 --- a/packages/plugin/src/sync/runtime/auto-cycle.ts +++ b/packages/plugin/src/features/sync/runtime/auto-cycle.ts @@ -1,7 +1,8 @@ -import { ESyncLogOperation } from "@/logs/store"; -import { autoMergeOp } from "@/sync/auto-merge"; -import type { AutoPushSelector } from "@/sync/auto-push"; -import { pullPathsOp, pushPathsOp } from "@/sync/operations"; +import { ESyncLogOperation } from "@/core/logs"; +import { autoMergeOp } from "../apply/auto-merge"; +import type { AutoPushSelector } from "../automation/auto-push"; +import { pullPathsOp } from "../operations/pull"; +import { pushPathsOp } from "../operations/push"; import type { SyncControllerRuntimeState } from "./controller-state"; import type { OperationRunner, SpaceOperation } from "./operation-runner"; diff --git a/packages/plugin/src/sync/runtime/controller-state.ts b/packages/plugin/src/features/sync/runtime/controller-state.ts similarity index 97% rename from packages/plugin/src/sync/runtime/controller-state.ts rename to packages/plugin/src/features/sync/runtime/controller-state.ts index ce48f790..2cd1ea84 100644 --- a/packages/plugin/src/sync/runtime/controller-state.ts +++ b/packages/plugin/src/features/sync/runtime/controller-state.ts @@ -1,7 +1,7 @@ -import type { CompareResult } from "@/sync/engine"; -import { changeCount } from "@/sync/moves"; -import { type Space, VAULT_SPACE } from "@/sync/space"; -import { StatusBroadcaster } from "@/sync/status-broadcaster"; +import { changeCount } from "../changes/moves"; +import type { CompareResult } from "../engine"; +import { type Space, VAULT_SPACE } from "../remote/space"; +import { StatusBroadcaster } from "../status-broadcaster"; import { mergeResults } from "./merged-result"; /** A shared folder the last refresh could not compare; the others went on. */ diff --git a/packages/plugin/src/sync/runtime/file-diff-service.ts b/packages/plugin/src/features/sync/runtime/file-diff-service.ts similarity index 71% rename from packages/plugin/src/sync/runtime/file-diff-service.ts rename to packages/plugin/src/features/sync/runtime/file-diff-service.ts index 539d6065..10f72c51 100644 --- a/packages/plugin/src/sync/runtime/file-diff-service.ts +++ b/packages/plugin/src/features/sync/runtime/file-diff-service.ts @@ -1,13 +1,19 @@ -import { isTextMergeCandidate } from "@/sync/auto-merge"; +import { sha256Hex } from "@/core/crypto"; +import { formatBytes } from "@/core/shared"; +import { isTextMergeCandidate } from "../apply/auto-merge"; import { + hasKnownBinaryExtension, loadBaselineText, loadLocalText, loadRemoteText, -} from "@/sync/content"; -import { DiffCache, type DiffCacheInput } from "@/sync/diff-cache"; -import type { CompareResult, EngineDependencies } from "@/sync/engine"; -import type { FileDiffModel } from "@/sync/projection"; -import type { Space } from "@/sync/space"; + textToBytes, +} from "../changes/content"; +import { HUNK_TEXT_MAX_BYTES } from "../constants"; +import type { CompareResult, EngineDependencies } from "../engine"; +import { DiffCache, type DiffCacheInput } from "../hunks/diff-cache"; +import { alignJsonSides } from "../hunks/json-align"; +import type { FileDiffModel } from "../hunks/projection"; +import type { Space } from "../remote/space"; import type { Conflict, DiffResult, @@ -15,7 +21,7 @@ import type { FileChange, ManifestEntry, Move, -} from "@/sync/types"; +} from "../types"; export interface PathStatus { change?: FileChange; @@ -74,37 +80,57 @@ export class FileDiffService { return paths; } - async getConflictThreeWay(path: string): Promise<{ - base: string; - local: string; - remote: string; - expected: { localHash: string; remoteHash: string }; - } | null> { + /** The three versions to merge, or why there are none, worded to end "Cannot merge this file: ". */ + async getConflictThreeWay(path: string): Promise< + | { + base: string; + local: string; + remote: string; + expected: { localHash: string; remoteHash: string }; + } + | string + > { const result = this.deps.getResult(); - if (!result) return null; - const conflict = this.pathIndex()?.conflict.get(path); - if (!conflict?.baselineHash) return null; - const session = await this.deps.openSession(path); - if (!session) return null; - // Pre-flight size/extension so binary or oversized conflicts return null before downloading. + const conflict = result && this.pathIndex()?.conflict.get(path); + const session = conflict && (await this.deps.openSession(path)); + if (!result || !conflict || !session) return "refresh and try again."; + const whole = "Use Keep local, Accept remote or Keep both."; + if (!conflict.baselineHash) { + return `its two versions share no earlier one. ${whole}`; + } + // Pre-flight size/extension so binary or oversized conflicts stop before downloading. const mergeable = await isTextMergeCandidate( session, path, result.remote, session.state.baseline, ); - if (!mergeable) return null; + if (!mergeable) { + return hasKnownBinaryExtension(path) + ? `it is binary. ${whole}` + : `it is over ${formatBytes(HUNK_TEXT_MAX_BYTES)}. ${whole}`; + } const fetch = { storage: session.storage, key: session.key }; const [base, local, remote] = await Promise.all([ loadRemoteText(fetch, conflict.baselineHash), loadLocalText(session.adapter, path), loadRemoteText(fetch, conflict.remoteHash), ]); - if (base === null || local === null || remote === null) return null; + if (base === null || local === null || remote === null) { + return `a version of it is not plain text or could not be downloaded. ${whole}`; + } + // Save checks the compare's hashes: a disk edit since would fail only there, or restore a draft over it. + if ((await sha256Hex(textToBytes(local))) !== conflict.localHash) { + return "it changed since the last compare. Refresh and try again."; + } + // Reordered keys would read as changes: base and remote follow local's order and indent. + const aligned = path.endsWith(".json") + ? alignJsonSides(base, local, remote) + : null; return { - base, + base: aligned?.base ?? base, local, - remote, + remote: aligned?.remote ?? remote, expected: { localHash: conflict.localHash, remoteHash: conflict.remoteHash, diff --git a/packages/plugin/src/sync/runtime/history-service.ts b/packages/plugin/src/features/sync/runtime/history-service.ts similarity index 50% rename from packages/plugin/src/sync/runtime/history-service.ts rename to packages/plugin/src/features/sync/runtime/history-service.ts index 959fd561..b9c0f8c8 100644 --- a/packages/plugin/src/sync/runtime/history-service.ts +++ b/packages/plugin/src/features/sync/runtime/history-service.ts @@ -1,5 +1,7 @@ -import { DEFAULT_CONCURRENCY } from "@/constants"; -import { sha256Hex } from "@/crypto"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { sha256Hex } from "@/core/crypto"; +import { runWithConcurrency, withEolOf } from "@/core/utils"; +import { trashPath, unchangedSince } from "@/core/vault"; import { bytesToText, isLikelyText, @@ -7,38 +9,48 @@ import { textToBytes, writeLocalFile, writeRemoteObject, -} from "@/sync/content"; -import type { EngineDependencies } from "@/sync/engine"; -import { ownedFiles } from "@/sync/foreign"; +} from "../changes/content"; +import { runWithFileConcurrency } from "../changes/file-concurrency"; +import { entryAt } from "../changes/records"; +import { skipUnholdableNames } from "../changes/remote-names"; +import type { EngineDependencies } from "../engine"; +import { historyTracks, untrackedDir } from "../history/changes"; +import type { Activity } from "../history/model/types"; import { - type DeletedFilesResult, - type FileVersion, + type HistoryQuery, loadVersionBytes, - planVaultRestore, listDeletedFiles as queryDeletedFiles, getFileHistory as queryFileHistory, listSnapshots as querySnapshots, resolveSnapshotManifest, - type SnapshotListResult, - sameRestorePlan, setSnapshotPinned as storeSetSnapshotPinned, +} from "../history/query"; +import { + planVaultRestore, + sameRestorePlan, type VaultRestorePlan, -} from "@/sync/history"; +} from "../history/restore-vault"; +import type { + DeletedFilesResult, + FileVersion, + SnapshotListResult, +} from "../history/types"; import { applyHunks, complementSelection, computeHunks, type HunkSelection, -} from "@/sync/hunks"; +} from "../hunks/hunks"; import { buildHistoryDiff, type FileDiffModel, type HistoryDiffRequest, -} from "@/sync/projection"; -import type { LocalSnapshot, Manifest } from "@/sync/types"; -import { runWithConcurrency, runWithFileConcurrency, withEolOf } from "@/utils"; -import { diskRefuses, trashPath } from "@/vault/io"; -import { scanVault } from "@/vault/scanner"; +} from "../hunks/projection"; +import { coldSince } from "../live-notes"; +import { ownedFiles } from "../remote/foreign"; +import type { Space } from "../remote/space"; +import { scanVault } from "../scope/scanner"; +import type { LocalSnapshot, Manifest } from "../types"; const NO_SESSION = "Storage session unavailable"; @@ -48,6 +60,10 @@ interface HistoryServiceDeps { /** Serialises writes against the rest of the sync queue. */ enqueue: (task: () => Promise) => Promise; refresh: () => Promise; + /** Keeps the vault's activity for the settings overview. */ + remember: (storage: string, activity: Activity, since: number) => void; + /** What a restore left in a space (null: removed), kept out of automatic pushes; before its refresh. */ + restored: (space: Space, left: ReadonlyMap) => void; } /** Reads and restores past file versions from the snapshot history. */ @@ -57,22 +73,13 @@ export class HistoryService { async getFileHistory(path: string): Promise { const session = await this.deps.openSession(path); if (!session) return []; - return queryFileHistory({ - storage: session.storage, - key: session.key, - root: session.space.root, - path, - }); + return queryFileHistory({ ...queryOf(session), path }); } async listDeletedFiles(): Promise { const session = await this.deps.openSession(); if (!session) return { files: [], lagging: false, truncated: false }; - const deleted = await queryDeletedFiles({ - storage: session.storage, - key: session.key, - root: session.space.root, - }); + const deleted = await queryDeletedFiles(queryOf(session)); return { ...deleted, files: deleted.files.filter(({ path }) => session.scope.includes(path)), @@ -81,21 +88,19 @@ export class HistoryService { async listSnapshots(): Promise { const session = await this.deps.openSession(); - if (!session) return { snapshots: [], lagging: false }; - return querySnapshots({ - storage: session.storage, - key: session.key, - root: session.space.root, - }); + if (!session) + return { snapshots: [], lagging: false, truncated: false, activity: {} }; + const since = Date.now(); + const result = await querySnapshots(queryOf(session)); + this.deps.remember(session.storage.identity(), result.activity, since); + return result; } /** What a restore would change, computed against a fresh scan of the vault. */ async previewVaultRestore(snapshotId: string): Promise { const session = await this.requireSession(); - return this.planRestore( - session, - await this.requireSnapshot(session, snapshotId), - ); + const target = await this.requireSnapshot(session, snapshotId); + return planRestore(session, target, await scanLocal(session)); } /** @@ -109,8 +114,32 @@ export class HistoryService { return this.deps.enqueue(async () => { const session = await this.requireSession(); const target = await this.requireSnapshot(session, snapshotId); - const plan = await this.planRestore(session, target); + const local = await scanLocal(session); + const plan = planRestore(session, target, local); if (!sameRestorePlan(plan, confirmed)) return { plan, applied: false }; + // An edit saved while the restore downloads keeps its file, as in a pull. + const seen = (path: string) => entryAt(local.files, path); + // On a case-blind disk a recased file answers for the target's spelling. + const spelled = new Map( + Object.keys(local.files).map((path) => [path.toLowerCase(), path]), + ); + const recased = (path: string) => spelled.get(path.toLowerCase()); + const ready = (path: string) => { + const exact = coldSince(session, path, seen(path)); + const alias = recased(path); + const other = alias && coldSince(session, path, seen(alias)); + return async () => (await exact()) || (!!other && (await other())); + }; + // Held before the first write: a restore cut short must not reach an automatic push either. + this.deps.restored( + session.space, + new Map( + plan.write.flatMap(({ path, entry: { hash } }) => [ + [path, hash], + [recased(path) ?? path, hash], + ]), + ), + ); const claims = await session.journal?.claim( session.space, new Map( @@ -122,23 +151,27 @@ export class HistoryService { plan.write, session.concurrency ?? DEFAULT_CONCURRENCY, (item) => item.entry.size, - async (item) => { - await writeRemoteObject( - session, - item.path, - item.entry.hash, + async ({ path, entry }) => { + await writeRemoteObject(session, path, entry.hash, { claims, - ); + ready: ready(path), + }); }, ); } finally { if (claims) await session.journal?.settle(claims); } + this.deps.restored( + session.space, + new Map(plan.remove.map((path) => [path, null])), + ); await runWithConcurrency( plan.remove, session.concurrency ?? DEFAULT_CONCURRENCY, async (path) => { - await trashPath(session.adapter, path); + if (await unchangedSince(session.adapter, path, seen(path))) { + await trashPath(session.adapter, path); + } }, ); await this.deps.refresh(); @@ -146,27 +179,11 @@ export class HistoryService { }); } - private async planRestore( - session: EngineDependencies, - target: Manifest, - ): Promise { - return planVaultRestore( - target, - await scanLocal(session), - (path) => session.scope.includes(path) && !diskRefuses(path), - ); - } - private async requireSnapshot( session: EngineDependencies, snapshotId: string, ): Promise { - const target = await resolveSnapshotManifest( - session.storage, - session.key, - session.space.root, - snapshotId, - ); + const target = await resolveSnapshotManifest(queryOf(session), snapshotId); if (!target) { throw new Error( "That snapshot can no longer be rebuilt from history, so the vault cannot be restored to it.", @@ -175,42 +192,74 @@ export class HistoryService { return { ...target, files: ownedFiles(target.files, session.scope) }; } - /** Queued: it rewrites the history log a push or GC of this device also rewrites. */ + /** + * Queued with pushes: the pin is replayed from the history they write. `path` names a file of the space + * whose snapshot it is (a shared folder's History); the vault's without one. + */ setSnapshotPinned( snapshotId: string, pinned: boolean, label?: string, + path?: string, ): Promise { return this.deps.enqueue(async () => { - const session = await this.requireSession(); - await storeSetSnapshotPinned( - session.storage, - session.key, - session.space.root, - snapshotId, - pinned, - label, - ); + const session = await this.requireSession(path); + await storeSetSnapshotPinned(queryOf(session), snapshotId, pinned, label); }); } + /** The version is read in the space of `source`: the vault adapter serves the current side of any path. */ async getHistoryDiff( request: HistoryDiffRequest, ): Promise { - const session = await this.deps.openSession(request.path); + const session = await this.deps.openSession(request.source ?? request.path); if (!session) return null; return buildHistoryDiff(session, request); } - async restoreFileVersion(path: string, hash: string): Promise { + /** `from` is the path the version was stored under, when it lands at another (a restore-to). */ + async restoreFileVersion( + path: string, + hash: string, + from = path, + ): Promise { await this.deps.enqueue(async () => { - const session = await this.requireSession(path); - const bytes = await loadVersionBytes(session.storage, session.key, hash); - await writeLocalFile(session, path, bytes); + await this.writeVersion(path, hash, from); await this.deps.refresh(); }); } + /** + * Many files in one queue turn and one refresh: each refresh is a full vault scan and remote compare. + * Returns the paths that failed; only the closing refresh rejects. + */ + async restoreFileVersions( + items: { path: string; hash: string }[], + ): Promise { + if (items.length === 0) return []; + return this.deps.enqueue(async () => { + const failed: string[] = []; + for (const { path, hash } of items) { + await this.writeVersion(path, hash).catch(() => failed.push(path)); + } + if (failed.length < items.length) await this.deps.refresh(); + return failed; + }); + } + + /** Read in the space that stored it, written in the one that owns `path`: a batch may span spaces. */ + private async writeVersion( + path: string, + hash: string, + from = path, + ): Promise { + const source = await this.requireSession(from); + const bytes = await loadVersionBytes(source.storage, source.key, hash); + const target = from === path ? source : await this.requireSession(path); + this.deps.restored(target.space, new Map([[path, hash]])); + await writeLocalFile(target, path, bytes); + } + async restoreHistoryHunks( path: string, hash: string, @@ -252,7 +301,12 @@ export class HistoryService { currentText, applyHunks(versionText, hunks, complementSelection(hunks, selected)), ); - await writeLocalFile(session, path, textToBytes(merged)); + const bytes = textToBytes(merged); + this.deps.restored( + session.space, + new Map([[path, await sha256Hex(bytes)]]), + ); + await writeLocalFile(session, path, bytes); await this.deps.refresh(); }); } @@ -264,6 +318,30 @@ export class HistoryService { } } +function queryOf(session: EngineDependencies): HistoryQuery { + return { + storage: session.storage, + key: session.key, + root: session.space.root, + horizon: session.history?.horizon ?? null, + configDir: untrackedDir(session), + }; +} + +/** A name this disk cannot hold (reserved, or one spelling of a case clash) is skipped, as a pull skips it. */ +function planRestore( + session: EngineDependencies, + target: Manifest, + local: LocalSnapshot, +): VaultRestorePlan { + return planVaultRestore( + target, + skipUnholdableNames(local, target, session.state.baseline, session.scope), + (path) => session.scope.includes(path), + historyTracks(untrackedDir(session)), + ); +} + /** The local half of a compare: a restore plan needs only the disk, not the remote manifest download. */ async function scanLocal(session: EngineDependencies): Promise { const { snapshot } = await scanVault( diff --git a/packages/plugin/src/features/sync/runtime/maintenance-service.ts b/packages/plugin/src/features/sync/runtime/maintenance-service.ts new file mode 100644 index 00000000..2ea5dd60 --- /dev/null +++ b/packages/plugin/src/features/sync/runtime/maintenance-service.ts @@ -0,0 +1,133 @@ +import { ESyncLogOperation } from "@/core/logs"; +import { errorMessage } from "@/core/shared"; +import { LOG_PATH_LIMIT } from "../constants"; +import type { EngineDependencies } from "../engine"; +import { collectHistoryGarbage } from "../history/gc"; +import { clearLegacyHistory } from "../history/legacy"; +import type { Activity } from "../history/model/types"; +import { type Space, VAULT_SPACE } from "../remote/space"; +import { + type CleanResult, + cleanSummary, + deepCleanOrphans, + type VerifyResult, + verifyRemote, +} from "./maintenance"; + +/** A run with nothing due still lists `history/`: one per space this often is plenty. */ +const HISTORY_GC_EVERY_MS = 10 * 60_000; + +type Log = ( + operation: ESyncLogOperation, + message: string, + details?: readonly string[], +) => Promise; + +interface MaintenanceServiceDeps { + openSession: (space: Space) => Promise; + /** Between operations: a push of this device uploads blobs its manifest does not name yet. */ + enqueue: (task: () => Promise) => Promise; + /** As `enqueue`, without showing the plugin busy. */ + enqueueQuiet: (task: () => Promise) => Promise; + logInfo: Log; + logWarn: Log; + /** Keeps the vault's activity GC read anyway, for the settings overview. */ + remember: (storage: string, activity: Activity, since: number) => void; +} + +export class MaintenanceService { + private readonly lastGc = new Map(); + private readonly legacyCleared = new Set(); + private disposed = false; + + constructor(private readonly deps: MaintenanceServiceDeps) {} + + /** Clears 1.x history and thins history after a published push; never awaited by it, and a failure only logs. */ + afterPush(space: Space): void { + const now = Date.now(); + if (now - (this.lastGc.get(space.id) ?? 0) < HISTORY_GC_EVERY_MS) return; + this.lastGc.set(space.id, now); + void this.deps + .enqueueQuiet(async () => { + if (this.disposed) return; + const session = await this.deps.openSession(space); + if (!session) return; + // Once a session per storage, history on or off: a 1.x pin blocks every sweep. + const target = `${session.storage.identity()}\n${space.id}`; + if (!this.legacyCleared.has(target)) { + const removed = await clearLegacyHistory( + session.storage, + session.key, + ); + this.legacyCleared.add(target); + if (removed > 0) { + await this.deps.logInfo( + ESyncLogOperation.Push, + `Old-format file history removed (${removed} object(s)).`, + ); + } + } + if (!session.history) return; + const since = Date.now(); + const { written, retired, swept, activity } = + await collectHistoryGarbage( + session.storage, + session.key, + session.space.root, + session.history, + ); + if (activity && space.id === VAULT_SPACE.id) + this.deps.remember(session.storage.identity(), activity, since); + if (written + retired + swept > 0) { + await this.deps.logInfo( + ESyncLogOperation.Push, + `History cleanup: ${written} object(s) written, ${retired} retired, ${swept} file version(s) removed.`, + ); + } + }) + .catch((err) => + this.deps.logWarn( + ESyncLogOperation.Push, + `History cleanup failed: ${errorMessage(err)}`, + ), + ); + } + + dispose(): void { + this.disposed = true; + } + + async verifyRemote(deep: boolean): Promise { + const session = await this.deps.openSession(VAULT_SPACE); + if (!session) return null; + const result = await verifyRemote( + session.storage, + session.key, + session.space.root, + deep, + ); + await this.deps.logInfo( + ESyncLogOperation.Compare, + `Integrity check: ${result.checked} object(s), ${result.missing.length} missing, ${result.corrupt.length} corrupt.`, + [...result.missing, ...result.corrupt].slice(0, LOG_PATH_LIMIT), + ); + return result; + } + + deepCleanRemote(): Promise { + return this.deps.enqueue(async () => { + const session = await this.deps.openSession(VAULT_SPACE); + if (!session) return null; + const result = await deepCleanOrphans( + session.storage, + session.key, + session.space.root, + ); + await this.deps.logInfo( + ESyncLogOperation.Reset, + `Deep-clean ${cleanSummary(result)}`, + ); + return result; + }); + } +} diff --git a/packages/plugin/src/features/sync/runtime/maintenance.ts b/packages/plugin/src/features/sync/runtime/maintenance.ts new file mode 100644 index 00000000..87e8c8b7 --- /dev/null +++ b/packages/plugin/src/features/sync/runtime/maintenance.ts @@ -0,0 +1,103 @@ +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import type { EncryptionKey } from "@/core/crypto"; +import type { StorageAdapter } from "@/features/storage"; +import { runWithFileConcurrency } from "../changes/file-concurrency"; +import { REMOTE_CHUNKS_PREFIX } from "../constants"; +import { chunkKey, isRecipeKey } from "../content/keys"; +import { + ContentError, + fetchRoot, + openContent, + prepareContent, + recipeChunks, +} from "../content/load"; +import { + reachableHashes, + type SweepOptions, + sweepObjects, +} from "../history/sweep"; + +export type MaintenanceOptions = Omit; + +export interface VerifyResult { + checked: number; + missing: string[]; + corrupt: string[]; +} + +export interface CleanResult { + deletedObjects: number; +} + +/** Catches missing objects or silent backend corruption; `deep` also decrypts and hashes. */ +export async function verifyRemote( + storage: StorageAdapter, + key: EncryptionKey, + root: string, + deep: boolean, + options: MaintenanceOptions = {}, +): Promise { + const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY; + const reachable = await reachableHashes(storage, key, root); + if (!reachable.complete) { + throw new Error( + "Some history records could not be read, so the check would be incomplete. Try again later.", + ); + } + + const list = [...reachable.hashes].map(([hash, size]) => ({ hash, size })); + const missing: string[] = []; + const corrupt: string[] = []; + const source = { storage, key }; + let stored: Promise> | undefined; + // One listing of `chunks/` answers for every recipe, listed only once one is met. + const chunksMissing = async (blob: Uint8Array): Promise => { + stored ??= storage.list(REMOTE_CHUNKS_PREFIX).then((keys) => new Set(keys)); + const have = await stored; + return (await recipeChunks(key, blob)).some( + ([id]) => !have.has(chunkKey(id)), + ); + }; + let done = 0; + await prepareContent(source, list); + await runWithFileConcurrency( + list, + concurrency, + (file) => file.size, + async ({ hash, size }) => { + const root = await fetchRoot(storage, hash, size); + try { + if (!root) missing.push(hash); + else if ( + isRecipeKey(root.storageKey) && + (await chunksMissing(root.blob)) + ) { + missing.push(hash); + } else if (deep) { + await openContent(source, root.blob, hash, root.storageKey); + } + } catch (error) { + // A failed read aborts the check: an outage must not read as corrupt. + if (!(error instanceof ContentError)) throw error; + corrupt.push(hash); + } + options.onProgress?.(++done, list.length); + }, + ); + return { checked: list.length, missing, corrupt }; +} + +/** Removes every settled object nothing reaches. */ +export async function deepCleanOrphans( + storage: StorageAdapter, + key: EncryptionKey, + root: string, + options: MaintenanceOptions = {}, +): Promise { + return { deletedObjects: await sweepObjects(storage, key, root, options) }; +} + +/** One sentence for the log and the notice, so both stay in step. */ +export function cleanSummary(result: CleanResult): string { + return `removed ${result.deletedObjects} object(s).`; +} diff --git a/packages/plugin/src/sync/runtime/merged-result.ts b/packages/plugin/src/features/sync/runtime/merged-result.ts similarity index 92% rename from packages/plugin/src/sync/runtime/merged-result.ts rename to packages/plugin/src/features/sync/runtime/merged-result.ts index 877983ae..930f0980 100644 --- a/packages/plugin/src/sync/runtime/merged-result.ts +++ b/packages/plugin/src/features/sync/runtime/merged-result.ts @@ -1,6 +1,6 @@ -import { sortedByPath } from "@/shared"; -import type { CompareResult } from "@/sync/engine"; -import type { Manifest } from "@/sync/types"; +import { sortedByPath } from "../changes/records"; +import type { CompareResult } from "../engine"; +import type { Manifest } from "../types"; /** * One UI view of every space's compare. Spaces own disjoint paths, so the union loses nothing; operations diff --git a/packages/plugin/src/sync/runtime/operation-runner.ts b/packages/plugin/src/features/sync/runtime/operation-runner.ts similarity index 91% rename from packages/plugin/src/sync/runtime/operation-runner.ts rename to packages/plugin/src/features/sync/runtime/operation-runner.ts index 89911277..740ec9f3 100644 --- a/packages/plugin/src/sync/runtime/operation-runner.ts +++ b/packages/plugin/src/features/sync/runtime/operation-runner.ts @@ -1,38 +1,38 @@ -import { ESyncLogOperation } from "@/logs/store"; -import { errorMessage, isOffline, OFFLINE_MESSAGE } from "@/shared"; +import { ESyncLogOperation } from "@/core/logs"; +import { errorMessage, isOffline, OFFLINE_MESSAGE } from "@/core/shared"; import { isRefusedCredentials, ShareRefusedError, StorageRequestError, -} from "@/storage"; -import { publishedByOthers, publisher } from "@/sync/authors"; -import { advanceBaselineForPaths } from "@/sync/baseline"; -import { isCancellation } from "@/sync/cancel"; -import { reconcileBaselineResetGenerations } from "@/sync/config-reset"; -import type { SyncControllerHost } from "@/sync/controller"; -import { settleLanded } from "@/sync/cut-short"; +} from "@/features/storage"; +import { isCancellation } from "../cancel"; +import type { SyncControllerHost } from "../controller"; import { type CompareResult, compare, type EngineDependencies, -} from "@/sync/engine"; -import { forgetDroppedForeign, heldShareBases } from "@/sync/foreign"; -import { ConcurrentPushError } from "@/sync/manifest"; +} from "../engine"; +import { publishedByOthers, publisher } from "../identity/authors"; import type { OperationContext, OperationOutcome, SyncOperationResult, -} from "@/sync/operations"; -import { deleteShareObjects } from "@/sync/reset"; +} from "../operations/types"; +import { settleLanded } from "../recovery/cut-short"; +import { advanceBaselineForPaths } from "../remote/baseline"; +import { reconcileBaselineResetGenerations } from "../remote/config-reset"; +import { forgetDroppedForeign, heldShareBases } from "../remote/foreign"; +import { ConcurrentPushError } from "../remote/manifest"; +import { deleteShareObjects } from "../remote/reset"; +import { type Space, SpaceGoneError, VAULT_SPACE } from "../remote/space"; import { forgetShare, mergeSessionIntoLocal, projectSession, recomputeAfterWrite, sharesHold, -} from "@/sync/session-state"; -import { type Space, SpaceGoneError, VAULT_SPACE } from "@/sync/space"; -import type { LocalState, SessionState } from "@/sync/types"; +} from "../session-state"; +import type { LocalState, SessionState } from "../types"; import type { SpaceError, SyncControllerRuntimeState, @@ -51,6 +51,10 @@ interface OperationRunnerDeps { runtimeState: SyncControllerRuntimeState; clearFileDiffs: () => void; localRevision?: () => number; + /** A push of this device published its manifest. */ + onPublished?: (space: Space) => void; + /** A fresh compare of `space` became its result. */ + onCompared?: (space: Space, result: CompareResult) => void; } export class OperationRunner { @@ -68,6 +72,7 @@ export class OperationRunner { ): void { if (this.invalidatedSince(epoch)) return; this.deps.runtimeState.setResult(space, result); + this.deps.onCompared?.(space, result); if (space.id === VAULT_SPACE.id) { this.deps.runtimeState.setVaultChecked(storage); } @@ -153,6 +158,10 @@ export class OperationRunner { }); if (this.invalidatedSince(epoch)) return; this.deps.runtimeState.setResults(results); + for (const [space, result] of results) { + if (refreshedRoots.has(space.root)) + this.deps.onCompared?.(space, result); + } if (vaultStorage) this.deps.runtimeState.setVaultChecked(vaultStorage); this.deps.runtimeState.setSpaceErrors(failed); this.unindexed = new Set( @@ -408,6 +417,14 @@ export class OperationRunner { ); if (theirs.length > 0) this.deps.host.onTheirsPulled?.(space, theirs); } + if ( + operation === ESyncLogOperation.Pull && + [...outcome.touchedPaths].some((path) => + session.scope.loadsOnStartup(path), + ) + ) { + this.deps.host.onPluginsPulled?.(); + } if (outcome.cancelled) { this.deps.runtimeState.setStaleReason( outcome.touchedPaths.size === 0 @@ -422,6 +439,7 @@ export class OperationRunner { outcome.newRemote !== result.remote ) { this.deps.host.onPushComplete?.(space); + this.deps.onPublished?.(space); } return { ok: true }; } catch (err) { diff --git a/packages/plugin/src/sync/runtime/refresh-queue.ts b/packages/plugin/src/features/sync/runtime/refresh-queue.ts similarity index 96% rename from packages/plugin/src/sync/runtime/refresh-queue.ts rename to packages/plugin/src/features/sync/runtime/refresh-queue.ts index 6584247f..2f28163a 100644 --- a/packages/plugin/src/sync/runtime/refresh-queue.ts +++ b/packages/plugin/src/features/sync/runtime/refresh-queue.ts @@ -1,4 +1,4 @@ -import { VAULT_SPACE } from "@/sync/space"; +import { VAULT_SPACE } from "../remote/space"; export interface RefreshRequest { spaces: Set | null; diff --git a/packages/plugin/src/sync/runtime/saved-refresh.ts b/packages/plugin/src/features/sync/runtime/saved-refresh.ts similarity index 91% rename from packages/plugin/src/sync/runtime/saved-refresh.ts rename to packages/plugin/src/features/sync/runtime/saved-refresh.ts index b4eca3ea..097a0e65 100644 --- a/packages/plugin/src/sync/runtime/saved-refresh.ts +++ b/packages/plugin/src/features/sync/runtime/saved-refresh.ts @@ -1,9 +1,8 @@ -import type { LocalSession } from "@/core/session-factory"; -import type { SyncControllerHost } from "@/sync/controller"; -import { diffWithin } from "@/sync/diff"; -import { pathsBySpace } from "@/sync/space"; -import type { ManifestEntry } from "@/sync/types"; -import { buildEntry } from "@/vault/entry"; +import { diffWithin } from "../changes/diff"; +import type { LocalSession, SyncControllerHost } from "../controller"; +import { pathsBySpace } from "../remote/space"; +import { buildEntry } from "../scope/entry"; +import type { ManifestEntry } from "../types"; import type { SyncControllerRuntimeState } from "./controller-state"; const SAVED_QUIET_MS = 300; diff --git a/packages/plugin/src/sync/runtime/scan-cycle.ts b/packages/plugin/src/features/sync/runtime/scan-cycle.ts similarity index 89% rename from packages/plugin/src/sync/runtime/scan-cycle.ts rename to packages/plugin/src/features/sync/runtime/scan-cycle.ts index 063537a4..0a9942fe 100644 --- a/packages/plugin/src/sync/runtime/scan-cycle.ts +++ b/packages/plugin/src/features/sync/runtime/scan-cycle.ts @@ -1,10 +1,6 @@ -import { type Space, spaceOf } from "@/sync/space"; -import type { HashCacheEntry } from "@/sync/types"; -import type { - IndexedFile, - IndexedFolder, - VaultIndex, -} from "@/vault/file-index"; +import type { IndexedFile, IndexedFolder, VaultIndex } from "@/core/vault"; +import { type Space, spaceOf } from "../remote/space"; +import type { HashCacheEntry } from "../types"; export class ScanCycle { readonly cache: Record; diff --git a/packages/plugin/src/ui/source-control/sync-gates.ts b/packages/plugin/src/features/sync/runtime/sync-gates.ts similarity index 91% rename from packages/plugin/src/ui/source-control/sync-gates.ts rename to packages/plugin/src/features/sync/runtime/sync-gates.ts index 923b4ae1..f5451ff9 100644 --- a/packages/plugin/src/ui/source-control/sync-gates.ts +++ b/packages/plugin/src/features/sync/runtime/sync-gates.ts @@ -1,5 +1,5 @@ /** Whether Push all / Pull all may run now; the summary card and the status menu agree on it. */ -import type { SyncStatusSnapshot } from "@/sync/controller"; +import type { SyncStatusSnapshot } from "../controller"; export function canPushAll(snapshot: SyncStatusSnapshot): boolean { const diff = snapshot.result?.diff; diff --git a/packages/plugin/src/features/sync/scope/configuration-scope-section.ts b/packages/plugin/src/features/sync/scope/configuration-scope-section.ts new file mode 100644 index 00000000..9eb035a3 --- /dev/null +++ b/packages/plugin/src/features/sync/scope/configuration-scope-section.ts @@ -0,0 +1,295 @@ +import type { Setting, SettingDefinitionGroup } from "obsidian"; +import { + EFieldKind, + EPluginLevel, + type FieldContext, + fieldRow, + group, + introRow, + type MdsyncSettings, + type SettingsField, + type SettingsRow, + type SettingsSyncCategories, + SUB_SETTING_CLASS, +} from "@/core/settings"; +import { + notifyError, + notifyInfo, + openConfirmModal, + renderSegments, +} from "@/core/ui"; +import type { SyncHost } from "../host"; +import type { Manifest } from "../types"; +import { + listPlugins, + PLUGIN_LEVEL_OPTIONS, + PluginLevelsModal, +} from "./plugin-levels-modal"; +import { + createScopePolicy, + defaultPluginLevel, + type ScopePolicy, +} from "./scope"; + +interface SettingsSyncRow { + key: keyof SettingsSyncCategories; + name: string; + desc: string; +} + +const SETTINGS_SYNC_ROWS: ReadonlyArray = [ + { + key: "coreSettings", + name: "Core settings", + desc: "App, appearance, core plugins, graph, bookmarks and templates.", + }, + { key: "hotkeys", name: "Hotkeys", desc: "hotkeys.json" }, + { + key: "pluginList", + name: "Enabled community plugins", + desc: "community-plugins.json only", + }, + { + key: "pluginConfigs", + name: "Plugins", + desc: "Settings: each plugin's data.json. Code: also the plugin itself, so it installs and updates everywhere. All: also the rest of its folder, such as caches. MDSync and device-local plugins never sync.", + }, + { + key: "snippets", + name: "CSS snippets", + desc: "snippets folder inside the config folder", + }, + { + key: "themes", + name: "Themes", + desc: "themes folder inside the config folder", + }, +]; + +function countRemoteCategories( + remote: Manifest | null | undefined, + scope: ScopePolicy, +): Map { + const counts = new Map(); + const paths = [ + ...Object.keys(remote?.files ?? {}), + ...(remote?.folders ?? []).map((dir) => `${dir}/`), + ]; + for (const path of paths) { + const category = scope.getCategory(path); + if (category) counts.set(category, (counts.get(category) ?? 0) + 1); + } + return counts; +} + +export function configurationScopeSection( + ctx: FieldContext, +): SettingDefinitionGroup { + const { plugin } = ctx; + return group("Obsidian configuration scope", [ + introRow( + "Workspace, cache, trash and device-local plugin data are never synced. Turning a category off only stops this device from syncing it; the remote keeps its files.", + ), + { + ...introRow("Compare with the remote to see which categories it holds."), + visible: () => !plugin.controller.getSnapshot().result?.remote, + render: (setting) => { + setting.setName("").addButton((button) => + button.setButtonText("Check remote").onClick(async () => { + button.setDisabled(true); + await plugin.controller.refresh(); + ctx.rerender(); + }), + ); + }, + }, + ...SETTINGS_SYNC_ROWS.flatMap((row) => + row.key === "pluginConfigs" + ? [pluginsRow(ctx, row, true), perPluginRow(ctx)] + : [categoryRow(ctx, row)], + ), + ]); +} + +/** The Plugins level and Per plugin rows for the setup wizard, which offers no Clear on remote. */ +export function pluginLevelRows(ctx: FieldContext): SettingsRow[] { + const row = SETTINGS_SYNC_ROWS.find(({ key }) => key === "pluginConfigs"); + return row ? [pluginsRow(ctx, row, false), perPluginRow(ctx)] : []; +} + +/** One category's toggle: the settings tab and the setup wizard word it their own way. */ +export function categoryField( + key: keyof SettingsSyncCategories, + name: string, + desc: string, +): SettingsField { + return { + kind: EFieldKind.Toggle, + name, + desc, + get: (s) => s.settingsSync[key], + set: (v, plugin) => ({ + settingsSync: { ...plugin.settings.settingsSync, [key]: v }, + }), + refreshScope: true, + }; +} + +function categoryRow( + ctx: FieldContext, + row: SettingsSyncRow, +): SettingsRow { + const field = fieldRow(ctx, categoryField(row.key, row.name, row.desc)); + return { + ...field, + render: (setting) => { + field.render(setting); + addClearButton(ctx, row, setting); + }, + }; +} + +/** Off turns the category off and keeps the level for when it is back on. */ +function pluginsRow( + ctx: FieldContext, + row: SettingsSyncRow, + clear: boolean, +): SettingsRow { + const { plugin } = ctx; + return { + name: row.name, + desc: row.desc, + render: (setting) => { + setting.setClass("mdsync-stacked-setting"); + renderSegments( + setting.controlEl, + "plugin-level", + PLUGIN_LEVEL_OPTIONS, + () => + defaultPluginLevel( + plugin.settings.settingsSync, + plugin.settings.pluginLevel, + ), + async (level) => { + const { settingsSync, pluginLevel, pluginLevels } = plugin.settings; + await saveScope(ctx, { + settingsSync: { + ...settingsSync, + pluginConfigs: level !== EPluginLevel.Off, + }, + pluginLevel: level === EPluginLevel.Off ? pluginLevel : level, + // One equal to the new default would stay pinned there unseen. + pluginLevels: Object.fromEntries( + Object.entries(pluginLevels).filter(([, own]) => own !== level), + ), + }); + ctx.rerender(); + }, + ).el.addClasses(["is-compact", "mdsync-plugin-level"]); + if (clear) addClearButton(ctx, row, setting); + }, + }; +} + +function perPluginRow(ctx: FieldContext): SettingsRow { + const { plugin } = ctx; + return { + name: "Per plugin", + desc: "Give single plugins a level of their own.", + render: (setting) => { + setting.settingEl.addClass(SUB_SETTING_CLASS); + const own = Object.keys(plugin.settings.pluginLevels).length; + if (own > 0) { + setting.setDesc(`${own} plugin(s) have a level of their own.`); + } + setting.addButton((button) => + button.setButtonText("Choose").onClick(() => void choosePerPlugin(ctx)), + ); + }, + }; +} + +async function choosePerPlugin(ctx: FieldContext): Promise { + const { plugin } = ctx; + const { adapter, configDir } = plugin.app.vault; + const remote = plugin.controller.getSnapshot().result?.remote ?? null; + const plugins = await listPlugins( + adapter, + createScopePolicy({ + settingsSync: plugin.settings.settingsSync, + configDir, + }), + configDir, + remote, + ); + // Read after the listing: the default may have changed meanwhile. + const { settingsSync, pluginLevel } = plugin.settings; + new PluginLevelsModal(plugin.app, { + plugins, + remoteKnown: remote !== null, + defaultLevel: defaultPluginLevel(settingsSync, pluginLevel), + levels: () => plugin.settings.pluginLevels, + save: (pluginLevels) => saveScope(ctx, { pluginLevels }), + onClose: () => ctx.rerender(), + }).open(); +} + +async function saveScope( + ctx: FieldContext, + patch: Partial, +): Promise { + Object.assign(ctx.plugin.settings, patch); + await ctx.plugin.saveSettings(); + ctx.plugin.scheduleScopeRefresh("Sync scope settings changed."); +} + +function addClearButton( + ctx: FieldContext, + row: SettingsSyncRow, + setting: Setting, +): void { + const { plugin } = ctx; + const counts = countRemoteCategories( + plugin.controller.getSnapshot().result?.remote, + createScopePolicy({ + settingsSync: plugin.settings.settingsSync, + configDir: plugin.app.vault.configDir, + }), + ); + const count = counts.get(row.key); + if (!count) return; + setting.addButton((button) => + button + .setButtonText("Clear on remote") + .setTooltip(`${count} remote item(s)`) + .setDestructive() + .onClick(() => void clearCategory(ctx, row)), + ); +} + +async function clearCategory( + ctx: FieldContext, + row: SettingsSyncRow, +): Promise { + const { plugin } = ctx; + const confirmed = await openConfirmModal({ + app: plugin.app, + title: `Clear ${row.name} on remote?`, + body: [ + `Removes every ${row.name} file from the remote storage. Local files stay on every device, and devices with this category enabled re-upload theirs on their next push.`, + "Disable the category on every device first if it should stay gone. Update MDSync on your other devices before clearing: older versions refuse the cleared remote.", + ], + confirmLabel: "Clear on remote", + confirmClass: "mod-warning", + }); + if (!confirmed) return; + if (await plugin.controller.resetCategory(row.key)) { + notifyInfo(`Cleared ${row.name} on remote.`); + } else { + notifyError( + plugin.controller.getSnapshot().error ?? + "Could not clear the category on the remote.", + ); + } + ctx.rerender(); +} diff --git a/packages/plugin/src/vault/entry.ts b/packages/plugin/src/features/sync/scope/entry.ts similarity index 84% rename from packages/plugin/src/vault/entry.ts rename to packages/plugin/src/features/sync/scope/entry.ts index c589d56f..e7f59063 100644 --- a/packages/plugin/src/vault/entry.ts +++ b/packages/plugin/src/features/sync/scope/entry.ts @@ -1,7 +1,7 @@ import type { DataAdapter } from "obsidian"; -import { sha256Hex } from "@/crypto"; -import { sceneOfBytes } from "@/drawing"; -import type { HashCacheEntry, ManifestEntry } from "@/sync/types"; +import { sha256Hex } from "@/core/crypto"; +import { sceneOfBytes } from "@/core/drawing"; +import type { HashCacheEntry, ManifestEntry } from "../types"; export async function buildEntry( adapter: DataAdapter, diff --git a/packages/plugin/src/settings/sections/exclusions.ts b/packages/plugin/src/features/sync/scope/exclusions-section.ts similarity index 83% rename from packages/plugin/src/settings/sections/exclusions.ts rename to packages/plugin/src/features/sync/scope/exclusions-section.ts index a929b87f..d9faf026 100644 --- a/packages/plugin/src/settings/sections/exclusions.ts +++ b/packages/plugin/src/features/sync/scope/exclusions-section.ts @@ -1,28 +1,35 @@ -import { type App, type SettingDefinitionGroup, TFile } from "obsidian"; - -import { IGNORE_FILE_NAME } from "@/constants"; import { + type App, + Platform, + type SettingDefinitionGroup, + TFile, +} from "obsidian"; +import { IGNORE_FILE_NAME } from "@/core/constants"; +import { + bind, + EFieldKind, type FieldContext, fieldRow, group, + NUMERIC_BOUNDS, onSettled, type SettingsField, -} from "@/settings/fields"; -import { NUMERIC_BOUNDS } from "@/settings/model"; -import { EFieldKind } from "@/storage"; -import { notifyError, notifyInfo, openInEditor, reportError } from "@/ui"; +} from "@/core/settings"; +import { notifyError, notifyInfo, openInEditor, reportError } from "@/core/ui"; +import type { SyncHost } from "../host"; const SCOPE_CHANGED = "Sync scope settings changed."; const BYTES_PER_MB = 1024 * 1024; const MIN_MAX_FILE_MB = 1; -const EXCLUSION_FIELDS: ReadonlyArray = [ +const EXCLUSION_FIELDS: ReadonlyArray> = [ { kind: EFieldKind.Toggle, name: "Ignore symlinks", desc: "Skip symbolic links, Windows junctions and directory links on this device. They can point outside the vault.", - get: (s) => s.ignoreSymlinks, - set: (v) => ({ ignoreSymlinks: v }), + // Links are detected on desktop only (core/vault/symlinks.ts). + when: () => !Platform.isMobile, + ...bind("ignoreSymlinks"), refreshScope: true, }, { @@ -40,7 +47,9 @@ const EXCLUSION_FIELDS: ReadonlyArray = [ }, ]; -export function exclusionsSection(ctx: FieldContext): SettingDefinitionGroup { +export function exclusionsSection( + ctx: FieldContext, +): SettingDefinitionGroup { const { plugin } = ctx; const savePatterns = onSettled(() => { void plugin @@ -68,6 +77,7 @@ export function exclusionsSection(ctx: FieldContext): SettingDefinitionGroup { desc: `Added to the shared rules; does not edit ${IGNORE_FILE_NAME}. One gitignore-style pattern per line.`, render: (patterns) => { patterns.setClass("mdsync-ignore-patterns"); + patterns.setClass("mdsync-stacked-setting"); patterns.nameEl.id = "mdsync-local-ignore-label"; patterns.descEl.id = "mdsync-local-ignore-description"; patterns.addTextArea((text) => { diff --git a/packages/plugin/src/settings/ignore-rules.ts b/packages/plugin/src/features/sync/scope/ignore-rules.ts similarity index 95% rename from packages/plugin/src/settings/ignore-rules.ts rename to packages/plugin/src/features/sync/scope/ignore-rules.ts index 99412fc3..b54db761 100644 --- a/packages/plugin/src/settings/ignore-rules.ts +++ b/packages/plugin/src/features/sync/scope/ignore-rules.ts @@ -1,4 +1,4 @@ -import { normalizePath } from "@/shared"; +import { normalizePath } from "@/core/shared"; const GITIGNORE_SPECIAL_CHARACTERS = /([*[\]\\])/g; diff --git a/packages/plugin/src/plugin/ignore-state.ts b/packages/plugin/src/features/sync/scope/ignore-state.ts similarity index 97% rename from packages/plugin/src/plugin/ignore-state.ts rename to packages/plugin/src/features/sync/scope/ignore-state.ts index f6dd5593..1d1dbf56 100644 --- a/packages/plugin/src/plugin/ignore-state.ts +++ b/packages/plugin/src/features/sync/scope/ignore-state.ts @@ -1,13 +1,12 @@ import { type Plugin, type TAbstractFile, TFile, TFolder } from "obsidian"; - -import { type Space, spaceOf } from "@/sync/space"; +import type { SyncHost } from "../host"; +import { type Space, spaceOf } from "../remote/space"; import { createIgnoreMatcher, type IgnoreMatcher, ignoreNoteOf, isIgnoreNote, -} from "@/vault/ignore"; -import type { PluginHost } from "./host"; +} from "./ignore"; /** * Device-local patterns plus each space's syncignore.md, kept in memory so menus answer synchronously without @@ -27,7 +26,7 @@ export interface IgnoreStateHandle { const PASS_THROUGH: IgnoreMatcher = { ignores: () => false }; export function registerIgnoreState( - plugin: Plugin & PluginHost, + plugin: Plugin & SyncHost, ): IgnoreStateHandle { const listeners = new Set<() => void>(); let local: IgnoreMatcher = PASS_THROUGH; diff --git a/packages/plugin/src/vault/ignore.ts b/packages/plugin/src/features/sync/scope/ignore.ts similarity index 94% rename from packages/plugin/src/vault/ignore.ts rename to packages/plugin/src/features/sync/scope/ignore.ts index eb1dad89..867f1a33 100644 --- a/packages/plugin/src/vault/ignore.ts +++ b/packages/plugin/src/features/sync/scope/ignore.ts @@ -1,8 +1,8 @@ import ignore, { type Ignore } from "ignore"; import type { DataAdapter } from "obsidian"; -import { IGNORE_FILE_NAME } from "@/constants"; -import { isUnder, type Space, spaceOf } from "@/sync/space"; +import { IGNORE_FILE_NAME } from "@/core/constants"; +import { isUnder, type Space, spaceOf } from "../remote/space"; export interface IgnoreMatcher { ignores(path: string): boolean; diff --git a/packages/plugin/src/features/sync/scope/plugin-levels-modal.ts b/packages/plugin/src/features/sync/scope/plugin-levels-modal.ts new file mode 100644 index 00000000..9da1ab98 --- /dev/null +++ b/packages/plugin/src/features/sync/scope/plugin-levels-modal.ts @@ -0,0 +1,189 @@ +import { + type App, + ButtonComponent, + type DataAdapter, + Modal, + SearchComponent, +} from "obsidian"; +import { EPluginLevel } from "@/core/settings"; +import { + modalCard, + modalFooter, + modalHint, + renderModalHead, + renderSegments, +} from "@/core/ui"; +import type { Manifest } from "../types"; +import type { ScopePolicy } from "./scope"; + +export const PLUGIN_LEVEL_OPTIONS = [ + { value: EPluginLevel.Off, text: "Off" }, + { value: EPluginLevel.Settings, text: "Settings" }, + { value: EPluginLevel.Code, text: "Code" }, + { value: EPluginLevel.Data, text: "All" }, +] as const; + +export interface PluginEntry { + id: string; + name: string; + /** Its code is on this device. */ + installed: boolean; +} + +export interface PluginLevelsChoice { + plugins: readonly PluginEntry[]; + /** False before a compare: plugins only on other devices are missing. */ + remoteKnown: boolean; + defaultLevel: EPluginLevel; + levels(): Readonly>; + save(levels: Record): Promise; + onClose(): void; +} + +/** Plugin folders here and plugins only the remote holds, named by their manifest here. */ +export async function listPlugins( + adapter: DataAdapter, + scope: ScopePolicy, + configDir: string, + remote: Manifest | null, +): Promise { + const pluginsDir = `${configDir}/plugins`; + const local = await adapter.list(pluginsDir).then( + (listed) => listed.folders, + () => [], + ); + const ids = new Set(); + for (const path of [...local, ...Object.keys(remote?.files ?? {})]) { + const id = scope.pluginIdOf(path); + if (id) ids.add(id); + } + const entries = await Promise.all( + [...ids].map(async (id): Promise => { + const name = await manifestName( + adapter, + `${pluginsDir}/${id}/manifest.json`, + ); + return { id, name: name ?? id, installed: name !== null }; + }), + ); + return entries.sort((a, b) => a.name.localeCompare(b.name)); +} + +async function manifestName( + adapter: DataAdapter, + path: string, +): Promise { + try { + const { name } = JSON.parse(await adapter.read(path)) as { + name?: unknown; + }; + return typeof name === "string" && name ? name : null; + } catch { + return null; + } +} + +export class PluginLevelsModal extends Modal { + private filter = ""; + + constructor( + app: App, + private readonly choice: PluginLevelsChoice, + ) { + super(app); + } + + onOpen(): void { + const { contentEl, choice } = this; + const fallback = PLUGIN_LEVEL_OPTIONS[choice.defaultLevel].text; + renderModalHead(this, { + icon: "puzzle", + title: "Choose per plugin", + sub: `On this device only. Each level includes the one before; the rest follow Plugins: ${fallback}.`, + }); + const body = contentEl.createDiv({ cls: "mdsync-plugin-levels" }); + const search = new SearchComponent(body).setPlaceholder("Filter plugins…"); + search.inputEl.setAttr("aria-label", "Filter plugins"); + const list = body.createDiv(); + search.onChange((value) => { + this.filter = value.trim().toLowerCase(); + this.renderList(list); + }); + this.renderList(list); + if (!choice.remoteKnown) { + modalHint( + body, + "Plugins only on other devices appear after Check remote.", + ); + } + new ButtonComponent(modalFooter(this)) + .setButtonText("Done") + .onClick(() => this.close()); + } + + onClose(): void { + this.contentEl.empty(); + this.choice.onClose(); + } + + private renderList(list: HTMLElement): void { + list.empty(); + const shown = this.choice.plugins.filter( + ({ id, name }) => + id.toLowerCase().includes(this.filter) || + name.toLowerCase().includes(this.filter), + ); + if (shown.length === 0) { + modalHint( + list, + this.filter ? "No plugins match the filter." : "No plugins found.", + ); + return; + } + const card = modalCard(list); + for (const entry of shown) this.renderRow(card, entry); + } + + private renderRow( + card: HTMLElement, + { id, name, installed }: PluginEntry, + ): void { + const { choice } = this; + const row = card.createDiv({ + cls: "mdsync-modal-row is-compact mdsync-plugin-level-row", + }); + const text = row.createDiv({ cls: "mdsync-modal-row-text" }); + const custom = text + .createDiv({ cls: "mdsync-modal-row-name", text: name }) + .createSpan({ cls: "mdsync-plugin-level-custom", text: "Custom" }); + const detail = [ + name === id ? "" : id, + installed ? "" : "not installed here", + ] + .filter(Boolean) + .join(" · "); + if (detail) + text.createDiv({ cls: "mdsync-modal-row-detail", text: detail }); + const levelOf = (): EPluginLevel => { + const levels = choice.levels(); + return Object.hasOwn(levels, id) + ? (levels[id] ?? choice.defaultLevel) + : choice.defaultLevel; + }; + const mark = () => custom.toggle(levelOf() !== choice.defaultLevel); + mark(); + renderSegments( + row, + `plugin-level-${id}`, + PLUGIN_LEVEL_OPTIONS, + levelOf, + async (level) => { + // A computed key stays an own property even for an id like `__proto__`. + const levels = { ...choice.levels(), [id]: level }; + if (level === choice.defaultLevel) delete levels[id]; + await choice.save(levels); + mark(); + }, + ).el.addClasses(["is-compact", "mdsync-plugin-level"]); + } +} diff --git a/packages/plugin/src/features/sync/scope/plugin-levels.css b/packages/plugin/src/features/sync/scope/plugin-levels.css new file mode 100644 index 00000000..eb7b757f --- /dev/null +++ b/packages/plugin/src/features/sync/scope/plugin-levels.css @@ -0,0 +1,40 @@ +.mdsync-plugin-levels { + display: flex; + flex-direction: column; + gap: var(--size-4-2); +} + +.mdsync-plugin-levels .search-input-container { + width: 100%; + margin: 0; +} + +/* Equal columns would shrink to nothing beside a name. */ +.mdsync-plugin-level { + flex: none; +} + +.mdsync-stacked-setting .mdsync-plugin-level { + flex: 1 1 auto; +} + +/* Rows line up only while a checked label is no wider than the others. */ +.mdsync-plugin-level .mdsync-segment.is-checked { + font-weight: inherit; +} + +.mdsync-plugin-level-custom { + margin-inline-start: var(--size-4-2); + color: var(--text-accent); + font-size: var(--font-ui-smaller); + font-weight: var(--font-normal); +} + +/* Four segments and a name do not fit one phone line. */ +.is-phone .mdsync-plugin-level-row { + flex-wrap: wrap; +} + +.is-phone .mdsync-plugin-level-row .mdsync-plugin-level { + flex: 1 1 100%; +} diff --git a/packages/plugin/src/vault/scanner.ts b/packages/plugin/src/features/sync/scope/scanner.ts similarity index 97% rename from packages/plugin/src/vault/scanner.ts rename to packages/plugin/src/features/sync/scope/scanner.ts index 4958a06f..8785212d 100644 --- a/packages/plugin/src/vault/scanner.ts +++ b/packages/plugin/src/features/sync/scope/scanner.ts @@ -1,20 +1,21 @@ import type { DataAdapter } from "obsidian"; -import { DEFAULT_CONCURRENCY } from "@/constants"; -import { hasDotSegment, sortedByPath, stripTrailingSlash } from "@/shared"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { hasDotSegment, stripTrailingSlash } from "@/core/shared"; +import { runWithConcurrency } from "@/core/utils"; +import type { VaultIndex } from "@/core/vault"; +import { caseInsensitiveDisk } from "@/core/vault"; +import { + createLargeFileGate, + LARGE_FILE_BYTES, +} from "../changes/file-concurrency"; +import { sortedByPath } from "../changes/records"; import type { HashCacheEntry, LocalSnapshot, ManifestEntry, SkippedFile, -} from "@/sync/types"; -import { - createLargeFileGate, - LARGE_FILE_BYTES, - runWithConcurrency, -} from "@/utils"; +} from "../types"; import { buildEntry } from "./entry"; -import type { VaultIndex } from "./file-index"; -import { caseInsensitiveDisk } from "./io"; import type { ScopePolicy } from "./scope"; const RACY_INDEX_WINDOW_MS = 2_000; diff --git a/packages/plugin/src/vault/scope.ts b/packages/plugin/src/features/sync/scope/scope.ts similarity index 63% rename from packages/plugin/src/vault/scope.ts rename to packages/plugin/src/features/sync/scope/scope.ts index c1696387..f0fcf1dc 100644 --- a/packages/plugin/src/vault/scope.ts +++ b/packages/plugin/src/features/sync/scope/scope.ts @@ -1,10 +1,14 @@ -import { PLUGIN_ID } from "@/constants"; -import type { SettingsSyncCategories } from "@/settings/model"; -import { hasDotSegment, normalizePath, stripTrailingSlash } from "@/shared"; -import { isUnder } from "@/sync/space"; -import { EFileKind } from "@/sync/types"; +import { PLUGIN_ID } from "@/core/constants"; +import { EPluginLevel, type SettingsSyncCategories } from "@/core/settings"; +import { + hasDotSegment, + normalizePath, + stripTrailingSlash, +} from "@/core/shared"; +import type { SymlinkDetector } from "@/core/vault"; +import { isUnder } from "../remote/space"; +import { EFileKind } from "../types"; import { type IgnoreMatcher, ignoreNoteOf } from "./ignore"; -import type { SymlinkDetector } from "./symlinks"; /** community-plugins.json is absent on purpose: it has its own toggle, which "core settings" would bypass. */ const CONFIG_CORE_FILES: ReadonlyArray = [ @@ -24,6 +28,16 @@ const CONFIG_THEMES_DIR = "themes/"; const CONFIG_PLUGINS_DIR = "plugins/"; +/** Where `Plugin.saveData` writes a plugin's settings. */ +const PLUGIN_DATA_FILE = "data.json"; + +/** What Obsidian's installer writes; the rest of a plugin folder is the plugin's own data. */ +const PLUGIN_CODE_FILES: ReadonlyArray = [ + "manifest.json", + "main.js", + "styles.css", +]; + const CONFIG_FILE_DENYLIST: ReadonlyArray = [ "workspace.json", "workspace-mobile.json", @@ -53,10 +67,20 @@ export interface ScopePolicy { classify(path: string): EFileKind; isIgnoredByPattern(path: string): boolean; getCategory(path: string): keyof SettingsSyncCategories | null; + /** Obsidian's settings or a plugin's `data.json`: JSON written by `JSON.stringify`, so a conflict merges by key. */ + isSettingsJson(path: string): boolean; + /** Plugin code or the enabled list: Obsidian reads them only when it starts. */ + loadsOnStartup(path: string): boolean; + /** The synced plugin a path lies in; null outside plugins, for MDSync and device-local ones. */ + pluginIdOf(path: string): string | null; } export interface ScopeOptions { settingsSync: SettingsSyncCategories; + /** Every plugin's level while `pluginConfigs` is on; Settings by default. */ + pluginLevel?: EPluginLevel; + /** Plugins whose level differs from the default; they apply with `pluginConfigs` off too. */ + pluginLevels?: Readonly>; configDir: string; /** The space's own rules, read inside its root. */ sharedIgnore?: IgnoreMatcher; @@ -68,10 +92,19 @@ export interface ScopeOptions { otherRoots?: readonly string[]; } +/** The level of a plugin without one of its own. */ +export function defaultPluginLevel( + settingsSync: SettingsSyncCategories, + pluginLevel: EPluginLevel = EPluginLevel.Settings, +): EPluginLevel { + return settingsSync.pluginConfigs ? pluginLevel : EPluginLevel.Off; +} + export function createScopePolicy(options: ScopeOptions): ScopePolicy { const configDir = stripTrailingSlash(options.configDir); const configPrefix = `${configDir}/`; - const ownPluginPrefix = `${configDir}/plugins/${PLUGIN_ID}/`; + // No trailing slash: the folder entry itself must stay out too. + const ownPluginDir = `${configDir}/plugins/${PLUGIN_ID}`; const coreFiles = CONFIG_CORE_FILES.map((f) => `${configDir}/${f}`); const hotkeysFile = `${configDir}/${CONFIG_HOTKEYS_FILE}`; @@ -86,11 +119,18 @@ export function createScopePolicy(options: ScopeOptions): ScopePolicy { const deniedConfigDirs = CONFIG_SUBDIR_DENYLIST.map( (d) => `${configDir}/${d}`, ); - const deviceLocalPluginPrefixes = DEVICE_LOCAL_PLUGIN_IDS.map( - (id) => `${pluginsDir}${id}/`, + const deviceLocalPluginDirs = DEVICE_LOCAL_PLUGIN_IDS.map( + (id) => `${pluginsDir}${id}`, ); const sync = { ...options.settingsSync }; + const defaultLevel = defaultPluginLevel(sync, options.pluginLevel); + const pluginLevels = new Map(Object.entries(options.pluginLevels ?? {})); + const levelOf = (id: string): EPluginLevel => + pluginLevels.get(id) ?? defaultLevel; + const anyPluginSynced = + defaultLevel > EPluginLevel.Off || + [...pluginLevels.values()].some((level) => level > EPluginLevel.Off); const sharedIgnoreMatcher = options.sharedIgnore; const localIgnoreMatcher = options.localIgnore; const symlinks = options.symlinks; @@ -120,7 +160,7 @@ export function createScopePolicy(options: ScopeOptions): ScopePolicy { if (otherRoots.some((other) => isUnder(dir, other))) return false; if (isInVaultDenylist(dirPath)) return false; if (symlinks?.isLink(dir)) return false; - if (dirPath.startsWith(ownPluginPrefix)) return false; + if (isUnder(dir, ownPluginDir)) return false; if ( isIgnoredDir(sharedIgnoreMatcher, dirPath) || isIgnoredDir(localIgnoreMatcher, dirPath) @@ -148,7 +188,7 @@ export function createScopePolicy(options: ScopeOptions): ScopePolicy { const path = normalizePath(rawPath); if (!path || !owns(path)) return false; if (isInVaultDenylist(path)) return false; - if (path.startsWith(ownPluginPrefix)) return false; + if (isUnder(path, ownPluginDir)) return false; if (path.startsWith(configPrefix)) return false; if (hasDotSegment(path)) return false; if (isIgnoreFile(path)) return false; @@ -157,6 +197,34 @@ export function createScopePolicy(options: ScopeOptions): ScopePolicy { getCategory(rawPath) { return configCategory(normalizePath(rawPath)); }, + isSettingsJson(rawPath) { + const path = normalizePath(rawPath); + const category = configCategory(path); + if (category === "pluginConfigs") { + return ( + path === `${pluginsDir}${pluginPath(path).id}/${PLUGIN_DATA_FILE}` + ); + } + return ( + category === "coreSettings" || + category === "hotkeys" || + category === "pluginList" + ); + }, + loadsOnStartup(rawPath) { + const path = normalizePath(rawPath); + if (path === communityPluginsFile) return true; + return ( + configCategory(path) === "pluginConfigs" && + pluginPath(path).needs === EPluginLevel.Code + ); + }, + pluginIdOf(rawPath) { + const path = normalizePath(rawPath); + return configCategory(path) === "pluginConfigs" + ? pluginPath(path).id + : null; + }, }; /** A share's root folder is its mount point, in no space: never published, never removed. */ @@ -174,7 +242,7 @@ export function createScopePolicy(options: ScopeOptions): ScopePolicy { return false; } if (isInVaultDenylist(path)) return false; - if (path.startsWith(ownPluginPrefix)) return false; + if (isUnder(path, ownPluginDir)) return false; // Device-local like ignore patterns: excluded from diff so links are not read as deletions. if (symlinks?.isLink(path)) return false; @@ -200,13 +268,32 @@ export function createScopePolicy(options: ScopeOptions): ScopePolicy { return Boolean(localIgnoreMatcher?.ignores(path)); } + /** A plugin part above its plugin's level stays frozen like a disabled category; the category stays whole for resets. */ function isConfigAllowed(path: string): boolean { const category = configCategory(path); + if (category === "pluginConfigs") { + const { id, needs } = pluginPath(path); + return levelOf(id) >= needs; + } return category !== null && sync[category]; } + /** For a `pluginConfigs` path: its plugin and the level that syncs it. */ + function pluginPath(path: string): { id: string; needs: EPluginLevel } { + const [id = "", file, ...rest] = path.slice(pluginsDir.length).split("/"); + // Directly in `plugins/` is a stray file: folders go through `canDescend`. + if (file === undefined || rest.length > 0) { + return { id, needs: EPluginLevel.Data }; + } + if (file === PLUGIN_DATA_FILE) return { id, needs: EPluginLevel.Settings }; + if (PLUGIN_CODE_FILES.includes(file)) { + return { id, needs: EPluginLevel.Code }; + } + return { id, needs: EPluginLevel.Data }; + } + function configCategory(path: string): keyof SettingsSyncCategories | null { - if (!path.startsWith(configPrefix) || path.startsWith(ownPluginPrefix)) + if (!path.startsWith(configPrefix) || isUnder(path, ownPluginDir)) return null; if (hasDotSegment(stripConfigPrefix(path, configPrefix))) return null; if ( @@ -219,7 +306,7 @@ export function createScopePolicy(options: ScopeOptions): ScopePolicy { if (path === communityPluginsFile) return "pluginList"; if ( path.startsWith(pluginsDir) && - !deviceLocalPluginPrefixes.some((p) => path.startsWith(p)) + !deviceLocalPluginDirs.some((d) => isUnder(path, d)) ) return "pluginConfigs"; if (path.startsWith(snippetsDir)) return "snippets"; @@ -228,16 +315,23 @@ export function createScopePolicy(options: ScopeOptions): ScopePolicy { } function hasConfigDescendants(): boolean { - return Object.values(sync).some((enabled) => enabled); + return Object.values(sync).some((enabled) => enabled) || anyPluginSynced; } function canDescendConfigDir(dirPath: string): boolean { if (deniedConfigDirs.some((d) => dirPath === d || dirPath.startsWith(d))) return false; if (dirPath.startsWith(pluginsDir)) { - if (!sync.pluginConfigs) return false; - return !deviceLocalPluginPrefixes.some( - (p) => dirPath === p || dirPath.startsWith(p), + if (deviceLocalPluginDirs.some((d) => isUnder(dirPath, d))) return false; + const [id, ...below] = dirPath + .slice(pluginsDir.length) + .split("/") + .filter(Boolean); + if (id === undefined) return anyPluginSynced; + // `/` holds the settings file; anything deeper is the plugin's data. + return ( + levelOf(id) >= + (below.length > 0 ? EPluginLevel.Data : EPluginLevel.Settings) ); } if (dirPath.startsWith(snippetsDir)) return sync.snippets; diff --git a/packages/plugin/src/sync/session-state.ts b/packages/plugin/src/features/sync/session-state.ts similarity index 96% rename from packages/plugin/src/sync/session-state.ts rename to packages/plugin/src/features/sync/session-state.ts index 13454946..acd0c3d6 100644 --- a/packages/plugin/src/sync/session-state.ts +++ b/packages/plugin/src/features/sync/session-state.ts @@ -1,10 +1,9 @@ -import { entryAt } from "@/shared"; - -import { diff } from "./diff"; +import { diff } from "./changes/diff"; +import { entryAt } from "./changes/records"; import type { CompareResult, EngineDependencies } from "./engine"; import type { OperationOutcome } from "./operations/types"; -import { type Space, spaceOf } from "./space"; -import { manifestMoved } from "./space-paths"; +import { type Space, spaceOf } from "./remote/space"; +import { manifestMoved } from "./remote/space-paths"; import type { HashCacheEntry, LocalSnapshot, diff --git a/packages/plugin/src/features/sync/settings.ts b/packages/plugin/src/features/sync/settings.ts new file mode 100644 index 00000000..2056e6ba --- /dev/null +++ b/packages/plugin/src/features/sync/settings.ts @@ -0,0 +1,24 @@ +import type { MdsyncSettings } from "@/core/settings"; +import { isStorageConfigured } from "@/features/storage"; + +/** Share records are the spaces slice's: read structurally, never imported. */ +type GuestSettings = Pick< + MdsyncSettings, + "storageConfigs" | "activeStorageKind" +> & { + spaces: readonly { closed?: true; access: { kind: string } }[]; +}; + +/** No vault storage, only shares joined by invite: those sync, the vault stays on this device. */ +export function isGuest(settings: GuestSettings): boolean { + return ( + !isStorageConfigured(settings) && + settings.spaces.some( + (record) => !record.closed && record.access.kind === "participant", + ) + ); +} + +export function canSync(settings: GuestSettings): boolean { + return isStorageConfigured(settings) || isGuest(settings); +} diff --git a/packages/plugin/src/sync/state.ts b/packages/plugin/src/features/sync/state.ts similarity index 92% rename from packages/plugin/src/sync/state.ts rename to packages/plugin/src/features/sync/state.ts index 9cba5de6..bc531ae3 100644 --- a/packages/plugin/src/sync/state.ts +++ b/packages/plugin/src/features/sync/state.ts @@ -1,10 +1,9 @@ import type { DataAdapter } from "obsidian"; -import { PLUGIN_ID } from "@/constants"; -import { randomId } from "@/crypto"; -import { reportWarning } from "@/shared"; -import { writeAtomic } from "@/vault/atomic-write"; -import { ensureParent } from "@/vault/io"; -import { defaultDeviceName } from "./device"; +import { PLUGIN_ID } from "@/core/constants"; +import { randomId } from "@/core/crypto"; +import { reportWarning } from "@/core/shared"; +import { ensureParent, writeAtomic } from "@/core/vault"; +import { defaultDeviceName } from "./identity/device"; import type { LocalState } from "./types"; const STATE_FILE_NAME = "state.json"; diff --git a/packages/plugin/src/sync/status-broadcaster.ts b/packages/plugin/src/features/sync/status-broadcaster.ts similarity index 100% rename from packages/plugin/src/sync/status-broadcaster.ts rename to packages/plugin/src/features/sync/status-broadcaster.ts diff --git a/packages/plugin/src/sync/types.ts b/packages/plugin/src/features/sync/types.ts similarity index 96% rename from packages/plugin/src/sync/types.ts rename to packages/plugin/src/features/sync/types.ts index a8e4af85..da324e04 100644 --- a/packages/plugin/src/sync/types.ts +++ b/packages/plugin/src/features/sync/types.ts @@ -67,6 +67,12 @@ export interface StorageState { shareBases?: Record; } +/** Device-local and never synced: one key of Obsidian's local storage for this vault. */ +export interface LocalStore { + load(): unknown; + save(value: unknown): void; +} + /** Persisted to state.json; the hash cache is storage-agnostic. */ export interface LocalState { deviceId: string; diff --git a/packages/plugin/src/features/sync/ui/automation-section.ts b/packages/plugin/src/features/sync/ui/automation-section.ts new file mode 100644 index 00000000..c2a281f4 --- /dev/null +++ b/packages/plugin/src/features/sync/ui/automation-section.ts @@ -0,0 +1,156 @@ +import type { SettingDefinitionGroup } from "obsidian"; +import { + AUTO_PUSH_SETTLE_MAX_SECONDS, + AUTO_PUSH_SETTLE_MIN_SECONDS, + BULK_DELETE_LIMIT_MAX, + BULK_DELETE_LIMIT_MIN, + SLOW_FILE_SETTLE_MAX_SECONDS, + SLOW_FILE_SETTLE_MIN_SECONDS, +} from "@/core/constants"; +import { + bind, + DEFAULT_CORE_SETTINGS, + EFieldKind, + type FieldContext, + fieldRow, + group, + type SettingsField, + type SettingsHost, +} from "@/core/settings"; +import { pluralize } from "@/core/shared"; + +const INTERVAL_CHOICES: Readonly> = { + 0: "Only at startup", + 5: "Every 5 minutes", + 15: "Every 15 minutes", + 30: "Every 30 minutes", + 60: "Every hour", + 240: "Every 4 hours", +}; + +const AUTOSYNC_FIELD: SettingsField = { + kind: EFieldKind.Toggle, + name: "Autosync", + desc: "Sync automatically: once after startup and on a schedule. Pulls remote changes; conflicts that cannot be merged safely stop the cycle.", + ...bind("autoSyncEnabled"), + rerender: true, +}; + +const AUTOMATION_FIELDS: ReadonlyArray> = [ + AUTOSYNC_FIELD, + { + kind: EFieldKind.Choice, + name: "Interval", + desc: "How often to sync after the sync at startup.", + when: (s) => s.autoSyncEnabled, + sub: true, + options: (s) => intervalChoices(s.autoSyncIntervalMinutes), + get: (s) => String(s.autoSyncIntervalMinutes), + set: (v) => ({ autoSyncIntervalMinutes: Number(v) }), + }, + { + kind: EFieldKind.Toggle, + name: "Push after successful pull", + desc: "After a pull with no conflicts, also push local changes. Disable to only pull and review incoming changes.", + when: (s) => s.autoSyncEnabled, + sub: true, + ...bind("autoPushAfterSync"), + }, + { + kind: EFieldKind.Toggle, + name: "Push after changes settle", + desc: "Queue changed files and push once the vault has been quiet for the delay below. Rapid saves are combined into one compare and push. Never pulls: conflicts and incoming changes are left untouched.", + ...bind("autoPushAfterChange"), + rerender: true, + }, + { + kind: EFieldKind.Slider, + name: "Quiet period (seconds)", + desc: `How long the vault must stay quiet after a change before the queued push runs (${AUTO_PUSH_SETTLE_MIN_SECONDS}–${AUTO_PUSH_SETTLE_MAX_SECONDS}). Shorter pushes sooner, longer batches more saves.`, + when: (s) => s.autoPushAfterChange, + sub: true, + min: AUTO_PUSH_SETTLE_MIN_SECONDS, + max: AUTO_PUSH_SETTLE_MAX_SECONDS, + step: 1, + ...bind("autoPushSettleSeconds"), + }, + { + kind: EFieldKind.Toggle, + name: "Push only queued files", + desc: "Push only files changed during the quiet period. Disable to also push other pending local changes.", + when: (s) => s.autoPushAfterChange, + sub: true, + ...bind("autoPushChangedFilesOnly"), + }, + { + kind: EFieldKind.Text, + name: "Slow files", + desc: "Files ending with these, separated by commas, save every few seconds while you work on them. A push after changes waits until you stop or leave the file, at most 10 minutes. Excalidraw drawings count as .excalidraw.md whatever their name. Pushing by hand sends them at once.", + placeholder: ".excalidraw.md, .canvas", + ...bind("slowFileSuffixes"), + }, + { + kind: EFieldKind.Slider, + name: "Slow files quiet period (seconds)", + desc: `How long a slow file must stay unchanged before an automatic push takes it (${SLOW_FILE_SETTLE_MIN_SECONDS}-${SLOW_FILE_SETTLE_MAX_SECONDS}).`, + sub: true, + min: SLOW_FILE_SETTLE_MIN_SECONDS, + max: SLOW_FILE_SETTLE_MAX_SECONDS, + step: 5, + ...bind("slowFileSettleSeconds"), + }, + { + kind: EFieldKind.Toggle, + name: "Ask before pushing many deletions", + desc: "An automatic push holds back deleting more files than the limit below and asks you to review them first. Guards against storage that briefly hides a folder. Pushing by hand is not affected.", + ...bind("confirmBulkDeletes"), + rerender: true, + }, + { + kind: EFieldKind.Number, + name: "Deletion limit", + desc: `How many deleted files an automatic push may publish without asking (${BULK_DELETE_LIMIT_MIN}-${BULK_DELETE_LIMIT_MAX}).`, + when: (s) => s.confirmBulkDeletes, + sub: true, + get: (s) => String(s.bulkDeleteLimit), + parse: (raw) => + clampInt( + raw, + BULK_DELETE_LIMIT_MIN, + BULK_DELETE_LIMIT_MAX, + DEFAULT_CORE_SETTINGS.bulkDeleteLimit, + ), + set: (v) => ({ bulkDeleteLimit: v }), + }, +]; + +export function automationSection( + ctx: FieldContext, +): SettingDefinitionGroup { + return group( + "Automatic sync", + AUTOMATION_FIELDS.map((field) => fieldRow(ctx, field)), + ); +} + +/** A value from an older version or a setup link stays choosable as it is. */ +function intervalChoices(current: number): Record { + if (current in INTERVAL_CHOICES) return { ...INTERVAL_CHOICES }; + return { + ...INTERVAL_CHOICES, + [current]: `Every ${pluralize(current, "minute")}`, + }; +} + +function clampInt( + raw: string, + min: number, + max: number, + fallback: number, +): number { + const parsed = Number.parseInt(raw, 10); + return Math.max( + min, + Math.min(max, Number.isFinite(parsed) ? parsed : fallback), + ); +} diff --git a/packages/plugin/src/ui/common/change-action.ts b/packages/plugin/src/features/sync/ui/change-action.ts similarity index 85% rename from packages/plugin/src/ui/common/change-action.ts rename to packages/plugin/src/features/sync/ui/change-action.ts index 0a9456c3..defb72dd 100644 --- a/packages/plugin/src/ui/common/change-action.ts +++ b/packages/plugin/src/features/sync/ui/change-action.ts @@ -1,4 +1,4 @@ -import type { EChangeType } from "@/sync/types"; +import type { EChangeType } from "../types"; export type ChangeAction = "add" | "modify" | "delete"; diff --git a/packages/plugin/src/settings/sections/security.ts b/packages/plugin/src/features/sync/ui/encryption-section.ts similarity index 80% rename from packages/plugin/src/settings/sections/security.ts rename to packages/plugin/src/features/sync/ui/encryption-section.ts index 30062384..2f40d129 100644 --- a/packages/plugin/src/settings/sections/security.ts +++ b/packages/plugin/src/features/sync/ui/encryption-section.ts @@ -1,12 +1,18 @@ import type { SettingDefinitionGroup } from "obsidian"; +import { type FieldContext, group } from "@/core/settings"; +import { + askNewPassphrase, + notifyError, + notifyInfo, + reportError, +} from "@/core/ui"; +import { isStorageConfigured } from "@/features/storage"; +import type { SyncHost } from "../host"; +import { PassphraseRotatedError } from "../remote/keyfile"; -import { clearCachedPassphrase } from "@/crypto/passphrase-cache"; -import { type FieldContext, group } from "@/settings/fields"; -import { isStorageConfigured } from "@/settings/model"; -import { PassphraseRotatedError } from "@/sync/keyfile"; -import { askNewPassphrase, notifyError, notifyInfo, reportError } from "@/ui"; - -export function securitySection(ctx: FieldContext): SettingDefinitionGroup { +export function encryptionSection( + ctx: FieldContext, +): SettingDefinitionGroup { const { plugin, rerender } = ctx; return group("Encryption", [ { @@ -17,14 +23,7 @@ export function securitySection(ctx: FieldContext): SettingDefinitionGroup { t.setValue(plugin.settings.cachePassphrase).onChange(async (v) => { Object.assign(plugin.settings, { cachePassphrase: v }); await plugin.saveSettings(); - if (v) { - await plugin.passphrase.persistIfEnabled(); - return; - } - await clearCachedPassphrase( - plugin.app.vault.adapter, - plugin.app.vault.configDir, - ); + await plugin.passphrase.applyCachePreference(); }), ); }, diff --git a/packages/plugin/src/features/sync/ui/history/activity-calendar.css b/packages/plugin/src/features/sync/ui/history/activity-calendar.css new file mode 100644 index 00000000..ff927d75 --- /dev/null +++ b/packages/plugin/src/features/sync/ui/history/activity-calendar.css @@ -0,0 +1,147 @@ +.mdsync-calendar { + position: relative; + --mdsync-cal-cell: 10px; + --mdsync-cal-gap: 3px; + overflow-x: auto; + /* Room for an overlay scrollbar under the strip. */ + padding: 2px 2px var(--size-4-2); + font-size: var(--font-ui-smaller); + color: var(--text-faint); +} + +/* Too small for a finger either way; larger cells and the tap notice make up for it. */ +body.is-phone .mdsync-calendar { + --mdsync-cal-cell: 16px; + --mdsync-cal-gap: 4px; +} + +.mdsync-calendar-months, +.mdsync-calendar-grid, +.mdsync-calendar-bands { + display: flex; + gap: var(--mdsync-cal-gap); + width: max-content; +} + +.mdsync-calendar-month { + width: var(--mdsync-cal-cell); + overflow: visible; + white-space: nowrap; + line-height: 1.6; +} + +.mdsync-calendar-week { + display: flex; + flex-direction: column; + gap: var(--mdsync-cal-gap); +} + +.mdsync-calendar-day { + width: var(--mdsync-cal-cell); + height: var(--mdsync-cal-cell); + border-radius: 2px; + background: var(--background-modifier-border); +} + +.mdsync-calendar-day.is-level-1 { + background: color-mix( + in srgb, + var(--interactive-accent) 32%, + var(--background-modifier-border) + ); +} + +.mdsync-calendar-day.is-level-2 { + background: color-mix( + in srgb, + var(--interactive-accent) 55%, + var(--background-modifier-border) + ); +} + +.mdsync-calendar-day.is-level-3 { + background: color-mix( + in srgb, + var(--interactive-accent) 78%, + var(--background-modifier-border) + ); +} + +.mdsync-calendar-day.is-level-4 { + background: var(--interactive-accent); +} + +/* Only counts remain: no version to open. */ +.mdsync-calendar-day.is-counts:not(.is-level-0) { + opacity: 0.45; +} + +.mdsync-calendar-grid.is-pickable .mdsync-calendar-day { + cursor: pointer; +} + +.mdsync-calendar-grid.is-pickable .mdsync-calendar-day:hover { + outline: 1px solid var(--text-muted); +} + +.mdsync-calendar-day.is-picked { + outline: 1.5px solid var(--text-normal); +} + +.mdsync-calendar-day:focus-visible { + outline: 2px solid var(--interactive-accent); +} + +.mdsync-calendar-bands { + margin-top: var(--size-4-1); +} + +.mdsync-calendar-band { + display: flex; + flex-direction: column; + gap: 3px; + width: calc( + var(--mdsync-weeks) * + (var(--mdsync-cal-cell) + var(--mdsync-cal-gap)) - + var(--mdsync-cal-gap) + ); + min-width: 0; + white-space: nowrap; + overflow: hidden; +} + +.mdsync-calendar-band::before { + content: ""; + height: 2px; + border-radius: 1px; + background: var(--background-modifier-border-hover); +} + +.mdsync-calendar-band[data-res="push"]::before, +.mdsync-calendar-band[data-res="10m"]::before { + background: var(--interactive-accent); +} + +.mdsync-calendar-band[data-res="1h"]::before { + background: color-mix( + in srgb, + var(--interactive-accent) 75%, + var(--background-modifier-border) + ); +} + +.mdsync-calendar-band[data-res="1d"]::before { + background: color-mix( + in srgb, + var(--interactive-accent) 55%, + var(--background-modifier-border) + ); +} + +.mdsync-calendar-band[data-res="1w"]::before { + background: color-mix( + in srgb, + var(--interactive-accent) 35%, + var(--background-modifier-border) + ); +} diff --git a/packages/plugin/src/features/sync/ui/history/activity-calendar.ts b/packages/plugin/src/features/sync/ui/history/activity-calendar.ts new file mode 100644 index 00000000..1381fb0b --- /dev/null +++ b/packages/plugin/src/features/sync/ui/history/activity-calendar.ts @@ -0,0 +1,129 @@ +import { Platform } from "obsidian"; +import { observeResize, tapTooltip } from "@/core/ui"; +import { + type ActivityCalendar, + bandsOf, + type CalendarDay, + dayTooltip, + RESOLUTION_TEXT, +} from "./calendar"; + +/** Narrower bands leave their label out. */ +const LABELED_WEEKS = 4; +/** Cells run day by day, a week per column. */ +const KEY_STEPS: Record = { + ArrowUp: -1, + ArrowDown: 1, + ArrowLeft: -7, + ArrowRight: 7, +}; + +export interface CalendarOptions { + /** Start of the day drawn ringed. */ + picked?: number | null; + onPick?: (day: CalendarDay) => void; +} + +/** Weeks as columns, scrolled to the picked day or today; the strip under them says how each stretch is kept. */ +export function renderActivityCalendar( + parent: HTMLElement, + calendar: ActivityCalendar, + { picked = null, onPick }: CalendarOptions = {}, +): void { + const scroller = parent.createDiv({ cls: "mdsync-calendar" }); + const months = scroller.createDiv({ cls: "mdsync-calendar-months" }); + const grid = scroller.createDiv({ cls: "mdsync-calendar-grid" }); + const days = new Map(); + const cells: HTMLElement[] = []; + for (const week of calendar.weeks) { + months.createSpan({ cls: "mdsync-calendar-month", text: week.month ?? "" }); + const column = grid.createDiv({ cls: "mdsync-calendar-week" }); + for (const day of week.days) { + const key = String(day.start); + days.set(key, day); + const cell = column.createDiv({ + cls: `mdsync-calendar-day is-level-${day.level}`, + attr: { "aria-label": dayTooltip(day), "data-day": key }, + }); + cell.toggleClass("is-counts", day.res === "counts"); + cell.toggleClass("is-picked", day.start === picked); + cells.push(cell); + } + } + renderBands(scroller, calendar.weeks); + const ringed = grid.querySelector(".is-picked"); + const showTip = tapTooltip(); + const pick = (cell: HTMLElement): void => { + const day = days.get(cell.dataset.day ?? ""); + if (!day) return; + if (Platform.isMobile) showTip(cell); + onPick?.(day); + }; + grid.addEventListener("click", (event) => { + const cell = + event.target instanceof Element + ? event.target.closest("[data-day]") + : null; + if (cell) pick(cell); + }); + if (onPick) makeRoving(grid, cells, ringed ?? cells[cells.length - 1], pick); + // Every resize until the person scrolls: settings narrow it as the page opens, a scrollbar or the window later. + const stopAnchor = observeResize(scroller, () => { + if (!scroller.isConnected) return stopAnchor(); + scroller.scrollLeft = ringed + ? ringed.offsetLeft - scroller.clientWidth / 2 + : scroller.scrollWidth; + }); + for (const type of ["pointerdown", "wheel", "keydown"]) + scroller.addEventListener(type, stopAnchor, { once: true, passive: true }); +} + +/** Left out when no week's resolution is known. */ +function renderBands( + scroller: HTMLElement, + weeks: ActivityCalendar["weeks"], +): void { + const bands = bandsOf(weeks); + if (!bands.some((band) => band.res)) return; + const strip = scroller.createDiv({ cls: "mdsync-calendar-bands" }); + for (const band of bands) { + const el = strip.createDiv({ + cls: "mdsync-calendar-band", + attr: { "data-res": band.res ?? "none" }, + }); + el.style.setProperty("--mdsync-weeks", String(band.weeks)); + if (band.res && band.weeks >= LABELED_WEEKS) + el.createSpan({ text: RESOLUTION_TEXT[band.res] }); + } +} + +/** One tab stop for the whole grid; arrows move a day or a week, Enter or Space picks. */ +function makeRoving( + grid: HTMLElement, + cells: readonly HTMLElement[], + start: HTMLElement | undefined, + pick: (cell: HTMLElement) => void, +): void { + grid.addClass("is-pickable"); + for (const cell of cells) { + cell.setAttr("role", "button"); + cell.tabIndex = cell === start ? 0 : -1; + cell.setAttr("aria-pressed", String(cell.hasClass("is-picked"))); + } + grid.addEventListener("keydown", (event) => { + const index = cells.indexOf(event.target as HTMLElement); + const cell = cells[index]; + if (!cell) return; + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + pick(cell); + return; + } + const next = cells[index + (KEY_STEPS[event.key] ?? Number.NaN)]; + if (!next) return; + event.preventDefault(); + cell.tabIndex = -1; + next.tabIndex = 0; + next.focus(); + }); +} diff --git a/packages/plugin/src/features/sync/ui/history/calendar.ts b/packages/plugin/src/features/sync/ui/history/calendar.ts new file mode 100644 index 00000000..ca72c601 --- /dev/null +++ b/packages/plugin/src/features/sync/ui/history/calendar.ts @@ -0,0 +1,211 @@ +import { formatDay, pluralize, startOfDay, startOfWeek } from "@/core/shared"; +import { + countsBefore, + RESOLUTIONS, + type Stage, + stagesOf, +} from "../../history/model/periods"; +import type { Activity, Resolution } from "../../history/model/types"; +import type { Dating } from "../../history/types"; + +const HOUR_MS = 3_600_000; +/** A year: Settings and the Timeline show the same days, so a day picked in one exists in the other. */ +const WEEKS = 53; +/** Upper bounds of pushes per day for levels 1-3; more is level 4. */ +const LEVELS = [5, 12, 24]; + +export const RESOLUTION_TEXT: Record = { + push: "every push", + "10m": "1 per 10 min", + "1h": "1 per hour", + "1d": "1 per day", + "1w": "1 per week", + counts: "counts only", +}; + +export interface CalendarDay { + start: number; + pushes: number; + /** 0 for none, 4 for the busiest. */ + level: number; + /** The coarsest a version covering it is kept at, `counts` between the first push and the oldest version; else null. */ + res: Resolution | null; +} + +export interface CalendarWeek { + /** From Monday, up to today. */ + days: CalendarDay[]; + /** Short month name on the week a month starts in. */ + month: string | null; + /** Its newest kept day's, else the newer week's: a week without a version, after the first push, keeps what surrounds it. */ + res: Resolution | null; +} + +export interface ActivityCalendar { + weeks: CalendarWeek[]; + pushes: number; + since: number; +} + +/** Pushes per local day over `weekCount` weeks to today, with how finely history keeps each day; `versions` null: unknown. */ +export function buildCalendar( + activity: Activity, + versions: readonly Dating[] | null, + weekCount = WEEKS, + now: number = Date.now(), +): ActivityCalendar { + const perDay = new Map(); + let origin = Number.POSITIVE_INFINITY; + for (const [hour, [pushes]] of Object.entries(activity)) { + const day = startOfDay(Number(hour) * HOUR_MS); + perDay.set(day, (perDay.get(day) ?? 0) + pushes); + origin = Math.min(origin, day); + } + const walked = versions?.filter((version) => version.res !== null) ?? []; + const cut = versions + ? walked.reduce( + (oldest, version) => Math.min(oldest, version.firstAt), + Number.POSITIVE_INFINITY, + ) + : Number.NEGATIVE_INFINITY; + // Before the first known push nothing was kept or dropped; activity covers every walked push. + const known = { from: origin, cut }; + const monday = new Date(startOfWeek(now)); + // Built from the date, never by adding hours: a DST switch can skip a midnight. + const dayStart = (offset: number): number => + new Date( + monday.getFullYear(), + monday.getMonth(), + monday.getDate() + offset - 7 * (weekCount - 1), + ).getTime(); + const weeks: CalendarWeek[] = []; + let pushes = 0; + for (let week = 0; week < weekCount; week++) { + const days: CalendarDay[] = []; + for (let index = 0; index < 7; index++) { + const start = dayStart(week * 7 + index); + if (start > now) break; + const count = perDay.get(start) ?? 0; + pushes += count; + days.push({ + start, + pushes: count, + level: levelOf(count), + res: dayRes(start, dayStart(week * 7 + index + 1), walked, known), + }); + } + const opens = new Date(days[0]?.start ?? 0); + const previous = weeks[weeks.length - 1]?.days[0]?.start; + const starts = + previous === undefined + ? opens.getDate() <= 7 + : new Date(previous).getMonth() !== opens.getMonth(); + weeks.push({ + days, + month: starts + ? opens.toLocaleDateString(undefined, { month: "short" }) + : null, + res: [...days].reverse().find((day) => day.res)?.res ?? null, + }); + } + for (let index = weeks.length - 2; index >= 0; index--) { + const week = weeks[index] as CalendarWeek; + const last = week.days[week.days.length - 1]?.start ?? 0; + if (last >= known.from) week.res ??= weeks[index + 1]?.res ?? null; + } + return { weeks, pushes, since: dayStart(0) }; +} + +export interface LadderStep { + res: Resolution; + title: string; + /** The ages it covers: "Last 7 days", "Back to 29 Jul", "Older". */ + span: string; +} + +/** How finely history keeps each age under `horizon`, newest first. */ +export function ladderOf( + horizon: number | null, + now: number = Date.now(), +): LadderStep[] { + const stages = stagesOf(horizon); + return stages.map(({ res }, index) => { + const text = RESOLUTION_TEXT[res]; + return { + res, + title: + res === "counts" + ? "Activity only" + : `${text.charAt(0).toUpperCase()}${text.slice(1)}`, + span: spanOf(res, stages[index + 1], now), + }; + }); +} + +/** A stage lasts until the next one may start. */ +function spanOf(res: Resolution, next: Stage | undefined, now: number): string { + if (res === "counts") return "Older"; + if (!next) return "Kept for good"; + if (next.res === "counts") + return `Back to ${formatDay(countsBefore(now, next.from), now, false)}`; + const hours = next.from / HOUR_MS; + if (hours === 1) return "Last hour"; + return hours <= 24 ? `Last ${hours} hours` : `Last ${hours / 24} days`; +} + +/** Runs of weeks kept alike, oldest first, for the strip under the calendar. */ +export function bandsOf( + weeks: readonly CalendarWeek[], +): Array<{ res: Resolution | null; weeks: number }> { + const bands: Array<{ res: Resolution | null; weeks: number }> = []; + for (const { res } of weeks) { + const last = bands[bands.length - 1]; + if (last && last.res === res) last.weeks++; + else bands.push({ res, weeks: 1 }); + } + return bands; +} + +/** "Wed 14 Oct: 21 pushes · versions 1 per day". */ +export function dayTooltip(day: CalendarDay, now: number = Date.now()): string { + const date = formatDay(day.start, now); + if (day.pushes === 0) return `${date}: no pushes`; + const count = `${date}: ${pluralize(day.pushes, "push", "pushes")}`; + if (day.res === null) return count; + return day.res === "counts" + ? `${count} · only counts kept` + : `${count} · versions ${RESOLUTION_TEXT[day.res]}`; +} + +function levelOf(pushes: number): number { + if (pushes === 0) return 0; + const index = LEVELS.findIndex((bound) => pushes <= bound); + return index === -1 ? LEVELS.length + 1 : index + 1; +} + +function dayRes( + start: number, + end: number, + walked: readonly Dating[], + known: { from: number; cut: number }, +): Resolution | null { + const covering = walked + .filter((version) => version.firstAt < end && version.at >= start) + .map((version) => version.res); + const counted = start >= known.from && end <= known.cut; + return coarsest(covering) ?? (counted ? "counts" : null); +} + +function coarsest( + resolutions: ReadonlyArray, +): Resolution | null { + let found: Resolution | null = null; + for (const res of resolutions) { + if ( + res && + (!found || RESOLUTIONS.indexOf(res) > RESOLUTIONS.indexOf(found)) + ) + found = res; + } + return found; +} diff --git a/packages/plugin/src/features/sync/ui/history/history-section.ts b/packages/plugin/src/features/sync/ui/history/history-section.ts new file mode 100644 index 00000000..12bb75e8 --- /dev/null +++ b/packages/plugin/src/features/sync/ui/history/history-section.ts @@ -0,0 +1,101 @@ +import type { SettingDefinitionGroup } from "obsidian"; +import { HISTORY_KEEP_MS, HISTORY_KEEP_TEXT } from "@/core/constants"; +import { + bind, + EFieldKind, + type FieldContext, + fieldRow, + group, + type HistoryKeep, + type SettingsField, + type SettingsHost, + type SettingsRow, + SUB_SETTING_CLASS, +} from "@/core/settings"; +import { closePluginSettings } from "@/core/ui"; +import type { SnapshotListResult } from "../../history/types"; +import type { HistorySectionHost } from "../../host"; +import { renderHistoryHolds } from "./holds-row"; + +const KEEP_HISTORY_FIELD: SettingsField = { + kind: EFieldKind.Choice, + name: "Keep history for", + desc: "Every push stays for an hour, then one version per 10 minutes, hour, day and week; past this only how busy each day was remains. Pinned versions stay. Each device thins the same history, so the shortest choice among them applies.", + when: (s) => s.fileHistoryEnabled, + sub: true, + options: HISTORY_KEEP_TEXT, + get: (s) => s.fileHistoryKeep, + set: (v) => ({ fileHistoryKeep: v as HistoryKeep }), + after: (plugin) => plugin.refreshSourceControlView(true), + // The ladder below it follows the choice. + rerender: true, +}; + +const HISTORY_FIELDS: ReadonlyArray> = [ + { + kind: EFieldKind.Toggle, + name: "Keep history", + desc: "Keep past versions of files so you can view or restore them. Each push stores what it changed as a small encrypted record; old versions thin out automatically.", + ...bind("fileHistoryEnabled"), + rerender: true, + }, + KEEP_HISTORY_FIELD, + { + kind: EFieldKind.Toggle, + name: "Show activity in Timeline", + desc: "A calendar of pushes per day above the Timeline; select a day to jump to it.", + when: (s) => s.fileHistoryEnabled, + sub: true, + ...bind("fileHistoryActivity"), + after: (plugin) => plugin.refreshSourceControlView(), + }, + { + kind: EFieldKind.Toggle, + name: "Auto-refresh history after push", + desc: "Reload the open file-history view automatically when a push completes. Disable to refresh only via the ⟳ button.", + when: (s) => s.fileHistoryEnabled, + sub: true, + ...bind("historyAutoRefresh"), + }, +]; + +/** What the History page's row says beside its name. */ +export function historyValue(plugin: SettingsHost): string { + const { fileHistoryEnabled, fileHistoryKeep } = plugin.settings; + return fileHistoryEnabled ? HISTORY_KEEP_TEXT[fileHistoryKeep] : "Off"; +} + +export function historySection( + ctx: FieldContext, + loadHistory: () => Promise, +): SettingDefinitionGroup { + const rows = HISTORY_FIELDS.map((field) => fieldRow(ctx, field)); + const keep = HISTORY_FIELDS.indexOf(KEEP_HISTORY_FIELD) + 1; + return group(undefined, [ + ...rows.slice(0, keep), + historyHoldsRow(ctx.plugin, loadHistory), + ...rows.slice(keep), + ]); +} + +function historyHoldsRow( + plugin: HistorySectionHost, + loadHistory: () => Promise, +): SettingsRow { + return { + name: "What history holds", + desc: "Pushes per day across your devices. Faded days keep counts only. Select a day to open it in Timeline.", + visible: () => plugin.settings.fileHistoryEnabled, + render: (setting) => { + setting.settingEl.addClass(SUB_SETTING_CLASS); + renderHistoryHolds(setting, { + load: loadHistory, + horizon: HISTORY_KEEP_MS[plugin.settings.fileHistoryKeep], + onPick: (day) => { + closePluginSettings(plugin.app); + void plugin.openTimeline(day.start); + }, + }); + }, + }; +} diff --git a/packages/plugin/src/features/sync/ui/history/holds-row.css b/packages/plugin/src/features/sync/ui/history/holds-row.css new file mode 100644 index 00000000..4e510c8e --- /dev/null +++ b/packages/plugin/src/features/sync/ui/history/holds-row.css @@ -0,0 +1,75 @@ +/* The calendar and the ladder take the row's whole width, under its name. */ +.mdsync-holds.setting-item { + flex-direction: column; + align-items: stretch; + gap: var(--size-4-3); +} + +.mdsync-holds .setting-item-info { + margin-inline-end: 0; +} + +/* Obsidian's phone rule aligns a modal's stacked rows to the start, which would shrink the body to its content. */ +.mdsync-holds-body { + align-self: stretch; +} + +.mdsync-holds-calendar { + min-height: 120px; + color: var(--text-faint); + font-size: var(--font-ui-smaller); +} + +.mdsync-holds-ladder { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(72px, 1fr)); + gap: var(--size-4-1); +} + +/* Three to a row on a phone: auto-fit would leave the six steps four and two. */ +.is-phone .mdsync-holds-ladder { + grid-template-columns: repeat(3, minmax(0, 1fr)); +} + +.mdsync-holds-step { + padding: var(--size-4-2); + border: 1px solid var(--background-modifier-border); + border-radius: var(--radius-m); + background: var(--background-secondary); +} + +.mdsync-holds-title { + margin-top: var(--size-4-2); + font-size: var(--font-ui-smaller); + font-weight: var(--font-semibold); + color: var(--text-normal); +} + +.mdsync-holds-span { + font-size: var(--font-smallest); + color: var(--text-muted); +} + +.mdsync-holds-ticks { + display: flex; + justify-content: space-between; + height: 12px; +} + +.mdsync-holds-ticks span { + width: 2px; + border-radius: 1px; + background: var(--interactive-accent); +} + +.mdsync-holds-step[data-res="counts"] .mdsync-holds-ticks { + width: 28px; + background: repeating-linear-gradient( + 90deg, + var(--background-modifier-border-hover) 0 8px, + transparent 8px 10px + ); + background-size: 100% 8px; + background-repeat: no-repeat; + background-position: left center; +} diff --git a/packages/plugin/src/features/sync/ui/history/holds-row.ts b/packages/plugin/src/features/sync/ui/history/holds-row.ts new file mode 100644 index 00000000..772b3e00 --- /dev/null +++ b/packages/plugin/src/features/sync/ui/history/holds-row.ts @@ -0,0 +1,65 @@ +import type { Setting } from "obsidian"; +import { errorMessage } from "@/core/shared"; +import { alertLine } from "@/core/ui"; +import type { Resolution } from "../../history/model/types"; +import type { SnapshotListResult } from "../../history/types"; +import { renderActivityCalendar } from "./activity-calendar"; +import { buildCalendar, type CalendarDay, ladderOf } from "./calendar"; + +/** Ticks spread across a card, sparser down the ladder; counts draws its own. */ +const TICKS: Record = { + push: 16, + "10m": 9, + "1h": 5, + "1d": 3, + "1w": 2, + counts: 0, +}; + +export interface HoldsOptions { + load: () => Promise; + horizon: number | null; + onPick: (day: CalendarDay) => void; +} + +/** **What history holds**: a year of pushes over how each stretch is kept, then the ladder for `horizon`. */ +export function renderHistoryHolds( + setting: Setting, + { load, horizon, onPick }: HoldsOptions, +): void { + setting.setClass("mdsync-holds"); + const body = setting.settingEl.createDiv({ cls: "mdsync-holds-body" }); + const calendar = body.createDiv({ + cls: "mdsync-holds-calendar", + text: "Reading history…", + }); + const ladder = body.createDiv({ cls: "mdsync-holds-ladder" }); + for (const step of ladderOf(horizon)) { + const card = ladder.createDiv({ + cls: "mdsync-holds-step", + attr: { "data-res": step.res }, + }); + const ticks = card.createDiv({ cls: "mdsync-holds-ticks" }); + for (let tick = 0; tick < TICKS[step.res]; tick++) ticks.createSpan(); + card.createDiv({ cls: "mdsync-holds-title", text: step.title }); + card.createDiv({ cls: "mdsync-holds-span", text: step.span }); + } + load().then( + (result) => { + // Settings may have redrawn or closed meanwhile. + if (!calendar.isConnected) return; + calendar.empty(); + renderActivityCalendar( + calendar, + buildCalendar(result.activity, result.snapshots), + { onPick }, + ); + }, + (error: unknown) => { + calendar.empty(); + alertLine(calendar).setText( + `Could not read history: ${errorMessage(error)}`, + ); + }, + ); +} diff --git a/packages/plugin/src/ui/actions/ignore-action.ts b/packages/plugin/src/features/sync/ui/ignore-action.ts similarity index 93% rename from packages/plugin/src/ui/actions/ignore-action.ts rename to packages/plugin/src/features/sync/ui/ignore-action.ts index e6b3f14b..aca8d836 100644 --- a/packages/plugin/src/ui/actions/ignore-action.ts +++ b/packages/plugin/src/features/sync/ui/ignore-action.ts @@ -1,22 +1,20 @@ import { type App, type Menu, TFile, TFolder } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; +import { notifyError, notifyInfo, openChoiceModal } from "@/core/ui"; +import type { SyncHost } from "../host"; +import { isUnder, spaceOf } from "../remote/space"; +import { ignoreHome, ignoreNoteOf, isIgnoreNote } from "../scope/ignore"; import { appendIgnoreRule, buildIgnoreRule, removeIgnoreRule, -} from "@/settings/ignore-rules"; -import { isUnder, spaceOf } from "@/sync/space"; -import { notifyError, notifyInfo } from "@/ui/common"; -import { openChoiceModal } from "@/ui/modals"; -import { ignoreHome, ignoreNoteOf, isIgnoreNote } from "@/vault/ignore"; +} from "../scope/ignore-rules"; const IGNORE_RULES_CHANGED = "Ignore rules changed."; /** One ignore entry per menu: a plain path opens a level picker, an ignored one clears both levels at once. */ export function addIgnoreMenuItem( menu: Menu, - plugin: PluginHost, + plugin: SyncHost, path: string, isFolder: boolean, titlePrefix = "", @@ -47,7 +45,7 @@ export function addIgnoreMenuItem( type IgnoreLevel = "local" | "global"; async function chooseIgnoreLevel( - plugin: PluginHost, + plugin: SyncHost, path: string, isFolder: boolean, ): Promise { @@ -80,7 +78,7 @@ async function askIgnoreLevel( } export async function toggleLocalIgnore( - plugin: PluginHost, + plugin: SyncHost, path: string, isFolder: boolean, ): Promise { @@ -116,7 +114,7 @@ export async function toggleLocalIgnore( } export async function toggleGlobalIgnore( - plugin: PluginHost, + plugin: SyncHost, path: string, isFolder: boolean, ): Promise { @@ -142,7 +140,7 @@ export async function toggleGlobalIgnore( } export async function stopIgnoring( - plugin: PluginHost, + plugin: SyncHost, path: string, isFolder: boolean, ): Promise { @@ -188,7 +186,7 @@ export async function stopIgnoring( * none of it is shared. */ export async function carryVaultIgnores( - plugin: PluginHost, + plugin: SyncHost, root: string, ): Promise { const ignored = [...plugin.ignoreState.ignoredPaths()].filter( @@ -215,7 +213,7 @@ export async function carryVaultIgnores( /** Read, edit, write back; null when it failed (and said so), false when unchanged. */ async function editIgnoreNote( - plugin: PluginHost, + plugin: SyncHost, note: string, edit: (content: string) => string, ): Promise { diff --git a/packages/plugin/src/ui/actions/maintenance-actions.ts b/packages/plugin/src/features/sync/ui/maintenance-actions.ts similarity index 78% rename from packages/plugin/src/ui/actions/maintenance-actions.ts rename to packages/plugin/src/features/sync/ui/maintenance-actions.ts index 4baf6409..bb2a0ce8 100644 --- a/packages/plugin/src/ui/actions/maintenance-actions.ts +++ b/packages/plugin/src/features/sync/ui/maintenance-actions.ts @@ -1,13 +1,17 @@ -import type { PluginHost } from "@/plugin/host"; -import { activeStorage } from "@/settings/model"; -import { describeStorageTarget } from "@/storage"; -import { cleanSummary } from "@/sync/maintenance"; -import { notifyError, notifyInfo, reportError } from "@/ui/common"; -import { confirmRemoteReset, openConfirmModal } from "@/ui/modals"; +import { + notifyError, + notifyInfo, + openConfirmModal, + reportError, +} from "@/core/ui"; +import { activeStorage, describeStorageTarget } from "@/features/storage"; +import type { SyncHost } from "../host"; +import { cleanSummary } from "../runtime/maintenance"; +import { confirmRemoteReset } from "./reset-modal"; const NO_STORAGE = "Configure a storage backend first."; -export async function verifyRemoteIntegrity(plugin: PluginHost): Promise { +export async function verifyRemoteIntegrity(plugin: SyncHost): Promise { try { const result = await plugin.controller.maintenance.verifyRemote(true); if (!result) { @@ -27,7 +31,7 @@ export async function verifyRemoteIntegrity(plugin: PluginHost): Promise { } export async function deepCleanOrphanedObjects( - plugin: PluginHost, + plugin: SyncHost, ): Promise { const confirmed = await openConfirmModal({ app: plugin.app, @@ -52,7 +56,7 @@ export async function deepCleanOrphanedObjects( } } -export async function resetLocalState(plugin: PluginHost): Promise { +export async function resetLocalState(plugin: SyncHost): Promise { const confirmed = await openConfirmModal({ app: plugin.app, title: "Reset local state?", @@ -73,7 +77,7 @@ export async function resetLocalState(plugin: PluginHost): Promise { } /** Returns true when the remote was reset, so callers can follow up. */ -export async function resetRemoteStorage(plugin: PluginHost): Promise { +export async function resetRemoteStorage(plugin: SyncHost): Promise { const confirmed = await confirmRemoteReset(plugin.app, { description: describeStorageTarget(activeStorage(plugin.settings)), }); diff --git a/packages/plugin/src/settings/sections/maintenance.ts b/packages/plugin/src/features/sync/ui/maintenance-section.ts similarity index 88% rename from packages/plugin/src/settings/sections/maintenance.ts rename to packages/plugin/src/features/sync/ui/maintenance-section.ts index 925282ec..c0322b47 100644 --- a/packages/plugin/src/settings/sections/maintenance.ts +++ b/packages/plugin/src/features/sync/ui/maintenance-section.ts @@ -1,20 +1,19 @@ import type { SettingDefinitionGroup } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; -import { type FieldContext, group } from "@/settings/fields"; +import { type FieldContext, group } from "@/core/settings"; +import type { SyncHost } from "../host"; import { deepCleanOrphanedObjects, resetLocalState, resetRemoteStorage, verifyRemoteIntegrity, -} from "@/ui"; +} from "./maintenance-actions"; interface MaintenanceAction { name: string; desc: string; buttonText: string; warning?: boolean; - run: (plugin: PluginHost) => Promise; + run: (plugin: SyncHost) => Promise; } const MAINTENANCE_ACTIONS: ReadonlyArray = [ @@ -49,7 +48,7 @@ const MAINTENANCE_ACTIONS: ReadonlyArray = [ export function maintenanceSection({ plugin, -}: FieldContext): SettingDefinitionGroup { +}: FieldContext): SettingDefinitionGroup { return group( undefined, MAINTENANCE_ACTIONS.map((action) => ({ diff --git a/packages/plugin/src/ui/source-control/modals.ts b/packages/plugin/src/features/sync/ui/modals.ts similarity index 94% rename from packages/plugin/src/ui/source-control/modals.ts rename to packages/plugin/src/features/sync/ui/modals.ts index c1a4fa20..f8eaae7b 100644 --- a/packages/plugin/src/ui/source-control/modals.ts +++ b/packages/plugin/src/features/sync/ui/modals.ts @@ -1,7 +1,6 @@ import type { App } from "obsidian"; - -import { EConflictStrategy } from "@/sync/controller"; -import { openConfirmModal } from "@/ui/modals"; +import { openConfirmModal } from "@/core/ui"; +import { EConflictStrategy } from "../controller"; export function confirmBatchResolve( app: App, diff --git a/packages/plugin/src/ui/actions/push-action.ts b/packages/plugin/src/features/sync/ui/push-action.ts similarity index 77% rename from packages/plugin/src/ui/actions/push-action.ts rename to packages/plugin/src/features/sync/ui/push-action.ts index 08a32a30..7804d6a2 100644 --- a/packages/plugin/src/ui/actions/push-action.ts +++ b/packages/plugin/src/features/sync/ui/push-action.ts @@ -1,9 +1,7 @@ import type { Menu } from "obsidian"; - -import { SOURCE_CONTROL_VIEW_TYPE } from "@/constants"; -import type { PluginHost } from "@/plugin/host"; -import { notifyError, notifyInfo, runWithNotice } from "@/ui/common"; -import { openSourceControlView } from "@/ui/source-control-view"; +import { notifyError, notifyInfo, runWithNotice } from "@/core/ui"; +import type { SyncHost } from "../host"; +import { heldByConflicts } from "./sync-actions"; /** Changes inside `scope`: a file matches itself, a folder everything below it (the vault root "/" covers all). */ export function scopedPaths( @@ -28,7 +26,7 @@ function folderPrefix(scope: string): string { /** File-explorer and editor right-click entry: push one file or a folder. */ export function addPushMenuItem( menu: Menu, - plugin: PluginHost, + plugin: SyncHost, path: string, isFolder: boolean, ): void { @@ -42,7 +40,7 @@ export function addPushMenuItem( } export async function pushScope( - plugin: PluginHost, + plugin: SyncHost, path: string, isFolder: boolean, ): Promise { @@ -63,17 +61,17 @@ export async function pushScope( ); return; } - const conflicts = scopedPaths(diff.conflicts, path, isFolder); - if (conflicts.length > 0) { - notifyInfo( - conflicts.length === 1 - ? `Resolve the conflict in "${conflicts[0]}" first.` - : `Resolve ${conflicts.length} conflicts under this ${target} first.`, - ); - await openSourceControlView(plugin.app, SOURCE_CONTROL_VIEW_TYPE); + const paths = scopedPaths(diff.localChanges, path, isFolder); + // A conflict elsewhere in the same space holds this push too. + const held = heldByConflicts(plugin.controller, [ + ...scopedPaths(diff.conflicts, path, isFolder), + ...paths, + ]); + if (held) { + notifyInfo(held); + await plugin.openSourceControl(); return; } - const paths = scopedPaths(diff.localChanges, path, isFolder); if (paths.length === 0) { const where = isFolder && path === "/" diff --git a/packages/plugin/src/ui/modals/reset-modal.ts b/packages/plugin/src/features/sync/ui/reset-modal.ts similarity index 96% rename from packages/plugin/src/ui/modals/reset-modal.ts rename to packages/plugin/src/features/sync/ui/reset-modal.ts index 444620f4..b41450c0 100644 --- a/packages/plugin/src/ui/modals/reset-modal.ts +++ b/packages/plugin/src/features/sync/ui/reset-modal.ts @@ -1,13 +1,11 @@ import { type App, ButtonComponent, Modal, Setting } from "obsidian"; - import { modalFooter, modalWarning, onEnter, + openPromiseModal, renderModalHead, -} from "@/ui/common"; - -import { openPromiseModal } from "./promise-modal"; +} from "@/core/ui"; const CONFIRMATION_TEXT = "RESET"; diff --git a/packages/plugin/src/ui/common/skipped.ts b/packages/plugin/src/features/sync/ui/skipped.ts similarity index 87% rename from packages/plugin/src/ui/common/skipped.ts rename to packages/plugin/src/features/sync/ui/skipped.ts index 50086501..07f3c2a2 100644 --- a/packages/plugin/src/ui/common/skipped.ts +++ b/packages/plugin/src/features/sync/ui/skipped.ts @@ -1,6 +1,6 @@ -import { formatBytes } from "@/shared"; -import type { SyncController } from "@/sync/controller"; -import type { SkippedFile } from "@/sync/types"; +import { formatBytes } from "@/core/shared"; +import type { SyncController } from "../controller"; +import type { SkippedFile } from "../types"; /** One instance: callers cache by identity. */ const NONE: readonly SkippedFile[] = []; diff --git a/packages/plugin/src/features/sync/ui/sync-actions.ts b/packages/plugin/src/features/sync/ui/sync-actions.ts new file mode 100644 index 00000000..1e854b13 --- /dev/null +++ b/packages/plugin/src/features/sync/ui/sync-actions.ts @@ -0,0 +1,98 @@ +import { notifyError, notifyInfo, runWithNotice } from "@/core/ui"; +import type { SyncController } from "../controller"; +import type { SyncHost } from "../host"; +import type { DiffResult } from "../types"; + +export async function runCompare(plugin: SyncHost): Promise { + try { + await plugin.controller.refresh(); + await plugin.openChanges(); + } catch (err) { + notifyError("Compare failed", err); + } +} + +export async function runPushAll(plugin: SyncHost): Promise { + try { + // Re-compare first: a stale diff can push a file another device changed, or miss conflicts. + await plugin.controller.refresh(); + const diff = comparedDiff(plugin); + if (!diff || (await announceConflicts(plugin, diff))) return; + // A read-only share's changes cannot go out; they must not hold back the rest. + const paths = diff.localChanges + .map((c) => c.path) + .filter((path) => !plugin.controller.spaceFor(path).readOnly); + if (paths.length === 0) { + notifyInfo("Nothing to push."); + return; + } + await runWithNotice( + () => plugin.controller.pushPaths(paths), + `Pushed ${paths.length} file(s).`, + "Push all failed", + ); + } catch (err) { + notifyError("Push all failed", err); + } +} + +export async function runPullAll(plugin: SyncHost): Promise { + try { + await plugin.controller.refresh(); + const diff = comparedDiff(plugin); + if (!diff || (await announceConflicts(plugin, diff))) return; + const paths = diff.remoteChanges.map((c) => c.path); + if (paths.length === 0) { + notifyInfo("Nothing to pull."); + return; + } + await runWithNotice( + () => plugin.controller.pullPaths(paths), + `Pulled ${paths.length} file(s).`, + "Pull all failed", + ); + } catch (err) { + notifyError("Pull all failed", err); + } +} + +/** The fresh compare's diff; null, said so, when the compare did not finish. */ +function comparedDiff(plugin: SyncHost): DiffResult | null { + const { error, result } = plugin.controller.getSnapshot(); + if (error) throw new Error(error); + if (!result) notifyInfo("The compare did not finish. Try again."); + return result?.diff ?? null; +} + +/** Push and pull must never choose a side silently; conflicts go to the user. */ +async function announceConflicts( + plugin: SyncHost, + diff: DiffResult, +): Promise { + if (diff.conflicts.length === 0) return false; + notifyInfo(conflictsFirst(diff.conflicts.map((c) => c.path))); + await plugin.openChanges(); + return true; +} + +export function conflictsFirst(paths: ReadonlyArray): string { + const which = + paths.length === 1 + ? `the conflict in "${paths[0]}"` + : `the ${paths.length} conflicts`; + return `Resolve ${which} first: nothing pushes or pulls until then.`; +} + +/** Why `paths` cannot go now, or null: an open conflict holds every push and pull of its space. */ +export function heldByConflicts( + controller: Pick, + paths: ReadonlyArray, +): string | null { + const conflicts = controller.getSnapshot().result?.diff.conflicts ?? []; + if (conflicts.length === 0) return null; + const spaces = new Set(paths.map((path) => controller.spaceFor(path).id)); + const holding = conflicts + .map((c) => c.path) + .filter((path) => spaces.has(controller.spaceFor(path).id)); + return holding.length > 0 ? conflictsFirst(holding) : null; +} diff --git a/packages/plugin/src/plugin/vault-adoption.ts b/packages/plugin/src/features/sync/ui/vault-adoption.ts similarity index 74% rename from packages/plugin/src/plugin/vault-adoption.ts rename to packages/plugin/src/features/sync/ui/vault-adoption.ts index 40a20820..1445c0f5 100644 --- a/packages/plugin/src/plugin/vault-adoption.ts +++ b/packages/plugin/src/features/sync/ui/vault-adoption.ts @@ -1,9 +1,8 @@ import type { Plugin } from "obsidian"; - -import type { SyncController, SyncStatusSnapshot } from "@/sync/controller"; -import { confirmAdoptNewVault, notifyError, notifyInfo } from "@/ui"; - -const VAULT_MISMATCH_ERROR = "Remote vault id does not match local"; +import { notifyError, notifyInfo } from "@/core/ui"; +import type { SyncController, SyncStatusSnapshot } from "../controller"; +import { isVaultMismatch } from "../identity/vault-mismatch"; +import { confirmAdoptNewVault } from "./modals"; /** * Offers to adopt the remote vault when its id stopped matching ours, usually because another device reset @@ -17,9 +16,7 @@ export function registerVaultAdoptionPrompt( let active = false; const maybePrompt = async (snapshot: SyncStatusSnapshot): Promise => { - if (active || !(snapshot.error?.includes(VAULT_MISMATCH_ERROR) ?? false)) { - return; - } + if (active || !isVaultMismatch(snapshot.error)) return; active = true; try { if (!(await confirmAdoptNewVault(plugin.app))) return; diff --git a/packages/plugin/src/features/transfer/host.ts b/packages/plugin/src/features/transfer/host.ts new file mode 100644 index 00000000..3db22ffb --- /dev/null +++ b/packages/plugin/src/features/transfer/host.ts @@ -0,0 +1,9 @@ +import type { App } from "obsidian"; +import type { SettingsHost } from "@/core/settings"; +import type { SettingsTransferController } from "./transfer-controller"; + +/** What device transfer needs from the plugin. */ +export interface TransferHost extends SettingsHost { + readonly app: App; + readonly transfer: SettingsTransferController; +} diff --git a/packages/plugin/src/features/transfer/index.ts b/packages/plugin/src/features/transfer/index.ts new file mode 100644 index 00000000..ab8183e4 --- /dev/null +++ b/packages/plugin/src/features/transfer/index.ts @@ -0,0 +1,5 @@ +export type { TransferHost } from "./host"; +export { TRANSFER_ACTION } from "./transfer"; +export { SettingsTransferController } from "./transfer-controller"; +export { deviceTransferSection } from "./ui/device-transfer-section"; +export { showSettingsTransferExport } from "./ui/settings-transfer-export-modal"; diff --git a/packages/plugin/src/settings/transfer-controller.ts b/packages/plugin/src/features/transfer/transfer-controller.ts similarity index 92% rename from packages/plugin/src/settings/transfer-controller.ts rename to packages/plugin/src/features/transfer/transfer-controller.ts index 08c7d025..3a0761c0 100644 --- a/packages/plugin/src/settings/transfer-controller.ts +++ b/packages/plugin/src/features/transfer/transfer-controller.ts @@ -1,9 +1,7 @@ import type { App, ObsidianProtocolData } from "obsidian"; - -import type { PassphraseManager } from "@/core"; -import { confirmSettingsTransferImport, notifyError, notifyInfo } from "@/ui"; - -import type { MdsyncSettings } from "./model"; +import type { MdsyncSettings } from "@/core/settings"; +import { notifyError, notifyInfo } from "@/core/ui"; +import type { PassphraseManager } from "@/features/sync"; import { createSettingsTransferPackage, importedSections, @@ -12,6 +10,7 @@ import { type SettingsTransferExportOptions, type SettingsTransferPackage, } from "./transfer"; +import { confirmSettingsTransferImport } from "./ui/settings-transfer-modal"; export interface SettingsTransferDeps { app: App; diff --git a/packages/plugin/src/settings/transfer.ts b/packages/plugin/src/features/transfer/transfer.ts similarity index 92% rename from packages/plugin/src/settings/transfer.ts rename to packages/plugin/src/features/transfer/transfer.ts index b9452f92..dbc9189f 100644 --- a/packages/plugin/src/settings/transfer.ts +++ b/packages/plugin/src/features/transfer/transfer.ts @@ -1,19 +1,20 @@ -import { LINK_PARAM, openLink, sealLink } from "@/crypto/sealed-link"; +import { LINK_PARAM, openLink, sealLink } from "@/core/crypto"; import { + DEFAULT_CORE_SETTINGS, + DEFAULT_SETTINGS_SYNC, + type MdsyncSettings, + mergeCoreSettings, + type SettingsSyncCategories, +} from "@/core/settings"; +import { + activeStorage, type CompactStorageConfig, compactStorageConfig, EStorageBackend, + parseStorageSettings, type StorageAdapterConfig, storageDefaults, -} from "@/storage"; -import { - activeStorage, - DEFAULT_SETTINGS, - DEFAULT_SETTINGS_SYNC, - type MdsyncSettings, - mergeSettings, - type SettingsSyncCategories, -} from "./model"; +} from "@/features/storage"; export const TRANSFER_ACTION = "mdsync"; const SETTINGS_TRANSFER_MAX_QR_BYTES = 1024; @@ -33,11 +34,14 @@ const STORAGE_BACKENDS = new Set(Object.values(EStorageBackend)); const encoder = new TextEncoder(); const decoder = new TextDecoder(); +// A retired key is never reused: links made before still carry it ("j" was a history limit, "a" plugin code). const TRANSFER_FIELDS = { q: { ignorePatterns: "i", ignoreSymlinks: "k", maxFileBytes: "m", + pluginLevel: "p", + pluginLevels: "o", }, a: { autoSyncEnabled: "x", @@ -46,12 +50,15 @@ const TRANSFER_FIELDS = { autoPushAfterChange: "p", autoPushSettleSeconds: "g", autoPushChangedFilesOnly: "c", + slowFileSuffixes: "l", + slowFileSettleSeconds: "q", confirmBulkDeletes: "d", bulkDeleteLimit: "b", pushSharesRightAway: "s", shareEditsWait: "w", fileHistoryEnabled: "h", - fileHistoryMaxSnapshots: "j", + fileHistoryKeep: "y", + fileHistoryActivity: "f", historyAutoRefresh: "r", }, l: { @@ -205,12 +212,16 @@ export function mergeTransferredSettings( ...imported.storageConfigs, } : current.storageConfigs; - return mergeSettings({ + // A transfer carries core fields and storage only, so only those are parsed again. + return { ...current, - ...imported, - storageConfigs, - activeStorageKind: imported.activeStorageKind ?? current.activeStorageKind, - }); + ...mergeCoreSettings({ ...current, ...imported }), + ...parseStorageSettings({ + storageConfigs, + activeStorageKind: + imported.activeStorageKind ?? current.activeStorageKind, + }), + }; } function createTransferPayload( @@ -264,8 +275,8 @@ function createSectionPayload( TRANSFER_FIELDS[sectionId], )) { const value = settings[settingsKey as TransferFieldKey]; - const fallback = DEFAULT_SETTINGS[settingsKey as TransferFieldKey]; - if (value === fallback) continue; + const fallback = DEFAULT_CORE_SETTINGS[settingsKey as TransferFieldKey]; + if (JSON.stringify(value) === JSON.stringify(fallback)) continue; out[transferKey] = typeof fallback === "boolean" ? Number(value) : value; } return out; @@ -280,7 +291,7 @@ function applySectionDefaults( for (const [settingsKey, transferKey] of Object.entries( TRANSFER_FIELDS[sectionId], )) { - const fallback = DEFAULT_SETTINGS[settingsKey as TransferFieldKey]; + const fallback = DEFAULT_CORE_SETTINGS[settingsKey as TransferFieldKey]; const transferred = section[transferKey]; if (transferred === undefined) { sink[settingsKey] = fallback; @@ -350,7 +361,7 @@ function isOptionalSectionPayload( )) { const transferred = payload[transferKey]; if (transferred === undefined) continue; - const fallback = DEFAULT_SETTINGS[settingsKey as TransferFieldKey]; + const fallback = DEFAULT_CORE_SETTINGS[settingsKey as TransferFieldKey]; // A bool travels only when it differs from its default, as the flipped bit. const valid = typeof fallback === "boolean" diff --git a/packages/plugin/src/settings/sections/device-transfer.ts b/packages/plugin/src/features/transfer/ui/device-transfer-section.ts similarity index 79% rename from packages/plugin/src/settings/sections/device-transfer.ts rename to packages/plugin/src/features/transfer/ui/device-transfer-section.ts index 9ca811b3..ed0d03fc 100644 --- a/packages/plugin/src/settings/sections/device-transfer.ts +++ b/packages/plugin/src/features/transfer/ui/device-transfer-section.ts @@ -1,15 +1,13 @@ import type { SettingDefinitionGroup } from "obsidian"; -import { type FieldContext, group, introRow } from "@/settings/fields"; -import { - askSettingsTransferInput, - notifyInfo, - reportError, - showSettingsTransferExport, -} from "@/ui"; +import { type FieldContext, group, introRow } from "@/core/settings"; +import { notifyInfo, reportError } from "@/core/ui"; +import type { TransferHost } from "../host"; +import { showSettingsTransferExport } from "./settings-transfer-export-modal"; +import { askSettingsTransferInput } from "./settings-transfer-modal"; export function deviceTransferSection( - ctx: FieldContext, + ctx: FieldContext, ): SettingDefinitionGroup { const { plugin } = ctx; return group("Device transfer", [ diff --git a/packages/plugin/src/ui/modals/settings-transfer-export-modal.ts b/packages/plugin/src/features/transfer/ui/settings-transfer-export-modal.ts similarity index 98% rename from packages/plugin/src/ui/modals/settings-transfer-export-modal.ts rename to packages/plugin/src/features/transfer/ui/settings-transfer-export-modal.ts index d5a620e5..b9c95b43 100644 --- a/packages/plugin/src/ui/modals/settings-transfer-export-modal.ts +++ b/packages/plugin/src/features/transfer/ui/settings-transfer-export-modal.ts @@ -1,14 +1,6 @@ import { type App, ButtonComponent, Modal, Setting } from "obsidian"; import * as QRCode from "qrcode"; - -import { - DEFAULT_SETTINGS_TRANSFER_EXPORT_OPTIONS, - ESettingsTransferStorageMode, - hasSettingsTransferSelection, - type SettingsTransferExportOptions, - type SettingsTransferPackage, -} from "@/settings/transfer"; -import { errorMessage } from "@/shared"; +import { errorMessage } from "@/core/shared"; import { focusKey, modalFooter, @@ -17,7 +9,14 @@ import { renderKeepingFocus, renderModalHead, runWithNotice, -} from "@/ui/common"; +} from "@/core/ui"; +import { + DEFAULT_SETTINGS_TRANSFER_EXPORT_OPTIONS, + ESettingsTransferStorageMode, + hasSettingsTransferSelection, + type SettingsTransferExportOptions, + type SettingsTransferPackage, +} from "../transfer"; const QR_SIZE = 320; diff --git a/packages/plugin/src/ui/modals/settings-transfer-modal.ts b/packages/plugin/src/features/transfer/ui/settings-transfer-modal.ts similarity index 93% rename from packages/plugin/src/ui/modals/settings-transfer-modal.ts rename to packages/plugin/src/features/transfer/ui/settings-transfer-modal.ts index 5c2b87b3..4a25c41c 100644 --- a/packages/plugin/src/ui/modals/settings-transfer-modal.ts +++ b/packages/plugin/src/features/transfer/ui/settings-transfer-modal.ts @@ -1,15 +1,15 @@ import { type App, ButtonComponent, Modal, Setting } from "obsidian"; -import { activeStorage, type MdsyncSettings } from "@/settings/model"; -import type { TransferSection } from "@/settings/transfer"; -import { describeStorageTarget } from "@/storage"; +import type { MdsyncSettings } from "@/core/settings"; import { modalFooter, modalWarning, onEnter, + openPromiseModal, renderModalHead, -} from "@/ui/common"; -import { openPromiseModal } from "./promise-modal"; +} from "@/core/ui"; +import { activeStorage, describeStorageTarget } from "@/features/storage"; +import type { TransferSection } from "../transfer"; const IMPORT_CONFIRMATION_TEXT = "IMPORT"; const SECTION_NAMES: Record = { diff --git a/packages/plugin/src/styles/settings/transfer.css b/packages/plugin/src/features/transfer/ui/transfer.css similarity index 100% rename from packages/plugin/src/styles/settings/transfer.css rename to packages/plugin/src/features/transfer/ui/transfer.css diff --git a/packages/plugin/src/hub/index.ts b/packages/plugin/src/hub/index.ts deleted file mode 100644 index d319ce3d..00000000 --- a/packages/plugin/src/hub/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -export { - HubConnection, - type SpaceFrame, - type SpaceHub, - type SpaceListener, -} from "./connection"; diff --git a/packages/plugin/src/links/index.ts b/packages/plugin/src/links/index.ts deleted file mode 100644 index 055f30bc..00000000 --- a/packages/plugin/src/links/index.ts +++ /dev/null @@ -1,34 +0,0 @@ -export { - DEFAULT_EXPIRY, - DEFAULT_VIEWS, - EXPIRY_CHOICES, - expiryLine, - leftOutText, - linkStatusText, - PICK_DATE, - resolveExpiry, - VIEW_CHOICES, -} from "./describe"; -export { linkError } from "./errors"; -export { type NoteLinks, noteLinks, noteLinksText } from "./note-links"; -export { - linkStatusOf, - NO_RELAY, - previewLink, - publishLink, - type RenderedNote, - revokeLinkRecord, - type ShareOptions, - TOO_LARGE, - updateLink, -} from "./publish"; -export { - isExpired, - isStale, - type LinkRecord, - noteName, - onRelay, - type StoredLink, -} from "./record"; -export { SharedLinks } from "./shared-links"; -export type { Snapshot } from "./snapshot"; diff --git a/packages/plugin/src/live/index.ts b/packages/plugin/src/live/index.ts deleted file mode 100644 index 42f94296..00000000 --- a/packages/plugin/src/live/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -export { AgreedTexts } from "./cold/agreed-texts"; -export { LiveColdSync } from "./cold/cold-sync"; -export { docKindOf, LIVE_VIEWS, liveKindOf } from "./doc-types"; -export { - type ExcalidrawApi, - type ExcalidrawView, - isViewMode, - setViewMode, -} from "./drawing/excalidraw"; -export type { LiveSession } from "./session/session"; -export { cursorsIn, type WatchedCursor, watchCursor } from "./text/cursors"; -export { - type ColdCause, - LiveSessions, - type NoteState, -} from "./workspace/sessions"; -export type { LiveSpace } from "./workspace/space"; diff --git a/packages/plugin/src/live/session/index.ts b/packages/plugin/src/live/session/index.ts deleted file mode 100644 index 45ff48f3..00000000 --- a/packages/plugin/src/live/session/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { closedBefore } from "./closing"; -export { FollowerSession } from "./follower-session"; -export { LOCAL_AWARENESS } from "./room-awareness"; -export { LiveSession } from "./session"; diff --git a/packages/plugin/src/main.ts b/packages/plugin/src/main.ts index a7b89c2e..a9dcf3b7 100644 --- a/packages/plugin/src/main.ts +++ b/packages/plugin/src/main.ts @@ -1,79 +1,64 @@ import { Plugin } from "obsidian"; - -import { registerCommands } from "@/commands"; +import { bootstrapPluginRuntime } from "@/app/bootstrap"; +import { registerCommands } from "@/app/commands"; import { - DeviceName, - type LogService, - type PassphraseManager, - type StatePersister, -} from "@/core"; -import { DeviceKey } from "@/crypto/device-key"; -import { registerReadOnlyLock } from "@/editor/read-only"; -import { registerEditorSigns, type SignsHandle } from "@/editor/signs"; -import { SharedLinks } from "@/links"; -import type { Unseen } from "@/presence"; -import { SettingsEnvelope } from "@/settings/envelope"; + registerHashCarry, + registerStatePersistenceFlush, + registerWorkspaceMenus, +} from "@/app/events"; +import type { PluginHost } from "@/app/host"; +import { registerProtocolHandlers } from "@/app/protocols"; +import { createRealtime, type Realtime } from "@/app/realtime"; +import { createRuntimeHooks } from "@/app/runtime-hooks"; +import { createScopeRefresh } from "@/app/scope-refresh"; +import { DEFAULT_SETTINGS } from "@/app/settings"; +import { SettingsStore } from "@/app/settings/store"; +import { registerPluginUi } from "@/app/views"; +import { SOURCE_CONTROL_VIEW_TYPE } from "@/core/constants"; +import { DeviceKey } from "@/core/crypto"; +import type { LogService } from "@/core/logs"; +import type { MdsyncSettings } from "@/core/settings"; +import { reportWarning } from "@/core/shared"; +import { notifyAction } from "@/core/ui"; +import { loadNodeFs } from "@/core/vault"; +import { registerEditorSigns, type SignsHandle } from "@/features/editor-signs"; +import type { IndicatorHandle } from "@/features/explorer"; +import { registerLinkPaths, SharedLinks } from "@/features/links"; +import { createDeletedElsewhere } from "@/features/live"; +import type { Unseen } from "@/features/presence"; import { - canSync, - DEFAULT_SETTINGS, - isStorageConfigured, - type MdsyncSettings, - mergeSettings, -} from "@/settings/model"; + type CursorFollow, + registerFollows, + registerUnseen, +} from "@/features/presence"; +import { type RelayUpdate, registerRelayUpdate } from "@/features/relay"; +import type { MdsyncSettingTab } from "@/features/settings"; import { closeSetupWizard, type ESetupStep, openSetupWizard, -} from "@/settings/setup"; -import type { MdsyncSettingTab } from "@/settings/tab"; -import { SettingsTransferController } from "@/settings/transfer-controller"; -import { reportWarning } from "@/shared"; -import type { SpaceRecords } from "@/spaces"; -import type { SyncController } from "@/sync/controller"; -import type { WriteJournal } from "@/sync/journal"; -import { registerScheduler } from "@/sync/scheduler"; +} from "@/features/setup"; import { - type CursorFollow, - createAccessEnded, - createDeletedElsewhere, - createSpaceGone, - type IndicatorHandle, - notifyAction, - notifyInfo, openSourceControlChanges, -} from "@/ui"; -import { loadNodeFs } from "@/vault/symlinks"; -import { - bootstrapPluginRuntime, - disposePluginRuntime, -} from "./plugin/bootstrap"; -import { - registerHashCarry, - registerStatePersistenceFlush, - registerWorkspaceMenus, -} from "./plugin/events"; -import { registerFollows } from "./plugin/follows"; -import type { PluginHost } from "./plugin/host"; + openSourceControlTimeline, + openSourceControlView, + refreshSourceControlViews, +} from "@/features/source-control"; +import type { SpaceRecords } from "@/features/spaces"; +import { registerReadOnlyLock, registerShareRenames } from "@/features/spaces"; +import { isStorageConfigured } from "@/features/storage"; +import type { SyncController, WriteJournal } from "@/features/sync"; import { + canSync, + DeviceName, type IgnoreStateHandle, + type PassphraseManager, registerIgnoreState, -} from "./plugin/ignore-state"; -import { registerLinkPaths } from "./plugin/links"; -import { registerProtocolHandlers } from "./plugin/protocols"; -import { createRealtime, type Realtime } from "./plugin/realtime"; -import { type RelayUpdate, registerRelayUpdate } from "./plugin/relay-update"; -import { registerShareRenames } from "./plugin/share-moves"; -import { createShareRegistration } from "./plugin/share-registration"; -import { createStorageRefused } from "./plugin/storage-refused"; -import { - refreshOpenHistoryViewsAfterPush, - refreshOpenSourceControlViews, - registerPluginUi, -} from "./plugin/ui"; -import { markTheirs, registerUnseen } from "./plugin/unseen"; -import { registerVaultAdoptionPrompt } from "./plugin/vault-adoption"; - -const SCOPE_REFRESH_DEBOUNCE_MS = 800; + registerScheduler, + registerVaultAdoptionPrompt, + type StatePersister, +} from "@/features/sync"; +import { SettingsTransferController } from "@/features/transfer"; /** Runs a teardown step without letting its failure abort the rest. */ function safely(step: () => void): void { @@ -106,19 +91,19 @@ export default class MdsyncPlugin extends Plugin implements PluginHost { if (isStorageConfigured(this.settings)) void this.controller.refresh(); }, }); + private readonly scopeRefresh = createScopeRefresh( + () => this.controller, + () => this.settings, + ); + private store!: SettingsStore; private settingsTab?: MdsyncSettingTab; private deviceKey!: DeviceKey; - private envelope!: SettingsEnvelope; private statePersister!: StatePersister; private journal?: WriteJournal; - private scopeRefreshTimer: number | null = null; private editorSigns: SignsHandle | null = null; private fileIndicators: IndicatorHandle | null = null; private refreshStatusBar: (() => void) | null = null; unloaded = false; - private freshInstall = false; - /** One settings write at a time: two in flight may land the older one last. */ - private savingSettings: Promise = Promise.resolve(); async onload(): Promise { await loadNodeFs(); @@ -128,53 +113,27 @@ export default class MdsyncPlugin extends Plugin implements PluginHost { vault.adapter, vault.configDir, ); - this.envelope = new SettingsEnvelope(this.deviceKey); - await this.loadSettings(); - const registerShare = createShareRegistration(this); + this.store = new SettingsStore(this, this.deviceKey); + this.settings = await this.store.load(); const runtime = await bootstrapPluginRuntime({ app: this.app, settings: this.settings, deviceKey: this.deviceKey, links: this.sharedLinks, - onPushComplete: (space) => { - this.realtime.hub.signal(space.id); - refreshOpenHistoryViewsAfterPush(this); - }, - onSpaceRefreshed: (space) => void registerShare(space), - onShareRefused: createAccessEnded(this), - onStorageRefused: createStorageRefused(this), - onSpaceGone: createSpaceGone(this), - onUnindexed: (count) => - notifyInfo( - `Obsidian has not loaded ${count} files that are on disk. MDSync syncs them; restart Obsidian to see them.`, - ), - onDeletionsHeld: (space, paths) => - notifyAction( - `Auto-push held back ${paths.length} deleted files${space.root ? ` in "${space.root}"` : ""}. Review them before they sync.`, - "Review", - () => void openSourceControlChanges(this), - ), - onTheirsPulled: (space, paths) => - markTheirs(this, this.unseen, space, paths), - onNoStorage: () => - notifyAction("Set up storage to sync.", "Set up", () => - this.openSetup(), - ), - persistSettings: () => this.saveSettings(), - liveNotes: (space) => this.realtime?.liveNotes(space), + ...createRuntimeHooks(this), }); - // Obsidian can unload mid-onload (it awaits a 3 MB state file); a teardown registered past that point - // never runs and leaks sockets, timers and views. - if (this.unloaded) { - disposePluginRuntime(runtime); - return; - } this.logs = runtime.logs; this.statePersister = runtime.statePersister; this.journal = runtime.journal; this.spaces = runtime.spaces; this.passphrase = runtime.passphraseManager; this.controller = runtime.controller; + // Obsidian can unload mid-onload (it awaits a 3 MB state file); a teardown registered past that point + // never runs and leaks sockets, timers and views. + if (this.unloaded) { + this.teardown(); + return; + } this.unseen = registerUnseen(this); this.realtime = createRealtime({ app: this.app, @@ -226,11 +185,11 @@ export default class MdsyncPlugin extends Plugin implements PluginHost { // Re-render the open Settings tab so auth status updates live. registerProtocolHandlers(this, () => this.settingsTab?.update()); - if (this.freshInstall) { + if (this.store.freshInstall) { // Saved first: closing the wizard must not bring it back on every start. await this.saveSettings(); this.app.workspace.onLayoutReady(() => this.openSetup()); - } else if (this.envelope.unreadable()) { + } else if (this.store.unreadable()) { this.app.workspace.onLayoutReady(() => notifyAction( "MDSync cannot read its saved connection on this device: this vault was copied or moved, or Obsidian's keychain was reset. Import a setup link from another device, or set up again.", @@ -243,10 +202,12 @@ export default class MdsyncPlugin extends Plugin implements PluginHost { onunload(): void { this.unloaded = true; - if (this.scopeRefreshTimer !== null) { - window.clearTimeout(this.scopeRefreshTimer); - this.scopeRefreshTimer = null; - } + this.teardown(); + } + + /** Also ends an onload that found itself unloaded; a step that is not built yet is skipped. */ + private teardown(): void { + this.scopeRefresh.cancel(); // Isolated: one throwing teardown must not leave the rest running after unload. safely(() => closeSetupWizard()); safely(() => this.editorSigns?.dispose()); @@ -261,29 +222,12 @@ export default class MdsyncPlugin extends Plugin implements PluginHost { safely(() => this.logs?.dispose()); } - async loadSettings(): Promise { - const data = (await this.loadData()) as Record | null; - this.freshInstall = data === null; - const { stored, inTheClear } = await this.envelope.open(data); - this.settings = mergeSettings(stored); - // Sealed now, not at the next change: the secrets of an earlier build must not linger in the clear. - if (inTheClear) await this.writeSettings(); - } - async saveSettings(): Promise { - await this.writeSettings(); + await this.store.write(this.settings); // Any settings write can change the room, the relay credentials or a note's space. this.realtime.refresh(); } - private writeSettings(): Promise { - const save = this.savingSettings.then(async () => - this.saveData(await this.envelope.seal(this.settings)), - ); - this.savingSettings = save.catch(() => undefined); - return save; - } - async resetLocalState(): Promise { this.controller.cancel(); await this.controller.between(() => this.statePersister.reset()); @@ -298,8 +242,8 @@ export default class MdsyncPlugin extends Plugin implements PluginHost { this.fileIndicators?.refresh(enabled); } - refreshSourceControlView(): void { - refreshOpenSourceControlViews(this); + refreshSourceControlView(history?: boolean): void { + refreshSourceControlViews(this.app, history); } openSetup(step?: ESetupStep): void { @@ -311,21 +255,20 @@ export default class MdsyncPlugin extends Plugin implements PluginHost { }); } - scheduleScopeRefresh(reason = "Sync scope changed."): void { - const snapshot = this.controller.getSnapshot(); - // A first refresh still running read the old scope: drop it too. - if (!snapshot.result && snapshot.lastCompareAt === null && !snapshot.busy) { - return; - } - this.controller.invalidate(reason); - if (!canSync(this.settings)) return; - if (this.scopeRefreshTimer !== null) { - window.clearTimeout(this.scopeRefreshTimer); - } - this.scopeRefreshTimer = window.setTimeout(() => { - this.scopeRefreshTimer = null; - void this.controller.refresh(); - }, SCOPE_REFRESH_DEBOUNCE_MS); + async openSourceControl(): Promise { + await openSourceControlView(this.app, SOURCE_CONTROL_VIEW_TYPE); + } + + openChanges(): Promise { + return openSourceControlChanges(this); + } + + openTimeline(day?: number): Promise { + return openSourceControlTimeline(this, day); + } + + scheduleScopeRefresh(reason?: string): void { + this.scopeRefresh.schedule(reason); } /** diff --git a/packages/plugin/src/plugin/events.ts b/packages/plugin/src/plugin/events.ts deleted file mode 100644 index 51f6bbdf..00000000 --- a/packages/plugin/src/plugin/events.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { - type Menu, - type Plugin, - type TAbstractFile, - TFile, - TFolder, -} from "obsidian"; -import type { StatePersister } from "@/core"; -import type { PluginHost } from "@/plugin/host"; -import { reportWarning } from "@/shared"; -import { - addIgnoreMenuItem, - addLinkMenuItems, - addPushMenuItem, - addShareMenuItem, - openSourceControlDeleted, - openSourceControlHistory, -} from "@/ui"; - -/** - * History is otherwise only in the side panel and a deleted file has no menu, so the entry rides on whatever - * the user right-clicks. - */ -export function registerWorkspaceMenus(plugin: Plugin & PluginHost): void { - plugin.registerEvent( - plugin.app.workspace.on("file-menu", (menu, file) => { - addIgnoreItem(menu, plugin, file); - addPushMenuItem(menu, plugin, file.path, file instanceof TFolder); - addLinkMenuItems(menu, plugin, file); - if (file instanceof TFolder && !file.isRoot()) { - addShareMenuItem(menu, plugin, file.path); - } - if (plugin.settings.fileHistoryEnabled) { - if (file instanceof TFile) addHistoryItem(menu, plugin, file.path); - addDeletedItem(menu, plugin); - } - }), - ); - plugin.registerEvent( - plugin.app.workspace.on("editor-menu", (menu, _editor, view) => { - const path = view.file?.path; - if (path) addPushMenuItem(menu, plugin, path, false); - if (!plugin.settings.fileHistoryEnabled) return; - if (path) addHistoryItem(menu, plugin, path); - addDeletedItem(menu, plugin); - }), - ); -} - -function addIgnoreItem( - menu: Menu, - plugin: Plugin & PluginHost, - file: TAbstractFile, -): void { - addIgnoreMenuItem( - menu, - plugin, - file.path, - file instanceof TFolder, - "MDSync: ", - ); -} - -function addHistoryItem( - menu: Menu, - plugin: Plugin & PluginHost, - path: string, -): void { - menu.addItem((item) => - item - .setTitle("MDSync: File history") - .setIcon("history") - .onClick(() => void openSourceControlHistory(plugin, path)), - ); -} - -function addDeletedItem(menu: Menu, plugin: Plugin & PluginHost): void { - menu.addItem((item) => - item - .setTitle("MDSync: Restore deleted files") - .setIcon("trash-2") - .onClick(() => void openSourceControlDeleted(plugin)), - ); -} - -export function registerHashCarry( - plugin: Plugin, - statePersister: StatePersister, -): void { - plugin.registerEvent( - plugin.app.vault.on("rename", (file, oldPath) => - statePersister.carry({ - from: oldPath, - to: file.path, - folder: file instanceof TFolder, - }), - ), - ); -} - -export function registerStatePersistenceFlush( - plugin: Plugin & PluginHost, - statePersister: StatePersister, -): void { - const flush = (): void => { - statePersister - .flush() - .catch((err) => reportWarning("Could not save the sync state.", err)); - }; - - plugin.registerDomEvent(document, "visibilitychange", () => { - if (document.visibilityState === "hidden") flush(); - }); - plugin.registerDomEvent(window, "beforeunload", flush); -} diff --git a/packages/plugin/src/plugin/protocols.ts b/packages/plugin/src/plugin/protocols.ts deleted file mode 100644 index 289a3f2c..00000000 --- a/packages/plugin/src/plugin/protocols.ts +++ /dev/null @@ -1,48 +0,0 @@ -import type { ObsidianProtocolData, Plugin } from "obsidian"; - -import { LINK_PARAM } from "@/crypto/sealed-link"; -import { TRANSFER_ACTION } from "@/settings/transfer"; -import { INVITE_ACTION } from "@/spaces"; -import { handleStorageProtocol } from "@/storage"; -import { notifyError, notifyInfo, openInvite } from "@/ui"; - -import type { PluginHost } from "./host"; - -/** obsidian:// entry points owned by the plugin itself. */ -export function registerProtocolHandlers( - plugin: Plugin & PluginHost, - onStorageAuthorized: () => void, -): void { - plugin.registerObsidianProtocolHandler(TRANSFER_ACTION, (params) => { - void plugin.transfer.handleProtocol(params); - }); - plugin.registerObsidianProtocolHandler("mdsync-auth", (params) => { - void authorizeStorage(plugin, params, onStorageAuthorized); - }); - plugin.registerObsidianProtocolHandler(INVITE_ACTION, (params) => { - void openInvite(plugin, params[LINK_PARAM] ?? ""); - }); -} - -/** A failure here must be visible: the callback fires once and never retries. */ -async function authorizeStorage( - plugin: PluginHost, - params: ObsidianProtocolData, - onAuthorized: () => void, -): Promise { - try { - const outcome = await handleStorageProtocol( - params, - (kind) => plugin.settings.storageConfigs[kind], - async () => { - await plugin.saveSettings(); - onAuthorized(); - }, - ); - if (!outcome) return; - if (outcome.ok) notifyInfo(outcome.message); - else notifyError(outcome.message, outcome.detail); - } catch (err) { - notifyError("Storage authorization failed", err); - } -} diff --git a/packages/plugin/src/plugin/storage-refused.ts b/packages/plugin/src/plugin/storage-refused.ts deleted file mode 100644 index e11fa22d..00000000 --- a/packages/plugin/src/plugin/storage-refused.ts +++ /dev/null @@ -1,30 +0,0 @@ -import type { PluginHost } from "@/plugin/host"; -import { activeStorage } from "@/settings/model"; -import { type Space, VAULT_SPACE } from "@/sync/space"; -import { openStorageRefusedModal } from "@/ui"; - -const VOLATILE = new Set(["accessToken", "expiresAt"]); - -/** - * The vault and owned shares reach the storage with this device's keys; a participant's are the owner's to fix. - * Asks once per set of keys: every sync run hits the same refusal until they change, here or in the settings. - */ -export function createStorageRefused( - plugin: PluginHost, -): (space: Space) => void { - let askedFor: string | null = null; - return (space) => { - const own = - space.root === VAULT_SPACE.root || - plugin.spaces.get(space.id)?.access.kind === "owner"; - const keys = JSON.stringify( - activeStorage(plugin.settings), - (key, value: unknown) => - // Drive replaces its access token hourly; the keys are what the person set. - VOLATILE.has(key) ? undefined : value, - ); - if (!own || keys === askedFor) return; - askedFor = keys; - void openStorageRefusedModal(plugin); - }; -} diff --git a/packages/plugin/src/presence/index.ts b/packages/plugin/src/presence/index.ts deleted file mode 100644 index 9efd3a3b..00000000 --- a/packages/plugin/src/presence/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { watchHere } from "./here"; -export { People } from "./people"; -export { Unseen } from "./unseen"; -export { isAtNote, mergePeople, type Person } from "./views"; diff --git a/packages/plugin/src/settings/connection-test.ts b/packages/plugin/src/settings/connection-test.ts deleted file mode 100644 index 3e57ff4b..00000000 --- a/packages/plugin/src/settings/connection-test.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { requestUrl } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; -import { - activeStorage, - isRelayConfigured, - type RelayConfig, -} from "@/settings/model"; -import { - errorMessage, - isCleartextRemote, - relayBase, - reportWarning, -} from "@/shared"; -import { - createStorageAdapter, - describeStorageTarget, - isAdapterConfigured, -} from "@/storage"; -import { REMOTE_MANIFEST_KEY } from "@/sync/constants"; - -export interface ConnectionTestResult { - ok: boolean; - message: string; -} - -export interface RelayTestResult extends ConnectionTestResult { - /** The build the relay runs; null for one deployed outside MDSync. */ - version?: string | null; -} - -/** - * Reaches the remote without a passphrase, so credentials can be checked before anything is encrypted. - * Reads only the manifest key: absent is a healthy empty remote, anything else a real connection problem. - */ -export async function testConnection( - plugin: PluginHost, -): Promise { - const config = activeStorage(plugin.settings); - if (!isAdapterConfigured(config)) { - return { ok: false, message: "This backend is not fully configured yet." }; - } - const target = describeStorageTarget(config); - try { - // A test may refresh a Drive token: saved, or a rotated one is lost on restart. - const adapter = createStorageAdapter(config, () => { - plugin - .saveSettings() - .catch((err) => reportWarning("Could not save the settings.", err)); - }); - const found = await adapter.exists(REMOTE_MANIFEST_KEY); - return { - ok: true, - message: found - ? `Connected to ${target}. A vault is already published there.` - : `Connected to ${target}. No vault published yet - your first push will create one.`, - }; - } catch (err) { - return { - ok: false, - message: `Could not reach ${target}: ${errorMessage(err)}`, - }; - } -} - -/** Tells a wrong URL (unreachable, HTTP 404) apart from a wrong secret. */ -export async function testRelay(relay: RelayConfig): Promise { - if (isCleartextRemote(relay.relayUrl)) { - return { - ok: false, - message: - "Use an https:// relay URL: the secret is sent with every request.", - }; - } - if (!isRelayConfigured(relay)) { - return { ok: false, message: "Enter the relay URL and secret first." }; - } - try { - const res = await requestUrl({ - url: `${relayBase(relay.relayUrl)}/status`, - method: "GET", - headers: { "X-Mdsync-Admin": relay.relaySecret }, - throw: false, - }); - const body = jsonOf(res) as { - message?: string; - version?: string | null; - } | null; - return res.status === 200 - ? { - ok: true, - message: "Connected. The relay accepts this secret.", - version: body?.version ?? null, - } - : { - ok: false, - message: `Relay error: ${body?.message ?? `HTTP ${res.status}`}`, - }; - } catch (err) { - return { ok: false, message: errorMessage(err) }; - } -} - -/** - * An edge error page is HTML and Obsidian parses `.json` lazily: reading it would throw a SyntaxError over - * the status the caller needs. - */ -function jsonOf(res: { json?: unknown }): unknown { - try { - return res.json ?? null; - } catch { - return null; - } -} diff --git a/packages/plugin/src/settings/sections/automation.ts b/packages/plugin/src/settings/sections/automation.ts deleted file mode 100644 index 372e672b..00000000 --- a/packages/plugin/src/settings/sections/automation.ts +++ /dev/null @@ -1,261 +0,0 @@ -import type { Setting, SettingDefinitionGroup } from "obsidian"; - -import { - AUTO_PUSH_SETTLE_MAX_SECONDS, - AUTO_PUSH_SETTLE_MIN_SECONDS, - AUTO_SYNC_MAX_MINUTES, - AUTO_SYNC_MIN_MINUTES, - BULK_DELETE_LIMIT_MAX, - BULK_DELETE_LIMIT_MIN, - FILE_HISTORY_MAX_SNAPSHOTS, - FILE_HISTORY_MIN_SNAPSHOTS, - LIVE_SEND_MS, -} from "@/constants"; -import type { RelayStatus } from "@/hub/status"; -import type { PluginHost } from "@/plugin/host"; -import type { People } from "@/presence"; -import { - type FieldContext, - fieldRow, - group, - type SettingsField, - SUB_SETTING_CLASS, -} from "@/settings/fields"; -import { DEFAULT_SETTINGS, isRelayConfigured } from "@/settings/model"; -import { EFieldKind } from "@/storage"; -import { clampMaxSnapshots } from "@/sync/history"; -import { VAULT_SPACE } from "@/sync/space"; -import { RELAY_TEXT } from "@/ui/common"; - -const AUTOSYNC_FIELD: SettingsField = { - kind: EFieldKind.Toggle, - name: "Autosync", - desc: "Sync automatically: once after startup and on a schedule. Pulls remote changes; conflicts that cannot be merged safely stop the cycle.", - get: (s) => s.autoSyncEnabled, - set: (v) => ({ autoSyncEnabled: v }), - rerender: true, -}; - -const REALTIME_FIELD: SettingsField = { - kind: EFieldKind.Toggle, - name: "Real-time sync", - desc: "Other devices pull the moment you push, and you see who is in which note. Turning it off also stops live editing. Your devices use the relay server (Connection tab), shared folders their owner's.", - get: (s) => s.realtimeSync, - set: (v) => ({ realtimeSync: v }), - after: restartRelay, - rerender: true, -}; - -const LIVE_EDITING_FIELD: SettingsField = { - kind: EFieldKind.Toggle, - name: "Live editing", - desc: "Notes open in the editor edit together, keystroke by keystroke, across your devices and with the people in shared folders, through the relay.", - when: (s) => s.realtimeSync, - sub: true, - get: (s) => s.liveEditing, - set: (v) => ({ liveEditing: v }), - after: (plugin) => void plugin.realtime.live.refresh(), - rerender: true, -}; - -const LIVE_SPEED_FIELD: SettingsField = { - kind: EFieldKind.Choice, - name: "Live editing speed", - desc: "How often your typing reaches others. Each send is a write on the relay, and Cloudflare's free plan allows 100,000 a day. Set per device.", - when: (s) => s.realtimeSync && s.liveEditing, - sub: true, - options: { - [LIVE_SEND_MS.instant]: "Instant", - [LIVE_SEND_MS.balanced]: "Balanced", - [LIVE_SEND_MS.economical]: "Economical: once a second", - }, - get: (s) => String(s.liveSendMs), - set: (v) => ({ liveSendMs: Number(v) }), -}; - -/** What the setup wizard offers once the vault syncs; real-time sync only with a relay to carry it. */ -export const SETUP_FIELDS: ReadonlyArray = [ - AUTOSYNC_FIELD, - { ...REALTIME_FIELD, when: isRelayConfigured }, - LIVE_EDITING_FIELD, -]; - -const AUTOMATION_FIELDS: ReadonlyArray = [ - AUTOSYNC_FIELD, - { - kind: EFieldKind.Number, - name: "Interval (minutes)", - desc: `How often to sync. 0 means only once after startup. Max ${AUTO_SYNC_MAX_MINUTES}.`, - when: (s) => s.autoSyncEnabled, - sub: true, - get: (s) => String(s.autoSyncIntervalMinutes), - parse: (raw) => - clampInt(raw, AUTO_SYNC_MIN_MINUTES, AUTO_SYNC_MAX_MINUTES, 0), - set: (v) => ({ autoSyncIntervalMinutes: v }), - }, - { - kind: EFieldKind.Toggle, - name: "Push after successful pull", - desc: "After a pull with no conflicts, also push local changes. Disable to only pull and review incoming changes.", - when: (s) => s.autoSyncEnabled, - sub: true, - get: (s) => s.autoPushAfterSync, - set: (v) => ({ autoPushAfterSync: v }), - }, - { - kind: EFieldKind.Toggle, - name: "Push after changes settle", - desc: "Queue changed files and push once the vault has been quiet for the delay below. Rapid saves are combined into one compare and push. Never pulls: conflicts and incoming changes are left untouched.", - get: (s) => s.autoPushAfterChange, - set: (v) => ({ autoPushAfterChange: v }), - rerender: true, - }, - { - kind: EFieldKind.Slider, - name: "Quiet period (seconds)", - desc: `How long the vault must stay quiet after a change before the queued push runs (${AUTO_PUSH_SETTLE_MIN_SECONDS}–${AUTO_PUSH_SETTLE_MAX_SECONDS}). Shorter pushes sooner, longer batches more saves.`, - when: (s) => s.autoPushAfterChange, - sub: true, - min: AUTO_PUSH_SETTLE_MIN_SECONDS, - max: AUTO_PUSH_SETTLE_MAX_SECONDS, - step: 1, - get: (s) => s.autoPushSettleSeconds, - set: (v) => ({ autoPushSettleSeconds: v }), - }, - { - kind: EFieldKind.Toggle, - name: "Push only queued files", - desc: "Push only files changed during the quiet period. Disable to also push other pending local changes.", - when: (s) => s.autoPushAfterChange, - sub: true, - get: (s) => s.autoPushChangedFilesOnly, - set: (v) => ({ autoPushChangedFilesOnly: v }), - }, - { - kind: EFieldKind.Toggle, - name: "Ask before pushing many deletions", - desc: "An automatic push holds back deleting more files than the limit below and asks you to review them first. Guards against storage that briefly hides a folder. Pushing by hand is not affected.", - get: (s) => s.confirmBulkDeletes, - set: (v) => ({ confirmBulkDeletes: v }), - rerender: true, - }, - { - kind: EFieldKind.Number, - name: "Deletion limit", - desc: `How many deleted files an automatic push may publish without asking (${BULK_DELETE_LIMIT_MIN}-${BULK_DELETE_LIMIT_MAX}).`, - when: (s) => s.confirmBulkDeletes, - sub: true, - get: (s) => String(s.bulkDeleteLimit), - parse: (raw) => - clampInt( - raw, - BULK_DELETE_LIMIT_MIN, - BULK_DELETE_LIMIT_MAX, - DEFAULT_SETTINGS.bulkDeleteLimit, - ), - set: (v) => ({ bulkDeleteLimit: v }), - }, - { - kind: EFieldKind.Toggle, - name: "File version history", - desc: "Keep past versions of files so you can view or restore them. Each push appends what it changed to one small encrypted log; old versions are pruned automatically.", - get: (s) => s.fileHistoryEnabled, - set: (v) => ({ fileHistoryEnabled: v }), - rerender: true, - }, - { - kind: EFieldKind.Number, - name: "Versions to keep", - desc: `How many snapshots to retain (${FILE_HISTORY_MIN_SNAPSHOTS}–${FILE_HISTORY_MAX_SNAPSHOTS}). Older versions are garbage-collected.`, - when: (s) => s.fileHistoryEnabled, - sub: true, - get: (s) => String(s.fileHistoryMaxSnapshots), - parse: (raw) => clampMaxSnapshots(Number.parseInt(raw, 10)), - set: (v) => ({ fileHistoryMaxSnapshots: v }), - }, - { - kind: EFieldKind.Toggle, - name: "Auto-refresh history after push", - desc: "Reload the open file-history view automatically when a push completes. Disable to refresh only via the ⟳ button.", - when: (s) => s.fileHistoryEnabled, - sub: true, - get: (s) => s.historyAutoRefresh, - set: (v) => ({ historyAutoRefresh: v }), - }, - REALTIME_FIELD, - LIVE_EDITING_FIELD, - LIVE_SPEED_FIELD, - { - kind: EFieldKind.Toggle, - name: "Show my open note to others", - desc: "Off, others see only that you are online. Live editing still shows you in a note you both have open.", - when: (s) => s.realtimeSync, - sub: true, - get: (s) => s.showOpenNote, - set: (v) => ({ showOpenNote: v }), - }, -]; - -export function automationSection(ctx: FieldContext): SettingDefinitionGroup { - return group("Automation", [ - ...AUTOMATION_FIELDS.map((field) => fieldRow(ctx, field)), - { - name: "Connected devices", - visible: () => ctx.plugin.settings.realtimeSync, - render: (setting) => renderConnectedDevices(setting, ctx.plugin), - }, - ]); -} - -function renderConnectedDevices( - devicesSetting: Setting, - plugin: PluginHost, -): () => void { - devicesSetting.settingEl.addClass(SUB_SETTING_CLASS); - const { hub, people } = plugin.realtime; - const render = (): void => { - devicesSetting.setDesc( - describeConnectedDevices( - plugin.realtime.hub.statusOf(VAULT_SPACE.id), - people.devices(), - ), - ); - }; - render(); - - const unsubscribeStatus = hub.listen({ onConnectionChange: render }); - const unsubscribeDevices = people.subscribe(render); - return () => { - unsubscribeStatus(); - unsubscribeDevices(); - }; -} - -function restartRelay(plugin: PluginHost): void { - plugin.realtime.hub.restart(); -} - -function clampInt( - raw: string, - min: number, - max: number, - fallback: number, -): number { - const parsed = Number.parseInt(raw, 10); - return Math.max( - min, - Math.min(max, Number.isFinite(parsed) ? parsed : fallback), - ); -} - -function describeConnectedDevices( - status: RelayStatus, - { locked, devices }: ReturnType, -): string { - if (status !== "connected") return RELAY_TEXT[status]; - if (locked) return "Sync once to unlock the device list."; - if (devices.length === 0) { - return "No other devices connected."; - } - return devices.map((device) => device.name).join(", "); -} diff --git a/packages/plugin/src/settings/sections/configuration-scope.ts b/packages/plugin/src/settings/sections/configuration-scope.ts deleted file mode 100644 index 2c0b2ed0..00000000 --- a/packages/plugin/src/settings/sections/configuration-scope.ts +++ /dev/null @@ -1,150 +0,0 @@ -import type { SettingDefinitionGroup } from "obsidian"; - -import { - type FieldContext, - fieldRow, - group, - introRow, - type SettingsRow, -} from "@/settings/fields"; -import type { SettingsSyncCategories } from "@/settings/model"; -import { EFieldKind } from "@/storage"; -import type { Manifest } from "@/sync/types"; -import { notifyError, notifyInfo, openConfirmModal } from "@/ui"; -import { createScopePolicy, type ScopePolicy } from "@/vault/scope"; - -interface SettingsSyncRow { - key: keyof SettingsSyncCategories; - name: string; - desc: string; -} - -const SETTINGS_SYNC_ROWS: ReadonlyArray = [ - { - key: "coreSettings", - name: "Core settings", - desc: "App, appearance, core plugins, graph, bookmarks and templates.", - }, - { key: "hotkeys", name: "Hotkeys", desc: "hotkeys.json" }, - { - key: "pluginList", - name: "Enabled community plugins", - desc: "community-plugins.json only", - }, - { - key: "pluginConfigs", - name: "Plugins and their settings", - desc: "Plugin files and settings (MDSync and device-local plugins excluded).", - }, - { - key: "snippets", - name: "CSS snippets", - desc: "snippets folder inside the config folder", - }, - { - key: "themes", - name: "Themes", - desc: "themes folder inside the config folder", - }, -]; - -function countRemoteCategories( - remote: Manifest | null | undefined, - scope: ScopePolicy, -): Map { - const counts = new Map(); - const paths = [ - ...Object.keys(remote?.files ?? {}), - ...(remote?.folders ?? []).map((dir) => `${dir}/`), - ]; - for (const path of paths) { - const category = scope.getCategory(path); - if (category) counts.set(category, (counts.get(category) ?? 0) + 1); - } - return counts; -} - -export function configurationScopeSection( - ctx: FieldContext, -): SettingDefinitionGroup { - const { plugin } = ctx; - return group("Obsidian configuration scope", [ - introRow( - "Workspace, cache, trash and device-local plugin data are never synced. Turning a category off only stops this device from syncing it; the remote keeps its files.", - ), - { - ...introRow("Compare with the remote to see which categories it holds."), - visible: () => !plugin.controller.getSnapshot().result?.remote, - render: (setting) => { - setting.setName("").addButton((button) => - button.setButtonText("Check remote").onClick(async () => { - button.setDisabled(true); - await plugin.controller.refresh(); - ctx.rerender(); - }), - ); - }, - }, - ...SETTINGS_SYNC_ROWS.map((row): SettingsRow => { - const field = fieldRow(ctx, { - kind: EFieldKind.Toggle, - name: row.name, - desc: row.desc, - get: (s) => s.settingsSync[row.key], - set: (v) => ({ - settingsSync: { ...plugin.settings.settingsSync, [row.key]: v }, - }), - refreshScope: true, - }); - return { - ...field, - render: (setting) => { - field.render(setting); - const counts = countRemoteCategories( - plugin.controller.getSnapshot().result?.remote, - createScopePolicy({ - settingsSync: plugin.settings.settingsSync, - configDir: plugin.app.vault.configDir, - }), - ); - const count = counts.get(row.key); - if (!count) return; - setting.addButton((button) => - button - .setButtonText("Clear on remote") - .setTooltip(`${count} remote item(s)`) - .setDestructive() - .onClick(() => void clearCategory(ctx, row)), - ); - }, - }; - }), - ]); -} - -async function clearCategory( - ctx: FieldContext, - row: SettingsSyncRow, -): Promise { - const { plugin } = ctx; - const confirmed = await openConfirmModal({ - app: plugin.app, - title: `Clear ${row.name} on remote?`, - body: [ - `Removes every ${row.name} file from the remote storage. Local files stay on every device, and devices with this category enabled re-upload theirs on their next push.`, - "Disable the category on every device first if it should stay gone. Update MDSync on your other devices before clearing: older versions refuse the cleared remote.", - ], - confirmLabel: "Clear on remote", - confirmClass: "mod-warning", - }); - if (!confirmed) return; - if (await plugin.controller.resetCategory(row.key)) { - notifyInfo(`Cleared ${row.name} on remote.`); - } else { - notifyError( - plugin.controller.getSnapshot().error ?? - "Could not clear the category on the remote.", - ); - } - ctx.rerender(); -} diff --git a/packages/plugin/src/settings/sections/index.ts b/packages/plugin/src/settings/sections/index.ts deleted file mode 100644 index 3ce831de..00000000 --- a/packages/plugin/src/settings/sections/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -export { advancedSection } from "./advanced"; -export { automationSection, SETUP_FIELDS } from "./automation"; -export { backendSection } from "./backend"; -export { configurationScopeSection } from "./configuration-scope"; -export { deviceTransferSection } from "./device-transfer"; -export { exclusionsSection } from "./exclusions"; -export { interfaceSection } from "./interface"; -export { linksSection } from "./links"; -export { maintenanceSection } from "./maintenance"; -export { relaySection } from "./relay"; -export { securitySection } from "./security"; -export { sharesSection } from "./shares"; diff --git a/packages/plugin/src/settings/sections/storage-fields.ts b/packages/plugin/src/settings/sections/storage-fields.ts deleted file mode 100644 index f8acbaca..00000000 --- a/packages/plugin/src/settings/sections/storage-fields.ts +++ /dev/null @@ -1,150 +0,0 @@ -import type { Setting } from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; -import { onSettled, type SettingsRow } from "@/settings/fields"; -import { - EFieldKind, - EStorageBackend, - type GoogleDriveStorageConfig, - getDescriptor, - googleLoginUrl, - type SettingsFieldSpec, -} from "@/storage"; -import { notifyError, notifyInfo } from "@/ui"; - -export function storageRows( - plugin: PluginHost, - kind: EStorageBackend, -): SettingsRow[] { - const rows: SettingsRow[] = getDescriptor(kind).fields.map((field) => ({ - name: field.name, - desc: field.desc, - render: (setting) => renderStorageField(setting, plugin, kind, field), - })); - if (kind === EStorageBackend.GoogleDrive) { - rows.push({ - name: "Google account", - render: (setting) => renderGoogleDriveAuth(setting, plugin, kind), - }); - } - return rows; -} - -function storageOf( - plugin: PluginHost, - kind: EStorageBackend, -): Record { - const config = - plugin.settings.storageConfigs[kind] ?? getDescriptor(kind).defaults(); - return config as unknown as Record; -} - -function renderStorageField( - setting: Setting, - plugin: PluginHost, - kind: EStorageBackend, - field: SettingsFieldSpec, -): void { - const storage = storageOf(plugin, kind); - // An identity field changes the hub route key: save once typing settles, not per key. - const saveTyped = onSettled(() => saveSettings(plugin)); - - if (field.kind === EFieldKind.Toggle) { - setting.addToggle((t) => - t.setValue(Boolean(storage[field.key])).onChange((v) => { - updateStorage(plugin, kind, { [field.key]: v }); - }), - ); - return; - } - if (field.kind === EFieldKind.Number) { - const numberField = field; - setting.addText((t) => { - t.inputEl.type = "number"; - t.inputEl.min = String(numberField.min); - t.inputEl.max = String(numberField.max); - const raw = storage[numberField.key]; - const value = typeof raw === "number" ? raw : numberField.fallback; - t.setValue(String(value)).onChange((v) => { - const parsed = Number.parseInt(v, 10); - if (!Number.isFinite(parsed)) return; - const next = Math.min( - numberField.max, - Math.max(numberField.min, parsed), - ); - updateStorage(plugin, kind, { [numberField.key]: next }, saveTyped); - }); - }); - return; - } - setting.addText((t) => { - const isSecret = field.kind === EFieldKind.Password; - if (isSecret) t.inputEl.type = "password"; - if (field.placeholder) t.setPlaceholder(field.placeholder); - const raw = storage[field.key]; - const text = typeof raw === "string" ? raw : ""; - t.setValue(text).onChange((v) => { - // Trim non-secret fields only; trailing spaces in passwords must be preserved. - updateStorage( - plugin, - kind, - { [field.key]: isSecret ? v : v.trim() }, - saveTyped, - ); - }); - }); -} - -function renderGoogleDriveAuth( - setting: Setting, - plugin: PluginHost, - kind: EStorageBackend, -): void { - // Read on click too: editing a field replaces the config object. - const config = () => - storageOf(plugin, kind) as unknown as GoogleDriveStorageConfig; - const isAuth = Boolean(config().refreshToken); - - setting - .setDesc( - isAuth - ? "Authenticated. Tokens are stored on this device." - : createFragment((f) => { - f.appendText("Not authenticated. Select "); - f.createEl("strong", { text: "Log in" }); - f.appendText(" to authorize."); - }), - ) - .addButton((b) => - b - .setButtonText(isAuth ? "Re-authenticate" : "Log in") - .setCta() - .onClick(() => { - if (!config().authServerUrl) { - notifyInfo("Set the auth server URL first."); - return; - } - window.open(googleLoginUrl(config())); - }), - ); -} - -function updateStorage( - plugin: PluginHost, - kind: EStorageBackend, - patch: Record, - save: () => void = () => saveSettings(plugin), -): void { - const settings = plugin.settings; - settings.storageConfigs[kind] = { - ...(settings.storageConfigs[kind] ?? getDescriptor(kind).defaults()), - ...patch, - }; - save(); -} - -function saveSettings(plugin: PluginHost): void { - void plugin - .saveSettings() - .catch((err: unknown) => notifyError("Could not save settings", err)); -} diff --git a/packages/plugin/src/settings/setup/form.ts b/packages/plugin/src/settings/setup/form.ts deleted file mode 100644 index 40351984..00000000 --- a/packages/plugin/src/settings/setup/form.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { Setting } from "obsidian"; - -/** Buttons that belong to the fields above them: no separator, so they read as part of the form. */ -export function actionRow(parent: HTMLElement): Setting { - const row = new Setting(parent); - row.settingEl.addClass("mdsync-button-row"); - return row; -} - -/** A line for work that is still going. */ -export function busyLine(parent: HTMLElement, text: string): void { - const line = parent.createDiv({ cls: "mdsync-setup-busy" }); - line.createSpan({ cls: "mdsync-status-spinner" }); - line.createSpan({ text }); -} diff --git a/packages/plugin/src/settings/setup/index.ts b/packages/plugin/src/settings/setup/index.ts deleted file mode 100644 index 202eaa63..00000000 --- a/packages/plugin/src/settings/setup/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { ESetupStep } from "./steps"; -export { closeSetupWizard, openSetupWizard } from "./wizard"; diff --git a/packages/plugin/src/settings/setup/ready-step.ts b/packages/plugin/src/settings/setup/ready-step.ts deleted file mode 100644 index 7ba5ef4c..00000000 --- a/packages/plugin/src/settings/setup/ready-step.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { Setting, setIcon } from "obsidian"; - -import { SOURCE_CONTROL_VIEW_TYPE } from "@/constants"; -import { fieldRow, renderDefinitions } from "@/settings/fields"; -import { - activeStorage, - canSync, - isRelayConfigured, - isStorageConfigured, -} from "@/settings/model"; -import { SETUP_FIELDS } from "@/settings/sections/automation"; -import { describeStorageTarget } from "@/storage"; -import type { SyncStatusSnapshot } from "@/sync/controller"; -import { openSourceControlView, showSettingsTransferExport } from "@/ui"; -import { alertLine } from "@/ui/common"; - -import type { StepView, Wizard } from "./wizard"; - -function summaryRow( - list: HTMLElement, - icon: string, - label: string, - value: string, - on: boolean, -): void { - const row = list.createEl("li", { cls: "mdsync-summary-row" }); - row.toggleClass("is-off", !on); - setIcon(row.createSpan({ cls: "mdsync-summary-icon" }), icon); - const text = row.createDiv({ cls: "mdsync-summary-text" }); - text.createDiv({ cls: "mdsync-summary-label", text: label }); - text.createDiv({ cls: "mdsync-summary-value", text: value }); - setIcon( - row.createSpan({ cls: "mdsync-summary-state" }), - on ? "check" : "minus", - ); -} - -export function createReadyStep(wizard: Wizard): StepView { - const { plugin } = wizard; - const { controller } = plugin; - let syncing = false; - let synced: SyncStatusSnapshot | null = null; - - /** The scheduled sync's own cycle: pulls, pushes, and leaves files changed on both sides for Changes. */ - const syncNow = async (): Promise => { - syncing = true; - wizard.redraw(); - const unsubscribe = controller.subscribe(() => wizard.redraw()); - try { - await controller.refreshAndAutoSync(true); - } finally { - unsubscribe(); - syncing = false; - synced = controller.getSnapshot(); - wizard.redraw(); - } - }; - - const renderSync = (el: HTMLElement): void => { - const ready = canSync(plugin.settings); - const row = new Setting(el) - .setName("First sync") - .setDesc( - "Compares this vault with the storage, then pulls and pushes what changed.", - ) - .addButton((b) => - b - .setButtonText(syncing ? "Syncing…" : "Sync now") - .setCta() - .setDisabled(syncing || !ready) - .onClick(() => void syncNow()), - ); - if (!ready) { - row.setDesc("Set up a storage first."); - return; - } - if (syncing) { - row.setDesc(controller.getSnapshot().progressText ?? "Syncing…"); - return; - } - if (!synced) return; - const { error, spaceErrors, conflicts, pendingLocal, pendingRemote } = - synced; - const left = conflicts + pendingLocal + pendingRemote; - if (error) { - alertLine(el).setText(error); - return; - } - if (spaceErrors.length > 0) { - for (const { root, message } of spaceErrors) { - alertLine(el).setText(`Error in "${root}": ${message}`); - } - return; - } - if (left === 0) { - row.setDesc("In sync."); - return; - } - row.setDesc( - conflicts > 0 - ? `${conflicts} file(s) changed both here and in the storage. Choose a side for each in Changes.` - : `${left} change(s) were not synced. Review them in Changes.`, - ); - row.addButton((b) => - b.setButtonText("Open changes").onClick(() => { - wizard.close(); - void openSourceControlView(plugin.app, SOURCE_CONTROL_VIEW_TYPE); - }), - ); - }; - - const renderSummary = (el: HTMLElement): void => { - const { settings } = plugin; - const list = el.createEl("ul", { cls: "mdsync-summary" }); - const storage = isStorageConfigured(settings); - summaryRow( - list, - "hard-drive", - "Storage", - storage ? describeStorageTarget(activeStorage(settings)) : "Not set up", - storage, - ); - summaryRow( - list, - "key-round", - "Encryption", - !plugin.passphrase.has() - ? "No passphrase yet" - : settings.cachePassphrase - ? "Passphrase saved on this device" - : "Passphrase unlocked for this session", - plugin.passphrase.has(), - ); - const relay = isRelayConfigured(settings); - summaryRow( - list, - "radio-tower", - "Relay", - relay ? settings.relayUrl : "Not set up (optional)", - relay, - ); - }; - - const view: StepView = { - render(el) { - const ready = canSync(plugin.settings); - const hero = el.createDiv({ cls: "mdsync-hero" }); - const icon = hero.createDiv({ cls: "mdsync-hero-icon" }); - icon.toggleClass("is-success", ready); - setIcon(icon, ready ? "party-popper" : "sparkles"); - const text = hero.createDiv({ cls: "mdsync-hero-text" }); - text.createEl("h3", { text: ready ? "You're all set" : "Almost there" }); - text.createEl("p", { - text: ready - ? "Your vault syncs through storage you own, encrypted on this device." - : "Set up a storage to start syncing.", - }); - renderSummary(el); - renderSync(el); - renderDefinitions( - el, - SETUP_FIELDS.map((field) => - fieldRow({ plugin, rerender: () => wizard.redraw() }, field), - ), - ); - new Setting(el) - .setName("Set up another device") - .setDesc( - "Shows a link and QR code that bring this setup to your phone or another computer.", - ) - .addButton((b) => - b.setButtonText("Show setup link").onClick(() => - showSettingsTransferExport(plugin.app, { - createPackage: (options) => - plugin.transfer.createPackage(options), - }), - ), - ); - }, - }; - return view; -} diff --git a/packages/plugin/src/settings/setup/start-step.ts b/packages/plugin/src/settings/setup/start-step.ts deleted file mode 100644 index c7f8fb31..00000000 --- a/packages/plugin/src/settings/setup/start-step.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { setIcon } from "obsidian"; - -import { openInvite } from "@/ui"; - -import { choiceCard } from "./choice-card"; -import { ESetupPath } from "./steps"; -import type { StepView, Wizard } from "./wizard"; - -export function createStartStep(wizard: Wizard): StepView { - return { - render(el) { - const hero = el.createDiv({ cls: "mdsync-hero" }); - setIcon(hero.createDiv({ cls: "mdsync-hero-icon" }), "refresh-cw"); - const text = hero.createDiv({ cls: "mdsync-hero-text" }); - text.createEl("h3", { text: "Sync your vault, privately" }); - text.createEl("p", { - text: "MDSync keeps this vault in sync through storage you own. Everything is encrypted on this device with a passphrase only you know.", - }); - const choices = el.createDiv({ cls: "mdsync-choices" }); - choiceCard(choices, { - icon: "sparkles", - title: "Start syncing this vault", - desc: "The first device: choose a storage and set a passphrase.", - primary: true, - onClick: () => wizard.choose(ESetupPath.New), - }); - choiceCard(choices, { - icon: "smartphone", - title: "Connect to a vault set up on another device", - desc: "Use the setup link or QR code from that device.", - onClick: () => wizard.choose(ESetupPath.Join), - }); - choiceCard(choices, { - icon: "folder-input", - title: "Accept an invite to a shared folder", - desc: "Someone shared a folder with you. No storage of your own is needed.", - onClick: () => void openInvite(wizard.plugin, "", () => wizard.close()), - }); - }, - }; -} diff --git a/packages/plugin/src/settings/tab.ts b/packages/plugin/src/settings/tab.ts deleted file mode 100644 index c43b225d..00000000 --- a/packages/plugin/src/settings/tab.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { - type App, - type Plugin, - PluginSettingTab, - type SettingDefinitionItem, -} from "obsidian"; - -import type { PluginHost } from "@/plugin/host"; -import { type FieldContext, settleTyping } from "./fields"; -import { logsPage } from "./logs-view"; -import { overviewGroup } from "./overview"; -import { - advancedSection, - automationSection, - backendSection, - configurationScopeSection, - deviceTransferSection, - exclusionsSection, - interfaceSection, - linksSection, - maintenanceSection, - relaySection, - securitySection, - sharesSection, -} from "./sections"; - -export class MdsyncSettingTab extends PluginSettingTab { - private readonly plugin: Plugin & PluginHost; - - constructor(app: App, plugin: Plugin & PluginHost) { - super(app, plugin); - this.plugin = plugin; - } - - override hide(): void { - settleTyping(); - super.hide(); - } - - getSettingDefinitions(): SettingDefinitionItem[] { - const ctx: FieldContext = { - plugin: this.plugin, - rerender: () => this.update(), - }; - return [ - overviewGroup(ctx), - { - type: "group", - // The row order picks each page's icon in CSS. - cls: "mdsync-settings-sections", - items: [ - { - type: "page", - name: "Connection", - desc: "Storage, encryption, relay and device transfer.", - items: [ - backendSection(ctx), - securitySection(ctx), - relaySection(ctx), - deviceTransferSection(ctx), - advancedSection(ctx), - ], - }, - { - type: "page", - name: "Sync", - desc: "Automation, shared folders, share links, configuration scope and exclusions.", - displayValue: () => { - const open = this.plugin.spaces - .list() - .filter((record) => !record.closed).length; - return open ? `${open} shared` : ""; - }, - items: [ - automationSection(ctx), - sharesSection(ctx), - linksSection(ctx), - configurationScopeSection(ctx), - exclusionsSection(ctx), - ], - }, - { - type: "page", - name: "Interface", - desc: "Status bar, ribbon, file indicators and editor signs.", - items: [interfaceSection(ctx)], - }, - { - type: "page", - name: "Maintenance", - desc: "Local state, remote integrity and storage cleanup.", - items: [maintenanceSection(ctx)], - }, - logsPage(this.plugin), - ], - }, - ]; - } -} diff --git a/packages/plugin/src/shared/index.ts b/packages/plugin/src/shared/index.ts deleted file mode 100644 index f3e744e8..00000000 --- a/packages/plugin/src/shared/index.ts +++ /dev/null @@ -1,7 +0,0 @@ -export * from "./colors"; -export * from "./diagnostics"; -export * from "./errors"; -export * from "./format"; -export * from "./offline"; -export * from "./path"; -export * from "./records"; diff --git a/packages/plugin/src/spaces/index.ts b/packages/plugin/src/spaces/index.ts deleted file mode 100644 index 9e4aa98c..00000000 --- a/packages/plugin/src/spaces/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -export { - acceptInvite, - INVITE_ACTION, - type Invite, - inviteAccess, - inviteLink, - invitePassword, - readInvite, -} from "./invite"; -export { - brokerStorage, - createShare, - ownerNameOf, - renameOwner, -} from "./owner"; -export { mountError, type PauseKind, pauseOf, spacesOf } from "./partition"; -export { type PendingMove, SpaceRecords } from "./records"; diff --git a/packages/plugin/src/storage/index.ts b/packages/plugin/src/storage/index.ts deleted file mode 100644 index c19befc5..00000000 --- a/packages/plugin/src/storage/index.ts +++ /dev/null @@ -1,56 +0,0 @@ -export { - defaultGoogleDriveConfig, - googleLoginUrl, -} from "./adapters/google-drive-auth"; -export { - createLink, - linkStatus, - replaceLink, - revokeLink, -} from "./adapters/link-broker"; -export { defaultS3Config } from "./adapters/s3"; -export { - type BrokerAccess, - type BrokerAdmin, - createBrokerAdapter, - endShare, - issueShareToken, - leaveShare, - listParticipants, - type Participant, - registerShareStorage, - revokeParticipant, -} from "./adapters/share-broker"; -export { isRefusedCredentials } from "./adapters/util"; -export { defaultWebDAVConfig } from "./adapters/webdav"; -export { - EStorageBackend, - type GoogleDriveStorageConfig, - type S3StorageConfig, - type StorageAdapterConfig, - type WebDAVStorageConfig, -} from "./config"; -export { - CONCURRENCY_FIELD, - EFieldKind, - type SettingsFieldSpec, -} from "./field-spec"; -export { - type CompactStorageConfig, - compactStorageConfig, - createStorageAdapter, - describeStorageTarget, - getDescriptor, - handleStorageProtocol, - isAdapterConfigured, - isKnownBackend, - listBackends, - storageDefaults, - storageIdentity, -} from "./registry"; -export type { - ObjectStorage, - StorageAdapter, - StorageAuthOutcome, -} from "./types"; -export { ShareRefusedError, StorageRequestError } from "./types"; diff --git a/packages/plugin/src/styles.css b/packages/plugin/src/styles.css new file mode 100644 index 00000000..eda61efb --- /dev/null +++ b/packages/plugin/src/styles.css @@ -0,0 +1,73 @@ +/* + * Bundled to packages/plugin/styles.css by esbuild.config.mjs. + * Import order is the cascade (equal specificity): append within a slice rather than reordering. + */ + +@import "./core/ui/styles/tokens.css"; +@import "./core/ui/styles/file-path.css"; +@import "./core/ui/styles/marquee.css"; +@import "./core/ui/styles/segments.css"; +@import "./core/ui/styles/callout.css"; + +@import "./features/sync/ui/history/activity-calendar.css"; +@import "./features/sync/ui/history/holds-row.css"; +@import "./features/sync/scope/plugin-levels.css"; + +@import "./features/settings/tabs-and-logs.css"; + +@import "./features/source-control/styles/shell.css"; +@import "./features/source-control/styles/toolbar.css"; +@import "./features/source-control/styles/summary.css"; +@import "./features/source-control/styles/states.css"; +@import "./features/source-control/styles/sections.css"; +@import "./features/source-control/styles/file-rows.css"; +@import "./features/source-control/styles/tree.css"; +@import "./features/source-control/styles/containers.css"; + +@import "./features/diff/styles/view.css"; +@import "./core/ui/styles/icon-button.css"; +@import "./core/ui/styles/notice.css"; +@import "./features/diff/styles/tones.css"; +@import "./features/diff/styles/toolbars.css"; +@import "./features/diff/styles/pane-grid.css"; +@import "./features/diff/styles/divider.css"; +@import "./features/diff/styles/rail.css"; +@import "./features/diff/styles/cm-lines.css"; +@import "./features/diff/styles/source-blocks.css"; +@import "./features/diff/styles/code-lines.css"; +@import "./features/diff/styles/gaps.css"; +@import "./features/diff/styles/cards.css"; +@import "./features/diff/styles/merge.css"; +@import "./features/diff/styles/hunk-preview.css"; +@import "./features/diff/styles/search.css"; + +@import "./features/transfer/ui/transfer.css"; +@import "./features/settings/overview.css"; +@import "./features/setup/styles/setup.css"; +@import "./features/setup/styles/setup-stepper.css"; +@import "./features/setup/styles/setup-cards.css"; +@import "./features/setup/styles/setup-forms.css"; +@import "./features/setup/styles/setup-progress.css"; +@import "./features/explorer/explorer.css"; +@import "./features/status/status-bar.css"; +@import "./features/status/ribbon.css"; +@import "./core/ui/styles/modals.css"; +@import "./core/ui/styles/modal-frame.css"; +@import "./features/source-control/styles/file-list.css"; +@import "./features/spaces/ui/shares.css"; +@import "./features/links/ui/links.css"; + +@import "./features/source-control/history/history.css"; +@import "./features/editor-signs/signs.css"; +@import "./features/editor-signs/hunk-popup.css"; +@import "./features/source-control/timeline/restore.css"; +@import "./features/source-control/timeline/timeline.css"; +@import "./features/presence/ui/presence.css"; +@import "./features/source-control/styles/phone.css"; +@import "./features/diff/styles/phone.css"; + +/* After every feature: `.mdsync-hidden` beats a feature's own display. */ +@import "./core/ui/styles/utilities.css"; + +/* Last: phone overrides win on specificity, but stay last as documented. */ +@import "./core/ui/styles/mobile.css"; diff --git a/packages/plugin/src/styles/diff/hunk-preview.css b/packages/plugin/src/styles/diff/hunk-preview.css deleted file mode 100644 index 1982b63e..00000000 --- a/packages/plugin/src/styles/diff/hunk-preview.css +++ /dev/null @@ -1,41 +0,0 @@ -.mdsync-hunk-preview { - margin-bottom: var(--size-4-2); - border: 1px solid var(--background-modifier-border); - border-radius: var(--radius-s); - overflow: hidden; - background: var(--background-primary); - font-family: var(--font-monospace); - font-size: var(--font-ui-smaller); -} - -@media (max-width: 700px) { - .mdsync-layout-btn { - display: none; - } -} -.mdsync-unified-line { - display: block; -} - -.mdsync-line-prefix { - display: inline-block; - width: 1.5em; - text-align: center; - user-select: none; - opacity: 0.6; -} - -.mdsync-line-content { - white-space: pre; -} - -/* Tint from the theme's own hue, not `--background-modifier-error/success`: solid fills make same-hue text invisible. */ -.mdsync-unified-line.is-add { - background-color: rgba(var(--color-green-rgb), 0.15); - color: var(--text-normal); -} - -.mdsync-unified-line.is-del { - background-color: rgba(var(--color-red-rgb), 0.15); - color: var(--text-normal); -} diff --git a/packages/plugin/src/styles/index.css b/packages/plugin/src/styles/index.css deleted file mode 100644 index 37412aec..00000000 --- a/packages/plugin/src/styles/index.css +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Bundled to packages/plugin/styles.css by esbuild.config.mjs. - * Import order is the cascade (equal specificity): append within a slice rather than reordering. - */ - -@import "./tokens.css"; -@import "./base/file-path.css"; -@import "./base/marquee.css"; -@import "./base/segments.css"; -@import "./base/callout.css"; - -@import "./settings/tabs-and-logs.css"; - -@import "./source-control/shell.css"; -@import "./source-control/toolbar.css"; -@import "./source-control/summary.css"; -@import "./source-control/states.css"; -@import "./source-control/sections.css"; -@import "./source-control/file-rows.css"; -@import "./source-control/tree.css"; -@import "./source-control/containers.css"; - -@import "./diff/view.css"; -@import "./base/icon-button.css"; -@import "./base/notice.css"; -@import "./diff/tones.css"; -@import "./diff/toolbars.css"; -@import "./diff/pane-grid.css"; -@import "./diff/divider.css"; -@import "./diff/rail.css"; -@import "./diff/cm-lines.css"; -@import "./diff/source-blocks.css"; -@import "./diff/code-lines.css"; -@import "./diff/gaps.css"; -@import "./diff/cards.css"; -@import "./diff/merge.css"; -@import "./diff/hunk-preview.css"; - -@import "./settings/transfer.css"; -@import "./settings/overview.css"; -@import "./settings/setup.css"; -@import "./settings/setup-stepper.css"; -@import "./settings/setup-cards.css"; -@import "./settings/setup-forms.css"; -@import "./settings/setup-progress.css"; -@import "./explorer.css"; -@import "./status-bar.css"; -@import "./ribbon.css"; -@import "./modals.css"; -@import "./modal-frame.css"; -@import "./source-control/file-list.css"; -@import "./shares.css"; -@import "./links.css"; - -@import "./source-control/history.css"; -@import "./editor/signs.css"; -@import "./editor/hunk-popup.css"; -@import "./source-control/restore.css"; -@import "./source-control/timeline.css"; -@import "./presence.css"; -@import "./source-control/phone.css"; -@import "./diff/phone.css"; - -/* Last: phone overrides win on specificity, but stay last as documented. */ -@import "./mobile.css"; diff --git a/packages/plugin/src/styles/status-bar.css b/packages/plugin/src/styles/status-bar.css deleted file mode 100644 index 5ed78c40..00000000 --- a/packages/plugin/src/styles/status-bar.css +++ /dev/null @@ -1,92 +0,0 @@ -.mdsync-status-bar, -.mdsync-status-sync, -.mdsync-status-relay { - display: inline-flex; - gap: var(--size-4-2); - align-items: center; -} - -.mdsync-status-bar:focus-visible { - outline: 2px solid var(--interactive-accent); - outline-offset: -2px; -} - -.mdsync-status-sync { - font-variant-numeric: tabular-nums; -} - -.mdsync-status-part { - display: inline-flex; - gap: var(--size-2-1); - align-items: center; -} - -.mdsync-status-part svg { - width: var(--icon-xs); - height: var(--icon-xs); -} - -.mdsync-status-sync.is-error, -.mdsync-status-part.is-conflict { - color: var(--color-red); -} - -/* Mutually exclusive with is-error (see status-bar.ts), so order is free. */ -.mdsync-status-sync.is-offline, -.mdsync-status-part.is-offline { - color: var(--text-muted); -} - -.mdsync-status-relay { - --mdsync-avatar: 16px; -} - -/* A hairline between where sync stands and the relay. */ -.mdsync-status-relay::before { - content: ""; - width: 1px; - height: 12px; - background: var(--background-modifier-border); -} - -.mdsync-status-relay.mdsync-hidden { - display: none; -} - -.mdsync-menu-headline { - color: var(--text-normal); - font-weight: var(--font-semibold); -} - -.mdsync-menu-detail { - color: var(--text-muted); - font-size: var(--font-ui-smaller); -} - -.mdsync-status-spinner, -.mdsync-file-row.is-opening::after { - display: inline-block; - width: 0.75rem; - height: 0.75rem; - border: 2px solid var(--background-modifier-border); - border-top-color: var(--interactive-accent); - border-radius: 50%; - animation: mdsync-spin 0.65s linear infinite; -} - -.mdsync-status-spinner.mdsync-hidden, -.mdsync-hidden { - display: none; -} - -@keyframes mdsync-spin { - to { - transform: rotate(360deg); - } -} - -@media (prefers-reduced-motion: reduce) { - .mdsync-file-row.is-opening::after { - animation: none; - } -} diff --git a/packages/plugin/src/sync/conflict-merge.ts b/packages/plugin/src/sync/conflict-merge.ts deleted file mode 100644 index fa7e577b..00000000 --- a/packages/plugin/src/sync/conflict-merge.ts +++ /dev/null @@ -1,39 +0,0 @@ -import type { DataAdapter } from "obsidian"; - -import { isDrawing, mergeDrawings } from "@/drawing"; -import { withEolOf } from "@/utils"; -import { - loadLocalText, - loadRemoteText, - type RemoteFetchOptions, -} from "./content"; -import { buildMergeSession, countUnresolved } from "./merge-model"; -import type { Conflict } from "./types"; - -/** - * Null, leaving the file untouched, when a side is binary or missing, there is no ancestor, or the conflict - * is real. The caller writes the result and should gate on `isTextMergeCandidate` to skip needless downloads. - */ -export async function tryAutoMergeConflict( - deps: RemoteFetchOptions & { adapter: DataAdapter }, - conflict: Conflict, -): Promise { - if (!conflict.baselineHash || !conflict.localHash || !conflict.remoteHash) { - return null; - } - const [baseText, remoteText, localText] = await Promise.all([ - loadRemoteText(deps, conflict.baselineHash), - loadRemoteText(deps, conflict.remoteHash), - loadLocalText(deps.adapter, conflict.path), - ]); - if (baseText === null || remoteText === null || localText === null) { - return null; - } - if ([baseText, remoteText, localText].some(isDrawing)) { - return mergeDrawings(baseText, localText, remoteText); - } - // The same regions the merge editor shows, so a file it calls clean opens without conflicts. - const { text, changes } = buildMergeSession(baseText, localText, remoteText); - if (countUnresolved(changes) > 0) return null; - return withEolOf(localText, text); -} diff --git a/packages/plugin/src/sync/history/changes.ts b/packages/plugin/src/sync/history/changes.ts deleted file mode 100644 index 83bf726f..00000000 --- a/packages/plugin/src/sync/history/changes.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { entryAt } from "@/shared"; -import type { Manifest, ManifestEntry } from "@/sync/types"; - -import type { SnapshotChanges, SnapshotEntry } from "./types"; - -function sameEntry(a: ManifestEntry, b: ManifestEntry): boolean { - return ( - a.hash === b.hash && - a.size === b.size && - a.mtime === b.mtime && - a.kind === b.kind - ); -} - -/** Every differing field counts, not just the hash, so replaying backwards reproduces the parent exactly. */ -export function diffManifests( - parent: Manifest | null, - next: Manifest, -): SnapshotChanges { - const changes: SnapshotChanges = { added: {}, modified: {}, deleted: {} }; - const parentFiles = parent?.files ?? {}; - for (const [path, entry] of Object.entries(next.files)) { - const before = entryAt(parentFiles, path); - if (!before) { - changes.added[path] = entry; - } else if (!sameEntry(before, entry)) { - changes.modified[path] = { from: before, to: entry }; - } - } - for (const [path, entry] of Object.entries(parentFiles)) { - if (!entryAt(next.files, path)) changes.deleted[path] = entry; - } - return changes; -} - -/** Undoes one snapshot's changes in place, mutating the given file map into its parent's. */ -export function undoChanges( - files: Record, - changes: SnapshotChanges, -): void { - for (const path of Object.keys(changes.added)) delete files[path]; - for (const [path, change] of Object.entries(changes.modified)) { - files[path] = change.from; - } - for (const [path, entry] of Object.entries(changes.deleted)) { - files[path] = entry; - } -} - -/** Undoes one snapshot for a single path. `null` means the path did not exist. */ -export function undoChangesForPath( - entry: ManifestEntry | null, - changes: SnapshotChanges, - path: string, -): ManifestEntry | null { - if (entryAt(changes.added, path)) return null; - const modified = entryAt(changes.modified, path); - if (modified) return modified.from; - return entryAt(changes.deleted, path) ?? entry; -} - -/** Every version a record names, so all it can restore stays reachable. */ -export function changeEntries(changes: SnapshotChanges): ManifestEntry[] { - return [ - ...Object.values(changes.added), - ...Object.values(changes.modified).flatMap(({ from, to }) => [from, to]), - ...Object.values(changes.deleted), - ]; -} - -export function collectChangeHashes( - changes: SnapshotChanges, - into: Set, -): void { - for (const { hash } of changeEntries(changes)) into.add(hash); -} - -/** - * History is best-effort: a dropped update leaves a parent/child mismatch, and walking past it would - * attribute one snapshot's changes to another. - */ -export function contiguousLength(snapshots: readonly SnapshotEntry[]): number { - let length = 0; - for (const [index, entry] of snapshots.entries()) { - length = index + 1; - const parent = snapshots[index + 1]; - if (!parent) break; - if (entry.parentId !== parent.id) break; - } - return length; -} diff --git a/packages/plugin/src/sync/history/gc.ts b/packages/plugin/src/sync/history/gc.ts deleted file mode 100644 index 511f9dee..00000000 --- a/packages/plugin/src/sync/history/gc.ts +++ /dev/null @@ -1,303 +0,0 @@ -import { - FILE_HISTORY_MAX_SNAPSHOTS, - FILE_HISTORY_MIN_SNAPSHOTS, -} from "@/constants"; -import type { EncryptionKey } from "@/crypto"; -import { reportWarning } from "@/shared"; -import type { ObjectStorage } from "@/storage/types"; -import { REMOTE_OBJECTS_PREFIX } from "@/sync/constants"; -import { fetchRemoteManifest, objectKey } from "@/sync/manifest"; -import type { Manifest } from "@/sync/types"; -import { keysByAge, SETTLED_AFTER_MS } from "@/sync/uploads"; -import { runWithConcurrency } from "@/utils"; -import { collectChangeHashes } from "./changes"; -import { pinKey, readPinManifest, updateHistoryLog } from "./store"; -import type { HistoryLog, SnapshotEntry } from "./types"; - -/** Deletes are network round trips; a serial sweep of thousands of them crawls. */ -const GC_CONCURRENCY = 4; - -/** GC fires only when retained snapshots exceed max by this fraction... */ -const FILE_HISTORY_GC_EXCESS_RATIO = 0.3; - -/** ...or by this absolute count, whichever is larger. Bounds GC frequency. */ -const FILE_HISTORY_GC_MIN_EXCESS = 10; - -export function clampMaxSnapshots(value: number): number { - if (!Number.isFinite(value)) return FILE_HISTORY_MIN_SNAPSHOTS; - return Math.max( - FILE_HISTORY_MIN_SNAPSHOTS, - Math.min(FILE_HISTORY_MAX_SNAPSHOTS, Math.floor(value)), - ); -} - -/** - * Amortised: runs only once retained count overshoots the limit by a buffer, so small limits still get - * meaningful batches. - */ -export function gcExcessBuffer(maxSnapshots: number): number { - const max = clampMaxSnapshots(maxSnapshots); - return Math.max( - Math.ceil(max * FILE_HISTORY_GC_EXCESS_RATIO), - FILE_HISTORY_GC_MIN_EXCESS, - ); -} - -export function shouldRunGc( - log: HistoryLog, - maxSnapshots: number, - now = Date.now(), -): boolean { - return ( - evictable(log, maxSnapshots, now).length > gcExcessBuffer(maxSnapshots) - ); -} - -/** - * Past the limit and old enough for their blobs to have settled: a younger record's orphans cannot be swept - * yet, and once it is pruned nothing names them again. - */ -function evictable( - log: HistoryLog, - maxSnapshots: number, - now: number, -): SnapshotEntry[] { - return log.snapshots - .filter((entry) => !entry.pinned) - .slice(clampMaxSnapshots(maxSnapshots)) - .filter((entry) => now - entry.createdAt >= SETTLED_AFTER_MS); -} - -export interface GcInput { - storage: ObjectStorage; - key: EncryptionKey; - root: string; - log: HistoryLog; - maxSnapshots: number; - headManifest: Manifest; -} - -export interface GcResult { - log: HistoryLog; - deletedObjects: number; - deletedSnapshots: number; - skippedObjectSweep: boolean; -} - -/** - * Orphans are hashes an evicted record mentions that nothing retained references. An unreadable pinned - * manifest skips the sweep: a bounded blob leak beats a dangling reference. - */ -export async function collectGarbage(input: GcInput): Promise { - const { storage, key, root, log } = input; - const candidates = evictable(log, input.maxSnapshots, Date.now()); - if (candidates.length === 0) return untouched(log); - const hashes = new Map( - candidates.map((entry) => [entry.id, recordHashes(log, entry.id)]), - ); - const hashesOf = (entry: SnapshotEntry): string[] => - hashes.get(entry.id) ?? []; - - const liveHashes = new Set(); - collectHashes(input.headManifest, liveHashes); - let retainedComplete = true; - for (const entry of log.snapshots) { - if (hashes.has(entry.id)) continue; - const changes = log.changes[entry.id]; - // A kept record we cannot read leaves its hashes unaccounted for. - if (!changes) { - retainedComplete = false; - continue; - } - collectChangeHashes(changes, liveHashes); - } - const pinned = log.snapshots.filter((entry) => entry.pinned); - retainedComplete = - (await addPinnedHashes(storage, key, root, pinned, liveHashes)) && - retainedComplete; - - // Another device may have re-uploaded an old hash for a push it has not published: only settled blobs go. - // Listed before the prune: a record naming one still settling stays, or nothing would name that blob again. - const orphan = (hash: string): boolean => !liveHashes.has(hash); - const ages = - retainedComplete && candidates.some((entry) => hashesOf(entry).some(orphan)) - ? await keysByAge(storage, REMOTE_OBJECTS_PREFIX) - : null; - const settling = ages - ? candidates.filter((entry) => - hashesOf(entry).some( - (hash) => orphan(hash) && ages.settling.has(objectKey(hash)), - ), - ) - : []; - for (const entry of settling) { - for (const hash of hashesOf(entry)) liveHashes.add(hash); - } - const evicted = candidates.filter((entry) => !settling.includes(entry)); - if (evicted.length === 0) return untouched(log); - - const evictedHashes = new Set(); - for (const entry of evicted) { - for (const hash of hashesOf(entry)) evictedHashes.add(hash); - } - - // Prune before sweeping: a crash in between leaves orphan blobs (deep-clean collects them), not log - // versions whose content is gone. - const evictedIds = new Set(evicted.map((entry) => entry.id)); - const nextLog = await updateHistoryLog( - storage, - key, - root, - (current) => pruneLog(current, evictedIds), - (current) => - current.snapshots.every( - (entry) => !evictedIds.has(entry.id) || entry.pinned === true, - ), - ); - - // Re-read head late: a device that published while we pruned may reference a blob we were about to sweep. - const headNow = await readHead(storage, key, root); - if (headNow.manifest) collectHashes(headNow.manifest, liveHashes); - // An unreadable or vanished head might have moved; sweeping risks deleting what it references. - const headUnchanged = - headNow.read && - headNow.manifest !== null && - headNow.manifest.snapshotId === input.headManifest.snapshotId; - - // A pinned snapshot's objects must survive but are not in liveHashes: withhold the sweep until the next round. - const rescued = await pinnedAmong(storage, evictedIds, nextLog); - const skippedObjectSweep = - !retainedComplete || !headUnchanged || rescued.size > 0; - - let deletedObjects = 0; - const orphans = skippedObjectSweep - ? [] - : [...evictedHashes].filter((hash) => !liveHashes.has(hash)); - if (orphans.length > 0) { - await runWithConcurrency(orphans, GC_CONCURRENCY, async (hash) => { - if (!ages?.settled.has(objectKey(hash))) return; - if (await safeDelete(storage, objectKey(hash))) deletedObjects++; - }); - } - - const stillPresent = nextLog.snapshots.filter((entry) => - evictedIds.has(entry.id), - ).length; - return { - log: nextLog, - deletedObjects, - deletedSnapshots: evicted.length - stillPresent, - skippedObjectSweep, - }; -} - -function untouched(log: HistoryLog): GcResult { - return { - log, - deletedObjects: 0, - deletedSnapshots: 0, - skippedObjectSweep: false, - }; -} - -function recordHashes(log: HistoryLog, id: string): string[] { - const changes = log.changes[id]; - const into = new Set(); - if (changes) collectChangeHashes(changes, into); - return [...into]; -} - -/** - * Pin manifests are written before their flag, so storage, not the log, is the reliable signal: a racing flag - * can be lost to our log rewrite. - */ -async function pinnedAmong( - storage: ObjectStorage, - ids: ReadonlySet, - log: HistoryLog, -): Promise> { - const flagged = new Set( - log.snapshots.filter((entry) => entry.pinned).map((entry) => entry.id), - ); - const found = new Set(); - await runWithConcurrency([...ids], GC_CONCURRENCY, async (id) => { - if (flagged.has(id) || (await storage.exists(pinKey(id)))) found.add(id); - }); - return found; -} - -/** Drops evicted snapshots, except any a concurrent device has pinned meanwhile. */ -function pruneLog( - log: HistoryLog, - evictedIds: ReadonlySet, -): HistoryLog { - const snapshots = log.snapshots.filter( - (entry) => !evictedIds.has(entry.id) || entry.pinned === true, - ); - const keptIds = new Set(snapshots.map((entry) => entry.id)); - const changes: HistoryLog["changes"] = {}; - for (const [id, record] of Object.entries(log.changes)) { - if (keptIds.has(id)) changes[id] = record; - } - return { ...log, snapshots, changes }; -} - -/** Returns false when a pin's manifest could not be read. */ -async function addPinnedHashes( - storage: ObjectStorage, - key: EncryptionKey, - root: string, - pinned: readonly SnapshotEntry[], - into: Set, -): Promise { - let complete = true; - await runWithConcurrency(pinned, GC_CONCURRENCY, async (entry) => { - const manifest = await readPinManifest(storage, key, root, entry.id); - if (!manifest) { - reportWarning( - `Pinned snapshot "${entry.id}" has no stored manifest, so old file contents cannot be cleaned up. Unpin and pin it again to repair it.`, - ); - complete = false; - return; - } - collectHashes(manifest, into); - }); - return complete; -} - -function collectHashes(manifest: Manifest, into: Set): void { - for (const entry of Object.values(manifest.files)) into.add(entry.hash); -} - -async function safeDelete( - storage: ObjectStorage, - storageKey: string, -): Promise { - try { - await storage.delete(storageKey); - return true; - } catch (err) { - reportWarning( - `Could not delete "${storageKey}" during history cleanup.`, - err, - ); - return false; - } -} - -/** Separates "no vault published" from a failed fetch. */ -async function readHead( - storage: ObjectStorage, - key: EncryptionKey, - root: string, -): Promise<{ read: boolean; manifest: Manifest | null }> { - try { - return { - read: true, - manifest: await fetchRemoteManifest(storage, key, root), - }; - } catch (err) { - reportWarning("Could not re-read the head before collecting garbage.", err); - return { read: false, manifest: null }; - } -} diff --git a/packages/plugin/src/sync/history/index.ts b/packages/plugin/src/sync/history/index.ts deleted file mode 100644 index e4557b15..00000000 --- a/packages/plugin/src/sync/history/index.ts +++ /dev/null @@ -1,43 +0,0 @@ -export { - changeEntries, - contiguousLength, - diffManifests, - undoChanges, - undoChangesForPath, -} from "./changes"; -export { - clampMaxSnapshots, - gcExcessBuffer, - shouldRunGc, -} from "./gc"; -export { publishManifestWithHistory } from "./publish"; -export { - getFileHistory, - listDeletedFiles, - listSnapshots, - loadVersionBytes, -} from "./query"; -export { replayTo } from "./replay"; -export { - planVaultRestore, - sameRestorePlan, - type VaultRestorePlan, -} from "./restore-vault"; -export { - pinKey, - readHistoryLog, - readPinManifest, - resolveSnapshotManifest, - setSnapshotPinned, -} from "./store"; -export type { - DeletedFile, - DeletedFilesResult, - FileVersion, - HistoryConfig, - HistoryLog, - SnapshotChanges, - SnapshotEntry, - SnapshotListResult, - SnapshotSummary, -} from "./types"; diff --git a/packages/plugin/src/sync/history/publish.ts b/packages/plugin/src/sync/history/publish.ts deleted file mode 100644 index 1fddfe0d..00000000 --- a/packages/plugin/src/sync/history/publish.ts +++ /dev/null @@ -1,65 +0,0 @@ -import type { EncryptionKey } from "@/crypto"; -import { reportWarning } from "@/shared"; -import type { ObjectStorage } from "@/storage/types"; -import { publishManifestWithGuard } from "@/sync/manifest"; -import type { Manifest } from "@/sync/types"; -import { diffManifests } from "./changes"; -import { collectGarbage, shouldRunGc } from "./gc"; -import { prependSnapshot, updateHistoryLog } from "./store"; -import type { HistoryConfig, SnapshotEntry } from "./types"; - -/** - * Records the change set only on the guard's winner, which proved remote head equals `parent`. - * Best-effort: failures log but never fail the push. GC is safe, as the guard serialises publishers. - */ -export async function publishManifestWithHistory( - storage: ObjectStorage, - key: EncryptionKey, - root: string, - manifest: Manifest, - parent: Manifest | null, - history: HistoryConfig | undefined, - baseline: Manifest | null = null, -): Promise { - await publishManifestWithGuard( - storage, - key, - root, - manifest, - parent?.snapshotId ?? null, - baseline, - ); - if (!history) return; - try { - const entry: SnapshotEntry = { - id: manifest.snapshotId, - parentId: manifest.parentSnapshotId, - createdAt: manifest.createdAt, - deviceId: manifest.deviceId, - deviceName: manifest.deviceName, - }; - const changes = diffManifests(parent, manifest); - const log = await updateHistoryLog( - storage, - key, - root, - (current) => prependSnapshot(current, entry, changes), - (current) => current.snapshots.some((s) => s.id === entry.id), - ); - if (shouldRunGc(log, history.maxSnapshots)) { - await collectGarbage({ - storage, - key, - root, - log, - maxSnapshots: history.maxSnapshots, - headManifest: manifest, - }); - } - } catch (err) { - reportWarning( - "File history could not be updated; the push itself succeeded.", - err, - ); - } -} diff --git a/packages/plugin/src/sync/history/query.ts b/packages/plugin/src/sync/history/query.ts deleted file mode 100644 index 579ee56c..00000000 --- a/packages/plugin/src/sync/history/query.ts +++ /dev/null @@ -1,359 +0,0 @@ -import type { EncryptionKey } from "@/crypto"; -import { entryAt } from "@/shared"; -import type { ObjectStorage } from "@/storage/types"; -import { loadRemoteBytes } from "@/sync/content"; -import { fetchRemoteManifest } from "@/sync/manifest"; -import type { Manifest, ManifestEntry } from "@/sync/types"; -import { runWithConcurrency } from "@/utils"; -import { contiguousLength, undoChangesForPath } from "./changes"; -import { readHistoryLog, readPinManifest } from "./store"; -import type { - DeletedFile, - DeletedFilesResult, - FileVersion, - HistoryLog, - SnapshotEntry, - SnapshotListResult, - SnapshotSummary, -} from "./types"; - -const PIN_READ_CONCURRENCY = 4; -/** Manifests are big, so only a few stay. */ -const PIN_CACHE_SIZE = 4; - -// A pin's manifest never changes once written, so a query can reuse it. -const pinCache = new WeakMap< - ObjectStorage, - { key: EncryptionKey; root: string; manifests: Map } ->(); - -/** Keeps only what `pick` takes from each pin, so no more than the cache's manifests are held at once. */ -async function readPins( - storage: ObjectStorage, - key: EncryptionKey, - root: string, - ids: readonly string[], - pick: (manifest: Manifest) => T, -): Promise<(T | null)[]> { - let cache = pinCache.get(storage); - if (cache?.key !== key || cache.root !== root) { - cache = { key, root, manifests: new Map() }; - pinCache.set(storage, cache); - } - const { manifests } = cache; - const out: (T | null)[] = []; - await runWithConcurrency(ids, PIN_READ_CONCURRENCY, async (id, index) => { - let manifest = manifests.get(id) ?? null; - if (!manifest) { - manifest = await readPinManifest(storage, key, root, id); - if (!manifest) return; - manifests.set(id, manifest); - for (const oldest of manifests.keys()) { - if (manifests.size <= PIN_CACHE_SIZE) break; - manifests.delete(oldest); - } - } - out[index] = pick(manifest); - }); - return ids.map((_, index) => out[index] ?? null); -} - -export interface FileHistoryQuery { - storage: ObjectStorage; - key: EncryptionKey; - root: string; - path: string; -} - -export interface DeletedFilesQuery { - storage: ObjectStorage; - key: EncryptionKey; - root: string; -} - -/** Distinct-version timeline for one path from one log read plus HEAD; cost scales with snapshots, not vault size. */ -export async function getFileHistory( - query: FileHistoryQuery, -): Promise { - const { storage, key, root, path } = query; - const [log, head] = await Promise.all([ - readHistoryLog(storage, key, root), - fetchRemoteManifest(storage, key, root), - ]); - if (!head) return []; - - const chain = walkableChain(log, head); - const { versions, visited } = walkChain(log, head, chain, path); - versions.push( - ...(await pinnedVersions(storage, key, root, log, visited, path)), - ); - return orderByChain(versions, log); -} - -/** Position in the log, never `createdAt`: device clock skew could order a snapshot before its parent. */ -function logPositions(log: HistoryLog): Map { - return new Map(log.snapshots.map((entry, index) => [entry.id, index])); -} - -/** Newest first. */ -function orderByChain(versions: FileVersion[], log: HistoryLog): FileVersion[] { - const position = logPositions(log); - return versions.sort( - (a, b) => - (position.get(a.snapshotId) ?? -1) - (position.get(b.snapshotId) ?? -1), - ); -} - -/** - * The contiguous run from HEAD. History is best-effort (the log can lag or have gaps), so only provably - * consecutive snapshots are walked; pins cover the rest. - */ -function walkableChain(log: HistoryLog, head: Manifest): SnapshotEntry[] { - if (log.snapshots[0]?.id !== head.snapshotId) return []; - return log.snapshots.slice(0, contiguousLength(log.snapshots)); -} - -/** Also reports which snapshots it actually reached, since the walk stops at a gap. */ -function walkChain( - log: HistoryLog, - head: Manifest, - chain: readonly SnapshotEntry[], - path: string, -): { versions: FileVersion[]; visited: Set } { - const versions: FileVersion[] = []; - const visited = new Set(); - let entry = entryAt(head.files, path) ?? null; - let lastHash: string | null = null; - for (const meta of chain.length > 0 ? chain : [headEntry(head)]) { - visited.add(meta.id); - if (entry === null) { - lastHash = null; - } else if (entry.hash !== lastHash) { - versions.push(toVersion(meta, entry)); - lastHash = entry.hash; - } - const changes = entryAt(log.changes, meta.id); - if (!changes) break; - entry = undoChangesForPath(entry, changes, path); - } - return { versions, visited }; -} - -/** Pins outlive the chain, so they are the only way back to an evicted snapshot. */ -async function pinnedVersions( - storage: ObjectStorage, - key: EncryptionKey, - root: string, - log: HistoryLog, - visited: ReadonlySet, - path: string, -): Promise { - const pins = log.snapshots.filter((m) => m.pinned && !visited.has(m.id)); - const manifests = await readPins( - storage, - key, - root, - pins.map((m) => m.id), - (manifest) => entryAt(manifest.files, path), - ); - const versions: FileVersion[] = []; - for (const [index, meta] of pins.entries()) { - const entry = manifests[index]; - if (entry) versions.push(toVersion(meta, entry)); - } - return versions; -} - -function headEntry(head: Manifest): SnapshotEntry { - return { - id: head.snapshotId, - parentId: head.parentSnapshotId, - createdAt: head.createdAt, - deviceId: head.deviceId, - deviceName: head.deviceName, - }; -} - -function toVersion(meta: SnapshotEntry, entry: ManifestEntry): FileVersion { - return { - snapshotId: meta.id, - hash: entry.hash, - size: entry.size, - mtime: entry.mtime, - kind: entry.kind, - createdAt: meta.createdAt, - deviceId: meta.deviceId, - deviceName: meta.deviceName, - pinned: meta.pinned === true, - label: meta.label, - }; -} - -/** - * Files gone from HEAD but restorable. Newest first, so a path deleted, recreated and deleted again reports - * its latest death; pins are folded in after. - */ -export async function listDeletedFiles( - query: DeletedFilesQuery, -): Promise { - const { storage, key, root } = query; - const [log, head] = await Promise.all([ - readHistoryLog(storage, key, root), - fetchRemoteManifest(storage, key, root), - ]); - if (!head) return { files: [], lagging: false, truncated: false }; - - const chain = walkableChain(log, head); - const { found, walked } = collectDeletions(log, head, chain); - await applyPins(storage, key, root, log, head, found); - const position = logPositions(log); - return { - files: [...found.values()].sort( - (a, b) => - (position.get(a.snapshotId) ?? 0) - (position.get(b.snapshotId) ?? 0), - ), - lagging: chain.length === 0, - truncated: walked < chain.length, - }; -} - -/** Also reports how far it got, since the walk stops at a missing record. */ -function collectDeletions( - log: HistoryLog, - head: Manifest, - chain: readonly SnapshotEntry[], -): { found: Map; walked: number } { - const found = new Map(); - let rank = 0; - let walked = 0; - for (const meta of chain) { - const changes = entryAt(log.changes, meta.id); - // Past a missing record nothing is attributable to a snapshot. - if (!changes) break; - walked++; - for (const [path, entry] of Object.entries(changes.deleted)) { - // Back in HEAD means it was recreated; the newest death wins otherwise. - if (entryAt(head.files, path) || found.has(path)) continue; - found.set(path, { - path, - entry, - snapshotId: meta.id, - source: "deleted", - createdAt: meta.createdAt, - deviceId: meta.deviceId, - deviceName: meta.deviceName, - rank: meta.pinned ? null : rank, - }); - } - if (!meta.pinned) rank++; - } - return { found, walked }; -} - -/** - * Folds pinned manifests in: adds files no change record explains and clears the eviction countdown on files - * they hold. - */ -async function applyPins( - storage: ObjectStorage, - key: EncryptionKey, - root: string, - log: HistoryLog, - head: Manifest, - found: Map, -): Promise { - const pinned = log.snapshots.filter((meta) => meta.pinned); - if (pinned.length === 0) return; - const manifests = await readPins( - storage, - key, - root, - pinned.map((meta) => meta.id), - (manifest) => - Object.entries(manifest.files).filter( - ([path]) => !entryAt(head.files, path), - ), - ); - // Newest first, so the freshest pinned version of a path wins. - for (const [index, meta] of pinned.entries()) { - for (const [path, entry] of manifests[index] ?? []) { - const existing = found.get(path); - if (existing) { - // The pin only holds its own hash reachable; a newer death still ages out. - if (existing.entry.hash === entry.hash) existing.rank = null; - continue; - } - found.set(path, { - path, - entry, - snapshotId: meta.id, - source: "pinned", - label: meta.label, - createdAt: meta.createdAt, - deviceId: meta.deviceId, - deviceName: meta.deviceName, - rank: null, - }); - } - } -} - -/** The vault's push timeline; file lists are the change records from the log already read for HEAD. */ -export async function listSnapshots( - query: DeletedFilesQuery, -): Promise { - const { storage, key, root } = query; - const [log, head] = await Promise.all([ - readHistoryLog(storage, key, root), - fetchRemoteManifest(storage, key, root), - ]); - if (!head) return { snapshots: [], lagging: false }; - - const chain = walkableChain(log, head); - const replayable = new Set( - chain.slice(0, chainDepth(log, chain)).map((meta) => meta.id), - ); - let rank = 0; - const snapshots = log.snapshots.map((meta) => { - const changes = entryAt(log.changes, meta.id); - const summary: SnapshotSummary = { - id: meta.id, - createdAt: meta.createdAt, - deviceId: meta.deviceId, - deviceName: meta.deviceName, - pinned: meta.pinned === true, - label: meta.label, - files: changes ?? null, - rank: meta.pinned ? null : rank, - restorable: replayable.has(meta.id) || meta.pinned === true, - isHead: meta.id === head.snapshotId, - }; - if (!meta.pinned) rank++; - return summary; - }); - return { snapshots, lagging: chain.length === 0 }; -} - -/** How far the chain replays: it stops at the first snapshot with no record. */ -function chainDepth(log: HistoryLog, chain: readonly SnapshotEntry[]): number { - let depth = 0; - for (const meta of chain) { - // The oldest reachable snapshot is reached by undoing the one before it, - // so its own record is not needed to arrive at it. - depth++; - if (!entryAt(log.changes, meta.id)) break; - } - return depth; -} - -export async function loadVersionBytes( - storage: ObjectStorage, - key: EncryptionKey, - hash: string, -): Promise { - const plaintext = await loadRemoteBytes({ storage, key }, hash); - if (!plaintext) { - throw new Error(`Version content is no longer available (${hash})`); - } - return plaintext; -} diff --git a/packages/plugin/src/sync/history/replay.ts b/packages/plugin/src/sync/history/replay.ts deleted file mode 100644 index fc678ff2..00000000 --- a/packages/plugin/src/sync/history/replay.ts +++ /dev/null @@ -1,39 +0,0 @@ -import type { Manifest } from "@/sync/types"; -import { contiguousLength, undoChanges } from "./changes"; -import type { HistoryLog } from "./types"; - -/** - * Null when the log does not start at HEAD or the chain breaks before the target: a partial replay would - * invent a state. Empty folders are not tracked per snapshot, so the result carries none. - */ -export function replayTo( - head: Manifest, - log: HistoryLog, - snapshotId: string, -): Manifest | null { - const snapshots = log.snapshots; - if (snapshots[0]?.id !== head.snapshotId) return null; - const reachable = contiguousLength(snapshots); - - const files = { ...head.files }; - for (let index = 0; index < reachable; index++) { - const entry = snapshots[index]; - if (!entry) return null; - if (entry.id === snapshotId) { - return { - version: head.version, - vaultId: head.vaultId, - snapshotId: entry.id, - parentSnapshotId: entry.parentId, - createdAt: entry.createdAt, - deviceId: entry.deviceId, - deviceName: entry.deviceName, - files, - }; - } - const changes = log.changes[entry.id]; - if (!changes) return null; - undoChanges(files, changes); - } - return null; -} diff --git a/packages/plugin/src/sync/history/store.ts b/packages/plugin/src/sync/history/store.ts deleted file mode 100644 index c9e7a1fb..00000000 --- a/packages/plugin/src/sync/history/store.ts +++ /dev/null @@ -1,242 +0,0 @@ -import { decryptJson, type EncryptionKey, encryptJson } from "@/crypto"; -import { errorMessage, reportWarning } from "@/shared"; -import type { ObjectStorage } from "@/storage/types"; -import { REMOTE_HISTORY_LOG_KEY, REMOTE_PINS_PREFIX } from "@/sync/constants"; -import { fetchRemoteManifest, readIfChanged } from "@/sync/manifest"; -import { - historyLogToSpace, - historyLogToVault, - manifestToSpace, - manifestToVault, -} from "@/sync/space-paths"; -import type { Manifest } from "@/sync/types"; -import { replayTo } from "./replay"; -import type { HistoryLog, SnapshotChanges, SnapshotEntry } from "./types"; - -const HISTORY_LOG_VERSION = 2; - -// Callers treat the log as read-only, so the cached object is handed out as is. -const validators = new WeakMap< - ObjectStorage, - { etag: string; log: HistoryLog; key: EncryptionKey; root: string } ->(); - -export function pinKey(snapshotId: string): string { - return `${REMOTE_PINS_PREFIX}${snapshotId}.json.enc`; -} - -export async function readHistoryLog( - storage: ObjectStorage, - key: EncryptionKey, - root: string, -): Promise { - const cached = validators.get(storage); - const validator = - cached?.key === key && cached.root === root ? cached : undefined; - const read = await readIfChanged( - storage, - REMOTE_HISTORY_LOG_KEY, - validator?.etag ?? null, - ); - if (read.status === "unchanged") { - // Only an answer about the validator we sent; otherwise it describes nothing we hold. - if (!validator) { - throw new Error( - "Storage answered 'not modified' to a read that carried no validator.", - ); - } - return validator.log; - } - validators.delete(storage); - if (read.status === "absent") { - // Read as empty, a log that is there gets rewritten from scratch or its blobs cleaned: ask twice. - if (await storage.exists(REMOTE_HISTORY_LOG_KEY)) { - throw new Error( - "History log is there but could not be read; refusing to reset it.", - ); - } - return { version: HISTORY_LOG_VERSION, snapshots: [], changes: {} }; - } - let parsed: HistoryLog; - try { - parsed = await decryptJson(key, read.body); - } catch (err) { - // Present but unreadable (corruption, key rotation). Failing loudly beats - // returning a fresh log, which would overwrite the real one and orphan history. - throw new Error( - `History log present but unreadable; refusing to reset it: ${errorMessage(err)}`, - ); - } - if (!Array.isArray(parsed.snapshots) || !isRecord(parsed.changes)) { - throw new Error("History log is malformed; refusing to reset it."); - } - // Rewritten as ours, a newer client's log would lose what it added. - if (parsed.version > HISTORY_LOG_VERSION) { - throw new Error("History log is from a newer MDSync; update the plugin."); - } - const log = historyLogToVault(parsed, root); - if (read.etag) { - validators.set(storage, { etag: read.etag, log, key, root }); - } - return log; -} - -export async function writeHistoryLog( - storage: ObjectStorage, - key: EncryptionKey, - root: string, - log: HistoryLog, -): Promise { - const blob = await encryptJson(key, historyLogToSpace(log, root)); - await storage.put(REMOTE_HISTORY_LOG_KEY, blob, "application/octet-stream"); - validators.delete(storage); -} - -/** Applies a change and confirms it survived: log updates are not serialised by the manifest guard. */ -export async function updateHistoryLog( - storage: ObjectStorage, - key: EncryptionKey, - root: string, - mutate: (log: HistoryLog) => HistoryLog, - survived: (log: HistoryLog) => boolean, -): Promise { - let next = mutate(await readHistoryLog(storage, key, root)); - await writeHistoryLog(storage, key, root, next); - const verify = await readHistoryLog(storage, key, root); - // Return what is stored, not what we computed: a concurrent writer may have - // won and still satisfied `survived`, and callers act on the result. - if (survived(verify)) return verify; - next = mutate(verify); - await writeHistoryLog(storage, key, root, next); - return readHistoryLog(storage, key, root); -} - -export function prependSnapshot( - log: HistoryLog, - entry: SnapshotEntry, - changes: SnapshotChanges, -): HistoryLog { - const deduped = log.snapshots.filter((s) => s.id !== entry.id); - const parentAt = deduped.findIndex((s) => s.id === entry.parentId); - const childAt = deduped.findIndex((s) => s.parentId === entry.id); - const at = parentAt >= 0 ? parentAt : childAt >= 0 ? childAt + 1 : 0; - return { - version: HISTORY_LOG_VERSION, - snapshots: [...deduped.slice(0, at), entry, ...deduped.slice(at)], - changes: { ...log.changes, [entry.id]: changes }, - }; -} - -export async function readPinManifest( - storage: ObjectStorage, - key: EncryptionKey, - root: string, - snapshotId: string, -): Promise { - const blob = await storage.get(pinKey(snapshotId)); - if (!blob) return null; - try { - const raw = await decryptJson(key, blob); - return manifestToVault(raw, root); - } catch (err) { - reportWarning(`Pinned snapshot "${snapshotId}" is unreadable.`, err); - return null; - } -} - -/** Replay first, as the log is one object; a pin's stored manifest covers snapshots the chain can no longer reach. */ -export async function resolveSnapshotManifest( - storage: ObjectStorage, - key: EncryptionKey, - root: string, - snapshotId: string, -): Promise { - const [log, head] = await Promise.all([ - readHistoryLog(storage, key, root), - fetchRemoteManifest(storage, key, root), - ]); - const replayed = head ? replayTo(head, log, snapshotId) : null; - if (replayed) return replayed; - return readPinManifest(storage, key, root, snapshotId); -} - -/** Pins keep a full manifest so they outlive their chain once the snapshots between HEAD and the pin are evicted. */ -export async function setSnapshotPinned( - storage: ObjectStorage, - key: EncryptionKey, - root: string, - snapshotId: string, - pinned: boolean, - /** Undefined keeps whatever name the pin already has; "" clears it. */ - label?: string, -): Promise { - // A readable manifest for this snapshot is the pin (no replay needed); anything else there must be - // replaced, or GC would trust an unreadable pin. - const stored = pinned - ? await readPinManifest(storage, key, root, snapshotId) - : null; - if (pinned && stored?.snapshotId !== snapshotId) { - const [log, head] = await Promise.all([ - readHistoryLog(storage, key, root), - fetchRemoteManifest(storage, key, root), - ]); - if (!head) throw new Error("No manifest is published on this remote."); - const manifest = replayTo(head, log, snapshotId); - if (!manifest) { - throw new Error( - "That snapshot can no longer be rebuilt from the history log, so it cannot be pinned.", - ); - } - // Manifest before flag: a flag without its manifest lets GC believe objects are protected. - const blob = await encryptJson(key, manifestToSpace(manifest, root)); - await storage.put(pinKey(snapshotId), blob, "application/octet-stream"); - } - // No rollback on failure: the flag may have landed anyway, and an unflagged manifest is inert (deep clean takes it). - await updateHistoryLog( - storage, - key, - root, - (log) => ({ - ...log, - snapshots: log.snapshots.map((entry) => - entry.id === snapshotId ? repin(entry, pinned, label) : entry, - ), - }), - (log) => - log.snapshots.some( - (entry) => - entry.id === snapshotId && - entry.pinned === pinned && - (label === undefined || - entry.label === (pinned ? label || undefined : undefined)), - ), - ); - // A leftover manifest is inert - GC only reads pins that are still flagged. - if (!pinned) await safeDeletePin(storage, snapshotId); -} - -async function safeDeletePin( - storage: ObjectStorage, - snapshotId: string, -): Promise { - try { - await storage.delete(pinKey(snapshotId)); - } catch (err) { - reportWarning(`Could not remove the pin for "${snapshotId}".`, err); - } -} - -/** Unpinning drops the name with the pin; an empty name clears it in place. */ -function repin( - entry: SnapshotEntry, - pinned: boolean, - label: string | undefined, -): SnapshotEntry { - if (!pinned) return { ...entry, pinned, label: undefined }; - if (label === undefined) return { ...entry, pinned }; - return { ...entry, pinned, label: label || undefined }; -} - -function isRecord(value: unknown): value is Record { - return typeof value === "object" && value !== null && !Array.isArray(value); -} diff --git a/packages/plugin/src/sync/maintenance.ts b/packages/plugin/src/sync/maintenance.ts deleted file mode 100644 index cd1f0bdd..00000000 --- a/packages/plugin/src/sync/maintenance.ts +++ /dev/null @@ -1,208 +0,0 @@ -import { DEFAULT_CONCURRENCY } from "@/constants"; -import { decryptBytes, type EncryptionKey, sha256Hex } from "@/crypto"; -import type { StorageAdapter } from "@/storage/types"; -import { REMOTE_OBJECTS_PREFIX, REMOTE_PINS_PREFIX } from "@/sync/constants"; -import { runWithConcurrency, runWithFileConcurrency } from "@/utils"; -import { - changeEntries, - type HistoryLog, - pinKey, - readHistoryLog, - readPinManifest, -} from "./history"; -import { fetchRemoteManifest, objectKey } from "./manifest"; -import type { Manifest, ManifestEntry } from "./types"; -import { settledKeys } from "./uploads"; - -export interface MaintenanceOptions { - concurrency?: number; - onProgress?: (done: number, total: number) => void; -} - -export interface VerifyResult { - checked: number; - missing: string[]; - corrupt: string[]; -} - -export interface CleanResult { - deletedObjects: number; - deletedPins: number; -} - -interface ReachableSet { - /** Each reachable hash with its largest known size. */ - hashes: Map; - head: Manifest | null; - log: HistoryLog; - /** False when a pinned manifest could not be read, so the live set is unknown. */ - complete: boolean; -} - -/** Every hash reachable from HEAD, the retained change records, and the pins. */ -async function reachableHashes( - storage: StorageAdapter, - key: EncryptionKey, - root: string, -): Promise { - const [head, log] = await Promise.all([ - fetchRemoteManifest(storage, key, root), - readHistoryLog(storage, key, root), - ]); - const hashes = new Map(); - const reach = (entries: Iterable): void => { - for (const { hash, size } of entries) { - hashes.set(hash, Math.max(hashes.get(hash) ?? 0, size)); - } - }; - if (head) reach(Object.values(head.files)); - let complete = true; - for (const entry of log.snapshots) { - const changes = log.changes[entry.id]; - if (!changes) { - complete = false; - continue; - } - reach(changeEntries(changes)); - } - for (const entry of log.snapshots) { - if (!entry.pinned) continue; - const manifest = await readPinManifest(storage, key, root, entry.id); - if (!manifest) { - complete = false; - continue; - } - reach(Object.values(manifest.files)); - } - return { hashes, head, log, complete }; -} - -/** Catches missing objects or silent backend corruption; `deep` also decrypts and hashes. */ -export async function verifyRemote( - storage: StorageAdapter, - key: EncryptionKey, - root: string, - deep: boolean, - options: MaintenanceOptions = {}, -): Promise { - const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY; - const reachable = await reachableHashes(storage, key, root); - if (!reachable.complete) { - throw new Error( - "Some history records could not be read, so the check would be incomplete. Try again later.", - ); - } - - const list = [...reachable.hashes.keys()]; - const missing: string[] = []; - const corrupt: string[] = []; - let done = 0; - storage.prepareReads?.(list.map(objectKey)); - await runWithFileConcurrency( - list, - concurrency, - (hash) => reachable.hashes.get(hash) ?? Number.POSITIVE_INFINITY, - async (hash) => { - const blob = await storage.get(objectKey(hash)); - if (!blob) { - missing.push(hash); - } else if (deep) { - try { - const plain = await decryptBytes(key, blob); - if ((await sha256Hex(plain)) !== hash) corrupt.push(hash); - } catch { - corrupt.push(hash); - } - } - options.onProgress?.(++done, list.length); - }, - ); - return { checked: list.length, missing, corrupt }; -} - -/** Removes objects and pin manifests unreachable from HEAD or the history log. Needs a backend that can list. */ -export async function deepCleanOrphans( - storage: StorageAdapter, - key: EncryptionKey, - root: string, - options: MaintenanceOptions = {}, -): Promise { - const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY; - const reachable = await reachableHashes(storage, key, root); - // An unreadable record means the live set is unknown, so we cannot safely delete. - if (!reachable.complete) { - throw new Error( - "Some history records could not be read, so orphans cannot be identified safely. Try again later.", - ); - } - // Without head, objects from an in-progress upload would look like orphans. - if (!reachable.head) { - throw new Error( - "No manifest is published on this remote, so nothing can be identified as an orphan.", - ); - } - - const livePinKeys = new Set( - reachable.log.snapshots - .filter((entry) => entry.pinned) - .map((entry) => pinKey(entry.id)), - ); - - const [objectKeys, pinKeys] = await Promise.all([ - settledKeys(storage, REMOTE_OBJECTS_PREFIX), - settledKeys(storage, REMOTE_PINS_PREFIX), - ]); - - // Another device publishing during the listing makes its new objects look like orphans: bail. - const headNow = await fetchRemoteManifest(storage, key, root); - if ((headNow?.snapshotId ?? null) !== (reachable.head?.snapshotId ?? null)) { - throw new Error( - "Another device pushed while cleaning; nothing was deleted. Try again.", - ); - } - // Pinning does not move HEAD, so a pin created during the listing needs its own check. - const logNow = await readHistoryLog(storage, key, root); - if (pinnedSignature(logNow) !== pinnedSignature(reachable.log)) { - throw new Error( - "Another device changed a pinned snapshot while cleaning; nothing was deleted. Try again.", - ); - } - - const liveObjectKeys = new Set( - [...reachable.hashes.keys()].map((hash) => objectKey(hash)), - ); - const orphanObjects = objectKeys.filter( - (storageKey) => !liveObjectKeys.has(storageKey), - ); - const orphanPins = pinKeys.filter( - (storageKey) => !livePinKeys.has(storageKey), - ); - - const targets = [...orphanObjects, ...orphanPins]; - let done = 0; - await runWithConcurrency(targets, concurrency, async (storageKey) => { - await storage.delete(storageKey); - options.onProgress?.(++done, targets.length); - }); - return { - deletedObjects: orphanObjects.length, - deletedPins: orphanPins.length, - }; -} - -function pinnedSignature(log: HistoryLog): string { - return log.snapshots - .filter((entry) => entry.pinned) - .map((entry) => entry.id) - .sort() - .join(","); -} - -/** One sentence for the log and the notice, so both stay in step. */ -export function cleanSummary(result: CleanResult): string { - const parts = [ - `${result.deletedObjects} object(s)`, - `${result.deletedPins} pinned snapshot(s)`, - ]; - return `removed ${parts.join(", ")}.`; -} diff --git a/packages/plugin/src/sync/operations/index.ts b/packages/plugin/src/sync/operations/index.ts deleted file mode 100644 index 10d7fa67..00000000 --- a/packages/plugin/src/sync/operations/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -export { runAdoptNewVaultFlow, runResetRemoteStorageFlow } from "./flows"; -export { type LocalHunksArgs, localHunksOp, pullHunksOp } from "./hunks"; -export { pullPathsOp } from "./pull"; -export { pushPathsOp } from "./push"; -export { - batchAcceptRemoteOp, - batchKeepLocalOp, - keepBothConflictOp, - type MergedSaveArgs, - saveMergedOp, -} from "./resolve"; -export { revertPathsOp } from "./revert"; -export { - EHunkPair, - type HunkSidesHash, - loadHunkSides, -} from "./text-loaders"; -export type { - Operation, - OperationContext, - OperationOutcome, - SyncOperationResult, -} from "./types"; diff --git a/packages/plugin/src/sync/runtime/maintenance-service.ts b/packages/plugin/src/sync/runtime/maintenance-service.ts deleted file mode 100644 index efc50d99..00000000 --- a/packages/plugin/src/sync/runtime/maintenance-service.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { ESyncLogOperation } from "@/logs/store"; -import { LOG_PATH_LIMIT } from "@/sync/constants"; -import type { EngineDependencies } from "@/sync/engine"; -import { - type CleanResult, - cleanSummary, - deepCleanOrphans, - type VerifyResult, - verifyRemote, -} from "@/sync/maintenance"; - -interface MaintenanceServiceDeps { - openSession: () => Promise; - /** Between operations: a push of this device uploads blobs its manifest does not name yet. */ - enqueue: (task: () => Promise) => Promise; - logInfo: ( - operation: ESyncLogOperation, - message: string, - details?: readonly string[], - ) => Promise; -} - -export class MaintenanceService { - constructor(private readonly deps: MaintenanceServiceDeps) {} - - async verifyRemote(deep: boolean): Promise { - const session = await this.deps.openSession(); - if (!session) return null; - const result = await verifyRemote( - session.storage, - session.key, - session.space.root, - deep, - ); - await this.deps.logInfo( - ESyncLogOperation.Compare, - `Integrity check: ${result.checked} object(s), ${result.missing.length} missing, ${result.corrupt.length} corrupt.`, - [...result.missing, ...result.corrupt].slice(0, LOG_PATH_LIMIT), - ); - return result; - } - - deepCleanRemote(): Promise { - return this.deps.enqueue(async () => { - const session = await this.deps.openSession(); - if (!session) return null; - const result = await deepCleanOrphans( - session.storage, - session.key, - session.space.root, - ); - await this.deps.logInfo( - ESyncLogOperation.Reset, - `Deep-clean ${cleanSummary(result)}`, - ); - return result; - }); - } -} diff --git a/packages/plugin/src/ui/actions/sync-actions.ts b/packages/plugin/src/ui/actions/sync-actions.ts deleted file mode 100644 index a1becc0b..00000000 --- a/packages/plugin/src/ui/actions/sync-actions.ts +++ /dev/null @@ -1,80 +0,0 @@ -import type { PluginHost } from "@/plugin/host"; -import type { DiffResult } from "@/sync/types"; -import { notifyError, notifyInfo, runWithNotice } from "@/ui/common"; -import { openSourceControlChanges } from "../source-control-view"; - -export async function runCompare(plugin: PluginHost): Promise { - try { - await plugin.controller.refresh(); - await openSourceControlChanges(plugin); - } catch (err) { - notifyError("Compare failed", err); - } -} - -export async function runPushAll(plugin: PluginHost): Promise { - try { - // Re-compare first: a stale diff can push a file another device changed, or miss conflicts. - await plugin.controller.refresh(); - const diff = comparedDiff(plugin); - if (!diff || (await announceConflicts(plugin, diff.conflicts.length))) { - return; - } - // A read-only share's changes cannot go out; they must not hold back the rest. - const paths = diff.localChanges - .map((c) => c.path) - .filter((path) => !plugin.controller.spaceFor(path).readOnly); - if (paths.length === 0) { - notifyInfo("Nothing to push."); - return; - } - await runWithNotice( - () => plugin.controller.pushPaths(paths), - `Pushed ${paths.length} file(s).`, - "Push all failed", - ); - } catch (err) { - notifyError("Push all failed", err); - } -} - -export async function runPullAll(plugin: PluginHost): Promise { - try { - await plugin.controller.refresh(); - const diff = comparedDiff(plugin); - if (!diff || (await announceConflicts(plugin, diff.conflicts.length))) { - return; - } - const paths = diff.remoteChanges.map((c) => c.path); - if (paths.length === 0) { - notifyInfo("Nothing to pull."); - return; - } - await runWithNotice( - () => plugin.controller.pullPaths(paths), - `Pulled ${paths.length} file(s).`, - "Pull all failed", - ); - } catch (err) { - notifyError("Pull all failed", err); - } -} - -/** The fresh compare's diff; null, said so, when the compare did not finish. */ -function comparedDiff(plugin: PluginHost): DiffResult | null { - const { error, result } = plugin.controller.getSnapshot(); - if (error) throw new Error(error); - if (!result) notifyInfo("The compare did not finish. Try again."); - return result?.diff ?? null; -} - -/** Push and pull must never choose a side silently; conflicts go to the user. */ -async function announceConflicts( - plugin: PluginHost, - count: number, -): Promise { - if (count === 0) return false; - notifyInfo(`Resolve ${count} conflict(s) first.`); - await openSourceControlChanges(plugin); - return true; -} diff --git a/packages/plugin/src/ui/common/index.ts b/packages/plugin/src/ui/common/index.ts deleted file mode 100644 index 48351032..00000000 --- a/packages/plugin/src/ui/common/index.ts +++ /dev/null @@ -1,46 +0,0 @@ -export { makeActivatable } from "./activatable"; -export { alertLine } from "./alert-line"; -export { describePeople, renderAvatar, renderAvatarStack } from "./avatars"; -export { type CalloutTone, callout } from "./callout"; -export { type ChangeAction, changeActionOf } from "./change-action"; -export { copyable, copyText } from "./copyable"; -export { onEnter } from "./enter-key"; -export { renderPath } from "./file-path"; -export { focusKey, renderKeepingFocus } from "./focus"; -export { appendIconButton, appendLabeledButton } from "./icon-button"; -export { lastEditLabel, lastEditor } from "./last-edit"; -export { onLongPress } from "./long-press"; -export { measureSlide, slideWhenCut } from "./marquee"; -export { infoTitle, personTitle, showMenuAt } from "./menu"; -export { - asDrawer, - type ModalHead, - modalCard, - modalFooter, - modalHint, - modalSection, - modalWarning, - renderModalHead, -} from "./modal-frame"; -export { - attempt, - notifyAction, - notifyError, - notifyInfo, - reportError, - runWithNotice, -} from "./notices"; -export { openInEditor, revealInFileExplorer } from "./obsidian-helpers"; -export { openNote } from "./open-note"; -export { redrawOnPhoneChange } from "./phone-change"; -export { - openPluginSettings, - RELAY_TEXT, - type RelayFix, - relayFixOf, - relaySummary, - UNREADABLE_TEXT, -} from "./relay"; -export { renderSegments, type Segments } from "./segments"; -export { serial } from "./serial"; -export { skippedFiles, skippedText } from "./skipped"; diff --git a/packages/plugin/src/ui/diff/index.ts b/packages/plugin/src/ui/diff/index.ts deleted file mode 100644 index f46fbaf6..00000000 --- a/packages/plugin/src/ui/diff/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export { renderBinaryDiff } from "./binary-view"; -export { ComparePanel } from "./compare-panel"; -export { type DiffHeaderActions, renderDiffHeader } from "./header"; -export { renderHunkPreview } from "./hunk-renderer"; -export { MergeEditorPanel } from "./merge-editor"; diff --git a/packages/plugin/src/ui/diff/preview-panel.ts b/packages/plugin/src/ui/diff/preview-panel.ts deleted file mode 100644 index 6d7e9c53..00000000 --- a/packages/plugin/src/ui/diff/preview-panel.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { EditorState } from "@codemirror/state"; -import { EditorView, lineNumbers } from "@codemirror/view"; - -export class PreviewPanel { - private view: EditorView | null = null; - - render(parent: HTMLElement, text: string, label: string): void { - this.destroy(); - const header = parent.createDiv({ cls: "mdsync-diff-preview-header" }); - header.createSpan({ text: label }); - - const container = parent.createDiv({ cls: "mdsync-diff-preview-body" }); - this.view = new EditorView({ - parent: container, - state: EditorState.create({ - doc: text, - extensions: [ - EditorState.readOnly.of(true), - EditorView.editable.of(false), - lineNumbers(), - EditorView.lineWrapping, - ], - }), - }); - } - - destroy(): void { - this.view?.destroy(); - this.view = null; - } -} diff --git a/packages/plugin/src/ui/index.ts b/packages/plugin/src/ui/index.ts deleted file mode 100644 index 96cecae4..00000000 --- a/packages/plugin/src/ui/index.ts +++ /dev/null @@ -1,74 +0,0 @@ -export { addIgnoreMenuItem } from "./actions/ignore-action"; -export { - deepCleanOrphanedObjects, - resetLocalState, - resetRemoteStorage, - verifyRemoteIntegrity, -} from "./actions/maintenance-actions"; -export { addPushMenuItem } from "./actions/push-action"; -export { - runCompare, - runPullAll, - runPushAll, -} from "./actions/sync-actions"; -export { - notifyAction, - notifyError, - notifyInfo, - reportError, - runWithNotice, -} from "./common/notices"; -export { - openInEditor, - revealInFileExplorer, -} from "./common/obsidian-helpers"; -export { DiffView } from "./diff-view"; -export { registerFileContextIndicators } from "./explorer/file-context-indicators"; -export { registerFileExplorerIndicators } from "./explorer/file-explorer-indicators"; -export type { IndicatorHandle } from "./explorer/indicator-handle"; -export { - addLinkMenuItems, - isLinkable, - openManageLinks, - openShareLink, - registerNoteLinkActions, - updateSharedLinks, -} from "./links"; -export { createDeletedElsewhere } from "./live/deleted-elsewhere"; -export { CursorFollow } from "./live/header/cursor-follow"; -export { rebuildLiveNote, toggleAuthors } from "./live/header/live-actions"; -export { canRebuild } from "./live/header/note-menu-items"; -export { registerNotePresence } from "./live/header/note-presence"; -export { - askNewPassphrase, - askPassphrase, - askSettingsTransferInput, - confirmRemoteReset, - confirmSettingsTransferImport, - openConfirmModal, - openPromiseModal, - openRelayUpdateModal, - openStorageRefusedModal, - showSettingsTransferExport, -} from "./modals"; -export { registerRibbon } from "./ribbon"; -export { createAccessEnded } from "./shares/access-ended"; -export { openInvite } from "./shares/invite-action"; -export { shareSummary } from "./shares/share-summary"; -export { addShareMenuItem, openShareWindow } from "./shares/share-window"; -export { createSpaceGone } from "./shares/space-gone"; -export { - confirmAdoptNewVault, - confirmBatchResolve, -} from "./source-control"; -export { - keepInRightSidebar, - openDiffView, - openSourceControlChanges, - openSourceControlDeleted, - openSourceControlHistory, - openSourceControlView, - SourceControlView, -} from "./source-control-view"; -export { registerStatusBar } from "./status-bar"; -export { openStatusMenu } from "./status-menu"; diff --git a/packages/plugin/src/ui/links/index.ts b/packages/plugin/src/ui/links/index.ts deleted file mode 100644 index d21c9746..00000000 --- a/packages/plugin/src/ui/links/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -export { updateSharedLinks } from "./link-actions"; -export { - addLinkMenuItems, - isLinkable, - openManageLinks, - openShareLink, -} from "./link-menu"; -export { registerNoteLinkActions } from "./note-link-action"; diff --git a/packages/plugin/src/ui/live/status/live-spaces.ts b/packages/plugin/src/ui/live/status/live-spaces.ts deleted file mode 100644 index 1900cd3b..00000000 --- a/packages/plugin/src/ui/live/status/live-spaces.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { isLinkState, type LinkState } from "@/hub/status"; -import type { PluginHost } from "@/plugin/host"; -import { isAtNote, type Person } from "@/presence"; -import { VAULT_SPACE } from "@/sync/space"; - -export interface CarriedSpace { - id: string; - status: LinkState; -} - -export function carried(plugin: PluginHost): CarriedSpace[] { - return plugin.spaces.partition().flatMap(({ id }) => { - const status = plugin.realtime.hub.statusOf(id); - return isLinkState(status) ? [{ id, status }] : []; - }); -} - -export function inSharedNotes(plugin: PluginHost): Person[] { - return carried(plugin) - .filter(({ id }) => id !== VAULT_SPACE.id) - .flatMap(({ id }) => plugin.realtime.people.online(id).filter(isAtNote)); -} - -export function spaceName(plugin: PluginHost, id: string): string { - if (id === VAULT_SPACE.id) return "Vault"; - return plugin.spaces.get(id)?.name ?? id; -} diff --git a/packages/plugin/src/ui/live/status/where-menu.ts b/packages/plugin/src/ui/live/status/where-menu.ts deleted file mode 100644 index bb5ea5c9..00000000 --- a/packages/plugin/src/ui/live/status/where-menu.ts +++ /dev/null @@ -1,132 +0,0 @@ -import type { Menu } from "obsidian"; - -import { isConnected } from "@/hub/status"; -import type { PluginHost } from "@/plugin/host"; -import { VAULT_SPACE } from "@/sync/space"; -import { - infoTitle, - lastEditLabel, - openNote, - openPluginSettings, - personTitle, - RELAY_TEXT, - relayFixOf, - UNREADABLE_TEXT, -} from "@/ui/common"; -import { LINK_LIVE_STATE, STATE_ICONS } from "@/ui/live/live-state"; -import { - type CarriedSpace, - carried, - inSharedNotes, - spaceName, -} from "./live-spaces"; - -/** The relay of every space, its fixes, who is in shared notes and what others changed. */ -export function addRelaySections(menu: Menu, plugin: PluginHost): void { - const spaces = carried(plugin); - addStatuses(menu, plugin, spaces); - addRelayFixes(menu, plugin, spaces); - menu.addSeparator(); - const here = inSharedNotes(plugin); - if (here.length === 0) { - menu.addItem((item) => - item.setTitle(infoTitle("Nobody is in a shared note")).setIsLabel(true), - ); - } - for (const person of here) { - const note = person.note ?? ""; - menu.addItem((item) => - item - .setTitle(personTitle(person, note)) - .onClick(() => void openNote(plugin.app, note)), - ); - } - addUnseen(menu, plugin); -} - -function addStatuses( - menu: Menu, - plugin: PluginHost, - spaces: readonly CarriedSpace[], -): void { - if (spaces.length === 0) { - menu.addItem((item) => - item - .setTitle( - infoTitle(RELAY_TEXT[plugin.realtime.hub.statusOf(VAULT_SPACE.id)]), - ) - .setIcon(STATE_ICONS.cold) - .setIsLabel(true), - ); - return; - } - for (const { id, status } of spaces) { - const unreadable = - isConnected(status) && plugin.realtime.people.unreadable(id); - menu.addItem((item) => - item - .setTitle( - infoTitle( - spaceName(plugin, id), - unreadable ? UNREADABLE_TEXT : RELAY_TEXT[status], - ), - ) - .setIcon(STATE_ICONS[unreadable ? "warning" : LINK_LIVE_STATE[status]]) - .setIsLabel(true), - ); - } -} - -function addRelayFixes( - menu: Menu, - plugin: PluginHost, - spaces: readonly CarriedSpace[], -): void { - const unreachable = spaces.filter( - ({ status }) => relayFixOf(status) === "reconnect", - ); - const refused = spaces.some( - ({ status }) => relayFixOf(status) === "settings", - ); - if (unreachable.length === 0 && !refused) return; - menu.addSeparator(); - if (unreachable.length > 0) { - menu.addItem((item) => - item - .setTitle("Reconnect") - .setIcon("refresh-cw") - .onClick(() => { - for (const { id } of unreachable) plugin.realtime.hub.reconnect(id); - }), - ); - } - if (refused) { - menu.addItem((item) => - item - .setTitle("Open relay settings") - .setIcon("settings") - .onClick(() => openPluginSettings(plugin.app)), - ); - } -} - -function addUnseen(menu: Menu, plugin: PluginHost): void { - const notes = [...plugin.unseen.all()].filter((path) => - plugin.app.vault.getFileByPath(path), - ); - const latest = notes.at(-1); - if (latest === undefined) return; - menu.addSeparator(); - menu.addItem((item) => - item - .setTitle(infoTitle(`${notes.length} changed by others`)) - .setIcon("dot") - .setIsLabel(true), - ); - const edited = lastEditLabel(plugin, latest); - if (edited) { - menu.addItem((item) => - item.setTitle(infoTitle(edited)).setIcon("pencil").setIsLabel(true), - ); - } -} diff --git a/packages/plugin/src/ui/modals/index.ts b/packages/plugin/src/ui/modals/index.ts deleted file mode 100644 index e06774c7..00000000 --- a/packages/plugin/src/ui/modals/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -export { - type ConfirmModalOptions, - openChoiceModal, - openConfirmModal, -} from "./confirm-modal"; -export { AcceptInviteModal } from "./invite-modal"; -export { askNewPassphrase, askPassphrase } from "./passphrase-modal"; -export { openPromiseModal } from "./promise-modal"; -export { openPromptModal, type PromptModalOptions } from "./prompt-modal"; -export { openRelayUpdateModal } from "./relay-update-modal"; -export { confirmRemoteReset } from "./reset-modal"; -export { showSettingsTransferExport } from "./settings-transfer-export-modal"; -export { - askSettingsTransferInput, - confirmSettingsTransferImport, -} from "./settings-transfer-modal"; -export { openStorageRefusedModal } from "./storage-refused-modal"; diff --git a/packages/plugin/src/ui/modals/passphrase-modal.ts b/packages/plugin/src/ui/modals/passphrase-modal.ts deleted file mode 100644 index 458f4d2f..00000000 --- a/packages/plugin/src/ui/modals/passphrase-modal.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { type App, ButtonComponent, Modal, Setting } from "obsidian"; - -import { weakPassphrase } from "@/crypto"; -import { alertLine, modalFooter, onEnter, renderModalHead } from "@/ui/common"; - -import { openPromiseModal } from "./promise-modal"; - -class PassphraseModal extends Modal { - private readonly resolveValue: (value: string | null) => void; - private value = ""; - private errorEl: HTMLElement | null = null; - - constructor(app: App, resolveValue: (value: string | null) => void) { - super(app); - this.resolveValue = resolveValue; - } - - onOpen(): void { - const { contentEl } = this; - renderModalHead(this, { icon: "lock", title: "MDSync passphrase" }); - contentEl.createEl("p", { - text: "Enter the encryption passphrase for this vault. It is never sent to the remote storage.", - }); - - new Setting(contentEl).setName("Passphrase").addText((t) => { - t.inputEl.type = "password"; - t.inputEl.setAttr("aria-label", "Passphrase"); - t.onChange((v) => { - this.value = v; - }); - onEnter(t.inputEl, () => this.submit()); - }); - - this.errorEl = alertLine(contentEl); - - const footer = modalFooter(this); - new ButtonComponent(footer).setButtonText("Cancel").onClick(() => { - this.resolveValue(null); - this.close(); - }); - new ButtonComponent(footer) - .setButtonText("Continue") - .setCta() - .onClick(() => this.submit()); - } - - onClose(): void { - this.contentEl.empty(); - } - - private submit(): void { - if (!this.value) { - this.errorEl?.setText("Enter the passphrase, or cancel."); - return; - } - this.resolveValue(this.value); - this.close(); - } -} - -class NewPassphraseModal extends Modal { - private readonly resolveValue: (value: string | null) => void; - private next = ""; - private confirm = ""; - private errorEl: HTMLElement | null = null; - - constructor(app: App, resolveValue: (value: string | null) => void) { - super(app); - this.resolveValue = resolveValue; - } - - onOpen(): void { - const { contentEl } = this; - renderModalHead(this, { icon: "key-round", title: "Change passphrase" }); - contentEl.createEl("p", { - text: "Re-wraps the vault's data key under a new passphrase. Your notes are not re-encrypted, so this is instant. Every device must switch to the new passphrase afterwards.", - }); - - let confirmField: HTMLInputElement | undefined; - new Setting(contentEl).setName("New passphrase").addText((t) => { - t.inputEl.type = "password"; - t.inputEl.setAttr("aria-label", "New passphrase"); - t.onChange((v) => { - this.next = v; - }); - onEnter(t.inputEl, () => - this.next ? confirmField?.focus() : this.submit(), - ); - }); - - new Setting(contentEl).setName("Confirm passphrase").addText((t) => { - confirmField = t.inputEl; - t.inputEl.type = "password"; - t.inputEl.setAttr("aria-label", "Confirm passphrase"); - t.onChange((v) => { - this.confirm = v; - }); - onEnter(t.inputEl, () => this.submit()); - }); - - this.errorEl = alertLine(contentEl); - this.errorEl.hidden = true; - - const footer = modalFooter(this); - new ButtonComponent(footer).setButtonText("Cancel").onClick(() => { - this.resolveValue(null); - this.close(); - }); - new ButtonComponent(footer) - .setButtonText("Change") - .setCta() - .onClick(() => this.submit()); - } - - onClose(): void { - this.contentEl.empty(); - } - - private submit(): void { - const weak = weakPassphrase(this.next); - if (weak) { - this.showError(weak); - return; - } - if (this.next !== this.confirm) { - this.showError("Passphrases do not match."); - return; - } - this.resolveValue(this.next); - this.close(); - } - - private showError(message: string): void { - if (!this.errorEl) return; - this.errorEl.setText(message); - this.errorEl.hidden = false; - } -} - -export function askNewPassphrase(app: App): Promise { - return openPromiseModal( - (answer) => new NewPassphraseModal(app, answer), - null, - ); -} - -export function askPassphrase(app: App): Promise { - return openPromiseModal( - (answer) => new PassphraseModal(app, answer), - null, - ); -} diff --git a/packages/plugin/src/ui/source-control/day-groups.ts b/packages/plugin/src/ui/source-control/day-groups.ts deleted file mode 100644 index 5c4bba86..00000000 --- a/packages/plugin/src/ui/source-control/day-groups.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { formatDayLabel, formatRelativeTime } from "@/shared"; - -/** A dated row's title: its age today, its clock time on an older day, whose name heads the group. */ -export function timeInDay(ms: number, now: number = Date.now()): string { - if (new Date(ms).toDateString() === new Date(now).toDateString()) - return formatRelativeTime(ms, now); - return new Date(ms).toLocaleTimeString(undefined, { - hour: "2-digit", - minute: "2-digit", - }); -} - -export interface DayGroup { - label: string; - rows: T[]; -} - -export const PINNED_LABEL = "Pinned"; - -/** Pinned rows lead under their own heading; the rest bucket by calendar day, keeping their order. */ -export function groupRows( - rows: readonly T[], - now: number = Date.now(), -): DayGroup[] { - const pinned = rows.filter((row) => row.pinned); - const groups = groupByDay( - rows.filter((row) => !row.pinned), - now, - ); - if (pinned.length > 0) groups.unshift({ label: PINNED_LABEL, rows: pinned }); - return groups; -} - -function groupByDay( - rows: readonly T[], - now: number, -): DayGroup[] { - const groups: DayGroup[] = []; - for (const row of rows) { - const label = formatDayLabel(row.createdAt, now); - const last = groups[groups.length - 1]; - if (last?.label === label) last.rows.push(row); - else groups.push({ label, rows: [row] }); - } - return groups; -} diff --git a/packages/plugin/src/ui/source-control/index.ts b/packages/plugin/src/ui/source-control/index.ts deleted file mode 100644 index 88337928..00000000 --- a/packages/plugin/src/ui/source-control/index.ts +++ /dev/null @@ -1,33 +0,0 @@ -export { SourceControlActions } from "./actions"; -export { ChangesTab } from "./changes-tab"; -export { renderConflictPreview } from "./conflict-preview"; -export { ConflictPreviewManager } from "./conflict-preview-manager"; -export { type DayGroup, groupRows } from "./day-groups"; -export { buildHistoryRows, type HistoryRow } from "./history-rows"; -export { HistoryTab } from "./history-tab"; -export { - confirmAdoptNewVault, - confirmBatchResolve, -} from "./modals"; -export { confirmRestore } from "./restore-modal"; -export { rowFromChange, rowFromConflict } from "./row-formatter"; -export { canPullAll, canPushAll } from "./sync-gates"; -export { - buildTimelineRows, - countsText, - describeRestorePlan, - samplePaths, - type TimelineFileRow, - type TimelineRow, - timelineDiffTarget, -} from "./timeline-rows"; -export { TimelineTab } from "./timeline-tab"; -export { - buildTrashRows, - resolveRestoreTarget, - type TrashRow, -} from "./trash-rows"; -export { TrashTab } from "./trash-tab"; -export { buildTree } from "./tree-builder"; -export type { FileRow, TreeNode } from "./types"; -export { ESection } from "./types"; diff --git a/packages/plugin/src/ui/source-control/timeline-tab.ts b/packages/plugin/src/ui/source-control/timeline-tab.ts deleted file mode 100644 index c7143333..00000000 --- a/packages/plugin/src/ui/source-control/timeline-tab.ts +++ /dev/null @@ -1,328 +0,0 @@ -import { setIcon } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import { formatBytes } from "@/shared"; -import type { SnapshotListResult } from "@/sync/history"; -import { - appendIconButton, - callout, - makeActivatable, - notifyError, - onLongPress, - renderPath, -} from "@/ui/common"; -import type { HistoryDiffTarget } from "@/ui/source-control-view"; -import { groupRows } from "./day-groups"; -import { HistoryList } from "./history-list"; -import { STATUS_CLASSES, STATUS_LETTERS } from "./row-formatter"; -import { RowPager } from "./row-pager"; -import { renderDelta } from "./row-parts"; -import { - renderEmptyState, - renderHistoryOff, - renderLoadError, - renderLoading, -} from "./tab-states"; -import { TimelineActions } from "./timeline-actions"; -import { - buildTimelineRows, - type TimelineFileRow, - type TimelineRow, - timelineDiffTarget, -} from "./timeline-rows"; - -export class TimelineTab { - private readonly snapshots = new HistoryList(() => { - const loaded = this.snapshots.value; - if (loaded) this.prune(loaded); - this.onRerender(); - }); - private openGeneration = 0; - private readonly expanded = new Set(); - private readonly pages = new Map(); - private selected: string | null = null; - private opening: string | null = null; - private list: HTMLElement | null = null; - private scrollTop = 0; - private focusKey: string | null = null; - private readonly actions: TimelineActions; - - constructor( - private readonly plugin: PluginHost, - private readonly onRerender: () => void, - private readonly openDiff: ( - path: string, - history: HistoryDiffTarget, - ) => Promise, - onSnapshotsChanged: () => void, - ) { - this.actions = new TimelineActions( - plugin, - onSnapshotsChanged, - (row, file, mode) => void this.openFile(row, file, mode), - ); - } - - captureState(): void { - if ( - !this.list?.isConnected || - this.list.hasClass("is-loading") || - !this.snapshots.value - ) - return; - this.scrollTop = this.list.scrollTop; - const active = this.list.ownerDocument.activeElement; - this.focusKey = - active && this.list.contains(active) - ? active.getAttribute("data-timeline-focus") - : null; - } - - clear(): void { - this.captureState(); - this.snapshots.clear(); - } - - clearOffline(): boolean { - if (!this.snapshots.offline) return false; - this.clear(); - return true; - } - - dispose(): void { - this.snapshots.clear(); - this.openGeneration++; - this.list = null; - } - - render(parent: HTMLElement, tools: HTMLElement): void { - const pane = parent.createDiv({ - cls: "mdsync-history-pane mdsync-timeline", - }); - if (!this.plugin.settings.fileHistoryEnabled) { - renderHistoryOff( - pane, - this.plugin.app, - "File version history is disabled. Enable it in settings to see the timeline.", - ); - return; - } - appendIconButton(tools, "refresh-cw", "Refresh timeline", () => - this.reload(), - ); - this.list = pane.createDiv({ - cls: "mdsync-history-list mdsync-timeline-list", - }); - this.list.toggleClass("is-loading", this.snapshots.value === null); - this.renderBody(this.list); - if (this.snapshots.value) { - this.list.scrollTop = this.scrollTop; - if (this.focusKey) { - const target = Array.from( - this.list.querySelectorAll("[data-timeline-focus]"), - ).find( - (el) => el.getAttribute("data-timeline-focus") === this.focusKey, - ); - target?.focus({ preventScroll: true }); - this.focusKey = null; - } - } - } - - private reload(): void { - this.clear(); - this.onRerender(); - } - - private renderBody(body: HTMLElement): void { - const { value: snapshots, error } = this.snapshots; - if (error) { - renderLoadError(body, "Could not load the timeline", error, () => - this.reload(), - ); - return; - } - if (!snapshots) { - renderLoading(body); - this.snapshots.load(() => this.plugin.controller.history.listSnapshots()); - return; - } - if (snapshots.lagging) { - callout( - body, - "warning", - "History has not caught up with the latest push yet, so the newest snapshot is missing.", - ); - } - const rows = buildTimelineRows(snapshots.snapshots, { - currentDevice: this.plugin.controller.currentDevice(), - }); - if (rows.length === 0 && !snapshots.lagging) { - renderEmptyState(body, { - icon: "clock-3", - title: "No pushes yet", - text: "No pushes recorded yet. The timeline fills up as you push.", - }); - } - for (const group of groupRows(rows)) { - body.createDiv({ cls: "mdsync-timeline-day", text: group.label }); - for (const row of group.rows) this.renderRow(body, row); - } - } - - /** Rows gone from the new list take their open state with them. */ - private prune({ snapshots }: SnapshotListResult): void { - const ids = new Set(snapshots.map((row) => row.id)); - for (const id of this.expanded) if (!ids.has(id)) this.expanded.delete(id); - for (const id of this.pages.keys()) if (!ids.has(id)) this.pages.delete(id); - } - - private renderRow(body: HTMLElement, row: TimelineRow): void { - const expanded = this.expanded.has(row.snapshotId); - const card = body.createDiv({ cls: "mdsync-timeline-card" }); - const head = card.createDiv({ cls: "mdsync-timeline-head" }); - head.setAttr("data-timeline-focus", row.snapshotId); - head.setAttr("aria-expanded", String(expanded)); - makeActivatable(head, `${row.title} · ${row.tooltip}`, () => { - if (expanded) this.expanded.delete(row.snapshotId); - else this.expanded.add(row.snapshotId); - this.onRerender(); - }); - const chevron = head.createSpan({ cls: "mdsync-timeline-icon" }); - setIcon(chevron, expanded ? "chevron-down" : "chevron-right"); - const copy = head.createDiv({ cls: "mdsync-timeline-copy" }); - const title = copy.createDiv({ cls: "mdsync-timeline-title" }); - title.createSpan({ cls: "mdsync-history-row-title", text: row.title }); - if (row.isHead) - title.createSpan({ cls: "mdsync-pill", text: "Latest push" }); - if (row.pinned) { - const pin = title.createSpan({ cls: "mdsync-history-pin" }); - setIcon(pin, "pin"); - pin.setAttr("aria-label", "Pinned snapshot"); - } - this.renderMeta(copy, row); - const actions = head.createDiv({ cls: "mdsync-timeline-actions" }); - const more = appendIconButton( - actions, - "ellipsis", - "Snapshot actions", - (event) => { - event.stopPropagation(); - this.actions.showSnapshotMenu(event, row); - }, - ); - more.setAttr("data-timeline-focus", `${row.snapshotId}:menu`); - head.addEventListener("contextmenu", (event) => { - event.preventDefault(); - this.actions.showSnapshotMenu(event, row); - }); - if (!expanded) return; - const list = card.createDiv({ cls: "mdsync-timeline-files" }); - if (!row.files || row.files.length === 0) { - list.createDiv({ - cls: "mdsync-status-line", - text: row.files - ? "No file changes in this push." - : "The change record for this push is unavailable.", - }); - return; - } - let pager = this.pages.get(row.snapshotId); - if (!pager) { - pager = new RowPager(); - this.pages.set(row.snapshotId, pager); - } - for (const file of pager.slice(row.files)) this.renderFile(list, row, file); - pager.render(list, row.files.length, this.onRerender); - } - - /** Who pushed, a chip per kind of change and the net size. */ - private renderMeta(parent: HTMLElement, row: TimelineRow): void { - const meta = parent.createDiv({ - cls: "mdsync-history-row-meta mdsync-timeline-meta", - }); - meta.createSpan({ cls: "mdsync-timeline-device", text: row.meta }); - if (!row.tally) { - meta.createSpan({ text: "Change record unavailable" }); - return; - } - const chips = meta.createSpan({ cls: "mdsync-timeline-chips" }); - if (row.counts) chips.setAttr("aria-label", row.counts); - for (const [action, count] of row.tally) { - chips.createSpan({ - cls: `mdsync-count-chip ${STATUS_CLASSES[action]}`, - text: `${STATUS_LETTERS[action]} ${count}`, - }); - } - if (row.netDelta) renderDelta(meta, row.netDelta, "mdsync-timeline-net"); - } - - private renderFile( - parent: HTMLElement, - row: TimelineRow, - file: TimelineFileRow, - ): void { - const key = JSON.stringify([row.snapshotId, file.path]); - const item = parent.createDiv({ - cls: "mdsync-file-row mdsync-timeline-file", - }); - item.toggleClass("is-deleted", file.action === "delete"); - item.setAttr("data-timeline-focus", key); - item.toggleClass("is-active", this.selected === key); - item.toggleClass("is-opening", this.opening === key); - if (this.selected === key) item.setAttr("aria-current", "true"); - if (this.opening === key) item.setAttr("aria-busy", "true"); - // Before makeActivatable: the hold has to swallow its own trailing click. - onLongPress(item, (event) => this.actions.showFileMenu(event, row, file)); - makeActivatable(item, file.path, () => void this.openFile(row, file)); - renderPath(item, file.path); - // What a change moved; an addition, a deletion or an even change shows its size. - if (file.sizeDelta) - renderDelta(item, file.sizeDelta, "mdsync-timeline-size"); - else - item.createSpan({ - cls: "mdsync-timeline-size", - text: formatBytes(file.size), - }); - item.createSpan({ - cls: `mdsync-file-status ${STATUS_CLASSES[file.action]}`, - text: STATUS_LETTERS[file.action], - }); - const actions = item.createDiv({ cls: "mdsync-timeline-actions" }); - const more = appendIconButton( - actions, - "ellipsis", - `Actions for ${file.path}`, - (event) => { - event.stopPropagation(); - this.actions.showFileMenu(event, row, file); - }, - ); - more.setAttr("data-timeline-focus", `${key}:menu`); - item.addEventListener("contextmenu", (event) => { - event.preventDefault(); - this.actions.showFileMenu(event, row, file); - }); - } - - private async openFile( - row: TimelineRow, - file: TimelineFileRow, - mode: "current" | "change" = "current", - ): Promise { - const generation = ++this.openGeneration; - this.selected = JSON.stringify([row.snapshotId, file.path]); - this.opening = this.selected; - this.onRerender(); - try { - await this.openDiff(file.path, timelineDiffTarget(file, mode)); - } catch (error) { - if (generation === this.openGeneration) - notifyError("Could not open historical file", error); - } finally { - if (generation === this.openGeneration) { - this.opening = null; - this.onRerender(); - } - } - } -} diff --git a/packages/plugin/src/utils/index.ts b/packages/plugin/src/utils/index.ts deleted file mode 100644 index 9304c298..00000000 --- a/packages/plugin/src/utils/index.ts +++ /dev/null @@ -1,9 +0,0 @@ -export * from "./base64"; -export * from "./bytes"; -export * from "./compress"; -export * from "./concurrency"; -export * from "./diff"; -export * from "./eol"; -export * from "./file-concurrency"; -export * from "./revision"; -export * from "./search"; diff --git a/packages/plugin/tests/ui/push-result.test.ts b/packages/plugin/tests/app/push-result.test.ts similarity index 91% rename from packages/plugin/tests/ui/push-result.test.ts rename to packages/plugin/tests/app/push-result.test.ts index e228ade8..fb15bf6c 100644 --- a/packages/plugin/tests/ui/push-result.test.ts +++ b/packages/plugin/tests/app/push-result.test.ts @@ -1,9 +1,9 @@ import { TestSession, useEncryptionKey } from "@tests/helpers/session"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { PluginHost } from "@/plugin/host"; -import { SyncController } from "@/sync/controller"; -import { runWithNotice } from "@/ui/common/notices"; -import { SourceControlActions } from "@/ui/source-control/actions"; +import type { PluginHost } from "@/app/host"; +import { runWithNotice } from "@/core/ui/notices"; +import { SourceControlActions } from "@/features/source-control/actions/actions"; +import { SyncController } from "@/features/sync/controller"; const notices: string[] = []; vi.mock("obsidian", async (importOriginal) => ({ diff --git a/packages/plugin/tests/plugin/realtime.test.ts b/packages/plugin/tests/app/realtime.test.ts similarity index 80% rename from packages/plugin/tests/plugin/realtime.test.ts rename to packages/plugin/tests/app/realtime.test.ts index 4bbe6de5..ad1dc945 100644 --- a/packages/plugin/tests/plugin/realtime.test.ts +++ b/packages/plugin/tests/app/realtime.test.ts @@ -1,9 +1,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -import type { HubListener } from "@/hub/connection"; -import type { LiveHost } from "@/plugin/live"; -import { createRealtime } from "@/plugin/realtime"; -import { VAULT_SPACE } from "@/sync/space"; +import { createRealtime } from "@/app/realtime"; +import type { HubListener } from "@/core/hub"; +import type { LiveHost } from "@/features/live/register"; +import type { SpaceAccessHost } from "@/features/spaces/space-access"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; const state = vi.hoisted(() => ({ listener: {} as HubListener })); @@ -26,7 +26,7 @@ vi.mock("obsidian", async (original) => ({ }); }, })); -vi.mock("@/hub", () => ({ +vi.mock("@/features/relay/connection", () => ({ HubConnection: class { listen(listener: HubListener) { state.listener = listener; @@ -35,15 +35,17 @@ vi.mock("@/hub", () => ({ dispose() {} }, })); -vi.mock("@/presence", () => ({ +vi.mock("@/features/presence/here", () => ({ People: class { refresh() {} dispose() {} }, watchHere: () => ({ refresh() {}, stop() {} }), })); -vi.mock("@/plugin/space-access", () => ({ createSpaceAccess: () => ({}) })); -vi.mock("@/plugin/live", () => ({ +vi.mock("@/features/spaces/space-access", () => ({ + createSpaceAccess: () => ({}), +})); +vi.mock("@/features/live/register", () => ({ createLive: () => ({ sessions: { refresh: async () => {} }, notes: () => ({}), @@ -64,7 +66,7 @@ function realtime() { settings: () => ({}), spaces: { partition: () => [] }, app: {}, - } as unknown as LiveHost; + } as unknown as LiveHost & SpaceAccessHost; return { pull, realtime: createRealtime(host) }; } diff --git a/packages/plugin/tests/app/scope-refresh.test.ts b/packages/plugin/tests/app/scope-refresh.test.ts new file mode 100644 index 00000000..b2d69961 --- /dev/null +++ b/packages/plugin/tests/app/scope-refresh.test.ts @@ -0,0 +1,74 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { createScopeRefresh } from "@/app/scope-refresh"; +import { mergeSettings } from "@/app/settings"; +import type { MdsyncSettings } from "@/core/settings/model"; +import { defaultS3Config } from "@/features/storage/backends/s3"; +import type { SyncController } from "@/features/sync"; + +function setup( + snapshot: { result: boolean; lastCompareAt: number | null; busy: boolean }, + settings: MdsyncSettings, +) { + const controller = { + getSnapshot: () => snapshot, + invalidate: vi.fn(), + refresh: vi.fn(async () => {}), + }; + const scope = createScopeRefresh( + () => controller as unknown as SyncController, + () => settings, + ); + return { controller, scope }; +} + +const COMPARED = { result: true, lastCompareAt: 1, busy: false }; +const CONFIGURED = mergeSettings({ + storageConfigs: { + s3: { + ...defaultS3Config(), + bucket: "notes", + accessKeyId: "AKIA", + secretAccessKey: "S".repeat(40), + }, + }, +}); + +describe("createScopeRefresh", () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + + it("drops the comparison now and compares once the changes settle", () => { + const { controller, scope } = setup(COMPARED, CONFIGURED); + scope.schedule("a"); + scope.schedule("b"); + expect(controller.invalidate).toHaveBeenCalledTimes(2); + expect(controller.refresh).not.toHaveBeenCalled(); + vi.advanceTimersByTime(800); + expect(controller.refresh).toHaveBeenCalledOnce(); + }); + + it("does nothing before the first comparison has started", () => { + const { controller, scope } = setup( + { result: false, lastCompareAt: null, busy: false }, + CONFIGURED, + ); + scope.schedule(); + expect(controller.invalidate).not.toHaveBeenCalled(); + }); + + it("does not compare when sync is not possible", () => { + const { controller, scope } = setup(COMPARED, mergeSettings(null)); + scope.schedule(); + vi.advanceTimersByTime(800); + expect(controller.invalidate).toHaveBeenCalledOnce(); + expect(controller.refresh).not.toHaveBeenCalled(); + }); + + it("cancel stops a pending compare", () => { + const { controller, scope } = setup(COMPARED, CONFIGURED); + scope.schedule(); + scope.cancel(); + vi.advanceTimersByTime(800); + expect(controller.refresh).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/plugin/tests/core/session-factory.test.ts b/packages/plugin/tests/app/session-factory.test.ts similarity index 90% rename from packages/plugin/tests/core/session-factory.test.ts rename to packages/plugin/tests/app/session-factory.test.ts index b9bd12f3..dad16ecf 100644 --- a/packages/plugin/tests/core/session-factory.test.ts +++ b/packages/plugin/tests/app/session-factory.test.ts @@ -1,16 +1,16 @@ import { joined, record } from "@tests/helpers/space-records"; import { describe, expect, it, vi } from "vitest"; - -import type { PassphraseManager } from "@/core/passphrase-manager"; import { createSessionOpeners, type SessionFactoryDeps, -} from "@/core/session-factory"; -import type { StatePersister } from "@/core/state-persister"; -import { DEFAULT_SETTINGS, type MdsyncSettings } from "@/settings/model"; -import type { SpaceRecord } from "@/spaces/record"; -import { defaultS3Config } from "@/storage"; -import type { Space } from "@/sync/space"; +} from "@/app/session-factory"; +import { DEFAULT_SETTINGS } from "@/app/settings"; +import type { MdsyncSettings } from "@/core/settings/model"; +import type { SpaceRecord } from "@/features/spaces/record"; +import { defaultS3Config } from "@/features/storage/backends/s3"; +import type { StatePersister } from "@/features/sync/recovery/state-persister"; +import type { PassphraseManager } from "@/features/sync/remote/passphrase-manager"; +import type { Space } from "@/features/sync/remote/space"; const SHARE: Space = { id: "team", root: "Team" }; diff --git a/packages/plugin/tests/settings/envelope.test.ts b/packages/plugin/tests/app/settings/envelope.test.ts similarity index 93% rename from packages/plugin/tests/settings/envelope.test.ts rename to packages/plugin/tests/app/settings/envelope.test.ts index 51ab8089..8dbaca6f 100644 --- a/packages/plugin/tests/settings/envelope.test.ts +++ b/packages/plugin/tests/app/settings/envelope.test.ts @@ -1,12 +1,12 @@ import { deviceKey, FakeSecretStorage } from "@tests/helpers/device-key"; import { link } from "@tests/helpers/shared-links"; import { describe, expect, it } from "vitest"; - -import { encryptJson } from "@/crypto"; -import { SettingsEnvelope } from "@/settings/envelope"; -import { type MdsyncSettings, mergeSettings } from "@/settings/model"; -import { defaultS3Config } from "@/storage"; -import { bytesToBase64 } from "@/utils"; +import { mergeSettings } from "@/app/settings"; +import { SettingsEnvelope } from "@/app/settings/envelope"; +import { encryptJson } from "@/core/crypto/cipher"; +import type { MdsyncSettings } from "@/core/settings/model"; +import { bytesToBase64 } from "@/core/utils/base64"; +import { defaultS3Config } from "@/features/storage/backends/s3"; const SEALED = [ "storageConfigs", diff --git a/packages/plugin/tests/settings/model.test.ts b/packages/plugin/tests/app/settings/index.test.ts similarity index 74% rename from packages/plugin/tests/settings/model.test.ts rename to packages/plugin/tests/app/settings/index.test.ts index a1565052..02a25fa6 100644 --- a/packages/plugin/tests/settings/model.test.ts +++ b/packages/plugin/tests/app/settings/index.test.ts @@ -1,47 +1,16 @@ import { describe, expect, it } from "vitest"; +import { DEFAULT_SETTINGS, mergeSettings } from "@/app/settings"; import { AUTO_PUSH_SETTLE_MAX_SECONDS, BULK_DELETE_LIMIT_MAX, LIVE_SEND_MS, -} from "@/constants"; +} from "@/core/constants"; +import { EPluginLevel, type MdsyncSettings } from "@/core/settings"; +import { defaultS3Config } from "@/features/storage/backends/s3"; import { - DEFAULT_SETTINGS, - isRelayConfigured, - mergeSettings, -} from "@/settings/model"; -import { defaultS3Config } from "@/storage"; -import { EStorageBackend, type StorageAdapterConfig } from "@/storage/config"; - -describe("isRelayConfigured", () => { - const secret = "s3cret"; - - it.each([ - "https://relay.example", - "http://localhost:8787", - "http://127.0.0.1:8787/", - "http://[::1]:8787", - ])("accepts %s", (relayUrl) => { - expect(isRelayConfigured({ relayUrl, relaySecret: secret })).toBe(true); - }); - - it("needs both the URL and the secret", () => { - expect(isRelayConfigured({ relayUrl: "", relaySecret: secret })).toBe( - false, - ); - expect( - isRelayConfigured({ relayUrl: "https://relay.example", relaySecret: "" }), - ).toBe(false); - }); - - it("refuses a remote relay that would take the secret over plain http", () => { - expect( - isRelayConfigured({ - relayUrl: "http://relay.example", - relaySecret: secret, - }), - ).toBe(false); - }); -}); + EStorageBackend, + type StorageAdapterConfig, +} from "@/features/storage/config"; describe("mergeSettings", () => { it("requires opt-in for every configuration category on a fresh device", () => { @@ -182,13 +151,71 @@ describe("mergeSettings", () => { }); }); +describe("mergeSettings plugin levels", () => { + it("syncs each plugin's settings by default", () => { + expect(mergeSettings(null).pluginLevel).toBe(EPluginLevel.Settings); + expect(mergeSettings(null).pluginLevels).toEqual({}); + }); + + it("keeps a listed default level", () => { + for (const pluginLevel of [ + EPluginLevel.Settings, + EPluginLevel.Code, + EPluginLevel.Data, + ]) { + expect(mergeSettings({ pluginLevel }).pluginLevel).toBe(pluginLevel); + } + }); + + it("falls back to Settings on a default level that is Off or not a level", () => { + for (const pluginLevel of [EPluginLevel.Off, 4, -1, "2", null, {}]) { + const merged = mergeSettings({ + pluginLevel: pluginLevel as unknown as EPluginLevel, + }); + expect(merged.pluginLevel).toBe(EPluginLevel.Settings); + } + }); + + it("keeps the levels 0 to 3 of a plugin and drops any other value", () => { + const merged = mergeSettings({ + pluginLevels: { + off: 0, + settings: 1, + code: 2, + data: 3, + four: 4, + negative: -1, + fraction: 1.5, + text: "2", + none: null, + nested: {}, + } as unknown as Record, + }); + + expect(merged.pluginLevels).toEqual({ + off: EPluginLevel.Off, + settings: EPluginLevel.Settings, + code: EPluginLevel.Code, + data: EPluginLevel.Data, + }); + }); + + it("takes no levels from a stored value that is not a map", () => { + for (const pluginLevels of ["data", 3, null, true]) { + const merged = mergeSettings({ + pluginLevels: pluginLevels as unknown as Record, + }); + expect(merged.pluginLevels).toEqual({}); + } + }); +}); + describe("mergeSettings clamps", () => { it("refuses a negative or zero value and falls back to the default", () => { const merged = mergeSettings({ autoSyncIntervalMinutes: -5, autoPushSettleSeconds: 0, maxFileBytes: 0, - fileHistoryMaxSnapshots: 0, }); expect(merged.autoSyncIntervalMinutes).toBe( @@ -198,21 +225,16 @@ describe("mergeSettings clamps", () => { DEFAULT_SETTINGS.autoPushSettleSeconds, ); expect(merged.maxFileBytes).toBe(DEFAULT_SETTINGS.maxFileBytes); - expect(merged.fileHistoryMaxSnapshots).toBe( - DEFAULT_SETTINGS.fileHistoryMaxSnapshots, - ); }); it("caps a value that is merely greedy", () => { const merged = mergeSettings({ autoSyncIntervalMinutes: 999_999, autoPushSettleSeconds: 999, - fileHistoryMaxSnapshots: 1e9, }); expect(merged.autoSyncIntervalMinutes).toBe(24 * 60); expect(merged.autoPushSettleSeconds).toBe(AUTO_PUSH_SETTLE_MAX_SECONDS); - expect(merged.fileHistoryMaxSnapshots).toBe(1000); }); it("ignores a number that is not one", () => { @@ -227,6 +249,19 @@ describe("mergeSettings clamps", () => { ); }); + it("keeps history 3 months by default and only for a listed choice; drops the old version count", () => { + expect(DEFAULT_SETTINGS.fileHistoryKeep).toBe("quarter"); + expect(mergeSettings({ fileHistoryKeep: "year" }).fileHistoryKeep).toBe( + "year", + ); + const merged = mergeSettings({ + fileHistoryKeep: "toString", + fileHistoryMaxSnapshots: 50, + } as unknown as Partial); + expect(merged.fileHistoryKeep).toBe("quarter"); + expect(merged).not.toHaveProperty("fileHistoryMaxSnapshots"); + }); + it("defaults the bulk delete guard to on with a limit of 5", () => { expect(DEFAULT_SETTINGS.confirmBulkDeletes).toBe(true); expect(DEFAULT_SETTINGS.bulkDeleteLimit).toBe(5); diff --git a/packages/plugin/tests/app/settings/store.test.ts b/packages/plugin/tests/app/settings/store.test.ts new file mode 100644 index 00000000..23d24a24 --- /dev/null +++ b/packages/plugin/tests/app/settings/store.test.ts @@ -0,0 +1,88 @@ +import { deviceKey, FakeSecretStorage } from "@tests/helpers/device-key"; +import { describe, expect, it, vi } from "vitest"; +import { mergeSettings } from "@/app/settings"; +import { SettingsStore } from "@/app/settings/store"; + +function plugin(data: Record | null) { + return { + loadData: vi.fn(async () => data), + saveData: vi.fn(async (_data: unknown) => {}), + }; +} + +describe("SettingsStore", () => { + it("tells a first install from a saved one", async () => { + const fresh = new SettingsStore( + plugin(null), + deviceKey(new FakeSecretStorage()), + ); + await fresh.load(); + expect(fresh.freshInstall).toBe(true); + + const saved = new SettingsStore( + plugin({}), + deviceKey(new FakeSecretStorage()), + ); + await saved.load(); + expect(saved.freshInstall).toBe(false); + }); + + it("starts a first install with history on, and keeps a saved choice", async () => { + const fresh = new SettingsStore( + plugin(null), + deviceKey(new FakeSecretStorage()), + ); + expect((await fresh.load()).fileHistoryEnabled).toBe(true); + + const saved = new SettingsStore( + plugin({}), + deviceKey(new FakeSecretStorage()), + ); + expect((await saved.load()).fileHistoryEnabled).toBe(false); + }); + + it("seals secrets an earlier build left in the clear at load", async () => { + const host = plugin({ relaySecret: "relay-secret" }); + const store = new SettingsStore(host, deviceKey(new FakeSecretStorage())); + + const settings = await store.load(); + + expect(settings.relaySecret).toBe("relay-secret"); + expect(host.saveData).toHaveBeenCalledOnce(); + expect(host.saveData.mock.calls[0]?.[0]).not.toHaveProperty("relaySecret"); + }); + + it("saves one write at a time, in call order", async () => { + const host = plugin(null); + const landed: string[] = []; + let release: () => void = () => {}; + host.saveData.mockImplementationOnce(async (data) => { + await new Promise((resolve) => { + release = resolve; + }); + landed.push(`first:${(data as { uiLayout?: string }).uiLayout}`); + }); + host.saveData.mockImplementationOnce(async (data) => { + landed.push(`second:${(data as { uiLayout?: string }).uiLayout}`); + }); + const store = new SettingsStore(host, deviceKey(new FakeSecretStorage())); + + const first = store.write(mergeSettings({ uiLayout: "flat" })); + const second = store.write(mergeSettings({ uiLayout: "tree" })); + await vi.waitFor(() => expect(host.saveData).toHaveBeenCalledOnce()); + expect(landed).toEqual([]); + release(); + await Promise.all([first, second]); + + expect(landed).toEqual(["first:flat", "second:tree"]); + }); + + it("keeps writing after one write failed", async () => { + const host = plugin(null); + host.saveData.mockRejectedValueOnce(new Error("disk full")); + const store = new SettingsStore(host, deviceKey(new FakeSecretStorage())); + + await expect(store.write(mergeSettings(null))).rejects.toThrow("disk full"); + await expect(store.write(mergeSettings(null))).resolves.toBeUndefined(); + }); +}); diff --git a/packages/plugin/tests/ui/share-menu.test.ts b/packages/plugin/tests/app/share-menu.test.ts similarity index 91% rename from packages/plugin/tests/ui/share-menu.test.ts rename to packages/plugin/tests/app/share-menu.test.ts index 281235a9..2997c4d3 100644 --- a/packages/plugin/tests/ui/share-menu.test.ts +++ b/packages/plugin/tests/app/share-menu.test.ts @@ -2,10 +2,13 @@ import { device, record } from "@tests/helpers/space-records"; import type { Menu, MenuItem } from "obsidian"; import { describe, expect, it } from "vitest"; -import type { PluginHost } from "@/plugin/host"; -import type { SpaceRecord } from "@/spaces/record"; -import { EStorageBackend, type S3StorageConfig } from "@/storage"; -import { addShareMenuItem } from "@/ui/shares/share-window"; +import type { PluginHost } from "@/app/host"; +import type { SpaceRecord } from "@/features/spaces/record"; +import { addShareMenuItem } from "@/features/spaces/ui/window/share-window"; +import { + EStorageBackend, + type S3StorageConfig, +} from "@/features/storage/config"; const S3: S3StorageConfig = { kind: EStorageBackend.S3, diff --git a/packages/plugin/tests/app/storage-refused.test.ts b/packages/plugin/tests/app/storage-refused.test.ts new file mode 100644 index 00000000..3a31130c --- /dev/null +++ b/packages/plugin/tests/app/storage-refused.test.ts @@ -0,0 +1,64 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { PluginHost } from "@/app/host"; +import { mergeSettings } from "@/app/settings"; +import { createStorageRefused } from "@/app/storage-refused"; +import { defaultS3Config } from "@/features/storage/backends/s3"; +import { EStorageBackend } from "@/features/storage/config"; +import { openStorageRefusedModal } from "@/features/storage/ui/storage-refused-modal"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; + +vi.mock("@/features/storage/ui/storage-refused-modal", () => ({ + openStorageRefusedModal: vi.fn(async () => false), +})); + +const owned = { id: "owned", root: "Team" }; +const joined = { id: "joined", root: "Other" }; + +function host(): PluginHost { + return { + settings: mergeSettings({ + activeStorageKind: EStorageBackend.S3, + storageConfigs: { + [EStorageBackend.S3]: { + ...defaultS3Config(), + bucket: "vault", + accessKeyId: "id", + secretAccessKey: "old", + }, + }, + }), + spaces: { + get: (id: string) => + id === owned.id + ? { access: { kind: "owner" } } + : id === joined.id + ? { access: { kind: "participant" } } + : undefined, + }, + } as unknown as PluginHost; +} + +describe("createStorageRefused", () => { + beforeEach(() => { + vi.mocked(openStorageRefusedModal).mockClear(); + }); + + it("asks for the vault", () => { + const plugin = host(); + createStorageRefused(plugin)(VAULT_SPACE); + expect(openStorageRefusedModal).toHaveBeenCalledExactlyOnceWith(plugin); + }); + + it("asks for an owned share", () => { + createStorageRefused(host())(owned); + expect(openStorageRefusedModal).toHaveBeenCalledOnce(); + }); + + it("never asks for a participant's share, nor spends the ask on one", () => { + const refused = createStorageRefused(host()); + refused(joined); + expect(openStorageRefusedModal).not.toHaveBeenCalled(); + refused(VAULT_SPACE); + expect(openStorageRefusedModal).toHaveBeenCalledOnce(); + }); +}); diff --git a/packages/plugin/tests/arch/folders.test.ts b/packages/plugin/tests/arch/folders.test.ts new file mode 100644 index 00000000..008461ac --- /dev/null +++ b/packages/plugin/tests/arch/folders.test.ts @@ -0,0 +1,28 @@ +import { readdirSync } from "node:fs"; +import { join, relative } from "node:path"; +import { expect, test } from "vitest"; + +const SRC = join(__dirname, "../../src"); +const MAX_MODULES = 12; + +function crowded(dir: string): string[] { + const entries = readdirSync(dir, { withFileTypes: true }); + const modules = entries.filter( + (e) => e.isFile() && e.name.endsWith(".ts") && !e.name.endsWith(".d.ts"), + ); + const here = + modules.length > MAX_MODULES + ? [`${relative(SRC, dir) || "."}: ${modules.length}`] + : []; + return [ + ...here, + ...entries + .filter((e) => e.isDirectory()) + .flatMap((e) => crowded(join(dir, e.name))), + ]; +} + +// Past the cap, group by sub-area, never by kind of file. +test("no source folder holds more than 12 modules", () => { + expect(crowded(SRC)).toEqual([]); +}); diff --git a/packages/plugin/tests/core/chunking/fastcdc.test.ts b/packages/plugin/tests/core/chunking/fastcdc.test.ts new file mode 100644 index 00000000..2b9dec23 --- /dev/null +++ b/packages/plugin/tests/core/chunking/fastcdc.test.ts @@ -0,0 +1,63 @@ +import { seeded } from "@tests/helpers/seeded"; +import { describe, expect, it } from "vitest"; +import { chunkEnds, gearTable } from "@/core/chunking"; + +const PARAMS = { min: 1024, avg: 4096, max: 16_384 }; +const GEAR = gearTable(7); + +function noise(length: number, seed: number): Uint8Array { + const random = seeded(seed); + return Uint8Array.from({ length }, () => Math.floor(random() * 256)); +} + +function chunks(bytes: Uint8Array): string[] { + const out: string[] = []; + let start = 0; + for (const end of chunkEnds(bytes, PARAMS, GEAR)) { + out.push(Array.from(bytes.subarray(start, end)).join(",")); + start = end; + } + return out; +} + +describe("chunkEnds", () => { + it("keeps every chunk within bounds, near the average, and ends at the input's end", () => { + const bytes = noise(400_000, 1); + const ends = chunkEnds(bytes, PARAMS, GEAR); + const sizes = ends.map((end, index) => end - (ends[index - 1] ?? 0)); + expect(ends.at(-1)).toBe(bytes.length); + for (const size of sizes.slice(0, -1)) { + expect(size).toBeGreaterThanOrEqual(PARAMS.min); + expect(size).toBeLessThanOrEqual(PARAMS.max); + } + const average = bytes.length / sizes.length; + expect(average).toBeGreaterThan(PARAMS.avg / 2); + expect(average).toBeLessThan(PARAMS.avg * 2); + }); + + it("cuts the same content the same way, and another gear elsewhere", () => { + const bytes = noise(100_000, 2); + expect(chunkEnds(bytes, PARAMS, GEAR)).toEqual( + chunkEnds(bytes, PARAMS, gearTable(7)), + ); + expect(chunkEnds(bytes, PARAMS, gearTable(8))).not.toEqual( + chunkEnds(bytes, PARAMS, GEAR), + ); + }); + + it("changes only the chunks around an insertion", () => { + const before = noise(200_000, 3); + const after = new Uint8Array(before.length + 100); + after.set(before.subarray(0, 100_000)); + after.set(noise(100, 4), 100_000); + after.set(before.subarray(100_000), 100_100); + const kept = new Set(chunks(before)); + const fresh = chunks(after).filter((chunk) => !kept.has(chunk)); + expect(fresh.length).toBeLessThanOrEqual(2); + }); + + it("leaves an input up to the minimum whole", () => { + expect(chunkEnds(noise(1000, 5), PARAMS, GEAR)).toEqual([1000]); + expect(chunkEnds(new Uint8Array(0), PARAMS, GEAR)).toEqual([]); + }); +}); diff --git a/packages/plugin/tests/cloudflare/api.test.ts b/packages/plugin/tests/core/cloudflare/api.test.ts similarity index 95% rename from packages/plugin/tests/cloudflare/api.test.ts rename to packages/plugin/tests/core/cloudflare/api.test.ts index 3be6e044..74f8214e 100644 --- a/packages/plugin/tests/cloudflare/api.test.ts +++ b/packages/plugin/tests/core/cloudflare/api.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { cloudflareApi, hasCode } from "@/cloudflare"; +import { cloudflareApi, hasCode } from "@/core/cloudflare/api"; function apiReplying(status: number, text: string) { return cloudflareApi(async () => ({ status, text }), "tok"); diff --git a/packages/plugin/tests/core/cloudflare/token.test.ts b/packages/plugin/tests/core/cloudflare/token.test.ts new file mode 100644 index 00000000..d9164e97 --- /dev/null +++ b/packages/plugin/tests/core/cloudflare/token.test.ts @@ -0,0 +1,78 @@ +import { failure, fakeCloudflare } from "@tests/helpers/fake-cloudflare"; +import { describe, expect, it } from "vitest"; +import { CloudflareError, isRefusedToken } from "@/core/cloudflare/api"; +import { tokenTemplateUrl, verifyToken } from "@/core/cloudflare/token"; + +describe("isRefusedToken", () => { + it.each([401, 403])("is true for a Cloudflare %i", (status) => { + expect(isRefusedToken(new CloudflareError(status, [], "no"))).toBe(true); + }); + + it.each([new CloudflareError(409, [], "conflict"), new Error("401")])( + "is false for %s", + (err) => { + expect(isRefusedToken(err)).toBe(false); + }, + ); +}); + +describe("verifyToken", () => { + const ACCOUNT_VERIFY = "/accounts/acc/tokens/verify"; + const USER_VERIFY = "/user/tokens/verify"; + + it("verifies an account token under its account", async () => { + const cf = fakeCloudflare([ + { + method: "GET", + path: ACCOUNT_VERIFY, + reply: () => ({ result: { id: "acct-token", status: "active" } }), + }, + ]); + expect(await verifyToken(cf.api, "acc")).toBe("acct-token"); + }); + + it("falls back to the user endpoint for a user token", async () => { + const cf = fakeCloudflare([ + { method: "GET", path: ACCOUNT_VERIFY, reply: () => failure(1000, 401) }, + { + method: "GET", + path: USER_VERIFY, + reply: () => ({ result: { id: "user-token", status: "active" } }), + }, + ]); + expect(await verifyToken(cf.api, "acc")).toBe("user-token"); + }); + + it("refuses a token that is not active", async () => { + const cf = fakeCloudflare([ + { + method: "GET", + path: ACCOUNT_VERIFY, + reply: () => ({ result: { id: "t", status: "expired" } }), + }, + ]); + const err: unknown = await verifyToken(cf.api, "acc").catch( + (e: unknown) => e, + ); + expect(err).toBeInstanceOf(Error); + expect((err as Error).message).toMatch(/expired/); + expect(isRefusedToken(err)).toBe(true); + }); +}); + +describe("tokenTemplateUrl", () => { + it("pre-fills an account token with the permissions the relay deploy and R2 setup need", () => { + const url = new URL(tokenTemplateUrl()); + expect(url.origin + url.pathname).toBe("https://dash.cloudflare.com/"); + expect(url.searchParams.get("to")).toBe("/:account/api-tokens"); + expect(url.searchParams.get("name")).toBe("MDSync"); + expect( + JSON.parse(url.searchParams.get("permissionGroupKeys") ?? ""), + ).toEqual([ + { key: "workers_scripts", type: "edit" }, + { key: "workers_kv_storage", type: "edit" }, + { key: "workers_r2", type: "edit" }, + { key: "account_settings", type: "read" }, + ]); + }); +}); diff --git a/packages/plugin/tests/live/chaos.test.ts b/packages/plugin/tests/core/crypto/chaos.test.ts similarity index 93% rename from packages/plugin/tests/live/chaos.test.ts rename to packages/plugin/tests/core/crypto/chaos.test.ts index 7fdc0f54..36328af8 100644 --- a/packages/plugin/tests/live/chaos.test.ts +++ b/packages/plugin/tests/core/crypto/chaos.test.ts @@ -2,10 +2,10 @@ import { LiveHub, type TestConnection } from "@tests/helpers/live-hub"; import { seeded } from "@tests/helpers/seeded"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { deriveLiveKeys } from "@/crypto/live-keys"; -import { docIdFor } from "@/live/doc-id"; -import { LiveSession } from "@/live/session/session"; -import { TEXT, type TextModel } from "@/live/text/model"; +import { deriveLiveKeys } from "@/core/crypto/live-keys"; +import { docIdFor } from "@/features/live/doc-id"; +import { LiveSession } from "@/features/live/session/session"; +import { TEXT, type TextModel } from "@/features/live/text/model"; const FLUSHED_MS = 300; const DEVICES = 3; diff --git a/packages/plugin/tests/core/crypto/chunk-ids.test.ts b/packages/plugin/tests/core/crypto/chunk-ids.test.ts new file mode 100644 index 00000000..3c8c846a --- /dev/null +++ b/packages/plugin/tests/core/crypto/chunk-ids.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vitest"; +import { chunkId, deriveChunkIds } from "@/core/crypto"; + +describe("chunk ids", () => { + const bytes = new TextEncoder().encode("a chunk"); + + it("names equal bytes alike under one data key, on any device", async () => { + const here = await deriveChunkIds(new Uint8Array(32).fill(1)); + const there = await deriveChunkIds(new Uint8Array(32).fill(1)); + const id = await chunkId(here, bytes); + expect(id).toMatch(/^[0-9a-f]{64}$/); + expect(await chunkId(there, bytes)).toBe(id); + }); + + it("names them apart under another data key, and never by their plain hash", async () => { + const one = await chunkId( + await deriveChunkIds(new Uint8Array(32).fill(1)), + bytes, + ); + const two = await chunkId( + await deriveChunkIds(new Uint8Array(32).fill(2)), + bytes, + ); + const plain = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); + expect(one).not.toBe(two); + expect(one).not.toBe(Buffer.from(plain).toString("hex")); + }); +}); diff --git a/packages/plugin/tests/core/crypto/described-envelope.test.ts b/packages/plugin/tests/core/crypto/described-envelope.test.ts new file mode 100644 index 00000000..39e97e48 --- /dev/null +++ b/packages/plugin/tests/core/crypto/described-envelope.test.ts @@ -0,0 +1,175 @@ +import { afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { + decryptBytes, + decryptDescribed, + decryptJson, + deriveKey, + type EncryptionKey, + encryptBytes, + encryptCompressible, + encryptDescribed, + isDescribed, +} from "@/core/crypto"; +import { + BLOB_VERSION, + BLOB_VERSION_DESCRIBED, + BLOB_VERSION_GZIP, + GZIP_PAD_BYTES, +} from "@/core/crypto/constants"; + +let key: EncryptionKey; +beforeAll(async () => { + key = await deriveKey("pw", new Uint8Array(16)); +}); +afterEach(() => vi.unstubAllGlobals()); + +const encoder = new TextEncoder(); + +describe("described envelope", () => { + it("round-trips a header and a payload", async () => { + const header = { codec: { name: "x", width: 3 }, list: [1, "é", null] }; + const payload = encoder.encode("payload ".repeat(500)); + const blob = await encryptDescribed(key, header, payload); + + expect(blob[0]).toBe(BLOB_VERSION_DESCRIBED); + expect(isDescribed(blob)).toBe(true); + const opened = await decryptDescribed(key, blob); + expect(opened.header).toEqual(header); + expect(opened.payload).toEqual(payload); + }); + + it("round-trips an empty payload and an empty header", async () => { + const opened = await decryptDescribed( + key, + await encryptDescribed(key, {}, new Uint8Array()), + ); + expect(opened.header).toEqual({}); + expect(opened.payload).toEqual(new Uint8Array()); + }); + + it("pads the sealed length to the gzip unit, whatever the payload", async () => { + const sizes = new Set(); + for (const text of ["a", "bb", "ccc dd"]) { + const blob = await encryptDescribed(key, {}, encoder.encode(text)); + sizes.add(blob.length); + } + expect(sizes.size).toBe(1); + const [size] = [...sizes]; + // version byte + iv + padded plaintext + GCM tag + expect((size ?? 0) - 1 - 12 - 16).toBe(GZIP_PAD_BYTES); + }); + + it("is told apart by its first byte only", async () => { + expect(isDescribed(await encryptBytes(key, encoder.encode("a")))).toBe( + false, + ); + expect( + isDescribed( + await encryptCompressible(key, encoder.encode("a".repeat(9000))), + ), + ).toBe(false); + expect(isDescribed(new Uint8Array())).toBe(false); + }); + + it("is refused by decryptBytes and decryptJson: they also open JSON, keys and links", async () => { + const blob = await encryptDescribed(key, {}, encoder.encode("{}")); + await expect(decryptBytes(key, blob)).rejects.toThrow( + `Unsupported blob version: ${BLOB_VERSION_DESCRIBED}`, + ); + await expect(decryptJson(key, blob)).rejects.toThrow(/Unsupported blob/); + }); + + it("is the only version decryptDescribed opens", async () => { + for (const blob of [ + await encryptBytes(key, encoder.encode("plain")), + await encryptCompressible(key, encoder.encode("z".repeat(9000))), + ]) { + await expect(decryptDescribed(key, blob)).rejects.toThrow( + /Unsupported blob version/, + ); + } + }); + + it("fails when the version byte is flipped to another version", async () => { + const blob = await encryptDescribed( + key, + {}, + encoder.encode("x".repeat(100)), + ); + for (const version of [BLOB_VERSION, BLOB_VERSION_GZIP]) { + const relabelled = blob.slice(); + relabelled[0] = version; + await expect(decryptBytes(key, relabelled)).rejects.toThrow(); + } + const gzip = await encryptCompressible( + key, + encoder.encode("y".repeat(9000)), + ); + expect(gzip[0]).toBe(BLOB_VERSION_GZIP); + const relabelled = gzip.slice(); + relabelled[0] = BLOB_VERSION_DESCRIBED; + await expect(decryptDescribed(key, relabelled)).rejects.toThrow(); + }); + + it("fails on a wrong key and on a flipped ciphertext byte", async () => { + const blob = await encryptDescribed(key, { a: 1 }, encoder.encode("p")); + const other = await deriveKey("other", new Uint8Array(16)); + await expect(decryptDescribed(other, blob)).rejects.toThrow(); + const flipped = blob.slice(); + flipped[flipped.length - 20] = (flipped[flipped.length - 20] ?? 0) ^ 1; + await expect(decryptDescribed(key, flipped)).rejects.toThrow(); + }); + + it("throws where compression is unavailable, so the caller stores plain", async () => { + vi.stubGlobal("CompressionStream", undefined); + await expect( + encryptDescribed(key, {}, encoder.encode("p")), + ).rejects.toThrow(/cannot compress/); + }); + + it("refuses a header length that runs past the plaintext", async () => { + const sealed = await encryptDescribed(key, { a: 1 }, encoder.encode("p")); + // Rebuild a blob whose declared header length is larger than what follows. + const plain = new Uint8Array(8); + new DataView(plain.buffer).setUint32(0, 1000, true); + const forged = await sealDescribed(key, plain); + expect(sealed.length).toBe(forged.length); + await expect(decryptDescribed(key, forged)).rejects.toThrow(/truncated/); + }); +}); + +/** A described blob over arbitrary plaintext, built as `encryptDescribed` does. */ +async function sealDescribed( + aesKey: EncryptionKey, + plaintext: Uint8Array, +): Promise { + const gzipped = new Uint8Array( + await new Response( + new Blob([plaintext as BlobPart]) + .stream() + .pipeThrough(new CompressionStream("gzip")), + ).arrayBuffer(), + ); + const framed = new Uint8Array( + Math.ceil((4 + gzipped.length) / GZIP_PAD_BYTES) * GZIP_PAD_BYTES, + ); + new DataView(framed.buffer).setUint32(0, gzipped.length, true); + framed.set(gzipped, 4); + const iv = new Uint8Array(12); + const ciphertext = new Uint8Array( + await crypto.subtle.encrypt( + { + name: "AES-GCM", + iv, + additionalData: new Uint8Array([BLOB_VERSION_DESCRIBED]), + }, + aesKey, + framed, + ), + ); + const blob = new Uint8Array(1 + iv.length + ciphertext.length); + blob[0] = BLOB_VERSION_DESCRIBED; + blob.set(iv, 1); + blob.set(ciphertext, 1 + iv.length); + return blob; +} diff --git a/packages/plugin/tests/crypto/device-key.test.ts b/packages/plugin/tests/core/crypto/device-key.test.ts similarity index 95% rename from packages/plugin/tests/crypto/device-key.test.ts rename to packages/plugin/tests/core/crypto/device-key.test.ts index 77ae95d3..e6a87679 100644 --- a/packages/plugin/tests/crypto/device-key.test.ts +++ b/packages/plugin/tests/core/crypto/device-key.test.ts @@ -2,9 +2,9 @@ import { deviceKey, FakeSecretStorage } from "@tests/helpers/device-key"; import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; import { describe, expect, it, vi } from "vitest"; -import { decryptJson, encryptJson, importAesKey } from "@/crypto"; +import { decryptJson, encryptJson, importAesKey } from "@/core/crypto/cipher"; -vi.mock("@/shared/diagnostics", async (importOriginal) => ({ +vi.mock("@/core/shared/diagnostics", async (importOriginal) => ({ ...(await importOriginal>()), reportWarning: vi.fn(), })); diff --git a/packages/plugin/tests/sync/failed-batch.test.ts b/packages/plugin/tests/core/crypto/failed-batch.test.ts similarity index 94% rename from packages/plugin/tests/sync/failed-batch.test.ts rename to packages/plugin/tests/core/crypto/failed-batch.test.ts index a2cf066b..c422ece6 100644 --- a/packages/plugin/tests/sync/failed-batch.test.ts +++ b/packages/plugin/tests/core/crypto/failed-batch.test.ts @@ -6,11 +6,11 @@ import { useEncryptionKey, } from "@tests/helpers/session"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { sha256Hex } from "@/crypto"; -import { textToBytes } from "@/sync/content"; -import { SyncController } from "@/sync/controller"; -import { objectKey } from "@/sync/manifest"; -import { pullPaths } from "@/sync/pull"; +import { sha256Hex } from "@/core/crypto/cipher"; +import { pullPaths } from "@/features/sync/apply/pull"; +import { textToBytes } from "@/features/sync/changes/content"; +import { objectKey } from "@/features/sync/content/keys"; +import { SyncController } from "@/features/sync/controller"; useEncryptionKey(); afterEach(() => vi.restoreAllMocks()); diff --git a/packages/plugin/tests/crypto/json-envelope.test.ts b/packages/plugin/tests/core/crypto/json-envelope.test.ts similarity index 63% rename from packages/plugin/tests/crypto/json-envelope.test.ts rename to packages/plugin/tests/core/crypto/json-envelope.test.ts index 7646fb03..6ee68512 100644 --- a/packages/plugin/tests/crypto/json-envelope.test.ts +++ b/packages/plugin/tests/core/crypto/json-envelope.test.ts @@ -1,19 +1,22 @@ -import { beforeAll, describe, expect, it } from "vitest"; +import { seeded } from "@tests/helpers/seeded"; +import { afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { decryptBytes, decryptJson, deriveKey, type EncryptionKey, encryptBytes, + encryptCompressible, encryptJson, -} from "@/crypto"; +} from "@/core/crypto/cipher"; import { BLOB_VERSION, BLOB_VERSION_GZIP, GZIP_PAD_BYTES, + GZIP_SAMPLE_BYTES, IV_BYTES, JSON_GZIP_MIN_BYTES, -} from "@/crypto/constants"; +} from "@/core/crypto/constants"; let key: EncryptionKey; beforeAll(async () => { @@ -133,9 +136,8 @@ describe("encrypted JSON envelope", () => { expect(second.length).toBe(first.length); }); - it("keeps opaque bytes uncompressed, however large", async () => { - // File contents stream through this path and are as often already - // compressed media; a second pass would only cost time. + it("keeps raw sealing uncompressed, however large", async () => { + // The key file and links seal through it; file content opts in with encryptCompressible. const bytes = new Uint8Array(JSON_GZIP_MIN_BYTES * 4); const blob = await encryptBytes(key, bytes); @@ -143,3 +145,64 @@ describe("encrypted JSON envelope", () => { expect(await decryptBytes(key, blob)).toEqual(bytes); }); }); + +/** Incompressible, like media or an archive. */ +function noise(length: number, seed = 1): Uint8Array { + const next = seeded(seed); + return Uint8Array.from({ length }, () => Math.floor(next() * 256)); +} + +function note(length: number): Uint8Array { + const line = "- [ ] A task line in a long note, with a [[link]] and #tag\n"; + return new TextEncoder() + .encode(line.repeat(Math.ceil(length / line.length))) + .subarray(0, length); +} + +describe("compressible file content", () => { + afterEach(() => vi.unstubAllGlobals()); + + it("stores text compressed and reads it back", async () => { + const bytes = note(200 * 1024); + const blob = await encryptCompressible(key, bytes); + + expect(blob[0]).toBe(BLOB_VERSION_GZIP); + expect(blob.length).toBeLessThan(bytes.length / 4); + expect(await decryptBytes(key, blob)).toEqual(bytes); + }); + + it("leaves a note smaller than one pad unit as it is", async () => { + const bytes = note(GZIP_PAD_BYTES - 1); + const blob = await encryptCompressible(key, bytes); + + expect(blob[0]).toBe(BLOB_VERSION); + expect(await decryptBytes(key, blob)).toEqual(bytes); + }); + + it("leaves incompressible content as it is", async () => { + const bytes = noise(32 * 1024); + const blob = await encryptCompressible(key, bytes); + + expect(blob[0]).toBe(BLOB_VERSION); + expect(await decryptBytes(key, blob)).toEqual(bytes); + }); + + it("judges a large file by its start", async () => { + // Compressible past the sample, but media and archives look like noise from the first byte. + const bytes = new Uint8Array(GZIP_SAMPLE_BYTES * 4); + bytes.set(noise(GZIP_SAMPLE_BYTES)); + const blob = await encryptCompressible(key, bytes); + + expect(blob[0]).toBe(BLOB_VERSION); + expect(await decryptBytes(key, blob)).toEqual(bytes); + }); + + it("writes a blob every build reads where the platform cannot compress", async () => { + vi.stubGlobal("CompressionStream", undefined); + const bytes = note(200 * 1024); + const blob = await encryptCompressible(key, bytes); + + expect(blob[0]).toBe(BLOB_VERSION); + expect(await decryptBytes(key, blob)).toEqual(bytes); + }); +}); diff --git a/packages/plugin/tests/crypto/passphrase-cache.test.ts b/packages/plugin/tests/core/crypto/passphrase-cache.test.ts similarity index 98% rename from packages/plugin/tests/crypto/passphrase-cache.test.ts rename to packages/plugin/tests/core/crypto/passphrase-cache.test.ts index 36852f64..08322b85 100644 --- a/packages/plugin/tests/crypto/passphrase-cache.test.ts +++ b/packages/plugin/tests/core/crypto/passphrase-cache.test.ts @@ -5,7 +5,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { loadCachedPassphrase, saveCachedPassphrase, -} from "@/crypto/passphrase-cache"; +} from "@/core/crypto/passphrase-cache"; const cachePath = ".obsidian/plugins/mdsync/passphrase.enc"; const binding = "s3|example|region|bucket|prefix"; diff --git a/packages/plugin/tests/crypto/seal.test.ts b/packages/plugin/tests/core/crypto/seal.test.ts similarity index 90% rename from packages/plugin/tests/crypto/seal.test.ts rename to packages/plugin/tests/core/crypto/seal.test.ts index 646a994f..dc8f82a4 100644 --- a/packages/plugin/tests/crypto/seal.test.ts +++ b/packages/plugin/tests/core/crypto/seal.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; -import { deriveLiveKeys } from "@/crypto/live-keys"; -import { seal, unseal } from "@/crypto/seal"; +import { deriveLiveKeys } from "@/core/crypto/live-keys"; +import { seal, unseal } from "@/core/crypto/seal"; function dataKey(): Uint8Array { return crypto.getRandomValues(new Uint8Array(32)); diff --git a/packages/plugin/tests/live/session-reconnect.test.ts b/packages/plugin/tests/core/crypto/session-reconnect.test.ts similarity index 99% rename from packages/plugin/tests/live/session-reconnect.test.ts rename to packages/plugin/tests/core/crypto/session-reconnect.test.ts index 621f0483..58c3ad30 100644 --- a/packages/plugin/tests/live/session-reconnect.test.ts +++ b/packages/plugin/tests/core/crypto/session-reconnect.test.ts @@ -13,7 +13,7 @@ import { import { afterEach, describe, expect, it, vi } from "vitest"; import * as Y from "yjs"; -import * as sealing from "@/crypto/seal"; +import * as sealing from "@/core/crypto/seal"; const live = useLiveRoom(); const { synced } = live; diff --git a/packages/plugin/tests/live/session-rooms.test.ts b/packages/plugin/tests/core/crypto/session-rooms.test.ts similarity index 97% rename from packages/plugin/tests/live/session-rooms.test.ts rename to packages/plugin/tests/core/crypto/session-rooms.test.ts index fa04aebe..d36518b1 100644 --- a/packages/plugin/tests/live/session-rooms.test.ts +++ b/packages/plugin/tests/core/crypto/session-rooms.test.ts @@ -13,9 +13,9 @@ import { } from "@tests/helpers/live-session"; import { describe, expect, it, vi } from "vitest"; import * as Y from "yjs"; -import { seal } from "@/crypto/seal"; -import { docIdFor } from "@/live/doc-id"; -import { COMPACT_AFTER } from "@/live/session/room-log"; +import { seal } from "@/core/crypto/seal"; +import { docIdFor } from "@/features/live/doc-id"; +import { COMPACT_AFTER } from "@/features/live/session/room-log"; const live = useLiveRoom(); const { device, synced, typedElsewhere, roomState } = live; diff --git a/packages/plugin/tests/core/drawing/codec.test.ts b/packages/plugin/tests/core/drawing/codec.test.ts new file mode 100644 index 00000000..0eadc219 --- /dev/null +++ b/packages/plugin/tests/core/drawing/codec.test.ts @@ -0,0 +1,180 @@ +import { + bytesOf, + compressedDrawing, + drawingAround, + exactMultipleScene, + plainDrawing, + sceneJson, + wrapLikeExcalidraw, +} from "@tests/helpers/drawing-file"; +import { compressToBase64 } from "lz-string"; +import { describe, expect, it } from "vitest"; +import { + type DrawingCodec, + decodeDrawing, + encodeDrawing, + isDrawingCodec, +} from "@/core/drawing/codec"; + +const decoder = new TextDecoder(); + +function roundTrip(text: string) { + const bytes = bytesOf(text); + const encoded = encodeDrawing(bytes); + expect(encoded).not.toBeNull(); + const { stored, codec } = encoded as NonNullable; + expect(decodeDrawing(stored, codec)).toEqual(bytes); + return { stored: decoder.decode(stored), codec }; +} + +describe("excalidraw codec", () => { + it("stores a scene past its budget as it is, so no read rebuilds megabytes", () => { + const json = JSON.stringify({ + type: "excalidraw", + elements: [{ id: "a", text: "x".repeat(2 * 1024 * 1024) }], + }); + expect(encodeDrawing(bytesOf(compressedDrawing(json)))).toBeNull(); + // Compressing megabytes can pass the default timeout in a loaded suite. + }, 30_000); + + it("stores the scene as plain JSON and rebuilds the file byte for byte", () => { + const json = sceneJson(60); + const { stored, codec } = roundTrip(compressedDrawing(json)); + + expect(codec).toEqual({ name: "excalidraw-lz", width: 256, gap: "\n\n" }); + expect(stored).toContain(`\`\`\`json\n${json}\n\`\`\``); + expect(stored).not.toContain("compressed-json"); + expect(stored).toContain("excalidraw-plugin: parsed"); + }); + + it("round-trips when the base64 length is an exact multiple of the width", () => { + const json = exactMultipleScene(); + const base64 = compressToBase64(json); + expect(base64.length % 256).toBe(0); + // The plugin's regex also puts the gap after a last full line. + expect(wrapLikeExcalidraw(base64).endsWith("\n\n")).toBe(true); + + const { codec } = roundTrip(compressedDrawing(json)); + expect(codec).toMatchObject({ width: 256, gap: "\n\n" }); + }); + + it("reads another writer's width and gap from the file", () => { + const json = sceneJson(30); + const wrapped = compressToBase64(json).replace(/(.{64})/g, "$1\n"); + const { codec } = roundTrip( + drawingAround(`\`\`\`compressed-json\n${wrapped}\n\`\`\``), + ); + expect(codec).toMatchObject({ width: 64, gap: "\n" }); + }); + + it("handles one unwrapped line", () => { + const json = sceneJson(2); + roundTrip( + drawingAround(`\`\`\`compressed-json\n${compressToBase64(json)}\n\`\`\``), + ); + }); + + it("keeps text after the block, with other blocks before and after it", () => { + const text = `${compressedDrawing()}\n## Later\n\`\`\`json\n{"a":1}\n\`\`\`\n`; + const { stored } = roundTrip(text); + expect(stored.endsWith('{"a":1}\n```\n')).toBe(true); + }); + + it("gives null for a scene that is plain JSON already", () => { + expect(encodeDrawing(bytesOf(plainDrawing()))).toBeNull(); + }); + + it("gives null for anything that is not a drawing", () => { + expect(encodeDrawing(bytesOf("# a note\n"))).toBeNull(); + expect(encodeDrawing(new Uint8Array())).toBeNull(); + expect(encodeDrawing(new Uint8Array([0, 255, 254, 1, 2]))).toBeNull(); + const block = `## Drawing\n\`\`\`compressed-json\n${compressToBase64("{}")}\n\`\`\``; + expect(encodeDrawing(bytesOf(block))).toBeNull(); + const moved = `# A note\n\n---\nexcalidraw-plugin: parsed\n---\n${block}`; + expect(encodeDrawing(bytesOf(moved))).toBeNull(); + }); + + it("gives null when the block does not decompress", () => { + const text = drawingAround("```compressed-json\n!!not base64!!\n```"); + expect(encodeDrawing(bytesOf(text))).toBeNull(); + }); + + it("gives null for a tampered block that does not reproduce", () => { + const json = sceneJson(30); + const wrapped = wrapLikeExcalidraw(compressToBase64(json)); + // Uneven gaps decompress fine, but no single width and gap rebuild them. + const uneven = wrapped.replace("\n\n", "\n\n\n"); + expect( + encodeDrawing( + bytesOf(drawingAround(`\`\`\`compressed-json\n${uneven}\n\`\`\``)), + ), + ).toBeNull(); + + // A last line followed by trailing spaces is not what the codec writes back. + const spaced = `${wrapped} `; + expect( + encodeDrawing( + bytesOf(drawingAround(`\`\`\`compressed-json\n${spaced}\n\`\`\``)), + ), + ).toBeNull(); + }); + + it("gives null for a stream that is not the canonical LZString of its own JSON", () => { + const valid = compressToBase64(sceneJson(10)); + const swapped = `${valid.slice(0, -1)}${valid.endsWith("A") ? "B" : "A"}`; + const text = drawingAround( + `\`\`\`compressed-json\n${wrapLikeExcalidraw(swapped)}\n\`\`\``, + ); + expect(encodeDrawing(bytesOf(text))).toBeNull(); + }); + + it("round-trips CRLF line endings, keeping them in the gap", () => { + const text = compressedDrawing().replace(/\n/g, "\r\n"); + const { codec, stored } = roundTrip(text); + expect(codec).toMatchObject({ width: 256, gap: "\r\n\r\n" }); + expect(stored).toContain("```json\r\n"); + }); + + it("round-trips non-ASCII text around the scene", () => { + const text = compressedDrawing().replace("label 0", "étiquette 🎨 日本語"); + roundTrip(text); + }); + + it("never reproduces a different file: only equal bytes are encoded", () => { + for (const mutate of [ + (text: string) => text.replace("\n\n%%", "\n%%"), + (text: string) => `${text}\u0000`, + (text: string) => + text.replace("```compressed-json\n", "```compressed-json\n\n"), + ]) { + const bytes = bytesOf(mutate(compressedDrawing())); + const encoded = encodeDrawing(bytes); + if (encoded) { + expect(decodeDrawing(encoded.stored, encoded.codec)).toEqual(bytes); + } + } + }); + + it("refuses an unknown or malformed codec on decode", () => { + const { stored } = roundTrip(compressedDrawing()); + const bytes = bytesOf(stored); + const bad = [ + { name: "other", width: 256, gap: "\n\n" }, + { name: "excalidraw-lz", width: 0, gap: "\n\n" }, + { name: "excalidraw-lz", width: 2.5, gap: "\n\n" }, + { name: "excalidraw-lz", width: 256, gap: "x" }, + { name: "excalidraw-lz", width: 256, gap: "\n\n", extra: 1 }, + ]; + for (const codec of bad) { + expect(isDrawingCodec(codec)).toBe(false); + expect(() => decodeDrawing(bytes, codec as DrawingCodec)).toThrow(); + } + expect(() => + decodeDrawing(bytesOf("# no scene"), { + name: "excalidraw-lz", + width: 256, + gap: "\n\n", + }), + ).toThrow(/no scene/); + }); +}); diff --git a/packages/plugin/tests/drawing/drawing.test.ts b/packages/plugin/tests/core/drawing/drawing.test.ts similarity index 95% rename from packages/plugin/tests/drawing/drawing.test.ts rename to packages/plugin/tests/core/drawing/drawing.test.ts index 651f4816..646f11ce 100644 --- a/packages/plugin/tests/drawing/drawing.test.ts +++ b/packages/plugin/tests/core/drawing/drawing.test.ts @@ -1,13 +1,8 @@ import { compressToBase64 } from "lz-string"; import { describe, expect, it } from "vitest"; - -import { - mergeDrawings, - mergeElements, - readDrawing, - type SceneElement, - sceneOf, -} from "@/drawing"; +import { readDrawing, type SceneElement } from "@/core/drawing/format"; +import { mergeDrawings, mergeElements } from "@/core/drawing/merge"; +import { sceneOf } from "@/core/drawing/scene"; function element( id: string, diff --git a/packages/plugin/tests/hub/link.test.ts b/packages/plugin/tests/core/hub/link.test.ts similarity index 99% rename from packages/plugin/tests/hub/link.test.ts rename to packages/plugin/tests/core/hub/link.test.ts index 7455bb48..b25e8c03 100644 --- a/packages/plugin/tests/hub/link.test.ts +++ b/packages/plugin/tests/core/hub/link.test.ts @@ -8,7 +8,7 @@ import { } from "@mdsync/protocol"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { HubLink, type HubLinkOptions } from "@/hub/link"; +import { HubLink, type HubLinkOptions } from "@/core/hub/link"; class FakeSocket extends EventTarget { static readonly CONNECTING = 0; diff --git a/packages/plugin/tests/ui/relay.test.ts b/packages/plugin/tests/core/hub/relay.test.ts similarity index 95% rename from packages/plugin/tests/ui/relay.test.ts rename to packages/plugin/tests/core/hub/relay.test.ts index 8974b6ab..8096b235 100644 --- a/packages/plugin/tests/ui/relay.test.ts +++ b/packages/plugin/tests/core/hub/relay.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { relayFixOf, relaySummary } from "@/ui/common/relay"; +import { relayFixOf, relaySummary } from "@/core/hub/relay-text"; describe("relay summary", () => { it("says the relay is connected while every space is, and what cannot be read", () => { diff --git a/packages/plugin/tests/hub/status.test.ts b/packages/plugin/tests/core/hub/status.test.ts similarity index 98% rename from packages/plugin/tests/hub/status.test.ts rename to packages/plugin/tests/core/hub/status.test.ts index 53709534..0f426c23 100644 --- a/packages/plugin/tests/hub/status.test.ts +++ b/packages/plugin/tests/core/hub/status.test.ts @@ -5,7 +5,7 @@ import { type LinkState, type RelayFacts, relayStatus, -} from "@/hub/status"; +} from "@/core/hub/status"; const facts = (over: Partial = {}): RelayFacts => ({ realtime: true, diff --git a/packages/plugin/tests/core/log-service.test.ts b/packages/plugin/tests/core/logs/log-service.test.ts similarity index 94% rename from packages/plugin/tests/core/log-service.test.ts rename to packages/plugin/tests/core/logs/log-service.test.ts index d1fe3ac5..32512d48 100644 --- a/packages/plugin/tests/core/log-service.test.ts +++ b/packages/plugin/tests/core/logs/log-service.test.ts @@ -1,8 +1,8 @@ import type { DataAdapter } from "obsidian"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { LogService } from "@/core/log-service"; -import { ESyncLogOperation } from "@/logs/store"; +import { LogService } from "@/core/logs/log-service"; +import { ESyncLogOperation } from "@/core/logs/store"; function service() { const write = vi.fn(async () => undefined); diff --git a/packages/plugin/tests/core/settings/fields.test.ts b/packages/plugin/tests/core/settings/fields.test.ts new file mode 100644 index 00000000..6aa15ce5 --- /dev/null +++ b/packages/plugin/tests/core/settings/fields.test.ts @@ -0,0 +1,179 @@ +import { Setting, type SettingDefinitionRender } from "obsidian"; +import { describe, expect, it, vi } from "vitest"; +import { EFieldKind } from "@/core/settings"; +import { + bind, + type FieldContext, + fieldRow, + group, + introRow, + renderDefinitions, + type SettingsRow, + type SliderField, + type ToggleField, +} from "@/core/settings/fields"; +import { notifyError } from "@/core/ui/notices"; + +vi.mock("@/core/ui/notices", () => ({ notifyError: vi.fn() })); + +vi.mock("obsidian", async (importOriginal) => ({ + ...(await importOriginal()), + debounce: (fn: unknown) => fn, + Setting: class { + name = ""; + desc = ""; + heading = false; + constructor() { + rows.push(this); + } + addToggle(build: (toggle: unknown) => void) { + build({ + setValue() { + return this; + }, + onChange(handler: (value: boolean) => void) { + toggled = handler; + return this; + }, + }); + return this; + } + setName(name: string) { + this.name = name; + return this; + } + setDesc(desc: string) { + this.desc = desc; + return this; + } + setHeading() { + this.heading = true; + return this; + } + }, +})); + +const rows: { name: string; desc: string; heading: boolean }[] = []; +let toggled: (value: boolean) => void = () => undefined; + +describe("setting definitions", () => { + it("evaluates field visibility against current settings", () => { + const settings = { realtimeSync: false }; + const ctx = { + plugin: { settings }, + rerender: vi.fn(), + } as unknown as FieldContext; + const row: SettingDefinitionRender = fieldRow(ctx, { + kind: EFieldKind.Toggle, + name: "Live editing", + when: (s) => s.realtimeSync, + get: (s) => s.liveEditing, + set: (value) => ({ liveEditing: value }), + }); + if (typeof row.visible !== "function") + throw new Error("Missing visibility predicate"); + expect(row.visible()).toBe(false); + settings.realtimeSync = true; + expect(row.visible()).toBe(true); + }); + + it("renders group headings, names and descriptions, skipping invisible rows", () => { + rows.length = 0; + const render = vi.fn(); + const hidden = vi.fn(); + const items: SettingsRow[] = [ + { name: "Shown", desc: "Description", render }, + { name: "Hidden", visible: false, render: hidden }, + { name: "Conditional", visible: () => false, render: hidden }, + introRow("Introduction"), + ]; + renderDefinitions({} as HTMLElement, [group("Heading", items)]); + expect(rows).toEqual([ + { name: "Heading", desc: "", heading: true }, + { name: "Shown", desc: "Description", heading: false }, + { name: "", desc: "Introduction", heading: false }, + ]); + expect(render).toHaveBeenCalledWith(rows[1] as unknown as Setting); + expect(hidden).not.toHaveBeenCalled(); + }); +}); + +describe("a field's save", () => { + function toggleRow(saveSettings: () => Promise) { + const settings = { liveEditing: false }; + const after = vi.fn(); + const ctx = { + plugin: { settings, saveSettings }, + rerender: vi.fn(), + } as unknown as FieldContext; + fieldRow(ctx, { + kind: EFieldKind.Toggle, + name: "Live editing", + ...bind("liveEditing"), + after, + rerender: true, + }).render(new Setting({} as HTMLElement)); + return { settings, after, ctx }; + } + + it("tells the user when settings cannot be saved, and skips what follows", async () => { + const failure = new Error("disk full"); + const { settings, after, ctx } = toggleRow(() => Promise.reject(failure)); + + toggled(true); + await vi.waitFor(() => expect(notifyError).toHaveBeenCalled()); + + expect(notifyError).toHaveBeenCalledWith( + "Could not save settings", + failure, + ); + expect(settings.liveEditing).toBe(true); + expect(after).not.toHaveBeenCalled(); + expect(ctx.rerender).not.toHaveBeenCalled(); + }); + + it("runs what follows once saved", async () => { + vi.mocked(notifyError).mockClear(); + const { after, ctx } = toggleRow(async () => undefined); + + toggled(true); + await vi.waitFor(() => expect(after).toHaveBeenCalled()); + + expect(ctx.rerender).toHaveBeenCalled(); + expect(notifyError).not.toHaveBeenCalled(); + }); +}); + +describe("bind", () => { + it("reads and patches one key", () => { + const field = bind("autoSyncEnabled"); + expect(field.get({ autoSyncEnabled: true } as never)).toBe(true); + expect(field.set(false)).toEqual({ autoSyncEnabled: false }); + }); + + it("only fits a field of the key's value type", () => { + const toggle = (field: ToggleField) => field; + const slider = (field: SliderField) => field; + const range = { min: 0, max: 1 }; + toggle({ kind: EFieldKind.Toggle, name: "ok", ...bind("autoSyncEnabled") }); + slider({ + kind: EFieldKind.Slider, + name: "ok", + ...range, + ...bind("autoPushSettleSeconds"), + }); + // @ts-expect-error a number setting is no toggle + toggle({ + kind: EFieldKind.Toggle, + name: "no", + ...bind("autoPushSettleSeconds"), + }); + // @ts-expect-error a boolean setting is no slider + slider({ + kind: EFieldKind.Slider, + name: "no", + ...range, + ...bind("autoSyncEnabled"), + }); + }); +}); diff --git a/packages/plugin/tests/core/settings/model.test.ts b/packages/plugin/tests/core/settings/model.test.ts new file mode 100644 index 00000000..29d729bc --- /dev/null +++ b/packages/plugin/tests/core/settings/model.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vitest"; +import { isRelayConfigured } from "@/core/settings/model"; + +describe("isRelayConfigured", () => { + const secret = "s3cret"; + + it.each([ + "https://relay.example", + "http://localhost:8787", + "http://127.0.0.1:8787/", + "http://[::1]:8787", + ])("accepts %s", (relayUrl) => { + expect(isRelayConfigured({ relayUrl, relaySecret: secret })).toBe(true); + }); + + it("needs both the URL and the secret", () => { + expect(isRelayConfigured({ relayUrl: "", relaySecret: secret })).toBe( + false, + ); + expect( + isRelayConfigured({ relayUrl: "https://relay.example", relaySecret: "" }), + ).toBe(false); + }); + + it("refuses a remote relay that would take the secret over plain http", () => { + expect( + isRelayConfigured({ + relayUrl: "http://relay.example", + relaySecret: secret, + }), + ).toBe(false); + }); +}); diff --git a/packages/plugin/tests/settings/number-field.test.ts b/packages/plugin/tests/core/settings/number-field.test.ts similarity index 59% rename from packages/plugin/tests/settings/number-field.test.ts rename to packages/plugin/tests/core/settings/number-field.test.ts index aa67fe9d..d59266f3 100644 --- a/packages/plugin/tests/settings/number-field.test.ts +++ b/packages/plugin/tests/core/settings/number-field.test.ts @@ -1,14 +1,14 @@ import { Setting } from "obsidian"; import { describe, expect, it, vi } from "vitest"; +import { EFieldKind } from "@/core/settings"; import { type FieldContext, fieldRow, type NumberField, -} from "@/settings/fields"; -import { EFieldKind } from "@/storage/field-spec"; +} from "@/core/settings/fields"; -vi.mock("obsidian", () => { +vi.mock("obsidian", async (importOriginal) => { class Setting { settingEl = { addClass: () => undefined }; setName() { @@ -19,6 +19,7 @@ vi.mock("obsidian", () => { } addText(build: (text: unknown) => void) { build({ + inputEl: input, setValue() { return this; }, @@ -30,10 +31,15 @@ vi.mock("obsidian", () => { return this; } } - return { Setting, debounce: (fn: unknown) => fn }; + return { + ...(await importOriginal()), + Setting, + debounce: (fn: unknown) => fn, + }; }); let typed: (raw: string) => void = () => undefined; +let input: Record = {}; const minutes: NumberField = { kind: EFieldKind.Number, @@ -43,13 +49,14 @@ const minutes: NumberField = { set: (value) => ({ autoSyncIntervalMinutes: value }), }; -function typeInto(raw: string) { +function typeInto(raw: string, field: NumberField = minutes) { const settings = { autoSyncIntervalMinutes: 15 }; const ctx = { plugin: { settings, saveSettings: async () => undefined }, rerender: () => undefined, } as unknown as FieldContext; - fieldRow(ctx, minutes).render(new Setting({} as HTMLElement)); + input = {}; + fieldRow(ctx, field).render(new Setting({} as HTMLElement)); typed(raw); return settings.autoSyncIntervalMinutes; } @@ -65,4 +72,19 @@ describe("a number field", () => { it("saves a whole number", () => { expect(typeInto("30")).toBe(30); }); + + it("leaves the input a plain text box without bounds", () => { + typeInto("30"); + expect(input).toEqual({}); + }); + + it("becomes a native number input with its bounds", () => { + typeInto("30", { ...minutes, min: 1, max: 60 }); + expect(input).toEqual({ type: "number", min: "1", max: "60" }); + }); + + it("sets only the bound it has", () => { + typeInto("30", { ...minutes, min: 0 }); + expect(input).toEqual({ type: "number", min: "0" }); + }); }); diff --git a/packages/plugin/tests/shared/colors.test.ts b/packages/plugin/tests/core/shared/colors.test.ts similarity index 84% rename from packages/plugin/tests/shared/colors.test.ts rename to packages/plugin/tests/core/shared/colors.test.ts index f632ec88..30d03941 100644 --- a/packages/plugin/tests/shared/colors.test.ts +++ b/packages/plugin/tests/core/shared/colors.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { personColor, personTint } from "@/shared/colors"; +import { personColor, personTint } from "@/core/shared/colors"; describe("person colours", () => { it("are hex, so y-codemirror's own tint of a cursor matches the tint of their text", () => { diff --git a/packages/plugin/tests/shared/errors.test.ts b/packages/plugin/tests/core/shared/errors.test.ts similarity index 87% rename from packages/plugin/tests/shared/errors.test.ts rename to packages/plugin/tests/core/shared/errors.test.ts index 2e11642b..df3ccf08 100644 --- a/packages/plugin/tests/shared/errors.test.ts +++ b/packages/plugin/tests/core/shared/errors.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { errorMessage } from "@/shared/errors"; +import { errorMessage } from "@/core/shared/errors"; describe("errorMessage", () => { it("prefers a real message over the string form", () => { diff --git a/packages/plugin/tests/shared/format.test.ts b/packages/plugin/tests/core/shared/format.test.ts similarity index 57% rename from packages/plugin/tests/shared/format.test.ts rename to packages/plugin/tests/core/shared/format.test.ts index 20eedcd1..766c8b33 100644 --- a/packages/plugin/tests/shared/format.test.ts +++ b/packages/plugin/tests/core/shared/format.test.ts @@ -1,10 +1,11 @@ -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it } from "vitest"; import { formatBytes, formatDayLabel, pluralize, + startOfWeek, withDevices, -} from "@/shared/format"; +} from "@/core/shared/format"; describe("withDevices", () => { it("names a person's devices after them, and nothing when none is known", () => { @@ -35,6 +36,7 @@ describe("pluralize", () => { expect(pluralize(1, "file")).toBe("1 file"); expect(pluralize(0, "file")).toBe("0 files"); expect(pluralize(2, "file")).toBe("2 files"); + expect(pluralize(2, "push", "pushes")).toBe("2 pushes"); }); }); @@ -48,19 +50,38 @@ describe("formatDayLabel", () => { expect(formatDayLabel(day(1, 23), noon)).toBe("Yesterday"); }); - it("names the weekday for the rest of the week", () => { - const midweek = day(3); - expect(formatDayLabel(midweek, noon)).toBe( - new Date(midweek).toLocaleDateString(undefined, { weekday: "long" }), - ); - }); - - it("falls back to the date once the week is out", () => { + it("dates the rest by weekday and date, with the year only when it differs", () => { + const short = { weekday: "short", day: "numeric", month: "short" } as const; const old = day(10); - expect(formatDayLabel(old, noon)).toBe(new Date(old).toLocaleDateString()); + expect(formatDayLabel(old, noon)).toBe( + new Date(old).toLocaleDateString(undefined, short), + ); + const lastYear = day(200); + expect(formatDayLabel(lastYear, noon)).toBe( + new Date(lastYear).toLocaleDateString(undefined, { + ...short, + year: "numeric", + }), + ); }); it("treats a clock skew into the future as today", () => { expect(formatDayLabel(day(-1), noon)).toBe("Today"); }); }); + +describe("startOfWeek", () => { + const zone = process.env.TZ; + afterEach(() => { + if (zone === undefined) delete process.env.TZ; + else process.env.TZ = zone; + }); + + it("lands on Monday's midnight, also from a Sunday whose midnight was skipped", () => { + process.env.TZ = "America/Santiago"; + const monday = new Date(2026, 7, 31).getTime(); + expect(startOfWeek(new Date(2026, 8, 6, 12).getTime())).toBe(monday); + expect(startOfWeek(new Date(2026, 7, 31, 23).getTime())).toBe(monday); + expect(new Date(monday).getHours()).toBe(0); + }); +}); diff --git a/packages/plugin/tests/shared/offline.test.ts b/packages/plugin/tests/core/shared/offline.test.ts similarity index 95% rename from packages/plugin/tests/shared/offline.test.ts rename to packages/plugin/tests/core/shared/offline.test.ts index 42009ace..98324dd4 100644 --- a/packages/plugin/tests/shared/offline.test.ts +++ b/packages/plugin/tests/core/shared/offline.test.ts @@ -5,8 +5,11 @@ import { isOffline, OFFLINE_MESSAGE, userMessage, -} from "@/shared/offline"; -import { StorageHttpError, StorageTimeoutError } from "@/storage/adapters/util"; +} from "@/core/shared/offline"; +import { + StorageHttpError, + StorageTimeoutError, +} from "@/core/shared/transport-errors"; function browserOnline(online: boolean): void { vi.stubGlobal("navigator", { onLine: online }); diff --git a/packages/plugin/tests/shared/path.test.ts b/packages/plugin/tests/core/shared/path.test.ts similarity index 98% rename from packages/plugin/tests/shared/path.test.ts rename to packages/plugin/tests/core/shared/path.test.ts index 2afcb7b3..e558b339 100644 --- a/packages/plugin/tests/shared/path.test.ts +++ b/packages/plugin/tests/core/shared/path.test.ts @@ -6,7 +6,7 @@ import { hasReservedChar, normalizeKeyPrefix, normalizePath, -} from "@/shared/path"; +} from "@/core/shared/path"; describe("path normalisation", () => { it("strips a leading separator whichever way it leans", () => { diff --git a/packages/plugin/tests/ui/attempt.test.ts b/packages/plugin/tests/core/ui/attempt.test.ts similarity index 93% rename from packages/plugin/tests/ui/attempt.test.ts rename to packages/plugin/tests/core/ui/attempt.test.ts index 81a024a2..e0d2ab5a 100644 --- a/packages/plugin/tests/ui/attempt.test.ts +++ b/packages/plugin/tests/core/ui/attempt.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { attempt } from "@/ui/common"; +import { attempt } from "@/core/ui/notices"; afterEach(() => vi.restoreAllMocks()); diff --git a/packages/plugin/tests/core/ui/observe-resize.test.ts b/packages/plugin/tests/core/ui/observe-resize.test.ts new file mode 100644 index 00000000..45e94115 --- /dev/null +++ b/packages/plugin/tests/core/ui/observe-resize.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it, vi } from "vitest"; +import { observeResize } from "@/core/ui/observe-resize"; + +/** A window whose observers record what they watch. */ +function fakeWindow() { + const watched: object[] = []; + const stopped: object[] = []; + class ResizeObserver { + observe(target: object): void { + watched.push(target); + } + disconnect(): void { + stopped.push(this); + } + } + return { win: { ResizeObserver }, watched, stopped }; +} + +function element(win: object) { + let migrated: ((win: Window) => void) | null = null; + const unmigrated = vi.fn(); + const el = { + win, + onWindowMigrated(listener: (win: Window) => void) { + migrated = listener; + return unmigrated; + }, + }; + const moveTo = (next: object) => { + el.win = next; + migrated?.(next as Window); + }; + return { el: el as unknown as HTMLElement, moveTo, unmigrated }; +} + +describe("observeResize", () => { + it("observes with the element's window, again with the next one after a move", () => { + const main = fakeWindow(); + const popout = fakeWindow(); + const { el, moveTo } = element(main.win); + observeResize(el, () => {}); + expect(main.watched).toEqual([el]); + moveTo(popout.win); + expect(main.stopped).toHaveLength(1); + expect(popout.watched).toEqual([el]); + }); + + it("stops the observer and the move listener", () => { + const main = fakeWindow(); + const { el, unmigrated } = element(main.win); + observeResize(el, () => {})(); + expect(main.stopped).toHaveLength(1); + expect(unmigrated).toHaveBeenCalledOnce(); + }); +}); diff --git a/packages/plugin/tests/utils/base64.test.ts b/packages/plugin/tests/core/utils/base64.test.ts similarity index 96% rename from packages/plugin/tests/utils/base64.test.ts rename to packages/plugin/tests/core/utils/base64.test.ts index 2c8a1501..d8c1299b 100644 --- a/packages/plugin/tests/utils/base64.test.ts +++ b/packages/plugin/tests/core/utils/base64.test.ts @@ -5,7 +5,7 @@ import { base64UrlToBytes, bytesToBase64, bytesToBase64Url, -} from "@/utils/base64"; +} from "@/core/utils/base64"; describe("base64", () => { it("round-trips arbitrary bytes", () => { diff --git a/packages/plugin/tests/utils/compress.test.ts b/packages/plugin/tests/core/utils/compress.test.ts similarity index 86% rename from packages/plugin/tests/utils/compress.test.ts rename to packages/plugin/tests/core/utils/compress.test.ts index 189c8595..f5c2e43e 100644 --- a/packages/plugin/tests/utils/compress.test.ts +++ b/packages/plugin/tests/core/utils/compress.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { deflateBytes, inflateBytes } from "@/utils/compress"; +import { deflateBytes, inflateBytes } from "@/core/utils/compress"; describe("compress", () => { it("round-trips through deflate when it is available", async () => { diff --git a/packages/plugin/tests/utils/concurrency.test.ts b/packages/plugin/tests/core/utils/concurrency.test.ts similarity index 96% rename from packages/plugin/tests/utils/concurrency.test.ts rename to packages/plugin/tests/core/utils/concurrency.test.ts index 68751239..4aa063f1 100644 --- a/packages/plugin/tests/utils/concurrency.test.ts +++ b/packages/plugin/tests/core/utils/concurrency.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { runWithConcurrency } from "@/utils/concurrency"; +import { runWithConcurrency } from "@/core/utils/concurrency"; describe("runWithConcurrency", () => { it("processes all items", async () => { diff --git a/packages/plugin/tests/utils/eol.test.ts b/packages/plugin/tests/core/utils/eol.test.ts similarity index 85% rename from packages/plugin/tests/utils/eol.test.ts rename to packages/plugin/tests/core/utils/eol.test.ts index 7dd74485..c4253915 100644 --- a/packages/plugin/tests/utils/eol.test.ts +++ b/packages/plugin/tests/core/utils/eol.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from "vitest"; - -import { computeHunks } from "@/sync/hunks"; -import { eolOf, toLf, withEolOf } from "@/utils/eol"; +import { eolOf, toLf, withEolOf } from "@/core/utils/eol"; +import { computeHunks } from "@/features/sync/hunks/hunks"; describe("line endings", () => { it("reads CRLF and a lone CR as the line break CodeMirror sees", () => { diff --git a/packages/plugin/tests/utils/revision.test.ts b/packages/plugin/tests/core/utils/revision.test.ts similarity index 89% rename from packages/plugin/tests/utils/revision.test.ts rename to packages/plugin/tests/core/utils/revision.test.ts index 0d8a990a..95823d63 100644 --- a/packages/plugin/tests/utils/revision.test.ts +++ b/packages/plugin/tests/core/utils/revision.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { isNewer } from "@/utils/revision"; +import { isNewer } from "@/core/utils/revision"; describe("isNewer", () => { it("lets the higher revision win, then the larger author", () => { diff --git a/packages/plugin/tests/vault/atomic-write.test.ts b/packages/plugin/tests/core/vault/atomic-write.test.ts similarity index 97% rename from packages/plugin/tests/vault/atomic-write.test.ts rename to packages/plugin/tests/core/vault/atomic-write.test.ts index 51a2bb79..6b4a7c7f 100644 --- a/packages/plugin/tests/vault/atomic-write.test.ts +++ b/packages/plugin/tests/core/vault/atomic-write.test.ts @@ -1,7 +1,7 @@ import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; import type { DataAdapter } from "obsidian"; import { describe, expect, it } from "vitest"; -import { writeAtomic } from "@/vault/atomic-write"; +import { writeAtomic } from "@/core/vault/atomic-write"; /** Fails the rename that moves the new file into place, and only that one. */ function adapterFailingFinalRename(inner: InMemoryAdapter): DataAdapter { diff --git a/packages/plugin/tests/vault/io.test.ts b/packages/plugin/tests/core/vault/io.test.ts similarity index 98% rename from packages/plugin/tests/vault/io.test.ts rename to packages/plugin/tests/core/vault/io.test.ts index 8f180837..11567163 100644 --- a/packages/plugin/tests/vault/io.test.ts +++ b/packages/plugin/tests/core/vault/io.test.ts @@ -1,7 +1,12 @@ import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; import type { DataAdapter } from "obsidian"; import { describe, expect, it } from "vitest"; -import { deletePath, ensureDir, removeEmptyDir, writeBinary } from "@/vault/io"; +import { + deletePath, + ensureDir, + removeEmptyDir, + writeBinary, +} from "@/core/vault/io"; interface Counted { adapter: DataAdapter; diff --git a/packages/plugin/tests/vault/symlinks.test.ts b/packages/plugin/tests/core/vault/symlinks.test.ts similarity index 98% rename from packages/plugin/tests/vault/symlinks.test.ts rename to packages/plugin/tests/core/vault/symlinks.test.ts index 00c354af..5e11657c 100644 --- a/packages/plugin/tests/vault/symlinks.test.ts +++ b/packages/plugin/tests/core/vault/symlinks.test.ts @@ -1,10 +1,10 @@ import { describe, expect, it } from "vitest"; -import { createScopePolicy } from "@/vault/scope"; import { createSymlinkDetector, type LinkLister, symlinkDetector, -} from "@/vault/symlinks"; +} from "@/core/vault/symlinks"; +import { createScopePolicy } from "@/features/sync/scope/scope"; const vault = "/vault"; const linksByDir = new Map>([ diff --git a/packages/plugin/tests/ui/choices.test.ts b/packages/plugin/tests/features/diff/choices.test.ts similarity index 96% rename from packages/plugin/tests/ui/choices.test.ts rename to packages/plugin/tests/features/diff/choices.test.ts index 11b2e8cb..ed7230c2 100644 --- a/packages/plugin/tests/ui/choices.test.ts +++ b/packages/plugin/tests/features/diff/choices.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { EChoiceKind, HunkChoices } from "@/ui/diff/choices"; +import { EChoiceKind, HunkChoices } from "@/features/diff/choices"; describe("HunkChoices", () => { it("toggles a segment on, replaces its kind, and off again", () => { diff --git a/packages/plugin/tests/ui/diff-chrome.test.ts b/packages/plugin/tests/features/diff/diff-chrome.test.ts similarity index 96% rename from packages/plugin/tests/ui/diff-chrome.test.ts rename to packages/plugin/tests/features/diff/diff-chrome.test.ts index 6b5561d7..42e0c6d8 100644 --- a/packages/plugin/tests/ui/diff-chrome.test.ts +++ b/packages/plugin/tests/features/diff/diff-chrome.test.ts @@ -1,6 +1,6 @@ // @vitest-environment jsdom import { describe, expect, it, vi } from "vitest"; -import { watchDiffChrome } from "@/ui/diff/action-bar"; +import { watchDiffChrome } from "@/features/diff/action-bar"; function chrome() { const header = document.createElement("div"); diff --git a/packages/plugin/tests/ui/diff-operations.test.ts b/packages/plugin/tests/features/diff/diff-operations.test.ts similarity index 71% rename from packages/plugin/tests/ui/diff-operations.test.ts rename to packages/plugin/tests/features/diff/diff-operations.test.ts index 9121588e..d3aca6f3 100644 --- a/packages/plugin/tests/ui/diff-operations.test.ts +++ b/packages/plugin/tests/features/diff/diff-operations.test.ts @@ -1,13 +1,16 @@ import { describe, expect, it, vi } from "vitest"; -import type { PluginHost } from "@/plugin/host"; -import { EDiffDirection, type FileDiffModel } from "@/sync/projection"; -import { EChoiceKind, HunkChoices } from "@/ui/diff/choices"; -import type { HistoryChange } from "@/ui/diff/history-state"; +import type { PluginHost } from "@/app/host"; +import { EChoiceKind, HunkChoices } from "@/features/diff/choices"; +import type { HistoryChange } from "@/features/diff/history-state"; import type { DiffOperationCallbacks, DiffOperationState, -} from "@/ui/diff/operations"; -import { DiffOperations } from "@/ui/diff/operations"; +} from "@/features/diff/operations"; +import { DiffOperations } from "@/features/diff/operations"; +import { + EDiffDirection, + type FileDiffModel, +} from "@/features/sync/hunks/projection"; function fakeModel(overrides: Partial = {}): FileDiffModel { return { @@ -51,6 +54,7 @@ function setup(stateOverrides: Partial = {}) { const restoreFn = vi.fn().mockResolvedValue(undefined); const restoreHunksFn = vi.fn().mockResolvedValue(undefined); + const resolveMergedFn = vi.fn().mockResolvedValue({ ok: true }); const plugin = { app: { @@ -61,13 +65,45 @@ function setup(stateOverrides: Partial = {}) { restoreFileVersion: restoreFn, restoreHistoryHunks: restoreHunksFn, }, + resolveConflictMerged: resolveMergedFn, }, }; const ops = new DiffOperations(plugin as unknown as PluginHost, callbacks); - return { ops, restoreFn, restoreHunksFn, refreshFn, advanceFn }; + return { + ops, + restoreFn, + restoreHunksFn, + resolveMergedFn, + refreshFn, + advanceFn, + }; } +describe("DiffOperations.saveMerge", () => { + const expected = { localHash: "l", remoteHash: "r" }; + + it("saves the merged text, then lets the merge go before the next file opens", async () => { + const { ops, resolveMergedFn, advanceFn } = setup(); + const saved = vi.fn(); + await ops.saveMerge("merged", expected, saved); + expect(resolveMergedFn).toHaveBeenCalledWith("note.md", "merged", expected); + expect(saved).toHaveBeenCalledOnce(); + expect(saved.mock.invocationCallOrder[0]).toBeLessThan( + advanceFn.mock.invocationCallOrder[0] ?? 0, + ); + }); + + it("keeps the merge open and stays on the file when the save is refused", async () => { + const { ops, resolveMergedFn, advanceFn } = setup(); + resolveMergedFn.mockResolvedValue({ ok: false, error: "changed" }); + const saved = vi.fn(); + await ops.saveMerge("merged", expected, saved); + expect(saved).not.toHaveBeenCalled(); + expect(advanceFn).not.toHaveBeenCalled(); + }); +}); + describe("DiffOperations with historyChange", () => { it("applyChoices does nothing when historyChange is set", async () => { const change: HistoryChange = { @@ -101,7 +137,7 @@ describe("DiffOperations.restoreVersion uses selected hash", () => { it.each(["add", "modify", "delete"])( "confirms the correct %s side and label", async (action) => { - const restoreMod = await import("@/ui/source-control/restore-modal"); + const restoreMod = await import("@/features/diff/ui/restore-modal"); const spy = vi .spyOn(restoreMod, "confirmRestore") .mockResolvedValue(true); @@ -126,7 +162,7 @@ describe("DiffOperations.restoreVersion uses selected hash", () => { ); it("does not restore if confirmation is cancelled", async () => { - const restoreMod = await import("@/ui/source-control/restore-modal"); + const restoreMod = await import("@/features/diff/ui/restore-modal"); const spy = vi.spyOn(restoreMod, "confirmRestore").mockResolvedValue(false); const { ops, restoreFn } = setup(); await ops.restoreVersion(); @@ -135,7 +171,7 @@ describe("DiffOperations.restoreVersion uses selected hash", () => { }); it("restores using the historyHash which is the selected version", async () => { - const restoreMod = await import("@/ui/source-control/restore-modal"); + const restoreMod = await import("@/features/diff/ui/restore-modal"); const spy = vi.spyOn(restoreMod, "confirmRestore").mockResolvedValue(true); const { ops, restoreFn } = setup({ historyHash: "selected-hash" }); diff --git a/packages/plugin/tests/ui/diff-view-status.test.ts b/packages/plugin/tests/features/diff/diff-view-status.test.ts similarity index 81% rename from packages/plugin/tests/ui/diff-view-status.test.ts rename to packages/plugin/tests/features/diff/diff-view-status.test.ts index 6dbd5f73..70bf0674 100644 --- a/packages/plugin/tests/ui/diff-view-status.test.ts +++ b/packages/plugin/tests/features/diff/diff-view-status.test.ts @@ -1,20 +1,21 @@ // @vitest-environment jsdom + +import { installElementMethods } from "@tests/helpers/element-methods"; import { beforeAll, describe, expect, it, vi } from "vitest"; -import type { PluginHost } from "@/plugin/host"; -import type { CompareResult } from "@/sync/engine"; -import { DiffView } from "@/ui/diff-view"; -import { installElementMethods } from "../settings/setup/element-methods"; +import type { PluginHost } from "@/app/host"; +import { type DiffTarget, fileTarget } from "@/features/diff/history-state"; +import { DiffView } from "@/features/diff/view"; +import type { CompareResult } from "@/features/sync/engine"; -vi.mock("@/ui/diff/header", () => ({ +vi.mock("@/features/diff/header", () => ({ renderDiffFrame: vi.fn(), refitDiffTitle: vi.fn(), })); -vi.mock("@/ui/common", () => ({ - notifyError: vi.fn(), - redrawOnPhoneChange: vi.fn(), +vi.mock("@/core/ui/notices", () => ({ notifyError: vi.fn() })); +vi.mock("@/core/ui/phone-change", () => ({ redrawOnPhoneChange: vi.fn() })); +vi.mock("@/core/ui/modals/confirm-modal", () => ({ + openConfirmModal: vi.fn(), })); -vi.mock("@/ui/modals", () => ({ openConfirmModal: vi.fn() })); -vi.mock("@/ui/source-control-view", () => ({ openSourceControlView: vi.fn() })); beforeAll(installElementMethods); @@ -23,7 +24,7 @@ const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); type Snapshot = { result: CompareResult | null; busy: boolean }; type Listener = (snapshot: Snapshot) => void; -async function open(fields: Record = {}) { +async function open(fields: Partial = {}) { let listener: Listener = () => undefined; const getFileDiff = vi.fn(async () => null); const getHistoryDiff = vi.fn(async () => null); @@ -46,8 +47,7 @@ async function open(fields: Record = {}) { Object.assign(view, { contentEl: document.createElement("div"), containerEl: { isShown: () => shown.value }, - path: "a.md", - ...fields, + target: { ...fileTarget("a.md"), ...fields }, }); await view.onOpen(); await settle(); diff --git a/packages/plugin/tests/ui/history-state.test.ts b/packages/plugin/tests/features/diff/history-state.test.ts similarity index 72% rename from packages/plugin/tests/ui/history-state.test.ts rename to packages/plugin/tests/features/diff/history-state.test.ts index 66216278..9b372d20 100644 --- a/packages/plugin/tests/ui/history-state.test.ts +++ b/packages/plugin/tests/features/diff/history-state.test.ts @@ -1,87 +1,19 @@ import { describe, expect, it } from "vitest"; -import { HUNK_TEXT_MAX_BYTES } from "@/sync/constants"; -import { EDiffDirection, type FileDiffModel } from "@/sync/projection"; import { buildHistoryRequest, changesDiffer, + fileTarget, type HistoryChange, - type HistoryModeInput, hunkHintText, - selectHistoryMode, -} from "@/ui/diff/history-state"; - -function modeInput( - overrides: Partial = {}, -): HistoryModeInput { - return { - historyHash: "abc123", - historyChange: null, - historyPreviewIfMissing: false, - against: null, - localExists: true, - ...overrides, - }; -} - -describe("selectHistoryMode", () => { - it("returns diff when no historyHash", () => { - expect(selectHistoryMode(modeInput({ historyHash: null }))).toBe("diff"); - }); - - it("returns change when historyChange is set", () => { - const change: HistoryChange = { - before: { hash: "a", label: "Before" }, - after: { hash: "b", label: "After" }, - }; - expect(selectHistoryMode(modeInput({ historyChange: change }))).toBe( - "change", - ); - }); - - it("returns diff when against is set (even with previewIfMissing)", () => { - expect( - selectHistoryMode( - modeInput({ - against: { hash: "x", label: "Other" }, - historyPreviewIfMissing: true, - localExists: false, - }), - ), - ).toBe("diff"); - }); - - it("returns preview when previewIfMissing and local missing", () => { - expect( - selectHistoryMode( - modeInput({ historyPreviewIfMissing: true, localExists: false }), - ), - ).toBe("preview"); - }); - - it("returns diff when previewIfMissing but local exists", () => { - expect( - selectHistoryMode( - modeInput({ historyPreviewIfMissing: true, localExists: true }), - ), - ).toBe("diff"); - }); - - it("change takes priority over previewIfMissing", () => { - const change: HistoryChange = { - before: null, - after: { hash: "b", label: "After" }, - }; - expect( - selectHistoryMode( - modeInput({ - historyChange: change, - historyPreviewIfMissing: true, - localExists: false, - }), - ), - ).toBe("change"); - }); -}); + readTarget, + sameTarget, + targetState, +} from "@/features/diff/history-state"; +import { HUNK_TEXT_MAX_BYTES } from "@/features/sync/constants"; +import { + EDiffDirection, + type FileDiffModel, +} from "@/features/sync/hunks/projection"; describe("buildHistoryRequest", () => { it("builds change request with absent before (added file)", () => { @@ -156,6 +88,43 @@ describe("buildHistoryRequest", () => { }); }); +describe("diff targets", () => { + const version = readTarget( + { path: "a.md", historyHash: "h1", historyLabel: "Pin", historySize: 5 }, + null, + ); + + it("keeps the current path for a state without one, and resets the rest", () => { + expect(readTarget({ historyHash: "h1" }, "a.md")).toMatchObject({ + path: "a.md", + historyLabel: "Version", + against: null, + }); + }); + + it("round-trips through the stored state", () => { + const against = readTarget( + { ...targetState(version), againstHash: "h2", againstLabel: "B" }, + null, + ); + expect(readTarget(targetState(against), null)).toEqual(against); + }); + + it("reloads for another version or a renamed pin, not for a size", () => { + expect(sameTarget(version, { ...version, historySize: 9 })).toBe(true); + expect(sameTarget(version, { ...version, historyLabel: "Renamed" })).toBe( + false, + ); + expect(sameTarget(version, { ...version, historyHash: "h2" })).toBe(false); + expect(sameTarget(version, fileTarget("a.md"))).toBe(false); + }); + + it("ignores a label on the file itself", () => { + const file = fileTarget("a.md"); + expect(sameTarget(file, { ...file, historyLabel: "Other" })).toBe(true); + }); +}); + describe("changesDiffer", () => { it("returns false for identical nulls", () => { expect(changesDiffer(null, null)).toBe(false); diff --git a/packages/plugin/tests/features/diff/lines/change-overlay.test.ts b/packages/plugin/tests/features/diff/lines/change-overlay.test.ts new file mode 100644 index 00000000..8c072bdd --- /dev/null +++ b/packages/plugin/tests/features/diff/lines/change-overlay.test.ts @@ -0,0 +1,59 @@ +// @vitest-environment jsdom +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { installElementMethods } from "@tests/helpers/element-methods"; +import { installElementFactories } from "@tests/helpers/obsidian-dom"; +import { afterEach, beforeAll, describe, expect, it } from "vitest"; +import type { CompareSegment } from "@/features/diff/compare/compare-decorations"; +import { ChangeOverlay } from "@/features/diff/lines/change-overlay"; + +beforeAll(() => { + installElementFactories(); + installElementMethods(); +}); + +const views: EditorView[] = []; +// A live view measures in a later frame, which jsdom cannot. +afterEach(() => { + for (const view of views.splice(0)) view.destroy(); +}); + +/** Line 2 of the left side, kept or deleted on the right. */ +const change = (right: [number, number]): CompareSegment => ({ + key: 0, + hunk: 0, + segment: 0, + left: [1, 2], + right, + removed: 1, + added: right[1] - right[0], + leftText: ["gone"], + rightText: [], + leftMarks: () => [], + rightMarks: () => [], +}); + +function pane() { + const host = document.body.createDiv(); + // jsdom lays nothing out, and a pane of no height runs no ring. + Object.defineProperty(host, "clientHeight", { value: 400 }); + const view = new EditorView({ + state: EditorState.create({ doc: "a\nb\nc" }), + parent: host, + }); + views.push(view); + const overlay = new ChangeOverlay(host, view, "right", () => {}); + const rings = () => host.querySelectorAll(".mdsync-change-ring"); + return { overlay, rings }; +} + +describe("ChangeOverlay ring", () => { + it("draws nothing until a layout places it", () => { + const { overlay, rings } = pane(); + const segment = change([1, 2]); + overlay.flash(segment); + expect(rings()).toHaveLength(0); + overlay.layout([segment], new Set()); + expect(rings()).toHaveLength(1); + }); +}); diff --git a/packages/plugin/tests/ui/code-lines.test.ts b/packages/plugin/tests/features/diff/lines/code-lines.test.ts similarity index 94% rename from packages/plugin/tests/ui/code-lines.test.ts rename to packages/plugin/tests/features/diff/lines/code-lines.test.ts index cce04eff..974b9ead 100644 --- a/packages/plugin/tests/ui/code-lines.test.ts +++ b/packages/plugin/tests/features/diff/lines/code-lines.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { lineMarks } from "@/ui/diff/code-lines"; +import { lineMarks } from "@/features/diff/lines/code-lines"; const NONE = { removed: [], added: [] }; diff --git a/packages/plugin/tests/features/diff/lines/follow-window.test.ts b/packages/plugin/tests/features/diff/lines/follow-window.test.ts new file mode 100644 index 00000000..8a7e3bcc --- /dev/null +++ b/packages/plugin/tests/features/diff/lines/follow-window.test.ts @@ -0,0 +1,28 @@ +// @vitest-environment jsdom +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { describe, expect, it } from "vitest"; +import { followWindow } from "@/features/diff/lines/follow-window"; + +describe("followWindow", () => { + it("mounts the editor in the document its host moved to", () => { + const host = document.body.appendChild(document.createElement("div")); + let migrate = () => {}; + Object.assign(host, { + doc: document, + onWindowMigrated: (listener: () => void) => { + migrate = listener; + return () => {}; + }, + }); + const view = new EditorView({ + state: EditorState.create({ extensions: followWindow(host) }), + parent: host, + }); + const popout = document.implementation.createHTMLDocument(); + Object.assign(host, { doc: popout }); + migrate(); + expect(view.root).toBe(popout); + view.destroy(); + }); +}); diff --git a/packages/plugin/tests/ui/gap-widgets.test.ts b/packages/plugin/tests/features/diff/lines/gap-widgets.test.ts similarity index 89% rename from packages/plugin/tests/ui/gap-widgets.test.ts rename to packages/plugin/tests/features/diff/lines/gap-widgets.test.ts index 67f9f997..9060ef33 100644 --- a/packages/plugin/tests/ui/gap-widgets.test.ts +++ b/packages/plugin/tests/features/diff/lines/gap-widgets.test.ts @@ -1,7 +1,7 @@ import { Text } from "@codemirror/state"; import { describe, expect, it } from "vitest"; -import type { LineRange } from "@/sync/hunks"; -import { foldedBands } from "@/ui/diff/gap-widgets"; +import { foldedBands } from "@/features/diff/lines/gap-widgets"; +import type { LineRange } from "@/features/sync/hunks/hunks"; const docOf = (lines: number) => Text.of(Array.from({ length: lines }, (_, index) => `line ${index + 1}`)); diff --git a/packages/plugin/tests/features/diff/lines/geometry.test.ts b/packages/plugin/tests/features/diff/lines/geometry.test.ts new file mode 100644 index 00000000..5cfea427 --- /dev/null +++ b/packages/plugin/tests/features/diff/lines/geometry.test.ts @@ -0,0 +1,83 @@ +import { BlockType, type EditorView, WidgetType } from "@codemirror/view"; +import { describe, expect, it } from "vitest"; +import { spanBounds } from "@/features/diff/lines/geometry"; +import { SourceBlockWidget } from "@/features/diff/lines/source-widget"; + +class RowWidget extends WidgetType { + toDOM(): HTMLElement { + throw new Error("never drawn"); + } +} + +const card = (key: string) => + new SourceBlockWidget({ + key, + tone: "removed", + head: { text: "Line 2 · removed" }, + lines: ["gone"], + firstLine: 1, + }); + +interface Part { + from: number; + height: number; + widget?: WidgetType; +} + +/** Line 2 runs from 4 to the file's end at 5; `parts` stack down from its top, the text where `widget` is left out. */ +function lineOf(parts: Part[]) { + let top = 20; + const type = parts.map(({ from, height, widget }) => { + const part = { + from, + widget: widget ?? null, + type: widget ? BlockType.WidgetBefore : BlockType.Text, + top, + bottom: top + height, + }; + top += height; + return part; + }); + const block = { + from: 4, + top: 20, + bottom: top, + type: type.length > 1 ? type : BlockType.Text, + }; + return { lineBlockAt: () => block } as unknown as EditorView; +} + +const text: Part = { from: 4, height: 20 }; +const atLineStart = { from: 4, to: 4 }; + +describe("spanBounds of an empty span", () => { + it("is a point at the line's top", () => { + expect(spanBounds(lineOf([text]), atLineStart)).toEqual({ + top: 20, + bottom: 20, + }); + }); + + it("is the card standing in the change's place, not a row above it", () => { + const view = lineOf([ + { from: 4, height: 30, widget: new RowWidget() }, + { from: 4, height: 50, widget: card("0") }, + text, + ]); + expect(spanBounds(view, atLineStart)).toEqual({ top: 50, bottom: 100 }); + }); + + it("leaves the card closing the file to its own change", () => { + const view = lineOf([text, { from: 5, height: 50, widget: card("1") }]); + expect(spanBounds(view, atLineStart)).toEqual({ top: 20, bottom: 20 }); + }); + + it("covers every card at one place, never picks one", () => { + const view = lineOf([ + { from: 4, height: 40, widget: card("0") }, + { from: 4, height: 30, widget: card("1") }, + text, + ]); + expect(spanBounds(view, atLineStart)).toEqual({ top: 20, bottom: 90 }); + }); +}); diff --git a/packages/plugin/tests/features/diff/lines/pane-search.test.ts b/packages/plugin/tests/features/diff/lines/pane-search.test.ts new file mode 100644 index 00000000..70a81330 --- /dev/null +++ b/packages/plugin/tests/features/diff/lines/pane-search.test.ts @@ -0,0 +1,124 @@ +// @vitest-environment jsdom +import { + closeSearchPanel, + openSearchPanel, + searchPanelOpen, +} from "@codemirror/search"; +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { installElementMethods } from "@tests/helpers/element-methods"; +import { installElementFactories } from "@tests/helpers/obsidian-dom"; +import { beforeAll, describe, expect, it, vi } from "vitest"; +import { PanelSearch } from "@/features/diff/lines/pane-search"; + +beforeAll(() => { + installElementFactories(); + installElementMethods(); +}); + +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); + +type Pane = "left" | "right"; + +function panel(onOpen: (pane: Pane) => void = () => {}) { + const search = new PanelSearch("right", onOpen); + const view = (pane: Pane) => + new EditorView({ + state: EditorState.create({ + doc: "a\nb", + extensions: search.extension(pane), + }), + parent: document.body, + }); + const views = { left: view("left"), right: view("right") }; + return { + search, + views, + destroy: () => { + views.left.destroy(); + views.right.destroy(); + }, + }; +} + +describe("PanelSearch", () => { + it("unfolds once each time a pane's search opens", async () => { + const onOpen = vi.fn(); + const { views, destroy } = panel(onOpen); + + openSearchPanel(views.left); + openSearchPanel(views.left); + await settle(); + expect(onOpen).toHaveBeenCalledTimes(1); + expect(onOpen).toHaveBeenCalledWith("left", views.left); + + closeSearchPanel(views.left); + openSearchPanel(views.left); + await settle(); + expect(onOpen).toHaveBeenCalledTimes(2); + destroy(); + }); + + it("unfolds before Go to line, which opens no search panel", () => { + const onOpen = vi.fn(); + const { views, destroy } = panel(onOpen); + views.right.contentDOM.dispatchEvent( + new KeyboardEvent("keydown", { key: "g", ctrlKey: true, altKey: true }), + ); + expect(onOpen).toHaveBeenCalledWith("right", views.right); + destroy(); + }); + + it("toggles a pane's search from its head, pressed while open however it opened", () => { + const { search, views, destroy } = panel(); + const head = document.body.createDiv(); + search.appendToggle(head, "left"); + const toggle = head.querySelector("button") as HTMLButtonElement; + + toggle.click(); + expect(searchPanelOpen(views.left.state)).toBe(true); + expect(searchPanelOpen(views.right.state)).toBe(false); + expect(toggle.getAttribute("aria-pressed")).toBe("true"); + + toggle.focus(); + toggle.click(); + expect(searchPanelOpen(views.left.state)).toBe(false); + expect(toggle.classList.contains("is-active")).toBe(false); + expect(views.left.hasFocus).toBe(true); + + openSearchPanel(views.left); + expect(toggle.classList.contains("is-active")).toBe(true); + destroy(); + }); + + it("shows the toolbar's toggle only Inline, for the main pane", () => { + const { search, views, destroy } = panel(); + const toolbar = document.createElement("div"); + search.appendInlineToggle(toolbar); + const toggle = toolbar.querySelector("button") as HTMLButtonElement; + search.setInline(false); + expect(toggle.hidden).toBe(true); + search.setInline(true); + expect(toggle.hidden).toBe(false); + + toggle.click(); + expect(searchPanelOpen(views.right.state)).toBe(true); + destroy(); + }); + + it("toggles the focused pane's search on Mod+F, else the main pane's", () => { + const { search, views, destroy } = panel(); + search.toggleFocused(); + expect(searchPanelOpen(views.right.state)).toBe(true); + search.toggleFocused(); + expect(searchPanelOpen(views.right.state)).toBe(false); + + views.left.contentDOM.focus(); + search.toggleFocused(); + expect(searchPanelOpen(views.left.state)).toBe(true); + // The focus is in the left pane's bar now: Mod+F there closes it. + search.toggleFocused(); + expect(searchPanelOpen(views.left.state)).toBe(false); + destroy(); + }); +}); diff --git a/packages/plugin/tests/ui/scroll-sync.test.ts b/packages/plugin/tests/features/diff/lines/scroll-sync.test.ts similarity index 96% rename from packages/plugin/tests/ui/scroll-sync.test.ts rename to packages/plugin/tests/features/diff/lines/scroll-sync.test.ts index adf50faa..71c5d420 100644 --- a/packages/plugin/tests/ui/scroll-sync.test.ts +++ b/packages/plugin/tests/features/diff/lines/scroll-sync.test.ts @@ -1,6 +1,9 @@ import type { EditorView } from "@codemirror/view"; import { describe, expect, it, vi } from "vitest"; -import { PaneScrollSync, type ScrollPair } from "@/ui/diff/scroll-sync"; +import { + PaneScrollSync, + type ScrollPair, +} from "@/features/diff/lines/scroll-sync"; function pane(height: number, viewport = 300): EditorView { const scrollDOM = Object.assign(new EventTarget(), { diff --git a/packages/plugin/tests/features/diff/lines/search-bar.test.ts b/packages/plugin/tests/features/diff/lines/search-bar.test.ts new file mode 100644 index 00000000..292c8563 --- /dev/null +++ b/packages/plugin/tests/features/diff/lines/search-bar.test.ts @@ -0,0 +1,126 @@ +// @vitest-environment jsdom +import { + getSearchQuery, + openSearchPanel, + searchPanelOpen, +} from "@codemirror/search"; +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { installElementMethods } from "@tests/helpers/element-methods"; +import { installElementFactories } from "@tests/helpers/obsidian-dom"; +import { beforeAll, describe, expect, it } from "vitest"; +import { PanelSearch } from "@/features/diff/lines/pane-search"; + +beforeAll(() => { + installElementFactories(); + installElementMethods(); +}); + +function openBar(doc: string, editable = false, select?: [number, number]) { + const view = new EditorView({ + state: EditorState.create({ + doc, + extensions: [ + new PanelSearch("pane", () => {}).extension("pane"), + EditorState.readOnly.of(!editable), + ], + }), + parent: document.body, + }); + if (select) + view.dispatch({ selection: { anchor: select[0], head: select[1] } }); + openSearchPanel(view); + const bar = view.dom.querySelector(".cm-panels-top .mdsync-search-bar"); + if (!(bar instanceof HTMLElement)) throw new Error("no search bar"); + const field = (label: string) => + bar.querySelector(`input[aria-label="${label}"]`) as HTMLInputElement; + const button = (label: string) => + bar.querySelector(`button[aria-label="${label}"]`); + return { + view, + field, + button, + labeled: (text: string) => + [...bar.querySelectorAll("button")].find((b) => b.textContent === text), + type(label: string, text: string) { + field(label).value = text; + field(label).dispatchEvent(new Event("input")); + }, + press(key: string, shiftKey = false) { + field("Find").dispatchEvent( + new KeyboardEvent("keydown", { key, shiftKey, bubbles: true }), + ); + }, + count: () => bar.querySelector(".mdsync-search-count")?.textContent, + }; +} + +describe("SearchBar", () => { + it("sets CodeMirror's query, counts and steps through matches", () => { + const bar = openBar("Apple and apple\napple pie"); + bar.type("Find", "apple"); + expect(getSearchQuery(bar.view.state).search).toBe("apple"); + expect(bar.count()).toBe("3"); + + bar.press("Enter"); + expect(bar.count()).toBe("1/3"); + bar.press("Enter", true); + expect(bar.count()).toBe("3/3"); + + bar.button("Match case")?.click(); + expect(getSearchQuery(bar.view.state).caseSensitive).toBe(true); + expect(bar.button("Match case")?.classList.contains("is-active")).toBe( + true, + ); + expect(bar.count()).toBe("2/2"); + + bar.type("Find", "pear"); + expect(bar.count()).toBe("0"); + bar.view.destroy(); + }); + + it("shows a query taken from the selection", () => { + const bar = openBar("Apple and apple", false, [6, 9]); + expect(bar.field("Find").value).toBe("and"); + bar.view.destroy(); + }); + + it("offers replace only where the pane can be edited", () => { + const readOnly = openBar("cat cat"); + expect(readOnly.button("Show replace")).toBeNull(); + readOnly.view.destroy(); + + const bar = openBar("cat cat", true); + bar.button("Show replace")?.click(); + bar.type("Find", "cat"); + bar.type("Replace", "dog"); + bar.labeled("Replace all")?.click(); + expect(bar.view.state.doc.toString()).toBe("dog dog"); + bar.view.destroy(); + }); + + it("focuses Find when it opens", () => { + const bar = openBar("cat", true); + expect(document.activeElement).toBe(bar.field("Find")); + bar.view.destroy(); + }); + + it("leaves Enter on a button to the button", () => { + const bar = openBar("cat cat"); + bar.type("Find", "cat"); + bar + .button("Match case") + ?.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }), + ); + expect(bar.count()).toBe("2"); + bar.view.destroy(); + }); + + it("closes on Escape through CodeMirror's search keys", () => { + const bar = openBar("cat"); + bar.press("Escape"); + expect(searchPanelOpen(bar.view.state)).toBe(false); + bar.view.destroy(); + }); +}); diff --git a/packages/plugin/tests/utils/search.test.ts b/packages/plugin/tests/features/diff/lines/search.test.ts similarity index 90% rename from packages/plugin/tests/utils/search.test.ts rename to packages/plugin/tests/features/diff/lines/search.test.ts index 2608e1a8..6685951f 100644 --- a/packages/plugin/tests/utils/search.test.ts +++ b/packages/plugin/tests/features/diff/lines/search.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { firstIndex } from "@/utils/search"; +import { firstIndex } from "@/features/diff/lines/search"; describe("firstIndex", () => { const values = [1, 3, 3, 7, 9]; diff --git a/packages/plugin/tests/sync/merge-model.test.ts b/packages/plugin/tests/features/diff/merge/edit-plan.test.ts similarity index 56% rename from packages/plugin/tests/sync/merge-model.test.ts rename to packages/plugin/tests/features/diff/merge/edit-plan.test.ts index c094721b..e9ed0454 100644 --- a/packages/plugin/tests/sync/merge-model.test.ts +++ b/packages/plugin/tests/features/diff/merge/edit-plan.test.ts @@ -2,14 +2,11 @@ import { Text } from "@codemirror/state"; import { describe, expect, it } from "vitest"; import { applyPlan, - buildMergeSession, - countUnresolved, - type MergeChange, revertPlan, type StatusPatch, snapToLines, - threeWayRegions, -} from "@/sync/merge-model"; +} from "@/features/diff/merge/edit-plan"; +import type { MergeChange } from "@/features/sync/hunks/merge-model"; const doc = (text: string) => Text.of(text.split("\n")); @@ -31,131 +28,6 @@ function conflictAt( }; } -describe("threeWayRegions", () => { - it("gives every region all three ranges; the unchanged side owns the base lines", () => { - const regions = threeWayRegions( - ["a", "b", "c"], - ["a", "B", "c"], - ["a", "b", "c", "d"], - ); - expect(regions).toEqual([ - { - base: [1, 2], - local: [1, 2], - remote: [1, 2], - changed: { local: true, remote: false }, - }, - { - base: [3, 3], - local: [3, 3], - remote: [3, 4], - changed: { local: false, remote: true }, - }, - ]); - }); - - it("merges touching hunks from both sides into one region, like diff3", () => { - // Local inserts before "b" while remote rewrites "b": adjacent, so one region. - const regions = threeWayRegions( - ["a", "b", "c"], - ["a", "X", "b", "c"], - ["a", "B", "c"], - ); - expect(regions).toEqual([ - { - base: [1, 2], - local: [1, 3], - remote: [1, 2], - changed: { local: true, remote: true }, - }, - ]); - }); - - it("keeps a side past the diff budget as one region around its differing middle", () => { - const base = Array.from({ length: 2000 }, (_, i) => `line ${i}`); - const local = base.map((line, i) => - i === 0 || i === 1999 ? line : `${line} local`, - ); - expect(threeWayRegions(base, local, base)).toEqual([ - { - base: [1, 1999], - local: [1, 1999], - remote: [1, 1999], - changed: { local: true, remote: false }, - }, - ]); - }); -}); - -describe("buildMergeSession", () => { - it("applies one-sided edits up front and marks them applied", () => { - const base = "one\ntwo\nthree\nfour\nfive\n"; - const local = "one\nTWO\nthree\nfour\nfive\nsix\n"; - const remote = "one\ntwo\nthree\nFOUR\nfive\n"; - const session = buildMergeSession(base, local, remote); - expect(session.text).toBe("one\nTWO\nthree\nFOUR\nfive\nsix\n"); - expect(session.changes.map((c) => c.conflict)).toEqual([ - false, - false, - false, - ]); - expect(session.changes.map((c) => c.status)).toEqual([ - { local: "applied", remote: "none" }, - { local: "none", remote: "applied" }, - { local: "applied", remote: "none" }, - ]); - const spans = session.changes.map((c) => - session.text.slice(c.result.from, c.result.to), - ); - expect(spans).toEqual(["TWO\n", "FOUR\n", "six\n"]); - }); - - it("keeps the base lines where both sides disagree and leaves both sides open", () => { - const session = buildMergeSession("a\nb\nc", "a\nL\nc", "a\nR\nc"); - expect(session.text).toBe("a\nb\nc"); - expect(session.changes).toEqual([ - { - index: 0, - conflict: true, - base: [1, 2], - endsAtEof: false, - local: [1, 2], - remote: [1, 2], - result: { from: 2, to: 4 }, - taken: {}, - status: { local: "open", remote: "open" }, - }, - ]); - expect(countUnresolved(session.changes)).toBe(1); - }); - - it("treats the same edit on both sides as one applied change", () => { - const session = buildMergeSession("a\nb", "a\nB", "a\nB"); - expect(session.text).toBe("a\nB"); - expect(session.changes[0]?.conflict).toBe(false); - expect(session.changes[0]?.status).toEqual({ - local: "applied", - remote: "applied", - }); - }); - - it("puts a conflict appended to a file without final newline at the doc end", () => { - const session = buildMergeSession("a", "a\nL", "a\nR"); - expect(session.text).toBe("a"); - expect(session.changes[0]?.result).toEqual({ from: 1, to: 1 }); - }); - - it("compares on LF so CRLF on one side is not one whole conflict", () => { - const session = buildMergeSession( - "a\nb\nc\nd\ne", - "a\r\nLOCAL\r\nc\r\nd\r\ne", - "a\nb\nc\nREMOTE\ne", - ); - expect(session.text).toBe("a\nLOCAL\nc\nREMOTE\ne"); - expect(countUnresolved(session.changes)).toBe(0); - }); -}); - describe("applyPlan", () => { it("replaces the base lines with the chosen side", () => { const plan = applyPlan(doc("a\nb\nc"), conflictAt(2, 4), "local", [ diff --git a/packages/plugin/tests/ui/merge-actions.test.ts b/packages/plugin/tests/features/diff/merge/merge-actions.test.ts similarity index 79% rename from packages/plugin/tests/ui/merge-actions.test.ts rename to packages/plugin/tests/features/diff/merge/merge-actions.test.ts index fdd53f88..33f4bb05 100644 --- a/packages/plugin/tests/ui/merge-actions.test.ts +++ b/packages/plugin/tests/features/diff/merge/merge-actions.test.ts @@ -6,10 +6,13 @@ import { } from "@codemirror/state"; import type { EditorView } from "@codemirror/view"; import { describe, expect, it } from "vitest"; -import { buildMergeSession } from "@/sync/merge-model"; -import { mergeActions } from "@/ui/diff/merge-actions"; -import { mergeResultState } from "@/ui/diff/merge-decorations"; -import { initialMergeChanges, mergeChangesField } from "@/ui/diff/merge-state"; +import { mergeActions } from "@/features/diff/merge/merge-actions"; +import { mergeResultState } from "@/features/diff/merge/merge-decorations"; +import { + initialMergeChanges, + mergeChangesField, +} from "@/features/diff/merge/merge-state"; +import { buildMergeSession } from "@/features/sync/hunks/merge-model"; /** A Result editor without a DOM: the actions only read its state and dispatch. */ function open(base: string, local: string, remote: string) { @@ -127,3 +130,28 @@ describe("settling a conflict", () => { expect(merge.status()).toEqual({ local: "open", remote: "open" }); }); }); + +describe("taking a side that never changed the region", () => { + const BASE = "a\nb\nc\nd\ne\n"; + + it("puts the base lines back over text typed there", () => { + const merge = open(BASE, "a\nL\nc\nd\ne\n", "a\nb\nc\nR\ne\n"); + expect(merge.text()).toBe("a\nL\nc\nR\ne\n"); + merge.type(2, 3, "typed"); + + merge.actions.settle(0, ["remote"]); + + expect(merge.text()).toBe("a\nb\nc\nR\ne\n"); + }); + + it("leaves the document alone when the base lines are already there", () => { + const merge = open(BASE, "a\nL\nc\nd\ne\n", "a\nb\nc\nR\ne\n"); + merge.actions.settle(0, []); + expect(merge.text()).toBe("a\nb\nc\nR\ne\n"); + + merge.actions.settle(0, ["remote"]); + merge.undoOnce(); + + expect(merge.text()).toBe("a\nL\nc\nR\ne\n"); + }); +}); diff --git a/packages/plugin/tests/ui/merge-cards.test.ts b/packages/plugin/tests/features/diff/merge/merge-cards.test.ts similarity index 80% rename from packages/plugin/tests/ui/merge-cards.test.ts rename to packages/plugin/tests/features/diff/merge/merge-cards.test.ts index 8cfa7970..a707db16 100644 --- a/packages/plugin/tests/ui/merge-cards.test.ts +++ b/packages/plugin/tests/features/diff/merge/merge-cards.test.ts @@ -1,13 +1,16 @@ import { EditorState } from "@codemirror/state"; import type { EditorView } from "@codemirror/view"; import { describe, expect, it } from "vitest"; -import { buildMergeSession } from "@/sync/merge-model"; -import { mergeActions } from "@/ui/diff/merge-actions"; -import { type CombinedMergeConfig, mergeCards } from "@/ui/diff/merge-cards"; -import { mergeResultState } from "@/ui/diff/merge-decorations"; -import { sideMarks } from "@/ui/diff/merge-marks"; -import { initialMergeChanges } from "@/ui/diff/merge-state"; -import type { SourceBlock } from "@/ui/diff/source-widget"; +import type { SourceBlock } from "@/features/diff/lines/source-widget"; +import { mergeActions } from "@/features/diff/merge/merge-actions"; +import { + type CombinedMergeConfig, + mergeCards, +} from "@/features/diff/merge/merge-cards"; +import { mergeResultState } from "@/features/diff/merge/merge-decorations"; +import { sideMarks } from "@/features/diff/merge/merge-marks"; +import { initialMergeChanges } from "@/features/diff/merge/merge-state"; +import { buildMergeSession } from "@/features/sync/hunks/merge-model"; function open(base: string, local: string, remote: string) { const session = buildMergeSession(base, local, remote); diff --git a/packages/plugin/tests/features/diff/merge/merge-drafts.test.ts b/packages/plugin/tests/features/diff/merge/merge-drafts.test.ts new file mode 100644 index 00000000..c739c898 --- /dev/null +++ b/packages/plugin/tests/features/diff/merge/merge-drafts.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it } from "vitest"; +import { + keepMergeDraft, + type MergeDraft, + startMerge, + takeMergeDraft, +} from "@/features/diff/merge/merge-drafts"; +import type { MergeChange } from "@/features/sync/hunks/merge-model"; + +const expected = { localHash: "l1", remoteHash: "r1" }; +const draft = (text: string): MergeDraft => ({ text, changes: [], expected }); + +describe("merge drafts", () => { + it("gives a kept draft back once, for the same versions", () => { + keepMergeDraft("a.md", draft("edited")); + + expect(takeMergeDraft("a.md", expected)).toEqual(draft("edited")); + expect(takeMergeDraft("a.md", expected)).toBeNull(); + }); + + it("drops a draft whose local or remote side changed since", () => { + keepMergeDraft("b.md", draft("edited")); + expect(takeMergeDraft("b.md", { ...expected, remoteHash: "r2" })).toBe( + "stale", + ); + expect(takeMergeDraft("b.md", expected)).toBeNull(); + + keepMergeDraft("b.md", draft("edited")); + expect(takeMergeDraft("b.md", { ...expected, localHash: "l2" })).toBe( + "stale", + ); + }); + + it("keeps the latest draft of a path and only the five newest paths", () => { + keepMergeDraft("c.md", draft("first")); + keepMergeDraft("c.md", draft("second")); + for (const n of [1, 2, 3, 4, 5]) keepMergeDraft(`n${n}.md`, draft("x")); + + expect(takeMergeDraft("c.md", expected)).toBeNull(); + expect(takeMergeDraft("n1.md", expected)).toEqual(draft("x")); + + keepMergeDraft("d.md", draft("first")); + keepMergeDraft("e.md", draft("e")); + keepMergeDraft("d.md", draft("second")); + expect(takeMergeDraft("d.md", expected)).toEqual(draft("second")); + }); +}); + +describe("startMerge", () => { + const conflict = { conflict: true } as MergeChange; + const session = { text: "fresh", changes: [conflict] }; + + it("resumes a kept draft of the same versions and says so", () => { + keepMergeDraft("s1.md", draft("edited")); + + expect(startMerge("s1.md", expected, session)).toEqual({ + text: "edited", + changes: [], + restored: true, + notice: "Restored your unsaved merge.", + }); + }); + + it("starts fresh over a stale draft and says the edits were dropped", () => { + keepMergeDraft("s2.md", draft("edited")); + + const start = startMerge( + "s2.md", + { ...expected, localHash: "l2" }, + session, + ); + + expect(start).toMatchObject({ text: "fresh", restored: false }); + expect(start.notice).toMatch(/unsaved edits were dropped/); + }); + + it("says a merge with no conflict merged itself", () => { + expect(startMerge("s3.md", expected, session).notice).toBeNull(); + expect( + startMerge("s3.md", expected, { text: "fresh", changes: [] }).notice, + ).toMatch(/auto-merged/); + }); +}); diff --git a/packages/plugin/tests/ui/merge-state.test.ts b/packages/plugin/tests/features/diff/merge/merge-state.test.ts similarity index 87% rename from packages/plugin/tests/ui/merge-state.test.ts rename to packages/plugin/tests/features/diff/merge/merge-state.test.ts index 788615a8..e8abb7bc 100644 --- a/packages/plugin/tests/ui/merge-state.test.ts +++ b/packages/plugin/tests/features/diff/merge/merge-state.test.ts @@ -1,24 +1,33 @@ import { history, isolateHistory, redo, undo } from "@codemirror/commands"; -import { EditorState, Transaction } from "@codemirror/state"; -import { assert, describe, expect, it } from "vitest"; import { - applyPlan, - buildMergeSession, - type EMergeSide, - type MergeChange, - revertPlan, -} from "@/sync/merge-model"; -import { openedGapsField, toggleMergeGap } from "@/ui/diff/merge-cards"; + EditorState, + Transaction, + type TransactionSpec, +} from "@codemirror/state"; +import type { EditorView } from "@codemirror/view"; +import { assert, describe, expect, it } from "vitest"; import { combinedModeField, - mergeResultState, setCombinedMode, -} from "@/ui/diff/merge-decorations"; +} from "@/features/diff/layout-mode"; +import { applyPlan, revertPlan } from "@/features/diff/merge/edit-plan"; +import { + openAllMergeGaps, + openedGapsField, + toggleMergeGap, +} from "@/features/diff/merge/merge-cards"; +import { mergeResultState } from "@/features/diff/merge/merge-decorations"; import { + changeAt, initialMergeChanges, mergeChangesField, setChangeState, -} from "@/ui/diff/merge-state"; +} from "@/features/diff/merge/merge-state"; +import { + buildMergeSession, + type EMergeSide, + type MergeChange, +} from "@/features/sync/hunks/merge-model"; function open(base: string, local: string, remote: string): EditorState { const session = buildMergeSession(base, local, remote); @@ -434,3 +443,49 @@ describe("responsive merge state", () => { expect(state.field(openedGapsField).size).toBe(0); }); }); + +describe("changeAt", () => { + it("finds the change whose lines hold the position", () => { + const state = open("a\nb\nc\nd\ne\n", "a\nB\nc\nd\ne\n", "a\nb\nc\nD\ne\n"); + expect(state.doc.toString()).toBe("a\nB\nc\nD\ne\n"); + + expect(changeAt(state, 2)).toBe(0); + expect(changeAt(state, 3)).toBe(0); + expect(changeAt(state, 6)).toBe(1); + expect(changeAt(state, 0)).toBe(-1); + expect(changeAt(state, 4)).toBe(-1); + }); +}); + +describe("changeAt at the end of the file", () => { + it("holds a last change whose final line has no line break", () => { + const state = open("a\nb\nc\nd\ne", "a\nL\nc\nd\nX", "a\nR\nc\nd\nY"); + + expect(changeAt(state, state.doc.length)).toBe(1); + }); + + it("leaves out the empty line after a final line break", () => { + const state = open("a\nb\nc\nd\ne\n", "a\nB\nc\nd\ne\n", "a\nb\nc\nd\nE\n"); + + expect(changeAt(state, state.doc.length)).toBe(-1); + }); +}); + +describe("openAllMergeGaps", () => { + it("opens every folded run and leaves open ones open", () => { + let state = open("a\nb\nc\nd\ne\n", "a\nB\nc\nd\ne\n", "a\nb\nc\nd\nE\n"); + state = state.update({ effects: toggleMergeGap.of(1) }).state; + const view = { + get state() { + return state; + }, + dispatch: (spec: TransactionSpec) => { + state = state.update(spec).state; + }, + } as unknown as EditorView; + + openAllMergeGaps(view); + + expect([...state.field(openedGapsField)].sort()).toEqual([0, 1, 2]); + }); +}); diff --git a/packages/plugin/tests/features/diff/rail.test.ts b/packages/plugin/tests/features/diff/rail.test.ts new file mode 100644 index 00000000..a4f82286 --- /dev/null +++ b/packages/plugin/tests/features/diff/rail.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from "vitest"; +import { stepIndex } from "@/features/diff/rail"; + +describe("stepIndex", () => { + it("starts at the first going forward and at the last going back", () => { + expect(stepIndex(-1, 1, 3)).toBe(0); + expect(stepIndex(-1, -1, 3)).toBe(2); + }); + + it("wraps round both ways", () => { + expect(stepIndex(2, 1, 3)).toBe(0); + expect(stepIndex(0, -1, 3)).toBe(2); + }); + + it("has nowhere to go without changes", () => { + expect(stepIndex(-1, 1, 0)).toBe(-1); + }); +}); diff --git a/packages/plugin/tests/features/diff/ui/copy-menu.test.ts b/packages/plugin/tests/features/diff/ui/copy-menu.test.ts new file mode 100644 index 00000000..0feec230 --- /dev/null +++ b/packages/plugin/tests/features/diff/ui/copy-menu.test.ts @@ -0,0 +1,70 @@ +import type { Menu } from "obsidian"; +import { describe, expect, it, vi } from "vitest"; +import { copyText } from "@/core/ui/controls/copyable"; +import { addCopyItems } from "@/features/diff/ui/copy-menu"; +import type { FileDiffModel } from "@/features/sync"; + +vi.mock("@/core/ui/controls/copyable", () => ({ + copyText: vi.fn(async () => true), +})); + +class FakeItem { + title = ""; + click = () => {}; + setTitle(title: string) { + this.title = title; + return this; + } + setIcon() { + return this; + } + onClick(click: () => void) { + this.click = click; + return this; + } +} + +function menuItems(model: Partial | null) { + const items: FakeItem[] = []; + const menu = { + addItem(build: (item: FakeItem) => void) { + const item = new FakeItem(); + build(item); + items.push(item); + return menu; + }, + }; + addCopyItems(menu as unknown as Menu, "a/note.md", model as FileDiffModel); + return items; +} + +const model: Partial = { + isBinary: false, + leftLabel: "This device", + leftText: "mine", + leftPresent: true, + rightLabel: "Incoming", + rightText: "theirs", + rightPresent: true, +}; + +describe("addCopyItems", () => { + it("copies the path and each side's text", () => { + const items = menuItems(model); + expect(items.map((item) => item.title)).toEqual([ + "Copy path", + "Copy text (This device)", + "Copy text (Incoming)", + ]); + items[2]?.click(); + expect(copyText).toHaveBeenLastCalledWith("Text", "theirs"); + }); + + it("offers no text for an absent side, a binary file or no model", () => { + expect( + menuItems({ ...model, leftPresent: false }).map((item) => item.title), + ).toEqual(["Copy path", "Copy text (Incoming)"]); + expect(menuItems({ ...model, isBinary: true })).toHaveLength(1); + expect(menuItems(null)).toHaveLength(1); + }); +}); diff --git a/packages/plugin/tests/features/diff/ui/leave-guard.test.ts b/packages/plugin/tests/features/diff/ui/leave-guard.test.ts new file mode 100644 index 00000000..1f8e956a --- /dev/null +++ b/packages/plugin/tests/features/diff/ui/leave-guard.test.ts @@ -0,0 +1,36 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { openConfirmModal } from "@/core/ui/modals/confirm-modal"; +import { confirmLeave } from "@/features/diff/ui/leave-guard"; + +vi.mock("@/core/ui/modals/confirm-modal", () => ({ + openConfirmModal: vi.fn(async () => false), +})); + +const app = {} as never; +const asked = () => vi.mocked(openConfirmModal).mock.calls[0]?.[0]; + +describe("confirmLeave", () => { + beforeEach(() => vi.mocked(openConfirmModal).mockClear()); + + it("leaves at once with nothing unsaved", async () => { + expect(await confirmLeave(app, { mergeEdits: false, picked: 0 })).toBe( + true, + ); + expect(openConfirmModal).not.toHaveBeenCalled(); + }); + + it("asks before dropping changes picked and not applied", async () => { + expect(await confirmLeave(app, { mergeEdits: false, picked: 2 })).toBe( + false, + ); + expect(asked()).toMatchObject({ + title: "Discard your choices?", + body: ["2 picked changes are not applied yet. Leaving drops them."], + }); + }); + + it("asks about the merge first", async () => { + await confirmLeave(app, { mergeEdits: true, picked: 1 }); + expect(asked()).toMatchObject({ title: "Discard this merge?" }); + }); +}); diff --git a/packages/plugin/tests/editor/signs/integration.test.ts b/packages/plugin/tests/features/editor-signs/integration.test.ts similarity index 92% rename from packages/plugin/tests/editor/signs/integration.test.ts rename to packages/plugin/tests/features/editor-signs/integration.test.ts index 272a75f2..eb04b620 100644 --- a/packages/plugin/tests/editor/signs/integration.test.ts +++ b/packages/plugin/tests/features/editor-signs/integration.test.ts @@ -1,8 +1,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; - -import { registerEditorSigns } from "@/editor/signs"; -import { SignsProvider } from "@/editor/signs/provider"; -import type { SyncStatusSnapshot } from "@/sync/controller"; +import { SignsProvider } from "@/features/editor-signs/provider"; +import { registerEditorSigns } from "@/features/editor-signs/register"; +import type { SyncStatusSnapshot } from "@/features/sync/controller"; afterEach(() => { vi.restoreAllMocks(); diff --git a/packages/plugin/tests/editor/popup-dismiss.test.ts b/packages/plugin/tests/features/editor-signs/popup/popup-dismiss.test.ts similarity index 92% rename from packages/plugin/tests/editor/popup-dismiss.test.ts rename to packages/plugin/tests/features/editor-signs/popup/popup-dismiss.test.ts index 81861a65..b5d79006 100644 --- a/packages/plugin/tests/editor/popup-dismiss.test.ts +++ b/packages/plugin/tests/features/editor-signs/popup/popup-dismiss.test.ts @@ -1,7 +1,7 @@ // @vitest-environment jsdom import type { EditorView } from "@codemirror/view"; import { describe, expect, it, vi } from "vitest"; -import { installDismissHandlers } from "@/editor/signs/popup-dismiss"; +import { installDismissHandlers } from "@/features/editor-signs/popup/popup-dismiss"; describe("installDismissHandlers", () => { it("listens in the editor's own window, a popout included", () => { diff --git a/packages/plugin/tests/editor/signs/provider.test.ts b/packages/plugin/tests/features/editor-signs/provider.test.ts similarity index 90% rename from packages/plugin/tests/editor/signs/provider.test.ts rename to packages/plugin/tests/features/editor-signs/provider.test.ts index 2e62a4f4..b75d0d70 100644 --- a/packages/plugin/tests/editor/signs/provider.test.ts +++ b/packages/plugin/tests/features/editor-signs/provider.test.ts @@ -3,9 +3,9 @@ import { EditorState } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import { describe, expect, it, vi } from "vitest"; -import { SignsProvider } from "@/editor/signs/provider"; -import { compareTextField } from "@/editor/signs/state"; -import type { SyncController } from "@/sync/controller"; +import { SignsProvider } from "@/features/editor-signs/provider"; +import { compareTextField } from "@/features/editor-signs/state"; +import type { SyncController } from "@/features/sync/controller"; function setup() { let text: string | null = "base\n"; diff --git a/packages/plugin/tests/editor/signs.test.ts b/packages/plugin/tests/features/editor-signs/signs.test.ts similarity index 86% rename from packages/plugin/tests/editor/signs.test.ts rename to packages/plugin/tests/features/editor-signs/signs.test.ts index fc5a65ee..d805f02e 100644 --- a/packages/plugin/tests/editor/signs.test.ts +++ b/packages/plugin/tests/features/editor-signs/signs.test.ts @@ -1,8 +1,8 @@ import { EditorState, Text } from "@codemirror/state"; -import { describe, expect, it, vi } from "vitest"; - -import { registerEditorSigns } from "@/editor/signs"; -import { signsField } from "@/editor/signs/gutter"; +import type { EditorView } from "@codemirror/view"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { focusHunk, hunkFocusField } from "@/features/editor-signs/focus"; +import { signsField } from "@/features/editor-signs/gutter"; import { type ChangeMark, findChangeForLine, @@ -11,15 +11,16 @@ import { presentSyncChange, shouldRedeliverBaseline, toCmText, -} from "@/editor/signs/helpers"; -import { segmentRevert } from "@/editor/signs/hunk-revert"; +} from "@/features/editor-signs/marks"; +import { segmentRevert } from "@/features/editor-signs/popup/hunk-revert"; +import { registerEditorSigns } from "@/features/editor-signs/register"; import { changesField, compareTextField, setChangesEffect, setCompareTextEffect, -} from "@/editor/signs/state"; -import { computeHunks, hunkSegments } from "@/sync/hunks"; +} from "@/features/editor-signs/state"; +import { computeHunks, hunkSegments } from "@/features/sync/hunks/hunks"; const marksOf = (baseline: Text, current: Text): ChangeMark[] => markedChanges(baseline, current).map(({ mark }) => mark); @@ -195,10 +196,17 @@ describe("signs helpers", () => { }); describe("signs gutter field", () => { + beforeAll(() => { + vi.stubGlobal("createDiv", ({ cls }: { cls: string }) => ({ + className: cls, + })); + }); + afterAll(() => vi.unstubAllGlobals()); + function stateWithSigns(doc: string, baseline: string): EditorState { const initial = EditorState.create({ doc, - extensions: [compareTextField, changesField, signsField], + extensions: [compareTextField, changesField, hunkFocusField, signsField], }); const withBaseline = initial.update({ effects: setCompareTextEffect.of(toCmText(baseline)), @@ -228,6 +236,25 @@ describe("signs gutter field", () => { } }); + it.each([ + ["add", "a\n", "a\nb\n"], + ["change", "one\ntwo\n", "one\nTWO\n"], + ["delete", "a\nb\n", "a\n"], + ["topdelete", "a\nb\n", "b\n"], + ["changedelete", "a\nb\nc\n", "a\nB\n"], + ])("draws a %s sign with its class", (kind, baseline, current) => { + const state = stateWithSigns(current, baseline); + expect(signClasses(state)).toEqual([`mdsync-sign mdsync-sign-${kind}`]); + + const [first] = marks(baseline, current); + const wide = state.update({ + effects: focusHunk.of({ hover: first as ChangeMark }), + }).state; + expect(signClasses(wide)).toEqual([ + `mdsync-sign mdsync-sign-${kind} is-wide`, + ]); + }); + it("drops every marker once the baseline is cleared", () => { const state = stateWithSigns("one\nTWO\n", "one\ntwo\n"); const cleared = state.update({ @@ -237,6 +264,17 @@ describe("signs gutter field", () => { }); }); +function signClasses(state: EditorState): string[] { + const classes: string[] = []; + const cursor = state.field(signsField).iter(); + while (cursor.value) { + const node = cursor.value.toDOM?.({} as EditorView) as HTMLElement; + classes.push(node.className); + cursor.next(); + } + return classes; +} + function countMarkers(state: EditorState): number { let count = 0; const cursor = state.field(signsField).iter(); diff --git a/packages/plugin/tests/ui/file-explorer-decorations.test.ts b/packages/plugin/tests/features/explorer/file-explorer-decorations.test.ts similarity index 95% rename from packages/plugin/tests/ui/file-explorer-decorations.test.ts rename to packages/plugin/tests/features/explorer/file-explorer-decorations.test.ts index 2670dafd..859090e0 100644 --- a/packages/plugin/tests/ui/file-explorer-decorations.test.ts +++ b/packages/plugin/tests/features/explorer/file-explorer-decorations.test.ts @@ -2,17 +2,17 @@ import { ALEX, host, SAM } from "@tests/helpers/explorer-host"; import { Platform, setIcon } from "obsidian"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { PluginHost } from "@/plugin/host"; -import { badgeActivation } from "@/ui/explorer/file-explorer-badges"; +import type { PluginHost } from "@/app/host"; +import { badgeActivation } from "@/features/explorer/file-explorer-badges"; import { type PathDecoration, renderDecoration, sameDecoration, -} from "@/ui/explorer/file-explorer-decorations"; -import type { ShareMark } from "@/ui/explorer/file-explorer-marks"; -import { openManageLinks } from "@/ui/links"; +} from "@/features/explorer/file-explorer-decorations"; +import type { ShareMark } from "@/features/explorer/file-explorer-marks"; +import { openManageLinks } from "@/features/links/ui/link-menu"; -vi.mock("@/ui/links", () => ({ openManageLinks: vi.fn() })); +vi.mock("@/features/links/ui/link-menu", () => ({ openManageLinks: vi.fn() })); vi.mock("obsidian", async (original) => ({ ...(await original()), setIcon: vi.fn(), diff --git a/packages/plugin/tests/ui/file-explorer-indicators.test.ts b/packages/plugin/tests/features/explorer/file-explorer-indicators.test.ts similarity index 91% rename from packages/plugin/tests/ui/file-explorer-indicators.test.ts rename to packages/plugin/tests/features/explorer/file-explorer-indicators.test.ts index 3c4bd500..e2b8619a 100644 --- a/packages/plugin/tests/ui/file-explorer-indicators.test.ts +++ b/packages/plugin/tests/features/explorer/file-explorer-indicators.test.ts @@ -1,15 +1,14 @@ import { ALEX, host, LINK } from "@tests/helpers/explorer-host"; import type { Plugin, TAbstractFile } from "obsidian"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -import { SharedLinks } from "@/links"; -import type { PluginHost } from "@/plugin/host"; -import type { SyncController } from "@/sync/controller"; -import { type Space, VAULT_SPACE } from "@/sync/space"; -import { renderDecoration } from "@/ui/explorer/file-explorer-decorations"; -import { registerFileExplorerIndicators } from "@/ui/explorer/file-explorer-indicators"; - -vi.mock("@/ui/explorer/file-explorer-decorations", async (original) => ({ +import type { PluginHost } from "@/app/host"; +import { renderDecoration } from "@/features/explorer/file-explorer-decorations"; +import { registerFileExplorerIndicators } from "@/features/explorer/file-explorer-indicators"; +import { SharedLinks } from "@/features/links/shared-links"; +import type { SyncController } from "@/features/sync/controller"; +import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; + +vi.mock("@/features/explorer/file-explorer-decorations", async (original) => ({ ...(await original()), renderDecoration: vi.fn(), clearDecoration: vi.fn(), diff --git a/packages/plugin/tests/ui/file-explorer-marks.test.ts b/packages/plugin/tests/features/explorer/file-explorer-marks.test.ts similarity index 95% rename from packages/plugin/tests/ui/file-explorer-marks.test.ts rename to packages/plugin/tests/features/explorer/file-explorer-marks.test.ts index d7ae3787..2a2e4e24 100644 --- a/packages/plugin/tests/ui/file-explorer-marks.test.ts +++ b/packages/plugin/tests/features/explorer/file-explorer-marks.test.ts @@ -1,8 +1,10 @@ import { ALEX, host, LAPTOP, LINK, SAM } from "@tests/helpers/explorer-host"; import { describe, expect, it, vi } from "vitest"; - -import { type Space, VAULT_SPACE } from "@/sync/space"; -import { presenceMarks, shareMarks } from "@/ui/explorer/file-explorer-marks"; +import { + presenceMarks, + shareMarks, +} from "@/features/explorer/file-explorer-marks"; +import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; describe("presence in the file explorer", () => { const spaces: Space[] = [ diff --git a/packages/plugin/tests/ui/link-scan.test.ts b/packages/plugin/tests/features/explorer/link-scan.test.ts similarity index 87% rename from packages/plugin/tests/ui/link-scan.test.ts rename to packages/plugin/tests/features/explorer/link-scan.test.ts index b9718e30..e900e40a 100644 --- a/packages/plugin/tests/ui/link-scan.test.ts +++ b/packages/plugin/tests/features/explorer/link-scan.test.ts @@ -1,10 +1,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { createSymlinkDetector } from "@/core/vault/symlinks"; +import type { FileExplorerRows } from "@/features/explorer/file-explorer-api"; +import { LinkScan } from "@/features/explorer/link-scan"; -import type { FileExplorerRows } from "@/ui/explorer/file-explorer-api"; -import { LinkScan } from "@/ui/explorer/link-scan"; -import { createSymlinkDetector } from "@/vault/symlinks"; - -vi.mock("@/vault/symlinks", () => ({ createSymlinkDetector: vi.fn() })); +vi.mock("@/core/vault/symlinks", () => ({ createSymlinkDetector: vi.fn() })); const frames = new Map(); let nextFrame = 0; @@ -54,7 +53,7 @@ describe("incremental explorer link scans", () => { frame(); expect(detector.findLink).toHaveBeenCalledOnce(); expect(detector.findLink).toHaveBeenCalledWith("notes/new.md"); - expect([...scan.links.keys()]).toEqual(["notes/0.md"]); + expect([...scan.links]).toEqual(["notes/0.md"]); }); it("retains published links when a change interrupts a multi-frame scan", () => { @@ -81,7 +80,7 @@ describe("incremental explorer link scans", () => { scan.invalidate("Moved"); scan.scan(); frame(); - expect([...scan.links.keys()]).toEqual(["Moved/alias.md"]); + expect([...scan.links]).toEqual(["Moved/alias.md"]); expect(detector.invalidate.mock.calls).toEqual([["notes"], ["Moved"]]); expect(detector.findLink).toHaveBeenCalledOnce(); }); diff --git a/packages/plugin/tests/ui/row-decorator.test.ts b/packages/plugin/tests/features/explorer/row-decorator.test.ts similarity index 92% rename from packages/plugin/tests/ui/row-decorator.test.ts rename to packages/plugin/tests/features/explorer/row-decorator.test.ts index b625b4f2..5485dbff 100644 --- a/packages/plugin/tests/ui/row-decorator.test.ts +++ b/packages/plugin/tests/features/explorer/row-decorator.test.ts @@ -1,18 +1,17 @@ import { ALEX, host, LINK, SAM } from "@tests/helpers/explorer-host"; import { beforeEach, describe, expect, it, vi } from "vitest"; - -import type { Person } from "@/presence/people"; -import type { SyncController } from "@/sync/controller"; -import { type Space, VAULT_SPACE } from "@/sync/space"; -import { EChangeType, type Move } from "@/sync/types"; -import type { FileExplorerRows } from "@/ui/explorer/file-explorer-api"; +import type { FileExplorerRows } from "@/features/explorer/file-explorer-api"; import { clearDecoration, renderDecoration, -} from "@/ui/explorer/file-explorer-decorations"; -import { RowDecorator } from "@/ui/explorer/row-decorator"; - -vi.mock("@/ui/explorer/file-explorer-decorations", async (original) => ({ +} from "@/features/explorer/file-explorer-decorations"; +import { RowDecorator } from "@/features/explorer/row-decorator"; +import type { Person } from "@/features/presence/people"; +import type { SyncController } from "@/features/sync/controller"; +import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; +import { EChangeType, type Move } from "@/features/sync/types"; + +vi.mock("@/features/explorer/file-explorer-decorations", async (original) => ({ ...(await original()), renderDecoration: vi.fn(), clearDecoration: vi.fn(), @@ -54,7 +53,7 @@ function setup(people: Person[] = [ALEX], unseen: string[] = []) { collapsed: (path) => folded.has(path), }; const decorator = new RowDecorator(plugin, controller); - let links: ReadonlyMap = new Map(); + let links: ReadonlySet = new Set(); return { plugin, decorator, @@ -71,7 +70,7 @@ function setup(people: Person[] = [ALEX], unseen: string[] = []) { statuses = next; result = { diff: { moves }, snapshot: { skipped: [] } }; }, - setLinks: (next: ReadonlyMap) => { + setLinks: (next: ReadonlySet) => { links = next; }, setPartition: (next: Space[]) => { @@ -244,7 +243,7 @@ describe("the base layer", () => { "the diff", (rig) => rig.setStatuses(new Map([[CHANGED, EChangeType.LocalDelete]])), ], - ["the links", (rig) => rig.setLinks(new Map([["Team/link", "Team/link"]]))], + ["the links", (rig) => rig.setLinks(new Set(["Team/link"]))], ["the ignore rules", (rig) => rig.decorator.ignoredChanged()], ["the partition", (rig) => rig.setPartition([...SPACES])], ]; diff --git a/packages/plugin/tests/links/describe.test.ts b/packages/plugin/tests/features/links/describe.test.ts similarity index 98% rename from packages/plugin/tests/links/describe.test.ts rename to packages/plugin/tests/features/links/describe.test.ts index baf5961a..4d3e20ac 100644 --- a/packages/plugin/tests/links/describe.test.ts +++ b/packages/plugin/tests/features/links/describe.test.ts @@ -8,8 +8,8 @@ import { leftOutText, linkStatusText, resolveExpiry, -} from "@/links/describe"; -import type { LinkRecord } from "@/links/record"; +} from "@/features/links/describe"; +import type { LinkRecord } from "@/features/links/record"; const MS_PER_S = 1000; const MINUTE_MS = 60 * MS_PER_S; diff --git a/packages/plugin/tests/links/errors.test.ts b/packages/plugin/tests/features/links/errors.test.ts similarity index 87% rename from packages/plugin/tests/links/errors.test.ts rename to packages/plugin/tests/features/links/errors.test.ts index f4baa560..421ec017 100644 --- a/packages/plugin/tests/links/errors.test.ts +++ b/packages/plugin/tests/features/links/errors.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { linkError } from "@/links/errors"; -import { StorageRequestError } from "@/storage"; +import { linkError } from "@/features/links/errors"; +import { StorageRequestError } from "@/features/storage/types"; describe("linkError", () => { it("uses the storage refusal's user-facing message", () => { diff --git a/packages/plugin/tests/storage/link-broker.test.ts b/packages/plugin/tests/features/links/link-broker.test.ts similarity index 97% rename from packages/plugin/tests/storage/link-broker.test.ts rename to packages/plugin/tests/features/links/link-broker.test.ts index 16a7c93a..24a2abae 100644 --- a/packages/plugin/tests/storage/link-broker.test.ts +++ b/packages/plugin/tests/features/links/link-broker.test.ts @@ -1,13 +1,13 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; +import { StorageHttpError } from "@/core/shared/transport-errors"; import { createLink, linkStatus, type NewLink, replaceLink, revokeLink, -} from "@/storage/adapters/link-broker"; -import { StorageHttpError } from "@/storage/adapters/util"; -import { StorageRequestError } from "@/storage/types"; +} from "@/features/links/link-broker"; +import { StorageRequestError } from "@/features/storage/types"; interface Recorded { url: string; diff --git a/packages/plugin/tests/links/publish.test.ts b/packages/plugin/tests/features/links/publish.test.ts similarity index 95% rename from packages/plugin/tests/links/publish.test.ts rename to packages/plugin/tests/features/links/publish.test.ts index 1a27b2f9..13fffa23 100644 --- a/packages/plugin/tests/links/publish.test.ts +++ b/packages/plugin/tests/features/links/publish.test.ts @@ -14,7 +14,13 @@ import { } from "@mdsync/protocol"; import { TFile } from "obsidian"; import { assert, beforeEach, describe, expect, it, vi } from "vitest"; -import { noteText } from "@/links/note-text"; +import type { PluginHost } from "@/app/host"; +import { + createLink, + linkStatus, + replaceLink, + revokeLink, +} from "@/features/links/link-broker"; import { linkStatusOf, previewLink, @@ -23,22 +29,26 @@ import { type ShareOptions, TOO_LARGE, updateLink, -} from "@/links/publish"; -import type { LinkRecord } from "@/links/record"; -import { SharedLinks } from "@/links/shared-links"; -import { type Snapshot, takeSnapshot } from "@/links/snapshot"; -import type { PluginHost } from "@/plugin/host"; -import { createLink, linkStatus, replaceLink, revokeLink } from "@/storage"; - -vi.mock("@/storage", async (original) => ({ - ...(await original()), +} from "@/features/links/publish"; +import type { LinkRecord } from "@/features/links/record"; +import { SharedLinks } from "@/features/links/shared-links"; +import { noteText } from "@/features/links/snapshot/note-text"; +import { + type Snapshot, + takeSnapshot, +} from "@/features/links/snapshot/snapshot"; + +vi.mock("@/features/links/link-broker", async (original) => ({ + ...(await original()), createLink: vi.fn(async () => 2_000_000_000), replaceLink: vi.fn(async () => {}), linkStatus: vi.fn(async () => null), revokeLink: vi.fn(async () => {}), })); -vi.mock("@/links/snapshot", () => ({ takeSnapshot: vi.fn() })); -vi.mock("@/links/note-text", () => ({ noteText: vi.fn() })); +vi.mock("@/features/links/snapshot/snapshot", () => ({ + takeSnapshot: vi.fn(), +})); +vi.mock("@/features/links/snapshot/note-text", () => ({ noteText: vi.fn() })); const relay = "https://relay.example"; const admin = { relayUrl: relay, secret: "secret" }; diff --git a/packages/plugin/tests/links/record.test.ts b/packages/plugin/tests/features/links/record.test.ts similarity index 99% rename from packages/plugin/tests/links/record.test.ts rename to packages/plugin/tests/features/links/record.test.ts index 9558671c..7dd5ab21 100644 --- a/packages/plugin/tests/links/record.test.ts +++ b/packages/plugin/tests/features/links/record.test.ts @@ -8,7 +8,7 @@ import { parseTradedLink, renamedLinks, tradedLink, -} from "@/links/record"; +} from "@/features/links/record"; const record: LinkRecord = { id: "abcdefghijklmnopqrstuv", diff --git a/packages/plugin/tests/links/remote.test.ts b/packages/plugin/tests/features/links/remote.test.ts similarity index 95% rename from packages/plugin/tests/links/remote.test.ts rename to packages/plugin/tests/features/links/remote.test.ts index a8fc3775..174d46a9 100644 --- a/packages/plugin/tests/links/remote.test.ts +++ b/packages/plugin/tests/features/links/remote.test.ts @@ -9,12 +9,12 @@ import { deriveKey, type EncryptionKey, encryptJson, -} from "@/crypto"; -import type { LinkRecord } from "@/links/record"; -import { tradeLinks } from "@/links/remote"; -import { syncRecords } from "@/spaces/remote"; +} from "@/core/crypto/cipher"; +import type { LinkRecord } from "@/features/links/record"; +import { tradeLinks } from "@/features/links/remote"; +import { syncRecords } from "@/features/spaces/remote"; -vi.mock("@/shared/diagnostics", async (importOriginal) => ({ +vi.mock("@/core/shared/diagnostics", async (importOriginal) => ({ ...(await importOriginal>()), reportWarning: vi.fn(), })); diff --git a/packages/plugin/tests/links/shared-links.test.ts b/packages/plugin/tests/features/links/shared-links.test.ts similarity index 97% rename from packages/plugin/tests/links/shared-links.test.ts rename to packages/plugin/tests/features/links/shared-links.test.ts index 407354e8..01d80083 100644 --- a/packages/plugin/tests/links/shared-links.test.ts +++ b/packages/plugin/tests/features/links/shared-links.test.ts @@ -1,17 +1,16 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { link, linkDevice, linkId } from "@tests/helpers/shared-links"; import { beforeAll, describe, expect, it, vi } from "vitest"; - +import type { PluginHost } from "@/app/host"; import { decryptJson, deriveKey, type EncryptionKey, encryptJson, -} from "@/crypto"; -import { noteLinks, noteLinksText } from "@/links/note-links"; -import type { StoredLink } from "@/links/record"; -import { SharedLinks } from "@/links/shared-links"; -import type { PluginHost } from "@/plugin/host"; +} from "@/core/crypto/cipher"; +import { noteLinks, noteLinksText } from "@/features/links/note-links"; +import type { StoredLink } from "@/features/links/record"; +import { SharedLinks } from "@/features/links/shared-links"; const PUBLISHED = 1_760_000_000_000; const VAULT = "vault"; diff --git a/packages/plugin/tests/links/fixtures/rendered-note.html b/packages/plugin/tests/features/links/snapshot/fixtures/rendered-note.html similarity index 100% rename from packages/plugin/tests/links/fixtures/rendered-note.html rename to packages/plugin/tests/features/links/snapshot/fixtures/rendered-note.html diff --git a/packages/plugin/tests/links/images.test.ts b/packages/plugin/tests/features/links/snapshot/images.test.ts similarity index 98% rename from packages/plugin/tests/links/images.test.ts rename to packages/plugin/tests/features/links/snapshot/images.test.ts index d38d7082..05882149 100644 --- a/packages/plugin/tests/links/images.test.ts +++ b/packages/plugin/tests/features/links/snapshot/images.test.ts @@ -1,7 +1,7 @@ // @vitest-environment jsdom import type { App, TFile } from "obsidian"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { IMAGE_MAX_BYTES, inlineImage } from "@/links/images"; +import { IMAGE_MAX_BYTES, inlineImage } from "@/features/links/snapshot/images"; const sourcePath = "notes/Trip.md"; diff --git a/packages/plugin/tests/links/math.test.ts b/packages/plugin/tests/features/links/snapshot/math.test.ts similarity index 97% rename from packages/plugin/tests/links/math.test.ts rename to packages/plugin/tests/features/links/snapshot/math.test.ts index f4f383de..a77f1f8d 100644 --- a/packages/plugin/tests/links/math.test.ts +++ b/packages/plugin/tests/features/links/snapshot/math.test.ts @@ -2,7 +2,7 @@ import { installElementFactories } from "@tests/helpers/obsidian-dom"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { mathToMathML, tagMathSources } from "@/links/math"; +import { mathToMathML, tagMathSources } from "@/features/links/snapshot/math"; installElementFactories(); diff --git a/packages/plugin/tests/links/sanitize.test.ts b/packages/plugin/tests/features/links/snapshot/sanitize.test.ts similarity index 99% rename from packages/plugin/tests/links/sanitize.test.ts rename to packages/plugin/tests/features/links/snapshot/sanitize.test.ts index 9ddba976..8ca192f9 100644 --- a/packages/plugin/tests/links/sanitize.test.ts +++ b/packages/plugin/tests/features/links/snapshot/sanitize.test.ts @@ -3,7 +3,10 @@ import { readFileSync } from "node:fs"; import { URL as NodeURL } from "node:url"; import { installElementFactories } from "@tests/helpers/obsidian-dom"; import { beforeEach, describe, expect, it } from "vitest"; -import { type SanitizeReport, sanitizeRendered } from "@/links/sanitize"; +import { + type SanitizeReport, + sanitizeRendered, +} from "@/features/links/snapshot/sanitize"; installElementFactories(); diff --git a/packages/plugin/tests/ui/link-actions.test.ts b/packages/plugin/tests/features/links/ui/link-actions.test.ts similarity index 84% rename from packages/plugin/tests/ui/link-actions.test.ts rename to packages/plugin/tests/features/links/ui/link-actions.test.ts index 7ae0a28b..7b649370 100644 --- a/packages/plugin/tests/ui/link-actions.test.ts +++ b/packages/plugin/tests/features/links/ui/link-actions.test.ts @@ -1,56 +1,52 @@ +import { linkRecord } from "@tests/helpers/shared-links"; import type { Command, Plugin } from "obsidian"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { registerCommands } from "@/commands"; -import { type LinkRecord, SharedLinks, updateLink } from "@/links"; -import type { PluginHost } from "@/plugin/host"; -import { notifyError, notifyInfo } from "@/ui/common"; -import { updateSharedLinks } from "@/ui/links/link-actions"; -import { openPromptModal } from "@/ui/modals"; +import { registerCommands } from "@/app/commands"; +import type { PluginHost } from "@/app/host"; +import { openPromptModal } from "@/core/ui/modals/prompt-modal"; +import { notifyError, notifyInfo } from "@/core/ui/notices"; +import { updateLink } from "@/features/links/publish"; +import type { LinkRecord } from "@/features/links/record"; +import { SharedLinks } from "@/features/links/shared-links"; +import { updateSharedLinks } from "@/features/links/ui/link-actions"; -vi.mock("@/links", async (original) => ({ - ...(await original()), +vi.mock("@/features/links/publish", async (original) => ({ + ...(await original()), updateLink: vi.fn(async () => {}), })); -vi.mock("@/ui/common", () => ({ notifyInfo: vi.fn(), notifyError: vi.fn() })); -vi.mock("@/ui/modals", () => ({ openPromptModal: vi.fn() })); -vi.mock("@/ui", async () => ({ - ...(await import("@/ui/common")), - ...(await import("@/ui/links/link-actions")), +vi.mock("@/core/ui/notices", () => ({ + notifyInfo: vi.fn(), + notifyError: vi.fn(), + runWithNotice: vi.fn(), +})); +vi.mock("@/core/ui/modals/prompt-modal", () => ({ openPromptModal: vi.fn() })); +vi.mock("@/features/note-header/note-menu-items", () => ({ canRebuild: vi.fn(), - deepCleanOrphanedObjects: vi.fn(), +})); +vi.mock("@/features/note-header/live-actions", () => ({ + rebuildLiveNote: vi.fn(), + toggleAuthors: vi.fn(), +})); +vi.mock("@/features/links/ui/link-menu", () => ({ isLinkable: vi.fn(), - openDiffView: vi.fn(), - openInvite: vi.fn(), openManageLinks: vi.fn(), openShareLink: vi.fn(), +})); +vi.mock("@/features/spaces/ui/invites/invite-action", () => ({ + openInvite: vi.fn(), +})); +vi.mock("@/features/spaces/ui/window/share-window", () => ({ openShareWindow: vi.fn(), - openSourceControlDeleted: vi.fn(), - openSourceControlHistory: vi.fn(), - openSourceControlView: vi.fn(), - openWhereMenu: vi.fn(), - rebuildLiveNote: vi.fn(), +})); +vi.mock("@/features/sync/ui/maintenance-actions", () => ({ + deepCleanOrphanedObjects: vi.fn(), + resetLocalState: vi.fn(), resetRemoteStorage: vi.fn(), - runWithNotice: vi.fn(), - toggleAuthors: vi.fn(), verifyRemoteIntegrity: vi.fn(), })); -const RECORD: LinkRecord = { - id: "one", - url: "https://relay.example/one", - rev: 0, - author: "", - path: "note.md", - showTitle: true, - detached: false, - createdAt: 1, - publishedAt: 1, - expires: null, - maxViews: null, - salt: null, - images: false, -}; +const RECORD = linkRecord(); function host(records: LinkRecord[] = [RECORD]) { let file: { path: string } | null = { path: RECORD.path }; diff --git a/packages/plugin/tests/ui/link-menu.test.ts b/packages/plugin/tests/features/links/ui/link-menu.test.ts similarity index 94% rename from packages/plugin/tests/ui/link-menu.test.ts rename to packages/plugin/tests/features/links/ui/link-menu.test.ts index f798d6e6..5d66ad2c 100644 --- a/packages/plugin/tests/ui/link-menu.test.ts +++ b/packages/plugin/tests/features/links/ui/link-menu.test.ts @@ -1,7 +1,7 @@ import { type App, type CachedMetadata, TFile, TFolder } from "obsidian"; import { describe, expect, it } from "vitest"; -import { isLinkable } from "@/ui/links/link-menu"; +import { isLinkable } from "@/features/links/ui/link-menu"; function appWith(cache: CachedMetadata | null): App { return { metadataCache: { getFileCache: () => cache } } as unknown as App; diff --git a/packages/plugin/tests/ui/manage-links-modal.test.ts b/packages/plugin/tests/features/links/ui/manage-links-modal.test.ts similarity index 63% rename from packages/plugin/tests/ui/manage-links-modal.test.ts rename to packages/plugin/tests/features/links/ui/manage-links-modal.test.ts index 0e982f9f..583b9eeb 100644 --- a/packages/plugin/tests/ui/manage-links-modal.test.ts +++ b/packages/plugin/tests/features/links/ui/manage-links-modal.test.ts @@ -1,114 +1,64 @@ import type { LinkStatus } from "@mdsync/protocol"; +import { linkRecord } from "@tests/helpers/shared-links"; +import type { + ButtonComponent, + ExtraButtonComponent, + Setting, +} from "@tests/stubs/obsidian"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -import { type LinkRecord, linkStatusOf, SharedLinks } from "@/links"; -import type { PluginHost } from "@/plugin/host"; -import { updateSharedLinks } from "@/ui/links/link-actions"; -import { ManageLinksModal } from "@/ui/links/manage-links-modal"; - -vi.mock("@/links", async (original) => ({ - ...(await original()), +import type { PluginHost } from "@/app/host"; +import { linkStatusOf } from "@/features/links/publish"; +import { SharedLinks } from "@/features/links/shared-links"; +import { updateSharedLinks } from "@/features/links/ui/link-actions"; +import { ManageLinksModal } from "@/features/links/ui/manage-links-modal"; + +vi.mock("@/features/links/publish", async (original) => ({ + ...(await original()), linkStatusOf: vi.fn(async () => null), })); -vi.mock("@/ui/links/link-actions", () => ({ +vi.mock("@/features/links/ui/link-actions", () => ({ updateSharedLinks: vi.fn(async () => {}), })); -vi.mock("@/ui/modals", () => ({ openConfirmModal: vi.fn() })); -vi.mock("@/ui/common", async () => ({ - serial: (await import("@/ui/common/serial")).serial, - copyText: vi.fn(), - notifyError: vi.fn(), +vi.mock("@/core/ui/modals/confirm-modal", () => ({ + openConfirmModal: vi.fn(), +})); +vi.mock("@/core/ui/controls/copyable", () => ({ copyText: vi.fn() })); +vi.mock("@/core/ui/notices", () => ({ notifyError: vi.fn() })); +vi.mock("@/core/ui/modal-frame", () => ({ renderModalHead: vi.fn(), modalFooter: vi.fn(), modalHint: vi.fn(), modalCard: vi.fn(), })); -vi.mock("obsidian", () => ({ - Modal: class { - modalEl = { addClass: () => {} }; - contentEl = { - empty: () => { - rows.length = 0; - }, - createEl: () => {}, - }; - constructor(readonly app: object) {} - }, - ButtonComponent: class { - setButtonText() { - return this; - } - onClick() { - return this; - } - }, - Setting: class { - name = ""; - desc = ""; - descEl = { createDiv: () => {} }; - buttons: Button[] = []; - constructor() { - rows.push(this); - } - setName(name: string) { - this.name = name; - return this; - } - setDesc(desc: string) { - this.desc = desc; - return this; - } - addButton(build: (button: Button) => void) { - const button = new Button(); - build(button); - this.buttons.push(button); - return this; - } - addExtraButton(build: (button: Button) => void) { - return this.addButton(build); - } - }, -})); - -class Button { - text = ""; - click: () => Promise = async () => {}; - setButtonText(text: string) { - this.text = text; - return this; - } - setTooltip(text: string) { - this.text = text; - return this; - } - setIcon() { - return this; - } - setDisabled() { - return this; - } - onClick(click: () => Promise) { - this.click = click; - return this; - } -} +vi.mock("obsidian", async (original) => { + const actual = await original(); + return { + ...actual, + Modal: class extends actual.Modal { + constructor(app: unknown) { + super(app); + // A redraw empties the list: the rows drawn before it are gone. + this.contentEl.empty = () => { + rows.length = 0; + }; + } + }, + Setting: class extends actual.Setting { + constructor(containerEl?: unknown) { + super(containerEl); + rows.push(this); + } + }, + }; +}); -const rows: { name: string; desc: string; buttons: Button[] }[] = []; -const RECORD: LinkRecord = { - id: "one", - url: "https://relay.example/one", - rev: 0, - author: "", - path: "note.md", - showTitle: true, - detached: false, - createdAt: 1, - publishedAt: 1, - expires: null, - maxViews: null, - salt: null, - images: false, -}; +const rows: Setting[] = []; +const RECORD = linkRecord(); +const labelOf = (button: ButtonComponent | ExtraButtonComponent) => + "text" in button ? button.text : button.tooltip; +const labels = (row: Setting | undefined) => row?.buttons.map(labelOf); +const press = (row: Setting | undefined, label: string) => + row?.buttons.find((button) => labelOf(button) === label)?.click(); const LIVE: LinkStatus = { views: 0, maxViews: null, @@ -162,18 +112,13 @@ describe("ManageLinksModal", () => { await vi.waitFor(() => expect(rows[0]?.desc).toContain("never expires")); expect(rows[0]?.name).toBe("note"); expect(rows[0]?.desc).toBe("The note was deleted. 0 views · never expires"); - expect(rows[0]?.buttons.map(({ text }) => text)).toEqual([ - "Copy link", - "Stop sharing", - ]); + expect(labels(rows[0])).toEqual(["Copy link", "Stop sharing"]); }); it("draws a record with a damaged address and still offers its removal", () => { host(null, [{ ...RECORD, url: "not a URL" }, RECORD]); expect(rows).toHaveLength(2); expect(rows[0]?.desc).toContain("address is damaged"); - expect(rows[0]?.buttons.map(({ text }) => text)).toEqual([ - "Remove from the list", - ]); + expect(labels(rows[0])).toEqual(["Remove from the list"]); }); it("starts changed notes with the stale line and keeps the status copy", async () => { @@ -205,7 +150,7 @@ describe("ManageLinksModal", () => { vi.mocked(updateSharedLinks).mockImplementationOnce(async () => { expect(linkStatusOf).not.toHaveBeenCalled(); }); - await rows[0]?.buttons.find(({ text }) => text === "Update")?.click(); + await press(rows[0], "Update"); expect(updateSharedLinks).toHaveBeenCalledExactlyOnceWith(plugin, [RECORD]); expect(linkStatusOf).toHaveBeenCalledExactlyOnceWith(plugin, RECORD); }); @@ -215,7 +160,7 @@ describe("ManageLinksModal", () => { vi.useFakeTimers({ now, toFake: ["Date", "setTimeout", "clearTimeout"] }); vi.mocked(linkStatusOf).mockResolvedValue(LIVE); host(1, [{ ...RECORD, expires: now / 1000 + 60 }]); - const actions = () => rows[0]?.buttons.map(({ text }) => text); + const actions = () => labels(rows[0]); await vi.waitFor(() => expect(actions()).toContain("Update")); vi.advanceTimersByTime(60_000); @@ -231,7 +176,7 @@ describe("ManageLinksModal", () => { if (note) note.path = "moved.md"; await sharedLinks.move(RECORD.path, "moved.md"); expect(rows).toHaveLength(1); - await rows[0]?.buttons.find(({ text }) => text === "Update")?.click(); + await press(rows[0], "Update"); expect(updateSharedLinks).toHaveBeenCalledWith(plugin, [ { ...RECORD, @@ -245,9 +190,7 @@ describe("ManageLinksModal", () => { it("removes an ended link through SharedLinks", async () => { const { sharedLinks } = host(1); await vi.waitFor(() => expect(rows[0]?.desc).toContain("Ended:")); - await rows[0]?.buttons - .find(({ text }) => text === "Remove from the list") - ?.click(); + await press(rows[0], "Remove from the list"); expect(sharedLinks.all()).toEqual([]); }); }); diff --git a/packages/plugin/tests/ui/note-link-action.test.ts b/packages/plugin/tests/features/links/ui/note-link-action.test.ts similarity index 88% rename from packages/plugin/tests/ui/note-link-action.test.ts rename to packages/plugin/tests/features/links/ui/note-link-action.test.ts index 9170e56e..4cb22f54 100644 --- a/packages/plugin/tests/ui/note-link-action.test.ts +++ b/packages/plugin/tests/features/links/ui/note-link-action.test.ts @@ -1,28 +1,14 @@ +import { linkRecord } from "@tests/helpers/shared-links"; import { FileView, type Plugin } from "obsidian"; import { describe, expect, it, vi } from "vitest"; +import type { PluginHost } from "@/app/host"; +import { SharedLinks } from "@/features/links/shared-links"; +import { openManageLinks } from "@/features/links/ui/link-menu"; +import { registerNoteLinkActions } from "@/features/links/ui/note-link-action"; -import { type LinkRecord, SharedLinks } from "@/links"; -import type { PluginHost } from "@/plugin/host"; -import { openManageLinks } from "@/ui/links/link-menu"; -import { registerNoteLinkActions } from "@/ui/links/note-link-action"; +vi.mock("@/features/links/ui/link-menu", () => ({ openManageLinks: vi.fn() })); -vi.mock("@/ui/links/link-menu", () => ({ openManageLinks: vi.fn() })); - -const RECORD: LinkRecord = { - id: "one", - url: "https://relay.example/one", - rev: 0, - author: "", - path: "note.md", - showTitle: true, - detached: false, - createdAt: 1, - publishedAt: 1, - expires: null, - maxViews: null, - salt: null, - images: false, -}; +const RECORD = linkRecord(); class Action { parentElement: object | null = {}; diff --git a/packages/plugin/tests/ui/preview-frame.test.ts b/packages/plugin/tests/features/links/ui/preview-frame.test.ts similarity index 89% rename from packages/plugin/tests/ui/preview-frame.test.ts rename to packages/plugin/tests/features/links/ui/preview-frame.test.ts index 852c1c8f..75582448 100644 --- a/packages/plugin/tests/ui/preview-frame.test.ts +++ b/packages/plugin/tests/features/links/ui/preview-frame.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { previewDocument } from "@/ui/links/preview-frame"; +import { previewDocument } from "@/features/links/ui/preview-frame"; describe("previewDocument", () => { it("wraps the note under a policy that allows no script and no remote style", () => { diff --git a/packages/plugin/tests/live/authors.test.ts b/packages/plugin/tests/features/live/authors.test.ts similarity index 93% rename from packages/plugin/tests/live/authors.test.ts rename to packages/plugin/tests/features/live/authors.test.ts index 623ba170..738e8c51 100644 --- a/packages/plugin/tests/live/authors.test.ts +++ b/packages/plugin/tests/features/live/authors.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from "vitest"; import * as Y from "yjs"; -import { authorOf, authorRanges, USERS } from "@/live/authors"; -import { BODY } from "@/live/text/rebuild"; +import { authorOf, authorRanges, USERS } from "@/features/live/authors"; +import { BODY } from "@/features/live/text/rebuild"; const OWNER = { person: "owner", name: "Owner" }; const FRIEND = { person: "p1", name: "Friend" }; diff --git a/packages/plugin/tests/live/agreed-texts.test.ts b/packages/plugin/tests/features/live/cold/agreed-texts.test.ts similarity index 98% rename from packages/plugin/tests/live/agreed-texts.test.ts rename to packages/plugin/tests/features/live/cold/agreed-texts.test.ts index 3b8d54bf..bcfd0d11 100644 --- a/packages/plugin/tests/live/agreed-texts.test.ts +++ b/packages/plugin/tests/features/live/cold/agreed-texts.test.ts @@ -2,7 +2,7 @@ import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; import type { DataAdapter } from "obsidian"; import { describe, expect, it, vi } from "vitest"; -import { AgreedTexts } from "@/live/cold/agreed-texts"; +import { AgreedTexts } from "@/features/live/cold/agreed-texts"; const DIR = ".obsidian/plugins/mdsync/live"; diff --git a/packages/plugin/tests/live/doc-id.test.ts b/packages/plugin/tests/features/live/doc-id.test.ts similarity index 91% rename from packages/plugin/tests/live/doc-id.test.ts rename to packages/plugin/tests/features/live/doc-id.test.ts index 6ad30955..701312d5 100644 --- a/packages/plugin/tests/live/doc-id.test.ts +++ b/packages/plugin/tests/features/live/doc-id.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vitest"; -import { deriveLiveKeys } from "@/crypto/live-keys"; -import { docIdFor } from "@/live/doc-id"; +import { deriveLiveKeys } from "@/core/crypto/live-keys"; +import { docIdFor } from "@/features/live/doc-id"; function dataKey(): Uint8Array { return crypto.getRandomValues(new Uint8Array(32)); diff --git a/packages/plugin/tests/live/doc-types.test.ts b/packages/plugin/tests/features/live/doc-types.test.ts similarity index 94% rename from packages/plugin/tests/live/doc-types.test.ts rename to packages/plugin/tests/features/live/doc-types.test.ts index 7d0e0ff6..1af7f1b3 100644 --- a/packages/plugin/tests/live/doc-types.test.ts +++ b/packages/plugin/tests/features/live/doc-types.test.ts @@ -1,7 +1,7 @@ import { type App, type CachedMetadata, TFile } from "obsidian"; import { describe, expect, it } from "vitest"; -import { docKindOf, liveKindOf } from "@/live/doc-types"; +import { docKindOf, liveKindOf } from "@/features/live/doc-types"; function appWith(cache: CachedMetadata | null): App { return { metadataCache: { getFileCache: () => cache } } as unknown as App; diff --git a/packages/plugin/tests/live/drawing-binding-live.test.ts b/packages/plugin/tests/features/live/drawing/drawing-binding-live.test.ts similarity index 87% rename from packages/plugin/tests/live/drawing-binding-live.test.ts rename to packages/plugin/tests/features/live/drawing/drawing-binding-live.test.ts index 92a2ab7b..949d378b 100644 --- a/packages/plugin/tests/live/drawing-binding-live.test.ts +++ b/packages/plugin/tests/features/live/drawing/drawing-binding-live.test.ts @@ -11,12 +11,12 @@ import { import { LiveHub } from "@tests/helpers/live-hub"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { deriveLiveKeys } from "@/crypto/live-keys"; -import type { SceneElement } from "@/drawing"; -import { docIdFor } from "@/live/doc-id"; -import { bindDrawing } from "@/live/drawing/binding"; -import { DRAWING, type DrawingModel } from "@/live/drawing/model"; -import { LiveSession } from "@/live/session/session"; +import { deriveLiveKeys } from "@/core/crypto/live-keys"; +import type { SceneElement } from "@/core/drawing/format"; +import { docIdFor } from "@/features/live/doc-id"; +import { bindDrawing } from "@/features/live/drawing/binding"; +import { DRAWING, type DrawingModel } from "@/features/live/drawing/model"; +import { LiveSession } from "@/features/live/session/session"; useExcalidrawLib(); diff --git a/packages/plugin/tests/live/drawing-binding.test.ts b/packages/plugin/tests/features/live/drawing/drawing-binding.test.ts similarity index 97% rename from packages/plugin/tests/live/drawing-binding.test.ts rename to packages/plugin/tests/features/live/drawing/drawing-binding.test.ts index 7bbbb324..aa91f5f7 100644 --- a/packages/plugin/tests/live/drawing-binding.test.ts +++ b/packages/plugin/tests/features/live/drawing/drawing-binding.test.ts @@ -19,10 +19,10 @@ import { useExcalidrawLib, } from "@tests/helpers/drawing-view"; import { describe, expect, it, vi } from "vitest"; -import type { SceneElement } from "@/drawing"; -import { bindDrawing } from "@/live/drawing/binding"; -import type { DrawingModel } from "@/live/drawing/model"; -import type { LiveSession } from "@/live/session/session"; +import type { SceneElement } from "@/core/drawing/format"; +import { bindDrawing } from "@/features/live/drawing/binding"; +import type { DrawingModel } from "@/features/live/drawing/model"; +import type { LiveSession } from "@/features/live/session/session"; useExcalidrawLib(); diff --git a/packages/plugin/tests/live/drawing-model.test.ts b/packages/plugin/tests/features/live/drawing/drawing-model.test.ts similarity index 96% rename from packages/plugin/tests/live/drawing-model.test.ts rename to packages/plugin/tests/features/live/drawing/drawing-model.test.ts index df64aa6f..5fb4e4d8 100644 --- a/packages/plugin/tests/live/drawing-model.test.ts +++ b/packages/plugin/tests/features/live/drawing/drawing-model.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from "vitest"; import * as Y from "yjs"; -import type { SceneElement } from "@/drawing"; -import { DRAWING, elementsIn } from "@/live/drawing/model"; +import type { SceneElement } from "@/core/drawing/format"; +import { DRAWING, elementsIn } from "@/features/live/drawing/model"; function element(id: string, version = 1, isDeleted?: boolean): SceneElement { return { id, version, versionNonce: version, index: `a${id}`, isDeleted }; diff --git a/packages/plugin/tests/plugin/live-base.test.ts b/packages/plugin/tests/features/live/live-base.test.ts similarity index 94% rename from packages/plugin/tests/plugin/live-base.test.ts rename to packages/plugin/tests/features/live/live-base.test.ts index 6ca4bb24..7b22a09c 100644 --- a/packages/plugin/tests/plugin/live-base.test.ts +++ b/packages/plugin/tests/features/live/live-base.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vitest"; -import { baseTextOf } from "@/plugin/live"; -import { type Space, VAULT_SPACE } from "@/sync/space"; +import { baseTextOf } from "@/features/live/register"; +import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; const TEAM: Space = { id: "team", root: "Team" }; diff --git a/packages/plugin/tests/live/follower.test.ts b/packages/plugin/tests/features/live/session/follower.test.ts similarity index 92% rename from packages/plugin/tests/live/follower.test.ts rename to packages/plugin/tests/features/live/session/follower.test.ts index 66736d7c..a7d4fe04 100644 --- a/packages/plugin/tests/live/follower.test.ts +++ b/packages/plugin/tests/features/live/session/follower.test.ts @@ -13,13 +13,12 @@ import { encodeAwarenessUpdate, } from "y-protocols/awareness"; import * as Y from "yjs"; - -import type { SpaceFrame } from "@/hub/connection"; -import { docIdFor } from "@/live/doc-id"; -import { FollowerSession } from "@/live/session/follower-session"; -import { FOLLOWS, RoomAwareness } from "@/live/session/room-awareness"; -import type { Refused, Unfollowed } from "@/live/session/session-deps"; -import { TEXT, type TextModel } from "@/live/text/model"; +import type { SpaceFrame } from "@/core/hub"; +import { docIdFor } from "@/features/live/doc-id"; +import { FollowerSession } from "@/features/live/session/follower-session"; +import { FOLLOWS, RoomAwareness } from "@/features/live/session/room-awareness"; +import type { Refused, Unfollowed } from "@/features/live/session/session-deps"; +import { TEXT, type TextModel } from "@/features/live/text/model"; const live = useLiveRoom(); const { synced, roomState } = live; diff --git a/packages/plugin/tests/live/outbox.test.ts b/packages/plugin/tests/features/live/session/outbox.test.ts similarity index 98% rename from packages/plugin/tests/live/outbox.test.ts rename to packages/plugin/tests/features/live/session/outbox.test.ts index 65394e9c..170b08d7 100644 --- a/packages/plugin/tests/live/outbox.test.ts +++ b/packages/plugin/tests/features/live/session/outbox.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import * as Y from "yjs"; -import { Outbox } from "@/live/session/outbox"; +import { Outbox } from "@/features/live/session/outbox"; beforeEach(() => { vi.useFakeTimers(); diff --git a/packages/plugin/tests/live/room-awareness.test.ts b/packages/plugin/tests/features/live/session/room-awareness.test.ts similarity index 96% rename from packages/plugin/tests/live/room-awareness.test.ts rename to packages/plugin/tests/features/live/session/room-awareness.test.ts index 5ba45952..66f2f528 100644 --- a/packages/plugin/tests/live/room-awareness.test.ts +++ b/packages/plugin/tests/features/live/session/room-awareness.test.ts @@ -1,8 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import * as Y from "yjs"; -import { deriveLiveKeys } from "@/crypto/live-keys"; -import { ANNOUNCE_MS, RoomAwareness } from "@/live/session/room-awareness"; +import { deriveLiveKeys } from "@/core/crypto/live-keys"; +import { + ANNOUNCE_MS, + RoomAwareness, +} from "@/features/live/session/room-awareness"; beforeEach(() => { vi.useFakeTimers(); diff --git a/packages/plugin/tests/live/session-staged.test.ts b/packages/plugin/tests/features/live/session/session-staged.test.ts similarity index 96% rename from packages/plugin/tests/live/session-staged.test.ts rename to packages/plugin/tests/features/live/session/session-staged.test.ts index 55c7b71b..b44addeb 100644 --- a/packages/plugin/tests/live/session-staged.test.ts +++ b/packages/plugin/tests/features/live/session/session-staged.test.ts @@ -9,9 +9,9 @@ import { } from "@tests/helpers/live-session"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { docIdFor } from "@/live/doc-id"; -import { LiveSession } from "@/live/session/session"; -import { TEXT } from "@/live/text/model"; +import { docIdFor } from "@/features/live/doc-id"; +import { LiveSession } from "@/features/live/session/session"; +import { TEXT } from "@/features/live/text/model"; const live = useLiveRoom(); const { synced } = live; diff --git a/packages/plugin/tests/live/session.test.ts b/packages/plugin/tests/features/live/session/session.test.ts similarity index 97% rename from packages/plugin/tests/live/session.test.ts rename to packages/plugin/tests/features/live/session/session.test.ts index 9275e464..4fc17784 100644 --- a/packages/plugin/tests/live/session.test.ts +++ b/packages/plugin/tests/features/live/session/session.test.ts @@ -17,11 +17,11 @@ import { waitUntil, } from "@tests/helpers/live-session"; import { describe, expect, it, vi } from "vitest"; -import { deriveLiveKeys } from "@/crypto/live-keys"; -import { docIdFor } from "@/live/doc-id"; -import { closedBefore } from "@/live/session/closing"; -import { LiveSession } from "@/live/session/session"; -import { TEXT } from "@/live/text/model"; +import { deriveLiveKeys } from "@/core/crypto/live-keys"; +import { docIdFor } from "@/features/live/doc-id"; +import { closedBefore } from "@/features/live/session/closing"; +import { LiveSession } from "@/features/live/session/session"; +import { TEXT } from "@/features/live/text/model"; const live = useLiveRoom(); const { device, synced, roomState } = live; diff --git a/packages/plugin/tests/live/binding-cleanup.test.ts b/packages/plugin/tests/features/live/text/binding-cleanup.test.ts similarity index 95% rename from packages/plugin/tests/live/binding-cleanup.test.ts rename to packages/plugin/tests/features/live/text/binding-cleanup.test.ts index 0ed9f21f..fd1bfc25 100644 --- a/packages/plugin/tests/live/binding-cleanup.test.ts +++ b/packages/plugin/tests/features/live/text/binding-cleanup.test.ts @@ -2,7 +2,7 @@ import type { EditorView } from "@codemirror/view"; import { describe, expect, it } from "vitest"; import * as Y from "yjs"; -import { forgetView } from "@/live/text/binding"; +import { forgetView } from "@/features/live/text/binding"; describe("forgetView", () => { it("drops one view's selections from both stacks and keeps the history", () => { diff --git a/packages/plugin/tests/live/cursors.test.ts b/packages/plugin/tests/features/live/text/cursors.test.ts similarity index 96% rename from packages/plugin/tests/live/cursors.test.ts rename to packages/plugin/tests/features/live/text/cursors.test.ts index bf0606d3..301bf131 100644 --- a/packages/plugin/tests/live/cursors.test.ts +++ b/packages/plugin/tests/features/live/text/cursors.test.ts @@ -7,7 +7,7 @@ import { import { describe, expect, it, vi } from "vitest"; import * as Y from "yjs"; -import { cursorsIn, watchCursor } from "@/live/text/cursors"; +import { cursorsIn, watchCursor } from "@/features/live/text/cursors"; const live = useLiveRoom(); diff --git a/packages/plugin/tests/live/rebuild.test.ts b/packages/plugin/tests/features/live/text/rebuild.test.ts similarity index 94% rename from packages/plugin/tests/live/rebuild.test.ts rename to packages/plugin/tests/features/live/text/rebuild.test.ts index a5de2e88..bab5a73e 100644 --- a/packages/plugin/tests/live/rebuild.test.ts +++ b/packages/plugin/tests/features/live/text/rebuild.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from "vitest"; import * as Y from "yjs"; -import { USERS } from "@/live/authors"; -import { BODY, rebuild } from "@/live/text/rebuild"; +import { USERS } from "@/features/live/authors"; +import { BODY, rebuild } from "@/features/live/text/rebuild"; function authored(doc: Y.Doc): [number, string][] { const runs: [number, string][] = []; diff --git a/packages/plugin/tests/live/remote-selections.test.ts b/packages/plugin/tests/features/live/text/remote-selections.test.ts similarity index 97% rename from packages/plugin/tests/live/remote-selections.test.ts rename to packages/plugin/tests/features/live/text/remote-selections.test.ts index 764b0c1e..ebacec40 100644 --- a/packages/plugin/tests/live/remote-selections.test.ts +++ b/packages/plugin/tests/features/live/text/remote-selections.test.ts @@ -5,7 +5,7 @@ import { installElementFactories } from "@tests/helpers/obsidian-dom"; import { describe, expect, it, vi } from "vitest"; import { Awareness } from "y-protocols/awareness"; import * as Y from "yjs"; -import { remoteSelections } from "@/live/text/remote-selections"; +import { remoteSelections } from "@/features/live/text/remote-selections"; installElementFactories(); diff --git a/packages/plugin/tests/live/scroll-marks.test.ts b/packages/plugin/tests/features/live/text/scroll-marks.test.ts similarity index 97% rename from packages/plugin/tests/live/scroll-marks.test.ts rename to packages/plugin/tests/features/live/text/scroll-marks.test.ts index e78e7d12..8e68c6c5 100644 --- a/packages/plugin/tests/live/scroll-marks.test.ts +++ b/packages/plugin/tests/features/live/text/scroll-marks.test.ts @@ -7,9 +7,9 @@ import { } from "y-protocols/awareness"; import * as Y from "yjs"; -import type { LiveSession } from "@/live/session/session"; -import { TextModel } from "@/live/text/model"; -import { ScrollMarks } from "@/live/text/scroll-marks"; +import type { LiveSession } from "@/features/live/session/session"; +import { TextModel } from "@/features/live/text/model"; +import { ScrollMarks } from "@/features/live/text/scroll-marks"; class FakeElement { children: FakeElement[] = []; diff --git a/packages/plugin/tests/live/text.test.ts b/packages/plugin/tests/features/live/text/text.test.ts similarity index 97% rename from packages/plugin/tests/live/text.test.ts rename to packages/plugin/tests/features/live/text/text.test.ts index 01020795..0f27cec6 100644 --- a/packages/plugin/tests/live/text.test.ts +++ b/packages/plugin/tests/features/live/text/text.test.ts @@ -1,9 +1,8 @@ import { describe, expect, it } from "vitest"; import * as Y from "yjs"; - -import { mergeThreeWay } from "@/live/text/merge"; -import { patchYText } from "@/live/text/patch"; -import { commonEnds } from "@/utils"; +import { commonEnds } from "@/core/utils/diff"; +import { mergeThreeWay } from "@/features/live/text/merge"; +import { patchYText } from "@/features/live/text/patch"; describe("mergeThreeWay", () => { it("takes the room when this device changed nothing", () => { diff --git a/packages/plugin/tests/ui/deleted-elsewhere.test.ts b/packages/plugin/tests/features/live/ui/deleted-elsewhere.test.ts similarity index 86% rename from packages/plugin/tests/ui/deleted-elsewhere.test.ts rename to packages/plugin/tests/features/live/ui/deleted-elsewhere.test.ts index 7902c5e8..2c22b48a 100644 --- a/packages/plugin/tests/ui/deleted-elsewhere.test.ts +++ b/packages/plugin/tests/features/live/ui/deleted-elsewhere.test.ts @@ -1,11 +1,10 @@ import { describe, expect, it, vi } from "vitest"; +import { openChoiceModal } from "@/core/ui/modals/confirm-modal"; +import { createDeletedElsewhere } from "@/features/live/ui/deleted-elsewhere"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; -import { VAULT_SPACE } from "@/sync/space"; -import { createDeletedElsewhere } from "@/ui/live/deleted-elsewhere"; -import { openChoiceModal } from "@/ui/modals"; - -vi.mock("@/ui/modals", () => ({ openChoiceModal: vi.fn() })); -vi.mock("@/ui/common", () => ({ +vi.mock("@/core/ui/modals/confirm-modal", () => ({ openChoiceModal: vi.fn() })); +vi.mock("@/core/ui/notices", () => ({ notifyError: vi.fn(), runWithNotice: vi.fn(async (run: () => Promise) => run()), })); diff --git a/packages/plugin/tests/live/editors.test.ts b/packages/plugin/tests/features/live/workspace/editors.test.ts similarity index 85% rename from packages/plugin/tests/live/editors.test.ts rename to packages/plugin/tests/features/live/workspace/editors.test.ts index 4c1ec376..939031cd 100644 --- a/packages/plugin/tests/live/editors.test.ts +++ b/packages/plugin/tests/features/live/workspace/editors.test.ts @@ -1,7 +1,7 @@ import type { App } from "obsidian"; import { describe, expect, it } from "vitest"; -import { EDITORS, readOpen } from "@/live/workspace/editors"; +import { EDITORS, readOpen } from "@/features/live/workspace/editors"; describe("readOpen", () => { it("fails for a note gone mid-join instead of reading it as emptied", async () => { diff --git a/packages/plugin/tests/live/rename.test.ts b/packages/plugin/tests/features/live/workspace/rename.test.ts similarity index 94% rename from packages/plugin/tests/live/rename.test.ts rename to packages/plugin/tests/features/live/workspace/rename.test.ts index 5f653208..3718a6a7 100644 --- a/packages/plugin/tests/live/rename.test.ts +++ b/packages/plugin/tests/features/live/workspace/rename.test.ts @@ -3,20 +3,19 @@ import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; import { LiveHub } from "@tests/helpers/live-hub"; import { type App, type DataAdapter, MarkdownView, TFile } from "obsidian"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -import { deriveLiveKeys, type LiveKeys } from "@/crypto/live-keys"; -import { seal } from "@/crypto/seal"; -import type { SpaceFrame, SpaceHub } from "@/hub/connection"; -import { AgreedTexts } from "@/live/cold/agreed-texts"; -import { docIdFor } from "@/live/doc-id"; -import type { LiveSession } from "@/live/session/session"; -import type { TextModel } from "@/live/text/model"; -import { movedWith, moveRoom } from "@/live/workspace/rename"; -import { LiveSessions } from "@/live/workspace/sessions"; -import type { LiveSpace } from "@/live/workspace/space"; -import { renameCaseSafe } from "@/vault/io"; - -vi.mock("@/live/text/binding", () => ({ +import { deriveLiveKeys, type LiveKeys } from "@/core/crypto/live-keys"; +import { seal } from "@/core/crypto/seal"; +import type { SpaceFrame, SpaceHub } from "@/core/hub"; +import { renameCaseSafe } from "@/core/vault/io"; +import { AgreedTexts } from "@/features/live/cold/agreed-texts"; +import { docIdFor } from "@/features/live/doc-id"; +import type { LiveSession } from "@/features/live/session/session"; +import type { TextModel } from "@/features/live/text/model"; +import { movedWith, moveRoom } from "@/features/live/workspace/rename"; +import { LiveSessions } from "@/features/live/workspace/sessions"; +import type { LiveSpace } from "@/features/live/workspace/space"; + +vi.mock("@/features/live/text/binding", () => ({ bindEditor: vi.fn(() => ({ detach: vi.fn(), showAuthors: vi.fn() })), })); diff --git a/packages/plugin/tests/live/sessions.test.ts b/packages/plugin/tests/features/live/workspace/sessions.test.ts similarity index 96% rename from packages/plugin/tests/live/sessions.test.ts rename to packages/plugin/tests/features/live/workspace/sessions.test.ts index 033de1cc..6a1b2a84 100644 --- a/packages/plugin/tests/live/sessions.test.ts +++ b/packages/plugin/tests/features/live/workspace/sessions.test.ts @@ -4,20 +4,20 @@ import { LiveHub, type TestConnection } from "@tests/helpers/live-hub"; import { type App, type DataAdapter, MarkdownView, TFile } from "obsidian"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { sha256Hex } from "@/crypto"; -import { deriveLiveKeys, type LiveKeys } from "@/crypto/live-keys"; -import { seal } from "@/crypto/seal"; -import { AgreedTexts } from "@/live/cold/agreed-texts"; -import { LiveColdSync } from "@/live/cold/cold-sync"; -import { docIdFor } from "@/live/doc-id"; -import { FollowerSession } from "@/live/session/follower-session"; -import type { LiveSession } from "@/live/session/session"; -import { bindEditor } from "@/live/text/binding"; -import type { TextModel } from "@/live/text/model"; -import { LiveSessions } from "@/live/workspace/sessions"; -import type { LiveSpace } from "@/live/workspace/space"; - -vi.mock("@/live/text/binding", () => ({ +import { sha256Hex } from "@/core/crypto/cipher"; +import { deriveLiveKeys, type LiveKeys } from "@/core/crypto/live-keys"; +import { seal } from "@/core/crypto/seal"; +import { AgreedTexts } from "@/features/live/cold/agreed-texts"; +import { LiveColdSync } from "@/features/live/cold/cold-sync"; +import { docIdFor } from "@/features/live/doc-id"; +import { FollowerSession } from "@/features/live/session/follower-session"; +import type { LiveSession } from "@/features/live/session/session"; +import { bindEditor } from "@/features/live/text/binding"; +import type { TextModel } from "@/features/live/text/model"; +import { LiveSessions } from "@/features/live/workspace/sessions"; +import type { LiveSpace } from "@/features/live/workspace/space"; + +vi.mock("@/features/live/text/binding", () => ({ bindEditor: vi.fn(() => ({ detach: vi.fn(), showAuthors: vi.fn() })), })); diff --git a/packages/plugin/tests/ui/live-actions.test.ts b/packages/plugin/tests/features/note-header/live-actions.test.ts similarity index 84% rename from packages/plugin/tests/ui/live-actions.test.ts rename to packages/plugin/tests/features/note-header/live-actions.test.ts index b4e3eb9a..7f3f1ce9 100644 --- a/packages/plugin/tests/ui/live-actions.test.ts +++ b/packages/plugin/tests/features/note-header/live-actions.test.ts @@ -1,10 +1,13 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import type { PluginHost } from "@/plugin/host"; -import { notifyInfo } from "@/ui/common/notices"; -import { rebuildLiveNote, toggleAuthors } from "@/ui/live/header/live-actions"; +import type { PluginHost } from "@/app/host"; +import { notifyInfo } from "@/core/ui/notices"; +import { + rebuildLiveNote, + toggleAuthors, +} from "@/features/note-header/live-actions"; -vi.mock("@/ui/common/notices", () => ({ +vi.mock("@/core/ui/notices", () => ({ notifyInfo: vi.fn(), reportError: vi.fn(), })); diff --git a/packages/plugin/tests/ui/live-status.test.ts b/packages/plugin/tests/features/note-header/live-status.test.ts similarity index 91% rename from packages/plugin/tests/ui/live-status.test.ts rename to packages/plugin/tests/features/note-header/live-status.test.ts index 62eeab6b..fc967d61 100644 --- a/packages/plugin/tests/ui/live-status.test.ts +++ b/packages/plugin/tests/features/note-header/live-status.test.ts @@ -1,12 +1,11 @@ import { type FileView, MarkdownView, TFile } from "obsidian"; import { describe, expect, it } from "vitest"; - -import type { RelayStatus } from "@/hub/status"; -import type { ColdCause } from "@/live/workspace/sessions"; -import type { PluginHost } from "@/plugin/host"; -import { spaceOf } from "@/sync/space"; -import { RELAY_TEXT, UNREADABLE_TEXT } from "@/ui/common/relay"; -import { liveStatusOf } from "@/ui/live/header/live-status"; +import type { PluginHost } from "@/app/host"; +import { RELAY_TEXT, UNREADABLE_TEXT } from "@/core/hub/relay-text"; +import type { RelayStatus } from "@/core/hub/status"; +import type { ColdCause } from "@/features/live/workspace/sessions"; +import { liveStatusOf } from "@/features/note-header/live-status"; +import { spaceOf } from "@/features/sync/remote/space"; interface Facts { status: RelayStatus; diff --git a/packages/plugin/tests/ui/note-menu-items.test.ts b/packages/plugin/tests/features/note-header/note-menu-items.test.ts similarity index 95% rename from packages/plugin/tests/ui/note-menu-items.test.ts rename to packages/plugin/tests/features/note-header/note-menu-items.test.ts index 528a2bc0..57183800 100644 --- a/packages/plugin/tests/ui/note-menu-items.test.ts +++ b/packages/plugin/tests/features/note-header/note-menu-items.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; - -import type { LiveStatus } from "@/ui/live/header/live-status"; +import { type LiveState, STATE_ICONS } from "@/features/live/live-state"; +import type { LiveStatus } from "@/features/note-header/live-status"; import { actionItems, canRebuild, @@ -9,8 +9,7 @@ import { type MenuFacts, type PersonView, personState, -} from "@/ui/live/header/note-menu-items"; -import { type LiveState, STATE_ICONS } from "@/ui/live/live-state"; +} from "@/features/note-header/note-menu-items"; const NONE: MenuFacts = { locked: false, diff --git a/packages/plugin/tests/ui/cursor-follow.test.ts b/packages/plugin/tests/features/presence/follow/cursor-follow.test.ts similarity index 91% rename from packages/plugin/tests/ui/cursor-follow.test.ts rename to packages/plugin/tests/features/presence/follow/cursor-follow.test.ts index e4d332e8..f4e3164a 100644 --- a/packages/plugin/tests/ui/cursor-follow.test.ts +++ b/packages/plugin/tests/features/presence/follow/cursor-follow.test.ts @@ -1,13 +1,15 @@ import { MarkdownView, type WorkspaceLeaf } from "obsidian"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import type { PluginHost } from "@/plugin/host"; -import { CursorFollow } from "@/ui/live/header/cursor-follow"; -import { showFollowBanner } from "@/ui/live/header/follow-banner"; -import { trackCursor } from "@/ui/live/header/follow-scroll"; +import type { PluginHost } from "@/app/host"; +import { CursorFollow } from "@/features/presence/follow/cursor-follow"; +import { showFollowBanner } from "@/features/presence/follow/follow-banner"; +import { trackCursor } from "@/features/presence/follow/follow-scroll"; -vi.mock("@/ui/live/header/follow-scroll", () => ({ trackCursor: vi.fn() })); -vi.mock("@/ui/live/header/follow-banner", () => ({ +vi.mock("@/features/presence/follow/follow-scroll", () => ({ + trackCursor: vi.fn(), +})); +vi.mock("@/features/presence/follow/follow-banner", () => ({ showFollowBanner: vi.fn(), })); diff --git a/packages/plugin/tests/ui/follow-scroll.test.ts b/packages/plugin/tests/features/presence/follow/follow-scroll.test.ts similarity index 87% rename from packages/plugin/tests/ui/follow-scroll.test.ts rename to packages/plugin/tests/features/presence/follow/follow-scroll.test.ts index f622ce6b..54c1005a 100644 --- a/packages/plugin/tests/ui/follow-scroll.test.ts +++ b/packages/plugin/tests/features/presence/follow/follow-scroll.test.ts @@ -1,11 +1,11 @@ import type { MarkdownView } from "obsidian"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { LiveSession } from "@/live/session/session"; -import { watchCursor } from "@/live/text/cursors"; -import { trackCursor } from "@/ui/live/header/follow-scroll"; +import type { LiveSession } from "@/features/live/session/session"; +import { watchCursor } from "@/features/live/text/cursors"; +import { trackCursor } from "@/features/presence/follow/follow-scroll"; -vi.mock("@/live/text/cursors", () => ({ watchCursor: vi.fn() })); +vi.mock("@/features/live/text/cursors", () => ({ watchCursor: vi.fn() })); /** A 400px view; each offset is a 10px line. */ function setup(at: number | null) { diff --git a/packages/plugin/tests/presence/here.test.ts b/packages/plugin/tests/features/presence/here.test.ts similarity index 97% rename from packages/plugin/tests/presence/here.test.ts rename to packages/plugin/tests/features/presence/here.test.ts index 9a333251..e20fa8fe 100644 --- a/packages/plugin/tests/presence/here.test.ts +++ b/packages/plugin/tests/features/presence/here.test.ts @@ -1,7 +1,7 @@ import { FileView } from "obsidian"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { watchHere } from "@/presence/here"; -import type { Here } from "@/presence/people"; +import { watchHere } from "@/features/presence/here"; +import type { Here } from "@/features/presence/people"; const NOTE = "Team/a.md"; diff --git a/packages/plugin/tests/presence/people-views.test.ts b/packages/plugin/tests/features/presence/people-views.test.ts similarity index 96% rename from packages/plugin/tests/presence/people-views.test.ts rename to packages/plugin/tests/features/presence/people-views.test.ts index 210edb46..7d13172e 100644 --- a/packages/plugin/tests/presence/people-views.test.ts +++ b/packages/plugin/tests/features/presence/people-views.test.ts @@ -1,9 +1,9 @@ import { SHARE_ID, setup, spacesWith } from "@tests/helpers/presence-relay"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { ChannelPresence } from "@/presence/channel"; -import type { People } from "@/presence/people"; -import { type Space, VAULT_SPACE } from "@/sync/space"; +import { ChannelPresence } from "@/features/presence/channel"; +import type { People } from "@/features/presence/people"; +import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; const NOTE = "Team/a.md"; diff --git a/packages/plugin/tests/presence/people.test.ts b/packages/plugin/tests/features/presence/people.test.ts similarity index 98% rename from packages/plugin/tests/presence/people.test.ts rename to packages/plugin/tests/features/presence/people.test.ts index 22bab56e..56142c6a 100644 --- a/packages/plugin/tests/presence/people.test.ts +++ b/packages/plugin/tests/features/presence/people.test.ts @@ -7,9 +7,12 @@ import { } from "@tests/helpers/presence-relay"; import { describe, expect, it, vi } from "vitest"; -import { openAnnouncement, sealAnnouncement } from "@/presence/announcement"; -import { People } from "@/presence/people"; -import { VAULT_SPACE } from "@/sync/space"; +import { + openAnnouncement, + sealAnnouncement, +} from "@/features/presence/announcement"; +import { People } from "@/features/presence/people"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; describe("people", () => { it("open no channel once disposed", () => { diff --git a/packages/plugin/tests/presence/unseen.test.ts b/packages/plugin/tests/features/presence/unseen.test.ts similarity index 95% rename from packages/plugin/tests/presence/unseen.test.ts rename to packages/plugin/tests/features/presence/unseen.test.ts index 4f6ae558..ebab01a4 100644 --- a/packages/plugin/tests/presence/unseen.test.ts +++ b/packages/plugin/tests/features/presence/unseen.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { Unseen } from "@/presence/unseen"; +import { Unseen } from "@/features/presence/unseen"; function unseen(saved: unknown = []) { const store = { diff --git a/packages/plugin/tests/presence/views.test.ts b/packages/plugin/tests/features/presence/views.test.ts similarity index 97% rename from packages/plugin/tests/presence/views.test.ts rename to packages/plugin/tests/features/presence/views.test.ts index 0d376d4c..d520c681 100644 --- a/packages/plugin/tests/presence/views.test.ts +++ b/packages/plugin/tests/features/presence/views.test.ts @@ -5,7 +5,7 @@ import { mergePeople, onePerPerson, type Person, -} from "@/presence/views"; +} from "@/features/presence/views"; const ALEX: Person = { key: "p1", diff --git a/packages/plugin/tests/hub/connection.test.ts b/packages/plugin/tests/features/relay/connection.test.ts similarity index 90% rename from packages/plugin/tests/hub/connection.test.ts rename to packages/plugin/tests/features/relay/connection.test.ts index 36cc3c3d..179df047 100644 --- a/packages/plugin/tests/hub/connection.test.ts +++ b/packages/plugin/tests/features/relay/connection.test.ts @@ -7,13 +7,13 @@ import { shareChannel, } from "@mdsync/protocol"; import { beforeEach, describe, expect, it, vi } from "vitest"; - -import { hubRoutes } from "@/hub/channels"; -import { HubConnection } from "@/hub/connection"; -import type { HubLinkOptions } from "@/hub/link"; -import type { LinkState } from "@/hub/status"; -import { DEFAULT_SETTINGS, type MdsyncSettings } from "@/settings/model"; -import type { SpaceRecord } from "@/spaces/record"; +import { DEFAULT_SETTINGS } from "@/app/settings"; +import type { HubLinkOptions } from "@/core/hub/link"; +import type { LinkState } from "@/core/hub/status"; +import type { MdsyncSettings } from "@/core/settings/model"; +import { hubRoutes } from "@/features/relay/channels"; +import { HubConnection } from "@/features/relay/connection"; +import type { SpaceRecord } from "@/features/spaces/record"; const { links, FakeLink } = vi.hoisted(() => { const links: InstanceType[] = []; @@ -30,7 +30,7 @@ const { links, FakeLink } = vi.hoisted(() => { return { links, FakeLink }; }); -vi.mock("@/hub/link", () => ({ HubLink: FakeLink })); +vi.mock("@/core/hub/link", () => ({ HubLink: FakeLink })); const HOME = "https://home.example"; const OTHER = "https://other.example"; @@ -365,6 +365,32 @@ describe("HubConnection", () => { expect(hub.statusOf("late")).toBe("full"); }); + it("lists each socket with its spaces, the home relay first", () => { + settings = settingsWith([ + joined("theirs", OTHER), + ...Array.from({ length: MAX_SLOTS }, (_, i) => owned(`s${i}`)), + ]); + const hub = connection(); + expect(hub.relays()).toEqual([]); + + hub.restart(); + const [home, other] = links; + if (other) other.state = "offline"; + const [first, second] = hub.relays(); + + expect(first?.url).toBe(HOME); + expect(first?.state).toBe(home?.state); + expect(first?.spaces[0]).toBe("vault"); + expect(first?.spaces).toHaveLength(MAX_SLOTS); + expect(first?.full).toEqual([`s${MAX_SLOTS - 1}`]); + expect(second).toEqual({ + url: OTHER, + state: "offline", + spaces: ["theirs"], + full: [], + }); + }); + it("asks again for a slot the relay refused while its socket stays up, a few times", () => { vi.useFakeTimers(); settings = settingsWith([owned("mine")]); diff --git a/packages/plugin/tests/cloudflare/migrations.test.ts b/packages/plugin/tests/features/relay/deploy/migrations.test.ts similarity index 93% rename from packages/plugin/tests/cloudflare/migrations.test.ts rename to packages/plugin/tests/features/relay/deploy/migrations.test.ts index 99c52e89..279c4a7f 100644 --- a/packages/plugin/tests/cloudflare/migrations.test.ts +++ b/packages/plugin/tests/features/relay/deploy/migrations.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { pendingMigrations } from "@/cloudflare/migrations"; +import { pendingMigrations } from "@/features/relay/deploy/migrations"; const MIGRATIONS = [ { tag: "v1", new_sqlite_classes: ["SyncRelay"] }, diff --git a/packages/plugin/tests/cloudflare/relay-account.test.ts b/packages/plugin/tests/features/relay/deploy/relay-account.test.ts similarity index 98% rename from packages/plugin/tests/cloudflare/relay-account.test.ts rename to packages/plugin/tests/features/relay/deploy/relay-account.test.ts index ad4269ff..8767f492 100644 --- a/packages/plugin/tests/cloudflare/relay-account.test.ts +++ b/packages/plugin/tests/features/relay/deploy/relay-account.test.ts @@ -7,7 +7,7 @@ import { relayBehind, relayNameError, relayUrlOf, -} from "@/cloudflare"; +} from "@/features/relay/deploy/relay-account"; const A = "/accounts/acc"; const RELAYS = { taken: ["mdsync-relay", "other"], subdomain: "me" }; diff --git a/packages/plugin/tests/cloudflare/relay-deploy.test.ts b/packages/plugin/tests/features/relay/deploy/relay-deploy.test.ts similarity index 98% rename from packages/plugin/tests/cloudflare/relay-deploy.test.ts rename to packages/plugin/tests/features/relay/deploy/relay-deploy.test.ts index 13ffedd4..4da7aeb6 100644 --- a/packages/plugin/tests/cloudflare/relay-deploy.test.ts +++ b/packages/plugin/tests/features/relay/deploy/relay-deploy.test.ts @@ -5,14 +5,14 @@ import { readForm, } from "@tests/helpers/fake-cloudflare"; import { describe, expect, it, vi } from "vitest"; +import type { HttpRequest } from "@/core/cloudflare/api"; +import type { RelayBundle } from "@/features/relay/deploy/bundle"; import { deployRelay, - type HttpRequest, - type RelayBundle, workerNames, workersSubdomain, workerUrl, -} from "@/cloudflare"; +} from "@/features/relay/deploy/relay-deploy"; const A = "/accounts/acc"; const SCRIPT = `${A}/workers/scripts/mdsync-relay`; diff --git a/packages/plugin/tests/settings/setup/relay.test.ts b/packages/plugin/tests/features/relay/deploy/relay.test.ts similarity index 88% rename from packages/plugin/tests/settings/setup/relay.test.ts rename to packages/plugin/tests/features/relay/deploy/relay.test.ts index 3c5b4b8b..497e65c3 100644 --- a/packages/plugin/tests/settings/setup/relay.test.ts +++ b/packages/plugin/tests/features/relay/deploy/relay.test.ts @@ -6,10 +6,8 @@ import { readForm, } from "@tests/helpers/fake-cloudflare"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { ERelayDeployStep, RELAY_NAME, RELAY_VERSION } from "@/cloudflare"; -import type { PluginHost } from "@/plugin/host"; -import { testRelay } from "@/settings/connection-test"; -import { mergeSettings } from "@/settings/model"; +import type { PluginHost } from "@/app/host"; +import { mergeSettings } from "@/app/settings"; import { activateRelay, deployOwnRelay, @@ -18,9 +16,17 @@ import { runningRelayDeploy, useRelay, waitForRelay, -} from "@/settings/setup/relay"; +} from "@/features/relay/deploy/deploy-flow"; +import { + RELAY_NAME, + RELAY_VERSION, +} from "@/features/relay/deploy/relay-account"; +import { ERelayDeployStep } from "@/features/relay/deploy/relay-deploy"; +import { testRelay } from "@/features/relay/relay-test"; -vi.mock("@/settings/connection-test", () => ({ testRelay: vi.fn() })); +vi.mock("@/features/relay/relay-test", () => ({ + testRelay: vi.fn(), +})); const A = "/accounts/acc"; const RELAYS = { taken: ["mdsync-relay", "other"], subdomain: "me" }; @@ -391,6 +397,39 @@ describe("activateRelay", () => { expect(plugin.realtime.hub.restart).toHaveBeenCalledTimes(1); }); + it("asks whether to enable real-time sync when the relay answers, not before", async () => { + vi.useFakeTimers(); + vi.mocked(testRelay).mockResolvedValue({ + ok: true, + message: "ready", + version: RELAY_VERSION, + }); + const plugin = host(); + let wanted = true; + + const answer = activateRelay(plugin, () => wanted); + wanted = false; + + expect(await answer).toBe(true); + expect(plugin.settings.realtimeSync).toBe(false); + expect(plugin.saveSettings).toHaveBeenCalledTimes(1); + }); + + it("keeps real-time sync as it is without a choice, as for a relay update", async () => { + vi.useFakeTimers(); + vi.mocked(testRelay).mockResolvedValue({ + ok: true, + message: "ready", + version: RELAY_VERSION, + }); + const plugin = host(); + plugin.settings.realtimeSync = false; + + expect(await activateRelay(plugin)).toBe(true); + expect(plugin.settings.realtimeSync).toBe(false); + expect(plugin.realtime.hub.restart).toHaveBeenCalledTimes(1); + }); + it("gives up without switching anything on once the plugin is unloaded", async () => { const plugin = Object.assign(host(), { unloaded: true }); @@ -412,6 +451,13 @@ describe("useRelay", () => { expect(plugin.realtime.hub.restart).toHaveBeenCalledTimes(1); }); + it("leaves real-time sync as it is when the person chose otherwise", async () => { + const plugin = host(); + await useRelay(plugin, false); + expect(plugin.settings.realtimeSync).toBe(false); + expect(plugin.saveSettings).toHaveBeenCalledTimes(1); + }); + it("does not restart the hub when saving fails", async () => { const plugin = host(); vi.mocked(plugin.saveSettings).mockRejectedValueOnce( diff --git a/packages/plugin/tests/settings/connection-test.test.ts b/packages/plugin/tests/features/relay/relay-test.test.ts similarity index 98% rename from packages/plugin/tests/settings/connection-test.test.ts rename to packages/plugin/tests/features/relay/relay-test.test.ts index 544c5373..2a020aff 100644 --- a/packages/plugin/tests/settings/connection-test.test.ts +++ b/packages/plugin/tests/features/relay/relay-test.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import { testRelay } from "@/settings/connection-test"; +import { testRelay } from "@/features/relay/relay-test"; interface Reply { status: number; diff --git a/packages/plugin/tests/settings/relay-section.test.ts b/packages/plugin/tests/features/relay/ui/relay-section.test.ts similarity index 86% rename from packages/plugin/tests/settings/relay-section.test.ts rename to packages/plugin/tests/features/relay/ui/relay-section.test.ts index e4154269..24cbd473 100644 --- a/packages/plugin/tests/settings/relay-section.test.ts +++ b/packages/plugin/tests/features/relay/ui/relay-section.test.ts @@ -1,30 +1,16 @@ import type { Setting } from "obsidian"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { type FieldContext, fieldRow } from "@/settings/fields"; -import { relaySection } from "@/settings/sections/relay"; +import { type FieldContext, fieldRow } from "@/core/settings/fields"; +import type { RelayHost } from "@/features/relay"; +import { relaySection } from "@/features/relay/ui/relay-section"; -vi.mock("obsidian", () => ({ - Setting: class { - setName() { - return this; - } - setHeading() { - return this; - } - setDesc() { - return this; - } - addButton() { - return this; - } - }, -})); -vi.mock("@/settings/fields", () => ({ +vi.mock("@/core/settings/fields", async (importOriginal) => ({ + ...(await importOriginal>()), fieldRow: vi.fn(), checkRow: vi.fn(), group: (_heading: string, items: unknown[]) => ({ items }), })); -vi.mock("@/ui/common/notices", () => ({ +vi.mock("@/core/ui/notices", () => ({ runWithNotice: vi.fn(async (action: () => Promise) => { await action(); return true; @@ -62,7 +48,7 @@ function relayForm(relaySecret: string) { const definitions = relaySection({ plugin: { settings, saveSettings }, rerender, - } as unknown as FieldContext); + } as unknown as FieldContext); const row = definitions.items?.find((item) => item.name === "Relay secret"); if (!row || !("render" in row) || !row.render) throw new Error("No relay secret row"); diff --git a/packages/plugin/tests/plugin/relay-update.test.ts b/packages/plugin/tests/features/relay/update/relay-update.test.ts similarity index 86% rename from packages/plugin/tests/plugin/relay-update.test.ts rename to packages/plugin/tests/features/relay/update/relay-update.test.ts index fe157a76..c3922535 100644 --- a/packages/plugin/tests/plugin/relay-update.test.ts +++ b/packages/plugin/tests/features/relay/update/relay-update.test.ts @@ -1,17 +1,24 @@ import type { Plugin } from "obsidian"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { RELAY_VERSION } from "@/cloudflare"; -import type { HubListener } from "@/hub/connection"; -import type { PluginHost } from "@/plugin/host"; -import { type RelayUpdate, registerRelayUpdate } from "@/plugin/relay-update"; -import { testRelay } from "@/settings/connection-test"; -import { mergeSettings } from "@/settings/model"; -import { openRelayUpdateModal } from "@/ui"; +import type { PluginHost } from "@/app/host"; +import { mergeSettings } from "@/app/settings"; +import type { HubListener } from "@/core/hub"; +import { RELAY_VERSION } from "@/features/relay/deploy/relay-account"; +import { testRelay } from "@/features/relay/relay-test"; +import { + type RelayUpdate, + registerRelayUpdate, +} from "@/features/relay/update/relay-update"; +import { openRelayUpdateModal } from "@/features/relay/update/relay-update-modal"; -vi.mock("@/ui", () => ({ openRelayUpdateModal: vi.fn(async () => false) })); -vi.mock("@/settings/connection-test", () => ({ testRelay: vi.fn() })); -vi.mock("@/cloudflare", async (original) => ({ - ...(await original()), +vi.mock("@/features/relay/update/relay-update-modal", () => ({ + openRelayUpdateModal: vi.fn(async () => false), +})); +vi.mock("@/features/relay/relay-test", () => ({ + testRelay: vi.fn(), +})); +vi.mock("@/features/relay/deploy/relay-account", async (original) => ({ + ...(await original()), accountRelays: async () => ({ taken: ["mdsync-relay", "mdsync-relay-2"], subdomain: "me", diff --git a/packages/plugin/tests/settings/logs-view.test.ts b/packages/plugin/tests/features/settings/logs-view.test.ts similarity index 62% rename from packages/plugin/tests/settings/logs-view.test.ts rename to packages/plugin/tests/features/settings/logs-view.test.ts index 4945d863..7046e09c 100644 --- a/packages/plugin/tests/settings/logs-view.test.ts +++ b/packages/plugin/tests/features/settings/logs-view.test.ts @@ -1,28 +1,12 @@ // @vitest-environment jsdom -import { describe, expect, it, vi } from "vitest"; -import { ESyncLogLevel, ESyncLogOperation } from "@/logs/store"; -import { renderLogEntry } from "@/settings/logs-view"; -import { copyText } from "@/ui/common"; -import { installElementMethods } from "./setup/element-methods"; -const copy = vi.hoisted(() => ({ clicks: [] as Array<() => void> })); +import { installElementMethods } from "@tests/helpers/element-methods"; +import { describe, expect, it, vi } from "vitest"; +import { ESyncLogLevel, ESyncLogOperation } from "@/core/logs/store"; +import { copyText } from "@/core/ui/controls/copyable"; +import { renderLogEntry } from "@/features/settings/logs-view"; -vi.mock("obsidian", async (importOriginal) => ({ - ...(await importOriginal()), - ExtraButtonComponent: class { - setIcon() { - return this; - } - setTooltip() { - return this; - } - onClick(fn: () => void) { - copy.clicks.push(fn); - return this; - } - }, -})); -vi.mock("@/ui/common", () => ({ +vi.mock("@/core/ui/controls/copyable", () => ({ copyText: vi.fn(() => Promise.resolve(true)), })); @@ -56,10 +40,10 @@ describe("renderLogEntry", () => { }); it("copies the whole entry while the details are still closed", () => { - copy.clicks.length = 0; - renderLogEntry(document.createElement("div"), entry); + const parent = document.createElement("div"); + renderLogEntry(parent, entry); - copy.clicks[0]?.(); + parent.querySelector(".extra-setting-button")?.click(); expect(copyText).toHaveBeenCalledWith( "Log entry", diff --git a/packages/plugin/tests/features/settings/tab.test.ts b/packages/plugin/tests/features/settings/tab.test.ts new file mode 100644 index 00000000..b0472009 --- /dev/null +++ b/packages/plugin/tests/features/settings/tab.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it, vi } from "vitest"; +import { MdsyncSettingTab } from "@/features/settings/tab"; + +function tab(listSnapshots: () => Promise) { + const plugin = { + settings: { + activeStorageKind: "s3", + storageConfigs: { s3: { kind: "s3", bucket: "a" } }, + }, + controller: { + history: { listSnapshots: vi.fn(listSnapshots) }, + vaultCheck: { at: 1 }, + getSnapshot(): { vaultCheck: { at: number } } { + return { vaultCheck: this.vaultCheck }; + }, + }, + }; + // biome-ignore lint/suspicious/noExplicitAny: a partial plugin is enough for the history read. + const settings = new MdsyncSettingTab({} as any, plugin as any); + const load = (): Promise => + (settings as unknown as { loadHistory(): Promise }).loadHistory(); + return { + settings, + plugin, + load, + calls: plugin.controller.history.listSnapshots, + }; +} + +describe("MdsyncSettingTab history read", () => { + it("reads history once per visit, storage and compare", async () => { + const { settings, plugin, load, calls } = tab(async () => ({})); + await load(); + await load(); + expect(calls).toHaveBeenCalledTimes(1); + + plugin.settings.storageConfigs.s3.bucket = "b"; + await load(); + expect(calls).toHaveBeenCalledTimes(2); + + plugin.controller.vaultCheck = { at: 2 }; + await load(); + expect(calls).toHaveBeenCalledTimes(3); + + settings.hide(); + await load(); + expect(calls).toHaveBeenCalledTimes(4); + }); + + it("reads again after a failure", async () => { + const { load, calls } = tab(() => Promise.reject(new Error("offline"))); + await expect(load()).rejects.toThrow("offline"); + await expect(load()).rejects.toThrow("offline"); + expect(calls).toHaveBeenCalledTimes(2); + }); +}); diff --git a/packages/plugin/tests/features/setup/feature-choices.test.ts b/packages/plugin/tests/features/setup/feature-choices.test.ts new file mode 100644 index 00000000..4a71f017 --- /dev/null +++ b/packages/plugin/tests/features/setup/feature-choices.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, it } from "vitest"; +import { mergeSettings } from "@/app/settings"; +import type { MdsyncSettings } from "@/core/settings/model"; +import { + AUTOMATIC_INTERVAL_MINUTES, + ESyncMode, + enablesRealtime, + shownSyncMode, + syncModeOf, + syncModePatch, +} from "@/features/setup/feature-choices"; + +const RELAY = { relayUrl: "https://relay.example", relaySecret: "secret" }; + +function apply( + settings: MdsyncSettings, + patch: Partial, +): MdsyncSettings { + return { ...settings, ...patch }; +} + +describe("sync mode", () => { + it("reads Manual from fresh settings", () => { + expect(syncModeOf(mergeSettings({}))).toBe(ESyncMode.Manual); + }); + + it("reads push after change alone as Automatic, since it uploads on its own", () => { + const settings = mergeSettings({ + autoSyncEnabled: false, + autoPushAfterChange: true, + }); + expect(syncModeOf(settings)).toBe(ESyncMode.Automatic); + }); + + it("turns real-time sync on with a relay unless Manual or Automatic was picked", () => { + const base = mergeSettings(RELAY); + const instant = apply(base, syncModePatch(base, ESyncMode.Instant)); + expect(enablesRealtime(null, base)).toBe(true); + expect(enablesRealtime(ESyncMode.Instant, instant)).toBe(true); + expect(enablesRealtime(ESyncMode.Automatic, base)).toBe(false); + expect(enablesRealtime(ESyncMode.Manual, base)).toBe(false); + }); + + it("round-trips every mode with a relay", () => { + const base = mergeSettings(RELAY); + for (const mode of Object.values(ESyncMode)) { + expect(syncModeOf(apply(base, syncModePatch(base, mode)))).toBe(mode); + } + }); + + it("keeps real-time sync off without a relay, so Instant reads as Automatic until one answers", () => { + const base = mergeSettings({}); + const patch = syncModePatch(base, ESyncMode.Instant); + expect(patch.realtimeSync).toBe(false); + expect(syncModeOf(apply(base, patch))).toBe(ESyncMode.Automatic); + }); + + it("drops a picked Instant without a relay once the settings turn Manual, shown and on activation alike", () => { + const base = mergeSettings({}); + const instant = apply(base, syncModePatch(base, ESyncMode.Instant)); + expect(shownSyncMode(ESyncMode.Instant, instant)).toBe(ESyncMode.Instant); + expect(shownSyncMode(null, instant)).toBe(ESyncMode.Automatic); + expect(shownSyncMode(ESyncMode.Instant, apply(instant, RELAY))).toBe( + ESyncMode.Automatic, + ); + expect(shownSyncMode(ESyncMode.Instant, base)).toBe(ESyncMode.Manual); + expect(enablesRealtime(ESyncMode.Instant, apply(base, RELAY))).toBe(false); + }); + + it("gives Automatic a schedule when the interval was left at startup only, and keeps one already set", () => { + const fresh = mergeSettings({}); + expect( + syncModePatch(fresh, ESyncMode.Automatic).autoSyncIntervalMinutes, + ).toBe(AUTOMATIC_INTERVAL_MINUTES); + const set = mergeSettings({ autoSyncIntervalMinutes: 30 }); + expect( + syncModePatch(set, ESyncMode.Automatic).autoSyncIntervalMinutes, + ).toBe(30); + }); + + it("turns every automatic path off for Manual", () => { + const auto = mergeSettings({ + ...RELAY, + autoSyncEnabled: true, + autoPushAfterChange: true, + realtimeSync: true, + }); + expect(syncModePatch(auto, ESyncMode.Manual)).toEqual({ + autoSyncEnabled: false, + autoPushAfterChange: false, + realtimeSync: false, + }); + }); +}); diff --git a/packages/plugin/tests/settings/setup/passphrase-meter.test.ts b/packages/plugin/tests/features/setup/passphrase-meter.test.ts similarity index 90% rename from packages/plugin/tests/settings/setup/passphrase-meter.test.ts rename to packages/plugin/tests/features/setup/passphrase-meter.test.ts index 71280382..dc8094c7 100644 --- a/packages/plugin/tests/settings/setup/passphrase-meter.test.ts +++ b/packages/plugin/tests/features/setup/passphrase-meter.test.ts @@ -1,14 +1,14 @@ // @vitest-environment jsdom -import { installElementMethods } from "@tests/settings/setup/element-methods"; +import { installElementMethods } from "@tests/helpers/element-methods"; import { describe, expect, it } from "vitest"; -import { MIN_PASSPHRASE_LENGTH } from "@/crypto/constants"; +import { MIN_PASSPHRASE_LENGTH } from "@/core/crypto/constants"; import { METER_BARS, passphraseMeter, passphraseStrength, -} from "@/settings/setup/passphrase-meter"; +} from "@/features/setup/passphrase-meter"; installElementMethods(); diff --git a/packages/plugin/tests/settings/setup/run-action.test.ts b/packages/plugin/tests/features/setup/run-action.test.ts similarity index 96% rename from packages/plugin/tests/settings/setup/run-action.test.ts rename to packages/plugin/tests/features/setup/run-action.test.ts index 82a009b1..9a485b29 100644 --- a/packages/plugin/tests/settings/setup/run-action.test.ts +++ b/packages/plugin/tests/features/setup/run-action.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import { runAction } from "@/settings/setup/run-action"; +import { runAction } from "@/features/setup/run-action"; function setup() { const wizard = { redraw: vi.fn() }; diff --git a/packages/plugin/tests/settings/setup/steps.test.ts b/packages/plugin/tests/features/setup/step-state.test.ts similarity index 92% rename from packages/plugin/tests/settings/setup/steps.test.ts rename to packages/plugin/tests/features/setup/step-state.test.ts index 0c63fc9d..3d259e36 100644 --- a/packages/plugin/tests/settings/setup/steps.test.ts +++ b/packages/plugin/tests/features/setup/step-state.test.ts @@ -1,15 +1,17 @@ import { describe, expect, it, vi } from "vitest"; -import type { PluginHost } from "@/plugin/host"; -import { type MdsyncSettings, mergeSettings } from "@/settings/model"; +import type { PluginHost } from "@/app/host"; +import { mergeSettings } from "@/app/settings"; +import type { MdsyncSettings } from "@/core/settings/model"; import { ESetupPath, ESetupStep, firstStep, isStepDone, PATH_STEPS, -} from "@/settings/setup/steps"; -import type { SpaceRecord } from "@/spaces/record"; -import { defaultS3Config, EStorageBackend } from "@/storage"; +} from "@/features/setup/step-state"; +import type { SpaceRecord } from "@/features/spaces/record"; +import { defaultS3Config } from "@/features/storage/backends/s3"; +import { EStorageBackend } from "@/features/storage/config"; const STORAGE = { storageConfigs: { @@ -42,11 +44,13 @@ describe("setup paths", () => { expect(PATH_STEPS[ESetupPath.New]).toEqual([ ESetupStep.Storage, ESetupStep.Passphrase, + ESetupStep.Features, ESetupStep.Relay, ESetupStep.Ready, ]); expect(PATH_STEPS[ESetupPath.Join]).toEqual([ ESetupStep.Import, + ESetupStep.Features, ESetupStep.Relay, ESetupStep.Ready, ]); diff --git a/packages/plugin/tests/settings/setup/stepper.test.ts b/packages/plugin/tests/features/setup/stepper.test.ts similarity index 94% rename from packages/plugin/tests/settings/setup/stepper.test.ts rename to packages/plugin/tests/features/setup/stepper.test.ts index 1a8677d9..c71a51db 100644 --- a/packages/plugin/tests/settings/setup/stepper.test.ts +++ b/packages/plugin/tests/features/setup/stepper.test.ts @@ -1,13 +1,13 @@ // @vitest-environment jsdom -import { installElementMethods } from "@tests/settings/setup/element-methods"; +import { installElementMethods } from "@tests/helpers/element-methods"; import { describe, expect, it } from "vitest"; import { createStepper, EStepState, stepStates, -} from "@/settings/setup/stepper"; +} from "@/features/setup/stepper"; installElementMethods(); diff --git a/packages/plugin/tests/features/setup/steps/first-sync.test.ts b/packages/plugin/tests/features/setup/steps/first-sync.test.ts new file mode 100644 index 00000000..94455fb2 --- /dev/null +++ b/packages/plugin/tests/features/setup/steps/first-sync.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it, vi } from "vitest"; +import { createFirstSync, syncHeld } from "@/features/setup/steps/first-sync"; +import type { Wizard } from "@/features/setup/wizard"; +import type { DiffResult } from "@/features/sync"; + +const compared = { diff: { conflicts: [] } }; + +function setup(snapshot: Record) { + const controller = { + subscribe: () => () => {}, + refresh: vi.fn(async () => {}), + getSnapshot: () => ({ + error: null, + spaceErrors: [], + result: compared, + pendingLocal: 0, + pendingRemote: 0, + conflicts: 0, + ...snapshot, + }), + }; + const wizard = { + plugin: { controller }, + redraw: () => {}, + } as unknown as Wizard; + return createFirstSync(wizard); +} + +async function compare(snapshot: Record) { + const sync = setup(snapshot); + sync.start(); + await new Promise((resolve) => setTimeout(resolve, 0)); + return sync; +} + +describe("first sync", () => { + it("is done once a comparison finds nothing left to move", async () => { + expect((await compare({})).done()).toBe(true); + }); + + it("is not done when the comparison never ran, as after a cancelled passphrase prompt", async () => { + const sync = await compare({ result: null }); + expect(sync.done()).toBe(false); + expect(sync.leads()).toBe(true); + }); + + it("is not done while a file is left to move or an error stands", async () => { + expect((await compare({ pendingRemote: 2 })).done()).toBe(false); + expect((await compare({ error: "offline" })).done()).toBe(false); + }); +}); + +describe("syncHeld", () => { + const spaceOf = (path: string) => (path.startsWith("shared/") ? "s" : "v"); + const conflict = (path: string, baselineHash: string | null = null) => ({ + path, + localHash: "l", + remoteHash: "r", + baselineHash, + }); + const change = (path: string) => ({ path }) as DiffResult["localChanges"][0]; + const diff = (parts: Partial) => + ({ + localChanges: [], + remoteChanges: [], + conflicts: [], + ...parts, + }) as DiffResult; + + it("holds when every pending file sits in a space with a conflict that cannot merge", () => { + expect( + syncHeld( + diff({ + conflicts: [conflict("shared/a.md")], + remoteChanges: [change("shared/b.md")], + }), + spaceOf, + ), + ).toBe(true); + }); + + it("does not hold another space's files", () => { + expect( + syncHeld( + diff({ + conflicts: [conflict("shared/a.md")], + remoteChanges: [change("note.md")], + }), + spaceOf, + ), + ).toBe(false); + }); + + it("does not hold while a conflict with a common version may merge, or without conflicts", () => { + expect( + syncHeld(diff({ conflicts: [conflict("a.md", "b")] }), spaceOf), + ).toBe(false); + expect(syncHeld(diff({ localChanges: [change("a.md")] }), spaceOf)).toBe( + false, + ); + }); +}); diff --git a/packages/plugin/tests/settings/setup/relay-step.test.ts b/packages/plugin/tests/features/setup/steps/relay-step.test.ts similarity index 74% rename from packages/plugin/tests/settings/setup/relay-step.test.ts rename to packages/plugin/tests/features/setup/steps/relay-step.test.ts index 95fc1e0d..28c1e69e 100644 --- a/packages/plugin/tests/settings/setup/relay-step.test.ts +++ b/packages/plugin/tests/features/setup/steps/relay-step.test.ts @@ -1,10 +1,9 @@ // @vitest-environment jsdom -import { installElementMethods } from "@tests/settings/setup/element-methods"; -import { beforeEach, describe, expect, it, vi } from "vitest"; -import type { PluginHost } from "@/plugin/host"; -import { testRelay } from "@/settings/connection-test"; -import { mergeSettings } from "@/settings/model"; +import { installElementMethods } from "@tests/helpers/element-methods"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { PluginHost } from "@/app/host"; +import { mergeSettings } from "@/app/settings"; import { activateRelay, deployOwnRelay, @@ -12,80 +11,28 @@ import { planRelay, runningRelayDeploy, useRelay, -} from "@/settings/setup/relay"; -import { createRelayStep } from "@/settings/setup/relay-step"; -import type { StepView, Wizard } from "@/settings/setup/wizard"; +} from "@/features/relay/deploy/deploy-flow"; +import { testRelay } from "@/features/relay/relay-test"; +import { ESyncMode } from "@/features/setup/feature-choices"; +import { createRelayStep } from "@/features/setup/steps/relay-step"; +import type { StepView, Wizard } from "@/features/setup/wizard"; installElementMethods(); -const buttons: Array<{ label: string; click: () => void }> = []; - -vi.mock("obsidian", async (original) => { - class Setting { - readonly settingEl: HTMLElement; - constructor(parent: HTMLElement) { - this.settingEl = parent.createDiv(); - } - setName() { - return this; - } - setDesc() { - return this; - } - addText(build: (text: unknown) => void) { - const inputEl = this.settingEl.createEl("input"); - const text = { - inputEl, - setPlaceholder: () => text, - setValue: (v: string) => { - inputEl.value = v; - return text; - }, - onChange: (cb: (v: string) => void) => { - inputEl.addEventListener("input", () => cb(inputEl.value)); - return text; - }, - }; - build(text); - return this; - } - addButton(build: (button: unknown) => void) { - const entry = { label: "", click: () => {} }; - const button = { - buttonEl: this.settingEl.createEl("button"), - setButtonText: (label: string) => { - entry.label = label; - return button; - }, - setCta: () => button, - setDisabled: () => button, - onClick: (cb: () => void) => { - entry.click = cb; - return button; - }, - }; - build(button); - buttons.push(entry); - return this; - } - } - return { - ...(await original()), - Setting, - }; -}); -vi.mock("@/settings/connection-test", () => ({ testRelay: vi.fn() })); -vi.mock("@/settings/cloudflare-login", () => ({ +vi.mock("@/features/relay/relay-test", () => ({ + testRelay: vi.fn(), +})); +vi.mock("@/features/storage/cloudflare/cloudflare-login", () => ({ cloudflareOf: () => ({ api: {}, accountId: "acc" }), cloudflareErrorMessage: (err: Error) => err.message, forgetCloudflare: vi.fn(), })); -vi.mock("@/cloudflare", async (original) => ({ - ...(await original()), +vi.mock("@/features/relay/deploy/relay-account", async (original) => ({ + ...(await original()), accountRelays: vi.fn(async () => ({ taken: [], subdomain: "me" })), })); -vi.mock("@/settings/setup/relay", async (original) => ({ - ...(await original()), +vi.mock("@/features/relay/deploy/deploy-flow", async (original) => ({ + ...(await original()), planRelay: vi.fn(async () => ({ deploy: { name: "r", secret: "s" } })), deployOwnRelay: vi.fn(), failedRelay: vi.fn(() => null), @@ -118,9 +65,11 @@ function setup() { plugin, isShowing: (v: StepView) => open && v === view, isLive: () => open, + syncMode: null as ESyncMode | null, + currentPath: () => null, + moveOn: () => {}, redraw: () => { el.replaceChildren(); - buttons.length = 0; if (open) view?.render(el); }, next: vi.fn(), @@ -135,9 +84,7 @@ function setup() { [...el.querySelectorAll(".mdsync-choice")] .find((c) => c.textContent?.includes(title)) ?.click(); - const press = (label: string) => - buttons.find((b) => b.label === label)?.click(); - return { plugin, wizard, view, el, card, press }; + return { plugin, wizard, view, el, card }; } const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); @@ -178,10 +125,24 @@ describe("the manual relay form", () => { relayUrl: "https://relay.example", relaySecret: "typed", }); - expect(useRelay).toHaveBeenCalledOnce(); + expect(useRelay).toHaveBeenCalledExactlyOnceWith(plugin, true); expect(wizard.next).toHaveBeenCalledOnce(); }); + it("leaves real-time sync off for a relay connected after Manual was picked", async () => { + vi.mocked(testRelay).mockResolvedValue({ ok: true, message: "" }); + const { plugin, el, card, wizard } = setup(); + wizard.syncMode = ESyncMode.Manual; + card("I already have a relay"); + const input = fill(el)[0]; + if (!input) throw new Error("no input"); + + enter(input); + await flush(); + + expect(useRelay).toHaveBeenCalledExactlyOnceWith(plugin, false); + }); + it("leaves the settings alone when the wizard closed while the relay was tested", async () => { const answer = deferred<{ ok: boolean; message: string }>(); vi.mocked(testRelay).mockReturnValue(answer.promise); @@ -257,10 +218,30 @@ describe("deploying from the wizard", () => { answer.resolve(true); await flush(); - expect(activateRelay).toHaveBeenCalledExactlyOnceWith(plugin); + expect(activateRelay).toHaveBeenCalledExactlyOnceWith( + plugin, + expect.any(Function), + ); expect(wizard.next).not.toHaveBeenCalled(); }); + it("keeps real-time sync off for a relay deployed after Automatic was picked", async () => { + vi.mocked(deployOwnRelay).mockResolvedValue(); + vi.mocked(activateRelay).mockResolvedValue(true); + const { plugin, wizard, card } = setup(); + wizard.syncMode = ESyncMode.Automatic; + plugin.settings.autoSyncEnabled = true; + + card("Deploy to my Cloudflare"); + await flush(); + + const realtime = vi.mocked(activateRelay).mock.calls[0]?.[1]; + expect(realtime?.()).toBe(false); + // Asked when the relay answers: the choice may change while it is awaited. + wizard.syncMode = ESyncMode.Instant; + expect(realtime?.()).toBe(true); + }); + it("ignores a remembered failed deploy once a relay is set", async () => { vi.mocked(failedRelay).mockReturnValue({ name: "stale", secret: "old" }); vi.mocked(deployOwnRelay).mockReturnValue(new Promise(() => {})); diff --git a/packages/plugin/tests/features/setup/wizard.test.ts b/packages/plugin/tests/features/setup/wizard.test.ts new file mode 100644 index 00000000..1e4b6aa5 --- /dev/null +++ b/packages/plugin/tests/features/setup/wizard.test.ts @@ -0,0 +1,22 @@ +import { Modal } from "obsidian"; +import { describe, expect, it, vi } from "vitest"; +import { mergeSettings } from "@/app/settings"; +import { ESyncMode, enablesRealtime } from "@/features/setup/feature-choices"; +import type { SetupHost } from "@/features/setup/host"; +import { ESetupStep } from "@/features/setup/step-state"; +import { openSetupWizard, type Wizard } from "@/features/setup/wizard"; + +describe("setup wizard", () => { + it("shares the sync mode pick with a wizard closed before its relay answered", () => { + const open = vi.spyOn(Modal.prototype, "open"); + const plugin = { app: {}, settings: {} } as unknown as SetupHost; + openSetupWizard(plugin, ESetupStep.Features, () => {}); + openSetupWizard(plugin, ESetupStep.Features, () => {}); + const [closed, reopened] = open.mock.contexts as Wizard[]; + const realtime = () => + enablesRealtime(closed?.syncMode ?? null, mergeSettings({})); + expect(realtime()).toBe(true); + if (reopened) reopened.syncMode = ESyncMode.Manual; + expect(realtime()).toBe(false); + }); +}); diff --git a/packages/plugin/tests/features/source-control/actions/held-by-conflict.test.ts b/packages/plugin/tests/features/source-control/actions/held-by-conflict.test.ts new file mode 100644 index 00000000..0b5f0325 --- /dev/null +++ b/packages/plugin/tests/features/source-control/actions/held-by-conflict.test.ts @@ -0,0 +1,69 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { SourceControlActions } from "@/features/source-control/actions/actions"; +import type { SourceControlHost } from "@/features/source-control/host"; + +const notices: string[] = []; +vi.mock("obsidian", async (importOriginal) => ({ + ...(await importOriginal>()), + Notice: class { + constructor(message: string) { + notices.push(message); + } + }, +})); + +/** `cached` conflicts show until `refresh` swaps in `fresh`. */ +function setup(cached: string[], fresh: string[]) { + let conflicts = cached; + const controller = { + getSnapshot: () => ({ + result: { diff: { conflicts: conflicts.map((path) => ({ path })) } }, + }), + spaceFor: () => ({ id: "vault" }), + refresh: vi.fn(async () => { + conflicts = fresh; + }), + pushPaths: vi.fn(async () => ({ ok: true })), + pullPaths: vi.fn(async () => ({ ok: true })), + }; + const actions = new SourceControlActions({ + plugin: { controller } as unknown as SourceControlHost, + showHistory: () => {}, + openDiff: async () => {}, + }); + return { actions, controller }; +} + +beforeEach(() => { + notices.length = 0; +}); + +describe("a push or pull a conflict holds", () => { + it("is refused with the conflict named when a fresh compare still shows it", async () => { + const { actions, controller } = setup(["a.md"], ["a.md"]); + + expect(await actions.pushPaths(["b.md"])).toBe(false); + + expect(controller.refresh).toHaveBeenCalledOnce(); + expect(controller.pushPaths).not.toHaveBeenCalled(); + expect(notices).toEqual([ + 'MDSync: Resolve the conflict in "a.md" first: nothing pushes or pulls until then.', + ]); + }); + + it("goes ahead once the conflict was resolved elsewhere", async () => { + const { actions, controller } = setup(["a.md"], []); + + expect(await actions.pullPaths(["b.md"])).toBe(true); + + expect(controller.pullPaths).toHaveBeenCalledWith(["b.md"]); + }); + + it("compares only when a cached conflict could hold it", async () => { + const { actions, controller } = setup([], []); + + expect(await actions.pushPaths(["b.md"])).toBe(true); + + expect(controller.refresh).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/plugin/tests/ui/conflict-preview-manager.test.ts b/packages/plugin/tests/features/source-control/changes/conflict-preview-manager.test.ts similarity index 92% rename from packages/plugin/tests/ui/conflict-preview-manager.test.ts rename to packages/plugin/tests/features/source-control/changes/conflict-preview-manager.test.ts index 52ba3243..a092d6fd 100644 --- a/packages/plugin/tests/ui/conflict-preview-manager.test.ts +++ b/packages/plugin/tests/features/source-control/changes/conflict-preview-manager.test.ts @@ -1,8 +1,12 @@ // @vitest-environment jsdom + +import { installElementMethods } from "@tests/helpers/element-methods"; import { beforeAll, describe, expect, it, vi } from "vitest"; -import { EDiffDirection, type FileDiffModel } from "@/sync/projection"; -import { ConflictPreviewManager } from "@/ui/source-control/conflict-preview-manager"; -import { installElementMethods } from "../settings/setup/element-methods"; +import { ConflictPreviewManager } from "@/features/source-control/changes/conflict-preview-manager"; +import { + EDiffDirection, + type FileDiffModel, +} from "@/features/sync/hunks/projection"; beforeAll(installElementMethods); diff --git a/packages/plugin/tests/ui/diff-identity.test.ts b/packages/plugin/tests/features/source-control/changes/diff-identity.test.ts similarity index 94% rename from packages/plugin/tests/ui/diff-identity.test.ts rename to packages/plugin/tests/features/source-control/changes/diff-identity.test.ts index 939259fe..f71bfbf9 100644 --- a/packages/plugin/tests/ui/diff-identity.test.ts +++ b/packages/plugin/tests/features/source-control/changes/diff-identity.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { type DiffResult, EChangeType } from "@/sync/types"; -import { diffEquals } from "@/ui/source-control/diff-identity"; +import { diffEquals } from "@/features/source-control/changes/diff-identity"; +import { type DiffResult, EChangeType } from "@/features/sync/types"; function change( path: string, diff --git a/packages/plugin/tests/ui/row-formatter.test.ts b/packages/plugin/tests/features/source-control/changes/row-formatter.test.ts similarity index 76% rename from packages/plugin/tests/ui/row-formatter.test.ts rename to packages/plugin/tests/features/source-control/changes/row-formatter.test.ts index fe5a3b81..b6434041 100644 --- a/packages/plugin/tests/ui/row-formatter.test.ts +++ b/packages/plugin/tests/features/source-control/changes/row-formatter.test.ts @@ -1,10 +1,10 @@ import { describe, expect, it } from "vitest"; -import { EChangeType } from "@/sync/types"; import { foldMoves, rowFromChange, rowFromConflict, -} from "@/ui/source-control/row-formatter"; +} from "@/features/source-control/changes/row-formatter"; +import { EChangeType } from "@/features/sync/types"; describe("source control row formatting", () => { it("keeps a change size for compact display", () => { @@ -58,6 +58,24 @@ describe("source control row formatting", () => { expect(row.statusLetter).toBe("C"); }); + it("offers Merge only for text with an earlier version", () => { + const conflict = (path: string, baselineHash: string | null) => + rowFromConflict({ path, localHash: "l", remoteHash: "r", baselineHash }); + + expect(conflict("a.md", "base")).toMatchObject({ + hasBase: true, + mergeable: true, + }); + expect(conflict("a.md", null)).toMatchObject({ + hasBase: false, + mergeable: false, + }); + expect(conflict("photo.png", "base")).toMatchObject({ + hasBase: true, + mergeable: false, + }); + }); + it("does not show a delta for additions", () => { const row = rowFromChange( { diff --git a/packages/plugin/tests/ui/tree-flatten.test.ts b/packages/plugin/tests/features/source-control/changes/tree-flatten.test.ts similarity index 95% rename from packages/plugin/tests/ui/tree-flatten.test.ts rename to packages/plugin/tests/features/source-control/changes/tree-flatten.test.ts index ae76d30f..63550eb6 100644 --- a/packages/plugin/tests/ui/tree-flatten.test.ts +++ b/packages/plugin/tests/features/source-control/changes/tree-flatten.test.ts @@ -3,8 +3,8 @@ import { buildTree, flattenRows, flattenTree, -} from "@/ui/source-control/tree-builder"; -import type { FileRow } from "@/ui/source-control/types"; +} from "@/features/source-control/changes/tree-builder"; +import type { FileRow } from "@/features/source-control/types"; function file(path: string): FileRow { return { diff --git a/packages/plugin/tests/features/source-control/history/age-groups.test.ts b/packages/plugin/tests/features/source-control/history/age-groups.test.ts new file mode 100644 index 00000000..da4b3092 --- /dev/null +++ b/packages/plugin/tests/features/source-control/history/age-groups.test.ts @@ -0,0 +1,114 @@ +import { describe, expect, it } from "vitest"; +import { + type Aged, + ageTitle, + groupByAge, + PINNED_LABEL, +} from "@/features/source-control/history/age-groups"; +import type { Resolution } from "@/features/sync"; + +const NOW = new Date(2026, 9, 28, 15, 0).getTime(); +const MINUTE = 60_000; +const DAY = 86_400_000; + +function row( + id: string, + at: number, + res: Resolution | null = "push", + pinned = false, +): Aged & { id: string } { + return { id, at, res, pinned }; +} + +function shape(rows: Array) { + return groupByAge(rows, NOW).map(({ label, chip, rows }) => ({ + label, + chip, + ids: rows.map((row) => row.id), + })); +} + +describe("groupByAge", () => { + it("leads with pins, then the last hour of single pushes, then days", () => { + expect( + shape([ + row("a", NOW - 5 * MINUTE), + row("p", NOW - 30 * MINUTE, "push", true), + row("b", NOW - 59 * MINUTE), + row("c", NOW - 61 * MINUTE), + row("d", NOW - 3 * 60 * MINUTE, "10m"), + row("e", NOW - DAY, "1h"), + ]), + ).toEqual([ + { label: PINNED_LABEL, chip: null, ids: ["p"] }, + { label: "Last hour", chip: "push", ids: ["a", "b"] }, + { label: "Today", chip: "10m", ids: ["c", "d"] }, + { label: "Yesterday", chip: "1h", ids: ["e"] }, + ]); + }); + + it("names a chip only where the resolution changes", () => { + const groups = shape([ + row("a", NOW - 2 * DAY, "1h"), + row("b", NOW - 3 * DAY, "1h"), + ]); + expect(groups.map((group) => group.chip)).toEqual(["1h", null]); + }); + + it("groups daily versions by week and weekly ones by month", () => { + const daily = new Date(2026, 9, 14, 12).getTime(); + const weekly = new Date(2026, 8, 9, 12).getTime(); + const groups = shape([ + row("a", daily, "1d"), + row("b", daily - DAY, "1d"), + row("c", weekly, "1w"), + row("d", weekly - 7 * DAY, "1w"), + ]); + const range = new Intl.DateTimeFormat(undefined, { + month: "short", + day: "numeric", + }).formatRange(new Date(2026, 9, 12), new Date(2026, 9, 18)); + expect(groups).toEqual([ + { label: range, chip: "1d", ids: ["a", "b"] }, + { + label: new Date(weekly).toLocaleDateString(undefined, { + month: "long", + year: "numeric", + }), + chip: "1w", + ids: ["c", "d"], + }, + ]); + }); + + it("keeps a version off the walk with single pushes", () => { + expect(shape([row("a", NOW - MINUTE, null)])).toEqual([ + { label: "Last hour", chip: "push", ids: ["a"] }, + ]); + }); +}); + +describe("ageTitle", () => { + it("says the time, the day or the week the version stands for", () => { + const at = new Date(2026, 8, 9, 14, 41).getTime(); + expect(ageTitle({ at, res: "1h" }, NOW)).toBe( + new Date(at).toLocaleTimeString(undefined, { + hour: "2-digit", + minute: "2-digit", + }), + ); + expect(ageTitle({ at, res: "1d" }, NOW)).toBe( + new Date(at).toLocaleDateString(undefined, { + weekday: "short", + day: "numeric", + month: "short", + }), + ); + expect(ageTitle({ at, res: "1w" }, NOW)).toBe( + `Week of ${new Date(2026, 8, 7).toLocaleDateString(undefined, { + day: "numeric", + month: "short", + })}`, + ); + }); +}); diff --git a/packages/plugin/tests/ui/history-list.test.ts b/packages/plugin/tests/features/source-control/history/history-list.test.ts similarity index 94% rename from packages/plugin/tests/ui/history-list.test.ts rename to packages/plugin/tests/features/source-control/history/history-list.test.ts index dfb3fae7..fe897ca1 100644 --- a/packages/plugin/tests/ui/history-list.test.ts +++ b/packages/plugin/tests/features/source-control/history/history-list.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from "vitest"; -import { HistoryList } from "@/ui/source-control/history-list"; +import { HistoryList } from "@/features/source-control/history/history-list"; function deferred() { let resolve!: (value: T) => void; diff --git a/packages/plugin/tests/ui/history-rows.test.ts b/packages/plugin/tests/features/source-control/history/history-rows.test.ts similarity index 54% rename from packages/plugin/tests/ui/history-rows.test.ts rename to packages/plugin/tests/features/source-control/history/history-rows.test.ts index c0345be2..71f7250b 100644 --- a/packages/plugin/tests/ui/history-rows.test.ts +++ b/packages/plugin/tests/features/source-control/history/history-rows.test.ts @@ -1,7 +1,12 @@ import { describe, expect, it } from "vitest"; -import type { FileVersion } from "@/sync/history"; -import type { EFileKind } from "@/sync/types"; -import { buildHistoryRows } from "@/ui/source-control/history-rows"; +import { formatDay } from "@/core/shared"; +import { + ageTitle, + clockTime, +} from "@/features/source-control/history/age-groups"; +import { buildHistoryRows } from "@/features/source-control/history/history-rows"; +import type { FileVersion } from "@/features/sync/history/types"; +import type { EFileKind } from "@/features/sync/types"; const NOW = 1_700_000_000_000; const DAY = 86_400_000; @@ -16,7 +21,13 @@ function version(overrides: Partial = {}): FileVersion { kind: KIND, createdAt: NOW - DAY, deviceId: "device-abcdef123456", - pinned: false, + pinId: null, + first: false, + replayable: true, + at: NOW - DAY, + firstAt: NOW - DAY, + pushes: 1, + res: "push", ...overrides, }; } @@ -34,11 +45,19 @@ describe("buildHistoryRows", () => { expect(row?.tooltip).toBe(new Date(NOW - DAY).toLocaleString()); }); - it("titles a row from today by its age", () => { - const [row] = buildHistoryRows([version({ createdAt: NOW - 60_000 })], { - now: NOW, - }); - expect(row?.title).toBe("1 minute ago"); + it("titles a row by storage time, as finely as it is kept", () => { + const at = NOW - 60_000; + const rows = buildHistoryRows( + [ + version({ createdAt: NOW - DAY, at, res: "push" }), + version({ createdAt: at, at, res: "1d" }), + ], + { now: NOW }, + ); + expect(rows.map((row) => row.title)).toEqual([ + ageTitle({ at, res: "push" }, NOW), + ageTitle({ at, res: "1d" }, NOW), + ]); }); it("measures the size against the next older version", () => { @@ -67,22 +86,35 @@ describe("buildHistoryRows", () => { expect(rows[1]?.previous).toBeUndefined(); }); + it("builds only the asked positions, each still against its next older version", () => { + const versions = [ + version({ snapshotId: "s3", hash: "H3", size: 3072, createdAt: NOW }), + version({ snapshotId: "s2", hash: "H2", size: 2048 }), + version({ snapshotId: "s1", hash: "H1", size: 1024 }), + ]; + const rows = buildHistoryRows(versions, { now: NOW, only: [2, 1] }); + expect(rows.map((row) => row.snapshotId)).toEqual(["s1", "s2"]); + expect(rows[1]).toMatchObject({ sizeDelta: 1024, isLatest: false }); + expect(rows[1]?.previous?.hash).toBe("H1"); + expect(rows[0]?.previous).toBeUndefined(); + }); + it("prefers a pin's name over the timestamp, but keeps both apart", () => { const [row] = buildHistoryRows( - [version({ pinned: true, label: " before the rewrite " })], + [version({ pinId: "p1", label: " before the rewrite " })], { now: NOW }, ); expect(row?.title).toBe("before the rewrite"); expect(row?.label).toBe("before the rewrite"); - // The age leaves the title, so it moves to the meta line. - expect(row?.meta).toContain("1 day ago"); + // Pins sit apart from their day, so the meta carries it. + expect(row?.meta).toBe(`${formatDay(NOW - DAY, NOW)} · Device device-a`); // The diff pane still names the version by age, not by the pin. expect(row?.version.label).toBe("1 day ago"); }); it("falls back to the timestamp when a pin has no name", () => { - const [row] = buildHistoryRows([version({ pinned: true })], { now: NOW }); - expect(row?.title).toBe("1 day ago"); + const [row] = buildHistoryRows([version({ pinId: "p1" })], { now: NOW }); + expect(row?.title).toBe(clockTime(NOW - DAY)); expect(row?.label).toBe(""); }); @@ -91,10 +123,10 @@ describe("buildHistoryRows", () => { }); it("treats a whitespace-only pin name as no name at all", () => { - const [row] = buildHistoryRows([version({ pinned: true, label: " " })], { + const [row] = buildHistoryRows([version({ pinId: "p1", label: " " })], { now: NOW, }); - expect(row?.title).toBe("1 day ago"); + expect(row?.title).toBe(clockTime(NOW - DAY)); expect(row?.label).toBe(""); }); @@ -106,6 +138,17 @@ describe("buildHistoryRows", () => { expect(rows.map((r) => r.isLatest)).toEqual([true, false]); }); + it("says how many pushes a version stands for, and which one created the file", () => { + const rows = buildHistoryRows( + [version({ pushes: 3, res: "10m" }), version({ first: true })], + { now: NOW }, + ); + expect(rows.map((row) => row.meta)).toEqual([ + "Device device-a · last of 3 pushes", + "Device device-a · first version", + ]); + }); + it("names this device instead of showing a raw id", () => { const [row] = buildHistoryRows([version()], { now: NOW, diff --git a/packages/plugin/tests/features/source-control/history/history-tab.test.ts b/packages/plugin/tests/features/source-control/history/history-tab.test.ts new file mode 100644 index 00000000..c638eab3 --- /dev/null +++ b/packages/plugin/tests/features/source-control/history/history-tab.test.ts @@ -0,0 +1,137 @@ +// @vitest-environment jsdom + +import { installElementMethods } from "@tests/helpers/element-methods"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { HistoryTab } from "@/features/source-control/history/history-tab"; +import type { SourceControlHost } from "@/features/source-control/host"; +import type { FileVersion } from "@/features/sync/history/types"; +import type { EFileKind } from "@/features/sync/types"; + +installElementMethods(); + +const NOW = new Date(2026, 9, 28, 18, 0).getTime(); +const HOUR = 3_600_000; +const ME = { id: "laptop", name: "Laptop" }; + +function version(index: number, pinned = false): FileVersion { + const at = NOW - index * HOUR; + return { + snapshotId: `s${index}`, + hash: `H${index}`, + size: 10 + index, + mtime: 1, + kind: "vault" as EFileKind, + createdAt: at, + deviceId: "laptop", + pinId: pinned ? `s${index}` : null, + first: false, + replayable: true, + at, + firstAt: at, + pushes: 1, + res: "push", + }; +} + +const settled = () => new Promise((resolve) => setTimeout(resolve, 0)); + +function harness(results: FileVersion[][]) { + const getFileHistory = vi.fn(async () => results.shift() as FileVersion[]); + const plugin = { + app: { workspace: { getActiveFile: () => null } }, + settings: { fileHistoryEnabled: true, fileHistoryKeep: "forever" }, + controller: { + history: { getFileHistory }, + currentDevice: () => ME, + }, + } as unknown as SourceControlHost; + let pane!: HTMLElement; + const draw = () => { + // In the document, so focus moves as it does in Obsidian. + pane = document.createElement("div"); + document.body.replaceChildren(pane); + tab.render(pane, document.createElement("div")); + }; + const tab = new HistoryTab(plugin, draw, vi.fn(), vi.fn(), vi.fn()); + tab.setPath("note.md"); + return { tab, draw, getFileHistory, pane: () => pane }; +} + +function pager(pane: HTMLElement) { + const buttons = Array.from( + pane.querySelectorAll( + ".mdsync-history-row-actions button", + ), + ); + return { + meta: pane.querySelector( + ".mdsync-history-row-actions .mdsync-history-row-meta", + )?.textContent, + next: buttons.find((button) => button.textContent === "Next page"), + }; +} + +describe("HistoryTab paging", () => { + beforeEach(() => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(NOW); + }); + + it("renders 100 rows of 150 versions with the pager, and the next page the rest", async () => { + const versions = Array.from({ length: 150 }, (_, index) => version(index)); + const { draw, pane } = harness([versions]); + draw(); + await settled(); + + expect(pane().querySelectorAll(".mdsync-history-row")).toHaveLength(100); + expect(pager(pane()).meta).toBe("1-100 of 150"); + + pager(pane()).next?.click(); + + expect(pane().querySelectorAll(".mdsync-history-row")).toHaveLength(50); + expect(pager(pane()).meta).toBe("101-150 of 150"); + // Next is disabled on the last page, so keyboard focus lands on Previous. + expect(document.activeElement?.textContent).toBe("Previous page"); + }); + + it("keeps a pinned version from deep in the list on page 1", async () => { + const versions = Array.from({ length: 150 }, (_, index) => + version(index, index === 120), + ); + const { draw, pane } = harness([versions]); + draw(); + await settled(); + + const rows = pane().querySelectorAll(".mdsync-history-row"); + expect(rows).toHaveLength(100); + expect(rows[0]?.querySelector(".has-pin")).not.toBeNull(); + expect(pane().querySelectorAll(".has-pin")).toHaveLength(1); + }); + + it("starts over at page 1 on a new path", async () => { + const versions = () => + Array.from({ length: 150 }, (_, index) => version(index)); + const { tab, draw, pane } = harness([versions(), versions()]); + draw(); + await settled(); + pager(pane()).next?.click(); + + tab.setPath("other.md"); + draw(); + await settled(); + + expect(pane().querySelectorAll(".mdsync-history-row")).toHaveLength(100); + expect(pager(pane()).meta).toBe("1-100 of 150"); + }); + + it("shows no pager for a short list", async () => { + const { draw, pane } = harness([ + Array.from({ length: 100 }, (_, index) => version(index)), + ]); + draw(); + await settled(); + + expect(pane().querySelectorAll(".mdsync-history-row")).toHaveLength(100); + expect(pager(pane()).meta).toBeUndefined(); + }); +}); diff --git a/packages/plugin/tests/ui/row-pager.test.ts b/packages/plugin/tests/features/source-control/history/row-pager.test.ts similarity index 93% rename from packages/plugin/tests/ui/row-pager.test.ts rename to packages/plugin/tests/features/source-control/history/row-pager.test.ts index 5b3126c4..ed0f9cb7 100644 --- a/packages/plugin/tests/ui/row-pager.test.ts +++ b/packages/plugin/tests/features/source-control/history/row-pager.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { RowPager } from "@/ui/source-control/row-pager"; +import { RowPager } from "@/features/source-control/history/row-pager"; const rows = Array.from({ length: 20_001 }, (_, index) => index); diff --git a/packages/plugin/tests/features/source-control/restore-file.test.ts b/packages/plugin/tests/features/source-control/restore-file.test.ts new file mode 100644 index 00000000..1e8b4d19 --- /dev/null +++ b/packages/plugin/tests/features/source-control/restore-file.test.ts @@ -0,0 +1,68 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { SourceControlHost } from "@/features/source-control/host"; +import { confirmAndRestoreFile } from "@/features/source-control/restore-file"; + +const { confirmRestore, notifyError, notifyInfo } = vi.hoisted(() => ({ + confirmRestore: vi.fn(), + notifyError: vi.fn(), + notifyInfo: vi.fn(), +})); + +vi.mock("@/features/diff/ui/restore-modal", () => ({ confirmRestore })); +vi.mock("@/core/ui/notices", () => ({ notifyError, notifyInfo })); + +const restoreFileVersion = vi.fn(); +const plugin = { + controller: { history: { restoreFileVersion } }, +} as unknown as SourceControlHost; +const confirm = { + path: "notes/a.md", + target: "notes/b.md", + version: { hash: "H1", label: "2 days ago", size: 10 }, +}; + +beforeEach(() => { + vi.clearAllMocks(); + confirmRestore.mockResolvedValue(true); + restoreFileVersion.mockResolvedValue(undefined); +}); + +describe("confirmAndRestoreFile", () => { + it("asks about the target, restores the version read under its own path there, says so and runs the callback", async () => { + const after = vi.fn(); + await confirmAndRestoreFile(plugin, confirm, "Restored.", after); + + expect(confirmRestore).toHaveBeenCalledWith({ ...confirm, plugin }); + expect(restoreFileVersion).toHaveBeenCalledExactlyOnceWith( + "notes/b.md", + "H1", + "notes/a.md", + ); + expect(notifyInfo).toHaveBeenCalledExactlyOnceWith("Restored."); + expect(after).toHaveBeenCalledOnce(); + }); + + it("stops on cancel without a notice", async () => { + confirmRestore.mockResolvedValue(false); + const after = vi.fn(); + await confirmAndRestoreFile(plugin, confirm, "Restored.", after); + + expect(restoreFileVersion).not.toHaveBeenCalled(); + expect(notifyInfo).not.toHaveBeenCalled(); + expect(after).not.toHaveBeenCalled(); + }); + + it("reports a failed restore, with no success notice or callback", async () => { + const error = new Error("gone"); + restoreFileVersion.mockRejectedValue(error); + const after = vi.fn(); + await confirmAndRestoreFile(plugin, confirm, "Restored.", after); + + expect(notifyError).toHaveBeenCalledExactlyOnceWith( + "Restore failed", + error, + ); + expect(notifyInfo).not.toHaveBeenCalled(); + expect(after).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/plugin/tests/features/source-control/tab-states.test.ts b/packages/plugin/tests/features/source-control/tab-states.test.ts new file mode 100644 index 00000000..deaa0ee3 --- /dev/null +++ b/packages/plugin/tests/features/source-control/tab-states.test.ts @@ -0,0 +1,31 @@ +// @vitest-environment jsdom + +import { installElementMethods } from "@tests/helpers/element-methods"; +import { describe, expect, it, vi } from "vitest"; +import type { SettingsHost } from "@/core/settings"; +import { renderHistoryOff } from "@/features/source-control/tab-states"; + +installElementMethods(); + +describe("renderHistoryOff", () => { + it("turns history on, saves, then redraws", async () => { + const order: string[] = []; + const plugin = { + settings: { fileHistoryEnabled: false }, + saveSettings: vi.fn(async () => { + order.push(`saved ${plugin.settings.fileHistoryEnabled}`); + }), + scheduleScopeRefresh: vi.fn(), + } as unknown as SettingsHost; + const parent = document.createElement("div"); + const redraw = vi.fn(() => order.push("redrawn")); + + renderHistoryOff(parent, plugin, "Keep past versions.", redraw); + const button = parent.querySelector("button"); + expect(button?.textContent).toBe("Turn on history"); + button?.click(); + await vi.waitFor(() => expect(redraw).toHaveBeenCalledOnce()); + + expect(order).toEqual(["saved true", "redrawn"]); + }); +}); diff --git a/packages/plugin/tests/features/source-control/timeline/session-card.test.ts b/packages/plugin/tests/features/source-control/timeline/session-card.test.ts new file mode 100644 index 00000000..564765ce --- /dev/null +++ b/packages/plugin/tests/features/source-control/timeline/session-card.test.ts @@ -0,0 +1,119 @@ +// @vitest-environment jsdom + +import { installElementMethods } from "@tests/helpers/element-methods"; +import { describe, expect, it, vi } from "vitest"; +import { RowPager } from "@/features/source-control/history/row-pager"; +import { + type CardContext, + renderSessionCard, +} from "@/features/source-control/timeline/session-card"; +import { buildSessionRows } from "@/features/source-control/timeline/session-rows"; +import type { SnapshotSummary } from "@/features/sync"; +import type { EFileKind } from "@/features/sync/types"; + +installElementMethods(); + +const NOW = new Date(2026, 9, 28, 18, 0).getTime(); +const MINUTE = 60_000; + +/** A minute apart, all on one path: one session whose files stay under a page of their own. */ +function pushes(count: number, res: SnapshotSummary["res"]): SnapshotSummary[] { + return Array.from({ length: count }, (_, index) => { + const at = NOW - 2 * 60 * MINUTE - index * MINUTE; + return { + id: `s${index}`, + createdAt: at, + deviceId: "laptop", + pinned: false, + files: { + added: { + "a.md": { + hash: `h${index}`, + size: 1, + mtime: 1, + kind: "vault" as EFileKind, + }, + }, + modified: {}, + deleted: {}, + }, + keptUntil: null, + restorable: true, + isHead: false, + at, + firstAt: at, + pushes: 1, + res, + }; + }); +} + +function draw(count: number, res: SnapshotSummary["res"]) { + const [row] = buildSessionRows(pushes(count, res), { now: NOW }); + if (!row) throw new Error("no session"); + const pagers = new Map(); + const parent = document.createElement("div"); + const render = () => { + parent.replaceChildren(); + renderSessionCard(parent, row, ctx); + }; + const ctx = { + query: "", + selected: null, + opening: null, + isOpen: (key: string) => key === row.key || key === `all:${row.key}`, + toggle: vi.fn(), + pager: (key: string) => { + let pager = pagers.get(key); + if (!pager) { + pager = new RowPager(); + pagers.set(key, pager); + } + return pager; + }, + rerender: render, + } as unknown as CardContext; + render(); + return { + parent, + versions: () => + parent.querySelectorAll( + ".mdsync-timeline-files > .mdsync-timeline-version", + ), + meta: () => + parent.querySelector( + ".mdsync-timeline-files > .mdsync-history-row-actions .mdsync-history-row-meta", + )?.textContent, + next: () => + Array.from(parent.querySelectorAll("button")).find( + (button) => button.textContent === "Next page", + ), + }; +} + +describe("renderSessionCard versions", () => { + it.each([ + ["every push", "push"], + ["a packed period", "10m"], + ] as const)( + "renders 100 of 150 versions with the pager for %s, and the next page the rest", + (_, res) => { + const card = draw(150, res); + + expect(card.versions()).toHaveLength(100); + expect(card.meta()).toBe("1-100 of 150"); + + card.next()?.click(); + + expect(card.versions()).toHaveLength(50); + expect(card.meta()).toBe("101-150 of 150"); + }, + ); + + it("shows no pager for a short session", () => { + const card = draw(100, "push"); + + expect(card.versions()).toHaveLength(100); + expect(card.meta()).toBeUndefined(); + }); +}); diff --git a/packages/plugin/tests/features/source-control/timeline/session-rows.test.ts b/packages/plugin/tests/features/source-control/timeline/session-rows.test.ts new file mode 100644 index 00000000..59bca335 --- /dev/null +++ b/packages/plugin/tests/features/source-control/timeline/session-rows.test.ts @@ -0,0 +1,146 @@ +import { describe, expect, it } from "vitest"; +import { formatDay } from "@/core/shared"; +import { + buildSessionRows, + touches, +} from "@/features/source-control/timeline/session-rows"; +import { buildTimelineRows } from "@/features/source-control/timeline/timeline-rows"; +import type { SnapshotChanges, SnapshotSummary } from "@/features/sync"; +import type { EFileKind, ManifestEntry } from "@/features/sync/types"; + +const NOW = new Date(2026, 9, 28, 18, 0).getTime(); +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; +const ME = { id: "laptop", name: "Laptop" }; + +function entry(hash: string, size: number): ManifestEntry { + return { hash, size, mtime: 1, kind: "vault" as EFileKind }; +} + +function changes(overrides: Partial = {}): SnapshotChanges { + return { added: {}, modified: {}, deleted: {}, ...overrides }; +} + +let id = 0; +function version( + at: number, + overrides: Partial = {}, +): SnapshotSummary { + return { + id: `s${++id}`, + createdAt: at, + deviceId: "phone", + deviceName: "Phone", + pinned: false, + files: changes({ added: { "a.md": entry("a", 1) } }), + keptUntil: null, + restorable: true, + isHead: false, + at, + firstAt: at, + pushes: 1, + res: "push", + ...overrides, + }; +} + +describe("buildSessionRows", () => { + it("sums a sitting of pushes: files composed, net size, the head", () => { + const [row] = buildSessionRows( + [ + version(NOW - 2 * HOUR, { + isHead: true, + files: changes({ + modified: { + "a.md": { from: entry("A1", 10), to: entry("A2", 30) }, + }, + }), + }), + version(NOW - 2 * HOUR - 5 * MINUTE, { + files: changes({ + added: { "a.md": entry("A1", 10), "b.md": entry("B1", 5) }, + }), + }), + ], + { now: NOW, currentDevice: ME }, + ); + expect(row).toMatchObject({ + meta: "2 pushes · 2 files", + everyPush: true, + isHead: true, + tally: [["add", 2]], + netDelta: 35, + }); + expect(row?.title.startsWith("Phone · ")).toBe(true); + expect(row?.files?.map((file) => file.path)).toEqual(["a.md", "b.md"]); + }); + + it("counts versions where history keeps one per period", () => { + const [row] = buildSessionRows( + [ + version(NOW - 5 * HOUR, { + res: "1h", + pushes: 3, + firstAt: NOW - 5 * HOUR - 40 * MINUTE, + }), + version(NOW - 6 * HOUR, { res: "1h", pushes: 4 }), + ], + { now: NOW, currentDevice: ME }, + ); + // A picked day matches the session from its first push, not only its last. + expect(row).toMatchObject({ + meta: "2 versions · 7 pushes · 1 file", + everyPush: false, + firstAt: NOW - 6 * HOUR, + }); + expect(row?.versions.map((item) => item.meta)).toEqual([ + "last of 3 pushes", + "last of 4 pushes", + ]); + }); + + it("names a pin by its label and dates it, as it sits apart from its day", () => { + const at = NOW - 3 * HOUR; + const [row] = buildSessionRows( + [version(at, { pinned: true, label: "Release 1.4", files: null })], + { now: NOW, currentDevice: ME }, + ); + expect(row).toMatchObject({ + title: "Release 1.4", + meta: `${formatDay(at, NOW)} · Phone`, + tally: null, + pinned: true, + }); + }); + + it("names this device as it is called here", () => { + const [row] = buildSessionRows( + [version(NOW - HOUR, { deviceId: "laptop" })], + { + now: NOW, + currentDevice: ME, + }, + ); + expect(row?.title.startsWith("Laptop · ")).toBe(true); + }); +}); + +describe("touches", () => { + it("finds a path part in any kind of change, ignoring case in the path", () => { + const [row] = buildTimelineRows( + [ + version(NOW, { + files: changes({ + added: { "Projects/Alpha/Brief.md": entry("A", 1) }, + deleted: { "Inbox/Draft.md": entry("D", 1) }, + }), + }), + ], + NOW, + ); + if (!row) throw new Error("no row"); + expect(touches(row, "alpha/")).toBe(true); + expect(touches(row, "draft")).toBe(true); + expect(touches(row, "beta")).toBe(false); + }); +}); diff --git a/packages/plugin/tests/features/source-control/timeline/sessions.test.ts b/packages/plugin/tests/features/source-control/timeline/sessions.test.ts new file mode 100644 index 00000000..8c180132 --- /dev/null +++ b/packages/plugin/tests/features/source-control/timeline/sessions.test.ts @@ -0,0 +1,196 @@ +import { describe, expect, it } from "vitest"; +import { sessionsOf } from "@/features/source-control/timeline/sessions"; +import type { SnapshotSummary } from "@/features/sync"; +import type { EFileKind, ManifestEntry } from "@/features/sync/types"; + +const NOW = new Date(2026, 9, 28, 18, 0).getTime(); +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; + +function entry(hash: string, size = 1): ManifestEntry { + return { hash, size, mtime: 1, kind: "vault" as EFileKind }; +} + +let id = 0; +function version( + at: number, + overrides: Partial = {}, +): SnapshotSummary { + return { + id: `s${++id}`, + createdAt: at, + deviceId: "laptop", + pinned: false, + files: { added: { "a.md": entry("a") }, modified: {}, deleted: {} }, + keptUntil: null, + restorable: true, + isHead: false, + at, + firstAt: at, + pushes: 1, + res: "push", + ...overrides, + }; +} + +const none = { added: {}, modified: {}, deleted: {} }; + +const sizes = (list: ReturnType) => + list.map((session) => session.versions.length); + +describe("sessionsOf", () => { + it("joins one device's pushes close together, newest first", () => { + const list = sessionsOf( + [ + version(NOW - 2 * HOUR), + version(NOW - 2 * HOUR - 5 * MINUTE), + version(NOW - 2 * HOUR - 9 * MINUTE), + version(NOW - 3 * HOUR), + ], + NOW, + ); + expect(sizes(list)).toEqual([3, 1]); + expect(list[0]).toMatchObject({ + at: NOW - 2 * HOUR, + firstAt: NOW - 2 * HOUR - 9 * MINUTE, + pushes: 3, + }); + }); + + it("splits at another device, a resolution, a pin and a heading", () => { + expect( + sizes( + sessionsOf( + [ + version(NOW - 3 * HOUR), + version(NOW - 3 * HOUR - MINUTE, { deviceId: "phone" }), + version(NOW - 3 * HOUR - 2 * MINUTE, { + deviceId: "phone", + res: "10m", + }), + version(NOW - 3 * HOUR - 3 * MINUTE, { res: "10m" }), + version(NOW - 3 * HOUR - 4 * MINUTE, { res: "10m", pinned: true }), + version(NOW - 3 * HOUR - 5 * MINUTE, { res: "10m" }), + ], + NOW, + ), + ), + ).toEqual([1, 1, 1, 1, 1, 1]); + // 17:05 is the last hour, 16:58 today: one sitting, two headings. + expect( + sizes( + sessionsOf( + [version(NOW - 55 * MINUTE), version(NOW - 62 * MINUTE)], + NOW, + ), + ), + ).toEqual([1, 1]); + }); + + it("lets packed versions sit one period apart", () => { + const hourly = (hours: number) => + version(NOW - hours * HOUR, { + res: "1h", + firstAt: NOW - hours * HOUR - 40 * MINUTE, + }); + expect(sizes(sessionsOf([hourly(5), hourly(6), hourly(9)], NOW))).toEqual([ + 2, 1, + ]); + }); + + it("composes the session's changes from its oldest parent", () => { + const [session] = sessionsOf( + [ + version(NOW - 2 * HOUR, { + pushes: 2, + files: { + added: {}, + modified: { "a.md": { from: entry("A1", 5), to: entry("A2", 9) } }, + deleted: { "b.md": entry("B1") }, + }, + }), + version(NOW - 2 * HOUR - MINUTE, { + files: { + added: { "a.md": entry("A1", 5) }, + modified: {}, + deleted: {}, + }, + }), + ], + NOW, + ); + expect(session?.pushes).toBe(3); + expect(session?.changes).toEqual({ + added: { "a.md": entry("A2", 9) }, + modified: {}, + deleted: { "b.md": entry("B1") }, + }); + }); + + it("hides a version that changed no vault file, unless it is pinned", () => { + const hidden = version(NOW - 2 * HOUR, { files: none }); + const pinned = version(NOW - 3 * HOUR, { files: none, pinned: true }); + const shown = version(NOW - 4 * HOUR); + + const list = sessionsOf([hidden, pinned, shown], NOW); + + expect( + list.flatMap((session) => session.versions.map((v) => v.id)), + ).toEqual([pinned.id, shown.id]); + }); + + it("hands HEAD to the newest shown version when the head version is hidden", () => { + const head = version(NOW - 2 * HOUR, { files: none, isHead: true }); + const older = version(NOW - 3 * HOUR); + + const list = sessionsOf([head, older], NOW); + + const shown = list.flatMap((session) => session.versions); + expect(shown.map((v) => [v.id, v.isHead])).toEqual([[older.id, true]]); + }); + + it("keeps HEAD where it is when the head version is shown", () => { + const head = version(NOW - 2 * HOUR, { isHead: true }); + const empty = version(NOW - 3 * HOUR, { files: none }); + const older = version(NOW - 4 * HOUR); + + const list = sessionsOf([head, empty, older], NOW); + + const shown = list.flatMap((session) => session.versions); + expect(shown.map((v) => [v.id, v.isHead])).toEqual([ + [head.id, true], + [older.id, false], + ]); + }); + + it("never hands HEAD to an off-walk pin, which holds another state", () => { + const head = version(NOW - 2 * HOUR, { files: none, isHead: true }); + const pin = version(NOW - 30 * HOUR, { files: null, pinned: true }); + + const list = sessionsOf([head, pin], NOW); + + const shown = list.flatMap((session) => session.versions); + expect(shown.map((v) => [v.id, v.isHead])).toEqual([[pin.id, false]]); + }); + + it("makes no version HEAD when the hidden newest one was not", () => { + const empty = version(NOW - 2 * HOUR, { files: none }); + const older = version(NOW - 3 * HOUR); + + const list = sessionsOf([empty, older], NOW); + + const shown = list.flatMap((session) => session.versions); + expect(shown.map((v) => [v.id, v.isHead])).toEqual([[older.id, false]]); + }); + + it("knows nothing of a session with a version no record explains", () => { + const [session] = sessionsOf( + [ + version(NOW - 2 * HOUR, { files: null }), + version(NOW - 2 * HOUR - MINUTE), + ], + NOW, + ); + expect(session?.changes).toBeNull(); + }); +}); diff --git a/packages/plugin/tests/features/source-control/timeline/snapshot-menu.test.ts b/packages/plugin/tests/features/source-control/timeline/snapshot-menu.test.ts new file mode 100644 index 00000000..26aa6409 --- /dev/null +++ b/packages/plugin/tests/features/source-control/timeline/snapshot-menu.test.ts @@ -0,0 +1,68 @@ +import type { Menu } from "obsidian"; +import { describe, expect, it, vi } from "vitest"; +import type { SourceControlHost } from "@/features/source-control/host"; +import { addSnapshotPinItems } from "@/features/source-control/timeline/snapshot-menu"; + +vi.mock("@/core/ui/notices", () => ({ + notifyError: vi.fn(), + notifyInfo: vi.fn(), +})); + +interface Item { + title: string; + click: () => unknown; +} + +/** Records each item's title and click. */ +function recordingMenu(): { menu: Menu; items: Item[] } { + const items: Item[] = []; + const menu = { + addItem(build: (item: unknown) => void) { + const item: Item & Record = { + title: "", + click: () => undefined, + setTitle(title: string) { + item.title = title; + return item; + }, + setIcon: () => item, + setDisabled: () => item, + onClick(click: () => unknown) { + item.click = click; + return item; + }, + }; + build(item); + items.push(item); + return menu; + }, + }; + return { menu: menu as unknown as Menu, items }; +} + +describe("addSnapshotPinItems", () => { + it("unpins in the space of the file whose History it came from", async () => { + const setSnapshotPinned = vi.fn().mockResolvedValue(undefined); + const plugin = { + controller: { history: { setSnapshotPinned } }, + } as unknown as SourceControlHost; + const { menu, items } = recordingMenu(); + const changed = vi.fn(); + + addSnapshotPinItems( + menu, + plugin, + { snapshotId: "s1", pinned: true, label: "", path: "Shared/a.md" }, + changed, + ); + await items.find(({ title }) => title === "Unpin")?.click(); + await vi.waitFor(() => expect(changed).toHaveBeenCalled()); + + expect(setSnapshotPinned).toHaveBeenCalledExactlyOnceWith( + "s1", + false, + undefined, + "Shared/a.md", + ); + }); +}); diff --git a/packages/plugin/tests/ui/timeline-actions.test.ts b/packages/plugin/tests/features/source-control/timeline/timeline-actions.test.ts similarity index 86% rename from packages/plugin/tests/ui/timeline-actions.test.ts rename to packages/plugin/tests/features/source-control/timeline/timeline-actions.test.ts index 66a75b0c..f525b9ab 100644 --- a/packages/plugin/tests/ui/timeline-actions.test.ts +++ b/packages/plugin/tests/features/source-control/timeline/timeline-actions.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import type { PluginHost } from "@/plugin/host"; -import { TimelineActions } from "@/ui/source-control/timeline-actions"; -import type { TimelineFileRow } from "@/ui/source-control/timeline-rows"; +import type { PluginHost } from "@/app/host"; +import { TimelineActions } from "@/features/source-control/timeline/timeline-actions"; +import type { TimelineFileRow } from "@/features/source-control/timeline/timeline-rows"; const { confirmRestore, notifyError, notifyInfo } = vi.hoisted(() => ({ confirmRestore: vi.fn(), @@ -9,8 +9,8 @@ const { confirmRestore, notifyError, notifyInfo } = vi.hoisted(() => ({ notifyInfo: vi.fn(), })); -vi.mock("@/ui/source-control/restore-modal", () => ({ confirmRestore })); -vi.mock("@/ui/common/notices", () => ({ notifyError, notifyInfo })); +vi.mock("@/features/diff/ui/restore-modal", () => ({ confirmRestore })); +vi.mock("@/core/ui/notices", () => ({ notifyError, notifyInfo })); const before = { hash: "before", label: "Before push", size: 100 }; const after = { hash: "after", label: "After push", size: 120 }; @@ -58,6 +58,7 @@ describe("Timeline file restoration", () => { expect(restoreFileVersion).toHaveBeenCalledExactlyOnceWith( file.path, file.version.hash, + file.path, ); }, ); diff --git a/packages/plugin/tests/ui/timeline-rows.test.ts b/packages/plugin/tests/features/source-control/timeline/timeline-rows.test.ts similarity index 74% rename from packages/plugin/tests/ui/timeline-rows.test.ts rename to packages/plugin/tests/features/source-control/timeline/timeline-rows.test.ts index 572b91e4..1ca7a823 100644 --- a/packages/plugin/tests/ui/timeline-rows.test.ts +++ b/packages/plugin/tests/features/source-control/timeline/timeline-rows.test.ts @@ -1,18 +1,26 @@ -import { describe, expect, it } from "vitest"; -import type { - SnapshotChanges, - SnapshotSummary, - VaultRestorePlan, -} from "@/sync/history"; -import type { EFileKind, ManifestEntry } from "@/sync/types"; +import { describe, expect, it, vi } from "vitest"; +import { formatTimestamp } from "@/core/shared"; +import { clockTime } from "@/features/source-control/history/age-groups"; import { buildTimelineRows, countsText, describeRestorePlan, samplePaths, + summaryOf, type TimelineFileRow, timelineDiffTarget, -} from "@/ui/source-control/timeline-rows"; +} from "@/features/source-control/timeline/timeline-rows"; +import type { VaultRestorePlan } from "@/features/sync/history/restore-vault"; +import type { + SnapshotChanges, + SnapshotSummary, +} from "@/features/sync/history/types"; +import type { EFileKind, ManifestEntry } from "@/features/sync/types"; + +vi.mock("@/core/shared", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, formatTimestamp: vi.fn(actual.formatTimestamp) }; +}); const NOW = 1_700_000_000_000; const DAY = 86_400_000; @@ -37,9 +45,13 @@ function snapshot(overrides: Partial = {}): SnapshotSummary { deviceId: "device-abcdef123456", pinned: false, files: changes({ added: { "a.md": entry("A1", 10) } }), - rank: 0, + keptUntil: null, restorable: true, isHead: false, + at: NOW - DAY, + firstAt: NOW - DAY, + pushes: 1, + res: "push", ...overrides, }; } @@ -52,35 +64,31 @@ describe("countsText", () => { it("names only the parts that actually changed", () => { expect( countsText( - snapshot({ - files: changes({ - added: { a: entry("A1") }, - modified: { - b: { from: entry("B1"), to: entry("B2") }, - c: { from: entry("C1"), to: entry("C2") }, - }, - }), + changes({ + added: { a: entry("A1") }, + modified: { + b: { from: entry("B1"), to: entry("B2") }, + c: { from: entry("C1"), to: entry("C2") }, + }, }), ), ).toBe("+1 new · 2 changed"); }); it("says so when a push changed no files", () => { - expect(countsText(snapshot({ files: changes() }))).toBe("no file changes"); + expect(countsText(changes())).toBe("no file changes"); }); it("stays null when no record explains the snapshot", () => { - expect(countsText(snapshot({ files: null }))).toBeNull(); + expect(countsText(null)).toBeNull(); }); it("works with records not arrays", () => { expect( countsText( - snapshot({ - files: changes({ - added: { x: entry("X1"), y: entry("Y1") }, - deleted: { z: entry("Z1") }, - }), + changes({ + added: { x: entry("X1"), y: entry("Y1") }, + deleted: { z: entry("Z1") }, }), ), ).toBe("+2 new · 1 removed"); @@ -94,24 +102,18 @@ describe("buildTimelineRows", () => { snapshot({ id: "s2", createdAt: NOW, isHead: true }), snapshot({ isHead: false }), ], - { now: NOW }, + NOW, ); expect(rows[0]?.isHead).toBe(true); expect(rows[1]?.isHead).toBe(false); }); - it("titles a push from today by age and an older one by its clock time", () => { - const rows = buildTimelineRows( - [snapshot({ id: "s2", createdAt: NOW - 60_000 }), snapshot()], - { now: NOW }, - ); - expect(rows[0]?.title).toBe("1 minute ago"); - expect(rows[1]?.title).toBe( - new Date(NOW - DAY).toLocaleTimeString(undefined, { - hour: "2-digit", - minute: "2-digit", - }), + it("titles a push by its storage time, not the device clock", () => { + const [row] = buildTimelineRows( + [snapshot({ createdAt: NOW - 3 * DAY, at: NOW - 60_000 })], + NOW, ); + expect(row?.title).toBe(clockTime(NOW - 60_000)); }); it("counts each kind of change for the chips, leaving out the empty ones", () => { @@ -125,7 +127,7 @@ describe("buildTimelineRows", () => { }, }), ], - { now: NOW }, + NOW, ); expect(row?.tally).toEqual([ ["add", 1], @@ -136,7 +138,7 @@ describe("buildTimelineRows", () => { it("real HEAD versus lagging entry", () => { const rows = buildTimelineRows( [snapshot({ id: "old", createdAt: NOW - DAY, isHead: false })], - { now: NOW }, + NOW, ); expect(rows[0]?.isHead).toBe(false); }); @@ -144,19 +146,15 @@ describe("buildTimelineRows", () => { it("prefers a pin's name over the timestamp", () => { const [row] = buildTimelineRows( [snapshot({ pinned: true, label: " before the rewrite " })], - { now: NOW }, + NOW, ); expect(row?.title).toBe("before the rewrite"); expect(row?.pinned).toBe(true); expect(row?.label).toBe("before the rewrite"); - // The age leaves the title, so it moves to the meta line. - expect(row?.meta).toContain("1 day ago"); }); it("carries restorability through untouched", () => { - const [row] = buildTimelineRows([snapshot({ restorable: false })], { - now: NOW, - }); + const [row] = buildTimelineRows([snapshot({ restorable: false })], NOW); expect(row?.restorable).toBe(false); }); @@ -174,7 +172,7 @@ describe("buildTimelineRows", () => { }), }), ], - { now: NOW }, + NOW, ); expect(row?.files).toHaveLength(3); const [first, second, third] = row?.files ?? []; @@ -201,6 +199,27 @@ describe("buildTimelineRows", () => { expect(third?.after?.hash).toBe("N1"); }); + it("restores a merged deletion to the content right before it, not the parent's", () => { + const [row] = buildTimelineRows( + [ + snapshot({ + files: changes({ + deleted: { "a.md": entry("A1", 10) }, + deletedLast: { "a.md": entry("A2", 30) }, + }), + }), + ], + NOW, + ); + const [file] = row?.files ?? []; + expect(file).toMatchObject({ + action: "delete", + version: { hash: "A2", size: 30 }, + before: { hash: "A2" }, + size: 30, + }); + }); + it("deletion preserves pre-delete version with size", () => { const [row] = buildTimelineRows( [ @@ -211,7 +230,7 @@ describe("buildTimelineRows", () => { }), }), ], - { now: NOW }, + NOW, ); const file = row?.files?.[0]; expect(file?.action).toBe("delete"); @@ -229,7 +248,7 @@ describe("buildTimelineRows", () => { }), }), ], - { now: NOW }, + NOW, ); const file = row?.files?.[0]; expect(file?.action).toBe("add"); @@ -247,7 +266,7 @@ describe("buildTimelineRows", () => { }), }), ], - { now: NOW }, + NOW, ); expect(row?.files?.[0]?.path).toBe("constructor"); }); @@ -264,7 +283,7 @@ describe("buildTimelineRows", () => { }), }), ], - { now: NOW }, + NOW, ); const file = row?.files?.[0]; expect(file?.before?.hash).toBe("OLD"); @@ -275,7 +294,7 @@ describe("buildTimelineRows", () => { }); it("files is null when snapshot has no change record", () => { - const [row] = buildTimelineRows([snapshot({ files: null })], { now: NOW }); + const [row] = buildTimelineRows([snapshot({ files: null })], NOW); expect(row?.files).toBeNull(); }); @@ -293,7 +312,7 @@ describe("buildTimelineRows", () => { }), }), ], - { now: NOW }, + NOW, ); const [modified, deleted, added] = row?.files ?? []; expect(modified?.size).toBe(250); @@ -317,7 +336,7 @@ describe("buildTimelineRows", () => { }), }), ], - { now: NOW }, + NOW, ); // 3072 added, 1024 lost on the edit, 1024 removed. expect(row?.netDelta).toBe(1024); @@ -334,12 +353,10 @@ describe("buildTimelineRows", () => { }), }), ], - { now: NOW }, + NOW, ); expect(even?.netDelta).toBeNull(); - const [unknown] = buildTimelineRows([snapshot({ files: null })], { - now: NOW, - }); + const [unknown] = buildTimelineRows([snapshot({ files: null })], NOW); expect(unknown?.netDelta).toBeNull(); }); }); @@ -355,12 +372,12 @@ describe("timelineDiffTarget", () => { sizeDelta: 100, }; - it("current mode returns version with previewIfMissing", () => { - const target = timelineDiffTarget(fileRow, "current"); - expect(target.hash).toBe("NEW"); - expect(target.size).toBe(200); - expect(target.previewIfMissing).toBe(true); - expect(target.change).toBeUndefined(); + it("current mode returns the version alone", () => { + expect(timelineDiffTarget(fileRow, "current")).toEqual({ + hash: "NEW", + label: "after push", + size: 200, + }); }); it("change mode returns version with before/after change", () => { @@ -368,12 +385,10 @@ describe("timelineDiffTarget", () => { expect(target.hash).toBe("NEW"); expect(target.change?.before?.hash).toBe("OLD"); expect(target.change?.after?.hash).toBe("NEW"); - expect(target.previewIfMissing).toBeUndefined(); }); it("defaults to current mode", () => { - const target = timelineDiffTarget(fileRow); - expect(target.previewIfMissing).toBe(true); + expect(timelineDiffTarget(fileRow).change).toBeUndefined(); }); it("targets do not lose sizes", () => { @@ -459,13 +474,73 @@ describe("samplePaths", () => { }); }); +describe("summaryOf", () => { + it("words the counts as countsText does, from the tally it returns", () => { + const record = changes({ + added: { a: entry("A1", 4) }, + deleted: { b: entry("B1", 1), c: entry("C1", 1) }, + }); + expect(summaryOf(record)).toMatchObject({ + counts: "+1 new · 2 removed", + tally: [ + ["add", 1], + ["delete", 2], + ], + fileCount: 3, + }); + expect(summaryOf(record).counts).toBe(countsText(record)); + expect(summaryOf(changes()).counts).toBe(countsText(changes())); + expect(summaryOf(null).counts).toBeNull(); + }); +}); + describe("buildTimelineRows file rows", () => { + it("formats the push time once for all of its files", () => { + const at = NOW - DAY; + const [row] = buildTimelineRows( + [ + snapshot({ + at, + files: changes({ + added: { "a.md": entry("A1"), "b.md": entry("B1") }, + modified: { + "c.md": { from: entry("C1"), to: entry("C2") }, + "d.md": { from: entry("D1"), to: entry("D2") }, + }, + deleted: { "e.md": entry("E1") }, + }), + }), + ], + NOW, + ); + const stamp = formatTimestamp(at); + vi.mocked(formatTimestamp).mockClear(); + + const files = row?.files ?? []; + + expect(formatTimestamp).toHaveBeenCalledTimes(1); + expect(files.map((file) => file.before?.label)).toEqual([ + undefined, + undefined, + `${stamp} (before push)`, + `${stamp} (before push)`, + `${stamp} (before push)`, + ]); + expect(files.map((file) => file.after?.label)).toEqual([ + `${stamp} (after push)`, + `${stamp} (after push)`, + `${stamp} (after push)`, + `${stamp} (after push)`, + undefined, + ]); + }); + it("builds them on first read and reuses them across redraws", () => { const summary = snapshot({ files: changes({ added: { "a.md": entry("A1") } }), }); - const [first] = buildTimelineRows([summary], { now: NOW }); - const [again] = buildTimelineRows([summary], { now: NOW }); + const [first] = buildTimelineRows([summary], NOW); + const [again] = buildTimelineRows([summary], NOW); expect(first?.files).toBe(first?.files); expect(again?.files).toBe(first?.files); diff --git a/packages/plugin/tests/features/source-control/timeline/timeline-tab.test.ts b/packages/plugin/tests/features/source-control/timeline/timeline-tab.test.ts new file mode 100644 index 00000000..09dfaa8c --- /dev/null +++ b/packages/plugin/tests/features/source-control/timeline/timeline-tab.test.ts @@ -0,0 +1,447 @@ +// @vitest-environment jsdom + +import { installElementMethods } from "@tests/helpers/element-methods"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { SourceControlHost } from "@/features/source-control/host"; +import { renderSessionCard } from "@/features/source-control/timeline/session-card"; +import type { SessionRow } from "@/features/source-control/timeline/session-rows"; +import { TimelineTab } from "@/features/source-control/timeline/timeline-tab"; +import type { SnapshotListResult, SnapshotSummary } from "@/features/sync"; +import type { EFileKind, ManifestEntry } from "@/features/sync/types"; +import { buildCalendar } from "@/features/sync/ui/history/calendar"; + +vi.mock("@/features/sync/ui/history/calendar", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + buildCalendar: vi.fn( + (actual as { buildCalendar: typeof buildCalendar }).buildCalendar, + ), + }; +}); +vi.mock("@/features/source-control/timeline/session-card", () => ({ + renderSessionCard: vi.fn(), +})); + +installElementMethods(); +// jsdom has no layout, so it lacks scrollIntoView. +const scrollIntoView = vi.fn(); +Element.prototype.scrollIntoView = scrollIntoView; + +const NOW = new Date(2026, 9, 28, 18, 0).getTime(); +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; +const ME = { id: "laptop", name: "Laptop" }; + +function entry(hash: string): ManifestEntry { + return { hash, size: 1, mtime: 1, kind: "vault" as EFileKind }; +} + +function version(id: string, at: number, path: string): SnapshotSummary { + return { + id, + createdAt: at, + deviceId: "laptop", + pinned: false, + files: { added: { [path]: entry(id) }, modified: {}, deleted: {} }, + keptUntil: null, + restorable: true, + isHead: false, + at, + firstAt: at, + pushes: 1, + res: "push", + }; +} + +/** Two close pushes of one device: one session, whose changes are composed. */ +function loaded(): SnapshotListResult { + return { + snapshots: [ + version("s2", NOW - 20 * MINUTE, "b.md"), + version("s1", NOW - 25 * MINUTE, "a.md"), + ], + lagging: false, + truncated: false, + activity: {}, + }; +} + +const settled = () => new Promise((resolve) => setTimeout(resolve, 0)); + +function harness(results: SnapshotListResult[]) { + const listSnapshots = vi.fn( + async () => results.shift() as SnapshotListResult, + ); + const plugin = { + app: {}, + settings: { fileHistoryEnabled: true, fileHistoryActivity: false }, + controller: { + history: { listSnapshots }, + currentDevice: () => ME, + }, + } as unknown as SourceControlHost; + let tab!: TimelineTab; + let pane!: HTMLElement; + const draw = () => { + pane = document.createElement("div"); + tab.render(pane, document.createElement("div")); + }; + tab = new TimelineTab(plugin, draw, vi.fn(), vi.fn()); + return { + tab, + draw, + listSnapshots, + pane: () => pane, + }; +} + +/** One push per hour on its own path, newest first: each is a session of its own. */ +function many(count: number): SnapshotListResult { + return { + snapshots: Array.from({ length: count }, (_, index) => + version(`s${index}`, NOW - index * HOUR, `n${index}.md`), + ), + lagging: false, + truncated: false, + activity: {}, + }; +} + +function pagerOf(pane: HTMLElement) { + const buttons = Array.from( + pane.querySelectorAll( + ".mdsync-history-row-actions button", + ), + ); + return { + meta: pane.querySelector( + ".mdsync-history-row-actions .mdsync-history-row-meta", + )?.textContent, + next: buttons.find((button) => button.textContent === "Next page"), + }; +} + +/** The session rows the last render handed to the cards, and the card context. */ +function lastDrawn() { + const calls = vi.mocked(renderSessionCard).mock.calls; + const rows: SessionRow[] = calls.map(([, row]) => row); + return { rows, ctx: calls[calls.length - 1]?.[2] }; +} + +describe("TimelineTab session rows", () => { + beforeEach(() => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(NOW); + vi.mocked(renderSessionCard).mockClear(); + }); + afterEach(() => vi.useRealTimers()); + + it("keeps the composed changes across UI-only rerenders of one result", async () => { + const { draw, listSnapshots } = harness([loaded()]); + draw(); + await settled(); + const [first] = lastDrawn().rows; + expect(first?.versions).toHaveLength(2); + // File rows are cached by the composed changes object, so the same array means the same changes. + const files = first?.files; + expect(files?.map((file) => file.path)).toEqual(["a.md", "b.md"]); + + // Expanding a card redraws the pane without loading anything. + const { ctx } = lastDrawn(); + vi.mocked(renderSessionCard).mockClear(); + ctx?.toggle(first?.key ?? ""); + draw(); + + const [expanded, again] = lastDrawn().rows; + expect(vi.mocked(renderSessionCard)).toHaveBeenCalledTimes(2); + expect(expanded).toBe(first); + expect(again).toBe(first); + expect(again?.files).toBe(files); + expect(listSnapshots).toHaveBeenCalledTimes(1); + }); + + it("says no pushes only when none was recorded, not when every version is hidden", async () => { + const hidden = (activity: SnapshotListResult["activity"]) => ({ + ...loaded(), + snapshots: [ + { + ...version("s1", NOW - HOUR, "a.md"), + files: { added: {}, modified: {}, deleted: {} }, + }, + ], + activity, + }); + const { tab, draw, pane } = harness([ + hidden({}), + hidden({ [Math.floor((NOW - HOUR) / HOUR)]: [2, 0] }), + ]); + draw(); + await settled(); + expect(pane().textContent).toContain("No pushes yet"); + + tab.clear(); + draw(); + await settled(); + expect(pane().textContent).not.toContain("No pushes yet"); + }); + + it("builds new rows once a new result loads", async () => { + const { tab, draw, listSnapshots } = harness([loaded(), loaded()]); + draw(); + await settled(); + draw(); + const [first] = lastDrawn().rows; + const files = first?.files; + + tab.clear(); + draw(); + await settled(); + vi.mocked(renderSessionCard).mockClear(); + draw(); + + const [next] = lastDrawn().rows; + expect(listSnapshots).toHaveBeenCalledTimes(2); + expect(next).not.toBe(first); + expect(next?.files).not.toBe(files); + expect(next?.files?.map((file) => file.path)).toEqual(["a.md", "b.md"]); + }); + + it("rebuilds when the clock moves to another minute", async () => { + const { draw } = harness([loaded()]); + draw(); + await settled(); + draw(); + const [first] = lastDrawn().rows; + + vi.setSystemTime(NOW + MINUTE); + vi.mocked(renderSessionCard).mockClear(); + draw(); + + expect(lastDrawn().rows[0]).not.toBe(first); + }); + + it("rebuilds when a push leaves the last hour within a minute", async () => { + const at = NOW + 30_000; + const result = loaded(); + result.snapshots = [version("s1", at, "a.md")]; + vi.setSystemTime(at + 60 * MINUTE - 10_000); + const { draw } = harness([result]); + draw(); + await settled(); + draw(); + const [first] = lastDrawn().rows; + + vi.setSystemTime(at + 60 * MINUTE + 10_000); + vi.mocked(renderSessionCard).mockClear(); + draw(); + + expect(lastDrawn().rows[0]).not.toBe(first); + }); +}); + +describe("TimelineTab calendar", () => { + beforeEach(() => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(NOW); + vi.mocked(buildCalendar).mockClear(); + }); + afterEach(() => vi.useRealTimers()); + + it("builds the calendar once per result and day, not on every redraw", async () => { + const { tab, draw } = harness([loaded(), loaded()]); + draw(); + await settled(); + draw(); + draw(); + expect(buildCalendar).toHaveBeenCalledTimes(1); + + vi.setSystemTime(NOW + DAY); + draw(); + expect(buildCalendar).toHaveBeenCalledTimes(2); + + tab.clear(); + draw(); + await settled(); + expect(buildCalendar).toHaveBeenCalledTimes(3); + }); +}); + +describe("TimelineTab picked day", () => { + const zone = process.env.TZ; + beforeEach(() => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(NOW); + vi.mocked(renderSessionCard).mockClear(); + }); + afterEach(() => { + vi.useRealTimers(); + if (zone === undefined) delete process.env.TZ; + else process.env.TZ = zone; + }); + + async function pick(result: SnapshotListResult, day: number) { + const { tab, draw } = harness([result]); + tab.showDay(day); + draw(); + await settled(); + return lastDrawn().rows.map((row) => row.key); + } + + it("lists a pinned version of the picked day, pinned first, and none of a later day", async () => { + const day = new Date(2026, 9, 25).getTime(); + const at = (hour: number) => new Date(2026, 9, 25, hour).getTime(); + const pin = (id: string, when: number) => ({ + ...version(id, when, `${id}.md`), + pinned: true, + }); + const keys = await pick( + { + snapshots: [ + pin("later-pin", NOW), + version("later", NOW - HOUR, "x.md"), + version("today", at(14), "a.md"), + pin("today-pin", at(9)), + ], + lagging: false, + truncated: false, + activity: {}, + }, + day, + ); + + expect(keys).toEqual(["today-pin", "today"]); + }); + + it("ends the day at the next local midnight when midnight is skipped", async () => { + // Chile skips 2026-09-06 00:00, so that day starts at 01:00 and ends at the 7th's own midnight. + process.env.TZ = "America/Santiago"; + vi.setSystemTime(new Date(2026, 8, 9, 12)); + const keys = await pick( + { + snapshots: [ + version("monday", new Date(2026, 8, 7, 0, 30).getTime(), "b.md"), + version("sunday", new Date(2026, 8, 6, 12).getTime(), "a.md"), + ], + lagging: false, + truncated: false, + activity: {}, + }, + new Date(2026, 8, 6).getTime(), + ); + + expect(keys).toEqual(["sunday"]); + }); +}); + +describe("TimelineTab paging", () => { + beforeEach(() => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(NOW); + vi.mocked(renderSessionCard).mockClear(); + }); + afterEach(() => vi.useRealTimers()); + + it("renders 100 cards of 150 sessions with the pager, and the next page the rest", async () => { + const { draw, pane } = harness([many(150)]); + draw(); + await settled(); + vi.mocked(renderSessionCard).mockClear(); + draw(); + + expect(lastDrawn().rows.map((row) => row.key)).toEqual( + Array.from({ length: 100 }, (_, index) => `s${index}`), + ); + expect(pagerOf(pane()).meta).toBe("1-100 of 150"); + + vi.mocked(renderSessionCard).mockClear(); + scrollIntoView.mockClear(); + pagerOf(pane()).next?.click(); + + expect(lastDrawn().rows.map((row) => row.key)).toEqual( + Array.from({ length: 50 }, (_, index) => `s${index + 100}`), + ); + // The new page reads from its first card, not from the calendar above it. + expect(scrollIntoView).toHaveBeenCalledTimes(1); + expect(pagerOf(pane()).meta).toBe("101-150 of 150"); + }); + + it("repeats the age header at the top of a page when its group continues", async () => { + const { draw, pane } = harness([many(150)]); + draw(); + await settled(); + draw(); + const headers = (el: HTMLElement) => + Array.from( + el.querySelectorAll(".mdsync-timeline-day span:first-child"), + ).map((span) => span.textContent); + const first = headers(pane()); + pagerOf(pane()).next?.click(); + + // Hourly pushes cross a few days, so the day cut by the page edge heads both pages. + expect(first.at(-1)).toBe(headers(pane())[0]); + }); + + it("keeps the page across UI-only rerenders", async () => { + const { draw, pane } = harness([many(150)]); + draw(); + await settled(); + draw(); + pagerOf(pane()).next?.click(); + const { ctx } = lastDrawn(); + vi.mocked(renderSessionCard).mockClear(); + + ctx?.toggle("s100"); + + expect(lastDrawn().rows).toHaveLength(50); + expect(pagerOf(pane()).meta).toBe("101-150 of 150"); + }); + + it("starts over at page 1 on a new filter", async () => { + const { draw, pane } = harness([many(150)]); + draw(); + await settled(); + draw(); + pagerOf(pane()).next?.click(); + vi.mocked(renderSessionCard).mockClear(); + + // Every path ends in .md, so all 150 still match and only the query changed. + const filter = pane().querySelector( + ".mdsync-timeline-filter input", + ); + if (!filter) throw new Error("no filter input"); + filter.value = ".md"; + filter.dispatchEvent(new Event("input")); + + expect(lastDrawn().rows).toHaveLength(100); + expect(lastDrawn().rows[0]?.key).toBe("s0"); + expect(pagerOf(pane()).meta).toBe("1-100 of 150"); + }); + + it("starts over at page 1 on a new result", async () => { + const { tab, draw, pane } = harness([many(150), many(150)]); + draw(); + await settled(); + draw(); + pagerOf(pane()).next?.click(); + + tab.clear(); + draw(); + await settled(); + vi.mocked(renderSessionCard).mockClear(); + draw(); + + expect(lastDrawn().rows).toHaveLength(100); + expect(pagerOf(pane()).meta).toBe("1-100 of 150"); + }); + + it("shows no pager for a short list", async () => { + const { draw, pane } = harness([many(100)]); + draw(); + await settled(); + draw(); + + expect(pagerOf(pane()).meta).toBeUndefined(); + }); +}); diff --git a/packages/plugin/tests/ui/trash-rows.test.ts b/packages/plugin/tests/features/source-control/trash/trash-rows.test.ts similarity index 63% rename from packages/plugin/tests/ui/trash-rows.test.ts rename to packages/plugin/tests/features/source-control/trash/trash-rows.test.ts index f30f52cd..d8a5cd64 100644 --- a/packages/plugin/tests/ui/trash-rows.test.ts +++ b/packages/plugin/tests/features/source-control/trash/trash-rows.test.ts @@ -1,17 +1,18 @@ import { describe, expect, it } from "vitest"; -import { formatRelativeTime } from "@/shared"; -import type { DeletedFile } from "@/sync/history"; -import type { EFileKind } from "@/sync/types"; +import { formatDay, formatRelativeTime } from "@/core/shared/format"; import { buildTrashRows, resolveRestoreTarget, retentionText, -} from "@/ui/source-control/trash-rows"; +} from "@/features/source-control/trash/trash-rows"; +import type { DeletedFile } from "@/features/sync/history/types"; +import type { EFileKind } from "@/features/sync/types"; const NOW = 1_700_000_000_000; const KIND = "vault" as EFileKind; const HOUR = 3_600_000; const DAY = 24 * HOUR; +const KEPT_UNTIL = NOW + 30 * DAY; function deleted(overrides: Partial = {}): DeletedFile { return { @@ -21,7 +22,8 @@ function deleted(overrides: Partial = {}): DeletedFile { source: "deleted", createdAt: NOW - 3 * DAY, deviceId: "device-abcdef123456", - rank: 0, + pinned: false, + keptUntil: KEPT_UNTIL, ...overrides, }; } @@ -38,7 +40,7 @@ describe("formatRelativeTime", () => { it("switches to a date once the distance stops being useful", () => { const old = formatRelativeTime(NOW - 60 * DAY, NOW); expect(old).not.toContain("ago"); - expect(old).toBe(new Date(NOW - 60 * DAY).toLocaleDateString()); + expect(old).toBe(formatDay(NOW - 60 * DAY, NOW, false)); }); it("treats a clock-skewed future stamp as now, not as negative time", () => { @@ -47,46 +49,49 @@ describe("formatRelativeTime", () => { }); describe("retentionText", () => { - it("counts remaining pushes against the retention limit", () => { - expect(retentionText(0, 50)).toBe( - "Drops out of history after 50 more pushes", - ); - expect(retentionText(49, 50)).toBe( - "Drops out of history after 1 more push", + it("names the date history keeps the record until", () => { + expect(retentionText({ pinned: false, keptUntil: KEPT_UNTIL }, NOW)).toBe( + `Kept until ${formatDay(KEPT_UNTIL, NOW, false)}`, ); }); - it("warns when GC has not caught up with the limit yet", () => { - // GC is amortised, so records can outlive the limit and still be listed. - expect(retentionText(55, 50)).toBe( - "Drops out of history at the next cleanup", + it("still names a date that has passed while cleanup has not caught up", () => { + // Retention promises "at least": a record can outlive its date and still be listed. + const past = NOW - DAY; + expect(retentionText({ pinned: false, keptUntil: past }, NOW)).toBe( + `Kept until ${formatDay(past, NOW, false)}`, ); }); - it("warns on the exact push that reaches the limit", () => { - expect(retentionText(50, 50)).toBe( - "Drops out of history at the next cleanup", - ); + it("says nothing when no date applies", () => { + expect(retentionText({ pinned: false, keptUntil: null }, NOW)).toBeNull(); }); it("says a pin holds the record", () => { - expect(retentionText(null, 50)).toBe("Kept by a pinned snapshot"); + expect(retentionText({ pinned: true, keptUntil: null }, NOW)).toBe( + "Kept by a pinned snapshot", + ); + }); + + it("lets a pin win over a date", () => { + expect(retentionText({ pinned: true, keptUntil: KEPT_UNTIL }, NOW)).toBe( + "Kept by a pinned snapshot", + ); }); }); describe("buildTrashRows", () => { it("describes a deletion with time, device and size", () => { const [row] = buildTrashRows([deleted()], { - maxSnapshots: 50, now: NOW, currentDevice: null, }); expect(row?.title).toBe("notes/gone.md"); expect(row?.hash).toBe("H1"); - expect(row?.meta).toBe("deleted 3 days ago · Device device-a · 2.0 KB"); + expect(row?.meta).toBe("deleted 3 days ago · 2.0 KB · Device device-a"); expect(row?.note).toEqual({ - text: "Drops out of history after 50 more pushes", + text: `Kept until ${formatDay(KEPT_UNTIL, NOW, false)}`, tone: "plain", icon: "hourglass", }); @@ -94,22 +99,39 @@ describe("buildTrashRows", () => { }); it("has nothing to build from an empty list", () => { - expect(buildTrashRows([], { maxSnapshots: 50 })).toEqual([]); + expect(buildTrashRows([], {})).toEqual([]); }); - it("colours a record that drops out within a few pushes", () => { + it("colours a record whose retention ends within a week or already has", () => { const rows = buildTrashRows( - [deleted({ rank: 47 }), deleted({ rank: 46 })], - { maxSnapshots: 50, now: NOW }, + [ + deleted({ keptUntil: NOW - DAY }), + deleted({ keptUntil: NOW + 6 * DAY }), + deleted({ keptUntil: NOW + 7 * DAY }), + deleted({ keptUntil: NOW + 8 * DAY }), + ], + { now: NOW }, ); - expect(rows.map((row) => row.note?.tone)).toEqual(["soon", "plain"]); + expect(rows.map((row) => row.note?.tone)).toEqual([ + "soon", + "soon", + "soon", + "plain", + ]); + }); + + it("leaves a deletion with no end date without a note", () => { + const [row] = buildTrashRows([deleted({ keptUntil: null })], { + now: NOW, + }); + expect(row?.note).toBeNull(); + expect(row?.pinned).toBe(false); }); it("marks a file that is back in the vault as restored", () => { const rows = buildTrashRows( [deleted(), deleted({ path: "notes/other.md" })], { - maxSnapshots: 50, now: NOW, inVault: (path) => path === "notes/gone.md", }, @@ -118,21 +140,19 @@ describe("buildTrashRows", () => { }); it("treats every file as still deleted without a vault to ask", () => { - const [row] = buildTrashRows([deleted()], { maxSnapshots: 50, now: NOW }); + const [row] = buildTrashRows([deleted()], { now: NOW }); expect(row?.note?.tone).toBe("plain"); }); it("dates against the wall clock when no time is supplied", () => { - const [row] = buildTrashRows([deleted({ createdAt: Date.now() })], { - maxSnapshots: 50, - }); + const [row] = buildTrashRows([deleted({ createdAt: Date.now() })], {}); expect(row?.meta).toContain("deleted just now"); }); it("reports an empty file without collapsing its size", () => { const [row] = buildTrashRows( [deleted({ entry: { hash: "E", size: 0, mtime: 1, kind: KIND } })], - { maxSnapshots: 50, now: NOW }, + { now: NOW }, ); expect(row?.meta).toContain("0 B"); expect(row?.size).toBe(0); @@ -140,7 +160,6 @@ describe("buildTrashRows", () => { it("names this device instead of showing a raw id", () => { const [row] = buildTrashRows([deleted()], { - maxSnapshots: 50, now: NOW, currentDevice: { id: "device-abcdef123456", name: "Laptop" }, }); @@ -149,42 +168,54 @@ describe("buildTrashRows", () => { it("prefers the recorded device name over the id", () => { const [row] = buildTrashRows([deleted({ deviceName: "Phone" })], { - maxSnapshots: 50, now: NOW, }); expect(row?.meta).toContain("Phone"); }); it("keeps a bare age apart from the prefixed label", () => { - const [row] = buildTrashRows([deleted()], { maxSnapshots: 50, now: NOW }); + const [row] = buildTrashRows([deleted()], { now: NOW }); expect(row?.age).toBe("3 days ago"); expect(row?.label).toBe("deleted 3 days ago"); }); it("names the pin a file was last seen in", () => { const [row] = buildTrashRows( - [deleted({ source: "pinned", rank: null, label: "before the rewrite" })], - { maxSnapshots: 50, now: NOW }, + [ + deleted({ + source: "pinned", + pinned: true, + keptUntil: null, + label: "before the rewrite", + }), + ], + { now: NOW }, ); expect(row?.label).toBe('last seen in "before the rewrite"'); }); - it("still counts down for a deletion no pin covers", () => { - const [row] = buildTrashRows([deleted({ rank: null })], { - maxSnapshots: 50, + it("marks a deletion a pin also holds as pinned, whatever the source says", () => { + const [row] = buildTrashRows([deleted({ pinned: true, keptUntil: null })], { now: NOW, }); - // rank null means a pin holds it, whatever the source says. expect(row?.pinned).toBe(true); expect(row?.note?.text).toBe("Kept by a pinned snapshot"); expect(row?.note?.tone).toBe("pinned"); }); + it("keeps a pinned note from turning into a countdown", () => { + const [row] = buildTrashRows( + [deleted({ pinned: true, keptUntil: NOW + DAY })], + { now: NOW }, + ); + expect(row?.note?.tone).toBe("pinned"); + }); + it("says last seen, not deleted, for a file only a pin still holds", () => { - const [row] = buildTrashRows([deleted({ source: "pinned", rank: null })], { - maxSnapshots: 50, - now: NOW, - }); + const [row] = buildTrashRows( + [deleted({ source: "pinned", pinned: true, keptUntil: null })], + { now: NOW }, + ); expect(row?.meta).toContain("last seen 3 days ago"); expect(row?.pinned).toBe(true); expect(row?.note?.text).toBe("Kept by a pinned snapshot"); diff --git a/packages/plugin/tests/storage/share-broker.test.ts b/packages/plugin/tests/features/spaces/broker/share-broker.test.ts similarity index 99% rename from packages/plugin/tests/storage/share-broker.test.ts rename to packages/plugin/tests/features/spaces/broker/share-broker.test.ts index 563ff6b9..ddc9fcf1 100644 --- a/packages/plugin/tests/storage/share-broker.test.ts +++ b/packages/plugin/tests/features/spaces/broker/share-broker.test.ts @@ -3,8 +3,8 @@ import { createBrokerAdapter, listParticipants, revokeParticipant, -} from "@/storage/adapters/share-broker"; -import { ShareRefusedError } from "@/storage/types"; +} from "@/features/spaces/broker/share-broker"; +import { ShareRefusedError } from "@/features/storage/types"; interface Recorded { url: string; diff --git a/packages/plugin/tests/storage/share-signed-urls.test.ts b/packages/plugin/tests/features/spaces/broker/share-signed-urls.test.ts similarity index 98% rename from packages/plugin/tests/storage/share-signed-urls.test.ts rename to packages/plugin/tests/features/spaces/broker/share-signed-urls.test.ts index c222a41a..52bfada1 100644 --- a/packages/plugin/tests/storage/share-signed-urls.test.ts +++ b/packages/plugin/tests/features/spaces/broker/share-signed-urls.test.ts @@ -1,6 +1,6 @@ import { SIGN_BATCH_MAX } from "@mdsync/protocol"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { ShareSignedUrls } from "@/storage/adapters/share-signed-urls"; +import { ShareSignedUrls } from "@/features/spaces/broker/share-signed-urls"; const keysOf = (count: number) => Array.from({ length: count }, (_, index) => `objects/k${index}`); diff --git a/packages/plugin/tests/spaces/invite.test.ts b/packages/plugin/tests/features/spaces/invite.test.ts similarity index 93% rename from packages/plugin/tests/spaces/invite.test.ts rename to packages/plugin/tests/features/spaces/invite.test.ts index 77366270..d6932bd2 100644 --- a/packages/plugin/tests/spaces/invite.test.ts +++ b/packages/plugin/tests/features/spaces/invite.test.ts @@ -1,13 +1,17 @@ import { describe, expect, it } from "vitest"; -import { sealLink } from "@/crypto/sealed-link"; +import { sealLink } from "@/core/crypto/sealed-link"; import { acceptInvite, type Invite, inviteLink, invitePassword, readInvite, -} from "@/spaces/invite"; -import { closeRecord, isSpaceRecord, mergeRecords } from "@/spaces/record"; +} from "@/features/spaces/invite"; +import { + closeRecord, + isSpaceRecord, + mergeRecords, +} from "@/features/spaces/record"; const INVITE: Invite = { id: "share-1", diff --git a/packages/plugin/tests/spaces/owner.test.ts b/packages/plugin/tests/features/spaces/owner.test.ts similarity index 91% rename from packages/plugin/tests/spaces/owner.test.ts rename to packages/plugin/tests/features/spaces/owner.test.ts index 9ff1d6aa..4b0fc9a3 100644 --- a/packages/plugin/tests/spaces/owner.test.ts +++ b/packages/plugin/tests/features/spaces/owner.test.ts @@ -1,18 +1,21 @@ import { describe, expect, it } from "vitest"; -import { decryptJson, encryptJson } from "@/crypto"; -import { shareKey, shareStorage } from "@/spaces/access"; +import { decryptJson, encryptJson } from "@/core/crypto/cipher"; +import { shareKey, shareStorage } from "@/features/spaces/access"; import { createShare, ownerNameOf, ownerStorageConfig, renameOwner, -} from "@/spaces/owner"; +} from "@/features/spaces/owner"; import { isSpaceRecord, type ShareLocation, shareIdentity, -} from "@/spaces/record"; -import { EStorageBackend, type S3StorageConfig } from "@/storage"; +} from "@/features/spaces/record"; +import { + EStorageBackend, + type S3StorageConfig, +} from "@/features/storage/config"; const S3: S3StorageConfig = { kind: EStorageBackend.S3, diff --git a/packages/plugin/tests/spaces/records-partition.test.ts b/packages/plugin/tests/features/spaces/records-partition.test.ts similarity index 92% rename from packages/plugin/tests/spaces/records-partition.test.ts rename to packages/plugin/tests/features/spaces/records-partition.test.ts index 1776350b..768e13e9 100644 --- a/packages/plugin/tests/spaces/records-partition.test.ts +++ b/packages/plugin/tests/features/spaces/records-partition.test.ts @@ -2,13 +2,13 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { device, record } from "@tests/helpers/space-records"; import { beforeAll, describe, expect, it, vi } from "vitest"; -import { deriveKey, type EncryptionKey } from "@/crypto"; -import { spacesOf } from "@/spaces/partition"; -import { SpaceRecords } from "@/spaces/records"; -import { VAULT_SPACE } from "@/sync/space"; +import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; +import { spacesOf } from "@/features/spaces/partition"; +import { SpaceRecords } from "@/features/spaces/records"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; -vi.mock("@/spaces/partition", async (original) => { - const actual = await original(); +vi.mock("@/features/spaces/partition", async (original) => { + const actual = await original(); return { ...actual, spacesOf: vi.fn(actual.spacesOf) }; }); diff --git a/packages/plugin/tests/spaces/records.test.ts b/packages/plugin/tests/features/spaces/records.test.ts similarity index 98% rename from packages/plugin/tests/spaces/records.test.ts rename to packages/plugin/tests/features/spaces/records.test.ts index 9b297954..1e6d834d 100644 --- a/packages/plugin/tests/spaces/records.test.ts +++ b/packages/plugin/tests/features/spaces/records.test.ts @@ -1,16 +1,20 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { device, joined, record } from "@tests/helpers/space-records"; import { beforeAll, describe, expect, it } from "vitest"; -import { deriveKey, type EncryptionKey, encryptJson } from "@/crypto"; -import { mountError, spacesOf } from "@/spaces/partition"; +import { + deriveKey, + type EncryptionKey, + encryptJson, +} from "@/core/crypto/cipher"; +import { mountError, spacesOf } from "@/features/spaces/partition"; import { closeRecord, isSpaceRecord, mergeRecords, type SpaceRecord, -} from "@/spaces/record"; -import type { SpaceRecords } from "@/spaces/records"; -import { VAULT_SPACE } from "@/sync/space"; +} from "@/features/spaces/record"; +import type { SpaceRecords } from "@/features/spaces/records"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; let key: EncryptionKey; diff --git a/packages/plugin/tests/spaces/remote.test.ts b/packages/plugin/tests/features/spaces/remote.test.ts similarity index 95% rename from packages/plugin/tests/spaces/remote.test.ts rename to packages/plugin/tests/features/spaces/remote.test.ts index ff97675c..9f5a86ca 100644 --- a/packages/plugin/tests/spaces/remote.test.ts +++ b/packages/plugin/tests/features/spaces/remote.test.ts @@ -2,13 +2,17 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { RevalidatingStorage } from "@tests/helpers/revalidating-storage"; import { record } from "@tests/helpers/space-records"; import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; -import { deriveKey, type EncryptionKey, encryptJson } from "@/crypto"; -import { reportWarning } from "@/shared"; -import type { SpaceRecord } from "@/spaces/record"; -import { syncRecords } from "@/spaces/remote"; -import type { ConditionalRead, ListedObject } from "@/storage/types"; - -vi.mock("@/shared/diagnostics", async (importOriginal) => ({ +import { + deriveKey, + type EncryptionKey, + encryptJson, +} from "@/core/crypto/cipher"; +import { reportWarning } from "@/core/shared/diagnostics"; +import type { SpaceRecord } from "@/features/spaces/record"; +import { syncRecords } from "@/features/spaces/remote"; +import type { ConditionalRead, ListedObject } from "@/features/storage/types"; + +vi.mock("@/core/shared/diagnostics", async (importOriginal) => ({ ...(await importOriginal>()), reportWarning: vi.fn(), })); diff --git a/packages/plugin/tests/plugin/share-moves.test.ts b/packages/plugin/tests/features/spaces/share-moves.test.ts similarity index 96% rename from packages/plugin/tests/plugin/share-moves.test.ts rename to packages/plugin/tests/features/spaces/share-moves.test.ts index ebbd8bde..962f9787 100644 --- a/packages/plugin/tests/plugin/share-moves.test.ts +++ b/packages/plugin/tests/features/spaces/share-moves.test.ts @@ -1,8 +1,11 @@ import { TFolder } from "obsidian"; import { describe, expect, it, vi } from "vitest"; -import { createMoveFollower, registerShareRenames } from "@/plugin/share-moves"; -import type { SpaceRecord } from "@/spaces/record"; -import { SpaceRecords } from "@/spaces/records"; +import type { SpaceRecord } from "@/features/spaces/record"; +import { SpaceRecords } from "@/features/spaces/records"; +import { + createMoveFollower, + registerShareRenames, +} from "@/features/spaces/share-moves"; type MoveVault = Parameters[0]; diff --git a/packages/plugin/tests/plugin/share-registration.test.ts b/packages/plugin/tests/features/spaces/share-registration.test.ts similarity index 89% rename from packages/plugin/tests/plugin/share-registration.test.ts rename to packages/plugin/tests/features/spaces/share-registration.test.ts index 42add73a..098344f4 100644 --- a/packages/plugin/tests/plugin/share-registration.test.ts +++ b/packages/plugin/tests/features/spaces/share-registration.test.ts @@ -1,8 +1,9 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import { createShareRegistration } from "@/plugin/share-registration"; -import { DEFAULT_SETTINGS, type MdsyncSettings } from "@/settings/model"; -import type { SpaceRecord } from "@/spaces/record"; -import { SpaceRecords } from "@/spaces/records"; +import { DEFAULT_SETTINGS } from "@/app/settings"; +import type { MdsyncSettings } from "@/core/settings/model"; +import type { SpaceRecord } from "@/features/spaces/record"; +import { SpaceRecords } from "@/features/spaces/records"; +import { createShareRegistration } from "@/features/spaces/share-registration"; const broker = vi.hoisted(() => ({ listParticipants: vi.fn(async (_admin: unknown, id: string) => @@ -16,8 +17,10 @@ const broker = vi.hoisted(() => ({ ) => {}, ), })); -vi.mock("@/storage", async (importOriginal) => ({ - ...(await importOriginal>()), +vi.mock("@/features/spaces/broker/share-broker", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("@/features/spaces/broker/share-broker") + >()), ...broker, })); diff --git a/packages/plugin/tests/plugin/space-access.test.ts b/packages/plugin/tests/features/spaces/space-access.test.ts similarity index 86% rename from packages/plugin/tests/plugin/space-access.test.ts rename to packages/plugin/tests/features/spaces/space-access.test.ts index b081a3a6..1786e38c 100644 --- a/packages/plugin/tests/plugin/space-access.test.ts +++ b/packages/plugin/tests/features/spaces/space-access.test.ts @@ -1,12 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -import type { PassphraseManager } from "@/core"; -import { deriveLiveKeys, type LiveKeys } from "@/crypto/live-keys"; -import { createSpaceAccess } from "@/plugin/space-access"; -import { DEFAULT_SETTINGS, type MdsyncSettings } from "@/settings/model"; -import { VAULT_SPACE } from "@/sync/space"; - -vi.mock("@/shared/diagnostics", () => ({ reportWarning: vi.fn() })); +import { DEFAULT_SETTINGS } from "@/app/settings"; +import { deriveLiveKeys, type LiveKeys } from "@/core/crypto/live-keys"; +import type { MdsyncSettings } from "@/core/settings/model"; +import { createSpaceAccess } from "@/features/spaces/space-access"; +import type { PassphraseManager } from "@/features/sync/remote/passphrase-manager"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; + +vi.mock("@/core/shared/diagnostics", () => ({ reportWarning: vi.fn() })); const RETRY_MS = 30_000; diff --git a/packages/plugin/tests/ui/access-ended.test.ts b/packages/plugin/tests/features/spaces/ui/access-ended.test.ts similarity index 91% rename from packages/plugin/tests/ui/access-ended.test.ts rename to packages/plugin/tests/features/spaces/ui/access-ended.test.ts index f8875ef3..13fc2988 100644 --- a/packages/plugin/tests/ui/access-ended.test.ts +++ b/packages/plugin/tests/features/spaces/ui/access-ended.test.ts @@ -1,13 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { openConfirmModal } from "@/core/ui/modals/confirm-modal"; +import type { SpaceRecord } from "@/features/spaces/record"; +import { createAccessEnded } from "@/features/spaces/ui/access-ended"; -import type { SpaceRecord } from "@/spaces/record"; -import { openConfirmModal } from "@/ui/modals"; -import { createAccessEnded } from "@/ui/shares/access-ended"; - -vi.mock("@/ui/modals", () => ({ +vi.mock("@/core/ui/modals/confirm-modal", () => ({ openConfirmModal: vi.fn(async () => false), })); -vi.mock("@/ui/common/notices", () => ({ +vi.mock("@/core/ui/notices", () => ({ notifyInfo: vi.fn(), notifyError: vi.fn(), })); diff --git a/packages/plugin/tests/ui/invite-action.test.ts b/packages/plugin/tests/features/spaces/ui/invites/invite-action.test.ts similarity index 78% rename from packages/plugin/tests/ui/invite-action.test.ts rename to packages/plugin/tests/features/spaces/ui/invites/invite-action.test.ts index f4900bc4..a16504f2 100644 --- a/packages/plugin/tests/ui/invite-action.test.ts +++ b/packages/plugin/tests/features/spaces/ui/invites/invite-action.test.ts @@ -1,17 +1,17 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import type { PluginHost } from "@/plugin/host"; -import type { Invite } from "@/spaces/invite"; -import type { SpaceRecord } from "@/spaces/record"; -import { notifyInfo } from "@/ui/common/notices"; -import { mountShare } from "@/ui/shares/invite-action"; +import type { PluginHost } from "@/app/host"; +import { notifyInfo } from "@/core/ui/notices"; +import type { Invite } from "@/features/spaces/invite"; +import type { SpaceRecord } from "@/features/spaces/record"; +import { mountShare } from "@/features/spaces/ui/invites/invite-action"; -vi.mock("@/ui/actions/push-action", () => ({ scopedPaths: () => [] })); -vi.mock("@/ui/modals", () => ({ +vi.mock("@/features/sync/ui/push-action", () => ({ scopedPaths: () => [] })); +vi.mock("@/core/ui/modals/confirm-modal", () => ({ AcceptInviteModal: class {}, openConfirmModal: vi.fn(), })); -vi.mock("@/ui/common/notices", () => ({ +vi.mock("@/core/ui/notices", () => ({ notifyInfo: vi.fn(), notifyError: vi.fn(), runWithNotice: vi.fn(), diff --git a/packages/plugin/tests/editor/read-only.test.ts b/packages/plugin/tests/features/spaces/ui/read-only.test.ts similarity index 96% rename from packages/plugin/tests/editor/read-only.test.ts rename to packages/plugin/tests/features/spaces/ui/read-only.test.ts index 3b4c3f53..af19ba15 100644 --- a/packages/plugin/tests/editor/read-only.test.ts +++ b/packages/plugin/tests/features/spaces/ui/read-only.test.ts @@ -1,7 +1,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -import { registerReadOnlyLock } from "@/editor/read-only"; -import type { ExcalidrawApi, ExcalidrawView } from "@/live/drawing/excalidraw"; +import type { + ExcalidrawApi, + ExcalidrawView, +} from "@/features/live/drawing/excalidraw"; +import { registerReadOnlyLock } from "@/features/spaces/ui/read-only"; type AppState = Record; diff --git a/packages/plugin/tests/ui/share-action.test.ts b/packages/plugin/tests/features/spaces/ui/share-action.test.ts similarity index 82% rename from packages/plugin/tests/ui/share-action.test.ts rename to packages/plugin/tests/features/spaces/ui/share-action.test.ts index 8694049a..15bc35af 100644 --- a/packages/plugin/tests/ui/share-action.test.ts +++ b/packages/plugin/tests/features/spaces/ui/share-action.test.ts @@ -1,33 +1,33 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import type { PluginHost } from "@/plugin/host"; -import type { SpaceRecord } from "@/spaces/record"; -import { - EStorageBackend, - revokeParticipant, - type S3StorageConfig, -} from "@/storage"; -import { notifyInfo } from "@/ui/common/notices"; -import { RELAY_TEXT } from "@/ui/common/relay"; -import { openConfirmModal } from "@/ui/modals"; +import type { PluginHost } from "@/app/host"; +import { RELAY_TEXT } from "@/core/hub/relay-text"; +import { openConfirmModal } from "@/core/ui/modals/confirm-modal"; +import { notifyInfo } from "@/core/ui/notices"; +import { revokeParticipant } from "@/features/spaces/broker/share-broker"; +import type { SpaceRecord } from "@/features/spaces/record"; import { closeShare, revokeAccess, shareFolder, -} from "@/ui/shares/share-action"; +} from "@/features/spaces/ui/share-action"; +import { + EStorageBackend, + type S3StorageConfig, +} from "@/features/storage/config"; -vi.mock("@/ui/actions/ignore-action", () => ({ +vi.mock("@/features/sync/ui/ignore-action", () => ({ carryVaultIgnores: vi.fn(async () => true), })); -vi.mock("@/ui/actions/push-action", () => ({ pushScope: vi.fn() })); -vi.mock("@/ui/modals", () => ({ +vi.mock("@/features/sync/ui/push-action", () => ({ pushScope: vi.fn() })); +vi.mock("@/core/ui/modals/confirm-modal", () => ({ openConfirmModal: vi.fn(async () => false), })); -vi.mock("@/storage", async (original) => ({ - ...(await original()), +vi.mock("@/features/spaces/broker/share-broker", async (original) => ({ + ...(await original()), revokeParticipant: vi.fn(async () => {}), })); -vi.mock("@/ui/common/notices", () => ({ +vi.mock("@/core/ui/notices", () => ({ notifyInfo: vi.fn(), notifyError: vi.fn(), })); diff --git a/packages/plugin/tests/settings/shares-section.test.ts b/packages/plugin/tests/features/spaces/ui/shares-section.test.ts similarity index 82% rename from packages/plugin/tests/settings/shares-section.test.ts rename to packages/plugin/tests/features/spaces/ui/shares-section.test.ts index 06ad09b8..edb1c22e 100644 --- a/packages/plugin/tests/settings/shares-section.test.ts +++ b/packages/plugin/tests/features/spaces/ui/shares-section.test.ts @@ -1,11 +1,12 @@ import type { SettingDefinitionPage } from "obsidian"; import { describe, expect, it, vi } from "vitest"; -import type { FieldContext } from "@/settings/fields"; -import { sharesSection } from "@/settings/sections/shares"; +import type { FieldContext } from "@/core/settings/fields"; +import type { SpacesHost } from "@/features/spaces"; +import { sharesSection } from "@/features/spaces/ui/shares-section"; -vi.mock("@/settings/page", () => ({ imperativePage: vi.fn() })); -vi.mock("@/ui", () => ({ +vi.mock("@/core/settings/page", () => ({ imperativePage: vi.fn() })); +vi.mock("@/features/spaces/ui/invites/invite-action", () => ({ openInvite: vi.fn(), openShareWindow: vi.fn(), shareSummary: vi.fn(), @@ -17,7 +18,7 @@ function form() { const ctx = { plugin: { settings, spaces: { list: () => records } }, rerender: vi.fn(), - } as unknown as FieldContext; + } as unknown as FieldContext; const entry = sharesSection(ctx).items?.find( (item) => item.name === "Your shared folders", ) as SettingDefinitionPage; diff --git a/packages/plugin/tests/ui/share-people.test.ts b/packages/plugin/tests/features/spaces/ui/window/share-people.test.ts similarity index 91% rename from packages/plugin/tests/ui/share-people.test.ts rename to packages/plugin/tests/features/spaces/ui/window/share-people.test.ts index 095b3d57..3756c5bc 100644 --- a/packages/plugin/tests/ui/share-people.test.ts +++ b/packages/plugin/tests/features/spaces/ui/window/share-people.test.ts @@ -1,12 +1,15 @@ import { OWNER } from "@mdsync/protocol"; import { describe, expect, it } from "vitest"; - -import type { RelayStatus } from "@/hub/status"; -import type { Person } from "@/presence/people"; -import type { SpaceRecord } from "@/spaces/record"; -import type { Participant } from "@/storage"; -import { RELAY_TEXT, UNREADABLE_TEXT } from "@/ui/common/relay"; -import { presenceNote, selfRow, shareRows } from "@/ui/shares/share-people"; +import { RELAY_TEXT, UNREADABLE_TEXT } from "@/core/hub/relay-text"; +import type { RelayStatus } from "@/core/hub/status"; +import type { Person } from "@/features/presence/people"; +import type { Participant } from "@/features/spaces/broker/share-broker"; +import type { SpaceRecord } from "@/features/spaces/record"; +import { + presenceNote, + selfRow, + shareRows, +} from "@/features/spaces/ui/window/share-people"; const person = ( key: string, diff --git a/packages/plugin/tests/ui/share-summary.test.ts b/packages/plugin/tests/features/spaces/ui/window/share-summary.test.ts similarity index 92% rename from packages/plugin/tests/ui/share-summary.test.ts rename to packages/plugin/tests/features/spaces/ui/window/share-summary.test.ts index 57a78dce..7c2cfc6f 100644 --- a/packages/plugin/tests/ui/share-summary.test.ts +++ b/packages/plugin/tests/features/spaces/ui/window/share-summary.test.ts @@ -1,8 +1,8 @@ import { device, record } from "@tests/helpers/space-records"; import { describe, expect, it } from "vitest"; -import type { SpaceRecord } from "@/spaces/record"; -import { shareSummary } from "@/ui/shares/share-summary"; +import type { SpaceRecord } from "@/features/spaces/record"; +import { shareSummary } from "@/features/spaces/ui/window/share-summary"; const joined = (readOnly?: true): SpaceRecord => ({ ...record("b", "Friends"), diff --git a/packages/plugin/tests/features/status/live-spaces.test.ts b/packages/plugin/tests/features/status/live-spaces.test.ts new file mode 100644 index 00000000..c40d5eed --- /dev/null +++ b/packages/plugin/tests/features/status/live-spaces.test.ts @@ -0,0 +1,118 @@ +import { describe, expect, it } from "vitest"; +import type { RelayStatus } from "@/core/hub"; +import type { RelaySocket } from "@/features/relay"; +import type { StatusHost } from "@/features/status/host"; +import { relayGroups, sharesConnected } from "@/features/status/live-spaces"; + +const HOME = "https://relay.home.example"; +const OTHER = "https://relay.friend.example"; + +function host( + sockets: RelaySocket[], + statuses: Record, + ids = Object.keys(statuses), +): StatusHost { + return { + settings: { relayUrl: `${HOME}/`, relaySecret: "secret" }, + spaces: { partition: () => ids.map((id) => ({ id, root: id })) }, + realtime: { + hub: { + relays: () => sockets, + statusOf: (id: string) => statuses[id] ?? "off", + }, + }, + } as unknown as StatusHost; +} + +describe("relayGroups", () => { + it("puts each carried space under the socket that carries it", () => { + const groups = relayGroups( + host( + [ + { + url: HOME, + state: "connected", + spaces: ["vault", "a", "b"], + full: ["c"], + }, + { url: OTHER, state: "offline", spaces: ["d"], full: [] }, + ], + { + vault: "connected", + a: "connected", + b: "unauthorized", + c: "full", + d: "offline", + }, + ), + ); + + expect(groups).toEqual([ + { + name: "Your relay", + state: "connected", + spaces: [ + { id: "vault", status: "connected" }, + { id: "a", status: "connected" }, + { id: "b", status: "unauthorized" }, + ], + full: ["c"], + }, + { + name: "relay.friend.example", + state: "offline", + spaces: [{ id: "d", status: "offline" }], + full: [], + }, + ]); + }); + + it("leaves out spaces this device does not mount, and a relay left with none", () => { + const groups = relayGroups( + host( + [ + { + url: HOME, + state: "connecting", + spaces: ["vault", "gone"], + full: ["late"], + }, + { url: OTHER, state: "connected", spaces: ["gone"], full: [] }, + ], + { vault: "connecting", gone: "connected", late: "full" }, + ["vault"], + ), + ); + + expect(groups).toEqual([ + { + name: "Your relay", + state: "connecting", + spaces: [{ id: "vault", status: "connecting" }], + full: [], + }, + ]); + }); +}); + +describe("sharesConnected", () => { + it("is true only for a connected shared folder", () => { + expect(sharesConnected([{ id: "a", status: "connected" }])).toBe(true); + }); + + it.each(["offline", "connecting", "unauthorized"] as const)( + "is false while the only shared folder is %s", + (status) => { + expect( + sharesConnected([ + { id: "vault", status: "connected" }, + { id: "a", status }, + ]), + ).toBe(false); + }, + ); + + it("is false for the vault alone", () => { + expect(sharesConnected([{ id: "vault", status: "connected" }])).toBe(false); + }); +}); diff --git a/packages/plugin/tests/storage/google-drive-adapter.test.ts b/packages/plugin/tests/features/storage/backends/google-drive-adapter.test.ts similarity index 94% rename from packages/plugin/tests/storage/google-drive-adapter.test.ts rename to packages/plugin/tests/features/storage/backends/google-drive-adapter.test.ts index 24f82d67..f50a2df8 100644 --- a/packages/plugin/tests/storage/google-drive-adapter.test.ts +++ b/packages/plugin/tests/features/storage/backends/google-drive-adapter.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { isRefusedCredentials } from "@/storage"; -import { createGoogleDriveAdapter } from "@/storage/adapters/google-drive"; -import { EStorageBackend } from "@/storage/config"; +import { createGoogleDriveAdapter } from "@/features/storage/backends/google-drive"; +import { isRefusedCredentials } from "@/features/storage/backends/http"; +import { EStorageBackend } from "@/features/storage/config"; const requests: { url: string; method?: string }[] = []; let replies: unknown[] = []; @@ -238,6 +238,19 @@ describe("Google Drive bulk write hint", () => { ).toBe(true); }); + it("lists each folder of a mixed batch once", async () => { + const drive = adapter(); + const recipes = keys.map((key) => key.replace("objects/", "recipes/")); + drive.prepareWrites?.([...keys, ...recipes, "chunks/a"]); + replies = [FOLDER, { files: [] }, { files: [] }]; + for (const key of ["objects/1", "recipes/1", "objects/2", "recipes/2"]) { + await drive.put(key, new Uint8Array([1])); + } + + expect(searches()).toHaveLength(3); + expect(creates()).toHaveLength(4); + }); + it("still asks Drive for exists() and putIfAbsent()", async () => { const drive = adapter(); drive.prepareWrites?.(keys); diff --git a/packages/plugin/tests/storage/google-drive-auth.test.ts b/packages/plugin/tests/features/storage/backends/google-drive-auth.test.ts similarity index 97% rename from packages/plugin/tests/storage/google-drive-auth.test.ts rename to packages/plugin/tests/features/storage/backends/google-drive-auth.test.ts index 11e8d069..e206efe7 100644 --- a/packages/plugin/tests/storage/google-drive-auth.test.ts +++ b/packages/plugin/tests/features/storage/backends/google-drive-auth.test.ts @@ -3,7 +3,7 @@ import { defaultGoogleDriveConfig, googleLoginUrl, handleGoogleDriveProtocol, -} from "@/storage/adapters/google-drive-auth"; +} from "@/features/storage/backends/google-drive-auth"; const TOKENS = { access_token: "at", refresh_token: "rt", expires_in: "3600" }; const AUTH = "https://auth.example"; diff --git a/packages/plugin/tests/storage/util.test.ts b/packages/plugin/tests/features/storage/backends/http.test.ts similarity index 97% rename from packages/plugin/tests/storage/util.test.ts rename to packages/plugin/tests/features/storage/backends/http.test.ts index f7b075e5..f5476b93 100644 --- a/packages/plugin/tests/storage/util.test.ts +++ b/packages/plugin/tests/features/storage/backends/http.test.ts @@ -1,16 +1,18 @@ import { afterEach, describe, expect, it, vi } from "vitest"; +import { + StorageHttpError, + StorageTimeoutError, +} from "@/core/shared/transport-errors"; +import { toArrayBuffer } from "@/core/utils/bytes"; import { assertOk, isRetryableError, isRetryableStatus, - StorageHttpError, - StorageTimeoutError, transferBytes, withDeadline, withRetry, withTimeout, -} from "@/storage/adapters/util"; -import { toArrayBuffer } from "@/utils"; +} from "@/features/storage/backends/http"; describe("storage error semantics", () => { it("treats only 'come back later' statuses as retryable", () => { diff --git a/packages/plugin/tests/storage/s3-adapter.test.ts b/packages/plugin/tests/features/storage/backends/s3-adapter.test.ts similarity index 98% rename from packages/plugin/tests/storage/s3-adapter.test.ts rename to packages/plugin/tests/features/storage/backends/s3-adapter.test.ts index 81df040b..87a304d3 100644 --- a/packages/plugin/tests/storage/s3-adapter.test.ts +++ b/packages/plugin/tests/features/storage/backends/s3-adapter.test.ts @@ -1,7 +1,10 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import { isRefusedCredentials } from "@/storage"; -import { createS3Adapter } from "@/storage/adapters/s3"; -import { EStorageBackend, type S3StorageConfig } from "@/storage/config"; +import { isRefusedCredentials } from "@/features/storage/backends/http"; +import { createS3Adapter } from "@/features/storage/backends/s3"; +import { + EStorageBackend, + type S3StorageConfig, +} from "@/features/storage/config"; interface Recorded { url: string; diff --git a/packages/plugin/tests/storage/s3-signer.test.ts b/packages/plugin/tests/features/storage/backends/s3-signer.test.ts similarity index 97% rename from packages/plugin/tests/storage/s3-signer.test.ts rename to packages/plugin/tests/features/storage/backends/s3-signer.test.ts index c8ad3a53..4780ab9e 100644 --- a/packages/plugin/tests/storage/s3-signer.test.ts +++ b/packages/plugin/tests/features/storage/backends/s3-signer.test.ts @@ -1,6 +1,9 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { createS3Signer } from "@/storage/adapters/s3-signer"; -import { EStorageBackend, type S3StorageConfig } from "@/storage/config"; +import { createS3Signer } from "@/features/storage/backends/s3-signer"; +import { + EStorageBackend, + type S3StorageConfig, +} from "@/features/storage/config"; /** The credentials AWS publishes with its SigV4 examples. */ function config(overrides: Partial = {}): S3StorageConfig { diff --git a/packages/plugin/tests/storage/s3-xml.test.ts b/packages/plugin/tests/features/storage/backends/s3-xml.test.ts similarity index 98% rename from packages/plugin/tests/storage/s3-xml.test.ts rename to packages/plugin/tests/features/storage/backends/s3-xml.test.ts index a4697dfd..c24c1871 100644 --- a/packages/plugin/tests/storage/s3-xml.test.ts +++ b/packages/plugin/tests/features/storage/backends/s3-xml.test.ts @@ -1,5 +1,8 @@ import { describe, expect, it } from "vitest"; -import { parseErrorCode, parseListObjects } from "@/storage/adapters/s3-xml"; +import { + parseErrorCode, + parseListObjects, +} from "@/features/storage/backends/s3-xml"; function listing(body: string): string { return ` diff --git a/packages/plugin/tests/storage/webdav-adapter.test.ts b/packages/plugin/tests/features/storage/backends/webdav-adapter.test.ts similarity index 96% rename from packages/plugin/tests/storage/webdav-adapter.test.ts rename to packages/plugin/tests/features/storage/backends/webdav-adapter.test.ts index 8e45a184..3d7fc3e8 100644 --- a/packages/plugin/tests/storage/webdav-adapter.test.ts +++ b/packages/plugin/tests/features/storage/backends/webdav-adapter.test.ts @@ -1,7 +1,7 @@ import { FakeDOMParser } from "@tests/helpers/dom-parser"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { createWebDAVAdapter } from "@/storage/adapters/webdav"; -import { EStorageBackend } from "@/storage/config"; +import { createWebDAVAdapter } from "@/features/storage/backends/webdav"; +import { EStorageBackend } from "@/features/storage/config"; interface Recorded { url: string; diff --git a/packages/plugin/tests/settings/cloudflare-login.test.ts b/packages/plugin/tests/features/storage/cloudflare/cloudflare-login.test.ts similarity index 83% rename from packages/plugin/tests/settings/cloudflare-login.test.ts rename to packages/plugin/tests/features/storage/cloudflare/cloudflare-login.test.ts index 3c28cac1..1e7ba71f 100644 --- a/packages/plugin/tests/settings/cloudflare-login.test.ts +++ b/packages/plugin/tests/features/storage/cloudflare/cloudflare-login.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { cloudflareApi } from "@/cloudflare"; -import { cloudflareErrorMessage } from "@/settings/cloudflare-login"; +import { cloudflareApi } from "@/core/cloudflare/api"; +import { cloudflareErrorMessage } from "@/features/storage/cloudflare/cloudflare-login"; async function failureOf(code: number): Promise { const api = cloudflareApi( diff --git a/packages/plugin/tests/settings/r2.test.ts b/packages/plugin/tests/features/storage/cloudflare/r2-select.test.ts similarity index 95% rename from packages/plugin/tests/settings/r2.test.ts rename to packages/plugin/tests/features/storage/cloudflare/r2-select.test.ts index ada19a50..a10d5305 100644 --- a/packages/plugin/tests/settings/r2.test.ts +++ b/packages/plugin/tests/features/storage/cloudflare/r2-select.test.ts @@ -5,15 +5,20 @@ import { type Reply, } from "@tests/helpers/fake-cloudflare"; import { afterEach, describe, expect, it, vi } from "vitest"; -import * as cloudflareModule from "@/cloudflare"; -import { R2NotEnabledError } from "@/cloudflare"; -import type { PluginHost } from "@/plugin/host"; -import * as cloudflare from "@/settings/cloudflare-login"; -import { mergeSettings } from "@/settings/model"; -import { rekeyR2, useR2, vaultPrefix } from "@/settings/r2"; -import * as storage from "@/storage"; -import { defaultS3Config, EStorageBackend } from "@/storage"; -import { StorageHttpError } from "@/storage/adapters/util"; +import type { PluginHost } from "@/app/host"; +import { mergeSettings } from "@/app/settings"; +import * as cloudflareModule from "@/core/cloudflare"; +import { StorageHttpError } from "@/core/shared/transport-errors"; +import { defaultS3Config } from "@/features/storage/backends/s3"; +import * as cloudflare from "@/features/storage/cloudflare/cloudflare-login"; +import { R2NotEnabledError } from "@/features/storage/cloudflare/r2"; +import { + rekeyR2, + useR2, + vaultPrefix, +} from "@/features/storage/cloudflare/r2-select"; +import { EStorageBackend } from "@/features/storage/config"; +import * as storage from "@/features/storage/registry"; const BUCKETS = "/accounts/acc/r2/buckets"; const VERIFY = "/accounts/acc/tokens/verify"; diff --git a/packages/plugin/tests/cloudflare/r2.test.ts b/packages/plugin/tests/features/storage/cloudflare/r2.test.ts similarity index 52% rename from packages/plugin/tests/cloudflare/r2.test.ts rename to packages/plugin/tests/features/storage/cloudflare/r2.test.ts index 892bc93f..e14e6885 100644 --- a/packages/plugin/tests/cloudflare/r2.test.ts +++ b/packages/plugin/tests/features/storage/cloudflare/r2.test.ts @@ -3,15 +3,11 @@ import { failure, fakeCloudflare } from "@tests/helpers/fake-cloudflare"; import { describe, expect, it } from "vitest"; import { ensureBucket, - isRefusedToken, R2NotEnabledError, r2AccountOf, r2Keys, r2Storage, - tokenTemplateUrl, - verifyToken, -} from "@/cloudflare"; -import { CloudflareError } from "@/cloudflare/api"; +} from "@/features/storage/cloudflare/r2"; const BUCKETS = "/accounts/acc/r2/buckets"; @@ -91,77 +87,3 @@ describe("r2Keys", () => { }); }); }); - -describe("isRefusedToken", () => { - it.each([401, 403])("is true for a Cloudflare %i", (status) => { - expect(isRefusedToken(new CloudflareError(status, [], "no"))).toBe(true); - }); - - it.each([new CloudflareError(409, [], "conflict"), new Error("401")])( - "is false for %s", - (err) => { - expect(isRefusedToken(err)).toBe(false); - }, - ); -}); - -describe("verifyToken", () => { - const ACCOUNT_VERIFY = "/accounts/acc/tokens/verify"; - const USER_VERIFY = "/user/tokens/verify"; - - it("verifies an account token under its account", async () => { - const cf = fakeCloudflare([ - { - method: "GET", - path: ACCOUNT_VERIFY, - reply: () => ({ result: { id: "acct-token", status: "active" } }), - }, - ]); - expect(await verifyToken(cf.api, "acc")).toBe("acct-token"); - }); - - it("falls back to the user endpoint for a user token", async () => { - const cf = fakeCloudflare([ - { method: "GET", path: ACCOUNT_VERIFY, reply: () => failure(1000, 401) }, - { - method: "GET", - path: USER_VERIFY, - reply: () => ({ result: { id: "user-token", status: "active" } }), - }, - ]); - expect(await verifyToken(cf.api, "acc")).toBe("user-token"); - }); - - it("refuses a token that is not active", async () => { - const cf = fakeCloudflare([ - { - method: "GET", - path: ACCOUNT_VERIFY, - reply: () => ({ result: { id: "t", status: "expired" } }), - }, - ]); - const err: unknown = await verifyToken(cf.api, "acc").catch( - (e: unknown) => e, - ); - expect(err).toBeInstanceOf(Error); - expect((err as Error).message).toMatch(/expired/); - expect(isRefusedToken(err)).toBe(true); - }); -}); - -describe("tokenTemplateUrl", () => { - it("pre-fills an account token with the permissions the relay deploy and R2 setup need", () => { - const url = new URL(tokenTemplateUrl()); - expect(url.origin + url.pathname).toBe("https://dash.cloudflare.com/"); - expect(url.searchParams.get("to")).toBe("/:account/api-tokens"); - expect(url.searchParams.get("name")).toBe("MDSync"); - expect( - JSON.parse(url.searchParams.get("permissionGroupKeys") ?? ""), - ).toEqual([ - { key: "workers_scripts", type: "edit" }, - { key: "workers_kv_storage", type: "edit" }, - { key: "workers_r2", type: "edit" }, - { key: "account_settings", type: "read" }, - ]); - }); -}); diff --git a/packages/plugin/tests/storage/records.test.ts b/packages/plugin/tests/features/storage/records.test.ts similarity index 88% rename from packages/plugin/tests/storage/records.test.ts rename to packages/plugin/tests/features/storage/records.test.ts index 72cb043d..147257c5 100644 --- a/packages/plugin/tests/storage/records.test.ts +++ b/packages/plugin/tests/features/storage/records.test.ts @@ -1,9 +1,13 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { beforeAll, describe, expect, it } from "vitest"; -import { DEFAULT_CONCURRENCY } from "@/constants"; -import { deriveKey, type EncryptionKey, encryptJson } from "@/crypto"; -import { type RecordKind, readRecords } from "@/storage/records"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { + deriveKey, + type EncryptionKey, + encryptJson, +} from "@/core/crypto/cipher"; +import { type RecordKind, readRecords } from "@/features/storage/records"; interface Note { id: string; diff --git a/packages/plugin/tests/features/storage/refused-prompt.test.ts b/packages/plugin/tests/features/storage/refused-prompt.test.ts new file mode 100644 index 00000000..33002d30 --- /dev/null +++ b/packages/plugin/tests/features/storage/refused-prompt.test.ts @@ -0,0 +1,70 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { mergeSettings } from "@/app/settings"; +import { defaultGoogleDriveConfig } from "@/features/storage/backends/google-drive-auth"; +import { defaultS3Config } from "@/features/storage/backends/s3"; +import { EStorageBackend } from "@/features/storage/config"; +import type { StorageHost } from "@/features/storage/host"; +import { createStorageRefusedPrompt } from "@/features/storage/refused-prompt"; +import { openStorageRefusedModal } from "@/features/storage/ui/storage-refused-modal"; + +vi.mock("@/features/storage/ui/storage-refused-modal", () => ({ + openStorageRefusedModal: vi.fn(async () => false), +})); + +function host(): StorageHost { + return { + settings: mergeSettings({ + activeStorageKind: EStorageBackend.S3, + storageConfigs: { + [EStorageBackend.S3]: { + ...defaultS3Config(), + bucket: "vault", + accessKeyId: "id", + secretAccessKey: "old", + }, + }, + }), + } as unknown as StorageHost; +} + +describe("createStorageRefusedPrompt", () => { + beforeEach(() => { + vi.mocked(openStorageRefusedModal).mockClear(); + }); + + it("asks once while the keys stay the same", () => { + const plugin = host(); + const ask = createStorageRefusedPrompt(plugin); + ask(); + ask(); + expect(openStorageRefusedModal).toHaveBeenCalledExactlyOnceWith(plugin); + }); + + it("asks again once the keys changed, wherever they were fixed", () => { + const plugin = host(); + const ask = createStorageRefusedPrompt(plugin); + ask(); + Object.assign(plugin.settings.storageConfigs[EStorageBackend.S3] ?? {}, { + secretAccessKey: "new", + }); + ask(); + expect(openStorageRefusedModal).toHaveBeenCalledTimes(2); + }); + + it("does not ask again when Drive only replaced its access token", () => { + const plugin = host(); + plugin.settings.activeStorageKind = EStorageBackend.GoogleDrive; + const drive = { + ...defaultGoogleDriveConfig(), + refreshToken: "r", + accessToken: "a1", + expiresAt: 1, + }; + plugin.settings.storageConfigs[EStorageBackend.GoogleDrive] = drive; + const ask = createStorageRefusedPrompt(plugin); + ask(); + Object.assign(drive, { accessToken: "a2", expiresAt: 2 }); + ask(); + expect(openStorageRefusedModal).toHaveBeenCalledOnce(); + }); +}); diff --git a/packages/plugin/tests/features/storage/ui/storage-fields.test.ts b/packages/plugin/tests/features/storage/ui/storage-fields.test.ts new file mode 100644 index 00000000..d7490d4b --- /dev/null +++ b/packages/plugin/tests/features/storage/ui/storage-fields.test.ts @@ -0,0 +1,222 @@ +// @vitest-environment jsdom +import type { Setting } from "obsidian"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { settleTyping } from "@/core/settings/fields"; +import { notifyError } from "@/core/ui/notices"; +import { EStorageBackend } from "@/features/storage/config"; +import type { StorageHost } from "@/features/storage/host"; +import { storageRows } from "@/features/storage/ui/storage-fields"; + +vi.mock("@/core/ui/notices", () => ({ + notifyError: vi.fn(), + notifyInfo: vi.fn(), +})); + +vi.mock("obsidian", async (importActual) => ({ + ...(await importActual()), + debounce: (fn: (...args: unknown[]) => void, ms: number) => { + let timer: ReturnType | undefined; + let pending: unknown[] | null = null; + const fire = () => { + clearTimeout(timer); + const args = pending; + pending = null; + if (args) fn(...args); + }; + return Object.assign( + (...args: unknown[]) => { + pending = args; + clearTimeout(timer); + timer = setTimeout(fire, ms); + }, + { run: fire }, + ); + }, +})); + +interface S3Settings { + bucket: string; + secretAccessKey: string; + concurrency: number; + forcePathStyle: boolean; +} + +describe("backend fields", () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => { + vi.useRealTimers(); + vi.mocked(notifyError).mockClear(); + }); + + function backend(saveSettings = vi.fn(async () => undefined)) { + const plugin = { + settings: { storageConfigs: {} }, + saveSettings, + scheduleScopeRefresh: vi.fn(), + } as unknown as StorageHost; + const rows = storageRows({ plugin, rerender: vi.fn() }, EStorageBackend.S3); + const config = () => + plugin.settings.storageConfigs[ + EStorageBackend.S3 + ] as unknown as S3Settings; + + function field(name: string) { + const input = document.createElement("input"); + let changed: (value: string) => void = () => undefined; + let toggled: (value: boolean) => void = () => undefined; + const setting = { + settingEl: document.createElement("div"), + addText: (build: (text: unknown) => void) => { + build({ + inputEl: input, + setPlaceholder() {}, + setValue(value: string) { + input.value = value; + return this; + }, + onChange(handler: (value: string) => void) { + changed = handler; + return this; + }, + }); + }, + addToggle: (build: (toggle: unknown) => void) => { + build({ + setValue() { + return this; + }, + onChange(handler: (value: boolean) => void) { + toggled = handler; + return this; + }, + }); + }, + } as unknown as Setting; + rows.find((row) => row.name === name)?.render(setting); + return { + input, + type: (value: string) => changed(value), + toggle: (value: boolean) => toggled(value), + }; + } + + return { plugin, saveSettings, config, field }; + } + + it("keep every keystroke in memory and save the last value once", async () => { + const { saveSettings, config, field } = backend(); + const { type } = field("Bucket"); + + for (const value of ["b", "bu", "buck"]) type(value); + expect(saveSettings).not.toHaveBeenCalled(); + expect(config().bucket).toBe("buck"); + + await vi.advanceTimersByTimeAsync(800); + expect(saveSettings).toHaveBeenCalledTimes(1); + }); + + it("save what is still settling when the settings close", async () => { + const { saveSettings, field } = backend(); + field("Bucket").type("buck"); + + settleTyping(); + expect(saveSettings).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(800); + expect(saveSettings).toHaveBeenCalledTimes(1); + }); + + it("trim a text field but keep the spaces of a password", () => { + const { config, field } = backend(); + + field("Bucket").type(" buck "); + field("Secret access key").type(" se cret "); + + expect(config().bucket).toBe("buck"); + expect(config().secretAccessKey).toBe(" se cret "); + }); + + it("patch the config as it is now, not as it was when the row drew", () => { + const { plugin, config, field } = backend(); + const bucket = field("Bucket"); + const secret = field("Secret access key"); + + bucket.type("buck"); + const replaced = plugin.settings.storageConfigs[EStorageBackend.S3]; + secret.type("secret"); + + expect(config().bucket).toBe("buck"); + expect(config().secretAccessKey).toBe("secret"); + expect(plugin.settings.storageConfigs[EStorageBackend.S3]).not.toBe( + replaced, + ); + }); + + it("save a toggle at once", async () => { + const { saveSettings, config, field } = backend(); + + field("Force path-style URLs").toggle(false); + + expect(config().forcePathStyle).toBe(false); + expect(saveSettings).toHaveBeenCalledTimes(1); + }); + + it("draw concurrency as a native number input with its bounds", () => { + const { field } = backend(); + const { input } = field("Concurrency"); + + expect(input.type).toBe("number"); + expect(input.min).toBe("1"); + expect(input.max).toBe("32"); + expect(input.value).toBe("4"); + }); + + it("clamp a typed number into its bounds", () => { + const { config, field } = backend(); + const { type } = field("Concurrency"); + + type("100"); + expect(config().concurrency).toBe(32); + type("0"); + expect(config().concurrency).toBe(1); + type("8"); + expect(config().concurrency).toBe(8); + }); + + it("accept only whole numbers", () => { + const { plugin, field } = backend(); + const { type } = field("Concurrency"); + + for (const raw of ["", "abc", "-3", "1.5", "1e1"]) type(raw); + + expect(plugin.settings.storageConfigs).toEqual({}); + }); + + it("tell the user when the settings cannot be saved", async () => { + const failure = new Error("disk full"); + const { field } = backend(vi.fn(() => Promise.reject(failure))); + + field("Force path-style URLs").toggle(true); + await vi.advanceTimersByTimeAsync(0); + + expect(notifyError).toHaveBeenCalledWith( + "Could not save settings", + failure, + ); + }); +}); + +describe("the Google Drive rows", () => { + it("add the account row after the fields", () => { + const plugin = { + settings: { storageConfigs: {} }, + } as unknown as StorageHost; + const names = storageRows( + { plugin, rerender: vi.fn() }, + EStorageBackend.GoogleDrive, + ).map((row) => row.name); + + expect(names.at(-1)).toBe("Google account"); + expect(names).toContain("Folder Name"); + }); +}); diff --git a/packages/plugin/tests/sync/auto-merge.test.ts b/packages/plugin/tests/features/sync/apply/auto-merge.test.ts similarity index 66% rename from packages/plugin/tests/sync/auto-merge.test.ts rename to packages/plugin/tests/features/sync/apply/auto-merge.test.ts index 2dfa62ff..c3172657 100644 --- a/packages/plugin/tests/sync/auto-merge.test.ts +++ b/packages/plugin/tests/features/sync/apply/auto-merge.test.ts @@ -1,11 +1,16 @@ +import { Device, disabled } from "@tests/helpers/config-device"; +import { RevalidatingStorage } from "@tests/helpers/revalidating-storage"; import type { TestSession } from "@tests/helpers/session"; import { pairedSessions, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it, vi } from "vitest"; -import { autoMergeOp, isTextMergeCandidate } from "@/sync/auto-merge"; -import type { LiveNotes } from "@/sync/live-notes"; -import { pushPathsOp } from "@/sync/operations/push"; -import { recomputeAfterWrite } from "@/sync/session-state"; -import { VAULT_SPACE } from "@/sync/space"; +import { + autoMergeOp, + isTextMergeCandidate, +} from "@/features/sync/apply/auto-merge"; +import type { LiveNotes } from "@/features/sync/live-notes"; +import { pushPathsOp } from "@/features/sync/operations/push"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; +import { recomputeAfterWrite } from "@/features/sync/session-state"; useEncryptionKey(); @@ -16,20 +21,21 @@ async function diverged( localText: string, remoteText: string, base = BASE, + path = "note.md", ): Promise<[TestSession, TestSession]> { const [a, b] = pairedSessions(); - a.adapter.putText("note.md", base); + a.adapter.putText(path, base); const first = await a.compare(); - await pushPathsOp(a.deps(), first, ["note.md"], a.context()); + await pushPathsOp(a.deps(), first, [path], a.context()); - b.adapter.putText("note.md", base); + b.adapter.putText(path, base); await b.adoptRemote(); - b.adapter.putText("note.md", remoteText); + b.adapter.putText(path, remoteText); const bResult = await b.compare(); - await pushPathsOp(b.deps(), bResult, ["note.md"], b.context()); + await pushPathsOp(b.deps(), bResult, [path], b.context()); - a.adapter.putText("note.md", localText); + a.adapter.putText(path, localText); return [a, b]; } @@ -84,6 +90,40 @@ describe("autoMergeOp", () => { expect(a.text("note.md")).toBe(merged); }); + it.each(["data.json", "board.canvas", "script.js"])( + "leaves a %s conflict for the merge screen even when lines do not overlap", + async (path) => { + const localText = BASE.replace("one", "ONE"); + const [a] = await diverged( + localText, + BASE.replace("six", "SIX"), + BASE, + path, + ); + const result = await a.compare(); + expect(result.diff.conflicts.map((c) => c.path)).toEqual([path]); + + const outcome = await autoMergeOp(a.deps(), result, a.context()); + + expect(outcome.touchedPaths.size).toBe(0); + expect(a.text(path)).toBe(localText); + }, + ); + + it("merges a note whatever the case of its extension", async () => { + const [a] = await diverged( + BASE.replace("one", "ONE"), + BASE.replace("six", "SIX"), + BASE, + "NOTE.MD", + ); + const result = await a.compare(); + + const outcome = await autoMergeOp(a.deps(), result, a.context()); + + expect(outcome.touchedPaths).toEqual(new Set(["NOTE.MD"])); + }); + it("records the mtime it wrote so the next scan does not re-hash", async () => { const [a] = await diverged( BASE.replace("one", "ONE"), @@ -218,6 +258,68 @@ describe("autoMergeOp", () => { }); }); +describe("autoMergeOp on settings JSON", () => { + const plugin = ".obsidian/plugins/sample"; + const json = (value: unknown) => JSON.stringify(value, null, 2); + + /** Both devices hold `base` at `path`, then b pushes `remote` and a writes `local` unpushed. */ + async function diverged( + path: string, + base: string, + local: string, + remote: string, + ) { + const storage = new RevalidatingStorage(); + const [a, b] = [new Device("a", storage), new Device("b", storage)]; + for (const device of [a, b]) { + device.settingsSync = { ...disabled, pluginConfigs: true }; + } + a.adapter.putText(path, base); + await a.push(); + await b.pull(); + b.adapter.putText(path, remote); + await b.push(); + a.adapter.putText(path, local); + return { a, b }; + } + + it("merges a plugin's settings by key, and both devices converge", async () => { + const path = `${plugin}/data.json`; + const { a, b } = await diverged( + path, + json({ theme: "light", size: 12 }), + json({ theme: "dark", size: 12 }), + json({ theme: "light", size: 14 }), + ); + const result = await a.compare(); + expect(result.diff.conflicts.map((c) => c.path)).toEqual([path]); + + const outcome = await autoMergeOp(a.deps(), result, a.context()); + + expect(outcome.touchedPaths).toEqual(new Set([path])); + expect(a.text(path)).toBe(json({ theme: "dark", size: 14 })); + await a.push(); + await b.pull(); + expect(b.text(path)).toBe(a.text(path)); + const after = await a.compare(); + expect(after.diff.localChanges).toHaveLength(0); + expect(after.diff.conflicts).toHaveLength(0); + }); + + it("leaves plugin code for the merge screen even when lines do not overlap", async () => { + const path = `${plugin}/main.js`; + const local = BASE.replace("one", "ONE"); + const { a } = await diverged(path, BASE, local, BASE.replace("six", "SIX")); + const result = await a.compare(); + expect(result.diff.conflicts.map((c) => c.path)).toEqual([path]); + + const outcome = await autoMergeOp(a.deps(), result, a.context()); + + expect(outcome.touchedPaths.size).toBe(0); + expect(a.text(path)).toBe(local); + }); +}); + describe("isTextMergeCandidate", () => { const [a] = pairedSessions(); const deps = { adapter: a.adapter.asDataAdapter() }; diff --git a/packages/plugin/tests/sync/pull-hint.test.ts b/packages/plugin/tests/features/sync/apply/pull-hint.test.ts similarity index 94% rename from packages/plugin/tests/sync/pull-hint.test.ts rename to packages/plugin/tests/features/sync/apply/pull-hint.test.ts index 4a20532e..e429af2f 100644 --- a/packages/plugin/tests/sync/pull-hint.test.ts +++ b/packages/plugin/tests/features/sync/apply/pull-hint.test.ts @@ -1,9 +1,9 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { TestSession, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; -import { compare, pushPaths } from "@/sync/engine"; -import { objectKey } from "@/sync/manifest"; -import { pullPaths } from "@/sync/pull"; +import { pullPaths } from "@/features/sync/apply/pull"; +import { objectKey } from "@/features/sync/content/keys"; +import { compare, pushPaths } from "@/features/sync/engine"; class HintedStorage extends FakeStorage { readonly hints: string[][] = []; diff --git a/packages/plugin/tests/sync/auto-cycle.test.ts b/packages/plugin/tests/features/sync/auto-cycle.test.ts similarity index 73% rename from packages/plugin/tests/sync/auto-cycle.test.ts rename to packages/plugin/tests/features/sync/auto-cycle.test.ts index 6d17ccea..4ad16292 100644 --- a/packages/plugin/tests/sync/auto-cycle.test.ts +++ b/packages/plugin/tests/features/sync/auto-cycle.test.ts @@ -1,18 +1,26 @@ import { createTestControllerHost } from "@tests/helpers/controller"; import { pairedSessions, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it, vi } from "vitest"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; -import { decryptJson, sha256Hex } from "@/crypto"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; -import { OFFLINE_MESSAGE } from "@/shared"; -import { REMOTE_MANIFEST_KEY } from "@/sync/constants"; -import { SyncController } from "@/sync/controller"; -import { pushPaths } from "@/sync/engine"; -import type { Manifest } from "@/sync/types"; -import { createScopePolicy } from "@/vault/scope"; +import { decryptJson, sha256Hex } from "@/core/crypto/cipher"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import { OFFLINE_MESSAGE } from "@/core/shared/offline"; +import { SyncController } from "@/features/sync/controller"; +import { pushPaths } from "@/features/sync/engine"; +import { createScopePolicy } from "@/features/sync/scope/scope"; +import type { Manifest } from "@/features/sync/types"; useEncryptionKey(); +const hashOf = (text: string) => sha256Hex(new TextEncoder().encode(text)); + +async function headFiles(session: ReturnType[0]) { + const bytes = session.storage.map.get(REMOTE_MANIFEST_KEY); + if (!bytes) throw new Error("Missing head"); + return (await decryptJson(session.deps().key, bytes)).files; +} + function headReads(get: { mock: { calls: [string][] } }): number { return get.mock.calls.filter(([key]) => key === REMOTE_MANIFEST_KEY).length; } @@ -198,4 +206,44 @@ describe("serialized automatic refresh cycle", () => { expect(controller.getSnapshot().pendingLocal).toBe(2); controller.dispose(); }); + + it("keeps a restored file out of automatic pushes until it is edited", async () => { + const [a] = pairedSessions(); + a.adapter.putText("a.md", "one"); + const controller = new SyncController(createTestControllerHost(a)); + await controller.refreshAndAutoSync(); + a.adapter.putText("a.md", "two"); + await controller.refreshAndAutoSync(); + + await controller.history.restoreFileVersion("a.md", await hashOf("one")); + a.adapter.putText("b.md", "new"); + await controller.refreshAndAutoSync(); + expect((await headFiles(a))["a.md"]?.hash).toBe(await hashOf("two")); + expect((await headFiles(a))["b.md"]?.hash).toBe(await hashOf("new")); + expect(controller.getSnapshot().pendingLocal).toBe(1); + + a.adapter.putText("a.md", "three"); + await controller.refreshAndAutoSync(); + expect((await headFiles(a))["a.md"]?.hash).toBe(await hashOf("three")); + controller.dispose(); + }); + + it("ends a restore's hold at a push by hand, with automatic pushes off meanwhile", async () => { + const [a] = pairedSessions(); + a.adapter.putText("a.md", "one"); + const controller = new SyncController(createTestControllerHost(a)); + await controller.refreshAndAutoSync(); + a.adapter.putText("a.md", "two"); + await controller.pushPaths(["a.md"]); + await controller.history.restoreFileVersion("a.md", await hashOf("one")); + await controller.pushPaths(["a.md"]); + a.adapter.putText("a.md", "two"); + await controller.pushPaths(["a.md"]); + + a.adapter.putText("a.md", "one"); + await controller.refreshAndAutoSync(); + + expect((await headFiles(a))["a.md"]?.hash).toBe(await hashOf("one")); + controller.dispose(); + }); }); diff --git a/packages/plugin/tests/sync/auto-push.test.ts b/packages/plugin/tests/features/sync/automation/auto-push.test.ts similarity index 77% rename from packages/plugin/tests/sync/auto-push.test.ts rename to packages/plugin/tests/features/sync/automation/auto-push.test.ts index ee3664a4..41f47b32 100644 --- a/packages/plugin/tests/sync/auto-push.test.ts +++ b/packages/plugin/tests/features/sync/automation/auto-push.test.ts @@ -1,8 +1,11 @@ import { describe, expect, it, vi } from "vitest"; -import { createAutoPushSelector, selectAutoPushPaths } from "@/sync/auto-push"; -import { VAULT_SPACE } from "@/sync/space"; -import type { Conflict, DiffResult, FileChange } from "@/sync/types"; +import { + createAutoPushSelector, + selectAutoPushPaths, +} from "@/features/sync/automation/auto-push"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; +import type { Conflict, DiffResult, FileChange } from "@/features/sync/types"; function change(path: string): FileChange { return { path, type: "local-modify", localHash: "a", remoteHash: "b" }; @@ -104,7 +107,11 @@ describe("createAutoPushSelector", () => { it("reports a held set once, however many cycles hold it", () => { const report = vi.fn(); - const select = createAutoPushSelector(() => 1, report); + const select = createAutoPushSelector( + () => 1, + report, + () => () => false, + ); expect(select(VAULT_SPACE, two)).toEqual([]); select(VAULT_SPACE, two); expect(report).toHaveBeenCalledOnce(); @@ -114,7 +121,11 @@ describe("createAutoPushSelector", () => { it("reports the set again once a full selection held nothing", () => { const report = vi.fn(); let limit: number | null = 1; - const select = createAutoPushSelector(() => limit, report); + const select = createAutoPushSelector( + () => limit, + report, + () => () => false, + ); select(VAULT_SPACE, two); select(VAULT_SPACE, two, new Set(["c.md"])); select(VAULT_SPACE, two); @@ -125,4 +136,26 @@ describe("createAutoPushSelector", () => { select(VAULT_SPACE, two); expect(report).toHaveBeenCalledTimes(2); }); + + it("leaves out a slow file still being edited", () => { + const select = createAutoPushSelector( + () => null, + vi.fn(), + () => (path) => path === "a.md", + ); + expect(select(VAULT_SPACE, two)).toEqual(["b.md"]); + }); + + it("leaves out both ends of a move one held end belongs to", () => { + const select = createAutoPushSelector( + () => null, + vi.fn(), + () => (path) => path === "b.canvas", + ); + const moved = diff({ + localChanges: [deleted("a.canvas"), added("b.canvas"), change("c.md")], + moves: [{ from: "a.canvas", to: "b.canvas", side: "local" }], + }); + expect(select(VAULT_SPACE, moved)).toEqual(["c.md"]); + }); }); diff --git a/packages/plugin/tests/features/sync/automation/restored-files.test.ts b/packages/plugin/tests/features/sync/automation/restored-files.test.ts new file mode 100644 index 00000000..4cfb8c43 --- /dev/null +++ b/packages/plugin/tests/features/sync/automation/restored-files.test.ts @@ -0,0 +1,199 @@ +import { describe, expect, it } from "vitest"; +import { RestoredFiles } from "@/features/sync/automation/restored-files"; +import type { CompareResult } from "@/features/sync/engine"; +import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; +import type { DiffResult, FileChange, LocalStore } from "@/features/sync/types"; + +function changes(...localChanges: FileChange[]): DiffResult { + return { + localChanges, + remoteChanges: [], + conflicts: [], + moves: [], + converged: [], + remoteMoved: false, + }; +} + +const modified = (path: string, localHash: string): FileChange => ({ + path, + type: "local-modify", + localHash, + remoteHash: "r", +}); + +const deleted = (path: string): FileChange => ({ + path, + type: "local-delete", + localHash: null, + remoteHash: "r", +}); + +/** A compare that read `files` (path to hash), found `changed` and could not read `skipped`. */ +function compared( + files: Record, + changed: FileChange[], + skipped: string[] = [], +): CompareResult { + return { + snapshot: { + files: Object.fromEntries( + Object.entries(files).map(([path, hash]) => [ + path, + { hash, size: 1, mtime: 1, kind: "vault" }, + ]), + ), + skipped: skipped.map((path) => ({ path, reason: "unreadable" })), + emptyFolders: [], + ignoredPaths: [], + unreadableDirs: [], + }, + remote: null, + diff: changes(...changed), + updatedCache: {}, + }; +} + +function memory(): LocalStore & { value: unknown } { + const store = { + value: null as unknown, + load: () => store.value, + save: (value: unknown) => { + store.value = value; + }, + }; + return store; +} + +const SHARE: Space = { id: "s", root: "Shared" }; + +describe("RestoredFiles", () => { + it("holds what a restore wrote or removed while the diff still shows it", () => { + const restored = new RestoredFiles(memory()); + restored.hold( + VAULT_SPACE, + new Map([ + ["a.md", "h1"], + ["b.md", null], + ]), + ); + const diff = changes(modified("a.md", "h1"), deleted("b.md")); + + expect(restored.waiting(VAULT_SPACE, diff)).toEqual( + new Set(["a.md", "b.md"]), + ); + expect(restored.waiting(SHARE, diff)).toEqual(new Set()); + }); + + it("lets go once the file is edited, or published or pulled by any operation", () => { + const restored = new RestoredFiles(memory()); + restored.hold( + VAULT_SPACE, + new Map([ + ["a.md", "h1"], + ["b.md", "h2"], + ]), + ); + + restored.settle( + VAULT_SPACE, + compared({ "a.md": "edited", "b.md": "h2" }, [ + modified("a.md", "edited"), + ]), + ); + + expect( + restored.waiting( + VAULT_SPACE, + changes(modified("a.md", "h1"), modified("b.md", "h2")), + ), + ).toEqual(new Set()); + }); + + it("lets go of a file scanned with no change: pushed by hand or pulled", () => { + const restored = new RestoredFiles(memory()); + restored.hold(VAULT_SPACE, new Map([["a.md", "h1"]])); + + restored.settle(VAULT_SPACE, compared({ "a.md": "h1" }, [])); + + expect( + restored.waiting(VAULT_SPACE, changes(modified("a.md", "h1"))), + ).toEqual(new Set()); + }); + + it.each([ + ["could not read", compared({}, [], ["a.md"])], + ["left out, ignored or under another spelling", compared({}, [])], + [ + "found in conflict", + { + ...compared({ "a.md": "h1" }, []), + diff: { + ...changes(), + conflicts: [ + { + path: "a.md", + localHash: "h1", + remoteHash: "r", + baselineHash: "b", + }, + ], + }, + }, + ], + ])("keeps the hold of a file the compare %s", (_, result) => { + const restored = new RestoredFiles(memory()); + restored.hold(VAULT_SPACE, new Map([["a.md", "h1"]])); + + restored.settle(VAULT_SPACE, result); + + expect( + restored.waiting(VAULT_SPACE, changes(modified("a.md", "h1"))), + ).toEqual(new Set(["a.md"])); + }); + + it("follows a shared folder whose root moved", () => { + const restored = new RestoredFiles(memory()); + restored.hold(SHARE, new Map([["Shared/a.md", "h1"]])); + const moved = { ...SHARE, root: "Renamed" }; + + restored.settle( + moved, + compared({ "Renamed/a.md": "h1" }, [modified("Renamed/a.md", "h1")]), + ); + + expect( + restored.waiting(moved, changes(modified("Renamed/a.md", "h1"))), + ).toEqual(new Set(["Renamed/a.md"])); + }); + + it("keeps an earlier restore held when a later one never wrote", () => { + const restored = new RestoredFiles(memory()); + restored.hold(VAULT_SPACE, new Map([["a.md", "h1"]])); + restored.hold(VAULT_SPACE, new Map([["a.md", "h2"]])); + + restored.settle( + VAULT_SPACE, + compared({ "a.md": "h1" }, [modified("a.md", "h1")]), + ); + + expect( + restored.waiting(VAULT_SPACE, changes(modified("a.md", "h1"))), + ).toEqual(new Set(["a.md"])); + expect( + restored.waiting(VAULT_SPACE, changes(modified("a.md", "h2"))), + ).toEqual(new Set()); + }); + + it("keeps its holds across a restart", () => { + const store = memory(); + new RestoredFiles(store).hold(VAULT_SPACE, new Map([["a.md", "h1"]])); + + expect( + new RestoredFiles(store).waiting( + VAULT_SPACE, + changes(modified("a.md", "h1")), + ), + ).toEqual(new Set(["a.md"])); + }); +}); diff --git a/packages/plugin/tests/sync/scheduler-interval.test.ts b/packages/plugin/tests/features/sync/automation/scheduler-interval.test.ts similarity index 65% rename from packages/plugin/tests/sync/scheduler-interval.test.ts rename to packages/plugin/tests/features/sync/automation/scheduler-interval.test.ts index 28de974c..720b2528 100644 --- a/packages/plugin/tests/sync/scheduler-interval.test.ts +++ b/packages/plugin/tests/features/sync/automation/scheduler-interval.test.ts @@ -1,170 +1,20 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -import { DEFAULT_SETTINGS } from "@/settings/model"; -import type { SyncController } from "@/sync/controller"; import { - registerScheduler, - SCHEDULER_HEARTBEAT_MS, - type SchedulerHost, -} from "@/sync/scheduler"; -import { VAULT_SPACE } from "@/sync/space"; + type SchedulerHarness, + schedulerHarness, +} from "@tests/helpers/scheduler"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { MdsyncSettings } from "@/core/settings"; +import { SCHEDULER_HEARTBEAT_MS } from "@/features/sync/automation/scheduler"; const MINUTE_MS = 60_000; -interface Harness { - host: SchedulerHost; - syncs: () => number; - pushFlags: () => ReadonlyArray; - manualSync: () => void; - setSyncError: (error: string | null) => void; - /** The storage is unreachable while the browser still reports a connection. */ - setUnreachable: (unreachable: boolean) => void; - /** Only a shared folder's storage is unreachable; the vault's is fine. */ - setShareUnreachable: (unreachable: boolean) => void; - /** Whether a comparison has landed yet. */ - setCompared: (compared: boolean) => void; - /** Syncs stay in flight until the returned release runs. */ - holdSyncs: () => () => void; - fire: (event: "online" | "offline") => void; - refreshes: () => number; - connectivityChanges: () => number; - edit: (path: string) => void; - pushes: () => number; -} - -function harness(settings: { - autoSyncIntervalMinutes: number; - autoSyncEnabled?: boolean; - autoPushAfterSync?: boolean; -}): Harness { - let syncs = 0; - let pushes = 0; - let refreshes = 0; - let connectivityChanges = 0; - const vaultListeners = new Map void>(); - const domListeners = new Map void>(); - const pushFlags: Array = []; - let snapshotError: string | null = null; - let snapshotOffline = false; - let shareUnreachable = false; - let compared = true; - let gate: Promise | null = null; - const current = () => ({ - error: snapshotError, - offline: snapshotOffline, - spaceErrors: shareUnreachable - ? [{ root: "Team", message: "No connection", offline: true }] - : [], - result: compared ? {} : null, +function harness( + settings: Pick & + Partial, +) { + return schedulerHarness({ + settings: { autoSyncEnabled: true, autoPushAfterChange: true, ...settings }, }); - const statusListeners: Array< - (snapshot: ReturnType & { busy: boolean }) => void - > = []; - const host = { - settings: { - ...DEFAULT_SETTINGS, - autoSyncEnabled: settings.autoSyncEnabled ?? true, - autoSyncIntervalMinutes: settings.autoSyncIntervalMinutes, - autoPushAfterSync: settings.autoPushAfterSync ?? true, - autoPushAfterChange: true, - storageConfigs: { - [DEFAULT_SETTINGS.activeStorageKind]: { - ...DEFAULT_SETTINGS.storageConfigs[ - DEFAULT_SETTINGS.activeStorageKind - ], - bucket: "b", - accessKeyId: "k", - secretAccessKey: "s", - }, - }, - }, - app: { - workspace: { layoutReady: true }, - metadataCache: { - initialized: true, - on: () => ({}), - }, - vault: { - on: (event: string, listener: (file: { path: string }) => void) => { - vaultListeners.set(event, listener); - return {}; - }, - }, - }, - spaces: { partition: () => [VAULT_SPACE] }, - register: () => undefined, - registerInterval: () => undefined, - registerDomEvent: (_target: unknown, event: string, fn: () => void) => { - domListeners.set(event, fn); - }, - registerEvent: () => undefined, - } as unknown as SchedulerHost; - const controller = { - refreshAndAutoSync: async (push: boolean) => { - syncs++; - pushFlags.push(push); - await gate; - }, - refresh: async () => { - refreshes++; - }, - connectivityChanged: () => { - connectivityChanges++; - }, - refreshAndAutoPush: async () => { - pushes++; - }, - noteLocalChange: () => undefined, - refreshSaved: () => undefined, - getSnapshot: current, - subscribe: ( - listener: ( - snapshot: ReturnType & { busy: boolean }, - ) => void, - ) => { - statusListeners.push(listener); - return () => undefined; - }, - } as unknown as SyncController; - registerScheduler(host, controller); - return { - host, - syncs: () => syncs, - pushFlags: () => pushFlags, - manualSync: () => { - for (const listener of statusListeners) - listener({ ...current(), busy: true }); - for (const listener of statusListeners) - listener({ ...current(), busy: false }); - }, - setSyncError: (error: string | null) => { - snapshotError = error; - }, - setUnreachable: (unreachable) => { - snapshotOffline = unreachable; - }, - setShareUnreachable: (unreachable) => { - shareUnreachable = unreachable; - }, - setCompared: (value) => { - compared = value; - }, - holdSyncs: () => { - let release = () => {}; - gate = new Promise((resolve) => { - release = resolve; - }); - return () => { - gate = null; - release(); - }; - }, - fire: (event) => domListeners.get(event)?.(), - refreshes: () => refreshes, - connectivityChanges: () => connectivityChanges, - edit: (path) => vaultListeners.get("modify")?.({ path }), - pushes: () => pushes, - }; } describe("auto-sync intervals", () => { @@ -275,18 +125,18 @@ describe("auto-sync intervals", () => { h.setSyncError("backend down"); // Failures at 3s, 60s and 120s arm the backoff until 240s. await vi.advanceTimersByTimeAsync(120_000); - h.edit("a.md"); + h.emit("modify", "a.md"); await vi.advanceTimersByTimeAsync(settle); - expect(h.pushes()).toBe(0); + expect(h.pushes()).toHaveLength(0); h.setSyncError(null); h.manualSync(); await vi.advanceTimersByTimeAsync(settle); - expect(h.pushes()).toBe(1); + expect(h.pushes()).toHaveLength(1); }); describe("when the connection returns", () => { - const dropAndRestore = async (h: Harness): Promise => { + const dropAndRestore = async (h: SchedulerHarness): Promise => { vi.stubGlobal("navigator", { onLine: false }); h.fire("offline"); await vi.advanceTimersByTimeAsync(5_000); @@ -314,7 +164,7 @@ describe("auto-sync intervals", () => { await dropAndRestore(h); - expect(h.refreshes()).toBe(1); + expect(h.compares()).toBe(1); expect(h.syncs()).toBe(0); }); @@ -325,7 +175,7 @@ describe("auto-sync intervals", () => { }); h.fire("online"); await vi.advanceTimersByTimeAsync(0); - expect(h.refreshes()).toBe(0); + expect(h.compares()).toBe(0); }); it("compares after a failure the browser never announced", async () => { @@ -336,7 +186,7 @@ describe("auto-sync intervals", () => { h.setUnreachable(true); h.fire("online"); await vi.advanceTimersByTimeAsync(0); - expect(h.refreshes()).toBe(1); + expect(h.compares()).toBe(1); }); it("keeps a startup-only schedule to its one sync", async () => { @@ -347,7 +197,7 @@ describe("auto-sync intervals", () => { await dropAndRestore(h); expect(h.syncs()).toBe(1); - expect(h.refreshes()).toBe(1); + expect(h.compares()).toBe(1); }); it("still owes a startup-only schedule the sync it missed offline", async () => { @@ -421,7 +271,7 @@ describe("auto-sync intervals", () => { h.setShareUnreachable(true); h.fire("online"); await vi.advanceTimersByTimeAsync(0); - expect(h.refreshes()).toBe(1); + expect(h.compares()).toBe(1); }); it("does not queue a second cycle behind a retry that is still running", async () => { diff --git a/packages/plugin/tests/sync/scheduler-queued-push.test.ts b/packages/plugin/tests/features/sync/automation/scheduler-queued-push.test.ts similarity index 54% rename from packages/plugin/tests/sync/scheduler-queued-push.test.ts rename to packages/plugin/tests/features/sync/automation/scheduler-queued-push.test.ts index e1ed066d..6049be86 100644 --- a/packages/plugin/tests/sync/scheduler-queued-push.test.ts +++ b/packages/plugin/tests/features/sync/automation/scheduler-queued-push.test.ts @@ -1,21 +1,15 @@ +import { + type SchedulerHarness, + schedulerHarness, +} from "@tests/helpers/scheduler"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -import { DEFAULT_SETTINGS } from "@/settings/model"; -import type { SyncController } from "@/sync/controller"; -import { registerScheduler, type SchedulerHost } from "@/sync/scheduler"; -import { type Space, VAULT_SPACE } from "@/sync/space"; +import { DEFAULT_SETTINGS } from "@/app/settings"; +import { SLOW_FILE_CAP_MS } from "@/features/sync/automation/slow-files"; +import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; const SETTLE_MS = DEFAULT_SETTINGS.autoPushSettleSeconds * 1000; - -interface Harness { - host: SchedulerHost; - emit: (event: string, path: string, oldPath?: string) => void; - refreshes: () => number; - pushes: () => ReadonlyArray | undefined>; - sharePushes: () => ReadonlyArray>; - goOnline: () => void; - saved: () => readonly string[]; -} +const SLOW_MS = DEFAULT_SETTINGS.slowFileSettleSeconds * 1000; +const DRAWING = "d.excalidraw.md"; const SHARES: Record = { Team: { id: "team", root: "Team" }, @@ -28,95 +22,18 @@ function harness(options: { enabled: boolean; queuedOnly: boolean; settleSeconds?: number; -}): Harness { - let refreshes = 0; - const pushes: Array | undefined> = []; - const onlineListeners: Array<() => void> = []; - const listeners = new Map< - string, - (file: { path: string }, oldPath?: string) => void - >(); - const host = { +}) { + return schedulerHarness({ + spaces: [VAULT_SPACE, ...Object.values(SHARES)], settings: { - ...DEFAULT_SETTINGS, autoSyncIntervalMinutes: 0, autoPushAfterChange: options.enabled, - autoPushSettleSeconds: - options.settleSeconds ?? DEFAULT_SETTINGS.autoPushSettleSeconds, autoPushChangedFilesOnly: options.queuedOnly, - storageConfigs: { - [DEFAULT_SETTINGS.activeStorageKind]: { - ...DEFAULT_SETTINGS.storageConfigs[ - DEFAULT_SETTINGS.activeStorageKind - ], - bucket: "b", - accessKeyId: "k", - secretAccessKey: "s", - }, - }, - }, - app: { - workspace: { layoutReady: true }, - metadataCache: { - initialized: true, - on: () => ({}), - }, - vault: { - on: ( - event: string, - listener: (file: { path: string }, oldPath?: string) => void, - ) => { - listeners.set(event, listener); - return {}; - }, - }, - }, - spaces: { partition: () => [VAULT_SPACE, ...Object.values(SHARES)] }, - register: () => undefined, - registerInterval: () => undefined, - registerDomEvent: (_target: unknown, event: string, fn: () => void) => { - if (event === "online") onlineListeners.push(fn); - }, - registerEvent: () => undefined, - } as unknown as SchedulerHost; - const sharePushes: ReadonlySet[] = []; - const saved: string[] = []; - const controller = { - noteLocalChange: vi.fn(), - refreshSaved: (path: string) => saved.push(path), - refreshAndAutoPush: async (paths?: ReadonlySet) => { - refreshes++; - pushes.push(paths); - }, - autoPushShares: async (paths: ReadonlySet) => { - sharePushes.push(paths); - }, - subscribe: () => () => undefined, - connectivityChanged: () => undefined, - getSnapshot: () => ({ - offline: false, - error: null, - spaceErrors: [], - result: {}, - }), - } as unknown as SyncController; - registerScheduler(host, controller); - return { - host, - sharePushes: () => sharePushes, - emit: (event, path, oldPath) => { - const listener = listeners.get(event); - if (!listener) throw new Error(`Missing ${event} listener`); - listener({ path }, oldPath); - }, - refreshes: () => refreshes, - pushes: () => pushes, - saved: () => saved, - goOnline: () => { - vi.stubGlobal("navigator", { onLine: true }); - for (const fn of onlineListeners) fn(); + ...(options.settleSeconds !== undefined && { + autoPushSettleSeconds: options.settleSeconds, + }), }, - }; + }); } describe("queued push after changes settle", () => { @@ -145,7 +62,7 @@ describe("queued push after changes settle", () => { vi.stubGlobal("navigator", { onLine: false }); h.emit("modify", "a.md"); await vi.advanceTimersByTimeAsync(SETTLE_MS * 3); - expect(h.refreshes()).toBe(0); + expect(h.pushes()).toHaveLength(0); // Only the heartbeat interval is left: no quiet timer polls while offline. expect(vi.getTimerCount()).toBe(1); @@ -159,7 +76,6 @@ describe("queued push after changes settle", () => { const h = harness({ enabled: false, queuedOnly: true }); h.emit("modify", "a.md"); await vi.advanceTimersByTimeAsync(SETTLE_MS * 2); - expect(h.refreshes()).toBe(0); expect(h.pushes()).toHaveLength(0); }); @@ -169,10 +85,9 @@ describe("queued push after changes settle", () => { await vi.advanceTimersByTimeAsync(SETTLE_MS / 2); h.emit("create", "b.md"); await vi.advanceTimersByTimeAsync(SETTLE_MS - 1); - expect(h.refreshes()).toBe(0); + expect(h.pushes()).toHaveLength(0); await vi.advanceTimersByTimeAsync(1); - expect(h.refreshes()).toBe(1); expect(h.pushes()).toHaveLength(1); expect([...(h.pushes()[0] ?? [])]).toEqual(["a.md", "b.md"]); }); @@ -195,9 +110,9 @@ describe("queued push after changes settle", () => { const h = harness({ enabled: true, queuedOnly: true, settleSeconds: 5 }); h.emit("modify", "a.md"); await vi.advanceTimersByTimeAsync(4_999); - expect(h.refreshes()).toBe(0); + expect(h.pushes()).toHaveLength(0); await vi.advanceTimersByTimeAsync(1); - expect(h.refreshes()).toBe(1); + expect(h.pushes()).toHaveLength(1); }); it("pushes a shared folder's changes on their own, two quiet seconds later", async () => { @@ -266,7 +181,131 @@ describe("queued push after changes settle", () => { h.emit("modify", "a.md"); h.host.settings.autoPushAfterChange = false; await vi.advanceTimersByTimeAsync(SETTLE_MS); - expect(h.refreshes()).toBe(0); expect(h.pushes()).toHaveLength(0); }); }); + +describe("slow files", () => { + beforeEach(() => { + vi.useFakeTimers(); + vi.stubGlobal("navigator", { onLine: true }); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + + const pushed = (h: SchedulerHarness): string[][] => + h.pushes().map((paths) => [...(paths ?? [])]); + + /** Saves `path` every 5 s for `ms`, as Excalidraw does while someone draws. */ + async function drawFor( + h: SchedulerHarness, + path: string, + ms: number, + ): Promise { + for (let at = 0; at < ms; at += 5_000) { + h.emit("modify", path); + await vi.advanceTimersByTimeAsync(5_000); + } + } + + it("keeps a drawing's saves from holding back the vault's queue", async () => { + const h = harness({ enabled: true, queuedOnly: true }); + h.open(DRAWING); + h.emit("modify", "a.md"); + await drawFor(h, DRAWING, 30_000); + expect(pushed(h)).toEqual([["a.md"]]); + expect(h.slow.holds(DRAWING)).toBe(true); + }); + + it("pushes a drawing after its own quiet period", async () => { + const h = harness({ enabled: true, queuedOnly: true }); + h.open(DRAWING); + h.emit("modify", DRAWING); + await vi.advanceTimersByTimeAsync(SLOW_MS + SETTLE_MS - 1); + expect(h.pushes()).toHaveLength(0); + await vi.advanceTimersByTimeAsync(1); + expect(pushed(h)).toEqual([[DRAWING]]); + expect(h.slow.holds(DRAWING)).toBe(false); + }); + + it("pushes a drawing once its view is left", async () => { + const h = harness({ enabled: true, queuedOnly: true }); + h.open(DRAWING); + h.emit("modify", DRAWING); + h.open("a.md"); + await vi.advanceTimersByTimeAsync(SETTLE_MS); + expect(pushed(h)).toEqual([[DRAWING]]); + }); + + it("pushes nonstop drawing every 10 minutes, then holds it again", async () => { + const h = harness({ enabled: true, queuedOnly: true }); + h.open(DRAWING); + await drawFor(h, DRAWING, SLOW_FILE_CAP_MS + SETTLE_MS); + expect(pushed(h)).toEqual([[DRAWING]]); + expect(h.slow.holds(DRAWING)).toBe(true); + }); + + it("takes a drawing named as a plain note", async () => { + const h = harness({ enabled: true, queuedOnly: true }); + h.open("Sketch.md"); + h.emit("modify", "Sketch.md"); + await vi.advanceTimersByTimeAsync(SETTLE_MS); + expect(h.pushes()).toHaveLength(0); + expect(h.slow.holds("Sketch.md")).toBe(true); + }); + + it("queues a slow file as usual when it is not open or not listed", async () => { + const h = harness({ enabled: true, queuedOnly: true }); + h.open("a.md"); + h.emit("modify", DRAWING); + h.host.settings.slowFileSuffixes = ".canvas"; + h.open("b.excalidraw.md"); + h.emit("modify", "b.excalidraw.md"); + await vi.advanceTimersByTimeAsync(SETTLE_MS); + expect(pushed(h)).toEqual([[DRAWING, "b.excalidraw.md"]]); + }); + + it("lets a rename or deletion of a held file go with its own event", async () => { + const h = harness({ enabled: true, queuedOnly: true }); + h.open(DRAWING); + h.emit("modify", DRAWING); + h.emit("rename", "e.excalidraw.md", DRAWING); + expect(h.slow.holds(DRAWING)).toBe(false); + await vi.advanceTimersByTimeAsync(SETTLE_MS); + expect(pushed(h)).toEqual([["e.excalidraw.md", DRAWING]]); + }); + + it("holds nothing where an edit would not queue, so a scheduled push still takes it", () => { + const h = harness({ enabled: false, queuedOnly: true }); + h.open(DRAWING); + h.emit("modify", DRAWING); + expect(h.slow.holds(DRAWING)).toBe(false); + }); + + it("leaves a new shared drawing to its share's push while its edits wait", async () => { + const h = harness({ enabled: true, queuedOnly: true }); + h.open("Team/new.excalidraw.md"); + h.emit("create", "Team/new.excalidraw.md"); + h.emit("modify", "Team/new.excalidraw.md"); + expect(h.slow.holds("Team/new.excalidraw.md")).toBe(false); + await vi.advanceTimersByTimeAsync(2_000); + expect(h.sharePushes().map((paths) => [...paths])).toEqual([ + ["Team/new.excalidraw.md"], + ]); + }); + + it("drops a held file whose queue was turned off before it was due", async () => { + const h = harness({ enabled: true, queuedOnly: true }); + h.open(DRAWING); + h.emit("modify", DRAWING); + h.host.settings.autoPushAfterChange = false; + await vi.advanceTimersByTimeAsync(SLOW_MS); + expect(h.slow.holds(DRAWING)).toBe(false); + h.host.settings.autoPushAfterChange = true; + h.emit("modify", DRAWING); + expect(h.slow.holds(DRAWING)).toBe(true); + }); +}); diff --git a/packages/plugin/tests/features/sync/automation/scheduler-startup.test.ts b/packages/plugin/tests/features/sync/automation/scheduler-startup.test.ts new file mode 100644 index 00000000..83cc86f2 --- /dev/null +++ b/packages/plugin/tests/features/sync/automation/scheduler-startup.test.ts @@ -0,0 +1,138 @@ +import { + type SchedulerOptions, + schedulerHarness, +} from "@tests/helpers/scheduler"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +function harness( + state: Omit & { autosync?: boolean }, +) { + const { autosync, ...options } = state; + return schedulerHarness({ + compared: false, + ...options, + settings: { + autoSyncEnabled: autosync ?? true, + autoSyncIntervalMinutes: 10, + }, + }); +} + +describe("startup autosync", () => { + beforeEach(() => { + vi.useFakeTimers(); + vi.stubGlobal("navigator", { onLine: true }); + }); + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + + it("waits for the metadata cache while it is still filling", async () => { + const h = harness({ layoutReady: false, initialized: false }); + await vi.advanceTimersByTimeAsync(10_000); + expect(h.syncs()).toBe(0); + + h.resolveCache(); + await vi.advanceTimersByTimeAsync(0); + expect(h.syncs()).toBe(1); + + // The event keeps firing as the vault changes; the first run is the only one. + h.resolveCache(); + await vi.advanceTimersByTimeAsync(0); + expect(h.syncs()).toBe(1); + }); + + it("runs anyway when the cache never reports itself settled", async () => { + const h = harness({ layoutReady: false, initialized: false }); + await vi.advanceTimersByTimeAsync(60_000); + expect(h.syncs()).toBe(1); + }); + + it("keeps the short delay for a cache that settled before it registered", async () => { + const h = harness({ layoutReady: false, initialized: true }); + await vi.advanceTimersByTimeAsync(3_000); + expect(h.syncs()).toBe(1); + }); + + it("keeps the short delay for a plugin enabled by hand", async () => { + const h = harness({ layoutReady: true, initialized: true }); + await vi.advanceTimersByTimeAsync(3_000); + expect(h.syncs()).toBe(1); + }); + + it("does not run after unload", async () => { + const h = harness({ layoutReady: false, initialized: false }); + h.unload(); + await vi.advanceTimersByTimeAsync(60_000); + expect(h.syncs()).toBe(0); + }); + + it("only compares at startup when autosync is off", async () => { + const h = harness({ + layoutReady: true, + initialized: true, + autosync: false, + }); + await vi.advanceTimersByTimeAsync(60_000); + expect(h.syncs()).toBe(0); + expect(h.compares()).toBe(1); + }); + + it("waits for the metadata cache before that compare too", async () => { + const h = harness({ + layoutReady: false, + initialized: false, + autosync: false, + }); + await vi.advanceTimersByTimeAsync(10_000); + expect(h.compares()).toBe(0); + h.resolveCache(); + await vi.advanceTimersByTimeAsync(0); + expect(h.compares()).toBe(1); + }); + + it("never asks for a passphrase on launch to compare", async () => { + const h = harness({ + layoutReady: true, + initialized: true, + autosync: false, + savedPassphrase: false, + }); + await vi.advanceTimersByTimeAsync(60_000); + expect(h.compares()).toBe(0); + }); + + it("skips the compare when the saved passphrase no longer opens the vault", async () => { + const h = harness({ + layoutReady: true, + initialized: true, + autosync: false, + rotated: true, + }); + await vi.advanceTimersByTimeAsync(60_000); + expect(h.compares()).toBe(0); + }); + + it("leaves a compare that already ran alone", async () => { + const h = harness({ + layoutReady: true, + initialized: true, + autosync: false, + compared: true, + }); + await vi.advanceTimersByTimeAsync(60_000); + expect(h.compares()).toBe(0); + }); + + it("does not compare offline", async () => { + vi.stubGlobal("navigator", { onLine: false }); + const h = harness({ + layoutReady: true, + initialized: true, + autosync: false, + }); + await vi.advanceTimersByTimeAsync(60_000); + expect(h.compares()).toBe(0); + }); +}); diff --git a/packages/plugin/tests/sync/cancel.test.ts b/packages/plugin/tests/features/sync/cancel.test.ts similarity index 96% rename from packages/plugin/tests/sync/cancel.test.ts rename to packages/plugin/tests/features/sync/cancel.test.ts index 41dfa435..b160cc0b 100644 --- a/packages/plugin/tests/sync/cancel.test.ts +++ b/packages/plugin/tests/features/sync/cancel.test.ts @@ -1,15 +1,15 @@ import { TestSession, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; +import { runWithConcurrency } from "@/core/utils/concurrency"; +import { pullPaths } from "@/features/sync/apply/pull"; import { isCancellation, SyncCancelledError, throwIfCancelled, -} from "@/sync/cancel"; -import { REMOTE_OBJECTS_PREFIX } from "@/sync/constants"; -import { compare, pushPaths } from "@/sync/engine"; -import { fetchRemoteManifest } from "@/sync/manifest"; -import { pullPaths } from "@/sync/pull"; -import { runWithConcurrency } from "@/utils"; +} from "@/features/sync/cancel"; +import { REMOTE_OBJECTS_PREFIX } from "@/features/sync/constants"; +import { compare, pushPaths } from "@/features/sync/engine"; +import { fetchRemoteManifest } from "@/features/sync/remote/manifest"; describe("throwIfCancelled", () => { it("passes through when there is no signal or it is live", () => { diff --git a/packages/plugin/tests/sync/category-reset-roundtrip.test.ts b/packages/plugin/tests/features/sync/category-reset-roundtrip.test.ts similarity index 92% rename from packages/plugin/tests/sync/category-reset-roundtrip.test.ts rename to packages/plugin/tests/features/sync/category-reset-roundtrip.test.ts index 8d98238a..78aaf5ce 100644 --- a/packages/plugin/tests/sync/category-reset-roundtrip.test.ts +++ b/packages/plugin/tests/features/sync/category-reset-roundtrip.test.ts @@ -8,11 +8,15 @@ import { import { RevalidatingStorage } from "@tests/helpers/revalidating-storage"; import { useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; -import { encryptJson } from "@/crypto"; -import { REMOTE_MANIFEST_KEY } from "@/sync/constants"; -import { runCategoryResetFlow } from "@/sync/operations/config-reset"; -import { EHunkPair, loadHunkSides } from "@/sync/operations/text-loaders"; -import { EChangeType } from "@/sync/types"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; +import { encryptJson } from "@/core/crypto/cipher"; +import { MANIFEST_VERSION } from "@/features/sync/constants"; +import { runCategoryResetFlow } from "@/features/sync/operations/config-reset"; +import { + EHunkPair, + loadHunkSides, +} from "@/features/sync/operations/text-loaders"; +import { EChangeType } from "@/features/sync/types"; useEncryptionKey(); const pluginPath = ".obsidian/plugins/sample/data.json"; @@ -45,7 +49,7 @@ describe("remote category reset across devices", () => { expect(reset.compareResult.remote?.folders ?? []).not.toContain( ".obsidian/plugins/empty", ); - expect(reset.compareResult.remote?.version).toBe(2); + expect(reset.compareResult.remote?.version).toBe(MANIFEST_VERSION); expect(a.text(pluginPath)).toBe(`initial ${pluginPath}`); expect(a.state.baseline?.files[pluginPath]).toBeUndefined(); for (const path of configFiles.filter((p) => p !== pluginPath)) { diff --git a/packages/plugin/tests/sync/content-cache.test.ts b/packages/plugin/tests/features/sync/changes/content-cache.test.ts similarity index 94% rename from packages/plugin/tests/sync/content-cache.test.ts rename to packages/plugin/tests/features/sync/changes/content-cache.test.ts index d454db39..44171f16 100644 --- a/packages/plugin/tests/sync/content-cache.test.ts +++ b/packages/plugin/tests/features/sync/changes/content-cache.test.ts @@ -5,13 +5,13 @@ import { type EncryptionKey, encryptBytes, sha256Hex, -} from "@/crypto"; +} from "@/core/crypto/cipher"; import { clearRemoteTextCache, loadRemoteText, textToBytes, -} from "@/sync/content"; -import { objectKey } from "@/sync/manifest"; +} from "@/features/sync/changes/content"; +import { objectKey } from "@/features/sync/content/keys"; async function seed( storage: FakeStorage, @@ -66,7 +66,8 @@ describe("remote text cache", () => { expect(await loadRemoteText(deps, hash)).toBe( "uploaded later by another device", ); - expect(storage.getCalls).toBe(2); + // Without a size, a miss looks under both root folders. + expect(storage.getCalls).toBe(3); }); it("never serves one remote's content to another", async () => { @@ -79,7 +80,7 @@ describe("remote text cache", () => { const share = new FakeStorage(); expect(await loadRemoteText({ storage: share, key }, hash)).toBeNull(); - expect(share.getCalls).toBe(1); + expect(share.getCalls).toBe(2); }); it("keeps its budget intact when callers race the same hash", async () => { diff --git a/packages/plugin/tests/sync/content-text.test.ts b/packages/plugin/tests/features/sync/changes/content-text.test.ts similarity index 89% rename from packages/plugin/tests/sync/content-text.test.ts rename to packages/plugin/tests/features/sync/changes/content-text.test.ts index 38ecf566..e87388a6 100644 --- a/packages/plugin/tests/sync/content-text.test.ts +++ b/packages/plugin/tests/features/sync/changes/content-text.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from "vitest"; -import { bytesToText, isLikelyText, textToBytes } from "@/sync/content"; +import { + bytesToText, + isLikelyText, + textToBytes, +} from "@/features/sync/changes/content"; const LATIN1_CAFE = new Uint8Array([0x63, 0x61, 0x66, 0xe9]); const BOM_NOTE = new Uint8Array([0xef, 0xbb, 0xbf, 0x68, 0x69]); diff --git a/packages/plugin/tests/sync/diff.test.ts b/packages/plugin/tests/features/sync/changes/diff.test.ts similarity index 98% rename from packages/plugin/tests/sync/diff.test.ts rename to packages/plugin/tests/features/sync/changes/diff.test.ts index 3299f5ad..798bfc32 100644 --- a/packages/plugin/tests/sync/diff.test.ts +++ b/packages/plugin/tests/features/sync/changes/diff.test.ts @@ -1,12 +1,12 @@ import { describe, expect, it } from "vitest"; -import { type DiffInput, diff } from "@/sync/diff"; +import { type DiffInput, diff } from "@/features/sync/changes/diff"; import { EChangeType, EFileKind, type LocalSnapshot, type Manifest, type ManifestEntry, -} from "@/sync/types"; +} from "@/features/sync/types"; function mockManifest( snapshotId: string, diff --git a/packages/plugin/tests/utils/file-concurrency.test.ts b/packages/plugin/tests/features/sync/changes/file-concurrency.test.ts similarity index 97% rename from packages/plugin/tests/utils/file-concurrency.test.ts rename to packages/plugin/tests/features/sync/changes/file-concurrency.test.ts index 9ebd4aa3..54fd5bc3 100644 --- a/packages/plugin/tests/utils/file-concurrency.test.ts +++ b/packages/plugin/tests/features/sync/changes/file-concurrency.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest"; import { LARGE_FILE_BYTES, runWithFileConcurrency, -} from "@/utils/file-concurrency"; +} from "@/features/sync/changes/file-concurrency"; const pause = () => new Promise((resolve) => setTimeout(resolve, 0)); diff --git a/packages/plugin/tests/features/sync/changes/local-copy.test.ts b/packages/plugin/tests/features/sync/changes/local-copy.test.ts new file mode 100644 index 00000000..27b7811c --- /dev/null +++ b/packages/plugin/tests/features/sync/changes/local-copy.test.ts @@ -0,0 +1,30 @@ +import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; +import { describe, expect, it } from "vitest"; +import { loadLocalCopy } from "@/features/sync/changes/content"; +import { LARGE_FILE_BYTES } from "@/features/sync/changes/file-concurrency"; + +describe("loadLocalCopy", () => { + const MB = 1024 * 1024; + + async function disk(size: number) { + const adapter = new InMemoryAdapter(); + await adapter.writeBinary("big.bin", new ArrayBuffer(size)); + return adapter.asDataAdapter(); + } + + it("reads a copy no bigger than the remote file, or below the large-file mark", async () => { + expect( + await loadLocalCopy(await disk(MB), "big.bin", 256 * 1024), + ).toHaveLength(MB); + const large = LARGE_FILE_BYTES + MB; + expect( + await loadLocalCopy(await disk(large), "big.bin", large), + ).toHaveLength(large); + }); + + it("skips a large copy of a file pulled as small, and a missing one", async () => { + const adapter = await disk(LARGE_FILE_BYTES + MB); + expect(await loadLocalCopy(adapter, "big.bin", 256 * 1024)).toBeNull(); + expect(await loadLocalCopy(adapter, "gone.bin", 256 * 1024)).toBeNull(); + }); +}); diff --git a/packages/plugin/tests/sync/chaos.test.ts b/packages/plugin/tests/features/sync/chaos.test.ts similarity index 96% rename from packages/plugin/tests/sync/chaos.test.ts rename to packages/plugin/tests/features/sync/chaos.test.ts index 2ad6ed10..7cad878a 100644 --- a/packages/plugin/tests/sync/chaos.test.ts +++ b/packages/plugin/tests/features/sync/chaos.test.ts @@ -4,8 +4,8 @@ import { killNextWrite } from "@tests/helpers/faults"; import { seeded } from "@tests/helpers/seeded"; import { TestSession, useEncryptionKey } from "@tests/helpers/session"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { SyncController } from "@/sync/controller"; -import { WriteJournal } from "@/sync/journal"; +import { SyncController } from "@/features/sync/controller"; +import { WriteJournal } from "@/features/sync/recovery/journal"; useEncryptionKey(); afterEach(() => vi.restoreAllMocks()); diff --git a/packages/plugin/tests/features/sync/chunked-push.test.ts b/packages/plugin/tests/features/sync/chunked-push.test.ts new file mode 100644 index 00000000..f2c54dbe --- /dev/null +++ b/packages/plugin/tests/features/sync/chunked-push.test.ts @@ -0,0 +1,119 @@ +import { FakeStorage } from "@tests/helpers/fake-storage"; +import { seeded } from "@tests/helpers/seeded"; +import { TestSession, useEncryptionKey } from "@tests/helpers/session"; +import { beforeAll, describe, expect, it, vi } from "vitest"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; +import { deriveChunkIds, sha256Hex } from "@/core/crypto"; +import { pullPaths } from "@/features/sync/apply/pull"; +import { objectKey, recipeKey } from "@/features/sync/content/keys"; +import { compare, pushPaths } from "@/features/sync/engine"; +import { uploadedHere } from "@/features/sync/remote/uploads"; + +const SIZE = 600 * 1024; +let chunkIds: CryptoKey; +beforeAll(async () => { + chunkIds = await deriveChunkIds(new Uint8Array(32).fill(9)); +}); + +function random(seed: number): Uint8Array { + const next = seeded(seed); + return new Uint8Array(SIZE).map(() => Math.floor(next() * 256)); +} + +async function write(session: TestSession, bytes: Uint8Array): Promise { + await session.adapter.writeBinary("big.bin", bytes.slice().buffer); +} + +async function pushAll(session: TestSession): Promise { + const result = await compare(session.deps()); + await pushPaths( + session.deps(), + result, + result.diff.localChanges.map((change) => change.path), + ); + await session.adoptRemote(); +} + +describe("a big file pushed in chunks", () => { + useEncryptionKey(); + + it("lands as a recipe that another device pulls, and an edit uploads only its changed chunks", async () => { + const storage = new FakeStorage(); + const source = new TestSession("device-a", storage); + source.chunkIds = chunkIds; + const v1 = random(1); + await write(source, v1); + await pushAll(source); + const h1 = await sha256Hex(v1); + expect(storage.map.has(recipeKey(h1))).toBe(true); + expect(storage.map.has(objectKey(h1))).toBe(false); + + const v2 = v1.slice(); + v2.set(new Uint8Array(64).fill(1), SIZE / 2); + await write(source, v2); + const put = vi.spyOn(storage, "put"); + await pushAll(source); + const chunkPuts = put.mock.calls.filter(([at]) => at.startsWith("chunks/")); + expect(chunkPuts.length).toBeLessThanOrEqual(2); + + const target = new TestSession("device-b", storage); + const before = await compare(target.deps()); + await pullPaths(target.deps(), before, ["big.bin"]); + const pulled = new Uint8Array(await target.adapter.readBinary("big.bin")); + expect(pulled).toEqual(v2); + }); + + it("leaves a root that leans on HEAD's chunks out of the upload log, so a retry stores it again", async () => { + const storage = new FakeStorage(); + const source = new TestSession("device-a", storage); + source.chunkIds = chunkIds; + const v1 = random(2); + await write(source, v1); + await pushAll(source); + + const v2 = v1.slice(); + v2.set(new Uint8Array(64).fill(1), SIZE / 2); + await write(source, v2); + const fresh = random(3); + await source.adapter.writeBinary("new.bin", fresh.slice().buffer); + const put = storage.put.bind(storage); + vi.spyOn(storage, "put").mockImplementation((at, body) => + at === REMOTE_MANIFEST_KEY + ? Promise.reject(new Error("offline")) + : put(at, body), + ); + await expect(pushAll(source)).rejects.toThrow("offline"); + + const h2 = await sha256Hex(v2); + expect(storage.map.has(recipeKey(h2))).toBe(true); + expect(uploadedHere(storage, h2)).toBe(false); + expect(uploadedHere(storage, await sha256Hex(fresh))).toBe(true); + }); + + it("pulls a new version downloading only the chunks the old one on disk lacks", async () => { + const storage = new FakeStorage(); + const source = new TestSession("device-a", storage); + const target = new TestSession("device-b", storage); + source.chunkIds = chunkIds; + target.chunkIds = chunkIds; + const v1 = random(4); + await write(source, v1); + await pushAll(source); + const first = await compare(target.deps()); + await pullPaths(target.deps(), first, ["big.bin"]); + await target.adoptRemote(); + + const v2 = v1.slice(); + v2.set(new Uint8Array(64).fill(1), SIZE / 2); + await write(source, v2); + await pushAll(source); + const get = vi.spyOn(storage, "get"); + const second = await compare(target.deps()); + await pullPaths(target.deps(), second, ["big.bin"]); + + const pulled = new Uint8Array(await target.adapter.readBinary("big.bin")); + expect(pulled).toEqual(v2); + const chunkGets = get.mock.calls.filter(([at]) => at.startsWith("chunks/")); + expect(chunkGets.length).toBeLessThanOrEqual(2); + }); +}); diff --git a/packages/plugin/tests/features/sync/content/closure.test.ts b/packages/plugin/tests/features/sync/content/closure.test.ts new file mode 100644 index 00000000..c318f71d --- /dev/null +++ b/packages/plugin/tests/features/sync/content/closure.test.ts @@ -0,0 +1,149 @@ +import { FakeStorage } from "@tests/helpers/fake-storage"; +import { putRecipe } from "@tests/helpers/recipes"; +import { RevalidatingStorage } from "@tests/helpers/revalidating-storage"; +import { beforeAll, describe, expect, it, vi } from "vitest"; +import { deriveKey, type EncryptionKey, encryptBytes } from "@/core/crypto"; +import type { ListedObject } from "@/features/storage"; +import { + chunksNamed, + forgetUnlistedRecipes, +} from "@/features/sync/content/closure"; +import { chunkKey, recipeKey } from "@/features/sync/content/keys"; + +const A = "a".repeat(64); +const B = "b".repeat(64); + +let key: EncryptionKey; +beforeAll(async () => { + key = await deriveKey("pw", new Uint8Array(16)); +}); + +const listing = (storage: FakeStorage): Promise => + storage.listDetailed("recipes/"); + +const chunks = (...ids: string[]): Set => new Set(ids.map(chunkKey)); + +/** The keys `get` was asked for. */ +const reads = (get: { mock: { calls: unknown[][] } }): unknown[] => + get.mock.calls.map(([at]) => at); + +describe("chunksNamed", () => { + it("names the chunks of every listed recipe", async () => { + const storage = new RevalidatingStorage(); + await putRecipe(storage, key, A, [ + ["a0", 1], + ["a1", 1], + ]); + await putRecipe(storage, key, B, [["b0", 1]]); + + const named = await chunksNamed(storage, key, await listing(storage), 4); + + expect(named.chunks).toEqual(chunks("a0", "a1", "b0")); + expect(named.unreadable).toEqual([]); + }); + + it("reads nothing for a recipe whose etag it holds", async () => { + const storage = new RevalidatingStorage(); + await putRecipe(storage, key, A, [["a0", 1]]); + const listed = await listing(storage); + await chunksNamed(storage, key, listed, 4); + const get = vi.spyOn(storage, "get"); + + const again = await chunksNamed(storage, key, listed, 4); + + expect(get).not.toHaveBeenCalled(); + expect(again.chunks).toEqual(chunks("a0")); + }); + + it("reads a recipe again once its etag moved", async () => { + const storage = new RevalidatingStorage(); + await putRecipe(storage, key, A, [["a0", 1]]); + await chunksNamed(storage, key, await listing(storage), 4); + await putRecipe(storage, key, A, [["a1", 1]]); + const get = vi.spyOn(storage, "get"); + + const named = await chunksNamed(storage, key, await listing(storage), 4); + + expect(reads(get)).toEqual([recipeKey(A)]); + expect(named.chunks).toEqual(chunks("a1")); + }); + + it("does not remember a read listed without an etag", async () => { + const storage = new FakeStorage(); + await putRecipe(storage, key, A, [["a0", 1]]); + const listed = await listing(storage); + expect(listed[0]?.etag).toBeNull(); + await chunksNamed(storage, key, listed, 4); + const get = vi.spyOn(storage, "get"); + + const again = await chunksNamed(storage, key, listed, 4); + + expect(reads(get)).toEqual([recipeKey(A)]); + expect(again.chunks).toEqual(chunks("a0")); + }); + + it("reports a recipe that does not read, and still names the others", async () => { + const storage = new RevalidatingStorage(); + await putRecipe(storage, key, A, [["a0", 1]]); + await storage.put( + recipeKey(B), + await encryptBytes(key, new TextEncoder().encode("no recipe")), + ); + + const named = await chunksNamed(storage, key, await listing(storage), 4); + + expect(named.unreadable).toEqual([recipeKey(B)]); + expect(named.chunks).toEqual(chunks("a0")); + }); + + it("does not remember a recipe that failed to read", async () => { + const storage = new FakeStorage(); + // Listed under one etag throughout: only a remembered failure could keep it unreadable. + const listed: ListedObject[] = [ + { key: recipeKey(A), etag: '"e1"', modified: null }, + ]; + await storage.put(recipeKey(A), new Uint8Array([1, 2, 3])); + expect((await chunksNamed(storage, key, listed, 4)).unreadable).toEqual([ + recipeKey(A), + ]); + + await putRecipe(storage, key, A, [["a0", 1]]); + const named = await chunksNamed(storage, key, listed, 4); + + expect(named.unreadable).toEqual([]); + expect(named.chunks).toEqual(chunks("a0")); + }); + + it("names nothing for a recipe gone since the listing, and keeps the rest", async () => { + const storage = new RevalidatingStorage(); + await putRecipe(storage, key, A, [["a0", 1]]); + await putRecipe(storage, key, B, [["b0", 1]]); + const listed = await listing(storage); + await storage.delete(recipeKey(A)); + + const named = await chunksNamed(storage, key, listed, 4); + + expect(named.chunks).toEqual(chunks("b0")); + expect(named.unreadable).toEqual([]); + }); +}); + +describe("forgetUnlistedRecipes", () => { + it("drops what a listing no longer holds, so only that recipe is read again", async () => { + const storage = new RevalidatingStorage(); + await putRecipe(storage, key, A, [["a0", 1]]); + await putRecipe(storage, key, B, [["b0", 1]]); + const listed = await listing(storage); + await chunksNamed(storage, key, listed, 4); + + forgetUnlistedRecipes( + storage, + listed.filter(({ key: at }) => at === recipeKey(A)), + ); + const get = vi.spyOn(storage, "get"); + const named = await chunksNamed(storage, key, listed, 4); + + expect(reads(get)).toEqual([recipeKey(B)]); + expect(named.chunks).toEqual(chunks("a0", "b0")); + }); +}); diff --git a/packages/plugin/tests/features/sync/content/load.test.ts b/packages/plugin/tests/features/sync/content/load.test.ts new file mode 100644 index 00000000..0b0fbfc0 --- /dev/null +++ b/packages/plugin/tests/features/sync/content/load.test.ts @@ -0,0 +1,406 @@ +import { + bytesOf, + compressedDrawing, + plainDrawing, +} from "@tests/helpers/drawing-file"; +import { FakeStorage } from "@tests/helpers/fake-storage"; +import { + concat, + putChunked, + putChunks, + putRecipe, +} from "@tests/helpers/recipes"; +import { seeded } from "@tests/helpers/seeded"; +import { beforeAll, describe, expect, it, vi } from "vitest"; +import { + deriveChunkIds, + deriveKey, + type EncryptionKey, + encryptBytes, + encryptCompressible, + encryptDescribed, + sha256Hex, +} from "@/core/crypto"; +import { encodeDrawing } from "@/core/drawing"; +import { + CHUNK_THRESHOLD, + chunkKey, + objectKey, + recipeKey, +} from "@/features/sync/content/keys"; +import { + ContentError, + loadContent, + prepareContent, +} from "@/features/sync/content/load"; +import { storeContent } from "@/features/sync/content/store"; + +let key: EncryptionKey; +beforeAll(async () => { + key = await deriveKey("pw", new Uint8Array(16)); +}); + +async function put( + storage: FakeStorage, + bytes: Uint8Array, + blob: Uint8Array, +): Promise { + const hash = await sha256Hex(bytes); + await storage.put(objectKey(hash), blob); + return hash; +} + +function drawing() { + const bytes = bytesOf(compressedDrawing()); + const encoded = encodeDrawing(bytes); + if (!encoded) throw new Error("fixture does not encode"); + return { bytes, ...encoded }; +} + +describe("loadContent", () => { + it("reads a 0x01 blob", async () => { + const storage = new FakeStorage(); + const bytes = bytesOf("a plain note"); + const hash = await put(storage, bytes, await encryptBytes(key, bytes)); + expect(await loadContent({ storage, key }, hash)).toEqual(bytes); + }); + + it("reads a 0x02 blob", async () => { + const storage = new FakeStorage(); + const bytes = bytesOf("a long note. ".repeat(2000)); + const blob = await encryptCompressible(key, bytes); + expect(blob[0]).toBe(0x02); + const hash = await put(storage, bytes, blob); + expect(await loadContent({ storage, key }, hash)).toEqual(bytes); + }); + + it("rebuilds a drawing from a described codec blob, byte for byte", async () => { + const storage = new FakeStorage(); + const { bytes, stored, codec } = drawing(); + const blob = await encryptDescribed(key, { codec }, stored); + expect(blob[0]).toBe(0x03); + const hash = await put(storage, bytes, blob); + expect(await loadContent({ storage, key }, hash)).toEqual(bytes); + }); + + it("reads a described blob with no codec as the payload itself", async () => { + const storage = new FakeStorage(); + const bytes = bytesOf(plainDrawing()); + const hash = await put( + storage, + bytes, + await encryptDescribed(key, {}, bytes), + ); + expect(await loadContent({ storage, key }, hash)).toEqual(bytes); + }); + + it("is null only for an absent object, and passes the size on", async () => { + const storage = new FakeStorage(); + expect(await loadContent({ storage, key }, "f".repeat(64))).toBeNull(); + const sizes: Array = []; + const get = storage.get.bind(storage); + storage.get = (path: string, size?: number) => { + sizes.push(size); + return get(path); + }; + await loadContent({ storage, key }, "e".repeat(64), 1234); + expect(sizes).toEqual([1234]); + }); + + it("refuses an unknown codec name: wrong bytes are never returned", async () => { + const storage = new FakeStorage(); + const { bytes, stored, codec } = drawing(); + const blob = await encryptDescribed( + key, + { codec: { ...codec, name: "future-codec" } }, + stored, + ); + const hash = await put(storage, bytes, blob); + await expect(loadContent({ storage, key }, hash)).rejects.toThrow( + /Unknown content codec/, + ); + }); + + it("refuses a header with a chunks field, even beside a good codec", async () => { + const storage = new FakeStorage(); + const { bytes, stored, codec } = drawing(); + for (const header of [ + { chunks: [["a".repeat(64), 10]] }, + { codec, chunks: [] }, + ]) { + const hash = await put( + storage, + bytes, + await encryptDescribed(key, header, stored), + ); + await expect(loadContent({ storage, key }, hash)).rejects.toThrow( + /Unreadable chunk list/, + ); + } + }); + + it("refuses an unknown header shape", async () => { + const storage = new FakeStorage(); + const { bytes, stored, codec } = drawing(); + const odd: unknown[] = [ + { other: 1 }, + { codec, other: 1 }, + { codec: null }, + { codec: { name: "excalidraw-lz", width: "256", gap: "\n\n" } }, + { codec: { ...codec, width: 0 } }, + { codec: { ...codec, extra: true } }, + [1, 2], + "text", + null, + ]; + for (const header of odd) { + const hash = await put( + storage, + bytes, + await encryptDescribed(key, header as object, stored), + ); + await expect(loadContent({ storage, key }, hash)).rejects.toThrow( + /Unreadable content header|Unknown content/, + ); + } + }); + + it("refuses a rebuilt file that does not hash to its name", async () => { + const storage = new FakeStorage(); + const { bytes, stored, codec } = drawing(); + // Same scene, another width: decodes cleanly into a different file. + const wrongWidth = await encryptDescribed( + key, + { codec: { ...codec, width: 100 } }, + stored, + ); + const hash = await put(storage, bytes, wrongWidth); + await expect(loadContent({ storage, key }, hash)).rejects.toThrow( + /Hash mismatch/, + ); + + const other = bytesOf("something else"); + const named = await put( + storage, + bytes, + await encryptDescribed(key, {}, other), + ); + await expect(loadContent({ storage, key }, named)).rejects.toThrow( + /Hash mismatch/, + ); + }); + + it("keeps the hash mismatch error for a plain blob", async () => { + const storage = new FakeStorage(); + const hash = await put( + storage, + bytesOf("real"), + await encryptBytes(key, bytesOf("tampered")), + ); + await expect(loadContent({ storage, key }, hash)).rejects.toThrow( + `Hash mismatch for remote object ${hash}`, + ); + }); + + it("throws on a corrupt blob rather than returning null", async () => { + const storage = new FakeStorage(); + const bytes = bytesOf("note"); + const blob = await encryptBytes(key, bytes); + blob[blob.length - 1] = (blob[blob.length - 1] ?? 0) ^ 1; + const hash = await put(storage, bytes, blob); + await expect(loadContent({ storage, key }, hash)).rejects.toThrow(); + }); +}); + +describe("loadContent, chunked", () => { + const parts = [bytesOf("first part, "), bytesOf("second, "), bytesOf("last")]; + const bytes = concat(parts); + const BIG = CHUNK_THRESHOLD; + + it("joins the chunks a recipe names, looking under recipes/ first for a big file", async () => { + const storage = new FakeStorage(); + const hash = await putChunked(storage, key, parts); + const get = vi.spyOn(storage, "get"); + + expect(await loadContent({ storage, key }, hash, BIG)).toEqual(bytes); + expect(get.mock.calls[0]?.[0]).toBe(recipeKey(hash)); + expect(get).not.toHaveBeenCalledWith(objectKey(hash), BIG); + }); + + it("finds a big file stored whole, and a recipe when the size is unknown", async () => { + const storage = new FakeStorage(); + const whole = bytesOf("uploaded before chunking"); + const hash = await put(storage, whole, await encryptBytes(key, whole)); + expect(await loadContent({ storage, key }, hash, BIG)).toEqual(whole); + + const chunked = await putChunked(storage, key, parts); + expect(await loadContent({ storage, key }, chunked)).toEqual(bytes); + expect(await loadContent({ storage, key }, chunked, 10)).toBeNull(); + }); + + it("rebuilds a chunked drawing", async () => { + const storage = new FakeStorage(); + const { bytes: file, stored, codec } = drawing(); + const half = Math.floor(stored.length / 2); + await putChunks(storage, key, { + d0: stored.subarray(0, half), + d1: stored.subarray(half), + }); + const hash = await sha256Hex(file); + const sizes: [string, number][] = [ + ["d0", half], + ["d1", stored.length - half], + ]; + await putRecipe(storage, key, hash, sizes, codec); + expect(await loadContent({ storage, key }, hash)).toEqual(file); + }); + + it("throws, never null, on a missing chunk or one of the wrong size", async () => { + const storage = new FakeStorage(); + const hash = await putChunked(storage, key, parts); + await storage.put(chunkKey("c1"), await encryptBytes(key, bytesOf("x"))); + await expect(loadContent({ storage, key }, hash)).rejects.toThrow( + /wrong size/, + ); + + await storage.delete(chunkKey("c1")); + await expect(loadContent({ storage, key }, hash)).rejects.toThrow( + ContentError, + ); + }); + + it("refuses a recipe that is no recipe: a plain blob, a payload beside chunks, no chunks", async () => { + const storage = new FakeStorage(); + const hash = await putChunked(storage, key, parts); + const chunks = { chunks: [["c0", parts[0]?.length]] }; + for (const blob of [ + await encryptBytes(key, bytes), + await encryptDescribed(key, chunks, bytesOf("payload")), + await encryptDescribed(key, {}, bytes), + ]) { + await storage.put(recipeKey(hash), blob); + await expect(loadContent({ storage, key }, hash)).rejects.toThrow( + ContentError, + ); + } + }); + + it("refuses joined chunks that do not hash to the name", async () => { + const storage = new FakeStorage(); + await putChunks(storage, key, { x: bytesOf("other") }); + await putRecipe(storage, key, "a".repeat(64), [["x", 5]]); + await expect(loadContent({ storage, key }, "a".repeat(64))).rejects.toThrow( + /Hash mismatch/, + ); + }); +}); + +describe("prepareContent", () => { + class HintedStorage extends FakeStorage { + readonly hints: string[][] = []; + + prepareReads(keys: string[]): void { + this.hints.push(keys); + } + } + + it("hints roots, then roots and the chunks big files name, and reads each recipe once", async () => { + const storage = new HintedStorage(); + const parts = [bytesOf("one "), bytesOf("two")]; + const big = await putChunked(storage, key, parts); + const legacy = bytesOf("big, stored whole"); + const whole = await put(storage, legacy, await encryptBytes(key, legacy)); + const small = await put( + storage, + bytesOf("s"), + await encryptBytes(key, bytesOf("s")), + ); + const source = { storage, key }; + const entries = [ + { hash: big, size: CHUNK_THRESHOLD }, + { hash: whole, size: CHUNK_THRESHOLD }, + { hash: small, size: 1 }, + ]; + const roots = [ + recipeKey(big), + objectKey(big), + recipeKey(whole), + objectKey(whole), + objectKey(small), + ]; + + await prepareContent(source, entries); + expect(storage.hints).toEqual([ + roots, + [...roots, chunkKey("c0"), chunkKey("c1")], + ]); + + const get = vi.spyOn(storage, "get"); + expect(await loadContent(source, big, CHUNK_THRESHOLD)).toEqual( + concat(parts), + ); + expect(await loadContent(source, whole, CHUNK_THRESHOLD)).toEqual(legacy); + const read = get.mock.calls.map(([storageKey]) => storageKey); + expect(read).not.toContain(recipeKey(big)); + + // Taken once: a second load reads again. + await loadContent(source, big, CHUNK_THRESHOLD); + expect(get).toHaveBeenCalledWith(recipeKey(big), CHUNK_THRESHOLD); + }); +}); + +describe("loadContent, with a local copy", () => { + const SIZE = 600 * 1024; + let chunkIds: CryptoKey; + beforeAll(async () => { + chunkIds = await deriveChunkIds(new Uint8Array(32).fill(5)); + }); + + function random(seed: number): Uint8Array { + const next = seeded(seed); + return new Uint8Array(SIZE).map(() => Math.floor(next() * 256)); + } + + /** v2 stored chunked; v1 is what the disk holds. */ + async function versions() { + const storage = new FakeStorage(); + const v1 = random(1); + const v2 = v1.slice(); + v2.set(bytesOf("an edit in the middle"), SIZE / 2); + const h2 = await sha256Hex(v2); + await storeContent({ storage, key, chunkIds }, h2, v2); + const all = (await storage.list("chunks/")).length; + const gets = vi.spyOn(storage, "get"); + const chunkGets = () => + gets.mock.calls.filter(([at]) => at.startsWith("chunks/")).length; + return { storage, v1, v2, h2, all, chunkGets }; + } + + it("downloads only the chunks the local copy lacks", async () => { + const { storage, v1, v2, h2, chunkGets } = await versions(); + const loaded = await loadContent( + { storage, key, chunkIds }, + h2, + SIZE, + async () => v1, + ); + expect(loaded).toEqual(v2); + expect(chunkGets()).toBeLessThanOrEqual(2); + }); + + it("downloads every chunk without a chunk key, or when the copy does not read", async () => { + const { storage, v1, v2, h2, all, chunkGets } = await versions(); + expect( + await loadContent({ storage, key }, h2, SIZE, async () => v1), + ).toEqual(v2); + expect(chunkGets()).toBe(all); + + const failing = async (): Promise => { + throw new Error("locked"); + }; + expect( + await loadContent({ storage, key, chunkIds }, h2, SIZE, failing), + ).toEqual(v2); + expect(chunkGets()).toBe(2 * all); + }); +}); diff --git a/packages/plugin/tests/features/sync/content/roundtrip.test.ts b/packages/plugin/tests/features/sync/content/roundtrip.test.ts new file mode 100644 index 00000000..fc5a5ca4 --- /dev/null +++ b/packages/plugin/tests/features/sync/content/roundtrip.test.ts @@ -0,0 +1,86 @@ +import { + bytesOf, + compressedDrawing, + sceneJson, +} from "@tests/helpers/drawing-file"; +import { pairedSessions, useEncryptionKey } from "@tests/helpers/session"; +import { describe, expect, it } from "vitest"; +import { decryptDescribed } from "@/core/crypto"; +import { pullPaths } from "@/features/sync/apply/pull"; +import { objectKey } from "@/features/sync/content/keys"; +import { pushPaths, pushSingleFile } from "@/features/sync/engine"; + +useEncryptionKey(); + +const decoder = new TextDecoder(); + +describe("a drawing across two devices", () => { + it("is pushed described and pulled back byte for byte", async () => { + const [a, b] = pairedSessions(); + const text = compressedDrawing(sceneJson(80)); + a.adapter.putText("map.excalidraw.md", text); + a.adapter.putText("note.md", "a note\n"); + + const first = await a.compare(); + const manifest = await pushPaths(a.deps(), first, [ + "map.excalidraw.md", + "note.md", + ]); + const drawing = manifest.files["map.excalidraw.md"]; + const note = manifest.files["note.md"]; + expect(drawing?.size).toBe(bytesOf(text).length); + + const blob = a.storage.map.get(objectKey(drawing?.hash ?? "")); + expect(blob?.[0]).toBe(0x03); + expect(a.storage.map.get(objectKey(note?.hash ?? ""))?.[0]).toBe(0x01); + + const pulled = await b.compare(); + await pullPaths(b.deps(), pulled, ["map.excalidraw.md", "note.md"]); + expect(b.text("map.excalidraw.md")).toBe(text); + expect(b.text("note.md")).toBe("a note\n"); + }); + + it("is stored described by a single-file push too", async () => { + const [a, b] = pairedSessions(); + const text = compressedDrawing(sceneJson(50)); + const first = await a.compare(); + const manifest = await pushSingleFile( + a.deps(), + first, + "one.excalidraw.md", + bytesOf(text), + ); + const hash = manifest.files["one.excalidraw.md"]?.hash ?? ""; + const blob = a.storage.map.get(objectKey(hash)); + expect(blob?.[0]).toBe(0x03); + const opened = await decryptDescribed( + a.deps().key, + blob ?? new Uint8Array(), + ); + expect(decoder.decode(opened.payload)).toContain("```json\n"); + + const pulled = await b.compare(); + await pullPaths(b.deps(), pulled, ["one.excalidraw.md"]); + expect(b.text("one.excalidraw.md")).toBe(text); + }); + + it("stores an edited drawing as a new object that still reads back", async () => { + const [a, b] = pairedSessions(); + a.adapter.putText("map.excalidraw.md", compressedDrawing(sceneJson(40))); + const first = await a.compare(); + const one = await pushPaths(a.deps(), first, ["map.excalidraw.md"]); + a.state = { ...a.state, vaultId: one.vaultId, baseline: one }; + + const edited = compressedDrawing(sceneJson(41)); + a.adapter.putText("map.excalidraw.md", edited); + const second = await a.compare(); + const two = await pushPaths(a.deps(), second, ["map.excalidraw.md"]); + expect(two.files["map.excalidraw.md"]?.hash).not.toBe( + one.files["map.excalidraw.md"]?.hash, + ); + + const pulled = await b.compare(); + await pullPaths(b.deps(), pulled, ["map.excalidraw.md"]); + expect(b.text("map.excalidraw.md")).toBe(edited); + }); +}); diff --git a/packages/plugin/tests/features/sync/content/store.test.ts b/packages/plugin/tests/features/sync/content/store.test.ts new file mode 100644 index 00000000..42fc160a --- /dev/null +++ b/packages/plugin/tests/features/sync/content/store.test.ts @@ -0,0 +1,224 @@ +import { + bytesOf, + compressedDrawing, + plainDrawing, +} from "@tests/helpers/drawing-file"; +import { FakeStorage } from "@tests/helpers/fake-storage"; +import { seeded } from "@tests/helpers/seeded"; +import { afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { + decryptDescribed, + deriveChunkIds, + deriveKey, + type EncryptionKey, + encryptCompressible, + sha256Hex, +} from "@/core/crypto"; +import { + CHUNK_THRESHOLD, + objectKey, + recipeKey, +} from "@/features/sync/content/keys"; +import { loadContent } from "@/features/sync/content/load"; +import { storeContent } from "@/features/sync/content/store"; + +let key: EncryptionKey; +let chunkIds: CryptoKey; +beforeAll(async () => { + key = await deriveKey("pw", new Uint8Array(16)); + chunkIds = await deriveChunkIds(new Uint8Array(32).fill(7)); +}); +afterEach(() => vi.unstubAllGlobals()); + +async function store(bytes: Uint8Array) { + const storage = new FakeStorage(); + const hash = await sha256Hex(bytes); + await storeContent({ storage, key }, hash, bytes); + const blob = storage.map.get(objectKey(hash)); + if (!blob) throw new Error("nothing stored"); + return { storage, hash, blob }; +} + +describe("storeContent", () => { + it("stores a compressed drawing described, and loads it back byte for byte", async () => { + const bytes = bytesOf(compressedDrawing()); + const { storage, hash, blob } = await store(bytes); + + expect(blob[0]).toBe(0x03); + const { header } = await decryptDescribed(key, blob); + expect(header).toEqual({ + codec: { name: "excalidraw-lz", width: 256, gap: "\n\n" }, + }); + expect(await loadContent({ storage, key }, hash)).toEqual(bytes); + }); + + it("stores a note as before", async () => { + const bytes = bytesOf("# note\n\n".repeat(900)); + const { storage, hash, blob } = await store(bytes); + + expect(blob[0]).toBe(0x02); + expect(blob.length).toBe((await encryptCompressible(key, bytes)).length); + expect(await loadContent({ storage, key }, hash)).toEqual(bytes); + + const small = await store(bytesOf("hi")); + expect(small.blob[0]).toBe(0x01); + expect( + await loadContent({ storage: small.storage, key }, small.hash), + ).toEqual(bytesOf("hi")); + }); + + it("stores a drawing with a plain scene as before", async () => { + const bytes = bytesOf(plainDrawing()); + const { storage, hash, blob } = await store(bytes); + expect(blob[0]).not.toBe(0x03); + expect(await loadContent({ storage, key }, hash)).toEqual(bytes); + }); + + it("stores binary content as before", async () => { + const bytes = new Uint8Array(5000).map((_, at) => (at * 7919) % 256); + const { storage, hash, blob } = await store(bytes); + expect(blob[0]).not.toBe(0x03); + expect(await loadContent({ storage, key }, hash)).toEqual(bytes); + }); + + it("stores a drawing whole when this device cannot compress", async () => { + vi.stubGlobal("CompressionStream", undefined); + const bytes = bytesOf(compressedDrawing()); + const { storage, hash, blob } = await store(bytes); + expect(blob[0]).toBe(0x01); + expect(await loadContent({ storage, key }, hash)).toEqual(bytes); + }); + + it("shrinks a drawing's sealed blob against storing its compressed block", async () => { + const bytes = bytesOf(compressedDrawing()); + const { blob } = await store(bytes); + const whole = await encryptCompressible(key, bytes); + expect(blob.length).toBeLessThan(whole.length); + }); +}); + +describe("storeContent, chunked", () => { + const SIZE = 600 * 1024; + + function random(size: number, seed = 1): Uint8Array { + const next = seeded(seed); + return new Uint8Array(size).map(() => Math.floor(next() * 256)); + } + + function edited(bytes: Uint8Array): Uint8Array { + const copy = bytes.slice(); + copy.set(bytesOf("an edit in the middle"), bytes.length / 2); + return copy; + } + + /** A storage holding what `from` holds, with no upload log of its own. */ + function copyOf(from: FakeStorage): FakeStorage { + const storage = new FakeStorage(); + for (const [at, blob] of from.map) storage.map.set(at, blob); + return storage; + } + + function chunkPuts(storage: FakeStorage): () => number { + const put = vi.spyOn(storage, "put"); + return () => + put.mock.calls.filter(([at]) => at.startsWith("chunks/")).length; + } + + it("stores a big file as a recipe written after its chunks, and loads it back", async () => { + const storage = new FakeStorage(); + const bytes = random(SIZE); + const hash = await sha256Hex(bytes); + const put = vi.spyOn(storage, "put"); + + await storeContent({ storage, key, chunkIds }, hash, bytes); + + expect(storage.map.has(objectKey(hash))).toBe(false); + expect(put.mock.calls.at(-1)?.[0]).toBe(recipeKey(hash)); + const chunks = (await storage.list("chunks/")).length; + expect(chunks).toBeGreaterThan(3); + expect(chunks).toBeLessThan(40); + expect(await loadContent({ storage, key }, hash, SIZE)).toEqual(bytes); + }); + + it("keeps a file below the threshold whole, and every file whole without a chunk key", async () => { + const storage = new FakeStorage(); + const small = random(CHUNK_THRESHOLD - 1); + const big = random(SIZE, 2); + await storeContent( + { storage, key, chunkIds }, + await sha256Hex(small), + small, + ); + await storeContent({ storage, key }, await sha256Hex(big), big); + expect(storage.map.has(objectKey(await sha256Hex(small)))).toBe(true); + expect(storage.map.has(objectKey(await sha256Hex(big)))).toBe(true); + expect(await storage.list("chunks/")).toEqual([]); + }); + + it("uploads only the chunks an edit changed, trusting those HEAD's recipe names", async () => { + const first = new FakeStorage(); + const v1 = random(SIZE); + const h1 = await sha256Hex(v1); + await storeContent({ storage: first, key, chunkIds }, h1, v1); + const all = (await first.list("chunks/")).length; + const v2 = edited(v1); + const h2 = await sha256Hex(v2); + + const trusting = copyOf(first); + const trusted = chunkPuts(trusting); + const exists = vi.spyOn(trusting, "exists"); + await storeContent({ storage: trusting, key, chunkIds }, h2, v2, { + hash: h1, + size: SIZE, + }); + expect(trusted()).toBeLessThanOrEqual(2); + expect(exists).not.toHaveBeenCalled(); + expect(await loadContent({ storage: trusting, key }, h2, SIZE)).toEqual(v2); + + // Not HEAD's, not uploaded here: GC may be sweeping it, so it goes up again. + const unvouched = copyOf(first); + const again = chunkPuts(unvouched); + await storeContent({ storage: unvouched, key, chunkIds }, h2, v2); + expect(again()).toBe(all); + }); + + it("skips a chunk this device uploaded once a probe finds it", async () => { + const storage = new FakeStorage(); + const v1 = random(SIZE); + await storeContent({ storage, key, chunkIds }, await sha256Hex(v1), v1); + const puts = chunkPuts(storage); + const v2 = edited(v1); + await storeContent({ storage, key, chunkIds }, await sha256Hex(v2), v2); + expect(puts()).toBeLessThanOrEqual(2); + }); + + it("chunks a big drawing's decoded scene", async () => { + const storage = new FakeStorage(); + const next = seeded(3); + const text = Array.from({ length: 400_000 }, () => + String.fromCharCode(97 + Math.floor(next() * 26)), + ).join(""); + const json = JSON.stringify({ type: "excalidraw", elements: [{ text }] }); + const bytes = bytesOf(compressedDrawing(json)); + expect(bytes.length).toBeGreaterThanOrEqual(CHUNK_THRESHOLD); + const hash = await sha256Hex(bytes); + + await storeContent({ storage, key, chunkIds }, hash, bytes); + + const recipe = storage.map.get(recipeKey(hash)); + if (!recipe) throw new Error("no recipe"); + const { header } = await decryptDescribed(key, recipe); + expect((header as { codec?: unknown }).codec).toBeDefined(); + expect(await loadContent({ storage, key }, hash)).toEqual(bytes); + }); + + it("stores a big file whole when this device cannot compress", async () => { + vi.stubGlobal("CompressionStream", undefined); + const storage = new FakeStorage(); + const bytes = random(SIZE); + const hash = await sha256Hex(bytes); + await storeContent({ storage, key, chunkIds }, hash, bytes); + expect(storage.map.has(objectKey(hash))).toBe(true); + expect(await storage.list("chunks/")).toEqual([]); + }); +}); diff --git a/packages/plugin/tests/sync/controller-unload.test.ts b/packages/plugin/tests/features/sync/controller-unload.test.ts similarity index 93% rename from packages/plugin/tests/sync/controller-unload.test.ts rename to packages/plugin/tests/features/sync/controller-unload.test.ts index 9cad220c..ffd5c3ca 100644 --- a/packages/plugin/tests/sync/controller-unload.test.ts +++ b/packages/plugin/tests/features/sync/controller-unload.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vitest"; -import type { CompareResult } from "@/sync/engine"; -import { SyncControllerRuntimeState } from "@/sync/runtime/controller-state"; -import { VAULT_SPACE } from "@/sync/space"; +import type { CompareResult } from "@/features/sync/engine"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; +import { SyncControllerRuntimeState } from "@/features/sync/runtime/controller-state"; describe("SyncControllerRuntimeState.publishProgress", () => { it("carries the ratio of a counted step and clears it with the text", () => { diff --git a/packages/plugin/tests/sync/device-scope-roundtrip.test.ts b/packages/plugin/tests/features/sync/device-scope-roundtrip.test.ts similarity index 96% rename from packages/plugin/tests/sync/device-scope-roundtrip.test.ts rename to packages/plugin/tests/features/sync/device-scope-roundtrip.test.ts index 18ec8c17..897372ea 100644 --- a/packages/plugin/tests/sync/device-scope-roundtrip.test.ts +++ b/packages/plugin/tests/features/sync/device-scope-roundtrip.test.ts @@ -8,10 +8,10 @@ import { import { RevalidatingStorage } from "@tests/helpers/revalidating-storage"; import { useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; -import { EConflictStrategy } from "@/sync/controller"; -import { pullPathsOp } from "@/sync/operations/pull"; -import { batchAcceptRemoteOp } from "@/sync/operations/resolve"; -import { EChangeType } from "@/sync/types"; +import { EConflictStrategy } from "@/features/sync/controller"; +import { pullPathsOp } from "@/features/sync/operations/pull"; +import { batchAcceptRemoteOp } from "@/features/sync/operations/resolve"; +import { EChangeType } from "@/features/sync/types"; useEncryptionKey(); diff --git a/packages/plugin/tests/sync/engine-roundtrip.test.ts b/packages/plugin/tests/features/sync/engine-roundtrip.test.ts similarity index 81% rename from packages/plugin/tests/sync/engine-roundtrip.test.ts rename to packages/plugin/tests/features/sync/engine-roundtrip.test.ts index b1a15655..8a69f23c 100644 --- a/packages/plugin/tests/sync/engine-roundtrip.test.ts +++ b/packages/plugin/tests/features/sync/engine-roundtrip.test.ts @@ -1,18 +1,23 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; import { TestSession, useEncryptionKey } from "@tests/helpers/session"; -import { beforeAll, describe, expect, it, vi } from "vitest"; -import { deriveKey, type EncryptionKey } from "@/crypto"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; -import { advanceSessionAfterPush } from "@/sync/baseline"; -import { REMOTE_MANIFEST_KEY, REMOTE_OBJECTS_PREFIX } from "@/sync/constants"; -import { compare, type EngineDependencies, pushPaths } from "@/sync/engine"; -import { readHistoryLog } from "@/sync/history/store"; -import { pullPaths } from "@/sync/pull"; -import { VAULT_SPACE } from "@/sync/space"; -import { EChangeType, type SessionState } from "@/sync/types"; -import { SETTLED_AFTER_MS } from "@/sync/uploads"; -import { createScopePolicy } from "@/vault/scope"; +import { beforeAll, describe, expect, it } from "vitest"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; +import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import { pullPaths } from "@/features/sync/apply/pull"; +import { REMOTE_OBJECTS_PREFIX } from "@/features/sync/constants"; +import { + compare, + type EngineDependencies, + pushPaths, +} from "@/features/sync/engine"; +import { pushKey, readHistory } from "@/features/sync/history/remote"; +import type { HistoryConfig } from "@/features/sync/history/types"; +import { advanceSessionAfterPush } from "@/features/sync/remote/baseline"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; +import { createScopePolicy } from "@/features/sync/scope/scope"; +import { EChangeType, type SessionState } from "@/features/sync/types"; let key: EncryptionKey; beforeAll(async () => { @@ -38,7 +43,7 @@ function deps( adapter: InMemoryAdapter, storage: FakeStorage, state: SessionState, - history?: { maxSnapshots: number }, + history?: HistoryConfig, ): EngineDependencies { return { space: VAULT_SPACE, @@ -214,35 +219,46 @@ describe("engine round-trip", () => { expect(cmpA.diff.conflicts.map((c) => c.path)).toEqual(["note.md"]); }); - it("history records every push and GC bounds the log", async () => { + it("history writes one push record per push, chained by parent", async () => { const storage = new FakeStorage(); const adapter = new InMemoryAdapter(); - const history = { maxSnapshots: 2 }; + const history: HistoryConfig = { horizon: null }; let state = freshState("A"); - // A day between pushes: GC evicts only records whose blobs have settled. - vi.useFakeTimers({ toFake: ["Date"] }); - try { - for (let i = 0; i < 14; i++) { - vi.setSystemTime(Date.now() + SETTLED_AFTER_MS + 1); - adapter.putText("note.md", `rev ${i}`); - const cmp = await compare(deps(adapter, storage, state, history)); - const m = await pushPaths(deps(adapter, storage, state, history), cmp, [ - "note.md", - ]); - state = advanceSessionAfterPush(state, cmp, m); - } - } finally { - vi.useRealTimers(); + const ids: string[] = []; + for (let i = 0; i < 14; i++) { + adapter.putText("note.md", `rev ${i}`); + const cmp = await compare(deps(adapter, storage, state, history)); + const m = await pushPaths(deps(adapter, storage, state, history), cmp, [ + "note.md", + ]); + ids.push(m.snapshotId); + state = advanceSessionAfterPush(state, cmp, m); } - const log = await readHistoryLog(storage, key, ""); - // buffer floor is 10 → GC fires once count exceeds max(2)+10, prunes to 2. - expect(log.snapshots.length).toBeLessThanOrEqual(12); - expect(log.snapshots.length).toBeGreaterThanOrEqual(2); - // Change records are pruned with their snapshots, never left dangling. - expect(Object.keys(log.changes).sort()).toEqual( - log.snapshots.map((s) => s.id).sort(), - ); + + const { view, unreadable } = await readHistory(storage, key, ""); + + expect(unreadable).toEqual([]); + expect([...view.pushes.keys()].sort()).toEqual(ids.map(pushKey).sort()); + for (const [index, id] of ids.entries()) { + expect(view.pushes.get(pushKey(id))?.push.parentId).toBe( + ids[index - 1] ?? null, + ); + } + const last = view.pushes.get(pushKey(ids[13] ?? ""))?.push; + expect(Object.keys(last?.changes.modified ?? {})).toEqual(["note.md"]); + }); + + it("writes no push record without a history config", async () => { + const storage = new FakeStorage(); + const adapter = new InMemoryAdapter(); + adapter.putText("note.md", "hello"); + const state = freshState("A"); + const cmp = await compare(deps(adapter, storage, state)); + await pushPaths(deps(adapter, storage, state), cmp, ["note.md"]); + + expect(await storage.list("history/")).toEqual([]); }); + it("probes no blob it has not uploaded itself", async () => { const adapter = new InMemoryAdapter(); const storage = new FakeStorage(); diff --git a/packages/plugin/tests/sync/file-diff-index.test.ts b/packages/plugin/tests/features/sync/file-diff-index.test.ts similarity index 95% rename from packages/plugin/tests/sync/file-diff-index.test.ts rename to packages/plugin/tests/features/sync/file-diff-index.test.ts index 20a57187..10a6f5fa 100644 --- a/packages/plugin/tests/sync/file-diff-index.test.ts +++ b/packages/plugin/tests/features/sync/file-diff-index.test.ts @@ -1,12 +1,12 @@ import { describe, expect, it } from "vitest"; -import type { CompareResult } from "@/sync/engine"; -import { FileDiffService } from "@/sync/runtime/file-diff-service"; +import type { CompareResult } from "@/features/sync/engine"; +import { FileDiffService } from "@/features/sync/runtime/file-diff-service"; import { type Conflict, type DiffResult, EChangeType, type FileChange, -} from "@/sync/types"; +} from "@/features/sync/types"; function change(path: string, type: EChangeType): FileChange { return { path, type, localHash: null, remoteHash: null }; diff --git a/packages/plugin/tests/features/sync/history/activity-cache.test.ts b/packages/plugin/tests/features/sync/history/activity-cache.test.ts new file mode 100644 index 00000000..554b0f35 --- /dev/null +++ b/packages/plugin/tests/features/sync/history/activity-cache.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from "vitest"; +import { ActivityCache } from "@/features/sync/history/activity-cache"; + +function cache(initial: unknown = null) { + let stored = initial; + return new ActivityCache({ + load: () => stored, + save: (value) => { + stored = value; + }, + }); +} + +describe("ActivityCache", () => { + it("recalls what it remembered for the same storage only", () => { + const activity = cache(); + activity.remember("s3:a", { 100: [3, 2] }, 5); + expect(activity.recall("s3:a")).toEqual({ + activity: { 100: [3, 2] }, + at: 5, + }); + expect(activity.recall("s3:b")).toBeNull(); + }); + + it("keeps a newer read over one begun before it", () => { + const activity = cache(); + activity.remember("s3:a", { 100: [2, 1] }, 20); + activity.remember("s3:a", { 100: [1, 1] }, 10); + expect(activity.recall("s3:a")?.activity).toEqual({ 100: [2, 1] }); + }); + + it("forgets until a read begun after it", () => { + const activity = cache(); + activity.remember("s3:a", { 100: [2, 1] }, 5); + activity.forget(); + expect(activity.recall("s3:a")).toBeNull(); + activity.remember("s3:a", { 100: [2, 1] }, 5); + expect(activity.recall("s3:a")).toBeNull(); + activity.remember("s3:a", { 100: [1, 1] }, Date.now() + 1); + expect(activity.recall("s3:a")?.activity).toEqual({ 100: [1, 1] }); + }); + + it("recalls nothing from a malformed entry", () => { + expect(cache("junk").recall("s3:a")).toBeNull(); + expect(cache({ storage: "s3:a", at: 1 }).recall("s3:a")).toBeNull(); + }); +}); diff --git a/packages/plugin/tests/features/sync/history/compose.test.ts b/packages/plugin/tests/features/sync/history/compose.test.ts new file mode 100644 index 00000000..1529afba --- /dev/null +++ b/packages/plugin/tests/features/sync/history/compose.test.ts @@ -0,0 +1,231 @@ +import { seeded } from "@tests/helpers/seeded"; +import { describe, expect, it } from "vitest"; +import { + changeEntries, + composeChanges, + diffManifests, + historyTracks, + splitTracked, + undoChanges, + untrackedDir, +} from "@/features/sync/history/changes"; +import type { SnapshotChanges } from "@/features/sync/history/types"; +import type { EFileKind, Manifest, ManifestEntry } from "@/features/sync/types"; + +function entry(hash: string, mtime = 1): ManifestEntry { + return { hash, size: hash.length, mtime, kind: "vault" as EFileKind }; +} + +function manifest(files: Record): Manifest { + return { + version: 1, + vaultId: "v", + snapshotId: "s", + parentSnapshotId: null, + createdAt: 1, + deviceId: "d", + files, + }; +} + +function changes(partial: Partial): SnapshotChanges { + return { added: {}, modified: {}, deleted: {}, ...partial }; +} + +const a = entry("a"); +const b = entry("b"); +const c = entry("c"); + +describe("composeChanges", () => { + it("keeps the last content of a file added in the run", () => { + const merged = composeChanges([ + changes({ added: { n: a } }), + changes({ modified: { n: { from: a, to: b } } }), + ]); + expect(merged).toEqual(changes({ added: { n: b } })); + }); + + it("leaves no trace of a file added and deleted in the run", () => { + const merged = composeChanges([ + changes({ added: { n: a } }), + changes({ deleted: { n: a } }), + ]); + expect(merged).toEqual(changes({})); + }); + + it("chains edits and drops a file edited back to where it started", () => { + expect( + composeChanges([ + changes({ modified: { n: { from: a, to: b } } }), + changes({ modified: { n: { from: b, to: c } } }), + ]), + ).toEqual(changes({ modified: { n: { from: a, to: c } } })); + expect( + composeChanges([ + changes({ modified: { n: { from: a, to: b } } }), + changes({ modified: { n: { from: b, to: a } } }), + ]), + ).toEqual(changes({})); + }); + + it("keeps the content right before a deletion apart from the parent's", () => { + const merged = composeChanges([ + changes({ modified: { n: { from: a, to: b } } }), + changes({ deleted: { n: b } }), + ]); + expect(merged).toEqual( + changes({ deleted: { n: a }, deletedLast: { n: b } }), + ); + }); + + it("turns a deletion and a new file at the path into an edit", () => { + const merged = composeChanges([ + changes({ deleted: { n: a }, deletedLast: { n: b } }), + changes({ added: { n: c } }), + ]); + expect(merged).toEqual(changes({ modified: { n: { from: a, to: c } } })); + }); + + it("reads a path named like an Object member as a path", () => { + const merged = composeChanges([ + changes({ added: { toString: a } }), + changes({ modified: { toString: { from: a, to: b } } }), + ]); + expect(merged).toEqual(changes({ added: { toString: b } })); + }); + + it("counts the content before a merged deletion as reachable", () => { + const merged = changes({ deleted: { n: a }, deletedLast: { n: b } }); + expect(changeEntries(merged).map((e) => e.hash)).toEqual(["a", "b"]); + }); +}); + +describe("splitTracked", () => { + const tracks = historyTracks(".obsidian"); + + it("keeps vault paths and releases every hash the config folder names, once", () => { + const split = splitTracked( + changes({ + added: { "n.md": a, ".obsidian/new.json": b }, + modified: { + "m.md": { from: a, to: b }, + ".obsidian/app.json": { from: b, to: c }, + }, + deleted: { "d.md": a, ".obsidian/old.json": c }, + }), + tracks, + ); + + expect(split.changes).toEqual( + changes({ + added: { "n.md": a }, + modified: { "m.md": { from: a, to: b } }, + deleted: { "d.md": a }, + }), + ); + // b is named twice and c twice on the untracked side, and a only by vault paths. + expect([...split.released].sort()).toEqual(["b", "c"]); + }); + + it("releases nothing when no path is left out", () => { + const all = changes({ added: { "n.md": a }, deleted: { "d.md": b } }); + expect(splitTracked(all, tracks)).toEqual({ changes: all, released: [] }); + }); +}); + +describe("historyTracks", () => { + it("tracks every path without a configuration folder", () => { + const tracks = historyTracks(undefined); + expect(tracks(".obsidian/app.json")).toBe(true); + expect(tracks("n.md")).toBe(true); + }); + + it("leaves out only what sits under the folder itself", () => { + const tracks = historyTracks(".obsidian"); + expect(tracks(".obsidian/plugins/x/main.js")).toBe(false); + expect(tracks(".obsidian-other/x")).toBe(true); + expect(tracks("notes/.obsidian/x")).toBe(true); + }); + + it("leaves out the folder in any casing, as a case-blind disk holds one", () => { + expect(historyTracks(".obsidian")(".Obsidian/app.json")).toBe(false); + }); + + it("leaves out only the vault's folder: a share's scope names it too", () => { + const scope = { configDir: ".obsidian" }; + expect(untrackedDir({ space: { root: "" }, scope })).toBe(".obsidian"); + expect(untrackedDir({ space: { root: "Shared" }, scope })).toBeUndefined(); + }); +}); + +/** Few paths and few contents, so files come and go and edits land back where they started. */ +function chain(seed: number, steps: number): Manifest[] { + const random = seeded(seed); + const pick = (items: readonly T[]): T => + items[Math.floor(random() * items.length)] as T; + const pool = ["x", "y", "z"].flatMap((hash) => [ + entry(hash, 1), + entry(hash, 2), + ]); + const paths = ["a.md", "b.md", "c.md", "d/e.md", "toString"]; + const manifests = [manifest({})]; + for (let step = 0; step < steps; step++) { + const files = { ...manifests.at(-1)?.files }; + for (const path of paths) { + const roll = random(); + if (roll < 0.2) delete files[path]; + else if (roll < 0.55) files[path] = pick(pool); + } + manifests.push(manifest(files)); + } + return manifests; +} + +describe("composeChanges over generated chains", () => { + it("replays a merged run to its first parent and forward to its end", () => { + for (let seed = 1; seed <= 60; seed++) { + const manifests = chain(seed, 12); + const random = seeded(seed * 7); + let start = 0; + while (start < manifests.length - 1) { + const end = Math.min( + manifests.length - 1, + start + 1 + Math.floor(random() * 5), + ); + const run = manifests + .slice(start + 1, end + 1) + .map((next, index) => + diffManifests(manifests[start + index] ?? null, next), + ); + const merged = composeChanges(run); + const from = manifests[start] as Manifest; + const to = manifests[end] as Manifest; + + const back = { ...to.files }; + undoChanges(back, merged); + expect(back).toEqual(from.files); + expect(diffManifests(from, to)).toEqual({ + added: merged.added, + modified: merged.modified, + deleted: merged.deleted, + }); + + for (const path of Object.keys(merged.deleted)) { + const lastSeen = manifests + .slice(start, end) + .reverse() + .find((m) => Object.hasOwn(m.files, path))?.files[path]; + const last = merged.deletedLast ?? {}; + expect( + Object.hasOwn(last, path) ? last[path] : merged.deleted[path], + ).toBe(lastSeen); + } + const named = new Set(run.flatMap(changeEntries)); + for (const version of changeEntries(merged)) { + expect(named.has(version)).toBe(true); + } + start = end; + } + } + }); +}); diff --git a/packages/plugin/tests/features/sync/history/gc.test.ts b/packages/plugin/tests/features/sync/history/gc.test.ts new file mode 100644 index 00000000..25f3f3be --- /dev/null +++ b/packages/plugin/tests/features/sync/history/gc.test.ts @@ -0,0 +1,342 @@ +import { FakeStorage } from "@tests/helpers/fake-storage"; +import { + manifestOf, + pinSnapshot, + writePushRecord, +} from "@tests/helpers/history"; +import { seeded } from "@tests/helpers/seeded"; +import { + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from "vitest"; +import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; +import { objectKey } from "@/features/sync/content/keys"; +import { collectHistoryGarbage } from "@/features/sync/history/gc"; +import { publishManifestWithHistory } from "@/features/sync/history/publish"; +import { + listSnapshots, + resolveSnapshotManifest, +} from "@/features/sync/history/query"; +import { readHistory } from "@/features/sync/history/remote"; +import { + deepCleanOrphans, + verifyRemote, +} from "@/features/sync/runtime/maintenance"; +import type { Manifest } from "@/features/sync/types"; + +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; +const START = Date.UTC(2026, 0, 5); + +let key: EncryptionKey; +beforeAll(async () => { + key = await deriveKey("pw", new Uint8Array(16)); +}); +beforeEach(() => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(START); +}); +afterEach(() => { + vi.useRealTimers(); +}); + +/** One device pushing through the real publish path; every hash it names is uploaded first. */ +class Device { + readonly published = new Map(); + head: Manifest | null = null; + private files: Record = {}; + private count = 0; + + constructor( + readonly storage: FakeStorage, + readonly history: { horizon: number | null }, + ) {} + + async push(edit: (files: Record) => void): Promise { + this.files = { ...this.files }; + edit(this.files); + for (const hash of Object.values(this.files)) { + if (!this.storage.map.has(objectKey(hash))) { + await this.storage.put(objectKey(hash), new Uint8Array([1])); + } + } + const id = `s${++this.count}`; + const manifest = manifestOf( + id, + this.head?.snapshotId ?? null, + this.files, + Date.now(), + ); + await publishManifestWithHistory( + this.storage, + key, + "", + manifest, + this.head, + this.history, + ); + this.head = manifest; + this.published.set(id, manifest); + } + + gc() { + return collectHistoryGarbage(this.storage, key, "", this.history); + } +} + +/** Every listed snapshot replays to exactly the files it published. */ +async function expectReplays(device: Device): Promise { + const source = { storage: device.storage, key, root: "" }; + const { snapshots } = await listSnapshots({ ...source, horizon: null }); + for (const { id, restorable } of snapshots) { + expect(restorable).toBe(true); + const replayed = await resolveSnapshotManifest(source, id); + expect(replayed?.files).toEqual(device.published.get(id)?.files); + } + return snapshots.map(({ id }) => id); +} + +async function pushEvery( + device: Device, + step: number, + count: number, + random = seeded(1), +): Promise { + for (let n = 0; n < count; n++) { + vi.setSystemTime(Date.now() + step); + await device.push((files) => { + const path = `note-${Math.floor(random() * 6)}.md`; + if (random() < 0.2) delete files[path]; + else files[path] = `h${n}`; + }); + } +} + +describe("collectHistoryGarbage", () => { + it("thins aged pushes, keeps every remaining snapshot replayable, and a rerun changes nothing", async () => { + const device = new Device(new FakeStorage(), { horizon: null }); + await pushEvery(device, 7 * MINUTE, 60); + const before = await expectReplays(device); + vi.setSystemTime(Date.now() + 2 * DAY); + await device.push((files) => { + files["last.md"] = "L"; + }); + + const run = await device.gc(); + expect(run.written).toBeGreaterThan(0); + expect(run.retired).toBeGreaterThan(0); + const after = await expectReplays(device); + expect(after.length).toBeLessThan(before.length + 1); + expect(after[0]).toBe(device.head?.snapshotId); + + expect(await device.gc()).toMatchObject({ + written: 0, + retired: 0, + swept: 0, + }); + }); + + it("reads the objects it wrote from the cache, with no GET", async () => { + const device = new Device(new FakeStorage(), { horizon: null }); + await pushEvery(device, 7 * MINUTE, 60); + vi.setSystemTime(Date.now() + 2 * DAY); + await device.push(() => {}); + const run = await device.gc(); + expect(run.written).toBeGreaterThan(0); + + const get = vi.spyOn(device.storage, "get"); + const { view, unreadable } = await readHistory(device.storage, key, ""); + expect(unreadable).toEqual([]); + expect(view.objects.size).toBe(run.written); + expect(get).not.toHaveBeenCalled(); + }); + + it("lists packed snapshots at their period, with every push still counted", async () => { + const device = new Device(new FakeStorage(), { horizon: null }); + await pushEvery(device, 7 * MINUTE, 60); + vi.setSystemTime(Date.now() + 2 * DAY); + await device.push(() => {}); + await device.gc(); + + const { snapshots, activity } = await listSnapshots({ + storage: device.storage, + key, + root: "", + horizon: null, + }); + expect(snapshots[0]?.res).toBe("push"); + expect(new Set(snapshots.map((s) => s.res))).toContain("1h"); + expect(snapshots.reduce((sum, s) => sum + s.pushes, 0)).toBe(61); + const counted = Object.values(activity).reduce((sum, [n]) => sum + n, 0); + expect(counted).toBe(61); + for (const s of snapshots) expect(s.firstAt).toBeLessThanOrEqual(s.at); + }); + + it("sweeps the versions it freed only two days later, and leaves nothing dangling", async () => { + const device = new Device(new FakeStorage(), { horizon: null }); + await pushEvery(device, 7 * MINUTE, 60); + vi.setSystemTime(Date.now() + 2 * DAY); + await device.push(() => {}); + const blobs = (): number => + [...device.storage.map.keys()].filter((k) => k.startsWith("objects/")) + .length; + + const uploaded = blobs(); + expect((await device.gc()).swept).toBe(0); + expect(blobs()).toBe(uploaded); + + vi.setSystemTime(Date.now() + DAY + MINUTE); + expect((await device.gc()).swept).toBe(0); + + vi.setSystemTime(Date.now() + DAY); + expect((await device.gc()).swept).toBeGreaterThan(0); + expect(blobs()).toBeLessThan(uploaded); + expect( + (await verifyRemote(device.storage, key, "", false)).missing, + ).toEqual([]); + await expectReplays(device); + expect(await device.storage.list("history/g/")).toEqual([]); + }); + + it("holds what it freed from a deep clean for a day, and from one that cannot read the record", async () => { + const device = new Device(new FakeStorage(), { horizon: null }); + await pushEvery(device, 7 * MINUTE, 60); + vi.setSystemTime(Date.now() + 2 * DAY); + await device.push(() => {}); + const blobs = (): number => + [...device.storage.map.keys()].filter((k) => k.startsWith("objects/")) + .length; + const uploaded = blobs(); + await device.gc(); + + expect( + (await deepCleanOrphans(device.storage, key, "")).deletedObjects, + ).toBe(0); + expect(blobs()).toBe(uploaded); + + const [file] = await device.storage.list("history/g/"); + const intact = device.storage.map.get(file as string) as Uint8Array; + device.storage.map.set(file as string, new Uint8Array([1])); + await expect(deepCleanOrphans(device.storage, key, "")).rejects.toThrow( + /could not be read/, + ); + device.storage.map.set(file as string, intact); + + vi.setSystemTime(Date.now() + DAY + MINUTE); + expect( + (await deepCleanOrphans(device.storage, key, "")).deletedObjects, + ).toBeGreaterThan(0); + expect(await device.storage.list("history/g/")).toEqual([]); + await expectReplays(device); + }); + + it("keeps a freed version a pin holds by the time it sweeps", async () => { + const device = new Device(new FakeStorage(), { horizon: null }); + await pushEvery(device, 7 * MINUTE, 60); + const old = device.published.get("s3") as Manifest; + vi.setSystemTime(Date.now() + 2 * DAY); + await device.push(() => {}); + await device.gc(); + + await pinSnapshot(device.storage, key, old); + vi.setSystemTime(Date.now() + DAY + MINUTE); + await device.gc(); + for (const { hash } of Object.values(old.files)) { + expect(await device.storage.exists(objectKey(hash))).toBe(true); + } + }); + + it("drops versions past the horizon to counts, and their blobs a day later", async () => { + const device = new Device(new FakeStorage(), { horizon: 7 * DAY }); + await pushEvery(device, 3 * HOUR, 40); + vi.setSystemTime(Date.now() + 70 * DAY); + await device.push(() => {}); + await device.gc(); + vi.setSystemTime(Date.now() + DAY + MINUTE); + await device.gc(); + + const snapshots = await expectReplays(device); + expect(snapshots.length).toBeLessThan(5); + expect( + (await verifyRemote(device.storage, key, "", false)).missing, + ).toEqual([]); + expect(device.storage.map.has(objectKey("h0"))).toBe(false); + }); + + it("stops before writing anything when a history object cannot be read", async () => { + const device = new Device(new FakeStorage(), { horizon: null }); + await pushEvery(device, 7 * MINUTE, 20); + vi.setSystemTime(Date.now() + 2 * DAY); + await device.push(() => {}); + await device.storage.put("history/b/push-0-bad.enc", new Uint8Array([1])); + const keys = [...device.storage.map.keys()].sort(); + + await expect(device.gc()).rejects.toThrow(/could not be read/); + expect([...device.storage.map.keys()].sort()).toEqual(keys); + }); + + it("retires a settled push that lost the guard and another vault's records", async () => { + const device = new Device(new FakeStorage(), { horizon: null }); + await pushEvery(device, MINUTE, 3); + const s1 = device.published.get("s1") as Manifest; + await writePushRecord( + device.storage, + key, + manifestOf("lost", "s1", { "x.md": "X" }), + s1, + ); + await writePushRecord( + device.storage, + key, + { ...manifestOf("old", null, {}), vaultId: "gone" }, + null, + ); + vi.setSystemTime(Date.now() + DAY + MINUTE); + await device.push(() => {}); + + await device.gc(); + expect(await device.storage.exists("history/p/lost.enc")).toBe(false); + expect(await device.storage.exists("history/p/old.enc")).toBe(false); + }); + + it("does nothing on a storage that cannot date its objects", async () => { + const device = new Device(new FakeStorage(), { horizon: null }); + await pushEvery(device, 7 * MINUTE, 20); + vi.setSystemTime(Date.now() + 2 * DAY); + Object.assign(device.storage, { listDetailed: undefined }); + + expect(await device.gc()).toEqual({ + written: 0, + retired: 0, + swept: 0, + activity: null, + }); + }); + + it("holds every promise over a seeded season of pushes and GC runs", async () => { + const random = seeded(7); + const device = new Device(new FakeStorage(), { horizon: 14 * DAY }); + for (let n = 0; n < 240; n++) { + vi.setSystemTime(Date.now() + Math.floor(random() * 6 * HOUR)); + await device.push((files) => { + const path = `note-${Math.floor(random() * 8)}.md`; + if (random() < 0.15) delete files[path]; + else files[path] = `h${n}`; + }); + if (random() < 0.5) await device.gc(); + } + vi.setSystemTime(Date.now() + DAY + MINUTE); + await device.gc(); + + await expectReplays(device); + expect( + (await verifyRemote(device.storage, key, "", false)).missing, + ).toEqual([]); + }); +}); diff --git a/packages/plugin/tests/features/sync/history/history-deleted.test.ts b/packages/plugin/tests/features/sync/history/history-deleted.test.ts new file mode 100644 index 00000000..82bc02d3 --- /dev/null +++ b/packages/plugin/tests/features/sync/history/history-deleted.test.ts @@ -0,0 +1,654 @@ +import { FakeStorage } from "@tests/helpers/fake-storage"; +import { + pinSnapshot, + seedChain, + writePushRecord, +} from "@tests/helpers/history"; +import { publishManifest } from "@tests/helpers/manifest"; +import { beforeAll, describe, expect, it, vi } from "vitest"; +import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; +import { keptUntil } from "@/features/sync/history/model/periods"; +import { pinKey } from "@/features/sync/history/pins"; +import { listDeletedFiles, listSnapshots } from "@/features/sync/history/query"; +import { pushKey } from "@/features/sync/history/remote"; +import { manifestToSpace } from "@/features/sync/remote/space-paths"; +import type { EFileKind, Manifest, ManifestEntry } from "@/features/sync/types"; + +const MINUTE = 60_000; +const HORIZON = 30 * 24 * 60 * MINUTE; +const NOW = Date.UTC(2026, 0, 14, 10); + +let key: EncryptionKey; +beforeAll(async () => { + key = await deriveKey("pw", new Uint8Array(16)); +}); + +function entry(hash: string, size = 1, mtime = 1): ManifestEntry { + return { hash, size, mtime, kind: "vault" as EFileKind }; +} + +function manifest( + snapshotId: string, + parentSnapshotId: string | null, + files: Record, + createdAt = 1, +): Manifest { + return { + version: 1, + vaultId: "v", + snapshotId, + parentSnapshotId, + createdAt, + deviceId: "d", + deviceName: "Device", + files, + }; +} + +async function seed( + chain: readonly Manifest[], + skip: readonly string[] = [], +): Promise { + const storage = new FakeStorage(); + await seedChain(storage, key, chain, skip); + return storage; +} + +/** Dates the push records as storage would, a minute apart in chain order. */ +function stamp(storage: FakeStorage, ids: readonly string[]): void { + for (const [index, id] of ids.entries()) { + storage.modified.set(pushKey(id), NOW + index * MINUTE); + } +} + +function deleted(storage: FakeStorage, horizon: number | null = null) { + return listDeletedFiles({ storage, key, root: "", horizon }); +} + +function snapshots(storage: FakeStorage, horizon: number | null = null) { + return listSnapshots({ storage, key, root: "", horizon }); +} + +describe("listDeletedFiles", () => { + it("reports a deleted file with the content it had when it went", async () => { + const storage = await seed([ + manifest("s1", null, { keep: entry("K1"), gone: entry("G1", 42) }, 100), + manifest("s2", "s1", { keep: entry("K1") }, 200), + ]); + + const result = await deleted(storage); + + expect(result.lagging).toBe(false); + expect(result.files).toHaveLength(1); + const [file] = result.files; + expect(file?.path).toBe("gone"); + expect(file?.entry).toEqual(entry("G1", 42)); + // The snapshot that removed it, not the one that last held it. + expect(file?.snapshotId).toBe("s2"); + expect(file?.createdAt).toBe(200); + expect(file?.source).toBe("deleted"); + expect(file?.pinned).toBe(false); + expect(file?.keptUntil).toBeNull(); + }); + + it("gives an unpinned deletion a retention deadline past its record", async () => { + const storage = await seed([ + manifest("s1", null, { gone: entry("G1") }, 100), + manifest("s2", "s1", {}, 200), + ]); + stamp(storage, ["s1", "s2"]); + + const [file] = (await deleted(storage, HORIZON)).files; + + expect(file?.pinned).toBe(false); + expect(file?.keptUntil).toBe(keptUntil(NOW + MINUTE, HORIZON)); + expect(file?.keptUntil).toBeGreaterThan(NOW + MINUTE + HORIZON); + }); + + it("omits a file that came back", async () => { + const storage = await seed([ + manifest("s1", null, { a: entry("A1") }, 100), + manifest("s2", "s1", {}, 200), + manifest("s3", "s2", { a: entry("A2") }, 300), + ]); + + expect((await deleted(storage)).files).toEqual([]); + }); + + it("reports the latest death of a recreated-then-deleted file", async () => { + const storage = await seed([ + manifest("a", null, { note: entry("V1") }, 100), + manifest("b", "a", {}, 200), + manifest("c", "b", { note: entry("V2") }, 300), + manifest("d", "c", {}, 400), + ]); + + const result = await deleted(storage); + expect(result.files).toHaveLength(1); + expect(result.files[0]?.snapshotId).toBe("d"); + expect(result.files[0]?.entry.hash).toBe("V2"); + }); + + it("never reports an older death of a file HEAD's missing record deleted again", async () => { + const storage = await seed( + [ + manifest("a", null, { note: entry("V1") }, 100), + manifest("b", "a", {}, 200), + manifest("c", "b", { note: entry("V2") }, 300), + manifest("d", "c", {}, 400), + ], + ["d"], + ); + + const result = await deleted(storage); + expect(result.lagging).toBe(true); + expect(result.files).toEqual([]); + }); + + it("orders by the chain, not by device clock", async () => { + // The newer snapshot carries the older timestamp. + const storage = await seed([ + manifest("s1", null, { old: entry("O1"), recent: entry("R1") }, 100), + manifest("s2", "s1", { recent: entry("R1") }, 9000), + manifest("s3", "s2", {}, 200), + ]); + + const result = await deleted(storage); + expect(result.files.map((f) => [f.path, f.snapshotId])).toEqual([ + ["recent", "s3"], + ["old", "s2"], + ]); + }); + + it("stops at a gap instead of attributing deletions to the wrong snapshot", async () => { + const storage = await seed( + [ + manifest("s1", null, { early: entry("E1"), late: entry("L1") }, 100), + manifest("s2", "s1", { early: entry("E1") }, 200), + manifest("s3", "s2", {}, 300), + ], + ["s2"], + ); + + const result = await deleted(storage); + expect(result.files.map((f) => f.path)).toEqual(["early"]); + expect(result.files[0]?.snapshotId).toBe("s3"); + }); + + it("flags a history that has not caught up with HEAD", async () => { + const storage = await seed( + [ + manifest("s1", null, { a: entry("A1") }, 100), + manifest("s2", "s1", {}, 200), + ], + ["s2"], + ); + + const result = await deleted(storage); + expect(result.lagging).toBe(true); + expect(result.truncated).toBe(false); + expect(result.files).toEqual([]); + }); + + it("reports a gap as truncated, not as a healthy empty trash", async () => { + const storage = await seed( + [ + manifest("s1", null, { a: entry("A1") }, 100), + manifest("s2", "s1", {}, 200), + manifest("s3", "s2", {}, 300), + ], + ["s2"], + ); + + const result = await deleted(storage); + expect(result.lagging).toBe(false); + expect(result.truncated).toBe(true); + expect(result.files).toEqual([]); + }); + + it("reads a corrupt push record as a gap, not as an empty history", async () => { + const storage = await seed([ + manifest("s1", null, { a: entry("A1"), b: entry("B1") }, 100), + manifest("s2", "s1", { b: entry("B1") }, 200), + manifest("s3", "s2", {}, 300), + ]); + await storage.put( + pushKey("s2"), + crypto.getRandomValues(new Uint8Array(64)), + ); + + const result = await deleted(storage); + expect(result.lagging).toBe(false); + expect(result.truncated).toBe(true); + // What s3 removed is still known; what s2 removed is not. + expect(result.files.map((f) => f.path)).toEqual(["b"]); + expect((await snapshots(storage)).snapshots.map((s) => s.id)).toEqual([ + "s3", + ]); + }); + + it("returns a share's deleted file in vault paths", async () => { + const root = "Shared/p"; + const first = manifest( + "s1", + null, + { + [`${root}/keep.md`]: entry("K1"), + [`${root}/gone.md`]: entry("G1", 42), + }, + 100, + ); + const second = manifest( + "s2", + "s1", + { [`${root}/keep.md`]: entry("K1") }, + 200, + ); + const storage = new FakeStorage(); + await writePushRecord(storage, key, first, null, root); + await writePushRecord(storage, key, second, first, root); + await publishManifest(storage, key, manifestToSpace(second, root)); + + const result = await listDeletedFiles({ + storage, + key, + root, + horizon: null, + }); + + expect(result.files.map((f) => [f.path, f.snapshotId])).toEqual([ + [`${root}/gone.md`, "s2"], + ]); + expect(result.files[0]?.entry).toEqual(entry("G1", 42)); + }); + + it("prefers the chain record over a pin describing the same file", async () => { + const chain = [ + manifest("s1", null, { ancient: entry("A1", 7) }, 100), + manifest("s2", "s1", {}, 200), + ]; + const storage = await seed(chain); + await pinSnapshot(storage, key, chain[0] as Manifest); + + const result = await deleted(storage); + // The chain records the deletion, so that record wins over the pin. + expect(result.files.map((f) => f.path)).toEqual(["ancient"]); + expect(result.files[0]?.source).toBe("deleted"); + expect(result.files[0]?.snapshotId).toBe("s2"); + }); + + it("falls back to the pin when no change record explains the loss", async () => { + const storage = await seed([ + manifest("s9", "s8", { kept: entry("K1") }, 900), + ]); + await pinSnapshot( + storage, + key, + manifest("old", null, { kept: entry("K0"), lost: entry("L1", 5) }, 100), + ); + + const result = await deleted(storage, HORIZON); + expect(result.truncated).toBe(true); + expect(result.files).toHaveLength(1); + expect(result.files[0]?.path).toBe("lost"); + expect(result.files[0]?.source).toBe("pinned"); + expect(result.files[0]?.pinned).toBe(true); + expect(result.files[0]?.keptUntil).toBeNull(); + }); + + it("lists a deleted file named like an Object member", async () => { + const storage = await seed([ + manifest("s1", null, { toString: entry("T1") }, 100), + manifest("s2", "s1", {}, 200), + ]); + + const result = await deleted(storage); + expect(result.files.map((f) => f.path)).toEqual(["toString"]); + }); + + it("clears retention only for what a pin holds", async () => { + const chain = [ + manifest("s1", null, { a: entry("A1"), b: entry("B1") }, 100), + manifest("s2", "s1", { a: entry("A1") }, 200), + manifest("s3", "s2", {}, 300), + ]; + const storage = await seed(chain); + await pinSnapshot(storage, key, chain[1] as Manifest); + + const result = await deleted(storage, HORIZON); + expect( + result.files.map((f) => [f.path, f.pinned, f.keptUntil !== null]), + ).toEqual([ + ["a", true, false], + ["b", false, true], + ]); + }); + + it("keeps the countdown when a pin holds another version of the file", async () => { + const chain = [ + manifest("p", null, { f: entry("F1") }, 100), + manifest("s2", "p", { f: entry("F2") }, 200), + manifest("s3", "s2", {}, 300), + ]; + const storage = await seed(chain); + stamp(storage, ["p", "s2", "s3"]); + await pinSnapshot(storage, key, chain[0] as Manifest); + + const result = await deleted(storage, HORIZON); + expect(result.files).toHaveLength(1); + expect(result.files[0]?.entry.hash).toBe("F2"); + expect(result.files[0]?.pinned).toBe(false); + expect(result.files[0]?.keptUntil).toBe( + keptUntil(NOW + 2 * MINUTE, HORIZON), + ); + }); + + it("drops the countdown when an older pin holds the same version", async () => { + const chain = [ + manifest("p", null, { doomed: entry("D1") }, 100), + manifest("s2", "p", { doomed: entry("D1") }, 200), + manifest("s3", "s2", {}, 300), + ]; + const storage = await seed(chain); + await pinSnapshot(storage, key, chain[0] as Manifest); + + const result = await deleted(storage, HORIZON); + expect(result.files).toHaveLength(1); + // The deletion is dated from the chain, but the pin means it never ages out. + expect(result.files[0]?.source).toBe("deleted"); + expect(result.files[0]?.createdAt).toBe(300); + expect(result.files[0]?.pinned).toBe(true); + expect(result.files[0]?.keptUntil).toBeNull(); + }); + + it("still reaches a pin sitting past a gap in the chain", async () => { + const chain = [ + manifest("p", null, { archived: entry("R1", 9) }, 100), + manifest("s2", "p", {}, 200), + manifest("s3", "s2", {}, 300), + ]; + const storage = await seed(chain, ["s2"]); + await pinSnapshot(storage, key, chain[0] as Manifest); + + const result = await deleted(storage); + expect(result.truncated).toBe(true); + expect(result.files.map((f) => f.path)).toEqual(["archived"]); + expect(result.files[0]?.source).toBe("pinned"); + }); + + it("lets the newest pin win however the pin reads finish", async () => { + const chain = [ + manifest("p1", null, { f: entry("F1") }, 100), + manifest("p2", "p1", { f: entry("F2"), g: entry("G2") }, 200), + manifest("p3", "p2", { f: entry("F3") }, 300), + manifest("s4", "p3", {}, 400), + ]; + // With no record for p3 or s4 the walk reaches nothing, so the pins alone explain the files. + const storage = await seed(chain, ["p3", "s4"]); + const delays: Record = { p1: 0, p2: 15, p3: 30 }; + for (const pinned of chain.slice(0, 3)) { + await pinSnapshot(storage, key, pinned); + } + const get = storage.get.bind(storage); + vi.spyOn(storage, "get").mockImplementation(async (path) => { + const id = Object.keys(delays).find((pin) => path === pinKey(pin)); + if (id) await new Promise((r) => setTimeout(r, delays[id])); + return get(path); + }); + + const result = await deleted(storage); + const byPath = Object.fromEntries( + result.files.map((file) => [file.path, file]), + ); + expect(byPath.f?.snapshotId).toBe("p3"); + expect(byPath.f?.entry.hash).toBe("F3"); + expect(byPath.g?.snapshotId).toBe("p2"); + expect(result.files.every((file) => file.pinned)).toBe(true); + }); + + it("keeps rows, order and marks when several pins share absent paths", async () => { + const chain = [ + manifest( + "w1", + null, + { k: entry("K1"), walked: entry("W1"), other: entry("O1") }, + 100, + ), + manifest("w2", "w1", { k: entry("K1") }, 200), + ]; + const storage = await seed(chain); + // Newest first: p2 (500), then the 400 tie in read order (p4 is read before p3), then p1 (300). + const pins = [ + manifest( + "p1", + null, + { + k: entry("K1"), + early: entry("E1"), + shared: entry("S1"), + walked: entry("W1"), + other: entry("O0"), + }, + 300, + ), + manifest( + "p2", + null, + { shared: entry("S2"), walked: entry("W2"), solo: entry("X2") }, + 500, + ), + manifest( + "p3", + null, + { shared: entry("S3"), tied: entry("T3"), mid: entry("M3") }, + 400, + ), + manifest("p4", null, { tied: entry("T4"), shared: entry("S4") }, 400), + ]; + const delays: Record = { p1: 40, p2: 0, p3: 25, p4: 5 }; + for (const pinned of pins) await pinSnapshot(storage, key, pinned); + const get = storage.get.bind(storage); + vi.spyOn(storage, "get").mockImplementation(async (path) => { + const id = Object.keys(delays).find((pin) => path === pinKey(pin)); + if (id) await new Promise((r) => setTimeout(r, delays[id])); + return get(path); + }); + + const result = await deleted(storage, HORIZON); + expect( + result.files.map((file) => [ + file.path, + file.source, + file.snapshotId, + file.entry.hash, + file.pinned, + file.keptUntil !== null, + ]), + ).toEqual([ + // The walk's rows come first; a pin marks one only for the hash it holds. + ["walked", "deleted", "w2", "W1", true, false], + ["other", "deleted", "w2", "O1", false, true], + ["shared", "pinned", "p2", "S2", true, false], + ["solo", "pinned", "p2", "X2", true, false], + ["tied", "pinned", "p4", "T4", true, false], + ["mid", "pinned", "p3", "M3", true, false], + ["early", "pinned", "p1", "E1", true, false], + ]); + }); + + it("returns nothing when no vault is published", async () => { + const storage = new FakeStorage(); + const result = await deleted(storage); + expect(result).toEqual({ files: [], lagging: false, truncated: false }); + }); +}); + +describe("listSnapshots", () => { + it("surfaces full before/after manifest metadata per file", async () => { + const storage = await seed([ + manifest("s1", null, { a: entry("A1", 10), b: entry("B1", 20) }, 100), + manifest("s2", "s1", { a: entry("A2", 15), c: entry("C1", 5) }, 200), + ]); + + const result = await snapshots(storage); + expect(result.lagging).toBe(false); + expect(result.snapshots.map((s) => s.id)).toEqual(["s2", "s1"]); + expect(result.snapshots.map((s) => s.keptUntil)).toEqual([null, null]); + + expect(result.snapshots[0]?.files).toEqual({ + added: { c: entry("C1", 5) }, + modified: { a: { from: entry("A1", 10), to: entry("A2", 15) } }, + deleted: { b: entry("B1", 20) }, + }); + expect(result.snapshots[1]?.files?.added).toEqual({ + a: entry("A1", 10), + b: entry("B1", 20), + }); + }); + + it("gives each unpinned snapshot a deadline past its record and a pinned one none", async () => { + const chain = [ + manifest("s1", null, { a: entry("A1") }, 100), + manifest("s2", "s1", { a: entry("A2") }, 200), + manifest("s3", "s2", { a: entry("A3") }, 300), + ]; + const storage = await seed(chain); + stamp(storage, ["s1", "s2", "s3"]); + await pinSnapshot(storage, key, chain[1] as Manifest); + + const { snapshots: rows } = await snapshots(storage, HORIZON); + const byId = Object.fromEntries(rows.map((row) => [row.id, row])); + expect(byId.s1?.keptUntil).toBeGreaterThan(NOW + HORIZON); + expect(byId.s3?.keptUntil).toBeGreaterThan(NOW + 2 * MINUTE + HORIZON); + expect(byId.s3?.keptUntil).toBe(keptUntil(NOW + 2 * MINUTE, HORIZON)); + expect(byId.s2?.pinned).toBe(true); + expect(byId.s2?.keptUntil).toBeNull(); + }); + + it("dates each snapshot by storage and counts its pushes per hour", async () => { + const storage = await seed([ + manifest("s1", null, { a: entry("A1") }, 100), + manifest("s2", "s1", { a: entry("A2") }, 200), + ]); + stamp(storage, ["s1", "s2"]); + + const result = await snapshots(storage); + expect( + result.snapshots.map((s) => [s.id, s.at, s.firstAt, s.pushes, s.res]), + ).toEqual([ + ["s2", NOW + MINUTE, NOW + MINUTE, 1, "push"], + ["s1", NOW, NOW, 1, "push"], + ]); + const pushes = Object.values(result.activity).reduce( + (sum, [count]) => sum + count, + 0, + ); + expect(pushes).toBe(2); + expect(result.truncated).toBe(false); + }); + + it("lists only what the walk reaches past a gap, and a pin beyond it without its changes", async () => { + const chain = [ + manifest("s1", null, { a: entry("A1") }, 100), + manifest("s2", "s1", { a: entry("A2") }, 200), + manifest("s3", "s2", { a: entry("A3") }, 300), + ]; + const storage = await seed(chain, ["s2"]); + + const walked = await snapshots(storage); + expect(walked.truncated).toBe(true); + expect(walked.snapshots.map((s) => [s.id, s.restorable])).toEqual([ + ["s3", true], + ]); + + await pinSnapshot(storage, key, chain[0] as Manifest, "first"); + const { snapshots: rows } = await snapshots(storage, HORIZON); + expect( + rows.map((s) => [s.id, s.restorable, s.files !== null, s.keptUntil]), + ).toEqual([ + ["s3", true, true, expect.any(Number)], + ["s1", true, false, null], + ]); + expect(rows[1]?.pinned).toBe(true); + expect(rows[1]?.label).toBe("first"); + // Off the walk only its device's clock dates it. + expect([rows[1]?.at, rows[1]?.pushes, rows[1]?.res]).toEqual([ + 100, + 1, + null, + ]); + }); + + it("marks nothing restorable by replay while HEAD's record is missing", async () => { + const storage = await seed( + [ + manifest("s1", null, { a: entry("A1") }, 100), + manifest("s2", "s1", { a: entry("A2") }, 200), + manifest("s3", "s2", { a: entry("A3") }, 300), + ], + ["s3"], + ); + + const result = await snapshots(storage); + expect(result.lagging).toBe(true); + expect( + result.snapshots.map((s) => [s.id, s.restorable, s.files !== null]), + ).toEqual([ + ["s2", false, true], + ["s1", false, true], + ]); + }); + + it("counts a pin as restorable even when replay cannot start at HEAD", async () => { + const chain = [ + manifest("s1", null, { a: entry("A1") }, 100), + manifest("s2", "s1", { a: entry("A2") }, 200), + ]; + const storage = await seed(chain, ["s2"]); + await pinSnapshot(storage, key, chain[0] as Manifest); + + const result = await snapshots(storage, HORIZON); + const pinned = result.snapshots.find((s) => s.id === "s1"); + expect(pinned?.pinned).toBe(true); + // Its stored manifest needs no replay. + expect(pinned?.restorable).toBe(true); + expect(pinned?.keptUntil).toBeNull(); + }); + + it("flags a history that has not caught up with HEAD", async () => { + const storage = await seed( + [ + manifest("s1", null, { a: entry("A1") }, 100), + manifest("s2", "s1", {}, 200), + ], + ["s2"], + ); + + expect((await snapshots(storage)).lagging).toBe(true); + }); + + it("marks isHead from actual remote HEAD snapshotId", async () => { + const storage = await seed([ + manifest("s1", null, { a: entry("A1") }, 100), + manifest("s2", "s1", { a: entry("A2") }, 200), + ]); + + const result = await snapshots(storage); + expect(result.snapshots[0]?.id).toBe("s2"); + expect(result.snapshots[0]?.isHead).toBe(true); + expect(result.snapshots[1]?.isHead).toBe(false); + }); + + it("no entry is HEAD while HEAD's record is missing", async () => { + const storage = await seed( + [ + manifest("s1", null, { a: entry("A1") }, 100), + manifest("s2", "s1", {}, 200), + ], + ["s2"], + ); + + const result = await snapshots(storage); + expect(result.snapshots.every((s) => !s.isHead)).toBe(true); + }); +}); diff --git a/packages/plugin/tests/features/sync/history/history-query.test.ts b/packages/plugin/tests/features/sync/history/history-query.test.ts new file mode 100644 index 00000000..5890cd20 --- /dev/null +++ b/packages/plugin/tests/features/sync/history/history-query.test.ts @@ -0,0 +1,462 @@ +import { FakeStorage } from "@tests/helpers/fake-storage"; +import { pinSnapshot, seedChain } from "@tests/helpers/history"; +import { beforeAll, describe, expect, it } from "vitest"; +import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; +import { diffManifests, undoChanges } from "@/features/sync/history/changes"; +import { + mergeRecords, + storedRecord, +} from "@/features/sync/history/model/records"; +import { getFileHistory, readTimeline } from "@/features/sync/history/query"; +import { + pushKey, + readHistory, + writeHistoryObject, +} from "@/features/sync/history/remote"; +import { replayTo } from "@/features/sync/history/replay"; +import type { EFileKind, Manifest, ManifestEntry } from "@/features/sync/types"; + +let key: EncryptionKey; +beforeAll(async () => { + key = await deriveKey("pw", new Uint8Array(16)); +}); + +function entry(hash: string, size = 1, mtime = 1): ManifestEntry { + return { hash, size, mtime, kind: "vault" as EFileKind }; +} + +function manifest( + snapshotId: string, + parentSnapshotId: string | null, + files: Record, + createdAt = 1, +): Manifest { + return { + version: 1, + vaultId: "v", + snapshotId, + parentSnapshotId, + createdAt, + deviceId: "d", + deviceName: "Device", + files, + }; +} + +/** Deterministic chain: each step adds, edits and deletes a few paths. */ +function generateChain(steps: number): Manifest[] { + let seed = 42; + const random = (): number => { + seed = (seed * 1103515245 + 12345) % 2147483648; + return seed / 2147483648; + }; + const chain: Manifest[] = []; + let files: Record = {}; + let parent: string | null = null; + for (let step = 0; step < steps; step++) { + files = { ...files }; + for (let n = 0; n < 3; n++) { + files[`note-${step}-${n}.md`] = entry(`h${step}-${n}`, step + n, step); + } + const paths = Object.keys(files); + for (let n = 0; n < 2 && paths.length > 0; n++) { + const victim = paths[Math.floor(random() * paths.length)]; + if (!victim) continue; + if (random() < 0.5) { + delete files[victim]; + } else { + files[victim] = entry(`edit${step}-${n}`, step + 10, step + 1); + } + } + const id = `s${step}`; + chain.push(manifest(id, parent, files, step + 1)); + parent = id; + } + return chain; +} + +async function seed( + chain: readonly Manifest[], + skip: readonly string[] = [], +): Promise { + const storage = new FakeStorage(); + await seedChain(storage, key, chain, skip); + return storage; +} + +function historyOf(storage: FakeStorage, path: string) { + return getFileHistory({ storage, key, root: "", path }); +} + +describe("diffManifests / undoChanges", () => { + it("classifies added, modified and deleted", () => { + const parent = manifest("s1", null, { a: entry("A1"), gone: entry("G1") }); + const next = manifest("s2", "s1", { a: entry("A2"), fresh: entry("F1") }); + const changes = diffManifests(parent, next); + + expect(Object.keys(changes.added)).toEqual(["fresh"]); + expect(changes.modified.a).toEqual({ from: entry("A1"), to: entry("A2") }); + expect(changes.deleted.gone).toEqual(entry("G1")); + }); + + it("treats a null parent as everything added", () => { + const changes = diffManifests( + null, + manifest("s1", null, { a: entry("A1") }), + ); + expect(Object.keys(changes.added)).toEqual(["a"]); + expect(changes.deleted).toEqual({}); + }); + + it("records a metadata-only change so the parent stays reproducible", () => { + const parent = manifest("s1", null, { a: entry("A1", 1, 100) }); + const next = manifest("s2", "s1", { a: entry("A1", 1, 200) }); + const changes = diffManifests(parent, next); + expect(changes.modified.a?.from.mtime).toBe(100); + const files = { ...next.files }; + undoChanges(files, changes); + expect(files).toEqual(parent.files); + }); + + it("classifies a file named like an Object member as added, not modified", () => { + // Plain index access would return Object.prototype.toString here. + const next = manifest("s1", null, { toString: entry("T1") }); + const changes = diffManifests(manifest("s0", null, {}), next); + expect(Object.keys(changes.added)).toEqual(["toString"]); + expect(changes.modified).toEqual({}); + }); + + it("undo is the exact inverse across a generated chain", () => { + const chain = generateChain(25); + for (let index = 1; index < chain.length; index++) { + const parent = chain[index - 1] as Manifest; + const current = chain[index] as Manifest; + const changes = diffManifests(parent, current); + const files = { ...current.files }; + undoChanges(files, changes); + expect(files).toEqual(parent.files); + } + }); +}); + +describe("readTimeline", () => { + it("reads no head and an empty walk from an empty remote", async () => { + const { head, cover } = await readTimeline({ + storage: new FakeStorage(), + key, + root: "", + }); + expect(head).toBeNull(); + expect(cover).toMatchObject({ + chain: [], + lagging: false, + truncated: false, + }); + }); + + it("walks HEAD back to the first push", async () => { + const storage = await seed(generateChain(4)); + + const { head, cover } = await readTimeline({ storage, key, root: "" }); + expect(head?.snapshotId).toBe("s3"); + expect(cover.chain.map(({ record }) => record.id)).toEqual([ + "s3", + "s2", + "s1", + "s0", + ]); + expect(cover).toMatchObject({ lagging: false, truncated: false }); + }); + + it("is lagging, not truncated, while HEAD has no record", async () => { + const storage = await seed(generateChain(3), ["s2"]); + + const { cover } = await readTimeline({ storage, key, root: "" }); + expect(cover.chain.map(({ record }) => record.id)).toEqual(["s1", "s0"]); + expect(cover).toMatchObject({ lagging: true, truncated: false }); + }); + + it("is truncated at a record that is missing", async () => { + const storage = await seed(generateChain(4), ["s1"]); + + const { cover } = await readTimeline({ storage, key, root: "" }); + expect(cover.chain.map(({ record }) => record.id)).toEqual(["s3", "s2"]); + expect(cover).toMatchObject({ lagging: false, truncated: true }); + }); + + it("reads a corrupt record as a gap, never as an empty history", async () => { + const storage = await seed(generateChain(4)); + await storage.put( + pushKey("s2"), + crypto.getRandomValues(new Uint8Array(64)), + ); + + const { cover } = await readTimeline({ storage, key, root: "" }); + expect(cover.chain.map(({ record }) => record.id)).toEqual(["s3"]); + expect(cover).toMatchObject({ lagging: false, truncated: true }); + }); +}); + +describe("replayTo", () => { + async function replay( + storage: FakeStorage, + snapshotId: string, + ): Promise { + const { head, cover } = await readTimeline({ storage, key, root: "" }); + if (!head) throw new Error("no head"); + return replayTo(head, cover, snapshotId); + } + + it("reproduces every manifest in the chain", async () => { + const chain = generateChain(20); + const storage = await seed(chain); + const { head, cover } = await readTimeline({ storage, key, root: "" }); + if (!head) throw new Error("no head"); + for (const target of chain) { + const replayed = replayTo(head, cover, target.snapshotId); + expect(replayed?.files).toEqual(target.files); + expect(replayed?.snapshotId).toBe(target.snapshotId); + expect(replayed?.createdAt).toBe(target.createdAt); + } + }); + + it("does not hand back HEAD's own file map", async () => { + const chain = generateChain(3); + const storage = await seed(chain); + const { head, cover } = await readTimeline({ storage, key, root: "" }); + if (!head) throw new Error("no head"); + const replayed = replayTo(head, cover, head.snapshotId); + expect(replayed?.files).toEqual(head.files); + expect(replayed?.files).not.toBe(head.files); + }); + + it("refuses while HEAD has no record", async () => { + const storage = await seed(generateChain(4), ["s3"]); + expect(await replay(storage, "s0")).toBeNull(); + }); + + it("refuses to replay past a gap", async () => { + const storage = await seed(generateChain(5), ["s2"]); + expect(await replay(storage, "s3")).not.toBeNull(); + expect(await replay(storage, "s1")).toBeNull(); + }); + + it("refuses a snapshot the walk never reaches", async () => { + const storage = await seed(generateChain(3)); + expect(await replay(storage, "elsewhere")).toBeNull(); + }); +}); + +describe("getFileHistory", () => { + it("returns distinct versions newest first and skips unchanged pushes", async () => { + const storage = await seed([ + manifest("s1", null, { "a.md": entry("A1") }, 100), + manifest("s2", "s1", { "a.md": entry("A1") }, 200), + manifest("s3", "s2", { "a.md": entry("A2") }, 300), + ]); + + const versions = await historyOf(storage, "a.md"); + expect(versions.map((v) => v.hash)).toEqual(["A2", "A1"]); + // Each version is dated by the push that wrote it. + expect(versions.map((v) => v.snapshotId)).toEqual(["s3", "s1"]); + expect(versions.map((v) => v.createdAt)).toEqual([300, 100]); + }); + + it("marks a version pinned by the pin that holds its content", async () => { + const chain = [ + manifest("s1", null, { "a.md": entry("A1") }, 100), + manifest("s2", "s1", { "a.md": entry("A2") }, 200), + manifest("s3", "s2", { "a.md": entry("A2"), "b.md": entry("B1") }, 300), + ]; + const storage = await seed(chain); + await pinSnapshot(storage, key, chain[2] as Manifest, "release"); + + const versions = await historyOf(storage, "a.md"); + // Unpin and rename must reach s3's pin, not the s2 that wrote A2. + expect(versions.map((v) => [v.snapshotId, v.pinId, v.label])).toEqual([ + ["s2", "s3", "release"], + ["s1", null, undefined], + ]); + }); + + it("marks the version that created the file, in each of its lifetimes", async () => { + const storage = await seed([ + manifest("s1", null, { "a.md": entry("A1") }, 100), + manifest("s2", "s1", { "a.md": entry("A2") }, 200), + manifest("s3", "s2", {}, 300), + manifest("s4", "s3", { "a.md": entry("A3") }, 400), + ]); + + const versions = await historyOf(storage, "a.md"); + expect(versions.map((v) => [v.hash, v.first])).toEqual([ + ["A3", true], + ["A2", false], + ["A1", true], + ]); + expect(versions.map((v) => [v.res, v.pushes])).toEqual([ + ["push", 1], + ["push", 1], + ["push", 1], + ]); + }); + + it("lists the content a merged period held right before it deleted the file", async () => { + const storage = await seed([ + manifest("s1", null, { "a.md": entry("A1") }, 100), + manifest("s2", "s1", { "a.md": entry("A2") }, 200), + manifest("s3", "s2", {}, 300), + ]); + const { view } = await readHistory(storage, key, ""); + const merged = mergeRecords( + ["s2", "s3"].map((id) => { + const read = view.pushes.get(pushKey(id)); + if (!read) throw new Error(`No record ${id}`); + return storedRecord(read.push, read.at); + }), + ); + await writeHistoryObject(storage, key, "", { + vaultId: "v", + res: "1h", + group: 0, + records: [merged], + consumed: [pushKey("s2"), pushKey("s3")], + }); + for (const id of ["s2", "s3"]) await storage.delete(pushKey(id)); + + const versions = await historyOf(storage, "a.md"); + expect(versions.map((v) => [v.hash, v.snapshotId, v.replayable])).toEqual([ + ["A2", "s3", false], + ["A1", "s1", true], + ]); + }); + + it("returns nothing for a path in the configuration folder", async () => { + const storage = await seed([ + manifest("s1", null, { + ".obsidian/app.json": entry("J1"), + "a.md": entry("A1"), + }), + ]); + const query = { storage, key, root: "", configDir: ".obsidian" }; + + expect( + await getFileHistory({ ...query, path: ".obsidian/app.json" }), + ).toEqual([]); + expect(await getFileHistory({ ...query, path: "a.md" })).toHaveLength(1); + }); + + it("returns nothing for a path the history never saw", async () => { + const storage = await seed([manifest("s1", null, { "a.md": entry("A1") })]); + expect(await historyOf(storage, "b.md")).toEqual([]); + }); + + it("returns nothing when no vault is published", async () => { + expect(await historyOf(new FakeStorage(), "a.md")).toEqual([]); + }); + + it("still finds a file that was deleted", async () => { + const storage = await seed([ + manifest("s1", null, { "gone.md": entry("G1") }, 100), + manifest("s2", "s1", { "gone.md": entry("G2") }, 200), + manifest("s3", "s2", {}, 300), + ]); + + const versions = await historyOf(storage, "gone.md"); + expect(versions.map((v) => v.hash)).toEqual(["G2", "G1"]); + }); + + it("separates a recreated file from its earlier life", async () => { + const storage = await seed([ + manifest("s1", null, { "a.md": entry("A1") }, 100), + manifest("s2", "s1", {}, 200), + manifest("s3", "s2", { "a.md": entry("A1") }, 300), + ]); + + const versions = await historyOf(storage, "a.md"); + // Same content, but two distinct lifetimes - neither may swallow the other. + expect(versions.map((v) => v.snapshotId)).toEqual(["s3", "s1"]); + }); + + it("orders by the chain, not by device clocks", async () => { + // s2 is the child of s1 but carries an earlier timestamp, as a device with + // a lagging clock would produce. + const storage = await seed([ + manifest("s1", null, { "a.md": entry("A1") }, 5000), + manifest("s2", "s1", { "a.md": entry("A2") }, 1000), + ]); + + const versions = await historyOf(storage, "a.md"); + expect(versions.map((v) => v.hash)).toEqual(["A2", "A1"]); + }); + + it("marks and names a version whose snapshot is pinned", async () => { + const chain = [ + manifest("s1", null, { "a.md": entry("A1") }, 100), + manifest("s2", "s1", { "a.md": entry("A2") }, 200), + manifest("s3", "s2", { "a.md": entry("A3") }, 300), + ]; + const storage = await seed(chain); + await pinSnapshot(storage, key, chain[1] as Manifest, "keeper"); + + const versions = await historyOf(storage, "a.md"); + expect(versions.map((v) => [v.hash, v.pinId, v.label])).toEqual([ + ["A3", null, undefined], + ["A2", "s2", "keeper"], + ["A1", null, undefined], + ]); + }); + + it("surfaces a pin sitting past a missing record", async () => { + const chain = [ + manifest("s1", null, { "a.md": entry("A1") }, 100), + manifest("s2", "s1", { "a.md": entry("A2") }, 200), + manifest("s3", "s2", { "a.md": entry("A3") }, 300), + ]; + // s2's record is lost, so the walk stops there and must not claim to have + // covered s1: only its pin reaches it. + const storage = await seed(chain, ["s2"]); + await pinSnapshot(storage, key, chain[0] as Manifest); + + const versions = await historyOf(storage, "a.md"); + // A2 is s3's parent state, known only to precede s3, so it is dated there; replay cannot rebuild s2. + expect( + versions.map((v) => [v.hash, v.snapshotId, v.pinId, v.replayable]), + ).toEqual([ + ["A3", "s3", null, true], + ["A2", "s2", null, false], + ["A1", "s1", "s1", false], + ]); + expect(versions[1]?.at).toBe(versions[0]?.firstAt); + }); + + it("keeps to what a corrupt record leaves reachable", async () => { + const chain = [ + manifest("s1", null, { "a.md": entry("A1") }, 100), + manifest("s2", "s1", { "a.md": entry("A2") }, 200), + manifest("s3", "s2", { "a.md": entry("A3") }, 300), + ]; + const storage = await seed(chain); + await storage.put( + pushKey("s2"), + crypto.getRandomValues(new Uint8Array(64)), + ); + + // s3's record still names A2; nothing older is known. + const versions = await historyOf(storage, "a.md"); + expect(versions.map((v) => v.hash)).toEqual(["A3", "A2"]); + }); + + it("serves the current version while HEAD has no record", async () => { + const storage = await seed( + [ + manifest("s1", null, { "a.md": entry("A1") }, 100), + manifest("s2", "s1", { "a.md": entry("A2") }, 200), + ], + ["s2"], + ); + + const versions = await historyOf(storage, "a.md"); + expect(versions.map((v) => v.hash)).toEqual(["A2"]); + expect(versions[0]?.snapshotId).toBe("s2"); + }); +}); diff --git a/packages/plugin/tests/features/sync/history/legacy.test.ts b/packages/plugin/tests/features/sync/history/legacy.test.ts new file mode 100644 index 00000000..64271768 --- /dev/null +++ b/packages/plugin/tests/features/sync/history/legacy.test.ts @@ -0,0 +1,67 @@ +import { FakeStorage } from "@tests/helpers/fake-storage"; +import { manifestOf, pinSnapshot } from "@tests/helpers/history"; +import { beforeAll, describe, expect, it, vi } from "vitest"; +import { + deriveKey, + type EncryptionKey, + encryptJson, +} from "@/core/crypto/cipher"; +import { REMOTE_HISTORY_LOG_KEY } from "@/features/sync/constants"; +import { clearLegacyHistory } from "@/features/sync/history/legacy"; +import { pinKey } from "@/features/sync/history/pins"; + +let key: EncryptionKey; +let otherKey: EncryptionKey; +beforeAll(async () => { + key = await deriveKey("pw", new Uint8Array(16)); + otherKey = await deriveKey("other", new Uint8Array(16)); +}); + +async function legacyPin(storage: FakeStorage, id: string): Promise { + await storage.put( + pinKey(id), + await encryptJson(key, manifestOf(id, null, { "a.md": "A" })), + ); +} + +describe("clearLegacyHistory", () => { + it("deletes the 1.x log and its bare-manifest pins, keeping current and undecryptable pins", async () => { + const storage = new FakeStorage(); + await storage.put(REMOTE_HISTORY_LOG_KEY, await encryptJson(key, {})); + await legacyPin(storage, "old1"); + await legacyPin(storage, "old2"); + await pinSnapshot(storage, key, manifestOf("new", null, { "a.md": "A" })); + await storage.put( + pinKey("foreign"), + await encryptJson(otherKey, manifestOf("foreign", null, {})), + ); + + expect(await clearLegacyHistory(storage, key)).toBe(3); + expect((await storage.list("pins/")).sort()).toEqual([ + pinKey("foreign"), + pinKey("new"), + ]); + expect(await storage.exists(REMOTE_HISTORY_LOG_KEY)).toBe(false); + expect(await clearLegacyHistory(storage, key)).toBe(0); + }); + + it("deletes the log only after every 1.x pin, so a cut-short run still shows", async () => { + const storage = new FakeStorage(); + await storage.put(REMOTE_HISTORY_LOG_KEY, await encryptJson(key, {})); + await legacyPin(storage, "old1"); + vi.spyOn(storage, "delete").mockRejectedValueOnce(new Error("offline")); + + await expect(clearLegacyHistory(storage, key)).rejects.toThrow("offline"); + expect(await storage.exists(REMOTE_HISTORY_LOG_KEY)).toBe(true); + expect(await clearLegacyHistory(storage, key)).toBe(2); + expect(await storage.list("pins/")).toEqual([]); + }); + + it("deletes 1.x pins an interrupted reset left without the log", async () => { + const storage = new FakeStorage(); + await legacyPin(storage, "old1"); + + expect(await clearLegacyHistory(storage, key)).toBe(1); + expect(await storage.list("pins/")).toEqual([]); + }); +}); diff --git a/packages/plugin/tests/features/sync/history/model/activity.test.ts b/packages/plugin/tests/features/sync/history/model/activity.test.ts new file mode 100644 index 00000000..e66eceec --- /dev/null +++ b/packages/plugin/tests/features/sync/history/model/activity.test.ts @@ -0,0 +1,71 @@ +import { DAY } from "@tests/helpers/history-sim"; +import { expect, it } from "vitest"; +import { activityOf } from "@/features/sync/history/model/activity"; +import type { HistoryView } from "@/features/sync/history/model/cover"; +import { storedRecord } from "@/features/sync/history/model/records"; +import type { + Activity, + HistoryObject, +} from "@/features/sync/history/model/types"; + +function counts(group: number, activity: Activity) { + const object: HistoryObject = { + v: 1, + vaultId: "vault", + res: "counts", + group, + records: [], + activity, + consumed: [], + }; + return { object, at: 0 }; +} + +it("takes the larger of two counts of one group per hour, and adds other groups", () => { + const view: HistoryView = { + pushes: new Map(), + objects: new Map([ + ["b/1", counts(0, { 1: [2, 5], 2: [1, 1] })], + ["b/2", counts(0, { 1: [3, 4] })], + ["b/3", counts(28 * DAY, { 700: [1, 1] })], + ]), + }; + const cover = { + chain: [], + lagging: false, + truncated: false, + consumed: new Set(), + }; + expect(activityOf(view, cover, "vault")).toEqual({ + 1: [3, 5], + 2: [1, 1], + 700: [1, 1], + }); +}); + +it("takes a record walked into counted hours as another view of the same pushes", () => { + const at = Date.UTC(2026, 0, 6, 10); + const record = storedRecord( + { + v: 1, + vaultId: "vault", + id: "a", + parentId: null, + createdAt: at, + deviceId: "d", + changes: { added: {}, modified: {}, deleted: {} }, + }, + at, + ); + const view: HistoryView = { + pushes: new Map(), + objects: new Map([["b/1", counts(0, record.activity)]]), + }; + const cover = { + chain: [{ record, source: "b/week", res: "1w" as const }], + lagging: false, + truncated: false, + consumed: new Set(), + }; + expect(activityOf(view, cover, "vault")).toEqual(record.activity); +}); diff --git a/packages/plugin/tests/features/sync/history/model/cover.test.ts b/packages/plugin/tests/features/sync/history/model/cover.test.ts new file mode 100644 index 00000000..2385f08f --- /dev/null +++ b/packages/plugin/tests/features/sync/history/model/cover.test.ts @@ -0,0 +1,201 @@ +import { HistorySim, MINUTE } from "@tests/helpers/history-sim"; +import { describe, expect, it } from "vitest"; +import { coverOf } from "@/features/sync/history/model/cover"; +import { storedRecord, thin } from "@/features/sync/history/model/records"; +import type { HistoryObject } from "@/features/sync/history/model/types"; + +const START = Date.UTC(2026, 6, 1, 8, 0, 0); + +function vaultOf(pushes: number): HistorySim { + const sim = new HistorySim(1, null); + for (let i = 1; i <= pushes; i++) sim.push(START + i * MINUTE); + return sim; +} + +function headOf(sim: HistorySim) { + const head = sim.head; + if (!head) throw new Error("no head"); + return { + id: head.snapshotId, + parentId: head.parentSnapshotId, + vaultId: head.vaultId, + }; +} + +/** An object over the given push keys, as GC would write it. */ +function objectOf( + sim: HistorySim, + keys: string[], + res: HistoryObject["res"], +): HistoryObject { + const records = keys.map((key) => { + const pushed = sim.pushes.get(key); + if (!pushed) throw new Error(key); + return storedRecord(pushed.push, pushed.at); + }); + return { + v: 1, + vaultId: "vault", + res, + group: 0, + records: thin(records, res), + consumed: keys, + }; +} + +describe("coverOf", () => { + it("walks every push from HEAD back to the first", () => { + const sim = vaultOf(4); + const cover = coverOf(sim.view(), headOf(sim)); + expect(cover.chain.map((walked) => walked.record.id)).toEqual([ + "s4", + "s3", + "s2", + "s1", + ]); + expect(cover).toMatchObject({ lagging: false, truncated: false }); + }); + + it("starts at HEAD's parent while HEAD's record is not listed yet", () => { + const sim = vaultOf(3); + sim.pushes.delete("p/s3"); + const cover = coverOf(sim.view(), headOf(sim)); + expect(cover.chain.map((walked) => walked.record.id)).toEqual(["s2", "s1"]); + expect(cover.lagging).toBe(true); + }); + + it("stops at a missing record and says so", () => { + const sim = vaultOf(4); + sim.pushes.delete("p/s2"); + const cover = coverOf(sim.view(), headOf(sim)); + expect(cover.chain.map((walked) => walked.record.id)).toEqual(["s4", "s3"]); + expect(cover.truncated).toBe(true); + }); + + it("reads an object instead of the pushes it replaced", () => { + const sim = vaultOf(4); + sim.objects.set("b/1", { + object: objectOf(sim, ["p/s1", "p/s2", "p/s3"], "10m"), + at: START + 60 * MINUTE, + }); + const cover = coverOf(sim.view(), headOf(sim)); + expect( + cover.chain.map((walked) => [walked.record.id, walked.source]), + ).toEqual([ + ["s4", "p/s4"], + ["s3", "b/1"], + ]); + expect(cover.consumed).toEqual(new Set(["p/s1", "p/s2", "p/s3"])); + }); + + it("prefers the coarser of two objects covering the same pushes", () => { + const sim = vaultOf(4); + const coarse = objectOf(sim, ["p/s2", "p/s3"], "1h"); + sim.objects.set("b/coarse", { + object: { ...coarse, consumed: [] }, + at: START, + }); + const cover = coverOf(sim.view(), headOf(sim)); + expect(cover.chain.map((walked) => walked.source)).toEqual([ + "p/s4", + "b/coarse", + "p/s1", + ]); + }); + + it("takes the path that reaches the first push over a coarser one that dead-ends", () => { + const sim = vaultOf(4); + const coarse = objectOf(sim, ["p/s3"], "1h"); + const [record] = coarse.records; + if (!record) throw new Error("no record"); + sim.objects.set("b/coarse", { + object: { + ...coarse, + records: [{ ...record, parentId: "ghost" }], + consumed: [], + }, + at: START, + }); + const cover = coverOf(sim.view(), headOf(sim)); + expect(cover.chain.map((walked) => walked.source)).toEqual([ + "p/s4", + "p/s3", + "p/s2", + "p/s1", + ]); + expect(cover.truncated).toBe(false); + }); + + it("walks an object holding a straggler's runs by their parent links", () => { + const sim = vaultOf(3); + sim.objects.set("b/a", { + object: objectOf(sim, ["p/s1", "p/s3"], "push"), + at: START + 60 * MINUTE, + }); + sim.objects.set("b/b", { + object: objectOf(sim, ["p/s2"], "push"), + at: START + 60 * MINUTE, + }); + const cover = coverOf(sim.view(), headOf(sim)); + expect( + cover.chain.map((walked) => [walked.record.id, walked.source]), + ).toEqual([ + ["s3", "b/a"], + ["s2", "b/b"], + ["s1", "b/a"], + ]); + expect(cover.truncated).toBe(false); + sim.checkReplay(cover); + }); + + it("forks from inside a packed run when a delayed sibling wins", () => { + const sim = vaultOf(2); + sim.objects.set("b/run", { + object: objectOf(sim, ["p/s1", "p/s2"], "push"), + at: START + 60 * MINUTE, + }); + const first = sim.manifests.get("s1"); + if (!first) throw new Error("no s1"); + sim.head = first; + sim.push(START + 61 * MINUTE); + const cover = coverOf(sim.view(), headOf(sim)); + expect( + cover.chain.map((walked) => [walked.record.id, walked.source]), + ).toEqual([ + ["s3", "p/s3"], + ["s1", "b/run"], + ]); + expect(cover.truncated).toBe(false); + sim.checkReplay(cover); + }); + + it("lets only the later of two objects naming each other replace the other", () => { + const sim = vaultOf(2); + const object = objectOf(sim, ["p/s1", "p/s2"], "10m"); + sim.objects.set("b/old", { + object: { ...object, consumed: ["b/new"] }, + at: START, + }); + sim.objects.set("b/new", { + object: { ...object, consumed: ["b/old"] }, + at: START + MINUTE, + }); + const cover = coverOf(sim.view(), headOf(sim)); + expect(cover.consumed.has("b/old")).toBe(true); + expect(cover.consumed.has("b/new")).toBe(false); + }); + + it("ignores another vault's records and survives a cycle in corrupt data", () => { + const sim = vaultOf(2); + const s1 = sim.pushes.get("p/s1"); + if (!s1) throw new Error("no s1"); + sim.pushes.set("p/s1", { ...s1, push: { ...s1.push, parentId: "s2" } }); + sim.pushes.set("p/x", { + push: { ...s1.push, id: "x", vaultId: "other" }, + at: START, + }); + const cover = coverOf(sim.view(), headOf(sim)); + expect(cover.chain.map((walked) => walked.record.id)).toEqual(["s2", "s1"]); + expect(cover.truncated).toBe(true); + }); +}); diff --git a/packages/plugin/tests/features/sync/history/model/periods.test.ts b/packages/plugin/tests/features/sync/history/model/periods.test.ts new file mode 100644 index 00000000..0e77ced1 --- /dev/null +++ b/packages/plugin/tests/features/sync/history/model/periods.test.ts @@ -0,0 +1,113 @@ +import { seeded } from "@tests/helpers/seeded"; +import { describe, expect, it } from "vitest"; +import { + countsBefore, + dueResolution, + groupEnd, + groupStart, + isDue, + keepStart, + keptUntil, + RESOLUTIONS, + stagesOf, +} from "@/features/sync/history/model/periods"; + +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; +const NOW = Date.UTC(2026, 9, 27, 15, 37, 12); +const QUARTER = 90 * DAY; + +describe("history periods", () => { + it("nests every group inside the next coarser one, and every span inside its group", () => { + const random = seeded(3); + for (let i = 0; i < 500; i++) { + const at = Math.floor(random() * NOW); + for (const [index, res] of RESOLUTIONS.entries()) { + const start = groupStart(res, at); + expect(start).toBeLessThanOrEqual(at); + expect(groupEnd(res, start)).toBeGreaterThan(at); + const span = keepStart(res, at); + if (span !== null) expect(span).toBeGreaterThanOrEqual(start); + const coarser = RESOLUTIONS[index + 1]; + if (!coarser) continue; + const outer = groupStart(coarser, at); + expect(start).toBeGreaterThanOrEqual(outer); + expect(groupEnd(res, start)).toBeLessThanOrEqual( + groupEnd(coarser, outer), + ); + } + } + }); + + it("starts weeks on Monday at midnight UTC", () => { + expect(new Date(groupStart("1d", NOW)).toISOString()).toBe( + "2026-10-26T00:00:00.000Z", + ); + }); + + it("packs a 10-minute slot only 10 minutes after it ends", () => { + const slot = groupStart("push", NOW); + const end = groupEnd("push", slot); + expect(isDue("push", slot, end + 10 * MINUTE - 1, QUARTER)).toBe(false); + expect(isDue("push", slot, end + 10 * MINUTE, QUARTER)).toBe(true); + }); + + it("never drops to counts when history is kept forever", () => { + expect(dueResolution(0, NOW, null)).toBe("1w"); + expect(dueResolution(0, NOW, QUARTER)).toBe("counts"); + }); + + it("leaves fresh pushes unpacked and thins older ones by age", () => { + expect(dueResolution(NOW - MINUTE, NOW, QUARTER)).toBeNull(); + expect(dueResolution(NOW - 2 * HOUR, NOW, QUARTER)).toBe("10m"); + expect(dueResolution(NOW - 3 * DAY, NOW, QUARTER)).toBe("1h"); + expect(dueResolution(NOW - 20 * DAY, NOW, QUARTER)).toBe("1d"); + expect(dueResolution(NOW - 70 * DAY, NOW, QUARTER)).toBe("1w"); + expect(dueResolution(NOW - 150 * DAY, NOW, QUARTER)).toBe("counts"); + }); + + it("only ever coarsens a record as time passes", () => { + const random = seeded(9); + for (let i = 0; i < 200; i++) { + const at = NOW - Math.floor(random() * 200 * DAY); + let previous = -1; + for (let now = at; now < at + 200 * DAY; now += 7 * HOUR) { + const res = dueResolution(at, now, QUARTER); + const index = res === null ? -1 : RESOLUTIONS.indexOf(res); + expect(index).toBeGreaterThanOrEqual(previous); + previous = index; + } + } + }); + + it("stages exactly the resolutions a record reaches, none younger than its start", () => { + const random = seeded(5); + for (const horizon of [7 * DAY, 30 * DAY, QUARTER, null]) { + const youngest = new Map(); + for (let i = 0; i < 20; i++) { + const at = NOW - Math.floor(random() * 365 * DAY); + for ( + let age = 0; + age < (horizon ?? 0) + 120 * DAY; + age += 30 * MINUTE + ) { + const res = dueResolution(at, at + age, horizon) ?? "push"; + youngest.set(res, Math.min(youngest.get(res) ?? age, age)); + } + } + const stages = stagesOf(horizon); + expect([...youngest.keys()].sort()).toEqual( + stages.map((stage) => stage.res).sort(), + ); + for (const { res, from } of stages) + expect(youngest.get(res)).toBeGreaterThanOrEqual(from); + } + }); + + it("puts every record before countsBefore past keptUntil, and none after", () => { + const cutoff = countsBefore(NOW, QUARTER); + expect(keptUntil(cutoff - 1, QUARTER)).toBeLessThanOrEqual(NOW); + expect(keptUntil(cutoff, QUARTER)).toBeGreaterThan(NOW); + }); +}); diff --git a/packages/plugin/tests/features/sync/history/model/plan.test.ts b/packages/plugin/tests/features/sync/history/model/plan.test.ts new file mode 100644 index 00000000..c815e76f --- /dev/null +++ b/packages/plugin/tests/features/sync/history/model/plan.test.ts @@ -0,0 +1,351 @@ +import { DAY, HistorySim, HOUR, MINUTE } from "@tests/helpers/history-sim"; +import { seeded } from "@tests/helpers/seeded"; +import { describe, expect, it } from "vitest"; +import { coverOf, type HistoryView } from "@/features/sync/history/model/cover"; +import { groupStart } from "@/features/sync/history/model/periods"; +import { freedHashes, planGc } from "@/features/sync/history/model/plan"; +import { storedRecord } from "@/features/sync/history/model/records"; +import type { HistoryObject } from "@/features/sync/history/model/types"; +import type { EFileKind } from "@/features/sync/types"; + +/** The key of the object holding the record of `id`. */ +function holder(sim: HistorySim, id: string): string | undefined { + return [...sim.objects].find(([, { object }]) => + object.records.some((record) => record.id === id), + )?.[0]; +} + +function expectSound(sim: HistorySim): void { + const cover = sim.cover(); + expect(cover.lagging).toBe(false); + expect(cover.truncated).toBe(false); + sim.checkReplay(cover); + expect(sim.countedPushes(cover)).toBe(sim.pushCount); +} + +describe("history GC plan over a simulated vault", () => { + it.each([0, 0.05])( + "keeps every retained state replayable and every push counted, for 60 days of bursts (straggling %s)", + (straggle) => { + const sim = new HistorySim(11, 14 * DAY); + sim.straggle = straggle; + const random = seeded(5); + const end = sim.now + 60 * DAY; + let lastGc = sim.now; + while (sim.now < end) { + // A burst of instant saves, then a pause of minutes to hours. + const burst = random() < 0.3 ? 40 : 3; + for (let i = 0; i < burst; i++) { + sim.push(sim.after(5_000 + Math.floor(random() * 20_000))); + } + sim.after(Math.floor(random() * 3 * HOUR)); + if (sim.now - lastGc >= 10 * MINUTE) { + sim.gc(sim.now); + lastGc = sim.now; + expectSound(sim); + } + } + const before = sim.objects.size + sim.pushes.size; + expect(sim.gc(sim.now)).toBe(0); + expect(sim.objects.size + sim.pushes.size).toBe(before); + // Thinned: a few dozen objects for 60 days of pushes, the oldest down to counts. + expect(sim.objects.size).toBeLessThan(80); + const resolutions = [...sim.objects.values()].map( + ({ object }) => object.res, + ); + expect(resolutions).toContain("counts"); + expect(resolutions).toContain("1d"); + expect(sim.pushCount).toBeGreaterThan(1000); + }, + ); + + it("keeps history forever when there is no horizon, thinned to weeks", () => { + const sim = new HistorySim(2, null); + for (let day = 0; day < 120; day++) { + for (let i = 0; i < 6; i++) sim.push(sim.after(HOUR)); + sim.gc(sim.after(18 * HOUR)); + } + expectSound(sim); + const resolutions = [...sim.objects.values()].map( + ({ object }) => object.res, + ); + expect(resolutions).not.toContain("counts"); + expect(resolutions).toContain("1w"); + }); + + it("rebuilds a slot when a record written before its publish joins the chain late", () => { + const sim = new HistorySim(3, 14 * DAY); + for (let i = 0; i < 5; i++) sim.push(sim.after(MINUTE)); + const late = sim.push(sim.after(MINUTE), false); + sim.gc(sim.after(HOUR)); + expectSound(sim); + expect(sim.pushes.has(`p/${late.snapshotId}`)).toBe(true); + sim.publish(late); + sim.gc(sim.after(10 * MINUTE)); + expectSound(sim); + expect(sim.pushes.size).toBe(0); + }); + + it.each([ + ["forever", null, 15 * DAY], + ["past the horizon", 7 * DAY, 50 * DAY], + ])( + "keeps a packed object whose records a late parent record moved to another group (%s)", + (_, horizon, retryAfter) => { + const start = Date.UTC(2026, 0, 5, 8); + const sim = new HistorySim(8, horizon, start); + sim.push(sim.now); + sim.push(sim.after(DAY)); + // Its record write failed: the device retries it at its next push. + const held = sim.pushes.get("p/s2"); + sim.pushes.delete("p/s2"); + for (let i = 0; i < 3; i++) sim.push(sim.after(DAY)); + sim.gc(sim.after(2 * DAY)); + expect(holder(sim, "s4")).toBeDefined(); + sim.after(start + retryAfter - sim.now); + if (held) sim.pushes.set("p/s2", { ...held, at: sim.now }); + sim.push(sim.after(MINUTE)); + sim.gc(sim.after(MINUTE)); + expectSound(sim); + }, + ); + + it("builds no counts that would replace only earlier counts while a packed source stays", () => { + const start = Date.UTC(2026, 0, 5, 8); + const sim = new HistorySim(9, 7 * DAY, start); + for (let i = 0; i < 4; i++) sim.push(i === 0 ? sim.now : sim.after(DAY)); + const held = sim.pushes.get("p/s2"); + // One object holding two runs: s1, then s3 and s4 past the missing s2. + const records = ["s1", "s3", "s4"].map((id) => { + const read = sim.pushes.get(`p/${id}`); + if (!read) throw new Error(`No record ${id}`); + sim.pushes.delete(`p/${id}`); + return storedRecord(read.push, read.at); + }); + sim.pushes.delete("p/s2"); + sim.objects.set("b/1d-runs", { + object: { + v: 1, + vaultId: "vault", + res: "1d", + group: groupStart("1d", start), + records, + consumed: [], + }, + at: sim.now, + }); + sim.after(start + 50 * DAY - sim.now); + if (held) sim.pushes.set("p/s2", { ...held, at: sim.now }); + sim.push(sim.after(MINUTE)); + sim.gc(sim.after(MINUTE)); + expectSound(sim); + + const plan = planGc({ + view: sim.view(), + cover: sim.cover(), + vaultId: "vault", + now: sim.after(10 * MINUTE), + horizon: 7 * DAY, + settledBefore: sim.now - DAY, + }); + expect(plan.builds.filter((build) => build.res === "counts")).toEqual([]); + }); + + it("deletes a push that lost the guard once it is settled, and not before", () => { + const sim = new HistorySim(4, 14 * DAY); + sim.push(sim.after(MINUTE)); + const lost = sim.push(sim.after(MINUTE), false); + // Another device published on the same parent: the lost push can never join. + sim.push(sim.after(MINUTE)); + sim.gc(sim.after(HOUR)); + expect(sim.pushes.has(`p/${lost.snapshotId}`)).toBe(true); + sim.gc(sim.after(DAY)); + expect(sim.pushes.has(`p/${lost.snapshotId}`)).toBe(false); + expectSound(sim); + }); + + it("builds nothing over a group the walk has not reached the start of", () => { + const sim = new HistorySim(6, 14 * DAY); + const first = groupStart("push", sim.now + MINUTE); + for (let i = 0; i < 20; i++) sim.push(sim.after(MINUTE)); + // The first record is gone: the walk stops inside the slot it opened. + sim.pushes.delete("p/s1"); + const plan = planGc({ + view: sim.view(), + cover: sim.cover(), + vaultId: "vault", + now: sim.after(HOUR), + horizon: 14 * DAY, + settledBefore: sim.now - DAY, + }); + expect(plan.builds.some((build) => build.group === first)).toBe(false); + expect(plan.builds.length).toBeGreaterThan(0); + }); +}); + +describe("freedHashes", () => { + const entry = (hash: string) => ({ + hash, + size: 1, + mtime: 1, + kind: "vault" as EFileKind, + }); + const changes = (hash: string) => ({ + added: { "a.md": entry(hash) }, + modified: {}, + deleted: {}, + }); + + it("frees what a replaced record released, and not what a kept record names", () => { + const freed = freedHashes( + [{ changes: changes("A"), released: ["R1", "R2"] }], + [{ changes: changes("R2") }], + ); + expect([...freed].sort()).toEqual(["A", "R1"]); + }); + + it("frees only what a record names without a released list", () => { + expect([...freedHashes([{ changes: changes("A") }], [])]).toEqual(["A"]); + }); +}); + +describe("history GC plan, races", () => { + it("keeps a straggler's record on the walk while its neighbours pack", () => { + const sim = new HistorySim(7, null); + const t0 = sim.now; + for (let i = 1; i <= 5; i++) sim.push(t0 + i * MINUTE); + // s3's storage clock ran ahead of its successors'. + const s3 = sim.pushes.get("p/s3"); + if (s3) s3.at = t0 + 30 * MINUTE; + for (const now of [t0 + 25 * MINUTE, t0 + 2 * HOUR, t0 + 9 * DAY]) { + sim.gc(now); + expectSound(sim); + } + }); + + it("keeps a sibling that held HEAD for a moment until the horizon", () => { + const sim = new HistorySim(8, 14 * DAY); + const t0 = sim.now; + sim.push(t0 + MINUTE); + const parent = sim.push(t0 + 2 * MINUTE); + sim.push(t0 + 12 * MINUTE); + sim.gc(t0 + 31 * MINUTE); + const sibling = holder(sim, "s3"); + // A push that passed its precheck on the same parent lands over s3. + sim.head = parent; + sim.push(t0 + 15 * MINUTE); + for (const now of [t0 + 40 * MINUTE, t0 + 2 * DAY]) { + sim.gc(now); + expect(holder(sim, "s3")).toBe(sibling); + expect(sim.cover().truncated).toBe(false); + sim.checkReplay(sim.cover()); + } + sim.gc(t0 + 60 * DAY); + expect(holder(sim, "s3")).toBeUndefined(); + }); + + it("leaves a packed record behind a gap alone when a straggler after the gap looks older", () => { + const sim = new HistorySim(9, null); + const t0 = sim.now; + sim.push(t0 + 61 * MINUTE); + sim.gc(t0 + 81 * MINUTE); + sim.push(t0 + 82 * MINUTE); + // s2's record never landed: a gap. + sim.pushes.delete("p/s2"); + sim.push(t0 + 83 * MINUTE); + sim.push(t0 + 84 * MINUTE); + const s3 = sim.pushes.get("p/s3"); + const s4 = sim.pushes.get("p/s4"); + if (!s3 || !s4) throw new Error("no record"); + s3.at = t0 + 49 * MINUTE; + s4.at = t0 + 62 * MINUTE; + sim.push(t0 + DAY); + sim.gc(t0 + DAY + HOUR); + expect(holder(sim, "s1")).toBeDefined(); + }); + + it("keeps a record whose successor straggles back over a four-week boundary", () => { + const boundary = groupStart("counts", Date.UTC(2026, 6, 1)) + 28 * DAY; + const sim = new HistorySim(10, 7 * DAY, boundary - 10 * MINUTE); + sim.push(boundary - 2 * MINUTE); + sim.push(boundary + MINUTE); + sim.push(boundary + 2 * MINUTE); + const s3 = sim.pushes.get("p/s3"); + if (!s3) throw new Error("no record"); + s3.at = boundary - MINUTE; + sim.push(boundary + 7 * DAY + MINUTE); + sim.gc(boundary + 7 * DAY + 2 * MINUTE); + const cover = sim.cover(); + // s3 moves up to s2's time, so the hour keeps them as one record reaching back to the counted s1. + expect( + cover.chain.map(({ record }) => [record.id, record.parentId]), + ).toEqual([ + ["s4", "s3"], + ["s3", "s1"], + ]); + expect(cover.truncated).toBe(false); + sim.checkReplay(cover); + }); + + it("merges a later view into a group's counts instead of adding it", () => { + const at = Date.UTC(2026, 0, 6, 10); + const record = storedRecord( + { + v: 1, + vaultId: "vault", + id: "a", + parentId: null, + createdAt: at, + deviceId: "d", + changes: { added: {}, modified: {}, deleted: {} }, + }, + at, + ); + const group = groupStart("counts", at); + const object = (res: HistoryObject["res"]): HistoryObject => ({ + v: 1, + vaultId: "vault", + res, + group, + records: res === "counts" ? [] : [record], + consumed: [], + }); + const view: HistoryView = { + pushes: new Map(), + objects: new Map([ + ["b/week", { object: object("1w"), at }], + [ + "b/counts", + { + object: { + ...object("counts"), + activity: record.activity, + lastId: "a", + }, + at, + }, + ], + ]), + }; + const now = at + 120 * DAY; + const plan = planGc({ + view, + cover: coverOf(view, { id: "a", parentId: null, vaultId: "vault" }), + vaultId: "vault", + now, + horizon: 14 * DAY, + settledBefore: now - DAY, + }); + expect(plan.builds).toEqual([ + { + vaultId: "vault", + res: "counts", + group, + records: [], + activity: record.activity, + lastId: "a", + consumed: ["b/counts", "b/week"], + }, + ]); + }); +}); diff --git a/packages/plugin/tests/features/sync/history/model/records.test.ts b/packages/plugin/tests/features/sync/history/model/records.test.ts new file mode 100644 index 00000000..051e21e4 --- /dev/null +++ b/packages/plugin/tests/features/sync/history/model/records.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, it } from "vitest"; +import { hourOf } from "@/features/sync/history/model/periods"; +import { storedRecord, thin } from "@/features/sync/history/model/records"; +import type { + PushRecord, + StoredRecord, +} from "@/features/sync/history/model/types"; +import type { EFileKind, ManifestEntry } from "@/features/sync/types"; + +const MINUTE = 60_000; +const BASE = Date.UTC(2026, 9, 27, 10, 0, 0); + +function entry(hash: string): ManifestEntry { + return { hash, size: 1, mtime: 1, kind: "vault" as EFileKind }; +} + +/** Push n edits `note.md` from v(n-1) to vn, so a merge is easy to read. */ +function pushes( + times: readonly number[], + parentOfFirst: string | null = null, +): StoredRecord[] { + return times.map((at, index) => + storedRecord( + { + v: 1, + vaultId: "v", + id: `p${index + 1}`, + parentId: index === 0 ? parentOfFirst : `p${index}`, + createdAt: at, + deviceId: "d", + changes: { + added: {}, + modified: { + "note.md": { from: entry(`v${index}`), to: entry(`v${index + 1}`) }, + }, + deleted: {}, + }, + }, + at, + ), + ); +} + +describe("storedRecord", () => { + const push = (overrides: Partial): PushRecord => ({ + v: 1, + vaultId: "v", + id: "p1", + parentId: null, + createdAt: BASE, + deviceId: "d", + changes: { added: {}, modified: {}, deleted: {} }, + ...overrides, + }); + + it("counts no activity for a push of only the configuration folder", () => { + expect(storedRecord(push({ released: ["R1"] }), BASE).activity).toEqual({}); + }); + + it("still counts one push for an empty push that released nothing", () => { + expect(storedRecord(push({}), BASE).activity).toEqual({ + [hourOf(BASE)]: [1, 0], + }); + }); + + it("counts a push that changed vault files even when it released versions", () => { + const changed = push({ + changes: { added: { "a.md": entry("A") }, modified: {}, deleted: {} }, + released: ["R1"], + }); + expect(storedRecord(changed, BASE).activity).toEqual({ + [hourOf(BASE)]: [1, 1], + }); + }); +}); + +describe("thin", () => { + it("keeps every push at push resolution", () => { + const records = pushes([BASE, BASE + MINUTE]); + expect(thin(records, "push")).toEqual(records); + }); + + it("merges a contiguous run inside one span into its last push", () => { + const records = pushes([ + BASE + MINUTE, + BASE + 3 * MINUTE, + BASE + 9 * MINUTE, + BASE + 11 * MINUTE, + ]); + const [first, second] = thin(records, "10m"); + expect(first).toMatchObject({ + id: "p3", + parentId: null, + at: BASE + 9 * MINUTE, + firstAt: BASE + MINUTE, + pushes: 3, + activity: { [hourOf(BASE)]: [3, 3] }, + }); + expect(first?.changes.modified["note.md"]).toEqual({ + from: entry("v0"), + to: entry("v3"), + }); + expect(second).toBe(records[3]); + }); + + it("never merges across a gap in the chain", () => { + const [first, second] = pushes([BASE + MINUTE, BASE + 2 * MINUTE]); + const broken = [first, { ...second, parentId: "elsewhere" }]; + expect(thin(broken as StoredRecord[], "10m")).toHaveLength(2); + }); + + it("gives the same result thinned at once or step by step", () => { + const times = Array.from({ length: 200 }, (_, i) => BASE + i * 7 * MINUTE); + const records = pushes(times, "root"); + const direct = thin(records, "1d"); + const stepped = thin(thin(thin(records, "10m"), "1h"), "1d"); + expect(stepped).toEqual(direct); + }); +}); diff --git a/packages/plugin/tests/features/sync/history/pins.test.ts b/packages/plugin/tests/features/sync/history/pins.test.ts new file mode 100644 index 00000000..ae7d0c54 --- /dev/null +++ b/packages/plugin/tests/features/sync/history/pins.test.ts @@ -0,0 +1,370 @@ +import { FakeStorage } from "@tests/helpers/fake-storage"; +import { manifestOf, pinSnapshot, seedChain } from "@tests/helpers/history"; +import { RevalidatingStorage } from "@tests/helpers/revalidating-storage"; +import { beforeAll, describe, expect, it, vi } from "vitest"; +import { + decryptJson, + deriveKey, + type EncryptionKey, + encryptJson, +} from "@/core/crypto/cipher"; +import { + pinKey, + readPinById, + readPinInfos, + readPins, + writePin, +} from "@/features/sync/history/pins"; +import { + resolveSnapshotManifest, + setSnapshotPinned, +} from "@/features/sync/history/query"; +import { pushKey } from "@/features/sync/history/remote"; +import type { Manifest } from "@/features/sync/types"; + +let key: EncryptionKey; +beforeAll(async () => { + key = await deriveKey("pw", new Uint8Array(16)); +}); + +const chain = [ + manifestOf("s1", null, { a: "A1" }), + manifestOf("s2", "s1", { a: "A2", b: "B1" }), + manifestOf("s3", "s2", { a: "A3" }), +]; + +async function seeded(): Promise { + const storage = new FakeStorage(); + await seedChain(storage, key, chain); + return storage; +} + +describe("setSnapshotPinned", () => { + it("stores the replayed manifest with its label", async () => { + const storage = await seeded(); + await setSnapshotPinned({ storage, key, root: "" }, "s2", true, "Draft"); + + const pin = await readPinById(storage, key, "", "s2"); + expect(pin?.manifest.files).toEqual(chain[1]?.files); + expect(pin?.label).toBe("Draft"); + }); + + it("leaves the configuration folder out of a new pin, and keeps the vault files", async () => { + const storage = new FakeStorage(); + const withConfig = [ + manifestOf("c1", null, { "a.md": "A1" }), + manifestOf("c2", "c1", { + "a.md": "A2", + ".obsidian/app.json": "J1", + ".obsidian-other/x": "O1", + }), + manifestOf("c3", "c2", { "a.md": "A3" }), + ]; + await seedChain(storage, key, withConfig); + + await setSnapshotPinned( + { storage, key, root: "", configDir: ".obsidian" }, + "c2", + true, + ); + + const pin = await readPinById(storage, key, "", "c2"); + expect(Object.keys(pin?.manifest.files ?? {}).sort()).toEqual([ + ".obsidian-other/x", + "a.md", + ]); + expect(pin?.manifest.files["a.md"]).toEqual(withConfig[1]?.files["a.md"]); + }); + + it("deletes the pin on unpin", async () => { + const storage = await seeded(); + const source = { storage, key, root: "" }; + await setSnapshotPinned(source, "s1", true); + await setSnapshotPinned(source, "s1", false); + expect(await storage.exists(pinKey("s1"))).toBe(false); + }); + + it("relabels a pin history no longer reaches, keeping its manifest", async () => { + const storage = await seeded(); + const source = { storage, key, root: "" }; + await setSnapshotPinned(source, "s1", true, "Old"); + await storage.delete(pushKey("s2")); + + await setSnapshotPinned(source, "s1", true, "New"); + expect(await readPinById(storage, key, "", "s1")).toMatchObject({ + label: "New", + manifest: { files: chain[0]?.files }, + }); + await setSnapshotPinned(source, "s1", true); + expect((await readPinById(storage, key, "", "s1"))?.label).toBe("New"); + await setSnapshotPinned(source, "s1", true, ""); + expect((await readPinById(storage, key, "", "s1"))?.label).toBeUndefined(); + }); + + it("rewrites a pin that cannot be read", async () => { + const storage = await seeded(); + await storage.put(pinKey("s1"), new Uint8Array([1, 2, 3])); + + await setSnapshotPinned({ storage, key, root: "" }, "s1", true); + expect((await readPinById(storage, key, "", "s1"))?.manifest.files).toEqual( + chain[0]?.files, + ); + }); + + it("refuses a snapshot history can no longer rebuild", async () => { + const storage = await seeded(); + await storage.delete(pushKey("s2")); + + await expect( + setSnapshotPinned({ storage, key, root: "" }, "s1", true), + ).rejects.toThrow(/can no longer be rebuilt/); + expect(await storage.exists(pinKey("s1"))).toBe(false); + }); + + it("reads the pin once when history cannot rebuild the snapshot", async () => { + const storage = await seeded(); + await storage.delete(pushKey("s2")); + const get = vi.spyOn(storage, "get"); + + await expect( + setSnapshotPinned({ storage, key, root: "" }, "s1", true), + ).rejects.toThrow(/can no longer be rebuilt/); + expect(get.mock.calls.filter(([got]) => got === pinKey("s1"))).toHaveLength( + 1, + ); + }); +}); + +describe("resolveSnapshotManifest", () => { + it("falls back to the pin once replay cannot reach the snapshot", async () => { + const storage = await seeded(); + const source = { storage, key, root: "" }; + await setSnapshotPinned(source, "s1", true); + await storage.delete(pushKey("s2")); + + expect((await resolveSnapshotManifest(source, "s1"))?.files).toEqual( + chain[0]?.files, + ); + expect(await resolveSnapshotManifest(source, "s2")).toBeNull(); + }); +}); + +async function pinMany(storage: FakeStorage, count: number): Promise { + for (let i = 0; i < count; i++) { + await pinSnapshot(storage, key, manifestOf(`p${i}`, null, {}, i + 1)); + } +} + +describe("readPinInfos", () => { + it("downloads no pin again while its etag holds, past the manifest cache", async () => { + const storage = new RevalidatingStorage(); + await pinMany(storage, 6); + const get = vi.spyOn(storage, "get"); + + const first = await readPinInfos(storage, key, ""); + expect(get).toHaveBeenCalledTimes(6); + get.mockClear(); + const second = await readPinInfos(storage, key, ""); + expect(get).not.toHaveBeenCalled(); + expect(second).toEqual(first); + expect(second.pins.map(({ id }) => id)).toEqual([ + "p5", + "p4", + "p3", + "p2", + "p1", + "p0", + ]); + }); + + it("reads again only the pin whose etag changed", async () => { + const storage = new RevalidatingStorage(); + await pinMany(storage, 6); + await readPinInfos(storage, key, ""); + await pinSnapshot(storage, key, manifestOf("p2", null, {}, 3), "Renamed"); + const get = vi.spyOn(storage, "get"); + + const read = await readPinInfos(storage, key, ""); + expect(get.mock.calls).toEqual([[pinKey("p2")]]); + expect(read.pins.find(({ id }) => id === "p2")?.label).toBe("Renamed"); + }); + + it("drops a pin that is no longer listed", async () => { + const storage = new RevalidatingStorage(); + await pinMany(storage, 6); + await readPinInfos(storage, key, ""); + await storage.delete(pinKey("p3")); + const get = vi.spyOn(storage, "get"); + + const read = await readPinInfos(storage, key, ""); + expect(read.pins.map(({ id }) => id)).not.toContain("p3"); + expect(read.pins).toHaveLength(5); + expect(get).not.toHaveBeenCalled(); + }); + + it("reads every pin again without an etag, and keeps naming an unreadable one", async () => { + const storage = new FakeStorage(); + await pinMany(storage, 6); + await storage.put(pinKey("bad"), new Uint8Array([1])); + const get = vi.spyOn(storage, "get"); + + await readPinInfos(storage, key, ""); + const read = await readPinInfos(storage, key, ""); + expect(get).toHaveBeenCalledTimes(14); + expect(read.pins).toHaveLength(6); + expect(read.unreadable).toEqual([pinKey("bad")]); + }); + + it("is warmed by readPins", async () => { + const storage = new RevalidatingStorage(); + await pinMany(storage, 6); + await readPins(storage, key, "", () => null); + const get = vi.spyOn(storage, "get"); + + await readPinInfos(storage, key, ""); + expect(get).not.toHaveBeenCalled(); + }); +}); + +describe("readPins", () => { + it("lists pins newest snapshot first and names the unreadable ones", async () => { + const storage = new FakeStorage(); + await pinSnapshot(storage, key, manifestOf("old", null, {}, 1)); + await pinSnapshot(storage, key, manifestOf("new", null, {}, 2), "Kept"); + await storage.put(pinKey("bad"), new Uint8Array([1])); + // The legacy shape: a bare manifest. + await storage.put( + pinKey("legacy"), + await encryptJson(key, manifestOf("legacy", null, {})), + ); + + const read = await readPins(storage, key, "", () => null); + expect(read.pins.map(({ info }) => [info.id, info.label])).toEqual([ + ["new", "Kept"], + ["old", undefined], + ]); + expect(read.unreadable.sort()).toEqual([pinKey("bad"), pinKey("legacy")]); + }); + + it("skips a pin unpinned between its listing and its read", async () => { + const storage = new FakeStorage(); + await pinSnapshot(storage, key, manifestOf("kept", null, {}, 1)); + await pinSnapshot(storage, key, manifestOf("gone", null, {}, 2)); + const get = storage.get.bind(storage); + vi.spyOn(storage, "get").mockImplementation(async (storageKey) => + storageKey === pinKey("gone") ? null : get(storageKey), + ); + + const read = await readPins(storage, key, "", () => null); + expect(read.pins.map(({ info }) => info.id)).toEqual(["kept"]); + expect(read.unreadable).toEqual([]); + }); + + it("downloads a pin once, and again after it is rewritten", async () => { + const storage = new RevalidatingStorage(); + const pinned = manifestOf("p", null, { a: "A" }); + await pinSnapshot(storage, key, pinned, "One"); + const get = vi.spyOn(storage, "get"); + const pinGets = (): number => + get.mock.calls.filter(([got]) => got === pinKey("p")).length; + + await readPins(storage, key, "", () => null); + await readPins(storage, key, "", () => null); + expect(pinGets()).toBe(1); + + await pinSnapshot(storage, key, pinned, "Two"); + const read = await readPins(storage, key, "", () => null); + expect(read.pins[0]?.info.label).toBe("Two"); + expect(pinGets()).toBe(2); + }); + + it("downloads every time without an etag: a timestamp may not move on a rewrite", async () => { + const storage = new FakeStorage(); + await pinSnapshot(storage, key, manifestOf("p", null, {})); + const get = vi.spyOn(storage, "get"); + + await readPins(storage, key, "", () => null); + await readPins(storage, key, "", () => null); + expect(get).toHaveBeenCalledTimes(2); + }); + + it("keeps every pin of a small vault, so a second read downloads none", async () => { + const storage = new RevalidatingStorage(); + await pinMany(storage, 6); + await readPins(storage, key, "", () => null); + const get = vi.spyOn(storage, "get"); + + const read = await readPins(storage, key, "", () => null); + expect(read.pins).toHaveLength(6); + expect(get).not.toHaveBeenCalled(); + }); + + it("drops the manifest of a pin that is no longer listed", async () => { + const storage = new RevalidatingStorage(); + await pinMany(storage, 3); + await readPins(storage, key, "", () => null); + const list = storage.listDetailed.bind(storage); + vi.spyOn(storage, "listDetailed").mockImplementationOnce(async (prefix) => + (await list(prefix)).filter((object) => object.key !== pinKey("p1")), + ); + await readPins(storage, key, "", () => null); + const get = vi.spyOn(storage, "get"); + + // Listed again with the etag it had: a manifest held meanwhile would answer without a GET. + await readPins(storage, key, "", () => null); + expect(get.mock.calls).toEqual([[pinKey("p1")]]); + }); + + describe("past the cache bound", () => { + // Two of these are past the 200k file entries the cache holds; one alone is under it. + const big = (id: string, createdAt: number, count = 110_000): Manifest => + manifestOf( + id, + null, + Object.fromEntries( + Array.from({ length: count }, (_, i) => [`${id}/${i}`, `h${i}`]), + ), + createdAt, + ); + + it("drops the oldest read first and keeps the rest", async () => { + const storage = new RevalidatingStorage(); + await pinSnapshot(storage, key, big("big1", 1)); + await readPins(storage, key, "", () => null); + await pinSnapshot(storage, key, big("big2", 2)); + await readPins(storage, key, "", () => null); + const get = vi.spyOn(storage, "get"); + + await readPins(storage, key, "", () => null); + expect(get.mock.calls).toEqual([[pinKey("big1")]]); + }); + + it("keeps the pin just read even when it alone is past the bound", async () => { + const storage = new RevalidatingStorage(); + await pinSnapshot(storage, key, big("huge", 1, 200_001)); + await readPins(storage, key, "", () => null); + const get = vi.spyOn(storage, "get"); + + await readPins(storage, key, "", () => null); + expect(get).not.toHaveBeenCalled(); + }); + }); + + it("stores a share's pin in space paths and reads it back in vault paths", async () => { + const storage = new FakeStorage(); + const pinned = manifestOf("p", null, { "Shared/p/a.md": "A" }); + await writePin(storage, key, "Shared/p", { + id: "p", + manifest: pinned, + pinnedAt: 1, + }); + + const raw = await decryptJson<{ manifest: Manifest }>( + key, + (await storage.get(pinKey("p"))) as Uint8Array, + ); + expect(Object.keys(raw.manifest.files)).toEqual(["a.md"]); + const pin = await readPinById(storage, key, "Shared/p", "p"); + expect(Object.keys(pin?.manifest.files ?? {})).toEqual(["Shared/p/a.md"]); + }); +}); diff --git a/packages/plugin/tests/features/sync/history/publish.test.ts b/packages/plugin/tests/features/sync/history/publish.test.ts new file mode 100644 index 00000000..5a0b42ce --- /dev/null +++ b/packages/plugin/tests/features/sync/history/publish.test.ts @@ -0,0 +1,286 @@ +import { FakeStorage } from "@tests/helpers/fake-storage"; +import { manifestOf } from "@tests/helpers/history"; +import { beforeAll, describe, expect, it, vi } from "vitest"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; +import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; +import { objectKey, recipeKey } from "@/features/sync/content/keys"; +import { publishManifestWithHistory } from "@/features/sync/history/publish"; +import { pushKey, readHistory } from "@/features/sync/history/remote"; +import { resetRemoteStorage } from "@/features/sync/remote/reset"; + +let key: EncryptionKey; +beforeAll(async () => { + key = await deriveKey("pw", new Uint8Array(16)); +}); + +const history = { horizon: null }; + +const s1 = manifestOf("s1", null, { "a.md": "A1" }); +const s2 = manifestOf("s2", "s1", { "a.md": "A2" }); + +/** A push uploads its blobs before any record names them. */ +async function stored(): Promise { + const storage = new FakeStorage(); + for (const hash of ["A1", "A2", "L", "X"]) { + await storage.put(objectKey(hash), new Uint8Array([1])); + } + return storage; +} + +function failPutOnce(storage: FakeStorage, failing: string): void { + const put = storage.put.bind(storage); + vi.spyOn(storage, "put").mockImplementation((objectKey, body) => + objectKey === failing + ? Promise.reject(new Error("offline")) + : put(objectKey, body), + ); +} + +describe("publishManifestWithHistory", () => { + it("writes the push record, with the diff from its parent, before the manifest", async () => { + const storage = await stored(); + await publishManifestWithHistory(storage, key, "", s1, null, history); + const put = vi.spyOn(storage, "put"); + + await publishManifestWithHistory(storage, key, "", s2, s1, history); + + expect(put.mock.calls.map(([objectKey]) => objectKey)).toEqual([ + pushKey("s2"), + REMOTE_MANIFEST_KEY, + ]); + const { view } = await readHistory(storage, key, ""); + expect(view.pushes.get(pushKey("s2"))?.push.changes.modified).toEqual({ + "a.md": { from: s1.files["a.md"], to: s2.files["a.md"] }, + }); + }); + + it("publishes when the record write fails, and the next push writes it", async () => { + const storage = await stored(); + vi.spyOn(console, "warn").mockImplementation(() => {}); + failPutOnce(storage, pushKey("s1")); + + await publishManifestWithHistory(storage, key, "", s1, null, history); + expect(await storage.exists(pushKey("s1"))).toBe(false); + vi.mocked(storage.put).mockRestore(); + + await publishManifestWithHistory(storage, key, "", s2, s1, history); + expect(await storage.exists(pushKey("s1"))).toBe(true); + expect(await storage.exists(pushKey("s2"))).toBe(true); + }); + + it("keeps the record of a failed publish waiting: its manifest may have landed", async () => { + const storage = await stored(); + vi.spyOn(console, "warn").mockImplementation(() => {}); + await publishManifestWithHistory(storage, key, "", s1, null, history); + failPutOnce(storage, pushKey("lost")); + const lost = manifestOf("lost", "x", { "a.md": "L" }); + + await expect( + publishManifestWithHistory( + storage, + key, + "", + lost, + manifestOf("x", null, { "a.md": "X" }), + history, + ), + ).rejects.toThrow(/changed since the last compare/); + vi.mocked(storage.put).mockRestore(); + await publishManifestWithHistory(storage, key, "", s2, s1, history); + + expect(await storage.exists(pushKey("lost"))).toBe(true); + expect(await storage.exists(pushKey("s2"))).toBe(true); + }); + + it("retries through an adapter rebuilt for the same storage", async () => { + const storage = await stored(); + vi.spyOn(console, "warn").mockImplementation(() => {}); + failPutOnce(storage, pushKey("s1")); + await publishManifestWithHistory(storage, key, "", s1, null, history); + vi.mocked(storage.put).mockRestore(); + + // A share move or a token refresh: a new adapter over the same objects. + const rebuilt = Object.create(storage) as FakeStorage; + await publishManifestWithHistory(rebuilt, key, "", s2, s1, history); + expect(await storage.exists(pushKey("s1"))).toBe(true); + }); + + it("withholds a delayed record once a blob it names is swept", async () => { + const storage = await stored(); + vi.spyOn(console, "warn").mockImplementation(() => {}); + failPutOnce(storage, pushKey("s1")); + await publishManifestWithHistory(storage, key, "", s1, null, history); + vi.mocked(storage.put).mockRestore(); + + await storage.delete(objectKey("A1")); + await publishManifestWithHistory(storage, key, "", s2, s1, history); + expect(await storage.list("history/")).toEqual([pushKey("s2")]); + }); + + it("lands a delayed record whose blob is chunked", async () => { + const storage = await stored(); + vi.spyOn(console, "warn").mockImplementation(() => {}); + failPutOnce(storage, pushKey("s1")); + await publishManifestWithHistory(storage, key, "", s1, null, history); + vi.mocked(storage.put).mockRestore(); + + await storage.delete(objectKey("A1")); + await storage.put(recipeKey("A1"), new Uint8Array([1])); + await publishManifestWithHistory(storage, key, "", s2, s1, history); + expect(await storage.exists(pushKey("s1"))).toBe(true); + }); + + it("checks a record naming more than a listing page with a listing per root folder, not a probe per blob", async () => { + const storage = new FakeStorage("big"); + vi.spyOn(console, "warn").mockImplementation(() => {}); + const hashes = Array.from({ length: 1001 }, (_, i) => `h${i}`); + for (const hash of [...hashes, "A2"]) { + await storage.put(objectKey(hash), new Uint8Array([1])); + } + await storage.delete(objectKey("h7")); + await storage.put(recipeKey("h7"), new Uint8Array([1])); + const big = manifestOf( + "big1", + null, + Object.fromEntries(hashes.map((hash) => [`${hash}.md`, hash])), + ); + const next = manifestOf("big2", "big1", { "a.md": "A2" }); + failPutOnce(storage, pushKey("big1")); + await publishManifestWithHistory(storage, key, "", big, null, history); + vi.mocked(storage.put).mockRestore(); + storage.existsCalls = 0; + storage.listCalls = 0; + + await publishManifestWithHistory(storage, key, "", next, big, history); + + expect(storage.existsCalls).toBe(0); + expect(storage.listCalls).toBe(2); + expect(storage.map.has(pushKey("big1"))).toBe(true); + expect(storage.map.has(pushKey("big2"))).toBe(true); + }); + + it("withholds a record naming more than a listing page once one of its blobs is swept", async () => { + const storage = new FakeStorage("big-swept"); + vi.spyOn(console, "warn").mockImplementation(() => {}); + const hashes = Array.from({ length: 1001 }, (_, i) => `h${i}`); + for (const hash of [...hashes, "A2"]) { + await storage.put(objectKey(hash), new Uint8Array([1])); + } + const big = manifestOf( + "big1", + null, + Object.fromEntries(hashes.map((hash) => [`${hash}.md`, hash])), + ); + const next = manifestOf("big2", "big1", { "a.md": "A2" }); + failPutOnce(storage, pushKey("big1")); + await publishManifestWithHistory(storage, key, "", big, null, history); + vi.mocked(storage.put).mockRestore(); + + await storage.delete(objectKey("h500")); + await publishManifestWithHistory(storage, key, "", next, big, history); + + expect(await storage.list("history/")).toEqual([pushKey("big2")]); + }); + + it("withholds a delayed record of another vault", async () => { + const storage = await stored(); + vi.spyOn(console, "warn").mockImplementation(() => {}); + failPutOnce(storage, pushKey("s1")); + await publishManifestWithHistory(storage, key, "", s1, null, history); + vi.mocked(storage.put).mockRestore(); + + // Reset elsewhere, its blobs still there: only the vault tells the record apart. + await storage.delete(REMOTE_MANIFEST_KEY); + const adopted = { ...manifestOf("w1", null, {}), vaultId: "w" }; + await publishManifestWithHistory(storage, key, "", adopted, null, history); + expect(await storage.list("history/")).toEqual([pushKey("w1")]); + }); + + it("lands a delayed record after the key is unlocked again", async () => { + const storage = await stored(); + vi.spyOn(console, "warn").mockImplementation(() => {}); + failPutOnce(storage, pushKey("s1")); + await publishManifestWithHistory(storage, key, "", s1, null, history); + vi.mocked(storage.put).mockRestore(); + + const unlocked = await deriveKey("pw", new Uint8Array(16)); + await publishManifestWithHistory(storage, unlocked, "", s2, s1, history); + expect(await storage.list("history/")).toEqual([ + pushKey("s1"), + pushKey("s2"), + ]); + }); + + it("withholds a delayed record after the remote is reset", async () => { + const storage = await stored(); + vi.spyOn(console, "warn").mockImplementation(() => {}); + failPutOnce(storage, pushKey("s1")); + await publishManifestWithHistory(storage, key, "", s1, null, history); + vi.mocked(storage.put).mockRestore(); + + await resetRemoteStorage(storage); + await publishManifestWithHistory(storage, key, "", s2, null, history); + expect(await storage.list("history/")).toEqual([pushKey("s2")]); + }); + + it("leaves the configuration folder out of the record and releases its versions", async () => { + const storage = await stored(); + const before = manifestOf("c1", null, { + "a.md": "A1", + ".obsidian/plugins/x/main.js": "M1", + }); + const after = manifestOf("c2", "c1", { + "a.md": "A2", + ".obsidian/plugins/x/main.js": "M2", + }); + await publishManifestWithHistory(storage, key, "", before, null, history); + + await publishManifestWithHistory( + storage, + key, + "", + after, + before, + history, + null, + ".obsidian", + ); + + const { view } = await readHistory(storage, key, ""); + const push = view.pushes.get(pushKey("c2"))?.push; + expect(push?.changes.modified).toEqual({ + "a.md": { from: before.files["a.md"], to: after.files["a.md"] }, + }); + expect([...(push?.released ?? [])].sort()).toEqual(["M1", "M2"]); + }); + + it("writes no released list when the configuration folder did not change", async () => { + const storage = await stored(); + const config = { ".obsidian/app.json": "J1" }; + const before = manifestOf("c1", null, { "a.md": "A1", ...config }); + const after = manifestOf("c2", "c1", { "a.md": "A2", ...config }); + await publishManifestWithHistory(storage, key, "", before, null, history); + + await publishManifestWithHistory( + storage, + key, + "", + after, + before, + history, + null, + ".obsidian", + ); + + const { view } = await readHistory(storage, key, ""); + const push = view.pushes.get(pushKey("c2"))?.push; + expect(push).toBeDefined(); + expect(push && Object.hasOwn(push, "released")).toBe(false); + }); + + it("writes no record with history off", async () => { + const storage = await stored(); + await publishManifestWithHistory(storage, key, "", s1, null, undefined); + expect(await storage.list("history/")).toEqual([]); + }); +}); diff --git a/packages/plugin/tests/features/sync/history/remote.test.ts b/packages/plugin/tests/features/sync/history/remote.test.ts new file mode 100644 index 00000000..1cc1e1dd --- /dev/null +++ b/packages/plugin/tests/features/sync/history/remote.test.ts @@ -0,0 +1,109 @@ +import { FakeStorage } from "@tests/helpers/fake-storage"; +import { manifestOf, seedChain } from "@tests/helpers/history"; +import { beforeAll, describe, expect, it, vi } from "vitest"; +import { + deriveKey, + type EncryptionKey, + encryptJson, +} from "@/core/crypto/cipher"; +import { + pushKey, + readHistory, + writeHistoryObject, +} from "@/features/sync/history/remote"; + +let key: EncryptionKey; +beforeAll(async () => { + key = await deriveKey("pw", new Uint8Array(16)); +}); + +const chain = [ + manifestOf("s1", null, { "a.md": "A1" }), + manifestOf("s2", "s1", { "a.md": "A2" }), + manifestOf("s3", "s2", { "a.md": "A3" }), +]; + +async function seeded(): Promise { + const storage = new FakeStorage(); + await seedChain(storage, key, chain); + return storage; +} + +const ids = (pushes: ReadonlyMap): string[] => + [...pushes.values()].map(({ push }) => push.id).sort(); + +describe("readHistory", () => { + it("decodes each record once across reads", async () => { + const storage = await seeded(); + const get = vi.spyOn(storage, "get"); + + await readHistory(storage, key, ""); + const { view } = await readHistory(storage, key, ""); + expect(ids(view.pushes)).toEqual(["s1", "s2", "s3"]); + expect(get).toHaveBeenCalledTimes(3); + }); + + it("lists again when a record is gone before it is read", async () => { + const storage = await seeded(); + const list = vi.spyOn(storage, "listDetailed"); + const get = storage.get.bind(storage); + vi.spyOn(storage, "get").mockImplementation(async (objectKey) => { + if (objectKey !== pushKey("s2")) return get(objectKey); + await storage.delete(objectKey); + return null; + }); + + const { view, unreadable } = await readHistory(storage, key, ""); + expect(ids(view.pushes)).toEqual(["s1", "s3"]); + expect(unreadable).toEqual([]); + expect(list).toHaveBeenCalledTimes(2); + }); + + it("names what it cannot decode, a newer format too, and reads the rest", async () => { + const storage = await seeded(); + await storage.put(pushKey("s2"), new Uint8Array([1, 2, 3])); + await storage.put( + pushKey("s4"), + await encryptJson(key, { v: 2, vaultId: "v", id: "s4" }), + ); + + const { view, unreadable } = await readHistory(storage, key, ""); + expect(ids(view.pushes)).toEqual(["s1", "s3"]); + expect(unreadable.sort()).toEqual([pushKey("s2"), pushKey("s4")]); + }); + + it("reads an object under a key its content does not name as unreadable", async () => { + const storage = await seeded(); + const { key: written } = await writeHistoryObject(storage, key, "", { + vaultId: "v", + res: "counts", + group: 0, + records: [], + activity: {}, + lastId: "s1", + consumed: [pushKey("s1")], + }); + const moved = "history/b/counts-0-0000000000000000.enc"; + storage.map.set(moved, storage.map.get(written) as Uint8Array); + storage.modified.set(moved, Date.now()); + + const { view, unreadable } = await readHistory(storage, key, ""); + expect(view.objects.has(written)).toBe(true); + expect(unreadable).toEqual([moved]); + }); + + it("dates an undated record by its parent's listing, a root one by the newest", async () => { + const storage = await seeded(); + storage.modified.set(pushKey("s1"), 1_000); + storage.modified.delete(pushKey("s2")); + storage.modified.set(pushKey("s3"), 3_000); + + const { view } = await readHistory(storage, key, ""); + expect(view.pushes.get(pushKey("s2"))?.at).toBe(1_000); + + storage.modified.delete(pushKey("s1")); + const again = await readHistory(storage, key, ""); + expect(again.view.pushes.get(pushKey("s1"))?.at).toBe(3_000); + expect(again.now).toBe(3_000); + }); +}); diff --git a/packages/plugin/tests/sync/restore-vault.test.ts b/packages/plugin/tests/features/sync/history/restore-vault.test.ts similarity index 70% rename from packages/plugin/tests/sync/restore-vault.test.ts rename to packages/plugin/tests/features/sync/history/restore-vault.test.ts index 381f72d4..1d8405a0 100644 --- a/packages/plugin/tests/sync/restore-vault.test.ts +++ b/packages/plugin/tests/features/sync/history/restore-vault.test.ts @@ -1,11 +1,12 @@ import { describe, expect, it } from "vitest"; -import { planVaultRestore } from "@/sync/history/restore-vault"; +import { historyTracks } from "@/features/sync/history/changes"; +import { planVaultRestore } from "@/features/sync/history/restore-vault"; import type { EFileKind, LocalSnapshot, Manifest, ManifestEntry, -} from "@/sync/types"; +} from "@/features/sync/types"; const KIND = "vault" as EFileKind; @@ -85,6 +86,23 @@ describe("planVaultRestore", () => { expect(plan.remove).toEqual([]); }); + it("leaves a skipped path alone: unreadable here, or a second spelling of a case clash", () => { + const plan = planVaultRestore( + target({ "A.md": entry("H1"), "a.md": entry("H2"), "l.md": entry("L2") }), + local( + { "A.md": entry("H1") }, + { + skipped: [ + { path: "a.md", reason: "case-clash", other: "A.md" }, + { path: "l.md", reason: "unreadable" }, + ], + }, + ), + ); + expect(plan.write).toEqual([]); + expect(plan.ignored.sort()).toEqual(["a.md", "l.md"]); + }); + it("handles a path named like an Object member", () => { const plan = planVaultRestore( target({ toString: entry("T1") }), @@ -117,6 +135,35 @@ describe("planVaultRestore", () => { expect(plan.ignored).toEqual([".obsidian/app.json"]); }); + it("neither writes nor removes a path history does not track", () => { + const plan = planVaultRestore( + target({ + "notes/a.md": entry("A2"), + ".obsidian/app.json": entry("J2"), + }), + local({ + "notes/a.md": entry("A1"), + ".obsidian/app.json": entry("J1"), + ".obsidian/local.json": entry("L1"), + }), + undefined, + historyTracks(".obsidian"), + ); + expect(plan.write.map((w) => w.path)).toEqual(["notes/a.md"]); + expect(plan.remove).toEqual([]); + expect(plan.ignored).toEqual([]); + }); + + it("does not report an untracked path as out of scope", () => { + const plan = planVaultRestore( + target({ ".obsidian/app.json": entry("J2") }), + local({}), + (path) => !path.startsWith(".obsidian/"), + historyTracks(".obsidian"), + ); + expect(plan.ignored).toEqual([]); + }); + it("does not remove a file that differs from a written one only in case", () => { const plan = planVaultRestore( target({ "notes/a.md": entry("A1") }), diff --git a/packages/plugin/tests/features/sync/history/sweep.test.ts b/packages/plugin/tests/features/sync/history/sweep.test.ts new file mode 100644 index 00000000..67bd4ef0 --- /dev/null +++ b/packages/plugin/tests/features/sync/history/sweep.test.ts @@ -0,0 +1,214 @@ +import { FakeStorage } from "@tests/helpers/fake-storage"; +import { manifestOf, pinSnapshot, seedChain } from "@tests/helpers/history"; +import { putChunks, putRecipe } from "@tests/helpers/recipes"; +import { beforeAll, describe, expect, it, vi } from "vitest"; +import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; +import { chunkKey, objectKey, recipeKey } from "@/features/sync/content/keys"; +import { writeCandidates } from "@/features/sync/history/remote"; +import { sweepObjects } from "@/features/sync/history/sweep"; +import { SETTLED_AFTER_MS } from "@/features/sync/remote/uploads"; + +let key: EncryptionKey; +beforeAll(async () => { + key = await deriveKey("pw", new Uint8Array(16)); +}); + +const MINUTE = 60_000; +const old = manifestOf("s1", null, { "a.md": "A1" }); +const head = manifestOf("s2", "s1", { "a.md": "A2" }); + +/** HEAD names A2 and no record names anything: only a pin can hold A1. */ +async function seeded(): Promise { + const storage = new FakeStorage(); + await seedChain(storage, key, [old, head], ["s1", "s2"]); + for (const hash of ["A1", "A2", "Z"]) { + await storage.put(objectKey(hash), new Uint8Array([1])); + } + await pinSnapshot(storage, key, old); + return storage; +} + +function objectListings(storage: FakeStorage): () => number { + const listed = vi.spyOn(storage, "listDetailed"); + return () => + listed.mock.calls.filter(([prefix]) => prefix.startsWith("objects/")) + .length; +} + +describe("sweepObjects freedOnly", () => { + it("deletes the due candidate file and never lists objects/ when every freed hash is still reachable", async () => { + const storage = await seeded(); + await writeCandidates(storage, key, ["A1"]); + const [due] = await storage.list("history/g/"); + storage.age(SETTLED_AFTER_MS + MINUTE); + await writeCandidates(storage, key, ["Z"]); + const [, young] = await storage.list("history/g/"); + const listings = objectListings(storage); + const get = vi.spyOn(storage, "get"); + + expect(await sweepObjects(storage, key, "", { freedOnly: true })).toBe(0); + + expect(listings()).toBe(0); + expect(get).not.toHaveBeenCalledWith(young); + expect(await storage.list("history/g/")).toEqual([young]); + expect(storage.map.has(due as string)).toBe(false); + for (const hash of ["A1", "A2", "Z"]) { + expect(storage.map.has(objectKey(hash))).toBe(true); + } + }); + + it("lists, rechecks and deletes a freed blob nothing reaches", async () => { + const storage = await seeded(); + await writeCandidates(storage, key, ["A1", "Z"]); + storage.age(SETTLED_AFTER_MS + MINUTE); + const listings = objectListings(storage); + + expect(await sweepObjects(storage, key, "", { freedOnly: true })).toBe(1); + + expect(listings()).toBe(1); + expect(storage.map.has(objectKey("Z"))).toBe(false); + expect(storage.map.has(objectKey("A1"))).toBe(true); + expect(await storage.list("history/g/")).toEqual([]); + }); + + it("fails closed on an unreadable young candidate file when a blob could go", async () => { + const storage = await seeded(); + await writeCandidates(storage, key, ["Z"]); + storage.age(SETTLED_AFTER_MS + MINUTE); + await storage.put("history/g/young.enc", new Uint8Array([1])); + const before = [...storage.map.keys()].sort(); + + await expect( + sweepObjects(storage, key, "", { freedOnly: true }), + ).rejects.toThrow(/could not be read/); + expect([...storage.map.keys()].sort()).toEqual(before); + }); +}); + +describe("sweepObjects recheck", () => { + it("deletes nothing when another run writes a candidate file while it lists", async () => { + const storage = await seeded(); + storage.age(SETTLED_AFTER_MS + MINUTE); + const list = storage.listDetailed.bind(storage); + vi.spyOn(storage, "listDetailed").mockImplementation(async (prefix) => { + // A GC elsewhere freed Z after this sweep read history: its file is the only trace. + if (prefix.startsWith("objects/")) + await writeCandidates(storage, key, ["Z"]); + return list(prefix); + }); + + await expect(sweepObjects(storage, key, "")).rejects.toThrow( + /wrote file history/, + ); + expect(storage.map.has(objectKey("Z"))).toBe(true); + }); +}); + +describe("sweepObjects, chunked files", () => { + const part = new Uint8Array([7]); + + /** HEAD's A2 and the orphan Z are chunked and share `shared`; `loose` is named by no recipe. */ + async function chunked(): Promise { + const storage = await seeded(); + await putChunks(storage, key, { + a0: part, + z0: part, + shared: part, + loose: part, + }); + await putRecipe(storage, key, "A2", [ + ["a0", 1], + ["shared", 1], + ]); + await putRecipe(storage, key, "Z", [ + ["z0", 1], + ["shared", 1], + ]); + return storage; + } + + it("deep clean deletes orphan roots, then every settled chunk no surviving recipe names", async () => { + const storage = await chunked(); + storage.age(SETTLED_AFTER_MS + MINUTE); + const deleted: string[] = []; + const remove = storage.delete.bind(storage); + vi.spyOn(storage, "delete").mockImplementation((storageKey) => { + deleted.push(storageKey); + return remove(storageKey); + }); + + expect(await sweepObjects(storage, key, "")).toBe(4); + + expect(deleted.slice(0, 2).sort()).toEqual([ + objectKey("Z"), + recipeKey("Z"), + ]); + expect(deleted.slice(2).sort()).toEqual([ + chunkKey("loose"), + chunkKey("z0"), + ]); + for (const kept of [recipeKey("A2"), chunkKey("a0"), chunkKey("shared")]) { + expect(storage.map.has(kept)).toBe(true); + } + }); + + it("keeps the settled chunks a young recipe names, even one nothing reaches", async () => { + const storage = await chunked(); + storage.age(SETTLED_AFTER_MS + MINUTE); + await putRecipe(storage, key, "Y", [["loose", 1]]); + + await sweepObjects(storage, key, ""); + + expect(storage.map.has(recipeKey("Y"))).toBe(true); + expect(storage.map.has(chunkKey("loose"))).toBe(true); + expect(storage.map.has(chunkKey("z0"))).toBe(false); + }); + + it("deletes nothing when a surviving recipe does not read", async () => { + const storage = await chunked(); + await storage.put(recipeKey("A2"), new Uint8Array([3, 1, 2])); + storage.age(SETTLED_AFTER_MS + MINUTE); + const before = [...storage.map.keys()].sort(); + + await expect(sweepObjects(storage, key, "")).rejects.toThrow( + /could not be read/, + ); + expect([...storage.map.keys()].sort()).toEqual(before); + }); + + it("keeps the chunks of a recipe that settles while the sweep reads", async () => { + const storage = await chunked(); + await putRecipe(storage, key, "Y", [["shared", 1]]); + await writeCandidates(storage, key, ["Z", "Y"]); + storage.age(SETTLED_AFTER_MS + MINUTE); + const start = Date.now(); + storage.modified.set(recipeKey("Y"), start - SETTLED_AFTER_MS + 1000); + await putRecipe(storage, key, "A2", [["a0", 1]]); + const get = storage.get.bind(storage); + vi.spyOn(storage, "get").mockImplementation((storageKey) => { + if (storageKey === recipeKey("Z")) { + vi.spyOn(Date, "now").mockReturnValue(start + 5000); + } + return get(storageKey); + }); + + await sweepObjects(storage, key, "", { freedOnly: true }); + vi.mocked(Date.now).mockRestore(); + + expect(storage.map.has(recipeKey("Z"))).toBe(false); + expect(storage.map.has(recipeKey("Y"))).toBe(true); + expect(storage.map.has(chunkKey("shared"))).toBe(true); + }); + + it("phase 2 takes only the chunks of the recipes it deletes", async () => { + const storage = await chunked(); + await writeCandidates(storage, key, ["Z"]); + storage.age(SETTLED_AFTER_MS + MINUTE); + + expect(await sweepObjects(storage, key, "", { freedOnly: true })).toBe(3); + + expect(storage.map.has(chunkKey("z0"))).toBe(false); + expect(storage.map.has(chunkKey("shared"))).toBe(true); + expect(storage.map.has(chunkKey("loose"))).toBe(true); + }); +}); diff --git a/packages/plugin/tests/sync/anchored-hunks.test.ts b/packages/plugin/tests/features/sync/hunks/anchored-hunks.test.ts similarity index 93% rename from packages/plugin/tests/sync/anchored-hunks.test.ts rename to packages/plugin/tests/features/sync/hunks/anchored-hunks.test.ts index c4124513..fc602133 100644 --- a/packages/plugin/tests/sync/anchored-hunks.test.ts +++ b/packages/plugin/tests/features/sync/hunks/anchored-hunks.test.ts @@ -1,9 +1,8 @@ import { describe, expect, it } from "vitest"; - -import { anchoredHunks } from "@/sync/anchored-hunks"; -import { DIFF_BUDGET } from "@/sync/hunks"; -import { threeWayRegions } from "@/sync/merge-model"; -import { type DiffRange, diffRanges } from "@/utils"; +import { type DiffRange, diffRanges } from "@/core/utils/diff"; +import { anchoredHunks } from "@/features/sync/hunks/anchored-hunks"; +import { DIFF_BUDGET } from "@/features/sync/hunks/hunks"; +import { threeWayRegions } from "@/features/sync/hunks/merge-model"; /** * Rebuilds the right side from the left and the hunks; matches only if the stretches between hunks are diff --git a/packages/plugin/tests/features/sync/hunks/bounded-map.test.ts b/packages/plugin/tests/features/sync/hunks/bounded-map.test.ts new file mode 100644 index 00000000..26510086 --- /dev/null +++ b/packages/plugin/tests/features/sync/hunks/bounded-map.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from "vitest"; +import { trimOldest } from "@/features/sync/hunks/bounded-map"; + +describe("trimOldest", () => { + it("drops the oldest until the weight fits", () => { + const map = new Map([ + ["a", 3], + ["b", 3], + ["c", 3], + ]); + trimOldest(map, 6, (v) => v); + expect([...map.keys()]).toEqual(["b", "c"]); + }); + + it("keeps the newest even alone over the bound", () => { + const map = new Map([ + ["a", 1], + ["b", 10], + ]); + trimOldest(map, 5, (v) => v); + expect([...map.keys()]).toEqual(["b"]); + }); + + it("bounds the count too", () => { + const map = new Map([ + ["a", 1], + ["b", 1], + ["c", 1], + ]); + trimOldest(map, 100, (v) => v, 2); + expect([...map.keys()]).toEqual(["b", "c"]); + }); + + it("counts entries without a weight", () => { + const map = new Map([ + ["a", 0], + ["b", 0], + ]); + trimOldest(map, 1); + expect([...map.keys()]).toEqual(["b"]); + }); +}); diff --git a/packages/plugin/tests/sync/conflict-merge.test.ts b/packages/plugin/tests/features/sync/hunks/conflict-merge.test.ts similarity index 76% rename from packages/plugin/tests/sync/conflict-merge.test.ts rename to packages/plugin/tests/features/sync/hunks/conflict-merge.test.ts index f10c5059..d0bfb214 100644 --- a/packages/plugin/tests/sync/conflict-merge.test.ts +++ b/packages/plugin/tests/features/sync/hunks/conflict-merge.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { toLines } from "@/sync/merge-model"; +import { toLines } from "@/features/sync/hunks/merge-model"; describe("line helpers", () => { it("splits on LF after folding CRLF", () => { diff --git a/packages/plugin/tests/sync/diff-cache.test.ts b/packages/plugin/tests/features/sync/hunks/diff-cache.test.ts similarity index 95% rename from packages/plugin/tests/sync/diff-cache.test.ts rename to packages/plugin/tests/features/sync/hunks/diff-cache.test.ts index 77d6ca20..36da821c 100644 --- a/packages/plugin/tests/sync/diff-cache.test.ts +++ b/packages/plugin/tests/features/sync/hunks/diff-cache.test.ts @@ -1,9 +1,9 @@ import { TestSession, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; -import { DiffCache } from "@/sync/diff-cache"; -import { pushPathsOp } from "@/sync/operations/push"; -import { EDiffDirection } from "@/sync/projection"; -import { EChangeType } from "@/sync/types"; +import { DiffCache } from "@/features/sync/hunks/diff-cache"; +import { EDiffDirection } from "@/features/sync/hunks/projection"; +import { pushPathsOp } from "@/features/sync/operations/push"; +import { EChangeType } from "@/features/sync/types"; useEncryptionKey(); diff --git a/packages/plugin/tests/sync/hunks-apply.test.ts b/packages/plugin/tests/features/sync/hunks/hunks-apply.test.ts similarity index 99% rename from packages/plugin/tests/sync/hunks-apply.test.ts rename to packages/plugin/tests/features/sync/hunks/hunks-apply.test.ts index 2e9d92f6..d4f2ccce 100644 --- a/packages/plugin/tests/sync/hunks-apply.test.ts +++ b/packages/plugin/tests/features/sync/hunks/hunks-apply.test.ts @@ -5,7 +5,7 @@ import { computeHunks, type HunkSelection, wholeHunks, -} from "@/sync/hunks"; +} from "@/features/sync/hunks/hunks"; // Locks controller.history.restoreHistoryHunks: selected hunks restore OLD content, unselected keep // CURRENT. Forward/reverse hunk counts must match so the view's per-hunk index stays valid; regions sit >3 diff --git a/packages/plugin/tests/sync/hunks.test.ts b/packages/plugin/tests/features/sync/hunks/hunks.test.ts similarity index 98% rename from packages/plugin/tests/sync/hunks.test.ts rename to packages/plugin/tests/features/sync/hunks/hunks.test.ts index 2a5e934b..c09d971d 100644 --- a/packages/plugin/tests/sync/hunks.test.ts +++ b/packages/plugin/tests/features/sync/hunks/hunks.test.ts @@ -1,4 +1,6 @@ import { describe, expect, it } from "vitest"; +import { diffRanges } from "@/core/utils/diff"; +import { toLf } from "@/core/utils/eol"; import { applyHunks, complementSelection, @@ -9,8 +11,7 @@ import { type SyncHunk, selectionSize, wholeHunks, -} from "@/sync/hunks"; -import { diffRanges, toLf } from "@/utils"; +} from "@/features/sync/hunks/hunks"; describe("hunks", () => { describe("computeHunks", () => { diff --git a/packages/plugin/tests/features/sync/hunks/json-align.test.ts b/packages/plugin/tests/features/sync/hunks/json-align.test.ts new file mode 100644 index 00000000..5b806a79 --- /dev/null +++ b/packages/plugin/tests/features/sync/hunks/json-align.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it } from "vitest"; +import { alignJsonSides } from "@/features/sync/hunks/json-align"; +import { buildMergeSession } from "@/features/sync/hunks/merge-model"; + +const json = (value: unknown, indent: string | number = 2) => + JSON.stringify(value, null, indent); + +describe("alignJsonSides", () => { + it("leaves no change where only the key order differs", () => { + const local = json({ theme: "dark", font: 14, nested: { a: 1, b: 2 } }); + const remote = json({ nested: { b: 2, a: 1 }, font: 14, theme: "dark" }); + + const aligned = alignJsonSides(local, local, remote); + + expect(aligned?.remote).toBe(local); + const session = buildMergeSession( + aligned?.base ?? "", + local, + aligned?.remote ?? "", + ); + expect(session.changes).toHaveLength(0); + }); + + it("keeps real changes, with keys local lacks after local's own", () => { + const local = json({ a: 1, b: 2 }); + const remote = json({ c: 3, b: 5, a: 1 }); + + expect(alignJsonSides(local, local, remote)?.remote).toBe( + json({ a: 1, b: 5, c: 3 }), + ); + }); + + it("follows local's indent and final newline", () => { + const local = `${json({ a: 1, b: 2 }, "\t")}\n`; + const remote = json({ b: 2, a: 1 }, 4); + + expect(alignJsonSides(remote, local, remote)).toEqual({ + base: local, + remote: local, + }); + }); + + it("orders objects inside arrays by the element at the same place", () => { + const local = json({ list: [{ id: 1, name: "x" }] }); + const remote = json({ list: [{ name: "y", id: 1 }, { z: 0 }] }); + + expect(alignJsonSides(local, local, remote)?.remote).toBe( + json({ list: [{ id: 1, name: "y" }, { z: 0 }] }), + ); + }); + + it.each([ + ["text that is not JSON", "{ nope"], + ["hand formatting", '{"a": 1, "b": 2}'], + ["a big integer", '{"a": 12345678901234567890}'], + ["a number form parsing rewrites", '{\n "a": 1.0\n}'], + ])("refuses %s on any side", (_, odd) => { + const plain = json({ a: 1, b: 2 }); + + expect(alignJsonSides(odd, plain, plain)).toBeNull(); + expect(alignJsonSides(plain, odd, plain)).toBeNull(); + expect(alignJsonSides(plain, plain, odd)).toBeNull(); + }); + + it("keeps a __proto__ key as a key", () => { + const local = '{\n "__proto__": 1,\n "a": 2\n}'; + const remote = '{\n "a": 2,\n "__proto__": 3\n}'; + + expect(alignJsonSides(local, local, remote)?.remote).toBe( + '{\n "__proto__": 3,\n "a": 2\n}', + ); + }); +}); diff --git a/packages/plugin/tests/features/sync/hunks/json-merge.test.ts b/packages/plugin/tests/features/sync/hunks/json-merge.test.ts new file mode 100644 index 00000000..b28bfda4 --- /dev/null +++ b/packages/plugin/tests/features/sync/hunks/json-merge.test.ts @@ -0,0 +1,107 @@ +import { describe, expect, it } from "vitest"; +import { mergeJsonByKey } from "@/features/sync/hunks/json-merge"; + +/** As Obsidian's `saveData` writes it. */ +const json = (value: unknown, indent: string | number = 2) => + JSON.stringify(value, null, indent); + +const merge = (base: unknown, local: unknown, remote: unknown) => + mergeJsonByKey(json(base), json(local), json(remote)); + +describe("mergeJsonByKey", () => { + it.each([ + [ + "edits of different keys", + { a: 1, b: 1 }, + { a: 2, b: 1 }, + { a: 1, b: 2 }, + { a: 2, b: 2 }, + ], + [ + "edits inside one nested object", + { view: { size: 1, theme: "a" } }, + { view: { size: 2, theme: "a" } }, + { view: { size: 1, theme: "b" } }, + { view: { size: 2, theme: "b" } }, + ], + ["the same edit on both sides", { a: 1 }, { a: 2 }, { a: 2 }, { a: 2 }], + [ + "a key deleted on one side only", + { a: 1, b: 1 }, + { a: 1 }, + { a: 1, b: 1, c: 1 }, + { a: 1, c: 1 }, + ], + ["null added where nothing was", {}, { a: null }, {}, { a: null }], + [ + "an array changed on one side, whole", + { list: [1, 2], a: 1 }, + { list: [1, 2], a: 2 }, + { list: [2, 1, 3], a: 1 }, + { list: [2, 1, 3], a: 2 }, + ], + ])("merges %s", (_, base, local, remote, merged) => { + expect(merge(base, local, remote)).toBe(json(merged)); + }); + + it.each([ + ["different edits of one key", { a: 1 }, { a: 2 }, { a: 3 }], + ["a deletion against an edit", { a: 1 }, {}, { a: 2 }], + ["null against a deletion", { a: 1 }, { a: null }, {}], + ["one key added with two values", {}, { a: 1 }, { a: 2 }], + [ + "two edits of one array", + { list: [1] }, + { list: [1, 2] }, + { list: [0, 1] }, + ], + ["an object against a scalar", { a: { b: 1 } }, { a: { b: 2 } }, { a: 5 }], + ])("leaves %s to a person", (_, base, local, remote) => { + expect(merge(base, local, remote)).toBeNull(); + }); + + it("keeps local's key order, remote's new keys after it in their order", () => { + const base = { a: 1, b: 1 }; + const local = { b: 2, a: 1 }; + const remote = { a: 1, b: 1, z: 1, y: 1 }; + expect(merge(base, local, remote)).toBe( + '{\n "b": 2,\n "a": 1,\n "z": 1,\n "y": 1\n}', + ); + }); + + it("takes a reorder alone as no edit", () => { + expect(merge({ a: 1, b: 1 }, { b: 1, a: 1 }, { a: 2, b: 1 })).toBe( + json({ b: 1, a: 2 }), + ); + }); + + it("writes local's indent and final newline", () => { + const base = json({ a: 1, b: 1 }, "\t"); + const local = `${json({ a: 2, b: 1 }, "\t")}\n`; + const remote = json({ a: 1, b: 2 }, "\t"); + expect(mergeJsonByKey(base, local, remote)).toBe( + `${json({ a: 2, b: 2 }, "\t")}\n`, + ); + }); + + it("keeps a __proto__ key as a key", () => { + const base = '{\n "__proto__": 1,\n "a": 1\n}'; + const local = '{\n "__proto__": 1,\n "a": 2\n}'; + const remote = '{\n "__proto__": 2,\n "a": 1\n}'; + expect(mergeJsonByKey(base, local, remote)).toBe( + '{\n "__proto__": 2,\n "a": 2\n}', + ); + }); + + it.each([ + ["a side that is not JSON", "{", json({ a: 1 })], + ["a side not written by JSON.stringify", '{ "a": 2 }', json({ a: 1 })], + [ + "an integer JavaScript would round", + '{\n "id": 12345678901234567890\n}', + json({ id: 1 }), + ], + ])("refuses %s", (_, local, remote) => { + expect(mergeJsonByKey(json({ a: 1 }), local, remote)).toBeNull(); + }); +}); diff --git a/packages/plugin/tests/features/sync/hunks/merge-model.test.ts b/packages/plugin/tests/features/sync/hunks/merge-model.test.ts new file mode 100644 index 00000000..fac3b5d9 --- /dev/null +++ b/packages/plugin/tests/features/sync/hunks/merge-model.test.ts @@ -0,0 +1,131 @@ +import { describe, expect, it } from "vitest"; +import { + buildMergeSession, + countUnresolved, + threeWayRegions, +} from "@/features/sync/hunks/merge-model"; + +describe("threeWayRegions", () => { + it("gives every region all three ranges; the unchanged side owns the base lines", () => { + const regions = threeWayRegions( + ["a", "b", "c"], + ["a", "B", "c"], + ["a", "b", "c", "d"], + ); + expect(regions).toEqual([ + { + base: [1, 2], + local: [1, 2], + remote: [1, 2], + changed: { local: true, remote: false }, + }, + { + base: [3, 3], + local: [3, 3], + remote: [3, 4], + changed: { local: false, remote: true }, + }, + ]); + }); + + it("merges touching hunks from both sides into one region, like diff3", () => { + // Local inserts before "b" while remote rewrites "b": adjacent, so one region. + const regions = threeWayRegions( + ["a", "b", "c"], + ["a", "X", "b", "c"], + ["a", "B", "c"], + ); + expect(regions).toEqual([ + { + base: [1, 2], + local: [1, 3], + remote: [1, 2], + changed: { local: true, remote: true }, + }, + ]); + }); + + it("keeps a side past the diff budget as one region around its differing middle", () => { + const base = Array.from({ length: 2000 }, (_, i) => `line ${i}`); + const local = base.map((line, i) => + i === 0 || i === 1999 ? line : `${line} local`, + ); + expect(threeWayRegions(base, local, base)).toEqual([ + { + base: [1, 1999], + local: [1, 1999], + remote: [1, 1999], + changed: { local: true, remote: false }, + }, + ]); + }); +}); + +describe("buildMergeSession", () => { + it("applies one-sided edits up front and marks them applied", () => { + const base = "one\ntwo\nthree\nfour\nfive\n"; + const local = "one\nTWO\nthree\nfour\nfive\nsix\n"; + const remote = "one\ntwo\nthree\nFOUR\nfive\n"; + const session = buildMergeSession(base, local, remote); + expect(session.text).toBe("one\nTWO\nthree\nFOUR\nfive\nsix\n"); + expect(session.changes.map((c) => c.conflict)).toEqual([ + false, + false, + false, + ]); + expect(session.changes.map((c) => c.status)).toEqual([ + { local: "applied", remote: "none" }, + { local: "none", remote: "applied" }, + { local: "applied", remote: "none" }, + ]); + const spans = session.changes.map((c) => + session.text.slice(c.result.from, c.result.to), + ); + expect(spans).toEqual(["TWO\n", "FOUR\n", "six\n"]); + }); + + it("keeps the base lines where both sides disagree and leaves both sides open", () => { + const session = buildMergeSession("a\nb\nc", "a\nL\nc", "a\nR\nc"); + expect(session.text).toBe("a\nb\nc"); + expect(session.changes).toEqual([ + { + index: 0, + conflict: true, + base: [1, 2], + endsAtEof: false, + local: [1, 2], + remote: [1, 2], + result: { from: 2, to: 4 }, + taken: {}, + status: { local: "open", remote: "open" }, + }, + ]); + expect(countUnresolved(session.changes)).toBe(1); + }); + + it("treats the same edit on both sides as one applied change", () => { + const session = buildMergeSession("a\nb", "a\nB", "a\nB"); + expect(session.text).toBe("a\nB"); + expect(session.changes[0]?.conflict).toBe(false); + expect(session.changes[0]?.status).toEqual({ + local: "applied", + remote: "applied", + }); + }); + + it("puts a conflict appended to a file without final newline at the doc end", () => { + const session = buildMergeSession("a", "a\nL", "a\nR"); + expect(session.text).toBe("a"); + expect(session.changes[0]?.result).toEqual({ from: 1, to: 1 }); + }); + + it("compares on LF so CRLF on one side is not one whole conflict", () => { + const session = buildMergeSession( + "a\nb\nc\nd\ne", + "a\r\nLOCAL\r\nc\r\nd\r\ne", + "a\nb\nc\nREMOTE\ne", + ); + expect(session.text).toBe("a\nLOCAL\nc\nREMOTE\ne"); + expect(countUnresolved(session.changes)).toBe(0); + }); +}); diff --git a/packages/plugin/tests/sync/operations-hunks.test.ts b/packages/plugin/tests/features/sync/hunks/operations-hunks.test.ts similarity index 96% rename from packages/plugin/tests/sync/operations-hunks.test.ts rename to packages/plugin/tests/features/sync/hunks/operations-hunks.test.ts index c212e1d8..f74b2824 100644 --- a/packages/plugin/tests/sync/operations-hunks.test.ts +++ b/packages/plugin/tests/features/sync/hunks/operations-hunks.test.ts @@ -4,14 +4,17 @@ import { useEncryptionKey, } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; -import { sha256Hex } from "@/crypto"; -import { textToBytes } from "@/sync/content"; -import { computeHunks, type HunkSelection } from "@/sync/hunks"; -import { EHunkPair, loadHunkSides } from "@/sync/operations"; -import { localHunksOp, pullHunksOp } from "@/sync/operations/hunks"; -import { pushPathsOp } from "@/sync/operations/push"; -import { batchAcceptRemoteOp } from "@/sync/operations/resolve"; -import { recomputeAfterWrite } from "@/sync/session-state"; +import { sha256Hex } from "@/core/crypto/cipher"; +import { textToBytes } from "@/features/sync/changes/content"; +import { computeHunks, type HunkSelection } from "@/features/sync/hunks/hunks"; +import { localHunksOp, pullHunksOp } from "@/features/sync/operations/hunks"; +import { pushPathsOp } from "@/features/sync/operations/push"; +import { batchAcceptRemoteOp } from "@/features/sync/operations/resolve"; +import { + EHunkPair, + loadHunkSides, +} from "@/features/sync/operations/text-loaders"; +import { recomputeAfterWrite } from "@/features/sync/session-state"; useEncryptionKey(); diff --git a/packages/plugin/tests/sync/projection-absent.test.ts b/packages/plugin/tests/features/sync/hunks/projection-absent.test.ts similarity index 96% rename from packages/plugin/tests/sync/projection-absent.test.ts rename to packages/plugin/tests/features/sync/hunks/projection-absent.test.ts index bf756d90..0fc05970 100644 --- a/packages/plugin/tests/sync/projection-absent.test.ts +++ b/packages/plugin/tests/features/sync/hunks/projection-absent.test.ts @@ -6,10 +6,13 @@ import { type EncryptionKey, encryptBytes, sha256Hex, -} from "@/crypto"; -import { HUNK_TEXT_MAX_BYTES } from "@/sync/constants"; -import { textToBytes } from "@/sync/content"; -import { buildHistoryDiff, type HistoryDiffRequest } from "@/sync/projection"; +} from "@/core/crypto/cipher"; +import { textToBytes } from "@/features/sync/changes/content"; +import { HUNK_TEXT_MAX_BYTES } from "@/features/sync/constants"; +import { + buildHistoryDiff, + type HistoryDiffRequest, +} from "@/features/sync/hunks/projection"; let key: EncryptionKey; beforeAll(async () => { diff --git a/packages/plugin/tests/sync/projection-binary.test.ts b/packages/plugin/tests/features/sync/hunks/projection-binary.test.ts similarity index 89% rename from packages/plugin/tests/sync/projection-binary.test.ts rename to packages/plugin/tests/features/sync/hunks/projection-binary.test.ts index 39e15bfa..901bd6ab 100644 --- a/packages/plugin/tests/sync/projection-binary.test.ts +++ b/packages/plugin/tests/features/sync/hunks/projection-binary.test.ts @@ -1,10 +1,16 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; import { beforeAll, describe, expect, it } from "vitest"; -import { deriveKey, type EncryptionKey } from "@/crypto"; -import { FORCE_DIFF_MAX_BYTES, HUNK_TEXT_MAX_BYTES } from "@/sync/constants"; -import { buildLocalChangeDiff, type ProjectionDeps } from "@/sync/projection"; -import { EChangeType, type FileChange } from "@/sync/types"; +import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; +import { + FORCE_DIFF_MAX_BYTES, + HUNK_TEXT_MAX_BYTES, +} from "@/features/sync/constants"; +import { + buildLocalChangeDiff, + type ProjectionDeps, +} from "@/features/sync/hunks/projection"; +import { EChangeType, type FileChange } from "@/features/sync/types"; let key: EncryptionKey; beforeAll(async () => { diff --git a/packages/plugin/tests/sync/projection-lazy.test.ts b/packages/plugin/tests/features/sync/hunks/projection-lazy.test.ts similarity index 95% rename from packages/plugin/tests/sync/projection-lazy.test.ts rename to packages/plugin/tests/features/sync/hunks/projection-lazy.test.ts index 8959e17a..922b75cb 100644 --- a/packages/plugin/tests/sync/projection-lazy.test.ts +++ b/packages/plugin/tests/features/sync/hunks/projection-lazy.test.ts @@ -1,22 +1,25 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; import { beforeAll, describe, expect, it } from "vitest"; -import { deriveKey, type EncryptionKey } from "@/crypto"; -import { HUNK_TEXT_MAX_BYTES, MANIFEST_VERSION } from "@/sync/constants"; -import { hasKnownBinaryExtension } from "@/sync/content"; +import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; +import { hasKnownBinaryExtension } from "@/features/sync/changes/content"; +import { + HUNK_TEXT_MAX_BYTES, + MANIFEST_VERSION, +} from "@/features/sync/constants"; import { buildConflictDiff, buildLocalChangeDiff, buildRemoteChangeDiff, type ProjectionDeps, -} from "@/sync/projection"; +} from "@/features/sync/hunks/projection"; import { type Conflict, EChangeType, EFileKind, type FileChange, type Manifest, -} from "@/sync/types"; +} from "@/features/sync/types"; let key: EncryptionKey; beforeAll(async () => { diff --git a/packages/plugin/tests/sync/authors.test.ts b/packages/plugin/tests/features/sync/identity/authors.test.ts similarity index 91% rename from packages/plugin/tests/sync/authors.test.ts rename to packages/plugin/tests/features/sync/identity/authors.test.ts index 3c2c601a..b344fb33 100644 --- a/packages/plugin/tests/sync/authors.test.ts +++ b/packages/plugin/tests/features/sync/identity/authors.test.ts @@ -1,7 +1,15 @@ import { describe, expect, it } from "vitest"; -import { attribute, authorOf, publisher } from "@/sync/authors"; -import { EFileKind, type Manifest, type ManifestEntry } from "@/sync/types"; +import { + attribute, + authorOf, + publisher, +} from "@/features/sync/identity/authors"; +import { + EFileKind, + type Manifest, + type ManifestEntry, +} from "@/features/sync/types"; const ALEX = { key: "p1", name: "Alex" }; const SAM = { key: "p2", name: "Sam" }; diff --git a/packages/plugin/tests/core/device-name.test.ts b/packages/plugin/tests/features/sync/identity/device-name.test.ts similarity index 85% rename from packages/plugin/tests/core/device-name.test.ts rename to packages/plugin/tests/features/sync/identity/device-name.test.ts index e5ed7660..ee0c6316 100644 --- a/packages/plugin/tests/core/device-name.test.ts +++ b/packages/plugin/tests/features/sync/identity/device-name.test.ts @@ -1,9 +1,8 @@ import { describe, expect, it, vi } from "vitest"; - -import { DeviceName } from "@/core/device-name"; -import type { StatePersister } from "@/core/state-persister"; -import { defaultDeviceName } from "@/sync/device"; -import type { LocalState } from "@/sync/types"; +import { defaultDeviceName } from "@/features/sync/identity/device"; +import { DeviceName } from "@/features/sync/identity/device-name"; +import type { StatePersister } from "@/features/sync/recovery/state-persister"; +import type { LocalState } from "@/features/sync/types"; describe("DeviceName", () => { it("reads the name out of the loaded state", () => { diff --git a/packages/plugin/tests/sync/manifest-device.test.ts b/packages/plugin/tests/features/sync/identity/manifest-device.test.ts similarity index 57% rename from packages/plugin/tests/sync/manifest-device.test.ts rename to packages/plugin/tests/features/sync/identity/manifest-device.test.ts index 4ae42ac1..905bb5a8 100644 --- a/packages/plugin/tests/sync/manifest-device.test.ts +++ b/packages/plugin/tests/features/sync/identity/manifest-device.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; -import { defaultDeviceName } from "@/sync/device"; -import { buildManifest } from "@/sync/manifest"; +import { MANIFEST_VERSION } from "@/features/sync/constants"; +import { defaultDeviceName } from "@/features/sync/identity/device"; +import { buildManifest } from "@/features/sync/remote/manifest"; const snapshot = { files: {}, @@ -24,3 +25,17 @@ describe("buildManifest deviceName", () => { expect(m.deviceName).toBe(defaultDeviceName()); }); }); + +describe("buildManifest version", () => { + it("publishes MANIFEST_VERSION over an older parent, so 1.x clients refuse it", () => { + const parent = buildManifest("dev1", "d", "v", null, snapshot); + const m = buildManifest( + "dev1", + "d", + "v", + { ...parent, version: 2 }, + snapshot, + ); + expect(m.version).toBe(MANIFEST_VERSION); + }); +}); diff --git a/packages/plugin/tests/sync/live-notes.test.ts b/packages/plugin/tests/features/sync/live-notes.test.ts similarity index 95% rename from packages/plugin/tests/sync/live-notes.test.ts rename to packages/plugin/tests/features/sync/live-notes.test.ts index 49dcfdfb..33be3fea 100644 --- a/packages/plugin/tests/sync/live-notes.test.ts +++ b/packages/plugin/tests/features/sync/live-notes.test.ts @@ -5,13 +5,17 @@ import { } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; -import { sha256Hex } from "@/crypto"; -import { autoMergeOp } from "@/sync/auto-merge"; -import { textToBytes } from "@/sync/content"; -import type { IncomingText, LiveNotes, LiveTake } from "@/sync/live-notes"; -import { pullPathsOp } from "@/sync/operations/pull"; -import { pushPathsOp } from "@/sync/operations/push"; -import type { LiveMark } from "@/sync/types"; +import { sha256Hex } from "@/core/crypto/cipher"; +import { autoMergeOp } from "@/features/sync/apply/auto-merge"; +import { textToBytes } from "@/features/sync/changes/content"; +import type { + IncomingText, + LiveNotes, + LiveTake, +} from "@/features/sync/live-notes"; +import { pullPathsOp } from "@/features/sync/operations/pull"; +import { pushPathsOp } from "@/features/sync/operations/push"; +import type { LiveMark } from "@/features/sync/types"; useEncryptionKey(); diff --git a/packages/plugin/tests/sync/moves.test.ts b/packages/plugin/tests/features/sync/moves.test.ts similarity index 97% rename from packages/plugin/tests/sync/moves.test.ts rename to packages/plugin/tests/features/sync/moves.test.ts index c9ec186e..c14bfdf6 100644 --- a/packages/plugin/tests/sync/moves.test.ts +++ b/packages/plugin/tests/features/sync/moves.test.ts @@ -6,11 +6,11 @@ import { useEncryptionKey, } from "@tests/helpers/session"; import { describe, expect, it, vi } from "vitest"; -import { REMOTE_OBJECTS_PREFIX } from "@/sync/constants"; -import { SyncController } from "@/sync/controller"; -import type { LiveNotes } from "@/sync/live-notes"; -import { pushPathsOp } from "@/sync/operations/push"; -import { pullPaths } from "@/sync/pull"; +import { pullPaths } from "@/features/sync/apply/pull"; +import { REMOTE_OBJECTS_PREFIX } from "@/features/sync/constants"; +import { SyncController } from "@/features/sync/controller"; +import type { LiveNotes } from "@/features/sync/live-notes"; +import { pushPathsOp } from "@/features/sync/operations/push"; useEncryptionKey(); diff --git a/packages/plugin/tests/sync/drawings.test.ts b/packages/plugin/tests/features/sync/operations/drawings.test.ts similarity index 88% rename from packages/plugin/tests/sync/drawings.test.ts rename to packages/plugin/tests/features/sync/operations/drawings.test.ts index 8f105dcb..b65f3957 100644 --- a/packages/plugin/tests/sync/drawings.test.ts +++ b/packages/plugin/tests/features/sync/operations/drawings.test.ts @@ -1,12 +1,12 @@ import { pairedSessions, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; -import { readDrawing } from "@/drawing"; -import { autoMergeOp } from "@/sync/auto-merge"; -import { textToBytes } from "@/sync/content"; -import { pushSingleFile } from "@/sync/engine"; -import { pushPathsOp } from "@/sync/operations/push"; -import { batchKeepLocalOp } from "@/sync/operations/resolve"; +import { readDrawing } from "@/core/drawing/format"; +import { autoMergeOp } from "@/features/sync/apply/auto-merge"; +import { textToBytes } from "@/features/sync/changes/content"; +import { pushSingleFile } from "@/features/sync/engine"; +import { pushPathsOp } from "@/features/sync/operations/push"; +import { batchKeepLocalOp } from "@/features/sync/operations/resolve"; useEncryptionKey(); diff --git a/packages/plugin/tests/sync/empty-folders.test.ts b/packages/plugin/tests/features/sync/operations/empty-folders.test.ts similarity index 92% rename from packages/plugin/tests/sync/empty-folders.test.ts rename to packages/plugin/tests/features/sync/operations/empty-folders.test.ts index ea252a80..866e0a0e 100644 --- a/packages/plugin/tests/sync/empty-folders.test.ts +++ b/packages/plugin/tests/features/sync/operations/empty-folders.test.ts @@ -5,9 +5,9 @@ import { } from "@tests/helpers/session"; import { describe, expect, it, vi } from "vitest"; -import { compare } from "@/sync/engine"; -import { pullPathsOp } from "@/sync/operations/pull"; -import { pushPathsOp } from "@/sync/operations/push"; +import { compare } from "@/features/sync/engine"; +import { pullPathsOp } from "@/features/sync/operations/pull"; +import { pushPathsOp } from "@/features/sync/operations/push"; useEncryptionKey(); diff --git a/packages/plugin/tests/sync/live-operations.test.ts b/packages/plugin/tests/features/sync/operations/live-operations.test.ts similarity index 91% rename from packages/plugin/tests/sync/live-operations.test.ts rename to packages/plugin/tests/features/sync/operations/live-operations.test.ts index 94f714b9..3fd70fb7 100644 --- a/packages/plugin/tests/sync/live-operations.test.ts +++ b/packages/plugin/tests/features/sync/operations/live-operations.test.ts @@ -1,11 +1,11 @@ import type { TestSession } from "@tests/helpers/session"; import { pairedSessions, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it, vi } from "vitest"; -import type { CompareResult } from "@/sync/engine"; -import type { LiveNotes } from "@/sync/live-notes"; -import { pushPathsOp } from "@/sync/operations/push"; -import { batchAcceptRemoteOp } from "@/sync/operations/resolve"; -import { revertPathsOp } from "@/sync/operations/revert"; +import type { CompareResult } from "@/features/sync/engine"; +import type { LiveNotes } from "@/features/sync/live-notes"; +import { pushPathsOp } from "@/features/sync/operations/push"; +import { batchAcceptRemoteOp } from "@/features/sync/operations/resolve"; +import { revertPathsOp } from "@/features/sync/operations/revert"; useEncryptionKey(); diff --git a/packages/plugin/tests/sync/lost-push.test.ts b/packages/plugin/tests/features/sync/operations/lost-push.test.ts similarity index 88% rename from packages/plugin/tests/sync/lost-push.test.ts rename to packages/plugin/tests/features/sync/operations/lost-push.test.ts index 145f379a..856d4d36 100644 --- a/packages/plugin/tests/sync/lost-push.test.ts +++ b/packages/plugin/tests/features/sync/operations/lost-push.test.ts @@ -1,11 +1,14 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { TestSession, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; -import { encryptJson } from "@/crypto"; -import { REMOTE_MANIFEST_KEY } from "@/sync/constants"; -import { ConcurrentPushError, fetchRemoteManifest } from "@/sync/manifest"; -import { pushPathsOp } from "@/sync/operations/push"; -import { EChangeType } from "@/sync/types"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; +import { encryptJson } from "@/core/crypto/cipher"; +import { pushPathsOp } from "@/features/sync/operations/push"; +import { + ConcurrentPushError, + fetchRemoteManifest, +} from "@/features/sync/remote/manifest"; +import { EChangeType } from "@/features/sync/types"; useEncryptionKey(); diff --git a/packages/plugin/tests/sync/operations-batch.test.ts b/packages/plugin/tests/features/sync/operations/operations-batch.test.ts similarity index 93% rename from packages/plugin/tests/sync/operations-batch.test.ts rename to packages/plugin/tests/features/sync/operations/operations-batch.test.ts index 2f30339f..accb728b 100644 --- a/packages/plugin/tests/sync/operations-batch.test.ts +++ b/packages/plugin/tests/features/sync/operations/operations-batch.test.ts @@ -1,21 +1,21 @@ import type { TestSession } from "@tests/helpers/session"; import { pairedSessions, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; -import { compare } from "@/sync/engine"; -import { pullPathsOp } from "@/sync/operations/pull"; -import { pushPathsOp } from "@/sync/operations/push"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import { pullPaths } from "@/features/sync/apply/pull"; +import { compare } from "@/features/sync/engine"; +import { pullPathsOp } from "@/features/sync/operations/pull"; +import { pushPathsOp } from "@/features/sync/operations/push"; import { batchAcceptRemoteOp, batchKeepLocalOp, keepBothConflictOp, saveMergedOp, -} from "@/sync/operations/resolve"; -import { revertPathsOp } from "@/sync/operations/revert"; -import { pullPaths } from "@/sync/pull"; -import { recomputeAfterWrite } from "@/sync/session-state"; -import { createIgnoreMatcher } from "@/vault/ignore"; -import { createScopePolicy } from "@/vault/scope"; +} from "@/features/sync/operations/resolve"; +import { revertPathsOp } from "@/features/sync/operations/revert"; +import { createIgnoreMatcher } from "@/features/sync/scope/ignore"; +import { createScopePolicy } from "@/features/sync/scope/scope"; +import { recomputeAfterWrite } from "@/features/sync/session-state"; useEncryptionKey(); @@ -456,12 +456,12 @@ describe("batch operations", () => { describe("saving a merge resolution", () => { const SHARED = "one\ntwo\nthree\nfour\nfive\nsix\n"; - async function conflicted() { - const [a, b] = await syncedPair({ "note.md": SHARED }); - b.adapter.putText("note.md", SHARED.replace("one", "ONE")); + async function conflicted(path = "note.md") { + const [a, b] = await syncedPair({ [path]: SHARED }); + b.adapter.putText(path, SHARED.replace("one", "ONE")); const bResult = await b.compare(); - await pushPathsOp(b.deps(), bResult, ["note.md"], b.context()); - a.adapter.putText("note.md", SHARED.replace("six", "SIX")); + await pushPathsOp(b.deps(), bResult, [path], b.context()); + a.adapter.putText(path, SHARED.replace("six", "SIX")); const result = await a.compare(); const [conflict] = result.diff.conflicts; if (!conflict) throw new Error("expected a conflict"); @@ -522,6 +522,22 @@ describe("saving a merge resolution", () => { expect(a.text("note.md")).toBe("typed meanwhile\n"); }); + it("refuses a JSON result that does not parse, writing and publishing nothing", async () => { + const { a, result, expected } = await conflicted("data.json"); + + await expect( + saveMergedOp( + a.deps(), + result, + { path: "data.json", content: '{"a": 1,}', expected }, + a.context(), + ), + ).rejects.toThrow(/not valid JSON/); + expect(a.text("data.json")).toBe(SHARED.replace("six", "SIX")); + const after = await a.compare(); + expect(after.diff.conflicts.map((c) => c.path)).toEqual(["data.json"]); + }); + it("refuses when the conflict is gone", async () => { const { a, expected } = await conflicted(); a.adapter.putText("note.md", SHARED.replace("one", "ONE")); diff --git a/packages/plugin/tests/sync/pull-size-limit.test.ts b/packages/plugin/tests/features/sync/operations/pull-size-limit.test.ts similarity index 86% rename from packages/plugin/tests/sync/pull-size-limit.test.ts rename to packages/plugin/tests/features/sync/operations/pull-size-limit.test.ts index f4b30eb7..66ce50a7 100644 --- a/packages/plugin/tests/sync/pull-size-limit.test.ts +++ b/packages/plugin/tests/features/sync/operations/pull-size-limit.test.ts @@ -1,8 +1,8 @@ import { pairedSessions, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; -import { pullPathsOp } from "@/sync/operations/pull"; -import { pushPathsOp } from "@/sync/operations/push"; +import { pullPathsOp } from "@/features/sync/operations/pull"; +import { pushPathsOp } from "@/features/sync/operations/push"; useEncryptionKey(); diff --git a/packages/plugin/tests/sync/remote-names.test.ts b/packages/plugin/tests/features/sync/operations/remote-names.test.ts similarity index 96% rename from packages/plugin/tests/sync/remote-names.test.ts rename to packages/plugin/tests/features/sync/operations/remote-names.test.ts index bbb1acae..d83177a4 100644 --- a/packages/plugin/tests/sync/remote-names.test.ts +++ b/packages/plugin/tests/features/sync/operations/remote-names.test.ts @@ -2,9 +2,9 @@ import type { TestSession } from "@tests/helpers/session"; import { pairedSessions, useEncryptionKey } from "@tests/helpers/session"; import { Platform } from "obsidian"; import { describe, expect, it } from "vitest"; -import { compare } from "@/sync/engine"; -import { pullPathsOp } from "@/sync/operations/pull"; -import { pushPathsOp } from "@/sync/operations/push"; +import { compare } from "@/features/sync/engine"; +import { pullPathsOp } from "@/features/sync/operations/pull"; +import { pushPathsOp } from "@/features/sync/operations/push"; useEncryptionKey(); diff --git a/packages/plugin/tests/sync/push-hunks.test.ts b/packages/plugin/tests/features/sync/push-hunks.test.ts similarity index 93% rename from packages/plugin/tests/sync/push-hunks.test.ts rename to packages/plugin/tests/features/sync/push-hunks.test.ts index ffffac8d..4c1e5392 100644 --- a/packages/plugin/tests/sync/push-hunks.test.ts +++ b/packages/plugin/tests/features/sync/push-hunks.test.ts @@ -1,7 +1,7 @@ import { createTestControllerHost } from "@tests/helpers/controller"; import { pairedSessions, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; -import { SyncController } from "@/sync/controller"; +import { SyncController } from "@/features/sync/controller"; useEncryptionKey(); diff --git a/packages/plugin/tests/sync/cut-short-baseline.test.ts b/packages/plugin/tests/features/sync/recovery/cut-short-baseline.test.ts similarity index 91% rename from packages/plugin/tests/sync/cut-short-baseline.test.ts rename to packages/plugin/tests/features/sync/recovery/cut-short-baseline.test.ts index 853aac30..73930d38 100644 --- a/packages/plugin/tests/sync/cut-short-baseline.test.ts +++ b/packages/plugin/tests/features/sync/recovery/cut-short-baseline.test.ts @@ -14,20 +14,23 @@ import { useEncryptionKey, } from "@tests/helpers/session"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { sha256Hex } from "@/crypto"; -import { autoMergeOp } from "@/sync/auto-merge"; -import { textToBytes } from "@/sync/content"; -import { SyncController } from "@/sync/controller"; -import { restoreCutShort, settleLanded } from "@/sync/cut-short"; -import { compare } from "@/sync/engine"; -import { type BaseStep, WriteJournal } from "@/sync/journal"; -import type { LiveNotes } from "@/sync/live-notes"; -import { pullPathsOp } from "@/sync/operations/pull"; -import { pushPathsOp } from "@/sync/operations/push"; -import { batchAcceptRemoteOp } from "@/sync/operations/resolve"; -import { pullPaths } from "@/sync/pull"; -import { VAULT_SPACE } from "@/sync/space"; -import type { SessionState } from "@/sync/types"; +import { sha256Hex } from "@/core/crypto/cipher"; +import { autoMergeOp } from "@/features/sync/apply/auto-merge"; +import { pullPaths } from "@/features/sync/apply/pull"; +import { textToBytes } from "@/features/sync/changes/content"; +import { SyncController } from "@/features/sync/controller"; +import { compare } from "@/features/sync/engine"; +import type { LiveNotes } from "@/features/sync/live-notes"; +import { pullPathsOp } from "@/features/sync/operations/pull"; +import { pushPathsOp } from "@/features/sync/operations/push"; +import { batchAcceptRemoteOp } from "@/features/sync/operations/resolve"; +import { + restoreCutShort, + settleLanded, +} from "@/features/sync/recovery/cut-short"; +import { type BaseStep, WriteJournal } from "@/features/sync/recovery/journal"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; +import type { SessionState } from "@/features/sync/types"; useEncryptionKey(); afterEach(() => vi.restoreAllMocks()); diff --git a/packages/plugin/tests/sync/cut-short.test.ts b/packages/plugin/tests/features/sync/recovery/cut-short.test.ts similarity index 96% rename from packages/plugin/tests/sync/cut-short.test.ts rename to packages/plugin/tests/features/sync/recovery/cut-short.test.ts index 682cc5e7..16ed2788 100644 --- a/packages/plugin/tests/sync/cut-short.test.ts +++ b/packages/plugin/tests/features/sync/recovery/cut-short.test.ts @@ -14,18 +14,18 @@ import { useEncryptionKey, } from "@tests/helpers/session"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { sha256Hex } from "@/crypto"; -import { textToBytes } from "@/sync/content"; -import { restoreCutShort } from "@/sync/cut-short"; -import { compare } from "@/sync/engine"; +import { sha256Hex } from "@/core/crypto/cipher"; +import { pullPaths } from "@/features/sync/apply/pull"; +import { textToBytes } from "@/features/sync/changes/content"; +import { compare } from "@/features/sync/engine"; +import type { LiveNotes } from "@/features/sync/live-notes"; +import { restoreCutShort } from "@/features/sync/recovery/cut-short"; import { type Intent, UnfinishedWriteError, WriteJournal, -} from "@/sync/journal"; -import type { LiveNotes } from "@/sync/live-notes"; -import { pullPaths } from "@/sync/pull"; -import { VAULT_SPACE } from "@/sync/space"; +} from "@/features/sync/recovery/journal"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; useEncryptionKey(); afterEach(() => vi.restoreAllMocks()); diff --git a/packages/plugin/tests/core/state-persister.test.ts b/packages/plugin/tests/features/sync/recovery/state-persister.test.ts similarity index 98% rename from packages/plugin/tests/core/state-persister.test.ts rename to packages/plugin/tests/features/sync/recovery/state-persister.test.ts index 89d8aa7a..75780bfd 100644 --- a/packages/plugin/tests/core/state-persister.test.ts +++ b/packages/plugin/tests/features/sync/recovery/state-persister.test.ts @@ -1,7 +1,11 @@ import { describe, expect, it, vi } from "vitest"; -import { StatePersister } from "@/core/state-persister"; -import { loadState, serializeState, stateFilePath } from "@/sync/state"; -import type { LocalState } from "@/sync/types"; +import { StatePersister } from "@/features/sync/recovery/state-persister"; +import { + loadState, + serializeState, + stateFilePath, +} from "@/features/sync/state"; +import type { LocalState } from "@/features/sync/types"; describe("StatePersister.load", () => { const stored = createState({ diff --git a/packages/plugin/tests/sync/baseline.test.ts b/packages/plugin/tests/features/sync/remote/baseline.test.ts similarity index 96% rename from packages/plugin/tests/sync/baseline.test.ts rename to packages/plugin/tests/features/sync/remote/baseline.test.ts index 4bdefeca..9a2935a3 100644 --- a/packages/plugin/tests/sync/baseline.test.ts +++ b/packages/plugin/tests/features/sync/remote/baseline.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import type { CompareResult } from "@/features/sync/engine"; import { advanceBaselineForPaths, foldersToPublish, @@ -7,15 +8,14 @@ import { mergeFolderArrays, mergeWrittenIntoCache, publishedDelta, -} from "@/sync/baseline"; -import type { CompareResult } from "@/sync/engine"; +} from "@/features/sync/remote/baseline"; +import { createScopePolicy } from "@/features/sync/scope/scope"; import { EFileKind, type HashCacheEntry, type Manifest, type ManifestEntry, -} from "@/sync/types"; -import { createScopePolicy } from "@/vault/scope"; +} from "@/features/sync/types"; function entry(hash: string, overrides: Partial = {}) { return { diff --git a/packages/plugin/tests/sync/config-reset.test.ts b/packages/plugin/tests/features/sync/remote/config-reset.test.ts similarity index 91% rename from packages/plugin/tests/sync/config-reset.test.ts rename to packages/plugin/tests/features/sync/remote/config-reset.test.ts index dde995cc..4c64c405 100644 --- a/packages/plugin/tests/sync/config-reset.test.ts +++ b/packages/plugin/tests/features/sync/remote/config-reset.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from "vitest"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; -import { reconcileBaselineResetGenerations } from "@/sync/config-reset"; -import { EFileKind, type Manifest } from "@/sync/types"; -import { createScopePolicy } from "@/vault/scope"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import { reconcileBaselineResetGenerations } from "@/features/sync/remote/config-reset"; +import { createScopePolicy } from "@/features/sync/scope/scope"; +import { EFileKind, type Manifest } from "@/features/sync/types"; describe("reconcileBaselineResetGenerations", () => { const scope = createScopePolicy({ diff --git a/packages/plugin/tests/sync/foreign.test.ts b/packages/plugin/tests/features/sync/remote/foreign.test.ts similarity index 80% rename from packages/plugin/tests/sync/foreign.test.ts rename to packages/plugin/tests/features/sync/remote/foreign.test.ts index fd31ad1a..258b5dfa 100644 --- a/packages/plugin/tests/sync/foreign.test.ts +++ b/packages/plugin/tests/features/sync/remote/foreign.test.ts @@ -1,18 +1,24 @@ import { TestSession, useEncryptionKey } from "@tests/helpers/session"; -import { describe, expect, it, vi } from "vitest"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; -import { advanceSessionAfterPush } from "@/sync/baseline"; -import { compare, pushPaths } from "@/sync/engine"; +import { describe, expect, it } from "vitest"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import { REMOTE_HISTORY_PREFIX } from "@/features/sync/constants"; +import { objectKey } from "@/features/sync/content/keys"; +import { compare, pushPaths } from "@/features/sync/engine"; +import { pushKey, readHistory } from "@/features/sync/history/remote"; +import { advanceSessionAfterPush } from "@/features/sync/remote/baseline"; import { forgetDroppedForeign, heldShareBases, ownedFiles, -} from "@/sync/foreign"; -import { readHistoryLog } from "@/sync/history/store"; -import { objectKey } from "@/sync/manifest"; -import { EFileKind, type Manifest, type ManifestEntry } from "@/sync/types"; -import { SETTLED_AFTER_MS } from "@/sync/uploads"; -import { createScopePolicy } from "@/vault/scope"; +} from "@/features/sync/remote/foreign"; +import { SETTLED_AFTER_MS } from "@/features/sync/remote/uploads"; +import { deepCleanOrphans } from "@/features/sync/runtime/maintenance"; +import { createScopePolicy } from "@/features/sync/scope/scope"; +import { + EFileKind, + type Manifest, + type ManifestEntry, +} from "@/features/sync/types"; const vaultScope = createScopePolicy({ settingsSync: DEFAULT_SETTINGS_SYNC, @@ -165,7 +171,7 @@ describe("publishing from a space with another space's folder in it", () => { const deps = { ...session.deps(), scope: vaultScope, - history: { maxSnapshots: 50 }, + history: { horizon: null }, }; const result = await compare(deps); expect(result.remote?.files["Shared/p/b.md"]).toBeDefined(); @@ -173,13 +179,16 @@ describe("publishing from a space with another space's folder in it", () => { const published = await pushPaths(deps, result, ["a.md"]); expect(Object.keys(published.files)).toEqual(["a.md"]); - const log = await readHistoryLog( + const { view } = await readHistory( session.storage, deps.key, deps.space.root, ); expect( - Object.keys(log.changes[published.snapshotId]?.deleted ?? {}), + Object.keys( + view.pushes.get(pushKey(published.snapshotId))?.push.changes.deleted ?? + {}, + ), ).toEqual(["Shared/p/b.md"]); }); @@ -199,35 +208,26 @@ describe("publishing from a space with another space's folder in it", () => { expect(published.folders).toEqual(["mine"]); }); - it("frees the folder's blobs once the prune rolls off the history", async () => { + it("frees the folder's blobs once no history record names them", async () => { const session = await vaultWithFrozenCopy(); const frozenBlob = objectKey( (await session.compare()).remote?.files["Shared/p/b.md"]?.hash ?? "", ); + const deps = { + ...session.deps(), + scope: vaultScope, + history: { horizon: null }, + }; + await pushPaths(deps, await compare(deps), ["a.md"]); + session.storage.age(SETTLED_AFTER_MS + 1); + + await deepCleanOrphans(session.storage, deps.key, deps.space.root); expect(await session.storage.exists(frozenBlob)).toBe(true); - // GC sweeps only blobs, and evicts only records, past any push still in flight: a day between pushes. - vi.useFakeTimers({ toFake: ["Date"] }); - try { - for (let edit = 2; edit < 40; edit++) { - vi.setSystemTime(Date.now() + SETTLED_AFTER_MS + 1); - const deps = { - ...session.deps(), - scope: vaultScope, - history: { maxSnapshots: 1 }, - }; - session.adapter.putText("a.md", `A${edit}`); - const result = await compare(deps); - const published = await pushPaths(deps, result, ["a.md"]); - session.state = advanceSessionAfterPush( - session.state, - result, - published, - ); - } - } finally { - vi.useRealTimers(); - } + for (const record of await session.storage.list(REMOTE_HISTORY_PREFIX)) { + await session.storage.delete(record); + } + await deepCleanOrphans(session.storage, deps.key, deps.space.root); expect(await session.storage.exists(frozenBlob)).toBe(false); }); diff --git a/packages/plugin/tests/sync/keyfile.test.ts b/packages/plugin/tests/features/sync/remote/keyfile.test.ts similarity index 95% rename from packages/plugin/tests/sync/keyfile.test.ts rename to packages/plugin/tests/features/sync/remote/keyfile.test.ts index 70efc781..5b83f214 100644 --- a/packages/plugin/tests/sync/keyfile.test.ts +++ b/packages/plugin/tests/features/sync/remote/keyfile.test.ts @@ -1,14 +1,14 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { describe, expect, it } from "vitest"; -import { decryptBytes, encryptBytes } from "@/crypto"; -import { REMOTE_KEYFILE_KEY } from "@/sync/constants"; +import { decryptBytes, encryptBytes } from "@/core/crypto/cipher"; +import { REMOTE_KEYFILE_KEY } from "@/features/sync/constants"; import { type Keyfile, PassphraseRotatedError, readKeyfile, resolveContentKey, rotatePassphrase, -} from "@/sync/keyfile"; +} from "@/features/sync/remote/keyfile"; async function roundTrip(storage: FakeStorage, passphrase: string) { const { contentKey } = await resolveContentKey(storage, passphrase); diff --git a/packages/plugin/tests/sync/manifest-guard.test.ts b/packages/plugin/tests/features/sync/remote/manifest-guard.test.ts similarity index 96% rename from packages/plugin/tests/sync/manifest-guard.test.ts rename to packages/plugin/tests/features/sync/remote/manifest-guard.test.ts index 7ea2e544..44581d94 100644 --- a/packages/plugin/tests/sync/manifest-guard.test.ts +++ b/packages/plugin/tests/features/sync/remote/manifest-guard.test.ts @@ -8,15 +8,19 @@ import { it, vi, } from "vitest"; -import { deriveKey, type EncryptionKey, encryptJson } from "@/crypto"; -import { REMOTE_MANIFEST_KEY } from "@/sync/constants"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; +import { + deriveKey, + type EncryptionKey, + encryptJson, +} from "@/core/crypto/cipher"; import { ConcurrentPushError, fetchRemoteManifest, publishManifestWithGuard, reconcileRemoteAgainstBaseline, -} from "@/sync/manifest"; -import { EFileKind, type Manifest } from "@/sync/types"; +} from "@/features/sync/remote/manifest"; +import { EFileKind, type Manifest } from "@/features/sync/types"; let key: EncryptionKey; beforeAll(async () => { diff --git a/packages/plugin/tests/sync/manifest-revalidate.test.ts b/packages/plugin/tests/features/sync/remote/manifest-revalidate.test.ts similarity index 94% rename from packages/plugin/tests/sync/manifest-revalidate.test.ts rename to packages/plugin/tests/features/sync/remote/manifest-revalidate.test.ts index fbc78f84..19165794 100644 --- a/packages/plugin/tests/sync/manifest-revalidate.test.ts +++ b/packages/plugin/tests/features/sync/remote/manifest-revalidate.test.ts @@ -1,16 +1,20 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { RevalidatingStorage } from "@tests/helpers/revalidating-storage"; import { beforeAll, describe, expect, it } from "vitest"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; -import { deriveKey, type EncryptionKey, encryptJson } from "@/crypto"; -import { advanceBaselineForPaths } from "@/sync/baseline"; -import { REMOTE_MANIFEST_KEY } from "@/sync/constants"; +import { + deriveKey, + type EncryptionKey, + encryptJson, +} from "@/core/crypto/cipher"; +import { advanceBaselineForPaths } from "@/features/sync/remote/baseline"; import { ConcurrentPushError, fetchRemoteManifest, publishManifestWithGuard, -} from "@/sync/manifest"; -import { EFileKind, type Manifest } from "@/sync/types"; +} from "@/features/sync/remote/manifest"; +import { EFileKind, type Manifest } from "@/features/sync/types"; let key: EncryptionKey; beforeAll(async () => { diff --git a/packages/plugin/tests/core/passphrase-manager.test.ts b/packages/plugin/tests/features/sync/remote/passphrase-manager.test.ts similarity index 72% rename from packages/plugin/tests/core/passphrase-manager.test.ts rename to packages/plugin/tests/features/sync/remote/passphrase-manager.test.ts index e367f9fd..13eb309b 100644 --- a/packages/plugin/tests/core/passphrase-manager.test.ts +++ b/packages/plugin/tests/features/sync/remote/passphrase-manager.test.ts @@ -1,28 +1,30 @@ import type { DataAdapter } from "obsidian"; import { beforeEach, describe, expect, it, vi } from "vitest"; - -import { PassphraseManager } from "@/core/passphrase-manager"; -import type { DeviceKey } from "@/crypto/device-key"; +import { DEFAULT_SETTINGS } from "@/app/settings"; +import type { DeviceKey } from "@/core/crypto/device-key"; import { + clearCachedPassphrase, loadCachedPassphrase, saveCachedPassphrase, -} from "@/crypto/passphrase-cache"; -import { DEFAULT_SETTINGS, type MdsyncSettings } from "@/settings/model"; -import { defaultS3Config, type ObjectStorage } from "@/storage"; +} from "@/core/crypto/passphrase-cache"; +import type { MdsyncSettings } from "@/core/settings/model"; +import { defaultS3Config } from "@/features/storage/backends/s3"; +import type { ObjectStorage } from "@/features/storage/types"; import { type Keyfile, PassphraseRotatedError, readKeyfile, resolveContentKey, -} from "@/sync/keyfile"; +} from "@/features/sync/remote/keyfile"; +import { PassphraseManager } from "@/features/sync/remote/passphrase-manager"; -vi.mock("@/sync/keyfile", async (importOriginal) => ({ +vi.mock("@/features/sync/remote/keyfile", async (importOriginal) => ({ ...(await importOriginal>()), readKeyfile: vi.fn(), resolveContentKey: vi.fn(), rotatePassphrase: vi.fn(), })); -vi.mock("@/crypto/passphrase-cache", () => ({ +vi.mock("@/core/crypto/passphrase-cache", () => ({ clearCachedPassphrase: vi.fn(async () => undefined), loadCachedPassphrase: vi.fn(async () => null), saveCachedPassphrase: vi.fn(async () => undefined), @@ -138,6 +140,80 @@ describe("PassphraseManager", () => { }); }); +describe("PassphraseManager.resolveKeyRecovering", () => { + const say = () => ({ warn: vi.fn(), notify: vi.fn() }); + + it("forgets the rotated passphrase, asks again and retries once", async () => { + vi.mocked(resolveContentKey) + .mockRejectedValueOnce(new PassphraseRotatedError()) + .mockResolvedValueOnce(resolved("new")); + const passphrase = manager(["old", "new"]); + await passphrase.prompt(false); + const feedback = say(); + + const key = await passphrase.resolveKeyRecovering(STORAGE, feedback); + + expect(key).toBe("new"); + expect(passphrase.current()).toBe("new"); + expect(feedback.notify).toHaveBeenCalledWith( + "Passphrase changed on another device. Enter the new one.", + ); + }); + + it("gives up when the second passphrase is also rotated", async () => { + vi.mocked(resolveContentKey).mockRejectedValue( + new PassphraseRotatedError(), + ); + const passphrase = manager(["old", "still-old"]); + await passphrase.prompt(false); + const feedback = say(); + + expect(await passphrase.resolveKeyRecovering(STORAGE, feedback)).toBeNull(); + expect(feedback.notify).toHaveBeenLastCalledWith( + "Passphrase still incorrect.", + ); + }); + + it("returns null when the prompt is declined", async () => { + vi.mocked(resolveContentKey).mockRejectedValue( + new PassphraseRotatedError(), + ); + const passphrase = manager(["old"]); + await passphrase.prompt(false); + + expect(await passphrase.resolveKeyRecovering(STORAGE, say())).toBeNull(); + expect(passphrase.has()).toBe(false); + }); + + it("rethrows other failures untouched", async () => { + vi.mocked(resolveContentKey).mockRejectedValue(new Error("offline")); + const passphrase = manager(["secret"]); + await passphrase.prompt(false); + const feedback = say(); + + await expect( + passphrase.resolveKeyRecovering(STORAGE, feedback), + ).rejects.toThrow("offline"); + expect(feedback.notify).not.toHaveBeenCalled(); + expect(passphrase.has()).toBe(true); + }); +}); + +describe("PassphraseManager.applyCachePreference", () => { + it("removes the saved copy when caching is off and saves it when on", async () => { + const settings = { ...DEFAULT_SETTINGS, cachePassphrase: false }; + const passphrase = vaultManager(settings); + await passphrase.replacePassphrase("secret"); + await passphrase.applyCachePreference(); + expect(clearCachedPassphrase).toHaveBeenCalledOnce(); + expect(saveCachedPassphrase).not.toHaveBeenCalled(); + + settings.cachePassphrase = true; + await passphrase.applyCachePreference(); + expect(saveCachedPassphrase).toHaveBeenCalledOnce(); + }); +}); + describe("PassphraseManager.isUnlocked", () => { it("is locked before any key is resolved", async () => { const passphrase = vaultManager(configured("notes"), ["secret"]); diff --git a/packages/plugin/tests/core/passphrase-storage.test.ts b/packages/plugin/tests/features/sync/remote/passphrase-storage.test.ts similarity index 69% rename from packages/plugin/tests/core/passphrase-storage.test.ts rename to packages/plugin/tests/features/sync/remote/passphrase-storage.test.ts index 4295b298..c14b598b 100644 --- a/packages/plugin/tests/core/passphrase-storage.test.ts +++ b/packages/plugin/tests/features/sync/remote/passphrase-storage.test.ts @@ -1,13 +1,12 @@ import type { DataAdapter } from "obsidian"; import { describe, expect, it, vi } from "vitest"; - -import { PassphraseManager } from "@/core/passphrase-manager"; -import type { DeviceKey } from "@/crypto/device-key"; -import { DEFAULT_SETTINGS } from "@/settings/model"; +import { DEFAULT_SETTINGS } from "@/app/settings"; +import type { DeviceKey } from "@/core/crypto/device-key"; +import { PassphraseManager } from "@/features/sync/remote/passphrase-manager"; const created = vi.hoisted(() => ({ changed: null as (() => void) | null })); -vi.mock("@/storage", async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock("@/features/storage/registry", async (importOriginal) => ({ + ...(await importOriginal()), createStorageAdapter: (_config: unknown, changed?: () => void) => { created.changed = changed ?? null; return {}; diff --git a/packages/plugin/tests/sync/record-order.test.ts b/packages/plugin/tests/features/sync/remote/record-order.test.ts similarity index 85% rename from packages/plugin/tests/sync/record-order.test.ts rename to packages/plugin/tests/features/sync/remote/record-order.test.ts index eaa0d035..d549fe4b 100644 --- a/packages/plugin/tests/sync/record-order.test.ts +++ b/packages/plugin/tests/features/sync/remote/record-order.test.ts @@ -1,13 +1,24 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; import { beforeAll, describe, expect, it } from "vitest"; -import { deriveKey, type EncryptionKey } from "@/crypto"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; -import { buildSessionState, mergeWrittenIntoCache } from "@/sync/baseline"; -import { compare, type EngineDependencies, pushPaths } from "@/sync/engine"; -import { VAULT_SPACE } from "@/sync/space"; -import { EFileKind, type ManifestEntry, type SessionState } from "@/sync/types"; -import { createScopePolicy } from "@/vault/scope"; +import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import { + compare, + type EngineDependencies, + pushPaths, +} from "@/features/sync/engine"; +import { + buildSessionState, + mergeWrittenIntoCache, +} from "@/features/sync/remote/baseline"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; +import { createScopePolicy } from "@/features/sync/scope/scope"; +import { + EFileKind, + type ManifestEntry, + type SessionState, +} from "@/features/sync/types"; let key: EncryptionKey; beforeAll(async () => { diff --git a/packages/plugin/tests/sync/reset.test.ts b/packages/plugin/tests/features/sync/remote/reset.test.ts similarity index 66% rename from packages/plugin/tests/sync/reset.test.ts rename to packages/plugin/tests/features/sync/remote/reset.test.ts index 2078d8a9..78657159 100644 --- a/packages/plugin/tests/sync/reset.test.ts +++ b/packages/plugin/tests/features/sync/remote/reset.test.ts @@ -1,15 +1,16 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; -import { beforeAll, describe, expect, it } from "vitest"; -import { deriveKey, type EncryptionKey } from "@/crypto"; +import { beforeAll, describe, expect, it, vi } from "vitest"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; +import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; import { REMOTE_HISTORY_LOG_KEY, REMOTE_KEYFILE_KEY, - REMOTE_MANIFEST_KEY, REMOTE_PINS_PREFIX, REMOTE_SALT_KEY, -} from "@/sync/constants"; -import { objectKey } from "@/sync/manifest"; -import { resetRemoteStorage } from "@/sync/reset"; +} from "@/features/sync/constants"; +import { chunkKey, objectKey, recipeKey } from "@/features/sync/content/keys"; +import { pushKey } from "@/features/sync/history/remote"; +import { resetRemoteStorage } from "@/features/sync/remote/reset"; let key: EncryptionKey; beforeAll(async () => { @@ -22,8 +23,11 @@ function seed(): FakeStorage { storage.map.set(REMOTE_MANIFEST_KEY, bytes); storage.map.set(objectKey("aaa"), bytes); storage.map.set(objectKey("bbb"), bytes); + storage.map.set(recipeKey("ccc"), bytes); + storage.map.set(chunkKey("c0"), bytes); storage.map.set(`${REMOTE_PINS_PREFIX}snap1.json.enc`, bytes); storage.map.set(REMOTE_HISTORY_LOG_KEY, bytes); + storage.map.set(pushKey("s1"), bytes); storage.map.set(REMOTE_SALT_KEY, bytes); storage.map.set(REMOTE_KEYFILE_KEY, bytes); return storage; @@ -39,9 +43,25 @@ describe("resetRemoteStorage", () => { expect(storage.map.has(objectKey("bbb"))).toBe(false); expect(storage.map.has(`${REMOTE_PINS_PREFIX}snap1.json.enc`)).toBe(false); expect(storage.map.has(REMOTE_HISTORY_LOG_KEY)).toBe(false); + expect(storage.map.has(pushKey("s1"))).toBe(false); expect(result.deletedKeys).toContain(REMOTE_MANIFEST_KEY); }); + it("deletes chunked files, their chunks only after every root", async () => { + const storage = seed(); + const deleted: string[] = []; + const remove = storage.delete.bind(storage); + vi.spyOn(storage, "delete").mockImplementation((storageKey) => { + deleted.push(storageKey); + return remove(storageKey); + }); + + await resetRemoteStorage(storage, 4); + + expect(storage.map.has(recipeKey("ccc"))).toBe(false); + expect(deleted.at(-1)).toBe(chunkKey("c0")); + }); + it("keeps the salt and the keyfile, so the passphrase still works", async () => { const storage = seed(); await resetRemoteStorage(storage, 2); diff --git a/packages/plugin/tests/features/sync/remote/space-paths.test.ts b/packages/plugin/tests/features/sync/remote/space-paths.test.ts new file mode 100644 index 00000000..a650c1df --- /dev/null +++ b/packages/plugin/tests/features/sync/remote/space-paths.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it } from "vitest"; +import type { SnapshotChanges } from "@/features/sync/history/types"; +import { + changesToSpace, + changesToVault, + manifestToSpace, + manifestToVault, +} from "@/features/sync/remote/space-paths"; +import type { EFileKind, Manifest, ManifestEntry } from "@/features/sync/types"; + +function entry(hash: string, size = 1, mtime = 1): ManifestEntry { + return { hash, size, mtime, kind: "vault" as EFileKind }; +} + +function manifest(files: Record): Manifest { + return { + version: 1, + vaultId: "v", + snapshotId: "s1", + parentSnapshotId: null, + createdAt: 1, + deviceId: "d", + files, + folders: ["Shared/p/sub"], + }; +} + +describe("manifestToSpace / manifestToVault", () => { + it("round-trips through space and back", () => { + const m = manifest({ "Shared/p/a.md": entry("A") }); + const spaced = manifestToSpace(m, "Shared/p"); + expect(Object.keys(spaced.files)).toEqual(["a.md"]); + expect(spaced.folders).toEqual(["sub"]); + const back = manifestToVault(spaced, "Shared/p"); + expect(Object.keys(back.files)).toEqual(["Shared/p/a.md"]); + expect(back.folders).toEqual(["Shared/p/sub"]); + }); + + it('returns the same object for root ""', () => { + const m = manifest({ "a.md": entry("A") }); + expect(manifestToSpace(m, "")).toBe(m); + expect(manifestToVault(m, "")).toBe(m); + }); + + it("throws when a path is outside the root", () => { + const m = manifest({ "Other/b.md": entry("B") }); + expect(() => manifestToSpace(m, "Shared/p")).toThrow("outside the space"); + }); +}); + +describe("changesToSpace / changesToVault", () => { + const changes: SnapshotChanges = { + added: { "Shared/p/new.md": entry("N") }, + modified: { + "Shared/p/edit.md": { from: entry("E1"), to: entry("E2") }, + }, + deleted: { "Shared/p/gone.md": entry("G1") }, + deletedLast: { "Shared/p/gone.md": entry("G2") }, + }; + + it("translates change keys to root-relative", () => { + const spaced = changesToSpace(changes, "Shared/p"); + expect(Object.keys(spaced.added)).toEqual(["new.md"]); + expect(Object.keys(spaced.modified)).toEqual(["edit.md"]); + expect(Object.keys(spaced.deleted)).toEqual(["gone.md"]); + expect(spaced.modified["edit.md"]).toEqual({ + from: entry("E1"), + to: entry("E2"), + }); + }); + + it("rekeys deletedLast with the rest", () => { + const spaced = changesToSpace(changes, "Shared/p"); + expect(spaced.deletedLast).toEqual({ "gone.md": entry("G2") }); + expect(changesToVault(spaced, "Shared/p").deletedLast).toEqual({ + "Shared/p/gone.md": entry("G2"), + }); + }); + + it("adds no deletedLast to a record that had none", () => { + const { deletedLast: _, ...plain } = changes; + expect(changesToSpace(plain, "Shared/p")).not.toHaveProperty("deletedLast"); + expect(changesToVault(plain, "Shared/p")).not.toHaveProperty("deletedLast"); + }); + + it("round-trips back to vault paths", () => { + const back = changesToVault( + changesToSpace(changes, "Shared/p"), + "Shared/p", + ); + expect(back).toEqual(changes); + }); + + it('returns the same object for root ""', () => { + expect(changesToSpace(changes, "")).toBe(changes); + expect(changesToVault(changes, "")).toBe(changes); + }); + + it("throws when a path is outside the root, deletedLast included", () => { + expect(() => changesToSpace(changes, "Other")).toThrow("outside the space"); + const stray: SnapshotChanges = { + added: {}, + modified: {}, + deleted: {}, + deletedLast: { "Other/x.md": entry("X") }, + }; + expect(() => changesToSpace(stray, "Shared/p")).toThrow( + "outside the space", + ); + }); +}); diff --git a/packages/plugin/tests/sync/space-roundtrip.test.ts b/packages/plugin/tests/features/sync/remote/space-roundtrip.test.ts similarity index 88% rename from packages/plugin/tests/sync/space-roundtrip.test.ts rename to packages/plugin/tests/features/sync/remote/space-roundtrip.test.ts index 86babfd5..fc076680 100644 --- a/packages/plugin/tests/sync/space-roundtrip.test.ts +++ b/packages/plugin/tests/features/sync/remote/space-roundtrip.test.ts @@ -1,11 +1,15 @@ import { TestSession, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; -import { decryptJson } from "@/crypto"; -import { advanceSessionAfterPush } from "@/sync/baseline"; -import { REMOTE_MANIFEST_KEY } from "@/sync/constants"; -import { compare, pushPaths } from "@/sync/engine"; -import { assertSpacePresent, SpaceGoneError, VAULT_SPACE } from "@/sync/space"; -import type { Manifest } from "@/sync/types"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; +import { decryptJson } from "@/core/crypto/cipher"; +import { compare, pushPaths } from "@/features/sync/engine"; +import { advanceSessionAfterPush } from "@/features/sync/remote/baseline"; +import { + assertSpacePresent, + SpaceGoneError, + VAULT_SPACE, +} from "@/features/sync/remote/space"; +import type { Manifest } from "@/features/sync/types"; describe("space root translation at the codec boundary", () => { useEncryptionKey(); diff --git a/packages/plugin/tests/sync/spaces.test.ts b/packages/plugin/tests/features/sync/remote/spaces.test.ts similarity index 96% rename from packages/plugin/tests/sync/spaces.test.ts rename to packages/plugin/tests/features/sync/remote/spaces.test.ts index b0422d07..cefcbf74 100644 --- a/packages/plugin/tests/sync/spaces.test.ts +++ b/packages/plugin/tests/features/sync/remote/spaces.test.ts @@ -1,15 +1,23 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; import { beforeAll, describe, expect, it, vi } from "vitest"; -import { decryptJson, deriveKey, type EncryptionKey } from "@/crypto"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; -import { REMOTE_MANIFEST_KEY } from "@/sync/constants"; -import { SyncController } from "@/sync/controller"; -import { projectSession } from "@/sync/session-state"; -import { nestedRoots, type Space, VAULT_SPACE } from "@/sync/space"; -import type { LocalState, Manifest } from "@/sync/types"; -import type { VaultIndex } from "@/vault/file-index"; -import { createScopePolicy } from "@/vault/scope"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; +import { + decryptJson, + deriveKey, + type EncryptionKey, +} from "@/core/crypto/cipher"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import type { VaultIndex } from "@/core/vault/file-index"; +import { SyncController } from "@/features/sync/controller"; +import { + nestedRoots, + type Space, + VAULT_SPACE, +} from "@/features/sync/remote/space"; +import { createScopePolicy } from "@/features/sync/scope/scope"; +import { projectSession } from "@/features/sync/session-state"; +import type { LocalState, Manifest } from "@/features/sync/types"; let vaultKey: EncryptionKey; let shareKey: EncryptionKey; @@ -69,7 +77,7 @@ function device( state: projectSession(local, storage.identity(), space.root), maxFileBytes: 1_000_000, concurrency: 2, - history: { maxSnapshots: 50 }, + history: { horizon: null }, }; }, persistState: async (state) => { diff --git a/packages/plugin/tests/features/sync/remote/uploads.test.ts b/packages/plugin/tests/features/sync/remote/uploads.test.ts new file mode 100644 index 00000000..41f842f5 --- /dev/null +++ b/packages/plugin/tests/features/sync/remote/uploads.test.ts @@ -0,0 +1,20 @@ +import { FakeStorage } from "@tests/helpers/fake-storage"; +import { describe, expect, it } from "vitest"; +import { rememberUpload, uploadedHere } from "@/features/sync/remote/uploads"; + +describe("upload log", () => { + it("keeps the newest 20 000 uploads, a re-upload counting as new", () => { + const storage = new FakeStorage(); + rememberUpload(storage, "first"); + rememberUpload(storage, "second"); + for (let index = 0; index < 19_998; index++) { + rememberUpload(storage, `chunks/${index}`); + } + rememberUpload(storage, "first"); + rememberUpload(storage, "newest"); + + expect(uploadedHere(storage, "second")).toBe(false); + expect(uploadedHere(storage, "first")).toBe(true); + expect(uploadedHere(storage, "newest")).toBe(true); + }); +}); diff --git a/packages/plugin/tests/features/sync/runtime/file-diff-service.test.ts b/packages/plugin/tests/features/sync/runtime/file-diff-service.test.ts new file mode 100644 index 00000000..38e12f2d --- /dev/null +++ b/packages/plugin/tests/features/sync/runtime/file-diff-service.test.ts @@ -0,0 +1,97 @@ +import { + pairedSessions, + type TestSession, + useEncryptionKey, +} from "@tests/helpers/session"; +import { describe, expect, it } from "vitest"; +import type { CompareResult } from "@/features/sync/engine"; +import { pushPathsOp } from "@/features/sync/operations/push"; +import { FileDiffService } from "@/features/sync/runtime/file-diff-service"; + +useEncryptionKey(); + +async function push(session: TestSession, path: string): Promise { + const result = await session.compare(); + await pushPathsOp(session.deps(), result, [path], session.context()); +} + +function service(a: TestSession, result: CompareResult): FileDiffService { + return new FileDiffService({ + openSession: async () => a.deps(), + getResult: () => result, + shareBases: () => undefined, + }); +} + +/** `path` edited on both devices since the version they share. */ +async function conflicted( + path = "note.md", + [base, local, remote] = ["base\n", "local\n", "remote\n"], +): Promise<{ a: TestSession; result: CompareResult }> { + const [a, b] = pairedSessions(); + a.adapter.putText(path, base); + await push(a, path); + b.adapter.putText(path, base); + await b.adoptRemote(); + b.adapter.putText(path, remote); + await push(b, path); + a.adapter.putText(path, local); + return { a, result: await a.compare() }; +} + +describe("getConflictThreeWay", () => { + it("gives the three versions with the compare's hashes", async () => { + const { a, result } = await conflicted(); + const [conflict] = result.diff.conflicts; + + const texts = await service(a, result).getConflictThreeWay("note.md"); + + expect(texts).toEqual({ + base: "base\n", + local: "local\n", + remote: "remote\n", + expected: { + localHash: conflict?.localHash, + remoteHash: conflict?.remoteHash, + }, + }); + }); + + it("gives JSON base and remote in local's key order", async () => { + const json = (value: unknown) => JSON.stringify(value, null, 2); + const { a, result } = await conflicted("data.json", [ + json({ a: 1, b: 1 }), + json({ b: 2, a: 1 }), + json({ a: 3, b: 1 }), + ]); + + const texts = await service(a, result).getConflictThreeWay("data.json"); + + expect(texts).toMatchObject({ + base: json({ b: 1, a: 1 }), + local: json({ b: 2, a: 1 }), + remote: json({ b: 1, a: 3 }), + }); + }); + + it("refuses a local file edited since the compare", async () => { + const { a, result } = await conflicted(); + a.adapter.putText("note.md", "typed after the compare\n"); + + const texts = await service(a, result).getConflictThreeWay("note.md"); + + expect(texts).toMatch(/changed since the last compare/); + }); + + it("says why when the two versions share no earlier one", async () => { + const [a, b] = pairedSessions(); + b.adapter.putText("new.md", "from b\n"); + await push(b, "new.md"); + a.adapter.putText("new.md", "from a\n"); + const result = await a.compare(); + + const texts = await service(a, result).getConflictThreeWay("new.md"); + + expect(texts).toMatch(/share no earlier one/); + }); +}); diff --git a/packages/plugin/tests/sync/history-service-scope.test.ts b/packages/plugin/tests/features/sync/runtime/history-service-scope.test.ts similarity index 89% rename from packages/plugin/tests/sync/history-service-scope.test.ts rename to packages/plugin/tests/features/sync/runtime/history-service-scope.test.ts index a4d070ce..f0514ab6 100644 --- a/packages/plugin/tests/sync/history-service-scope.test.ts +++ b/packages/plugin/tests/features/sync/runtime/history-service-scope.test.ts @@ -1,12 +1,12 @@ import { TestSession, useEncryptionKey } from "@tests/helpers/session"; import { Platform } from "obsidian"; import { describe, expect, it } from "vitest"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; -import type { EngineDependencies } from "@/sync/engine"; -import { pushPathsOp } from "@/sync/operations/push"; -import { HistoryService } from "@/sync/runtime/history-service"; -import { createIgnoreMatcher } from "@/vault/ignore"; -import { createScopePolicy } from "@/vault/scope"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import type { EngineDependencies } from "@/features/sync/engine"; +import { pushPathsOp } from "@/features/sync/operations/push"; +import { HistoryService } from "@/features/sync/runtime/history-service"; +import { createIgnoreMatcher } from "@/features/sync/scope/ignore"; +import { createScopePolicy } from "@/features/sync/scope/scope"; useEncryptionKey(); @@ -17,7 +17,7 @@ const ignoringDrafts = createScopePolicy({ }); function withHistory(session: TestSession): EngineDependencies { - return { ...session.deps(), history: { maxSnapshots: 10 } }; + return { ...session.deps(), history: { horizon: null } }; } async function pushAll(session: TestSession): Promise { @@ -38,6 +38,8 @@ function serviceFor(session: TestSession): HistoryService { }), enqueue: (task) => task(), refresh: async () => undefined, + remember: () => undefined, + restored: () => undefined, }); } diff --git a/packages/plugin/tests/features/sync/runtime/history-service.test.ts b/packages/plugin/tests/features/sync/runtime/history-service.test.ts new file mode 100644 index 00000000..91d19e75 --- /dev/null +++ b/packages/plugin/tests/features/sync/runtime/history-service.test.ts @@ -0,0 +1,261 @@ +import { TestSession, useEncryptionKey } from "@tests/helpers/session"; +import { describe, expect, it, vi } from "vitest"; +import { sha256Hex } from "@/core/crypto"; +import { objectKey } from "@/features/sync/content/keys"; +import type { EngineDependencies } from "@/features/sync/engine"; +import { pushPathsOp } from "@/features/sync/operations/push"; +import { HistoryService } from "@/features/sync/runtime/history-service"; + +useEncryptionKey(); + +const encode = (text: string) => new TextEncoder().encode(text); + +async function pushAll(session: TestSession): Promise { + const deps: EngineDependencies = { + ...session.deps(), + history: { horizon: null }, + }; + const result = await session.compare(); + await pushPathsOp( + deps, + result, + result.diff.localChanges.map((change) => change.path), + session.context(), + ); +} + +function serviceFor(session: TestSession) { + const openSession = vi.fn( + async (_path?: string): Promise => + session.deps(), + ); + const refresh = vi.fn(async () => undefined); + const restored = vi.fn(); + let turns = 0; + const service = new HistoryService({ + openSession, + enqueue: (task) => { + turns++; + return task(); + }, + refresh, + remember: () => undefined, + restored, + }); + return { service, openSession, refresh, restored, turns: () => turns }; +} + +describe("restoreFileVersions", () => { + it("restores two files in one turn with one refresh, and reports the one that failed", async () => { + const session = new TestSession(); + session.adapter.putText("a.md", "a1"); + session.adapter.putText("b.md", "b1"); + await pushAll(session); + session.adapter.putText("a.md", "a2"); + session.adapter.putText("b.md", "b2"); + const { service, openSession, refresh, turns } = serviceFor(session); + + const failed = await service.restoreFileVersions([ + { path: "a.md", hash: await sha256Hex(encode("a1")) }, + { path: "gone.md", hash: "0".repeat(64) }, + { path: "b.md", hash: await sha256Hex(encode("b1")) }, + ]); + + expect(failed).toEqual(["gone.md"]); + expect(session.text("a.md")).toBe("a1"); + expect(session.text("b.md")).toBe("b1"); + expect(session.adapter.hasFile("gone.md")).toBe(false); + expect(turns()).toBe(1); + expect(refresh).toHaveBeenCalledTimes(1); + // A batch may span spaces, so each item opens the session of its own path. + expect(openSession.mock.calls.map(([path]) => path)).toEqual([ + "a.md", + "gone.md", + "b.md", + ]); + }); + + it("does not refresh when no write landed", async () => { + const session = new TestSession(); + const { service, refresh } = serviceFor(session); + + const failed = await service.restoreFileVersions([ + { path: "a.md", hash: "0".repeat(64) }, + ]); + + expect(failed).toEqual(["a.md"]); + expect(refresh).not.toHaveBeenCalled(); + }); + + it("refreshes once for what landed even when the session is gone for a later item", async () => { + const session = new TestSession(); + session.adapter.putText("a.md", "a1"); + await pushAll(session); + session.adapter.putText("a.md", "a2"); + const { service, openSession, refresh } = serviceFor(session); + openSession.mockImplementation(async (path?: string) => + path === "other/b.md" ? null : session.deps(), + ); + + const failed = await service.restoreFileVersions([ + { path: "a.md", hash: await sha256Hex(encode("a1")) }, + { path: "other/b.md", hash: await sha256Hex(encode("a1")) }, + ]); + + expect(failed).toEqual(["other/b.md"]); + expect(session.text("a.md")).toBe("a1"); + expect(refresh).toHaveBeenCalledTimes(1); + }); +}); + +describe("restoreVault", () => { + it("keeps what is edited while it runs: a file it downloads for, a file it would remove", async () => { + const session = new TestSession(); + session.adapter.putText("a.md", "a1"); + session.adapter.putText("b.md", "b1"); + await pushAll(session); + const first = session.state.baseline?.snapshotId as string; + session.adapter.putText("a.md", "a2"); + session.adapter.putText("b.md", "b2"); + session.adapter.putText("c.md", "c1"); + await pushAll(session); + const { service } = serviceFor(session); + const confirmed = await service.previewVaultRestore(first); + const a1 = objectKey(await sha256Hex(encode("a1"))); + const get = session.storage.get.bind(session.storage); + vi.spyOn(session.storage, "get").mockImplementation(async (storageKey) => { + // Saved while the restore downloads. + if (storageKey === a1) { + session.adapter.putText("a.md", "mine"); + session.adapter.putText("c.md", "c2"); + } + return get(storageKey); + }); + + const { applied } = await service.restoreVault(first, confirmed); + + expect(applied).toBe(true); + expect(session.text("a.md")).toBe("mine"); + expect(session.text("b.md")).toBe("b1"); + expect(session.text("c.md")).toBe("c2"); + }); + + it("holds what it writes, then what it removes, out of automatic pushes", async () => { + const session = new TestSession(); + session.adapter.putText("a.md", "a1"); + await pushAll(session); + const first = session.state.baseline?.snapshotId as string; + session.adapter.putText("a.md", "a2"); + session.adapter.putText("c.md", "c1"); + await pushAll(session); + const { service, restored } = serviceFor(session); + + await service.restoreVault(first, await service.previewVaultRestore(first)); + + expect(restored.mock.calls).toEqual([ + [ + expect.objectContaining({ id: "vault" }), + new Map([["a.md", await sha256Hex(encode("a1"))]]), + ], + [expect.objectContaining({ id: "vault" }), new Map([["c.md", null]])], + ]); + }); + + it("holds no removal when a write fails", async () => { + const session = new TestSession(); + session.adapter.putText("a.md", "a1"); + await pushAll(session); + const first = session.state.baseline?.snapshotId as string; + session.adapter.putText("a.md", "a2"); + session.adapter.putText("c.md", "c1"); + await pushAll(session); + const { service, restored } = serviceFor(session); + const confirmed = await service.previewVaultRestore(first); + const a1 = objectKey(await sha256Hex(encode("a1"))); + const get = session.storage.get.bind(session.storage); + vi.spyOn(session.storage, "get").mockImplementation(async (key) => { + if (key === a1) throw new Error("offline"); + return get(key); + }); + + await expect(service.restoreVault(first, confirmed)).rejects.toThrow(); + + expect(restored).toHaveBeenCalledOnce(); + expect(session.text("c.md")).toBe("c1"); + }); + + it("writes over a file a case-blind disk holds under another spelling", async () => { + const session = new TestSession(); + session.adapter.putText("notes/a.md", "a1"); + await pushAll(session); + const first = session.state.baseline?.snapshotId as string; + session.adapter.remove("notes/a.md"); + session.adapter.putText("Notes/A.md", "a2"); + await pushAll(session); + const stat = session.adapter.stat.bind(session.adapter); + vi.spyOn(session.adapter, "stat").mockImplementation((path) => + stat(path === "notes/a.md" ? "Notes/A.md" : path), + ); + const { service, restored } = serviceFor(session); + + const confirmed = await service.previewVaultRestore(first); + await service.restoreVault(first, confirmed); + + expect(session.text("notes/a.md")).toBe("a1"); + const hash = await sha256Hex(encode("a1")); + expect(restored).toHaveBeenCalledWith( + expect.objectContaining({ id: "vault" }), + new Map([ + ["notes/a.md", hash], + ["Notes/A.md", hash], + ]), + ); + }); +}); + +describe("space routing", () => { + it("restores to another path with the version read in the space that stored it", async () => { + const session = new TestSession(); + session.adapter.putText("a.md", "a1"); + await pushAll(session); + const { service, openSession } = serviceFor(session); + + await service.restoreFileVersion( + "Shared/a.md", + await sha256Hex(encode("a1")), + "a.md", + ); + + expect(session.text("Shared/a.md")).toBe("a1"); + expect(openSession.mock.calls.map(([path]) => path)).toEqual([ + "a.md", + "Shared/a.md", + ]); + }); + + it("previews a restore-to in the space of its source", async () => { + const session = new TestSession(); + const { service, openSession } = serviceFor(session); + openSession.mockResolvedValue(null); + + await service.getHistoryDiff({ + path: "Shared/a.md", + source: "a.md", + left: { current: true }, + right: { current: true }, + }); + + expect(openSession).toHaveBeenCalledWith("a.md"); + }); + + it("pins in the space of the file whose History it came from", async () => { + const session = new TestSession(); + const { service, openSession } = serviceFor(session); + openSession.mockResolvedValue(null); + + await expect( + service.setSnapshotPinned("s1", false, undefined, "Shared/a.md"), + ).rejects.toThrow(); + expect(openSession).toHaveBeenCalledWith("Shared/a.md"); + }); +}); diff --git a/packages/plugin/tests/features/sync/runtime/maintenance-service.test.ts b/packages/plugin/tests/features/sync/runtime/maintenance-service.test.ts new file mode 100644 index 00000000..949088af --- /dev/null +++ b/packages/plugin/tests/features/sync/runtime/maintenance-service.test.ts @@ -0,0 +1,153 @@ +import { FakeStorage } from "@tests/helpers/fake-storage"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { REMOTE_HISTORY_LOG_KEY } from "@/features/sync/constants"; +import type { EngineDependencies } from "@/features/sync/engine"; +import { collectHistoryGarbage } from "@/features/sync/history/gc"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; +import { MaintenanceService } from "@/features/sync/runtime/maintenance-service"; + +vi.mock("@/features/sync/history/gc", () => ({ + collectHistoryGarbage: vi.fn(), +})); + +const collect = vi.mocked(collectHistoryGarbage); + +/** `null`: history off. */ +function service( + history: { horizon: number | null } | null = { horizon: null }, + storage = new FakeStorage(), +) { + const logWarn = vi.fn(() => Promise.resolve()); + const logInfo = vi.fn(() => Promise.resolve()); + const remember = vi.fn(); + const queued: Promise[] = []; + // Settings can switch the storage under a running service. + const target = { storage }; + const maintenance = new MaintenanceService({ + openSession: async (space) => + ({ + space, + storage: target.storage, + key: {}, + history: history ?? undefined, + }) as unknown as EngineDependencies, + enqueue: (task) => task(), + enqueueQuiet: (task) => { + const run = Promise.resolve().then(task); + queued.push(run.catch(() => undefined)); + return run; + }, + logInfo, + logWarn, + remember, + }); + const settled = () => Promise.all(queued).then(() => undefined); + return { maintenance, logWarn, logInfo, remember, settled, target }; +} + +beforeEach(() => { + vi.useFakeTimers({ toFake: ["Date"] }); + collect.mockReset(); + collect.mockResolvedValue({ + written: 0, + retired: 0, + swept: 0, + activity: null, + }); +}); +afterEach(() => { + vi.useRealTimers(); +}); + +describe("MaintenanceService.afterPush", () => { + it("cleans history at most every 10 minutes per space", async () => { + const { maintenance, settled } = service(); + maintenance.afterPush(VAULT_SPACE); + maintenance.afterPush(VAULT_SPACE); + vi.setSystemTime(Date.now() + 10 * 60_000); + maintenance.afterPush(VAULT_SPACE); + await settled(); + expect(collect).toHaveBeenCalledTimes(2); + }); + + it("remembers the vault's activity, never a share's", async () => { + const activity = { 100: [2, 1] as [number, number] }; + collect.mockResolvedValue({ written: 0, retired: 0, swept: 0, activity }); + const storage = new FakeStorage(); + const { maintenance, remember, settled } = service(undefined, storage); + maintenance.afterPush({ id: "share", root: "Shared" }); + maintenance.afterPush(VAULT_SPACE); + await settled(); + expect(remember.mock.calls).toEqual([ + [storage.identity(), activity, Date.now()], + ]); + }); + + it("skips a session with history off and runs nothing once disposed", async () => { + const off = service(null); + off.maintenance.afterPush(VAULT_SPACE); + await off.settled(); + + const disposed = service(); + disposed.maintenance.afterPush(VAULT_SPACE); + disposed.maintenance.dispose(); + await disposed.settled(); + expect(collect).not.toHaveBeenCalled(); + }); + + it("clears 1.x history even with history off", async () => { + const storage = new FakeStorage(); + await storage.put(REMOTE_HISTORY_LOG_KEY, new Uint8Array([1])); + const { maintenance, logInfo, settled } = service(null, storage); + maintenance.afterPush(VAULT_SPACE); + await settled(); + expect(await storage.exists(REMOTE_HISTORY_LOG_KEY)).toBe(false); + expect(logInfo).toHaveBeenCalledWith( + "push", + "Old-format file history removed (1 object(s)).", + ); + expect(collect).not.toHaveBeenCalled(); + }); + + it("scans for 1.x history once a session, again after a failed scan", async () => { + const storage = new FakeStorage(); + const list = vi + .spyOn(storage, "list") + .mockRejectedValueOnce(new Error("offline")); + const { maintenance, settled } = service(null, storage); + for (let run = 0; run < 3; run++) { + maintenance.afterPush(VAULT_SPACE); + await settled(); + vi.setSystemTime(Date.now() + 10 * 60_000); + } + expect(list).toHaveBeenCalledTimes(2); + }); + + it("clears 1.x history again on another storage", async () => { + const { maintenance, settled, target } = service( + null, + new FakeStorage("a"), + ); + maintenance.afterPush(VAULT_SPACE); + await settled(); + const other = new FakeStorage("b"); + await other.put(REMOTE_HISTORY_LOG_KEY, new Uint8Array([1])); + target.storage = other; + vi.setSystemTime(Date.now() + 10 * 60_000); + maintenance.afterPush(VAULT_SPACE); + await settled(); + expect(await other.exists(REMOTE_HISTORY_LOG_KEY)).toBe(false); + }); + + it("logs a failure instead of throwing it at the push", async () => { + collect.mockRejectedValue(new Error("listing failed")); + const { maintenance, logWarn, settled } = service(); + maintenance.afterPush(VAULT_SPACE); + await settled(); + await Promise.resolve(); + expect(logWarn).toHaveBeenCalledWith( + "push", + "History cleanup failed: listing failed", + ); + }); +}); diff --git a/packages/plugin/tests/features/sync/runtime/maintenance.test.ts b/packages/plugin/tests/features/sync/runtime/maintenance.test.ts new file mode 100644 index 00000000..24551f6c --- /dev/null +++ b/packages/plugin/tests/features/sync/runtime/maintenance.test.ts @@ -0,0 +1,362 @@ +import { bytesOf, compressedDrawing } from "@tests/helpers/drawing-file"; +import { FakeStorage } from "@tests/helpers/fake-storage"; +import { + manifestOf, + pinSnapshot, + seedChain, + writePushRecord, +} from "@tests/helpers/history"; +import { publishManifest } from "@tests/helpers/manifest"; +import { putChunked } from "@tests/helpers/recipes"; +import { beforeAll, describe, expect, it } from "vitest"; +import { + deriveKey, + type EncryptionKey, + encryptBytes, + encryptDescribed, + encryptJson, + sha256Hex, +} from "@/core/crypto/cipher"; +import { encodeDrawing } from "@/core/drawing"; +import { + REMOTE_OBJECTS_PREFIX, + REMOTE_PINS_PREFIX, +} from "@/features/sync/constants"; +import { + CHUNK_THRESHOLD, + chunkKey, + objectKey, +} from "@/features/sync/content/keys"; +import { storeContent } from "@/features/sync/content/store"; +import { + deepCleanOrphans, + verifyRemote, +} from "@/features/sync/runtime/maintenance"; +import type { Manifest } from "@/features/sync/types"; + +const DAY_MS = 24 * 60 * 60 * 1000; + +let key: EncryptionKey; +beforeAll(async () => { + key = await deriveKey("pw", new Uint8Array(16)); +}); + +describe("verifyRemote", () => { + it("passes on a complete remote and flags a missing object", async () => { + const storage = new FakeStorage(); + const head = manifestOf("s1", null, { "a.md": "H1" }); + await publishManifest(storage, key, head); + await storage.put(objectKey("H1"), new Uint8Array([1])); + + const ok = await verifyRemote(storage, key, "", false); + expect(ok.checked).toBe(1); + expect(ok.missing).toHaveLength(0); + + await storage.delete(objectKey("H1")); + const bad = await verifyRemote(storage, key, "", false); + expect(bad.missing).toEqual(["H1"]); + }); + + it("announces every object read before the first get", async () => { + const calls: string[] = []; + class PreparingStorage extends FakeStorage { + prepareReads(keys: string[]): void { + calls.push(`prepare:${[...keys].sort().join(",")}`); + } + override get(path: string): Promise { + if (path.startsWith(REMOTE_OBJECTS_PREFIX)) calls.push("get"); + return super.get(path); + } + } + const storage = new PreparingStorage(); + await publishManifest( + storage, + key, + manifestOf("s1", null, { "a.md": "H1", "b.md": "H2" }), + ); + await storage.put(objectKey("H1"), new Uint8Array([1])); + await storage.put(objectKey("H2"), new Uint8Array([1])); + + await verifyRemote(storage, key, "", false); + expect(calls[0]).toBe(`prepare:${objectKey("H1")},${objectKey("H2")}`); + expect(calls.filter((c) => c === "get")).toHaveLength(2); + }); +}); + +describe("verifyRemote, deep", () => { + async function remoteWith( + blobFor: (bytes: Uint8Array) => Promise, + ) { + const storage = new FakeStorage(); + const bytes = bytesOf(compressedDrawing()); + const hash = await sha256Hex(bytes); + await publishManifest( + storage, + key, + manifestOf("s1", null, { "a.excalidraw.md": hash }), + ); + await storage.put(objectKey(hash), await blobFor(bytes)); + return { storage, hash }; + } + + it("verifies a described root clean", async () => { + const { storage } = await remoteWith(async (bytes) => { + const probe = new FakeStorage(); + await storeContent( + { storage: probe, key }, + await sha256Hex(bytes), + bytes, + ); + const blob = probe.map.get(objectKey(await sha256Hex(bytes))); + expect(blob?.[0]).toBe(0x03); + return blob as Uint8Array; + }); + + expect(await verifyRemote(storage, key, "", true)).toEqual({ + checked: 1, + missing: [], + corrupt: [], + }); + }); + + it("flags a described root whose rebuilt bytes do not hash to its name", async () => { + const { storage, hash } = await remoteWith(async (bytes) => { + const encoded = encodeDrawing(bytes); + if (!encoded) throw new Error("fixture does not encode"); + return encryptDescribed( + key, + { codec: { ...encoded.codec, width: 64 } }, + encoded.stored, + ); + }); + + const result = await verifyRemote(storage, key, "", true); + expect(result.corrupt).toEqual([hash]); + expect(result.missing).toEqual([]); + // Shallow verify only checks that the object exists. + expect((await verifyRemote(storage, key, "", false)).corrupt).toEqual([]); + }); + + it("flags a described root with an unknown codec, and still reports a missing one", async () => { + const { storage, hash } = await remoteWith((bytes) => + encryptDescribed( + key, + { codec: { name: "future", width: 256, gap: "\n\n" } }, + bytes, + ), + ); + expect((await verifyRemote(storage, key, "", true)).corrupt).toEqual([ + hash, + ]); + + await storage.delete(objectKey(hash)); + expect((await verifyRemote(storage, key, "", true)).missing).toEqual([ + hash, + ]); + }); +}); + +describe("verifyRemote, chunked", () => { + async function chunkedRemote() { + const storage = new FakeStorage(); + const hash = await putChunked(storage, key, [bytesOf("ab"), bytesOf("cd")]); + const head = manifestOf("s1", null, { "big.bin": hash }); + (head.files["big.bin"] as { size: number }).size = CHUNK_THRESHOLD; + await publishManifest(storage, key, head); + return { storage, hash }; + } + + it("passes a complete chunked file, shallow and deep", async () => { + const { storage } = await chunkedRemote(); + for (const deep of [false, true]) { + expect(await verifyRemote(storage, key, "", deep)).toEqual({ + checked: 1, + missing: [], + corrupt: [], + }); + } + }); + + it("flags a missing chunk as missing, shallow and deep", async () => { + const { storage, hash } = await chunkedRemote(); + await storage.delete(chunkKey("c1")); + for (const deep of [false, true]) { + const result = await verifyRemote(storage, key, "", deep); + expect(result.missing).toEqual([hash]); + expect(result.corrupt).toEqual([]); + } + }); + + it("flags a chunk with other bytes only when deep", async () => { + const { storage, hash } = await chunkedRemote(); + await storage.put(chunkKey("c1"), await encryptBytes(key, bytesOf("xy"))); + expect((await verifyRemote(storage, key, "", false)).corrupt).toEqual([]); + expect((await verifyRemote(storage, key, "", true)).corrupt).toEqual([ + hash, + ]); + }); + + it("aborts on a failed chunk read instead of calling it corrupt", async () => { + const { storage } = await chunkedRemote(); + const get = storage.get.bind(storage); + storage.get = (storageKey) => + storageKey === chunkKey("c1") + ? Promise.reject(new Error("offline")) + : get(storageKey); + await expect(verifyRemote(storage, key, "", true)).rejects.toThrow( + "offline", + ); + }); +}); + +async function putObjects( + storage: FakeStorage, + ...hashes: string[] +): Promise { + for (const hash of hashes) { + await storage.put(objectKey(hash), new Uint8Array([1])); + } +} + +describe("deepCleanOrphans", () => { + it("removes unreachable blobs, keeps those HEAD, a push record or a pin names", async () => { + const storage = new FakeStorage(); + const chain = [ + manifestOf("s1", null, { "a.md": "H1", "b.md": "B1" }), + manifestOf("s2", "s1", { "a.md": "H2" }), + ]; + await seedChain(storage, key, chain); + await pinSnapshot(storage, key, manifestOf("p", null, { "c.md": "P1" })); + await putObjects(storage, "H1", "H2", "B1", "P1", "ORPHAN"); + await storage.put(`${REMOTE_OBJECTS_PREFIX}stray`, new Uint8Array([9])); + storage.age(DAY_MS + 1); + + const res = await deepCleanOrphans(storage, key, ""); + expect(res.deletedObjects).toBe(2); + for (const hash of ["H1", "H2", "B1", "P1"]) { + expect(await storage.exists(objectKey(hash))).toBe(true); + } + expect(await storage.exists(objectKey("ORPHAN"))).toBe(false); + expect((await deepCleanOrphans(storage, key, "")).deletedObjects).toBe(0); + }); + + it("refuses a HEAD below the fence: 1.x clients still sync and name what looks orphaned", async () => { + const storage = new FakeStorage(); + await publishManifest(storage, key, { + ...manifestOf("s1", null, { "a.md": "H1" }), + version: 2, + }); + await putObjects(storage, "H1", "OLD"); + storage.age(DAY_MS + 1); + + await expect(deepCleanOrphans(storage, key, "")).rejects.toThrow( + /old file history format/, + ); + expect(await storage.exists(objectKey("OLD"))).toBe(true); + }); + + it("refuses while a history record or pin cannot be read", async () => { + const storage = new FakeStorage(); + await seedChain(storage, key, [manifestOf("s1", null, { "a.md": "H1" })]); + await putObjects(storage, "H1", "ORPHAN"); + // A 1.x pin is a bare manifest: unreadable until the post-push cleanup deletes it. + await storage.put( + `${REMOTE_PINS_PREFIX}s0.json.enc`, + await encryptJson(key, manifestOf("s0", null, { "a.md": "ORPHAN" })), + ); + storage.age(DAY_MS + 1); + + await expect(deepCleanOrphans(storage, key, "")).rejects.toThrow( + /could not be read/, + ); + await expect(verifyRemote(storage, key, "", false)).rejects.toThrow( + /could not be read/, + ); + expect(await storage.exists(objectKey("ORPHAN"))).toBe(true); + }); + + it("keeps what was written in the last day: another device's push not yet published", async () => { + const storage = new FakeStorage(); + await seedChain(storage, key, [manifestOf("s1", null, { "a.md": "H1" })]); + await putObjects(storage, "H1", "OLD"); + storage.age(DAY_MS + 1); + await putObjects(storage, "UPLOADING"); + + expect(await deepCleanOrphans(storage, key, "")).toEqual({ + deletedObjects: 1, + }); + expect(await storage.exists(objectKey("OLD"))).toBe(false); + expect(await storage.exists(objectKey("UPLOADING"))).toBe(true); + }); + + it("needs a published HEAD", async () => { + const storage = new FakeStorage(); + await putObjects(storage, "ORPHAN"); + storage.age(DAY_MS + 1); + await expect(deepCleanOrphans(storage, key, "")).rejects.toThrow( + /No manifest/, + ); + }); +}); + +describe("deepCleanOrphans concurrency", () => { + class RacingStorage extends FakeStorage { + raceOnce: (() => Promise) | null = null; + override async listDetailed(prefix: string) { + const listed = await super.listDetailed(prefix); + const race = prefix === REMOTE_OBJECTS_PREFIX ? this.raceOnce : null; + if (race) { + this.raceOnce = null; + await race(); + } + return listed; + } + } + + it("bails when another device pins a snapshot while it lists", async () => { + // Pinning does not move HEAD, so only a pin listing catches it. + const storage = new RacingStorage(); + const chain = [ + manifestOf("s1", null, { "a.md": "H1" }), + manifestOf("s2", "s1", { "a.md": "H2" }), + ]; + await seedChain(storage, key, chain); + await putObjects(storage, "H1", "H2"); + storage.age(DAY_MS + 1); + storage.raceOnce = () => pinSnapshot(storage, key, chain[0] as Manifest); + + await expect(deepCleanOrphans(storage, key, "")).rejects.toThrow( + /pinned snapshot while cleaning/, + ); + }); + + it("bails when a record retried by another device appears while it lists", async () => { + const storage = new RacingStorage(); + const s1 = manifestOf("s1", null, { "a.md": "A1" }); + const s2 = manifestOf("s2", "s1", {}); + // Both record writes failed: only their retry names A1. + await seedChain(storage, key, [s1, s2], ["s1", "s2"]); + await putObjects(storage, "A1"); + storage.age(DAY_MS + 1); + storage.raceOnce = () => writePushRecord(storage, key, s1, null); + + await expect(deepCleanOrphans(storage, key, "")).rejects.toThrow( + /wrote file history while cleaning/, + ); + expect(await storage.exists(objectKey("A1"))).toBe(true); + }); + + it("bails when another device pushes while it lists", async () => { + const storage = new RacingStorage(); + const head = manifestOf("s1", null, { "a.md": "H1" }); + await seedChain(storage, key, [head]); + await putObjects(storage, "H1"); + storage.age(DAY_MS + 1); + storage.raceOnce = () => + publishManifest(storage, key, manifestOf("s2", "s1", { "a.md": "H1" })); + + await expect(deepCleanOrphans(storage, key, "")).rejects.toThrow( + /pushed while cleaning/, + ); + }); +}); diff --git a/packages/plugin/tests/sync/operation-runner.test.ts b/packages/plugin/tests/features/sync/runtime/operation-runner.test.ts similarity index 86% rename from packages/plugin/tests/sync/operation-runner.test.ts rename to packages/plugin/tests/features/sync/runtime/operation-runner.test.ts index d32254d2..3fce56d9 100644 --- a/packages/plugin/tests/sync/operation-runner.test.ts +++ b/packages/plugin/tests/features/sync/runtime/operation-runner.test.ts @@ -1,19 +1,24 @@ +import { Device } from "@tests/helpers/config-device"; import { createTestControllerHost } from "@tests/helpers/controller"; import type { TestSession } from "@tests/helpers/session"; import { pairedSessions, useEncryptionKey } from "@tests/helpers/session"; import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest"; -import { ESyncLogOperation } from "@/logs/store"; -import { OFFLINE_MESSAGE } from "@/shared"; -import { ShareRefusedError, StorageRequestError } from "@/storage"; -import { StorageHttpError } from "@/storage/adapters/util"; -import { SyncCancelledError } from "@/sync/cancel"; -import { splitSpaceErrors } from "@/sync/controller"; -import { ConcurrentPushError } from "@/sync/manifest"; -import { pushPathsOp } from "@/sync/operations/push"; -import { SyncControllerRuntimeState } from "@/sync/runtime/controller-state"; -import { OperationRunner } from "@/sync/runtime/operation-runner"; -import { VAULT_SPACE } from "@/sync/space"; -import type { Manifest } from "@/sync/types"; +import { ESyncLogOperation } from "@/core/logs/store"; +import { EPluginLevel } from "@/core/settings/model"; +import { OFFLINE_MESSAGE } from "@/core/shared/offline"; +import { StorageHttpError } from "@/core/shared/transport-errors"; +import { + ShareRefusedError, + StorageRequestError, +} from "@/features/storage/types"; +import { SyncCancelledError } from "@/features/sync/cancel"; +import { splitSpaceErrors } from "@/features/sync/controller"; +import { pushPathsOp } from "@/features/sync/operations/push"; +import { ConcurrentPushError } from "@/features/sync/remote/manifest"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; +import { SyncControllerRuntimeState } from "@/features/sync/runtime/controller-state"; +import { OperationRunner } from "@/features/sync/runtime/operation-runner"; +import type { Manifest } from "@/features/sync/types"; useEncryptionKey(); @@ -21,12 +26,14 @@ function createTestRunner(session: TestSession) { const host = createTestControllerHost(session); const runtimeState = new SyncControllerRuntimeState(); onTestFinished(() => runtimeState.dispose()); + const onPublished = vi.fn(); const runner = new OperationRunner({ host, runtimeState, clearFileDiffs: () => {}, + onPublished, }); - return { runner, runtimeState, host }; + return { runner, runtimeState, host, onPublished }; } const unchanged = async () => ({ @@ -37,11 +44,12 @@ const unchanged = async () => ({ describe("OperationRunner.runOperation", () => { it("reports completion only after a push that published", async () => { const [session] = pairedSessions(); - const { runner, host } = createTestRunner(session); + const { runner, host, onPublished } = createTestRunner(session); expect( await runner.runOperation(VAULT_SPACE, ESyncLogOperation.Push, unchanged), ).toEqual({ ok: true }); expect(host.onPushComplete).not.toHaveBeenCalled(); + expect(onPublished).not.toHaveBeenCalled(); const published = async () => ({ newRemote: { snapshotId: "next" } as Manifest, @@ -49,6 +57,7 @@ describe("OperationRunner.runOperation", () => { }); await runner.runOperation(VAULT_SPACE, ESyncLogOperation.Push, published); expect(host.onPushComplete).toHaveBeenCalledOnce(); + expect(onPublished).toHaveBeenCalledWith(VAULT_SPACE); }); it("refuses an operation whose space left the partition before it ran", async () => { @@ -247,6 +256,68 @@ describe("OperationRunner.runOperation", () => { expect(runtimeState.getSnapshot().error).toBeNull(); }); }); +describe("OperationRunner plugins pulled", () => { + const pulled = + (...paths: string[]) => + async () => ({ + newRemote: null, + touchedPaths: new Set(paths), + }); + + async function pluginsPulledBy( + operation: ESyncLogOperation, + paths: string[], + level: EPluginLevel = EPluginLevel.Code, + ) { + const device = new Device("device-a"); + device.settingsSync = { ...device.settingsSync, pluginConfigs: true }; + device.pluginLevel = level; + const { runner, host } = createTestRunner(device); + const onPluginsPulled = vi.fn(); + Object.assign(host, { onPluginsPulled }); + await runner.runOperation(VAULT_SPACE, operation, pulled(...paths)); + return onPluginsPulled; + } + + it("tells when a pull brings plugin code or the enabled list, even on a first sync", async () => { + for (const path of [ + ".obsidian/plugins/x/main.js", + ".obsidian/plugins/x/manifest.json", + ".obsidian/community-plugins.json", + ]) { + const onPluginsPulled = await pluginsPulledBy(ESyncLogOperation.Pull, [ + "note.md", + path, + ]); + expect(onPluginsPulled).toHaveBeenCalledOnce(); + } + }); + + it("stays quiet for a pull of notes or plugin settings alone", async () => { + for (const paths of [ + ["note.md", "folder/other.md"], + [".obsidian/plugins/x/data.json"], + // Data level takes it in, but Obsidian never reads it at startup. + [".obsidian/plugins/x/cache.json"], + [".obsidian/plugins/mdsync/main.js"], + ]) { + const onPluginsPulled = await pluginsPulledBy( + ESyncLogOperation.Pull, + paths, + EPluginLevel.Data, + ); + expect(onPluginsPulled).not.toHaveBeenCalled(); + } + }); + + it("stays quiet for a push, which only reads this device's own code", async () => { + const onPluginsPulled = await pluginsPulledBy(ESyncLogOperation.Push, [ + ".obsidian/plugins/x/main.js", + ]); + expect(onPluginsPulled).not.toHaveBeenCalled(); + }); +}); + describe("OperationRunner.refreshNow", () => { it("adopts converged files without adopting the remote's empty folders", async () => { const [a, b] = pairedSessions(); diff --git a/packages/plugin/tests/sync/refresh-queue.test.ts b/packages/plugin/tests/features/sync/runtime/refresh-queue.test.ts similarity index 91% rename from packages/plugin/tests/sync/refresh-queue.test.ts rename to packages/plugin/tests/features/sync/runtime/refresh-queue.test.ts index d706f1cc..f60f3a2e 100644 --- a/packages/plugin/tests/sync/refresh-queue.test.ts +++ b/packages/plugin/tests/features/sync/runtime/refresh-queue.test.ts @@ -1,11 +1,10 @@ import { describe, expect, it } from "vitest"; - -import { SyncControllerRuntimeState } from "@/sync/runtime/controller-state"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; +import { SyncControllerRuntimeState } from "@/features/sync/runtime/controller-state"; import { RefreshQueue, type RefreshRequest, -} from "@/sync/runtime/refresh-queue"; -import { VAULT_SPACE } from "@/sync/space"; +} from "@/features/sync/runtime/refresh-queue"; function deferred() { let resolve!: () => void; diff --git a/packages/plugin/tests/sync/saved-refresh.test.ts b/packages/plugin/tests/features/sync/runtime/saved-refresh.test.ts similarity index 92% rename from packages/plugin/tests/sync/saved-refresh.test.ts rename to packages/plugin/tests/features/sync/runtime/saved-refresh.test.ts index 0f004076..d918cce2 100644 --- a/packages/plugin/tests/sync/saved-refresh.test.ts +++ b/packages/plugin/tests/features/sync/runtime/saved-refresh.test.ts @@ -6,14 +6,14 @@ import { } from "@tests/helpers/session"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { LocalSession } from "@/core/session-factory"; -import { SyncController } from "@/sync/controller"; -import type { CompareResult } from "@/sync/engine"; -import { pushPathsOp } from "@/sync/operations/push"; -import { SyncControllerRuntimeState } from "@/sync/runtime/controller-state"; -import { SavedRefresh } from "@/sync/runtime/saved-refresh"; -import { projectSession } from "@/sync/session-state"; -import { type Space, VAULT_SPACE } from "@/sync/space"; +import type { LocalSession } from "@/features/sync"; +import { SyncController } from "@/features/sync/controller"; +import type { CompareResult } from "@/features/sync/engine"; +import { pushPathsOp } from "@/features/sync/operations/push"; +import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; +import { SyncControllerRuntimeState } from "@/features/sync/runtime/controller-state"; +import { SavedRefresh } from "@/features/sync/runtime/saved-refresh"; +import { projectSession } from "@/features/sync/session-state"; useEncryptionKey(); @@ -261,6 +261,8 @@ describe("SyncController.refreshSaved", () => { })); const controller = new SyncController({ ...host, openLocal }); await controller.refreshAndAutoSync(); + // History cleanup queued after the sync's push opens its own session. + await controller.between(async () => {}); host.openSession.mockClear(); session.adapter.putText("note.md", "two"); diff --git a/packages/plugin/tests/sync/scan-cycle.test.ts b/packages/plugin/tests/features/sync/runtime/scan-cycle.test.ts similarity index 90% rename from packages/plugin/tests/sync/scan-cycle.test.ts rename to packages/plugin/tests/features/sync/runtime/scan-cycle.test.ts index 98cfdf6c..b4078327 100644 --- a/packages/plugin/tests/sync/scan-cycle.test.ts +++ b/packages/plugin/tests/features/sync/runtime/scan-cycle.test.ts @@ -1,8 +1,7 @@ import { describe, expect, it, vi } from "vitest"; - -import { ScanCycle } from "@/sync/runtime/scan-cycle"; -import { VAULT_SPACE } from "@/sync/space"; -import type { HashCacheEntry } from "@/sync/types"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; +import { ScanCycle } from "@/features/sync/runtime/scan-cycle"; +import type { HashCacheEntry } from "@/features/sync/types"; const entry: HashCacheEntry = { hash: "h", size: 1, mtime: 1 }; diff --git a/packages/plugin/tests/features/sync/runtime/sync-gates.test.ts b/packages/plugin/tests/features/sync/runtime/sync-gates.test.ts new file mode 100644 index 00000000..46064648 --- /dev/null +++ b/packages/plugin/tests/features/sync/runtime/sync-gates.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, it } from "vitest"; +import type { SyncStatusSnapshot } from "@/features/sync/controller"; +import type { CompareResult } from "@/features/sync/engine"; +import { canPullAll, canPushAll } from "@/features/sync/runtime/sync-gates"; +import { + type Conflict, + type DiffResult, + EChangeType, + type FileChange, +} from "@/features/sync/types"; + +interface Input { + busy?: boolean; + offline?: boolean; + /** No comparison has landed. */ + uncompared?: boolean; + local?: number; + remote?: number; + conflicts?: number; +} + +function change(side: "local" | "remote", index: number): FileChange { + return { + path: `${side}-${index}.md`, + type: side === "local" ? EChangeType.LocalModify : EChangeType.RemoteModify, + localHash: "l", + remoteHash: "r", + }; +} + +function snapshot(input: Input): SyncStatusSnapshot { + const count = (n = 0) => Array.from({ length: n }, (_, index) => index); + const conflicts: Conflict[] = count(input.conflicts).map((index) => ({ + path: `both-${index}.md`, + localHash: "l", + remoteHash: "r", + baselineHash: "b", + })); + const diff: DiffResult = { + localChanges: count(input.local).map((i) => change("local", i)), + remoteChanges: count(input.remote).map((i) => change("remote", i)), + conflicts, + moves: [], + converged: [], + remoteMoved: false, + }; + const result = input.uncompared + ? null + : ({ diff } as Pick as CompareResult); + return { + busy: input.busy ?? false, + offline: input.offline ?? false, + result, + } as SyncStatusSnapshot; +} + +const CASES: Array<[string, Input, boolean, boolean]> = [ + ["only local changes", { local: 2 }, true, false], + ["only remote changes", { remote: 2 }, false, true], + ["changes on both sides", { local: 1, remote: 1 }, false, true], + ["nothing to move", {}, false, false], + ["a conflict beside local changes", { local: 1, conflicts: 1 }, false, false], + [ + "a conflict beside remote changes", + { remote: 1, conflicts: 1 }, + false, + false, + ], + ["no comparison yet", { uncompared: true }, false, false], + [ + "an operation running over local changes", + { local: 1, busy: true }, + false, + false, + ], + [ + "an operation running over remote changes", + { remote: 1, busy: true }, + false, + false, + ], + ["no connection to local changes", { local: 1, offline: true }, false, false], + [ + "no connection to remote changes", + { remote: 1, offline: true }, + false, + false, + ], +]; + +describe("canPushAll and canPullAll", () => { + it.each(CASES)("push with %s", (_, input, push) => { + expect(canPushAll(snapshot(input))).toBe(push); + }); + + it.each(CASES)("pull with %s", (_, input, _push, pull) => { + expect(canPullAll(snapshot(input))).toBe(pull); + }); +}); diff --git a/packages/plugin/tests/settings/ignore-rules.test.ts b/packages/plugin/tests/features/sync/scope/ignore-rules.test.ts similarity index 94% rename from packages/plugin/tests/settings/ignore-rules.test.ts rename to packages/plugin/tests/features/sync/scope/ignore-rules.test.ts index 87ce89ad..42c8babb 100644 --- a/packages/plugin/tests/settings/ignore-rules.test.ts +++ b/packages/plugin/tests/features/sync/scope/ignore-rules.test.ts @@ -1,10 +1,10 @@ import { describe, expect, it } from "vitest"; +import { createIgnoreMatcher } from "@/features/sync/scope/ignore"; import { appendIgnoreRule, buildIgnoreRule, removeIgnoreRule, -} from "@/settings/ignore-rules"; -import { createIgnoreMatcher } from "@/vault/ignore"; +} from "@/features/sync/scope/ignore-rules"; describe("ignore rules", () => { it("anchors a file to its exact vault path", async () => { diff --git a/packages/plugin/tests/plugin/ignore-state.test.ts b/packages/plugin/tests/features/sync/scope/ignore-state.test.ts similarity index 96% rename from packages/plugin/tests/plugin/ignore-state.test.ts rename to packages/plugin/tests/features/sync/scope/ignore-state.test.ts index 062631eb..1e6b7d90 100644 --- a/packages/plugin/tests/plugin/ignore-state.test.ts +++ b/packages/plugin/tests/features/sync/scope/ignore-state.test.ts @@ -1,8 +1,7 @@ import { TFile, TFolder } from "obsidian"; import { describe, expect, it, vi } from "vitest"; - -import { registerIgnoreState } from "@/plugin/ignore-state"; -import { type Space, VAULT_SPACE } from "@/sync/space"; +import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; +import { registerIgnoreState } from "@/features/sync/scope/ignore-state"; /** Paths ending in "/" are folders. */ function setup(notes: Record, paths: string[]) { diff --git a/packages/plugin/tests/vault/ignore.test.ts b/packages/plugin/tests/features/sync/scope/ignore.test.ts similarity index 96% rename from packages/plugin/tests/vault/ignore.test.ts rename to packages/plugin/tests/features/sync/scope/ignore.test.ts index 29eb94a5..2a2c949d 100644 --- a/packages/plugin/tests/vault/ignore.test.ts +++ b/packages/plugin/tests/features/sync/scope/ignore.test.ts @@ -1,12 +1,12 @@ import type { DataAdapter } from "obsidian"; import { describe, expect, it } from "vitest"; -import { VAULT_SPACE } from "@/sync/space"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; import { createIgnoreMatcher, ignoreHome, isIgnoreNote, loadSharedIgnoreMatcher, -} from "@/vault/ignore"; +} from "@/features/sync/scope/ignore"; describe("ignore matcher loading", () => { it("loads local ignore patterns from settings only", async () => { diff --git a/packages/plugin/tests/features/sync/scope/plugin-code.test.ts b/packages/plugin/tests/features/sync/scope/plugin-code.test.ts new file mode 100644 index 00000000..4720723d --- /dev/null +++ b/packages/plugin/tests/features/sync/scope/plugin-code.test.ts @@ -0,0 +1,177 @@ +import { Device, disabled } from "@tests/helpers/config-device"; +import { RevalidatingStorage } from "@tests/helpers/revalidating-storage"; +import { useEncryptionKey } from "@tests/helpers/session"; +import { describe, expect, it } from "vitest"; +import { EPluginLevel } from "@/core/settings/model"; +import { keepBothConflictOp } from "@/features/sync/operations/resolve"; + +useEncryptionKey(); +const data = ".obsidian/plugins/sample/data.json"; +const code = ".obsidian/plugins/sample/main.js"; + +async function pair() { + const storage = new RevalidatingStorage(); + const a = new Device("a", storage); + const b = new Device("b", storage); + for (const device of [a, b]) { + device.settingsSync = { ...disabled, pluginConfigs: true }; + } + a.adapter.putText(data, '{"a":1}'); + a.adapter.putText(code, "v1"); + await a.push(); + return { a, b }; +} + +const remoteEntry = async (device: Device, path: string) => + (await device.compare()).remote?.files[path]; + +describe("plugin settings without their code", () => { + it("pulls only data.json and never publishes this device's code", async () => { + const { a, b } = await pair(); + b.pluginLevel = EPluginLevel.Settings; + await b.pull(); + expect(b.text(data)).toBe('{"a":1}'); + expect(b.adapter.hasFile(code)).toBe(false); + + const published = await remoteEntry(a, code); + b.adapter.putText(code, "a local build"); + b.adapter.putText(data, '{"a":2}'); + await b.push(); + expect(await remoteEntry(a, code)).toEqual(published); + + await a.pull(); + expect(a.text(data)).toBe('{"a":2}'); + expect(a.text(code)).toBe("v1"); + }); + + it("leaves code synced before frozen: no update pulled, no deletion published", async () => { + const { a, b } = await pair(); + await b.pull(); + expect(b.text(code)).toBe("v1"); + b.pluginLevel = EPluginLevel.Settings; + + a.adapter.putText(code, "v2"); + await a.push(); + const published = await remoteEntry(a, code); + expect((await b.compare()).diff.remoteChanges).toEqual([]); + + await b.adapter.remove(code); + b.adapter.putText(data, '{"a":3}'); + const result = await b.compare(); + expect(result.diff.localChanges.map((change) => change.path)).toEqual([ + data, + ]); + await b.push(); + expect(await remoteEntry(a, code)).toEqual(published); + expect(b.text(data)).toBe('{"a":3}'); + }); + + it("refuses Keep both when the copy beside data.json would not sync", async () => { + const { a, b } = await pair(); + b.pluginLevel = EPluginLevel.Settings; + await b.pull(); + a.adapter.putText(data, '{"a":"there"}'); + await a.push(); + b.adapter.putText(data, '{"a":"here"}'); + const result = await b.compare(); + const published = await remoteEntry(a, data); + + await expect( + keepBothConflictOp(b.deps(), result, data, b.context()), + ).rejects.toThrow("would not sync"); + const copies = (await b.adapter.list(".obsidian/plugins/sample")).files; + expect(copies).toEqual([data]); + expect(await remoteEntry(a, data)).toEqual(published); + }); +}); + +describe("plugin levels per plugin", () => { + const x = ".obsidian/plugins/x"; + const y = ".obsidian/plugins/y"; + const files = [ + `${x}/data.json`, + `${x}/main.js`, + `${x}/sub/a.bin`, + `${y}/data.json`, + `${y}/main.js`, + ]; + + async function pairOfPlugins() { + const storage = new RevalidatingStorage(); + const a = new Device("a", storage); + const b = new Device("b", storage); + for (const device of [a, b]) { + device.settingsSync = { ...disabled, pluginConfigs: true }; + } + for (const path of files) a.adapter.putText(path, `a:${path}`); + await a.push(); + return { a, b }; + } + + it("keeps a plugin set to Off from arriving while the others do", async () => { + const { b } = await pairOfPlugins(); + b.pluginLevels = { x: EPluginLevel.Off }; + const offered = (await b.compare()).diff.remoteChanges.map((c) => c.path); + expect(offered.filter((path) => path.startsWith(x))).toEqual([]); + expect(offered).toContain(`${y}/main.js`); + await b.pull(); + for (const path of files.filter((path) => path.startsWith(x))) { + expect(b.adapter.hasFile(path)).toBe(false); + } + expect(b.text(`${y}/main.js`)).toBe(`a:${y}/main.js`); + expect(b.text(`${y}/data.json`)).toBe(`a:${y}/data.json`); + }); + + it("never publishes this device's files of a plugin set to Off", async () => { + const { a, b } = await pairOfPlugins(); + b.pluginLevels = { x: EPluginLevel.Off }; + const published = await remoteEntry(a, `${x}/data.json`); + b.adapter.putText(`${x}/data.json`, "b's own"); + b.adapter.putText(`${x}/local.bin`, "b only"); + b.adapter.putText(`${y}/extra.bin`, "y is still synced"); + await b.push(); + + expect(await remoteEntry(a, `${x}/local.bin`)).toBeUndefined(); + expect(await remoteEntry(a, `${x}/data.json`)).toEqual(published); + expect(await remoteEntry(a, `${y}/extra.bin`)).toBeDefined(); + await a.pull(); + expect(a.text(`${x}/data.json`)).toBe(`a:${x}/data.json`); + expect(a.adapter.hasFile(`${x}/local.bin`)).toBe(false); + }); + + it("publishes no deletion when this device removes the folder of a plugin set to Off", async () => { + const { a, b } = await pairOfPlugins(); + await b.pull(); + expect(b.text(`${x}/sub/a.bin`)).toBe(`a:${x}/sub/a.bin`); + b.pluginLevels = { x: EPluginLevel.Off }; + const published = await remoteEntry(a, `${x}/main.js`); + + await b.adapter.rmdir(x, true); + b.adapter.putText(`${y}/data.json`, "b's y"); + const result = await b.compare(); + expect(result.diff.localChanges.map((change) => change.path)).toEqual([ + `${y}/data.json`, + ]); + await b.push(); + + expect(await remoteEntry(a, `${x}/main.js`)).toEqual(published); + await a.pull(); + for (const path of files.filter((path) => path.startsWith(x))) { + expect(a.text(path)).toBe(`a:${path}`); + } + expect(a.text(`${y}/data.json`)).toBe("b's y"); + }); + + it("takes just the plugins with a level while plugin configuration is off", async () => { + const { b } = await pairOfPlugins(); + b.settingsSync = { ...disabled }; + b.pluginLevels = { x: EPluginLevel.Code }; + await b.pull(); + + expect(b.text(`${x}/data.json`)).toBe(`a:${x}/data.json`); + expect(b.text(`${x}/main.js`)).toBe(`a:${x}/main.js`); + expect(b.adapter.hasFile(`${x}/sub/a.bin`)).toBe(false); + expect(b.adapter.hasFile(`${y}/data.json`)).toBe(false); + expect(b.adapter.hasFile(`${y}/main.js`)).toBe(false); + }); +}); diff --git a/packages/plugin/tests/vault/scanner-index.test.ts b/packages/plugin/tests/features/sync/scope/scanner-index.test.ts similarity index 97% rename from packages/plugin/tests/vault/scanner-index.test.ts rename to packages/plugin/tests/features/sync/scope/scanner-index.test.ts index 1b9cf1ac..f9b2373a 100644 --- a/packages/plugin/tests/vault/scanner-index.test.ts +++ b/packages/plugin/tests/features/sync/scope/scanner-index.test.ts @@ -1,12 +1,15 @@ import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; import type { DataAdapter } from "obsidian"; import { describe, expect, it } from "vitest"; -import type { SettingsSyncCategories } from "@/settings/model"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; -import type { VaultIndex } from "@/vault/file-index"; -import { createIgnoreMatcher } from "@/vault/ignore"; -import { scanVault } from "@/vault/scanner"; -import { createScopePolicy, type ScopeOptions } from "@/vault/scope"; +import type { SettingsSyncCategories } from "@/core/settings/model"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import type { VaultIndex } from "@/core/vault/file-index"; +import { createIgnoreMatcher } from "@/features/sync/scope/ignore"; +import { scanVault } from "@/features/sync/scope/scanner"; +import { + createScopePolicy, + type ScopeOptions, +} from "@/features/sync/scope/scope"; const CONFIG = ".obsidian"; const options = { maxFileBytes: 1000, concurrency: 2 }; @@ -186,7 +189,7 @@ describe("scanVault with a vault index", () => { [`${CONFIG}/app.json`]: "{}", [`${CONFIG}/hotkeys.json`]: "{}", [`${CONFIG}/snippets/s.css`]: "body{}", - [`${CONFIG}/plugins/other/main.js`]: "code", + [`${CONFIG}/plugins/other/data.json`]: "{}", }); const { snapshot } = await scanVault( @@ -198,7 +201,7 @@ describe("scanVault with a vault index", () => { expect(Object.keys(snapshot.files).sort()).toEqual([ `${CONFIG}/hotkeys.json`, - `${CONFIG}/plugins/other/main.js`, + `${CONFIG}/plugins/other/data.json`, `${CONFIG}/snippets/s.css`, "a.md", ]); diff --git a/packages/plugin/tests/vault/scanner-memory.test.ts b/packages/plugin/tests/features/sync/scope/scanner-memory.test.ts similarity index 86% rename from packages/plugin/tests/vault/scanner-memory.test.ts rename to packages/plugin/tests/features/sync/scope/scanner-memory.test.ts index 3e758781..29de4b60 100644 --- a/packages/plugin/tests/vault/scanner-memory.test.ts +++ b/packages/plugin/tests/features/sync/scope/scanner-memory.test.ts @@ -1,12 +1,12 @@ import type { DataAdapter } from "obsidian"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { sha256Hex } from "@/crypto"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; -import { scanVault } from "@/vault/scanner"; -import { createScopePolicy } from "@/vault/scope"; +import { sha256Hex } from "@/core/crypto/cipher"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import { scanVault } from "@/features/sync/scope/scanner"; +import { createScopePolicy } from "@/features/sync/scope/scope"; -vi.mock("@/crypto", () => ({ sha256Hex: vi.fn() })); +vi.mock("@/core/crypto/cipher", () => ({ sha256Hex: vi.fn() })); const LARGE_BYTES = 8 * 1024 * 1024; const paths = ["a.bin", "b.bin", "c.bin", "d.bin"]; diff --git a/packages/plugin/tests/vault/scanner-scope.test.ts b/packages/plugin/tests/features/sync/scope/scanner-scope.test.ts similarity index 96% rename from packages/plugin/tests/vault/scanner-scope.test.ts rename to packages/plugin/tests/features/sync/scope/scanner-scope.test.ts index 22456805..584646d7 100644 --- a/packages/plugin/tests/vault/scanner-scope.test.ts +++ b/packages/plugin/tests/features/sync/scope/scanner-scope.test.ts @@ -1,12 +1,19 @@ import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; import { describe, expect, it } from "vitest"; -import type { SettingsSyncCategories } from "@/settings/model"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; -import { diff } from "@/sync/diff"; -import { EFileKind, type Manifest, type ManifestEntry } from "@/sync/types"; -import { createIgnoreMatcher } from "@/vault/ignore"; -import { scanVault } from "@/vault/scanner"; -import { createScopePolicy, type ScopeOptions } from "@/vault/scope"; +import type { SettingsSyncCategories } from "@/core/settings/model"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import { diff } from "@/features/sync/changes/diff"; +import { createIgnoreMatcher } from "@/features/sync/scope/ignore"; +import { scanVault } from "@/features/sync/scope/scanner"; +import { + createScopePolicy, + type ScopeOptions, +} from "@/features/sync/scope/scope"; +import { + EFileKind, + type Manifest, + type ManifestEntry, +} from "@/features/sync/types"; const CONFIG = ".obsidian"; diff --git a/packages/plugin/tests/vault/scanner-spaces.test.ts b/packages/plugin/tests/features/sync/scope/scanner-spaces.test.ts similarity index 93% rename from packages/plugin/tests/vault/scanner-spaces.test.ts rename to packages/plugin/tests/features/sync/scope/scanner-spaces.test.ts index f3882bfb..b7e8b360 100644 --- a/packages/plugin/tests/vault/scanner-spaces.test.ts +++ b/packages/plugin/tests/features/sync/scope/scanner-spaces.test.ts @@ -1,10 +1,17 @@ import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; import { describe, expect, it } from "vitest"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; -import { diff } from "@/sync/diff"; -import type { HashCacheEntry, Manifest, ManifestEntry } from "@/sync/types"; -import { scanVault } from "@/vault/scanner"; -import { createScopePolicy, type ScopeOptions } from "@/vault/scope"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import { diff } from "@/features/sync/changes/diff"; +import { scanVault } from "@/features/sync/scope/scanner"; +import { + createScopePolicy, + type ScopeOptions, +} from "@/features/sync/scope/scope"; +import type { + HashCacheEntry, + Manifest, + ManifestEntry, +} from "@/features/sync/types"; const CONFIG = ".obsidian"; const options = { maxFileBytes: 1000, concurrency: 2 }; diff --git a/packages/plugin/tests/vault/scope-spaces.test.ts b/packages/plugin/tests/features/sync/scope/scope-spaces.test.ts similarity index 96% rename from packages/plugin/tests/vault/scope-spaces.test.ts rename to packages/plugin/tests/features/sync/scope/scope-spaces.test.ts index 9114fa20..36895716 100644 --- a/packages/plugin/tests/vault/scope-spaces.test.ts +++ b/packages/plugin/tests/features/sync/scope/scope-spaces.test.ts @@ -1,7 +1,10 @@ import { describe, expect, it } from "vitest"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; -import { createIgnoreMatcher } from "@/vault/ignore"; -import { createScopePolicy, type ScopeOptions } from "@/vault/scope"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import { createIgnoreMatcher } from "@/features/sync/scope/ignore"; +import { + createScopePolicy, + type ScopeOptions, +} from "@/features/sync/scope/scope"; const CONFIG = ".obsidian"; diff --git a/packages/plugin/tests/features/sync/scope/scope.test.ts b/packages/plugin/tests/features/sync/scope/scope.test.ts new file mode 100644 index 00000000..1257827d --- /dev/null +++ b/packages/plugin/tests/features/sync/scope/scope.test.ts @@ -0,0 +1,350 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_SETTINGS_SYNC, EPluginLevel } from "@/core/settings/model"; +import { + createScopePolicy, + type ScopeOptions, +} from "@/features/sync/scope/scope"; + +describe("ScopePolicy getCategory", () => { + const scope = createScopePolicy({ + settingsSync: DEFAULT_SETTINGS_SYNC, + configDir: ".obsidian", + }); + + it("identifies core settings files", () => { + expect(scope.getCategory(".obsidian/app.json")).toBe("coreSettings"); + expect(scope.getCategory(".obsidian/appearance.json")).toBe("coreSettings"); + expect(scope.getCategory(".obsidian/core-plugins.json")).toBe( + "coreSettings", + ); + expect(scope.getCategory(".obsidian/graph.json")).toBe("coreSettings"); + expect(scope.getCategory(".obsidian/bookmarks.json")).toBe("coreSettings"); + expect(scope.getCategory(".obsidian/templates.json")).toBe("coreSettings"); + }); + + it("identifies hotkeys file", () => { + expect(scope.getCategory(".obsidian/hotkeys.json")).toBe("hotkeys"); + }); + + it("identifies community plugins list", () => { + expect(scope.getCategory(".obsidian/community-plugins.json")).toBe( + "pluginList", + ); + }); + + it("identifies plugin configs", () => { + expect(scope.getCategory(".obsidian/plugins/dataview/data.json")).toBe( + "pluginConfigs", + ); + expect(scope.getCategory(".obsidian/plugins/dataview/")).toBe( + "pluginConfigs", + ); + expect( + scope.getCategory(".obsidian/plugins/obsidian-git/data.json"), + ).toBeNull(); + expect(scope.getCategory(".obsidian/plugins/mdsync/data.json")).toBeNull(); + }); + + it("identifies snippets", () => { + expect(scope.getCategory(".obsidian/snippets/custom.css")).toBe("snippets"); + expect(scope.getCategory(".obsidian/snippets/")).toBe("snippets"); + }); + + it("identifies themes", () => { + expect(scope.getCategory(".obsidian/themes/Minimal/theme.css")).toBe( + "themes", + ); + expect(scope.getCategory(".obsidian/themes/")).toBe("themes"); + }); + + it("returns null for unknown config files", () => { + expect(scope.getCategory(".obsidian/workspace.json")).toBeNull(); + expect(scope.getCategory(".obsidian/unknown.json")).toBeNull(); + }); + + it("returns null for non-config files", () => { + expect(scope.getCategory("Welcome.md")).toBeNull(); + expect(scope.getCategory("folder/note.md")).toBeNull(); + }); +}); + +describe("ScopePolicy plugin code", () => { + const scopeOf = (extra: Partial = {}) => + createScopePolicy({ + settingsSync: { ...DEFAULT_SETTINGS_SYNC, pluginConfigs: true }, + configDir: ".obsidian", + ...extra, + }); + const plugin = ".obsidian/plugins/dataview"; + + it("takes only each plugin's data.json by default", () => { + const scope = scopeOf(); + expect(scope.includes(`${plugin}/data.json`)).toBe(true); + for (const path of [ + `${plugin}/main.js`, + `${plugin}/manifest.json`, + `${plugin}/sub/data.json`, + ".obsidian/plugins/data.json", + ]) { + expect(scope.includes(path)).toBe(false); + } + expect(scope.canDescend(".obsidian/plugins")).toBe(true); + expect(scope.canDescend(plugin)).toBe(true); + expect(scope.canDescend(`${plugin}/sub`)).toBe(false); + }); + + it("keeps code in its category, so a reset still clears the folder whole", () => { + expect(scopeOf().getCategory(`${plugin}/main.js`)).toBe("pluginConfigs"); + }); + + it("takes plugin folders whole when asked", () => { + const scope = scopeOf({ pluginLevel: EPluginLevel.Data }); + expect(scope.includes(`${plugin}/main.js`)).toBe(true); + expect(scope.includes(`${plugin}/sub/data.json`)).toBe(true); + expect(scope.canDescend(`${plugin}/sub`)).toBe(true); + }); + + it("keeps MDSync and device-local plugins out at any level", () => { + for (const scope of [ + scopeOf(), + scopeOf({ pluginLevel: EPluginLevel.Data }), + ]) { + expect(scope.includes(".obsidian/plugins/obsidian-git/data.json")).toBe( + false, + ); + expect(scope.includes(".obsidian/plugins/mdsync/data.json")).toBe(false); + } + }); +}); + +describe("ScopePolicy plugin levels", () => { + const scopeOf = (extra: Partial = {}) => + createScopePolicy({ + settingsSync: { ...DEFAULT_SETTINGS_SYNC, pluginConfigs: true }, + configDir: ".obsidian", + ...extra, + }); + const x = ".obsidian/plugins/x"; + const y = ".obsidian/plugins/y"; + const parts = [ + "data.json", + "manifest.json", + "main.js", + "styles.css", + "", + "cache.json", + "sub/a.bin", + ]; + const at = (id: string, part: string) => + part ? `.obsidian/plugins/${id}/${part}` : `.obsidian/plugins/${id}`; + const included = (scope: ReturnType, id: string) => + parts.filter((part) => scope.includes(at(id, part))); + + it.each([ + ["Off", EPluginLevel.Off, [], [true, false, false]], + ["Settings", EPluginLevel.Settings, ["data.json"], [true, true, false]], + [ + "Code", + EPluginLevel.Code, + ["data.json", "manifest.json", "main.js", "styles.css"], + [true, true, false], + ], + ["Data", EPluginLevel.Data, parts, [true, true, true]], + ])( + "syncs at %s level what that level adds to the ones before", + (_, level, files, dirs) => { + const scope = scopeOf({ pluginLevels: { x: level } }); + expect(included(scope, "x")).toEqual(files); + expect([ + scope.canDescend(".obsidian/plugins"), + scope.canDescend(x), + scope.canDescend(`${x}/sub`), + ]).toEqual(dirs); + }, + ); + + it("goes down a subfolder of a plugin at the data level", () => { + const scope = scopeOf({ pluginLevels: { x: EPluginLevel.Data } }); + expect(scope.canDescend(`${x}/sub/deep`)).toBe(true); + expect(scope.includes(`${x}/sub/deep/b.bin`)).toBe(true); + }); + + it("gives every plugin without its own level the default one", () => { + const scope = scopeOf({ pluginLevel: EPluginLevel.Code }); + expect(included(scope, "x")).toEqual(included(scope, "y")); + expect(included(scope, "y")).toContain("main.js"); + expect(included(scope, "y")).not.toContain("cache.json"); + }); + + it("lets a plugin's level win over the default, up or down", () => { + const down = scopeOf({ + pluginLevel: EPluginLevel.Data, + pluginLevels: { x: EPluginLevel.Settings }, + }); + expect(included(down, "x")).toEqual(["data.json"]); + expect(included(down, "y")).toEqual(parts); + expect(down.canDescend(`${x}/sub`)).toBe(false); + expect(down.canDescend(`${y}/sub`)).toBe(true); + + const up = scopeOf({ pluginLevels: { x: EPluginLevel.Data } }); + expect(included(up, "x")).toEqual(parts); + expect(included(up, "y")).toEqual(["data.json"]); + expect(up.canDescend(`${x}/sub`)).toBe(true); + expect(up.canDescend(`${y}/sub`)).toBe(false); + + const off = scopeOf({ pluginLevels: { x: EPluginLevel.Off } }); + expect(included(off, "x")).toEqual([]); + expect(off.canDescend(x)).toBe(false); + expect(included(off, "y")).toEqual(["data.json"]); + }); + + describe("with plugin configuration off", () => { + const scope = scopeOf({ + settingsSync: DEFAULT_SETTINGS_SYNC, + pluginLevels: { x: EPluginLevel.Code }, + }); + + it("syncs only the plugin with a level", () => { + expect(included(scope, "x")).toEqual([ + "data.json", + "manifest.json", + "main.js", + "styles.css", + ]); + expect(included(scope, "y")).toEqual([]); + expect(scope.includes(".obsidian/app.json")).toBe(false); + expect(scope.includes(".obsidian/community-plugins.json")).toBe(false); + }); + + it("reaches that plugin through the config folder and nothing else", () => { + expect(scope.canDescend(".obsidian")).toBe(true); + expect(scope.canDescend(".obsidian/plugins")).toBe(true); + expect(scope.canDescend(x)).toBe(true); + expect(scope.canDescend(`${x}/sub`)).toBe(false); + expect(scope.canDescend(y)).toBe(false); + expect(scope.canDescend(".obsidian/snippets")).toBe(false); + }); + }); + + it("does not enter the plugins folder when every level is off", () => { + const scopes = [ + scopeOf({ settingsSync: DEFAULT_SETTINGS_SYNC }), + scopeOf({ + settingsSync: DEFAULT_SETTINGS_SYNC, + pluginLevels: { x: EPluginLevel.Off }, + }), + scopeOf({ + pluginLevel: EPluginLevel.Off, + pluginLevels: { x: EPluginLevel.Off }, + }), + ]; + for (const scope of scopes) { + expect(scope.canDescend(".obsidian/plugins")).toBe(false); + expect(scope.canDescend(x)).toBe(false); + expect(included(scope, "x")).toEqual([]); + } + expect(scopes[0]?.canDescend(".obsidian")).toBe(false); + }); + + it("never takes MDSync or a device-local plugin, whatever level they are given", () => { + const levels = { + mdsync: EPluginLevel.Data, + "obsidian-git": EPluginLevel.Data, + "file-recovery": EPluginLevel.Data, + }; + for (const settingsSync of [ + DEFAULT_SETTINGS_SYNC, + { ...DEFAULT_SETTINGS_SYNC, pluginConfigs: true }, + ]) { + const scope = scopeOf({ settingsSync, pluginLevels: levels }); + for (const id of Object.keys(levels)) { + expect(included(scope, id).filter(Boolean)).toEqual([]); + expect(scope.canDescend(`.obsidian/plugins/${id}`)).toBe(false); + expect(scope.pluginIdOf(at(id, "data.json"))).toBeNull(); + } + } + }); + + it("never takes the folder entry of MDSync or a device-local plugin", () => { + const scope = scopeOf({ + pluginLevel: EPluginLevel.Data, + pluginLevels: { mdsync: EPluginLevel.Data }, + }); + for (const id of ["mdsync", "obsidian-git", "file-recovery"]) { + expect.soft(scope.includes(at(id, "")), `includes ${id}`).toBe(false); + expect.soft(scope.pluginIdOf(at(id, "")), `pluginIdOf ${id}`).toBeNull(); + expect + .soft(scope.loadsOnStartup(at(id, "")), `loadsOnStartup ${id}`) + .toBe(false); + } + }); + + it("names the plugins whose code Obsidian reads only at startup", () => { + const scope = scopeOf({ pluginLevel: EPluginLevel.Data }); + for (const part of ["manifest.json", "main.js", "styles.css"]) { + expect(scope.loadsOnStartup(at("x", part))).toBe(true); + } + for (const part of ["data.json", "cache.json", "sub/a.bin", ""]) { + expect(scope.loadsOnStartup(at("x", part))).toBe(false); + } + expect(scope.loadsOnStartup(".obsidian/community-plugins.json")).toBe(true); + for (const path of [ + ".obsidian/app.json", + ".obsidian/snippets/main.js", + ".obsidian/plugins/mdsync/main.js", + ".obsidian/plugins/obsidian-git/main.js", + "main.js", + "note.md", + ]) { + expect(scope.loadsOnStartup(path)).toBe(false); + } + }); + + it("names the plugin a path belongs to, and none outside the synced ones", () => { + const scope = scopeOf(); + for (const part of ["data.json", "main.js", "", "sub/a.bin"]) { + expect(scope.pluginIdOf(at("x", part))).toBe("x"); + } + for (const path of [ + ".obsidian/plugins/mdsync/data.json", + ".obsidian/plugins/obsidian-git/main.js", + ".obsidian/plugins/file-recovery/data.json", + ".obsidian/app.json", + ".obsidian/community-plugins.json", + ".obsidian/snippets/a.css", + "plugins/x/data.json", + "note.md", + ]) { + expect(scope.pluginIdOf(path)).toBeNull(); + } + }); +}); + +describe("ScopePolicy isSettingsJson", () => { + const scope = createScopePolicy({ + settingsSync: DEFAULT_SETTINGS_SYNC, + pluginLevel: EPluginLevel.Data, + configDir: ".obsidian", + }); + + it("names Obsidian's settings and plugins' data.json, never code or notes", () => { + for (const path of [ + ".obsidian/app.json", + ".obsidian/hotkeys.json", + ".obsidian/community-plugins.json", + ".obsidian/plugins/dataview/data.json", + ]) { + expect(scope.isSettingsJson(path)).toBe(true); + } + for (const path of [ + ".obsidian/plugins/dataview/manifest.json", + ".obsidian/plugins/dataview/sub/data.json", + ".obsidian/themes/Minimal/manifest.json", + ".obsidian/workspace.json", + "data.json", + "note.md", + ]) { + expect(scope.isSettingsJson(path)).toBe(false); + } + }); +}); diff --git a/packages/plugin/tests/sync/session-state.test.ts b/packages/plugin/tests/features/sync/session-state.test.ts similarity index 95% rename from packages/plugin/tests/sync/session-state.test.ts rename to packages/plugin/tests/features/sync/session-state.test.ts index 28d40d4b..c530c2bb 100644 --- a/packages/plugin/tests/sync/session-state.test.ts +++ b/packages/plugin/tests/features/sync/session-state.test.ts @@ -1,22 +1,22 @@ import { describe, expect, it } from "vitest"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; -import type { CompareResult, EngineDependencies } from "@/sync/engine"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import type { CompareResult, EngineDependencies } from "@/features/sync/engine"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; +import { createScopePolicy } from "@/features/sync/scope/scope"; import { carryHashes, mergeSessionIntoLocal, projectSession, recomputeAfterWrite, sharesHold, -} from "@/sync/session-state"; -import { VAULT_SPACE } from "@/sync/space"; +} from "@/features/sync/session-state"; import type { LocalState, Manifest, ManifestEntry, SessionState, -} from "@/sync/types"; -import { EFileKind } from "@/sync/types"; -import { createScopePolicy } from "@/vault/scope"; +} from "@/features/sync/types"; +import { EFileKind } from "@/features/sync/types"; const TEAM = { id: "team", root: "Team" }; diff --git a/packages/plugin/tests/ui/skipped.test.ts b/packages/plugin/tests/features/sync/skipped.test.ts similarity index 86% rename from packages/plugin/tests/ui/skipped.test.ts rename to packages/plugin/tests/features/sync/skipped.test.ts index 261bc630..e959ae65 100644 --- a/packages/plugin/tests/ui/skipped.test.ts +++ b/packages/plugin/tests/features/sync/skipped.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from "vitest"; -import type { SyncController } from "@/sync/controller"; -import type { SkippedFile } from "@/sync/types"; -import { skippedFiles, skippedText } from "@/ui/common"; +import type { SyncController } from "@/features/sync/controller"; +import type { SkippedFile } from "@/features/sync/types"; +import { skippedFiles, skippedText } from "@/features/sync/ui/skipped"; const MIB = 1024 * 1024; diff --git a/packages/plugin/tests/sync/transfer-memory.test.ts b/packages/plugin/tests/features/sync/transfer-memory.test.ts similarity index 92% rename from packages/plugin/tests/sync/transfer-memory.test.ts rename to packages/plugin/tests/features/sync/transfer-memory.test.ts index 912072c5..e6f3bb21 100644 --- a/packages/plugin/tests/sync/transfer-memory.test.ts +++ b/packages/plugin/tests/features/sync/transfer-memory.test.ts @@ -1,9 +1,8 @@ import { pairedSessions, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it, vi } from "vitest"; - -import { pushPaths } from "@/sync/engine"; -import { pullPaths } from "@/sync/pull"; -import { LARGE_FILE_BYTES } from "@/utils"; +import { pullPaths } from "@/features/sync/apply/pull"; +import { LARGE_FILE_BYTES } from "@/features/sync/changes/file-concurrency"; +import { pushPaths } from "@/features/sync/engine"; useEncryptionKey(); diff --git a/packages/plugin/tests/settings/security-section.test.ts b/packages/plugin/tests/features/sync/ui/encryption-section.test.ts similarity index 87% rename from packages/plugin/tests/settings/security-section.test.ts rename to packages/plugin/tests/features/sync/ui/encryption-section.test.ts index 30898c02..038da081 100644 --- a/packages/plugin/tests/settings/security-section.test.ts +++ b/packages/plugin/tests/features/sync/ui/encryption-section.test.ts @@ -1,22 +1,25 @@ import { Setting } from "obsidian"; import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { PluginHost } from "@/app/host"; +import { askNewPassphrase } from "@/core/ui/modals/passphrase-modal"; +import { notifyInfo, reportError } from "@/core/ui/notices"; +import { isStorageConfigured } from "@/features/storage"; +import { encryptionSection } from "@/features/sync/ui/encryption-section"; -import type { PluginHost } from "@/plugin/host"; -import { isStorageConfigured } from "@/settings/model"; -import { securitySection } from "@/settings/sections/security"; -import { askNewPassphrase, notifyInfo, reportError } from "@/ui"; - -vi.mock("@/settings/model", () => ({ isStorageConfigured: vi.fn(() => true) })); -vi.mock("@/crypto/passphrase-cache", () => ({ - clearCachedPassphrase: vi.fn(), +vi.mock("@/features/storage/settings", async (importOriginal) => ({ + ...(await importOriginal>()), + isStorageConfigured: vi.fn(() => true), })); -vi.mock("@/ui", () => ({ +vi.mock("@/core/ui/modals/passphrase-modal", () => ({ askNewPassphrase: vi.fn(), +})); +vi.mock("@/core/ui/notices", () => ({ notifyInfo: vi.fn(), notifyError: vi.fn(), reportError: vi.fn(), })); -vi.mock("obsidian", () => ({ +vi.mock("obsidian", async (importOriginal) => ({ + ...(await importOriginal>()), Setting: class { name = ""; desc = ""; @@ -78,7 +81,7 @@ function form(loaded = false) { rotate: vi.fn(async () => 2), }; const rerender = vi.fn(); - const definitions = securitySection({ + const definitions = encryptionSection({ plugin: { settings: {}, passphrase } as unknown as PluginHost, rerender, }); diff --git a/packages/plugin/tests/features/sync/ui/history/calendar.test.ts b/packages/plugin/tests/features/sync/ui/history/calendar.test.ts new file mode 100644 index 00000000..09c0b414 --- /dev/null +++ b/packages/plugin/tests/features/sync/ui/history/calendar.test.ts @@ -0,0 +1,268 @@ +import { afterEach, describe, expect, it } from "vitest"; +import type { Activity, Dating, Resolution } from "@/features/sync"; +import { + bandsOf, + buildCalendar, + type CalendarDay, + dayTooltip, + ladderOf, +} from "@/features/sync/ui/history/calendar"; + +// Wednesday. +const NOW = new Date(2026, 9, 28, 15, 0).getTime(); +const HOUR = 3_600_000; + +function local(month: number, day: number, hour = 12): number { + return new Date(2026, month, day, hour).getTime(); +} + +function activity(...pushes: Array<[number, number]>): Activity { + const result: Activity = {}; + for (const [at, count] of pushes) { + const hour = Math.floor(at / HOUR); + result[hour] = [(result[hour]?.[0] ?? 0) + count, count]; + } + return result; +} + +function dated(at: number, res: Resolution | null, firstAt = at): Dating { + return { at, firstAt, pushes: 1, res }; +} + +function dayOf(calendar: ReturnType, start: number) { + return calendar.weeks + .flatMap((week) => week.days) + .find((day) => day.start === start); +} + +describe("buildCalendar", () => { + it("lays weeks from Monday to today and sums pushes per local day", () => { + const calendar = buildCalendar( + activity([local(9, 28, 1), 3], [local(9, 28, 23), 2], [local(9, 26), 30]), + [dated(local(9, 28), "push")], + 2, + NOW, + ); + expect(calendar.since).toBe(new Date(2026, 9, 19).getTime()); + expect(calendar.weeks.map((week) => week.days.length)).toEqual([7, 3]); + expect(calendar.pushes).toBe(35); + expect(dayOf(calendar, new Date(2026, 9, 28).getTime())).toMatchObject({ + pushes: 5, + level: 1, + }); + expect(dayOf(calendar, new Date(2026, 9, 26).getTime())?.level).toBe(4); + }); + + it("rates days from 0 to 4 at 5, 12 and 24 pushes", () => { + const days = [0, 5, 6, 12, 13, 24, 25].map((count, index) => + index === 0 ? [local(9, 19), 0] : [local(9, 19 + index), count], + ) as Array<[number, number]>; + const calendar = buildCalendar(activity(...days), [], 2, NOW); + expect(calendar.weeks[0]?.days.map((day) => day.level)).toEqual([ + 0, 1, 2, 2, 3, 3, 4, + ]); + }); + + it("keeps a day at the coarsest version covering it, counts from the first push to the oldest", () => { + const calendar = buildCalendar( + activity([local(9, 20), 4]), + [ + dated(local(9, 28), "push"), + dated(local(9, 27, 18), "10m"), + dated(local(9, 27, 20), "1h", local(9, 26, 9)), + dated(local(9, 21), "1d", local(9, 21, 8)), + dated(local(9, 1), null), + ], + 2, + NOW, + ); + const res = calendar.weeks.flatMap((week) => + week.days.map((day) => day.res), + ); + expect(res).toEqual([ + null, + "counts", + "1d", + null, + null, + null, + null, + "1h", + "1h", + "push", + ]); + expect(calendar.weeks.map((week) => week.res)).toEqual(["1d", "push"]); + }); + + it("names no resolution when the versions are unknown", () => { + const calendar = buildCalendar(activity([local(9, 20), 4]), null, 2, NOW); + expect(dayOf(calendar, new Date(2026, 9, 20).getTime())).toMatchObject({ + pushes: 4, + res: null, + }); + expect(bandsOf(calendar.weeks)).toEqual([{ res: null, weeks: 2 }]); + }); + + it("carries the newer week's resolution over a week no version covers", () => { + const calendar = buildCalendar( + activity([local(9, 7), 1], [local(9, 28), 1]), + [dated(local(9, 28), "1h"), dated(local(9, 7), "1d")], + 4, + NOW, + ); + expect(calendar.weeks.map((week) => week.res)).toEqual([ + "1d", + "1h", + "1h", + "1h", + ]); + expect(bandsOf(calendar.weeks)).toEqual([ + { res: "1d", weeks: 1 }, + { res: "1h", weeks: 3 }, + ]); + }); + + it("keeps only counts without a version, and nothing before the first push", () => { + const calendar = buildCalendar(activity([local(9, 27), 2]), [], 1, NOW); + expect(calendar.weeks[0]?.days.map((day) => day.res)).toEqual([ + null, + "counts", + "counts", + ]); + }); + + it("leaves weeks before the first push without a band", () => { + const calendar = buildCalendar( + activity([local(9, 27), 2]), + [dated(local(9, 28), "push")], + 3, + NOW, + ); + expect(calendar.weeks.map((week) => week.res)).toEqual([ + null, + null, + "push", + ]); + }); + + it("starts a month label on the week its first Monday falls in", () => { + const calendar = buildCalendar({}, [], 6, NOW); + expect(calendar.weeks.map((week) => week.month)).toEqual([ + null, + null, + new Date(2026, 9, 1).toLocaleDateString(undefined, { month: "short" }), + null, + null, + null, + ]); + }); + + it("counts a DST day once, by its local date", () => { + // Europe and the US leave summer time on Oct 25 and Nov 1 2026; either way each hour lands on one day. + const hours = Array.from({ length: 48 }, (_, index): [number, number] => [ + new Date(2026, 9, 24).getTime() + index * HOUR, + 1, + ]); + const calendar = buildCalendar(activity(...hours), [], 2, NOW); + const total = calendar.weeks + .flatMap((week) => week.days) + .reduce((sum, day) => sum + day.pushes, 0); + expect(total).toBe(48); + }); +}); + +describe("buildCalendar across a skipped midnight", () => { + const zone = process.env.TZ; + afterEach(() => { + if (zone === undefined) delete process.env.TZ; + else process.env.TZ = zone; + }); + + it("keeps each day to its own midnights", () => { + // Chile skips 2026-09-06 00:00; Monday's first hour is not Sunday's. + process.env.TZ = "America/Santiago"; + const at = (day: number, hour: number, minute = 0) => + new Date(2026, 8, day, hour, minute).getTime(); + const calendar = buildCalendar( + activity([at(6, 12), 3], [at(1, 12), 2]), + [dated(at(7, 0, 30), "1h")], + 2, + at(9, 12), + ); + const days = calendar.weeks.flatMap((week) => week.days); + expect(days.every((day) => new Date(day.start).getMinutes() === 0)).toBe( + true, + ); + expect(days.find((day) => day.start === at(1, 0))?.pushes).toBe(2); + const sunday = days.find((day) => new Date(day.start).getDate() === 6); + expect(sunday).toMatchObject({ pushes: 3, res: "counts" }); + expect(days.find((day) => day.start === at(7, 0))?.res).toBe("1h"); + }); +}); + +describe("buildCalendar on a long walk", () => { + it("takes any number of versions", () => { + const versions = Array.from({ length: 200_000 }, (_, index) => + dated(local(9, 28) - index, "push"), + ); + expect(() => buildCalendar({}, versions, 1, NOW)).not.toThrow(); + }); +}); + +describe("dayTooltip", () => { + const day = (pushes: number, res: Resolution | null): CalendarDay => ({ + start: local(9, 14, 0), + pushes, + level: 0, + res, + }); + const date = new Date(local(9, 14, 0)).toLocaleDateString(undefined, { + weekday: "short", + day: "numeric", + month: "short", + }); + + it("says the pushes and how the day is kept", () => { + expect(dayTooltip(day(21, "1d"), NOW)).toBe( + `${date}: 21 pushes · versions 1 per day`, + ); + expect(dayTooltip(day(1, "counts"), NOW)).toBe( + `${date}: 1 push · only counts kept`, + ); + expect(dayTooltip(day(0, "1d"), NOW)).toBe(`${date}: no pushes`); + }); +}); + +describe("ladderOf", () => { + const DAY = 24 * HOUR; + const steps = (horizon: number | null) => + ladderOf(horizon, NOW).map((step) => `${step.title} · ${step.span}`); + + it("climbs from every push to activity only, the last version back to the counts cutoff", () => { + const ladder = steps(91 * DAY); + expect(ladder.slice(0, 4)).toEqual([ + "Every push · Last hour", + "1 per 10 min · Last 24 hours", + "1 per hour · Last 7 days", + "1 per day · Last 30 days", + ]); + expect(ladder[4]).toMatch(/^1 per week · Back to /); + expect(ladder[5]).toBe("Activity only · Older"); + }); + + it("leaves out a week a short horizon never keeps", () => { + const ladder = steps(7 * DAY); + expect(ladder.map((step) => step.split(" · ")[0])).toEqual([ + "Every push", + "1 per 10 min", + "1 per hour", + "1 per day", + "Activity only", + ]); + expect(ladder[3]).toMatch(/^1 per day · Back to /); + }); + + it("keeps weekly versions for good without a horizon", () => { + expect(steps(null).slice(-1)).toEqual(["1 per week · Kept for good"]); + }); +}); diff --git a/packages/plugin/tests/ui/ignore-action.test.ts b/packages/plugin/tests/features/sync/ui/ignore-action.test.ts similarity index 97% rename from packages/plugin/tests/ui/ignore-action.test.ts rename to packages/plugin/tests/features/sync/ui/ignore-action.test.ts index d5aa5f2b..b013d7c5 100644 --- a/packages/plugin/tests/ui/ignore-action.test.ts +++ b/packages/plugin/tests/features/sync/ui/ignore-action.test.ts @@ -1,15 +1,14 @@ import { TFile, TFolder } from "obsidian"; import { describe, expect, it } from "vitest"; - -import { IGNORE_FILE_NAME } from "@/constants"; -import type { PluginHost } from "@/plugin/host"; -import { type Space, VAULT_SPACE } from "@/sync/space"; +import type { PluginHost } from "@/app/host"; +import { IGNORE_FILE_NAME } from "@/core/constants"; +import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; import { carryVaultIgnores, stopIgnoring, toggleGlobalIgnore, toggleLocalIgnore, -} from "@/ui/actions/ignore-action"; +} from "@/features/sync/ui/ignore-action"; interface TestPlugin extends PluginHost { calls: { diff --git a/packages/plugin/tests/ui/push-action.test.ts b/packages/plugin/tests/features/sync/ui/push-action.test.ts similarity index 93% rename from packages/plugin/tests/ui/push-action.test.ts rename to packages/plugin/tests/features/sync/ui/push-action.test.ts index 1992e96d..0d133928 100644 --- a/packages/plugin/tests/ui/push-action.test.ts +++ b/packages/plugin/tests/features/sync/ui/push-action.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { scopedPaths } from "@/ui/actions/push-action"; +import { scopedPaths } from "@/features/sync/ui/push-action"; describe("scopedPaths", () => { const changes = [ diff --git a/packages/plugin/tests/features/sync/ui/sync-actions.test.ts b/packages/plugin/tests/features/sync/ui/sync-actions.test.ts new file mode 100644 index 00000000..5c85f44d --- /dev/null +++ b/packages/plugin/tests/features/sync/ui/sync-actions.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from "vitest"; + +import type { SyncController } from "@/features/sync/controller"; +import { heldByConflicts } from "@/features/sync/ui/sync-actions"; + +type Held = Pick; + +/** A vault with one shared folder at "Shared"; `conflicts` are the compare's. */ +function controller(conflicts: string[]): Held { + return { + getSnapshot: () => + ({ + result: { + diff: { conflicts: conflicts.map((path) => ({ path })) }, + }, + }) as unknown as ReturnType, + spaceFor: (path: string) => + path.startsWith("Shared/") + ? { id: "share", root: "Shared" } + : { id: "vault", root: "" }, + }; +} + +describe("heldByConflicts", () => { + it("lets everything go without a conflict", () => { + expect(heldByConflicts(controller([]), ["a.md"])).toBeNull(); + }); + + it("holds any path of the space a conflict is in, naming it", () => { + expect(heldByConflicts(controller(["Inbox.md"]), ["Phone.md"])).toBe( + 'Resolve the conflict in "Inbox.md" first: nothing pushes or pulls until then.', + ); + }); + + it("counts several conflicts", () => { + expect(heldByConflicts(controller(["a.md", "b.md"]), ["c.md"])).toBe( + "Resolve the 2 conflicts first: nothing pushes or pulls until then.", + ); + }); + + it("leaves another space alone", () => { + expect( + heldByConflicts(controller(["Inbox.md"]), ["Shared/plan.md"]), + ).toBeNull(); + expect( + heldByConflicts(controller(["Shared/plan.md"]), ["Phone.md"]), + ).toBeNull(); + }); + + it("names only the conflicts of the spaces asked for", () => { + expect( + heldByConflicts(controller(["Inbox.md", "Shared/plan.md"]), [ + "Shared/notes.md", + ]), + ).toBe( + 'Resolve the conflict in "Shared/plan.md" first: nothing pushes or pulls until then.', + ); + }); +}); diff --git a/packages/plugin/tests/sync/upload-listing.test.ts b/packages/plugin/tests/features/sync/upload-listing.test.ts similarity index 86% rename from packages/plugin/tests/sync/upload-listing.test.ts rename to packages/plugin/tests/features/sync/upload-listing.test.ts index b7790b55..4c7fa720 100644 --- a/packages/plugin/tests/sync/upload-listing.test.ts +++ b/packages/plugin/tests/features/sync/upload-listing.test.ts @@ -1,14 +1,19 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; import { afterEach, beforeAll, describe, expect, it, vi } from "vitest"; -import { deriveKey, type EncryptionKey } from "@/crypto"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; -import { REMOTE_MANIFEST_KEY, REMOTE_OBJECTS_PREFIX } from "@/sync/constants"; -import { compare, type EngineDependencies, pushPaths } from "@/sync/engine"; -import { VAULT_SPACE } from "@/sync/space"; -import type { SessionState } from "@/sync/types"; -import { UPLOAD_TRUST_MS } from "@/sync/uploads"; -import { createScopePolicy } from "@/vault/scope"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; +import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import { REMOTE_OBJECTS_PREFIX } from "@/features/sync/constants"; +import { + compare, + type EngineDependencies, + pushPaths, +} from "@/features/sync/engine"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; +import { UPLOAD_TRUST_MS } from "@/features/sync/remote/uploads"; +import { createScopePolicy } from "@/features/sync/scope/scope"; +import type { SessionState } from "@/features/sync/types"; let key: EncryptionKey; beforeAll(async () => { @@ -123,7 +128,7 @@ describe("upload existence probes", () => { expect(storage.existsCalls).toBe(3); }); - it("lists once to resume a big push, confirming each object it names", async () => { + it("lists each root folder once to resume a big push, confirming each object it names", async () => { const adapter = new InMemoryAdapter(); const storage = new PushStorage(); seed(adapter, BIG); @@ -133,7 +138,7 @@ describe("upload existence probes", () => { await pushAll(adapter, storage); expect(storage.objectPuts).toBe(0); - expect(storage.listCalls).toBe(1); + expect(storage.listCalls).toBe(2); // A listing can name an object being deleted, so a positive is worth a probe. expect(storage.existsCalls).toBe(BIG); }); diff --git a/packages/plugin/tests/settings/transfer-controller.test.ts b/packages/plugin/tests/features/transfer/transfer-controller.test.ts similarity index 89% rename from packages/plugin/tests/settings/transfer-controller.test.ts rename to packages/plugin/tests/features/transfer/transfer-controller.test.ts index 4e12705f..02267543 100644 --- a/packages/plugin/tests/settings/transfer-controller.test.ts +++ b/packages/plugin/tests/features/transfer/transfer-controller.test.ts @@ -1,20 +1,23 @@ import { deviceKey, FakeSecretStorage } from "@tests/helpers/device-key"; import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; +import { linkRecord } from "@tests/helpers/shared-links"; import type { App } from "obsidian"; import { describe, expect, it, vi } from "vitest"; -import { PassphraseManager } from "@/core/passphrase-manager"; -import type { LinkRecord } from "@/links"; -import { type MdsyncSettings, mergeSettings } from "@/settings/model"; +import { mergeSettings } from "@/app/settings"; +import type { MdsyncSettings } from "@/core/settings/model"; +import { defaultS3Config } from "@/features/storage/backends/s3"; +import { PassphraseManager } from "@/features/sync/remote/passphrase-manager"; import { createSettingsTransferUrl, ESettingsTransferStorageMode, -} from "@/settings/transfer"; -import { SettingsTransferController } from "@/settings/transfer-controller"; -import { defaultS3Config } from "@/storage"; -import { confirmSettingsTransferImport } from "@/ui"; +} from "@/features/transfer/transfer"; +import { SettingsTransferController } from "@/features/transfer/transfer-controller"; +import { confirmSettingsTransferImport } from "@/features/transfer/ui/settings-transfer-modal"; -vi.mock("@/ui", () => ({ +vi.mock("@/features/transfer/ui/settings-transfer-modal", () => ({ confirmSettingsTransferImport: vi.fn(async () => true), +})); +vi.mock("@/core/ui/notices", () => ({ notifyError: vi.fn(), notifyInfo: vi.fn(), })); @@ -94,21 +97,7 @@ describe("settings import", () => { settings, deviceKey(new FakeSecretStorage(), adapter), ); - const link: LinkRecord = { - id: "one", - url: "https://relay.example/s/one", - rev: 0, - author: "", - path: "note.md", - showTitle: true, - detached: false, - createdAt: 1, - publishedAt: 1, - expires: null, - maxViews: null, - salt: null, - images: false, - }; + const link = linkRecord({ url: "https://relay.example/s/one" }); vi.mocked(confirmSettingsTransferImport).mockImplementationOnce( async () => { settings.links = [link]; diff --git a/packages/plugin/tests/settings/transfer.test.ts b/packages/plugin/tests/features/transfer/transfer.test.ts similarity index 82% rename from packages/plugin/tests/settings/transfer.test.ts rename to packages/plugin/tests/features/transfer/transfer.test.ts index 4d6cec5b..6c6314fe 100644 --- a/packages/plugin/tests/settings/transfer.test.ts +++ b/packages/plugin/tests/features/transfer/transfer.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from "vitest"; -import { sealLink } from "@/crypto/sealed-link"; -import { DEFAULT_SETTINGS, type MdsyncSettings } from "@/settings/model"; +import { DEFAULT_SETTINGS } from "@/app/settings"; +import { openLink, sealLink } from "@/core/crypto/sealed-link"; +import { EPluginLevel, type MdsyncSettings } from "@/core/settings/model"; +import { defaultS3Config } from "@/features/storage/backends/s3"; +import { defaultWebDAVConfig } from "@/features/storage/backends/webdav"; +import { EStorageBackend } from "@/features/storage/config"; import { createSettingsTransferPackage, createSettingsTransferUrl, @@ -9,12 +13,7 @@ import { mergeTransferredSettings, readSettingsTransfer, type SettingsTransferExportOptions, -} from "@/settings/transfer"; -import { - defaultS3Config, - defaultWebDAVConfig, - EStorageBackend, -} from "@/storage"; +} from "@/features/transfer/transfer"; const PASSPHRASE = "correct horse battery staple"; @@ -161,6 +160,8 @@ describe("settings transfer", () => { }, ignorePatterns: "*.tmp\n*.swp", ignoreSymlinks: !DEFAULT_SETTINGS.ignoreSymlinks, + pluginLevel: EPluginLevel.Data, + pluginLevels: { x: EPluginLevel.Off, y: EPluginLevel.Code }, maxFileBytes: DEFAULT_SETTINGS.maxFileBytes + 1024, autoSyncEnabled: !DEFAULT_SETTINGS.autoSyncEnabled, autoSyncIntervalMinutes: DEFAULT_SETTINGS.autoSyncIntervalMinutes + 5, @@ -171,7 +172,7 @@ describe("settings transfer", () => { confirmBulkDeletes: !DEFAULT_SETTINGS.confirmBulkDeletes, bulkDeleteLimit: DEFAULT_SETTINGS.bulkDeleteLimit + 20, fileHistoryEnabled: !DEFAULT_SETTINGS.fileHistoryEnabled, - fileHistoryMaxSnapshots: DEFAULT_SETTINGS.fileHistoryMaxSnapshots + 7, + fileHistoryKeep: "forever", historyAutoRefresh: !DEFAULT_SETTINGS.historyAutoRefresh, realtimeSync: !DEFAULT_SETTINGS.realtimeSync, showOpenNote: !DEFAULT_SETTINGS.showOpenNote, @@ -198,6 +199,8 @@ describe("settings transfer", () => { expect(imported.settingsSync).toEqual(settings.settingsSync); expect(imported.ignorePatterns).toBe(settings.ignorePatterns); expect(imported.ignoreSymlinks).toBe(settings.ignoreSymlinks); + expect(imported.pluginLevel).toBe(EPluginLevel.Data); + expect(imported.pluginLevels).toEqual(settings.pluginLevels); expect(imported.maxFileBytes).toBe(settings.maxFileBytes); expect(imported.autoSyncEnabled).toBe(settings.autoSyncEnabled); expect(imported.autoSyncIntervalMinutes).toBe( @@ -212,9 +215,7 @@ describe("settings transfer", () => { expect(imported.confirmBulkDeletes).toBe(settings.confirmBulkDeletes); expect(imported.bulkDeleteLimit).toBe(settings.bulkDeleteLimit); expect(imported.fileHistoryEnabled).toBe(settings.fileHistoryEnabled); - expect(imported.fileHistoryMaxSnapshots).toBe( - settings.fileHistoryMaxSnapshots, - ); + expect(imported.fileHistoryKeep).toBe(settings.fileHistoryKeep); expect(imported.historyAutoRefresh).toBe(settings.historyAutoRefresh); expect(imported.realtimeSync).toBe(settings.realtimeSync); expect(imported.showOpenNote).toBe(false); @@ -222,6 +223,53 @@ describe("settings transfer", () => { expect(imported.relaySecret).toBe(settings.relaySecret); }); + it("leaves the plugin levels out of the link while they are the defaults", async () => { + const defaults = buildSettings({ + pluginLevel: EPluginLevel.Settings, + pluginLevels: {}, + }); + expect(await sectionOf(defaults)).toEqual({}); + + const changed = buildSettings({ + pluginLevel: EPluginLevel.Code, + pluginLevels: { x: EPluginLevel.Off }, + }); + expect(await sectionOf(changed)).toEqual({ + p: EPluginLevel.Code, + o: { x: EPluginLevel.Off }, + }); + expect( + await sectionOf(buildSettings({ pluginLevel: EPluginLevel.Data })), + ).toEqual({ + p: EPluginLevel.Data, + }); + }); + + it("resets the plugin levels an old link does not carry", async () => { + const url = await createSettingsTransferUrl(buildSettings({}), PASSPHRASE); + const imported = await readSettingsTransfer(url, PASSPHRASE); + const merged = mergeTransferredSettings( + buildSettings({ + pluginLevel: EPluginLevel.Data, + pluginLevels: { x: EPluginLevel.Off }, + }), + imported, + ); + + expect(merged.pluginLevel).toBe(EPluginLevel.Settings); + expect(merged.pluginLevels).toEqual({}); + }); + + it("rejects a plugin level that is not a number", async () => { + const token = await sealLink( + new TextEncoder().encode(JSON.stringify({ q: { p: "data" } })), + PASSPHRASE, + ); + await expect(readSettingsTransfer(token, PASSPHRASE)).rejects.toThrow( + /Invalid MDSync settings transfer payload/, + ); + }); + it("clamps a crafted token that carries an out-of-range number", async () => { const settings = buildSettings({ autoSyncIntervalMinutes: 15 }); const url = await createSettingsTransferUrl(settings, PASSPHRASE); @@ -257,7 +305,8 @@ describe("settings transfer", () => { }); expect(imported.ignorePatterns).toBe("*.tmp\n*.swp"); expect(imported.ignoreSymlinks).toBe(!DEFAULT_SETTINGS.ignoreSymlinks); - expect(imported.maxFileBytes).toBe(DEFAULT_SETTINGS.maxFileBytes + 1024); + // Sealed when the default was 100 MB. + expect(imported.maxFileBytes).toBe(100 * 1024 * 1024 + 1024); expect(imported.autoSyncEnabled).toBe(!DEFAULT_SETTINGS.autoSyncEnabled); expect(imported.autoSyncIntervalMinutes).toBe( DEFAULT_SETTINGS.autoSyncIntervalMinutes + 5, @@ -281,9 +330,9 @@ describe("settings transfer", () => { expect(imported.fileHistoryEnabled).toBe( !DEFAULT_SETTINGS.fileHistoryEnabled, ); - expect(imported.fileHistoryMaxSnapshots).toBe( - DEFAULT_SETTINGS.fileHistoryMaxSnapshots + 7, - ); + // Its version count (`j`) is retired: the default horizon applies. + expect(imported.fileHistoryKeep).toBe(DEFAULT_SETTINGS.fileHistoryKeep); + expect(imported).not.toHaveProperty("fileHistoryMaxSnapshots"); expect(imported.historyAutoRefresh).toBe( !DEFAULT_SETTINGS.historyAutoRefresh, ); @@ -402,6 +451,23 @@ describe("settings transfer", () => { }); }); +/** The scope section as it travels in the link. */ +async function sectionOf( + settings: MdsyncSettings, +): Promise> { + const url = await createSettingsTransferUrl(settings, PASSPHRASE, { + storageMode: ESettingsTransferStorageMode.None, + includeSyncScope: true, + includeAutomation: false, + includeRealtime: false, + }); + const token = new URL(url).searchParams.get("d") as string; + const payload = JSON.parse( + new TextDecoder().decode(await openLink(token, PASSPHRASE)), + ); + return payload.q; +} + function buildSettings(overrides: Partial): MdsyncSettings { return { ...DEFAULT_SETTINGS, diff --git a/packages/plugin/tests/helpers/config-device.ts b/packages/plugin/tests/helpers/config-device.ts index 937d1295..65bd9a69 100644 --- a/packages/plugin/tests/helpers/config-device.ts +++ b/packages/plugin/tests/helpers/config-device.ts @@ -1,11 +1,17 @@ -import type { SettingsSyncCategories } from "@/settings/model"; -import { SyncController } from "@/sync/controller"; -import { pullPathsOp } from "@/sync/operations/pull"; -import { pushPathsOp } from "@/sync/operations/push"; -import { mergeSessionIntoLocal, projectSession } from "@/sync/session-state"; -import { VAULT_SPACE } from "@/sync/space"; -import type { LocalState } from "@/sync/types"; -import { createScopePolicy } from "@/vault/scope"; +import { + EPluginLevel, + type SettingsSyncCategories, +} from "@/core/settings/model"; +import { SyncController } from "@/features/sync/controller"; +import { pullPathsOp } from "@/features/sync/operations/pull"; +import { pushPathsOp } from "@/features/sync/operations/push"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; +import { createScopePolicy } from "@/features/sync/scope/scope"; +import { + mergeSessionIntoLocal, + projectSession, +} from "@/features/sync/session-state"; +import type { LocalState } from "@/features/sync/types"; import { TestSession } from "./session"; export const disabled: SettingsSyncCategories = { coreSettings: false, @@ -29,11 +35,16 @@ export const enabled = Object.fromEntries( export class Device extends TestSession { settingsSync = { ...disabled }; + /** Whole plugin folders, so `enabled` means everything. */ + pluginLevel: EPluginLevel = EPluginLevel.Data; + pluginLevels: Record = {}; override deps() { return { ...super.deps(), scope: createScopePolicy({ settingsSync: this.settingsSync, + pluginLevel: this.pluginLevel, + pluginLevels: this.pluginLevels, configDir: ".obsidian", }), }; diff --git a/packages/plugin/tests/helpers/controller.ts b/packages/plugin/tests/helpers/controller.ts index c6ac5438..19bba494 100644 --- a/packages/plugin/tests/helpers/controller.ts +++ b/packages/plugin/tests/helpers/controller.ts @@ -1,8 +1,11 @@ import { vi } from "vitest"; -import type { SyncControllerHost } from "@/sync/controller"; -import { mergeSessionIntoLocal, projectSession } from "@/sync/session-state"; -import { VAULT_SPACE } from "@/sync/space"; -import type { LocalState } from "@/sync/types"; +import type { SyncControllerHost } from "@/features/sync/controller"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; +import { + mergeSessionIntoLocal, + projectSession, +} from "@/features/sync/session-state"; +import type { LocalState } from "@/features/sync/types"; import type { TestSession } from "./session"; export function createTestControllerHost(session: TestSession) { diff --git a/packages/plugin/tests/helpers/cut-short.ts b/packages/plugin/tests/helpers/cut-short.ts index f3bd0c6c..99ef2075 100644 --- a/packages/plugin/tests/helpers/cut-short.ts +++ b/packages/plugin/tests/helpers/cut-short.ts @@ -1,6 +1,6 @@ import { expect } from "vitest"; -import { SyncController } from "@/sync/controller"; -import { pullPaths } from "@/sync/pull"; +import { pullPaths } from "@/features/sync/apply/pull"; +import { SyncController } from "@/features/sync/controller"; import { createTestControllerHost } from "./controller"; import { killNextWrite } from "./faults"; import { pairedSessions, type TestSession } from "./session"; diff --git a/packages/plugin/tests/helpers/device-key.ts b/packages/plugin/tests/helpers/device-key.ts index 71e14940..2b49f514 100644 --- a/packages/plugin/tests/helpers/device-key.ts +++ b/packages/plugin/tests/helpers/device-key.ts @@ -1,6 +1,6 @@ import type { DataAdapter, SecretStorage } from "obsidian"; -import { DeviceKey } from "@/crypto/device-key"; +import { DeviceKey } from "@/core/crypto/device-key"; import { InMemoryAdapter } from "./in-memory-adapter"; diff --git a/packages/plugin/tests/helpers/drawing-file.ts b/packages/plugin/tests/helpers/drawing-file.ts new file mode 100644 index 00000000..3554a139 --- /dev/null +++ b/packages/plugin/tests/helpers/drawing-file.ts @@ -0,0 +1,96 @@ +import { compressToBase64 } from "lz-string"; +import { seeded } from "./seeded"; + +const encoder = new TextEncoder(); + +/** A scene shaped like Excalidraw's own: the fields every element carries, a few text elements. */ +export function sceneJson(elements = 40, note = ""): string { + const random = seeded(7); + const shapes = Array.from({ length: elements }, (_, at) => ({ + id: `el${at.toString(36)}${Math.floor(random() * 1e9).toString(36)}`, + type: at % 5 === 0 ? "text" : "rectangle", + x: Math.round(random() * 2000) / 3, + y: Math.round(random() * 2000) / 3, + width: 120 + at, + height: 60, + angle: 0, + strokeColor: "#1e1e1e", + backgroundColor: "transparent", + fillStyle: "solid", + strokeWidth: 2, + roughness: 1, + opacity: 100, + groupIds: [], + index: `a${at}`, + seed: Math.floor(random() * 2 ** 31), + version: 1 + at, + versionNonce: Math.floor(random() * 2 ** 31), + isDeleted: false, + boundElements: null, + updated: 1_750_000_000_000 + at, + link: null, + locked: false, + ...(at % 5 === 0 ? { text: `label ${at}`, fontSize: 20 } : {}), + })); + return JSON.stringify({ + type: "excalidraw", + version: 2, + elements: shapes, + appState: { gridSize: null, viewBackgroundColor: "#ffffff", note }, + files: {}, + }); +} + +/** What obsidian-excalidraw-plugin writes: 256 base64 characters a line, a blank line between lines. */ +export function wrapLikeExcalidraw(base64: string): string { + return base64.replace(/(.{256})/g, "$1\n\n"); +} + +/** A drawing file around `block`, the way the plugin lays it out. */ +export function drawingAround(block: string): string { + return `--- + +excalidraw-plugin: parsed +tags: [excalidraw] + +--- +==⚠ Switch to EXCALIDRAW VIEW in the MORE OPTIONS menu of this document. ⚠== + + +# Excalidraw Data + +## Text Elements +label 0 ^abc123 + +%% +## Drawing +${block} +%% +`; +} + +export function compressedDrawing(json = sceneJson()): string { + return drawingAround( + `\`\`\`compressed-json\n${wrapLikeExcalidraw(compressToBase64(json))}\n\`\`\``, + ); +} + +export function plainDrawing(json = sceneJson()): string { + return drawingAround(`\`\`\`json\n${json}\n\`\`\``); +} + +/** A scene whose LZString base64 is an exact multiple of 256 characters, so the last line is a full one. */ +export function exactMultipleScene(): string { + const random = seeded(11); + let note = ""; + for (let size = 0; size < 4000; size++) { + note += String.fromCharCode(33 + Math.floor(random() * 90)); + const json = sceneJson(10, note); + if (compressToBase64(json).length % 256 === 0) return json; + } + throw new Error("no scene with a 256-multiple base64 length"); +} + +export function bytesOf(text: string): Uint8Array { + return encoder.encode(text); +} diff --git a/packages/plugin/tests/helpers/drawing-view.ts b/packages/plugin/tests/helpers/drawing-view.ts index 6310c072..af7990a6 100644 --- a/packages/plugin/tests/helpers/drawing-view.ts +++ b/packages/plugin/tests/helpers/drawing-view.ts @@ -2,10 +2,14 @@ import { afterEach, beforeEach, vi } from "vitest"; import { Awareness } from "y-protocols/awareness"; import * as Y from "yjs"; -import { type SceneElement, wins } from "@/drawing"; -import type { ExcalidrawLib, ExcalidrawView } from "@/live/drawing/excalidraw"; -import { DRAWING, type DrawingModel } from "@/live/drawing/model"; -import type { LiveSession } from "@/live/session/session"; +import type { SceneElement } from "@/core/drawing/format"; +import { wins } from "@/core/drawing/merge"; +import type { + ExcalidrawLib, + ExcalidrawView, +} from "@/features/live/drawing/excalidraw"; +import { DRAWING, type DrawingModel } from "@/features/live/drawing/model"; +import type { LiveSession } from "@/features/live/session/session"; export const LIB: ExcalidrawLib = { reconcileElements(local, remote, appState) { diff --git a/packages/plugin/tests/settings/setup/element-methods.ts b/packages/plugin/tests/helpers/element-methods.ts similarity index 100% rename from packages/plugin/tests/settings/setup/element-methods.ts rename to packages/plugin/tests/helpers/element-methods.ts diff --git a/packages/plugin/tests/helpers/explorer-host.ts b/packages/plugin/tests/helpers/explorer-host.ts index 26c9dfd5..27042515 100644 --- a/packages/plugin/tests/helpers/explorer-host.ts +++ b/packages/plugin/tests/helpers/explorer-host.ts @@ -1,9 +1,10 @@ -import { type LinkRecord, SharedLinks } from "@/links"; -import type { PluginHost } from "@/plugin/host"; -import type { Person } from "@/presence/people"; -import { Unseen } from "@/presence/unseen"; -import { DEFAULT_SETTINGS } from "@/settings/model"; -import type { Space } from "@/sync/space"; +import type { PluginHost } from "@/app/host"; +import { DEFAULT_SETTINGS } from "@/app/settings"; +import type { LinkRecord } from "@/features/links/record"; +import { SharedLinks } from "@/features/links/shared-links"; +import type { Person } from "@/features/presence/people"; +import { Unseen } from "@/features/presence/unseen"; +import type { Space } from "@/features/sync/remote/space"; export const ALEX: Person = { key: "p1", diff --git a/packages/plugin/tests/helpers/fake-cloudflare.ts b/packages/plugin/tests/helpers/fake-cloudflare.ts index fe7f1800..69393caf 100644 --- a/packages/plugin/tests/helpers/fake-cloudflare.ts +++ b/packages/plugin/tests/helpers/fake-cloudflare.ts @@ -2,7 +2,7 @@ import { type CloudflareApi, cloudflareApi, type HttpRequest, -} from "@/cloudflare"; +} from "@/core/cloudflare/api"; const BASE = "https://api.cloudflare.com/client/v4"; diff --git a/packages/plugin/tests/helpers/fake-storage.ts b/packages/plugin/tests/helpers/fake-storage.ts index 6b0f729f..28678b47 100644 --- a/packages/plugin/tests/helpers/fake-storage.ts +++ b/packages/plugin/tests/helpers/fake-storage.ts @@ -1,4 +1,4 @@ -import type { ListedObject, StorageAdapter } from "@/storage/types"; +import type { ListedObject, StorageAdapter } from "@/features/storage/types"; export class FakeStorage implements StorageAdapter { readonly map = new Map(); diff --git a/packages/plugin/tests/helpers/history-sim.ts b/packages/plugin/tests/helpers/history-sim.ts new file mode 100644 index 00000000..48d5013b --- /dev/null +++ b/packages/plugin/tests/helpers/history-sim.ts @@ -0,0 +1,181 @@ +import { seeded } from "@tests/helpers/seeded"; +import { diffManifests, undoChanges } from "@/features/sync/history/changes"; +import { activityOf } from "@/features/sync/history/model/activity"; +import { + type Cover, + coverOf, + type HistoryView, +} from "@/features/sync/history/model/cover"; +import { planGc } from "@/features/sync/history/model/plan"; +import type { + HistoryObject, + PushRecord, +} from "@/features/sync/history/model/types"; +import type { EFileKind, Manifest, ManifestEntry } from "@/features/sync/types"; + +export const MINUTE = 60_000; +export const HOUR = 60 * MINUTE; +export const DAY = 24 * HOUR; +const SETTLED = DAY; + +/** FNV-1a: a stand-in for the store's SHA-256 digest. */ +function digest(text: string): string { + let hash = 0x811c9dc5; + for (let i = 0; i < text.length; i++) { + hash ^= text.charCodeAt(i); + hash = Math.imul(hash, 0x01000193); + } + return (hash >>> 0).toString(16); +} + +/** Storage and devices in memory: pushes write records, GC applies plans the way the store will. */ +export class HistorySim { + readonly pushes = new Map(); + readonly objects = new Map(); + readonly manifests = new Map(); + head: Manifest | null = null; + pushCount = 0; + /** Share of push records whose storage time straggles up to 15 min either way. */ + straggle = 0; + /** Storage time. */ + now: number; + private readonly random: () => number; + + constructor( + seed: number, + readonly horizon: number | null, + start = Date.UTC(2026, 6, 1, 8, 0, 0), + readonly vaultId = "vault", + ) { + this.random = seeded(seed); + this.now = start; + } + + after(ms: number): number { + this.now += ms; + return this.now; + } + + view(): HistoryView { + return { pushes: this.pushes, objects: this.objects }; + } + + /** Writes the record; publishing makes it HEAD. */ + push(at: number, publish = true): Manifest { + const parent = this.head; + const files = { ...parent?.files }; + for (const path of ["a.md", "b.md", "c.md", "d/e.md", "f.md"]) { + const roll = this.random(); + if (roll < 0.1) delete files[path]; + else if (roll < 0.5) files[path] = this.entry(at); + } + const manifest: Manifest = { + version: 1, + vaultId: this.vaultId, + snapshotId: `s${this.manifests.size + 1}`, + parentSnapshotId: parent?.snapshotId ?? null, + createdAt: at, + deviceId: "d", + files, + }; + this.manifests.set(manifest.snapshotId, manifest); + this.pushes.set(`p/${manifest.snapshotId}`, { + push: { + v: 1, + vaultId: this.vaultId, + id: manifest.snapshotId, + parentId: manifest.parentSnapshotId, + createdAt: at, + deviceId: "d", + changes: diffManifests(parent, manifest), + }, + at: + this.straggle > 0 && this.random() < this.straggle + ? at + (this.random() - 0.5) * 30 * MINUTE + : at, + }); + if (publish) this.publish(manifest); + return manifest; + } + + publish(manifest: Manifest): void { + this.head = manifest; + this.pushCount++; + } + + cover(): Cover { + const head = this.head; + return coverOf( + this.view(), + head && { + id: head.snapshotId, + parentId: head.parentSnapshotId, + vaultId: head.vaultId, + }, + ); + } + + /** One GC run at storage time `now`; returns how many writes and deletes it made. */ + gc(now: number): number { + const plan = planGc({ + view: this.view(), + cover: this.cover(), + vaultId: this.head?.vaultId ?? this.vaultId, + now, + horizon: this.horizon, + settledBefore: now - SETTLED, + }); + for (const build of plan.builds) { + const key = `b/${build.res}-${build.group}-${digest( + JSON.stringify([build.records, build.activity, build.lastId]), + )}`; + const consumed = build.consumed.filter((named) => named !== key); + this.objects.set(key, { object: { v: 1, ...build, consumed }, at: now }); + for (const named of consumed) this.drop(named); + } + for (const key of plan.deletes) this.drop(key); + return plan.builds.length + plan.deletes.length; + } + + /** Replays back from HEAD through the walked records; throws where a state differs from the push's. */ + checkReplay(cover: Cover): void { + if (!this.head) return; + const files = { ...this.head.files }; + for (const { record } of cover.chain) { + const expected = this.manifests.get(record.id); + if (!expected) throw new Error(`Unknown snapshot ${record.id}`); + if ( + JSON.stringify(sorted(files)) !== JSON.stringify(sorted(expected.files)) + ) { + throw new Error(`Replay differs at ${record.id}`); + } + undoChanges(files, record.changes); + } + const reachedFirst = cover.chain.at(-1)?.record.parentId === null; + if (reachedFirst && Object.keys(files).length > 0) { + throw new Error("Replay past the first push left files behind"); + } + } + + /** Pushes the walk and the counts objects account for. */ + countedPushes(cover: Cover): number { + const activity = activityOf(this.view(), cover, this.vaultId); + return Object.values(activity).reduce((sum, [pushes]) => sum + pushes, 0); + } + + private drop(key: string): void { + this.pushes.delete(key); + this.objects.delete(key); + } + + private entry(at: number): ManifestEntry { + const hash = `h${Math.floor(this.random() * 4)}`; + return { hash, size: hash.length, mtime: at, kind: "vault" as EFileKind }; + } +} + +function sorted( + files: Record, +): [string, ManifestEntry][] { + return Object.entries(files).sort(([a], [b]) => a.localeCompare(b)); +} diff --git a/packages/plugin/tests/helpers/history.ts b/packages/plugin/tests/helpers/history.ts new file mode 100644 index 00000000..7d31d154 --- /dev/null +++ b/packages/plugin/tests/helpers/history.ts @@ -0,0 +1,83 @@ +import type { EncryptionKey } from "@/core/crypto/cipher"; +import type { ObjectStorage } from "@/features/storage/types"; +import { MANIFEST_VERSION } from "@/features/sync/constants"; +import { diffManifests } from "@/features/sync/history/changes"; +import { writePin } from "@/features/sync/history/pins"; +import { pushKey, sealPushRecord } from "@/features/sync/history/remote"; +import type { EFileKind, Manifest } from "@/features/sync/types"; +import { publishManifest } from "./manifest"; + +/** Each file at size 1, mtime 1, named by its hash. */ +export function manifestOf( + snapshotId: string, + parentSnapshotId: string | null, + files: Record, + createdAt = 1, +): Manifest { + const entries: Manifest["files"] = {}; + for (const [path, hash] of Object.entries(files)) { + entries[path] = { hash, size: 1, mtime: 1, kind: "vault" as EFileKind }; + } + return { + version: MANIFEST_VERSION, + vaultId: "v", + snapshotId, + parentSnapshotId, + createdAt, + deviceId: "d", + files: entries, + }; +} + +export async function writePushRecord( + storage: ObjectStorage, + key: EncryptionKey, + manifest: Manifest, + parent: Manifest | null, + root = "", +): Promise { + const blob = await sealPushRecord(key, root, { + v: 1, + vaultId: manifest.vaultId, + id: manifest.snapshotId, + parentId: manifest.parentSnapshotId, + createdAt: manifest.createdAt, + deviceId: manifest.deviceId, + deviceName: manifest.deviceName, + changes: diffManifests(parent, manifest), + }); + await storage.put( + pushKey(manifest.snapshotId), + blob, + "application/octet-stream", + ); +} + +/** Oldest-first chain: one push record per manifest (but `skip`), the last one published as HEAD. */ +export async function seedChain( + storage: ObjectStorage, + key: EncryptionKey, + chain: readonly Manifest[], + skip: readonly string[] = [], +): Promise { + for (const [index, manifest] of chain.entries()) { + if (skip.includes(manifest.snapshotId)) continue; + await writePushRecord(storage, key, manifest, chain[index - 1] ?? null); + } + const head = chain.at(-1); + if (head) await publishManifest(storage, key, head); +} + +export function pinSnapshot( + storage: ObjectStorage, + key: EncryptionKey, + manifest: Manifest, + label?: string, +): Promise { + return writePin(storage, key, "", { + id: manifest.snapshotId, + manifest, + label, + pinnedAt: 1, + }); +} diff --git a/packages/plugin/tests/helpers/live-hub.ts b/packages/plugin/tests/helpers/live-hub.ts index 9660cb16..caca8981 100644 --- a/packages/plugin/tests/helpers/live-hub.ts +++ b/packages/plugin/tests/helpers/live-hub.ts @@ -8,8 +8,7 @@ import { HubCore } from "mdsync-relay/src/hub/core"; import type { DocSub, HubPeer } from "mdsync-relay/src/hub/peer"; import { SqlDocStore } from "mdsync-relay/src/hub/store"; import { memorySql } from "mdsync-relay/tests/helpers/memory-sql"; - -import type { SpaceFrame, SpaceHub, SpaceListener } from "@/hub/connection"; +import type { SpaceFrame, SpaceHub, SpaceListener } from "@/core/hub"; /** * The relay's own hub logic over a real SQLite store, in-process; frames cross the "wire" on a later diff --git a/packages/plugin/tests/helpers/live-session.ts b/packages/plugin/tests/helpers/live-session.ts index 2592ff62..dcc97409 100644 --- a/packages/plugin/tests/helpers/live-session.ts +++ b/packages/plugin/tests/helpers/live-session.ts @@ -2,13 +2,13 @@ import { EFrame, type ServerFrame } from "@mdsync/protocol"; import { afterEach, beforeEach, expect, vi } from "vitest"; import * as Y from "yjs"; -import { LIVE_SEND_MS } from "@/constants"; -import { deriveLiveKeys, type LiveKeys } from "@/crypto/live-keys"; -import { seal } from "@/crypto/seal"; -import { docIdFor } from "@/live/doc-id"; -import { LiveSession } from "@/live/session/session"; -import type { Refused } from "@/live/session/session-deps"; -import { TEXT, type TextModel } from "@/live/text/model"; +import { LIVE_SEND_MS } from "@/core/constants"; +import { deriveLiveKeys, type LiveKeys } from "@/core/crypto/live-keys"; +import { seal } from "@/core/crypto/seal"; +import { docIdFor } from "@/features/live/doc-id"; +import { LiveSession } from "@/features/live/session/session"; +import type { Refused } from "@/features/live/session/session-deps"; +import { TEXT, type TextModel } from "@/features/live/text/model"; import { LiveHub, type TestConnection } from "./live-hub"; /** Longer than the default send interval, so a typed edit has left. */ diff --git a/packages/plugin/tests/helpers/manifest.ts b/packages/plugin/tests/helpers/manifest.ts index e922e83d..d07796c8 100644 --- a/packages/plugin/tests/helpers/manifest.ts +++ b/packages/plugin/tests/helpers/manifest.ts @@ -1,7 +1,7 @@ -import { type EncryptionKey, encryptJson } from "@/crypto"; -import type { ObjectStorage } from "@/storage/types"; -import { REMOTE_MANIFEST_KEY } from "@/sync/constants"; -import type { Manifest } from "@/sync/types"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; +import { type EncryptionKey, encryptJson } from "@/core/crypto/cipher"; +import type { ObjectStorage } from "@/features/storage/types"; +import type { Manifest } from "@/features/sync/types"; export async function publishManifest( storage: ObjectStorage, diff --git a/packages/plugin/tests/helpers/presence-relay.ts b/packages/plugin/tests/helpers/presence-relay.ts index b70b441c..c4715f5d 100644 --- a/packages/plugin/tests/helpers/presence-relay.ts +++ b/packages/plugin/tests/helpers/presence-relay.ts @@ -1,9 +1,8 @@ import { EFrame, OWNER, type ServerFrame } from "@mdsync/protocol"; - -import { deriveLiveKeys, type LiveKeys } from "@/crypto/live-keys"; -import type { SpaceFrame, SpaceListener } from "@/hub/connection"; -import { People, type PresenceAccess } from "@/presence/people"; -import { type Space, VAULT_SPACE } from "@/sync/space"; +import { deriveLiveKeys, type LiveKeys } from "@/core/crypto/live-keys"; +import type { SpaceFrame, SpaceListener } from "@/core/hub"; +import { People, type PresenceAccess } from "@/features/presence/people"; +import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; /** Who the hub knows a socket as on a space's channel. */ export type Vouch = (space: string) => { who: string; name: string }; diff --git a/packages/plugin/tests/helpers/recipes.ts b/packages/plugin/tests/helpers/recipes.ts new file mode 100644 index 00000000..b32528cf --- /dev/null +++ b/packages/plugin/tests/helpers/recipes.ts @@ -0,0 +1,70 @@ +import type { FakeStorage } from "@tests/helpers/fake-storage"; +import { + type EncryptionKey, + encryptCompressible, + encryptDescribed, + sha256Hex, +} from "@/core/crypto"; +import type { DrawingCodec } from "@/core/drawing"; +import { chunkKey, recipeKey } from "@/features/sync/content/keys"; + +/** Stores each part under `chunks/`. */ +export async function putChunks( + storage: FakeStorage, + key: EncryptionKey, + parts: Record, +): Promise { + for (const [id, part] of Object.entries(parts)) { + await storage.put(chunkKey(id), await encryptCompressible(key, part)); + } +} + +/** Stores a recipe for `hash` naming `chunks`, without storing them. */ +export async function putRecipe( + storage: FakeStorage, + key: EncryptionKey, + hash: string, + chunks: [id: string, size: number][], + codec?: DrawingCodec, +): Promise { + const header = codec ? { codec, chunks } : { chunks }; + await storage.put( + recipeKey(hash), + await encryptDescribed(key, header, new Uint8Array(0)), + ); +} + +/** Stores `parts` as one chunked file, chunk ids being `