From 1b5444037c0ef804cc8fbc940341025e14c1a9c8 Mon Sep 17 00:00:00 2001 From: kitbyte Date: Tue, 27 Oct 2026 14:21:21 +0200 Subject: [PATCH 01/26] refactor(plugin): feature slices layout with pnpm arch boundary check --- .claude/architecture.md | 102 - .claude/commands-and-settings.md | 50 - .claude/hunts/data-loss.md | 24 - .claude/platform-contracts.md | 14 - .claude/releasing.md | 23 - .claude/rules/history.md | 51 + .claude/rules/hunks.md | 38 + .claude/rules/links.md | 60 + .claude/rules/live.md | 54 + .claude/rules/presence.md | 43 + .claude/rules/realtime.md | 61 + .claude/rules/releasing.md | 32 + .claude/rules/security.md | 55 + .claude/rules/settings-setup.md | 53 + .claude/rules/spaces.md | 55 + .claude/rules/structure.md | 59 + .claude/rules/sync-integrity.md | 69 + .claude/rules/testing.md | 43 + .claude/rules/ui.md | 55 + .claude/rules/vault-io.md | 46 + .claude/security.md | 15 - .claude/share-links.md | 279 -- .claude/shares.md | 493 --- .claude/skills/hunt-data-loss/SKILL.md | 29 + .claude/skills/new-feature/SKILL.md | 39 + .claude/sync-invariants.md | 45 - .claude/testing.md | 106 - AGENTS.md | 37 +- CLAUDE.md | 55 + biome.json | 6 +- package.json | 1 + .../.dependency-cruiser-known-violations.json | 3827 +++++++++++++++++ packages/plugin/.dependency-cruiser.cjs | 82 + packages/plugin/esbuild.config.mjs | 2 +- packages/plugin/package.json | 4 +- .../plugin/src/{plugin => app}/bootstrap.ts | 34 +- .../{commands/index.ts => app/commands.ts} | 36 +- packages/plugin/src/{plugin => app}/events.ts | 15 +- packages/plugin/src/{plugin => app}/host.ts | 27 +- .../plugin/src/{plugin => app}/protocols.ts | 10 +- .../plugin/src/{plugin => app}/realtime.ts | 16 +- .../src/{core => app}/session-factory.ts | 54 +- .../envelope.ts => app/settings-envelope.ts} | 9 +- .../plugin/src/{plugin/ui.ts => app/views.ts} | 23 +- packages/plugin/src/cloudflare/index.ts | 43 - .../plugin/src/{ => core}/cloudflare/api.ts | 0 packages/plugin/src/core/cloudflare/index.ts | 14 + .../src/{ => core}/cloudflare/multipart.ts | 0 .../{ => core}/cloudflare/obsidian-http.ts | 0 .../plugin/src/{ => core}/cloudflare/token.ts | 0 packages/plugin/src/{ => core}/constants.ts | 0 .../index.ts => core/crypto/cipher.ts} | 9 +- .../plugin/src/{ => core}/crypto/constants.ts | 0 .../src/{ => core}/crypto/device-key.ts | 11 +- packages/plugin/src/core/crypto/index.ts | 24 + .../plugin/src/{ => core}/crypto/live-keys.ts | 0 .../src/{ => core}/crypto/passphrase-cache.ts | 9 +- packages/plugin/src/{ => core}/crypto/seal.ts | 0 .../src/{ => core}/crypto/sealed-link.ts | 4 +- .../plugin/src/{ => core}/drawing/format.ts | 0 packages/plugin/src/core/drawing/index.ts | 3 + .../plugin/src/{ => core}/drawing/merge.ts | 0 .../plugin/src/{ => core}/drawing/scene.ts | 2 +- packages/plugin/src/core/hub/index.ts | 16 + packages/plugin/src/{ => core}/hub/link.ts | 0 .../relay.ts => core/hub/relay-text.ts} | 4 +- packages/plugin/src/{ => core}/hub/status.ts | 0 packages/plugin/src/core/index.ts | 5 - packages/plugin/src/core/logs/index.ts | 2 + .../plugin/src/core/{ => logs}/log-service.ts | 5 +- packages/plugin/src/{ => core}/logs/store.ts | 7 +- .../plugin/src/{ => core}/settings/fields.ts | 7 +- packages/plugin/src/core/settings/index.ts | 30 + .../plugin/src/{ => core}/settings/model.ts | 22 +- .../plugin/src/{ => core}/settings/page.ts | 0 .../plugin/src/{ => core}/shared/colors.ts | 0 .../src/{ => core}/shared/diagnostics.ts | 0 .../plugin/src/{ => core}/shared/errors.ts | 0 .../plugin/src/{ => core}/shared/format.ts | 2 +- packages/plugin/src/core/shared/index.ts | 29 + .../plugin/src/{ => core}/shared/offline.ts | 0 packages/plugin/src/{ => core}/shared/path.ts | 0 .../plugin/src/{ => core}/shared/records.ts | 0 .../ui/controls}/action-button.ts | 0 .../common => core/ui/controls}/alert-line.ts | 0 .../common => core/ui/controls}/callout.ts | 0 .../common => core/ui/controls}/copyable.ts | 2 +- .../common => core/ui/controls}/file-path.ts | 0 .../ui/controls}/icon-button.ts | 0 .../common => core/ui/controls}/marquee.ts | 0 .../common => core/ui/controls}/segments.ts | 0 packages/plugin/src/core/ui/index.ts | 39 + .../common => core/ui/input}/activatable.ts | 0 .../{ui/common => core/ui/input}/enter-key.ts | 4 +- .../src/{ui/common => core/ui/input}/focus.ts | 0 .../common => core/ui/input}/long-press.ts | 0 .../plugin/src/{ui/common => core/ui}/menu.ts | 8 +- .../src/{ui/common => core/ui}/modal-frame.ts | 0 .../src/{ => core}/ui/modals/confirm-modal.ts | 5 +- .../{ => core}/ui/modals/passphrase-modal.ts | 6 +- .../src/{ => core}/ui/modals/promise-modal.ts | 0 .../src/{ => core}/ui/modals/prompt-modal.ts | 4 +- .../src/{ui/common => core/ui}/notices.ts | 4 +- .../common => core/ui}/obsidian-helpers.ts | 0 .../src/{ui/common => core/ui}/open-note.ts | 0 .../{ui/common => core/ui}/phone-change.ts | 0 .../src/{ui/common => core/ui}/serial.ts | 0 .../base => core/ui/styles}/callout.css | 0 .../base => core/ui/styles}/file-path.css | 0 .../base => core/ui/styles}/icon-button.css | 0 .../base => core/ui/styles}/marquee.css | 0 .../src/{ => core/ui}/styles/mobile.css | 0 .../src/{ => core/ui}/styles/modal-frame.css | 0 .../src/{ => core/ui}/styles/modals.css | 0 .../base => core/ui/styles}/notice.css | 0 .../base => core/ui/styles}/segments.css | 0 .../src/{ => core/ui}/styles/tokens.css | 0 .../plugin/src/{ => core}/utils/base64.ts | 0 packages/plugin/src/{ => core}/utils/bytes.ts | 0 .../plugin/src/{ => core}/utils/compress.ts | 0 .../src/{ => core}/utils/concurrency.ts | 0 packages/plugin/src/{ => core}/utils/diff.ts | 0 packages/plugin/src/{ => core}/utils/eol.ts | 0 .../src/{ => core}/utils/file-concurrency.ts | 0 packages/plugin/src/core/utils/index.ts | 18 + .../plugin/src/{ => core}/utils/revision.ts | 0 .../plugin/src/{ => core}/utils/search.ts | 0 .../src/{ => core}/vault/atomic-write.ts | 0 .../plugin/src/{ => core}/vault/file-index.ts | 0 packages/plugin/src/core/vault/index.ts | 28 + packages/plugin/src/{ => core}/vault/io.ts | 4 +- .../plugin/src/{ => core}/vault/symlinks.ts | 0 packages/plugin/src/drawing/index.ts | 11 - packages/plugin/src/editor/signs/index.ts | 1 - .../src/{ui => features}/diff/action-bar.ts | 2 +- .../src/{ui => features}/diff/choices.ts | 4 +- .../diff/compare}/binary-view.ts | 4 +- .../diff/compare}/compare-controls.ts | 12 +- .../diff/compare}/compare-decorations.ts | 30 +- .../diff/compare}/compare-panel.ts | 47 +- .../diff/compare}/hunk-renderer.ts | 6 +- .../diff/compare}/preview-panel.ts | 0 .../{ui => features}/diff/file-navigation.ts | 2 +- .../src/{ui => features}/diff/header.ts | 12 +- .../{ui => features}/diff/history-state.ts | 4 +- packages/plugin/src/features/diff/index.ts | 3 + .../src/{ui => features}/diff/layout-mode.ts | 4 +- .../diff/line-wrapping-control.ts | 2 +- .../diff/lines}/change-overlay.ts | 9 +- .../diff/lines}/code-lines.ts | 4 +- .../diff => features/diff/lines}/divider.ts | 6 +- .../diff/lines}/gap-widgets.ts | 5 +- .../diff => features/diff/lines}/geometry.ts | 5 +- .../diff/lines}/line-tints.ts | 0 .../diff/lines}/scroll-sync.ts | 4 +- .../diff/lines}/source-widget.ts | 4 +- .../diff/merge}/merge-actions.ts | 2 +- .../diff/merge}/merge-cards.ts | 12 +- .../diff/merge}/merge-controls.ts | 8 +- .../diff/merge}/merge-decorations.ts | 19 +- .../diff/merge}/merge-editor.ts | 38 +- .../diff/merge}/merge-marks.ts | 4 +- .../diff/merge}/merge-state.ts | 2 +- .../diff/merge}/merge-toolbar.ts | 6 +- .../src/{ui => features}/diff/operations.ts | 17 +- .../plugin/src/{ui => features}/diff/rail.ts | 2 +- .../diff}/restore-modal.ts | 14 +- .../diff => features/diff/styles}/cards.css | 0 .../diff/styles}/cm-lines.css | 0 .../diff/styles}/code-lines.css | 0 .../diff => features/diff/styles}/divider.css | 0 .../diff => features/diff/styles}/gaps.css | 0 .../diff/styles}/hunk-preview.css | 0 .../diff => features/diff/styles}/merge.css | 0 .../diff/styles}/pane-grid.css | 0 .../diff => features/diff/styles}/phone.css | 0 .../diff => features/diff/styles}/rail.css | 0 .../diff/styles}/source-blocks.css | 0 .../diff => features/diff/styles}/tones.css | 0 .../diff/styles}/toolbars.css | 0 .../diff => features/diff/styles}/view.css | 0 .../diff-view.ts => features/diff/view.ts} | 32 +- .../editor-signs}/compute.ts | 0 .../editor-signs}/extension.ts | 0 .../signs => features/editor-signs}/focus.ts | 0 .../signs => features/editor-signs}/gutter.ts | 2 +- .../editor-signs}/helpers.ts | 5 +- .../editor-signs}/hunk-popup.css | 0 .../plugin/src/features/editor-signs/index.ts | 1 + .../editor-signs/popup}/hunk-popup.ts | 10 +- .../editor-signs/popup}/hunk-revert.ts | 2 +- .../editor-signs/popup}/popup-dismiss.ts | 0 .../editor-signs/popup}/popup-placement.ts | 0 .../editor-signs/popup}/popup-view.ts | 8 +- .../editor-signs}/provider.ts | 12 +- .../editor-signs/register.ts} | 4 +- .../editor-signs}/signs.css | 0 .../signs => features/editor-signs}/state.ts | 0 .../editor-signs}/subscriber.ts | 0 .../explorer}/explorer.css | 0 .../explorer/file-context-indicators.ts | 6 +- .../explorer/file-explorer-api.ts | 0 .../explorer/file-explorer-badges.ts | 8 +- .../explorer/file-explorer-decorations.ts | 7 +- .../explorer/file-explorer-indicators.ts | 4 +- .../explorer/file-explorer-marks.ts | 8 +- .../plugin/src/features/explorer/index.ts | 3 + .../explorer/indicator-handle.ts | 0 .../{ui => features}/explorer/link-scan.ts | 2 +- .../explorer/row-decorator.ts | 6 +- packages/plugin/src/features/links/README.md | 116 + .../src/{ => features}/links/describe.ts | 0 .../plugin/src/{ => features}/links/errors.ts | 4 +- packages/plugin/src/features/links/index.ts | 18 + .../links}/link-broker.ts | 17 +- .../src/{ => features}/links/note-links.ts | 2 +- .../src/{ => features}/links/publish.ts | 19 +- .../plugin/src/{ => features}/links/record.ts | 4 +- .../links.ts => features/links/register.ts} | 6 +- .../plugin/src/{ => features}/links/remote.ts | 8 +- .../src/{ => features}/links/shared-links.ts | 4 +- .../links/snapshot}/images.ts | 0 .../links/snapshot}/math.ts | 0 .../links/snapshot}/note-text.ts | 0 .../links/snapshot}/sanitize.ts | 0 .../links/snapshot}/snapshot.ts | 0 .../links/ui}/link-actions.ts | 14 +- .../links => features/links/ui}/link-menu.ts | 8 +- .../links/ui/links-section.ts} | 4 +- .../{styles => features/links/ui}/links.css | 0 .../links/ui}/manage-links-modal.ts | 29 +- .../links/ui}/note-link-action.ts | 5 +- .../links/ui}/preview-frame.ts | 0 .../links/ui}/share-link-modal.ts | 30 +- packages/plugin/src/features/live/README.md | 45 + .../plugin/src/{ => features}/live/authors.ts | 0 .../{ => features}/live/cold/agreed-texts.ts | 6 +- .../src/{ => features}/live/cold/cold-sync.ts | 18 +- .../plugin/src/{ => features}/live/doc-id.ts | 2 +- .../src/{ => features}/live/doc-types.ts | 0 .../{ => features}/live/drawing/binding.ts | 7 +- .../{ => features}/live/drawing/excalidraw.ts | 4 +- .../src/{ => features}/live/drawing/model.ts | 4 +- packages/plugin/src/features/live/index.ts | 19 + .../src/{ui => features}/live/live-state.ts | 2 +- .../plugin/src/{ => features}/live/model.ts | 0 .../live.ts => features/live/register.ts} | 33 +- .../{ => features}/live/session/closing.ts | 0 .../live/session/follower-session.ts | 4 +- .../src/{ => features}/live/session/outbox.ts | 2 +- .../live/session/room-awareness.ts | 4 +- .../{ => features}/live/session/room-log.ts | 0 .../{ => features}/live/session/rotation.ts | 6 +- .../live/session/session-deps.ts | 8 +- .../{ => features}/live/session/session.ts | 14 +- .../{ => features}/live/text/author-marks.ts | 4 +- .../src/{ => features}/live/text/binding.ts | 6 +- .../src/{ => features}/live/text/cursors.ts | 2 +- .../src/{ => features}/live/text/merge.ts | 8 +- .../src/{ => features}/live/text/model.ts | 4 +- .../src/{ => features}/live/text/patch.ts | 5 +- .../src/{ => features}/live/text/rebuild.ts | 2 +- .../live/text/remote-selections.ts | 0 .../{ => features}/live/text/scroll-marks.ts | 5 +- .../live/ui}/deleted-elsewhere.ts | 7 +- .../{ => features}/live/workspace/editors.ts | 19 +- .../{ => features}/live/workspace/patience.ts | 0 .../{ => features}/live/workspace/rename.ts | 16 +- .../src/{ => features}/live/workspace/room.ts | 13 +- .../{ => features}/live/workspace/sessions.ts | 11 +- .../{ => features}/live/workspace/space.ts | 6 +- .../note-header}/header-state.ts | 15 +- .../plugin/src/features/note-header/index.ts | 3 + .../note-header}/live-actions.ts | 6 +- .../note-header}/live-status.ts | 23 +- .../note-header}/note-menu-items.ts | 4 +- .../note-header}/note-menu.ts | 14 +- .../note-header}/note-presence.ts | 14 +- .../plugin/src/features/presence/README.md | 34 + .../{ => features}/presence/announcement.ts | 4 +- .../src/{ => features}/presence/channel.ts | 2 +- .../presence/follow}/cursor-follow.ts | 9 +- .../presence/follow}/follow-banner.ts | 7 +- .../presence/follow}/follow-scroll.ts | 3 +- .../presence/follow}/follows.ts | 5 +- .../src/{ => features}/presence/here.ts | 0 .../plugin/src/features/presence/index.ts | 8 + .../src/{ => features}/presence/people.ts | 8 +- .../presence/register.ts} | 5 +- .../presence/ui}/avatars.ts | 4 +- .../presence/ui}/presence.css | 0 .../src/{ => features}/presence/unseen.ts | 0 .../src/{ => features}/presence/views.ts | 0 .../src/{hub => features/relay}/channels.ts | 17 +- .../src/{hub => features/relay}/connection.ts | 11 +- .../relay/deploy}/assets.ts | 7 +- .../relay/deploy}/bundle.ts | 0 .../relay/deploy/deploy-flow.ts} | 16 +- .../relay/deploy}/migrations.ts | 0 .../relay/deploy}/relay-account.ts | 2 +- .../relay/deploy}/relay-bundle.d.ts | 2 +- .../relay/deploy}/relay-deploy.ts | 3 +- packages/plugin/src/features/relay/index.ts | 27 + .../relay/ui/relay-section.ts} | 16 +- .../relay/update}/relay-update-modal.ts | 20 +- .../relay/update}/relay-update.ts | 15 +- .../plugin/src/features/settings/index.ts | 2 + .../src/{ => features}/settings/logs-view.ts | 10 +- .../settings/overview.css | 0 .../src/{ => features}/settings/overview.ts | 18 +- .../settings/sections/advanced.ts | 4 +- .../settings/sections/automation.ts | 22 +- .../settings/sections/interface.ts | 4 +- .../settings/sections/security.ts | 14 +- .../plugin/src/{ => features}/settings/tab.ts | 30 +- .../settings/tabs-and-logs.css | 0 packages/plugin/src/features/setup/README.md | 57 + .../setup/choice-card.ts | 0 .../src/{settings => features}/setup/form.ts | 0 .../src/{settings => features}/setup/index.ts | 2 +- .../setup/passphrase-meter.ts | 2 +- .../setup/run-action.ts | 2 +- .../steps.ts => features/setup/step-state.ts} | 4 +- .../{settings => features}/setup/stepper.ts | 0 .../setup/steps}/cloudflare-token.ts | 12 +- .../setup/steps}/import-step.ts | 10 +- .../setup/steps}/passphrase-step.ts | 24 +- .../setup/steps}/ready-step.ts | 20 +- .../setup/steps}/relay-deploy-view.ts | 33 +- .../setup/steps}/relay-step.ts | 21 +- .../setup/steps}/start-step.ts | 8 +- .../setup/steps}/storage-step.ts | 33 +- .../setup/styles}/setup-cards.css | 0 .../setup/styles}/setup-forms.css | 0 .../setup/styles}/setup-progress.css | 0 .../setup/styles}/setup-stepper.css | 0 .../setup/styles}/setup.css | 0 .../{settings => features}/setup/wizard.ts | 31 +- .../source-control/actions}/actions.ts | 16 +- .../actions}/section-actions.ts | 2 +- .../source-control/actions}/selection-bar.ts | 8 +- .../source-control/changes}/change-rows.ts | 12 +- .../changes}/changes-section.ts | 17 +- .../source-control/changes}/changes-tab.ts | 30 +- .../changes}/conflict-preview-manager.ts | 2 +- .../changes}/conflict-preview.ts | 2 +- .../source-control/changes}/diff-identity.ts | 2 +- .../source-control/changes}/excluded-files.ts | 8 +- .../changes}/file-list-modal.ts | 2 +- .../source-control/changes}/row-formatter.ts | 13 +- .../source-control/changes}/tree-builder.ts | 2 +- .../source-control/history}/day-groups.ts | 2 +- .../source-control/history}/history-list.ts | 2 +- .../source-control/history}/history-rows.ts | 6 +- .../source-control/history}/history-tab.ts | 24 +- .../source-control/history}/history.css | 0 .../source-control/history}/row-pager.ts | 0 .../src/features/source-control/index.ts | 9 + .../source-control/row-parts.ts | 2 +- .../source-control/setup-prompt.ts | 4 +- .../source-control/styles}/containers.css | 0 .../source-control/styles}/file-list.css | 0 .../source-control/styles}/file-rows.css | 0 .../source-control/styles}/phone.css | 0 .../source-control/styles}/sections.css | 0 .../source-control/styles}/shell.css | 0 .../source-control/styles}/states.css | 0 .../source-control/styles}/summary.css | 0 .../source-control/styles}/toolbar.css | 0 .../source-control/styles}/tree.css | 0 .../source-control/summary-card.ts | 23 +- .../source-control/tab-states.ts | 5 +- .../source-control/timeline}/restore.css | 0 .../source-control/timeline}/snapshot-menu.ts | 5 +- .../timeline}/timeline-actions.ts | 7 +- .../source-control/timeline}/timeline-rows.ts | 16 +- .../source-control/timeline}/timeline-tab.ts | 22 +- .../source-control/timeline}/timeline.css | 0 .../source-control/trash}/trash-rows.ts | 6 +- .../source-control/trash}/trash-tab.ts | 23 +- .../{ui => features}/source-control/types.ts | 0 .../source-control/view.ts} | 27 +- .../source-control/virtual-list.ts | 0 packages/plugin/src/features/spaces/README.md | 74 + .../src/{ => features}/spaces/access.ts | 14 +- .../spaces/broker}/share-broker.ts | 20 +- .../spaces/broker}/share-signed-urls.ts | 0 packages/plugin/src/features/spaces/index.ts | 20 + .../src/{ => features}/spaces/invite.ts | 4 +- .../common => features/spaces}/last-edit.ts | 8 +- .../plugin/src/{ => features}/spaces/owner.ts | 6 +- .../src/{ => features}/spaces/partition.ts | 4 +- .../src/{ => features}/spaces/record.ts | 2 +- .../src/{ => features}/spaces/records.ts | 6 +- .../src/{ => features}/spaces/remote.ts | 8 +- .../spaces}/share-moves.ts | 19 +- .../spaces}/share-registration.ts | 15 +- .../spaces}/space-access.ts | 19 +- .../spaces/ui}/access-ended.ts | 8 +- .../spaces/ui/invites}/invite-action.ts | 35 +- .../spaces/ui/invites}/invite-modal.ts | 6 +- .../spaces/ui/invites}/invite-section.ts | 4 +- .../spaces/ui}/read-only.ts | 6 +- .../spaces/ui}/share-action.ts | 21 +- .../spaces/ui/shares-section.ts} | 13 +- .../{styles => features/spaces/ui}/shares.css | 0 .../spaces/ui}/space-gone.ts | 7 +- .../spaces/ui/window}/pause-control.ts | 4 +- .../spaces/ui/window}/people-list.ts | 9 +- .../spaces/ui/window}/share-head.ts | 5 +- .../spaces/ui/window}/share-modal.ts | 39 +- .../spaces/ui/window}/share-people.ts | 10 +- .../spaces/ui/window}/share-summary.ts | 5 +- .../spaces/ui/window}/share-window.ts | 14 +- packages/plugin/src/features/status/index.ts | 3 + .../live => features}/status/live-spaces.ts | 8 +- .../live => features}/status/relay-status.ts | 13 +- .../{styles => features/status}/ribbon.css | 0 .../src/{ui => features/status}/ribbon.ts | 8 +- .../status}/status-bar.css | 0 .../src/{ui => features/status}/status-bar.ts | 15 +- .../{ui => features/status}/status-menu.ts | 26 +- .../live => features}/status/where-menu.ts | 17 +- .../storage/backends}/google-drive-auth.ts | 13 +- .../storage/backends}/google-drive-request.ts | 2 +- .../storage/backends}/google-drive-upload.ts | 2 +- .../storage/backends}/google-drive.ts | 8 +- .../storage/backends}/s3-signer.ts | 4 +- .../storage/backends}/s3-store.ts | 5 +- .../storage/backends}/s3-xml.ts | 2 +- .../storage/backends}/s3.ts | 10 +- .../storage/backends}/util.ts | 2 +- .../storage/backends}/webdav.ts | 16 +- .../storage/cloudflare}/cloudflare-login.ts | 10 +- .../storage/cloudflare/r2-select.ts} | 34 +- .../{ => features/storage}/cloudflare/r2.ts | 7 +- .../src/{ => features}/storage/config.ts | 0 .../src/{ => features}/storage/field-spec.ts | 2 +- packages/plugin/src/features/storage/index.ts | 63 + .../src/{ => features}/storage/records.ts | 8 +- .../src/{ => features}/storage/registry.ts | 8 +- .../storage}/storage-refused.ts | 8 +- .../src/{ => features}/storage/types.ts | 0 .../storage/ui/backend-section.ts} | 15 +- .../storage/ui}/connection-test.ts | 10 +- .../storage/ui}/storage-fields.ts | 18 +- .../storage/ui}/storage-refused-modal.ts | 17 +- packages/plugin/src/features/sync/README.md | 92 + .../sync/apply}/auto-merge.ts | 32 +- .../sync/apply}/conflict-copy.ts | 2 +- .../sync/apply}/conflict-merge.ts | 10 +- .../sync/apply}/pull-moves.ts | 12 +- .../src/{sync => features/sync/apply}/pull.ts | 22 +- .../sync/automation}/auto-push.ts | 4 +- .../sync/automation}/scheduler.ts | 6 +- .../plugin/src/{ => features}/sync/cancel.ts | 0 .../sync/changes}/binary-extensions.ts | 0 .../sync/changes}/content.ts | Bin 9349 -> 9388 bytes .../{sync => features/sync/changes}/diff.ts | 8 +- .../{sync => features/sync/changes}/moves.ts | 2 +- .../sync/changes}/remote-names.ts | 6 +- .../src/{ => features}/sync/constants.ts | 0 .../src/{ => features}/sync/controller.ts | 50 +- .../plugin/src/{ => features}/sync/engine.ts | 45 +- .../{ => features}/sync/history/changes.ts | 4 +- .../src/{ => features}/sync/history/gc.ts | 18 +- .../{ => features}/sync/history/publish.ts | 10 +- .../src/{ => features}/sync/history/query.ts | 14 +- .../src/{ => features}/sync/history/replay.ts | 2 +- .../sync/history/restore-vault.ts | 4 +- .../src/{ => features}/sync/history/store.ts | 14 +- .../src/{ => features}/sync/history/types.ts | 2 +- .../sync/hunks}/anchored-hunks.ts | 2 +- .../sync/hunks}/diff-cache.ts | 6 +- .../{sync => features/sync/hunks}/hunks.ts | 2 +- .../sync/hunks}/merge-model.ts | 2 +- .../sync/hunks}/projection.ts | 14 +- .../sync/identity}/authors.ts | 4 +- .../sync/identity}/device-name.ts | 5 +- .../sync/identity}/device.ts | 0 packages/plugin/src/features/sync/index.ts | 135 + .../src/{ => features}/sync/live-notes.ts | 4 +- .../sync/operations/config-reset.ts | 14 +- .../{ => features}/sync/operations/flows.ts | 10 +- .../{ => features}/sync/operations/hunks.ts | 24 +- .../{ => features}/sync/operations/pull.ts | 10 +- .../{ => features}/sync/operations/push.ts | 14 +- .../{ => features}/sync/operations/resolve.ts | 36 +- .../{ => features}/sync/operations/revert.ts | 20 +- .../sync/operations/text-loaders.ts | 12 +- .../{ => features}/sync/operations/types.ts | 6 +- .../sync/recovery}/cut-short.ts | 20 +- .../sync/recovery}/journal.ts | 16 +- .../sync/recovery}/state-persister.ts | 6 +- .../sync/remote}/baseline.ts | 16 +- .../sync/remote}/config-reset.ts | 4 +- .../{sync => features/sync/remote}/foreign.ts | 6 +- .../{sync => features/sync/remote}/keyfile.ts | 15 +- .../sync/remote}/manifest.ts | 10 +- .../sync/remote}/passphrase-manager.ts | 19 +- .../{sync => features/sync/remote}/reset.ts | 10 +- .../sync/remote}/space-paths.ts | 4 +- .../{sync => features/sync/remote}/space.ts | 0 .../{sync => features/sync/remote}/uploads.ts | 2 +- .../{ => features}/sync/runtime/auto-cycle.ts | 9 +- .../sync/runtime/controller-state.ts | 8 +- .../sync/runtime/file-diff-service.ts | 14 +- .../sync/runtime/history-service.ts | 46 +- .../sync/runtime/maintenance-service.ts | 8 +- .../sync/runtime}/maintenance.ts | 26 +- .../sync/runtime/merged-result.ts | 6 +- .../sync/runtime/operation-runner.ts | 34 +- .../sync/runtime/refresh-queue.ts | 2 +- .../sync/runtime/saved-refresh.ts | 12 +- .../{ => features}/sync/runtime/scan-cycle.ts | 10 +- .../sync/runtime}/sync-gates.ts | 2 +- .../scope/configuration-scope-section.ts} | 13 +- .../{vault => features/sync/scope}/entry.ts | 6 +- .../sync/scope/exclusions-section.ts} | 10 +- .../sync/scope}/ignore-rules.ts | 2 +- .../sync/scope}/ignore-state.ts | 7 +- .../{vault => features/sync/scope}/ignore.ts | 4 +- .../{vault => features/sync/scope}/scanner.ts | 20 +- .../{vault => features/sync/scope}/scope.ts | 16 +- .../src/{ => features}/sync/session-state.ts | 8 +- .../plugin/src/{ => features}/sync/session.ts | 6 +- .../plugin/src/{ => features}/sync/state.ts | 11 +- .../{ => features}/sync/status-broadcaster.ts | 0 .../plugin/src/{ => features}/sync/types.ts | 0 .../sync/ui}/change-action.ts | 2 +- .../sync/ui}/ignore-action.ts | 11 +- .../sync/ui}/maintenance-actions.ts | 17 +- .../sync/ui/maintenance-section.ts} | 6 +- .../sync/ui}/modals.ts | 5 +- .../sync/ui}/push-action.ts | 9 +- .../sync/ui}/reset-modal.ts | 6 +- .../common => features/sync/ui}/skipped.ts | 6 +- .../sync/ui}/sync-actions.ts | 8 +- .../sync/ui}/vault-adoption.ts | 6 +- .../plugin/src/features/transfer/index.ts | 4 + .../transfer}/transfer-controller.ts | 9 +- .../transfer}/transfer.ts | 18 +- .../transfer/ui/device-transfer-section.ts} | 11 +- .../ui}/settings-transfer-export-modal.ts | 19 +- .../transfer/ui}/settings-transfer-modal.ts | 10 +- .../transfer/ui}/transfer.css | 0 packages/plugin/src/hub/index.ts | 6 - packages/plugin/src/links/index.ts | 34 - packages/plugin/src/live/index.ts | 17 - packages/plugin/src/live/session/index.ts | 4 - packages/plugin/src/main.ts | 106 +- packages/plugin/src/presence/index.ts | 4 - .../plugin/src/settings/sections/index.ts | 12 - packages/plugin/src/shared/index.ts | 7 - packages/plugin/src/spaces/index.ts | 17 - packages/plugin/src/storage/index.ts | 56 - packages/plugin/src/styles.css | 65 + packages/plugin/src/styles/index.css | 65 - packages/plugin/src/sync/history/index.ts | 43 - packages/plugin/src/sync/operations/index.ts | 23 - packages/plugin/src/ui/common/index.ts | 46 - packages/plugin/src/ui/diff/index.ts | 5 - packages/plugin/src/ui/index.ts | 74 - packages/plugin/src/ui/links/index.ts | 8 - packages/plugin/src/ui/modals/index.ts | 17 - .../plugin/src/ui/source-control/index.ts | 33 - packages/plugin/src/utils/index.ts | 9 - .../tests/{settings => app}/envelope.test.ts | 11 +- .../tests/{ui => app}/push-result.test.ts | 8 +- .../tests/{plugin => app}/realtime.test.ts | 19 +- .../{core => app}/session-factory.test.ts | 15 +- .../tests/{ui => app}/share-menu.test.ts | 11 +- packages/plugin/tests/arch/folders.test.ts | 28 + .../tests/{ => core}/cloudflare/api.test.ts | 2 +- .../tests/{ => core}/cloudflare/r2.test.ts | 8 +- .../cloudflare/relay-account.test.ts | 2 +- .../cloudflare/relay-deploy.test.ts | 6 +- .../tests/{live => core/crypto}/chaos.test.ts | 8 +- .../{ => core}/crypto/device-key.test.ts | 4 +- .../crypto}/failed-batch.test.ts | 10 +- .../{ => core}/crypto/json-envelope.test.ts | 4 +- .../crypto/passphrase-cache.test.ts | 2 +- .../tests/{ => core}/crypto/seal.test.ts | 4 +- .../crypto}/session-reconnect.test.ts | 2 +- .../crypto}/session-rooms.test.ts | 6 +- .../tests/{ => core}/drawing/drawing.test.ts | 11 +- .../plugin/tests/{ => core}/hub/link.test.ts | 2 +- .../tests/{ui => core/hub}/relay.test.ts | 2 +- .../tests/{ => core}/hub/status.test.ts | 2 +- .../tests/core/{ => logs}/log-service.test.ts | 4 +- .../tests/{ => core}/settings/fields.test.ts | 4 +- .../tests/{ => core}/settings/model.test.ts | 11 +- .../{ => core}/settings/number-field.test.ts | 4 +- .../tests/{ => core}/shared/colors.test.ts | 2 +- .../tests/{ => core}/shared/errors.test.ts | 2 +- .../tests/{ => core}/shared/format.test.ts | 2 +- .../tests/{ => core}/shared/offline.test.ts | 7 +- .../tests/{ => core}/shared/path.test.ts | 2 +- .../tests/{ => core}/ui/attempt.test.ts | 2 +- .../tests/{ => core}/utils/base64.test.ts | 2 +- .../tests/{ => core}/utils/compress.test.ts | 2 +- .../{ => core}/utils/concurrency.test.ts | 2 +- .../plugin/tests/{ => core}/utils/eol.test.ts | 5 +- .../{ => core}/utils/file-concurrency.test.ts | 2 +- .../tests/{ => core}/utils/revision.test.ts | 2 +- .../tests/{ => core}/utils/search.test.ts | 2 +- .../{ => core}/vault/atomic-write.test.ts | 2 +- .../plugin/tests/{ => core}/vault/io.test.ts | 7 +- .../tests/{ => core}/vault/symlinks.test.ts | 4 +- .../{ui => features/diff}/choices.test.ts | 2 +- .../{ui => features/diff}/diff-chrome.test.ts | 2 +- .../diff}/diff-operations.test.ts | 21 +- .../diff}/diff-view-status.test.ts | 23 +- .../diff}/history-state.test.ts | 9 +- .../diff/lines}/code-lines.test.ts | 2 +- .../diff/lines}/gap-widgets.test.ts | 4 +- .../diff/lines}/scroll-sync.test.ts | 5 +- .../diff/merge}/merge-actions.test.ts | 11 +- .../diff/merge}/merge-cards.test.ts | 17 +- .../diff/merge}/merge-state.test.ts | 21 +- .../editor-signs}/integration.test.ts | 7 +- .../editor-signs/popup}/popup-dismiss.test.ts | 2 +- .../editor-signs}/provider.test.ts | 6 +- .../editor-signs}/signs.test.ts | 13 +- .../file-explorer-decorations.test.ts | 12 +- .../file-explorer-indicators.test.ts | 17 +- .../explorer}/file-explorer-marks.test.ts | 8 +- .../explorer}/link-scan.test.ts | 9 +- .../explorer}/row-decorator.test.ts | 19 +- .../{ => features}/links/describe.test.ts | 4 +- .../tests/{ => features}/links/errors.test.ts | 4 +- .../links}/link-broker.test.ts | 6 +- .../{ => features}/links/publish.test.ts | 34 +- .../tests/{ => features}/links/record.test.ts | 2 +- .../tests/{ => features}/links/remote.test.ts | 10 +- .../{ => features}/links/shared-links.test.ts | 11 +- .../snapshot}/fixtures/rendered-note.html | 0 .../links/snapshot}/images.test.ts | 2 +- .../links/snapshot}/math.test.ts | 2 +- .../links/snapshot}/sanitize.test.ts | 5 +- .../links}/ui/link-actions.test.ts | 57 +- .../{ => features/links}/ui/link-menu.test.ts | 2 +- .../links}/ui/manage-links-modal.test.ts | 30 +- .../links}/ui/note-link-action.test.ts | 12 +- .../links}/ui/preview-frame.test.ts | 2 +- .../tests/{ => features}/live/authors.test.ts | 4 +- .../live/cold}/agreed-texts.test.ts | 2 +- .../tests/{ => features}/live/doc-id.test.ts | 4 +- .../{ => features}/live/doc-types.test.ts | 2 +- .../drawing}/drawing-binding-live.test.ts | 12 +- .../live/drawing}/drawing-binding.test.ts | 8 +- .../live/drawing}/drawing-model.test.ts | 4 +- .../live}/live-base.test.ts | 4 +- .../live/session}/follower.test.ts | 13 +- .../live/session}/outbox.test.ts | 2 +- .../live/session}/room-awareness.test.ts | 7 +- .../live/session}/session-staged.test.ts | 6 +- .../live/session}/session.test.ts | 10 +- .../live/text}/binding-cleanup.test.ts | 2 +- .../live/text}/cursors.test.ts | 2 +- .../live/text}/rebuild.test.ts | 4 +- .../live/text}/remote-selections.test.ts | 2 +- .../live/text}/scroll-marks.test.ts | 6 +- .../{live => features/live/text}/text.test.ts | 7 +- .../live}/ui/deleted-elsewhere.test.ts | 11 +- .../live/workspace}/editors.test.ts | 2 +- .../live/workspace}/rename.test.ts | 26 +- .../live/workspace}/sessions.test.ts | 28 +- .../note-header}/live-actions.test.ts | 11 +- .../note-header}/live-status.test.ts | 13 +- .../note-header}/note-menu-items.test.ts | 7 +- .../presence/follow}/cursor-follow.test.ts | 14 +- .../presence/follow}/follow-scroll.test.ts | 8 +- .../{ => features}/presence/here.test.ts | 4 +- .../presence/people-views.test.ts | 6 +- .../{ => features}/presence/people.test.ts | 9 +- .../{ => features}/presence/unseen.test.ts | 2 +- .../{ => features}/presence/views.test.ts | 2 +- .../relay}/connection.test.ts | 15 +- .../relay/deploy}/migrations.test.ts | 2 +- .../relay/deploy}/relay.test.ts | 20 +- .../relay/ui}/relay-section.test.ts | 11 +- .../relay/update}/relay-update.test.ts | 29 +- .../{ => features}/settings/logs-view.test.ts | 11 +- .../sections}/security-section.test.ts | 19 +- .../setup/passphrase-meter.test.ts | 6 +- .../setup/run-action.test.ts | 2 +- .../setup/step-state.test.ts} | 11 +- .../setup/stepper.test.ts | 4 +- .../setup/steps}/relay-step.test.ts | 28 +- .../changes}/conflict-preview-manager.test.ts | 10 +- .../changes}/diff-identity.test.ts | 4 +- .../changes}/row-formatter.test.ts | 4 +- .../changes}/tree-flatten.test.ts | 4 +- .../history}/day-groups.test.ts | 2 +- .../history}/history-list.test.ts | 2 +- .../history}/history-rows.test.ts | 6 +- .../source-control/history}/row-pager.test.ts | 2 +- .../timeline}/timeline-actions.test.ts | 10 +- .../timeline}/timeline-rows.test.ts | 14 +- .../source-control/trash}/trash-rows.test.ts | 8 +- .../spaces/broker}/share-broker.test.ts | 4 +- .../spaces/broker}/share-signed-urls.test.ts | 2 +- .../{ => features}/spaces/invite.test.ts | 10 +- .../tests/{ => features}/spaces/owner.test.ts | 13 +- .../spaces/records-partition.test.ts | 12 +- .../{ => features}/spaces/records.test.ts | 14 +- .../{ => features}/spaces/remote.test.ts | 18 +- .../spaces}/share-moves.test.ts | 9 +- .../spaces}/share-registration.test.ts | 14 +- .../spaces}/space-access.test.ts | 13 +- .../spaces}/ui/access-ended.test.ts | 11 +- .../spaces/ui/invites}/invite-action.test.ts | 16 +- .../spaces/ui}/read-only.test.ts | 8 +- .../spaces}/ui/share-action.test.ts | 34 +- .../spaces/ui}/shares-section.test.ts | 8 +- .../spaces/ui/window}/share-people.test.ts | 17 +- .../spaces/ui/window}/share-summary.test.ts | 4 +- .../backends}/google-drive-adapter.test.ts | 6 +- .../backends}/google-drive-auth.test.ts | 2 +- .../storage/backends}/s3-adapter.test.ts | 9 +- .../storage/backends}/s3-signer.test.ts | 7 +- .../storage/backends}/s3-xml.test.ts | 5 +- .../storage/backends}/util.test.ts | 4 +- .../storage/backends}/webdav-adapter.test.ts | 4 +- .../cloudflare}/cloudflare-login.test.ts | 4 +- .../storage/cloudflare/r2-select.test.ts} | 23 +- .../{ => features}/storage/records.test.ts | 10 +- .../storage}/storage-refused.test.ts | 22 +- .../storage/ui}/connection-test.test.ts | 2 +- .../storage/ui}/storage-fields.test.ts | 8 +- .../sync/apply}/auto-merge.test.ts | 13 +- .../sync/apply}/pull-hint.test.ts | 6 +- .../{ => features}/sync/auto-cycle.test.ts | 16 +- .../sync/automation}/auto-push.test.ts | 9 +- .../automation}/scheduler-interval.test.ts | 8 +- .../automation}/scheduler-queued-push.test.ts | 11 +- .../automation}/scheduler-startup.test.ts | 9 +- .../tests/{ => features}/sync/cancel.test.ts | 12 +- .../sync/category-reset-roundtrip.test.ts | 13 +- .../sync/changes}/content-cache.test.ts | 6 +- .../sync/changes}/content-text.test.ts | 6 +- .../sync/changes}/diff.test.ts | 4 +- .../tests/{ => features}/sync/chaos.test.ts | 4 +- .../sync/controller-unload.test.ts | 6 +- .../sync/device-scope-roundtrip.test.ts | 8 +- .../sync/engine-roundtrip.test.ts | 29 +- .../sync/file-diff-index.test.ts | 6 +- .../sync/history}/history-deleted.test.ts | 16 +- .../sync/history}/history-gc.test.ts | 20 +- .../sync/history}/history-log.test.ts | 22 +- .../sync/history}/history-read-cache.test.ts | 18 +- .../sync/history}/restore-vault.test.ts | 4 +- .../sync/hunks}/anchored-hunks.test.ts | 9 +- .../sync/hunks}/conflict-merge.test.ts | 2 +- .../sync/hunks}/diff-cache.test.ts | 8 +- .../sync/hunks}/hunks-apply.test.ts | 2 +- .../sync/hunks}/hunks.test.ts | 5 +- .../sync/hunks}/merge-model.test.ts | 2 +- .../sync/hunks}/operations-hunks.test.ts | 19 +- .../sync/hunks}/projection-absent.test.ts | 11 +- .../sync/hunks}/projection-binary.test.ts | 14 +- .../sync/hunks}/projection-lazy.test.ts | 13 +- .../sync/identity}/authors.test.ts | 12 +- .../sync/identity}/device-name.test.ts | 9 +- .../sync/identity}/manifest-device.test.ts | 4 +- .../{ => features}/sync/live-notes.test.ts | 18 +- .../tests/{ => features}/sync/moves.test.ts | 10 +- .../sync/operations}/drawings.test.ts | 12 +- .../sync/operations}/empty-folders.test.ts | 6 +- .../sync/operations}/live-operations.test.ts | 10 +- .../sync/operations}/lost-push.test.ts | 13 +- .../sync/operations}/operations-batch.test.ts | 20 +- .../sync/operations}/pull-size-limit.test.ts | 4 +- .../sync/operations}/remote-names.test.ts | 6 +- .../{ => features}/sync/push-hunks.test.ts | 2 +- .../sync/recovery}/cut-short-baseline.test.ts | 31 +- .../sync/recovery}/cut-short.test.ts | 16 +- .../sync/recovery}/state-persister.test.ts | 10 +- .../sync/remote}/baseline.test.ts | 10 +- .../sync/remote}/config-reset.test.ts | 8 +- .../sync/remote}/foreign.test.ts | 22 +- .../sync/remote}/keyfile.test.ts | 6 +- .../sync/remote}/manifest-guard.test.ts | 12 +- .../sync/remote}/manifest-revalidate.test.ts | 14 +- .../sync/remote}/passphrase-manager.test.ts | 18 +- .../sync/remote}/passphrase-storage.test.ts | 11 +- .../sync/remote}/record-order.test.ts | 25 +- .../sync/remote}/reset.test.ts | 8 +- .../sync/remote}/space-paths.test.ts | 9 +- .../sync/remote}/space-roundtrip.test.ts | 16 +- .../sync/remote}/spaces.test.ts | 26 +- .../runtime}/history-service-scope.test.ts | 12 +- .../sync/runtime}/maintenance.test.ts | 20 +- .../sync/runtime}/operation-runner.test.ts | 27 +- .../sync/runtime}/refresh-queue.test.ts | 7 +- .../sync/runtime}/saved-refresh.test.ts | 16 +- .../sync/runtime}/scan-cycle.test.ts | 7 +- .../sync/scope}/ignore-rules.test.ts | 4 +- .../sync/scope}/ignore-state.test.ts | 5 +- .../sync/scope}/ignore.test.ts | 4 +- .../sync/scope}/scanner-index.test.ts | 15 +- .../sync/scope}/scanner-memory.test.ts | 10 +- .../sync/scope}/scanner-scope.test.ts | 21 +- .../sync/scope}/scanner-spaces.test.ts | 17 +- .../sync/scope}/scope-spaces.test.ts | 9 +- .../sync/scope}/scope.test.ts | 4 +- .../{ => features}/sync/session-state.test.ts | 14 +- .../{ui => features/sync}/skipped.test.ts | 6 +- .../sync/transfer-memory.test.ts | 7 +- .../sync}/ui/ignore-action.test.ts | 9 +- .../sync}/ui/push-action.test.ts | 2 +- .../sync/upload-listing.test.ts | 23 +- .../transfer}/transfer-controller.test.ts | 18 +- .../transfer}/transfer.test.ts | 14 +- .../plugin/tests/helpers/config-device.ts | 19 +- packages/plugin/tests/helpers/controller.ts | 11 +- packages/plugin/tests/helpers/cut-short.ts | 4 +- packages/plugin/tests/helpers/device-key.ts | 2 +- packages/plugin/tests/helpers/drawing-view.ts | 12 +- .../setup => helpers}/element-methods.ts | 0 .../plugin/tests/helpers/explorer-host.ts | 13 +- .../plugin/tests/helpers/fake-cloudflare.ts | 2 +- packages/plugin/tests/helpers/fake-storage.ts | 2 +- packages/plugin/tests/helpers/live-hub.ts | 6 +- packages/plugin/tests/helpers/live-session.ts | 14 +- packages/plugin/tests/helpers/manifest.ts | 8 +- .../plugin/tests/helpers/presence-relay.ts | 8 +- .../tests/helpers/revalidating-storage.ts | 2 +- packages/plugin/tests/helpers/session.ts | 16 +- packages/plugin/tests/helpers/shared-links.ts | 4 +- .../plugin/tests/helpers/space-records.ts | 4 +- packages/plugin/tests/stubs/relay-bundle.ts | 2 +- packages/protocol/README.md | 58 + packages/relay/README.md | 68 + packages/viewer/README.md | 60 + pnpm-lock.yaml | 299 ++ tests/e2e/README.md | 47 + tools/fixtures/diff-ui.mjs | 2 +- 839 files changed, 9591 insertions(+), 4663 deletions(-) delete mode 100644 .claude/architecture.md delete mode 100644 .claude/commands-and-settings.md delete mode 100644 .claude/hunts/data-loss.md delete mode 100644 .claude/platform-contracts.md delete mode 100644 .claude/releasing.md create mode 100644 .claude/rules/history.md create mode 100644 .claude/rules/hunks.md create mode 100644 .claude/rules/links.md create mode 100644 .claude/rules/live.md create mode 100644 .claude/rules/presence.md create mode 100644 .claude/rules/realtime.md create mode 100644 .claude/rules/releasing.md create mode 100644 .claude/rules/security.md create mode 100644 .claude/rules/settings-setup.md create mode 100644 .claude/rules/spaces.md create mode 100644 .claude/rules/structure.md create mode 100644 .claude/rules/sync-integrity.md create mode 100644 .claude/rules/testing.md create mode 100644 .claude/rules/ui.md create mode 100644 .claude/rules/vault-io.md delete mode 100644 .claude/security.md delete mode 100644 .claude/share-links.md delete mode 100644 .claude/shares.md create mode 100644 .claude/skills/hunt-data-loss/SKILL.md create mode 100644 .claude/skills/new-feature/SKILL.md delete mode 100644 .claude/sync-invariants.md delete mode 100644 .claude/testing.md create mode 100644 CLAUDE.md create mode 100644 packages/plugin/.dependency-cruiser-known-violations.json create mode 100644 packages/plugin/.dependency-cruiser.cjs rename packages/plugin/src/{plugin => app}/bootstrap.ts (87%) rename packages/plugin/src/{commands/index.ts => app/commands.ts} (92%) rename packages/plugin/src/{plugin => app}/events.ts (88%) rename packages/plugin/src/{plugin => app}/host.ts (66%) rename packages/plugin/src/{plugin => app}/protocols.ts (82%) rename packages/plugin/src/{plugin => app}/realtime.ts (85%) rename packages/plugin/src/{core => app}/session-factory.ts (89%) rename packages/plugin/src/{settings/envelope.ts => app/settings-envelope.ts} (91%) rename packages/plugin/src/{plugin/ui.ts => app/views.ts} (81%) delete mode 100644 packages/plugin/src/cloudflare/index.ts rename packages/plugin/src/{ => core}/cloudflare/api.ts (100%) create mode 100644 packages/plugin/src/core/cloudflare/index.ts rename packages/plugin/src/{ => core}/cloudflare/multipart.ts (100%) rename packages/plugin/src/{ => core}/cloudflare/obsidian-http.ts (100%) rename packages/plugin/src/{ => core}/cloudflare/token.ts (100%) rename packages/plugin/src/{ => core}/constants.ts (100%) rename packages/plugin/src/{crypto/index.ts => core/crypto/cipher.ts} (98%) rename packages/plugin/src/{ => core}/crypto/constants.ts (100%) rename packages/plugin/src/{ => core}/crypto/device-key.ts (91%) create mode 100644 packages/plugin/src/core/crypto/index.ts rename packages/plugin/src/{ => core}/crypto/live-keys.ts (100%) rename packages/plugin/src/{ => core}/crypto/passphrase-cache.ts (86%) rename packages/plugin/src/{ => core}/crypto/seal.ts (100%) rename packages/plugin/src/{ => core}/crypto/sealed-link.ts (98%) rename packages/plugin/src/{ => core}/drawing/format.ts (100%) create mode 100644 packages/plugin/src/core/drawing/index.ts rename packages/plugin/src/{ => core}/drawing/merge.ts (100%) rename packages/plugin/src/{ => core}/drawing/scene.ts (96%) create mode 100644 packages/plugin/src/core/hub/index.ts rename packages/plugin/src/{ => core}/hub/link.ts (100%) rename packages/plugin/src/{ui/common/relay.ts => core/hub/relay-text.ts} (94%) rename packages/plugin/src/{ => core}/hub/status.ts (100%) delete mode 100644 packages/plugin/src/core/index.ts create mode 100644 packages/plugin/src/core/logs/index.ts rename packages/plugin/src/core/{ => logs}/log-service.ts (97%) rename packages/plugin/src/{ => core}/logs/store.ts (94%) rename packages/plugin/src/{ => core}/settings/fields.ts (97%) create mode 100644 packages/plugin/src/core/settings/index.ts rename packages/plugin/src/{ => core}/settings/model.ts (95%) rename packages/plugin/src/{ => core}/settings/page.ts (100%) rename packages/plugin/src/{ => core}/shared/colors.ts (100%) rename packages/plugin/src/{ => core}/shared/diagnostics.ts (100%) rename packages/plugin/src/{ => core}/shared/errors.ts (100%) rename packages/plugin/src/{ => core}/shared/format.ts (97%) create mode 100644 packages/plugin/src/core/shared/index.ts rename packages/plugin/src/{ => core}/shared/offline.ts (100%) rename packages/plugin/src/{ => core}/shared/path.ts (100%) rename packages/plugin/src/{ => core}/shared/records.ts (100%) rename packages/plugin/src/{ui/source-control => core/ui/controls}/action-button.ts (100%) rename packages/plugin/src/{ui/common => core/ui/controls}/alert-line.ts (100%) rename packages/plugin/src/{ui/common => core/ui/controls}/callout.ts (100%) rename packages/plugin/src/{ui/common => core/ui/controls}/copyable.ts (93%) rename packages/plugin/src/{ui/common => core/ui/controls}/file-path.ts (100%) rename packages/plugin/src/{ui/common => core/ui/controls}/icon-button.ts (100%) rename packages/plugin/src/{ui/common => core/ui/controls}/marquee.ts (100%) rename packages/plugin/src/{ui/common => core/ui/controls}/segments.ts (100%) create mode 100644 packages/plugin/src/core/ui/index.ts rename packages/plugin/src/{ui/common => core/ui/input}/activatable.ts (100%) rename packages/plugin/src/{ui/common => core/ui/input}/enter-key.ts (88%) rename packages/plugin/src/{ui/common => core/ui/input}/focus.ts (100%) rename packages/plugin/src/{ui/common => core/ui/input}/long-press.ts (100%) rename packages/plugin/src/{ui/common => core/ui}/menu.ts (86%) rename packages/plugin/src/{ui/common => core/ui}/modal-frame.ts (100%) rename packages/plugin/src/{ => core}/ui/modals/confirm-modal.ts (97%) rename packages/plugin/src/{ => core}/ui/modals/passphrase-modal.ts (94%) rename packages/plugin/src/{ => core}/ui/modals/promise-modal.ts (100%) rename packages/plugin/src/{ => core}/ui/modals/prompt-modal.ts (94%) rename packages/plugin/src/{ui/common => core/ui}/notices.ts (93%) rename packages/plugin/src/{ui/common => core/ui}/obsidian-helpers.ts (100%) rename packages/plugin/src/{ui/common => core/ui}/open-note.ts (100%) rename packages/plugin/src/{ui/common => core/ui}/phone-change.ts (100%) rename packages/plugin/src/{ui/common => core/ui}/serial.ts (100%) rename packages/plugin/src/{styles/base => core/ui/styles}/callout.css (100%) rename packages/plugin/src/{styles/base => core/ui/styles}/file-path.css (100%) rename packages/plugin/src/{styles/base => core/ui/styles}/icon-button.css (100%) rename packages/plugin/src/{styles/base => core/ui/styles}/marquee.css (100%) rename packages/plugin/src/{ => core/ui}/styles/mobile.css (100%) rename packages/plugin/src/{ => core/ui}/styles/modal-frame.css (100%) rename packages/plugin/src/{ => core/ui}/styles/modals.css (100%) rename packages/plugin/src/{styles/base => core/ui/styles}/notice.css (100%) rename packages/plugin/src/{styles/base => core/ui/styles}/segments.css (100%) rename packages/plugin/src/{ => core/ui}/styles/tokens.css (100%) rename packages/plugin/src/{ => core}/utils/base64.ts (100%) rename packages/plugin/src/{ => core}/utils/bytes.ts (100%) rename packages/plugin/src/{ => core}/utils/compress.ts (100%) rename packages/plugin/src/{ => core}/utils/concurrency.ts (100%) rename packages/plugin/src/{ => core}/utils/diff.ts (100%) rename packages/plugin/src/{ => core}/utils/eol.ts (100%) rename packages/plugin/src/{ => core}/utils/file-concurrency.ts (100%) create mode 100644 packages/plugin/src/core/utils/index.ts rename packages/plugin/src/{ => core}/utils/revision.ts (100%) rename packages/plugin/src/{ => core}/utils/search.ts (100%) rename packages/plugin/src/{ => core}/vault/atomic-write.ts (100%) rename packages/plugin/src/{ => core}/vault/file-index.ts (100%) create mode 100644 packages/plugin/src/core/vault/index.ts rename packages/plugin/src/{ => core}/vault/io.ts (98%) rename packages/plugin/src/{ => core}/vault/symlinks.ts (100%) delete mode 100644 packages/plugin/src/drawing/index.ts delete mode 100644 packages/plugin/src/editor/signs/index.ts rename packages/plugin/src/{ui => features}/diff/action-bar.ts (97%) rename packages/plugin/src/{ui => features}/diff/choices.ts (96%) rename packages/plugin/src/{ui/diff => features/diff/compare}/binary-view.ts (89%) rename packages/plugin/src/{ui/diff => features/diff/compare}/compare-controls.ts (92%) rename packages/plugin/src/{ui/diff => features/diff/compare}/compare-decorations.ts (92%) rename packages/plugin/src/{ui/diff => features/diff/compare}/compare-panel.ts (95%) rename packages/plugin/src/{ui/diff => features/diff/compare}/hunk-renderer.ts (88%) rename packages/plugin/src/{ui/diff => features/diff/compare}/preview-panel.ts (100%) rename packages/plugin/src/{ui => features}/diff/file-navigation.ts (95%) rename packages/plugin/src/{ui => features}/diff/header.ts (99%) rename packages/plugin/src/{ui => features}/diff/history-state.ts (97%) create mode 100644 packages/plugin/src/features/diff/index.ts rename packages/plugin/src/{ui => features}/diff/layout-mode.ts (93%) rename packages/plugin/src/{ui => features}/diff/line-wrapping-control.ts (96%) rename packages/plugin/src/{ui/diff => features/diff/lines}/change-overlay.ts (96%) rename packages/plugin/src/{ui/diff => features/diff/lines}/code-lines.ts (96%) rename packages/plugin/src/{ui/diff => features/diff/lines}/divider.ts (98%) rename packages/plugin/src/{ui/diff => features/diff/lines}/gap-widgets.ts (97%) rename packages/plugin/src/{ui/diff => features/diff/lines}/geometry.ts (95%) rename packages/plugin/src/{ui/diff => features/diff/lines}/line-tints.ts (100%) rename packages/plugin/src/{ui/diff => features/diff/lines}/scroll-sync.ts (98%) rename packages/plugin/src/{ui/diff => features/diff/lines}/source-widget.ts (98%) rename packages/plugin/src/{ui/diff => features/diff/merge}/merge-actions.ts (98%) rename packages/plugin/src/{ui/diff => features/diff/merge}/merge-cards.ts (94%) rename packages/plugin/src/{ui/diff => features/diff/merge}/merge-controls.ts (93%) rename packages/plugin/src/{ui/diff => features/diff/merge}/merge-decorations.ts (93%) rename packages/plugin/src/{ui/diff => features/diff/merge}/merge-editor.ts (95%) rename packages/plugin/src/{ui/diff => features/diff/merge}/merge-marks.ts (88%) rename packages/plugin/src/{ui/diff => features/diff/merge}/merge-state.ts (99%) rename packages/plugin/src/{ui/diff => features/diff/merge}/merge-toolbar.ts (94%) rename packages/plugin/src/{ui => features}/diff/operations.ts (93%) rename packages/plugin/src/{ui => features}/diff/rail.ts (97%) rename packages/plugin/src/{ui/source-control => features/diff}/restore-modal.ts (94%) rename packages/plugin/src/{styles/diff => features/diff/styles}/cards.css (100%) rename packages/plugin/src/{styles/diff => features/diff/styles}/cm-lines.css (100%) rename packages/plugin/src/{styles/diff => features/diff/styles}/code-lines.css (100%) rename packages/plugin/src/{styles/diff => features/diff/styles}/divider.css (100%) rename packages/plugin/src/{styles/diff => features/diff/styles}/gaps.css (100%) rename packages/plugin/src/{styles/diff => features/diff/styles}/hunk-preview.css (100%) rename packages/plugin/src/{styles/diff => features/diff/styles}/merge.css (100%) rename packages/plugin/src/{styles/diff => features/diff/styles}/pane-grid.css (100%) rename packages/plugin/src/{styles/diff => features/diff/styles}/phone.css (100%) rename packages/plugin/src/{styles/diff => features/diff/styles}/rail.css (100%) rename packages/plugin/src/{styles/diff => features/diff/styles}/source-blocks.css (100%) rename packages/plugin/src/{styles/diff => features/diff/styles}/tones.css (100%) rename packages/plugin/src/{styles/diff => features/diff/styles}/toolbars.css (100%) rename packages/plugin/src/{styles/diff => features/diff/styles}/view.css (100%) rename packages/plugin/src/{ui/diff-view.ts => features/diff/view.ts} (94%) rename packages/plugin/src/{editor/signs => features/editor-signs}/compute.ts (100%) rename packages/plugin/src/{editor/signs => features/editor-signs}/extension.ts (100%) rename packages/plugin/src/{editor/signs => features/editor-signs}/focus.ts (100%) rename packages/plugin/src/{editor/signs => features/editor-signs}/gutter.ts (99%) rename packages/plugin/src/{editor/signs => features/editor-signs}/helpers.ts (98%) rename packages/plugin/src/{styles/editor => features/editor-signs}/hunk-popup.css (100%) create mode 100644 packages/plugin/src/features/editor-signs/index.ts rename packages/plugin/src/{editor/signs => features/editor-signs/popup}/hunk-popup.ts (91%) rename packages/plugin/src/{editor/signs => features/editor-signs/popup}/hunk-revert.ts (93%) rename packages/plugin/src/{editor/signs => features/editor-signs/popup}/popup-dismiss.ts (100%) rename packages/plugin/src/{editor/signs => features/editor-signs/popup}/popup-placement.ts (100%) rename packages/plugin/src/{editor/signs => features/editor-signs/popup}/popup-view.ts (96%) rename packages/plugin/src/{editor/signs => features/editor-signs}/provider.ts (95%) rename packages/plugin/src/{editor/signs/integration.ts => features/editor-signs/register.ts} (97%) rename packages/plugin/src/{styles/editor => features/editor-signs}/signs.css (100%) rename packages/plugin/src/{editor/signs => features/editor-signs}/state.ts (100%) rename packages/plugin/src/{editor/signs => features/editor-signs}/subscriber.ts (100%) rename packages/plugin/src/{styles => features/explorer}/explorer.css (100%) rename packages/plugin/src/{ui => features}/explorer/file-context-indicators.ts (96%) rename packages/plugin/src/{ui => features}/explorer/file-explorer-api.ts (100%) rename packages/plugin/src/{ui => features}/explorer/file-explorer-badges.ts (94%) rename packages/plugin/src/{ui => features}/explorer/file-explorer-decorations.ts (97%) rename packages/plugin/src/{ui => features}/explorer/file-explorer-indicators.ts (97%) rename packages/plugin/src/{ui => features}/explorer/file-explorer-marks.ts (92%) create mode 100644 packages/plugin/src/features/explorer/index.ts rename packages/plugin/src/{ui => features}/explorer/indicator-handle.ts (100%) rename packages/plugin/src/{ui => features}/explorer/link-scan.ts (97%) rename packages/plugin/src/{ui => features}/explorer/row-decorator.ts (95%) create mode 100644 packages/plugin/src/features/links/README.md rename packages/plugin/src/{ => features}/links/describe.ts (100%) rename packages/plugin/src/{ => features}/links/errors.ts (69%) create mode 100644 packages/plugin/src/features/links/index.ts rename packages/plugin/src/{storage/adapters => features/links}/link-broker.ts (93%) rename packages/plugin/src/{ => features}/links/note-links.ts (96%) rename packages/plugin/src/{ => features}/links/publish.ts (94%) rename packages/plugin/src/{ => features}/links/record.ts (98%) rename packages/plugin/src/{plugin/links.ts => features/links/register.ts} (87%) rename packages/plugin/src/{ => features}/links/remote.ts (91%) rename packages/plugin/src/{ => features}/links/shared-links.ts (98%) rename packages/plugin/src/{links => features/links/snapshot}/images.ts (100%) rename packages/plugin/src/{links => features/links/snapshot}/math.ts (100%) rename packages/plugin/src/{links => features/links/snapshot}/note-text.ts (100%) rename packages/plugin/src/{links => features/links/snapshot}/sanitize.ts (100%) rename packages/plugin/src/{links => features/links/snapshot}/snapshot.ts (100%) rename packages/plugin/src/{ui/links => features/links/ui}/link-actions.ts (82%) rename packages/plugin/src/{ui/links => features/links/ui}/link-menu.ts (87%) rename packages/plugin/src/{settings/sections/links.ts => features/links/ui/links-section.ts} (85%) rename packages/plugin/src/{styles => features/links/ui}/links.css (100%) rename packages/plugin/src/{ui/links => features/links/ui}/manage-links-modal.ts (95%) rename packages/plugin/src/{ui/links => features/links/ui}/note-link-action.ts (94%) rename packages/plugin/src/{ui/links => features/links/ui}/preview-frame.ts (100%) rename packages/plugin/src/{ui/links => features/links/ui}/share-link-modal.ts (96%) create mode 100644 packages/plugin/src/features/live/README.md rename packages/plugin/src/{ => features}/live/authors.ts (100%) rename packages/plugin/src/{ => features}/live/cold/agreed-texts.ts (97%) rename packages/plugin/src/{ => features}/live/cold/cold-sync.ts (88%) rename packages/plugin/src/{ => features}/live/doc-id.ts (95%) rename packages/plugin/src/{ => features}/live/doc-types.ts (100%) rename packages/plugin/src/{ => features}/live/drawing/binding.ts (96%) rename packages/plugin/src/{ => features}/live/drawing/excalidraw.ts (97%) rename packages/plugin/src/{ => features}/live/drawing/model.ts (97%) create mode 100644 packages/plugin/src/features/live/index.ts rename packages/plugin/src/{ui => features}/live/live-state.ts (93%) rename packages/plugin/src/{ => features}/live/model.ts (100%) rename packages/plugin/src/{plugin/live.ts => features/live/register.ts} (88%) rename packages/plugin/src/{ => features}/live/session/closing.ts (100%) rename packages/plugin/src/{ => features}/live/session/follower-session.ts (96%) rename packages/plugin/src/{ => features}/live/session/outbox.ts (98%) rename packages/plugin/src/{ => features}/live/session/room-awareness.ts (97%) rename packages/plugin/src/{ => features}/live/session/room-log.ts (100%) rename packages/plugin/src/{ => features}/live/session/rotation.ts (91%) rename packages/plugin/src/{ => features}/live/session/session-deps.ts (89%) rename packages/plugin/src/{ => features}/live/session/session.ts (97%) rename packages/plugin/src/{ => features}/live/text/author-marks.ts (96%) rename packages/plugin/src/{ => features}/live/text/binding.ts (96%) rename packages/plugin/src/{ => features}/live/text/cursors.ts (97%) rename packages/plugin/src/{ => features}/live/text/merge.ts (91%) rename packages/plugin/src/{ => features}/live/text/model.ts (93%) rename packages/plugin/src/{ => features}/live/text/patch.ts (93%) rename packages/plugin/src/{ => features}/live/text/rebuild.ts (96%) rename packages/plugin/src/{ => features}/live/text/remote-selections.ts (100%) rename packages/plugin/src/{ => features}/live/text/scroll-marks.ts (95%) rename packages/plugin/src/{ui/live => features/live/ui}/deleted-elsewhere.ts (87%) rename packages/plugin/src/{ => features}/live/workspace/editors.ts (90%) rename packages/plugin/src/{ => features}/live/workspace/patience.ts (100%) rename packages/plugin/src/{ => features}/live/workspace/rename.ts (90%) rename packages/plugin/src/{ => features}/live/workspace/room.ts (95%) rename packages/plugin/src/{ => features}/live/workspace/sessions.ts (97%) rename packages/plugin/src/{ => features}/live/workspace/space.ts (89%) rename packages/plugin/src/{ui/live/header => features/note-header}/header-state.ts (87%) create mode 100644 packages/plugin/src/features/note-header/index.ts rename packages/plugin/src/{ui/live/header => features/note-header}/live-actions.ts (81%) rename packages/plugin/src/{ui/live/header => features/note-header}/live-status.ts (88%) rename packages/plugin/src/{ui/live/header => features/note-header}/note-menu-items.ts (95%) rename packages/plugin/src/{ui/live/header => features/note-header}/note-menu.ts (92%) rename packages/plugin/src/{ui/live/header => features/note-header}/note-presence.ts (94%) create mode 100644 packages/plugin/src/features/presence/README.md rename packages/plugin/src/{ => features}/presence/announcement.ts (95%) rename packages/plugin/src/{ => features}/presence/channel.ts (98%) rename packages/plugin/src/{ui/live/header => features/presence/follow}/cursor-follow.ts (95%) rename packages/plugin/src/{ui/live/header => features/presence/follow}/follow-banner.ts (87%) rename packages/plugin/src/{ui/live/header => features/presence/follow}/follow-scroll.ts (91%) rename packages/plugin/src/{plugin => features/presence/follow}/follows.ts (76%) rename packages/plugin/src/{ => features}/presence/here.ts (100%) create mode 100644 packages/plugin/src/features/presence/index.ts rename packages/plugin/src/{ => features}/presence/people.ts (97%) rename packages/plugin/src/{plugin/unseen.ts => features/presence/register.ts} (91%) rename packages/plugin/src/{ui/common => features/presence/ui}/avatars.ts (92%) rename packages/plugin/src/{styles => features/presence/ui}/presence.css (100%) rename packages/plugin/src/{ => features}/presence/unseen.ts (100%) rename packages/plugin/src/{ => features}/presence/views.ts (100%) rename packages/plugin/src/{hub => features/relay}/channels.ts (88%) rename packages/plugin/src/{hub => features/relay}/connection.ts (96%) rename packages/plugin/src/{cloudflare => features/relay/deploy}/assets.ts (91%) rename packages/plugin/src/{cloudflare => features/relay/deploy}/bundle.ts (100%) rename packages/plugin/src/{settings/setup/relay.ts => features/relay/deploy/deploy-flow.ts} (92%) rename packages/plugin/src/{cloudflare => features/relay/deploy}/migrations.ts (100%) rename packages/plugin/src/{cloudflare => features/relay/deploy}/relay-account.ts (98%) rename packages/plugin/src/{cloudflare => features/relay/deploy}/relay-bundle.d.ts (73%) rename packages/plugin/src/{cloudflare => features/relay/deploy}/relay-deploy.ts (98%) create mode 100644 packages/plugin/src/features/relay/index.ts rename packages/plugin/src/{settings/sections/relay.ts => features/relay/ui/relay-section.ts} (86%) rename packages/plugin/src/{ui/modals => features/relay/update}/relay-update-modal.ts (87%) rename packages/plugin/src/{plugin => features/relay/update}/relay-update.ts (91%) create mode 100644 packages/plugin/src/features/settings/index.ts rename packages/plugin/src/{ => features}/settings/logs-view.ts (94%) rename packages/plugin/src/{styles => features}/settings/overview.css (100%) rename packages/plugin/src/{ => features}/settings/overview.ts (93%) rename packages/plugin/src/{ => features}/settings/sections/advanced.ts (80%) rename packages/plugin/src/{ => features}/settings/sections/automation.ts (94%) rename packages/plugin/src/{ => features}/settings/sections/interface.ts (96%) rename packages/plugin/src/{ => features}/settings/sections/security.ts (89%) rename packages/plugin/src/{ => features}/settings/tab.ts (68%) rename packages/plugin/src/{styles => features}/settings/tabs-and-logs.css (100%) create mode 100644 packages/plugin/src/features/setup/README.md rename packages/plugin/src/{settings => features}/setup/choice-card.ts (100%) rename packages/plugin/src/{settings => features}/setup/form.ts (100%) rename packages/plugin/src/{settings => features}/setup/index.ts (59%) rename packages/plugin/src/{settings => features}/setup/passphrase-meter.ts (96%) rename packages/plugin/src/{settings => features}/setup/run-action.ts (92%) rename packages/plugin/src/{settings/setup/steps.ts => features/setup/step-state.ts} (95%) rename packages/plugin/src/{settings => features}/setup/stepper.ts (100%) rename packages/plugin/src/{settings/setup => features/setup/steps}/cloudflare-token.ts (91%) rename packages/plugin/src/{settings/setup => features/setup/steps}/import-step.ts (89%) rename packages/plugin/src/{settings/setup => features/setup/steps}/passphrase-step.ts (89%) rename packages/plugin/src/{settings/setup => features/setup/steps}/ready-step.ts (89%) rename packages/plugin/src/{settings/setup => features/setup/steps}/relay-deploy-view.ts (95%) rename packages/plugin/src/{settings/setup => features/setup/steps}/relay-step.ts (89%) rename packages/plugin/src/{settings/setup => features/setup/steps}/start-step.ts (86%) rename packages/plugin/src/{settings/setup => features/setup/steps}/storage-step.ts (86%) rename packages/plugin/src/{styles/settings => features/setup/styles}/setup-cards.css (100%) rename packages/plugin/src/{styles/settings => features/setup/styles}/setup-forms.css (100%) rename packages/plugin/src/{styles/settings => features/setup/styles}/setup-progress.css (100%) rename packages/plugin/src/{styles/settings => features/setup/styles}/setup-stepper.css (100%) rename packages/plugin/src/{styles/settings => features/setup/styles}/setup.css (100%) rename packages/plugin/src/{settings => features}/setup/wizard.ts (92%) rename packages/plugin/src/{ui/source-control => features/source-control/actions}/actions.ts (94%) rename packages/plugin/src/{ui/source-control => features/source-control/actions}/section-actions.ts (96%) rename packages/plugin/src/{ui/source-control => features/source-control/actions}/selection-bar.ts (94%) rename packages/plugin/src/{ui/source-control => features/source-control/changes}/change-rows.ts (96%) rename packages/plugin/src/{ui/source-control => features/source-control/changes}/changes-section.ts (96%) rename packages/plugin/src/{ui/source-control => features/source-control/changes}/changes-tab.ts (95%) rename packages/plugin/src/{ui/source-control => features/source-control/changes}/conflict-preview-manager.ts (98%) rename packages/plugin/src/{ui/source-control => features/source-control/changes}/conflict-preview.ts (96%) rename packages/plugin/src/{ui/source-control => features/source-control/changes}/diff-identity.ts (94%) rename packages/plugin/src/{ui/source-control => features/source-control/changes}/excluded-files.ts (92%) rename packages/plugin/src/{ui/source-control => features/source-control/changes}/file-list-modal.ts (99%) rename packages/plugin/src/{ui/source-control => features/source-control/changes}/row-formatter.ts (85%) rename packages/plugin/src/{ui/source-control => features/source-control/changes}/tree-builder.ts (99%) rename packages/plugin/src/{ui/source-control => features/source-control/history}/day-groups.ts (95%) rename packages/plugin/src/{ui/source-control => features/source-control/history}/history-list.ts (95%) rename packages/plugin/src/{ui/source-control => features/source-control/history}/history-rows.ts (92%) rename packages/plugin/src/{ui/source-control => features/source-control/history}/history-tab.ts (95%) rename packages/plugin/src/{styles/source-control => features/source-control/history}/history.css (100%) rename packages/plugin/src/{ui/source-control => features/source-control/history}/row-pager.ts (100%) create mode 100644 packages/plugin/src/features/source-control/index.ts rename packages/plugin/src/{ui => features}/source-control/row-parts.ts (95%) rename packages/plugin/src/{ui => features}/source-control/setup-prompt.ts (87%) rename packages/plugin/src/{styles/source-control => features/source-control/styles}/containers.css (100%) rename packages/plugin/src/{styles/source-control => features/source-control/styles}/file-list.css (100%) rename packages/plugin/src/{styles/source-control => features/source-control/styles}/file-rows.css (100%) rename packages/plugin/src/{styles/source-control => features/source-control/styles}/phone.css (100%) rename packages/plugin/src/{styles/source-control => features/source-control/styles}/sections.css (100%) rename packages/plugin/src/{styles/source-control => features/source-control/styles}/shell.css (100%) rename packages/plugin/src/{styles/source-control => features/source-control/styles}/states.css (100%) rename packages/plugin/src/{styles/source-control => features/source-control/styles}/summary.css (100%) rename packages/plugin/src/{styles/source-control => features/source-control/styles}/toolbar.css (100%) rename packages/plugin/src/{styles/source-control => features/source-control/styles}/tree.css (100%) rename packages/plugin/src/{ui => features}/source-control/summary-card.ts (95%) rename packages/plugin/src/{ui => features}/source-control/tab-states.ts (94%) rename packages/plugin/src/{styles/source-control => features/source-control/timeline}/restore.css (100%) rename packages/plugin/src/{ui/source-control => features/source-control/timeline}/snapshot-menu.ts (90%) rename packages/plugin/src/{ui/source-control => features/source-control/timeline}/timeline-actions.ts (94%) rename packages/plugin/src/{ui/source-control => features/source-control/timeline}/timeline-rows.ts (95%) rename packages/plugin/src/{ui/source-control => features/source-control/timeline}/timeline-tab.ts (94%) rename packages/plugin/src/{styles/source-control => features/source-control/timeline}/timeline.css (100%) rename packages/plugin/src/{ui/source-control => features/source-control/trash}/trash-rows.ts (96%) rename packages/plugin/src/{ui/source-control => features/source-control/trash}/trash-tab.ts (96%) rename packages/plugin/src/{ui => features}/source-control/types.ts (100%) rename packages/plugin/src/{ui/source-control-view.ts => features/source-control/view.ts} (95%) rename packages/plugin/src/{ui => features}/source-control/virtual-list.ts (100%) create mode 100644 packages/plugin/src/features/spaces/README.md rename packages/plugin/src/{ => features}/spaces/access.ts (89%) rename packages/plugin/src/{storage/adapters => features/spaces/broker}/share-broker.ts (96%) rename packages/plugin/src/{storage/adapters => features/spaces/broker}/share-signed-urls.ts (100%) create mode 100644 packages/plugin/src/features/spaces/index.ts rename packages/plugin/src/{ => features}/spaces/invite.ts (96%) rename packages/plugin/src/{ui/common => features/spaces}/last-edit.ts (84%) rename packages/plugin/src/{ => features}/spaces/owner.ts (94%) rename packages/plugin/src/{ => features}/spaces/partition.ts (93%) rename packages/plugin/src/{ => features}/spaces/record.ts (99%) rename packages/plugin/src/{ => features}/spaces/records.ts (98%) rename packages/plugin/src/{ => features}/spaces/remote.ts (88%) rename packages/plugin/src/{plugin => features/spaces}/share-moves.ts (91%) rename packages/plugin/src/{plugin => features/spaces}/share-registration.ts (83%) rename packages/plugin/src/{plugin => features/spaces}/space-access.ts (85%) rename packages/plugin/src/{ui/shares => features/spaces/ui}/access-ended.ts (91%) rename packages/plugin/src/{ui/shares => features/spaces/ui/invites}/invite-action.ts (89%) rename packages/plugin/src/{ui/modals => features/spaces/ui/invites}/invite-modal.ts (97%) rename packages/plugin/src/{ui/shares => features/spaces/ui/invites}/invite-section.ts (97%) rename packages/plugin/src/{editor => features/spaces/ui}/read-only.ts (97%) rename packages/plugin/src/{ui/shares => features/spaces/ui}/share-action.ts (88%) rename packages/plugin/src/{settings/sections/shares.ts => features/spaces/ui/shares-section.ts} (92%) rename packages/plugin/src/{styles => features/spaces/ui}/shares.css (100%) rename packages/plugin/src/{ui/shares => features/spaces/ui}/space-gone.ts (87%) rename packages/plugin/src/{ui/shares => features/spaces/ui/window}/pause-control.ts (88%) rename packages/plugin/src/{ui/shares => features/spaces/ui/window}/people-list.ts (93%) rename packages/plugin/src/{ui/shares => features/spaces/ui/window}/share-head.ts (90%) rename packages/plugin/src/{ui/shares => features/spaces/ui/window}/share-modal.ts (92%) rename packages/plugin/src/{ui/shares => features/spaces/ui/window}/share-people.ts (90%) rename packages/plugin/src/{ui/shares => features/spaces/ui/window}/share-summary.ts (84%) rename packages/plugin/src/{ui/shares => features/spaces/ui/window}/share-window.ts (80%) create mode 100644 packages/plugin/src/features/status/index.ts rename packages/plugin/src/{ui/live => features}/status/live-spaces.ts (75%) rename packages/plugin/src/{ui/live => features}/status/relay-status.ts (91%) rename packages/plugin/src/{styles => features/status}/ribbon.css (100%) rename packages/plugin/src/{ui => features/status}/ribbon.ts (87%) rename packages/plugin/src/{styles => features/status}/status-bar.css (100%) rename packages/plugin/src/{ui => features/status}/status-bar.ts (92%) rename packages/plugin/src/{ui => features/status}/status-menu.ts (88%) rename packages/plugin/src/{ui/live => features}/status/where-menu.ts (90%) rename packages/plugin/src/{storage/adapters => features/storage/backends}/google-drive-auth.ts (94%) rename packages/plugin/src/{storage/adapters => features/storage/backends}/google-drive-request.ts (96%) rename packages/plugin/src/{storage/adapters => features/storage/backends}/google-drive-upload.ts (98%) rename packages/plugin/src/{storage/adapters => features/storage/backends}/google-drive.ts (98%) rename packages/plugin/src/{storage/adapters => features/storage/backends}/s3-signer.ts (98%) rename packages/plugin/src/{storage/adapters => features/storage/backends}/s3-store.ts (99%) rename packages/plugin/src/{storage/adapters => features/storage/backends}/s3-xml.ts (98%) rename packages/plugin/src/{storage/adapters => features/storage/backends}/s3.ts (90%) rename packages/plugin/src/{storage/adapters => features/storage/backends}/util.ts (99%) rename packages/plugin/src/{storage/adapters => features/storage/backends}/webdav.ts (97%) rename packages/plugin/src/{settings => features/storage/cloudflare}/cloudflare-login.ts (88%) rename packages/plugin/src/{settings/r2.ts => features/storage/cloudflare/r2-select.ts} (83%) rename packages/plugin/src/{ => features/storage}/cloudflare/r2.ts (92%) rename packages/plugin/src/{ => features}/storage/config.ts (100%) rename packages/plugin/src/{ => features}/storage/field-spec.ts (95%) create mode 100644 packages/plugin/src/features/storage/index.ts rename packages/plugin/src/{ => features}/storage/records.ts (96%) rename packages/plugin/src/{ => features}/storage/registry.ts (96%) rename packages/plugin/src/{plugin => features/storage}/storage-refused.ts (78%) rename packages/plugin/src/{ => features}/storage/types.ts (100%) rename packages/plugin/src/{settings/sections/backend.ts => features/storage/ui/backend-section.ts} (85%) rename packages/plugin/src/{settings => features/storage/ui}/connection-test.ts (94%) rename packages/plugin/src/{settings/sections => features/storage/ui}/storage-fields.ts (90%) rename packages/plugin/src/{ui/modals => features/storage/ui}/storage-refused-modal.ts (86%) create mode 100644 packages/plugin/src/features/sync/README.md rename packages/plugin/src/{sync => features/sync/apply}/auto-merge.ts (90%) rename packages/plugin/src/{sync => features/sync/apply}/conflict-copy.ts (97%) rename packages/plugin/src/{sync => features/sync/apply}/conflict-merge.ts (83%) rename packages/plugin/src/{sync => features/sync/apply}/pull-moves.ts (94%) rename packages/plugin/src/{sync => features/sync/apply}/pull.ts (89%) rename packages/plugin/src/{sync => features/sync/automation}/auto-push.ts (95%) rename packages/plugin/src/{sync => features/sync/automation}/scheduler.ts (97%) rename packages/plugin/src/{ => features}/sync/cancel.ts (100%) rename packages/plugin/src/{sync => features/sync/changes}/binary-extensions.ts (100%) rename packages/plugin/src/{sync => features/sync/changes}/content.ts (93%) rename packages/plugin/src/{sync => features/sync/changes}/diff.ts (96%) rename packages/plugin/src/{sync => features/sync/changes}/moves.ts (99%) rename packages/plugin/src/{sync => features/sync/changes}/remote-names.ts (92%) rename packages/plugin/src/{ => features}/sync/constants.ts (100%) rename packages/plugin/src/{ => features}/sync/controller.ts (94%) rename packages/plugin/src/{ => features}/sync/engine.ts (89%) rename packages/plugin/src/{ => features}/sync/history/changes.ts (96%) rename packages/plugin/src/{ => features}/sync/history/gc.ts (95%) rename packages/plugin/src/{ => features}/sync/history/publish.ts (85%) rename packages/plugin/src/{ => features}/sync/history/query.ts (96%) rename packages/plugin/src/{ => features}/sync/history/replay.ts (95%) rename packages/plugin/src/{ => features}/sync/history/restore-vault.ts (94%) rename packages/plugin/src/{ => features}/sync/history/store.ts (95%) rename packages/plugin/src/{ => features}/sync/history/types.ts (97%) rename packages/plugin/src/{sync => features/sync/hunks}/anchored-hunks.ts (98%) rename packages/plugin/src/{sync => features/sync/hunks}/diff-cache.ts (95%) rename packages/plugin/src/{sync => features/sync/hunks}/hunks.ts (99%) rename packages/plugin/src/{sync => features/sync/hunks}/merge-model.ts (99%) rename packages/plugin/src/{sync => features/sync/hunks}/projection.ts (97%) rename packages/plugin/src/{sync => features/sync/identity}/authors.ts (99%) rename packages/plugin/src/{core => features/sync/identity}/device-name.ts (81%) rename packages/plugin/src/{sync => features/sync/identity}/device.ts (100%) create mode 100644 packages/plugin/src/features/sync/index.ts rename packages/plugin/src/{ => features}/sync/live-notes.ts (98%) rename packages/plugin/src/{ => features}/sync/operations/config-reset.ts (83%) rename packages/plugin/src/{ => features}/sync/operations/flows.ts (87%) rename packages/plugin/src/{ => features}/sync/operations/hunks.ts (94%) rename packages/plugin/src/{ => features}/sync/operations/pull.ts (87%) rename packages/plugin/src/{ => features}/sync/operations/push.ts (84%) rename packages/plugin/src/{ => features}/sync/operations/resolve.ts (92%) rename packages/plugin/src/{ => features}/sync/operations/revert.ts (88%) rename packages/plugin/src/{ => features}/sync/operations/text-loaders.ts (92%) rename packages/plugin/src/{ => features}/sync/operations/types.ts (84%) rename packages/plugin/src/{sync => features/sync/recovery}/cut-short.ts (94%) rename packages/plugin/src/{sync => features/sync/recovery}/journal.ts (96%) rename packages/plugin/src/{core => features/sync/recovery}/state-persister.ts (98%) rename packages/plugin/src/{sync => features/sync/remote}/baseline.ts (94%) rename packages/plugin/src/{sync => features/sync/remote}/config-reset.ts (90%) rename packages/plugin/src/{sync => features/sync/remote}/foreign.ts (92%) rename packages/plugin/src/{sync => features/sync/remote}/keyfile.ts (94%) rename packages/plugin/src/{sync => features/sync/remote}/manifest.ts (96%) rename packages/plugin/src/{core => features/sync/remote}/passphrase-manager.ts (95%) rename packages/plugin/src/{sync => features/sync/remote}/reset.ts (85%) rename packages/plugin/src/{sync => features/sync/remote}/space-paths.ts (95%) rename packages/plugin/src/{sync => features/sync/remote}/space.ts (100%) rename packages/plugin/src/{sync => features/sync/remote}/uploads.ts (97%) rename packages/plugin/src/{ => features}/sync/runtime/auto-cycle.ts (89%) rename packages/plugin/src/{ => features}/sync/runtime/controller-state.ts (97%) rename packages/plugin/src/{ => features}/sync/runtime/file-diff-service.ts (94%) rename packages/plugin/src/{ => features}/sync/runtime/history-service.ts (91%) rename packages/plugin/src/{ => features}/sync/runtime/maintenance-service.ts (88%) rename packages/plugin/src/{sync => features/sync/runtime}/maintenance.ts (90%) rename packages/plugin/src/{ => features}/sync/runtime/merged-result.ts (92%) rename packages/plugin/src/{ => features}/sync/runtime/operation-runner.ts (94%) rename packages/plugin/src/{ => features}/sync/runtime/refresh-queue.ts (96%) rename packages/plugin/src/{ => features}/sync/runtime/saved-refresh.ts (91%) rename packages/plugin/src/{ => features}/sync/runtime/scan-cycle.ts (89%) rename packages/plugin/src/{ui/source-control => features/sync/runtime}/sync-gates.ts (91%) rename packages/plugin/src/{settings/sections/configuration-scope.ts => features/sync/scope/configuration-scope-section.ts} (92%) rename packages/plugin/src/{vault => features/sync/scope}/entry.ts (84%) rename packages/plugin/src/{settings/sections/exclusions.ts => features/sync/scope/exclusions-section.ts} (94%) rename packages/plugin/src/{settings => features/sync/scope}/ignore-rules.ts (95%) rename packages/plugin/src/{plugin => features/sync/scope}/ignore-state.ts (97%) rename packages/plugin/src/{vault => features/sync/scope}/ignore.ts (94%) rename packages/plugin/src/{vault => features/sync/scope}/scanner.ts (98%) rename packages/plugin/src/{vault => features/sync/scope}/scope.ts (96%) rename packages/plugin/src/{ => features}/sync/session-state.ts (96%) rename packages/plugin/src/{ => features}/sync/session.ts (82%) rename packages/plugin/src/{ => features}/sync/state.ts (92%) rename packages/plugin/src/{ => features}/sync/status-broadcaster.ts (100%) rename packages/plugin/src/{ => features}/sync/types.ts (100%) rename packages/plugin/src/{ui/common => features/sync/ui}/change-action.ts (85%) rename packages/plugin/src/{ui/actions => features/sync/ui}/ignore-action.ts (95%) rename packages/plugin/src/{ui/actions => features/sync/ui}/maintenance-actions.ts (87%) rename packages/plugin/src/{settings/sections/maintenance.ts => features/sync/ui/maintenance-section.ts} (93%) rename packages/plugin/src/{ui/source-control => features/sync/ui}/modals.ts (94%) rename packages/plugin/src/{ui/actions => features/sync/ui}/push-action.ts (90%) rename packages/plugin/src/{ui/modals => features/sync/ui}/reset-modal.ts (96%) rename packages/plugin/src/{ui/common => features/sync/ui}/skipped.ts (87%) rename packages/plugin/src/{ui/actions => features/sync/ui}/sync-actions.ts (90%) rename packages/plugin/src/{plugin => features/sync/ui}/vault-adoption.ts (86%) create mode 100644 packages/plugin/src/features/transfer/index.ts rename packages/plugin/src/{settings => features/transfer}/transfer-controller.ts (92%) rename packages/plugin/src/{settings => features/transfer}/transfer.ts (99%) rename packages/plugin/src/{settings/sections/device-transfer.ts => features/transfer/ui/device-transfer-section.ts} (83%) rename packages/plugin/src/{ui/modals => features/transfer/ui}/settings-transfer-export-modal.ts (98%) rename packages/plugin/src/{ui/modals => features/transfer/ui}/settings-transfer-modal.ts (93%) rename packages/plugin/src/{styles/settings => features/transfer/ui}/transfer.css (100%) delete mode 100644 packages/plugin/src/hub/index.ts delete mode 100644 packages/plugin/src/links/index.ts delete mode 100644 packages/plugin/src/live/index.ts delete mode 100644 packages/plugin/src/live/session/index.ts delete mode 100644 packages/plugin/src/presence/index.ts delete mode 100644 packages/plugin/src/settings/sections/index.ts delete mode 100644 packages/plugin/src/shared/index.ts delete mode 100644 packages/plugin/src/spaces/index.ts delete mode 100644 packages/plugin/src/storage/index.ts create mode 100644 packages/plugin/src/styles.css delete mode 100644 packages/plugin/src/styles/index.css delete mode 100644 packages/plugin/src/sync/history/index.ts delete mode 100644 packages/plugin/src/sync/operations/index.ts delete mode 100644 packages/plugin/src/ui/common/index.ts delete mode 100644 packages/plugin/src/ui/diff/index.ts delete mode 100644 packages/plugin/src/ui/index.ts delete mode 100644 packages/plugin/src/ui/links/index.ts delete mode 100644 packages/plugin/src/ui/modals/index.ts delete mode 100644 packages/plugin/src/ui/source-control/index.ts delete mode 100644 packages/plugin/src/utils/index.ts rename packages/plugin/tests/{settings => app}/envelope.test.ts (94%) rename packages/plugin/tests/{ui => app}/push-result.test.ts (91%) rename packages/plugin/tests/{plugin => app}/realtime.test.ts (83%) rename packages/plugin/tests/{core => app}/session-factory.test.ts (90%) rename packages/plugin/tests/{ui => app}/share-menu.test.ts (91%) create mode 100644 packages/plugin/tests/arch/folders.test.ts rename packages/plugin/tests/{ => core}/cloudflare/api.test.ts (95%) rename packages/plugin/tests/{ => core}/cloudflare/r2.test.ts (96%) rename packages/plugin/tests/{ => core}/cloudflare/relay-account.test.ts (98%) rename packages/plugin/tests/{ => core}/cloudflare/relay-deploy.test.ts (98%) rename packages/plugin/tests/{live => core/crypto}/chaos.test.ts (93%) rename packages/plugin/tests/{ => core}/crypto/device-key.test.ts (95%) rename packages/plugin/tests/{sync => core/crypto}/failed-batch.test.ts (94%) rename packages/plugin/tests/{ => core}/crypto/json-envelope.test.ts (98%) rename packages/plugin/tests/{ => core}/crypto/passphrase-cache.test.ts (98%) rename packages/plugin/tests/{ => core}/crypto/seal.test.ts (90%) rename packages/plugin/tests/{live => core/crypto}/session-reconnect.test.ts (99%) rename packages/plugin/tests/{live => core/crypto}/session-rooms.test.ts (97%) rename packages/plugin/tests/{ => core}/drawing/drawing.test.ts (95%) rename packages/plugin/tests/{ => core}/hub/link.test.ts (99%) rename packages/plugin/tests/{ui => core/hub}/relay.test.ts (95%) rename packages/plugin/tests/{ => core}/hub/status.test.ts (98%) rename packages/plugin/tests/core/{ => logs}/log-service.test.ts (94%) rename packages/plugin/tests/{ => core}/settings/fields.test.ts (95%) rename packages/plugin/tests/{ => core}/settings/model.test.ts (97%) rename packages/plugin/tests/{ => core}/settings/number-field.test.ts (94%) rename packages/plugin/tests/{ => core}/shared/colors.test.ts (84%) rename packages/plugin/tests/{ => core}/shared/errors.test.ts (87%) rename packages/plugin/tests/{ => core}/shared/format.test.ts (98%) rename packages/plugin/tests/{ => core}/shared/offline.test.ts (95%) rename packages/plugin/tests/{ => core}/shared/path.test.ts (98%) rename packages/plugin/tests/{ => core}/ui/attempt.test.ts (93%) rename packages/plugin/tests/{ => core}/utils/base64.test.ts (96%) rename packages/plugin/tests/{ => core}/utils/compress.test.ts (86%) rename packages/plugin/tests/{ => core}/utils/concurrency.test.ts (96%) rename packages/plugin/tests/{ => core}/utils/eol.test.ts (85%) rename packages/plugin/tests/{ => core}/utils/file-concurrency.test.ts (97%) rename packages/plugin/tests/{ => core}/utils/revision.test.ts (89%) rename packages/plugin/tests/{ => core}/utils/search.test.ts (92%) rename packages/plugin/tests/{ => core}/vault/atomic-write.test.ts (97%) rename packages/plugin/tests/{ => core}/vault/io.test.ts (98%) rename packages/plugin/tests/{ => core}/vault/symlinks.test.ts (98%) rename packages/plugin/tests/{ui => features/diff}/choices.test.ts (96%) rename packages/plugin/tests/{ui => features/diff}/diff-chrome.test.ts (96%) rename packages/plugin/tests/{ui => features/diff}/diff-operations.test.ts (88%) rename packages/plugin/tests/{ui => features/diff}/diff-view-status.test.ts (83%) rename packages/plugin/tests/{ui => features/diff}/history-state.test.ts (97%) rename packages/plugin/tests/{ui => features/diff/lines}/code-lines.test.ts (94%) rename packages/plugin/tests/{ui => features/diff/lines}/gap-widgets.test.ts (89%) rename packages/plugin/tests/{ui => features/diff/lines}/scroll-sync.test.ts (96%) rename packages/plugin/tests/{ui => features/diff/merge}/merge-actions.test.ts (93%) rename packages/plugin/tests/{ui => features/diff/merge}/merge-cards.test.ts (80%) rename packages/plugin/tests/{ui => features/diff/merge}/merge-state.test.ts (98%) rename packages/plugin/tests/{editor/signs => features/editor-signs}/integration.test.ts (92%) rename packages/plugin/tests/{editor => features/editor-signs/popup}/popup-dismiss.test.ts (92%) rename packages/plugin/tests/{editor/signs => features/editor-signs}/provider.test.ts (90%) rename packages/plugin/tests/{editor => features/editor-signs}/signs.test.ts (96%) rename packages/plugin/tests/{ui => features/explorer}/file-explorer-decorations.test.ts (95%) rename packages/plugin/tests/{ui => features/explorer}/file-explorer-indicators.test.ts (91%) rename packages/plugin/tests/{ui => features/explorer}/file-explorer-marks.test.ts (95%) rename packages/plugin/tests/{ui => features/explorer}/link-scan.test.ts (90%) rename packages/plugin/tests/{ui => features/explorer}/row-decorator.test.ts (94%) rename packages/plugin/tests/{ => features}/links/describe.test.ts (98%) rename packages/plugin/tests/{ => features}/links/errors.test.ts (87%) rename packages/plugin/tests/{storage => features/links}/link-broker.test.ts (97%) rename packages/plugin/tests/{ => features}/links/publish.test.ts (95%) rename packages/plugin/tests/{ => features}/links/record.test.ts (99%) rename packages/plugin/tests/{ => features}/links/remote.test.ts (95%) rename packages/plugin/tests/{ => features}/links/shared-links.test.ts (97%) rename packages/plugin/tests/{links => features/links/snapshot}/fixtures/rendered-note.html (100%) rename packages/plugin/tests/{links => features/links/snapshot}/images.test.ts (98%) rename packages/plugin/tests/{links => features/links/snapshot}/math.test.ts (97%) rename packages/plugin/tests/{links => features/links/snapshot}/sanitize.test.ts (99%) rename packages/plugin/tests/{ => features/links}/ui/link-actions.test.ts (85%) rename packages/plugin/tests/{ => features/links}/ui/link-menu.test.ts (94%) rename packages/plugin/tests/{ => features/links}/ui/manage-links-modal.test.ts (88%) rename packages/plugin/tests/{ => features/links}/ui/note-link-action.test.ts (92%) rename packages/plugin/tests/{ => features/links}/ui/preview-frame.test.ts (89%) rename packages/plugin/tests/{ => features}/live/authors.test.ts (93%) rename packages/plugin/tests/{live => features/live/cold}/agreed-texts.test.ts (98%) rename packages/plugin/tests/{ => features}/live/doc-id.test.ts (91%) rename packages/plugin/tests/{ => features}/live/doc-types.test.ts (94%) rename packages/plugin/tests/{live => features/live/drawing}/drawing-binding-live.test.ts (87%) rename packages/plugin/tests/{live => features/live/drawing}/drawing-binding.test.ts (97%) rename packages/plugin/tests/{live => features/live/drawing}/drawing-model.test.ts (96%) rename packages/plugin/tests/{plugin => features/live}/live-base.test.ts (94%) rename packages/plugin/tests/{live => features/live/session}/follower.test.ts (91%) rename packages/plugin/tests/{live => features/live/session}/outbox.test.ts (98%) rename packages/plugin/tests/{live => features/live/session}/room-awareness.test.ts (96%) rename packages/plugin/tests/{live => features/live/session}/session-staged.test.ts (96%) rename packages/plugin/tests/{live => features/live/session}/session.test.ts (97%) rename packages/plugin/tests/{live => features/live/text}/binding-cleanup.test.ts (95%) rename packages/plugin/tests/{live => features/live/text}/cursors.test.ts (96%) rename packages/plugin/tests/{live => features/live/text}/rebuild.test.ts (94%) rename packages/plugin/tests/{live => features/live/text}/remote-selections.test.ts (97%) rename packages/plugin/tests/{live => features/live/text}/scroll-marks.test.ts (97%) rename packages/plugin/tests/{live => features/live/text}/text.test.ts (97%) rename packages/plugin/tests/{ => features/live}/ui/deleted-elsewhere.test.ts (86%) rename packages/plugin/tests/{live => features/live/workspace}/editors.test.ts (85%) rename packages/plugin/tests/{live => features/live/workspace}/rename.test.ts (94%) rename packages/plugin/tests/{live => features/live/workspace}/sessions.test.ts (96%) rename packages/plugin/tests/{ui => features/note-header}/live-actions.test.ts (84%) rename packages/plugin/tests/{ui => features/note-header}/live-status.test.ts (91%) rename packages/plugin/tests/{ui => features/note-header}/note-menu-items.test.ts (95%) rename packages/plugin/tests/{ui => features/presence/follow}/cursor-follow.test.ts (91%) rename packages/plugin/tests/{ui => features/presence/follow}/follow-scroll.test.ts (87%) rename packages/plugin/tests/{ => features}/presence/here.test.ts (97%) rename packages/plugin/tests/{ => features}/presence/people-views.test.ts (96%) rename packages/plugin/tests/{ => features}/presence/people.test.ts (98%) rename packages/plugin/tests/{ => features}/presence/unseen.test.ts (95%) rename packages/plugin/tests/{ => features}/presence/views.test.ts (97%) rename packages/plugin/tests/{hub => features/relay}/connection.test.ts (96%) rename packages/plugin/tests/{cloudflare => features/relay/deploy}/migrations.test.ts (93%) rename packages/plugin/tests/{settings/setup => features/relay/deploy}/relay.test.ts (96%) rename packages/plugin/tests/{settings => features/relay/ui}/relay-section.test.ts (90%) rename packages/plugin/tests/{plugin => features/relay/update}/relay-update.test.ts (85%) rename packages/plugin/tests/{ => features}/settings/logs-view.test.ts (83%) rename packages/plugin/tests/{settings => features/settings/sections}/security-section.test.ts (90%) rename packages/plugin/tests/{settings => features}/setup/passphrase-meter.test.ts (90%) rename packages/plugin/tests/{settings => features}/setup/run-action.test.ts (96%) rename packages/plugin/tests/{settings/setup/steps.test.ts => features/setup/step-state.test.ts} (93%) rename packages/plugin/tests/{settings => features}/setup/stepper.test.ts (94%) rename packages/plugin/tests/{settings/setup => features/setup/steps}/relay-step.test.ts (90%) rename packages/plugin/tests/{ui => features/source-control/changes}/conflict-preview-manager.test.ts (92%) rename packages/plugin/tests/{ui => features/source-control/changes}/diff-identity.test.ts (94%) rename packages/plugin/tests/{ui => features/source-control/changes}/row-formatter.test.ts (94%) rename packages/plugin/tests/{ui => features/source-control/changes}/tree-flatten.test.ts (95%) rename packages/plugin/tests/{ui => features/source-control/history}/day-groups.test.ts (96%) rename packages/plugin/tests/{ui => features/source-control/history}/history-list.test.ts (94%) rename packages/plugin/tests/{ui => features/source-control/history}/history-rows.test.ts (94%) rename packages/plugin/tests/{ui => features/source-control/history}/row-pager.test.ts (93%) rename packages/plugin/tests/{ui => features/source-control/timeline}/timeline-actions.test.ts (87%) rename packages/plugin/tests/{ui => features/source-control/timeline}/timeline-rows.test.ts (98%) rename packages/plugin/tests/{ui => features/source-control/trash}/trash-rows.test.ts (96%) rename packages/plugin/tests/{storage => features/spaces/broker}/share-broker.test.ts (99%) rename packages/plugin/tests/{storage => features/spaces/broker}/share-signed-urls.test.ts (98%) rename packages/plugin/tests/{ => features}/spaces/invite.test.ts (93%) rename packages/plugin/tests/{ => features}/spaces/owner.test.ts (91%) rename packages/plugin/tests/{ => features}/spaces/records-partition.test.ts (92%) rename packages/plugin/tests/{ => features}/spaces/records.test.ts (98%) rename packages/plugin/tests/{ => features}/spaces/remote.test.ts (95%) rename packages/plugin/tests/{plugin => features/spaces}/share-moves.test.ts (96%) rename packages/plugin/tests/{plugin => features/spaces}/share-registration.test.ts (90%) rename packages/plugin/tests/{plugin => features/spaces}/space-access.test.ts (87%) rename packages/plugin/tests/{ => features/spaces}/ui/access-ended.test.ts (91%) rename packages/plugin/tests/{ui => features/spaces/ui/invites}/invite-action.test.ts (78%) rename packages/plugin/tests/{editor => features/spaces/ui}/read-only.test.ts (96%) rename packages/plugin/tests/{ => features/spaces}/ui/share-action.test.ts (82%) rename packages/plugin/tests/{settings => features/spaces/ui}/shares-section.test.ts (87%) rename packages/plugin/tests/{ui => features/spaces/ui/window}/share-people.test.ts (91%) rename packages/plugin/tests/{ui => features/spaces/ui/window}/share-summary.test.ts (92%) rename packages/plugin/tests/{storage => features/storage/backends}/google-drive-adapter.test.ts (98%) rename packages/plugin/tests/{storage => features/storage/backends}/google-drive-auth.test.ts (97%) rename packages/plugin/tests/{storage => features/storage/backends}/s3-adapter.test.ts (98%) rename packages/plugin/tests/{storage => features/storage/backends}/s3-signer.test.ts (97%) rename packages/plugin/tests/{storage => features/storage/backends}/s3-xml.test.ts (98%) rename packages/plugin/tests/{storage => features/storage/backends}/util.test.ts (98%) rename packages/plugin/tests/{storage => features/storage/backends}/webdav-adapter.test.ts (96%) rename packages/plugin/tests/{settings => features/storage/cloudflare}/cloudflare-login.test.ts (83%) rename packages/plugin/tests/{settings/r2.test.ts => features/storage/cloudflare/r2-select.test.ts} (95%) rename packages/plugin/tests/{ => features}/storage/records.test.ts (88%) rename packages/plugin/tests/{plugin => features/storage}/storage-refused.test.ts (79%) rename packages/plugin/tests/{settings => features/storage/ui}/connection-test.test.ts (98%) rename packages/plugin/tests/{settings => features/storage/ui}/storage-fields.test.ts (90%) rename packages/plugin/tests/{sync => features/sync/apply}/auto-merge.test.ts (95%) rename packages/plugin/tests/{sync => features/sync/apply}/pull-hint.test.ts (94%) rename packages/plugin/tests/{ => features}/sync/auto-cycle.test.ts (93%) rename packages/plugin/tests/{sync => features/sync/automation}/auto-push.test.ts (94%) rename packages/plugin/tests/{sync => features/sync/automation}/scheduler-interval.test.ts (98%) rename packages/plugin/tests/{sync => features/sync/automation}/scheduler-queued-push.test.ts (96%) rename packages/plugin/tests/{sync => features/sync/automation}/scheduler-startup.test.ts (94%) rename packages/plugin/tests/{ => features}/sync/cancel.test.ts (96%) rename packages/plugin/tests/{ => features}/sync/category-reset-roundtrip.test.ts (94%) rename packages/plugin/tests/{sync => features/sync/changes}/content-cache.test.ts (97%) rename packages/plugin/tests/{sync => features/sync/changes}/content-text.test.ts (89%) rename packages/plugin/tests/{sync => features/sync/changes}/diff.test.ts (98%) rename packages/plugin/tests/{ => features}/sync/chaos.test.ts (96%) rename packages/plugin/tests/{ => features}/sync/controller-unload.test.ts (93%) rename packages/plugin/tests/{ => features}/sync/device-scope-roundtrip.test.ts (96%) rename packages/plugin/tests/{ => features}/sync/engine-roundtrip.test.ts (93%) rename packages/plugin/tests/{ => features}/sync/file-diff-index.test.ts (95%) rename packages/plugin/tests/{sync => features/sync/history}/history-deleted.test.ts (97%) rename packages/plugin/tests/{sync => features/sync/history}/history-gc.test.ts (97%) rename packages/plugin/tests/{sync => features/sync/history}/history-log.test.ts (96%) rename packages/plugin/tests/{sync => features/sync/history}/history-read-cache.test.ts (88%) rename packages/plugin/tests/{sync => features/sync/history}/restore-vault.test.ts (97%) rename packages/plugin/tests/{sync => features/sync/hunks}/anchored-hunks.test.ts (93%) rename packages/plugin/tests/{sync => features/sync/hunks}/conflict-merge.test.ts (76%) rename packages/plugin/tests/{sync => features/sync/hunks}/diff-cache.test.ts (95%) rename packages/plugin/tests/{sync => features/sync/hunks}/hunks-apply.test.ts (99%) rename packages/plugin/tests/{sync => features/sync/hunks}/hunks.test.ts (98%) rename packages/plugin/tests/{sync => features/sync/hunks}/merge-model.test.ts (99%) rename packages/plugin/tests/{sync => features/sync/hunks}/operations-hunks.test.ts (96%) rename packages/plugin/tests/{sync => features/sync/hunks}/projection-absent.test.ts (96%) rename packages/plugin/tests/{sync => features/sync/hunks}/projection-binary.test.ts (89%) rename packages/plugin/tests/{sync => features/sync/hunks}/projection-lazy.test.ts (95%) rename packages/plugin/tests/{sync => features/sync/identity}/authors.test.ts (91%) rename packages/plugin/tests/{core => features/sync/identity}/device-name.test.ts (85%) rename packages/plugin/tests/{sync => features/sync/identity}/manifest-device.test.ts (84%) rename packages/plugin/tests/{ => features}/sync/live-notes.test.ts (95%) rename packages/plugin/tests/{ => features}/sync/moves.test.ts (97%) rename packages/plugin/tests/{sync => features/sync/operations}/drawings.test.ts (88%) rename packages/plugin/tests/{sync => features/sync/operations}/empty-folders.test.ts (92%) rename packages/plugin/tests/{sync => features/sync/operations}/live-operations.test.ts (91%) rename packages/plugin/tests/{sync => features/sync/operations}/lost-push.test.ts (88%) rename packages/plugin/tests/{sync => features/sync/operations}/operations-batch.test.ts (97%) rename packages/plugin/tests/{sync => features/sync/operations}/pull-size-limit.test.ts (86%) rename packages/plugin/tests/{sync => features/sync/operations}/remote-names.test.ts (96%) rename packages/plugin/tests/{ => features}/sync/push-hunks.test.ts (93%) rename packages/plugin/tests/{sync => features/sync/recovery}/cut-short-baseline.test.ts (91%) rename packages/plugin/tests/{sync => features/sync/recovery}/cut-short.test.ts (96%) rename packages/plugin/tests/{core => features/sync/recovery}/state-persister.test.ts (98%) rename packages/plugin/tests/{sync => features/sync/remote}/baseline.test.ts (96%) rename packages/plugin/tests/{sync => features/sync/remote}/config-reset.test.ts (91%) rename packages/plugin/tests/{sync => features/sync/remote}/foreign.test.ts (92%) rename packages/plugin/tests/{sync => features/sync/remote}/keyfile.test.ts (95%) rename packages/plugin/tests/{sync => features/sync/remote}/manifest-guard.test.ts (96%) rename packages/plugin/tests/{sync => features/sync/remote}/manifest-revalidate.test.ts (94%) rename packages/plugin/tests/{core => features/sync/remote}/passphrase-manager.test.ts (93%) rename packages/plugin/tests/{core => features/sync/remote}/passphrase-storage.test.ts (69%) rename packages/plugin/tests/{sync => features/sync/remote}/record-order.test.ts (85%) rename packages/plugin/tests/{sync => features/sync/remote}/reset.test.ts (90%) rename packages/plugin/tests/{sync => features/sync/remote}/space-paths.test.ts (92%) rename packages/plugin/tests/{sync => features/sync/remote}/space-roundtrip.test.ts (88%) rename packages/plugin/tests/{sync => features/sync/remote}/spaces.test.ts (97%) rename packages/plugin/tests/{sync => features/sync/runtime}/history-service-scope.test.ts (91%) rename packages/plugin/tests/{sync => features/sync/runtime}/maintenance.test.ts (91%) rename packages/plugin/tests/{sync => features/sync/runtime}/operation-runner.test.ts (95%) rename packages/plugin/tests/{sync => features/sync/runtime}/refresh-queue.test.ts (91%) rename packages/plugin/tests/{sync => features/sync/runtime}/saved-refresh.test.ts (93%) rename packages/plugin/tests/{sync => features/sync/runtime}/scan-cycle.test.ts (90%) rename packages/plugin/tests/{settings => features/sync/scope}/ignore-rules.test.ts (94%) rename packages/plugin/tests/{plugin => features/sync/scope}/ignore-state.test.ts (96%) rename packages/plugin/tests/{vault => features/sync/scope}/ignore.test.ts (96%) rename packages/plugin/tests/{vault => features/sync/scope}/scanner-index.test.ts (98%) rename packages/plugin/tests/{vault => features/sync/scope}/scanner-memory.test.ts (86%) rename packages/plugin/tests/{vault => features/sync/scope}/scanner-scope.test.ts (96%) rename packages/plugin/tests/{vault => features/sync/scope}/scanner-spaces.test.ts (93%) rename packages/plugin/tests/{vault => features/sync/scope}/scope-spaces.test.ts (96%) rename packages/plugin/tests/{vault => features/sync/scope}/scope.test.ts (94%) rename packages/plugin/tests/{ => features}/sync/session-state.test.ts (95%) rename packages/plugin/tests/{ui => features/sync}/skipped.test.ts (86%) rename packages/plugin/tests/{ => features}/sync/transfer-memory.test.ts (92%) rename packages/plugin/tests/{ => features/sync}/ui/ignore-action.test.ts (97%) rename packages/plugin/tests/{ => features/sync}/ui/push-action.test.ts (93%) rename packages/plugin/tests/{ => features}/sync/upload-listing.test.ts (89%) rename packages/plugin/tests/{settings => features/transfer}/transfer-controller.test.ts (90%) rename packages/plugin/tests/{settings => features/transfer}/transfer.test.ts (97%) rename packages/plugin/tests/{settings/setup => helpers}/element-methods.ts (100%) create mode 100644 packages/protocol/README.md create mode 100644 packages/relay/README.md create mode 100644 packages/viewer/README.md create mode 100644 tests/e2e/README.md 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..b9d7aec9 --- /dev/null +++ b/.claude/rules/history.md @@ -0,0 +1,51 @@ +--- +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/restore-modal.ts' + - 'packages/plugin/src/features/sync/runtime/maintenance*.ts' +--- + +# File history, restore and GC + +History is a change log, not an archive. 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`. + +## Change log + +- `history.json.enc` holds one record per push: the diff from that snapshot's parent, which is `compareResult.remote`, not `state.baseline` (they differ whenever another device pushed since the last compare). `publishManifestWithHistory` passes the remote as `parent`. +- 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 lost update leaves a detectable gap, not a corrupted chain. +- Walk the chain only while `entry.parentId === next.id` (`contiguousLength`), starting at HEAD (`walkableChain`); past a gap the log is not evidence of anything. Order by log position, never `createdAt` (clock skew). +- History is best-effort: a failed log update warns and never fails the push, and GC runs only for the guard's winner. A log that is there but unreadable, malformed or newer is an error, never read as empty (a fresh log would overwrite the real one and orphan its blobs): `readHistoryLog` asks twice before returning empty. +- Log writes go through `updateHistoryLog` (read, mutate, write, read back, redo once if the change did not survive): the manifest guard does not serialize them. Callers act on what it returns. +- Queue anything that rewrites the log on the operation queue (`setSnapshotPinned` does): a push or GC of this device rewrites it too. + +## Listings + +- `listDeletedFiles` walks deletions, never absences: `changes[snapshot].deleted` newest first, 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; those rows are `source: "pinned"` and say "last seen", never "deleted": a pin proves the file existed, not when it went. A pin clears the eviction `rank` only of the hash it holds. +- A log that lags HEAD sets `lagging` (and a gap `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. +- A snapshot is `restorable` only when replay reaches it from HEAD (`replayTo`) or it is pinned. `replayTo` returns null on any gap: 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 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`). +- Restore dialogs promise "nothing is pushed until you say so" (`features/diff/restore-modal.ts`); keep that true. + +## Pins + +- Write the pin manifest under `pins/` before setting the flag (`setSnapshotPinned`): a flag without its manifest makes GC believe objects are protected that nothing references. A pin whose manifest cannot be read is replaced, never trusted. +- Unpinning removes the flag first; a leftover manifest is inert (GC reads only flagged pins; deep clean removes it). No rollback on failure. +- A pin keeps its own full manifest so it outlives the chain once the snapshots between HEAD and the pin are evicted. + +## GC and deep clean + +- Never delete an object reachable from HEAD, from a retained change record (every version it names: `changeEntries`), or from a pinned snapshot's manifest. If any of those cannot be read, delete no objects at all (`skippedObjectSweep` in `collectGarbage`; 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: `settledKeys` / `keysByAge` list them by age, `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). +- Evict a record only when it is past the limit, unpinned and at least `SETTLED_AFTER_MS` old (`evictable`); a record naming a blob still settling stays, or nothing would name that blob again. GC fires only past `gcExcessBuffer` (amortized). +- Order in `collectGarbage`: list ages, prune the log, re-read HEAD late, then sweep. Prune before sweeping: a crash between leaves orphan blobs deep clean collects, never log versions whose content is gone. An unreadable or moved HEAD, an unreadable kept record, or a snapshot pinned meanwhile (`pinnedAmong` checks storage, not just the log) withholds the sweep. +- Deep clean (`deepCleanOrphans` in `features/sync/runtime/maintenance.ts`) needs a published HEAD and a complete live set, deletes nothing written in the last day, and bails if HEAD or the pinned set changed while it listed (a pin does not move HEAD). +- GC, verify and deep clean list only `objects/` and `pins/` of their own space. diff --git a/.claude/rules/hunks.md b/.claude/rules/hunks.md new file mode 100644 index 00000000..f0c8c4e6 --- /dev/null +++ b/.claude/rules/hunks.md @@ -0,0 +1,38 @@ +--- +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. + +## 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/helpers.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..0a36b1c4 --- /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. diff --git a/.claude/rules/realtime.md b/.claude/rules/realtime.md new file mode 100644 index 00000000..7f35443a --- /dev/null +++ b/.claude/rules/realtime.md @@ -0,0 +1,61 @@ +--- +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`; the content key is not extractable). +- 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). +- Relay state is one answer: `HubConnection.statusOf` -> `relayStatus` (`core/hub/status.ts`). A display never derives its own. + +## 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..1f568519 --- /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 and tests. +- 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..1df7824f --- /dev/null +++ b/.claude/rules/security.md @@ -0,0 +1,55 @@ +--- +paths: + - 'packages/plugin/src/core/crypto/**' + - 'packages/plugin/src/app/settings-envelope.ts' + - '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 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. + +## 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..8cfa6041 --- /dev/null +++ b/.claude/rules/settings-setup.md @@ -0,0 +1,53 @@ +--- +paths: + - 'packages/plugin/src/features/{settings,setup,transfer,relay}/**' + - 'packages/plugin/src/core/settings/**' + - 'packages/plugin/src/app/settings-envelope.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. +- `reset-remote-storage` stays confirmation-gated (`confirmRemoteReset`, `features/sync/ui/reset-modal.ts`). It deletes `manifest.json.enc`, `objects/`, `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. + +## Settings + +- Every write goes through `plugin.saveSettings()`; the plugin's saved settings file is sealed by `SettingsEnvelope` (`app/settings-envelope.ts`). A new secret field joins its `SEALED` list, or it is stored in the clear. +- Defaults, numeric bounds (`NUMERIC_BOUNDS`) and `mergeSettings` live in `core/settings/model.ts`; a value from a file or token is clamped there. A removed setting goes in `RETIRED_KEYS` (secrets are deleted, not kept). +- Rows are declarative fields (`fieldRow`, `group`, `checkRow`, `renderDefinitions` in `core/settings/fields.ts`). 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`, `sync/scope`, `transfer/ui`, `storage/ui`); `features/settings/sections/` holds only cross-cutting ones, and `features/settings/tab.ts` orders them. +- 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. +- **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 it stamps the current manifest version so older clients refuse the cleared remote. + +## 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. +- 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) 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`, `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`). +- 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..3a362cfb --- /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 `core/settings/model.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/` and `pins/`. +- 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..bd09fc07 --- /dev/null +++ b/.claude/rules/structure.md @@ -0,0 +1,59 @@ +--- +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, onunload, `saveSettings`, `scheduleScopeRefresh`). `styles.css` - the cascade order of every stylesheet. +- `app/` - composition root: the host container (`app/host.ts`), bootstrap, commands, events, protocol handlers, realtime coordinator, session factory, settings envelope, views. Only `app/` and `main.ts` call a feature's `register*()`. +- `core/` - infra that knows no feature: `cloudflare crypto drawing hub logs settings shared ui utils vault`, plus `core/constants.ts`. 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`. +- Domain order is not enforced by `pnpm arch` (`no-circular` is): import downward. Upward edges that exist are debt, never add one: `storage` -> `sync` (manifest key, `VAULT_SPACE`), `live` and `presence` -> `relay` types, `live` -> `spaces` type. + +## 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. +- `*.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. +- Deep imports into another slice (mostly `features/sync/**`) are baselined debt. New code adds none: export what is needed from the facade. +- esbuild emits CJS: a facade must not create a runtime cycle. `import type` edges are ignored by the cycle rule. +- Modules still take `PluginHost` (`app/host.ts`) and `core/settings/model.ts` still imports features. These are baselined, being removed. New code declares the narrow members it needs as its own interface (`SpaceAccessHost` in `features/spaces/space-access.ts`, `SettingsTransferDeps` in `features/transfer/transfer-controller.ts`); `MdsyncPlugin` satisfies it structurally. Navigation into another surface is a callback in those deps, not an import. +- A per-slice deps file and a per-slice settings module do not exist yet: do not cite or create them as if they did. + +## `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-not-surface`, `surface-`. +- Surface -> surface only: `setup` -> `settings`; `source-control` -> `diff`, `setup`; `status` -> `diff`, `note-header`, `source-control`. `diff`, `editor-signs`, `explorer`, `note-header`, `settings` reach no other surface. +- `packages/plugin/.dependency-cruiser-known-violations.json` is a baseline that only shrinks. Remove a violation, then regenerate: `npx depcruise src --config .dependency-cruiser.cjs --output-type baseline > .dependency-cruiser-known-violations.json` (in `packages/plugin`, file `packages/plugin/.dependency-cruiser-known-violations.json`). A change that adds an entry is wrong; fix the import. +- Remaining baselined groups: `slice-via-facade` (deep imports, mostly into `sync`), `features-not-app` (`PluginHost`), `core-independent` (`core/settings/{model,fields}.ts`, `core/ui/{menu,notices}.ts`, `core/shared/format.ts`), `domain-not-surface` (`features/sync/ui` -> `features/source-control/view.ts`, `features/links/ui` and `features/relay/ui` -> `features/setup/step-state.ts`), one each in `surface-diff`, `surface-setup`. +- 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, `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 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..bc3d9a99 --- /dev/null +++ b/.claude/rules/sync-integrity.md @@ -0,0 +1,69 @@ +--- +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`). +- 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. +- 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; a reset manifest carries `MANIFEST_VERSION` 2 so older clients refuse it (`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. + +## 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. +- 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. +- 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 change record still lists them `deleted`, so history GC sweeps the blobs later; 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: manifest, history log and pin manifests are translated only in `features/sync/remote/space-paths.ts`, called from `features/sync/remote/manifest.ts` and `features/sync/history/store.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/` and `pins/`: 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..84b4d8b5 --- /dev/null +++ b/.claude/rules/testing.md @@ -0,0 +1,43 @@ +--- +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. +- 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..ce474945 --- /dev/null +++ b/.claude/rules/ui.md @@ -0,0 +1,55 @@ +--- +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` (`core/ui/notices.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 | +| 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` | +| wizard-only parts | `choiceCard`, `actionRow`, `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 (`features/explorer/file-explorer-badges.ts`). + +## Style + +- Obsidian variables and tokens first: colors `--color-*`, `--text-*`, `--background-*`; spacing, radii and fonts from Obsidian's scales. A hex is only a fallback inside `var(--color-x, #hex)`, or one fixed on-color text (`features/presence/ui/presence.css`). +- 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. +- 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..68a59e84 --- /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; 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 the narrow members the slice reads as its own interface, structurally satisfied by `MdsyncPlugin`. 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, with no new entry in `packages/plugin/.dependency-cruiser-known-violations.json` 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/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/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..20581eff --- /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 shared by plugin, relay and viewer (hub frames, sealed link format) | +| `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/biome.json b/biome.json index ef294840..ddb8d268 100644 --- a/biome.json +++ b/biome.json @@ -7,7 +7,11 @@ }, "files": { "ignoreUnknown": false, - "includes": ["**", "!**/tests/**/fixtures/**/*.html"] + "includes": [ + "**", + "!**/tests/**/fixtures/**/*.html", + "!**/.dependency-cruiser-known-violations.json" + ] }, "formatter": { "enabled": true, diff --git a/package.json b/package.json index 4637a2e3..2db03497 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "lint": "biome check .", "lint:fix": "biome check --write .", "typecheck": "pnpm -r --if-present run typecheck && tsc -p tests", + "arch": "pnpm --filter mdsync run arch", "version": "node version-bump.mjs", "obsidian": "node tools/obsidian.mjs", "e2e:hub": "jiti tests/e2e/hub.ts", diff --git a/packages/plugin/.dependency-cruiser-known-violations.json b/packages/plugin/.dependency-cruiser-known-violations.json new file mode 100644 index 00000000..b0d9c8a3 --- /dev/null +++ b/packages/plugin/.dependency-cruiser-known-violations.json @@ -0,0 +1,3827 @@ +[ + { + "type": "dependency", + "from": "src/core/settings/fields.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "core-independent" + } + }, + { + "type": "dependency", + "from": "src/core/settings/fields.ts", + "to": "src/features/storage/field-spec.ts", + "unresolvedTo": "@/features/storage/field-spec", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "core-independent" + } + }, + { + "type": "dependency", + "from": "src/core/settings/fields.ts", + "to": "src/features/storage/ui/connection-test.ts", + "unresolvedTo": "@/features/storage/ui/connection-test", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "core-independent" + } + }, + { + "type": "dependency", + "from": "src/core/settings/model.ts", + "to": "src/features/links/record.ts", + "unresolvedTo": "@/features/links/record", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "core-independent" + } + }, + { + "type": "dependency", + "from": "src/core/settings/model.ts", + "to": "src/features/spaces/broker/share-broker.ts", + "unresolvedTo": "@/features/spaces/broker/share-broker", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "core-independent" + } + }, + { + "type": "dependency", + "from": "src/core/settings/model.ts", + "to": "src/features/spaces/record.ts", + "unresolvedTo": "@/features/spaces/record", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "core-independent" + } + }, + { + "type": "dependency", + "from": "src/core/settings/model.ts", + "to": "src/features/storage/backends/s3.ts", + "unresolvedTo": "@/features/storage/backends/s3", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "core-independent" + } + }, + { + "type": "dependency", + "from": "src/core/settings/model.ts", + "to": "src/features/storage/config.ts", + "unresolvedTo": "@/features/storage/config", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "core-independent" + } + }, + { + "type": "dependency", + "from": "src/core/settings/model.ts", + "to": "src/features/storage/field-spec.ts", + "unresolvedTo": "@/features/storage/field-spec", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "core-independent" + } + }, + { + "type": "dependency", + "from": "src/core/settings/model.ts", + "to": "src/features/storage/registry.ts", + "unresolvedTo": "@/features/storage/registry", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "core-independent" + } + }, + { + "type": "dependency", + "from": "src/core/shared/format.ts", + "to": "src/features/sync/types.ts", + "unresolvedTo": "@/features/sync/types", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "core-independent" + } + }, + { + "type": "dependency", + "from": "src/core/ui/menu.ts", + "to": "src/features/presence/ui/avatars.ts", + "unresolvedTo": "@/features/presence/ui/avatars", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "core-independent" + } + }, + { + "type": "dependency", + "from": "src/core/ui/menu.ts", + "to": "src/features/presence/views.ts", + "unresolvedTo": "@/features/presence/views", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "core-independent" + } + }, + { + "type": "dependency", + "from": "src/core/ui/notices.ts", + "to": "src/features/sync/controller.ts", + "unresolvedTo": "@/features/sync/controller", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "core-independent" + } + }, + { + "type": "dependency", + "from": "src/features/links/ui/link-menu.ts", + "to": "src/features/setup/step-state.ts", + "unresolvedTo": "@/features/setup/step-state", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "domain-not-surface" + } + }, + { + "type": "dependency", + "from": "src/features/relay/ui/relay-section.ts", + "to": "src/features/setup/step-state.ts", + "unresolvedTo": "@/features/setup/step-state", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "domain-not-surface" + } + }, + { + "type": "dependency", + "from": "src/features/sync/ui/push-action.ts", + "to": "src/features/source-control/view.ts", + "unresolvedTo": "@/features/source-control/view", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "domain-not-surface" + } + }, + { + "type": "dependency", + "from": "src/features/sync/ui/sync-actions.ts", + "to": "src/features/source-control/view.ts", + "unresolvedTo": "@/features/source-control/view", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "domain-not-surface" + } + }, + { + "type": "dependency", + "from": "src/features/diff/merge/merge-editor.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/diff/operations.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/diff/restore-modal.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/diff/view.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/editor-signs/register.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/explorer/file-context-indicators.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/explorer/file-explorer-badges.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/explorer/file-explorer-decorations.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/explorer/file-explorer-indicators.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/explorer/file-explorer-marks.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/explorer/row-decorator.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/links/note-links.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/links/publish.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/links/register.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/links/ui/link-actions.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/links/ui/link-menu.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/links/ui/manage-links-modal.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/links/ui/note-link-action.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/links/ui/share-link-modal.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/live/ui/deleted-elsewhere.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/note-header/header-state.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/note-header/live-actions.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/note-header/live-status.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/note-header/note-menu.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/note-header/note-presence.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/presence/follow/cursor-follow.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/presence/follow/follows.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/relay/deploy/deploy-flow.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/relay/update/relay-update-modal.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/relay/update/relay-update.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/settings/logs-view.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/settings/overview.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/settings/sections/automation.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/settings/tab.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/setup/step-state.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/setup/wizard.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/actions/actions.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/changes/changes-tab.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/changes/excluded-files.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/history/history-tab.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/setup-prompt.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/summary-card.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/timeline/snapshot-menu.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/timeline/timeline-actions.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/timeline/timeline-tab.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/trash/trash-tab.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/view.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/last-edit.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/share-moves.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/ui/access-ended.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/ui/invites/invite-action.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/ui/read-only.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/ui/share-action.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/ui/space-gone.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/ui/window/share-modal.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/ui/window/share-window.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/status/live-spaces.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/status/relay-status.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/status/status-bar.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/status/status-menu.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/status/where-menu.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/storage/cloudflare/cloudflare-login.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/storage/cloudflare/r2-select.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/storage/storage-refused.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/storage/ui/connection-test.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/storage/ui/storage-fields.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/storage/ui/storage-refused-modal.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/sync/controller.ts", + "to": "src/app/session-factory.ts", + "unresolvedTo": "@/app/session-factory", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/sync/runtime/saved-refresh.ts", + "to": "src/app/session-factory.ts", + "unresolvedTo": "@/app/session-factory", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/sync/scope/ignore-state.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/sync/ui/ignore-action.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/sync/ui/maintenance-actions.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/sync/ui/maintenance-section.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/sync/ui/push-action.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/features/sync/ui/sync-actions.ts", + "to": "src/app/host.ts", + "unresolvedTo": "@/app/host", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "features-not-app" + } + }, + { + "type": "dependency", + "from": "src/core/settings/fields.ts", + "to": "src/features/storage/field-spec.ts", + "unresolvedTo": "@/features/storage/field-spec", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/core/settings/fields.ts", + "to": "src/features/storage/ui/connection-test.ts", + "unresolvedTo": "@/features/storage/ui/connection-test", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/core/settings/model.ts", + "to": "src/features/links/record.ts", + "unresolvedTo": "@/features/links/record", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/core/settings/model.ts", + "to": "src/features/spaces/broker/share-broker.ts", + "unresolvedTo": "@/features/spaces/broker/share-broker", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/core/settings/model.ts", + "to": "src/features/spaces/record.ts", + "unresolvedTo": "@/features/spaces/record", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/core/settings/model.ts", + "to": "src/features/storage/backends/s3.ts", + "unresolvedTo": "@/features/storage/backends/s3", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/core/settings/model.ts", + "to": "src/features/storage/config.ts", + "unresolvedTo": "@/features/storage/config", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/core/settings/model.ts", + "to": "src/features/storage/field-spec.ts", + "unresolvedTo": "@/features/storage/field-spec", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/core/settings/model.ts", + "to": "src/features/storage/registry.ts", + "unresolvedTo": "@/features/storage/registry", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/core/shared/format.ts", + "to": "src/features/sync/types.ts", + "unresolvedTo": "@/features/sync/types", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/core/ui/menu.ts", + "to": "src/features/presence/ui/avatars.ts", + "unresolvedTo": "@/features/presence/ui/avatars", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/core/ui/menu.ts", + "to": "src/features/presence/views.ts", + "unresolvedTo": "@/features/presence/views", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/core/ui/notices.ts", + "to": "src/features/sync/controller.ts", + "unresolvedTo": "@/features/sync/controller", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/action-bar.ts", + "to": "src/features/sync/hunks/projection.ts", + "unresolvedTo": "@/features/sync/hunks/projection", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/choices.ts", + "to": "src/features/sync/hunks/hunks.ts", + "unresolvedTo": "@/features/sync/hunks/hunks", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/choices.ts", + "to": "src/features/sync/hunks/projection.ts", + "unresolvedTo": "@/features/sync/hunks/projection", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/compare/compare-decorations.ts", + "to": "src/features/sync/hunks/hunks.ts", + "unresolvedTo": "@/features/sync/hunks/hunks", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/compare/compare-decorations.ts", + "to": "src/features/sync/hunks/merge-model.ts", + "unresolvedTo": "@/features/sync/hunks/merge-model", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/compare/compare-decorations.ts", + "to": "src/features/sync/hunks/projection.ts", + "unresolvedTo": "@/features/sync/hunks/projection", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/compare/compare-panel.ts", + "to": "src/features/sync/hunks/projection.ts", + "unresolvedTo": "@/features/sync/hunks/projection", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/history-state.ts", + "to": "src/features/sync/constants.ts", + "unresolvedTo": "@/features/sync/constants", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/history-state.ts", + "to": "src/features/sync/hunks/projection.ts", + "unresolvedTo": "@/features/sync/hunks/projection", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/lines/source-widget.ts", + "to": "src/features/sync/hunks/merge-model.ts", + "unresolvedTo": "@/features/sync/hunks/merge-model", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/merge/merge-actions.ts", + "to": "src/features/sync/hunks/merge-model.ts", + "unresolvedTo": "@/features/sync/hunks/merge-model", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/merge/merge-cards.ts", + "to": "src/features/sync/hunks/hunks.ts", + "unresolvedTo": "@/features/sync/hunks/hunks", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/merge/merge-cards.ts", + "to": "src/features/sync/hunks/merge-model.ts", + "unresolvedTo": "@/features/sync/hunks/merge-model", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/merge/merge-controls.ts", + "to": "src/features/sync/hunks/merge-model.ts", + "unresolvedTo": "@/features/sync/hunks/merge-model", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/merge/merge-decorations.ts", + "to": "src/features/sync/hunks/merge-model.ts", + "unresolvedTo": "@/features/sync/hunks/merge-model", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/merge/merge-editor.ts", + "to": "src/features/sync/hunks/merge-model.ts", + "unresolvedTo": "@/features/sync/hunks/merge-model", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/merge/merge-state.ts", + "to": "src/features/sync/hunks/merge-model.ts", + "unresolvedTo": "@/features/sync/hunks/merge-model", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/operations.ts", + "to": "src/features/sync/controller.ts", + "unresolvedTo": "@/features/sync/controller", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/operations.ts", + "to": "src/features/sync/hunks/projection.ts", + "unresolvedTo": "@/features/sync/hunks/projection", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/view.ts", + "to": "src/features/source-control/view.ts", + "unresolvedTo": "@/features/source-control/view", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/view.ts", + "to": "src/features/sync/engine.ts", + "unresolvedTo": "@/features/sync/engine", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/view.ts", + "to": "src/features/sync/hunks/projection.ts", + "unresolvedTo": "@/features/sync/hunks/projection", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/links/link-broker.ts", + "to": "src/features/spaces/broker/share-broker.ts", + "unresolvedTo": "@/features/spaces/broker/share-broker", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/links/ui/link-menu.ts", + "to": "src/features/live/doc-types.ts", + "unresolvedTo": "@/features/live/doc-types", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/links/ui/link-menu.ts", + "to": "src/features/setup/step-state.ts", + "unresolvedTo": "@/features/setup/step-state", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/links/ui/share-link-modal.ts", + "to": "src/features/spaces/invite.ts", + "unresolvedTo": "@/features/spaces/invite", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/live/cold/cold-sync.ts", + "to": "src/features/sync/changes/content.ts", + "unresolvedTo": "@/features/sync/changes/content", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/live/cold/cold-sync.ts", + "to": "src/features/sync/live-notes.ts", + "unresolvedTo": "@/features/sync/live-notes", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/live/cold/cold-sync.ts", + "to": "src/features/sync/types.ts", + "unresolvedTo": "@/features/sync/types", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/live/register.ts", + "to": "src/features/sync/live-notes.ts", + "unresolvedTo": "@/features/sync/live-notes", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/live/register.ts", + "to": "src/features/sync/recovery/journal.ts", + "unresolvedTo": "@/features/sync/recovery/journal", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/live/register.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/live/text/merge.ts", + "to": "src/features/sync/hunks/merge-model.ts", + "unresolvedTo": "@/features/sync/hunks/merge-model", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/live/text/patch.ts", + "to": "src/features/sync/hunks/hunks.ts", + "unresolvedTo": "@/features/sync/hunks/hunks", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/live/ui/deleted-elsewhere.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/live/workspace/rename.ts", + "to": "src/features/sync/changes/content.ts", + "unresolvedTo": "@/features/sync/changes/content", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/live/workspace/rename.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/live/workspace/space.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/presence/follow/follow-scroll.ts", + "to": "src/features/live/session/session.ts", + "unresolvedTo": "@/features/live/session/session", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/presence/follow/follow-scroll.ts", + "to": "src/features/live/text/cursors.ts", + "unresolvedTo": "@/features/live/text/cursors", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/presence/people.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/presence/register.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/relay/channels.ts", + "to": "src/features/spaces/partition.ts", + "unresolvedTo": "@/features/spaces/partition", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/relay/channels.ts", + "to": "src/features/spaces/record.ts", + "unresolvedTo": "@/features/spaces/record", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/relay/channels.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/relay/connection.ts", + "to": "src/features/spaces/partition.ts", + "unresolvedTo": "@/features/spaces/partition", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/relay/connection.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/relay/ui/relay-section.ts", + "to": "src/features/setup/step-state.ts", + "unresolvedTo": "@/features/setup/step-state", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/settings/overview.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/settings/sections/advanced.ts", + "to": "src/features/sync/identity/device.ts", + "unresolvedTo": "@/features/sync/identity/device", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/settings/sections/automation.ts", + "to": "src/features/sync/history/gc.ts", + "unresolvedTo": "@/features/sync/history/gc", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/settings/sections/automation.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/settings/sections/security.ts", + "to": "src/features/sync/remote/keyfile.ts", + "unresolvedTo": "@/features/sync/remote/keyfile", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/settings/tab.ts", + "to": "src/features/links/ui/links-section.ts", + "unresolvedTo": "@/features/links/ui/links-section", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/settings/tab.ts", + "to": "src/features/relay/ui/relay-section.ts", + "unresolvedTo": "@/features/relay/ui/relay-section", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/settings/tab.ts", + "to": "src/features/spaces/ui/shares-section.ts", + "unresolvedTo": "@/features/spaces/ui/shares-section", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/settings/tab.ts", + "to": "src/features/sync/scope/configuration-scope-section.ts", + "unresolvedTo": "@/features/sync/scope/configuration-scope-section", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/settings/tab.ts", + "to": "src/features/sync/scope/exclusions-section.ts", + "unresolvedTo": "@/features/sync/scope/exclusions-section", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/settings/tab.ts", + "to": "src/features/sync/ui/maintenance-section.ts", + "unresolvedTo": "@/features/sync/ui/maintenance-section", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/setup/steps/passphrase-step.ts", + "to": "src/features/sync/remote/keyfile.ts", + "unresolvedTo": "@/features/sync/remote/keyfile", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/setup/steps/ready-step.ts", + "to": "src/features/settings/sections/automation.ts", + "unresolvedTo": "@/features/settings/sections/automation", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/setup/steps/ready-step.ts", + "to": "src/features/source-control/view.ts", + "unresolvedTo": "@/features/source-control/view", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/setup/steps/relay-deploy-view.ts", + "to": "src/features/relay/deploy/deploy-flow.ts", + "unresolvedTo": "@/features/relay/deploy/deploy-flow", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/setup/steps/relay-deploy-view.ts", + "to": "src/features/relay/deploy/relay-account.ts", + "unresolvedTo": "@/features/relay/deploy/relay-account", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/setup/steps/relay-deploy-view.ts", + "to": "src/features/relay/deploy/relay-deploy.ts", + "unresolvedTo": "@/features/relay/deploy/relay-deploy", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/setup/steps/relay-step.ts", + "to": "src/features/relay/deploy/deploy-flow.ts", + "unresolvedTo": "@/features/relay/deploy/deploy-flow", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/setup/steps/relay-step.ts", + "to": "src/features/relay/deploy/relay-account.ts", + "unresolvedTo": "@/features/relay/deploy/relay-account", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/setup/steps/start-step.ts", + "to": "src/features/spaces/ui/invites/invite-action.ts", + "unresolvedTo": "@/features/spaces/ui/invites/invite-action", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/actions/actions.ts", + "to": "src/features/sync/controller.ts", + "unresolvedTo": "@/features/sync/controller", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/actions/actions.ts", + "to": "src/features/sync/scope/ignore.ts", + "unresolvedTo": "@/features/sync/scope/ignore", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/actions/actions.ts", + "to": "src/features/sync/types.ts", + "unresolvedTo": "@/features/sync/types", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/actions/actions.ts", + "to": "src/features/sync/ui/ignore-action.ts", + "unresolvedTo": "@/features/sync/ui/ignore-action", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/actions/actions.ts", + "to": "src/features/sync/ui/modals.ts", + "unresolvedTo": "@/features/sync/ui/modals", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/changes/changes-section.ts", + "to": "src/features/sync/controller.ts", + "unresolvedTo": "@/features/sync/controller", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/changes/changes-tab.ts", + "to": "src/features/spaces/last-edit.ts", + "unresolvedTo": "@/features/spaces/last-edit", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/changes/excluded-files.ts", + "to": "src/features/sync/types.ts", + "unresolvedTo": "@/features/sync/types", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/changes/excluded-files.ts", + "to": "src/features/sync/ui/ignore-action.ts", + "unresolvedTo": "@/features/sync/ui/ignore-action", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/changes/row-formatter.ts", + "to": "src/features/sync/changes/moves.ts", + "unresolvedTo": "@/features/sync/changes/moves", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/changes/row-formatter.ts", + "to": "src/features/sync/identity/device.ts", + "unresolvedTo": "@/features/sync/identity/device", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/changes/row-formatter.ts", + "to": "src/features/sync/types.ts", + "unresolvedTo": "@/features/sync/types", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/changes/row-formatter.ts", + "to": "src/features/sync/ui/change-action.ts", + "unresolvedTo": "@/features/sync/ui/change-action", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/history/history-tab.ts", + "to": "src/features/diff/restore-modal.ts", + "unresolvedTo": "@/features/diff/restore-modal", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/setup-prompt.ts", + "to": "src/features/setup/step-state.ts", + "unresolvedTo": "@/features/setup/step-state", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/summary-card.ts", + "to": "src/features/spaces/ui/space-gone.ts", + "unresolvedTo": "@/features/spaces/ui/space-gone", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/summary-card.ts", + "to": "src/features/sync/controller.ts", + "unresolvedTo": "@/features/sync/controller", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/summary-card.ts", + "to": "src/features/sync/identity/device.ts", + "unresolvedTo": "@/features/sync/identity/device", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/summary-card.ts", + "to": "src/features/sync/runtime/sync-gates.ts", + "unresolvedTo": "@/features/sync/runtime/sync-gates", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/summary-card.ts", + "to": "src/features/sync/types.ts", + "unresolvedTo": "@/features/sync/types", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/timeline/timeline-actions.ts", + "to": "src/features/diff/restore-modal.ts", + "unresolvedTo": "@/features/diff/restore-modal", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/source-control/trash/trash-tab.ts", + "to": "src/features/diff/restore-modal.ts", + "unresolvedTo": "@/features/diff/restore-modal", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/last-edit.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/partition.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/records.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/share-moves.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/space-access.ts", + "to": "src/features/sync/controller.ts", + "unresolvedTo": "@/features/sync/controller", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/space-access.ts", + "to": "src/features/sync/remote/passphrase-manager.ts", + "unresolvedTo": "@/features/sync/remote/passphrase-manager", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/space-access.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/ui/invites/invite-action.ts", + "to": "src/features/sync/ui/push-action.ts", + "unresolvedTo": "@/features/sync/ui/push-action", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/ui/read-only.ts", + "to": "src/features/live/doc-types.ts", + "unresolvedTo": "@/features/live/doc-types", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/ui/read-only.ts", + "to": "src/features/live/drawing/excalidraw.ts", + "unresolvedTo": "@/features/live/drawing/excalidraw", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/ui/share-action.ts", + "to": "src/features/sync/ui/ignore-action.ts", + "unresolvedTo": "@/features/sync/ui/ignore-action", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/ui/share-action.ts", + "to": "src/features/sync/ui/push-action.ts", + "unresolvedTo": "@/features/sync/ui/push-action", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/ui/window/people-list.ts", + "to": "src/features/presence/ui/avatars.ts", + "unresolvedTo": "@/features/presence/ui/avatars", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/ui/window/people-list.ts", + "to": "src/features/presence/views.ts", + "unresolvedTo": "@/features/presence/views", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "type-only", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/ui/window/share-modal.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/spaces/ui/window/share-window.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/storage/cloudflare/r2-select.ts", + "to": "src/features/sync/constants.ts", + "unresolvedTo": "@/features/sync/constants", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/storage/storage-refused.ts", + "to": "src/features/sync/remote/space.ts", + "unresolvedTo": "@/features/sync/remote/space", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/storage/ui/connection-test.ts", + "to": "src/features/sync/constants.ts", + "unresolvedTo": "@/features/sync/constants", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/sync/ui/push-action.ts", + "to": "src/features/source-control/view.ts", + "unresolvedTo": "@/features/source-control/view", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/sync/ui/sync-actions.ts", + "to": "src/features/source-control/view.ts", + "unresolvedTo": "@/features/source-control/view", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "slice-via-facade" + } + }, + { + "type": "dependency", + "from": "src/features/diff/view.ts", + "to": "src/features/source-control/view.ts", + "unresolvedTo": "@/features/source-control/view", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "surface-diff" + } + }, + { + "type": "dependency", + "from": "src/features/setup/steps/ready-step.ts", + "to": "src/features/source-control/view.ts", + "unresolvedTo": "@/features/source-control/view", + "dependencyTypes": [ + "aliased", + "aliased-tsconfig", + "aliased-tsconfig-paths", + "local", + "import" + ], + "rule": { + "severity": "error", + "name": "surface-setup" + } + } +] diff --git a/packages/plugin/.dependency-cruiser.cjs b/packages/plugin/.dependency-cruiser.cjs new file mode 100644 index 00000000..b74446bd --- /dev/null +++ b/packages/plugin/.dependency-cruiser.cjs @@ -0,0 +1,82 @@ +const DOMAIN = "(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", "note-header", "source-control"], +}; +const SLICE = "^src/(features|core)/[^/]+/"; +const FACADE = "^src/(features|core)/[^/]+/index\\.ts$"; + +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/${DOMAIN}/` }, + to: { path: `^src/features/(${Object.keys(SURFACES).join("|")})/` }, + }, + ...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/package.json b/packages/plugin/package.json index a49471b1..775eb7ee 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 --ignore-known .dependency-cruiser-known-violations.json" }, "dependencies": { "@jest/diff-sequences": "^30.5.0", @@ -27,6 +28,7 @@ "@codemirror/commands": "^6.8.1", "@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:*", diff --git a/packages/plugin/src/plugin/bootstrap.ts b/packages/plugin/src/app/bootstrap.ts similarity index 87% rename from packages/plugin/src/plugin/bootstrap.ts rename to packages/plugin/src/app/bootstrap.ts index 17fdbcce..f68b016a 100644 --- a/packages/plugin/src/plugin/bootstrap.ts +++ b/packages/plugin/src/app/bootstrap.ts @@ -1,25 +1,23 @@ import type { App } from "obsidian"; - +import type { DeviceKey } from "@/core/crypto"; +import { LogService } from "@/core/logs"; +import { isStorageConfigured, type MdsyncSettings } from "@/core/settings"; +import { reportWarning } from "@/core/shared"; +import { askPassphrase, notifyError, notifyInfo } from "@/core/ui"; +import type { SharedLinks } from "@/features/links"; +import { createMoveFollower, SpaceRecords } from "@/features/spaces"; +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"; - -import { createMoveFollower } from "./share-moves"; + SyncController, + VAULT_SPACE, + WriteJournal, +} from "@/features/sync"; +import { createSessionOpeners } from "./session-factory"; export interface PluginRuntime { controller: SyncController; diff --git a/packages/plugin/src/commands/index.ts b/packages/plugin/src/app/commands.ts similarity index 92% rename from packages/plugin/src/commands/index.ts rename to packages/plugin/src/app/commands.ts index a6b66eb3..c35bbfbd 100644 --- a/packages/plugin/src/commands/index.ts +++ b/packages/plugin/src/app/commands.ts @@ -1,32 +1,38 @@ 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 { - canRebuild, - deepCleanOrphanedObjects, isLinkable, - notifyInfo, - openDiffView, - openInvite, + noteLinks, + onRelay, openManageLinks, openShareLink, - openShareWindow, + updateSharedLinks, +} from "@/features/links"; +import { + canRebuild, + rebuildLiveNote, + toggleAuthors, +} from "@/features/note-header"; +import { + openDiffView, 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"; export function registerCommands( plugin: Plugin & PluginHost, diff --git a/packages/plugin/src/plugin/events.ts b/packages/plugin/src/app/events.ts similarity index 88% rename from packages/plugin/src/plugin/events.ts rename to packages/plugin/src/app/events.ts index 51f6bbdf..83a9e472 100644 --- a/packages/plugin/src/plugin/events.ts +++ b/packages/plugin/src/app/events.ts @@ -5,17 +5,16 @@ import { TFile, TFolder, } from "obsidian"; -import type { StatePersister } from "@/core"; -import type { PluginHost } from "@/plugin/host"; -import { reportWarning } from "@/shared"; +import { reportWarning } from "@/core/shared"; +import { addLinkMenuItems } from "@/features/links"; import { - addIgnoreMenuItem, - addLinkMenuItems, - addPushMenuItem, - addShareMenuItem, openSourceControlDeleted, openSourceControlHistory, -} from "@/ui"; +} 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"; /** * History is otherwise only in the side panel and a deleted file has no menu, so the entry rides on whatever diff --git a/packages/plugin/src/plugin/host.ts b/packages/plugin/src/app/host.ts similarity index 66% rename from packages/plugin/src/plugin/host.ts rename to packages/plugin/src/app/host.ts index 72a8109c..216f280f 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 diff --git a/packages/plugin/src/plugin/protocols.ts b/packages/plugin/src/app/protocols.ts similarity index 82% rename from packages/plugin/src/plugin/protocols.ts rename to packages/plugin/src/app/protocols.ts index 289a3f2c..55aa1858 100644 --- a/packages/plugin/src/plugin/protocols.ts +++ b/packages/plugin/src/app/protocols.ts @@ -1,10 +1,10 @@ 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 { LINK_PARAM } from "@/core/crypto"; +import { notifyError, notifyInfo } from "@/core/ui"; +import { INVITE_ACTION, openInvite } from "@/features/spaces"; +import { handleStorageProtocol } from "@/features/storage"; +import { TRANSFER_ACTION } from "@/features/transfer"; import type { PluginHost } from "./host"; diff --git a/packages/plugin/src/plugin/realtime.ts b/packages/plugin/src/app/realtime.ts similarity index 85% rename from packages/plugin/src/plugin/realtime.ts rename to packages/plugin/src/app/realtime.ts index 7aa47455..ca14b27b 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 } 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. */ diff --git a/packages/plugin/src/core/session-factory.ts b/packages/plugin/src/app/session-factory.ts similarity index 89% rename from packages/plugin/src/core/session-factory.ts rename to packages/plugin/src/app/session-factory.ts index a618fdf9..89cf5d9d 100644 --- a/packages/plugin/src/core/session-factory.ts +++ b/packages/plugin/src/app/session-factory.ts @@ -1,38 +1,44 @@ import { type App, TFile } from "obsidian"; -import type { EncryptionKey } from "@/crypto"; -import { ESyncLogOperation } from "@/logs/store"; +import type { EncryptionKey } from "@/core/crypto"; +import type { LogService } from "@/core/logs"; +import { ESyncLogOperation } from "@/core/logs"; import { activeStorage, isGuest, 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"; +} from "@/core/settings"; +import { reportWarning } from "@/core/shared"; +import { createSymlinkDetector, createVaultIndex } from "@/core/vault"; +import type { SpaceRecords } from "@/features/spaces"; import { + pauseOf, + shareIdentity, + shareKey, + shareStorage, +} from "@/features/spaces"; +import { createStorageAdapter, type StorageAdapter } from "@/features/storage"; +import type { + EngineDependencies, + LiveNotes, + ManifestAuthor, + PassphraseManager, + StatePersister, + WriteJournal, +} from "@/features/sync"; +import { + clearRemoteTextCache, createIgnoreMatcher, + createScopePolicy, type IgnoreMatcher, ignoreNoteOf, 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, + PassphraseRotatedError, + projectSession, + type Space, + VAULT_SPACE, +} from "@/features/sync"; export interface SessionFactoryDeps { app: App; 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..554b9873 100644 --- a/packages/plugin/src/settings/envelope.ts +++ b/packages/plugin/src/app/settings-envelope.ts @@ -1,8 +1,7 @@ -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, mergeSettings } from "@/core/settings"; +import { base64ToBytes, bytesToBase64 } from "@/core/utils"; /** The secrets, and the share state that means nothing without them: kept or lost as one. */ const SEALED = [ diff --git a/packages/plugin/src/plugin/ui.ts b/packages/plugin/src/app/views.ts similarity index 81% rename from packages/plugin/src/plugin/ui.ts rename to packages/plugin/src/app/views.ts index fa4392c5..1bc1debb 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; 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/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 100% rename from packages/plugin/src/constants.ts rename to packages/plugin/src/core/constants.ts diff --git a/packages/plugin/src/crypto/index.ts b/packages/plugin/src/core/crypto/cipher.ts similarity index 98% rename from packages/plugin/src/crypto/index.ts rename to packages/plugin/src/core/crypto/cipher.ts index 4d28f245..79546439 100644 --- a/packages/plugin/src/crypto/index.ts +++ b/packages/plugin/src/core/crypto/cipher.ts @@ -1,4 +1,10 @@ import { toHex } from "@mdsync/protocol"; +import { + bytesToBase64Url, + deflateBytes, + GZIP, + inflateBytes, +} from "@/core/utils"; import { BLOB_VERSION, BLOB_VERSION_GZIP, @@ -9,8 +15,7 @@ import { 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(); diff --git a/packages/plugin/src/crypto/constants.ts b/packages/plugin/src/core/crypto/constants.ts similarity index 100% rename from packages/plugin/src/crypto/constants.ts rename to packages/plugin/src/core/crypto/constants.ts 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/index.ts b/packages/plugin/src/core/crypto/index.ts new file mode 100644 index 00000000..d2f5daf3 --- /dev/null +++ b/packages/plugin/src/core/crypto/index.ts @@ -0,0 +1,24 @@ +export { + decryptBytes, + decryptJson, + deriveKey, + type EncryptionKey, + encryptBytes, + encryptJson, + importAesKey, + 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/crypto/live-keys.ts b/packages/plugin/src/core/crypto/live-keys.ts similarity index 100% rename from packages/plugin/src/crypto/live-keys.ts rename to packages/plugin/src/core/crypto/live-keys.ts 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/drawing/format.ts b/packages/plugin/src/core/drawing/format.ts similarity index 100% rename from packages/plugin/src/drawing/format.ts rename to packages/plugin/src/core/drawing/format.ts diff --git a/packages/plugin/src/core/drawing/index.ts b/packages/plugin/src/core/drawing/index.ts new file mode 100644 index 00000000..fb6e340d --- /dev/null +++ b/packages/plugin/src/core/drawing/index.ts @@ -0,0 +1,3 @@ +export { 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 96% rename from packages/plugin/src/drawing/scene.ts rename to packages/plugin/src/core/drawing/scene.ts index de609deb..6c4de091 100644 --- a/packages/plugin/src/drawing/scene.ts +++ b/packages/plugin/src/core/drawing/scene.ts @@ -1,4 +1,4 @@ -import { sha256Hex } from "@/crypto"; +import { sha256Hex } from "@/core/crypto"; import { isDrawing, readDrawing, type SceneElement } from "./format"; diff --git a/packages/plugin/src/core/hub/index.ts b/packages/plugin/src/core/hub/index.ts new file mode 100644 index 00000000..9f56e0bb --- /dev/null +++ b/packages/plugin/src/core/hub/index.ts @@ -0,0 +1,16 @@ +export { type HubChannel, HubLink } from "./link"; +export { + openPluginSettings, + RELAY_TEXT, + type RelayFix, + relayFixOf, + relaySummary, + UNREADABLE_TEXT, +} from "./relay-text"; +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 94% rename from packages/plugin/src/ui/common/relay.ts rename to packages/plugin/src/core/hub/relay-text.ts index 9f5a6a06..48d7254f 100644 --- a/packages/plugin/src/ui/common/relay.ts +++ b/packages/plugin/src/core/hub/relay-text.ts @@ -1,8 +1,8 @@ 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 { PLUGIN_ID } from "@/core/constants"; +import { isConnected, type LinkState, type RelayStatus } from "./status"; export const RELAY_TEXT: Record = { off: "Real-time sync is off", 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 97% rename from packages/plugin/src/settings/fields.ts rename to packages/plugin/src/core/settings/fields.ts index f64758e3..9f24176c 100644 --- a/packages/plugin/src/settings/fields.ts +++ b/packages/plugin/src/core/settings/fields.ts @@ -6,10 +6,9 @@ import { type SettingGroupItem, } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import { EFieldKind } from "@/storage"; - -import type { ConnectionTestResult } from "./connection-test"; +import type { PluginHost } from "@/app/host"; +import { EFieldKind } from "@/features/storage/field-spec"; +import type { ConnectionTestResult } from "@/features/storage/ui/connection-test"; import type { MdsyncSettings } from "./model"; export const SUB_SETTING_CLASS = "mdsync-sub-setting"; diff --git a/packages/plugin/src/core/settings/index.ts b/packages/plugin/src/core/settings/index.ts new file mode 100644 index 00000000..76ffca59 --- /dev/null +++ b/packages/plugin/src/core/settings/index.ts @@ -0,0 +1,30 @@ +export { + checkRow, + type FieldContext, + fieldRow, + group, + introRow, + onSettled, + renderDefinitions, + type SettingsField, + type SettingsRow, + SUB_SETTING_CLASS, + settleTyping, +} from "./fields"; +export { + activeStorage, + canSync, + DEFAULT_SETTINGS, + DEFAULT_SETTINGS_SYNC, + isGuest, + isRelayConfigured, + isStorageConfigured, + type MdsyncSettings, + mergeSettings, + NUMERIC_BOUNDS, + ownerStorage, + type RelayConfig, + relayAdmin, + 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 95% rename from packages/plugin/src/settings/model.ts rename to packages/plugin/src/core/settings/model.ts index 6f40c414..99021cc1 100644 --- a/packages/plugin/src/settings/model.ts +++ b/packages/plugin/src/core/settings/model.ts @@ -8,21 +8,23 @@ import { FILE_HISTORY_MAX_SNAPSHOTS, FILE_HISTORY_MIN_SNAPSHOTS, LIVE_SEND_MS, -} from "@/constants"; -import { parseStoredLink, type StoredLink } from "@/links/record"; -import { isCleartextRemote } from "@/shared"; -import { isSpaceRecord, type SpaceRecord } from "@/spaces/record"; +} from "@/core/constants"; +import { isCleartextRemote } from "@/core/shared"; +import { parseStoredLink, type StoredLink } from "@/features/links/record"; +import type { BrokerAdmin } from "@/features/spaces/broker/share-broker"; +import { isSpaceRecord, type SpaceRecord } from "@/features/spaces/record"; +import { defaultS3Config } from "@/features/storage/backends/s3"; import { - type BrokerAdmin, - CONCURRENCY_FIELD, - defaultS3Config, EStorageBackend, + type S3StorageConfig, + type StorageAdapterConfig, +} from "@/features/storage/config"; +import { CONCURRENCY_FIELD } from "@/features/storage/field-spec"; +import { getDescriptor, isAdapterConfigured, isKnownBackend, - type S3StorageConfig, - type StorageAdapterConfig, -} from "@/storage"; +} from "@/features/storage/registry"; const DEFAULT_MAX_FILE_BYTES = 100 * 1024 * 1024; 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 97% rename from packages/plugin/src/shared/format.ts rename to packages/plugin/src/core/shared/format.ts index cc9e46b7..9bf6556d 100644 --- a/packages/plugin/src/shared/format.ts +++ b/packages/plugin/src/core/shared/format.ts @@ -1,4 +1,4 @@ -import type { ManifestEntry } from "@/sync/types"; +import type { ManifestEntry } from "@/features/sync/types"; const BYTES_PER_KB = 1024; const BYTES_PER_MB = 1024 * 1024; diff --git a/packages/plugin/src/core/shared/index.ts b/packages/plugin/src/core/shared/index.ts new file mode 100644 index 00000000..7d5f7043 --- /dev/null +++ b/packages/plugin/src/core/shared/index.ts @@ -0,0 +1,29 @@ +export { personColor, personTint } from "./colors"; +export { reportWarning, setDiagnosticsSink } from "./diagnostics"; +export { asError, errorMessage } from "./errors"; +export { + formatBytes, + formatDayLabel, + formatRelativeTime, + formatTimestamp, + pluralize, + sumBytes, + withDevices, +} from "./format"; +export { + isNetworkError, + isOffline, + OFFLINE_MESSAGE, + userMessage, +} from "./offline"; +export { + folderName, + hasDotSegment, + hasReservedChar, + isCleartextRemote, + normalizeKeyPrefix, + normalizePath, + relayBase, + stripTrailingSlash, +} from "./path"; +export { entryAt, sortedByPath } from "./records"; diff --git a/packages/plugin/src/shared/offline.ts b/packages/plugin/src/core/shared/offline.ts similarity index 100% rename from packages/plugin/src/shared/offline.ts rename to packages/plugin/src/core/shared/offline.ts 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/shared/records.ts b/packages/plugin/src/core/shared/records.ts similarity index 100% rename from packages/plugin/src/shared/records.ts rename to packages/plugin/src/core/shared/records.ts 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..a2269737 --- /dev/null +++ b/packages/plugin/src/core/ui/index.ts @@ -0,0 +1,39 @@ +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, personTitle, 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, +} from "./notices"; +export { openInEditor, 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 86% rename from packages/plugin/src/ui/common/menu.ts rename to packages/plugin/src/core/ui/menu.ts index 8a243220..ca129cdc 100644 --- a/packages/plugin/src/ui/common/menu.ts +++ b/packages/plugin/src/core/ui/menu.ts @@ -1,9 +1,7 @@ import type { Menu } from "obsidian"; - -import type { Person } from "@/presence"; -import { withDevices } from "@/shared"; - -import { renderAvatar } from "./avatars"; +import { withDevices } from "@/core/shared"; +import { renderAvatar } from "@/features/presence/ui/avatars"; +import type { Person } from "@/features/presence/views"; export function infoTitle(text: string, state?: string): DocumentFragment { const title = createFragment(); 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/ui/modals/passphrase-modal.ts b/packages/plugin/src/core/ui/modals/passphrase-modal.ts similarity index 94% rename from packages/plugin/src/ui/modals/passphrase-modal.ts rename to packages/plugin/src/core/ui/modals/passphrase-modal.ts index 458f4d2f..1c955975 100644 --- a/packages/plugin/src/ui/modals/passphrase-modal.ts +++ b/packages/plugin/src/core/ui/modals/passphrase-modal.ts @@ -1,7 +1,9 @@ import { type App, ButtonComponent, Modal, Setting } from "obsidian"; -import { weakPassphrase } from "@/crypto"; -import { alertLine, modalFooter, onEnter, renderModalHead } from "@/ui/common"; +import { weakPassphrase } from "@/core/crypto"; +import { alertLine } from "../controls/alert-line"; +import { onEnter } from "../input/enter-key"; +import { modalFooter, renderModalHead } from "../modal-frame"; import { openPromiseModal } from "./promise-modal"; 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 93% rename from packages/plugin/src/ui/common/notices.ts rename to packages/plugin/src/core/ui/notices.ts index 23ca4529..3aebc468 100644 --- a/packages/plugin/src/ui/common/notices.ts +++ b/packages/plugin/src/core/ui/notices.ts @@ -1,7 +1,7 @@ import { ButtonComponent, Notice } from "obsidian"; -import { errorMessage } from "@/shared"; -import type { SyncOperationResult } from "@/sync/controller"; +import { errorMessage } from "@/core/shared"; +import type { SyncOperationResult } from "@/features/sync/controller"; const NOTICE_DURATION_MS = 8000; diff --git a/packages/plugin/src/ui/common/obsidian-helpers.ts b/packages/plugin/src/core/ui/obsidian-helpers.ts similarity index 100% rename from packages/plugin/src/ui/common/obsidian-helpers.ts rename to packages/plugin/src/core/ui/obsidian-helpers.ts 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 100% rename from packages/plugin/src/styles/modal-frame.css rename to packages/plugin/src/core/ui/styles/modal-frame.css 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 100% rename from packages/plugin/src/styles/tokens.css rename to packages/plugin/src/core/ui/styles/tokens.css diff --git a/packages/plugin/src/utils/base64.ts b/packages/plugin/src/core/utils/base64.ts similarity index 100% rename from packages/plugin/src/utils/base64.ts rename to packages/plugin/src/core/utils/base64.ts 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/utils/file-concurrency.ts b/packages/plugin/src/core/utils/file-concurrency.ts similarity index 100% rename from packages/plugin/src/utils/file-concurrency.ts rename to packages/plugin/src/core/utils/file-concurrency.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..1703756a --- /dev/null +++ b/packages/plugin/src/core/utils/index.ts @@ -0,0 +1,18 @@ +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 { + createLargeFileGate, + LARGE_FILE_BYTES, + runWithFileConcurrency, +} from "./file-concurrency"; +export { isNewer, type Revised } from "./revision"; +export { firstIndex } from "./search"; 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/utils/search.ts b/packages/plugin/src/core/utils/search.ts similarity index 100% rename from packages/plugin/src/utils/search.ts rename to packages/plugin/src/core/utils/search.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/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..6bfde9c1 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/hunks/projection"; 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. */ 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..38b1eac6 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/hunks/hunks"; +import { EDiffDirection } from "@/features/sync/hunks/projection"; 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 92% rename from packages/plugin/src/ui/diff/compare-controls.ts rename to packages/plugin/src/features/diff/compare/compare-controls.ts index 9d07fead..c052fa59 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 type { 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 { renderCounters } from "../lines/source-widget"; +import { renderChangeNav } from "../rail"; const CONTEXT: Record = { local: "since the last sync", diff --git a/packages/plugin/src/ui/diff/compare-decorations.ts b/packages/plugin/src/features/diff/compare/compare-decorations.ts similarity index 92% rename from packages/plugin/src/ui/diff/compare-decorations.ts rename to packages/plugin/src/features/diff/compare/compare-decorations.ts index 6eda3b24..1497a0bc 100644 --- a/packages/plugin/src/ui/diff/compare-decorations.ts +++ b/packages/plugin/src/features/diff/compare/compare-decorations.ts @@ -11,22 +11,30 @@ 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 { hunkSegments, type LineRange } from "@/features/sync/hunks/hunks"; +import type { Span } from "@/features/sync/hunks/merge-model"; +import type { + EDiffDirection, + FileDiffModel, +} from "@/features/sync/hunks/projection"; +import { choiceVerb, type HunkChoices } from "../choices"; +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 { combinedModeField } from "../merge/merge-decorations"; +import type { RailAction } from "../rail"; export type CompareSide = "left" | "right"; diff --git a/packages/plugin/src/ui/diff/compare-panel.ts b/packages/plugin/src/features/diff/compare/compare-panel.ts similarity index 95% rename from packages/plugin/src/ui/diff/compare-panel.ts rename to packages/plugin/src/features/diff/compare/compare-panel.ts index 95d82266..4392f82f 100644 --- a/packages/plugin/src/ui/diff/compare-panel.ts +++ b/packages/plugin/src/features/diff/compare/compare-panel.ts @@ -1,34 +1,41 @@ 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 { CompareControls } from "./compare-controls"; import { - buildSegments, - type CompareSegment, - type CompareSide, - compareState, - 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"; + EDiffDirection, + type FileDiffModel, +} from "@/features/sync/hunks/projection"; +import { choiceActions, type EChoiceKind, HunkChoices } from "../choices"; +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"; +} from "../line-wrapping-control"; +import { ChangeOverlay } from "../lines/change-overlay"; +import { Divider, type DividerItem } from "../lines/divider"; +import { foldedBands } from "../lines/gap-widgets"; +import { + sideSpan, + spanBounds, + updatePaneViewportWidth, +} from "../lines/geometry"; import { NO_ANCHORS, PaneScrollSync, type ScrollAnchors, spanAnchors, -} from "./scroll-sync"; +} from "../lines/scroll-sync"; +import { setCombinedMode } from "../merge/merge-decorations"; +import { changeNavigation, type RailAction } from "../rail"; +import { CompareControls } from "./compare-controls"; +import { + buildSegments, + type CompareSegment, + type CompareSide, + compareState, + segmentKind, + segmentsChanged, +} from "./compare-decorations"; export interface ComparePanelOptions extends LineWrappingOptions { direction: EDiffDirection; 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/preview-panel.ts b/packages/plugin/src/features/diff/compare/preview-panel.ts similarity index 100% rename from packages/plugin/src/ui/diff/preview-panel.ts rename to packages/plugin/src/features/diff/compare/preview-panel.ts 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 99% rename from packages/plugin/src/ui/diff/header.ts rename to packages/plugin/src/features/diff/header.ts index 7e5e4980..58bebf34 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 type { + EDiffDirection, + FileDiffModel, + HistoryVersionRef, +} from "@/features/sync"; import { renderActionBar } from "./action-bar"; import { type FilePosition, getFilePosition } from "./file-navigation"; import { type HistoryChange, hunkHintText } from "./history-state"; diff --git a/packages/plugin/src/ui/diff/history-state.ts b/packages/plugin/src/features/diff/history-state.ts similarity index 97% rename from packages/plugin/src/ui/diff/history-state.ts rename to packages/plugin/src/features/diff/history-state.ts index ba1ea19b..b6c04a2d 100644 --- a/packages/plugin/src/ui/diff/history-state.ts +++ b/packages/plugin/src/features/diff/history-state.ts @@ -1,10 +1,10 @@ -import { HUNK_TEXT_MAX_BYTES } from "@/sync/constants"; +import { HUNK_TEXT_MAX_BYTES } from "@/features/sync/constants"; import { EDiffDirection, type FileDiffModel, type HistoryDiffRequest, type HistoryVersionRef, -} from "@/sync/projection"; +} from "@/features/sync/hunks/projection"; export interface HistoryChange { before: HistoryVersionRef | null; diff --git a/packages/plugin/src/features/diff/index.ts b/packages/plugin/src/features/diff/index.ts new file mode 100644 index 00000000..6d17e1b5 --- /dev/null +++ b/packages/plugin/src/features/diff/index.ts @@ -0,0 +1,3 @@ +export type { HistoryChange } from "./history-state"; +export { confirmBulkRestore, confirmRestore } from "./restore-modal"; +export { 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 93% rename from packages/plugin/src/ui/diff/layout-mode.ts rename to packages/plugin/src/features/diff/layout-mode.ts index 0b7e5e4a..a226adf8 100644 --- a/packages/plugin/src/ui/diff/layout-mode.ts +++ b/packages/plugin/src/features/diff/layout-mode.ts @@ -1,5 +1,5 @@ -import { randomId } from "@/crypto"; -import { renderSegments, type Segments } from "@/ui/common"; +import { randomId } from "@/core/crypto"; +import { renderSegments, type Segments } from "@/core/ui"; const COMBINED_BELOW_PX = 900; 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 96% rename from packages/plugin/src/ui/diff/change-overlay.ts rename to packages/plugin/src/features/diff/lines/change-overlay.ts index db0d43b1..7b1de676 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 { firstIndex } from "@/core/utils"; +import type { + CompareSegment, + CompareSide, +} from "../compare/compare-decorations"; +import { renderRailButton } from "../rail"; import { type Bounds, shiftBounds, sideSpan, spanBounds } from "./geometry"; -import { renderRailButton } from "./rail"; /** A shorter change is cheaper to scroll past than to fold. */ const MIN_FOLD_LINES = 10; 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..7b4e7ce5 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 { firstIndex } from "@/core/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"; /** 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/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..da882112 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 { firstIndex } from "@/core/utils"; +import type { LineRange, Span } from "@/features/sync"; 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 95% rename from packages/plugin/src/ui/diff/geometry.ts rename to packages/plugin/src/features/diff/lines/geometry.ts index a1071d1d..79fc12a1 100644 --- a/packages/plugin/src/ui/diff/geometry.ts +++ b/packages/plugin/src/features/diff/lines/geometry.ts @@ -1,8 +1,7 @@ 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 { firstIndex } from "@/core/utils"; +import type { LineRange, Span } from "@/features/sync"; export interface Bounds { top: number; 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/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..5843aac3 100644 --- a/packages/plugin/src/ui/diff/scroll-sync.ts +++ b/packages/plugin/src/features/diff/lines/scroll-sync.ts @@ -1,6 +1,6 @@ import type { EditorView } from "@codemirror/view"; -import type { Span } from "@/sync/merge-model"; -import { firstIndex } from "@/utils"; +import { firstIndex } from "@/core/utils"; +import type { Span } from "@/features/sync"; import { docBottom, spanBounds } from "./geometry"; /** IntelliJ keeps the line a third of the way down the viewport aligned. */ 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..ab6701dd 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/hunks/merge-model"; +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/ui/diff/merge-actions.ts b/packages/plugin/src/features/diff/merge/merge-actions.ts similarity index 98% rename from packages/plugin/src/ui/diff/merge-actions.ts rename to packages/plugin/src/features/diff/merge/merge-actions.ts index 9005a226..247883b1 100644 --- a/packages/plugin/src/ui/diff/merge-actions.ts +++ b/packages/plugin/src/features/diff/merge/merge-actions.ts @@ -11,7 +11,7 @@ import { revertPlan, type StatusPatch, sameStatus, -} from "@/sync/merge-model"; +} from "@/features/sync/hunks/merge-model"; import { fullTaken, mergeChangesField, setChangeState } from "./merge-state"; export interface MergeActions { diff --git a/packages/plugin/src/ui/diff/merge-cards.ts b/packages/plugin/src/features/diff/merge/merge-cards.ts similarity index 94% rename from packages/plugin/src/ui/diff/merge-cards.ts rename to packages/plugin/src/features/diff/merge/merge-cards.ts index c8428def..83a10e82 100644 --- a/packages/plugin/src/ui/diff/merge-cards.ts +++ b/packages/plugin/src/features/diff/merge/merge-cards.ts @@ -6,22 +6,22 @@ import { type Text, } from "@codemirror/state"; import { Decoration, type DecorationSet } from "@codemirror/view"; -import type { LineRange } from "@/sync/hunks"; +import type { LineRange } from "@/features/sync/hunks/hunks"; 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/hunks/merge-model"; +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 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"; 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 93% rename from packages/plugin/src/ui/diff/merge-controls.ts rename to packages/plugin/src/features/diff/merge/merge-controls.ts index cafff4e1..0b5b1352 100644 --- a/packages/plugin/src/ui/diff/merge-controls.ts +++ b/packages/plugin/src/features/diff/merge/merge-controls.ts @@ -3,11 +3,11 @@ import { type EMergeSide, type MergeChange, snapToLines, -} from "@/sync/merge-model"; -import type { DividerItem } from "./divider"; -import { sideSpan } from "./geometry"; +} from "@/features/sync/hunks/merge-model"; +import type { DividerItem } from "../lines/divider"; +import { sideSpan } from "../lines/geometry"; +import type { RailAction } from "../rail"; import type { MergeActions } from "./merge-actions"; -import type { RailAction } from "./rail"; export type MergeTone = "conflict" | EMergeSide | "base" | "shared"; diff --git a/packages/plugin/src/ui/diff/merge-decorations.ts b/packages/plugin/src/features/diff/merge/merge-decorations.ts similarity index 93% rename from packages/plugin/src/ui/diff/merge-decorations.ts rename to packages/plugin/src/features/diff/merge/merge-decorations.ts index 05ba1ca3..de31569c 100644 --- a/packages/plugin/src/ui/diff/merge-decorations.ts +++ b/packages/plugin/src/features/diff/merge/merge-decorations.ts @@ -6,18 +6,24 @@ import { type Text, } from "@codemirror/state"; import { Decoration, type DecorationSet, EditorView } from "@codemirror/view"; +import { firstIndex } from "@/core/utils"; import { type EMergeSide, 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/hunks/merge-model"; +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 { type SourceBlock, SourceBlockWidget } from "../lines/source-widget"; import type { MergeActions } from "./merge-actions"; import { type CombinedMergeConfig, @@ -28,7 +34,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({ diff --git a/packages/plugin/src/ui/diff/merge-editor.ts b/packages/plugin/src/features/diff/merge/merge-editor.ts similarity index 95% rename from packages/plugin/src/ui/diff/merge-editor.ts rename to packages/plugin/src/features/diff/merge/merge-editor.ts index 3a27fad0..7b5db1c2 100644 --- a/packages/plugin/src/ui/diff/merge-editor.ts +++ b/packages/plugin/src/features/diff/merge/merge-editor.ts @@ -9,8 +9,10 @@ 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 type { PluginHost } from "@/app/host"; +import { randomId } from "@/core/crypto"; +import { notifyError, notifyInfo, runWithNotice } from "@/core/ui"; +import { eolOf } from "@/core/utils"; import { buildMergeSession, countUnresolved, @@ -19,17 +21,26 @@ import { 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/hunks/merge-model"; +import type { PanelHosts } from "../header"; +import { LayoutMode } from "../layout-mode"; import { LineWrappingControl, type LineWrappingOptions, -} from "./line-wrapping-control"; +} from "../line-wrapping-control"; +import { Divider } from "../lines/divider"; +import { + sideSpan, + spanBounds, + updatePaneViewportWidth, +} from "../lines/geometry"; +import { + NO_ANCHORS, + PaneScrollSync, + type ScrollAnchors, + spanAnchors, +} from "../lines/scroll-sync"; +import { changeNavigation } from "../rail"; import { mergeActions } from "./merge-actions"; import { toggleMergeGap } from "./merge-cards"; import { dividerItems } from "./merge-controls"; @@ -42,13 +53,6 @@ import { import { type SideMarks, sideMarks } from "./merge-marks"; import { initialMergeChanges, mergeChangesField } from "./merge-state"; import { MergeToolbar } from "./merge-toolbar"; -import { changeNavigation } from "./rail"; -import { - NO_ANCHORS, - PaneScrollSync, - type ScrollAnchors, - spanAnchors, -} from "./scroll-sync"; export class MergeEditorPanel { private text = ""; 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/ui/diff/merge-state.ts b/packages/plugin/src/features/diff/merge/merge-state.ts similarity index 99% rename from packages/plugin/src/ui/diff/merge-state.ts rename to packages/plugin/src/features/diff/merge/merge-state.ts index f1a23070..3c57b709 100644 --- a/packages/plugin/src/ui/diff/merge-state.ts +++ b/packages/plugin/src/features/diff/merge/merge-state.ts @@ -15,7 +15,7 @@ import { sameStatus, type Taken, type TakenPatch, -} from "@/sync/merge-model"; +} from "@/features/sync/hunks/merge-model"; export interface ChangeStateUpdate { index: number; diff --git a/packages/plugin/src/ui/diff/merge-toolbar.ts b/packages/plugin/src/features/diff/merge/merge-toolbar.ts similarity index 94% rename from packages/plugin/src/ui/diff/merge-toolbar.ts rename to packages/plugin/src/features/diff/merge/merge-toolbar.ts index f57a47cf..55089978 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. */ diff --git a/packages/plugin/src/ui/diff/operations.ts b/packages/plugin/src/features/diff/operations.ts similarity index 93% rename from packages/plugin/src/ui/diff/operations.ts rename to packages/plugin/src/features/diff/operations.ts index 8b757bae..b2c5976a 100644 --- a/packages/plugin/src/ui/diff/operations.ts +++ b/packages/plugin/src/features/diff/operations.ts @@ -1,11 +1,16 @@ -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 type { PluginHost } from "@/app/host"; +import { notifyError, openConfirmModal, runWithNotice } from "@/core/ui"; +import { + EConflictStrategy, + type SyncOperationResult, +} from "@/features/sync/controller"; +import { + EDiffDirection, + type FileDiffModel, +} from "@/features/sync/hunks/projection"; import { EChoiceKind, type HunkChoices } from "./choices"; import type { HistoryChange } from "./history-state"; +import { confirmRestore } from "./restore-modal"; export interface DiffOperationState { path: string | null; diff --git a/packages/plugin/src/ui/diff/rail.ts b/packages/plugin/src/features/diff/rail.ts similarity index 97% rename from packages/plugin/src/ui/diff/rail.ts rename to packages/plugin/src/features/diff/rail.ts index 2aed2248..e0a407c0 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( diff --git a/packages/plugin/src/ui/source-control/restore-modal.ts b/packages/plugin/src/features/diff/restore-modal.ts similarity index 94% rename from packages/plugin/src/ui/source-control/restore-modal.ts rename to packages/plugin/src/features/diff/restore-modal.ts index 571bbe35..fe1495a6 100644 --- a/packages/plugin/src/ui/source-control/restore-modal.ts +++ b/packages/plugin/src/features/diff/restore-modal.ts @@ -1,17 +1,17 @@ import { ButtonComponent, Modal } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import { errorMessage, formatBytes } from "@/shared"; -import type { FileDiffModel, HistoryVersionRef } from "@/sync/projection"; +import type { PluginHost } from "@/app/host"; +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"; export interface RestoreConfirmOptions { plugin: PluginHost; 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/styles/diff/hunk-preview.css b/packages/plugin/src/features/diff/styles/hunk-preview.css similarity index 100% rename from packages/plugin/src/styles/diff/hunk-preview.css rename to packages/plugin/src/features/diff/styles/hunk-preview.css diff --git a/packages/plugin/src/styles/diff/merge.css b/packages/plugin/src/features/diff/styles/merge.css similarity index 100% rename from packages/plugin/src/styles/diff/merge.css rename to packages/plugin/src/features/diff/styles/merge.css diff --git a/packages/plugin/src/styles/diff/pane-grid.css b/packages/plugin/src/features/diff/styles/pane-grid.css similarity index 100% rename from packages/plugin/src/styles/diff/pane-grid.css rename to packages/plugin/src/features/diff/styles/pane-grid.css 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/styles/diff/source-blocks.css b/packages/plugin/src/features/diff/styles/source-blocks.css similarity index 100% rename from packages/plugin/src/styles/diff/source-blocks.css rename to packages/plugin/src/features/diff/styles/source-blocks.css diff --git a/packages/plugin/src/styles/diff/tones.css b/packages/plugin/src/features/diff/styles/tones.css similarity index 100% rename from packages/plugin/src/styles/diff/tones.css rename to packages/plugin/src/features/diff/styles/tones.css diff --git a/packages/plugin/src/styles/diff/toolbars.css b/packages/plugin/src/features/diff/styles/toolbars.css similarity index 100% rename from packages/plugin/src/styles/diff/toolbars.css rename to packages/plugin/src/features/diff/styles/toolbars.css diff --git a/packages/plugin/src/styles/diff/view.css b/packages/plugin/src/features/diff/styles/view.css similarity index 100% rename from packages/plugin/src/styles/diff/view.css rename to packages/plugin/src/features/diff/styles/view.css diff --git a/packages/plugin/src/ui/diff-view.ts b/packages/plugin/src/features/diff/view.ts similarity index 94% rename from packages/plugin/src/ui/diff-view.ts rename to packages/plugin/src/features/diff/view.ts index 77b3accf..1f0bc9c2 100644 --- a/packages/plugin/src/ui/diff-view.ts +++ b/packages/plugin/src/features/diff/view.ts @@ -1,24 +1,25 @@ 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 type { PluginHost } from "@/app/host"; +import { DIFF_VIEW_TYPE, SOURCE_CONTROL_VIEW_TYPE } from "@/core/constants"; +import { userMessage } from "@/core/shared"; +import { notifyError, openConfirmModal, redrawOnPhoneChange } from "@/core/ui"; +import { openSourceControlView } from "@/features/source-control/view"; +import type { CompareResult } from "@/features/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"; +} from "@/features/sync/hunks/projection"; +import { watchDiffChrome } from "./action-bar"; +import { renderBinaryDiff } from "./compare/binary-view"; +import { type ComparePanel, renderTextDiff } from "./compare/compare-panel"; +import { PreviewPanel } from "./compare/preview-panel"; import { getAdjacentPath, getNextConflictPath, getOrderedPaths, -} from "./diff/file-navigation"; -import { refitDiffTitle, renderDiffFrame } from "./diff/header"; +} from "./file-navigation"; +import { refitDiffTitle, renderDiffFrame } from "./header"; import { buildHistoryRequest, changesDiffer, @@ -26,10 +27,9 @@ import { 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"; +} from "./history-state"; +import { MergeEditorPanel } from "./merge/merge-editor"; +import { DiffOperations } from "./operations"; export class DiffView extends ItemView { private readonly plugin: PluginHost; diff --git a/packages/plugin/src/editor/signs/compute.ts b/packages/plugin/src/features/editor-signs/compute.ts similarity index 100% rename from packages/plugin/src/editor/signs/compute.ts rename to packages/plugin/src/features/editor-signs/compute.ts 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 100% rename from packages/plugin/src/editor/signs/focus.ts rename to packages/plugin/src/features/editor-signs/focus.ts diff --git a/packages/plugin/src/editor/signs/gutter.ts b/packages/plugin/src/features/editor-signs/gutter.ts similarity index 99% rename from packages/plugin/src/editor/signs/gutter.ts rename to packages/plugin/src/features/editor-signs/gutter.ts index f0a69004..a4a8bc31 100644 --- a/packages/plugin/src/editor/signs/gutter.ts +++ b/packages/plugin/src/features/editor-signs/gutter.ts @@ -8,7 +8,7 @@ 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 { showHunkPopupAt } from "./popup/hunk-popup"; import type { SignsProvider } from "./provider"; import { type ChangesData, diff --git a/packages/plugin/src/editor/signs/helpers.ts b/packages/plugin/src/features/editor-signs/helpers.ts similarity index 98% rename from packages/plugin/src/editor/signs/helpers.ts rename to packages/plugin/src/features/editor-signs/helpers.ts index 0c33d21b..70b16b63 100644 --- a/packages/plugin/src/editor/signs/helpers.ts +++ b/packages/plugin/src/features/editor-signs/helpers.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 { diff --git a/packages/plugin/src/styles/editor/hunk-popup.css b/packages/plugin/src/features/editor-signs/hunk-popup.css similarity index 100% rename from packages/plugin/src/styles/editor/hunk-popup.css rename to packages/plugin/src/features/editor-signs/hunk-popup.css 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..2f82dbf6 --- /dev/null +++ b/packages/plugin/src/features/editor-signs/index.ts @@ -0,0 +1 @@ +export { registerEditorSigns, type SignsHandle } from "./register"; 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..5f3e34f2 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 "../helpers"; +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 100% rename from packages/plugin/src/editor/signs/popup-placement.ts rename to packages/plugin/src/features/editor-signs/popup/popup-placement.ts 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..661be5ae 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 "../helpers"; +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 95% rename from packages/plugin/src/editor/signs/provider.ts rename to packages/plugin/src/features/editor-signs/provider.ts index 617f2e2f..2a8a4ca3 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 { 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 "./helpers"; -import { dismissPopupIn } from "./hunk-popup"; +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 97% rename from packages/plugin/src/editor/signs/integration.ts rename to packages/plugin/src/features/editor-signs/register.ts index 4dc03946..04e7f93e 100644 --- a/packages/plugin/src/editor/signs/integration.ts +++ b/packages/plugin/src/features/editor-signs/register.ts @@ -2,10 +2,10 @@ import type { Extension } from "@codemirror/state"; import type { Plugin, TAbstractFile } from "obsidian"; import { TFile } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; +import type { PluginHost } from "@/app/host"; import { buildSignsExtensions } from "./extension"; -import { dismissPopup } from "./hunk-popup"; +import { dismissPopup } from "./popup/hunk-popup"; import { SignsProvider } from "./provider"; export interface SignsHandle { diff --git a/packages/plugin/src/styles/editor/signs.css b/packages/plugin/src/features/editor-signs/signs.css similarity index 100% rename from packages/plugin/src/styles/editor/signs.css rename to packages/plugin/src/features/editor-signs/signs.css diff --git a/packages/plugin/src/editor/signs/state.ts b/packages/plugin/src/features/editor-signs/state.ts similarity index 100% rename from packages/plugin/src/editor/signs/state.ts rename to packages/plugin/src/features/editor-signs/state.ts diff --git a/packages/plugin/src/editor/signs/subscriber.ts b/packages/plugin/src/features/editor-signs/subscriber.ts similarity index 100% rename from packages/plugin/src/editor/signs/subscriber.ts rename to packages/plugin/src/features/editor-signs/subscriber.ts diff --git a/packages/plugin/src/styles/explorer.css b/packages/plugin/src/features/explorer/explorer.css similarity index 100% rename from packages/plugin/src/styles/explorer.css rename to packages/plugin/src/features/explorer/explorer.css diff --git a/packages/plugin/src/ui/explorer/file-context-indicators.ts b/packages/plugin/src/features/explorer/file-context-indicators.ts similarity index 96% rename from packages/plugin/src/ui/explorer/file-context-indicators.ts rename to packages/plugin/src/features/explorer/file-context-indicators.ts index 89065929..7e98027d 100644 --- a/packages/plugin/src/ui/explorer/file-context-indicators.ts +++ b/packages/plugin/src/features/explorer/file-context-indicators.ts @@ -1,8 +1,8 @@ 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 type { PluginHost } from "@/app/host"; +import { makeActivatable, revealInFileExplorer } from "@/core/ui"; +import { createSymlinkDetector, type SymlinkDetector } from "@/core/vault"; import type { IndicatorHandle } from "./indicator-handle"; export function registerFileContextIndicators( 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 94% rename from packages/plugin/src/ui/explorer/file-explorer-badges.ts rename to packages/plugin/src/features/explorer/file-explorer-badges.ts index dd9eeedb..a9fd628d 100644 --- a/packages/plugin/src/ui/explorer/file-explorer-badges.ts +++ b/packages/plugin/src/features/explorer/file-explorer-badges.ts @@ -1,9 +1,9 @@ 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 type { PluginHost } from "@/app/host"; +import { openManageLinks } from "@/features/links"; +import { describePeople, renderAvatarStack } from "@/features/presence"; +import { lastEditLabel, openShareWindow } from "@/features/spaces"; import type { PresenceMarks, diff --git a/packages/plugin/src/ui/explorer/file-explorer-decorations.ts b/packages/plugin/src/features/explorer/file-explorer-decorations.ts similarity index 97% rename from packages/plugin/src/ui/explorer/file-explorer-decorations.ts rename to packages/plugin/src/features/explorer/file-explorer-decorations.ts index 4051163a..c905fd87 100644 --- a/packages/plugin/src/ui/explorer/file-explorer-decorations.ts +++ b/packages/plugin/src/features/explorer/file-explorer-decorations.ts @@ -1,14 +1,13 @@ import { setIcon } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import type { SyncController } from "@/sync/controller"; -import type { EChangeType } from "@/sync/types"; +import type { PluginHost } from "@/app/host"; +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"; 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..dffe11f7 100644 --- a/packages/plugin/src/ui/explorer/file-explorer-indicators.ts +++ b/packages/plugin/src/features/explorer/file-explorer-indicators.ts @@ -1,7 +1,7 @@ import type { Plugin, TAbstractFile } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import type { SyncController } from "@/sync/controller"; +import type { PluginHost } from "@/app/host"; +import type { SyncController } from "@/features/sync"; import { readFileExplorer, diff --git a/packages/plugin/src/ui/explorer/file-explorer-marks.ts b/packages/plugin/src/features/explorer/file-explorer-marks.ts similarity index 92% rename from packages/plugin/src/ui/explorer/file-explorer-marks.ts rename to packages/plugin/src/features/explorer/file-explorer-marks.ts index 194319af..7c38e57e 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 { PluginHost } from "@/app/host"; +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"; export type ShareKind = "owned" | "joined" | "read-only" | "paused"; diff --git a/packages/plugin/src/features/explorer/index.ts b/packages/plugin/src/features/explorer/index.ts new file mode 100644 index 00000000..fba46e6c --- /dev/null +++ b/packages/plugin/src/features/explorer/index.ts @@ -0,0 +1,3 @@ +export { registerFileContextIndicators } from "./file-context-indicators"; +export { registerFileExplorerIndicators } from "./file-explorer-indicators"; +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 97% rename from packages/plugin/src/ui/explorer/link-scan.ts rename to packages/plugin/src/features/explorer/link-scan.ts index 52edfc23..2966467e 100644 --- a/packages/plugin/src/ui/explorer/link-scan.ts +++ b/packages/plugin/src/features/explorer/link-scan.ts @@ -1,6 +1,6 @@ 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; diff --git a/packages/plugin/src/ui/explorer/row-decorator.ts b/packages/plugin/src/features/explorer/row-decorator.ts similarity index 95% rename from packages/plugin/src/ui/explorer/row-decorator.ts rename to packages/plugin/src/features/explorer/row-decorator.ts index f22f1b76..32a962af 100644 --- a/packages/plugin/src/ui/explorer/row-decorator.ts +++ b/packages/plugin/src/features/explorer/row-decorator.ts @@ -1,6 +1,6 @@ -import type { PluginHost } from "@/plugin/host"; -import type { SyncController } from "@/sync/controller"; -import { skippedFiles } from "@/ui/common"; +import type { PluginHost } from "@/app/host"; +import type { SyncController } from "@/features/sync"; +import { skippedFiles } from "@/features/sync"; import type { FileExplorerRows } from "./file-explorer-api"; import { type AppliedDecoration, diff --git a/packages/plugin/src/features/links/README.md b/packages/plugin/src/features/links/README.md new file mode 100644 index 00000000..fb4fd54e --- /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/index.ts b/packages/plugin/src/features/links/index.ts new file mode 100644 index 00000000..65f7338b --- /dev/null +++ b/packages/plugin/src/features/links/index.ts @@ -0,0 +1,18 @@ +export { noteLinks, noteLinksText } from "./note-links"; +export { + type LinkRecord, + onRelay, + parseStoredLink, + 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 93% rename from packages/plugin/src/storage/adapters/link-broker.ts rename to packages/plugin/src/features/links/link-broker.ts index 40c7368b..463f2c29 100644 --- a/packages/plugin/src/storage/adapters/link-broker.ts +++ b/packages/plugin/src/features/links/link-broker.ts @@ -1,12 +1,17 @@ import { 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 } from "@/core/shared"; +import { toArrayBuffer } from "@/core/utils"; +import { + ADMIN_HEADER, + type BrokerAdmin, +} from "@/features/spaces/broker/share-broker"; +import { + errorCode, + StorageHttpError, + 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 96% rename from packages/plugin/src/links/note-links.ts rename to packages/plugin/src/features/links/note-links.ts index cee39829..2a11d82d 100644 --- a/packages/plugin/src/links/note-links.ts +++ b/packages/plugin/src/features/links/note-links.ts @@ -1,4 +1,4 @@ -import type { PluginHost } from "@/plugin/host"; +import type { PluginHost } from "@/app/host"; import { expiryLine } from "./describe"; import { isExpired, isStale, type LinkRecord } from "./record"; diff --git a/packages/plugin/src/links/publish.ts b/packages/plugin/src/features/links/publish.ts similarity index 94% rename from packages/plugin/src/links/publish.ts rename to packages/plugin/src/features/links/publish.ts index 6f540102..420d72a9 100644 --- a/packages/plugin/src/links/publish.ts +++ b/packages/plugin/src/features/links/publish.ts @@ -12,20 +12,15 @@ import { } 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 type { PluginHost } from "@/app/host"; +import { isRelayConfigured, relayAdmin } from "@/core/settings"; +import { relayBase } from "@/core/shared"; +import type { BrokerAdmin } from "@/features/spaces"; +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. */ diff --git a/packages/plugin/src/links/record.ts b/packages/plugin/src/features/links/record.ts similarity index 98% rename from packages/plugin/src/links/record.ts rename to packages/plugin/src/features/links/record.ts index da74e44f..b482bd0d 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; diff --git a/packages/plugin/src/plugin/links.ts b/packages/plugin/src/features/links/register.ts similarity index 87% rename from packages/plugin/src/plugin/links.ts rename to packages/plugin/src/features/links/register.ts index b3fbcc99..090f668a 100644 --- a/packages/plugin/src/plugin/links.ts +++ b/packages/plugin/src/features/links/register.ts @@ -1,8 +1,6 @@ import type { Plugin } from "obsidian"; - -import { reportWarning } from "@/shared"; - -import type { PluginHost } from "./host"; +import type { PluginHost } from "@/app/host"; +import { reportWarning } from "@/core/shared"; /** 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 { 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 82% rename from packages/plugin/src/ui/links/link-actions.ts rename to packages/plugin/src/features/links/ui/link-actions.ts index c9a9956b..568dd89e 100644 --- a/packages/plugin/src/ui/links/link-actions.ts +++ b/packages/plugin/src/features/links/ui/link-actions.ts @@ -1,12 +1,8 @@ -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 type { PluginHost } from "@/app/host"; +import { notifyError, notifyInfo, openPromptModal } from "@/core/ui"; +import { linkError } from "../errors"; +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( diff --git a/packages/plugin/src/ui/links/link-menu.ts b/packages/plugin/src/features/links/ui/link-menu.ts similarity index 87% rename from packages/plugin/src/ui/links/link-menu.ts rename to packages/plugin/src/features/links/ui/link-menu.ts index 7297bc05..b5189d2d 100644 --- a/packages/plugin/src/ui/links/link-menu.ts +++ b/packages/plugin/src/features/links/ui/link-menu.ts @@ -1,8 +1,8 @@ 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 type { PluginHost } from "@/app/host"; +import { isRelayConfigured } from "@/core/settings"; +import { docKindOf } from "@/features/live/doc-types"; +import { ESetupStep } from "@/features/setup/step-state"; import { ManageLinksModal } from "./manage-links-modal"; import { ShareLinkModal } from "./share-link-modal"; diff --git a/packages/plugin/src/settings/sections/links.ts b/packages/plugin/src/features/links/ui/links-section.ts similarity index 85% rename from packages/plugin/src/settings/sections/links.ts rename to packages/plugin/src/features/links/ui/links-section.ts index deb5463f..a9189f74 100644 --- a/packages/plugin/src/settings/sections/links.ts +++ b/packages/plugin/src/features/links/ui/links-section.ts @@ -1,7 +1,7 @@ import type { SettingDefinitionGroup } from "obsidian"; -import { type FieldContext, group } from "@/settings/fields"; -import { openManageLinks } from "@/ui"; +import { type FieldContext, group } from "@/core/settings"; +import { openManageLinks } from "./link-menu"; export function linksSection({ plugin }: FieldContext): SettingDefinitionGroup { return group("Share links", [ 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..efdc155e 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 type { PluginHost } from "@/app/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 { linkStatusOf, revokeLinkRecord } from "../publish"; +import { + isExpired, + isStale, + type LinkRecord, + noteName, + onRelay, +} from "../record"; import { updateSharedLinks } from "./link-actions"; 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 94% 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..5c2b8ebd 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 { PluginHost } from "@/app/host"; +import { noteLinks, noteLinksText } from "../note-links"; import { openManageLinks } from "./link-menu"; 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..1253fb21 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 type { PluginHost } from "@/app/host"; +import { + alertLine, + copyable, + modalFooter, + renderModalHead, + serial, +} from "@/core/ui"; +import { invitePassword } from "@/features/spaces/invite"; 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 { previewLink, publishLink } from "../publish"; +import type { LinkRecord } from "../record"; +import type { Snapshot } from "../snapshot/snapshot"; import { renderPreviewFrame } from "./preview-frame"; const MIN_PASSPHRASE = 8; 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 88% rename from packages/plugin/src/live/cold/cold-sync.ts rename to packages/plugin/src/features/live/cold/cold-sync.ts index e44af5ad..fb422249 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 { textToBytes } from "@/features/sync/changes/content"; import { type IncomingText, isNewerMark, type LiveNotes, type LiveTake, -} from "@/sync/live-notes"; -import type { LiveMark } from "@/sync/types"; -import { toLf } from "@/utils"; +} from "@/features/sync/live-notes"; +import type { LiveMark } from "@/features/sync/types"; +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 100% rename from packages/plugin/src/live/doc-types.ts rename to packages/plugin/src/features/live/doc-types.ts 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 88% rename from packages/plugin/src/plugin/live.ts rename to packages/plugin/src/features/live/register.ts index 7b697c30..71e1d879 100644 --- a/packages/plugin/src/plugin/live.ts +++ b/packages/plugin/src/features/live/register.ts @@ -1,21 +1,20 @@ import type { App, FileView, TFile, Vault, Workspace } from "obsidian"; - -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"; +import { personColor, reportWarning } from "@/core/shared"; +import { renameInVault } from "@/core/vault"; +import type { HubConnection } from "@/features/relay"; +import type { + SpaceAccess, + SpaceAccessHost, + SpaceRecords, +} from "@/features/spaces"; +import type { LiveNotes } from "@/features/sync/live-notes"; +import type { WriteJournal } from "@/features/sync/recovery/journal"; +import { type Space, spaceOf, VAULT_SPACE } from "@/features/sync/remote/space"; +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"; export interface LiveHost extends SpaceAccessHost { app: App; 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 91% rename from packages/plugin/src/live/session/rotation.ts rename to packages/plugin/src/features/live/session/rotation.ts index f4b65c0c..48cb774e 100644 --- a/packages/plugin/src/live/session/rotation.ts +++ b/packages/plugin/src/features/live/session/rotation.ts @@ -1,8 +1,8 @@ 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 "@/features/relay"; 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..d780631e 100644 --- a/packages/plugin/src/live/session/session-deps.ts +++ b/packages/plugin/src/features/live/session/session-deps.ts @@ -1,10 +1,10 @@ import type { Refusal } from "@mdsync/protocol"; -import type { LiveKeys } from "@/crypto/live-keys"; -import type { SpaceHub } from "@/hub"; +import type { LiveKeys } from "@/core/crypto"; +import type { SpaceHub } from "@/features/relay"; -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..4a0df980 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 { reportWarning } from "@/core/shared"; +import { runWithConcurrency } from "@/core/utils"; +import type { SpaceFrame, SpaceListener } from "@/features/relay"; +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 91% rename from packages/plugin/src/live/text/merge.ts rename to packages/plugin/src/features/live/text/merge.ts index 23f5855d..735f3e32 100644 --- a/packages/plugin/src/live/text/merge.ts +++ b/packages/plugin/src/features/live/text/merge.ts @@ -1,5 +1,9 @@ -import { sameLines, threeWayRegions, toLines } from "@/sync/merge-model"; -import { commonEnds } from "@/utils"; +import { commonEnds } from "@/core/utils"; +import { + sameLines, + threeWayRegions, + toLines, +} from "@/features/sync/hunks/merge-model"; /** * 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..9eb1f0db 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/hunks/hunks"; 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 87% rename from packages/plugin/src/ui/live/deleted-elsewhere.ts rename to packages/plugin/src/features/live/ui/deleted-elsewhere.ts index 71d69d8f..95c0c2c8 100644 --- a/packages/plugin/src/ui/live/deleted-elsewhere.ts +++ b/packages/plugin/src/features/live/ui/deleted-elsewhere.ts @@ -1,7 +1,6 @@ -import type { PluginHost } from "@/plugin/host"; -import { spaceOf } from "@/sync/space"; -import { notifyError, runWithNotice } from "@/ui/common"; -import { openChoiceModal } from "@/ui/modals"; +import type { PluginHost } from "@/app/host"; +import { notifyError, openChoiceModal, runWithNotice } from "@/core/ui"; +import { spaceOf } from "@/features/sync/remote/space"; /** Another device deleted a note open here: the person decides whether it goes here too or comes back everywhere. */ export function createDeletedElsewhere( 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 90% rename from packages/plugin/src/live/workspace/rename.ts rename to packages/plugin/src/features/live/workspace/rename.ts index 7b050a32..ee09440a 100644 --- a/packages/plugin/src/live/workspace/rename.ts +++ b/packages/plugin/src/features/live/workspace/rename.ts @@ -4,14 +4,14 @@ */ 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 { hasDotSegment, normalizePath } from "@/core/shared"; +import type { SpaceHub } from "@/features/relay"; +import { bytesToText, textToBytes } from "@/features/sync/changes/content"; +import { insideOf, vaultPathOf } from "@/features/sync/remote/space"; +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..048ff24f 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 { reportWarning, withDevices } from "@/core/shared"; +import { toLf } from "@/core/utils"; +import type { HubConnection } from "@/features/relay"; +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"; 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..abe4010e 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/remote/space"; +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 87% rename from packages/plugin/src/ui/live/header/header-state.ts rename to packages/plugin/src/features/note-header/header-state.ts index 920b5a36..370a420d 100644 --- a/packages/plugin/src/ui/live/header/header-state.ts +++ b/packages/plugin/src/features/note-header/header-state.ts @@ -1,10 +1,15 @@ 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 { PluginHost } from "@/app/host"; +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 LiveStatus, liveStatusOf } from "./live-status"; 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..b7de1904 --- /dev/null +++ b/packages/plugin/src/features/note-header/index.ts @@ -0,0 +1,3 @@ +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 81% rename from packages/plugin/src/ui/live/header/live-actions.ts rename to packages/plugin/src/features/note-header/live-actions.ts index 8370d6bc..74ddd452 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 type { PluginHost } from "@/app/host"; +import { notifyInfo, reportError } from "@/core/ui"; +import type { Rotation } from "@/features/live"; const REBUILT: Record = { moved: "Live note rebuilt from its text.", diff --git a/packages/plugin/src/ui/live/header/live-status.ts b/packages/plugin/src/features/note-header/live-status.ts similarity index 88% rename from packages/plugin/src/ui/live/header/live-status.ts rename to packages/plugin/src/features/note-header/live-status.ts index 5536d1ce..d9652cab 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 type { PluginHost } from "@/app/host"; +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"; const ARRIVES_ON_SYNC = "Changes arrive as they sync"; 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 92% rename from packages/plugin/src/ui/live/header/note-menu.ts rename to packages/plugin/src/features/note-header/note-menu.ts index 296725b6..ff30cb53 100644 --- a/packages/plugin/src/ui/live/header/note-menu.ts +++ b/packages/plugin/src/features/note-header/note-menu.ts @@ -1,15 +1,9 @@ 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 type { PluginHost } from "@/app/host"; +import { openPluginSettings, relayFixOf } from "@/core/hub"; +import { infoTitle, personTitle, showMenuAt } from "@/core/ui"; +import { lastEditLabel, openShareWindow } from "@/features/spaces"; import { headerOf, showsHeader } from "./header-state"; import { rebuildLiveNote, toggleAuthors } from "./live-actions"; import { diff --git a/packages/plugin/src/ui/live/header/note-presence.ts b/packages/plugin/src/features/note-header/note-presence.ts similarity index 94% rename from packages/plugin/src/ui/live/header/note-presence.ts rename to packages/plugin/src/features/note-header/note-presence.ts index 1ea4ca56..ff3a729d 100644 --- a/packages/plugin/src/ui/live/header/note-presence.ts +++ b/packages/plugin/src/features/note-header/note-presence.ts @@ -1,13 +1,9 @@ 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 type { PluginHost } from "@/app/host"; +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 { LiveStatus } from "./live-status"; import { openActiveNoteMenu, openNoteMenu } from "./note-menu"; 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 95% rename from packages/plugin/src/ui/live/header/cursor-follow.ts rename to packages/plugin/src/features/presence/follow/cursor-follow.ts index 5338eb61..24c03aab 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 type { PluginHost } from "@/app/host"; +import { openNote } from "@/core/ui"; +import type { LiveSession } from "@/features/live"; +import type { Person } from "../views"; import { showFollowBanner } from "./follow-banner"; import { trackCursor } from "./follow-scroll"; 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 91% rename from packages/plugin/src/ui/live/header/follow-scroll.ts rename to packages/plugin/src/features/presence/follow/follow-scroll.ts index 797b8ba4..eca2d2ce 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/session/session"; +import { watchCursor } from "@/features/live/text/cursors"; /** 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 76% rename from packages/plugin/src/plugin/follows.ts rename to packages/plugin/src/features/presence/follow/follows.ts index 2273582b..8e758584 100644 --- a/packages/plugin/src/plugin/follows.ts +++ b/packages/plugin/src/features/presence/follow/follows.ts @@ -1,7 +1,6 @@ import type { Plugin } from "obsidian"; - -import { CursorFollow } from "@/ui"; -import type { PluginHost } from "./host"; +import type { PluginHost } from "@/app/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 { 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/index.ts b/packages/plugin/src/features/presence/index.ts new file mode 100644 index 00000000..5a52011e --- /dev/null +++ b/packages/plugin/src/features/presence/index.ts @@ -0,0 +1,8 @@ +export { CursorFollow } from "./follow/cursor-follow"; +export { registerFollows } from "./follow/follows"; +export { watchHere } from "./here"; +export { People } from "./people"; +export { markTheirs, registerUnseen } from "./register"; +export { describePeople, 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..597197b1 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 { reportWarning } from "@/core/shared"; +import type { HubConnection, SpaceHub } from "@/features/relay"; import { insideOf, type Space, spaceOf, VAULT_SPACE, vaultPathOf, -} from "@/sync/space"; +} from "@/features/sync/remote/space"; import { type Announcement, sealAnnouncement } from "./announcement"; import { ChannelPresence } from "./channel"; diff --git a/packages/plugin/src/plugin/unseen.ts b/packages/plugin/src/features/presence/register.ts similarity index 91% rename from packages/plugin/src/plugin/unseen.ts rename to packages/plugin/src/features/presence/register.ts index de2a8cd8..f357b668 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/remote/space"; +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 92% rename from packages/plugin/src/ui/common/avatars.ts rename to packages/plugin/src/features/presence/ui/avatars.ts index 1c3efcef..669983fe 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; 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..4aa2d79a 100644 --- a/packages/plugin/src/hub/channels.ts +++ b/packages/plugin/src/features/relay/channels.ts @@ -5,20 +5,19 @@ import { deriveChannelGrant, MAX_SLOTS, shareChannel } from "@mdsync/protocol"; -import { sha256Hex } from "@/crypto"; +import { sha256Hex } from "@/core/crypto"; +import type { HubChannel } from "@/core/hub"; 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"; +} from "@/core/settings"; +import { relayBase } from "@/core/shared"; +import { pauseOf } from "@/features/spaces/partition"; +import type { SpaceRecord } from "@/features/spaces/record"; +import { storageIdentity } from "@/features/storage"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; export interface HubRoute { serverUrl: string; diff --git a/packages/plugin/src/hub/connection.ts b/packages/plugin/src/features/relay/connection.ts similarity index 96% rename from packages/plugin/src/hub/connection.ts rename to packages/plugin/src/features/relay/connection.ts index 035dda14..c0355218 100644 --- a/packages/plugin/src/hub/connection.ts +++ b/packages/plugin/src/features/relay/connection.ts @@ -4,14 +4,11 @@ */ 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 { HubLink, type RelayStatus, relayStatus } from "@/core/hub"; +import type { MdsyncSettings } from "@/core/settings"; +import { pauseOf } from "@/features/spaces/partition"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; 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 { 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 92% rename from packages/plugin/src/settings/setup/relay.ts rename to packages/plugin/src/features/relay/deploy/deploy-flow.ts index 2da749bf..faecd1da 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 type { PluginHost } from "@/app/host"; +import { randomBytes, randomSecret } from "@/core/crypto"; +import { isRelayConfigured, type RelayConfig } from "@/core/settings"; +import type { CloudflareLogin } from "@/features/storage"; +import { testRelay } from "@/features/storage"; 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. */ 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/index.ts b/packages/plugin/src/features/relay/index.ts new file mode 100644 index 00000000..40d39c54 --- /dev/null +++ b/packages/plugin/src/features/relay/index.ts @@ -0,0 +1,27 @@ +export { + HubConnection, + type SpaceFrame, + type SpaceHub, + type SpaceListener, +} 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 { relaySection } from "./ui/relay-section"; +export { type RelayUpdate, registerRelayUpdate } from "./update/relay-update"; diff --git a/packages/plugin/src/settings/sections/relay.ts b/packages/plugin/src/features/relay/ui/relay-section.ts similarity index 86% rename from packages/plugin/src/settings/sections/relay.ts rename to packages/plugin/src/features/relay/ui/relay-section.ts index 0e0c440b..64eb53ed 100644 --- a/packages/plugin/src/settings/sections/relay.ts +++ b/packages/plugin/src/features/relay/ui/relay-section.ts @@ -1,19 +1,17 @@ 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, 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 { runWithNotice } from "@/core/ui"; +import { ESetupStep } from "@/features/setup/step-state"; +import { EFieldKind, forgetCloudflare, testRelay } from "@/features/storage"; function secretButtonLabel(secret: string): string { return secret ? "Copy" : "Generate"; 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 87% 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..7ff40a66 100644 --- a/packages/plugin/src/ui/modals/relay-update-modal.ts +++ b/packages/plugin/src/features/relay/update/relay-update-modal.ts @@ -1,22 +1,20 @@ 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 type { PluginHost } from "@/app/host"; 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"; /** True once the relay is updated; any other close is "not now". */ export function openRelayUpdateModal( diff --git a/packages/plugin/src/plugin/relay-update.ts b/packages/plugin/src/features/relay/update/relay-update.ts similarity index 91% rename from packages/plugin/src/plugin/relay-update.ts rename to packages/plugin/src/features/relay/update/relay-update.ts index eea5865e..58b3817d 100644 --- a/packages/plugin/src/plugin/relay-update.ts +++ b/packages/plugin/src/features/relay/update/relay-update.ts @@ -1,19 +1,16 @@ import type { Plugin } from "obsidian"; - +import type { PluginHost } from "@/app/host"; +import { reportWarning } from "@/core/shared"; +import { cloudflareOf, testRelay } 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 { openRelayUpdateModal } from "./relay-update-modal"; const SKIPPED_KEY = "mdsync-relay-update-skipped"; diff --git a/packages/plugin/src/features/settings/index.ts b/packages/plugin/src/features/settings/index.ts new file mode 100644 index 00000000..7ef0e047 --- /dev/null +++ b/packages/plugin/src/features/settings/index.ts @@ -0,0 +1,2 @@ +export { SETUP_FIELDS } from "./sections/automation"; +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 94% rename from packages/plugin/src/settings/logs-view.ts rename to packages/plugin/src/features/settings/logs-view.ts index c6cab6ce..870ee7ea 100644 --- a/packages/plugin/src/settings/logs-view.ts +++ b/packages/plugin/src/features/settings/logs-view.ts @@ -3,15 +3,15 @@ import { Setting, type SettingDefinitionPage, } from "obsidian"; +import type { PluginHost } from "@/app/host"; 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"; const LOG_LEVEL_LABELS: Record = { [ESyncLogLevel.Info]: "Info", diff --git a/packages/plugin/src/styles/settings/overview.css b/packages/plugin/src/features/settings/overview.css similarity index 100% rename from packages/plugin/src/styles/settings/overview.css rename to packages/plugin/src/features/settings/overview.css diff --git a/packages/plugin/src/settings/overview.ts b/packages/plugin/src/features/settings/overview.ts similarity index 93% rename from packages/plugin/src/settings/overview.ts rename to packages/plugin/src/features/settings/overview.ts index 0b40db14..abb3f332 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 { PluginHost } from "@/app/host"; +import type { RelayStatus } from "@/core/hub"; +import { RELAY_TEXT } from "@/core/hub"; +import type { FieldContext } from "@/core/settings"; import { activeStorage, canSync, isGuest, isRelayConfigured, isStorageConfigured, -} from "./model"; +} from "@/core/settings"; +import { formatRelativeTime, pluralize } from "@/core/shared"; +import { describeStorageTarget, storageIdentity } from "@/features/storage"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; type Tone = "ok" | "muted" | "warning" | "error"; diff --git a/packages/plugin/src/settings/sections/advanced.ts b/packages/plugin/src/features/settings/sections/advanced.ts similarity index 80% rename from packages/plugin/src/settings/sections/advanced.ts rename to packages/plugin/src/features/settings/sections/advanced.ts index 95c02c6a..5caf4b86 100644 --- a/packages/plugin/src/settings/sections/advanced.ts +++ b/packages/plugin/src/features/settings/sections/advanced.ts @@ -1,7 +1,7 @@ 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/identity/device"; export function advancedSection({ plugin, diff --git a/packages/plugin/src/settings/sections/automation.ts b/packages/plugin/src/features/settings/sections/automation.ts similarity index 94% rename from packages/plugin/src/settings/sections/automation.ts rename to packages/plugin/src/features/settings/sections/automation.ts index 372e672b..1757301e 100644 --- a/packages/plugin/src/settings/sections/automation.ts +++ b/packages/plugin/src/features/settings/sections/automation.ts @@ -1,5 +1,5 @@ import type { Setting, SettingDefinitionGroup } from "obsidian"; - +import type { PluginHost } from "@/app/host"; import { AUTO_PUSH_SETTLE_MAX_SECONDS, AUTO_PUSH_SETTLE_MIN_SECONDS, @@ -10,22 +10,22 @@ import { 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"; +} from "@/core/constants"; +import type { RelayStatus } from "@/core/hub"; +import { RELAY_TEXT } from "@/core/hub"; import { + DEFAULT_SETTINGS, type FieldContext, fieldRow, group, + isRelayConfigured, 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"; +} from "@/core/settings"; +import type { People } from "@/features/presence"; +import { EFieldKind } from "@/features/storage"; +import { clampMaxSnapshots } from "@/features/sync/history/gc"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; const AUTOSYNC_FIELD: SettingsField = { kind: EFieldKind.Toggle, diff --git a/packages/plugin/src/settings/sections/interface.ts b/packages/plugin/src/features/settings/sections/interface.ts similarity index 96% rename from packages/plugin/src/settings/sections/interface.ts rename to packages/plugin/src/features/settings/sections/interface.ts index 64e2680c..1ffbbef2 100644 --- a/packages/plugin/src/settings/sections/interface.ts +++ b/packages/plugin/src/features/settings/sections/interface.ts @@ -5,8 +5,8 @@ import { fieldRow, group, type SettingsField, -} from "@/settings/fields"; -import { EFieldKind } from "@/storage"; +} from "@/core/settings"; +import { EFieldKind } from "@/features/storage"; const INTERFACE_FIELDS: ReadonlyArray = [ { diff --git a/packages/plugin/src/settings/sections/security.ts b/packages/plugin/src/features/settings/sections/security.ts similarity index 89% rename from packages/plugin/src/settings/sections/security.ts rename to packages/plugin/src/features/settings/sections/security.ts index 30062384..7e764864 100644 --- a/packages/plugin/src/settings/sections/security.ts +++ b/packages/plugin/src/features/settings/sections/security.ts @@ -1,10 +1,14 @@ import type { SettingDefinitionGroup } from "obsidian"; -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"; +import { clearCachedPassphrase } from "@/core/crypto"; +import { type FieldContext, group, isStorageConfigured } from "@/core/settings"; +import { + askNewPassphrase, + notifyError, + notifyInfo, + reportError, +} from "@/core/ui"; +import { PassphraseRotatedError } from "@/features/sync/remote/keyfile"; export function securitySection(ctx: FieldContext): SettingDefinitionGroup { const { plugin, rerender } = ctx; diff --git a/packages/plugin/src/settings/tab.ts b/packages/plugin/src/features/settings/tab.ts similarity index 68% rename from packages/plugin/src/settings/tab.ts rename to packages/plugin/src/features/settings/tab.ts index c43b225d..01691e65 100644 --- a/packages/plugin/src/settings/tab.ts +++ b/packages/plugin/src/features/settings/tab.ts @@ -5,24 +5,22 @@ import { type SettingDefinitionItem, } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import { type FieldContext, settleTyping } from "./fields"; +import type { PluginHost } from "@/app/host"; +import { type FieldContext, settleTyping } from "@/core/settings"; +import { linksSection } from "@/features/links/ui/links-section"; +import { relaySection } from "@/features/relay/ui/relay-section"; +import { sharesSection } from "@/features/spaces/ui/shares-section"; +import { backendSection } from "@/features/storage"; +import { configurationScopeSection } from "@/features/sync/scope/configuration-scope-section"; +import { exclusionsSection } from "@/features/sync/scope/exclusions-section"; +import { maintenanceSection } from "@/features/sync/ui/maintenance-section"; +import { deviceTransferSection } from "@/features/transfer"; import { logsPage } from "./logs-view"; import { overviewGroup } from "./overview"; -import { - advancedSection, - automationSection, - backendSection, - configurationScopeSection, - deviceTransferSection, - exclusionsSection, - interfaceSection, - linksSection, - maintenanceSection, - relaySection, - securitySection, - sharesSection, -} from "./sections"; +import { advancedSection } from "./sections/advanced"; +import { automationSection } from "./sections/automation"; +import { interfaceSection } from "./sections/interface"; +import { securitySection } from "./sections/security"; export class MdsyncSettingTab extends PluginSettingTab { private readonly plugin: Plugin & PluginHost; diff --git a/packages/plugin/src/styles/settings/tabs-and-logs.css b/packages/plugin/src/features/settings/tabs-and-logs.css similarity index 100% rename from packages/plugin/src/styles/settings/tabs-and-logs.css rename to packages/plugin/src/features/settings/tabs-and-logs.css diff --git a/packages/plugin/src/features/setup/README.md b/packages/plugin/src/features/setup/README.md new file mode 100644 index 00000000..3ee771eb --- /dev/null +++ b/packages/plugin/src/features/setup/README.md @@ -0,0 +1,57 @@ +# Setup wizard + +One modal stepper takes a fresh install to a syncing vault: storage (Cloudflare R2 from a token by default), passphrase, relay (deployed from the plugin), first sync and toggles. 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`), **Accept an invite to a shared folder** (hands off to `openInvite` of spaces, closes), **Not now**. +- `new`: Storage -> Passphrase -> Relay -> Ready. `join`: Import -> 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** is off until the step is done and `blocksNext()` is false. + +| 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 just moves on), 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 it replaces storage and relay settings and the button is the consent | +| Relay | `features/setup/steps/relay-step.ts`, `features/setup/steps/relay-deploy-view.ts` | see Relay below | +| Ready | `features/setup/steps/ready-step.ts` | summary rows (storage, encryption, relay); **Sync now** = `controller.refreshAndAutoSync(true)` with progress text, then conflicts or pending changes offer **Open changes**; Autosync, Real-time sync and Live editing toggles from `SETUP_FIELDS` of `features/settings/sections/automation.ts`; **Show setup link** for another device (`showSettingsTransferExport`) | + +## 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`, `next`, `choose(path)`, `close`, `isShowing(view)`, `isLive()`. +- `features/setup/stepper.ts`, `features/setup/choice-card.ts`, `features/setup/form.ts` (`actionRow`, `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`). +- Deep imports that bypass facades are baselined debt (`pnpm arch`): `features/source-control/view.ts` (**Open changes**), `features/spaces/ui/invites/invite-action.ts`, `features/settings/sections/automation.ts`, `features/relay/deploy/*`, `features/sync/remote/keyfile.ts`. Do not add more. + +## 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`). + +## 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/settings/setup/form.ts b/packages/plugin/src/features/setup/form.ts similarity index 100% rename from packages/plugin/src/settings/setup/form.ts rename to packages/plugin/src/features/setup/form.ts diff --git a/packages/plugin/src/settings/setup/index.ts b/packages/plugin/src/features/setup/index.ts similarity index 59% rename from packages/plugin/src/settings/setup/index.ts rename to packages/plugin/src/features/setup/index.ts index 202eaa63..3fff17b8 100644 --- a/packages/plugin/src/settings/setup/index.ts +++ b/packages/plugin/src/features/setup/index.ts @@ -1,2 +1,2 @@ -export { ESetupStep } from "./steps"; +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 95% rename from packages/plugin/src/settings/setup/steps.ts rename to packages/plugin/src/features/setup/step-state.ts index 420cda37..ad271e54 100644 --- a/packages/plugin/src/settings/setup/steps.ts +++ b/packages/plugin/src/features/setup/step-state.ts @@ -1,9 +1,9 @@ -import type { PluginHost } from "@/plugin/host"; +import type { PluginHost } from "@/app/host"; import { canSync, isRelayConfigured, isStorageConfigured, -} from "@/settings/model"; +} from "@/core/settings"; export const ESetupStep = { Start: "start", 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 91% rename from packages/plugin/src/settings/setup/cloudflare-token.ts rename to packages/plugin/src/features/setup/steps/cloudflare-token.ts index d9476c3a..6701aa90 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 { alertLine, 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 { actionRow } 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 = diff --git a/packages/plugin/src/settings/setup/import-step.ts b/packages/plugin/src/features/setup/steps/import-step.ts similarity index 89% rename from packages/plugin/src/settings/setup/import-step.ts rename to packages/plugin/src/features/setup/steps/import-step.ts index db46d411..ffadfbaf 100644 --- a/packages/plugin/src/settings/setup/import-step.ts +++ b/packages/plugin/src/features/setup/steps/import-step.ts @@ -1,10 +1,10 @@ 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 { canSync } from "@/core/settings"; +import { alertLine, callout, focusKey, onEnter } from "@/core/ui"; +import { actionRow } from "../form"; +import { runAction } from "../run-action"; +import type { StepView, Wizard } from "../wizard"; export function createImportStep(wizard: Wizard): StepView { const { plugin } = wizard; diff --git a/packages/plugin/src/settings/setup/passphrase-step.ts b/packages/plugin/src/features/setup/steps/passphrase-step.ts similarity index 89% rename from packages/plugin/src/settings/setup/passphrase-step.ts rename to packages/plugin/src/features/setup/steps/passphrase-step.ts index 3d96417c..a223cb29 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/remote/keyfile"; +import { actionRow, 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"; diff --git a/packages/plugin/src/settings/setup/ready-step.ts b/packages/plugin/src/features/setup/steps/ready-step.ts similarity index 89% rename from packages/plugin/src/settings/setup/ready-step.ts rename to packages/plugin/src/features/setup/steps/ready-step.ts index 7ba5ef4c..8ac393ae 100644 --- a/packages/plugin/src/settings/setup/ready-step.ts +++ b/packages/plugin/src/features/setup/steps/ready-step.ts @@ -1,20 +1,22 @@ import { Setting, setIcon } from "obsidian"; -import { SOURCE_CONTROL_VIEW_TYPE } from "@/constants"; -import { fieldRow, renderDefinitions } from "@/settings/fields"; +import { SOURCE_CONTROL_VIEW_TYPE } from "@/core/constants"; import { activeStorage, canSync, + fieldRow, 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"; + renderDefinitions, +} from "@/core/settings"; +import { alertLine } from "@/core/ui"; +import { SETUP_FIELDS } from "@/features/settings/sections/automation"; +import { openSourceControlView } from "@/features/source-control/view"; +import { describeStorageTarget } from "@/features/storage"; +import type { SyncStatusSnapshot } from "@/features/sync"; +import { showSettingsTransferExport } from "@/features/transfer"; -import type { StepView, Wizard } from "./wizard"; +import type { StepView, Wizard } from "../wizard"; function summaryRow( list: HTMLElement, 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 95% 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..3533cb5b 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,33 @@ import { Setting, setIcon } from "obsidian"; - +import { randomSecret } from "@/core/crypto"; +import { isRelayConfigured } from "@/core/settings"; +import { alertLine, callout, focusKey, serial } from "@/core/ui"; +import { + activateRelay, + deployOwnRelay, + failedRelay, + planRelay, + runningRelayDeploy, +} from "@/features/relay/deploy/deploy-flow"; import { type AccountRelays, accountRelays, - ERelayDeployStep, freeRelayName, RELAY_NAME, type RelayTarget, relayNameError, relayUrlOf, -} from "@/cloudflare"; -import { randomSecret } from "@/crypto"; +} from "@/features/relay/deploy/relay-account"; +import { ERelayDeployStep } from "@/features/relay/deploy/relay-deploy"; 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"; + testRelay, +} from "@/features/storage"; +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" diff --git a/packages/plugin/src/settings/setup/relay-step.ts b/packages/plugin/src/features/setup/steps/relay-step.ts similarity index 89% rename from packages/plugin/src/settings/setup/relay-step.ts rename to packages/plugin/src/features/setup/steps/relay-step.ts index 1b7c5f43..c00cd374 100644 --- a/packages/plugin/src/settings/setup/relay-step.ts +++ b/packages/plugin/src/features/setup/steps/relay-step.ts @@ -1,16 +1,15 @@ 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 { alertLine, callout, focusKey, onEnter } from "@/core/ui"; +import { useRelay } from "@/features/relay/deploy/deploy-flow"; +import { relayBehind } from "@/features/relay/deploy/relay-account"; +import { type RelayTestResult, testRelay } from "@/features/storage"; +import { choiceCard } from "../choice-card"; +import { actionRow, 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"; diff --git a/packages/plugin/src/settings/setup/start-step.ts b/packages/plugin/src/features/setup/steps/start-step.ts similarity index 86% rename from packages/plugin/src/settings/setup/start-step.ts rename to packages/plugin/src/features/setup/steps/start-step.ts index c7f8fb31..664be993 100644 --- a/packages/plugin/src/settings/setup/start-step.ts +++ b/packages/plugin/src/features/setup/steps/start-step.ts @@ -1,10 +1,10 @@ import { setIcon } from "obsidian"; -import { openInvite } from "@/ui"; +import { openInvite } from "@/features/spaces/ui/invites/invite-action"; -import { choiceCard } from "./choice-card"; -import { ESetupPath } from "./steps"; -import type { StepView, Wizard } from "./wizard"; +import { choiceCard } from "../choice-card"; +import { ESetupPath } from "../step-state"; +import type { StepView, Wizard } from "../wizard"; export function createStartStep(wizard: Wizard): StepView { return { diff --git a/packages/plugin/src/settings/setup/storage-step.ts b/packages/plugin/src/features/setup/steps/storage-step.ts similarity index 86% rename from packages/plugin/src/settings/setup/storage-step.ts rename to packages/plugin/src/features/setup/steps/storage-step.ts index 113a7740..bbbde862 100644 --- a/packages/plugin/src/settings/setup/storage-step.ts +++ b/packages/plugin/src/features/setup/steps/storage-step.ts @@ -1,25 +1,26 @@ +import { isRefusedToken } from "@/core/cloudflare"; import { - isRefusedToken, - R2NotEnabledError, - r2DashboardUrl, -} from "@/cloudflare"; + activeStorage, + isStorageConfigured, + renderDefinitions, +} from "@/core/settings"; +import { alertLine, callout } from "@/core/ui"; import { + 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"; + R2NotEnabledError, + r2DashboardUrl, + testConnection, + useR2, +} from "@/features/storage"; +import { choiceCard } from "../choice-card"; +import { actionRow } 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"; diff --git a/packages/plugin/src/styles/settings/setup-cards.css b/packages/plugin/src/features/setup/styles/setup-cards.css similarity index 100% rename from packages/plugin/src/styles/settings/setup-cards.css rename to packages/plugin/src/features/setup/styles/setup-cards.css 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 100% rename from packages/plugin/src/styles/settings/setup-progress.css rename to packages/plugin/src/features/setup/styles/setup-progress.css diff --git a/packages/plugin/src/styles/settings/setup-stepper.css b/packages/plugin/src/features/setup/styles/setup-stepper.css similarity index 100% rename from packages/plugin/src/styles/settings/setup-stepper.css rename to packages/plugin/src/features/setup/styles/setup-stepper.css diff --git a/packages/plugin/src/styles/settings/setup.css b/packages/plugin/src/features/setup/styles/setup.css similarity index 100% rename from packages/plugin/src/styles/settings/setup.css rename to packages/plugin/src/features/setup/styles/setup.css diff --git a/packages/plugin/src/settings/setup/wizard.ts b/packages/plugin/src/features/setup/wizard.ts similarity index 92% rename from packages/plugin/src/settings/setup/wizard.ts rename to packages/plugin/src/features/setup/wizard.ts index 083a99b3..2b182fa8 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 type { PluginHost } from "@/app/host"; +import { renderKeepingFocus } from "@/core/ui"; +import { + ESetupPath, + ESetupStep, + firstStep, + isStepDone, + PATH_STEPS, +} from "./step-state"; import { createStepper, EStepState, @@ -15,14 +16,12 @@ import { type StepperItem, stepStates, } from "./stepper"; -import { - ESetupPath, - ESetupStep, - firstStep, - isStepDone, - PATH_STEPS, -} from "./steps"; -import { createStorageStep } from "./storage-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; diff --git a/packages/plugin/src/ui/source-control/actions.ts b/packages/plugin/src/features/source-control/actions/actions.ts similarity index 94% rename from packages/plugin/src/ui/source-control/actions.ts rename to packages/plugin/src/features/source-control/actions/actions.ts index 38f812ed..fda53f40 100644 --- a/packages/plugin/src/ui/source-control/actions.ts +++ b/packages/plugin/src/features/source-control/actions/actions.ts @@ -1,22 +1,22 @@ 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 { PluginHost } from "@/app/host"; import { attempt, openInEditor, revealInFileExplorer, runWithNotice, -} from "@/ui/common"; -import { isIgnoreNote } from "@/vault/ignore"; +} from "@/core/ui"; +import { EConflictStrategy } from "@/features/sync/controller"; +import { isIgnoreNote } from "@/features/sync/scope/ignore"; +import { EChangeType } from "@/features/sync/types"; +import { addIgnoreMenuItem } from "@/features/sync/ui/ignore-action"; import { confirmAdoptNewVault, confirmBatchResolve, confirmRevert, -} from "./modals"; -import { ESection } from "./types"; +} from "@/features/sync/ui/modals"; +import { ESection } from "../types"; const BATCH_RESOLVE_CONFIRM_THRESHOLD = 5; 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 96% 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..1d53c867 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"; 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..2f1fc99d 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/controller"; +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 95% 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..80f6bd8f 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 type { PluginHost } from "@/app/host"; +import { canSync } from "@/core/settings"; +import { appendIconButton, appendLabeledButton, notifyError } from "@/core/ui"; +import { lastEditLabel, lastEditor } from "@/features/spaces/last-edit"; +import type { + DiffResult, + ManifestEntry, + SyncStatusSnapshot, +} from "@/features/sync"; +import type { SourceControlActions } from "../actions/actions"; +import { SelectionBar } from "../actions/selection-bar"; +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 { 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 92% 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..682d87e7 100644 --- a/packages/plugin/src/ui/source-control/excluded-files.ts +++ b/packages/plugin/src/features/source-control/changes/excluded-files.ts @@ -1,9 +1,9 @@ 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 type { PluginHost } from "@/app/host"; +import { formatBytes } from "@/core/shared"; +import type { SkippedFile } from "@/features/sync/types"; +import { stopIgnoring } from "@/features/sync/ui/ignore-action"; 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. */ 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 85% 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..6046fd8e 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,11 @@ -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 { movesByPath } from "@/features/sync/changes/moves"; +import { deviceLabel } from "@/features/sync/identity/device"; +import type { Conflict, FileChange, Move } from "@/features/sync/types"; +import { + type ChangeAction, + changeActionOf, +} from "@/features/sync/ui/change-action"; +import type { FileRow } from "../types"; export const STATUS_LETTERS: Record = { add: "A", 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/ui/source-control/day-groups.ts b/packages/plugin/src/features/source-control/history/day-groups.ts similarity index 95% rename from packages/plugin/src/ui/source-control/day-groups.ts rename to packages/plugin/src/features/source-control/history/day-groups.ts index 5c4bba86..510f7205 100644 --- a/packages/plugin/src/ui/source-control/day-groups.ts +++ b/packages/plugin/src/features/source-control/history/day-groups.ts @@ -1,4 +1,4 @@ -import { formatDayLabel, formatRelativeTime } from "@/shared"; +import { formatDayLabel, formatRelativeTime } from "@/core/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 { 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 92% 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..30d02533 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 { formatRelativeTime, formatTimestamp } from "@/core/shared"; +import type { FileVersion } from "@/features/sync"; +import { deviceText } from "../changes/row-formatter"; import { timeInDay } from "./day-groups"; -import { deviceText } from "./row-formatter"; export interface HistoryRowVersion { hash: string; 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 95% 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..8c7e5901 100644 --- a/packages/plugin/src/ui/source-control/history-tab.ts +++ b/packages/plugin/src/features/source-control/history/history-tab.ts @@ -1,7 +1,6 @@ import { Menu, setIcon } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import { pluralize } from "@/shared"; -import type { FileVersion } from "@/sync/history"; +import type { PluginHost } from "@/app/host"; +import { pluralize } from "@/core/shared"; import { appendIconButton, appendLabeledButton, @@ -9,20 +8,21 @@ import { 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"; +} from "@/core/ui"; +import { confirmRestore } from "@/features/diff/restore-modal"; +import type { FileVersion } from "@/features/sync"; +import { renderSize } from "../row-parts"; import { renderEmptyState, renderHistoryOff, renderLoadError, renderLoading, -} from "./tab-states"; +} from "../tab-states"; +import { addSnapshotPinItems } from "../timeline/snapshot-menu"; +import type { HistoryDiffTarget } from "../view"; +import { groupRows } from "./day-groups"; +import { HistoryList } from "./history-list"; +import { buildHistoryRows, type HistoryRow } from "./history-rows"; export class HistoryTab { private explicitPath: string | null = null; diff --git a/packages/plugin/src/styles/source-control/history.css b/packages/plugin/src/features/source-control/history/history.css similarity index 100% rename from packages/plugin/src/styles/source-control/history.css rename to packages/plugin/src/features/source-control/history/history.css 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 100% rename from packages/plugin/src/ui/source-control/row-pager.ts rename to packages/plugin/src/features/source-control/history/row-pager.ts 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..8879ba9d --- /dev/null +++ b/packages/plugin/src/features/source-control/index.ts @@ -0,0 +1,9 @@ +export { + keepInRightSidebar, + openDiffView, + openSourceControlChanges, + openSourceControlDeleted, + openSourceControlHistory, + openSourceControlView, + SourceControlView, +} from "./view"; diff --git a/packages/plugin/src/ui/source-control/row-parts.ts b/packages/plugin/src/features/source-control/row-parts.ts similarity index 95% rename from packages/plugin/src/ui/source-control/row-parts.ts rename to packages/plugin/src/features/source-control/row-parts.ts index 979dbed0..d2ac1b19 100644 --- a/packages/plugin/src/ui/source-control/row-parts.ts +++ b/packages/plugin/src/features/source-control/row-parts.ts @@ -1,4 +1,4 @@ -import { formatBytes } from "@/shared"; +import { formatBytes } from "@/core/shared"; /** 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 87% rename from packages/plugin/src/ui/source-control/setup-prompt.ts rename to packages/plugin/src/features/source-control/setup-prompt.ts index c808819e..2022babb 100644 --- a/packages/plugin/src/ui/source-control/setup-prompt.ts +++ b/packages/plugin/src/features/source-control/setup-prompt.ts @@ -1,5 +1,5 @@ -import type { PluginHost } from "@/plugin/host"; -import { ESetupStep } from "@/settings/setup/steps"; +import type { PluginHost } from "@/app/host"; +import { ESetupStep } from "@/features/setup/step-state"; import { renderEmptyState } from "./tab-states"; /** The Changes tab of a device that syncs nothing yet. */ 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 100% rename from packages/plugin/src/styles/source-control/file-rows.css rename to packages/plugin/src/features/source-control/styles/file-rows.css diff --git a/packages/plugin/src/styles/source-control/phone.css b/packages/plugin/src/features/source-control/styles/phone.css similarity index 100% rename from packages/plugin/src/styles/source-control/phone.css rename to packages/plugin/src/features/source-control/styles/phone.css 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 100% rename from packages/plugin/src/styles/source-control/summary.css rename to packages/plugin/src/features/source-control/styles/summary.css 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 95% rename from packages/plugin/src/ui/source-control/summary-card.ts rename to packages/plugin/src/features/source-control/summary-card.ts index 15e6835c..70cc506b 100644 --- a/packages/plugin/src/ui/source-control/summary-card.ts +++ b/packages/plugin/src/features/source-control/summary-card.ts @@ -1,14 +1,17 @@ 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 type { PluginHost } from "@/app/host"; +import { formatRelativeTime } from "@/core/shared"; +import { actionButton, textButton } from "@/core/ui"; +import { askSpaceGone } from "@/features/spaces/ui/space-gone"; +import { + type SyncStatusSnapshot, + splitSpaceErrors, +} from "@/features/sync/controller"; +import { deviceLabel } from "@/features/sync/identity/device"; +import { canPullAll, canPushAll } from "@/features/sync/runtime/sync-gates"; +import type { Manifest } from "@/features/sync/types"; +import type { SourceControlActions } from "./actions/actions"; +import { showIgnoredFiles, showSkippedFiles } from "./changes/excluded-files"; /** * The head of the Changes tab: what is pending, Push and Pull, what keeps files out and what stops a sync. diff --git a/packages/plugin/src/ui/source-control/tab-states.ts b/packages/plugin/src/features/source-control/tab-states.ts similarity index 94% rename from packages/plugin/src/ui/source-control/tab-states.ts rename to packages/plugin/src/features/source-control/tab-states.ts index 11b0f407..ebf0e766 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 { openPluginSettings } from "@/core/hub"; +import { OFFLINE_MESSAGE } from "@/core/shared"; +import { callout } from "@/core/ui"; interface StateAction { text: string; 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/ui/source-control/snapshot-menu.ts b/packages/plugin/src/features/source-control/timeline/snapshot-menu.ts similarity index 90% 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..c862c2a9 100644 --- a/packages/plugin/src/ui/source-control/snapshot-menu.ts +++ b/packages/plugin/src/features/source-control/timeline/snapshot-menu.ts @@ -1,7 +1,6 @@ import type { Menu } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import { notifyError, notifyInfo } from "@/ui/common"; -import { openPromptModal } from "@/ui/modals"; +import type { PluginHost } from "@/app/host"; +import { notifyError, notifyInfo, openPromptModal } from "@/core/ui"; interface SnapshotPin { snapshotId: string; 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 94% 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..88eb3aef 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,7 @@ 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 type { PluginHost } from "@/app/host"; +import { notifyError, notifyInfo, openConfirmModal } from "@/core/ui"; +import { confirmRestore } from "@/features/diff/restore-modal"; import { addSnapshotPinItems } from "./snapshot-menu"; import { describeRestorePlan, 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 95% 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..6b9e954b 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 { formatRelativeTime, formatTimestamp, pluralize } from "@/core/shared"; import type { + ChangeAction, + HistoryVersionRef, + ManifestEntry, 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 { deviceText } from "../changes/row-formatter"; +import { timeInDay } from "../history/day-groups"; +import type { HistoryDiffTarget } from "../view"; export interface TimelineFileRow { path: string; diff --git a/packages/plugin/src/ui/source-control/timeline-tab.ts b/packages/plugin/src/features/source-control/timeline/timeline-tab.ts similarity index 94% rename from packages/plugin/src/ui/source-control/timeline-tab.ts rename to packages/plugin/src/features/source-control/timeline/timeline-tab.ts index c7143333..7e76d493 100644 --- a/packages/plugin/src/ui/source-control/timeline-tab.ts +++ b/packages/plugin/src/features/source-control/timeline/timeline-tab.ts @@ -1,7 +1,6 @@ import { setIcon } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import { formatBytes } from "@/shared"; -import type { SnapshotListResult } from "@/sync/history"; +import type { PluginHost } from "@/app/host"; +import { formatBytes } from "@/core/shared"; import { appendIconButton, callout, @@ -9,19 +8,20 @@ import { 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"; +} from "@/core/ui"; +import type { SnapshotListResult } from "@/features/sync"; +import { STATUS_CLASSES, STATUS_LETTERS } from "../changes/row-formatter"; +import { groupRows } from "../history/day-groups"; +import { HistoryList } from "../history/history-list"; +import { RowPager } from "../history/row-pager"; +import { renderDelta } from "../row-parts"; import { renderEmptyState, renderHistoryOff, renderLoadError, renderLoading, -} from "./tab-states"; +} from "../tab-states"; +import type { HistoryDiffTarget } from "../view"; import { TimelineActions } from "./timeline-actions"; import { buildTimelineRows, diff --git a/packages/plugin/src/styles/source-control/timeline.css b/packages/plugin/src/features/source-control/timeline/timeline.css similarity index 100% rename from packages/plugin/src/styles/source-control/timeline.css rename to packages/plugin/src/features/source-control/timeline/timeline.css 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 96% 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..4133b431 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,6 @@ -import { formatBytes, formatRelativeTime, normalizePath } from "@/shared"; -import type { DeletedFile } from "@/sync/history"; -import { deviceText } from "./row-formatter"; +import { formatBytes, formatRelativeTime, normalizePath } from "@/core/shared"; +import type { DeletedFile } from "@/features/sync"; +import { deviceText } from "../changes/row-formatter"; export interface TrashRow { path: string; 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 96% 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..531c71a1 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,6 @@ 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 type { PluginHost } from "@/app/host"; +import { pluralize } from "@/core/shared"; import { appendIconButton, attempt, @@ -9,23 +8,27 @@ 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, + confirmRestore, +} from "@/features/diff/restore-modal"; +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 { renderEmptyState, renderHistoryOff, renderLoadError, renderLoading, -} from "./tab-states"; +} from "../tab-states"; import { buildTrashRows, resolveRestoreTarget, diff --git a/packages/plugin/src/ui/source-control/types.ts b/packages/plugin/src/features/source-control/types.ts similarity index 100% rename from packages/plugin/src/ui/source-control/types.ts rename to packages/plugin/src/features/source-control/types.ts diff --git a/packages/plugin/src/ui/source-control-view.ts b/packages/plugin/src/features/source-control/view.ts similarity index 95% rename from packages/plugin/src/ui/source-control-view.ts rename to packages/plugin/src/features/source-control/view.ts index 7cf487b8..d97ffd10 100644 --- a/packages/plugin/src/ui/source-control-view.ts +++ b/packages/plugin/src/features/source-control/view.ts @@ -5,25 +5,22 @@ import { setIcon, type WorkspaceLeaf, } from "obsidian"; +import type { PluginHost } from "@/app/host"; 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 { canSync } from "@/core/settings"; +import { redrawOnPhoneChange } from "@/core/ui"; +import type { HistoryChange } from "@/features/diff"; +import type { HistoryVersionRef, SyncStatusSnapshot } 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 { TimelineTab } from "./timeline/timeline-tab"; +import { TrashTab } from "./trash/trash-tab"; const ESourceTab = { Changes: "changes", diff --git a/packages/plugin/src/ui/source-control/virtual-list.ts b/packages/plugin/src/features/source-control/virtual-list.ts similarity index 100% rename from packages/plugin/src/ui/source-control/virtual-list.ts rename to packages/plugin/src/features/source-control/virtual-list.ts diff --git a/packages/plugin/src/features/spaces/README.md b/packages/plugin/src/features/spaces/README.md new file mode 100644 index 00000000..f98763ec --- /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/` and `pins/`. 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 89% rename from packages/plugin/src/spaces/access.ts rename to packages/plugin/src/features/spaces/access.ts index b69f4c52..49fa4c4b 100644 --- a/packages/plugin/src/spaces/access.ts +++ b/packages/plugin/src/features/spaces/access.ts @@ -1,12 +1,16 @@ -import { type EncryptionKey, importAesKey } from "@/crypto"; -import { deriveLiveKeys, type LiveKeys } from "@/crypto/live-keys"; import { - createBrokerAdapter, + 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"; diff --git a/packages/plugin/src/storage/adapters/share-broker.ts b/packages/plugin/src/features/spaces/broker/share-broker.ts similarity index 96% rename from packages/plugin/src/storage/adapters/share-broker.ts rename to packages/plugin/src/features/spaces/broker/share-broker.ts index 6f946886..58f84b54 100644 --- a/packages/plugin/src/storage/adapters/share-broker.ts +++ b/packages/plugin/src/features/spaces/broker/share-broker.ts @@ -6,23 +6,21 @@ import { requestUrl } from "obsidian"; -import { relayBase } from "@/shared"; -import type { S3StorageConfig } from "@/storage/config"; -import { - ShareRefusedError, - type StorageAdapter, - StorageRequestError, -} from "@/storage/types"; - +import { relayBase } from "@/core/shared"; +import type { S3StorageConfig } from "@/features/storage"; import { + createS3Store, endpointUrl, + errorCode, type S3Method, type S3RequestInput, + ShareRefusedError, + type StorageAdapter, + StorageHttpError, + 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; 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/index.ts b/packages/plugin/src/features/spaces/index.ts new file mode 100644 index 00000000..93d58ecc --- /dev/null +++ b/packages/plugin/src/features/spaces/index.ts @@ -0,0 +1,20 @@ +export { shareKey, shareStorage } from "./access"; +export { ADMIN_HEADER, type BrokerAdmin } from "./broker/share-broker"; +export { INVITE_ACTION, invitePassword } from "./invite"; +export { lastEditLabel, lastEditor } from "./last-edit"; +export { pauseOf } from "./partition"; +export { isSpaceRecord, 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 { openInvite } from "./ui/invites/invite-action"; +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/ui/common/last-edit.ts b/packages/plugin/src/features/spaces/last-edit.ts similarity index 84% rename from packages/plugin/src/ui/common/last-edit.ts rename to packages/plugin/src/features/spaces/last-edit.ts index 923dea31..56b116e2 100644 --- a/packages/plugin/src/ui/common/last-edit.ts +++ b/packages/plugin/src/features/spaces/last-edit.ts @@ -1,7 +1,7 @@ -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 type { PluginHost } from "@/app/host"; +import { formatRelativeTime } from "@/core/shared"; +import { type Space, spaceOf, VAULT_SPACE } from "@/features/sync/remote/space"; +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 { diff --git a/packages/plugin/src/spaces/owner.ts b/packages/plugin/src/features/spaces/owner.ts similarity index 94% rename from packages/plugin/src/spaces/owner.ts rename to packages/plugin/src/features/spaces/owner.ts index 24ae94ed..8c177014 100644 --- a/packages/plugin/src/spaces/owner.ts +++ b/packages/plugin/src/features/spaces/owner.ts @@ -1,12 +1,12 @@ import { sharePrefix } from "@mdsync/protocol"; -import { randomBytes, randomId } from "@/crypto"; +import { randomBytes, randomId } from "@/core/crypto"; +import { bytesToBase64, isNewer } from "@/core/utils"; import { EStorageBackend, type S3StorageConfig, type StorageAdapterConfig, -} from "@/storage"; -import { bytesToBase64, isNewer } from "@/utils"; +} from "@/features/storage"; import type { ShareLocation, SpaceRecord } from "./record"; diff --git a/packages/plugin/src/spaces/partition.ts b/packages/plugin/src/features/spaces/partition.ts similarity index 93% rename from packages/plugin/src/spaces/partition.ts rename to packages/plugin/src/features/spaces/partition.ts index 0e464a16..564c810f 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/remote/space"; import type { SpaceRecord } from "./record"; diff --git a/packages/plugin/src/spaces/record.ts b/packages/plugin/src/features/spaces/record.ts similarity index 99% rename from packages/plugin/src/spaces/record.ts rename to packages/plugin/src/features/spaces/record.ts index d355d2e5..e866c24f 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 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..3ac46a34 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/remote/space"; 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 91% rename from packages/plugin/src/plugin/share-moves.ts rename to packages/plugin/src/features/spaces/share-moves.ts index 90c9feaa..2cef490c 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 type { PluginHost } from "@/app/host"; +import { reportWarning } from "@/core/shared"; +import { notifyError, notifyInfo } from "@/core/ui"; +import { removeEmptyDir } from "@/core/vault"; +import { isUnder } from "@/features/sync/remote/space"; +import { mountError, spacesOf } from "./partition"; +import type { PendingMove, SpaceRecords } from "./records"; type MoveVault = Pick< Vault, diff --git a/packages/plugin/src/plugin/share-registration.ts b/packages/plugin/src/features/spaces/share-registration.ts similarity index 83% rename from packages/plugin/src/plugin/share-registration.ts rename to packages/plugin/src/features/spaces/share-registration.ts index 9fda0d4d..165b010e 100644 --- a/packages/plugin/src/plugin/share-registration.ts +++ b/packages/plugin/src/features/spaces/share-registration.ts @@ -1,14 +1,15 @@ -import type { LogService } from "@/core"; -import { ESyncLogOperation } from "@/logs/store"; +import type { LogService } from "@/core/logs"; +import { ESyncLogOperation } from "@/core/logs"; 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"; +} from "@/core/settings"; +import { errorMessage } from "@/core/shared"; +import type { Space } from "@/features/sync"; +import { listParticipants, registerShareStorage } from "./broker/share-broker"; +import { brokerStorage } 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 85% rename from packages/plugin/src/plugin/space-access.ts rename to packages/plugin/src/features/spaces/space-access.ts index bf449c47..a45eea67 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 { isStorageConfigured, type MdsyncSettings } from "@/core/settings"; +import { reportWarning } from "@/core/shared"; +import type { SyncController } from "@/features/sync/controller"; +import type { PassphraseManager } from "@/features/sync/remote/passphrase-manager"; +import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; +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 91% rename from packages/plugin/src/ui/shares/access-ended.ts rename to packages/plugin/src/features/spaces/ui/access-ended.ts index 4dab96c5..84607be0 100644 --- a/packages/plugin/src/ui/shares/access-ended.ts +++ b/packages/plugin/src/features/spaces/ui/access-ended.ts @@ -1,9 +1,9 @@ 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 type { PluginHost } from "@/app/host"; +import { openConfirmModal } from "@/core/ui"; +import type { Space } from "@/features/sync"; +import type { SpaceRecord } from "../record"; import { closeHere } from "./share-action"; diff --git a/packages/plugin/src/ui/shares/invite-action.ts b/packages/plugin/src/features/spaces/ui/invites/invite-action.ts similarity index 89% rename from packages/plugin/src/ui/shares/invite-action.ts rename to packages/plugin/src/features/spaces/ui/invites/invite-action.ts index 1b7dcd48..94a36591 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 type { PluginHost } from "@/app/host"; +import { randomId } from "@/core/crypto"; +import { ownerStorage, relayAdmin } from "@/core/settings"; +import { normalizePath, stripTrailingSlash } from "@/core/shared"; +import { notifyInfo, openConfirmModal, runWithNotice } from "@/core/ui"; +import { scopedPaths } from "@/features/sync/ui/push-action"; +import { + issueShareToken, + listParticipants, + registerShareStorage, + revokeParticipant, +} from "../../broker/share-broker"; 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 } from "../../owner"; +import { mountError } from "../../partition"; +import type { SpaceRecord } from "../../record"; +import { AcceptInviteModal } from "./invite-modal"; export interface CreatedInvite { link: string; 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/editor/read-only.ts b/packages/plugin/src/features/spaces/ui/read-only.ts similarity index 97% rename from packages/plugin/src/editor/read-only.ts rename to packages/plugin/src/features/spaces/ui/read-only.ts index 41308aaa..d3435088 100644 --- a/packages/plugin/src/editor/read-only.ts +++ b/packages/plugin/src/features/spaces/ui/read-only.ts @@ -1,14 +1,14 @@ import { EditorState, type Extension, Prec } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import { editorInfoField, type Plugin } from "obsidian"; +import type { PluginHost } from "@/app/host"; +import { LIVE_VIEWS } from "@/features/live/doc-types"; import { type ExcalidrawApi, type ExcalidrawView, isViewMode, - LIVE_VIEWS, setViewMode, -} from "@/live"; -import type { PluginHost } from "@/plugin/host"; +} from "@/features/live/drawing/excalidraw"; const LOADING_RETRY_MS = 500; diff --git a/packages/plugin/src/ui/shares/share-action.ts b/packages/plugin/src/features/spaces/ui/share-action.ts similarity index 88% rename from packages/plugin/src/ui/shares/share-action.ts rename to packages/plugin/src/features/spaces/ui/share-action.ts index e826997c..158a7a50 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 type { PluginHost } from "@/app/host"; +import { RELAY_TEXT } from "@/core/hub"; +import { isRelayConfigured, ownerStorage, relayAdmin } from "@/core/settings"; +import { relayBase } from "@/core/shared"; +import { notifyError, notifyInfo, openConfirmModal } from "@/core/ui"; +import { carryVaultIgnores } from "@/features/sync/ui/ignore-action"; +import { pushScope } from "@/features/sync/ui/push-action"; import { endShare, leaveShare, type Participant, 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 { createShare, ownerNameOf } from "../owner"; +import { mountError } from "../partition"; +import type { SpaceRecord } from "../record"; export function closeLabel({ access }: SpaceRecord): string { return access.kind === "owner" ? "Stop sharing" : "Leave"; diff --git a/packages/plugin/src/settings/sections/shares.ts b/packages/plugin/src/features/spaces/ui/shares-section.ts similarity index 92% rename from packages/plugin/src/settings/sections/shares.ts rename to packages/plugin/src/features/spaces/ui/shares-section.ts index 6ee3e937..3a6879eb 100644 --- a/packages/plugin/src/settings/sections/shares.ts +++ b/packages/plugin/src/features/spaces/ui/shares-section.ts @@ -1,15 +1,16 @@ import { Setting, type SettingDefinitionGroup } from "obsidian"; - import { 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 { EFieldKind } from "@/features/storage"; +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 { 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 87% rename from packages/plugin/src/ui/shares/space-gone.ts rename to packages/plugin/src/features/spaces/ui/space-gone.ts index 8ae0cb6e..fc5cbd78 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 type { PluginHost } from "@/app/host"; +import { openChoiceModal, runWithNotice } from "@/core/ui"; +import type { Space } from "@/features/sync"; const RESTORE = { key: "restore", 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..8af4d7e6 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 { renderAvatar } from "@/features/presence/ui/avatars"; +import type { Person } from "@/features/presence/views"; +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..46799bd7 100644 --- a/packages/plugin/src/ui/shares/share-modal.ts +++ b/packages/plugin/src/features/spaces/ui/window/share-modal.ts @@ -1,17 +1,8 @@ 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 type { PluginHost } from "@/app/host"; +import { isLinkState, RELAY_TEXT, relaySummary } from "@/core/hub"; +import { isRelayConfigured, relayAdmin } from "@/core/settings"; +import { errorMessage } from "@/core/shared"; import { alertLine, modalCard, @@ -21,21 +12,27 @@ 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/remote/space"; +import { + type BrokerAdmin, + listParticipants, + type Participant, +} from "../../broker/share-broker"; +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"; 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 80% rename from packages/plugin/src/ui/shares/share-window.ts rename to packages/plugin/src/features/spaces/ui/window/share-window.ts index 8a4b1aeb..18fd9975 100644 --- a/packages/plugin/src/ui/shares/share-window.ts +++ b/packages/plugin/src/features/spaces/ui/window/share-window.ts @@ -1,12 +1,12 @@ 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 type { PluginHost } from "@/app/host"; +import { ownerStorage } from "@/core/settings"; +import { notifyError } from "@/core/ui"; +import { isUnder } from "@/features/sync/remote/space"; +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. */ diff --git a/packages/plugin/src/features/status/index.ts b/packages/plugin/src/features/status/index.ts new file mode 100644 index 00000000..8e3b409f --- /dev/null +++ b/packages/plugin/src/features/status/index.ts @@ -0,0 +1,3 @@ +export { registerRibbon } from "./ribbon"; +export { registerStatusBar } from "./status-bar"; +export { openStatusMenu } from "./status-menu"; diff --git a/packages/plugin/src/ui/live/status/live-spaces.ts b/packages/plugin/src/features/status/live-spaces.ts similarity index 75% rename from packages/plugin/src/ui/live/status/live-spaces.ts rename to packages/plugin/src/features/status/live-spaces.ts index 1900cd3b..3b8078f9 100644 --- a/packages/plugin/src/ui/live/status/live-spaces.ts +++ b/packages/plugin/src/features/status/live-spaces.ts @@ -1,7 +1,7 @@ -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"; +import type { PluginHost } from "@/app/host"; +import { isLinkState, type LinkState } from "@/core/hub"; +import { isAtNote, type Person } from "@/features/presence"; +import { VAULT_SPACE } from "@/features/sync"; export interface CarriedSpace { id: string; diff --git a/packages/plugin/src/ui/live/status/relay-status.ts b/packages/plugin/src/features/status/relay-status.ts similarity index 91% rename from packages/plugin/src/ui/live/status/relay-status.ts rename to packages/plugin/src/features/status/relay-status.ts index 1b98a3e8..fa181fd9 100644 --- a/packages/plugin/src/ui/live/status/relay-status.ts +++ b/packages/plugin/src/features/status/relay-status.ts @@ -1,15 +1,14 @@ import type { Plugin } from "obsidian"; - -import { isConnected, type LinkState } from "@/hub/status"; -import type { PluginHost } from "@/plugin/host"; -import type { Person } from "@/presence"; +import type { PluginHost } from "@/app/host"; 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 { 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. */ 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 87% rename from packages/plugin/src/ui/ribbon.ts rename to packages/plugin/src/features/status/ribbon.ts index e0f3a427..b039341e 100644 --- a/packages/plugin/src/ui/ribbon.ts +++ b/packages/plugin/src/features/status/ribbon.ts @@ -1,9 +1,9 @@ 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"; export function registerRibbon( plugin: Plugin, diff --git a/packages/plugin/src/styles/status-bar.css b/packages/plugin/src/features/status/status-bar.css similarity index 100% rename from packages/plugin/src/styles/status-bar.css rename to packages/plugin/src/features/status/status-bar.css diff --git a/packages/plugin/src/ui/status-bar.ts b/packages/plugin/src/features/status/status-bar.ts similarity index 92% rename from packages/plugin/src/ui/status-bar.ts rename to packages/plugin/src/features/status/status-bar.ts index d9f29ff7..ba476d3f 100644 --- a/packages/plugin/src/ui/status-bar.ts +++ b/packages/plugin/src/features/status/status-bar.ts @@ -1,12 +1,11 @@ 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 type { PluginHost } from "@/app/host"; +import { RELATIVE_TIME_REFRESH_MS } from "@/core/constants"; +import { canSync } from "@/core/settings"; +import { formatRelativeTime, OFFLINE_MESSAGE, pluralize } from "@/core/shared"; +import { makeActivatable } from "@/core/ui"; +import { type SyncStatusSnapshot, splitSpaceErrors } from "@/features/sync"; +import { mountRelayStatus } from "./relay-status"; import { openStatusMenu, syncHeadline } from "./status-menu"; /** diff --git a/packages/plugin/src/ui/status-menu.ts b/packages/plugin/src/features/status/status-menu.ts similarity index 88% rename from packages/plugin/src/ui/status-menu.ts rename to packages/plugin/src/features/status/status-menu.ts index d4c4212f..c48d7f5a 100644 --- a/packages/plugin/src/ui/status-menu.ts +++ b/packages/plugin/src/features/status/status-menu.ts @@ -1,19 +1,23 @@ 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 type { PluginHost } from "@/app/host"; +import { SOURCE_CONTROL_VIEW_TYPE } from "@/core/constants"; +import { canSync } from "@/core/settings"; +import { formatRelativeTime, pluralize } from "@/core/shared"; +import { showMenuAt } from "@/core/ui"; import { openDiffView, openSourceControlChanges, openSourceControlView, -} from "./source-control-view"; +} from "@/features/source-control"; +import { + canPullAll, + canPushAll, + runPullAll, + runPushAll, + type SyncStatusSnapshot, + splitSpaceErrors, +} from "@/features/sync"; +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 { diff --git a/packages/plugin/src/ui/live/status/where-menu.ts b/packages/plugin/src/features/status/where-menu.ts similarity index 90% rename from packages/plugin/src/ui/live/status/where-menu.ts rename to packages/plugin/src/features/status/where-menu.ts index bb5ea5c9..b26369f2 100644 --- a/packages/plugin/src/ui/live/status/where-menu.ts +++ b/packages/plugin/src/features/status/where-menu.ts @@ -1,19 +1,16 @@ import type { Menu } from "obsidian"; - -import { isConnected } from "@/hub/status"; -import type { PluginHost } from "@/plugin/host"; -import { VAULT_SPACE } from "@/sync/space"; +import type { PluginHost } from "@/app/host"; import { - infoTitle, - lastEditLabel, - openNote, + isConnected, openPluginSettings, - personTitle, RELAY_TEXT, relayFixOf, UNREADABLE_TEXT, -} from "@/ui/common"; -import { LINK_LIVE_STATE, STATE_ICONS } from "@/ui/live/live-state"; +} from "@/core/hub"; +import { infoTitle, openNote, personTitle } from "@/core/ui"; +import { LINK_LIVE_STATE, STATE_ICONS } from "@/features/live"; +import { lastEditLabel } from "@/features/spaces"; +import { VAULT_SPACE } from "@/features/sync"; import { type CarriedSpace, carried, 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 94% 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..2621bd17 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,14 @@ 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 { randomBytes } from "@/core/crypto"; +import { relayBase } from "@/core/shared"; +import { EStorageBackend, type GoogleDriveStorageConfig } from "../config"; import { CONCURRENCY_FIELD, EFieldKind, type SettingsFieldSpec, -} from "@/storage/field-spec"; -import type { StorageAuthOutcome } from "@/storage/types"; +} 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 96% 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..fc1ad8c8 100644 --- a/packages/plugin/src/storage/adapters/google-drive-request.ts +++ b/packages/plugin/src/features/storage/backends/google-drive-request.ts @@ -1,5 +1,5 @@ import { type RequestUrlParam, requestUrl } from "obsidian"; -import { StorageRequestError } from "@/storage/types"; +import { StorageRequestError } from "../types"; import { isRetryableStatus, StorageHttpError, 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 98% 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..95744c37 100644 --- a/packages/plugin/src/storage/adapters/google-drive-upload.ts +++ b/packages/plugin/src/features/storage/backends/google-drive-upload.ts @@ -1,4 +1,4 @@ -import { toArrayBuffer } from "@/utils"; +import { toArrayBuffer } from "@/core/utils"; import { type AuthorizedRequest, driveRequest } from "./google-drive-request"; import { assertOk } from "./util"; diff --git a/packages/plugin/src/storage/adapters/google-drive.ts b/packages/plugin/src/features/storage/backends/google-drive.ts similarity index 98% rename from packages/plugin/src/storage/adapters/google-drive.ts rename to packages/plugin/src/features/storage/backends/google-drive.ts index 8326e1ab..b4fe4aa3 100644 --- a/packages/plugin/src/storage/adapters/google-drive.ts +++ b/packages/plugin/src/features/storage/backends/google-drive.ts @@ -1,10 +1,6 @@ import type { RequestUrlParam } from "obsidian"; -import type { GoogleDriveStorageConfig } from "@/storage/config"; -import type { - ConditionalRead, - ListedObject, - StorageAdapter, -} from "@/storage/types"; +import type { GoogleDriveStorageConfig } from "../config"; +import type { ConditionalRead, ListedObject, StorageAdapter } from "../types"; import { computeExpiresAt, googleAuthUrl, diff --git a/packages/plugin/src/storage/adapters/s3-signer.ts b/packages/plugin/src/features/storage/backends/s3-signer.ts similarity index 98% rename from packages/plugin/src/storage/adapters/s3-signer.ts rename to packages/plugin/src/features/storage/backends/s3-signer.ts index d3b6f2b6..36c5939d 100644 --- a/packages/plugin/src/storage/adapters/s3-signer.ts +++ b/packages/plugin/src/features/storage/backends/s3-signer.ts @@ -1,7 +1,7 @@ import { toHex } from "@mdsync/protocol"; -import { sha256Hex } from "@/crypto"; -import type { S3StorageConfig } from "@/storage/config"; +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 diff --git a/packages/plugin/src/storage/adapters/s3-store.ts b/packages/plugin/src/features/storage/backends/s3-store.ts similarity index 99% rename from packages/plugin/src/storage/adapters/s3-store.ts rename to packages/plugin/src/features/storage/backends/s3-store.ts index 64ba4336..04111aee 100644 --- a/packages/plugin/src/storage/adapters/s3-store.ts +++ b/packages/plugin/src/features/storage/backends/s3-store.ts @@ -1,12 +1,11 @@ import { requestUrl } from "obsidian"; - +import { toArrayBuffer } from "@/core/utils"; import { type ConditionalRead, type ListedObject, type StorageAdapter, StorageRequestError, -} from "@/storage/types"; -import { toArrayBuffer } from "@/utils"; +} from "../types"; import type { S3RequestInput, S3Signer } from "./s3-signer"; import { parseErrorCode, parseListObjects } from "./s3-xml"; diff --git a/packages/plugin/src/storage/adapters/s3-xml.ts b/packages/plugin/src/features/storage/backends/s3-xml.ts similarity index 98% rename from packages/plugin/src/storage/adapters/s3-xml.ts rename to packages/plugin/src/features/storage/backends/s3-xml.ts index 81a9c7c7..3078a301 100644 --- a/packages/plugin/src/storage/adapters/s3-xml.ts +++ b/packages/plugin/src/features/storage/backends/s3-xml.ts @@ -4,7 +4,7 @@ * match is exact for well-formed documents. */ -import type { ListedObject } from "@/storage/types"; +import type { ListedObject } from "../types"; import { dateOf } from "./util"; export interface ListPage { diff --git a/packages/plugin/src/storage/adapters/s3.ts b/packages/plugin/src/features/storage/backends/s3.ts similarity index 90% rename from packages/plugin/src/storage/adapters/s3.ts rename to packages/plugin/src/features/storage/backends/s3.ts index 38d04056..4492e85d 100644 --- a/packages/plugin/src/storage/adapters/s3.ts +++ b/packages/plugin/src/features/storage/backends/s3.ts @@ -1,12 +1,12 @@ -import { DEFAULT_CONCURRENCY } from "@/constants"; -import { normalizeKeyPrefix } from "@/shared"; -import { EStorageBackend, type S3StorageConfig } from "@/storage/config"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { normalizeKeyPrefix } from "@/core/shared"; +import { EStorageBackend, type S3StorageConfig } from "../config"; import { CONCURRENCY_FIELD, EFieldKind, type SettingsFieldSpec, -} from "@/storage/field-spec"; -import type { StorageAdapter } from "@/storage/types"; +} 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/util.ts b/packages/plugin/src/features/storage/backends/util.ts similarity index 99% rename from packages/plugin/src/storage/adapters/util.ts rename to packages/plugin/src/features/storage/backends/util.ts index 983756ad..8f2a3cd4 100644 --- a/packages/plugin/src/storage/adapters/util.ts +++ b/packages/plugin/src/features/storage/backends/util.ts @@ -1,4 +1,4 @@ -import { isNetworkError } from "@/shared"; +import { isNetworkError } from "@/core/shared"; const RETRY_DELAYS_MS: ReadonlyArray = [500, 2_000, 5_000]; diff --git a/packages/plugin/src/storage/adapters/webdav.ts b/packages/plugin/src/features/storage/backends/webdav.ts similarity index 97% rename from packages/plugin/src/storage/adapters/webdav.ts rename to packages/plugin/src/features/storage/backends/webdav.ts index a664f47f..69a16ce3 100644 --- a/packages/plugin/src/storage/adapters/webdav.ts +++ b/packages/plugin/src/features/storage/backends/webdav.ts @@ -1,19 +1,15 @@ import { type RequestUrlParam, requestUrl } from "obsidian"; -import { DEFAULT_CONCURRENCY } from "@/constants"; -import { normalizeKeyPrefix } from "@/shared"; -import { EStorageBackend, type WebDAVStorageConfig } from "@/storage/config"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { normalizeKeyPrefix } from "@/core/shared"; +import { bytesToBase64, toArrayBuffer } from "@/core/utils"; +import { EStorageBackend, type WebDAVStorageConfig } from "../config"; import { CONCURRENCY_FIELD, EFieldKind, type SettingsFieldSpec, -} from "@/storage/field-spec"; -import type { - ConditionalRead, - ListedObject, - StorageAdapter, -} from "@/storage/types"; -import { bytesToBase64, toArrayBuffer } from "@/utils"; +} from "../field-spec"; +import type { ConditionalRead, ListedObject, StorageAdapter } from "../types"; import { assertOk, dateOf, diff --git a/packages/plugin/src/settings/cloudflare-login.ts b/packages/plugin/src/features/storage/cloudflare/cloudflare-login.ts similarity index 88% rename from packages/plugin/src/settings/cloudflare-login.ts rename to packages/plugin/src/features/storage/cloudflare/cloudflare-login.ts index 4600ec24..273c2bf0 100644 --- a/packages/plugin/src/settings/cloudflare-login.ts +++ b/packages/plugin/src/features/storage/cloudflare/cloudflare-login.ts @@ -1,15 +1,15 @@ +import type { PluginHost } from "@/app/host"; import { type CloudflareAccount, type CloudflareApi, 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"; /** A per-Worker token or a role without the legacy Workers Scripts permission. */ const AUTH_ERROR = 10000; diff --git a/packages/plugin/src/settings/r2.ts b/packages/plugin/src/features/storage/cloudflare/r2-select.ts similarity index 83% rename from packages/plugin/src/settings/r2.ts rename to packages/plugin/src/features/storage/cloudflare/r2-select.ts index d93aa9b5..7ef8655c 100644 --- a/packages/plugin/src/settings/r2.ts +++ b/packages/plugin/src/features/storage/cloudflare/r2-select.ts @@ -1,25 +1,15 @@ -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 type { PluginHost } from "@/app/host"; +import { cloudflareApi, obsidianHttp, verifyToken } from "@/core/cloudflare"; +import { STORAGE_CHANGED_REASON } from "@/core/constants"; +import { sha256Hex } from "@/core/crypto"; +import { activeStorage, type MdsyncSettings } from "@/core/settings"; +import { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; +import { defaultS3Config } from "../backends/s3"; +import { isRefusedCredentials } from "../backends/util"; +import { EStorageBackend, type S3StorageConfig } from "../config"; +import { createStorageAdapter } from "../registry"; +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. */ 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 95% rename from packages/plugin/src/storage/field-spec.ts rename to packages/plugin/src/features/storage/field-spec.ts index 979d10f6..1afb03fb 100644 --- a/packages/plugin/src/storage/field-spec.ts +++ b/packages/plugin/src/features/storage/field-spec.ts @@ -1,4 +1,4 @@ -import { DEFAULT_CONCURRENCY } from "@/constants"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; export const EFieldKind = { Text: "text", diff --git a/packages/plugin/src/features/storage/index.ts b/packages/plugin/src/features/storage/index.ts new file mode 100644 index 00000000..31f0af0a --- /dev/null +++ b/packages/plugin/src/features/storage/index.ts @@ -0,0 +1,63 @@ +export { defaultS3Config } from "./backends/s3"; +export { + endpointUrl, + type S3Method, + type S3RequestInput, + signingRegion, +} from "./backends/s3-signer"; +export { createS3Store } from "./backends/s3-store"; +export { + errorCode, + isRefusedCredentials, + StorageHttpError, +} from "./backends/util"; +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 { CONCURRENCY_FIELD, EFieldKind } from "./field-spec"; +export { + type RecordKind, + readRecords, + removeRecord, + writeRecord, +} from "./records"; +export { + type CompactStorageConfig, + compactStorageConfig, + createStorageAdapter, + describeStorageTarget, + getDescriptor, + handleStorageProtocol, + isAdapterConfigured, + isKnownBackend, + storageDefaults, + storageIdentity, +} from "./registry"; +export { createStorageRefused } from "./storage-refused"; +export { + type ConditionalRead, + type ObjectStorage, + ShareRefusedError, + type StorageAdapter, + StorageRequestError, +} from "./types"; +export { backendSection } from "./ui/backend-section"; +export { + type ConnectionTestResult, + type RelayTestResult, + testConnection, + testRelay, +} from "./ui/connection-test"; +export { openStorageRefusedModal } from "./ui/storage-refused-modal"; diff --git a/packages/plugin/src/storage/records.ts b/packages/plugin/src/features/storage/records.ts similarity index 96% rename from packages/plugin/src/storage/records.ts rename to packages/plugin/src/features/storage/records.ts index 1e099962..9f78551b 100644 --- a/packages/plugin/src/storage/records.ts +++ b/packages/plugin/src/features/storage/records.ts @@ -3,10 +3,10 @@ * 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"; 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/plugin/storage-refused.ts b/packages/plugin/src/features/storage/storage-refused.ts similarity index 78% rename from packages/plugin/src/plugin/storage-refused.ts rename to packages/plugin/src/features/storage/storage-refused.ts index e11fa22d..09ac8fb2 100644 --- a/packages/plugin/src/plugin/storage-refused.ts +++ b/packages/plugin/src/features/storage/storage-refused.ts @@ -1,7 +1,7 @@ -import type { PluginHost } from "@/plugin/host"; -import { activeStorage } from "@/settings/model"; -import { type Space, VAULT_SPACE } from "@/sync/space"; -import { openStorageRefusedModal } from "@/ui"; +import type { PluginHost } from "@/app/host"; +import { activeStorage } from "@/core/settings"; +import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; +import { openStorageRefusedModal } from "./ui/storage-refused-modal"; const VOLATILE = new Set(["accessToken", "expiresAt"]); 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/settings/sections/backend.ts b/packages/plugin/src/features/storage/ui/backend-section.ts similarity index 85% rename from packages/plugin/src/settings/sections/backend.ts rename to packages/plugin/src/features/storage/ui/backend-section.ts index ab268e04..37f728ab 100644 --- a/packages/plugin/src/settings/sections/backend.ts +++ b/packages/plugin/src/features/storage/ui/backend-section.ts @@ -1,15 +1,10 @@ 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 { getDescriptor, listBackends } from "../registry"; +import { testConnection } from "./connection-test"; import { storageRows } from "./storage-fields"; export function backendSection(ctx: FieldContext): SettingDefinitionGroup { diff --git a/packages/plugin/src/settings/connection-test.ts b/packages/plugin/src/features/storage/ui/connection-test.ts similarity index 94% rename from packages/plugin/src/settings/connection-test.ts rename to packages/plugin/src/features/storage/ui/connection-test.ts index 3e57ff4b..e59bf288 100644 --- a/packages/plugin/src/settings/connection-test.ts +++ b/packages/plugin/src/features/storage/ui/connection-test.ts @@ -1,23 +1,23 @@ import { requestUrl } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; +import type { PluginHost } from "@/app/host"; import { activeStorage, isRelayConfigured, type RelayConfig, -} from "@/settings/model"; +} from "@/core/settings"; import { errorMessage, isCleartextRemote, relayBase, reportWarning, -} from "@/shared"; +} from "@/core/shared"; +import { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; import { createStorageAdapter, describeStorageTarget, isAdapterConfigured, -} from "@/storage"; -import { REMOTE_MANIFEST_KEY } from "@/sync/constants"; +} from "../registry"; export interface ConnectionTestResult { ok: boolean; diff --git a/packages/plugin/src/settings/sections/storage-fields.ts b/packages/plugin/src/features/storage/ui/storage-fields.ts similarity index 90% rename from packages/plugin/src/settings/sections/storage-fields.ts rename to packages/plugin/src/features/storage/ui/storage-fields.ts index f8acbaca..77ebf027 100644 --- a/packages/plugin/src/settings/sections/storage-fields.ts +++ b/packages/plugin/src/features/storage/ui/storage-fields.ts @@ -1,16 +1,12 @@ 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"; +import type { PluginHost } from "@/app/host"; +import { onSettled, type SettingsRow } from "@/core/settings"; +import { notifyError, notifyInfo } from "@/core/ui"; +import { googleLoginUrl } from "../backends/google-drive-auth"; +import { EStorageBackend, type GoogleDriveStorageConfig } from "../config"; +import { EFieldKind, type SettingsFieldSpec } from "../field-spec"; +import { getDescriptor } from "../registry"; export function storageRows( plugin: PluginHost, 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 86% 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..9a20dd25 100644 --- a/packages/plugin/src/ui/modals/storage-refused-modal.ts +++ b/packages/plugin/src/features/storage/ui/storage-refused-modal.ts @@ -1,19 +1,18 @@ 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 type { PluginHost } from "@/app/host"; +import { openPluginSettings } from "@/core/hub"; +import { activeStorage } from "@/core/settings"; 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 { describeStorageTarget } from "../registry"; const FIELD = "Token value or secret access key"; const UPDATE = "Update keys"; diff --git a/packages/plugin/src/features/sync/README.md b/packages/plugin/src/features/sync/README.md new file mode 100644 index 00000000..64bfdb2b --- /dev/null +++ b/packages/plugin/src/features/sync/README.md @@ -0,0 +1,92 @@ +# 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 | +| `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), `features/sync/automation/auto-push.ts` (bulk-deletion hold) | +| `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` | +| `history/` | change log, queries, replay, vault restore plan, GC | +| `ui/` | menu items, modals, the maintenance section | + +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`, 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: 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. + +## 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 after the change record rolls off. 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 + +`history.json.enc` is one encrypted object: snapshot entries newest first plus a change record per snapshot (`added`, `modified {from, to}`, `deleted`), each the diff from that snapshot's parent. Both sides are stored so one version restores without replaying, and a lost update (log writes are read-modify-write, verified by `updateHistoryLog`, not serialized by the manifest guard) shows as a parent/child gap that `contiguousLength` stops at. Pins store a full manifest under `pins/`, so they outlive the chain. + +Windows: a blob younger than `SETTLED_AFTER_MS` (24 h) is never swept, a record younger than that is never evicted, deep clean deletes nothing written in the last day. 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. A push by another device that re-uploaded an old hash is covered only by those windows. + +## Other flows + +- Reset and adopt (`features/sync/operations/flows.ts`): reset deletes the vault storage's manifest, log, 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 (`deep` also hashes it); deep clean removes unreachable settled objects and pins. +- 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. + +## 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 90% rename from packages/plugin/src/sync/auto-merge.ts rename to packages/plugin/src/features/sync/apply/auto-merge.ts index 019daa10..a43fa31b 100644 --- a/packages/plugin/src/sync/auto-merge.ts +++ b/packages/plugin/src/features/sync/apply/auto-merge.ts @@ -1,23 +1,23 @@ -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, sortedByPath } 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 { 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 { tryAutoMergeConflict } from "./conflict-merge"; export async function autoMergeOp( deps: EngineDependencies, diff --git a/packages/plugin/src/sync/conflict-copy.ts b/packages/plugin/src/features/sync/apply/conflict-copy.ts similarity index 97% rename from packages/plugin/src/sync/conflict-copy.ts rename to packages/plugin/src/features/sync/apply/conflict-copy.ts index 6797678f..cb77c309 100644 --- a/packages/plugin/src/sync/conflict-copy.ts +++ b/packages/plugin/src/features/sync/apply/conflict-copy.ts @@ -1,5 +1,5 @@ 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; diff --git a/packages/plugin/src/sync/conflict-merge.ts b/packages/plugin/src/features/sync/apply/conflict-merge.ts similarity index 83% rename from packages/plugin/src/sync/conflict-merge.ts rename to packages/plugin/src/features/sync/apply/conflict-merge.ts index fa7e577b..dfd1a264 100644 --- a/packages/plugin/src/sync/conflict-merge.ts +++ b/packages/plugin/src/features/sync/apply/conflict-merge.ts @@ -1,14 +1,14 @@ import type { DataAdapter } from "obsidian"; -import { isDrawing, mergeDrawings } from "@/drawing"; -import { withEolOf } from "@/utils"; +import { isDrawing, mergeDrawings } from "@/core/drawing"; +import { withEolOf } from "@/core/utils"; import { loadLocalText, loadRemoteText, type RemoteFetchOptions, -} from "./content"; -import { buildMergeSession, countUnresolved } from "./merge-model"; -import type { Conflict } from "./types"; +} from "../changes/content"; +import { buildMergeSession, countUnresolved } from "../hunks/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 diff --git a/packages/plugin/src/sync/pull-moves.ts b/packages/plugin/src/features/sync/apply/pull-moves.ts similarity index 94% rename from packages/plugin/src/sync/pull-moves.ts rename to packages/plugin/src/features/sync/apply/pull-moves.ts index 3d3e39e6..2f1631d3 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 { entryAt, reportWarning } from "@/core/shared"; import { diskRefuses, ensureDir, @@ -12,12 +12,12 @@ 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 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 89% rename from packages/plugin/src/sync/pull.ts rename to packages/plugin/src/features/sync/apply/pull.ts index b644d12b..f879e035 100644 --- a/packages/plugin/src/sync/pull.ts +++ b/packages/plugin/src/features/sync/apply/pull.ts @@ -1,17 +1,17 @@ /** 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, entryAt } from "@/core/shared"; +import { runWithConcurrency, runWithFileConcurrency } from "@/core/utils"; +import { deletePath, unchangedSince } from "@/core/vault"; +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 { objectKey } from "../remote/manifest"; +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; diff --git a/packages/plugin/src/sync/auto-push.ts b/packages/plugin/src/features/sync/automation/auto-push.ts similarity index 95% rename from packages/plugin/src/sync/auto-push.ts rename to packages/plugin/src/features/sync/automation/auto-push.ts index 7d5c7277..e7eadefa 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[]; diff --git a/packages/plugin/src/sync/scheduler.ts b/packages/plugin/src/features/sync/automation/scheduler.ts similarity index 97% rename from packages/plugin/src/sync/scheduler.ts rename to packages/plugin/src/features/sync/automation/scheduler.ts index 0ff241d3..762cc241 100644 --- a/packages/plugin/src/sync/scheduler.ts +++ b/packages/plugin/src/features/sync/automation/scheduler.ts @@ -1,8 +1,8 @@ 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 { canSync, type MdsyncSettings } from "@/core/settings"; +import type { SyncController, SyncStatusSnapshot } from "../controller"; +import { type Space, spaceOf, VAULT_SPACE } from "../remote/space"; const AUTO_PULL_STARTUP_DELAY_MS = 3_000; 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 93% rename from packages/plugin/src/sync/content.ts rename to packages/plugin/src/features/sync/changes/content.ts index 47be1d458f8ef70e4a2ad8995887aed734e0a1bc..6b04748ec31d8a3c8bc9bd1ec377c7525dce5994 100644 GIT binary patch delta 240 zcmXwxu}TCn6h+BcxEn;oLfhE|(Umm;TfsuB-NHt}#^xE{4#7z>yu4W*#M0g&Tlxuh z{(v9g&-e#M!RnrKx!jl8`|Q=N1;YORaKq%(cLWdCSLs5W%D-X>ZO#4LWNU%IEn(D= z13`spM;zQJrA_dW!E+p+Nb8zFTyoc7`6P#D5b=_+nabgL4c5gBS3nhVhHJ8n^U#uq zdMcmG1qD}*^C6)LOQbHX7yE->b%8OdVzT)!IyPW1t;F6S@1qF~rcbe(d@&NL|2p1Q U`qp}&?g$?leYC-Utcvf^5B(NV?f?J) delta 178 zcmZ4E+3GnVcVdwSdrDDad1hYv#CMwP#U=SgiRr16%bAQM9Q2DT^OE(GGV>CPDs@vU zN>cNRGxPI`C#y4Rut6jz2QrFG++e~{mROooqMw;RS&&JU-9aDBoovS>Zs3$yoElt` zTA-ugoRgTDTdboHl30|UTB4&6UX)pq>Xlzwl$V&JP^*wul%K1hq&Imrqx$4qjGC; 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 100% rename from packages/plugin/src/sync/constants.ts rename to packages/plugin/src/features/sync/constants.ts diff --git a/packages/plugin/src/sync/controller.ts b/packages/plugin/src/features/sync/controller.ts similarity index 94% rename from packages/plugin/src/sync/controller.ts rename to packages/plugin/src/features/sync/controller.ts index 9f2a6ef3..d7a1de05 100644 --- a/packages/plugin/src/sync/controller.ts +++ b/packages/plugin/src/features/sync/controller.ts @@ -1,31 +1,38 @@ -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 type { LocalOpener } from "@/app/session-factory"; +import { ESyncLogOperation } from "@/core/logs"; +import type { SettingsSyncCategories } from "@/core/settings"; +import { + type AutoPushSelector, + createAutoPushSelector, +} from "./automation/auto-push"; +import { clearRemoteTextCache } from "./changes/content"; import type { EngineDependencies } from "./engine"; -import type { HunkSelection } from "./hunks"; +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,7 +48,6 @@ 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"; export const EConflictStrategy = { diff --git a/packages/plugin/src/sync/engine.ts b/packages/plugin/src/features/sync/engine.ts similarity index 89% rename from packages/plugin/src/sync/engine.ts rename to packages/plugin/src/features/sync/engine.ts index a60c98e1..df43fb08 100644 --- a/packages/plugin/src/sync/engine.ts +++ b/packages/plugin/src/features/sync/engine.ts @@ -1,32 +1,34 @@ 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, encryptBytes, sha256Hex } from "@/core/crypto"; +import { sceneOfBytes } from "@/core/drawing"; +import { entryAt, reportWarning, sortedByPath } from "@/core/shared"; +import { runWithFileConcurrency } from "@/core/utils"; +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 { skipUnholdableNames } from "./changes/remote-names"; +import { REMOTE_OBJECTS_PREFIX } from "./constants"; +import { publishManifestWithHistory } from "./history/publish"; +import type { HistoryConfig } from "./history/types"; +import { attribute, publisher } from "./identity/authors"; 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 +41,6 @@ import { type ManifestEntry, type SessionState, } from "./types"; -import { forgetUploads, rememberUpload, uploadedHere } from "./uploads"; export interface EngineDependencies { space: Space; diff --git a/packages/plugin/src/sync/history/changes.ts b/packages/plugin/src/features/sync/history/changes.ts similarity index 96% rename from packages/plugin/src/sync/history/changes.ts rename to packages/plugin/src/features/sync/history/changes.ts index 83bf726f..4f176eca 100644 --- a/packages/plugin/src/sync/history/changes.ts +++ b/packages/plugin/src/features/sync/history/changes.ts @@ -1,5 +1,5 @@ -import { entryAt } from "@/shared"; -import type { Manifest, ManifestEntry } from "@/sync/types"; +import { entryAt } from "@/core/shared"; +import type { Manifest, ManifestEntry } from "../types"; import type { SnapshotChanges, SnapshotEntry } from "./types"; diff --git a/packages/plugin/src/sync/history/gc.ts b/packages/plugin/src/features/sync/history/gc.ts similarity index 95% rename from packages/plugin/src/sync/history/gc.ts rename to packages/plugin/src/features/sync/history/gc.ts index 511f9dee..498f34e8 100644 --- a/packages/plugin/src/sync/history/gc.ts +++ b/packages/plugin/src/features/sync/history/gc.ts @@ -1,15 +1,15 @@ 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"; +} from "@/core/constants"; +import type { EncryptionKey } from "@/core/crypto"; +import { reportWarning } from "@/core/shared"; +import { runWithConcurrency } from "@/core/utils"; +import type { ObjectStorage } from "@/features/storage"; +import { REMOTE_OBJECTS_PREFIX } from "../constants"; +import { fetchRemoteManifest, objectKey } from "../remote/manifest"; +import { keysByAge, SETTLED_AFTER_MS } from "../remote/uploads"; +import type { Manifest } from "../types"; import { collectChangeHashes } from "./changes"; import { pinKey, readPinManifest, updateHistoryLog } from "./store"; import type { HistoryLog, SnapshotEntry } from "./types"; diff --git a/packages/plugin/src/sync/history/publish.ts b/packages/plugin/src/features/sync/history/publish.ts similarity index 85% rename from packages/plugin/src/sync/history/publish.ts rename to packages/plugin/src/features/sync/history/publish.ts index 1fddfe0d..620feea4 100644 --- a/packages/plugin/src/sync/history/publish.ts +++ b/packages/plugin/src/features/sync/history/publish.ts @@ -1,8 +1,8 @@ -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 type { EncryptionKey } from "@/core/crypto"; +import { reportWarning } from "@/core/shared"; +import type { ObjectStorage } from "@/features/storage"; +import { publishManifestWithGuard } from "../remote/manifest"; +import type { Manifest } from "../types"; import { diffManifests } from "./changes"; import { collectGarbage, shouldRunGc } from "./gc"; import { prependSnapshot, updateHistoryLog } from "./store"; diff --git a/packages/plugin/src/sync/history/query.ts b/packages/plugin/src/features/sync/history/query.ts similarity index 96% rename from packages/plugin/src/sync/history/query.ts rename to packages/plugin/src/features/sync/history/query.ts index 579ee56c..86ed4d5c 100644 --- a/packages/plugin/src/sync/history/query.ts +++ b/packages/plugin/src/features/sync/history/query.ts @@ -1,10 +1,10 @@ -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 type { EncryptionKey } from "@/core/crypto"; +import { entryAt } from "@/core/shared"; +import { runWithConcurrency } from "@/core/utils"; +import type { ObjectStorage } from "@/features/storage"; +import { loadRemoteBytes } from "../changes/content"; +import { fetchRemoteManifest } from "../remote/manifest"; +import type { Manifest, ManifestEntry } from "../types"; import { contiguousLength, undoChangesForPath } from "./changes"; import { readHistoryLog, readPinManifest } from "./store"; import type { diff --git a/packages/plugin/src/sync/history/replay.ts b/packages/plugin/src/features/sync/history/replay.ts similarity index 95% rename from packages/plugin/src/sync/history/replay.ts rename to packages/plugin/src/features/sync/history/replay.ts index fc678ff2..86b75c08 100644 --- a/packages/plugin/src/sync/history/replay.ts +++ b/packages/plugin/src/features/sync/history/replay.ts @@ -1,4 +1,4 @@ -import type { Manifest } from "@/sync/types"; +import type { Manifest } from "../types"; import { contiguousLength, undoChanges } from "./changes"; import type { HistoryLog } from "./types"; diff --git a/packages/plugin/src/sync/history/restore-vault.ts b/packages/plugin/src/features/sync/history/restore-vault.ts similarity index 94% rename from packages/plugin/src/sync/history/restore-vault.ts rename to packages/plugin/src/features/sync/history/restore-vault.ts index 7cbdee39..f39c82ac 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 "@/core/shared"; +import type { LocalSnapshot, Manifest, ManifestEntry } from "../types"; export interface VaultRestoreWrite { path: string; diff --git a/packages/plugin/src/sync/history/store.ts b/packages/plugin/src/features/sync/history/store.ts similarity index 95% rename from packages/plugin/src/sync/history/store.ts rename to packages/plugin/src/features/sync/history/store.ts index c9e7a1fb..cce0746e 100644 --- a/packages/plugin/src/sync/history/store.ts +++ b/packages/plugin/src/features/sync/history/store.ts @@ -1,15 +1,15 @@ -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 { decryptJson, type EncryptionKey, encryptJson } from "@/core/crypto"; +import { errorMessage, reportWarning } from "@/core/shared"; +import type { ObjectStorage } from "@/features/storage"; +import { REMOTE_HISTORY_LOG_KEY, REMOTE_PINS_PREFIX } from "../constants"; +import { fetchRemoteManifest, readIfChanged } from "../remote/manifest"; import { historyLogToSpace, historyLogToVault, manifestToSpace, manifestToVault, -} from "@/sync/space-paths"; -import type { Manifest } from "@/sync/types"; +} from "../remote/space-paths"; +import type { Manifest } from "../types"; import { replayTo } from "./replay"; import type { HistoryLog, SnapshotChanges, SnapshotEntry } from "./types"; diff --git a/packages/plugin/src/sync/history/types.ts b/packages/plugin/src/features/sync/history/types.ts similarity index 97% rename from packages/plugin/src/sync/history/types.ts rename to packages/plugin/src/features/sync/history/types.ts index 312b2f64..40e4e1d7 100644 --- a/packages/plugin/src/sync/history/types.ts +++ b/packages/plugin/src/features/sync/history/types.ts @@ -1,4 +1,4 @@ -import type { EFileKind, ManifestEntry } from "@/sync/types"; +import type { EFileKind, ManifestEntry } from "../types"; export interface HistoryConfig { maxSnapshots: number; 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/sync/diff-cache.ts b/packages/plugin/src/features/sync/hunks/diff-cache.ts similarity index 95% rename from packages/plugin/src/sync/diff-cache.ts rename to packages/plugin/src/features/sync/hunks/diff-cache.ts index 805e8515..a4aa1f4c 100644 --- a/packages/plugin/src/sync/diff-cache.ts +++ b/packages/plugin/src/features/sync/hunks/diff-cache.ts @@ -1,5 +1,6 @@ -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 { buildConflictDiff, buildLocalChangeDiff, @@ -7,7 +8,6 @@ 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. */ const DIFF_CACHE_MAX_BYTES = 8 * 1024 * 1024; diff --git a/packages/plugin/src/sync/hunks.ts b/packages/plugin/src/features/sync/hunks/hunks.ts similarity index 99% rename from packages/plugin/src/sync/hunks.ts rename to packages/plugin/src/features/sync/hunks/hunks.ts index b1356a9f..98200496 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", diff --git a/packages/plugin/src/sync/merge-model.ts b/packages/plugin/src/features/sync/hunks/merge-model.ts similarity index 99% rename from packages/plugin/src/sync/merge-model.ts rename to packages/plugin/src/features/sync/hunks/merge-model.ts index 5d033f82..01f4e87e 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"; diff --git a/packages/plugin/src/sync/projection.ts b/packages/plugin/src/features/sync/hunks/projection.ts similarity index 97% rename from packages/plugin/src/sync/projection.ts rename to packages/plugin/src/features/sync/hunks/projection.ts index fb07e0c4..d9a717ee 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,17 @@ 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 { type ComputedHunks, computeHunks } from "./hunks"; export const EDiffDirection = { Local: "local", 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/index.ts b/packages/plugin/src/features/sync/index.ts new file mode 100644 index 00000000..8df958a1 --- /dev/null +++ b/packages/plugin/src/features/sync/index.ts @@ -0,0 +1,135 @@ +export { registerScheduler } from "./automation/scheduler"; +export { + bytesToText, + clearRemoteTextCache, + textToBytes, +} from "./changes/content"; +export { movesByPath } from "./changes/moves"; +export { HUNK_TEXT_MAX_BYTES, REMOTE_MANIFEST_KEY } from "./constants"; +export { + EConflictStrategy, + SyncController, + type SyncOperationResult, + type SyncStatusSnapshot, + splitSpaceErrors, +} from "./controller"; +export type { CompareResult, EngineDependencies } from "./engine"; +export { clampMaxSnapshots } from "./history/gc"; +export type { VaultRestorePlan } from "./history/restore-vault"; +export type { + DeletedFile, + DeletedFilesResult, + FileVersion, + SnapshotChanges, + SnapshotListResult, + SnapshotSummary, +} from "./history/types"; +export { + computeHunks, + DIFF_BUDGET, + type HunkSegment, + type HunkSelection, + hunkSegments, + type LineRange, + type SyncHunk, +} from "./hunks/hunks"; +export { + applyPlan, + buildMergeSession, + countUnresolved, + type EditPlan, + type EMergeSide, + type ESideStatus, + isResolved, + MERGE_SIDES, + type MergeChange, + patchTaken, + revertPlan, + type Span, + type StatusPatch, + sameLines, + sameStatus, + snapToLines, + type Taken, + type TakenPatch, + 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 { + 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 { configurationScopeSection } 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 { + type Conflict, + type DiffResult, + EChangeType, + type FileChange, + type LiveMark, + type Manifest, + type ManifestAuthor, + type ManifestEntry, + type Move, + type SkippedFile, +} from "./types"; +export { type ChangeAction, changeActionOf } from "./ui/change-action"; +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 { 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 98% rename from packages/plugin/src/sync/live-notes.ts rename to packages/plugin/src/features/sync/live-notes.ts index 445633cd..95990473 100644 --- a/packages/plugin/src/sync/live-notes.ts +++ b/packages/plugin/src/features/sync/live-notes.ts @@ -3,7 +3,7 @@ * room snapshot; a note with an open room is never written. */ -import { entryAt } from "@/shared"; +import { entryAt } from "@/core/shared"; import { bytesToText, @@ -13,7 +13,7 @@ import { untouchedSince, type WriteOptions, writeFetched, -} from "./content"; +} from "./changes/content"; import type { CompareResult, EngineDependencies } from "./engine"; import type { LiveMark, ManifestEntry } from "./types"; diff --git a/packages/plugin/src/sync/operations/config-reset.ts b/packages/plugin/src/features/sync/operations/config-reset.ts similarity index 83% rename from packages/plugin/src/sync/operations/config-reset.ts rename to packages/plugin/src/features/sync/operations/config-reset.ts index 332d43a4..4da0bd48 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 { MANIFEST_VERSION } from "../constants"; import { type CompareResult, compare, type EngineDependencies, -} from "@/sync/engine"; -import { publishManifestWithHistory } from "@/sync/history"; -import { buildManifest } from "@/sync/manifest"; +} from "../engine"; +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( 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 94% rename from packages/plugin/src/sync/operations/hunks.ts rename to packages/plugin/src/features/sync/operations/hunks.ts index 7fa7d7d4..59fe6bfc 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,13 @@ 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 { + advanceBaselineForPaths, + buildSessionState, + mergeWrittenIntoCache, +} from "../remote/baseline"; +import type { Manifest, ManifestEntry } from "../types"; import { assertSidesUnchanged, EHunkPair, diff --git a/packages/plugin/src/sync/operations/pull.ts b/packages/plugin/src/features/sync/operations/pull.ts similarity index 87% rename from packages/plugin/src/sync/operations/pull.ts rename to packages/plugin/src/features/sync/operations/pull.ts index 277dd88f..c3e0980c 100644 --- a/packages/plugin/src/sync/operations/pull.ts +++ b/packages/plugin/src/features/sync/operations/pull.ts @@ -1,8 +1,8 @@ -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 { entryAt, formatBytes, sumBytes } from "@/core/shared"; +import { pullPaths } from "../apply/pull"; +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 92% rename from packages/plugin/src/sync/operations/resolve.ts rename to packages/plugin/src/features/sync/operations/resolve.ts index bb97ec1d..4d63b337 100644 --- a/packages/plugin/src/sync/operations/resolve.ts +++ b/packages/plugin/src/features/sync/operations/resolve.ts @@ -1,33 +1,33 @@ -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 { entryAt } from "@/core/shared"; +import { runWithFileConcurrency } from "@/core/utils"; +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 { 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 { + advanceBaselineForPaths, + buildSessionState, + mergeWrittenIntoCache, +} from "../remote/baseline"; +import type { ManifestEntry } from "../types"; import type { Operation, OperationContext, OperationOutcome } from "./types"; const EDITED_SINCE = diff --git a/packages/plugin/src/sync/operations/revert.ts b/packages/plugin/src/features/sync/operations/revert.ts similarity index 88% rename from packages/plugin/src/sync/operations/revert.ts rename to packages/plugin/src/features/sync/operations/revert.ts index 6e5d56a3..5267a164 100644 --- a/packages/plugin/src/sync/operations/revert.ts +++ b/packages/plugin/src/features/sync/operations/revert.ts @@ -1,13 +1,13 @@ -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, runWithFileConcurrency } from "@/core/utils"; +import { trashPath } from "@/core/vault"; +import { renameLocal } from "../apply/pull-moves"; +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..d4267d4a 100644 --- a/packages/plugin/src/sync/cut-short.ts +++ b/packages/plugin/src/features/sync/recovery/cut-short.ts @@ -4,21 +4,21 @@ */ 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 { entryAt, reportWarning } from "@/core/shared"; +import { readBinary, writeBinary } from "@/core/vault"; +import { bytesToText, withLocalMtime } from "../changes/content"; +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 94% rename from packages/plugin/src/sync/baseline.ts rename to packages/plugin/src/features/sync/remote/baseline.ts index c93c8079..b2e5d636 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 { entryAt, sortedByPath } from "@/core/shared"; +import { diskRefuses } from "@/core/vault"; +import { isUnderUnreadableDir } from "../changes/diff"; +import type { CompareResult } 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, 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..f7517b0c 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 "@/core/shared"; +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 94% rename from packages/plugin/src/sync/keyfile.ts rename to packages/plugin/src/features/sync/remote/keyfile.ts index 75e560e3..9e65a4fd 100644 --- a/packages/plugin/src/sync/keyfile.ts +++ b/packages/plugin/src/features/sync/remote/keyfile.ts @@ -1,18 +1,19 @@ import { decryptBytes, 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 "../session"; const KEYFILE_VERSION = 1; diff --git a/packages/plugin/src/sync/manifest.ts b/packages/plugin/src/features/sync/remote/manifest.ts similarity index 96% rename from packages/plugin/src/sync/manifest.ts rename to packages/plugin/src/features/sync/remote/manifest.ts index fabf17df..4272f28f 100644 --- a/packages/plugin/src/sync/manifest.ts +++ b/packages/plugin/src/features/sync/remote/manifest.ts @@ -3,16 +3,16 @@ import { type EncryptionKey, encryptJson, randomId, -} from "@/crypto"; -import type { ConditionalRead, ObjectStorage } from "@/storage/types"; +} from "@/core/crypto"; +import type { ConditionalRead, ObjectStorage } from "@/features/storage"; import { MANIFEST_VERSION, REMOTE_MANIFEST_KEY, REMOTE_OBJECTS_PREFIX, -} from "@/sync/constants"; -import { defaultDeviceName } from "./device"; +} 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< diff --git a/packages/plugin/src/core/passphrase-manager.ts b/packages/plugin/src/features/sync/remote/passphrase-manager.ts similarity index 95% rename from packages/plugin/src/core/passphrase-manager.ts rename to packages/plugin/src/features/sync/remote/passphrase-manager.ts index 9754d62b..56d95a6c 100644 --- a/packages/plugin/src/core/passphrase-manager.ts +++ b/packages/plugin/src/features/sync/remote/passphrase-manager.ts @@ -1,29 +1,22 @@ 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 { activeStorage, isStorageConfigured, type MdsyncSettings, -} from "@/settings/model"; -import { reportWarning } from "@/shared"; +} from "@/core/settings"; +import { reportWarning } from "@/core/shared"; import { createStorageAdapter, type ObjectStorage, storageIdentity, -} from "@/storage"; -import { - readKeyfile, - resolveContentKey, - rotatePassphrase, -} from "@/sync/keyfile"; +} from "@/features/storage"; +import { readKeyfile, resolveContentKey, rotatePassphrase } from "./keyfile"; interface CachedKey { key: EncryptionKey; diff --git a/packages/plugin/src/sync/reset.ts b/packages/plugin/src/features/sync/remote/reset.ts similarity index 85% rename from packages/plugin/src/sync/reset.ts rename to packages/plugin/src/features/sync/remote/reset.ts index 03f2dff8..ec11f938 100644 --- a/packages/plugin/src/sync/reset.ts +++ b/packages/plugin/src/features/sync/remote/reset.ts @@ -1,13 +1,13 @@ -import { DEFAULT_CONCURRENCY } from "@/constants"; -import type { StorageAdapter } from "@/storage/types"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { runWithConcurrency } from "@/core/utils"; +import type { StorageAdapter } from "@/features/storage"; import { REMOTE_HISTORY_LOG_KEY, REMOTE_MANIFEST_KEY, REMOTE_OBJECTS_PREFIX, REMOTE_PINS_PREFIX, -} from "@/sync/constants"; -import type { EngineDependencies } from "@/sync/engine"; -import { runWithConcurrency } from "@/utils"; +} from "../constants"; +import type { EngineDependencies } from "../engine"; export interface RemoteResetResult { deletedKeys: string[]; diff --git a/packages/plugin/src/sync/space-paths.ts b/packages/plugin/src/features/sync/remote/space-paths.ts similarity index 95% rename from packages/plugin/src/sync/space-paths.ts rename to packages/plugin/src/features/sync/remote/space-paths.ts index 65e7353f..846f4e74 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 { HistoryLog } from "../history/types"; +import type { Manifest } from "../types"; type Rekey = (path: string) => string; 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 97% rename from packages/plugin/src/sync/uploads.ts rename to packages/plugin/src/features/sync/remote/uploads.ts index 329e7eb4..19bbeaaf 100644 --- a/packages/plugin/src/sync/uploads.ts +++ b/packages/plugin/src/features/sync/remote/uploads.ts @@ -1,4 +1,4 @@ -import type { ObjectStorage } from "@/storage/types"; +import type { ObjectStorage } from "@/features/storage"; /** * Blobs uploaded here but not yet in a published manifest, so an unpublished push resumes. Any other non-head 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 94% 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..d07989bf 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,13 @@ -import { isTextMergeCandidate } from "@/sync/auto-merge"; +import { isTextMergeCandidate } from "../apply/auto-merge"; import { 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"; +} from "../changes/content"; +import type { CompareResult, EngineDependencies } from "../engine"; +import { DiffCache, type DiffCacheInput } from "../hunks/diff-cache"; +import type { FileDiffModel } from "../hunks/projection"; +import type { Space } from "../remote/space"; import type { Conflict, DiffResult, @@ -15,7 +15,7 @@ import type { FileChange, ManifestEntry, Move, -} from "@/sync/types"; +} from "../types"; export interface PathStatus { change?: FileChange; diff --git a/packages/plugin/src/sync/runtime/history-service.ts b/packages/plugin/src/features/sync/runtime/history-service.ts similarity index 91% rename from packages/plugin/src/sync/runtime/history-service.ts rename to packages/plugin/src/features/sync/runtime/history-service.ts index 959fd561..86b58ae7 100644 --- a/packages/plugin/src/sync/runtime/history-service.ts +++ b/packages/plugin/src/features/sync/runtime/history-service.ts @@ -1,5 +1,11 @@ -import { DEFAULT_CONCURRENCY } from "@/constants"; -import { sha256Hex } from "@/crypto"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { sha256Hex } from "@/core/crypto"; +import { + runWithConcurrency, + runWithFileConcurrency, + withEolOf, +} from "@/core/utils"; +import { diskRefuses, trashPath } from "@/core/vault"; import { bytesToText, isLikelyText, @@ -7,38 +13,42 @@ import { textToBytes, writeLocalFile, writeRemoteObject, -} from "@/sync/content"; -import type { EngineDependencies } from "@/sync/engine"; -import { ownedFiles } from "@/sync/foreign"; +} from "../changes/content"; +import type { EngineDependencies } from "../engine"; import { - type DeletedFilesResult, - type FileVersion, loadVersionBytes, - planVaultRestore, listDeletedFiles as queryDeletedFiles, getFileHistory as queryFileHistory, listSnapshots as querySnapshots, - resolveSnapshotManifest, - type SnapshotListResult, +} from "../history/query"; +import { + planVaultRestore, sameRestorePlan, - setSnapshotPinned as storeSetSnapshotPinned, type VaultRestorePlan, -} from "@/sync/history"; +} from "../history/restore-vault"; +import { + resolveSnapshotManifest, + setSnapshotPinned as storeSetSnapshotPinned, +} from "../history/store"; +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 { ownedFiles } from "../remote/foreign"; +import { scanVault } from "../scope/scanner"; +import type { LocalSnapshot, Manifest } from "../types"; const NO_SESSION = "Storage session unavailable"; diff --git a/packages/plugin/src/sync/runtime/maintenance-service.ts b/packages/plugin/src/features/sync/runtime/maintenance-service.ts similarity index 88% rename from packages/plugin/src/sync/runtime/maintenance-service.ts rename to packages/plugin/src/features/sync/runtime/maintenance-service.ts index efc50d99..93fcd4dc 100644 --- a/packages/plugin/src/sync/runtime/maintenance-service.ts +++ b/packages/plugin/src/features/sync/runtime/maintenance-service.ts @@ -1,13 +1,13 @@ -import { ESyncLogOperation } from "@/logs/store"; -import { LOG_PATH_LIMIT } from "@/sync/constants"; -import type { EngineDependencies } from "@/sync/engine"; +import { ESyncLogOperation } from "@/core/logs"; +import { LOG_PATH_LIMIT } from "../constants"; +import type { EngineDependencies } from "../engine"; import { type CleanResult, cleanSummary, deepCleanOrphans, type VerifyResult, verifyRemote, -} from "@/sync/maintenance"; +} from "./maintenance"; interface MaintenanceServiceDeps { openSession: () => Promise; diff --git a/packages/plugin/src/sync/maintenance.ts b/packages/plugin/src/features/sync/runtime/maintenance.ts similarity index 90% rename from packages/plugin/src/sync/maintenance.ts rename to packages/plugin/src/features/sync/runtime/maintenance.ts index cd1f0bdd..ec91ded7 100644 --- a/packages/plugin/src/sync/maintenance.ts +++ b/packages/plugin/src/features/sync/runtime/maintenance.ts @@ -1,18 +1,14 @@ -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"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { decryptBytes, type EncryptionKey, sha256Hex } from "@/core/crypto"; +import { runWithConcurrency, runWithFileConcurrency } from "@/core/utils"; +import type { StorageAdapter } from "@/features/storage"; +import { REMOTE_OBJECTS_PREFIX, REMOTE_PINS_PREFIX } from "../constants"; +import { changeEntries } from "../history/changes"; +import { pinKey, readHistoryLog, readPinManifest } from "../history/store"; +import type { HistoryLog } from "../history/types"; +import { fetchRemoteManifest, objectKey } from "../remote/manifest"; +import { settledKeys } from "../remote/uploads"; +import type { Manifest, ManifestEntry } from "../types"; export interface MaintenanceOptions { concurrency?: number; 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..7a56b272 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 "@/core/shared"; +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 94% rename from packages/plugin/src/sync/runtime/operation-runner.ts rename to packages/plugin/src/features/sync/runtime/operation-runner.ts index 89911277..169d8b2d 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, 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..9eba997f 100644 --- a/packages/plugin/src/sync/runtime/saved-refresh.ts +++ b/packages/plugin/src/features/sync/runtime/saved-refresh.ts @@ -1,9 +1,9 @@ -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 type { LocalSession } from "@/app/session-factory"; +import { diffWithin } from "../changes/diff"; +import type { 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/settings/sections/configuration-scope.ts b/packages/plugin/src/features/sync/scope/configuration-scope-section.ts similarity index 92% rename from packages/plugin/src/settings/sections/configuration-scope.ts rename to packages/plugin/src/features/sync/scope/configuration-scope-section.ts index 2c0b2ed0..eeebe74c 100644 --- a/packages/plugin/src/settings/sections/configuration-scope.ts +++ b/packages/plugin/src/features/sync/scope/configuration-scope-section.ts @@ -1,17 +1,16 @@ import type { SettingDefinitionGroup } from "obsidian"; - +import type { SettingsSyncCategories } from "@/core/settings"; 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"; +} from "@/core/settings"; +import { notifyError, notifyInfo, openConfirmModal } from "@/core/ui"; +import { EFieldKind } from "@/features/storage"; +import type { Manifest } from "../types"; +import { createScopePolicy, type ScopePolicy } from "./scope"; interface SettingsSyncRow { key: keyof SettingsSyncCategories; 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 94% rename from packages/plugin/src/settings/sections/exclusions.ts rename to packages/plugin/src/features/sync/scope/exclusions-section.ts index a929b87f..3f2b5e0a 100644 --- a/packages/plugin/src/settings/sections/exclusions.ts +++ b/packages/plugin/src/features/sync/scope/exclusions-section.ts @@ -1,16 +1,16 @@ import { type App, type SettingDefinitionGroup, TFile } from "obsidian"; -import { IGNORE_FILE_NAME } from "@/constants"; +import { IGNORE_FILE_NAME } from "@/core/constants"; import { 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 { EFieldKind } from "@/features/storage"; const SCOPE_CHANGED = "Sync scope settings changed."; const BYTES_PER_MB = 1024 * 1024; 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..46d4e586 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 { PluginHost } from "@/app/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 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/vault/scanner.ts b/packages/plugin/src/features/sync/scope/scanner.ts similarity index 98% rename from packages/plugin/src/vault/scanner.ts rename to packages/plugin/src/features/sync/scope/scanner.ts index 4958a06f..3efcde27 100644 --- a/packages/plugin/src/vault/scanner.ts +++ b/packages/plugin/src/features/sync/scope/scanner.ts @@ -1,20 +1,20 @@ import type { DataAdapter } from "obsidian"; -import { DEFAULT_CONCURRENCY } from "@/constants"; -import { hasDotSegment, sortedByPath, stripTrailingSlash } from "@/shared"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { hasDotSegment, sortedByPath, stripTrailingSlash } from "@/core/shared"; +import { + createLargeFileGate, + LARGE_FILE_BYTES, + runWithConcurrency, +} from "@/core/utils"; +import type { VaultIndex } from "@/core/vault"; +import { caseInsensitiveDisk } from "@/core/vault"; 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 96% rename from packages/plugin/src/vault/scope.ts rename to packages/plugin/src/features/sync/scope/scope.ts index c1696387..bc870230 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 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 = [ 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..7c89e7ef 100644 --- a/packages/plugin/src/sync/session-state.ts +++ b/packages/plugin/src/features/sync/session-state.ts @@ -1,10 +1,10 @@ -import { entryAt } from "@/shared"; +import { entryAt } from "@/core/shared"; -import { diff } from "./diff"; +import { diff } from "./changes/diff"; 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/sync/session.ts b/packages/plugin/src/features/sync/session.ts similarity index 82% rename from packages/plugin/src/sync/session.ts rename to packages/plugin/src/features/sync/session.ts index cb9c7b30..925603d8 100644 --- a/packages/plugin/src/sync/session.ts +++ b/packages/plugin/src/features/sync/session.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/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 100% rename from packages/plugin/src/sync/types.ts rename to packages/plugin/src/features/sync/types.ts 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/ui/actions/ignore-action.ts b/packages/plugin/src/features/sync/ui/ignore-action.ts similarity index 95% rename from packages/plugin/src/ui/actions/ignore-action.ts rename to packages/plugin/src/features/sync/ui/ignore-action.ts index e6b3f14b..a3e4b2da 100644 --- a/packages/plugin/src/ui/actions/ignore-action.ts +++ b/packages/plugin/src/features/sync/ui/ignore-action.ts @@ -1,15 +1,14 @@ import { type App, type Menu, TFile, TFolder } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; +import type { PluginHost } from "@/app/host"; +import { notifyError, notifyInfo, openChoiceModal } from "@/core/ui"; +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."; diff --git a/packages/plugin/src/ui/actions/maintenance-actions.ts b/packages/plugin/src/features/sync/ui/maintenance-actions.ts similarity index 87% rename from packages/plugin/src/ui/actions/maintenance-actions.ts rename to packages/plugin/src/features/sync/ui/maintenance-actions.ts index 4baf6409..154aacac 100644 --- a/packages/plugin/src/ui/actions/maintenance-actions.ts +++ b/packages/plugin/src/features/sync/ui/maintenance-actions.ts @@ -1,9 +1,14 @@ -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 type { PluginHost } from "@/app/host"; +import { activeStorage } from "@/core/settings"; +import { + notifyError, + notifyInfo, + openConfirmModal, + reportError, +} from "@/core/ui"; +import { describeStorageTarget } from "@/features/storage"; +import { cleanSummary } from "../runtime/maintenance"; +import { confirmRemoteReset } from "./reset-modal"; const NO_STORAGE = "Configure a storage backend first."; diff --git a/packages/plugin/src/settings/sections/maintenance.ts b/packages/plugin/src/features/sync/ui/maintenance-section.ts similarity index 93% rename from packages/plugin/src/settings/sections/maintenance.ts rename to packages/plugin/src/features/sync/ui/maintenance-section.ts index 925282ec..1b978e8b 100644 --- a/packages/plugin/src/settings/sections/maintenance.ts +++ b/packages/plugin/src/features/sync/ui/maintenance-section.ts @@ -1,13 +1,13 @@ import type { SettingDefinitionGroup } from "obsidian"; -import type { PluginHost } from "@/plugin/host"; -import { type FieldContext, group } from "@/settings/fields"; +import type { PluginHost } from "@/app/host"; +import { type FieldContext, group } from "@/core/settings"; import { deepCleanOrphanedObjects, resetLocalState, resetRemoteStorage, verifyRemoteIntegrity, -} from "@/ui"; +} from "./maintenance-actions"; interface MaintenanceAction { name: string; 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 90% rename from packages/plugin/src/ui/actions/push-action.ts rename to packages/plugin/src/features/sync/ui/push-action.ts index 08a32a30..1bd9e6a3 100644 --- a/packages/plugin/src/ui/actions/push-action.ts +++ b/packages/plugin/src/features/sync/ui/push-action.ts @@ -1,9 +1,8 @@ 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 type { PluginHost } from "@/app/host"; +import { SOURCE_CONTROL_VIEW_TYPE } from "@/core/constants"; +import { notifyError, notifyInfo, runWithNotice } from "@/core/ui"; +import { openSourceControlView } from "@/features/source-control/view"; /** Changes inside `scope`: a file matches itself, a folder everything below it (the vault root "/" covers all). */ export function scopedPaths( 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/ui/actions/sync-actions.ts b/packages/plugin/src/features/sync/ui/sync-actions.ts similarity index 90% rename from packages/plugin/src/ui/actions/sync-actions.ts rename to packages/plugin/src/features/sync/ui/sync-actions.ts index a1becc0b..5a47beb9 100644 --- a/packages/plugin/src/ui/actions/sync-actions.ts +++ b/packages/plugin/src/features/sync/ui/sync-actions.ts @@ -1,7 +1,7 @@ -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"; +import type { PluginHost } from "@/app/host"; +import { notifyError, notifyInfo, runWithNotice } from "@/core/ui"; +import { openSourceControlChanges } from "@/features/source-control/view"; +import type { DiffResult } from "../types"; export async function runCompare(plugin: PluginHost): Promise { try { diff --git a/packages/plugin/src/plugin/vault-adoption.ts b/packages/plugin/src/features/sync/ui/vault-adoption.ts similarity index 86% rename from packages/plugin/src/plugin/vault-adoption.ts rename to packages/plugin/src/features/sync/ui/vault-adoption.ts index 40a20820..4a4739ce 100644 --- a/packages/plugin/src/plugin/vault-adoption.ts +++ b/packages/plugin/src/features/sync/ui/vault-adoption.ts @@ -1,7 +1,7 @@ import type { Plugin } from "obsidian"; - -import type { SyncController, SyncStatusSnapshot } from "@/sync/controller"; -import { confirmAdoptNewVault, notifyError, notifyInfo } from "@/ui"; +import { notifyError, notifyInfo } from "@/core/ui"; +import type { SyncController, SyncStatusSnapshot } from "../controller"; +import { confirmAdoptNewVault } from "./modals"; const VAULT_MISMATCH_ERROR = "Remote vault id does not match local"; diff --git a/packages/plugin/src/features/transfer/index.ts b/packages/plugin/src/features/transfer/index.ts new file mode 100644 index 00000000..2fb6ac36 --- /dev/null +++ b/packages/plugin/src/features/transfer/index.ts @@ -0,0 +1,4 @@ +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 99% rename from packages/plugin/src/settings/transfer.ts rename to packages/plugin/src/features/transfer/transfer.ts index b9452f92..0c22a69c 100644 --- a/packages/plugin/src/settings/transfer.ts +++ b/packages/plugin/src/features/transfer/transfer.ts @@ -1,11 +1,4 @@ -import { LINK_PARAM, openLink, sealLink } from "@/crypto/sealed-link"; -import { - type CompactStorageConfig, - compactStorageConfig, - EStorageBackend, - type StorageAdapterConfig, - storageDefaults, -} from "@/storage"; +import { LINK_PARAM, openLink, sealLink } from "@/core/crypto"; import { activeStorage, DEFAULT_SETTINGS, @@ -13,7 +6,14 @@ import { type MdsyncSettings, mergeSettings, type SettingsSyncCategories, -} from "./model"; +} from "@/core/settings"; +import { + type CompactStorageConfig, + compactStorageConfig, + EStorageBackend, + type StorageAdapterConfig, + storageDefaults, +} from "@/features/storage"; export const TRANSFER_ACTION = "mdsync"; const SETTINGS_TRANSFER_MAX_QR_BYTES = 1024; diff --git a/packages/plugin/src/settings/sections/device-transfer.ts b/packages/plugin/src/features/transfer/ui/device-transfer-section.ts similarity index 83% rename from packages/plugin/src/settings/sections/device-transfer.ts rename to packages/plugin/src/features/transfer/ui/device-transfer-section.ts index 9ca811b3..5256d170 100644 --- a/packages/plugin/src/settings/sections/device-transfer.ts +++ b/packages/plugin/src/features/transfer/ui/device-transfer-section.ts @@ -1,12 +1,9 @@ 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 { showSettingsTransferExport } from "./settings-transfer-export-modal"; +import { askSettingsTransferInput } from "./settings-transfer-modal"; export function deviceTransferSection( ctx: FieldContext, 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..c9134011 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 { activeStorage, type MdsyncSettings } from "@/core/settings"; import { modalFooter, modalWarning, onEnter, + openPromiseModal, renderModalHead, -} from "@/ui/common"; -import { openPromiseModal } from "./promise-modal"; +} from "@/core/ui"; +import { 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..66eb042e 100644 --- a/packages/plugin/src/main.ts +++ b/packages/plugin/src/main.ts @@ -1,77 +1,71 @@ import { Plugin } from "obsidian"; - -import { registerCommands } from "@/commands"; +import { bootstrapPluginRuntime, disposePluginRuntime } 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 { SettingsEnvelope } from "@/app/settings-envelope"; +import { + refreshOpenHistoryViewsAfterPush, + refreshOpenSourceControlViews, + registerPluginUi, +} from "@/app/views"; +import { DeviceKey } from "@/core/crypto"; +import type { LogService } from "@/core/logs"; import { canSync, DEFAULT_SETTINGS, isStorageConfigured, type MdsyncSettings, mergeSettings, -} from "@/settings/model"; +} from "@/core/settings"; +import { reportWarning } from "@/core/shared"; +import { notifyAction, notifyInfo } 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 { + type CursorFollow, + markTheirs, + 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 { openSourceControlChanges } from "@/features/source-control"; +import type { SpaceRecords } from "@/features/spaces"; import { - type CursorFollow, createAccessEnded, - createDeletedElsewhere, + createShareRegistration, 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"; + registerReadOnlyLock, + registerShareRenames, +} from "@/features/spaces"; +import { createStorageRefused } from "@/features/storage"; +import type { SyncController, WriteJournal } from "@/features/sync"; import { + 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"; + registerScheduler, + registerVaultAdoptionPrompt, + type StatePersister, +} from "@/features/sync"; +import { SettingsTransferController } from "@/features/transfer"; const SCOPE_REFRESH_DEBOUNCE_MS = 800; 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/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/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..0e331538 --- /dev/null +++ b/packages/plugin/src/styles.css @@ -0,0 +1,65 @@ +/* + * 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/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/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"; + +/* Last: phone overrides win on specificity, but stay last as documented. */ +@import "./core/ui/styles/mobile.css"; 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/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/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/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/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/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/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/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/settings/envelope.test.ts b/packages/plugin/tests/app/envelope.test.ts similarity index 94% rename from packages/plugin/tests/settings/envelope.test.ts rename to packages/plugin/tests/app/envelope.test.ts index 51ab8089..60f3bc7e 100644 --- a/packages/plugin/tests/settings/envelope.test.ts +++ b/packages/plugin/tests/app/envelope.test.ts @@ -1,12 +1,11 @@ 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 { SettingsEnvelope } from "@/app/settings-envelope"; +import { encryptJson } from "@/core/crypto/cipher"; +import { type MdsyncSettings, mergeSettings } 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/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 83% rename from packages/plugin/tests/plugin/realtime.test.ts rename to packages/plugin/tests/app/realtime.test.ts index 4bbe6de5..aae5df5c 100644 --- a/packages/plugin/tests/plugin/realtime.test.ts +++ b/packages/plugin/tests/app/realtime.test.ts @@ -1,9 +1,8 @@ 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 { LiveHost } from "@/features/live/register"; +import type { HubListener } from "@/features/relay/connection"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; const state = vi.hoisted(() => ({ listener: {} as HubListener })); @@ -26,7 +25,7 @@ vi.mock("obsidian", async (original) => ({ }); }, })); -vi.mock("@/hub", () => ({ +vi.mock("@/features/relay/connection", () => ({ HubConnection: class { listen(listener: HubListener) { state.listener = listener; @@ -35,15 +34,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: () => ({}), 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..79d5914c 100644 --- a/packages/plugin/tests/core/session-factory.test.ts +++ b/packages/plugin/tests/app/session-factory.test.ts @@ -1,16 +1,15 @@ 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, 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/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/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/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/cloudflare/r2.test.ts b/packages/plugin/tests/core/cloudflare/r2.test.ts similarity index 96% rename from packages/plugin/tests/cloudflare/r2.test.ts rename to packages/plugin/tests/core/cloudflare/r2.test.ts index 892bc93f..2c21dbfa 100644 --- a/packages/plugin/tests/cloudflare/r2.test.ts +++ b/packages/plugin/tests/core/cloudflare/r2.test.ts @@ -1,17 +1,15 @@ import { createHash } from "node:crypto"; 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"; 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"; diff --git a/packages/plugin/tests/cloudflare/relay-account.test.ts b/packages/plugin/tests/core/cloudflare/relay-account.test.ts similarity index 98% rename from packages/plugin/tests/cloudflare/relay-account.test.ts rename to packages/plugin/tests/core/cloudflare/relay-account.test.ts index ad4269ff..8767f492 100644 --- a/packages/plugin/tests/cloudflare/relay-account.test.ts +++ b/packages/plugin/tests/core/cloudflare/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/core/cloudflare/relay-deploy.test.ts similarity index 98% rename from packages/plugin/tests/cloudflare/relay-deploy.test.ts rename to packages/plugin/tests/core/cloudflare/relay-deploy.test.ts index 13ffedd4..4da7aeb6 100644 --- a/packages/plugin/tests/cloudflare/relay-deploy.test.ts +++ b/packages/plugin/tests/core/cloudflare/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/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/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..f0aa09c0 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 { SyncController } from "@/features/sync/controller"; +import { objectKey } from "@/features/sync/remote/manifest"; 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 98% rename from packages/plugin/tests/crypto/json-envelope.test.ts rename to packages/plugin/tests/core/crypto/json-envelope.test.ts index 7646fb03..645d212b 100644 --- a/packages/plugin/tests/crypto/json-envelope.test.ts +++ b/packages/plugin/tests/core/crypto/json-envelope.test.ts @@ -6,14 +6,14 @@ import { type EncryptionKey, encryptBytes, encryptJson, -} from "@/crypto"; +} from "@/core/crypto/cipher"; import { BLOB_VERSION, BLOB_VERSION_GZIP, GZIP_PAD_BYTES, IV_BYTES, JSON_GZIP_MIN_BYTES, -} from "@/crypto/constants"; +} from "@/core/crypto/constants"; let key: EncryptionKey; beforeAll(async () => { 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/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/settings/fields.test.ts b/packages/plugin/tests/core/settings/fields.test.ts similarity index 95% rename from packages/plugin/tests/settings/fields.test.ts rename to packages/plugin/tests/core/settings/fields.test.ts index 7a020c03..882bf768 100644 --- a/packages/plugin/tests/settings/fields.test.ts +++ b/packages/plugin/tests/core/settings/fields.test.ts @@ -8,8 +8,8 @@ import { introRow, renderDefinitions, type SettingsRow, -} from "@/settings/fields"; -import { EFieldKind } from "@/storage/field-spec"; +} from "@/core/settings/fields"; +import { EFieldKind } from "@/features/storage/field-spec"; vi.mock("obsidian", () => ({ debounce: (fn: unknown) => fn, diff --git a/packages/plugin/tests/settings/model.test.ts b/packages/plugin/tests/core/settings/model.test.ts similarity index 97% rename from packages/plugin/tests/settings/model.test.ts rename to packages/plugin/tests/core/settings/model.test.ts index a1565052..893d26a0 100644 --- a/packages/plugin/tests/settings/model.test.ts +++ b/packages/plugin/tests/core/settings/model.test.ts @@ -3,14 +3,17 @@ import { AUTO_PUSH_SETTLE_MAX_SECONDS, BULK_DELETE_LIMIT_MAX, LIVE_SEND_MS, -} from "@/constants"; +} from "@/core/constants"; import { DEFAULT_SETTINGS, isRelayConfigured, mergeSettings, -} from "@/settings/model"; -import { defaultS3Config } from "@/storage"; -import { EStorageBackend, type StorageAdapterConfig } from "@/storage/config"; +} from "@/core/settings/model"; +import { defaultS3Config } from "@/features/storage/backends/s3"; +import { + EStorageBackend, + type StorageAdapterConfig, +} from "@/features/storage/config"; describe("isRelayConfigured", () => { const secret = "s3cret"; diff --git a/packages/plugin/tests/settings/number-field.test.ts b/packages/plugin/tests/core/settings/number-field.test.ts similarity index 94% rename from packages/plugin/tests/settings/number-field.test.ts rename to packages/plugin/tests/core/settings/number-field.test.ts index aa67fe9d..b8a33ba3 100644 --- a/packages/plugin/tests/settings/number-field.test.ts +++ b/packages/plugin/tests/core/settings/number-field.test.ts @@ -5,8 +5,8 @@ import { type FieldContext, fieldRow, type NumberField, -} from "@/settings/fields"; -import { EFieldKind } from "@/storage/field-spec"; +} from "@/core/settings/fields"; +import { EFieldKind } from "@/features/storage/field-spec"; vi.mock("obsidian", () => { class Setting { 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 98% rename from packages/plugin/tests/shared/format.test.ts rename to packages/plugin/tests/core/shared/format.test.ts index 20eedcd1..d97c9c03 100644 --- a/packages/plugin/tests/shared/format.test.ts +++ b/packages/plugin/tests/core/shared/format.test.ts @@ -4,7 +4,7 @@ import { formatDayLabel, pluralize, withDevices, -} from "@/shared/format"; +} from "@/core/shared/format"; describe("withDevices", () => { it("names a person's devices after them, and nothing when none is known", () => { 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..9b2080f5 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 "@/features/storage/backends/util"; 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/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/file-concurrency.test.ts b/packages/plugin/tests/core/utils/file-concurrency.test.ts similarity index 97% rename from packages/plugin/tests/utils/file-concurrency.test.ts rename to packages/plugin/tests/core/utils/file-concurrency.test.ts index 9ebd4aa3..d1de04ef 100644 --- a/packages/plugin/tests/utils/file-concurrency.test.ts +++ b/packages/plugin/tests/core/utils/file-concurrency.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest"; import { LARGE_FILE_BYTES, runWithFileConcurrency, -} from "@/utils/file-concurrency"; +} from "@/core/utils/file-concurrency"; const pause = () => new Promise((resolve) => setTimeout(resolve, 0)); 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/utils/search.test.ts b/packages/plugin/tests/core/utils/search.test.ts similarity index 92% rename from packages/plugin/tests/utils/search.test.ts rename to packages/plugin/tests/core/utils/search.test.ts index 2608e1a8..99d2ea41 100644 --- a/packages/plugin/tests/utils/search.test.ts +++ b/packages/plugin/tests/core/utils/search.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { firstIndex } from "@/utils/search"; +import { firstIndex } from "@/core/utils/search"; describe("firstIndex", () => { const values = [1, 3, 3, 7, 9]; 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 88% rename from packages/plugin/tests/ui/diff-operations.test.ts rename to packages/plugin/tests/features/diff/diff-operations.test.ts index 9121588e..453c4081 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 { @@ -101,7 +104,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/restore-modal"); const spy = vi .spyOn(restoreMod, "confirmRestore") .mockResolvedValue(true); @@ -126,7 +129,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/restore-modal"); const spy = vi.spyOn(restoreMod, "confirmRestore").mockResolvedValue(false); const { ops, restoreFn } = setup(); await ops.restoreVersion(); @@ -135,7 +138,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/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 83% 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..6084b7ad 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,23 @@ // @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 { 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("@/features/source-control/view", () => ({ + openSourceControlView: vi.fn(), })); -vi.mock("@/ui/modals", () => ({ openConfirmModal: vi.fn() })); -vi.mock("@/ui/source-control-view", () => ({ openSourceControlView: vi.fn() })); beforeAll(installElementMethods); diff --git a/packages/plugin/tests/ui/history-state.test.ts b/packages/plugin/tests/features/diff/history-state.test.ts similarity index 97% rename from packages/plugin/tests/ui/history-state.test.ts rename to packages/plugin/tests/features/diff/history-state.test.ts index 66216278..a7e3a624 100644 --- a/packages/plugin/tests/ui/history-state.test.ts +++ b/packages/plugin/tests/features/diff/history-state.test.ts @@ -1,6 +1,4 @@ import { describe, expect, it } from "vitest"; -import { HUNK_TEXT_MAX_BYTES } from "@/sync/constants"; -import { EDiffDirection, type FileDiffModel } from "@/sync/projection"; import { buildHistoryRequest, changesDiffer, @@ -8,7 +6,12 @@ import { type HistoryModeInput, hunkHintText, selectHistoryMode, -} from "@/ui/diff/history-state"; +} from "@/features/diff/history-state"; +import { HUNK_TEXT_MAX_BYTES } from "@/features/sync/constants"; +import { + EDiffDirection, + type FileDiffModel, +} from "@/features/sync/hunks/projection"; function modeInput( overrides: Partial = {}, 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/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/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/ui/merge-actions.test.ts b/packages/plugin/tests/features/diff/merge/merge-actions.test.ts similarity index 93% rename from packages/plugin/tests/ui/merge-actions.test.ts rename to packages/plugin/tests/features/diff/merge/merge-actions.test.ts index fdd53f88..d73ba89c 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) { 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/ui/merge-state.test.ts b/packages/plugin/tests/features/diff/merge/merge-state.test.ts similarity index 98% rename from packages/plugin/tests/ui/merge-state.test.ts rename to packages/plugin/tests/features/diff/merge/merge-state.test.ts index 788615a8..344a0383 100644 --- a/packages/plugin/tests/ui/merge-state.test.ts +++ b/packages/plugin/tests/features/diff/merge/merge-state.test.ts @@ -2,23 +2,26 @@ 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"; + openedGapsField, + toggleMergeGap, +} from "@/features/diff/merge/merge-cards"; import { combinedModeField, mergeResultState, setCombinedMode, -} from "@/ui/diff/merge-decorations"; +} from "@/features/diff/merge/merge-decorations"; import { initialMergeChanges, mergeChangesField, setChangeState, -} from "@/ui/diff/merge-state"; +} from "@/features/diff/merge/merge-state"; +import { + applyPlan, + buildMergeSession, + type EMergeSide, + type MergeChange, + revertPlan, +} from "@/features/sync/hunks/merge-model"; function open(base: string, local: string, remote: string): EditorState { const session = buildMergeSession(base, local, remote); 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 96% rename from packages/plugin/tests/editor/signs.test.ts rename to packages/plugin/tests/features/editor-signs/signs.test.ts index fc5a65ee..82822b0b 100644 --- a/packages/plugin/tests/editor/signs.test.ts +++ b/packages/plugin/tests/features/editor-signs/signs.test.ts @@ -1,8 +1,6 @@ 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 { signsField } from "@/features/editor-signs/gutter"; import { type ChangeMark, findChangeForLine, @@ -11,15 +9,16 @@ import { presentSyncChange, shouldRedeliverBaseline, toCmText, -} from "@/editor/signs/helpers"; -import { segmentRevert } from "@/editor/signs/hunk-revert"; +} from "@/features/editor-signs/helpers"; +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); 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 90% rename from packages/plugin/tests/ui/link-scan.test.ts rename to packages/plugin/tests/features/explorer/link-scan.test.ts index b9718e30..12dfeb95 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; diff --git a/packages/plugin/tests/ui/row-decorator.test.ts b/packages/plugin/tests/features/explorer/row-decorator.test.ts similarity index 94% rename from packages/plugin/tests/ui/row-decorator.test.ts rename to packages/plugin/tests/features/explorer/row-decorator.test.ts index b625b4f2..94e9bd97 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(), 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..785f3d85 100644 --- a/packages/plugin/tests/storage/link-broker.test.ts +++ b/packages/plugin/tests/features/links/link-broker.test.ts @@ -5,9 +5,9 @@ import { 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 { StorageHttpError } from "@/features/storage/backends/util"; +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 85% rename from packages/plugin/tests/ui/link-actions.test.ts rename to packages/plugin/tests/features/links/ui/link-actions.test.ts index 7ae0a28b..a160e0f2 100644 --- a/packages/plugin/tests/ui/link-actions.test.ts +++ b/packages/plugin/tests/features/links/ui/link-actions.test.ts @@ -1,38 +1,53 @@ 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(), - openShareWindow: vi.fn(), +})); +vi.mock("@/features/source-control/view", () => ({ + openDiffView: vi.fn(), openSourceControlDeleted: vi.fn(), openSourceControlHistory: vi.fn(), openSourceControlView: vi.fn(), - openWhereMenu: vi.fn(), - rebuildLiveNote: vi.fn(), +})); +vi.mock("@/features/spaces/ui/invites/invite-action", () => ({ + openInvite: vi.fn(), +})); +vi.mock("@/features/spaces/ui/window/share-window", () => ({ + openShareWindow: 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(), })); 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 88% 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..979a5b34 100644 --- a/packages/plugin/tests/ui/manage-links-modal.test.ts +++ b/packages/plugin/tests/features/links/ui/manage-links-modal.test.ts @@ -1,23 +1,25 @@ import type { LinkStatus } from "@mdsync/protocol"; 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 type { LinkRecord } from "@/features/links/record"; +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(), 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 92% 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..6ce22fd6 100644 --- a/packages/plugin/tests/ui/note-link-action.test.ts +++ b/packages/plugin/tests/features/links/ui/note-link-action.test.ts @@ -1,12 +1,12 @@ import { FileView, type Plugin } from "obsidian"; import { describe, expect, it, vi } from "vitest"; +import type { PluginHost } from "@/app/host"; +import type { LinkRecord } from "@/features/links/record"; +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("@/ui/links/link-menu", () => ({ openManageLinks: vi.fn() })); +vi.mock("@/features/links/ui/link-menu", () => ({ openManageLinks: vi.fn() })); const RECORD: LinkRecord = { id: "one", 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 91% rename from packages/plugin/tests/live/follower.test.ts rename to packages/plugin/tests/features/live/session/follower.test.ts index 66736d7c..73c14c08 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 { 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"; +import type { SpaceFrame } from "@/features/relay/connection"; 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..e3628526 100644 --- a/packages/plugin/tests/live/rename.test.ts +++ b/packages/plugin/tests/features/live/workspace/rename.test.ts @@ -4,19 +4,19 @@ 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 { 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"; +import type { SpaceFrame, SpaceHub } from "@/features/relay/connection"; + +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 96% rename from packages/plugin/tests/hub/connection.test.ts rename to packages/plugin/tests/features/relay/connection.test.ts index 36cc3c3d..be8c13bf 100644 --- a/packages/plugin/tests/hub/connection.test.ts +++ b/packages/plugin/tests/features/relay/connection.test.ts @@ -7,13 +7,12 @@ 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 type { HubLinkOptions } from "@/core/hub/link"; +import type { LinkState } from "@/core/hub/status"; +import { DEFAULT_SETTINGS, 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 +29,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"; 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/settings/setup/relay.test.ts b/packages/plugin/tests/features/relay/deploy/relay.test.ts similarity index 96% rename from packages/plugin/tests/settings/setup/relay.test.ts rename to packages/plugin/tests/features/relay/deploy/relay.test.ts index 3c5b4b8b..4fd61a5c 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 "@/core/settings/model"; import { activateRelay, deployOwnRelay, @@ -18,9 +16,17 @@ import { runningRelayDeploy, useRelay, waitForRelay, -} from "@/settings/setup/relay"; - -vi.mock("@/settings/connection-test", () => ({ testRelay: vi.fn() })); +} 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/storage/ui/connection-test"; + +vi.mock("@/features/storage/ui/connection-test", () => ({ + testRelay: vi.fn(), +})); const A = "/accounts/acc"; const RELAYS = { taken: ["mdsync-relay", "other"], subdomain: "me" }; diff --git a/packages/plugin/tests/settings/relay-section.test.ts b/packages/plugin/tests/features/relay/ui/relay-section.test.ts similarity index 90% rename from packages/plugin/tests/settings/relay-section.test.ts rename to packages/plugin/tests/features/relay/ui/relay-section.test.ts index e4154269..1d9ca787 100644 --- a/packages/plugin/tests/settings/relay-section.test.ts +++ b/packages/plugin/tests/features/relay/ui/relay-section.test.ts @@ -1,9 +1,10 @@ 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 { relaySection } from "@/features/relay/ui/relay-section"; -vi.mock("obsidian", () => ({ +vi.mock("obsidian", async (importOriginal) => ({ + ...(await importOriginal()), Setting: class { setName() { return this; @@ -19,12 +20,12 @@ vi.mock("obsidian", () => ({ } }, })); -vi.mock("@/settings/fields", () => ({ +vi.mock("@/core/settings/fields", () => ({ 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; diff --git a/packages/plugin/tests/plugin/relay-update.test.ts b/packages/plugin/tests/features/relay/update/relay-update.test.ts similarity index 85% rename from packages/plugin/tests/plugin/relay-update.test.ts rename to packages/plugin/tests/features/relay/update/relay-update.test.ts index fe157a76..f86a434c 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 "@/core/settings/model"; +import type { HubListener } from "@/features/relay/connection"; +import { RELAY_VERSION } from "@/features/relay/deploy/relay-account"; +import { + type RelayUpdate, + registerRelayUpdate, +} from "@/features/relay/update/relay-update"; +import { openRelayUpdateModal } from "@/features/relay/update/relay-update-modal"; +import { testRelay } from "@/features/storage/ui/connection-test"; -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/storage/ui/connection-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 83% rename from packages/plugin/tests/settings/logs-view.test.ts rename to packages/plugin/tests/features/settings/logs-view.test.ts index 4945d863..c1127052 100644 --- a/packages/plugin/tests/settings/logs-view.test.ts +++ b/packages/plugin/tests/features/settings/logs-view.test.ts @@ -1,9 +1,10 @@ // @vitest-environment jsdom + +import { installElementMethods } from "@tests/helpers/element-methods"; 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"; +import { ESyncLogLevel, ESyncLogOperation } from "@/core/logs/store"; +import { copyText } from "@/core/ui/controls/copyable"; +import { renderLogEntry } from "@/features/settings/logs-view"; const copy = vi.hoisted(() => ({ clicks: [] as Array<() => void> })); @@ -22,7 +23,7 @@ vi.mock("obsidian", async (importOriginal) => ({ } }, })); -vi.mock("@/ui/common", () => ({ +vi.mock("@/core/ui/controls/copyable", () => ({ copyText: vi.fn(() => Promise.resolve(true)), })); diff --git a/packages/plugin/tests/settings/security-section.test.ts b/packages/plugin/tests/features/settings/sections/security-section.test.ts similarity index 90% rename from packages/plugin/tests/settings/security-section.test.ts rename to packages/plugin/tests/features/settings/sections/security-section.test.ts index 30898c02..f3b1223a 100644 --- a/packages/plugin/tests/settings/security-section.test.ts +++ b/packages/plugin/tests/features/settings/sections/security-section.test.ts @@ -1,17 +1,22 @@ import { Setting } from "obsidian"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import type { PluginHost } from "@/plugin/host"; -import { isStorageConfigured } from "@/settings/model"; -import { securitySection } from "@/settings/sections/security"; -import { askNewPassphrase, notifyInfo, reportError } from "@/ui"; +import type { PluginHost } from "@/app/host"; +import { isStorageConfigured } from "@/core/settings/model"; +import { askNewPassphrase } from "@/core/ui/modals/passphrase-modal"; +import { notifyInfo, reportError } from "@/core/ui/notices"; +import { securitySection } from "@/features/settings/sections/security"; -vi.mock("@/settings/model", () => ({ isStorageConfigured: vi.fn(() => true) })); -vi.mock("@/crypto/passphrase-cache", () => ({ +vi.mock("@/core/settings/model", () => ({ + isStorageConfigured: vi.fn(() => true), +})); +vi.mock("@/core/crypto/passphrase-cache", () => ({ clearCachedPassphrase: vi.fn(), })); -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(), 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 93% rename from packages/plugin/tests/settings/setup/steps.test.ts rename to packages/plugin/tests/features/setup/step-state.test.ts index 0c63fc9d..98cf0bf6 100644 --- a/packages/plugin/tests/settings/setup/steps.test.ts +++ b/packages/plugin/tests/features/setup/step-state.test.ts @@ -1,15 +1,16 @@ 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 { type MdsyncSettings, mergeSettings } 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: { 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/settings/setup/relay-step.test.ts b/packages/plugin/tests/features/setup/steps/relay-step.test.ts similarity index 90% 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..ca19d903 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 { installElementMethods } from "@tests/helpers/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 type { PluginHost } from "@/app/host"; +import { mergeSettings } from "@/core/settings/model"; import { activateRelay, deployOwnRelay, @@ -12,9 +11,10 @@ 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 { createRelayStep } from "@/features/setup/steps/relay-step"; +import type { StepView, Wizard } from "@/features/setup/wizard"; +import { testRelay } from "@/features/storage/ui/connection-test"; installElementMethods(); @@ -74,18 +74,20 @@ vi.mock("obsidian", async (original) => { Setting, }; }); -vi.mock("@/settings/connection-test", () => ({ testRelay: vi.fn() })); -vi.mock("@/settings/cloudflare-login", () => ({ +vi.mock("@/features/storage/ui/connection-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), 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 94% 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..ddc8dbaa 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", () => { 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/ui/day-groups.test.ts b/packages/plugin/tests/features/source-control/history/day-groups.test.ts similarity index 96% rename from packages/plugin/tests/ui/day-groups.test.ts rename to packages/plugin/tests/features/source-control/history/day-groups.test.ts index 26d51612..2b05a606 100644 --- a/packages/plugin/tests/ui/day-groups.test.ts +++ b/packages/plugin/tests/features/source-control/history/day-groups.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { groupRows } from "@/ui/source-control/day-groups"; +import { groupRows } from "@/features/source-control/history/day-groups"; const NOON = new Date(2024, 4, 15, 12).getTime(); const DAY = 86_400_000; 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 94% 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..6fd4c9a9 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,7 @@ 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 { 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; 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/ui/timeline-actions.test.ts b/packages/plugin/tests/features/source-control/timeline/timeline-actions.test.ts similarity index 87% 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..d7d516df 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/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 }; 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 98% 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..3155bcee 100644 --- a/packages/plugin/tests/ui/timeline-rows.test.ts +++ b/packages/plugin/tests/features/source-control/timeline/timeline-rows.test.ts @@ -1,10 +1,4 @@ import { describe, expect, it } from "vitest"; -import type { - SnapshotChanges, - SnapshotSummary, - VaultRestorePlan, -} from "@/sync/history"; -import type { EFileKind, ManifestEntry } from "@/sync/types"; import { buildTimelineRows, countsText, @@ -12,7 +6,13 @@ import { samplePaths, 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"; const NOW = 1_700_000_000_000; const DAY = 86_400_000; 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 96% 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..8aa6e009 100644 --- a/packages/plugin/tests/ui/trash-rows.test.ts +++ b/packages/plugin/tests/features/source-control/trash/trash-rows.test.ts @@ -1,12 +1,12 @@ import { describe, expect, it } from "vitest"; -import { formatRelativeTime } from "@/shared"; -import type { DeletedFile } from "@/sync/history"; -import type { EFileKind } from "@/sync/types"; +import { 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; 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 90% rename from packages/plugin/tests/plugin/share-registration.test.ts rename to packages/plugin/tests/features/spaces/share-registration.test.ts index 42add73a..5e3a6ee8 100644 --- a/packages/plugin/tests/plugin/share-registration.test.ts +++ b/packages/plugin/tests/features/spaces/share-registration.test.ts @@ -1,8 +1,8 @@ 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, 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 +16,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 87% rename from packages/plugin/tests/plugin/space-access.test.ts rename to packages/plugin/tests/features/spaces/space-access.test.ts index b081a3a6..42f1f6ee 100644 --- a/packages/plugin/tests/plugin/space-access.test.ts +++ b/packages/plugin/tests/features/spaces/space-access.test.ts @@ -1,12 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { deriveLiveKeys, type LiveKeys } from "@/core/crypto/live-keys"; +import { DEFAULT_SETTINGS, 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"; -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() })); +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 87% rename from packages/plugin/tests/settings/shares-section.test.ts rename to packages/plugin/tests/features/spaces/ui/shares-section.test.ts index 06ad09b8..3185c8ca 100644 --- a/packages/plugin/tests/settings/shares-section.test.ts +++ b/packages/plugin/tests/features/spaces/ui/shares-section.test.ts @@ -1,11 +1,11 @@ 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 { 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(), 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/storage/google-drive-adapter.test.ts b/packages/plugin/tests/features/storage/backends/google-drive-adapter.test.ts similarity index 98% 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..7ee54624 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/util"; +import { EStorageBackend } from "@/features/storage/config"; const requests: { url: string; method?: string }[] = []; let replies: unknown[] = []; 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/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..3cea5b9f 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 { createS3Adapter } from "@/features/storage/backends/s3"; +import { isRefusedCredentials } from "@/features/storage/backends/util"; +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/util.test.ts b/packages/plugin/tests/features/storage/backends/util.test.ts similarity index 98% rename from packages/plugin/tests/storage/util.test.ts rename to packages/plugin/tests/features/storage/backends/util.test.ts index f7b075e5..4c2b7116 100644 --- a/packages/plugin/tests/storage/util.test.ts +++ b/packages/plugin/tests/features/storage/backends/util.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; +import { toArrayBuffer } from "@/core/utils/bytes"; import { assertOk, isRetryableError, @@ -9,8 +10,7 @@ import { withDeadline, withRetry, withTimeout, -} from "@/storage/adapters/util"; -import { toArrayBuffer } from "@/utils"; +} from "@/features/storage/backends/util"; describe("storage error semantics", () => { it("treats only 'come back later' statuses as retryable", () => { 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..527101ea 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 * as cloudflareModule from "@/core/cloudflare"; +import { mergeSettings } from "@/core/settings/model"; +import { defaultS3Config } from "@/features/storage/backends/s3"; +import { StorageHttpError } from "@/features/storage/backends/util"; +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/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/plugin/storage-refused.test.ts b/packages/plugin/tests/features/storage/storage-refused.test.ts similarity index 79% rename from packages/plugin/tests/plugin/storage-refused.test.ts rename to packages/plugin/tests/features/storage/storage-refused.test.ts index a9db09a9..e0b2b06f 100644 --- a/packages/plugin/tests/plugin/storage-refused.test.ts +++ b/packages/plugin/tests/features/storage/storage-refused.test.ts @@ -1,16 +1,16 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import type { PluginHost } from "@/plugin/host"; -import { createStorageRefused } from "@/plugin/storage-refused"; -import { mergeSettings } from "@/settings/model"; -import { - defaultGoogleDriveConfig, - defaultS3Config, - EStorageBackend, -} from "@/storage"; -import { VAULT_SPACE } from "@/sync/space"; -import { openStorageRefusedModal } from "@/ui"; +import type { PluginHost } from "@/app/host"; +import { mergeSettings } from "@/core/settings/model"; +import { defaultGoogleDriveConfig } from "@/features/storage/backends/google-drive-auth"; +import { defaultS3Config } from "@/features/storage/backends/s3"; +import { EStorageBackend } from "@/features/storage/config"; +import { createStorageRefused } from "@/features/storage/storage-refused"; +import { openStorageRefusedModal } from "@/features/storage/ui/storage-refused-modal"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; -vi.mock("@/ui", () => ({ openStorageRefusedModal: vi.fn(async () => false) })); +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" }; diff --git a/packages/plugin/tests/settings/connection-test.test.ts b/packages/plugin/tests/features/storage/ui/connection-test.test.ts similarity index 98% rename from packages/plugin/tests/settings/connection-test.test.ts rename to packages/plugin/tests/features/storage/ui/connection-test.test.ts index 544c5373..8b786dc5 100644 --- a/packages/plugin/tests/settings/connection-test.test.ts +++ b/packages/plugin/tests/features/storage/ui/connection-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/storage/ui/connection-test"; interface Reply { status: number; diff --git a/packages/plugin/tests/settings/storage-fields.test.ts b/packages/plugin/tests/features/storage/ui/storage-fields.test.ts similarity index 90% rename from packages/plugin/tests/settings/storage-fields.test.ts rename to packages/plugin/tests/features/storage/ui/storage-fields.test.ts index 5772360f..cc6b4674 100644 --- a/packages/plugin/tests/settings/storage-fields.test.ts +++ b/packages/plugin/tests/features/storage/ui/storage-fields.test.ts @@ -1,10 +1,10 @@ import type { Setting } from "obsidian"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { PluginHost } from "@/plugin/host"; -import { settleTyping } from "@/settings/fields"; -import { storageRows } from "@/settings/sections/storage-fields"; -import { EStorageBackend } from "@/storage"; +import type { PluginHost } from "@/app/host"; +import { settleTyping } from "@/core/settings/fields"; +import { EStorageBackend } from "@/features/storage/config"; +import { storageRows } from "@/features/storage/ui/storage-fields"; vi.mock("obsidian", async (importActual) => ({ ...(await importActual()), diff --git a/packages/plugin/tests/sync/auto-merge.test.ts b/packages/plugin/tests/features/sync/apply/auto-merge.test.ts similarity index 95% rename from packages/plugin/tests/sync/auto-merge.test.ts rename to packages/plugin/tests/features/sync/apply/auto-merge.test.ts index 2dfa62ff..fbd40ead 100644 --- a/packages/plugin/tests/sync/auto-merge.test.ts +++ b/packages/plugin/tests/features/sync/apply/auto-merge.test.ts @@ -1,11 +1,14 @@ 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(); 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..b674ce11 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 { compare, pushPaths } from "@/features/sync/engine"; +import { objectKey } from "@/features/sync/remote/manifest"; 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 93% rename from packages/plugin/tests/sync/auto-cycle.test.ts rename to packages/plugin/tests/features/sync/auto-cycle.test.ts index 6d17ccea..1c29bd29 100644 --- a/packages/plugin/tests/sync/auto-cycle.test.ts +++ b/packages/plugin/tests/features/sync/auto-cycle.test.ts @@ -2,14 +2,14 @@ import { createTestControllerHost } from "@tests/helpers/controller"; import { pairedSessions, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it, vi } from "vitest"; -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 { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; +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(); diff --git a/packages/plugin/tests/sync/auto-push.test.ts b/packages/plugin/tests/features/sync/automation/auto-push.test.ts similarity index 94% rename from packages/plugin/tests/sync/auto-push.test.ts rename to packages/plugin/tests/features/sync/automation/auto-push.test.ts index ee3664a4..9ae9be12 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" }; diff --git a/packages/plugin/tests/sync/scheduler-interval.test.ts b/packages/plugin/tests/features/sync/automation/scheduler-interval.test.ts similarity index 98% rename from packages/plugin/tests/sync/scheduler-interval.test.ts rename to packages/plugin/tests/features/sync/automation/scheduler-interval.test.ts index 28de974c..5e017ef7 100644 --- a/packages/plugin/tests/sync/scheduler-interval.test.ts +++ b/packages/plugin/tests/features/sync/automation/scheduler-interval.test.ts @@ -1,13 +1,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { DEFAULT_SETTINGS } from "@/settings/model"; -import type { SyncController } from "@/sync/controller"; +import { DEFAULT_SETTINGS } from "@/core/settings/model"; import { registerScheduler, SCHEDULER_HEARTBEAT_MS, type SchedulerHost, -} from "@/sync/scheduler"; -import { VAULT_SPACE } from "@/sync/space"; +} from "@/features/sync/automation/scheduler"; +import type { SyncController } from "@/features/sync/controller"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; const MINUTE_MS = 60_000; 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 96% 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..27ffa3ef 100644 --- a/packages/plugin/tests/sync/scheduler-queued-push.test.ts +++ b/packages/plugin/tests/features/sync/automation/scheduler-queued-push.test.ts @@ -1,9 +1,12 @@ 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 "@/core/settings/model"; +import { + registerScheduler, + type SchedulerHost, +} from "@/features/sync/automation/scheduler"; +import type { SyncController } from "@/features/sync/controller"; +import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; const SETTLE_MS = DEFAULT_SETTINGS.autoPushSettleSeconds * 1000; diff --git a/packages/plugin/tests/sync/scheduler-startup.test.ts b/packages/plugin/tests/features/sync/automation/scheduler-startup.test.ts similarity index 94% rename from packages/plugin/tests/sync/scheduler-startup.test.ts rename to packages/plugin/tests/features/sync/automation/scheduler-startup.test.ts index e364f546..071c5c5f 100644 --- a/packages/plugin/tests/sync/scheduler-startup.test.ts +++ b/packages/plugin/tests/features/sync/automation/scheduler-startup.test.ts @@ -1,7 +1,10 @@ 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 { DEFAULT_SETTINGS } from "@/core/settings/model"; +import { + registerScheduler, + type SchedulerHost, +} from "@/features/sync/automation/scheduler"; +import type { SyncController } from "@/features/sync/controller"; interface Harness { host: SchedulerHost; 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 94% 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..83758373 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,14 @@ 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 { encryptJson } from "@/core/crypto/cipher"; +import { REMOTE_MANIFEST_KEY } 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"; diff --git a/packages/plugin/tests/sync/content-cache.test.ts b/packages/plugin/tests/features/sync/changes/content-cache.test.ts similarity index 97% rename from packages/plugin/tests/sync/content-cache.test.ts rename to packages/plugin/tests/features/sync/changes/content-cache.test.ts index d454db39..ac5327d6 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/remote/manifest"; async function seed( storage: FakeStorage, 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/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/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 93% rename from packages/plugin/tests/sync/engine-roundtrip.test.ts rename to packages/plugin/tests/features/sync/engine-roundtrip.test.ts index b1a15655..4bb5a3e2 100644 --- a/packages/plugin/tests/sync/engine-roundtrip.test.ts +++ b/packages/plugin/tests/features/sync/engine-roundtrip.test.ts @@ -2,17 +2,24 @@ 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 { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import { pullPaths } from "@/features/sync/apply/pull"; +import { + REMOTE_MANIFEST_KEY, + REMOTE_OBJECTS_PREFIX, +} from "@/features/sync/constants"; +import { + compare, + type EngineDependencies, + pushPaths, +} from "@/features/sync/engine"; +import { readHistoryLog } from "@/features/sync/history/store"; +import { advanceSessionAfterPush } from "@/features/sync/remote/baseline"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; +import { SETTLED_AFTER_MS } from "@/features/sync/remote/uploads"; +import { createScopePolicy } from "@/features/sync/scope/scope"; +import { EChangeType, type SessionState } from "@/features/sync/types"; let key: EncryptionKey; beforeAll(async () => { 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/sync/history-deleted.test.ts b/packages/plugin/tests/features/sync/history/history-deleted.test.ts similarity index 97% rename from packages/plugin/tests/sync/history-deleted.test.ts rename to packages/plugin/tests/features/sync/history/history-deleted.test.ts index 3572e6fa..03cfc854 100644 --- a/packages/plugin/tests/sync/history-deleted.test.ts +++ b/packages/plugin/tests/features/sync/history/history-deleted.test.ts @@ -1,12 +1,16 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { publishManifest } from "@tests/helpers/manifest"; import { beforeAll, describe, expect, it, vi } from "vitest"; -import { deriveKey, type EncryptionKey, encryptJson } from "@/crypto"; -import { diffManifests } from "@/sync/history/changes"; -import { listDeletedFiles, listSnapshots } from "@/sync/history/query"; -import { pinKey, writeHistoryLog } from "@/sync/history/store"; -import type { HistoryLog, SnapshotEntry } from "@/sync/history/types"; -import type { EFileKind, Manifest, ManifestEntry } from "@/sync/types"; +import { + deriveKey, + type EncryptionKey, + encryptJson, +} from "@/core/crypto/cipher"; +import { diffManifests } from "@/features/sync/history/changes"; +import { listDeletedFiles, listSnapshots } from "@/features/sync/history/query"; +import { pinKey, writeHistoryLog } from "@/features/sync/history/store"; +import type { HistoryLog, SnapshotEntry } from "@/features/sync/history/types"; +import type { EFileKind, Manifest, ManifestEntry } from "@/features/sync/types"; let key: EncryptionKey; beforeAll(async () => { diff --git a/packages/plugin/tests/sync/history-gc.test.ts b/packages/plugin/tests/features/sync/history/history-gc.test.ts similarity index 97% rename from packages/plugin/tests/sync/history-gc.test.ts rename to packages/plugin/tests/features/sync/history/history-gc.test.ts index a8d2e5a1..10e7800a 100644 --- a/packages/plugin/tests/sync/history-gc.test.ts +++ b/packages/plugin/tests/features/sync/history/history-gc.test.ts @@ -1,25 +1,29 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { publishManifest } from "@tests/helpers/manifest"; import { describe, expect, it, vi } from "vitest"; -import { deriveKey, type EncryptionKey, encryptJson } from "@/crypto"; -import { REMOTE_HISTORY_LOG_KEY } from "@/sync/constants"; -import { diffManifests } from "@/sync/history/changes"; +import { + deriveKey, + type EncryptionKey, + encryptJson, +} from "@/core/crypto/cipher"; +import { REMOTE_HISTORY_LOG_KEY } from "@/features/sync/constants"; +import { diffManifests } from "@/features/sync/history/changes"; import { clampMaxSnapshots, collectGarbage, gcExcessBuffer, shouldRunGc, -} from "@/sync/history/gc"; +} from "@/features/sync/history/gc"; import { pinKey, readHistoryLog, readPinManifest, setSnapshotPinned, writeHistoryLog, -} from "@/sync/history/store"; -import type { HistoryLog, SnapshotEntry } from "@/sync/history/types"; -import { objectKey } from "@/sync/manifest"; -import type { EFileKind, Manifest } from "@/sync/types"; +} from "@/features/sync/history/store"; +import type { HistoryLog, SnapshotEntry } from "@/features/sync/history/types"; +import { objectKey } from "@/features/sync/remote/manifest"; +import type { EFileKind, Manifest } from "@/features/sync/types"; const DAY_MS = 24 * 60 * 60 * 1000; diff --git a/packages/plugin/tests/sync/history-log.test.ts b/packages/plugin/tests/features/sync/history/history-log.test.ts similarity index 96% rename from packages/plugin/tests/sync/history-log.test.ts rename to packages/plugin/tests/features/sync/history/history-log.test.ts index 340d8c0a..cad336da 100644 --- a/packages/plugin/tests/sync/history-log.test.ts +++ b/packages/plugin/tests/features/sync/history/history-log.test.ts @@ -1,17 +1,25 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { publishManifest } from "@tests/helpers/manifest"; import { beforeAll, describe, expect, it } from "vitest"; -import { deriveKey, type EncryptionKey, encryptJson } from "@/crypto"; +import { + deriveKey, + type EncryptionKey, + encryptJson, +} from "@/core/crypto/cipher"; import { contiguousLength, diffManifests, undoChanges, -} from "@/sync/history/changes"; -import { getFileHistory } from "@/sync/history/query"; -import { replayTo } from "@/sync/history/replay"; -import { pinKey, prependSnapshot, writeHistoryLog } from "@/sync/history/store"; -import type { HistoryLog, SnapshotEntry } from "@/sync/history/types"; -import type { EFileKind, Manifest, ManifestEntry } from "@/sync/types"; +} from "@/features/sync/history/changes"; +import { getFileHistory } from "@/features/sync/history/query"; +import { replayTo } from "@/features/sync/history/replay"; +import { + pinKey, + prependSnapshot, + writeHistoryLog, +} from "@/features/sync/history/store"; +import type { HistoryLog, SnapshotEntry } from "@/features/sync/history/types"; +import type { EFileKind, Manifest, ManifestEntry } from "@/features/sync/types"; let key: EncryptionKey; beforeAll(async () => { diff --git a/packages/plugin/tests/sync/history-read-cache.test.ts b/packages/plugin/tests/features/sync/history/history-read-cache.test.ts similarity index 88% rename from packages/plugin/tests/sync/history-read-cache.test.ts rename to packages/plugin/tests/features/sync/history/history-read-cache.test.ts index 9c6e99a4..0e5d45b9 100644 --- a/packages/plugin/tests/sync/history-read-cache.test.ts +++ b/packages/plugin/tests/features/sync/history/history-read-cache.test.ts @@ -2,11 +2,19 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { publishManifest } from "@tests/helpers/manifest"; import { RevalidatingStorage } from "@tests/helpers/revalidating-storage"; import { beforeAll, describe, expect, it } from "vitest"; -import { deriveKey, type EncryptionKey, encryptJson } from "@/crypto"; -import { getFileHistory } from "@/sync/history/query"; -import { pinKey, readHistoryLog, writeHistoryLog } from "@/sync/history/store"; -import type { HistoryLog } from "@/sync/history/types"; -import type { EFileKind, Manifest } from "@/sync/types"; +import { + deriveKey, + type EncryptionKey, + encryptJson, +} from "@/core/crypto/cipher"; +import { getFileHistory } from "@/features/sync/history/query"; +import { + pinKey, + readHistoryLog, + writeHistoryLog, +} from "@/features/sync/history/store"; +import type { HistoryLog } from "@/features/sync/history/types"; +import type { EFileKind, Manifest } from "@/features/sync/types"; let key: EncryptionKey; let otherKey: EncryptionKey; diff --git a/packages/plugin/tests/sync/restore-vault.test.ts b/packages/plugin/tests/features/sync/history/restore-vault.test.ts similarity index 97% rename from packages/plugin/tests/sync/restore-vault.test.ts rename to packages/plugin/tests/features/sync/history/restore-vault.test.ts index 381f72d4..16e54de6 100644 --- a/packages/plugin/tests/sync/restore-vault.test.ts +++ b/packages/plugin/tests/features/sync/history/restore-vault.test.ts @@ -1,11 +1,11 @@ import { describe, expect, it } from "vitest"; -import { planVaultRestore } from "@/sync/history/restore-vault"; +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; 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/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/sync/merge-model.test.ts b/packages/plugin/tests/features/sync/hunks/merge-model.test.ts similarity index 99% rename from packages/plugin/tests/sync/merge-model.test.ts rename to packages/plugin/tests/features/sync/hunks/merge-model.test.ts index c094721b..5d7ab813 100644 --- a/packages/plugin/tests/sync/merge-model.test.ts +++ b/packages/plugin/tests/features/sync/hunks/merge-model.test.ts @@ -9,7 +9,7 @@ import { type StatusPatch, snapToLines, threeWayRegions, -} from "@/sync/merge-model"; +} from "@/features/sync/hunks/merge-model"; const doc = (text: string) => Text.of(text.split("\n")); 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 84% rename from packages/plugin/tests/sync/manifest-device.test.ts rename to packages/plugin/tests/features/sync/identity/manifest-device.test.ts index 4ae42ac1..3ed5a254 100644 --- a/packages/plugin/tests/sync/manifest-device.test.ts +++ b/packages/plugin/tests/features/sync/identity/manifest-device.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { defaultDeviceName } from "@/sync/device"; -import { buildManifest } from "@/sync/manifest"; +import { defaultDeviceName } from "@/features/sync/identity/device"; +import { buildManifest } from "@/features/sync/remote/manifest"; const snapshot = { files: {}, 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..c6cf6a7c 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 { encryptJson } from "@/core/crypto/cipher"; +import { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; +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 97% rename from packages/plugin/tests/sync/operations-batch.test.ts rename to packages/plugin/tests/features/sync/operations/operations-batch.test.ts index 2f30339f..009b3070 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(); 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 92% rename from packages/plugin/tests/sync/foreign.test.ts rename to packages/plugin/tests/features/sync/remote/foreign.test.ts index fd31ad1a..6131ac34 100644 --- a/packages/plugin/tests/sync/foreign.test.ts +++ b/packages/plugin/tests/features/sync/remote/foreign.test.ts @@ -1,18 +1,22 @@ 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 { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import { compare, pushPaths } from "@/features/sync/engine"; +import { readHistoryLog } from "@/features/sync/history/store"; +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 { objectKey } from "@/features/sync/remote/manifest"; +import { SETTLED_AFTER_MS } from "@/features/sync/remote/uploads"; +import { createScopePolicy } from "@/features/sync/scope/scope"; +import { + EFileKind, + type Manifest, + type ManifestEntry, +} from "@/features/sync/types"; const vaultScope = createScopePolicy({ settingsSync: DEFAULT_SETTINGS_SYNC, 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..af137934 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 { + deriveKey, + type EncryptionKey, + encryptJson, +} from "@/core/crypto/cipher"; +import { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; 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..59f09db5 100644 --- a/packages/plugin/tests/sync/manifest-revalidate.test.ts +++ b/packages/plugin/tests/features/sync/remote/manifest-revalidate.test.ts @@ -2,15 +2,19 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { RevalidatingStorage } from "@tests/helpers/revalidating-storage"; import { beforeAll, describe, expect, it } from "vitest"; -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 { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; +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 93% rename from packages/plugin/tests/core/passphrase-manager.test.ts rename to packages/plugin/tests/features/sync/remote/passphrase-manager.test.ts index e367f9fd..08985ba0 100644 --- a/packages/plugin/tests/core/passphrase-manager.test.ts +++ b/packages/plugin/tests/features/sync/remote/passphrase-manager.test.ts @@ -1,28 +1,28 @@ 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 type { DeviceKey } from "@/core/crypto/device-key"; import { 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 { DEFAULT_SETTINGS, 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), 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..b912f8e3 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 type { DeviceKey } from "@/core/crypto/device-key"; +import { DEFAULT_SETTINGS } from "@/core/settings/model"; +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 90% rename from packages/plugin/tests/sync/reset.test.ts rename to packages/plugin/tests/features/sync/remote/reset.test.ts index 2078d8a9..9e56e30f 100644 --- a/packages/plugin/tests/sync/reset.test.ts +++ b/packages/plugin/tests/features/sync/remote/reset.test.ts @@ -1,15 +1,15 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { beforeAll, describe, expect, it } from "vitest"; -import { deriveKey, type EncryptionKey } from "@/crypto"; +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 { objectKey } from "@/features/sync/remote/manifest"; +import { resetRemoteStorage } from "@/features/sync/remote/reset"; let key: EncryptionKey; beforeAll(async () => { diff --git a/packages/plugin/tests/sync/space-paths.test.ts b/packages/plugin/tests/features/sync/remote/space-paths.test.ts similarity index 92% rename from packages/plugin/tests/sync/space-paths.test.ts rename to packages/plugin/tests/features/sync/remote/space-paths.test.ts index 52535067..87a31b6c 100644 --- a/packages/plugin/tests/sync/space-paths.test.ts +++ b/packages/plugin/tests/features/sync/remote/space-paths.test.ts @@ -1,12 +1,15 @@ import { describe, expect, it } from "vitest"; -import type { HistoryLog, SnapshotChanges } from "@/sync/history/types"; +import type { + HistoryLog, + SnapshotChanges, +} from "@/features/sync/history/types"; import { historyLogToSpace, historyLogToVault, manifestToSpace, manifestToVault, -} from "@/sync/space-paths"; -import type { EFileKind, Manifest, ManifestEntry } from "@/sync/types"; +} 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 }; 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..3b4dfd52 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 { decryptJson } from "@/core/crypto/cipher"; +import { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; +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 97% rename from packages/plugin/tests/sync/spaces.test.ts rename to packages/plugin/tests/features/sync/remote/spaces.test.ts index b0422d07..e9a6ba42 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 { + 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 { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; +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; 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 91% 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..80ab02eb 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(); diff --git a/packages/plugin/tests/sync/maintenance.test.ts b/packages/plugin/tests/features/sync/runtime/maintenance.test.ts similarity index 91% rename from packages/plugin/tests/sync/maintenance.test.ts rename to packages/plugin/tests/features/sync/runtime/maintenance.test.ts index 481716d6..45653148 100644 --- a/packages/plugin/tests/sync/maintenance.test.ts +++ b/packages/plugin/tests/features/sync/runtime/maintenance.test.ts @@ -1,13 +1,19 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { publishManifest } from "@tests/helpers/manifest"; import { beforeAll, describe, expect, it } from "vitest"; -import { deriveKey, type EncryptionKey } from "@/crypto"; -import { REMOTE_OBJECTS_PREFIX, REMOTE_PINS_PREFIX } from "@/sync/constants"; -import { diffManifests } from "@/sync/history/changes"; -import { writeHistoryLog } from "@/sync/history/store"; -import { deepCleanOrphans, verifyRemote } from "@/sync/maintenance"; -import { objectKey } from "@/sync/manifest"; -import type { EFileKind, Manifest } from "@/sync/types"; +import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; +import { + REMOTE_OBJECTS_PREFIX, + REMOTE_PINS_PREFIX, +} from "@/features/sync/constants"; +import { diffManifests } from "@/features/sync/history/changes"; +import { writeHistoryLog } from "@/features/sync/history/store"; +import { objectKey } from "@/features/sync/remote/manifest"; +import { + deepCleanOrphans, + verifyRemote, +} from "@/features/sync/runtime/maintenance"; +import type { EFileKind, Manifest } from "@/features/sync/types"; const DAY_MS = 24 * 60 * 60 * 1000; diff --git a/packages/plugin/tests/sync/operation-runner.test.ts b/packages/plugin/tests/features/sync/runtime/operation-runner.test.ts similarity index 95% rename from packages/plugin/tests/sync/operation-runner.test.ts rename to packages/plugin/tests/features/sync/runtime/operation-runner.test.ts index d32254d2..1124f16c 100644 --- a/packages/plugin/tests/sync/operation-runner.test.ts +++ b/packages/plugin/tests/features/sync/runtime/operation-runner.test.ts @@ -2,18 +2,21 @@ 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 { OFFLINE_MESSAGE } from "@/core/shared/offline"; +import { StorageHttpError } from "@/features/storage/backends/util"; +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(); 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 93% rename from packages/plugin/tests/sync/saved-refresh.test.ts rename to packages/plugin/tests/features/sync/runtime/saved-refresh.test.ts index 0f004076..5735610c 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 "@/app/session-factory"; +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(); 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/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/vault/scanner-index.test.ts b/packages/plugin/tests/features/sync/scope/scanner-index.test.ts similarity index 98% rename from packages/plugin/tests/vault/scanner-index.test.ts rename to packages/plugin/tests/features/sync/scope/scanner-index.test.ts index 1b9cf1ac..54fe8b04 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 }; 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/vault/scope.test.ts b/packages/plugin/tests/features/sync/scope/scope.test.ts similarity index 94% rename from packages/plugin/tests/vault/scope.test.ts rename to packages/plugin/tests/features/sync/scope/scope.test.ts index 2033ed62..e7fb4df4 100644 --- a/packages/plugin/tests/vault/scope.test.ts +++ b/packages/plugin/tests/features/sync/scope/scope.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; -import { createScopePolicy } from "@/vault/scope"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import { createScopePolicy } from "@/features/sync/scope/scope"; describe("ScopePolicy getCategory", () => { const scope = createScopePolicy({ 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..ff7527f3 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 { LARGE_FILE_BYTES } from "@/core/utils/file-concurrency"; +import { pullPaths } from "@/features/sync/apply/pull"; +import { pushPaths } from "@/features/sync/engine"; useEncryptionKey(); 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/sync/upload-listing.test.ts b/packages/plugin/tests/features/sync/upload-listing.test.ts similarity index 89% rename from packages/plugin/tests/sync/upload-listing.test.ts rename to packages/plugin/tests/features/sync/upload-listing.test.ts index b7790b55..83838bb9 100644 --- a/packages/plugin/tests/sync/upload-listing.test.ts +++ b/packages/plugin/tests/features/sync/upload-listing.test.ts @@ -1,14 +1,21 @@ 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 { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; +import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import { + REMOTE_MANIFEST_KEY, + 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 () => { diff --git a/packages/plugin/tests/settings/transfer-controller.test.ts b/packages/plugin/tests/features/transfer/transfer-controller.test.ts similarity index 90% rename from packages/plugin/tests/settings/transfer-controller.test.ts rename to packages/plugin/tests/features/transfer/transfer-controller.test.ts index 4e12705f..e0abd06e 100644 --- a/packages/plugin/tests/settings/transfer-controller.test.ts +++ b/packages/plugin/tests/features/transfer/transfer-controller.test.ts @@ -2,19 +2,21 @@ import { deviceKey, FakeSecretStorage } from "@tests/helpers/device-key"; import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; 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 { type MdsyncSettings, mergeSettings } from "@/core/settings/model"; +import type { LinkRecord } from "@/features/links/record"; +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(), })); diff --git a/packages/plugin/tests/settings/transfer.test.ts b/packages/plugin/tests/features/transfer/transfer.test.ts similarity index 97% rename from packages/plugin/tests/settings/transfer.test.ts rename to packages/plugin/tests/features/transfer/transfer.test.ts index 4d6cec5b..34cb95ff 100644 --- a/packages/plugin/tests/settings/transfer.test.ts +++ b/packages/plugin/tests/features/transfer/transfer.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from "vitest"; -import { sealLink } from "@/crypto/sealed-link"; -import { DEFAULT_SETTINGS, type MdsyncSettings } from "@/settings/model"; +import { sealLink } from "@/core/crypto/sealed-link"; +import { DEFAULT_SETTINGS, 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 +12,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"; diff --git a/packages/plugin/tests/helpers/config-device.ts b/packages/plugin/tests/helpers/config-device.ts index 937d1295..b485ce68 100644 --- a/packages/plugin/tests/helpers/config-device.ts +++ b/packages/plugin/tests/helpers/config-device.ts @@ -1,11 +1,14 @@ -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 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, 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-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..1c763a8f 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 "@/core/settings/model"; +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/live-hub.ts b/packages/plugin/tests/helpers/live-hub.ts index 9660cb16..a91ac0c4 100644 --- a/packages/plugin/tests/helpers/live-hub.ts +++ b/packages/plugin/tests/helpers/live-hub.ts @@ -9,7 +9,11 @@ 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 "@/features/relay/connection"; /** * 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..1962a275 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 { type EncryptionKey, encryptJson } from "@/core/crypto/cipher"; +import type { ObjectStorage } from "@/features/storage/types"; +import { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; +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..62507547 100644 --- a/packages/plugin/tests/helpers/presence-relay.ts +++ b/packages/plugin/tests/helpers/presence-relay.ts @@ -1,9 +1,9 @@ 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 { People, type PresenceAccess } from "@/features/presence/people"; +import type { SpaceFrame, SpaceListener } from "@/features/relay/connection"; +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/revalidating-storage.ts b/packages/plugin/tests/helpers/revalidating-storage.ts index b154de39..ad87ac7f 100644 --- a/packages/plugin/tests/helpers/revalidating-storage.ts +++ b/packages/plugin/tests/helpers/revalidating-storage.ts @@ -1,4 +1,4 @@ -import type { ConditionalRead, ListedObject } from "@/storage/types"; +import type { ConditionalRead, ListedObject } from "@/features/storage/types"; import { FakeStorage } from "./fake-storage"; /** A backend that hands out a validator, as S3 and WebDAV do. */ diff --git a/packages/plugin/tests/helpers/session.ts b/packages/plugin/tests/helpers/session.ts index 525a69d0..068e1273 100644 --- a/packages/plugin/tests/helpers/session.ts +++ b/packages/plugin/tests/helpers/session.ts @@ -1,12 +1,12 @@ import { beforeAll } from "vitest"; -import { deriveKey, type EncryptionKey } from "@/crypto"; -import { DEFAULT_SETTINGS_SYNC } from "@/settings/model"; -import { compare, type EngineDependencies } from "@/sync/engine"; -import { WriteJournal } from "@/sync/journal"; -import type { OperationContext } from "@/sync/operations"; -import { VAULT_SPACE } from "@/sync/space"; -import 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 } from "@/features/sync/engine"; +import type { OperationContext } from "@/features/sync/operations/types"; +import { WriteJournal } from "@/features/sync/recovery/journal"; +import { VAULT_SPACE } from "@/features/sync/remote/space"; +import { createScopePolicy } from "@/features/sync/scope/scope"; +import type { SessionState } from "@/features/sync/types"; import { FakeStorage } from "./fake-storage"; import { InMemoryAdapter } from "./in-memory-adapter"; diff --git a/packages/plugin/tests/helpers/shared-links.ts b/packages/plugin/tests/helpers/shared-links.ts index a3b0d39a..04d0ee02 100644 --- a/packages/plugin/tests/helpers/shared-links.ts +++ b/packages/plugin/tests/helpers/shared-links.ts @@ -1,7 +1,7 @@ import { vi } from "vitest"; -import type { StoredLink } from "@/links/record"; -import { SharedLinks } from "@/links/shared-links"; +import type { StoredLink } from "@/features/links/record"; +import { SharedLinks } from "@/features/links/shared-links"; const PUBLISHED = 1_760_000_000_000; diff --git a/packages/plugin/tests/helpers/space-records.ts b/packages/plugin/tests/helpers/space-records.ts index cbb921e9..94f792ca 100644 --- a/packages/plugin/tests/helpers/space-records.ts +++ b/packages/plugin/tests/helpers/space-records.ts @@ -1,5 +1,5 @@ -import type { SpaceRecord } from "@/spaces/record"; -import { SpaceRecords } from "@/spaces/records"; +import type { SpaceRecord } from "@/features/spaces/record"; +import { SpaceRecords } from "@/features/spaces/records"; export function record( id: string, diff --git a/packages/plugin/tests/stubs/relay-bundle.ts b/packages/plugin/tests/stubs/relay-bundle.ts index 07af4b64..10ba64b5 100644 --- a/packages/plugin/tests/stubs/relay-bundle.ts +++ b/packages/plugin/tests/stubs/relay-bundle.ts @@ -1,4 +1,4 @@ -import type { RelayBundle } from "@/cloudflare/bundle"; +import type { RelayBundle } from "@/features/relay/deploy/bundle"; const bundle: RelayBundle = { name: "mdsync-relay", diff --git a/packages/protocol/README.md b/packages/protocol/README.md new file mode 100644 index 00000000..3604d68c --- /dev/null +++ b/packages/protocol/README.md @@ -0,0 +1,58 @@ +# Protocol + +`@mdsync/protocol`: the wire formats the plugin, the relay and the viewer share. Types and functions here are the single definition; a package that needs one imports it, never copies it. Source is the reference (`packages/protocol/package.json` points `main` at `packages/protocol/src/index.ts`, no build step), this file is the map. Hub constraints: `.claude/rules/realtime.md`; link constraints: `.claude/rules/links.md`. + +| File | Defines | +|---|---| +| `packages/protocol/src/frames.ts` | hub paths and query params, keepalive constants, `EFrame`, `ERefusal`, `ClientFrame` / `ServerFrame`, limits, `OWNER`, `CHANNEL_DOC` | +| `packages/protocol/src/codec.ts` | `encodeClient` / `decodeClient`, `encodeServer` / `decodeServer`, `withSlot` | +| `packages/protocol/src/bytes.ts` | `Writer` / `Reader` (u8, u32, length-prefixed text and blocks), base64url and hex | +| `packages/protocol/src/grant.ts` | the owner's channel grant: `deriveChannelGrant`, `grantExpiry`, `GRANT_TTL_S` | +| `packages/protocol/src/share.ts` | share ids, the share's hub channel and storage prefix, signing batch size | +| `packages/protocol/src/link.ts` | the share-link seal: ids, keys, gate, payload, URL, route headers, limits | +| `packages/protocol/src/link-content.ts` | the `href` and image `src` allow-lists used by the plugin's sanitizer and the viewer's | + +## Hub frames + +A frame is `[type:u8][slot:u8][docLen:u8][doc][body]`. `slot` names a channel within one socket (index in the `c`/`t` pairs of the connect URL); `doc` is an opaque HMAC, or `""` (`CHANNEL_DOC`) for the channel itself; `body` is ciphertext or a few integers. Text fields carry a one-byte length (255 bytes at most), blocks a four-byte one. + +**Client to hub** (`ClientFrame`): + +| Frame | Body | Meaning | +|---|---|---| +| `Sub` | `since` | follow a document; answered with `State` (the tail since `since`) | +| `Unsub` | none | stop following | +| `Update` | `n`, sealed update | append to the log; answered with `Echo(seq, n)` | +| `Seed` | `n`, sealed update | `Update` into a document with no log only | +| `Snapshot` | `upto`, sealed snapshot | replace the log up to `upto` (compaction) | +| `Rotate` | `target`, `upto`, sealed `note`, sealed seed | seed `target`, point this log at it, only while it ends at `upto` | +| `Awareness` | sealed payload | cursors (document) or presence (channel); never stored | +| `Signal` | none | on the channel: another device pushed, pull | + +**Hub to client** (`ServerFrame`): `State` (`head`, `snapshot`, `deltas`, then `log`, the log's name), `Fanout` (`seq`, `from`, sealed update), `Echo`, `Peer` (`from`, sealed awareness), `Join` and `Here` (`from`, `who`, `name`: a socket as the hub vouches for it; `Here` is someone already present, told to a newcomer), `Leave`, `Moved` (`target`, sealed note), `Revoked`, `Refused` (`ERefusal`), `Signal`. `from` is the hub's per-socket tag, not an identity. + +Connect and keepalive: `HUB_PATH` with one `c` and `t` per slot plus `d` (`EHubParam`); `HUB_SIGNAL_PATH` takes the same params for one channel over HTTP. Text `ping` is answered `pong` by the hub without waking it (`KEEPALIVE_*`). `UNAUTHORIZED_CLOSE_CODE` closes a socket none of whose slots is admitted. Limits: `MAX_SLOTS` 32, `MAX_FRAME_BYTES` 1 MiB, `MAX_DOC_SUBS` 64, `MAX_DOC_ID_LENGTH`, `MAX_MOVE_NOTE_BYTES`. + +Refusals (`ERefusal`): `TooLarge`, `TooManyDocs`, `ReadOnly`, `Unstored`. Each tells the client to stop waiting on that frame. + +## Grants and identity + +An owner grant is `.:")>` (unix seconds, lowercase hex), valid for one channel, `GRANT_TTL_S` (a day) long. A share's channel is `shareChannel(id)` (`mdsync-share-`), the vault's is the SHA-256 of its storage identity; a share's objects live under `sharePrefix(prefix, id)`. `isShareId` is the one validity check. `OWNER` is the `who` of a socket the secret admitted. Share tokens are the relay's (`packages/relay/src/share/kv.ts`), not a protocol format. + +## Sealed payloads + +The hub carries ciphertext sealed by the plugin (`packages/plugin/src/core/crypto/seal.ts`): AES-GCM under the space's frame key with the place as additional data (`doc:`, `awareness:`, `moved:`, `presence`). The protocol defines the frames around them, not the sealing; the docId derivation is `packages/plugin/src/features/live/doc-id.ts`. + +## Share links + +`packages/protocol/src/link.ts` is the only definition (plugin seals, viewer opens, relay checks the gate). + +- URL `/s/#[/]` via `linkUrl` / `parseLinkLocation`. `id` is 16 random bytes in base64url (22 chars, `isLinkId`), `key` 16 bytes (`LINK_KEY_BYTES`). +- Payload `{title, html, createdAt}` (`LinkPayload`) -> JSON -> deflate -> AES-GCM with additional data `link:`; blob = version byte, IV, ciphertext (`sealLinkPayload`, `openLinkPayload`). Inflating stops past a limit, since deflate ratios reach 1000x. +- `deriveLinkKeys`: content key and gate are two HKDF outputs of the fragment key, plus PBKDF2 (`LINK_KDF_ITERATIONS`) of the trimmed, NFC-normalized passphrase and a salt when protected. The relay stores only a hash of the gate. +- Relay routes use `LINK_HEADERS` (gate, salt in; views left, expiry out), `LinkMeta` and `LinkStatus` answers, `LinkPutMode` (`create` or `update`) and the `LINK_MAX_*` caps. + +## Changing a format + +- Plugin and relay deploy apart (the plugin ships a relay bundle, but a user's relay may be older or from the workflow), so a change keeps both directions readable: add a field at the end of a body, tolerate its absence, never reuse a frame number. +- Tests: `packages/protocol/tests/codec.test.ts` (round trips, malformed input, a state without a log), `packages/protocol/tests/link.test.ts` (seal, id binding, tampering, size). Both sides of a changed hub frame are also exercised by `packages/relay/tests/hub/`. diff --git a/packages/relay/README.md b/packages/relay/README.md new file mode 100644 index 00000000..71d52cfc --- /dev/null +++ b/packages/relay/README.md @@ -0,0 +1,68 @@ +# Relay + +`mdsync-relay`: one Cloudflare Worker, deployed to the user's own account, that adds live editing, instant sync signals, shared folders, share links and the Google Drive sign-in to the plugin. It uses Cloudflare Durable Objects directly (no PartyServer) and fits the Workers free tier. One `RELAY_SECRET` is one trust domain: the owner of the relay is the owner of everything on it. Constraints: `.claude/rules/realtime.md` (hub), `.claude/rules/spaces.md` (broker), `.claude/rules/links.md` (links). Formats: `packages/protocol/README.md`. Shared folders: `packages/plugin/src/features/spaces/README.md`. Share links: `packages/plugin/src/features/links/README.md` and `packages/viewer/README.md`. + +## Service map + +`packages/relay/src/index.ts` routes by path and falls through each handler in turn; CORS preflight is answered for every path. + +| Path | Handler | Auth | Holds | +|---|---|---|---| +| `/hub` (WebSocket), `/hub/signal` (POST) | `packages/relay/src/hub/access.ts` -> `Hub` Durable Object | channel grant or live share token, checked in the worker before the object wakes | document logs, presence fan-out, revoked grants | +| `/share/*` | `packages/relay/src/share/broker.ts`, `packages/relay/src/share/admin.ts` | participant: share token; owner routes: `X-Mdsync-Admin` = `RELAY_SECRET` | KV `SHARE_TOKENS`: tokens, pointers, share storage | +| `/link/*`, `/s/` | `packages/relay/src/link/routes.ts`, `packages/relay/src/link/shell.ts` -> one `Link` Durable Object per link | owner routes: relay secret; `meta` and `open`: public, behind the link's gate | sealed note, view counter, gate hash | +| `/auth`, `/refresh` | `packages/relay/src/google-oauth.ts` | public; `/auth` needs a nonce the plugin started | nothing stored | +| `/status` | `packages/relay/src/index.ts` | relay secret | tells a wrong URL (no answer) from a wrong secret (401); reports `RELAY_VERSION` | + +- **Hub.** One `Hub` object per deployment (`hubStub`): fewer sockets, handshakes and wake-ups, and one secret already is one trust domain. Model below. +- **Share broker.** A participant's share token buys a presigned S3 URL (120 s) for one key under `shares//` of the owner's bucket; bytes never pass through the relay. The owner registers where the share lives and issues tokens. `packages/relay/src/share/sigv4.ts` is a minimal WebCrypto presigner (the AWS SDK is too heavy for a worker); `packages/relay/src/share/key.ts` is the security boundary between an object name and a bucket key. +- **Link storage.** One `Link` object per link so a view is counted in the link's own turn (`packages/relay/src/link/store.ts`, synchronous on purpose); `handleShellRequest` serves `packages/viewer` with the CSP. See the links README. +- **Google OAuth proxy.** Keeps `GDRIVE_CLIENT_SECRET` off devices. `/auth` without a code takes the plugin's one-time nonce, issues a signed state (timestamp, nonce, HMAC under the client secret) plus a `HttpOnly` cookie, and redirects to Google's consent; the callback needs both state and cookie (a signature proves we minted it, the cookie proves the same browser returned: without it `/auth?code=...` would sync a victim's vault into the attacker's Drive), exchanges the code and redirects to `obsidian://mdsync-auth` with tokens and the nonce. `/refresh` (POST) swaps a refresh token for an access token, returns a rotated refresh token, and answers 401 `invalid_grant` for a revoked one so the plugin does not retry it as an outage. 503 `not_configured` without the Google secrets. + +## Persistence layout + +- **KV `SHARE_TOKENS`** (`packages/relay/src/share/kv.ts`; the key layout stays in that file): `tok:` -> token record (`shareId`, `participantId`, role `rw`/`ro`, label), `pt::` -> the participant's current token, `storage:` -> the owner's registered S3 location and credentials. A token is live only while its pointer names it, so two re-invites at once leave one live token, not an orphan no revoke finds. KV is eventually consistent (about a minute, negative answers cached) and the free tier allows 1k writes a day (`saveStorage` writes only a changed registration). +- **Hub object SQLite** (`packages/relay/src/hub/store.ts`, `packages/relay/src/hub/revoked.ts`): `docs` (one row per `(channel, doc)`: snapshot, forwarding pointer, log name), `chunks` (consecutive deltas, each after its 4-byte length), `revoked` (grant fingerprint, until), `closed` (channels shut for good). Per-socket state (slot -> channel, grant fingerprint, `who`, `name`, subscriptions) lives in the 16 KB WebSocket attachment, not in tags (at most 10). +- **Link object SQLite** (`packages/relay/src/link/store.ts`): `link` (views, limits, expiry, gate hash, salt, size), `chunks` of the sealed blob, `throttle` per client. An alarm erases an expired link and frees its storage. +- **Assets**: the viewer build (`packages/viewer/dist`), served as plain files under `/viewer/`; only `/s/*` runs the worker first (`packages/relay/wrangler.toml`). +- Everything the relay stores is ciphertext, hashes or what an owner registered: the owner's S3 credentials and invite labels (KV), a Drive refresh token in transit only. + +## Hub model + +- `/hub?c=&t=&...&d=` opens up to 32 slots (`MAX_SLOTS`); the worker checks every grant before waking the object. 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. +- Rates per socket (`packages/relay/src/hub/limits.ts`): frames 32 a second, bursts of 256, excess dropped unanswered; a read-only socket's awareness 20 a second, bursts of 40, 4 KB. 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 (the echo is the ack). +- A read-only share token follows documents but never writes (`Refused(ReadOnly)`) and never signals (the hub drops it, HTTP answers 403: it would only wake everyone into a sync). +- `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` for everyone already there, since presence is never stored. +- Keepalive: `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, and no answer in 5 s drops it sooner. +- Revocation: broker -> `Hub.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 hub keeps a revoked fingerprint 5 minutes (`REVOKED_MS`) and refuses it on connect, because KV may still let it in. The client retries a refused socket six times and then reads `unauthorized` until settings change or the device wakes; the share's own close waits longer (`.claude/rules/spaces.md`, "Close, leave, revoke"). +- Storage: 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 about 1.03 rows an update (a row per delta cost about 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 (`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 drawing may reach 1 MiB: past a frame the leader rebuilds the room, and past that the note goes back to the file sync). +- 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. + +## Deploy + +Both paths deploy the same `packages/relay/wrangler.toml`: KV binding `SHARE_TOKENS`, Durable Objects `Hub` and `Link`, assets from `../viewer/dist`, migrations. Secrets: `RELAY_SECRET` (admin auth; hub grants derive from it), optional `GDRIVE_CLIENT_ID` and `GDRIVE_CLIENT_SECRET`. + +- **In the plugin** (`features/relay/deploy/`, paths relative to `packages/plugin/src/`). `packages/relay/bundle.mjs` runs `wrangler deploy --dry-run`, reads the config (KV, Durable Objects, migrations, assets) and emits `packages/relay/dist/relay-bundle.json` (gitignored; text assets only); `packages/plugin/esbuild.relay-bundle.mjs` serves it as `mdsync:relay-bundle`, stamping `+` as the version, so a release deploys the relay of its own commit. `deployRelay` (`features/relay/deploy/relay-deploy.ts`) goes by steps: workers.dev subdomain, KV namespace, assets upload, worker upload (multipart: bindings, `RELAY_VERSION` plain text, `RELAY_SECRET` secret text, migrations), then `onUploaded`, then the subdomain route. `keep_bindings: ["secret_text"]` keeps secrets set outside MDSync (the Google client). An existing relay keeps its KV namespace (a new one orphans every share token); a first deploy finds one by wrangler's title, so a relay first deployed by the workflow is found. `pendingMigrations` sends every migration after the deployed tag and refuses an unknown deployed tag rather than replay from the start (it could recreate or delete a Durable Object class holding live data). A new kind of binding in `packages/relay/wrangler.toml` also needs `packages/relay/bundle.mjs`, `RelayBundle` (`features/relay/deploy/bundle.ts`) and `uploadForm` to carry it. Flow, update offers and consent: `.claude/rules/settings-setup.md`. +- **GitHub Actions** (`.github/workflows/deploy-relay.yml`, manual dispatch on a fork): relay tests, viewer build, then `wrangler deploy --secrets-file` with `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID`, `RELAY_SECRET` (the run fails without it) and the optional Google secrets. Wrangler creates the KV namespace and Durable Objects on the first deploy. Such a relay has no `RELAY_VERSION`: `/status` reports `null` and the plugin treats it as deployed outside MDSync (`relayBehind` is false, no update offer). +- `HUB_STALE_MS` overrides the stale-socket window and is set only by tests (`pnpm e2e:hub`). + +## Migrations and compatibility + +- `[[migrations]]` in `packages/relay/wrangler.toml` are append-only: `v1` created `SyncRelay`, `v2` replaced it with `Hub`, `v3` added `Link`. A new Durable Object class needs a new tag; never edit an old one. +- Plugin and relay deploy apart, so each tolerates the other's older build: a 1.3.0 client, which does not know `Refused(Unstored)`, goes cold under a generic status; an older relay answers `not_found` to link creation and one refused batch per transfer to batch signing (the plugin says to redeploy the relay). +- A 1.3 relay kept a row per delta (`deltas`). `SqlDocStore` 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, 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. The plugin never deploys an older relay; only a manual rollback does this, and every live log restarts (devices rotate from their text). + +## Accepted limitations + +- 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. +- The relay can withhold, replay or reorder a document's frames: additional data binds a frame to where it belongs, not to when. +- 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. +- A revoked writer keeps file storage for up to about three minutes (KV grant cached about 60 s, presigned URL 120 s): the broker never asks the hub's revoked table per signature. +- 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 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. +- The broker presigns DELETE too: a writer can remove a share's objects; history, not revocation, repairs that. +- The relay's operator is the owner and serves the viewer script, so a hostile operator could read link notes (`.claude/rules/security.md`). diff --git a/packages/viewer/README.md b/packages/viewer/README.md new file mode 100644 index 00000000..e5dd5151 --- /dev/null +++ b/packages/viewer/README.md @@ -0,0 +1,60 @@ +# Viewer + +The page a share link opens. It reads the link's id from the path and its key from the `#fragment`, asks the relay for the sealed note, decrypts it in the browser and shows it. The relay serves it: `GET /s/` returns this package's `packages/viewer/src/index.html` with the security headers (`packages/relay/src/link/shell.ts`), the scripts and styles are plain assets under `/viewer/` (`packages/relay/wrangler.toml`, `[assets]`). The link model, flows and format: `packages/plugin/src/features/links/README.md`. Constraints: `.claude/rules/links.md`. + +Vanilla TypeScript, no framework. `packages/viewer/build.mjs` bundles `packages/viewer/src/main.ts` and `packages/viewer/src/viewer.css` with esbuild to `dist/viewer/` (an IIFE, minified) and copies `packages/viewer/src/index.html`. `pnpm --filter mdsync-viewer run build` runs before every relay dev, deploy and bundle. Dependencies: `@mdsync/protocol` (format), DOMPurify, `idb-keyval`, turndown with its GFM plugin. + +## Visit + +`main.ts` parses the address with `parseLinkLocation`; a missing or cut-short key shows `invalid`. `LinkSession` (`packages/viewer/src/session.ts`) drives one visit and tells the view what to show (`ViewState`: `loading`, `passphrase`, `content`, `gone`, `invalid`, `error`): + +1. `cache.get(id)` (this tab's sealed copy), else `GET /link//meta`. 404 means `gone`, and any remembered keys for the id are dropped. +2. Unprotected: derive the keys from the fragment key alone. Protected: use remembered keys if the browser has them, else show the passphrase form. +3. `POST /link//open` with the gate counts a view and returns the sealed bytes, `X-Mdsync-Views-Left` and `X-Mdsync-Expires`. Without a cached copy this is the only call that spends a view. +4. `openLinkPayload` decrypts and inflates. A wrong passphrase is only known by failing to open: the form shows again with "Wrong passphrase.". A 401 or 429 shows the wait (`Retry-After`) and keeps the form; without a passphrase a failed gate means a damaged address. + +The passphrase is trimmed and normalized before it is stretched (`packages/protocol/src/link.ts`), so a pasted trailing space is no wrong attempt. + +## Cache and remembered keys + +- `packages/viewer/src/cache.ts`: the sealed bytes, views left and expiry in `sessionStorage` per id. A reload decrypts locally and costs no view; the key and the passphrase are never written. Storage the browser blocks, or a note past the quota, just costs a view on reload. +- `packages/viewer/src/keys.ts`: **Remember on this browser** (passphrase form, off by default: a shared computer must not keep a note by accident) stores the derived non-extractable AES `CryptoKey` and the gate in IndexedDB (`idb-keyval`, database `mdsync-viewer`), never the passphrase. It is kept until the link's expiry (each visit sweeps every expired entry) or until the relay says the link is gone. Kept keys the relay refuses are dropped. A link with no expiry keeps them until the relay says gone. + +## Rendering + +- `packages/viewer/src/sanitize.ts` is the only way payload HTML reaches the page: DOMPurify with HTML, SVG and MathML profiles; forms, buttons, `style`, `link`, `meta`, `base` and `srcset` forbidden; links limited to `LINK_HREF_ALLOWED` (http(s) ones get `target=_blank` and `rel="noopener noreferrer nofollow"`), images to `LINK_IMAGE_SRC_ALLOWED`, inputs to disabled checkboxes. A browser DOMPurify does not support shows an error rather than raw markup. +- The viewer's own controls (code **Copy**, heading `#`, fold chevrons) are added after sanitizing, since the snapshot carries no script. +- `packages/viewer/src/sections.ts` nests the renderer's flat blocks under their headings (footnotes stay outside every section); a click on the heading or its chevron folds it, unless text is selected or a link or button was hit. `reveal` unfolds every section and callout around an element. +- Callouts fold on a click of their title. `packages/viewer/src/code.ts` adds a **Copy** button per code block. `packages/viewer/src/images.ts` marks a paragraph holding only an image (`lone-image`). +- A note whose first element is an H1 equal to its name shows the name once; the document title is the name, or "Shared note". +- Tab icon: an inline SVG data URI in `packages/viewer/src/index.html`, since the CSP allows images from `data:` and `https:` only. The viewer itself requests only the two link routes (a note's own external images load from their hosts); the footer credit is a plain link to the project. + +## Anchors + +An address is `/s/#/`; the anchor is a heading's slug (`uniqueSlug`: Unicode letters and digits, deduplicated) or an element id such as a footnote's. + +- Each heading gets a `#` button (`packages/viewer/src/anchors.ts`): it copies the address, puts it in the bar with `history.replaceState` (key kept) and scrolls there. +- A load or `hashchange` with an anchor jumps to it, unfolding what hides it (`currentAnchor`). +- In-note `a[href^="#"]` links are rewritten to the full address: the bare `#fn-1` would replace the key, and a copy or a new tab would be dead. Clicks `preventDefault` and call the same jump. + +## Page chrome + +- `packages/viewer/src/sidebar.ts`: a column left of the note from 66rem; below it a panel behind a menu button (Escape or an outside click closes it, Tab stays inside while open). It holds the link card (`packages/viewer/src/facts.ts`: views left and the expiry, counting down every 30 s; a warning once the note lives only in this tab), the outline and the credit. +- `packages/viewer/src/outline.ts`: the headings as a list (three or more) that marks the one being read. +- `packages/viewer/src/topbar.ts`: name, fact chips, **Wide text** and **Copy as Markdown**. Wide text is kept in `localStorage` (`mdsync-viewer-wide`) and only applies from 66rem up (below it the toggle is hidden); a lone image is centered while wide. +- **Copy as Markdown** (`packages/viewer/src/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 mark kept), tasks `- [x]`, tables GFM, a formula is written back as TeX from `data-tex` on its ``; vault images (`data:`) and SVG drawings are left out. +- CSS is written once: `packages/viewer/src/viewer.css` (variables, page, layout) imports `packages/viewer/src/note.css`, `packages/viewer/src/sidebar.css`, `packages/viewer/src/topbar.css` and `packages/viewer/src/gate.css`. It uses Obsidian's variable names (`--h2-size`, `--code-keyword`, `--color-blue-rgb`...) because the note's SVG reads them and a theme could set them. Light and dark follow `prefers-color-scheme`; print styles are included. +- Every listener of a shown state is tied to its `AbortSignal` (`createView`'s `show` aborts the previous one); timers stop with it. + +## Tests + +`packages/viewer/tests/` under jsdom (`pnpm --filter mdsync-viewer test`; IndexedDB through `fake-indexeddb`). The page against a real relay and headless Chrome: `pnpm e2e:links` (`tests/e2e/links-viewer.ts`: text, passphrase, limit gone, reload costs no view). + +## Accepted limits + +- A view counts when the ciphertext is served. A closed tab after the response, or a failed decrypt, still costs one; another tab or browser spends another (views count opens, not people). +- The cache is per tab: a heading link opened in a new tab counts a view. A sealed note over about 3.9 MiB does not fit `sessionStorage`, so its reload spends another view. +- Once the last view or the expiry passes, the tab keeps showing the note until it is closed; the card says so. +- Remembering keys trades safety for convenience on that browser until the link expires; it is off by default. +- The relay's operator serves this script and could read a note; the page cannot defend against its own server (one trust domain, see the rule). +- No link previews: the shell is generic and the note is sealed. diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b4e80ffa..e9cf106c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -75,6 +75,9 @@ importers: '@types/qrcode': specifier: ^1.5.6 version: 1.5.6 + dependency-cruiser: + specifier: ^18.7.0 + version: 18.7.0 esbuild: specifier: ^0.25.12 version: 0.25.12 @@ -1003,6 +1006,27 @@ packages: '@vitest/utils@4.1.11': resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==} + acorn-jsx-walk@2.0.0: + resolution: {integrity: sha512-uuo6iJj4D4ygkdzd6jPtcxs8vZgDX9YFIkqczGImoypX2fQ4dVImmu3UzA4ynixCIMTrEOWW+95M2HuBaCEOVA==} + + acorn-jsx@5.3.2: + resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} + peerDependencies: + acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 + + acorn-loose@8.5.2: + resolution: {integrity: sha512-PPvV6g8UGMGgjrMu+n/f9E/tCSkNQ2Y97eFvuVdJfG11+xdIeDcLyNdC8SHcrHbRqkfwLASdplyR6B6sKM1U4A==} + engines: {node: '>=0.4.0'} + + acorn-walk@8.3.5: + resolution: {integrity: sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==} + engines: {node: '>=0.4.0'} + + acorn@8.19.0: + resolution: {integrity: sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==} + engines: {node: '>=0.4.0'} + hasBin: true + ansi-regex@5.0.1: resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} engines: {node: '>=8'} @@ -1033,6 +1057,10 @@ packages: resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==} engines: {node: '>=18'} + chalk@4.1.2: + resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} + engines: {node: '>=10'} + cliui@6.0.0: resolution: {integrity: sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==} @@ -1043,6 +1071,10 @@ packages: color-name@1.1.4: resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + commander@15.0.0: + resolution: {integrity: sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg==} + engines: {node: '>=22.12.0'} + convert-source-map@2.0.0: resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} @@ -1068,6 +1100,11 @@ packages: decimal.js@10.6.0: resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==} + dependency-cruiser@18.7.0: + resolution: {integrity: sha512-WexT4OswA6Gy86ms2J7SJ4FJscN43dyS+i5skpbtXlPTFQW4yWbontjFip1TOBAVnc+U+9zdH0a56YTRZX/IGw==} + engines: {node: ^22||^24||>=26} + hasBin: true + detect-libc@2.1.2: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} @@ -1081,6 +1118,10 @@ packages: emoji-regex@8.0.0: resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + enhanced-resolve@5.26.0: + resolution: {integrity: sha512-9vhedylFonb2YGogzUKX6+Ja72gOJbN1QHAqdrvqLwhdl/QWbKopzoUC9EbQNVsAns/bx/4uyqalrQAoy1IByw==} + engines: {node: '>=10.13.0'} + entities@7.0.1: resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==} engines: {node: '>=0.12'} @@ -1092,6 +1133,10 @@ packages: error-stack-parser-es@1.0.5: resolution: {integrity: sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==} + es-errors@1.3.0: + resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} + engines: {node: '>= 0.4'} + es-module-lexer@2.3.2: resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} @@ -1134,14 +1179,32 @@ packages: engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} os: [darwin] + function-bind@1.1.2: + resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + get-caller-file@2.0.5: resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} engines: {node: 6.* || 8.* || >= 10.*} + global-directory@4.0.1: + resolution: {integrity: sha512-wHTUcDUoZ1H5/0iVqEudYW4/kAlN5cZ3j/bXn0Dpbizl9iaUVeWSHqiOjsgk6OW2bkLclbBjzewBz6weQ1zA2Q==} + engines: {node: '>=18'} + + graceful-fs@4.2.11: + resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + happy-dom@20.14.5: resolution: {integrity: sha512-x/RzkpWO40bTjIoT30iQtt64FLLmH/iRcUCN2X//bLx7H3ifkdfPXyqsro/OYtqzIAhiLMMA7mmiOR9C3NOKjQ==} engines: {node: '>=20.0.0'} + has-flag@4.0.0: + resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} + engines: {node: '>=8'} + + hasown@2.0.4: + resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} + engines: {node: '>= 0.4'} + html-encoding-sniffer@7.0.0: resolution: {integrity: sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==} engines: {node: ^22.13.0 || >=24.0.0} @@ -1154,14 +1217,38 @@ packages: idb-keyval@6.3.0: resolution: {integrity: sha512-um+2dgAWmYsu615EXpWVwSmapJhON0G43t3Ka/EVaohzPQXSMqKEqeDK/oIW3Ow+BXaF2PvSc+oBTFp793A5Ow==} + ignore@7.0.12: + resolution: {integrity: sha512-/8UvqAPU9DGTI9k4mxtf49U37Isfwr8Uts96+SBHIkFxPJnHS0Ew4f00sM4Scd8V8EjM0jUNtVDdv1kPdt35lg==} + engines: {node: '>= 4'} + ignore@7.0.6: resolution: {integrity: sha512-BAg6QkE8W+TuQLrrw0Ugr7HegXduRuuj8/ti2kSOc+jz1dmx8/WNcjr6XGnq5YpDWxFwwaavqD0+jIUOKelTsw==} engines: {node: '>= 4'} + ini@4.1.1: + resolution: {integrity: sha512-QQnnxNyfvmHFIsj7gkPcYymR8Jdw/o7mp5ZFihxn6h8Ci6fh3Dx4E1gPjpQEpIuPo9XVNY/ZUwh4BPMjGyL01g==} + engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} + + interpret@3.1.1: + resolution: {integrity: sha512-6xwYfHbajpoF0xLW+iwLkhwgvLoZDfjYfoFNu8ftMoXINzwuymNLd9u/KmwtdT2GbR+/Cz66otEGEVVUHX9QLQ==} + engines: {node: '>=10.13.0'} + + is-core-module@2.17.0: + resolution: {integrity: sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA==} + engines: {node: '>= 0.4'} + is-fullwidth-code-point@3.0.0: resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} engines: {node: '>=8'} + is-installed-globally@1.0.1: + resolution: {integrity: sha512-li88H4QGRoNMX27jEmY8nR515oJVspAgC/WFMlhHfFV8RJ4QyGpHhXnwAe9gH5RIgKmdYRUmrOhQobcgEjIdSw==} + engines: {node: '>=18'} + + is-path-inside@4.0.0: + resolution: {integrity: sha512-lJJV/5dYS+RcL8uQdBDW9c9uWFLLBNRyFhnAKXw5tVqLlKZ4RMGZKv+YQ/IA3OhD+RpbJa1LLFM1FQPGyIXvOA==} + engines: {node: '>=12'} + is-potential-custom-element-name@1.0.1: resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} @@ -1181,6 +1268,15 @@ packages: canvas: optional: true + json5@2.2.3: + resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} + engines: {node: '>=6'} + hasBin: true + + kleur@3.0.3: + resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==} + engines: {node: '>=6'} + kleur@4.1.5: resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==} engines: {node: '>=6'} @@ -1282,6 +1378,9 @@ packages: resolution: {integrity: sha512-7IDj9monoYcCPrS8HfcTt90T3pDwKGvNEAR1Y061KbJhBd5JkStOwOpHMUDFBo9PEbjWVDxPICAnXGNNV2LNfQ==} engines: {node: '>=22.0.0'} + minimist@1.2.8: + resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} + moment@2.29.4: resolution: {integrity: sha512-5LC9SOxjSc2HF6vO2CyuTDNivEdoz2IvyJJGj6X8DJ0eFyfszE0QiEd+iXmBvUP3WHxSjFH/vIsA0EN00cgr8w==} @@ -1319,6 +1418,9 @@ packages: resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} engines: {node: '>=8'} + path-parse@1.0.7: + resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} + path-to-regexp@6.3.0: resolution: {integrity: sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==} @@ -1332,6 +1434,10 @@ packages: resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==} engines: {node: '>=12'} + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + playwright-core@1.63.0: resolution: {integrity: sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==} engines: {node: '>=20'} @@ -1345,6 +1451,10 @@ packages: resolution: {integrity: sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==} engines: {node: ^10 || ^12 || >=14} + prompts@2.4.2: + resolution: {integrity: sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==} + engines: {node: '>= 6'} + punycode@2.3.1: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} @@ -1354,6 +1464,14 @@ packages: engines: {node: '>=10.13.0'} hasBin: true + rechoir@0.8.0: + resolution: {integrity: sha512-/vxpCXddiX8NGfGO/mTafwjq4aFa/71pvamip0++IQk3zG8cbCj0fifNPrjjF1XMXUne91jL9OoxmdykoEtifQ==} + engines: {node: '>= 10.13.0'} + + regexp-tree@0.1.27: + resolution: {integrity: sha512-iETxpjK6YoRWJG5o6hXLwvjYAoW+FEZn9os0PD/b6AP6xQwsa/Y7lCVgIixBbUPMfhu+i2LtdeAqVTgGlQarfA==} + hasBin: true + require-directory@2.1.1: resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} engines: {node: '>=0.10.0'} @@ -1365,11 +1483,19 @@ packages: require-main-filename@2.0.0: resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==} + resolve@1.22.13: + resolution: {integrity: sha512-Dj/cW9zBV2aRj6XzCxuGIs3ESZKv02jixne3q6jFZYZ3/Tg09gHHviSMDL4kObh9pqSahdRHEnDoaP2gn8YLhA==} + engines: {node: '>= 0.4'} + hasBin: true + rolldown@1.0.1: resolution: {integrity: sha512-X0KQHljNnEkWNqqiz9zJrGunh1B0HgOxLXvnFpCOcadzcy5qohZ3tqMEUg00vncoRovXuK3ZqCT9KnnKzoInFQ==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true + safe-regex@2.1.1: + resolution: {integrity: sha512-rx+x8AMzKb5Q5lQ95Zoi6ZbJqwCLkqi3XuJXp5P3rT8OEc6sZCJG5AE5dU3lsgRr/F4Bs31jSlVN+j5KrsGu9A==} + saxes@6.0.0: resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} engines: {node: '>=v12.22.7'} @@ -1394,6 +1520,9 @@ packages: siginfo@2.0.0: resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + sisteransi@1.0.5: + resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==} + source-map-js@1.2.1: resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} engines: {node: '>=0.10.0'} @@ -1412,6 +1541,10 @@ packages: resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} engines: {node: '>=8'} + strip-bom@3.0.0: + resolution: {integrity: sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==} + engines: {node: '>=4'} + style-mod@4.1.3: resolution: {integrity: sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==} @@ -1419,6 +1552,18 @@ packages: resolution: {integrity: sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==} engines: {node: '>=18'} + supports-color@7.2.0: + resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} + engines: {node: '>=8'} + + supports-preserve-symlinks-flag@1.0.0: + resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} + engines: {node: '>= 0.4'} + + tapable@2.3.3: + resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==} + engines: {node: '>=6'} + tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} @@ -1449,6 +1594,14 @@ packages: resolution: {integrity: sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==} engines: {node: ^22.14.0 || >=24.0.0} + tsconfig-paths-webpack-plugin@4.2.0: + resolution: {integrity: sha512-zbem3rfRS8BgeNK50Zz5SIQgXzLafiHjOwUAvk/38/o1jHn/V5QAgVUcz884or7WYcPaH3N2CIfUc2u0ul7UcA==} + engines: {node: '>=10.13.0'} + + tsconfig-paths@4.2.0: + resolution: {integrity: sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg==} + engines: {node: '>=6'} + tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} @@ -1569,6 +1722,11 @@ packages: resolution: {integrity: sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==} engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0} + watskeburt@6.0.0: + resolution: {integrity: sha512-jfiuDABaxSkC71T6oZ3vCS99roYkSHm/+As+G0Dz8taAHQb+SJBvLEm5RlsgG71XdfAj3rv7eudUBTgwcQUPlQ==} + engines: {node: ^22.13||^24||>=26} + hasBin: true + webidl-conversions@8.0.1: resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==} engines: {node: '>=20'} @@ -2286,6 +2444,22 @@ snapshots: convert-source-map: 2.0.0 tinyrainbow: 3.1.1 + acorn-jsx-walk@2.0.0: {} + + acorn-jsx@5.3.2(acorn@8.19.0): + dependencies: + acorn: 8.19.0 + + acorn-loose@8.5.2: + dependencies: + acorn: 8.19.0 + + acorn-walk@8.3.5: + dependencies: + acorn: 8.19.0 + + acorn@8.19.0: {} + ansi-regex@5.0.1: {} ansi-styles@4.3.0: @@ -2309,6 +2483,11 @@ snapshots: chai@6.2.2: {} + chalk@4.1.2: + dependencies: + ansi-styles: 4.3.0 + supports-color: 7.2.0 + cliui@6.0.0: dependencies: string-width: 4.2.3 @@ -2321,6 +2500,8 @@ snapshots: color-name@1.1.4: {} + commander@15.0.0: {} + convert-source-map@2.0.0: {} cookie@1.1.1: {} @@ -2343,6 +2524,27 @@ snapshots: decimal.js@10.6.0: {} + dependency-cruiser@18.7.0: + dependencies: + acorn: 8.19.0 + acorn-jsx: 5.3.2(acorn@8.19.0) + acorn-jsx-walk: 2.0.0 + acorn-loose: 8.5.2 + acorn-walk: 8.3.5 + commander: 15.0.0 + enhanced-resolve: 5.26.0 + ignore: 7.0.12 + interpret: 3.1.1 + is-installed-globally: 1.0.1 + json5: 2.2.3 + picomatch: 4.0.7 + prompts: 2.4.2 + rechoir: 0.8.0 + safe-regex: 2.1.1 + semver: 7.8.5 + tsconfig-paths-webpack-plugin: 4.2.0 + watskeburt: 6.0.0 + detect-libc@2.1.2: {} dijkstrajs@1.0.3: {} @@ -2353,6 +2555,11 @@ snapshots: emoji-regex@8.0.0: {} + enhanced-resolve@5.26.0: + dependencies: + graceful-fs: 4.2.11 + tapable: 2.3.3 + entities@7.0.1: optional: true @@ -2360,6 +2567,8 @@ snapshots: error-stack-parser-es@1.0.5: {} + es-errors@1.3.0: {} + es-module-lexer@2.3.2: {} esbuild@0.25.12: @@ -2440,8 +2649,16 @@ snapshots: fsevents@2.3.3: optional: true + function-bind@1.1.2: {} + get-caller-file@2.0.5: {} + global-directory@4.0.1: + dependencies: + ini: 4.1.1 + + graceful-fs@4.2.11: {} + happy-dom@20.14.5: dependencies: '@types/node': 22.20.1 @@ -2456,6 +2673,12 @@ snapshots: - utf-8-validate optional: true + has-flag@4.0.0: {} + + hasown@2.0.4: + dependencies: + function-bind: 1.1.2 + html-encoding-sniffer@7.0.0: dependencies: '@exodus/bytes': 1.16.0 @@ -2466,10 +2689,27 @@ snapshots: idb-keyval@6.3.0: {} + ignore@7.0.12: {} + ignore@7.0.6: {} + ini@4.1.1: {} + + interpret@3.1.1: {} + + is-core-module@2.17.0: + dependencies: + hasown: 2.0.4 + is-fullwidth-code-point@3.0.0: {} + is-installed-globally@1.0.1: + dependencies: + global-directory: 4.0.1 + is-path-inside: 4.0.0 + + is-path-inside@4.0.0: {} + is-potential-custom-element-name@1.0.1: {} isomorphic.js@0.2.5: {} @@ -2501,6 +2741,10 @@ snapshots: transitivePeerDependencies: - '@noble/hashes' + json5@2.2.3: {} + + kleur@3.0.3: {} + kleur@4.1.5: {} lib0@0.2.117: @@ -2583,6 +2827,8 @@ snapshots: - bufferutil - utf-8-validate + minimist@1.2.8: {} + moment@2.29.4: {} nanoid@3.3.18: {} @@ -2612,6 +2858,8 @@ snapshots: path-exists@4.0.0: {} + path-parse@1.0.7: {} + path-to-regexp@6.3.0: {} pathe@2.0.3: {} @@ -2620,6 +2868,8 @@ snapshots: picomatch@4.0.5: {} + picomatch@4.0.7: {} + playwright-core@1.63.0: {} pngjs@5.0.0: {} @@ -2630,6 +2880,11 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.1 + prompts@2.4.2: + dependencies: + kleur: 3.0.3 + sisteransi: 1.0.5 + punycode@2.3.1: {} qrcode@1.5.4: @@ -2638,12 +2893,25 @@ snapshots: pngjs: 5.0.0 yargs: 15.4.1 + rechoir@0.8.0: + dependencies: + resolve: 1.22.13 + + regexp-tree@0.1.27: {} + require-directory@2.1.1: {} require-from-string@2.0.2: {} require-main-filename@2.0.0: {} + resolve@1.22.13: + dependencies: + es-errors: 1.3.0 + is-core-module: 2.17.0 + path-parse: 1.0.7 + supports-preserve-symlinks-flag: 1.0.0 + rolldown@1.0.1: dependencies: '@oxc-project/types': 0.130.0 @@ -2665,6 +2933,10 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.0.1 '@rolldown/binding-win32-x64-msvc': 1.0.1 + safe-regex@2.1.1: + dependencies: + regexp-tree: 0.1.27 + saxes@6.0.0: dependencies: xmlchars: 2.2.0 @@ -2708,6 +2980,8 @@ snapshots: siginfo@2.0.0: {} + sisteransi@1.0.5: {} + source-map-js@1.2.1: {} stackback@0.0.2: {} @@ -2724,10 +2998,20 @@ snapshots: dependencies: ansi-regex: 5.0.1 + strip-bom@3.0.0: {} + style-mod@4.1.3: {} supports-color@10.2.2: {} + supports-color@7.2.0: + dependencies: + has-flag: 4.0.0 + + supports-preserve-symlinks-flag@1.0.0: {} + + tapable@2.3.3: {} + tinybench@2.9.0: {} tinyexec@1.3.0: {} @@ -2753,6 +3037,19 @@ snapshots: dependencies: punycode: 2.3.1 + tsconfig-paths-webpack-plugin@4.2.0: + dependencies: + chalk: 4.1.2 + enhanced-resolve: 5.26.0 + tapable: 2.3.3 + tsconfig-paths: 4.2.0 + + tsconfig-paths@4.2.0: + dependencies: + json5: 2.2.3 + minimist: 1.2.8 + strip-bom: 3.0.0 + tslib@2.8.1: {} turndown-plugin-gfm@1.0.2: {} @@ -2865,6 +3162,8 @@ snapshots: dependencies: xml-name-validator: 5.0.0 + watskeburt@6.0.0: {} + webidl-conversions@8.0.1: {} whatwg-mimetype@3.0.0: diff --git a/tests/e2e/README.md b/tests/e2e/README.md new file mode 100644 index 00000000..7399716a --- /dev/null +++ b/tests/e2e/README.md @@ -0,0 +1,47 @@ +# End-to-end scenarios + +Scenarios run real processes (Obsidian, `wrangler dev`, headless Chrome, in-memory S3 and WebDAV) and tear them down. Run from the repo root with `pnpm e2e:`; the scripts that drive the plugin run `pnpm build` first (`tests/e2e/optimization-ui.ts` has no script: build by hand). Rules for writing tests: `.claude/rules/testing.md`. + +## Prerequisites + +- **Obsidian** at the default Windows path, or set `OBSIDIAN_EXE`. On macOS: `OBSIDIAN_EXE=/Applications/Obsidian.app/Contents/MacOS/Obsidian pnpm e2e:live`. Each scenario starts a throwaway Obsidian (own `--user-data-dir`, temp vault, the trust modal clicked) with the built `packages/plugin/main.js`, `packages/plugin/styles.css` and `manifest.json`. +- **Ports** 8799 (relay), 8801 (WebDAV), 8802 (S3), 9223 and 9224 (CDP) must be free; a few scenarios use their own (listed below). 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. +- Several Obsidians need distinct CDP ports. On Windows they run on a desktop of their own (`tests/e2e/hidden-desktop.ps1`) and never take focus; `E2E_VISIBLE=1` shows them. `E2E_SHOTS=1` saves screenshots under `artifacts/e2e-shots/`. + +## Scenarios + +| Command | Covers | +|---|---| +| `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. Build first. Ports 8832, 9233 | +| `pnpm e2e:settings` | passphrase and toggle scroll retention, device-only ignore rules, phone layouts at 320, 390 and 600 px. Port 9235 | +| `pnpm e2e:setup` | fresh install opens the wizard; one device starts a vault (Other storage on in-memory S3, passphrase, relay skipped, Sync now), a second joins by its setup link. Ports 9241, 9242, 8841 | +| `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, folds, anchors, wide text, code copy). Port 8799 | +| `pnpm e2e:links-obsidian` | 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, passphrase, view count, update, stop. Ports 8799, 9246; `E2E_SHOTS=1` saves `link-viewer.png` | +| `pnpm e2e:hub` | the relay hub under `wrangler dev` with scripted peers; ending a share cuts its channel for good, across a restart too; the last run sets `HUB_STALE_MS` low to watch the stale-socket sweep | +| `pnpm e2e:realtime` | the plugin in a throwaway Obsidian against the relay; a scripted peer reads and writes 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. Undo (phone toolbar path and Edit menu) takes back only the device's own typing. A file written under the open note from outside joins the room; a rename of the open note is followed by the other device | +| `pnpm e2e:shares` | two Obsidians of one owner on an in-memory S3: one shares a folder through its menu, the other mounts, pauses and resumes it; a rename of the folder is followed | +| `pnpm e2e:invite` | an owner and a participant with separate vaults: invite through the broker, accept through the protocol handler; each edit reaches the other on the share channel's signal alone; a change or rename in the share pushes by itself | +| `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 (editor locked, follows the owner live), a re-invite that kills the old link and takes over the folder in place, the owner's rotated S3 key (`s3.revoke`) reaching the broker, access and Revoke in the share's window | +| `pnpm e2e:live-share` | owner and participant type into one note of a share in its room; the cursor carries the invited name, authors tint the other's text, the sync after is clean; presence reaches a device with no note open, the tree and window show who is where, follow cursor jumps and scrolls until the owner's wheel ends 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/`): shapes, concurrent edits and a deletion cross, the pointer shows, file sync of drawings with different zoom settles clean; with live off a saved drawing view takes what the sync writes under it | +| `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 change signs of one note on the other, the header's live mark never drops, each note keeps its text | + +## Writing a scenario + +- Reuse `launchObsidian` (`tests/e2e/obsidian.ts`), `startRelay` (`tests/e2e/relay.ts`), `startWebDav` (`tests/e2e/webdav.ts`), `startS3` (`tests/e2e/s3.ts`) and `connectPeer` (`tests/e2e/peer.ts`); `runScenario`, `check` and `poll` are in `tests/e2e/harness.ts`. +- `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 an 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. +- Throw on the first broken expectation (`check`): later steps build on earlier ones. + +## Manual install + +Copy `main.js`, `styles.css` (both from `pnpm build` or `pnpm dev`, neither is in git) and `manifest.json` to `/.obsidian/plugins/mdsync/`, reload Obsidian and enable the plugin in **Settings → Community plugins**. To drive that instance by hand, see the Real Obsidian section of `.claude/rules/testing.md`. + +## Mobile + +Test on iOS and Android where feasible; the plugin is not desktop-only. The e2e phone layouts (`pnpm e2e:settings`) emulate widths, not a device. diff --git a/tools/fixtures/diff-ui.mjs b/tools/fixtures/diff-ui.mjs index 0e8a97de..52252b9f 100644 --- a/tools/fixtures/diff-ui.mjs +++ b/tools/fixtures/diff-ui.mjs @@ -8,7 +8,7 @@ const jiti = createJiti(import.meta.url, { }, }); const { computeHunks } = await jiti.import( - "../../packages/plugin/src/sync/hunks.ts", + "../../packages/plugin/src/features/sync/hunks/hunks.ts", ); // Synthetic models exercise the real renderer; controller calls are captured, never sent. From ddd22a2beea54c22e45f7fd6f455c685f08c2a30 Mon Sep 17 00:00:00 2001 From: kitbyte Date: Tue, 27 Oct 2026 16:02:47 +0200 Subject: [PATCH 02/26] refactor(plugin): slice facades and host interfaces, main.ts split into app/ --- .claude/rules/history.md | 4 +- .claude/rules/realtime.md | 1 + .claude/rules/security.md | 6 +- .claude/rules/settings-setup.md | 10 +- .claude/rules/spaces.md | 2 +- .claude/rules/structure.md | 21 +- .claude/skills/new-feature/SKILL.md | 6 +- biome.json | 6 +- .../.dependency-cruiser-known-violations.json | 3827 ----------------- packages/plugin/.dependency-cruiser.cjs | 25 +- packages/plugin/package.json | 2 +- packages/plugin/src/app/bootstrap.ts | 34 +- packages/plugin/src/app/commands.ts | 3 +- packages/plugin/src/app/events.ts | 78 +- packages/plugin/src/app/host.ts | 2 + packages/plugin/src/app/protocols.ts | 28 +- packages/plugin/src/app/realtime.ts | 4 +- packages/plugin/src/app/runtime-hooks.ts | 51 + packages/plugin/src/app/scope-refresh.ts | 44 + packages/plugin/src/app/session-factory.ts | 70 +- .../envelope.ts} | 3 +- packages/plugin/src/app/settings/index.ts | 18 + packages/plugin/src/app/settings/store.ts | 50 + .../storage => app}/storage-refused.ts | 7 +- packages/plugin/src/app/views.ts | 25 - packages/plugin/src/core/constants.ts | 3 + packages/plugin/src/core/hub/index.ts | 7 + packages/plugin/src/core/hub/space-hub.ts | 37 + packages/plugin/src/core/settings/fields.ts | 85 +- packages/plugin/src/core/settings/index.ts | 15 +- packages/plugin/src/core/settings/model.ts | 137 +- packages/plugin/src/core/shared/format.ts | 4 +- packages/plugin/src/core/shared/index.ts | 2 +- packages/plugin/src/core/shared/offline.ts | 8 +- .../src/core/shared/transport-errors.ts | 21 + packages/plugin/src/core/ui/index.ts | 2 +- packages/plugin/src/core/ui/menu.ts | 11 - packages/plugin/src/core/ui/notices.ts | 5 +- packages/plugin/src/core/utils/index.ts | 6 - .../plugin/src/features/diff/action-bar.ts | 2 +- packages/plugin/src/features/diff/choices.ts | 4 +- .../diff/compare/compare-decorations.ts | 8 +- .../features/diff/compare/compare-panel.ts | 5 +- .../plugin/src/features/diff/history-state.ts | 42 +- packages/plugin/src/features/diff/host.ts | 9 + packages/plugin/src/features/diff/index.ts | 9 +- .../src/features/diff/lines/change-overlay.ts | 2 +- .../plugin/src/features/diff/lines/divider.ts | 2 +- .../src/features/diff/lines/gap-widgets.ts | 2 +- .../src/features/diff/lines/geometry.ts | 2 +- .../src/features/diff/lines/scroll-sync.ts | 2 +- .../utils => features/diff/lines}/search.ts | 0 .../src/features/diff/lines/source-widget.ts | 2 +- .../src/features/diff/merge/edit-plan.ts | 226 + .../src/features/diff/merge/merge-actions.ts | 8 +- .../src/features/diff/merge/merge-cards.ts | 6 +- .../src/features/diff/merge/merge-controls.ts | 7 +- .../features/diff/merge/merge-decorations.ts | 6 +- .../src/features/diff/merge/merge-editor.ts | 10 +- .../src/features/diff/merge/merge-state.ts | 8 +- .../plugin/src/features/diff/operations.ts | 17 +- .../features/diff/{ => ui}/restore-modal.ts | 8 +- packages/plugin/src/features/diff/view.ts | 15 +- .../plugin/src/features/editor-signs/host.ts | 10 + .../plugin/src/features/editor-signs/index.ts | 1 + .../src/features/editor-signs/register.ts | 16 +- .../explorer/file-context-indicators.ts | 7 +- .../features/explorer/file-explorer-badges.ts | 10 +- .../explorer/file-explorer-decorations.ts | 8 +- .../explorer/file-explorer-indicators.ts | 6 +- .../features/explorer/file-explorer-marks.ts | 10 +- packages/plugin/src/features/explorer/host.ts | 8 + .../plugin/src/features/explorer/index.ts | 1 + .../src/features/explorer/row-decorator.ts | 4 +- packages/plugin/src/features/links/host.ts | 10 + packages/plugin/src/features/links/index.ts | 3 +- .../plugin/src/features/links/link-broker.ts | 15 +- .../plugin/src/features/links/note-links.ts | 5 +- packages/plugin/src/features/links/publish.ts | 18 +- packages/plugin/src/features/links/record.ts | 13 + .../plugin/src/features/links/register.ts | 4 +- .../src/features/links/ui/link-actions.ts | 6 +- .../plugin/src/features/links/ui/link-menu.ts | 13 +- .../src/features/links/ui/links-section.ts | 6 +- .../features/links/ui/manage-links-modal.ts | 4 +- .../src/features/links/ui/note-link-action.ts | 4 +- .../src/features/links/ui/share-link-modal.ts | 6 +- .../src/features/live/cold/cold-sync.ts | 6 +- packages/plugin/src/features/live/register.ts | 39 +- .../src/features/live/session/rotation.ts | 3 +- .../src/features/live/session/session-deps.ts | 3 +- .../src/features/live/session/session.ts | 2 +- .../plugin/src/features/live/text/merge.ts | 6 +- .../plugin/src/features/live/text/patch.ts | 2 +- .../src/features/live/ui/deleted-elsewhere.ts | 14 +- .../src/features/live/workspace/rename.ts | 10 +- .../src/features/live/workspace/room.ts | 4 +- .../src/features/live/workspace/space.ts | 2 +- .../src/features/note-header/header-state.ts | 7 +- .../plugin/src/features/note-header/host.ts | 13 + .../plugin/src/features/note-header/index.ts | 1 + .../src/features/note-header/live-actions.ts | 6 +- .../src/features/note-header/live-status.ts | 6 +- .../src/features/note-header/note-menu.ts | 10 +- .../src/features/note-header/note-presence.ts | 6 +- .../features/presence/follow/cursor-follow.ts | 4 +- .../features/presence/follow/follow-scroll.ts | 4 +- .../src/features/presence/follow/follows.ts | 4 +- packages/plugin/src/features/presence/host.ts | 9 + .../plugin/src/features/presence/index.ts | 8 +- .../plugin/src/features/presence/people.ts | 6 +- .../plugin/src/features/presence/register.ts | 2 +- .../src/features/presence/ui/avatars.ts | 8 + .../plugin/src/features/relay/channels.ts | 15 +- .../plugin/src/features/relay/connection.ts | 45 +- .../src/features/relay/deploy/deploy-flow.ts | 12 +- packages/plugin/src/features/relay/host.ts | 12 + packages/plugin/src/features/relay/index.ts | 9 +- .../plugin/src/features/relay/relay-test.ts | 64 + .../src/features/relay/ui/relay-section.ts | 13 +- .../relay/update/relay-update-modal.ts | 4 +- .../src/features/relay/update/relay-update.ts | 7 +- packages/plugin/src/features/settings/host.ts | 25 + .../plugin/src/features/settings/index.ts | 1 + .../plugin/src/features/settings/logs-view.ts | 6 +- .../plugin/src/features/settings/overview.ts | 27 +- .../features/settings/sections/advanced.ts | 6 +- .../features/settings/sections/automation.ts | 42 +- .../features/settings/sections/interface.ts | 10 +- packages/plugin/src/features/settings/tab.ts | 27 +- packages/plugin/src/features/setup/README.md | 1 - packages/plugin/src/features/setup/host.ts | 13 + packages/plugin/src/features/setup/index.ts | 1 + .../plugin/src/features/setup/step-state.ts | 14 +- .../src/features/setup/steps/import-step.ts | 3 +- .../features/setup/steps/passphrase-step.ts | 2 +- .../src/features/setup/steps/ready-step.ts | 17 +- .../features/setup/steps/relay-deploy-view.ts | 16 +- .../src/features/setup/steps/relay-step.ts | 9 +- .../src/features/setup/steps/start-step.ts | 2 +- .../src/features/setup/steps/storage-step.ts | 8 +- packages/plugin/src/features/setup/wizard.ts | 9 +- .../source-control/actions/actions.ts | 17 +- .../source-control/changes/changes-section.ts | 2 +- .../source-control/changes/changes-tab.ts | 8 +- .../source-control/changes/excluded-files.ts | 11 +- .../source-control/changes/row-formatter.ts | 8 +- .../source-control/history/history-tab.ts | 8 +- .../src/features/source-control/host.ts | 8 + .../src/features/source-control/index.ts | 9 +- .../features/source-control/setup-prompt.ts | 6 +- .../features/source-control/summary-card.ts | 26 +- .../source-control/timeline/snapshot-menu.ts | 4 +- .../timeline/timeline-actions.ts | 6 +- .../source-control/timeline/timeline-rows.ts | 2 +- .../source-control/timeline/timeline-tab.ts | 6 +- .../source-control/trash/trash-tab.ts | 9 +- .../src/features/source-control/view.ts | 115 +- .../src/features/source-control/workspace.ts | 107 + .../features/spaces/broker/share-broker.ts | 14 +- packages/plugin/src/features/spaces/host.ts | 14 + packages/plugin/src/features/spaces/index.ts | 13 +- packages/plugin/src/features/spaces/owner.ts | 10 + .../plugin/src/features/spaces/partition.ts | 2 +- packages/plugin/src/features/spaces/record.ts | 11 + .../plugin/src/features/spaces/records.ts | 2 +- .../plugin/src/features/spaces/share-moves.ts | 8 +- .../src/features/spaces/share-registration.ts | 8 +- .../src/features/spaces/space-access.ts | 8 +- .../src/features/spaces/ui/access-ended.ts | 7 +- .../src/features/spaces/ui/inert-warning.ts | 16 + .../spaces/ui/invites/invite-action.ts | 20 +- .../src/features/spaces/{ => ui}/last-edit.ts | 14 +- .../src/features/spaces/ui/read-only.ts | 10 +- .../src/features/spaces/ui/share-action.ts | 20 +- .../src/features/spaces/ui/shares-section.ts | 7 +- .../src/features/spaces/ui/space-gone.ts | 6 +- .../features/spaces/ui/window/people-list.ts | 4 +- .../features/spaces/ui/window/share-modal.ts | 9 +- .../features/spaces/ui/window/share-window.ts | 11 +- packages/plugin/src/features/status/host.ts | 9 + packages/plugin/src/features/status/index.ts | 1 + .../plugin/src/features/status/live-spaces.ts | 8 +- .../src/features/status/relay-status.ts | 4 +- .../plugin/src/features/status/status-bar.ts | 13 +- .../plugin/src/features/status/status-menu.ts | 16 +- .../plugin/src/features/status/where-menu.ts | 13 +- .../storage/backends/google-drive-auth.ts | 7 +- .../storage/backends/google-drive-request.ts | 2 +- .../features/storage/backends/google-drive.ts | 3 +- .../src/features/storage/backends/s3-store.ts | 2 +- .../src/features/storage/backends/s3.ts | 7 +- .../src/features/storage/backends/util.ts | 26 +- .../src/features/storage/backends/webdav.ts | 11 +- .../storage/cloudflare/cloudflare-login.ts | 6 +- .../features/storage/cloudflare/r2-select.ts | 12 +- .../plugin/src/features/storage/field-spec.ts | 11 +- packages/plugin/src/features/storage/host.ts | 7 + packages/plugin/src/features/storage/index.ts | 24 +- .../plugin/src/features/storage/settings.ts | 58 + .../src/features/storage/ui/authorize.ts | 27 + .../features/storage/ui/backend-section.ts | 6 +- .../features/storage/ui/connection-test.ts | 84 +- .../src/features/storage/ui/storage-fields.ts | 19 +- .../storage/ui/storage-refused-modal.ts | 7 +- .../src/features/sync/apply/auto-merge.ts | 3 +- .../src/features/sync/apply/pull-moves.ts | 3 +- .../plugin/src/features/sync/apply/pull.ts | 6 +- .../src/features/sync/automation/scheduler.ts | 4 +- .../sync/changes}/file-concurrency.ts | 2 +- .../sync/changes}/records.ts | 0 .../plugin/src/features/sync/constants.ts | 2 - .../plugin/src/features/sync/controller.ts | 17 +- packages/plugin/src/features/sync/engine.ts | 10 +- .../src/features/sync/history/changes.ts | 2 +- .../plugin/src/features/sync/history/query.ts | 2 +- .../features/sync/history/restore-vault.ts | 2 +- packages/plugin/src/features/sync/host.ts | 19 + .../src/features/sync/hunks/merge-model.ts | 216 - .../features/sync/identity/vault-mismatch.ts | 8 + packages/plugin/src/features/sync/index.ts | 18 +- .../plugin/src/features/sync/live-notes.ts | 3 +- .../src/features/sync/operations/pull.ts | 3 +- .../src/features/sync/operations/resolve.ts | 4 +- .../src/features/sync/operations/revert.ts | 3 +- .../src/features/sync/recovery/cut-short.ts | 3 +- .../src/features/sync/remote/baseline.ts | 2 +- .../src/features/sync/remote/foreign.ts | 2 +- .../src/features/sync/remote/keyfile.ts | 2 +- .../src/features/sync/remote/manifest.ts | 7 +- .../sync/remote/passphrase-manager.ts | 59 +- .../plugin/src/features/sync/remote/reset.ts | 3 +- .../sync/{session.ts => remote/salt.ts} | 2 +- .../features/sync/runtime/history-service.ts | 7 +- .../src/features/sync/runtime/maintenance.ts | 3 +- .../features/sync/runtime/merged-result.ts | 2 +- .../features/sync/runtime/saved-refresh.ts | 3 +- .../sync/scope/configuration-scope-section.ts | 7 +- .../features/sync/scope/exclusions-section.ts | 10 +- .../src/features/sync/scope/ignore-state.ts | 4 +- .../plugin/src/features/sync/scope/scanner.ts | 11 +- .../plugin/src/features/sync/session-state.ts | 3 +- packages/plugin/src/features/sync/settings.ts | 24 + .../ui/encryption-section.ts} | 21 +- .../src/features/sync/ui/ignore-action.ts | 17 +- .../features/sync/ui/maintenance-actions.ts | 13 +- .../features/sync/ui/maintenance-section.ts | 7 +- .../src/features/sync/ui/push-action.ts | 10 +- .../src/features/sync/ui/sync-actions.ts | 17 +- .../src/features/sync/ui/vault-adoption.ts | 7 +- packages/plugin/src/features/transfer/host.ts | 9 + .../plugin/src/features/transfer/index.ts | 1 + .../plugin/src/features/transfer/transfer.ts | 27 +- .../transfer/ui/device-transfer-section.ts | 3 +- .../transfer/ui/settings-transfer-modal.ts | 4 +- packages/plugin/src/main.ts | 158 +- packages/plugin/tests/app/realtime.test.ts | 5 +- .../plugin/tests/app/scope-refresh.test.ts | 74 + .../plugin/tests/app/session-factory.test.ts | 3 +- .../tests/app/{ => settings}/envelope.test.ts | 5 +- .../plugin/tests/app/settings/index.test.ts | 241 ++ .../plugin/tests/app/settings/store.test.ts | 74 + .../storage => app}/storage-refused.test.ts | 4 +- .../tests/core/cloudflare/token.test.ts | 78 + .../plugin/tests/core/settings/fields.test.ts | 2 +- .../plugin/tests/core/settings/model.test.ts | 245 +- .../tests/core/settings/number-field.test.ts | 2 +- .../plugin/tests/core/shared/offline.test.ts | 2 +- .../features/diff/diff-operations.test.ts | 6 +- .../features/diff/diff-view-status.test.ts | 3 - .../diff/lines}/search.test.ts | 2 +- .../features/diff/merge/edit-plan.test.ts | 194 + .../features/diff/merge/merge-state.test.ts | 3 +- .../tests/features/links/link-broker.test.ts | 2 +- .../features/links/ui/link-actions.test.ts | 6 - .../features/live/session/follower.test.ts | 2 +- .../features/live/workspace/rename.test.ts | 3 +- .../tests/features/relay/connection.test.ts | 3 +- .../relay/deploy}/relay-account.test.ts | 0 .../relay/deploy}/relay-deploy.test.ts | 0 .../tests/features/relay/deploy/relay.test.ts | 6 +- .../relay-test.test.ts} | 2 +- .../features/relay/ui/relay-section.test.ts | 6 +- .../relay/update/relay-update.test.ts | 8 +- .../tests/features/setup/step-state.test.ts | 3 +- .../features/setup/steps/relay-step.test.ts | 8 +- .../timeline/timeline-actions.test.ts | 2 +- .../spaces/share-registration.test.ts | 3 +- .../features/spaces/space-access.test.ts | 3 +- .../features/spaces/ui/shares-section.test.ts | 3 +- .../features/storage/backends/util.test.ts | 6 +- .../storage/cloudflare/r2-select.test.ts | 4 +- .../storage}/cloudflare/r2.test.ts | 76 - .../tests/features/sync/auto-cycle.test.ts | 2 +- .../automation/scheduler-interval.test.ts | 2 +- .../automation/scheduler-queued-push.test.ts | 2 +- .../sync/automation/scheduler-startup.test.ts | 2 +- .../sync/category-reset-roundtrip.test.ts | 2 +- .../sync/changes}/file-concurrency.test.ts | 2 +- .../features/sync/engine-roundtrip.test.ts | 6 +- .../features/sync/hunks/merge-model.test.ts | 191 - .../sync/operations/lost-push.test.ts | 2 +- .../sync/remote/manifest-guard.test.ts | 2 +- .../sync/remote/manifest-revalidate.test.ts | 2 +- .../sync/remote/passphrase-manager.test.ts | 78 +- .../sync/remote/passphrase-storage.test.ts | 2 +- .../tests/features/sync/remote/reset.test.ts | 2 +- .../sync/remote/space-roundtrip.test.ts | 2 +- .../tests/features/sync/remote/spaces.test.ts | 2 +- .../sync/runtime/operation-runner.test.ts | 2 +- .../sync/runtime/saved-refresh.test.ts | 2 +- .../features/sync/transfer-memory.test.ts | 2 +- .../ui/encryption-section.test.ts} | 16 +- .../features/sync/upload-listing.test.ts | 6 +- .../transfer/transfer-controller.test.ts | 3 +- .../tests/features/transfer/transfer.test.ts | 3 +- .../plugin/tests/helpers/explorer-host.ts | 2 +- packages/plugin/tests/helpers/live-hub.ts | 7 +- packages/plugin/tests/helpers/manifest.ts | 2 +- .../plugin/tests/helpers/presence-relay.ts | 3 +- packages/protocol/README.md | 1 + packages/protocol/src/admin.ts | 2 + packages/protocol/src/index.ts | 1 + packages/relay/src/index.ts | 3 +- packages/relay/src/secret.ts | 4 +- tests/e2e/README.md | 4 +- tests/e2e/live-drawing.ts | 17 +- tests/e2e/obsidian.ts | 7 +- 328 files changed, 2918 insertions(+), 6148 deletions(-) delete mode 100644 packages/plugin/.dependency-cruiser-known-violations.json create mode 100644 packages/plugin/src/app/runtime-hooks.ts create mode 100644 packages/plugin/src/app/scope-refresh.ts rename packages/plugin/src/app/{settings-envelope.ts => settings/envelope.ts} (96%) create mode 100644 packages/plugin/src/app/settings/index.ts create mode 100644 packages/plugin/src/app/settings/store.ts rename packages/plugin/src/{features/storage => app}/storage-refused.ts (78%) create mode 100644 packages/plugin/src/core/hub/space-hub.ts create mode 100644 packages/plugin/src/core/shared/transport-errors.ts create mode 100644 packages/plugin/src/features/diff/host.ts rename packages/plugin/src/{core/utils => features/diff/lines}/search.ts (100%) create mode 100644 packages/plugin/src/features/diff/merge/edit-plan.ts rename packages/plugin/src/features/diff/{ => ui}/restore-modal.ts (97%) create mode 100644 packages/plugin/src/features/editor-signs/host.ts create mode 100644 packages/plugin/src/features/explorer/host.ts create mode 100644 packages/plugin/src/features/links/host.ts create mode 100644 packages/plugin/src/features/note-header/host.ts create mode 100644 packages/plugin/src/features/presence/host.ts create mode 100644 packages/plugin/src/features/relay/host.ts create mode 100644 packages/plugin/src/features/relay/relay-test.ts create mode 100644 packages/plugin/src/features/settings/host.ts create mode 100644 packages/plugin/src/features/setup/host.ts create mode 100644 packages/plugin/src/features/source-control/host.ts create mode 100644 packages/plugin/src/features/source-control/workspace.ts create mode 100644 packages/plugin/src/features/spaces/host.ts create mode 100644 packages/plugin/src/features/spaces/ui/inert-warning.ts rename packages/plugin/src/features/spaces/{ => ui}/last-edit.ts (77%) create mode 100644 packages/plugin/src/features/status/host.ts create mode 100644 packages/plugin/src/features/storage/host.ts create mode 100644 packages/plugin/src/features/storage/settings.ts create mode 100644 packages/plugin/src/features/storage/ui/authorize.ts rename packages/plugin/src/{core/utils => features/sync/changes}/file-concurrency.ts (94%) rename packages/plugin/src/{core/shared => features/sync/changes}/records.ts (100%) create mode 100644 packages/plugin/src/features/sync/host.ts create mode 100644 packages/plugin/src/features/sync/identity/vault-mismatch.ts rename packages/plugin/src/features/sync/{session.ts => remote/salt.ts} (94%) create mode 100644 packages/plugin/src/features/sync/settings.ts rename packages/plugin/src/features/{settings/sections/security.ts => sync/ui/encryption-section.ts} (84%) create mode 100644 packages/plugin/src/features/transfer/host.ts create mode 100644 packages/plugin/tests/app/scope-refresh.test.ts rename packages/plugin/tests/app/{ => settings}/envelope.test.ts (96%) create mode 100644 packages/plugin/tests/app/settings/index.test.ts create mode 100644 packages/plugin/tests/app/settings/store.test.ts rename packages/plugin/tests/{features/storage => app}/storage-refused.test.ts (95%) create mode 100644 packages/plugin/tests/core/cloudflare/token.test.ts rename packages/plugin/tests/{core/utils => features/diff/lines}/search.test.ts (90%) create mode 100644 packages/plugin/tests/features/diff/merge/edit-plan.test.ts rename packages/plugin/tests/{core/cloudflare => features/relay/deploy}/relay-account.test.ts (100%) rename packages/plugin/tests/{core/cloudflare => features/relay/deploy}/relay-deploy.test.ts (100%) rename packages/plugin/tests/features/{storage/ui/connection-test.test.ts => relay/relay-test.test.ts} (98%) rename packages/plugin/tests/{core => features/storage}/cloudflare/r2.test.ts (52%) rename packages/plugin/tests/{core/utils => features/sync/changes}/file-concurrency.test.ts (97%) rename packages/plugin/tests/features/{settings/sections/security-section.test.ts => sync/ui/encryption-section.test.ts} (93%) create mode 100644 packages/protocol/src/admin.ts diff --git a/.claude/rules/history.md b/.claude/rules/history.md index b9d7aec9..70dd7fb1 100644 --- a/.claude/rules/history.md +++ b/.claude/rules/history.md @@ -4,7 +4,7 @@ paths: - '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/restore-modal.ts' + - 'packages/plugin/src/features/diff/ui/restore-modal.ts' - 'packages/plugin/src/features/sync/runtime/maintenance*.ts' --- @@ -33,7 +33,7 @@ History is a change log, not an archive. Model, publish order, windows and accep - 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 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`). -- Restore dialogs promise "nothing is pushed until you say so" (`features/diff/restore-modal.ts`); keep that true. +- Restore dialogs promise "nothing is pushed until you say so" (`features/diff/ui/restore-modal.ts`); keep that true. ## Pins diff --git a/.claude/rules/realtime.md b/.claude/rules/realtime.md index 7f35443a..0a1f586c 100644 --- a/.claude/rules/realtime.md +++ b/.claude/rules/realtime.md @@ -46,6 +46,7 @@ Hub model, storage, accepted limits: `packages/relay/README.md`. Wire formats: ` - 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. ## Client socket diff --git a/.claude/rules/security.md b/.claude/rules/security.md index 1df7824f..5ec01bf9 100644 --- a/.claude/rules/security.md +++ b/.claude/rules/security.md @@ -1,7 +1,7 @@ --- paths: - 'packages/plugin/src/core/crypto/**' - - 'packages/plugin/src/app/settings-envelope.ts' + - 'packages/plugin/src/app/settings/**' - 'packages/plugin/src/features/transfer/**' - 'packages/plugin/src/features/links/**' - 'packages/plugin/src/features/storage/**' @@ -23,13 +23,13 @@ Follows Obsidian's Developer Policies and Plugin Guidelines. Link model and limi ## 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. +- 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 or Forget clears it from disk (`clearCachedPassphrase`). +- 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. diff --git a/.claude/rules/settings-setup.md b/.claude/rules/settings-setup.md index 8cfa6041..47f75407 100644 --- a/.claude/rules/settings-setup.md +++ b/.claude/rules/settings-setup.md @@ -2,7 +2,8 @@ paths: - 'packages/plugin/src/features/{settings,setup,transfer,relay}/**' - 'packages/plugin/src/core/settings/**' - - 'packages/plugin/src/app/settings-envelope.ts' + - 'packages/plugin/src/app/settings/**' + - 'packages/plugin/src/features/*/settings.ts' - 'packages/plugin/src/app/commands.ts' --- @@ -19,9 +20,10 @@ Paths are relative to `packages/plugin/src/`. Wizard steps and modules: `feature ## Settings -- Every write goes through `plugin.saveSettings()`; the plugin's saved settings file is sealed by `SettingsEnvelope` (`app/settings-envelope.ts`). A new secret field joins its `SEALED` list, or it is stored in the clear. -- Defaults, numeric bounds (`NUMERIC_BOUNDS`) and `mergeSettings` live in `core/settings/model.ts`; a value from a file or token is clamped there. A removed setting goes in `RETIRED_KEYS` (secrets are deleted, not kept). -- Rows are declarative fields (`fieldRow`, `group`, `checkRow`, `renderDefinitions` in `core/settings/fields.ts`). 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`. +- 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`). 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`, `sync/scope`, `transfer/ui`, `storage/ui`); `features/settings/sections/` holds only cross-cutting ones, and `features/settings/tab.ts` orders them. - 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. diff --git a/.claude/rules/spaces.md b/.claude/rules/spaces.md index 3a362cfb..10bc8bdd 100644 --- a/.claude/rules/spaces.md +++ b/.claude/rules/spaces.md @@ -15,7 +15,7 @@ Model, flows, accepted limits: `features/spaces/README.md`. What the engine does - 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 `core/settings/model.ts`): WebDAV and Drive cannot presign. +- 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. diff --git a/.claude/rules/structure.md b/.claude/rules/structure.md index bd09fc07..3e448fb8 100644 --- a/.claude/rules/structure.md +++ b/.claude/rules/structure.md @@ -10,16 +10,17 @@ Paths in this file are relative to `packages/plugin/src/`. ## Layout -- `main.ts` - lifecycle only (onload, onunload, `saveSettings`, `scheduleScopeRefresh`). `styles.css` - the cascade order of every stylesheet. -- `app/` - composition root: the host container (`app/host.ts`), bootstrap, commands, events, protocol handlers, realtime coordinator, session factory, settings envelope, views. Only `app/` and `main.ts` call a feature's `register*()`. +- `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: `cloudflare crypto drawing hub logs settings shared ui utils vault`, plus `core/constants.ts`. 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`. -- Domain order is not enforced by `pnpm arch` (`no-circular` is): import downward. Upward edges that exist are debt, never add one: `storage` -> `sync` (manifest key, `VAULT_SPACE`), `live` and `presence` -> `relay` types, `live` -> `spaces` type. +- 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. @@ -27,17 +28,17 @@ Paths in this file are relative to `packages/plugin/src/`. ## 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. -- Deep imports into another slice (mostly `features/sync/**`) are baselined debt. New code adds none: export what is needed from the facade. +- 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. -- Modules still take `PluginHost` (`app/host.ts`) and `core/settings/model.ts` still imports features. These are baselined, being removed. New code declares the narrow members it needs as its own interface (`SpaceAccessHost` in `features/spaces/space-access.ts`, `SettingsTransferDeps` in `features/transfer/transfer-controller.ts`); `MdsyncPlugin` satisfies it structurally. Navigation into another surface is a callback in those deps, not an import. -- A per-slice deps file and a per-slice settings module do not exist yet: do not cite or create them as if they did. +- 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()`; `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-not-surface`, `surface-`. -- Surface -> surface only: `setup` -> `settings`; `source-control` -> `diff`, `setup`; `status` -> `diff`, `note-header`, `source-control`. `diff`, `editor-signs`, `explorer`, `note-header`, `settings` reach no other surface. -- `packages/plugin/.dependency-cruiser-known-violations.json` is a baseline that only shrinks. Remove a violation, then regenerate: `npx depcruise src --config .dependency-cruiser.cjs --output-type baseline > .dependency-cruiser-known-violations.json` (in `packages/plugin`, file `packages/plugin/.dependency-cruiser-known-violations.json`). A change that adds an entry is wrong; fix the import. -- Remaining baselined groups: `slice-via-facade` (deep imports, mostly into `sync`), `features-not-app` (`PluginHost`), `core-independent` (`core/settings/{model,fields}.ts`, `core/ui/{menu,notices}.ts`, `core/shared/format.ts`), `domain-not-surface` (`features/sync/ui` -> `features/source-control/view.ts`, `features/links/ui` and `features/relay/ui` -> `features/setup/step-state.ts`), one each in `surface-diff`, `surface-setup`. +- 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 diff --git a/.claude/skills/new-feature/SKILL.md b/.claude/skills/new-feature/SKILL.md index 68a59e84..dd6cc56a 100644 --- a/.claude/skills/new-feature/SKILL.md +++ b/.claude/skills/new-feature/SKILL.md @@ -15,9 +15,9 @@ The rules in `.claude/rules/` (structure, ui, testing) load as you touch files; ## 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; 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. +- 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 the narrow members the slice reads as its own interface, structurally satisfied by `MdsyncPlugin`. A way into another surface is a callback in it. +- 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 @@ -34,6 +34,6 @@ Mirror the tree under `packages/plugin/tests/features//` (the testing rule ## 5. Finish -- `pnpm lint && pnpm typecheck && pnpm test && pnpm arch`, all green, with no new entry in `packages/plugin/.dependency-cruiser-known-violations.json` and no folder over 12 modules. +- `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/biome.json b/biome.json index ddb8d268..ef294840 100644 --- a/biome.json +++ b/biome.json @@ -7,11 +7,7 @@ }, "files": { "ignoreUnknown": false, - "includes": [ - "**", - "!**/tests/**/fixtures/**/*.html", - "!**/.dependency-cruiser-known-violations.json" - ] + "includes": ["**", "!**/tests/**/fixtures/**/*.html"] }, "formatter": { "enabled": true, diff --git a/packages/plugin/.dependency-cruiser-known-violations.json b/packages/plugin/.dependency-cruiser-known-violations.json deleted file mode 100644 index b0d9c8a3..00000000 --- a/packages/plugin/.dependency-cruiser-known-violations.json +++ /dev/null @@ -1,3827 +0,0 @@ -[ - { - "type": "dependency", - "from": "src/core/settings/fields.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "core-independent" - } - }, - { - "type": "dependency", - "from": "src/core/settings/fields.ts", - "to": "src/features/storage/field-spec.ts", - "unresolvedTo": "@/features/storage/field-spec", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "core-independent" - } - }, - { - "type": "dependency", - "from": "src/core/settings/fields.ts", - "to": "src/features/storage/ui/connection-test.ts", - "unresolvedTo": "@/features/storage/ui/connection-test", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "core-independent" - } - }, - { - "type": "dependency", - "from": "src/core/settings/model.ts", - "to": "src/features/links/record.ts", - "unresolvedTo": "@/features/links/record", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "core-independent" - } - }, - { - "type": "dependency", - "from": "src/core/settings/model.ts", - "to": "src/features/spaces/broker/share-broker.ts", - "unresolvedTo": "@/features/spaces/broker/share-broker", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "core-independent" - } - }, - { - "type": "dependency", - "from": "src/core/settings/model.ts", - "to": "src/features/spaces/record.ts", - "unresolvedTo": "@/features/spaces/record", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "core-independent" - } - }, - { - "type": "dependency", - "from": "src/core/settings/model.ts", - "to": "src/features/storage/backends/s3.ts", - "unresolvedTo": "@/features/storage/backends/s3", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "core-independent" - } - }, - { - "type": "dependency", - "from": "src/core/settings/model.ts", - "to": "src/features/storage/config.ts", - "unresolvedTo": "@/features/storage/config", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "core-independent" - } - }, - { - "type": "dependency", - "from": "src/core/settings/model.ts", - "to": "src/features/storage/field-spec.ts", - "unresolvedTo": "@/features/storage/field-spec", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "core-independent" - } - }, - { - "type": "dependency", - "from": "src/core/settings/model.ts", - "to": "src/features/storage/registry.ts", - "unresolvedTo": "@/features/storage/registry", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "core-independent" - } - }, - { - "type": "dependency", - "from": "src/core/shared/format.ts", - "to": "src/features/sync/types.ts", - "unresolvedTo": "@/features/sync/types", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "core-independent" - } - }, - { - "type": "dependency", - "from": "src/core/ui/menu.ts", - "to": "src/features/presence/ui/avatars.ts", - "unresolvedTo": "@/features/presence/ui/avatars", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "core-independent" - } - }, - { - "type": "dependency", - "from": "src/core/ui/menu.ts", - "to": "src/features/presence/views.ts", - "unresolvedTo": "@/features/presence/views", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "core-independent" - } - }, - { - "type": "dependency", - "from": "src/core/ui/notices.ts", - "to": "src/features/sync/controller.ts", - "unresolvedTo": "@/features/sync/controller", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "core-independent" - } - }, - { - "type": "dependency", - "from": "src/features/links/ui/link-menu.ts", - "to": "src/features/setup/step-state.ts", - "unresolvedTo": "@/features/setup/step-state", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "domain-not-surface" - } - }, - { - "type": "dependency", - "from": "src/features/relay/ui/relay-section.ts", - "to": "src/features/setup/step-state.ts", - "unresolvedTo": "@/features/setup/step-state", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "domain-not-surface" - } - }, - { - "type": "dependency", - "from": "src/features/sync/ui/push-action.ts", - "to": "src/features/source-control/view.ts", - "unresolvedTo": "@/features/source-control/view", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "domain-not-surface" - } - }, - { - "type": "dependency", - "from": "src/features/sync/ui/sync-actions.ts", - "to": "src/features/source-control/view.ts", - "unresolvedTo": "@/features/source-control/view", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "domain-not-surface" - } - }, - { - "type": "dependency", - "from": "src/features/diff/merge/merge-editor.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/diff/operations.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/diff/restore-modal.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/diff/view.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/editor-signs/register.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/explorer/file-context-indicators.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/explorer/file-explorer-badges.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/explorer/file-explorer-decorations.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/explorer/file-explorer-indicators.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/explorer/file-explorer-marks.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/explorer/row-decorator.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/links/note-links.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/links/publish.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/links/register.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/links/ui/link-actions.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/links/ui/link-menu.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/links/ui/manage-links-modal.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/links/ui/note-link-action.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/links/ui/share-link-modal.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/live/ui/deleted-elsewhere.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/note-header/header-state.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/note-header/live-actions.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/note-header/live-status.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/note-header/note-menu.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/note-header/note-presence.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/presence/follow/cursor-follow.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/presence/follow/follows.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/relay/deploy/deploy-flow.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/relay/update/relay-update-modal.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/relay/update/relay-update.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/settings/logs-view.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/settings/overview.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/settings/sections/automation.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/settings/tab.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/setup/step-state.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/setup/wizard.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/actions/actions.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/changes/changes-tab.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/changes/excluded-files.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/history/history-tab.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/setup-prompt.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/summary-card.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/timeline/snapshot-menu.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/timeline/timeline-actions.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/timeline/timeline-tab.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/trash/trash-tab.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/view.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/last-edit.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/share-moves.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/ui/access-ended.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/ui/invites/invite-action.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/ui/read-only.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/ui/share-action.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/ui/space-gone.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/ui/window/share-modal.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/ui/window/share-window.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/status/live-spaces.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/status/relay-status.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/status/status-bar.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/status/status-menu.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/status/where-menu.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/storage/cloudflare/cloudflare-login.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/storage/cloudflare/r2-select.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/storage/storage-refused.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/storage/ui/connection-test.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/storage/ui/storage-fields.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/storage/ui/storage-refused-modal.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/sync/controller.ts", - "to": "src/app/session-factory.ts", - "unresolvedTo": "@/app/session-factory", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/sync/runtime/saved-refresh.ts", - "to": "src/app/session-factory.ts", - "unresolvedTo": "@/app/session-factory", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/sync/scope/ignore-state.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/sync/ui/ignore-action.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/sync/ui/maintenance-actions.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/sync/ui/maintenance-section.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/sync/ui/push-action.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/features/sync/ui/sync-actions.ts", - "to": "src/app/host.ts", - "unresolvedTo": "@/app/host", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "features-not-app" - } - }, - { - "type": "dependency", - "from": "src/core/settings/fields.ts", - "to": "src/features/storage/field-spec.ts", - "unresolvedTo": "@/features/storage/field-spec", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/core/settings/fields.ts", - "to": "src/features/storage/ui/connection-test.ts", - "unresolvedTo": "@/features/storage/ui/connection-test", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/core/settings/model.ts", - "to": "src/features/links/record.ts", - "unresolvedTo": "@/features/links/record", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/core/settings/model.ts", - "to": "src/features/spaces/broker/share-broker.ts", - "unresolvedTo": "@/features/spaces/broker/share-broker", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/core/settings/model.ts", - "to": "src/features/spaces/record.ts", - "unresolvedTo": "@/features/spaces/record", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/core/settings/model.ts", - "to": "src/features/storage/backends/s3.ts", - "unresolvedTo": "@/features/storage/backends/s3", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/core/settings/model.ts", - "to": "src/features/storage/config.ts", - "unresolvedTo": "@/features/storage/config", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/core/settings/model.ts", - "to": "src/features/storage/field-spec.ts", - "unresolvedTo": "@/features/storage/field-spec", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/core/settings/model.ts", - "to": "src/features/storage/registry.ts", - "unresolvedTo": "@/features/storage/registry", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/core/shared/format.ts", - "to": "src/features/sync/types.ts", - "unresolvedTo": "@/features/sync/types", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/core/ui/menu.ts", - "to": "src/features/presence/ui/avatars.ts", - "unresolvedTo": "@/features/presence/ui/avatars", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/core/ui/menu.ts", - "to": "src/features/presence/views.ts", - "unresolvedTo": "@/features/presence/views", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/core/ui/notices.ts", - "to": "src/features/sync/controller.ts", - "unresolvedTo": "@/features/sync/controller", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/action-bar.ts", - "to": "src/features/sync/hunks/projection.ts", - "unresolvedTo": "@/features/sync/hunks/projection", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/choices.ts", - "to": "src/features/sync/hunks/hunks.ts", - "unresolvedTo": "@/features/sync/hunks/hunks", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/choices.ts", - "to": "src/features/sync/hunks/projection.ts", - "unresolvedTo": "@/features/sync/hunks/projection", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/compare/compare-decorations.ts", - "to": "src/features/sync/hunks/hunks.ts", - "unresolvedTo": "@/features/sync/hunks/hunks", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/compare/compare-decorations.ts", - "to": "src/features/sync/hunks/merge-model.ts", - "unresolvedTo": "@/features/sync/hunks/merge-model", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/compare/compare-decorations.ts", - "to": "src/features/sync/hunks/projection.ts", - "unresolvedTo": "@/features/sync/hunks/projection", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/compare/compare-panel.ts", - "to": "src/features/sync/hunks/projection.ts", - "unresolvedTo": "@/features/sync/hunks/projection", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/history-state.ts", - "to": "src/features/sync/constants.ts", - "unresolvedTo": "@/features/sync/constants", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/history-state.ts", - "to": "src/features/sync/hunks/projection.ts", - "unresolvedTo": "@/features/sync/hunks/projection", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/lines/source-widget.ts", - "to": "src/features/sync/hunks/merge-model.ts", - "unresolvedTo": "@/features/sync/hunks/merge-model", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/merge/merge-actions.ts", - "to": "src/features/sync/hunks/merge-model.ts", - "unresolvedTo": "@/features/sync/hunks/merge-model", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/merge/merge-cards.ts", - "to": "src/features/sync/hunks/hunks.ts", - "unresolvedTo": "@/features/sync/hunks/hunks", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/merge/merge-cards.ts", - "to": "src/features/sync/hunks/merge-model.ts", - "unresolvedTo": "@/features/sync/hunks/merge-model", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/merge/merge-controls.ts", - "to": "src/features/sync/hunks/merge-model.ts", - "unresolvedTo": "@/features/sync/hunks/merge-model", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/merge/merge-decorations.ts", - "to": "src/features/sync/hunks/merge-model.ts", - "unresolvedTo": "@/features/sync/hunks/merge-model", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/merge/merge-editor.ts", - "to": "src/features/sync/hunks/merge-model.ts", - "unresolvedTo": "@/features/sync/hunks/merge-model", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/merge/merge-state.ts", - "to": "src/features/sync/hunks/merge-model.ts", - "unresolvedTo": "@/features/sync/hunks/merge-model", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/operations.ts", - "to": "src/features/sync/controller.ts", - "unresolvedTo": "@/features/sync/controller", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/operations.ts", - "to": "src/features/sync/hunks/projection.ts", - "unresolvedTo": "@/features/sync/hunks/projection", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/view.ts", - "to": "src/features/source-control/view.ts", - "unresolvedTo": "@/features/source-control/view", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/view.ts", - "to": "src/features/sync/engine.ts", - "unresolvedTo": "@/features/sync/engine", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/view.ts", - "to": "src/features/sync/hunks/projection.ts", - "unresolvedTo": "@/features/sync/hunks/projection", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/links/link-broker.ts", - "to": "src/features/spaces/broker/share-broker.ts", - "unresolvedTo": "@/features/spaces/broker/share-broker", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/links/ui/link-menu.ts", - "to": "src/features/live/doc-types.ts", - "unresolvedTo": "@/features/live/doc-types", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/links/ui/link-menu.ts", - "to": "src/features/setup/step-state.ts", - "unresolvedTo": "@/features/setup/step-state", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/links/ui/share-link-modal.ts", - "to": "src/features/spaces/invite.ts", - "unresolvedTo": "@/features/spaces/invite", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/live/cold/cold-sync.ts", - "to": "src/features/sync/changes/content.ts", - "unresolvedTo": "@/features/sync/changes/content", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/live/cold/cold-sync.ts", - "to": "src/features/sync/live-notes.ts", - "unresolvedTo": "@/features/sync/live-notes", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/live/cold/cold-sync.ts", - "to": "src/features/sync/types.ts", - "unresolvedTo": "@/features/sync/types", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/live/register.ts", - "to": "src/features/sync/live-notes.ts", - "unresolvedTo": "@/features/sync/live-notes", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/live/register.ts", - "to": "src/features/sync/recovery/journal.ts", - "unresolvedTo": "@/features/sync/recovery/journal", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/live/register.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/live/text/merge.ts", - "to": "src/features/sync/hunks/merge-model.ts", - "unresolvedTo": "@/features/sync/hunks/merge-model", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/live/text/patch.ts", - "to": "src/features/sync/hunks/hunks.ts", - "unresolvedTo": "@/features/sync/hunks/hunks", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/live/ui/deleted-elsewhere.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/live/workspace/rename.ts", - "to": "src/features/sync/changes/content.ts", - "unresolvedTo": "@/features/sync/changes/content", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/live/workspace/rename.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/live/workspace/space.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/presence/follow/follow-scroll.ts", - "to": "src/features/live/session/session.ts", - "unresolvedTo": "@/features/live/session/session", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/presence/follow/follow-scroll.ts", - "to": "src/features/live/text/cursors.ts", - "unresolvedTo": "@/features/live/text/cursors", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/presence/people.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/presence/register.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/relay/channels.ts", - "to": "src/features/spaces/partition.ts", - "unresolvedTo": "@/features/spaces/partition", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/relay/channels.ts", - "to": "src/features/spaces/record.ts", - "unresolvedTo": "@/features/spaces/record", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/relay/channels.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/relay/connection.ts", - "to": "src/features/spaces/partition.ts", - "unresolvedTo": "@/features/spaces/partition", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/relay/connection.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/relay/ui/relay-section.ts", - "to": "src/features/setup/step-state.ts", - "unresolvedTo": "@/features/setup/step-state", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/settings/overview.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/settings/sections/advanced.ts", - "to": "src/features/sync/identity/device.ts", - "unresolvedTo": "@/features/sync/identity/device", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/settings/sections/automation.ts", - "to": "src/features/sync/history/gc.ts", - "unresolvedTo": "@/features/sync/history/gc", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/settings/sections/automation.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/settings/sections/security.ts", - "to": "src/features/sync/remote/keyfile.ts", - "unresolvedTo": "@/features/sync/remote/keyfile", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/settings/tab.ts", - "to": "src/features/links/ui/links-section.ts", - "unresolvedTo": "@/features/links/ui/links-section", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/settings/tab.ts", - "to": "src/features/relay/ui/relay-section.ts", - "unresolvedTo": "@/features/relay/ui/relay-section", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/settings/tab.ts", - "to": "src/features/spaces/ui/shares-section.ts", - "unresolvedTo": "@/features/spaces/ui/shares-section", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/settings/tab.ts", - "to": "src/features/sync/scope/configuration-scope-section.ts", - "unresolvedTo": "@/features/sync/scope/configuration-scope-section", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/settings/tab.ts", - "to": "src/features/sync/scope/exclusions-section.ts", - "unresolvedTo": "@/features/sync/scope/exclusions-section", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/settings/tab.ts", - "to": "src/features/sync/ui/maintenance-section.ts", - "unresolvedTo": "@/features/sync/ui/maintenance-section", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/setup/steps/passphrase-step.ts", - "to": "src/features/sync/remote/keyfile.ts", - "unresolvedTo": "@/features/sync/remote/keyfile", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/setup/steps/ready-step.ts", - "to": "src/features/settings/sections/automation.ts", - "unresolvedTo": "@/features/settings/sections/automation", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/setup/steps/ready-step.ts", - "to": "src/features/source-control/view.ts", - "unresolvedTo": "@/features/source-control/view", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/setup/steps/relay-deploy-view.ts", - "to": "src/features/relay/deploy/deploy-flow.ts", - "unresolvedTo": "@/features/relay/deploy/deploy-flow", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/setup/steps/relay-deploy-view.ts", - "to": "src/features/relay/deploy/relay-account.ts", - "unresolvedTo": "@/features/relay/deploy/relay-account", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/setup/steps/relay-deploy-view.ts", - "to": "src/features/relay/deploy/relay-deploy.ts", - "unresolvedTo": "@/features/relay/deploy/relay-deploy", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/setup/steps/relay-step.ts", - "to": "src/features/relay/deploy/deploy-flow.ts", - "unresolvedTo": "@/features/relay/deploy/deploy-flow", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/setup/steps/relay-step.ts", - "to": "src/features/relay/deploy/relay-account.ts", - "unresolvedTo": "@/features/relay/deploy/relay-account", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/setup/steps/start-step.ts", - "to": "src/features/spaces/ui/invites/invite-action.ts", - "unresolvedTo": "@/features/spaces/ui/invites/invite-action", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/actions/actions.ts", - "to": "src/features/sync/controller.ts", - "unresolvedTo": "@/features/sync/controller", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/actions/actions.ts", - "to": "src/features/sync/scope/ignore.ts", - "unresolvedTo": "@/features/sync/scope/ignore", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/actions/actions.ts", - "to": "src/features/sync/types.ts", - "unresolvedTo": "@/features/sync/types", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/actions/actions.ts", - "to": "src/features/sync/ui/ignore-action.ts", - "unresolvedTo": "@/features/sync/ui/ignore-action", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/actions/actions.ts", - "to": "src/features/sync/ui/modals.ts", - "unresolvedTo": "@/features/sync/ui/modals", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/changes/changes-section.ts", - "to": "src/features/sync/controller.ts", - "unresolvedTo": "@/features/sync/controller", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/changes/changes-tab.ts", - "to": "src/features/spaces/last-edit.ts", - "unresolvedTo": "@/features/spaces/last-edit", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/changes/excluded-files.ts", - "to": "src/features/sync/types.ts", - "unresolvedTo": "@/features/sync/types", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/changes/excluded-files.ts", - "to": "src/features/sync/ui/ignore-action.ts", - "unresolvedTo": "@/features/sync/ui/ignore-action", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/changes/row-formatter.ts", - "to": "src/features/sync/changes/moves.ts", - "unresolvedTo": "@/features/sync/changes/moves", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/changes/row-formatter.ts", - "to": "src/features/sync/identity/device.ts", - "unresolvedTo": "@/features/sync/identity/device", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/changes/row-formatter.ts", - "to": "src/features/sync/types.ts", - "unresolvedTo": "@/features/sync/types", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/changes/row-formatter.ts", - "to": "src/features/sync/ui/change-action.ts", - "unresolvedTo": "@/features/sync/ui/change-action", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/history/history-tab.ts", - "to": "src/features/diff/restore-modal.ts", - "unresolvedTo": "@/features/diff/restore-modal", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/setup-prompt.ts", - "to": "src/features/setup/step-state.ts", - "unresolvedTo": "@/features/setup/step-state", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/summary-card.ts", - "to": "src/features/spaces/ui/space-gone.ts", - "unresolvedTo": "@/features/spaces/ui/space-gone", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/summary-card.ts", - "to": "src/features/sync/controller.ts", - "unresolvedTo": "@/features/sync/controller", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/summary-card.ts", - "to": "src/features/sync/identity/device.ts", - "unresolvedTo": "@/features/sync/identity/device", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/summary-card.ts", - "to": "src/features/sync/runtime/sync-gates.ts", - "unresolvedTo": "@/features/sync/runtime/sync-gates", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/summary-card.ts", - "to": "src/features/sync/types.ts", - "unresolvedTo": "@/features/sync/types", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/timeline/timeline-actions.ts", - "to": "src/features/diff/restore-modal.ts", - "unresolvedTo": "@/features/diff/restore-modal", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/source-control/trash/trash-tab.ts", - "to": "src/features/diff/restore-modal.ts", - "unresolvedTo": "@/features/diff/restore-modal", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/last-edit.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/partition.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/records.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/share-moves.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/space-access.ts", - "to": "src/features/sync/controller.ts", - "unresolvedTo": "@/features/sync/controller", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/space-access.ts", - "to": "src/features/sync/remote/passphrase-manager.ts", - "unresolvedTo": "@/features/sync/remote/passphrase-manager", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/space-access.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/ui/invites/invite-action.ts", - "to": "src/features/sync/ui/push-action.ts", - "unresolvedTo": "@/features/sync/ui/push-action", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/ui/read-only.ts", - "to": "src/features/live/doc-types.ts", - "unresolvedTo": "@/features/live/doc-types", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/ui/read-only.ts", - "to": "src/features/live/drawing/excalidraw.ts", - "unresolvedTo": "@/features/live/drawing/excalidraw", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/ui/share-action.ts", - "to": "src/features/sync/ui/ignore-action.ts", - "unresolvedTo": "@/features/sync/ui/ignore-action", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/ui/share-action.ts", - "to": "src/features/sync/ui/push-action.ts", - "unresolvedTo": "@/features/sync/ui/push-action", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/ui/window/people-list.ts", - "to": "src/features/presence/ui/avatars.ts", - "unresolvedTo": "@/features/presence/ui/avatars", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/ui/window/people-list.ts", - "to": "src/features/presence/views.ts", - "unresolvedTo": "@/features/presence/views", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "type-only", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/ui/window/share-modal.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/spaces/ui/window/share-window.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/storage/cloudflare/r2-select.ts", - "to": "src/features/sync/constants.ts", - "unresolvedTo": "@/features/sync/constants", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/storage/storage-refused.ts", - "to": "src/features/sync/remote/space.ts", - "unresolvedTo": "@/features/sync/remote/space", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/storage/ui/connection-test.ts", - "to": "src/features/sync/constants.ts", - "unresolvedTo": "@/features/sync/constants", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/sync/ui/push-action.ts", - "to": "src/features/source-control/view.ts", - "unresolvedTo": "@/features/source-control/view", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/sync/ui/sync-actions.ts", - "to": "src/features/source-control/view.ts", - "unresolvedTo": "@/features/source-control/view", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "slice-via-facade" - } - }, - { - "type": "dependency", - "from": "src/features/diff/view.ts", - "to": "src/features/source-control/view.ts", - "unresolvedTo": "@/features/source-control/view", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "surface-diff" - } - }, - { - "type": "dependency", - "from": "src/features/setup/steps/ready-step.ts", - "to": "src/features/source-control/view.ts", - "unresolvedTo": "@/features/source-control/view", - "dependencyTypes": [ - "aliased", - "aliased-tsconfig", - "aliased-tsconfig-paths", - "local", - "import" - ], - "rule": { - "severity": "error", - "name": "surface-setup" - } - } -] diff --git a/packages/plugin/.dependency-cruiser.cjs b/packages/plugin/.dependency-cruiser.cjs index b74446bd..7488c970 100644 --- a/packages/plugin/.dependency-cruiser.cjs +++ b/packages/plugin/.dependency-cruiser.cjs @@ -1,4 +1,14 @@ -const DOMAIN = "(storage|sync|live|presence|spaces|links|relay|transfer)"; +/** 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": [], @@ -7,11 +17,19 @@ const SURFACES = { settings: [], setup: ["settings"], "source-control": ["diff", "setup"], - status: ["diff", "note-header", "source-control"], + 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"}`, @@ -67,9 +85,10 @@ module.exports = { { name: "domain-not-surface", severity: "error", - from: { path: `^src/features/${DOMAIN}/` }, + from: { path: `^src/features/(${DOMAINS.join("|")})/` }, to: { path: `^src/features/(${Object.keys(SURFACES).join("|")})/` }, }, + ...domainOrderRules, ...surfaceRules, ], options: { diff --git a/packages/plugin/package.json b/packages/plugin/package.json index 775eb7ee..965484f5 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -11,7 +11,7 @@ "test": "vitest run", "test:watch": "vitest", "typecheck": "tsc -noEmit", - "arch": "depcruise src --config .dependency-cruiser.cjs --ignore-known .dependency-cruiser-known-violations.json" + "arch": "depcruise src --config .dependency-cruiser.cjs" }, "dependencies": { "@jest/diff-sequences": "^30.5.0", diff --git a/packages/plugin/src/app/bootstrap.ts b/packages/plugin/src/app/bootstrap.ts index f68b016a..a436e7a1 100644 --- a/packages/plugin/src/app/bootstrap.ts +++ b/packages/plugin/src/app/bootstrap.ts @@ -1,11 +1,16 @@ import type { App } from "obsidian"; import type { DeviceKey } from "@/core/crypto"; import { LogService } from "@/core/logs"; -import { isStorageConfigured, type MdsyncSettings } from "@/core/settings"; +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 { createMoveFollower, SpaceRecords } from "@/features/spaces"; +import { + createInertWarning, + createMoveFollower, + SpaceRecords, +} from "@/features/spaces"; +import { isStorageConfigured } from "@/features/storage"; import type { LiveNotes } from "@/features/sync"; import { fetchRemoteManifest, @@ -28,7 +33,7 @@ export interface PluginRuntime { journal: WriteJournal; } -interface BootstrapPluginRuntimeOptions { +export interface BootstrapPluginRuntimeOptions { app: App; settings: MdsyncSettings; deviceKey: DeviceKey; @@ -156,26 +161,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/app/commands.ts b/packages/plugin/src/app/commands.ts index c35bbfbd..479562fe 100644 --- a/packages/plugin/src/app/commands.ts +++ b/packages/plugin/src/app/commands.ts @@ -1,7 +1,7 @@ import { MarkdownView, type Plugin } from "obsidian"; - import { SOURCE_CONTROL_VIEW_TYPE } from "@/core/constants"; import { notifyInfo } from "@/core/ui"; +import { openDiffView } from "@/features/diff"; import { isLinkable, noteLinks, @@ -16,7 +16,6 @@ import { toggleAuthors, } from "@/features/note-header"; import { - openDiffView, openSourceControlDeleted, openSourceControlHistory, openSourceControlView, diff --git a/packages/plugin/src/app/events.ts b/packages/plugin/src/app/events.ts index 83a9e472..e3e83da6 100644 --- a/packages/plugin/src/app/events.ts +++ b/packages/plugin/src/app/events.ts @@ -1,87 +1,37 @@ -import { - type Menu, - type Plugin, - type TAbstractFile, - TFile, - TFolder, -} from "obsidian"; +import { type Plugin, TFile, TFolder } from "obsidian"; import { reportWarning } from "@/core/shared"; import { addLinkMenuItems } from "@/features/links"; -import { - openSourceControlDeleted, - openSourceControlHistory, -} from "@/features/source-control"; +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"; -/** - * 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. - */ +/** 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) => { - addIgnoreItem(menu, plugin, file); - addPushMenuItem(menu, plugin, file.path, file instanceof TFolder); + const folder = file instanceof TFolder; + addIgnoreMenuItem(menu, plugin, file.path, folder, "MDSync: "); + addPushMenuItem(menu, plugin, file.path, folder); 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); - } + 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; + const path = view.file?.path ?? null; if (path) addPushMenuItem(menu, plugin, path, false); - if (!plugin.settings.fileHistoryEnabled) return; - if (path) addHistoryItem(menu, plugin, path); - addDeletedItem(menu, plugin); + addHistoryMenuItems(menu, plugin, path); }), ); } -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, diff --git a/packages/plugin/src/app/host.ts b/packages/plugin/src/app/host.ts index 216f280f..507a0456 100644 --- a/packages/plugin/src/app/host.ts +++ b/packages/plugin/src/app/host.ts @@ -45,4 +45,6 @@ export interface PluginHost { refreshSourceControlView(): void; /** The setup wizard, at `step` or where this device's setup stopped. */ openSetup(step?: ESetupStep): void; + openSourceControl(): Promise; + openChanges(): Promise; } diff --git a/packages/plugin/src/app/protocols.ts b/packages/plugin/src/app/protocols.ts index 55aa1858..bc6a283b 100644 --- a/packages/plugin/src/app/protocols.ts +++ b/packages/plugin/src/app/protocols.ts @@ -1,9 +1,8 @@ -import type { ObsidianProtocolData, Plugin } from "obsidian"; +import type { Plugin } from "obsidian"; import { LINK_PARAM } from "@/core/crypto"; -import { notifyError, notifyInfo } from "@/core/ui"; import { INVITE_ACTION, openInvite } from "@/features/spaces"; -import { handleStorageProtocol } from "@/features/storage"; +import { authorizeStorage } from "@/features/storage"; import { TRANSFER_ACTION } from "@/features/transfer"; import type { PluginHost } from "./host"; @@ -23,26 +22,3 @@ export function registerProtocolHandlers( 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/app/realtime.ts b/packages/plugin/src/app/realtime.ts index ca14b27b..1ed6e94f 100644 --- a/packages/plugin/src/app/realtime.ts +++ b/packages/plugin/src/app/realtime.ts @@ -3,7 +3,7 @@ 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 } from "@/features/spaces"; +import { createSpaceAccess, type SpaceAccessHost } from "@/features/spaces"; import type { LiveNotes } from "@/features/sync"; import { type Space, VAULT_SPACE } from "@/features/sync"; @@ -22,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..624b162b --- /dev/null +++ b/packages/plugin/src/app/runtime-hooks.ts @@ -0,0 +1,51 @@ +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.`, + ), + 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/app/session-factory.ts b/packages/plugin/src/app/session-factory.ts index 89cf5d9d..4a9a8596 100644 --- a/packages/plugin/src/app/session-factory.ts +++ b/packages/plugin/src/app/session-factory.ts @@ -2,12 +2,7 @@ import { type App, TFile } from "obsidian"; import type { EncryptionKey } from "@/core/crypto"; import type { LogService } from "@/core/logs"; import { ESyncLogOperation } from "@/core/logs"; -import { - activeStorage, - isGuest, - isStorageConfigured, - type MdsyncSettings, -} from "@/core/settings"; +import type { MdsyncSettings } from "@/core/settings"; import { reportWarning } from "@/core/shared"; import { createSymlinkDetector, createVaultIndex } from "@/core/vault"; import type { SpaceRecords } from "@/features/spaces"; @@ -17,12 +12,19 @@ import { shareKey, shareStorage, } from "@/features/spaces"; -import { createStorageAdapter, type StorageAdapter } from "@/features/storage"; +import { + activeStorage, + createStorageAdapter, + isStorageConfigured, + type StorageAdapter, +} from "@/features/storage"; import type { EngineDependencies, LiveNotes, + LocalOpener, ManifestAuthor, PassphraseManager, + SessionFiles, StatePersister, WriteJournal, } from "@/features/sync"; @@ -32,9 +34,9 @@ import { createScopePolicy, type IgnoreMatcher, ignoreNoteOf, + isGuest, loadSharedIgnoreMatcher, nestedRoots, - PassphraseRotatedError, projectSession, type Space, VAULT_SPACE, @@ -62,22 +64,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; @@ -238,7 +224,10 @@ async function openVault( return null; } const storage = vaultStorage(deps, getStorage); - const key = await resolveKeyWithRotationRetry(deps, storage); + const key = await deps.passphrase.resolveKeyRecovering(storage, { + warn: (message) => deps.logs.warn(ESyncLogOperation.Session, message), + notify: deps.notify, + }); return key ? { storage, key, concurrency: activeStorage(deps.settings).concurrency } : null; @@ -335,34 +324,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/app/settings-envelope.ts b/packages/plugin/src/app/settings/envelope.ts similarity index 96% rename from packages/plugin/src/app/settings-envelope.ts rename to packages/plugin/src/app/settings/envelope.ts index 554b9873..0d211a3c 100644 --- a/packages/plugin/src/app/settings-envelope.ts +++ b/packages/plugin/src/app/settings/envelope.ts @@ -1,7 +1,8 @@ import type { DeviceKey } from "@/core/crypto"; import { decryptJson, encryptJson } from "@/core/crypto"; -import { type MdsyncSettings, mergeSettings } from "@/core/settings"; +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..292c1ae6 --- /dev/null +++ b/packages/plugin/src/app/settings/store.ts @@ -0,0 +1,50 @@ +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"; + +/** `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(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/features/storage/storage-refused.ts b/packages/plugin/src/app/storage-refused.ts similarity index 78% rename from packages/plugin/src/features/storage/storage-refused.ts rename to packages/plugin/src/app/storage-refused.ts index 09ac8fb2..1292b269 100644 --- a/packages/plugin/src/features/storage/storage-refused.ts +++ b/packages/plugin/src/app/storage-refused.ts @@ -1,7 +1,6 @@ -import type { PluginHost } from "@/app/host"; -import { activeStorage } from "@/core/settings"; -import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; -import { openStorageRefusedModal } from "./ui/storage-refused-modal"; +import { activeStorage, openStorageRefusedModal } from "@/features/storage"; +import { type Space, VAULT_SPACE } from "@/features/sync"; +import type { PluginHost } from "./host"; const VOLATILE = new Set(["accessToken", "expiresAt"]); diff --git a/packages/plugin/src/app/views.ts b/packages/plugin/src/app/views.ts index 1bc1debb..ea68fdae 100644 --- a/packages/plugin/src/app/views.ts +++ b/packages/plugin/src/app/views.ts @@ -64,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/core/constants.ts b/packages/plugin/src/core/constants.ts index 0bf24fef..f79dddc4 100644 --- a/packages/plugin/src/core/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; diff --git a/packages/plugin/src/core/hub/index.ts b/packages/plugin/src/core/hub/index.ts index 9f56e0bb..8631ee50 100644 --- a/packages/plugin/src/core/hub/index.ts +++ b/packages/plugin/src/core/hub/index.ts @@ -7,6 +7,13 @@ export { relaySummary, UNREADABLE_TEXT, } from "./relay-text"; +export type { + HubListener, + SpaceFrame, + SpaceHub, + SpaceHubs, + SpaceListener, +} from "./space-hub"; export { isConnected, isLinkState, 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/core/settings/fields.ts b/packages/plugin/src/core/settings/fields.ts index 9f24176c..03dd0526 100644 --- a/packages/plugin/src/core/settings/fields.ts +++ b/packages/plugin/src/core/settings/fields.ts @@ -6,11 +6,24 @@ import { type SettingGroupItem, } from "obsidian"; -import type { PluginHost } from "@/app/host"; -import { EFieldKind } from "@/features/storage/field-spec"; -import type { ConnectionTestResult } from "@/features/storage/ui/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. */ @@ -43,12 +56,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; @@ -56,58 +76,61 @@ 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; 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; 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; 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, @@ -119,10 +142,10 @@ 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); @@ -183,7 +206,7 @@ function applyControl( export function checkRow( name: string, desc: string, - run: () => Promise, + run: () => Promise, ): SettingsRow { return { name, @@ -244,10 +267,10 @@ export function renderDefinitions( } } -function applyPatch( - ctx: FieldContext, +function applyPatch( + ctx: FieldContext, patch: Partial, - field: SettingsField, + field: SettingsField, ): void { Object.assign(ctx.plugin.settings, patch); void ctx.plugin.saveSettings().then(() => { diff --git a/packages/plugin/src/core/settings/index.ts b/packages/plugin/src/core/settings/index.ts index 76ffca59..7a36ad7d 100644 --- a/packages/plugin/src/core/settings/index.ts +++ b/packages/plugin/src/core/settings/index.ts @@ -1,5 +1,7 @@ export { + type CheckResult, checkRow, + EFieldKind, type FieldContext, fieldRow, group, @@ -7,24 +9,21 @@ export { onSettled, renderDefinitions, type SettingsField, + type SettingsHost, type SettingsRow, SUB_SETTING_CLASS, settleTyping, } from "./fields"; export { - activeStorage, - canSync, - DEFAULT_SETTINGS, + type CoreSettings, + clamp, + DEFAULT_CORE_SETTINGS, DEFAULT_SETTINGS_SYNC, - isGuest, isRelayConfigured, - isStorageConfigured, type MdsyncSettings, - mergeSettings, + mergeCoreSettings, NUMERIC_BOUNDS, - ownerStorage, type RelayConfig, - relayAdmin, type SettingsSyncCategories, } from "./model"; export { imperativePage } from "./page"; diff --git a/packages/plugin/src/core/settings/model.ts b/packages/plugin/src/core/settings/model.ts index 99021cc1..de7d0ba5 100644 --- a/packages/plugin/src/core/settings/model.ts +++ b/packages/plugin/src/core/settings/model.ts @@ -10,21 +10,6 @@ import { LIVE_SEND_MS, } from "@/core/constants"; import { isCleartextRemote } from "@/core/shared"; -import { parseStoredLink, type StoredLink } from "@/features/links/record"; -import type { BrokerAdmin } from "@/features/spaces/broker/share-broker"; -import { isSpaceRecord, type SpaceRecord } from "@/features/spaces/record"; -import { defaultS3Config } from "@/features/storage/backends/s3"; -import { - EStorageBackend, - type S3StorageConfig, - type StorageAdapterConfig, -} from "@/features/storage/config"; -import { CONCURRENCY_FIELD } from "@/features/storage/field-spec"; -import { - getDescriptor, - isAdapterConfigured, - isKnownBackend, -} from "@/features/storage/registry"; const DEFAULT_MAX_FILE_BYTES = 100 * 1024 * 1024; @@ -48,9 +33,8 @@ 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; ignorePatterns: string; /** Skip symlinks and directory links pointing outside the vault. */ @@ -78,8 +62,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`. */ @@ -94,8 +76,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. */ @@ -114,11 +94,9 @@ 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, ignorePatterns: "", ignoreSymlinks: true, @@ -139,7 +117,6 @@ export const DEFAULT_SETTINGS: MdsyncSettings = { liveSendMs: LIVE_SEND_MS.balanced, showLiveAuthors: false, showOpenNote: true, - spaces: [], useSharedFolders: true, pausedSpaces: [], pauseArrivingShares: false, @@ -147,7 +124,6 @@ export const DEFAULT_SETTINGS: MdsyncSettings = { shareEditsWait: true, localRoots: {}, spacesVault: null, - links: [], relayUrl: "", relaySecret: "", cloudflareToken: "", @@ -162,38 +138,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 { @@ -203,14 +148,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", @@ -240,20 +177,19 @@ export const NUMERIC_BOUNDS = { 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)); @@ -270,68 +206,35 @@ function stringValues(value: unknown): Record { ); } -type StoredSettings = Partial; - -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); - - 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, settingsSync: { ...DEFAULT_SETTINGS_SYNC, ...((stored?.settingsSync as | Partial | undefined) ?? {}), }, - spaces: Array.isArray(stored?.spaces) - ? stored.spaces.filter(isSpaceRecord) - : [], 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/core/shared/format.ts b/packages/plugin/src/core/shared/format.ts index 9bf6556d..47f908c0 100644 --- a/packages/plugin/src/core/shared/format.ts +++ b/packages/plugin/src/core/shared/format.ts @@ -1,5 +1,3 @@ -import type { ManifestEntry } from "@/features/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) { diff --git a/packages/plugin/src/core/shared/index.ts b/packages/plugin/src/core/shared/index.ts index 7d5f7043..594f92ef 100644 --- a/packages/plugin/src/core/shared/index.ts +++ b/packages/plugin/src/core/shared/index.ts @@ -26,4 +26,4 @@ export { relayBase, stripTrailingSlash, } from "./path"; -export { entryAt, sortedByPath } from "./records"; +export { StorageHttpError, StorageTimeoutError } from "./transport-errors"; diff --git a/packages/plugin/src/core/shared/offline.ts b/packages/plugin/src/core/shared/offline.ts index 3f16ddf3..110b522e 100644 --- a/packages/plugin/src/core/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/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/core/ui/index.ts b/packages/plugin/src/core/ui/index.ts index a2269737..3188196d 100644 --- a/packages/plugin/src/core/ui/index.ts +++ b/packages/plugin/src/core/ui/index.ts @@ -10,7 +10,7 @@ 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, personTitle, showMenuAt } from "./menu"; +export { infoTitle, showMenuAt } from "./menu"; export { asDrawer, type ModalHead, diff --git a/packages/plugin/src/core/ui/menu.ts b/packages/plugin/src/core/ui/menu.ts index ca129cdc..88947fa1 100644 --- a/packages/plugin/src/core/ui/menu.ts +++ b/packages/plugin/src/core/ui/menu.ts @@ -1,7 +1,4 @@ import type { Menu } from "obsidian"; -import { withDevices } from "@/core/shared"; -import { renderAvatar } from "@/features/presence/ui/avatars"; -import type { Person } from "@/features/presence/views"; export function infoTitle(text: string, state?: string): DocumentFragment { const title = createFragment(); @@ -10,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/core/ui/notices.ts b/packages/plugin/src/core/ui/notices.ts index 3aebc468..26ac6449 100644 --- a/packages/plugin/src/core/ui/notices.ts +++ b/packages/plugin/src/core/ui/notices.ts @@ -1,7 +1,6 @@ import { ButtonComponent, Notice } from "obsidian"; import { errorMessage } from "@/core/shared"; -import type { SyncOperationResult } from "@/features/sync/controller"; const NOTICE_DURATION_MS = 8000; @@ -44,7 +43,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/utils/index.ts b/packages/plugin/src/core/utils/index.ts index 1703756a..1b3081f6 100644 --- a/packages/plugin/src/core/utils/index.ts +++ b/packages/plugin/src/core/utils/index.ts @@ -9,10 +9,4 @@ 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 { - createLargeFileGate, - LARGE_FILE_BYTES, - runWithFileConcurrency, -} from "./file-concurrency"; export { isNewer, type Revised } from "./revision"; -export { firstIndex } from "./search"; diff --git a/packages/plugin/src/features/diff/action-bar.ts b/packages/plugin/src/features/diff/action-bar.ts index 6bfde9c1..34c12aa8 100644 --- a/packages/plugin/src/features/diff/action-bar.ts +++ b/packages/plugin/src/features/diff/action-bar.ts @@ -1,5 +1,5 @@ import { ButtonComponent } from "obsidian"; -import { EDiffDirection } from "@/features/sync/hunks/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. */ diff --git a/packages/plugin/src/features/diff/choices.ts b/packages/plugin/src/features/diff/choices.ts index 38b1eac6..9864e344 100644 --- a/packages/plugin/src/features/diff/choices.ts +++ b/packages/plugin/src/features/diff/choices.ts @@ -1,5 +1,5 @@ -import type { HunkSelection } from "@/features/sync/hunks/hunks"; -import { EDiffDirection } from "@/features/sync/hunks/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/features/diff/compare/compare-decorations.ts b/packages/plugin/src/features/diff/compare/compare-decorations.ts index 1497a0bc..e7dc5339 100644 --- a/packages/plugin/src/features/diff/compare/compare-decorations.ts +++ b/packages/plugin/src/features/diff/compare/compare-decorations.ts @@ -11,12 +11,8 @@ import { type ViewUpdate, WidgetType, } from "@codemirror/view"; -import { hunkSegments, type LineRange } from "@/features/sync/hunks/hunks"; -import type { Span } from "@/features/sync/hunks/merge-model"; -import type { - EDiffDirection, - FileDiffModel, -} from "@/features/sync/hunks/projection"; +import type { EDiffDirection, FileDiffModel, Span } from "@/features/sync"; +import { hunkSegments, type LineRange } from "@/features/sync"; import { choiceVerb, type HunkChoices } from "../choices"; import { addCodeMarks, type LineMarks, lineMarks } from "../lines/code-lines"; import { diff --git a/packages/plugin/src/features/diff/compare/compare-panel.ts b/packages/plugin/src/features/diff/compare/compare-panel.ts index 4392f82f..223d48eb 100644 --- a/packages/plugin/src/features/diff/compare/compare-panel.ts +++ b/packages/plugin/src/features/diff/compare/compare-panel.ts @@ -1,9 +1,6 @@ import { EditorState } from "@codemirror/state"; import { EditorView, lineNumbers } from "@codemirror/view"; -import { - EDiffDirection, - type FileDiffModel, -} from "@/features/sync/hunks/projection"; +import { EDiffDirection, type FileDiffModel } from "@/features/sync"; import { choiceActions, type EChoiceKind, HunkChoices } from "../choices"; import type { PanelHosts } from "../header"; import { LayoutMode } from "../layout-mode"; diff --git a/packages/plugin/src/features/diff/history-state.ts b/packages/plugin/src/features/diff/history-state.ts index b6c04a2d..acac13d0 100644 --- a/packages/plugin/src/features/diff/history-state.ts +++ b/packages/plugin/src/features/diff/history-state.ts @@ -1,10 +1,12 @@ -import { HUNK_TEXT_MAX_BYTES } from "@/features/sync/constants"; +import { DIFF_VIEW_TYPE } from "@/core/constants"; import { EDiffDirection, type FileDiffModel, type HistoryDiffRequest, type HistoryVersionRef, -} from "@/features/sync/hunks/projection"; + HUNK_TEXT_MAX_BYTES, +} from "@/features/sync"; +import type { DiffHost } from "./host"; export interface HistoryChange { before: HistoryVersionRef | null; @@ -26,6 +28,42 @@ export interface DiffViewState { merge?: boolean; } +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: 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, + historyPreviewIfMissing: history?.previewIfMissing, + merge: merge || undefined, + }; + await leaf.setViewState({ + type: DIFF_VIEW_TYPE, + active: true, + state: { ...state }, + }); + await plugin.app.workspace.revealLeaf(leaf); +} + export type HistoryMode = "change" | "preview" | "diff"; export interface HistoryModeInput { 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 index 6d17e1b5..3f6d2a49 100644 --- a/packages/plugin/src/features/diff/index.ts +++ b/packages/plugin/src/features/diff/index.ts @@ -1,3 +1,8 @@ -export type { HistoryChange } from "./history-state"; -export { confirmBulkRestore, confirmRestore } from "./restore-modal"; +export { + type HistoryChange, + type HistoryDiffTarget, + openDiffView, +} from "./history-state"; +export type { DiffHost } from "./host"; +export { confirmBulkRestore, confirmRestore } from "./ui/restore-modal"; export { DiffView } from "./view"; diff --git a/packages/plugin/src/features/diff/lines/change-overlay.ts b/packages/plugin/src/features/diff/lines/change-overlay.ts index 7b1de676..3f37482c 100644 --- a/packages/plugin/src/features/diff/lines/change-overlay.ts +++ b/packages/plugin/src/features/diff/lines/change-overlay.ts @@ -1,11 +1,11 @@ import type { EditorView } from "@codemirror/view"; -import { firstIndex } from "@/core/utils"; import type { CompareSegment, CompareSide, } from "../compare/compare-decorations"; import { renderRailButton } from "../rail"; import { type Bounds, shiftBounds, sideSpan, spanBounds } from "./geometry"; +import { firstIndex } from "./search"; /** A shorter change is cheaper to scroll past than to fold. */ const MIN_FOLD_LINES = 10; diff --git a/packages/plugin/src/features/diff/lines/divider.ts b/packages/plugin/src/features/diff/lines/divider.ts index 7b4e7ce5..47b7aba9 100644 --- a/packages/plugin/src/features/diff/lines/divider.ts +++ b/packages/plugin/src/features/diff/lines/divider.ts @@ -1,8 +1,8 @@ import type { EditorView } from "@codemirror/view"; -import { firstIndex } from "@/core/utils"; import type { Span } from "@/features/sync"; import { type RailAction, renderRailButton } from "../rail"; import { type Bounds, shiftBounds, spanBounds } from "./geometry"; +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/gap-widgets.ts b/packages/plugin/src/features/diff/lines/gap-widgets.ts index da882112..6a459188 100644 --- a/packages/plugin/src/features/diff/lines/gap-widgets.ts +++ b/packages/plugin/src/features/diff/lines/gap-widgets.ts @@ -7,8 +7,8 @@ import { WidgetType, } from "@codemirror/view"; import { setIcon } from "obsidian"; -import { firstIndex } from "@/core/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/features/diff/lines/geometry.ts b/packages/plugin/src/features/diff/lines/geometry.ts index 79fc12a1..005dfad0 100644 --- a/packages/plugin/src/features/diff/lines/geometry.ts +++ b/packages/plugin/src/features/diff/lines/geometry.ts @@ -1,7 +1,7 @@ import type { Text } from "@codemirror/state"; import type { EditorView } from "@codemirror/view"; -import { firstIndex } from "@/core/utils"; import type { LineRange, Span } from "@/features/sync"; +import { firstIndex } from "./search"; export interface Bounds { top: number; diff --git a/packages/plugin/src/features/diff/lines/scroll-sync.ts b/packages/plugin/src/features/diff/lines/scroll-sync.ts index 5843aac3..81f83d56 100644 --- a/packages/plugin/src/features/diff/lines/scroll-sync.ts +++ b/packages/plugin/src/features/diff/lines/scroll-sync.ts @@ -1,7 +1,7 @@ import type { EditorView } from "@codemirror/view"; -import { firstIndex } from "@/core/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/core/utils/search.ts b/packages/plugin/src/features/diff/lines/search.ts similarity index 100% rename from packages/plugin/src/core/utils/search.ts rename to packages/plugin/src/features/diff/lines/search.ts diff --git a/packages/plugin/src/features/diff/lines/source-widget.ts b/packages/plugin/src/features/diff/lines/source-widget.ts index ab6701dd..01f327b7 100644 --- a/packages/plugin/src/features/diff/lines/source-widget.ts +++ b/packages/plugin/src/features/diff/lines/source-widget.ts @@ -1,6 +1,6 @@ import { type EditorView, WidgetType } from "@codemirror/view"; import { setIcon } from "obsidian"; -import { type Span, sameLines } from "@/features/sync/hunks/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"; 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/features/diff/merge/merge-actions.ts b/packages/plugin/src/features/diff/merge/merge-actions.ts index 247883b1..94c85fa4 100644 --- a/packages/plugin/src/features/diff/merge/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 "@/features/sync/hunks/merge-model"; +} from "./edit-plan"; import { fullTaken, mergeChangesField, setChangeState } from "./merge-state"; export interface MergeActions { diff --git a/packages/plugin/src/features/diff/merge/merge-cards.ts b/packages/plugin/src/features/diff/merge/merge-cards.ts index 83a10e82..2ad2cde5 100644 --- a/packages/plugin/src/features/diff/merge/merge-cards.ts +++ b/packages/plugin/src/features/diff/merge/merge-cards.ts @@ -6,18 +6,18 @@ import { type Text, } from "@codemirror/state"; import { Decoration, type DecorationSet } from "@codemirror/view"; -import type { LineRange } from "@/features/sync/hunks/hunks"; +import type { LineRange } from "@/features/sync"; import { type EMergeSide, isResolved, MERGE_SIDES, type MergeChange, - snapToLines, -} from "@/features/sync/hunks/merge-model"; +} 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"; diff --git a/packages/plugin/src/features/diff/merge/merge-controls.ts b/packages/plugin/src/features/diff/merge/merge-controls.ts index 0b5b1352..dd5ffcb6 100644 --- a/packages/plugin/src/features/diff/merge/merge-controls.ts +++ b/packages/plugin/src/features/diff/merge/merge-controls.ts @@ -1,12 +1,9 @@ import type { Text } from "@codemirror/state"; -import { - type EMergeSide, - type MergeChange, - snapToLines, -} from "@/features/sync/hunks/merge-model"; +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"; export type MergeTone = "conflict" | EMergeSide | "base" | "shared"; diff --git a/packages/plugin/src/features/diff/merge/merge-decorations.ts b/packages/plugin/src/features/diff/merge/merge-decorations.ts index de31569c..d7b81ee5 100644 --- a/packages/plugin/src/features/diff/merge/merge-decorations.ts +++ b/packages/plugin/src/features/diff/merge/merge-decorations.ts @@ -6,14 +6,12 @@ import { type Text, } from "@codemirror/state"; import { Decoration, type DecorationSet, EditorView } from "@codemirror/view"; -import { firstIndex } from "@/core/utils"; import { type EMergeSide, isResolved, MERGE_SIDES, type MergeChange, - snapToLines, -} from "@/features/sync/hunks/merge-model"; +} from "@/features/sync"; import { addCodeMarks } from "../lines/code-lines"; import { numberUnchangedLines } from "../lines/gap-widgets"; import { forEachVisibleRange, rangeLabel, sideSpan } from "../lines/geometry"; @@ -23,7 +21,9 @@ import { 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, diff --git a/packages/plugin/src/features/diff/merge/merge-editor.ts b/packages/plugin/src/features/diff/merge/merge-editor.ts index 7b5db1c2..609b1830 100644 --- a/packages/plugin/src/features/diff/merge/merge-editor.ts +++ b/packages/plugin/src/features/diff/merge/merge-editor.ts @@ -9,7 +9,6 @@ import { import { EditorState } from "@codemirror/state"; import { EditorView, keymap, lineNumbers } from "@codemirror/view"; import { setIcon } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { randomId } from "@/core/crypto"; import { notifyError, notifyInfo, runWithNotice } from "@/core/ui"; import { eolOf } from "@/core/utils"; @@ -20,9 +19,9 @@ import { isResolved, MERGE_SIDES, type MergeChange, - snapToLines, -} from "@/features/sync/hunks/merge-model"; +} from "@/features/sync"; import type { PanelHosts } from "../header"; +import type { DiffHost } from "../host"; import { LayoutMode } from "../layout-mode"; import { LineWrappingControl, @@ -41,6 +40,7 @@ import { 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 { dividerItems } from "./merge-controls"; @@ -96,7 +96,7 @@ export class MergeEditorPanel { /** `stillOn` says the view still shows `path` once the three versions arrive. */ async enter( - plugin: PluginHost, + plugin: DiffHost, path: string, stillOn: () => boolean, onEntered: () => void, @@ -405,7 +405,7 @@ export class MergeEditorPanel { } async save( - plugin: PluginHost, + plugin: DiffHost, path: string, onSaved: (resolvedPath: string) => Promise, ): Promise { diff --git a/packages/plugin/src/features/diff/merge/merge-state.ts b/packages/plugin/src/features/diff/merge/merge-state.ts index 3c57b709..a3306695 100644 --- a/packages/plugin/src/features/diff/merge/merge-state.ts +++ b/packages/plugin/src/features/diff/merge/merge-state.ts @@ -9,13 +9,15 @@ import { type EMergeSide, MERGE_SIDES, type MergeChange, - patchTaken, type Span, + type Taken, +} from "@/features/sync"; +import { + patchTaken, type StatusPatch, sameStatus, - type Taken, type TakenPatch, -} from "@/features/sync/hunks/merge-model"; +} from "./edit-plan"; export interface ChangeStateUpdate { index: number; diff --git a/packages/plugin/src/features/diff/operations.ts b/packages/plugin/src/features/diff/operations.ts index b2c5976a..8fc92496 100644 --- a/packages/plugin/src/features/diff/operations.ts +++ b/packages/plugin/src/features/diff/operations.ts @@ -1,16 +1,14 @@ -import type { PluginHost } from "@/app/host"; import { notifyError, openConfirmModal, runWithNotice } from "@/core/ui"; import { EConflictStrategy, - type SyncOperationResult, -} from "@/features/sync/controller"; -import { EDiffDirection, type FileDiffModel, -} from "@/features/sync/hunks/projection"; + type SyncOperationResult, +} from "@/features/sync"; import { EChoiceKind, type HunkChoices } from "./choices"; import type { HistoryChange } from "./history-state"; -import { confirmRestore } from "./restore-modal"; +import type { DiffHost } from "./host"; +import { confirmRestore } from "./ui/restore-modal"; export interface DiffOperationState { path: string | null; @@ -29,7 +27,7 @@ export class DiffOperations { private hunkOpInFlight = false; constructor( - private readonly plugin: PluginHost, + private readonly plugin: DiffHost, private readonly callbacks: DiffOperationCallbacks, ) {} @@ -189,10 +187,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/features/diff/restore-modal.ts b/packages/plugin/src/features/diff/ui/restore-modal.ts similarity index 97% rename from packages/plugin/src/features/diff/restore-modal.ts rename to packages/plugin/src/features/diff/ui/restore-modal.ts index fe1495a6..9e589c46 100644 --- a/packages/plugin/src/features/diff/restore-modal.ts +++ b/packages/plugin/src/features/diff/ui/restore-modal.ts @@ -1,5 +1,4 @@ import { ButtonComponent, Modal } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { errorMessage, formatBytes } from "@/core/shared"; import { actionButton, @@ -11,10 +10,11 @@ import { renderPath, } from "@/core/ui"; import type { FileDiffModel, HistoryVersionRef } from "@/features/sync"; -import { renderHunkPreview } from "./compare/hunk-renderer"; +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; @@ -99,7 +99,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/features/diff/view.ts b/packages/plugin/src/features/diff/view.ts index 1f0bc9c2..905dac63 100644 --- a/packages/plugin/src/features/diff/view.ts +++ b/packages/plugin/src/features/diff/view.ts @@ -1,15 +1,13 @@ import { ItemView, type ViewStateResult, type WorkspaceLeaf } from "obsidian"; -import type { PluginHost } from "@/app/host"; -import { DIFF_VIEW_TYPE, SOURCE_CONTROL_VIEW_TYPE } from "@/core/constants"; +import { DIFF_VIEW_TYPE } from "@/core/constants"; import { userMessage } from "@/core/shared"; import { notifyError, openConfirmModal, redrawOnPhoneChange } from "@/core/ui"; -import { openSourceControlView } from "@/features/source-control/view"; -import type { CompareResult } from "@/features/sync/engine"; +import type { CompareResult } from "@/features/sync"; import { EDiffDirection, type FileDiffModel, type HistoryVersionRef, -} from "@/features/sync/hunks/projection"; +} from "@/features/sync"; import { watchDiffChrome } from "./action-bar"; import { renderBinaryDiff } from "./compare/binary-view"; import { type ComparePanel, renderTextDiff } from "./compare/compare-panel"; @@ -28,11 +26,12 @@ import { type HistoryChange, selectHistoryMode, } from "./history-state"; +import type { DiffHost } from "./host"; import { MergeEditorPanel } from "./merge/merge-editor"; import { DiffOperations } from "./operations"; 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; @@ -59,7 +58,7 @@ 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, { @@ -457,7 +456,7 @@ 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 { 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/features/editor-signs/index.ts b/packages/plugin/src/features/editor-signs/index.ts index 2f82dbf6..edc32850 100644 --- a/packages/plugin/src/features/editor-signs/index.ts +++ b/packages/plugin/src/features/editor-signs/index.ts @@ -1 +1,2 @@ +export type { EditorSignsHost } from "./host"; export { registerEditorSigns, type SignsHandle } from "./register"; diff --git a/packages/plugin/src/features/editor-signs/register.ts b/packages/plugin/src/features/editor-signs/register.ts index 04e7f93e..d495619c 100644 --- a/packages/plugin/src/features/editor-signs/register.ts +++ b/packages/plugin/src/features/editor-signs/register.ts @@ -1,10 +1,8 @@ import type { Extension } from "@codemirror/state"; import type { Plugin, TAbstractFile } from "obsidian"; import { TFile } from "obsidian"; - -import type { PluginHost } from "@/app/host"; - import { buildSignsExtensions } from "./extension"; +import type { EditorSignsHost } from "./host"; import { dismissPopup } from "./popup/hunk-popup"; import { SignsProvider } from "./provider"; @@ -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/features/explorer/file-context-indicators.ts b/packages/plugin/src/features/explorer/file-context-indicators.ts index 7e98027d..cd7f4f87 100644 --- a/packages/plugin/src/features/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 "@/app/host"; 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/features/explorer/file-explorer-badges.ts b/packages/plugin/src/features/explorer/file-explorer-badges.ts index a9fd628d..df6ebc87 100644 --- a/packages/plugin/src/features/explorer/file-explorer-badges.ts +++ b/packages/plugin/src/features/explorer/file-explorer-badges.ts @@ -1,10 +1,7 @@ import { Notice, Platform, setIcon } from "obsidian"; - -import type { PluginHost } from "@/app/host"; import { openManageLinks } from "@/features/links"; import { describePeople, renderAvatarStack } from "@/features/presence"; import { lastEditLabel, openShareWindow } from "@/features/spaces"; - import type { PresenceMarks, PublishedMark, @@ -12,6 +9,7 @@ import type { ShareMark, UnseenMark, } from "./file-explorer-marks"; +import type { ExplorerHost } from "./host"; const SHARE_ICONS: Record = { owned: "share-2", @@ -36,7 +34,7 @@ const TIP_MS = 4000; export function renderPresenceMarks( target: HTMLElement, marks: PresenceMarks, - plugin: PluginHost, + plugin: ExplorerHost, ): void { if (marks.unseen) { target.createSpan({ @@ -60,7 +58,7 @@ 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; return (event) => { @@ -92,7 +90,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/features/explorer/file-explorer-decorations.ts b/packages/plugin/src/features/explorer/file-explorer-decorations.ts index c905fd87..34a40942 100644 --- a/packages/plugin/src/features/explorer/file-explorer-decorations.ts +++ b/packages/plugin/src/features/explorer/file-explorer-decorations.ts @@ -1,6 +1,4 @@ import { setIcon } from "obsidian"; - -import type { PluginHost } from "@/app/host"; import type { EChangeType, SyncController } from "@/features/sync"; import { type ChangeAction, @@ -8,9 +6,9 @@ import { skippedFiles, skippedText, } 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"; @@ -59,7 +57,7 @@ const TARGET_CLASSES = [ ]; export function computeBase( - plugin: PluginHost, + plugin: ExplorerHost, controller: SyncController, directLinks: ReadonlyMap, ): Map { @@ -120,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/features/explorer/file-explorer-indicators.ts b/packages/plugin/src/features/explorer/file-explorer-indicators.ts index dffe11f7..745638e6 100644 --- a/packages/plugin/src/features/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 "@/app/host"; 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/features/explorer/file-explorer-marks.ts b/packages/plugin/src/features/explorer/file-explorer-marks.ts index 7c38e57e..0dad231b 100644 --- a/packages/plugin/src/features/explorer/file-explorer-marks.ts +++ b/packages/plugin/src/features/explorer/file-explorer-marks.ts @@ -1,7 +1,7 @@ -import type { PluginHost } from "@/app/host"; 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 index fba46e6c..f39c8870 100644 --- a/packages/plugin/src/features/explorer/index.ts +++ b/packages/plugin/src/features/explorer/index.ts @@ -1,3 +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/features/explorer/row-decorator.ts b/packages/plugin/src/features/explorer/row-decorator.ts index 32a962af..bef71058 100644 --- a/packages/plugin/src/features/explorer/row-decorator.ts +++ b/packages/plugin/src/features/explorer/row-decorator.ts @@ -1,4 +1,3 @@ -import type { PluginHost } from "@/app/host"; import type { SyncController } from "@/features/sync"; import { skippedFiles } from "@/features/sync"; import type { FileExplorerRows } from "./file-explorer-api"; @@ -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, ) {} 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 index 65f7338b..d946e9be 100644 --- a/packages/plugin/src/features/links/index.ts +++ b/packages/plugin/src/features/links/index.ts @@ -1,8 +1,9 @@ +export type { LinksHost } from "./host"; export { noteLinks, noteLinksText } from "./note-links"; export { type LinkRecord, onRelay, - parseStoredLink, + parseStoredLinks, type StoredLink, } from "./record"; export { registerLinkPaths } from "./register"; diff --git a/packages/plugin/src/features/links/link-broker.ts b/packages/plugin/src/features/links/link-broker.ts index 463f2c29..5313e037 100644 --- a/packages/plugin/src/features/links/link-broker.ts +++ b/packages/plugin/src/features/links/link-broker.ts @@ -1,17 +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 "@/core/shared"; +import { relayBase, StorageHttpError } from "@/core/shared"; import { toArrayBuffer } from "@/core/utils"; -import { - ADMIN_HEADER, - type BrokerAdmin, -} from "@/features/spaces/broker/share-broker"; -import { - errorCode, - StorageHttpError, - StorageRequestError, -} from "@/features/storage"; +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/features/links/note-links.ts b/packages/plugin/src/features/links/note-links.ts index 2a11d82d..beeff49d 100644 --- a/packages/plugin/src/features/links/note-links.ts +++ b/packages/plugin/src/features/links/note-links.ts @@ -1,6 +1,5 @@ -import type { PluginHost } from "@/app/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/features/links/publish.ts b/packages/plugin/src/features/links/publish.ts index 420d72a9..db351ab7 100644 --- a/packages/plugin/src/features/links/publish.ts +++ b/packages/plugin/src/features/links/publish.ts @@ -11,11 +11,11 @@ import { toBase64Url, } from "@mdsync/protocol"; import type { TFile } from "obsidian"; - -import type { PluginHost } from "@/app/host"; -import { isRelayConfigured, relayAdmin } from "@/core/settings"; +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"; @@ -40,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 { @@ -52,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, @@ -112,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(), @@ -153,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/features/links/record.ts b/packages/plugin/src/features/links/record.ts index b482bd0d..e92f782e 100644 --- a/packages/plugin/src/features/links/record.ts +++ b/packages/plugin/src/features/links/record.ts @@ -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/features/links/register.ts b/packages/plugin/src/features/links/register.ts index 090f668a..3c145f77 100644 --- a/packages/plugin/src/features/links/register.ts +++ b/packages/plugin/src/features/links/register.ts @@ -1,9 +1,9 @@ import type { Plugin } from "obsidian"; -import type { PluginHost } from "@/app/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/features/links/ui/link-actions.ts b/packages/plugin/src/features/links/ui/link-actions.ts index 568dd89e..028b0f2a 100644 --- a/packages/plugin/src/features/links/ui/link-actions.ts +++ b/packages/plugin/src/features/links/ui/link-actions.ts @@ -1,12 +1,12 @@ -import type { PluginHost } from "@/app/host"; 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(); @@ -32,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/features/links/ui/link-menu.ts b/packages/plugin/src/features/links/ui/link-menu.ts index b5189d2d..8029e117 100644 --- a/packages/plugin/src/features/links/ui/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 type { PluginHost } from "@/app/host"; import { isRelayConfigured } from "@/core/settings"; -import { docKindOf } from "@/features/live/doc-types"; -import { ESetupStep } from "@/features/setup/step-state"; +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/features/links/ui/links-section.ts b/packages/plugin/src/features/links/ui/links-section.ts index a9189f74..d085fc7b 100644 --- a/packages/plugin/src/features/links/ui/links-section.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"; -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/features/links/ui/manage-links-modal.ts b/packages/plugin/src/features/links/ui/manage-links-modal.ts index efdc155e..4ebe45d0 100644 --- a/packages/plugin/src/features/links/ui/manage-links-modal.ts +++ b/packages/plugin/src/features/links/ui/manage-links-modal.ts @@ -6,7 +6,6 @@ import { Setting, type TFile, } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { copyText, modalCard, @@ -20,6 +19,7 @@ import { 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, @@ -47,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/features/links/ui/note-link-action.ts b/packages/plugin/src/features/links/ui/note-link-action.ts index 5c2b8ebd..1e86bfaf 100644 --- a/packages/plugin/src/features/links/ui/note-link-action.ts +++ b/packages/plugin/src/features/links/ui/note-link-action.ts @@ -1,5 +1,5 @@ import { FileView, type Plugin, type WorkspaceLeaf } from "obsidian"; -import type { PluginHost } from "@/app/host"; +import type { LinksHost } from "../host"; import { noteLinks, noteLinksText } from "../note-links"; import { openManageLinks } from "./link-menu"; @@ -10,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/features/links/ui/share-link-modal.ts b/packages/plugin/src/features/links/ui/share-link-modal.ts index 1253fb21..1681ad3c 100644 --- a/packages/plugin/src/features/links/ui/share-link-modal.ts +++ b/packages/plugin/src/features/links/ui/share-link-modal.ts @@ -6,7 +6,6 @@ import { type TextComponent, type TFile, } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { alertLine, copyable, @@ -14,7 +13,7 @@ import { renderModalHead, serial, } from "@/core/ui"; -import { invitePassword } from "@/features/spaces/invite"; +import { invitePassword } from "@/features/spaces"; import { DEFAULT_EXPIRY, DEFAULT_VIEWS, @@ -26,6 +25,7 @@ import { VIEW_CHOICES, } 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"; @@ -61,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/cold/cold-sync.ts b/packages/plugin/src/features/live/cold/cold-sync.ts index fb422249..2d148c03 100644 --- a/packages/plugin/src/features/live/cold/cold-sync.ts +++ b/packages/plugin/src/features/live/cold/cold-sync.ts @@ -5,14 +5,14 @@ import { sha256Hex } from "@/core/crypto"; import { toLf } from "@/core/utils"; -import { textToBytes } from "@/features/sync/changes/content"; +import type { LiveMark } from "@/features/sync"; import { type IncomingText, isNewerMark, type LiveNotes, type LiveTake, -} from "@/features/sync/live-notes"; -import type { LiveMark } from "@/features/sync/types"; + textToBytes, +} from "@/features/sync"; import { hasLiveExtension } from "../doc-types"; import type { LiveSession } from "../session/session"; import type { LiveSessions } from "../workspace/sessions"; diff --git a/packages/plugin/src/features/live/register.ts b/packages/plugin/src/features/live/register.ts index 71e1d879..da276b0b 100644 --- a/packages/plugin/src/features/live/register.ts +++ b/packages/plugin/src/features/live/register.ts @@ -1,34 +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 { HubConnection } from "@/features/relay"; -import type { - SpaceAccess, - SpaceAccessHost, - SpaceRecords, -} from "@/features/spaces"; -import type { LiveNotes } from "@/features/sync/live-notes"; -import type { WriteJournal } from "@/features/sync/recovery/journal"; -import { type Space, spaceOf, VAULT_SPACE } from "@/features/sync/remote/space"; +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"; -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; @@ -81,7 +88,7 @@ export function createLive( function refreshOnChanges( { workspace, vault, metadataCache }: App, - hub: HubConnection, + hub: SpaceHubs, sessions: LiveSessions, ): () => void { const refresh = () => void sessions.refresh(); @@ -127,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/features/live/session/rotation.ts b/packages/plugin/src/features/live/session/rotation.ts index 48cb774e..d74b19a4 100644 --- a/packages/plugin/src/features/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 "@/core/crypto"; import { seal } from "@/core/crypto"; -import type { SpaceFrame } from "@/features/relay"; +import type { SpaceFrame } from "@/core/hub"; import type { Rotation } from "./session-deps"; type RotateFrame = Omit< diff --git a/packages/plugin/src/features/live/session/session-deps.ts b/packages/plugin/src/features/live/session/session-deps.ts index d780631e..256fabad 100644 --- a/packages/plugin/src/features/live/session/session-deps.ts +++ b/packages/plugin/src/features/live/session/session-deps.ts @@ -1,7 +1,6 @@ import type { Refusal } from "@mdsync/protocol"; - import type { LiveKeys } from "@/core/crypto"; -import type { SpaceHub } from "@/features/relay"; +import type { SpaceHub } from "@/core/hub"; import type { Author } from "../authors"; import type { LiveKind, LiveModel } from "../model"; diff --git a/packages/plugin/src/features/live/session/session.ts b/packages/plugin/src/features/live/session/session.ts index 4a0df980..df9c5539 100644 --- a/packages/plugin/src/features/live/session/session.ts +++ b/packages/plugin/src/features/live/session/session.ts @@ -12,9 +12,9 @@ import { import * as Y from "yjs"; 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 type { SpaceFrame, SpaceListener } from "@/features/relay"; import { attribute } from "../authors"; import type { LiveModel } from "../model"; import { closingUntil } from "./closing"; diff --git a/packages/plugin/src/features/live/text/merge.ts b/packages/plugin/src/features/live/text/merge.ts index 735f3e32..8fb5873a 100644 --- a/packages/plugin/src/features/live/text/merge.ts +++ b/packages/plugin/src/features/live/text/merge.ts @@ -1,9 +1,5 @@ import { commonEnds } from "@/core/utils"; -import { - sameLines, - threeWayRegions, - toLines, -} from "@/features/sync/hunks/merge-model"; +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/features/live/text/patch.ts b/packages/plugin/src/features/live/text/patch.ts index 9eb1f0db..986fc031 100644 --- a/packages/plugin/src/features/live/text/patch.ts +++ b/packages/plugin/src/features/live/text/patch.ts @@ -1,6 +1,6 @@ import type * as Y from "yjs"; import { changedMiddle, diffRanges } from "@/core/utils"; -import { DIFF_BUDGET } from "@/features/sync/hunks/hunks"; +import { DIFF_BUDGET } from "@/features/sync"; const MIN_ANCHOR = 10; diff --git a/packages/plugin/src/features/live/ui/deleted-elsewhere.ts b/packages/plugin/src/features/live/ui/deleted-elsewhere.ts index 95c0c2c8..33d240c9 100644 --- a/packages/plugin/src/features/live/ui/deleted-elsewhere.ts +++ b/packages/plugin/src/features/live/ui/deleted-elsewhere.ts @@ -1,10 +1,16 @@ -import type { PluginHost } from "@/app/host"; +import type { App } from "obsidian"; import { notifyError, openChoiceModal, runWithNotice } from "@/core/ui"; -import { spaceOf } from "@/features/sync/remote/space"; +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) => { @@ -14,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/features/live/workspace/rename.ts b/packages/plugin/src/features/live/workspace/rename.ts index ee09440a..c7224ac8 100644 --- a/packages/plugin/src/features/live/workspace/rename.ts +++ b/packages/plugin/src/features/live/workspace/rename.ts @@ -5,10 +5,14 @@ import { EFrame } from "@mdsync/protocol"; import { seal, unseal } from "@/core/crypto"; +import type { SpaceHub } from "@/core/hub"; import { hasDotSegment, normalizePath } from "@/core/shared"; -import type { SpaceHub } from "@/features/relay"; -import { bytesToText, textToBytes } from "@/features/sync/changes/content"; -import { insideOf, vaultPathOf } from "@/features/sync/remote/space"; +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"; diff --git a/packages/plugin/src/features/live/workspace/room.ts b/packages/plugin/src/features/live/workspace/room.ts index 048ff24f..cb34300a 100644 --- a/packages/plugin/src/features/live/workspace/room.ts +++ b/packages/plugin/src/features/live/workspace/room.ts @@ -1,8 +1,8 @@ import { ERefusal } from "@mdsync/protocol"; import type { App, TFile } from "obsidian"; +import type { SpaceHubs } from "@/core/hub"; import { reportWarning, withDevices } from "@/core/shared"; import { toLf } from "@/core/utils"; -import type { HubConnection } from "@/features/relay"; import type { AgreedTexts } from "../cold/agreed-texts"; import { closedBefore } from "../session/closing"; import type { Refused, Unfollowed } from "../session/session-deps"; @@ -47,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/features/live/workspace/space.ts b/packages/plugin/src/features/live/workspace/space.ts index abe4010e..b2ca16c2 100644 --- a/packages/plugin/src/features/live/workspace/space.ts +++ b/packages/plugin/src/features/live/workspace/space.ts @@ -1,5 +1,5 @@ import type { LiveKeys } from "@/core/crypto"; -import { insideOf } from "@/features/sync/remote/space"; +import { insideOf } from "@/features/sync"; import { docIdFor } from "../doc-id"; export interface LiveUser { diff --git a/packages/plugin/src/features/note-header/header-state.ts b/packages/plugin/src/features/note-header/header-state.ts index 370a420d..37248dba 100644 --- a/packages/plugin/src/features/note-header/header-state.ts +++ b/packages/plugin/src/features/note-header/header-state.ts @@ -1,6 +1,4 @@ import { FileView, type TFile, type WorkspaceLeaf } from "obsidian"; - -import type { PluginHost } from "@/app/host"; import type { LiveState } from "@/features/live"; import type { Person } from "@/features/presence"; import { @@ -10,6 +8,7 @@ import { spaceOf, VAULT_SPACE, } from "@/features/sync"; +import type { NoteHeaderHost } from "./host"; import { type LiveStatus, liveStatusOf } from "./live-status"; @@ -30,7 +29,7 @@ interface Header { } export function headerOf( - plugin: PluginHost, + plugin: NoteHeaderHost, leaf: WorkspaceLeaf, ): Header | null { const { view } = leaf; @@ -55,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 index b7de1904..1ec8dbd1 100644 --- a/packages/plugin/src/features/note-header/index.ts +++ b/packages/plugin/src/features/note-header/index.ts @@ -1,3 +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/features/note-header/live-actions.ts b/packages/plugin/src/features/note-header/live-actions.ts index 74ddd452..347dd828 100644 --- a/packages/plugin/src/features/note-header/live-actions.ts +++ b/packages/plugin/src/features/note-header/live-actions.ts @@ -1,6 +1,6 @@ -import type { PluginHost } from "@/app/host"; 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/features/note-header/live-status.ts b/packages/plugin/src/features/note-header/live-status.ts index d9652cab..b1f7b386 100644 --- a/packages/plugin/src/features/note-header/live-status.ts +++ b/packages/plugin/src/features/note-header/live-status.ts @@ -1,5 +1,4 @@ import { type FileView, MarkdownView, type TFile } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { isLinkState, RELAY_TEXT, @@ -15,6 +14,7 @@ import { liveKindOf, } from "@/features/live"; import type { Space } from "@/features/sync"; +import type { NoteHeaderHost } from "./host"; const ARRIVES_ON_SYNC = "Changes arrive as they sync"; @@ -43,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, @@ -77,7 +77,7 @@ export function liveStatusOf( } function coldReason( - plugin: PluginHost, + plugin: NoteHeaderHost, view: FileView, file: TFile, space: Space, diff --git a/packages/plugin/src/features/note-header/note-menu.ts b/packages/plugin/src/features/note-header/note-menu.ts index ff30cb53..3373f263 100644 --- a/packages/plugin/src/features/note-header/note-menu.ts +++ b/packages/plugin/src/features/note-header/note-menu.ts @@ -1,10 +1,10 @@ import { MarkdownView, Menu, type WorkspaceLeaf } from "obsidian"; - -import type { PluginHost } from "@/app/host"; import { openPluginSettings, relayFixOf } from "@/core/hub"; -import { infoTitle, personTitle, showMenuAt } from "@/core/ui"; +import { infoTitle, 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, @@ -16,7 +16,7 @@ import { } from "./note-menu-items"; export function openActiveNoteMenu( - plugin: PluginHost, + plugin: NoteHeaderHost, checking: boolean, ): boolean { const leaf = plugin.app.workspace.getMostRecentLeaf(); @@ -28,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/features/note-header/note-presence.ts b/packages/plugin/src/features/note-header/note-presence.ts index ff3a729d..b6bb0d17 100644 --- a/packages/plugin/src/features/note-header/note-presence.ts +++ b/packages/plugin/src/features/note-header/note-presence.ts @@ -1,10 +1,10 @@ import { type Plugin, setIcon, type WorkspaceLeaf } from "obsidian"; -import type { PluginHost } from "@/app/host"; 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"; @@ -24,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; @@ -104,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/follow/cursor-follow.ts b/packages/plugin/src/features/presence/follow/cursor-follow.ts index 24c03aab..70301b95 100644 --- a/packages/plugin/src/features/presence/follow/cursor-follow.ts +++ b/packages/plugin/src/features/presence/follow/cursor-follow.ts @@ -1,7 +1,7 @@ import { FileView, MarkdownView, type WorkspaceLeaf } from "obsidian"; -import type { PluginHost } from "@/app/host"; 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"; @@ -24,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/features/presence/follow/follow-scroll.ts b/packages/plugin/src/features/presence/follow/follow-scroll.ts index eca2d2ce..7abe55b7 100644 --- a/packages/plugin/src/features/presence/follow/follow-scroll.ts +++ b/packages/plugin/src/features/presence/follow/follow-scroll.ts @@ -1,8 +1,8 @@ import type { EditorView } from "@codemirror/view"; import type { MarkdownView } from "obsidian"; -import type { LiveSession } from "@/features/live/session/session"; -import { watchCursor } from "@/features/live/text/cursors"; +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/features/presence/follow/follows.ts b/packages/plugin/src/features/presence/follow/follows.ts index 8e758584..5c5604c3 100644 --- a/packages/plugin/src/features/presence/follow/follows.ts +++ b/packages/plugin/src/features/presence/follow/follows.ts @@ -1,9 +1,9 @@ import type { Plugin } from "obsidian"; -import type { PluginHost } from "@/app/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/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 index 5a52011e..7457e9bf 100644 --- a/packages/plugin/src/features/presence/index.ts +++ b/packages/plugin/src/features/presence/index.ts @@ -1,8 +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, renderAvatar, renderAvatarStack } from "./ui/avatars"; +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/features/presence/people.ts b/packages/plugin/src/features/presence/people.ts index 597197b1..aaae7bc4 100644 --- a/packages/plugin/src/features/presence/people.ts +++ b/packages/plugin/src/features/presence/people.ts @@ -3,15 +3,15 @@ import { CHANNEL_DOC, EFrame } from "@mdsync/protocol"; import type { LiveKeys } from "@/core/crypto"; +import type { SpaceHub, SpaceHubs } from "@/core/hub"; import { reportWarning } from "@/core/shared"; -import type { HubConnection, SpaceHub } from "@/features/relay"; import { insideOf, type Space, spaceOf, VAULT_SPACE, vaultPathOf, -} from "@/features/sync/remote/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/features/presence/register.ts b/packages/plugin/src/features/presence/register.ts index f357b668..f585c22d 100644 --- a/packages/plugin/src/features/presence/register.ts +++ b/packages/plugin/src/features/presence/register.ts @@ -1,5 +1,5 @@ import type { Plugin } from "obsidian"; -import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; +import { type Space, VAULT_SPACE } from "@/features/sync"; import { Unseen } from "./unseen"; const STORAGE_KEY = "mdsync-unseen"; diff --git a/packages/plugin/src/features/presence/ui/avatars.ts b/packages/plugin/src/features/presence/ui/avatars.ts index 669983fe..ea9d3812 100644 --- a/packages/plugin/src/features/presence/ui/avatars.ts +++ b/packages/plugin/src/features/presence/ui/avatars.ts @@ -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/features/relay/channels.ts b/packages/plugin/src/features/relay/channels.ts index 4aa2d79a..676eb5ab 100644 --- a/packages/plugin/src/features/relay/channels.ts +++ b/packages/plugin/src/features/relay/channels.ts @@ -7,17 +7,16 @@ import { deriveChannelGrant, MAX_SLOTS, shareChannel } from "@mdsync/protocol"; 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 "@/core/settings"; -import { relayBase } from "@/core/shared"; -import { pauseOf } from "@/features/spaces/partition"; -import type { SpaceRecord } from "@/features/spaces/record"; -import { storageIdentity } from "@/features/storage"; -import { VAULT_SPACE } from "@/features/sync/remote/space"; + storageIdentity, +} from "@/features/storage"; +import { VAULT_SPACE } from "@/features/sync"; export interface HubRoute { serverUrl: string; diff --git a/packages/plugin/src/features/relay/connection.ts b/packages/plugin/src/features/relay/connection.ts index c0355218..540f371f 100644 --- a/packages/plugin/src/features/relay/connection.ts +++ b/packages/plugin/src/features/relay/connection.ts @@ -3,43 +3,20 @@ * credentials change; listeners outlive the rebuilds. */ -import { type ClientFrame, EFrame, type ServerFrame } from "@mdsync/protocol"; -import { HubLink, type RelayStatus, relayStatus } from "@/core/hub"; +import { EFrame, type ServerFrame } from "@mdsync/protocol"; +import { + HubLink, + type HubListener, + type RelayStatus, + relayStatus, + type SpaceHub, + type SpaceListener, +} from "@/core/hub"; import type { MdsyncSettings } from "@/core/settings"; -import { pauseOf } from "@/features/spaces/partition"; -import { VAULT_SPACE } from "@/features/sync/remote/space"; +import { pauseOf } from "@/features/spaces"; +import { VAULT_SPACE } from "@/features/sync"; import { type HubRoute, hubRoutes } from "./channels"; -/** 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; deviceId(): string; diff --git a/packages/plugin/src/features/relay/deploy/deploy-flow.ts b/packages/plugin/src/features/relay/deploy/deploy-flow.ts index faecd1da..a889a179 100644 --- a/packages/plugin/src/features/relay/deploy/deploy-flow.ts +++ b/packages/plugin/src/features/relay/deploy/deploy-flow.ts @@ -1,10 +1,10 @@ import bundle from "mdsync:relay-bundle"; import { toHex } from "@mdsync/protocol"; -import type { PluginHost } from "@/app/host"; import { randomBytes, randomSecret } from "@/core/crypto"; import { isRelayConfigured, type RelayConfig } from "@/core/settings"; import type { CloudflareLogin } from "@/features/storage"; -import { testRelay } from "@/features/storage"; +import type { RelayHost } from "../host"; +import { testRelay } from "../relay-test"; import { type AccountRelays, ownRelayName, @@ -62,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, @@ -88,7 +88,7 @@ export function deployOwnRelay( } async function deployTo( - plugin: PluginHost, + plugin: RelayHost, login: CloudflareLogin, target: RelayTarget, onStep: (step: ERelayDeployStep) => void, @@ -128,7 +128,7 @@ 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 { +export function activateRelay(plugin: RelayHost): Promise { activating ??= (async () => { try { const answered = await waitForRelay( @@ -145,7 +145,7 @@ export function activateRelay(plugin: PluginHost): Promise { } /** Real-time sync is what a relay is for: on once it answers. */ -export async function useRelay(plugin: PluginHost): Promise { +export async function useRelay(plugin: RelayHost): Promise { plugin.settings.realtimeSync = true; await plugin.saveSettings(); plugin.realtime.hub.restart(); 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 index 40d39c54..4a6c5f1d 100644 --- a/packages/plugin/src/features/relay/index.ts +++ b/packages/plugin/src/features/relay/index.ts @@ -1,9 +1,4 @@ -export { - HubConnection, - type SpaceFrame, - type SpaceHub, - type SpaceListener, -} from "./connection"; +export { HubConnection } from "./connection"; export { activateRelay, deployOwnRelay, @@ -23,5 +18,7 @@ export { 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/features/relay/ui/relay-section.ts b/packages/plugin/src/features/relay/ui/relay-section.ts index 64eb53ed..dd3cf812 100644 --- a/packages/plugin/src/features/relay/ui/relay-section.ts +++ b/packages/plugin/src/features/relay/ui/relay-section.ts @@ -1,8 +1,8 @@ import type { SettingDefinitionGroup } from "obsidian"; - import { randomSecret } from "@/core/crypto"; import { checkRow, + EFieldKind, type FieldContext, fieldRow, group, @@ -10,14 +10,17 @@ import { } from "@/core/settings"; import { relayBase } from "@/core/shared"; import { runWithNotice } from "@/core/ui"; -import { ESetupStep } from "@/features/setup/step-state"; -import { EFieldKind, forgetCloudflare, testRelay } from "@/features/storage"; +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, @@ -36,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")), ); }, }, diff --git a/packages/plugin/src/features/relay/update/relay-update-modal.ts b/packages/plugin/src/features/relay/update/relay-update-modal.ts index 7ff40a66..f7f4fa3c 100644 --- a/packages/plugin/src/features/relay/update/relay-update-modal.ts +++ b/packages/plugin/src/features/relay/update/relay-update-modal.ts @@ -1,5 +1,4 @@ import { ButtonComponent, Modal } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { alertLine, modalFooter, @@ -15,10 +14,11 @@ import { } 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/features/relay/update/relay-update.ts b/packages/plugin/src/features/relay/update/relay-update.ts index 58b3817d..637025b8 100644 --- a/packages/plugin/src/features/relay/update/relay-update.ts +++ b/packages/plugin/src/features/relay/update/relay-update.ts @@ -1,7 +1,6 @@ import type { Plugin } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { reportWarning } from "@/core/shared"; -import { cloudflareOf, testRelay } from "@/features/storage"; +import { cloudflareOf } from "@/features/storage"; import { runningRelayDeploy } from "../deploy/deploy-flow"; import { accountRelays, @@ -10,6 +9,8 @@ import { type RelayTarget, relayBehind, } 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"; @@ -26,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/host.ts b/packages/plugin/src/features/settings/host.ts new file mode 100644 index 00000000..e74665db --- /dev/null +++ b/packages/plugin/src/features/settings/host.ts @@ -0,0 +1,25 @@ +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, 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 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; + refreshSourceControlView(): void; +} diff --git a/packages/plugin/src/features/settings/index.ts b/packages/plugin/src/features/settings/index.ts index 7ef0e047..5664c19c 100644 --- a/packages/plugin/src/features/settings/index.ts +++ b/packages/plugin/src/features/settings/index.ts @@ -1,2 +1,3 @@ +export type { SettingsTabHost } from "./host"; export { SETUP_FIELDS } from "./sections/automation"; export { MdsyncSettingTab } from "./tab"; diff --git a/packages/plugin/src/features/settings/logs-view.ts b/packages/plugin/src/features/settings/logs-view.ts index 870ee7ea..653f352e 100644 --- a/packages/plugin/src/features/settings/logs-view.ts +++ b/packages/plugin/src/features/settings/logs-view.ts @@ -3,7 +3,6 @@ import { Setting, type SettingDefinitionPage, } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { ESyncLogLevel, ESyncLogOperation, @@ -12,6 +11,7 @@ import { 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/features/settings/overview.ts b/packages/plugin/src/features/settings/overview.ts index abb3f332..55f77732 100644 --- a/packages/plugin/src/features/settings/overview.ts +++ b/packages/plugin/src/features/settings/overview.ts @@ -3,20 +3,19 @@ import { type SettingDefinitionGroup, setIcon, } from "obsidian"; -import type { PluginHost } from "@/app/host"; 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 "@/core/settings"; -import { formatRelativeTime, pluralize } from "@/core/shared"; -import { describeStorageTarget, storageIdentity } from "@/features/storage"; -import { VAULT_SPACE } from "@/features/sync/remote/space"; + storageIdentity, +} from "@/features/storage"; +import { canSync, isGuest, VAULT_SPACE } from "@/features/sync"; +import type { SettingsTabHost } from "./host"; type Tone = "ok" | "muted" | "warning" | "error"; @@ -41,7 +40,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", @@ -101,7 +102,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)) { @@ -141,7 +142,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)) { @@ -176,7 +177,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 { @@ -211,7 +212,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/features/settings/sections/advanced.ts b/packages/plugin/src/features/settings/sections/advanced.ts index 5caf4b86..e98168df 100644 --- a/packages/plugin/src/features/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 "@/core/settings"; -import { defaultDeviceName } from "@/features/sync/identity/device"; +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/features/settings/sections/automation.ts b/packages/plugin/src/features/settings/sections/automation.ts index 1757301e..b2298baf 100644 --- a/packages/plugin/src/features/settings/sections/automation.ts +++ b/packages/plugin/src/features/settings/sections/automation.ts @@ -1,5 +1,4 @@ import type { Setting, SettingDefinitionGroup } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { AUTO_PUSH_SETTLE_MAX_SECONDS, AUTO_PUSH_SETTLE_MIN_SECONDS, @@ -14,20 +13,31 @@ import { import type { RelayStatus } from "@/core/hub"; import { RELAY_TEXT } from "@/core/hub"; import { - DEFAULT_SETTINGS, + DEFAULT_CORE_SETTINGS, + EFieldKind, type FieldContext, fieldRow, group, isRelayConfigured, type SettingsField, + type SettingsHost, SUB_SETTING_CLASS, } from "@/core/settings"; +import type { LiveSessions } from "@/features/live"; import type { People } from "@/features/presence"; -import { EFieldKind } from "@/features/storage"; -import { clampMaxSnapshots } from "@/features/sync/history/gc"; -import { VAULT_SPACE } from "@/features/sync/remote/space"; +import type { HubConnection } from "@/features/relay"; +import { clampMaxSnapshots, VAULT_SPACE } from "@/features/sync"; +import type { SettingsTabHost } from "../host"; -const AUTOSYNC_FIELD: SettingsField = { +/** The wizard shows these too, so they ask only what its host has. */ +type RealtimeFieldHost = SettingsHost & { + readonly realtime: { + readonly hub: HubConnection; + readonly live: LiveSessions; + }; +}; + +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.", @@ -36,7 +46,7 @@ const AUTOSYNC_FIELD: SettingsField = { rerender: true, }; -const REALTIME_FIELD: SettingsField = { +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.", @@ -46,7 +56,7 @@ const REALTIME_FIELD: SettingsField = { rerender: true, }; -const LIVE_EDITING_FIELD: SettingsField = { +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.", @@ -58,7 +68,7 @@ const LIVE_EDITING_FIELD: SettingsField = { rerender: true, }; -const LIVE_SPEED_FIELD: SettingsField = { +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.", @@ -74,13 +84,13 @@ const LIVE_SPEED_FIELD: SettingsField = { }; /** What the setup wizard offers once the vault syncs; real-time sync only with a relay to carry it. */ -export const SETUP_FIELDS: ReadonlyArray = [ +export const SETUP_FIELDS: ReadonlyArray> = [ AUTOSYNC_FIELD, { ...REALTIME_FIELD, when: isRelayConfigured }, LIVE_EDITING_FIELD, ]; -const AUTOMATION_FIELDS: ReadonlyArray = [ +const AUTOMATION_FIELDS: ReadonlyArray> = [ AUTOSYNC_FIELD, { kind: EFieldKind.Number, @@ -151,7 +161,7 @@ const AUTOMATION_FIELDS: ReadonlyArray = [ raw, BULK_DELETE_LIMIT_MIN, BULK_DELETE_LIMIT_MAX, - DEFAULT_SETTINGS.bulkDeleteLimit, + DEFAULT_CORE_SETTINGS.bulkDeleteLimit, ), set: (v) => ({ bulkDeleteLimit: v }), }, @@ -196,7 +206,9 @@ const AUTOMATION_FIELDS: ReadonlyArray = [ }, ]; -export function automationSection(ctx: FieldContext): SettingDefinitionGroup { +export function automationSection( + ctx: FieldContext, +): SettingDefinitionGroup { return group("Automation", [ ...AUTOMATION_FIELDS.map((field) => fieldRow(ctx, field)), { @@ -209,7 +221,7 @@ export function automationSection(ctx: FieldContext): SettingDefinitionGroup { function renderConnectedDevices( devicesSetting: Setting, - plugin: PluginHost, + plugin: SettingsTabHost, ): () => void { devicesSetting.settingEl.addClass(SUB_SETTING_CLASS); const { hub, people } = plugin.realtime; @@ -231,7 +243,7 @@ function renderConnectedDevices( }; } -function restartRelay(plugin: PluginHost): void { +function restartRelay(plugin: RealtimeFieldHost): void { plugin.realtime.hub.restart(); } diff --git a/packages/plugin/src/features/settings/sections/interface.ts b/packages/plugin/src/features/settings/sections/interface.ts index 1ffbbef2..9729d54c 100644 --- a/packages/plugin/src/features/settings/sections/interface.ts +++ b/packages/plugin/src/features/settings/sections/interface.ts @@ -1,14 +1,14 @@ import type { SettingDefinitionGroup } from "obsidian"; - import { + EFieldKind, type FieldContext, fieldRow, group, type SettingsField, } from "@/core/settings"; -import { EFieldKind } from "@/features/storage"; +import type { SettingsTabHost } from "../host"; -const INTERFACE_FIELDS: ReadonlyArray = [ +const INTERFACE_FIELDS: ReadonlyArray> = [ { kind: EFieldKind.Toggle, name: "Status bar indicator", @@ -63,7 +63,9 @@ const INTERFACE_FIELDS: ReadonlyArray = [ }, ]; -export function interfaceSection(ctx: FieldContext): SettingDefinitionGroup { +export function interfaceSection( + ctx: FieldContext, +): SettingDefinitionGroup { return group( undefined, INTERFACE_FIELDS.map((field) => fieldRow(ctx, field)), diff --git a/packages/plugin/src/features/settings/tab.ts b/packages/plugin/src/features/settings/tab.ts index 01691e65..c0717412 100644 --- a/packages/plugin/src/features/settings/tab.ts +++ b/packages/plugin/src/features/settings/tab.ts @@ -4,28 +4,29 @@ import { PluginSettingTab, type SettingDefinitionItem, } from "obsidian"; - -import type { PluginHost } from "@/app/host"; import { type FieldContext, settleTyping } from "@/core/settings"; -import { linksSection } from "@/features/links/ui/links-section"; -import { relaySection } from "@/features/relay/ui/relay-section"; -import { sharesSection } from "@/features/spaces/ui/shares-section"; +import { linksSection } from "@/features/links"; +import { relaySection } from "@/features/relay"; +import { sharesSection } from "@/features/spaces"; import { backendSection } from "@/features/storage"; -import { configurationScopeSection } from "@/features/sync/scope/configuration-scope-section"; -import { exclusionsSection } from "@/features/sync/scope/exclusions-section"; -import { maintenanceSection } from "@/features/sync/ui/maintenance-section"; +import { + configurationScopeSection, + encryptionSection, + exclusionsSection, + maintenanceSection, +} 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 { automationSection } from "./sections/automation"; import { interfaceSection } from "./sections/interface"; -import { securitySection } from "./sections/security"; export class MdsyncSettingTab extends PluginSettingTab { - private readonly plugin: Plugin & PluginHost; + private readonly plugin: Plugin & SettingsTabHost; - constructor(app: App, plugin: Plugin & PluginHost) { + constructor(app: App, plugin: Plugin & SettingsTabHost) { super(app, plugin); this.plugin = plugin; } @@ -36,7 +37,7 @@ export class MdsyncSettingTab extends PluginSettingTab { } getSettingDefinitions(): SettingDefinitionItem[] { - const ctx: FieldContext = { + const ctx: FieldContext = { plugin: this.plugin, rerender: () => this.update(), }; @@ -53,7 +54,7 @@ export class MdsyncSettingTab extends PluginSettingTab { desc: "Storage, encryption, relay and device transfer.", items: [ backendSection(ctx), - securitySection(ctx), + encryptionSection(ctx), relaySection(ctx), deviceTransferSection(ctx), advancedSection(ctx), diff --git a/packages/plugin/src/features/setup/README.md b/packages/plugin/src/features/setup/README.md index 3ee771eb..917ea18d 100644 --- a/packages/plugin/src/features/setup/README.md +++ b/packages/plugin/src/features/setup/README.md @@ -30,7 +30,6 @@ One modal stepper takes a fresh install to a syncing vault: storage (Cloudflare - `features/setup/stepper.ts`, `features/setup/choice-card.ts`, `features/setup/form.ts` (`actionRow`, `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`). -- Deep imports that bypass facades are baselined debt (`pnpm arch`): `features/source-control/view.ts` (**Open changes**), `features/spaces/ui/invites/invite-action.ts`, `features/settings/sections/automation.ts`, `features/relay/deploy/*`, `features/sync/remote/keyfile.ts`. Do not add more. ## Relay step 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 index 3fff17b8..ddf4fbca 100644 --- a/packages/plugin/src/features/setup/index.ts +++ b/packages/plugin/src/features/setup/index.ts @@ -1,2 +1,3 @@ +export type { SetupHost } from "./host"; export { ESetupStep } from "./step-state"; export { closeSetupWizard, openSetupWizard } from "./wizard"; diff --git a/packages/plugin/src/features/setup/step-state.ts b/packages/plugin/src/features/setup/step-state.ts index ad271e54..49a9456a 100644 --- a/packages/plugin/src/features/setup/step-state.ts +++ b/packages/plugin/src/features/setup/step-state.ts @@ -1,9 +1,7 @@ -import type { PluginHost } from "@/app/host"; -import { - canSync, - isRelayConfigured, - isStorageConfigured, -} from "@/core/settings"; +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", @@ -34,7 +32,7 @@ export const PATH_STEPS: Record = { }; /** 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 +48,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/features/setup/steps/import-step.ts b/packages/plugin/src/features/setup/steps/import-step.ts index ffadfbaf..8e3e6189 100644 --- a/packages/plugin/src/features/setup/steps/import-step.ts +++ b/packages/plugin/src/features/setup/steps/import-step.ts @@ -1,7 +1,6 @@ import { Setting } from "obsidian"; - -import { canSync } from "@/core/settings"; import { alertLine, callout, focusKey, onEnter } from "@/core/ui"; +import { canSync } from "@/features/sync"; import { actionRow } from "../form"; import { runAction } from "../run-action"; import type { StepView, Wizard } from "../wizard"; diff --git a/packages/plugin/src/features/setup/steps/passphrase-step.ts b/packages/plugin/src/features/setup/steps/passphrase-step.ts index a223cb29..4395a216 100644 --- a/packages/plugin/src/features/setup/steps/passphrase-step.ts +++ b/packages/plugin/src/features/setup/steps/passphrase-step.ts @@ -8,7 +8,7 @@ import { openStorageRefusedModal, r2StorageOf, } from "@/features/storage"; -import { PassphraseRotatedError } from "@/features/sync/remote/keyfile"; +import { PassphraseRotatedError } from "@/features/sync"; import { actionRow, busyLine } from "../form"; import { passphraseMeter } from "../passphrase-meter"; import { runAction } from "../run-action"; diff --git a/packages/plugin/src/features/setup/steps/ready-step.ts b/packages/plugin/src/features/setup/steps/ready-step.ts index 8ac393ae..4ce51a9f 100644 --- a/packages/plugin/src/features/setup/steps/ready-step.ts +++ b/packages/plugin/src/features/setup/steps/ready-step.ts @@ -1,19 +1,18 @@ import { Setting, setIcon } from "obsidian"; - -import { SOURCE_CONTROL_VIEW_TYPE } from "@/core/constants"; import { - activeStorage, - canSync, fieldRow, isRelayConfigured, - isStorageConfigured, renderDefinitions, } from "@/core/settings"; import { alertLine } from "@/core/ui"; -import { SETUP_FIELDS } from "@/features/settings/sections/automation"; -import { openSourceControlView } from "@/features/source-control/view"; -import { describeStorageTarget } from "@/features/storage"; +import { SETUP_FIELDS } from "@/features/settings"; +import { + activeStorage, + describeStorageTarget, + isStorageConfigured, +} from "@/features/storage"; import type { SyncStatusSnapshot } from "@/features/sync"; +import { canSync } from "@/features/sync"; import { showSettingsTransferExport } from "@/features/transfer"; import type { StepView, Wizard } from "../wizard"; @@ -106,7 +105,7 @@ export function createReadyStep(wizard: Wizard): StepView { row.addButton((b) => b.setButtonText("Open changes").onClick(() => { wizard.close(); - void openSourceControlView(plugin.app, SOURCE_CONTROL_VIEW_TYPE); + void plugin.openSourceControl(); }), ); }; diff --git a/packages/plugin/src/features/setup/steps/relay-deploy-view.ts b/packages/plugin/src/features/setup/steps/relay-deploy-view.ts index 3533cb5b..eb9abf85 100644 --- a/packages/plugin/src/features/setup/steps/relay-deploy-view.ts +++ b/packages/plugin/src/features/setup/steps/relay-deploy-view.ts @@ -3,27 +3,25 @@ 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, - planRelay, - runningRelayDeploy, -} from "@/features/relay/deploy/deploy-flow"; -import { - type AccountRelays, - accountRelays, freeRelayName, + planRelay, RELAY_NAME, type RelayTarget, relayNameError, relayUrlOf, -} from "@/features/relay/deploy/relay-account"; -import { ERelayDeployStep } from "@/features/relay/deploy/relay-deploy"; + runningRelayDeploy, + testRelay, +} from "@/features/relay"; import { cloudflareErrorMessage, cloudflareOf, forgetCloudflare, - testRelay, } from "@/features/storage"; import { actionRow, busyLine } from "../form"; import type { Wizard } from "../wizard"; diff --git a/packages/plugin/src/features/setup/steps/relay-step.ts b/packages/plugin/src/features/setup/steps/relay-step.ts index c00cd374..71b6afa9 100644 --- a/packages/plugin/src/features/setup/steps/relay-step.ts +++ b/packages/plugin/src/features/setup/steps/relay-step.ts @@ -2,9 +2,12 @@ import { Setting } from "obsidian"; import { isRelayConfigured } from "@/core/settings"; import { relayBase } from "@/core/shared"; import { alertLine, callout, focusKey, onEnter } from "@/core/ui"; -import { useRelay } from "@/features/relay/deploy/deploy-flow"; -import { relayBehind } from "@/features/relay/deploy/relay-account"; -import { type RelayTestResult, testRelay } from "@/features/storage"; +import { + type RelayTestResult, + relayBehind, + testRelay, + useRelay, +} from "@/features/relay"; import { choiceCard } from "../choice-card"; import { actionRow, busyLine } from "../form"; import { runAction } from "../run-action"; diff --git a/packages/plugin/src/features/setup/steps/start-step.ts b/packages/plugin/src/features/setup/steps/start-step.ts index 664be993..d366116c 100644 --- a/packages/plugin/src/features/setup/steps/start-step.ts +++ b/packages/plugin/src/features/setup/steps/start-step.ts @@ -1,6 +1,6 @@ import { setIcon } from "obsidian"; -import { openInvite } from "@/features/spaces/ui/invites/invite-action"; +import { openInvite } from "@/features/spaces"; import { choiceCard } from "../choice-card"; import { ESetupPath } from "../step-state"; diff --git a/packages/plugin/src/features/setup/steps/storage-step.ts b/packages/plugin/src/features/setup/steps/storage-step.ts index bbbde862..09a98c2f 100644 --- a/packages/plugin/src/features/setup/steps/storage-step.ts +++ b/packages/plugin/src/features/setup/steps/storage-step.ts @@ -1,16 +1,14 @@ import { isRefusedToken } from "@/core/cloudflare"; -import { - activeStorage, - isStorageConfigured, - renderDefinitions, -} from "@/core/settings"; +import { renderDefinitions } from "@/core/settings"; import { alertLine, callout } from "@/core/ui"; import { + activeStorage, backendSection, cloudflareErrorMessage, cloudflareOf, describeStorageTarget, forgetCloudflare, + isStorageConfigured, R2NotEnabledError, r2DashboardUrl, testConnection, diff --git a/packages/plugin/src/features/setup/wizard.ts b/packages/plugin/src/features/setup/wizard.ts index 2b182fa8..45b3959e 100644 --- a/packages/plugin/src/features/setup/wizard.ts +++ b/packages/plugin/src/features/setup/wizard.ts @@ -1,7 +1,6 @@ import { Modal, Setting } from "obsidian"; - -import type { PluginHost } from "@/app/host"; import { renderKeepingFocus } from "@/core/ui"; +import type { SetupHost } from "./host"; import { ESetupPath, ESetupStep, @@ -24,7 +23,7 @@ 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. */ @@ -92,7 +91,7 @@ class SetupWizardModal extends Modal implements Wizard { private bodyEl: HTMLElement | null = null; constructor( - readonly plugin: PluginHost, + readonly plugin: SetupHost, step: ESetupStep, private readonly onClosed: () => void, ) { @@ -233,7 +232,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 { diff --git a/packages/plugin/src/features/source-control/actions/actions.ts b/packages/plugin/src/features/source-control/actions/actions.ts index fda53f40..2bc4c85e 100644 --- a/packages/plugin/src/features/source-control/actions/actions.ts +++ b/packages/plugin/src/features/source-control/actions/actions.ts @@ -1,21 +1,20 @@ import { Menu, Platform } from "obsidian"; - -import type { PluginHost } from "@/app/host"; import { attempt, openInEditor, revealInFileExplorer, runWithNotice, } from "@/core/ui"; -import { EConflictStrategy } from "@/features/sync/controller"; -import { isIgnoreNote } from "@/features/sync/scope/ignore"; -import { EChangeType } from "@/features/sync/types"; -import { addIgnoreMenuItem } from "@/features/sync/ui/ignore-action"; import { + addIgnoreMenuItem, confirmAdoptNewVault, confirmBatchResolve, confirmRevert, -} from "@/features/sync/ui/modals"; + EChangeType, + EConflictStrategy, + isIgnoreNote, +} from "@/features/sync"; +import type { SourceControlHost } from "../host"; import { ESection } from "../types"; const BATCH_RESOLVE_CONFIRM_THRESHOLD = 5; @@ -33,13 +32,13 @@ function pathMenu(path: string): Menu { } 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; diff --git a/packages/plugin/src/features/source-control/changes/changes-section.ts b/packages/plugin/src/features/source-control/changes/changes-section.ts index 2f1fc99d..c4365e1c 100644 --- a/packages/plugin/src/features/source-control/changes/changes-section.ts +++ b/packages/plugin/src/features/source-control/changes/changes-section.ts @@ -1,6 +1,6 @@ import { Menu, setIcon } from "obsidian"; import { appendIconButton, makeActivatable } from "@/core/ui"; -import { EConflictStrategy } from "@/features/sync/controller"; +import { EConflictStrategy } from "@/features/sync"; import { SECTION_ACTIONS } from "../actions/section-actions"; import type { SelectionCommand, diff --git a/packages/plugin/src/features/source-control/changes/changes-tab.ts b/packages/plugin/src/features/source-control/changes/changes-tab.ts index 80f6bd8f..d6549202 100644 --- a/packages/plugin/src/features/source-control/changes/changes-tab.ts +++ b/packages/plugin/src/features/source-control/changes/changes-tab.ts @@ -1,15 +1,15 @@ import { Platform, SearchComponent } from "obsidian"; -import type { PluginHost } from "@/app/host"; -import { canSync } from "@/core/settings"; import { appendIconButton, appendLabeledButton, notifyError } from "@/core/ui"; -import { lastEditLabel, lastEditor } from "@/features/spaces/last-edit"; +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"; @@ -43,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/features/source-control/changes/excluded-files.ts b/packages/plugin/src/features/source-control/changes/excluded-files.ts index 682d87e7..73582bef 100644 --- a/packages/plugin/src/features/source-control/changes/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 "@/app/host"; import { formatBytes } from "@/core/shared"; -import type { SkippedFile } from "@/features/sync/types"; -import { stopIgnoring } from "@/features/sync/ui/ignore-action"; +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/features/source-control/changes/row-formatter.ts b/packages/plugin/src/features/source-control/changes/row-formatter.ts index 6046fd8e..413a0790 100644 --- a/packages/plugin/src/features/source-control/changes/row-formatter.ts +++ b/packages/plugin/src/features/source-control/changes/row-formatter.ts @@ -1,10 +1,10 @@ -import { movesByPath } from "@/features/sync/changes/moves"; -import { deviceLabel } from "@/features/sync/identity/device"; -import type { Conflict, FileChange, Move } from "@/features/sync/types"; +import type { Conflict, FileChange, Move } from "@/features/sync"; import { type ChangeAction, changeActionOf, -} from "@/features/sync/ui/change-action"; + deviceLabel, + movesByPath, +} from "@/features/sync"; import type { FileRow } from "../types"; export const STATUS_LETTERS: Record = { diff --git a/packages/plugin/src/features/source-control/history/history-tab.ts b/packages/plugin/src/features/source-control/history/history-tab.ts index 8c7e5901..cfbfcb3e 100644 --- a/packages/plugin/src/features/source-control/history/history-tab.ts +++ b/packages/plugin/src/features/source-control/history/history-tab.ts @@ -1,5 +1,4 @@ import { Menu, setIcon } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { pluralize } from "@/core/shared"; import { appendIconButton, @@ -9,8 +8,10 @@ import { notifyError, notifyInfo, } from "@/core/ui"; -import { confirmRestore } from "@/features/diff/restore-modal"; +import type { HistoryDiffTarget } from "@/features/diff"; +import { confirmRestore } from "@/features/diff"; import type { FileVersion } from "@/features/sync"; +import type { SourceControlHost } from "../host"; import { renderSize } from "../row-parts"; import { renderEmptyState, @@ -19,7 +20,6 @@ import { renderLoading, } from "../tab-states"; import { addSnapshotPinItems } from "../timeline/snapshot-menu"; -import type { HistoryDiffTarget } from "../view"; import { groupRows } from "./day-groups"; import { HistoryList } from "./history-list"; import { buildHistoryRows, type HistoryRow } from "./history-rows"; @@ -34,7 +34,7 @@ export class HistoryTab { private loadedPath: string | null = null; constructor( - private readonly plugin: PluginHost, + private readonly plugin: SourceControlHost, private readonly onRerender: () => void, private readonly openDiff: ( path: string, 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 index 8879ba9d..284b0afd 100644 --- a/packages/plugin/src/features/source-control/index.ts +++ b/packages/plugin/src/features/source-control/index.ts @@ -1,9 +1,12 @@ +export type { SourceControlHost } from "./host"; +export { SourceControlView } from "./view"; export { + addHistoryMenuItems, keepInRightSidebar, - openDiffView, openSourceControlChanges, openSourceControlDeleted, openSourceControlHistory, openSourceControlView, - SourceControlView, -} from "./view"; + refreshHistoryAfterPush, + refreshSourceControlViews, +} from "./workspace"; diff --git a/packages/plugin/src/features/source-control/setup-prompt.ts b/packages/plugin/src/features/source-control/setup-prompt.ts index 2022babb..40f0ba82 100644 --- a/packages/plugin/src/features/source-control/setup-prompt.ts +++ b/packages/plugin/src/features/source-control/setup-prompt.ts @@ -1,11 +1,11 @@ -import type { PluginHost } from "@/app/host"; -import { ESetupStep } from "@/features/setup/step-state"; +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", diff --git a/packages/plugin/src/features/source-control/summary-card.ts b/packages/plugin/src/features/source-control/summary-card.ts index 70cc506b..107010dd 100644 --- a/packages/plugin/src/features/source-control/summary-card.ts +++ b/packages/plugin/src/features/source-control/summary-card.ts @@ -1,17 +1,19 @@ import { ButtonComponent, setIcon } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { formatRelativeTime } from "@/core/shared"; import { actionButton, textButton } from "@/core/ui"; -import { askSpaceGone } from "@/features/spaces/ui/space-gone"; +import { askSpaceGone } from "@/features/spaces"; +import type { Manifest } from "@/features/sync"; import { + canPullAll, + canPushAll, + deviceLabel, + isVaultMismatch, type SyncStatusSnapshot, splitSpaceErrors, -} from "@/features/sync/controller"; -import { deviceLabel } from "@/features/sync/identity/device"; -import { canPullAll, canPushAll } from "@/features/sync/runtime/sync-gates"; -import type { Manifest } from "@/features/sync/types"; +} 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. @@ -40,7 +42,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" @@ -108,7 +110,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); @@ -234,7 +236,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()) @@ -327,12 +329,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 }); } diff --git a/packages/plugin/src/features/source-control/timeline/snapshot-menu.ts b/packages/plugin/src/features/source-control/timeline/snapshot-menu.ts index c862c2a9..592737a5 100644 --- a/packages/plugin/src/features/source-control/timeline/snapshot-menu.ts +++ b/packages/plugin/src/features/source-control/timeline/snapshot-menu.ts @@ -1,6 +1,6 @@ import type { Menu } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { notifyError, notifyInfo, openPromptModal } from "@/core/ui"; +import type { SourceControlHost } from "../host"; interface SnapshotPin { snapshotId: string; @@ -10,7 +10,7 @@ interface SnapshotPin { export function addSnapshotPinItems( menu: Menu, - plugin: PluginHost, + plugin: SourceControlHost, snapshot: SnapshotPin, onChanged: () => void, canPin = true, diff --git a/packages/plugin/src/features/source-control/timeline/timeline-actions.ts b/packages/plugin/src/features/source-control/timeline/timeline-actions.ts index 88eb3aef..b281b60f 100644 --- a/packages/plugin/src/features/source-control/timeline/timeline-actions.ts +++ b/packages/plugin/src/features/source-control/timeline/timeline-actions.ts @@ -1,7 +1,7 @@ import { Menu } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { notifyError, notifyInfo, openConfirmModal } from "@/core/ui"; -import { confirmRestore } from "@/features/diff/restore-modal"; +import { confirmRestore } from "@/features/diff"; +import type { SourceControlHost } from "../host"; import { addSnapshotPinItems } from "./snapshot-menu"; import { describeRestorePlan, @@ -12,7 +12,7 @@ import { export class TimelineActions { constructor( - private readonly plugin: PluginHost, + private readonly plugin: SourceControlHost, private readonly refresh: () => void, private readonly openFile: ( row: TimelineRow, diff --git a/packages/plugin/src/features/source-control/timeline/timeline-rows.ts b/packages/plugin/src/features/source-control/timeline/timeline-rows.ts index 6b9e954b..3ef37618 100644 --- a/packages/plugin/src/features/source-control/timeline/timeline-rows.ts +++ b/packages/plugin/src/features/source-control/timeline/timeline-rows.ts @@ -1,4 +1,5 @@ import { formatRelativeTime, formatTimestamp, pluralize } from "@/core/shared"; +import type { HistoryDiffTarget } from "@/features/diff"; import type { ChangeAction, HistoryVersionRef, @@ -9,7 +10,6 @@ import type { } from "@/features/sync"; import { deviceText } from "../changes/row-formatter"; import { timeInDay } from "../history/day-groups"; -import type { HistoryDiffTarget } from "../view"; export interface TimelineFileRow { path: string; diff --git a/packages/plugin/src/features/source-control/timeline/timeline-tab.ts b/packages/plugin/src/features/source-control/timeline/timeline-tab.ts index 7e76d493..0edbaf79 100644 --- a/packages/plugin/src/features/source-control/timeline/timeline-tab.ts +++ b/packages/plugin/src/features/source-control/timeline/timeline-tab.ts @@ -1,5 +1,4 @@ import { setIcon } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { formatBytes } from "@/core/shared"; import { appendIconButton, @@ -9,11 +8,13 @@ import { onLongPress, renderPath, } from "@/core/ui"; +import type { HistoryDiffTarget } from "@/features/diff"; import type { SnapshotListResult } from "@/features/sync"; import { STATUS_CLASSES, STATUS_LETTERS } from "../changes/row-formatter"; import { groupRows } from "../history/day-groups"; import { HistoryList } from "../history/history-list"; import { RowPager } from "../history/row-pager"; +import type { SourceControlHost } from "../host"; import { renderDelta } from "../row-parts"; import { renderEmptyState, @@ -21,7 +22,6 @@ import { renderLoadError, renderLoading, } from "../tab-states"; -import type { HistoryDiffTarget } from "../view"; import { TimelineActions } from "./timeline-actions"; import { buildTimelineRows, @@ -47,7 +47,7 @@ export class TimelineTab { private readonly actions: TimelineActions; constructor( - private readonly plugin: PluginHost, + private readonly plugin: SourceControlHost, private readonly onRerender: () => void, private readonly openDiff: ( path: string, diff --git a/packages/plugin/src/features/source-control/trash/trash-tab.ts b/packages/plugin/src/features/source-control/trash/trash-tab.ts index 531c71a1..89ee748d 100644 --- a/packages/plugin/src/features/source-control/trash/trash-tab.ts +++ b/packages/plugin/src/features/source-control/trash/trash-tab.ts @@ -1,5 +1,4 @@ import { Menu, Platform, setIcon, TFile, TFolder } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { pluralize } from "@/core/shared"; import { appendIconButton, @@ -11,10 +10,7 @@ import { openPromptModal, renderPath, } from "@/core/ui"; -import { - confirmBulkRestore, - confirmRestore, -} from "@/features/diff/restore-modal"; +import { confirmBulkRestore, confirmRestore } from "@/features/diff"; import type { DeletedFilesResult } from "@/features/sync"; import { SelectionBar, @@ -23,6 +19,7 @@ import { } from "../actions/selection-bar"; import { HistoryList } from "../history/history-list"; import { RowPager } from "../history/row-pager"; +import type { SourceControlHost } from "../host"; import { renderEmptyState, renderHistoryOff, @@ -48,7 +45,7 @@ export class TrashTab implements SelectionSource { private selectAll: HTMLInputElement | null = null; constructor( - private readonly plugin: PluginHost, + private readonly plugin: SourceControlHost, private readonly onRerender: () => void, private readonly openDiff: ( path: string, diff --git a/packages/plugin/src/features/source-control/view.ts b/packages/plugin/src/features/source-control/view.ts index d97ffd10..b31fe421 100644 --- a/packages/plugin/src/features/source-control/view.ts +++ b/packages/plugin/src/features/source-control/view.ts @@ -1,24 +1,17 @@ +import { ItemView, Platform, setIcon, type WorkspaceLeaf } from "obsidian"; import { - type App, - ItemView, - Platform, - setIcon, - type WorkspaceLeaf, -} from "obsidian"; -import type { PluginHost } from "@/app/host"; -import { - DIFF_VIEW_TYPE, RELATIVE_TIME_REFRESH_MS, SOURCE_CONTROL_VIEW_TYPE, } from "@/core/constants"; -import { canSync } from "@/core/settings"; import { redrawOnPhoneChange } from "@/core/ui"; -import type { HistoryChange } from "@/features/diff"; -import type { HistoryVersionRef, SyncStatusSnapshot } from "@/features/sync"; +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"; @@ -43,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; @@ -117,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({ @@ -406,38 +340,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/features/source-control/workspace.ts b/packages/plugin/src/features/source-control/workspace.ts new file mode 100644 index 00000000..c47aa3b7 --- /dev/null +++ b/packages/plugin/src/features/source-control/workspace.ts @@ -0,0 +1,107 @@ +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()); +} + +/** 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(); +} + +export function refreshSourceControlViews(app: App): void { + for (const view of openViews(app)) 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/broker/share-broker.ts b/packages/plugin/src/features/spaces/broker/share-broker.ts index 58f84b54..4664f2a3 100644 --- a/packages/plugin/src/features/spaces/broker/share-broker.ts +++ b/packages/plugin/src/features/spaces/broker/share-broker.ts @@ -4,9 +4,11 @@ * lives and issues the tokens. */ +import { ADMIN_HEADER } from "@mdsync/protocol"; import { requestUrl } from "obsidian"; -import { relayBase } from "@/core/shared"; +import type { RelayConfig } from "@/core/settings"; +import { relayBase, StorageHttpError } from "@/core/shared"; import type { S3StorageConfig } from "@/features/storage"; import { createS3Store, @@ -16,7 +18,6 @@ import { type S3RequestInput, ShareRefusedError, type StorageAdapter, - StorageHttpError, StorageRequestError, signingRegion, } from "@/features/storage"; @@ -33,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/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 index 93d58ecc..efaf4375 100644 --- a/packages/plugin/src/features/spaces/index.ts +++ b/packages/plugin/src/features/spaces/index.ts @@ -1,9 +1,14 @@ export { shareKey, shareStorage } from "./access"; -export { ADMIN_HEADER, type BrokerAdmin } from "./broker/share-broker"; +export { type BrokerAdmin, relayAdmin } from "./broker/share-broker"; +export type { SpacesHost } from "./host"; export { INVITE_ACTION, invitePassword } from "./invite"; -export { lastEditLabel, lastEditor } from "./last-edit"; export { pauseOf } from "./partition"; -export { isSpaceRecord, type SpaceRecord, shareIdentity } from "./record"; +export { + isSpaceRecord, + parseSpaceRecords, + type SpaceRecord, + shareIdentity, +} from "./record"; export { SpaceRecords } from "./records"; export { createMoveFollower, registerShareRenames } from "./share-moves"; export { createShareRegistration } from "./share-registration"; @@ -13,7 +18,9 @@ export { 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"; diff --git a/packages/plugin/src/features/spaces/owner.ts b/packages/plugin/src/features/spaces/owner.ts index 8c177014..a233ba34 100644 --- a/packages/plugin/src/features/spaces/owner.ts +++ b/packages/plugin/src/features/spaces/owner.ts @@ -1,9 +1,12 @@ import { sharePrefix } from "@mdsync/protocol"; 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 "@/features/storage"; @@ -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/features/spaces/partition.ts b/packages/plugin/src/features/spaces/partition.ts index 564c810f..4467a0e1 100644 --- a/packages/plugin/src/features/spaces/partition.ts +++ b/packages/plugin/src/features/spaces/partition.ts @@ -1,5 +1,5 @@ import { hasDotSegment } from "@/core/shared"; -import { isUnder, type Space, VAULT_SPACE } from "@/features/sync/remote/space"; +import { isUnder, type Space, VAULT_SPACE } from "@/features/sync"; import type { SpaceRecord } from "./record"; diff --git a/packages/plugin/src/features/spaces/record.ts b/packages/plugin/src/features/spaces/record.ts index e866c24f..77990d49 100644 --- a/packages/plugin/src/features/spaces/record.ts +++ b/packages/plugin/src/features/spaces/record.ts @@ -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/features/spaces/records.ts b/packages/plugin/src/features/spaces/records.ts index 3ac46a34..bfc1d462 100644 --- a/packages/plugin/src/features/spaces/records.ts +++ b/packages/plugin/src/features/spaces/records.ts @@ -1,6 +1,6 @@ import type { EncryptionKey } from "@/core/crypto"; import type { StorageAdapter } from "@/features/storage"; -import { isUnder, type Space, VAULT_SPACE } from "@/features/sync/remote/space"; +import { isUnder, type Space, VAULT_SPACE } from "@/features/sync"; import { mountError, type PauseKind, pauseOf, spacesOf } from "./partition"; import { diff --git a/packages/plugin/src/features/spaces/share-moves.ts b/packages/plugin/src/features/spaces/share-moves.ts index 2cef490c..0099bca8 100644 --- a/packages/plugin/src/features/spaces/share-moves.ts +++ b/packages/plugin/src/features/spaces/share-moves.ts @@ -1,9 +1,9 @@ import { type Plugin, TFolder, type Vault } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { reportWarning } from "@/core/shared"; import { notifyError, notifyInfo } from "@/core/ui"; import { removeEmptyDir } from "@/core/vault"; -import { isUnder } from "@/features/sync/remote/space"; +import { isUnder } from "@/features/sync"; +import type { SpacesHost } from "./host"; import { mountError, spacesOf } from "./partition"; import type { PendingMove, SpaceRecords } from "./records"; @@ -40,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); @@ -88,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/features/spaces/share-registration.ts b/packages/plugin/src/features/spaces/share-registration.ts index 165b010e..2ce68215 100644 --- a/packages/plugin/src/features/spaces/share-registration.ts +++ b/packages/plugin/src/features/spaces/share-registration.ts @@ -1,14 +1,10 @@ import type { LogService } from "@/core/logs"; import { ESyncLogOperation } from "@/core/logs"; -import { - isRelayConfigured, - type MdsyncSettings, - ownerStorage, -} from "@/core/settings"; +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 } from "./owner"; +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. */ diff --git a/packages/plugin/src/features/spaces/space-access.ts b/packages/plugin/src/features/spaces/space-access.ts index a45eea67..ce7cad57 100644 --- a/packages/plugin/src/features/spaces/space-access.ts +++ b/packages/plugin/src/features/spaces/space-access.ts @@ -1,10 +1,10 @@ import { OWNER } from "@mdsync/protocol"; import type { LiveKeys } from "@/core/crypto"; -import { isStorageConfigured, type MdsyncSettings } from "@/core/settings"; +import type { MdsyncSettings } from "@/core/settings"; import { reportWarning } from "@/core/shared"; -import type { SyncController } from "@/features/sync/controller"; -import type { PassphraseManager } from "@/features/sync/remote/passphrase-manager"; -import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; +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"; diff --git a/packages/plugin/src/features/spaces/ui/access-ended.ts b/packages/plugin/src/features/spaces/ui/access-ended.ts index 84607be0..c8690e20 100644 --- a/packages/plugin/src/features/spaces/ui/access-ended.ts +++ b/packages/plugin/src/features/spaces/ui/access-ended.ts @@ -1,8 +1,7 @@ import type { Plugin } from "obsidian"; - -import type { PluginHost } from "@/app/host"; 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/features/spaces/ui/invites/invite-action.ts b/packages/plugin/src/features/spaces/ui/invites/invite-action.ts index 94a36591..815884d2 100644 --- a/packages/plugin/src/features/spaces/ui/invites/invite-action.ts +++ b/packages/plugin/src/features/spaces/ui/invites/invite-action.ts @@ -1,16 +1,16 @@ import { TFile, TFolder } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { randomId } from "@/core/crypto"; -import { ownerStorage, relayAdmin } from "@/core/settings"; import { normalizePath, stripTrailingSlash } from "@/core/shared"; import { notifyInfo, openConfirmModal, runWithNotice } from "@/core/ui"; -import { scopedPaths } from "@/features/sync/ui/push-action"; +import { scopedPaths } from "@/features/sync"; import { issueShareToken, listParticipants, registerShareStorage, + relayAdmin, revokeParticipant, } from "../../broker/share-broker"; +import type { SpacesHost } from "../../host"; import { acceptInvite, type Invite, @@ -19,7 +19,7 @@ import { invitePassword, readInvite, } from "../../invite"; -import { brokerStorage } from "../../owner"; +import { brokerStorage, ownerStorage } from "../../owner"; import { mountError } from "../../partition"; import type { SpaceRecord } from "../../record"; import { AcceptInviteModal } from "./invite-modal"; @@ -31,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 { @@ -57,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", @@ -76,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, @@ -126,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 { @@ -162,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); @@ -174,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/features/spaces/last-edit.ts b/packages/plugin/src/features/spaces/ui/last-edit.ts similarity index 77% rename from packages/plugin/src/features/spaces/last-edit.ts rename to packages/plugin/src/features/spaces/ui/last-edit.ts index 56b116e2..ac8ac5c5 100644 --- a/packages/plugin/src/features/spaces/last-edit.ts +++ b/packages/plugin/src/features/spaces/ui/last-edit.ts @@ -1,10 +1,10 @@ -import type { PluginHost } from "@/app/host"; import { formatRelativeTime } from "@/core/shared"; -import { type Space, spaceOf, VAULT_SPACE } from "@/features/sync/remote/space"; -import { shareIdentity } from "./record"; +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/features/spaces/ui/read-only.ts b/packages/plugin/src/features/spaces/ui/read-only.ts index d3435088..19c17f52 100644 --- a/packages/plugin/src/features/spaces/ui/read-only.ts +++ b/packages/plugin/src/features/spaces/ui/read-only.ts @@ -1,19 +1,19 @@ import { EditorState, type Extension, Prec } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import { editorInfoField, type Plugin } from "obsidian"; -import type { PluginHost } from "@/app/host"; -import { LIVE_VIEWS } from "@/features/live/doc-types"; import { type ExcalidrawApi, type ExcalidrawView, isViewMode, + LIVE_VIEWS, setViewMode, -} from "@/features/live/drawing/excalidraw"; +} 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/features/spaces/ui/share-action.ts b/packages/plugin/src/features/spaces/ui/share-action.ts index 158a7a50..1fda3083 100644 --- a/packages/plugin/src/features/spaces/ui/share-action.ts +++ b/packages/plugin/src/features/spaces/ui/share-action.ts @@ -1,17 +1,17 @@ -import type { PluginHost } from "@/app/host"; import { RELAY_TEXT } from "@/core/hub"; -import { isRelayConfigured, ownerStorage, relayAdmin } from "@/core/settings"; +import { isRelayConfigured } from "@/core/settings"; import { relayBase } from "@/core/shared"; import { notifyError, notifyInfo, openConfirmModal } from "@/core/ui"; -import { carryVaultIgnores } from "@/features/sync/ui/ignore-action"; -import { pushScope } from "@/features/sync/ui/push-action"; +import { carryVaultIgnores, pushScope } from "@/features/sync"; import { endShare, leaveShare, type Participant, + relayAdmin, revokeParticipant, } from "../broker/share-broker"; -import { createShare, ownerNameOf } from "../owner"; +import type { SpacesHost } from "../host"; +import { createShare, ownerNameOf, ownerStorage } from "../owner"; import { mountError } from "../partition"; import type { SpaceRecord } from "../record"; @@ -21,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); @@ -53,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; @@ -66,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; @@ -113,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 { @@ -130,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/features/spaces/ui/shares-section.ts b/packages/plugin/src/features/spaces/ui/shares-section.ts index 3a6879eb..a64bbdfd 100644 --- a/packages/plugin/src/features/spaces/ui/shares-section.ts +++ b/packages/plugin/src/features/spaces/ui/shares-section.ts @@ -1,19 +1,22 @@ import { Setting, type SettingDefinitionGroup } from "obsidian"; import { + EFieldKind, type FieldContext, fieldRow, group, imperativePage, introRow, } from "@/core/settings"; -import { EFieldKind } from "@/features/storage"; +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; diff --git a/packages/plugin/src/features/spaces/ui/space-gone.ts b/packages/plugin/src/features/spaces/ui/space-gone.ts index fc5cbd78..97e2ebf1 100644 --- a/packages/plugin/src/features/spaces/ui/space-gone.ts +++ b/packages/plugin/src/features/spaces/ui/space-gone.ts @@ -1,6 +1,6 @@ -import type { PluginHost } from "@/app/host"; import { openChoiceModal, runWithNotice } from "@/core/ui"; import type { Space } from "@/features/sync"; +import type { SpacesHost } from "../host"; const RESTORE = { key: "restore", @@ -14,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; @@ -25,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/features/spaces/ui/window/people-list.ts b/packages/plugin/src/features/spaces/ui/window/people-list.ts index 8af4d7e6..320c896e 100644 --- a/packages/plugin/src/features/spaces/ui/window/people-list.ts +++ b/packages/plugin/src/features/spaces/ui/window/people-list.ts @@ -5,8 +5,8 @@ import { focusKey, showMenuAt, } from "@/core/ui"; -import { renderAvatar } from "@/features/presence/ui/avatars"; -import type { Person } from "@/features/presence/views"; +import type { Person } from "@/features/presence"; +import { renderAvatar } from "@/features/presence"; import type { Participant } from "../../broker/share-broker"; import type { ShareRow } from "./share-people"; diff --git a/packages/plugin/src/features/spaces/ui/window/share-modal.ts b/packages/plugin/src/features/spaces/ui/window/share-modal.ts index 46799bd7..53a6758d 100644 --- a/packages/plugin/src/features/spaces/ui/window/share-modal.ts +++ b/packages/plugin/src/features/spaces/ui/window/share-modal.ts @@ -1,7 +1,6 @@ import { ButtonComponent, Modal } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { isLinkState, RELAY_TEXT, relaySummary } from "@/core/hub"; -import { isRelayConfigured, relayAdmin } from "@/core/settings"; +import { isRelayConfigured } from "@/core/settings"; import { errorMessage } from "@/core/shared"; import { alertLine, @@ -16,12 +15,14 @@ import { serial, } from "@/core/ui"; import type { Person } from "@/features/presence"; -import { isUnder } from "@/features/sync/remote/space"; +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"; @@ -47,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/features/spaces/ui/window/share-window.ts b/packages/plugin/src/features/spaces/ui/window/share-window.ts index 18fd9975..516befe2 100644 --- a/packages/plugin/src/features/spaces/ui/window/share-window.ts +++ b/packages/plugin/src/features/spaces/ui/window/share-window.ts @@ -1,9 +1,8 @@ import type { Menu } from "obsidian"; - -import type { PluginHost } from "@/app/host"; -import { ownerStorage } from "@/core/settings"; import { notifyError } from "@/core/ui"; -import { isUnder } from "@/features/sync/remote/space"; +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"; @@ -12,7 +11,7 @@ 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 index 8e3b409f..ea6882da 100644 --- a/packages/plugin/src/features/status/index.ts +++ b/packages/plugin/src/features/status/index.ts @@ -1,3 +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 index 3b8078f9..bf6e8ea3 100644 --- a/packages/plugin/src/features/status/live-spaces.ts +++ b/packages/plugin/src/features/status/live-spaces.ts @@ -1,27 +1,27 @@ -import type { PluginHost } from "@/app/host"; import { isLinkState, type LinkState } from "@/core/hub"; 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; } -export function carried(plugin: PluginHost): CarriedSpace[] { +export function carried(plugin: StatusHost): 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[] { +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: PluginHost, id: string): string { +export function spaceName(plugin: StatusHost, id: string): string { if (id === VAULT_SPACE.id) return "Vault"; return plugin.spaces.get(id)?.name ?? id; } diff --git a/packages/plugin/src/features/status/relay-status.ts b/packages/plugin/src/features/status/relay-status.ts index fa181fd9..81840971 100644 --- a/packages/plugin/src/features/status/relay-status.ts +++ b/packages/plugin/src/features/status/relay-status.ts @@ -1,5 +1,4 @@ import type { Plugin } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { isConnected, type LinkState, @@ -9,11 +8,12 @@ import { } 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/features/status/status-bar.ts b/packages/plugin/src/features/status/status-bar.ts index ba476d3f..6a007f03 100644 --- a/packages/plugin/src/features/status/status-bar.ts +++ b/packages/plugin/src/features/status/status-bar.ts @@ -1,10 +1,13 @@ import { type Plugin, setIcon } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { RELATIVE_TIME_REFRESH_MS } from "@/core/constants"; -import { canSync } from "@/core/settings"; import { formatRelativeTime, OFFLINE_MESSAGE, pluralize } from "@/core/shared"; import { makeActivatable } from "@/core/ui"; -import { type SyncStatusSnapshot, splitSpaceErrors } from "@/features/sync"; +import { + canSync, + type SyncStatusSnapshot, + splitSpaceErrors, +} from "@/features/sync"; +import type { StatusHost } from "./host"; import { mountRelayStatus } from "./relay-status"; import { openStatusMenu, syncHeadline } from "./status-menu"; @@ -12,7 +15,7 @@ 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"); @@ -116,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/features/status/status-menu.ts b/packages/plugin/src/features/status/status-menu.ts index c48d7f5a..e3f4c00a 100644 --- a/packages/plugin/src/features/status/status-menu.ts +++ b/packages/plugin/src/features/status/status-menu.ts @@ -1,26 +1,26 @@ import { Menu } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { SOURCE_CONTROL_VIEW_TYPE } from "@/core/constants"; -import { canSync } from "@/core/settings"; import { formatRelativeTime, pluralize } from "@/core/shared"; import { showMenuAt } from "@/core/ui"; +import { openDiffView } from "@/features/diff"; import { - openDiffView, openSourceControlChanges, openSourceControlView, } 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) => @@ -44,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)) { @@ -110,7 +110,7 @@ function addSyncActions( } function summaryTitle( - plugin: PluginHost, + plugin: StatusHost, snapshot: SyncStatusSnapshot, ): DocumentFragment { const title = createFragment(); @@ -129,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"; @@ -153,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 index b26369f2..984f3357 100644 --- a/packages/plugin/src/features/status/where-menu.ts +++ b/packages/plugin/src/features/status/where-menu.ts @@ -1,5 +1,4 @@ import type { Menu } from "obsidian"; -import type { PluginHost } from "@/app/host"; import { isConnected, openPluginSettings, @@ -7,10 +6,12 @@ import { relayFixOf, UNREADABLE_TEXT, } from "@/core/hub"; -import { infoTitle, openNote, personTitle } from "@/core/ui"; +import { infoTitle, openNote } from "@/core/ui"; import { LINK_LIVE_STATE, STATE_ICONS } from "@/features/live"; +import { personTitle } from "@/features/presence"; import { lastEditLabel } from "@/features/spaces"; import { VAULT_SPACE } from "@/features/sync"; +import type { StatusHost } from "./host"; import { type CarriedSpace, carried, @@ -19,7 +20,7 @@ import { } 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 { +export function addRelaySections(menu: Menu, plugin: StatusHost): void { const spaces = carried(plugin); addStatuses(menu, plugin, spaces); addRelayFixes(menu, plugin, spaces); @@ -43,7 +44,7 @@ export function addRelaySections(menu: Menu, plugin: PluginHost): void { function addStatuses( menu: Menu, - plugin: PluginHost, + plugin: StatusHost, spaces: readonly CarriedSpace[], ): void { if (spaces.length === 0) { @@ -76,7 +77,7 @@ function addStatuses( function addRelayFixes( menu: Menu, - plugin: PluginHost, + plugin: StatusHost, spaces: readonly CarriedSpace[], ): void { const unreachable = spaces.filter( @@ -107,7 +108,7 @@ function addRelayFixes( } } -function addUnseen(menu: Menu, plugin: PluginHost): void { +function addUnseen(menu: Menu, plugin: StatusHost): void { const notes = [...plugin.unseen.all()].filter((path) => plugin.app.vault.getFileByPath(path), ); diff --git a/packages/plugin/src/features/storage/backends/google-drive-auth.ts b/packages/plugin/src/features/storage/backends/google-drive-auth.ts index 2621bd17..132eb17e 100644 --- a/packages/plugin/src/features/storage/backends/google-drive-auth.ts +++ b/packages/plugin/src/features/storage/backends/google-drive-auth.ts @@ -1,13 +1,10 @@ import { toHex } from "@mdsync/protocol"; import type { ObsidianProtocolData } from "obsidian"; import { randomBytes } from "@/core/crypto"; +import { EFieldKind } from "@/core/settings"; import { relayBase } from "@/core/shared"; import { EStorageBackend, type GoogleDriveStorageConfig } from "../config"; -import { - CONCURRENCY_FIELD, - EFieldKind, - type SettingsFieldSpec, -} from "../field-spec"; +import { CONCURRENCY_FIELD, type SettingsFieldSpec } from "../field-spec"; import type { StorageAuthOutcome } from "../types"; export function googleAuthUrl( diff --git a/packages/plugin/src/features/storage/backends/google-drive-request.ts b/packages/plugin/src/features/storage/backends/google-drive-request.ts index fc1ad8c8..91b639d9 100644 --- a/packages/plugin/src/features/storage/backends/google-drive-request.ts +++ b/packages/plugin/src/features/storage/backends/google-drive-request.ts @@ -1,8 +1,8 @@ import { type RequestUrlParam, requestUrl } from "obsidian"; +import { StorageHttpError } from "@/core/shared"; import { StorageRequestError } from "../types"; import { isRetryableStatus, - StorageHttpError, transferBytes, withDeadline, withRetry, diff --git a/packages/plugin/src/features/storage/backends/google-drive.ts b/packages/plugin/src/features/storage/backends/google-drive.ts index b4fe4aa3..c46c4f4f 100644 --- a/packages/plugin/src/features/storage/backends/google-drive.ts +++ b/packages/plugin/src/features/storage/backends/google-drive.ts @@ -1,4 +1,5 @@ import type { RequestUrlParam } from "obsidian"; +import { StorageHttpError } from "@/core/shared"; import type { GoogleDriveStorageConfig } from "../config"; import type { ConditionalRead, ListedObject, StorageAdapter } from "../types"; import { @@ -8,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 "./util"; const DRIVE_API = "https://www.googleapis.com/drive/v3/files"; const DRIVE_PAGE_SIZE = "1000"; diff --git a/packages/plugin/src/features/storage/backends/s3-store.ts b/packages/plugin/src/features/storage/backends/s3-store.ts index 04111aee..1730a8f7 100644 --- a/packages/plugin/src/features/storage/backends/s3-store.ts +++ b/packages/plugin/src/features/storage/backends/s3-store.ts @@ -1,4 +1,5 @@ import { requestUrl } from "obsidian"; +import { StorageHttpError } from "@/core/shared"; import { toArrayBuffer } from "@/core/utils"; import { type ConditionalRead, @@ -14,7 +15,6 @@ import { headerValue, isRetryableError, isRetryableStatus, - StorageHttpError, transferBytes, withDeadline, withRetry, diff --git a/packages/plugin/src/features/storage/backends/s3.ts b/packages/plugin/src/features/storage/backends/s3.ts index 4492e85d..5dcd95ae 100644 --- a/packages/plugin/src/features/storage/backends/s3.ts +++ b/packages/plugin/src/features/storage/backends/s3.ts @@ -1,11 +1,8 @@ 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, - EFieldKind, - type SettingsFieldSpec, -} from "../field-spec"; +import { CONCURRENCY_FIELD, type SettingsFieldSpec } from "../field-spec"; import type { StorageAdapter } from "../types"; import { createS3Signer } from "./s3-signer"; diff --git a/packages/plugin/src/features/storage/backends/util.ts b/packages/plugin/src/features/storage/backends/util.ts index 8f2a3cd4..5ff0a8bf 100644 --- a/packages/plugin/src/features/storage/backends/util.ts +++ b/packages/plugin/src/features/storage/backends/util.ts @@ -1,4 +1,8 @@ -import { isNetworkError } from "@/core/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/features/storage/backends/webdav.ts b/packages/plugin/src/features/storage/backends/webdav.ts index 69a16ce3..70952e29 100644 --- a/packages/plugin/src/features/storage/backends/webdav.ts +++ b/packages/plugin/src/features/storage/backends/webdav.ts @@ -1,21 +1,16 @@ import { type RequestUrlParam, requestUrl } from "obsidian"; - import { DEFAULT_CONCURRENCY } from "@/core/constants"; -import { normalizeKeyPrefix } from "@/core/shared"; +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, - EFieldKind, - type SettingsFieldSpec, -} from "../field-spec"; +import { CONCURRENCY_FIELD, type SettingsFieldSpec } from "../field-spec"; import type { ConditionalRead, ListedObject, StorageAdapter } from "../types"; import { assertOk, dateOf, headerValue, isRetryableStatus, - StorageHttpError, transferBytes, withDeadline, withRetry, diff --git a/packages/plugin/src/features/storage/cloudflare/cloudflare-login.ts b/packages/plugin/src/features/storage/cloudflare/cloudflare-login.ts index 273c2bf0..15476583 100644 --- a/packages/plugin/src/features/storage/cloudflare/cloudflare-login.ts +++ b/packages/plugin/src/features/storage/cloudflare/cloudflare-login.ts @@ -1,4 +1,3 @@ -import type { PluginHost } from "@/app/host"; import { type CloudflareAccount, type CloudflareApi, @@ -10,6 +9,7 @@ import { } 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/features/storage/cloudflare/r2-select.ts b/packages/plugin/src/features/storage/cloudflare/r2-select.ts index 7ef8655c..ce660988 100644 --- a/packages/plugin/src/features/storage/cloudflare/r2-select.ts +++ b/packages/plugin/src/features/storage/cloudflare/r2-select.ts @@ -1,13 +1,13 @@ -import type { PluginHost } from "@/app/host"; import { cloudflareApi, obsidianHttp, verifyToken } from "@/core/cloudflare"; -import { STORAGE_CHANGED_REASON } from "@/core/constants"; +import { REMOTE_MANIFEST_KEY, STORAGE_CHANGED_REASON } from "@/core/constants"; import { sha256Hex } from "@/core/crypto"; -import { activeStorage, type MdsyncSettings } from "@/core/settings"; -import { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; +import type { MdsyncSettings } from "@/core/settings"; import { defaultS3Config } from "../backends/s3"; import { isRefusedCredentials } from "../backends/util"; 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"; @@ -16,7 +16,7 @@ const BUCKET = "mdsync-vaults"; 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; @@ -54,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/features/storage/field-spec.ts b/packages/plugin/src/features/storage/field-spec.ts index 1afb03fb..b8c077de 100644 --- a/packages/plugin/src/features/storage/field-spec.ts +++ b/packages/plugin/src/features/storage/field-spec.ts @@ -1,14 +1,5 @@ import { DEFAULT_CONCURRENCY } from "@/core/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 { 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 index 31f0af0a..062b93ce 100644 --- a/packages/plugin/src/features/storage/index.ts +++ b/packages/plugin/src/features/storage/index.ts @@ -6,11 +6,7 @@ export { signingRegion, } from "./backends/s3-signer"; export { createS3Store } from "./backends/s3-store"; -export { - errorCode, - isRefusedCredentials, - StorageHttpError, -} from "./backends/util"; +export { errorCode, isRefusedCredentials } from "./backends/util"; export { accountsOf, type CloudflareLogin, @@ -26,7 +22,8 @@ export { type S3StorageConfig, type StorageAdapterConfig, } from "./config"; -export { CONCURRENCY_FIELD, EFieldKind } from "./field-spec"; +export { CONCURRENCY_FIELD } from "./field-spec"; +export type { StorageHost } from "./host"; export { type RecordKind, readRecords, @@ -39,13 +36,16 @@ export { createStorageAdapter, describeStorageTarget, getDescriptor, - handleStorageProtocol, isAdapterConfigured, isKnownBackend, storageDefaults, storageIdentity, } from "./registry"; -export { createStorageRefused } from "./storage-refused"; +export { + activeStorage, + isStorageConfigured, + parseStorageSettings, +} from "./settings"; export { type ConditionalRead, type ObjectStorage, @@ -53,11 +53,7 @@ export { type StorageAdapter, StorageRequestError, } from "./types"; +export { authorizeStorage } from "./ui/authorize"; export { backendSection } from "./ui/backend-section"; -export { - type ConnectionTestResult, - type RelayTestResult, - testConnection, - testRelay, -} from "./ui/connection-test"; +export { testConnection } from "./ui/connection-test"; export { openStorageRefusedModal } from "./ui/storage-refused-modal"; 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/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/features/storage/ui/backend-section.ts b/packages/plugin/src/features/storage/ui/backend-section.ts index 37f728ab..1d8e2997 100644 --- a/packages/plugin/src/features/storage/ui/backend-section.ts +++ b/packages/plugin/src/features/storage/ui/backend-section.ts @@ -1,13 +1,15 @@ import type { SettingDefinitionGroup } from "obsidian"; - 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( diff --git a/packages/plugin/src/features/storage/ui/connection-test.ts b/packages/plugin/src/features/storage/ui/connection-test.ts index e59bf288..281e37a7 100644 --- a/packages/plugin/src/features/storage/ui/connection-test.ts +++ b/packages/plugin/src/features/storage/ui/connection-test.ts @@ -1,41 +1,21 @@ -import { requestUrl } from "obsidian"; - -import type { PluginHost } from "@/app/host"; -import { - activeStorage, - isRelayConfigured, - type RelayConfig, -} from "@/core/settings"; -import { - errorMessage, - isCleartextRemote, - relayBase, - reportWarning, -} from "@/core/shared"; -import { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; +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"; - -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; -} +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: PluginHost, -): Promise { + plugin: StorageHost, +): Promise { const config = activeStorage(plugin.settings); if (!isAdapterConfigured(config)) { return { ok: false, message: "This backend is not fully configured yet." }; @@ -62,53 +42,3 @@ export async function testConnection( }; } } - -/** 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/features/storage/ui/storage-fields.ts b/packages/plugin/src/features/storage/ui/storage-fields.ts index 77ebf027..3e9ac2bd 100644 --- a/packages/plugin/src/features/storage/ui/storage-fields.ts +++ b/packages/plugin/src/features/storage/ui/storage-fields.ts @@ -1,15 +1,14 @@ import type { Setting } from "obsidian"; - -import type { PluginHost } from "@/app/host"; -import { onSettled, type SettingsRow } from "@/core/settings"; +import { EFieldKind, onSettled, type SettingsRow } from "@/core/settings"; import { notifyError, notifyInfo } from "@/core/ui"; import { googleLoginUrl } from "../backends/google-drive-auth"; import { EStorageBackend, type GoogleDriveStorageConfig } from "../config"; -import { EFieldKind, type SettingsFieldSpec } from "../field-spec"; +import type { SettingsFieldSpec } from "../field-spec"; +import type { StorageHost } from "../host"; import { getDescriptor } from "../registry"; export function storageRows( - plugin: PluginHost, + plugin: StorageHost, kind: EStorageBackend, ): SettingsRow[] { const rows: SettingsRow[] = getDescriptor(kind).fields.map((field) => ({ @@ -27,7 +26,7 @@ export function storageRows( } function storageOf( - plugin: PluginHost, + plugin: StorageHost, kind: EStorageBackend, ): Record { const config = @@ -37,7 +36,7 @@ function storageOf( function renderStorageField( setting: Setting, - plugin: PluginHost, + plugin: StorageHost, kind: EStorageBackend, field: SettingsFieldSpec, ): void { @@ -93,7 +92,7 @@ function renderStorageField( function renderGoogleDriveAuth( setting: Setting, - plugin: PluginHost, + plugin: StorageHost, kind: EStorageBackend, ): void { // Read on click too: editing a field replaces the config object. @@ -126,7 +125,7 @@ function renderGoogleDriveAuth( } function updateStorage( - plugin: PluginHost, + plugin: StorageHost, kind: EStorageBackend, patch: Record, save: () => void = () => saveSettings(plugin), @@ -139,7 +138,7 @@ function updateStorage( save(); } -function saveSettings(plugin: PluginHost): void { +function saveSettings(plugin: StorageHost): void { void plugin .saveSettings() .catch((err: unknown) => notifyError("Could not save settings", err)); diff --git a/packages/plugin/src/features/storage/ui/storage-refused-modal.ts b/packages/plugin/src/features/storage/ui/storage-refused-modal.ts index 9a20dd25..3abfeb83 100644 --- a/packages/plugin/src/features/storage/ui/storage-refused-modal.ts +++ b/packages/plugin/src/features/storage/ui/storage-refused-modal.ts @@ -1,8 +1,5 @@ import { ButtonComponent, Modal, Setting } from "obsidian"; - -import type { PluginHost } from "@/app/host"; import { openPluginSettings } from "@/core/hub"; -import { activeStorage } from "@/core/settings"; import { alertLine, modalFooter, @@ -12,13 +9,15 @@ import { } 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/apply/auto-merge.ts b/packages/plugin/src/features/sync/apply/auto-merge.ts index a43fa31b..f8e4fd92 100644 --- a/packages/plugin/src/features/sync/apply/auto-merge.ts +++ b/packages/plugin/src/features/sync/apply/auto-merge.ts @@ -1,12 +1,13 @@ import { DEFAULT_CONCURRENCY } from "@/core/constants"; import { ESyncLogOperation } from "@/core/logs"; -import { asError, sortedByPath } from "@/core/shared"; +import { asError } from "@/core/shared"; import { runWithConcurrency } from "@/core/utils"; import { hasKnownBinaryExtension, textToBytes, writeLocalFile, } 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"; diff --git a/packages/plugin/src/features/sync/apply/pull-moves.ts b/packages/plugin/src/features/sync/apply/pull-moves.ts index 2f1631d3..c7390622 100644 --- a/packages/plugin/src/features/sync/apply/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 "@/core/shared"; +import { reportWarning } from "@/core/shared"; import { diskRefuses, ensureDir, @@ -14,6 +14,7 @@ import { unchangedSince, } from "@/core/vault"; +import { entryAt } from "../changes/records"; import type { CompareResult, EngineDependencies } from "../engine"; import { coldSince, writeIncoming } from "../live-notes"; import { isUnder } from "../remote/space"; diff --git a/packages/plugin/src/features/sync/apply/pull.ts b/packages/plugin/src/features/sync/apply/pull.ts index f879e035..927372be 100644 --- a/packages/plugin/src/features/sync/apply/pull.ts +++ b/packages/plugin/src/features/sync/apply/pull.ts @@ -1,9 +1,11 @@ /** The pull: moves, downloads and deletions land, then the baseline follows what did. */ import { DEFAULT_CONCURRENCY } from "@/core/constants"; -import { asError, entryAt } from "@/core/shared"; -import { runWithConcurrency, runWithFileConcurrency } from "@/core/utils"; +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 type { CompareResult, EngineDependencies } from "../engine"; import { coldSince, settleLive, writeIncoming } from "../live-notes"; import { baseStep } from "../recovery/cut-short"; diff --git a/packages/plugin/src/features/sync/automation/scheduler.ts b/packages/plugin/src/features/sync/automation/scheduler.ts index 762cc241..16c942d2 100644 --- a/packages/plugin/src/features/sync/automation/scheduler.ts +++ b/packages/plugin/src/features/sync/automation/scheduler.ts @@ -1,8 +1,8 @@ import type { Plugin, TAbstractFile } from "obsidian"; - -import { canSync, type MdsyncSettings } from "@/core/settings"; +import type { MdsyncSettings } from "@/core/settings"; import type { SyncController, SyncStatusSnapshot } from "../controller"; import { type Space, spaceOf, VAULT_SPACE } from "../remote/space"; +import { canSync } from "../settings"; const AUTO_PULL_STARTUP_DELAY_MS = 3_000; diff --git a/packages/plugin/src/core/utils/file-concurrency.ts b/packages/plugin/src/features/sync/changes/file-concurrency.ts similarity index 94% rename from packages/plugin/src/core/utils/file-concurrency.ts rename to packages/plugin/src/features/sync/changes/file-concurrency.ts index 1ba4712f..948116ed 100644 --- a/packages/plugin/src/core/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/core/shared/records.ts b/packages/plugin/src/features/sync/changes/records.ts similarity index 100% rename from packages/plugin/src/core/shared/records.ts rename to packages/plugin/src/features/sync/changes/records.ts diff --git a/packages/plugin/src/features/sync/constants.ts b/packages/plugin/src/features/sync/constants.ts index 043c57b9..3b907d67 100644 --- a/packages/plugin/src/features/sync/constants.ts +++ b/packages/plugin/src/features/sync/constants.ts @@ -1,7 +1,5 @@ /** Remote object layout and engine-wide limits. */ -export const REMOTE_MANIFEST_KEY = "manifest.json.enc"; - export const REMOTE_OBJECTS_PREFIX = "objects/"; /** Single change log: snapshot metadata plus one parent-relative delta per snapshot. */ diff --git a/packages/plugin/src/features/sync/controller.ts b/packages/plugin/src/features/sync/controller.ts index d7a1de05..f48515a4 100644 --- a/packages/plugin/src/features/sync/controller.ts +++ b/packages/plugin/src/features/sync/controller.ts @@ -1,4 +1,3 @@ -import type { LocalOpener } from "@/app/session-factory"; import { ESyncLogOperation } from "@/core/logs"; import type { SettingsSyncCategories } from "@/core/settings"; import { @@ -57,6 +56,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 diff --git a/packages/plugin/src/features/sync/engine.ts b/packages/plugin/src/features/sync/engine.ts index df43fb08..b6305215 100644 --- a/packages/plugin/src/features/sync/engine.ts +++ b/packages/plugin/src/features/sync/engine.ts @@ -2,18 +2,20 @@ import type { DataAdapter } from "obsidian"; import { DEFAULT_CONCURRENCY } from "@/core/constants"; import { type EncryptionKey, encryptBytes, sha256Hex } from "@/core/crypto"; import { sceneOfBytes } from "@/core/drawing"; -import { entryAt, reportWarning, sortedByPath } from "@/core/shared"; -import { runWithFileConcurrency } from "@/core/utils"; +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 { 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 } from "./constants"; 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"; @@ -374,8 +376,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/changes.ts b/packages/plugin/src/features/sync/history/changes.ts index 4f176eca..9839e731 100644 --- a/packages/plugin/src/features/sync/history/changes.ts +++ b/packages/plugin/src/features/sync/history/changes.ts @@ -1,4 +1,4 @@ -import { entryAt } from "@/core/shared"; +import { entryAt } from "../changes/records"; import type { Manifest, ManifestEntry } from "../types"; import type { SnapshotChanges, SnapshotEntry } from "./types"; diff --git a/packages/plugin/src/features/sync/history/query.ts b/packages/plugin/src/features/sync/history/query.ts index 86ed4d5c..24651fe4 100644 --- a/packages/plugin/src/features/sync/history/query.ts +++ b/packages/plugin/src/features/sync/history/query.ts @@ -1,8 +1,8 @@ import type { EncryptionKey } from "@/core/crypto"; -import { entryAt } from "@/core/shared"; import { runWithConcurrency } from "@/core/utils"; 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 { contiguousLength, undoChangesForPath } from "./changes"; diff --git a/packages/plugin/src/features/sync/history/restore-vault.ts b/packages/plugin/src/features/sync/history/restore-vault.ts index f39c82ac..9beb70c3 100644 --- a/packages/plugin/src/features/sync/history/restore-vault.ts +++ b/packages/plugin/src/features/sync/history/restore-vault.ts @@ -1,4 +1,4 @@ -import { entryAt } from "@/core/shared"; +import { entryAt } from "../changes/records"; import type { LocalSnapshot, Manifest, ManifestEntry } from "../types"; export interface VaultRestoreWrite { diff --git a/packages/plugin/src/features/sync/host.ts b/packages/plugin/src/features/sync/host.ts new file mode 100644 index 00000000..cd4ff9a6 --- /dev/null +++ b/packages/plugin/src/features/sync/host.ts @@ -0,0 +1,19 @@ +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; +} diff --git a/packages/plugin/src/features/sync/hunks/merge-model.ts b/packages/plugin/src/features/sync/hunks/merge-model.ts index 01f4e87e..123f838f 100644 --- a/packages/plugin/src/features/sync/hunks/merge-model.ts +++ b/packages/plugin/src/features/sync/hunks/merge-model.ts @@ -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/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 index 8df958a1..3a409912 100644 --- a/packages/plugin/src/features/sync/index.ts +++ b/packages/plugin/src/features/sync/index.ts @@ -5,9 +5,12 @@ export { textToBytes, } from "./changes/content"; export { movesByPath } from "./changes/moves"; -export { HUNK_TEXT_MAX_BYTES, REMOTE_MANIFEST_KEY } from "./constants"; +export { HUNK_TEXT_MAX_BYTES } from "./constants"; export { EConflictStrategy, + type LocalOpener, + type LocalSession, + type SessionFiles, SyncController, type SyncOperationResult, type SyncStatusSnapshot, @@ -24,6 +27,7 @@ export type { SnapshotListResult, SnapshotSummary, } from "./history/types"; +export type { SyncHost } from "./host"; export { computeHunks, DIFF_BUDGET, @@ -34,24 +38,17 @@ export { type SyncHunk, } from "./hunks/hunks"; export { - applyPlan, buildMergeSession, countUnresolved, - type EditPlan, type EMergeSide, type ESideStatus, isResolved, MERGE_SIDES, type MergeChange, - patchTaken, - revertPlan, + type SideStatus, type Span, - type StatusPatch, sameLines, - sameStatus, - snapToLines, type Taken, - type TakenPatch, threeWayRegions, toLines, } from "./hunks/merge-model"; @@ -63,6 +60,7 @@ export { } 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, @@ -100,6 +98,7 @@ export { } from "./scope/ignore-state"; export { createScopePolicy } from "./scope/scope"; export { projectSession } from "./session-state"; +export { canSync, isGuest } from "./settings"; export { type Conflict, type DiffResult, @@ -113,6 +112,7 @@ export { type SkippedFile, } from "./types"; export { type ChangeAction, changeActionOf } from "./ui/change-action"; +export { encryptionSection } from "./ui/encryption-section"; export { addIgnoreMenuItem, carryVaultIgnores, diff --git a/packages/plugin/src/features/sync/live-notes.ts b/packages/plugin/src/features/sync/live-notes.ts index 95990473..86c525b2 100644 --- a/packages/plugin/src/features/sync/live-notes.ts +++ b/packages/plugin/src/features/sync/live-notes.ts @@ -3,8 +3,6 @@ * room snapshot; a note with an open room is never written. */ -import { entryAt } from "@/core/shared"; - import { bytesToText, loadBaselineText, @@ -14,6 +12,7 @@ import { type WriteOptions, writeFetched, } from "./changes/content"; +import { entryAt } from "./changes/records"; import type { CompareResult, EngineDependencies } from "./engine"; import type { LiveMark, ManifestEntry } from "./types"; diff --git a/packages/plugin/src/features/sync/operations/pull.ts b/packages/plugin/src/features/sync/operations/pull.ts index c3e0980c..3d6acfb1 100644 --- a/packages/plugin/src/features/sync/operations/pull.ts +++ b/packages/plugin/src/features/sync/operations/pull.ts @@ -1,6 +1,7 @@ import { ESyncLogOperation } from "@/core/logs"; -import { entryAt, formatBytes, sumBytes } from "@/core/shared"; +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"; diff --git a/packages/plugin/src/features/sync/operations/resolve.ts b/packages/plugin/src/features/sync/operations/resolve.ts index 4d63b337..7ae7ae6b 100644 --- a/packages/plugin/src/features/sync/operations/resolve.ts +++ b/packages/plugin/src/features/sync/operations/resolve.ts @@ -1,8 +1,6 @@ import { DEFAULT_CONCURRENCY } from "@/core/constants"; import { sceneOfBytes } from "@/core/drawing"; import { ESyncLogOperation } from "@/core/logs"; -import { entryAt } from "@/core/shared"; -import { runWithFileConcurrency } from "@/core/utils"; import { trashPath, unchangedSince } from "@/core/vault"; import { freeConflictCopyPath } from "../apply/conflict-copy"; import { @@ -12,6 +10,8 @@ import { withLocalMtime, writeLocalFile, } from "../changes/content"; +import { runWithFileConcurrency } from "../changes/file-concurrency"; +import { entryAt } from "../changes/records"; import { LOG_PATH_LIMIT } from "../constants"; import { type CompareResult, diff --git a/packages/plugin/src/features/sync/operations/revert.ts b/packages/plugin/src/features/sync/operations/revert.ts index 5267a164..5e056838 100644 --- a/packages/plugin/src/features/sync/operations/revert.ts +++ b/packages/plugin/src/features/sync/operations/revert.ts @@ -1,8 +1,9 @@ import { DEFAULT_CONCURRENCY } from "@/core/constants"; import { ESyncLogOperation } from "@/core/logs"; -import { runWithConcurrency, runWithFileConcurrency } from "@/core/utils"; +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"; diff --git a/packages/plugin/src/features/sync/recovery/cut-short.ts b/packages/plugin/src/features/sync/recovery/cut-short.ts index d4267d4a..081ca4f9 100644 --- a/packages/plugin/src/features/sync/recovery/cut-short.ts +++ b/packages/plugin/src/features/sync/recovery/cut-short.ts @@ -6,9 +6,10 @@ import type { DataAdapter } from "obsidian"; import { sha256Hex } from "@/core/crypto"; import { sceneOfBytes } from "@/core/drawing"; -import { entryAt, reportWarning } from "@/core/shared"; +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"; diff --git a/packages/plugin/src/features/sync/remote/baseline.ts b/packages/plugin/src/features/sync/remote/baseline.ts index b2e5d636..5f79dc38 100644 --- a/packages/plugin/src/features/sync/remote/baseline.ts +++ b/packages/plugin/src/features/sync/remote/baseline.ts @@ -1,7 +1,7 @@ import { randomId } from "@/core/crypto"; -import { entryAt, sortedByPath } from "@/core/shared"; import { diskRefuses } from "@/core/vault"; import { isUnderUnreadableDir } from "../changes/diff"; +import { entryAt, sortedByPath } from "../changes/records"; import type { CompareResult } from "../engine"; import type { ScopePolicy } from "../scope/scope"; import type { diff --git a/packages/plugin/src/features/sync/remote/foreign.ts b/packages/plugin/src/features/sync/remote/foreign.ts index f7517b0c..4e620c7b 100644 --- a/packages/plugin/src/features/sync/remote/foreign.ts +++ b/packages/plugin/src/features/sync/remote/foreign.ts @@ -1,4 +1,4 @@ -import { entryAt } from "@/core/shared"; +import { entryAt } from "../changes/records"; import type { ScopePolicy } from "../scope/scope"; import type { Manifest, ManifestEntry } from "../types"; diff --git a/packages/plugin/src/features/sync/remote/keyfile.ts b/packages/plugin/src/features/sync/remote/keyfile.ts index 9e65a4fd..069e26e9 100644 --- a/packages/plugin/src/features/sync/remote/keyfile.ts +++ b/packages/plugin/src/features/sync/remote/keyfile.ts @@ -13,7 +13,7 @@ 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 "../session"; +import { loadOrCreateSalt } from "./salt"; const KEYFILE_VERSION = 1; diff --git a/packages/plugin/src/features/sync/remote/manifest.ts b/packages/plugin/src/features/sync/remote/manifest.ts index 4272f28f..824f455a 100644 --- a/packages/plugin/src/features/sync/remote/manifest.ts +++ b/packages/plugin/src/features/sync/remote/manifest.ts @@ -1,3 +1,4 @@ +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; import { decryptJson, type EncryptionKey, @@ -5,11 +6,7 @@ import { randomId, } from "@/core/crypto"; import type { ConditionalRead, ObjectStorage } from "@/features/storage"; -import { - MANIFEST_VERSION, - REMOTE_MANIFEST_KEY, - REMOTE_OBJECTS_PREFIX, -} from "../constants"; +import { MANIFEST_VERSION, REMOTE_OBJECTS_PREFIX } from "../constants"; import { defaultDeviceName } from "../identity/device"; import type { LocalSnapshot, Manifest } from "../types"; import { manifestToSpace, manifestToVault } from "./space-paths"; diff --git a/packages/plugin/src/features/sync/remote/passphrase-manager.ts b/packages/plugin/src/features/sync/remote/passphrase-manager.ts index 56d95a6c..24a7fed5 100644 --- a/packages/plugin/src/features/sync/remote/passphrase-manager.ts +++ b/packages/plugin/src/features/sync/remote/passphrase-manager.ts @@ -5,18 +5,27 @@ import { loadCachedPassphrase, saveCachedPassphrase, } from "@/core/crypto"; -import { - activeStorage, - isStorageConfigured, - type MdsyncSettings, -} from "@/core/settings"; +import type { MdsyncSettings } from "@/core/settings"; import { reportWarning } from "@/core/shared"; import { + activeStorage, createStorageAdapter, + isStorageConfigured, type ObjectStorage, storageIdentity, } from "@/features/storage"; -import { readKeyfile, resolveContentKey, rotatePassphrase } from "./keyfile"; +import { + PassphraseRotatedError, + readKeyfile, + resolveContentKey, + rotatePassphrase, +} 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; @@ -75,6 +84,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) { @@ -82,6 +95,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; @@ -215,6 +234,34 @@ 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, diff --git a/packages/plugin/src/features/sync/remote/reset.ts b/packages/plugin/src/features/sync/remote/reset.ts index ec11f938..d5c3bbe1 100644 --- a/packages/plugin/src/features/sync/remote/reset.ts +++ b/packages/plugin/src/features/sync/remote/reset.ts @@ -1,9 +1,8 @@ -import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { DEFAULT_CONCURRENCY, REMOTE_MANIFEST_KEY } from "@/core/constants"; import { runWithConcurrency } from "@/core/utils"; import type { StorageAdapter } from "@/features/storage"; import { REMOTE_HISTORY_LOG_KEY, - REMOTE_MANIFEST_KEY, REMOTE_OBJECTS_PREFIX, REMOTE_PINS_PREFIX, } from "../constants"; diff --git a/packages/plugin/src/features/sync/session.ts b/packages/plugin/src/features/sync/remote/salt.ts similarity index 94% rename from packages/plugin/src/features/sync/session.ts rename to packages/plugin/src/features/sync/remote/salt.ts index 925603d8..c66deec9 100644 --- a/packages/plugin/src/features/sync/session.ts +++ b/packages/plugin/src/features/sync/remote/salt.ts @@ -1,6 +1,6 @@ import { randomBytes } from "@/core/crypto"; import type { ObjectStorage } from "@/features/storage"; -import { REMOTE_SALT_KEY } from "./constants"; +import { REMOTE_SALT_KEY } from "../constants"; const SALT_BYTES = 16; diff --git a/packages/plugin/src/features/sync/runtime/history-service.ts b/packages/plugin/src/features/sync/runtime/history-service.ts index 86b58ae7..f3df4c1b 100644 --- a/packages/plugin/src/features/sync/runtime/history-service.ts +++ b/packages/plugin/src/features/sync/runtime/history-service.ts @@ -1,10 +1,6 @@ import { DEFAULT_CONCURRENCY } from "@/core/constants"; import { sha256Hex } from "@/core/crypto"; -import { - runWithConcurrency, - runWithFileConcurrency, - withEolOf, -} from "@/core/utils"; +import { runWithConcurrency, withEolOf } from "@/core/utils"; import { diskRefuses, trashPath } from "@/core/vault"; import { bytesToText, @@ -14,6 +10,7 @@ import { writeLocalFile, writeRemoteObject, } from "../changes/content"; +import { runWithFileConcurrency } from "../changes/file-concurrency"; import type { EngineDependencies } from "../engine"; import { loadVersionBytes, diff --git a/packages/plugin/src/features/sync/runtime/maintenance.ts b/packages/plugin/src/features/sync/runtime/maintenance.ts index ec91ded7..0a5e3654 100644 --- a/packages/plugin/src/features/sync/runtime/maintenance.ts +++ b/packages/plugin/src/features/sync/runtime/maintenance.ts @@ -1,7 +1,8 @@ import { DEFAULT_CONCURRENCY } from "@/core/constants"; import { decryptBytes, type EncryptionKey, sha256Hex } from "@/core/crypto"; -import { runWithConcurrency, runWithFileConcurrency } from "@/core/utils"; +import { runWithConcurrency } from "@/core/utils"; import type { StorageAdapter } from "@/features/storage"; +import { runWithFileConcurrency } from "../changes/file-concurrency"; import { REMOTE_OBJECTS_PREFIX, REMOTE_PINS_PREFIX } from "../constants"; import { changeEntries } from "../history/changes"; import { pinKey, readHistoryLog, readPinManifest } from "../history/store"; diff --git a/packages/plugin/src/features/sync/runtime/merged-result.ts b/packages/plugin/src/features/sync/runtime/merged-result.ts index 7a56b272..930f0980 100644 --- a/packages/plugin/src/features/sync/runtime/merged-result.ts +++ b/packages/plugin/src/features/sync/runtime/merged-result.ts @@ -1,4 +1,4 @@ -import { sortedByPath } from "@/core/shared"; +import { sortedByPath } from "../changes/records"; import type { CompareResult } from "../engine"; import type { Manifest } from "../types"; diff --git a/packages/plugin/src/features/sync/runtime/saved-refresh.ts b/packages/plugin/src/features/sync/runtime/saved-refresh.ts index 9eba997f..097a0e65 100644 --- a/packages/plugin/src/features/sync/runtime/saved-refresh.ts +++ b/packages/plugin/src/features/sync/runtime/saved-refresh.ts @@ -1,6 +1,5 @@ -import type { LocalSession } from "@/app/session-factory"; import { diffWithin } from "../changes/diff"; -import type { SyncControllerHost } from "../controller"; +import type { LocalSession, SyncControllerHost } from "../controller"; import { pathsBySpace } from "../remote/space"; import { buildEntry } from "../scope/entry"; import type { ManifestEntry } from "../types"; diff --git a/packages/plugin/src/features/sync/scope/configuration-scope-section.ts b/packages/plugin/src/features/sync/scope/configuration-scope-section.ts index eeebe74c..c98b960b 100644 --- a/packages/plugin/src/features/sync/scope/configuration-scope-section.ts +++ b/packages/plugin/src/features/sync/scope/configuration-scope-section.ts @@ -1,6 +1,7 @@ import type { SettingDefinitionGroup } from "obsidian"; import type { SettingsSyncCategories } from "@/core/settings"; import { + EFieldKind, type FieldContext, fieldRow, group, @@ -8,7 +9,7 @@ import { type SettingsRow, } from "@/core/settings"; import { notifyError, notifyInfo, openConfirmModal } from "@/core/ui"; -import { EFieldKind } from "@/features/storage"; +import type { SyncHost } from "../host"; import type { Manifest } from "../types"; import { createScopePolicy, type ScopePolicy } from "./scope"; @@ -64,7 +65,7 @@ function countRemoteCategories( } export function configurationScopeSection( - ctx: FieldContext, + ctx: FieldContext, ): SettingDefinitionGroup { const { plugin } = ctx; return group("Obsidian configuration scope", [ @@ -122,7 +123,7 @@ export function configurationScopeSection( } async function clearCategory( - ctx: FieldContext, + ctx: FieldContext, row: SettingsSyncRow, ): Promise { const { plugin } = ctx; diff --git a/packages/plugin/src/features/sync/scope/exclusions-section.ts b/packages/plugin/src/features/sync/scope/exclusions-section.ts index 3f2b5e0a..efb573f2 100644 --- a/packages/plugin/src/features/sync/scope/exclusions-section.ts +++ b/packages/plugin/src/features/sync/scope/exclusions-section.ts @@ -1,7 +1,7 @@ import { type App, type SettingDefinitionGroup, TFile } from "obsidian"; - import { IGNORE_FILE_NAME } from "@/core/constants"; import { + EFieldKind, type FieldContext, fieldRow, group, @@ -10,13 +10,13 @@ import { type SettingsField, } from "@/core/settings"; import { notifyError, notifyInfo, openInEditor, reportError } from "@/core/ui"; -import { EFieldKind } from "@/features/storage"; +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", @@ -40,7 +40,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 diff --git a/packages/plugin/src/features/sync/scope/ignore-state.ts b/packages/plugin/src/features/sync/scope/ignore-state.ts index 46d4e586..1d1dbf56 100644 --- a/packages/plugin/src/features/sync/scope/ignore-state.ts +++ b/packages/plugin/src/features/sync/scope/ignore-state.ts @@ -1,5 +1,5 @@ import { type Plugin, type TAbstractFile, TFile, TFolder } from "obsidian"; -import type { PluginHost } from "@/app/host"; +import type { SyncHost } from "../host"; import { type Space, spaceOf } from "../remote/space"; import { createIgnoreMatcher, @@ -26,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/features/sync/scope/scanner.ts b/packages/plugin/src/features/sync/scope/scanner.ts index 3efcde27..8785212d 100644 --- a/packages/plugin/src/features/sync/scope/scanner.ts +++ b/packages/plugin/src/features/sync/scope/scanner.ts @@ -1,13 +1,14 @@ import type { DataAdapter } from "obsidian"; import { DEFAULT_CONCURRENCY } from "@/core/constants"; -import { hasDotSegment, sortedByPath, stripTrailingSlash } from "@/core/shared"; +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, - runWithConcurrency, -} from "@/core/utils"; -import type { VaultIndex } from "@/core/vault"; -import { caseInsensitiveDisk } from "@/core/vault"; +} from "../changes/file-concurrency"; +import { sortedByPath } from "../changes/records"; import type { HashCacheEntry, LocalSnapshot, diff --git a/packages/plugin/src/features/sync/session-state.ts b/packages/plugin/src/features/sync/session-state.ts index 7c89e7ef..acd0c3d6 100644 --- a/packages/plugin/src/features/sync/session-state.ts +++ b/packages/plugin/src/features/sync/session-state.ts @@ -1,6 +1,5 @@ -import { entryAt } from "@/core/shared"; - 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 "./remote/space"; 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/features/settings/sections/security.ts b/packages/plugin/src/features/sync/ui/encryption-section.ts similarity index 84% rename from packages/plugin/src/features/settings/sections/security.ts rename to packages/plugin/src/features/sync/ui/encryption-section.ts index 7e764864..2f40d129 100644 --- a/packages/plugin/src/features/settings/sections/security.ts +++ b/packages/plugin/src/features/sync/ui/encryption-section.ts @@ -1,16 +1,18 @@ import type { SettingDefinitionGroup } from "obsidian"; - -import { clearCachedPassphrase } from "@/core/crypto"; -import { type FieldContext, group, isStorageConfigured } from "@/core/settings"; +import { type FieldContext, group } from "@/core/settings"; import { askNewPassphrase, notifyError, notifyInfo, reportError, } from "@/core/ui"; -import { PassphraseRotatedError } from "@/features/sync/remote/keyfile"; +import { isStorageConfigured } from "@/features/storage"; +import type { SyncHost } from "../host"; +import { PassphraseRotatedError } from "../remote/keyfile"; -export function securitySection(ctx: FieldContext): SettingDefinitionGroup { +export function encryptionSection( + ctx: FieldContext, +): SettingDefinitionGroup { const { plugin, rerender } = ctx; return group("Encryption", [ { @@ -21,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/ignore-action.ts b/packages/plugin/src/features/sync/ui/ignore-action.ts index a3e4b2da..aca8d836 100644 --- a/packages/plugin/src/features/sync/ui/ignore-action.ts +++ b/packages/plugin/src/features/sync/ui/ignore-action.ts @@ -1,7 +1,6 @@ import { type App, type Menu, TFile, TFolder } from "obsidian"; - -import type { PluginHost } from "@/app/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 { @@ -15,7 +14,7 @@ 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 = "", @@ -46,7 +45,7 @@ export function addIgnoreMenuItem( type IgnoreLevel = "local" | "global"; async function chooseIgnoreLevel( - plugin: PluginHost, + plugin: SyncHost, path: string, isFolder: boolean, ): Promise { @@ -79,7 +78,7 @@ async function askIgnoreLevel( } export async function toggleLocalIgnore( - plugin: PluginHost, + plugin: SyncHost, path: string, isFolder: boolean, ): Promise { @@ -115,7 +114,7 @@ export async function toggleLocalIgnore( } export async function toggleGlobalIgnore( - plugin: PluginHost, + plugin: SyncHost, path: string, isFolder: boolean, ): Promise { @@ -141,7 +140,7 @@ export async function toggleGlobalIgnore( } export async function stopIgnoring( - plugin: PluginHost, + plugin: SyncHost, path: string, isFolder: boolean, ): Promise { @@ -187,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( @@ -214,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/features/sync/ui/maintenance-actions.ts b/packages/plugin/src/features/sync/ui/maintenance-actions.ts index 154aacac..bb2a0ce8 100644 --- a/packages/plugin/src/features/sync/ui/maintenance-actions.ts +++ b/packages/plugin/src/features/sync/ui/maintenance-actions.ts @@ -1,18 +1,17 @@ -import type { PluginHost } from "@/app/host"; -import { activeStorage } from "@/core/settings"; import { notifyError, notifyInfo, openConfirmModal, reportError, } from "@/core/ui"; -import { describeStorageTarget } from "@/features/storage"; +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) { @@ -32,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, @@ -57,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?", @@ -78,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/features/sync/ui/maintenance-section.ts b/packages/plugin/src/features/sync/ui/maintenance-section.ts index 1b978e8b..c0322b47 100644 --- a/packages/plugin/src/features/sync/ui/maintenance-section.ts +++ b/packages/plugin/src/features/sync/ui/maintenance-section.ts @@ -1,7 +1,6 @@ import type { SettingDefinitionGroup } from "obsidian"; - -import type { PluginHost } from "@/app/host"; import { type FieldContext, group } from "@/core/settings"; +import type { SyncHost } from "../host"; import { deepCleanOrphanedObjects, resetLocalState, @@ -14,7 +13,7 @@ interface MaintenanceAction { 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/features/sync/ui/push-action.ts b/packages/plugin/src/features/sync/ui/push-action.ts index 1bd9e6a3..070b7b59 100644 --- a/packages/plugin/src/features/sync/ui/push-action.ts +++ b/packages/plugin/src/features/sync/ui/push-action.ts @@ -1,8 +1,6 @@ import type { Menu } from "obsidian"; -import type { PluginHost } from "@/app/host"; -import { SOURCE_CONTROL_VIEW_TYPE } from "@/core/constants"; import { notifyError, notifyInfo, runWithNotice } from "@/core/ui"; -import { openSourceControlView } from "@/features/source-control/view"; +import type { SyncHost } from "../host"; /** Changes inside `scope`: a file matches itself, a folder everything below it (the vault root "/" covers all). */ export function scopedPaths( @@ -27,7 +25,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 { @@ -41,7 +39,7 @@ export function addPushMenuItem( } export async function pushScope( - plugin: PluginHost, + plugin: SyncHost, path: string, isFolder: boolean, ): Promise { @@ -69,7 +67,7 @@ export async function pushScope( ? `Resolve the conflict in "${conflicts[0]}" first.` : `Resolve ${conflicts.length} conflicts under this ${target} first.`, ); - await openSourceControlView(plugin.app, SOURCE_CONTROL_VIEW_TYPE); + await plugin.openSourceControl(); return; } const paths = scopedPaths(diff.localChanges, path, isFolder); diff --git a/packages/plugin/src/features/sync/ui/sync-actions.ts b/packages/plugin/src/features/sync/ui/sync-actions.ts index 5a47beb9..91e71ace 100644 --- a/packages/plugin/src/features/sync/ui/sync-actions.ts +++ b/packages/plugin/src/features/sync/ui/sync-actions.ts @@ -1,18 +1,17 @@ -import type { PluginHost } from "@/app/host"; import { notifyError, notifyInfo, runWithNotice } from "@/core/ui"; -import { openSourceControlChanges } from "@/features/source-control/view"; +import type { SyncHost } from "../host"; import type { DiffResult } from "../types"; -export async function runCompare(plugin: PluginHost): Promise { +export async function runCompare(plugin: SyncHost): Promise { try { await plugin.controller.refresh(); - await openSourceControlChanges(plugin); + await plugin.openChanges(); } catch (err) { notifyError("Compare failed", err); } } -export async function runPushAll(plugin: PluginHost): Promise { +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(); @@ -38,7 +37,7 @@ export async function runPushAll(plugin: PluginHost): Promise { } } -export async function runPullAll(plugin: PluginHost): Promise { +export async function runPullAll(plugin: SyncHost): Promise { try { await plugin.controller.refresh(); const diff = comparedDiff(plugin); @@ -61,7 +60,7 @@ export async function runPullAll(plugin: PluginHost): Promise { } /** The fresh compare's diff; null, said so, when the compare did not finish. */ -function comparedDiff(plugin: PluginHost): DiffResult | null { +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."); @@ -70,11 +69,11 @@ function comparedDiff(plugin: PluginHost): DiffResult | null { /** Push and pull must never choose a side silently; conflicts go to the user. */ async function announceConflicts( - plugin: PluginHost, + plugin: SyncHost, count: number, ): Promise { if (count === 0) return false; notifyInfo(`Resolve ${count} conflict(s) first.`); - await openSourceControlChanges(plugin); + await plugin.openChanges(); return true; } diff --git a/packages/plugin/src/features/sync/ui/vault-adoption.ts b/packages/plugin/src/features/sync/ui/vault-adoption.ts index 4a4739ce..1445c0f5 100644 --- a/packages/plugin/src/features/sync/ui/vault-adoption.ts +++ b/packages/plugin/src/features/sync/ui/vault-adoption.ts @@ -1,10 +1,9 @@ import type { Plugin } from "obsidian"; import { notifyError, notifyInfo } from "@/core/ui"; import type { SyncController, SyncStatusSnapshot } from "../controller"; +import { isVaultMismatch } from "../identity/vault-mismatch"; import { confirmAdoptNewVault } from "./modals"; -const VAULT_MISMATCH_ERROR = "Remote vault id does not match local"; - /** * Offers to adopt the remote vault when its id stopped matching ours, usually because another device reset * the storage. @@ -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 index 2fb6ac36..ab8183e4 100644 --- a/packages/plugin/src/features/transfer/index.ts +++ b/packages/plugin/src/features/transfer/index.ts @@ -1,3 +1,4 @@ +export type { TransferHost } from "./host"; export { TRANSFER_ACTION } from "./transfer"; export { SettingsTransferController } from "./transfer-controller"; export { deviceTransferSection } from "./ui/device-transfer-section"; diff --git a/packages/plugin/src/features/transfer/transfer.ts b/packages/plugin/src/features/transfer/transfer.ts index 0c22a69c..96f5af20 100644 --- a/packages/plugin/src/features/transfer/transfer.ts +++ b/packages/plugin/src/features/transfer/transfer.ts @@ -1,16 +1,17 @@ import { LINK_PARAM, openLink, sealLink } from "@/core/crypto"; import { - activeStorage, - DEFAULT_SETTINGS, + DEFAULT_CORE_SETTINGS, DEFAULT_SETTINGS_SYNC, type MdsyncSettings, - mergeSettings, + mergeCoreSettings, type SettingsSyncCategories, } from "@/core/settings"; import { + activeStorage, type CompactStorageConfig, compactStorageConfig, EStorageBackend, + parseStorageSettings, type StorageAdapterConfig, storageDefaults, } from "@/features/storage"; @@ -205,12 +206,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,7 +269,7 @@ function createSectionPayload( TRANSFER_FIELDS[sectionId], )) { const value = settings[settingsKey as TransferFieldKey]; - const fallback = DEFAULT_SETTINGS[settingsKey as TransferFieldKey]; + const fallback = DEFAULT_CORE_SETTINGS[settingsKey as TransferFieldKey]; if (value === fallback) continue; out[transferKey] = typeof fallback === "boolean" ? Number(value) : value; } @@ -280,7 +285,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 +355,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/features/transfer/ui/device-transfer-section.ts b/packages/plugin/src/features/transfer/ui/device-transfer-section.ts index 5256d170..ed0d03fc 100644 --- a/packages/plugin/src/features/transfer/ui/device-transfer-section.ts +++ b/packages/plugin/src/features/transfer/ui/device-transfer-section.ts @@ -2,11 +2,12 @@ import type { SettingDefinitionGroup } from "obsidian"; 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/features/transfer/ui/settings-transfer-modal.ts b/packages/plugin/src/features/transfer/ui/settings-transfer-modal.ts index c9134011..4a25c41c 100644 --- a/packages/plugin/src/features/transfer/ui/settings-transfer-modal.ts +++ b/packages/plugin/src/features/transfer/ui/settings-transfer-modal.ts @@ -1,6 +1,6 @@ import { type App, ButtonComponent, Modal, Setting } from "obsidian"; -import { activeStorage, type MdsyncSettings } from "@/core/settings"; +import type { MdsyncSettings } from "@/core/settings"; import { modalFooter, modalWarning, @@ -8,7 +8,7 @@ import { openPromiseModal, renderModalHead, } from "@/core/ui"; -import { describeStorageTarget } from "@/features/storage"; +import { activeStorage, describeStorageTarget } from "@/features/storage"; import type { TransferSection } from "../transfer"; const IMPORT_CONFIRMATION_TEXT = "IMPORT"; diff --git a/packages/plugin/src/main.ts b/packages/plugin/src/main.ts index 66eb042e..f0243372 100644 --- a/packages/plugin/src/main.ts +++ b/packages/plugin/src/main.ts @@ -1,5 +1,5 @@ import { Plugin } from "obsidian"; -import { bootstrapPluginRuntime, disposePluginRuntime } from "@/app/bootstrap"; +import { bootstrapPluginRuntime } from "@/app/bootstrap"; import { registerCommands } from "@/app/commands"; import { registerHashCarry, @@ -9,23 +9,17 @@ import { import type { PluginHost } from "@/app/host"; import { registerProtocolHandlers } from "@/app/protocols"; import { createRealtime, type Realtime } from "@/app/realtime"; -import { SettingsEnvelope } from "@/app/settings-envelope"; -import { - refreshOpenHistoryViewsAfterPush, - refreshOpenSourceControlViews, - registerPluginUi, -} from "@/app/views"; +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 { - canSync, - DEFAULT_SETTINGS, - isStorageConfigured, - type MdsyncSettings, - mergeSettings, -} from "@/core/settings"; +import type { MdsyncSettings } from "@/core/settings"; import { reportWarning } from "@/core/shared"; -import { notifyAction, notifyInfo } from "@/core/ui"; +import { notifyAction } from "@/core/ui"; import { loadNodeFs } from "@/core/vault"; import { registerEditorSigns, type SignsHandle } from "@/features/editor-signs"; import type { IndicatorHandle } from "@/features/explorer"; @@ -34,7 +28,6 @@ import { createDeletedElsewhere } from "@/features/live"; import type { Unseen } from "@/features/presence"; import { type CursorFollow, - markTheirs, registerFollows, registerUnseen, } from "@/features/presence"; @@ -45,18 +38,17 @@ import { type ESetupStep, openSetupWizard, } from "@/features/setup"; -import { openSourceControlChanges } from "@/features/source-control"; -import type { SpaceRecords } from "@/features/spaces"; import { - createAccessEnded, - createShareRegistration, - createSpaceGone, - registerReadOnlyLock, - registerShareRenames, -} from "@/features/spaces"; -import { createStorageRefused } from "@/features/storage"; + openSourceControlChanges, + 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, @@ -67,8 +59,6 @@ import { } from "@/features/sync"; import { SettingsTransferController } from "@/features/transfer"; -const SCOPE_REFRESH_DEBOUNCE_MS = 800; - /** Runs a teardown step without letting its failure abort the rest. */ function safely(step: () => void): void { try { @@ -100,19 +90,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(); @@ -122,53 +112,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, @@ -220,11 +184,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.", @@ -237,10 +201,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()); @@ -255,29 +221,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()); @@ -293,7 +242,7 @@ export default class MdsyncPlugin extends Plugin implements PluginHost { } refreshSourceControlView(): void { - refreshOpenSourceControlViews(this); + refreshSourceControlViews(this.app); } openSetup(step?: ESetupStep): void { @@ -305,21 +254,16 @@ 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); + } + + scheduleScopeRefresh(reason?: string): void { + this.scopeRefresh.schedule(reason); } /** diff --git a/packages/plugin/tests/app/realtime.test.ts b/packages/plugin/tests/app/realtime.test.ts index aae5df5c..ad1dc945 100644 --- a/packages/plugin/tests/app/realtime.test.ts +++ b/packages/plugin/tests/app/realtime.test.ts @@ -1,7 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createRealtime } from "@/app/realtime"; +import type { HubListener } from "@/core/hub"; import type { LiveHost } from "@/features/live/register"; -import type { HubListener } from "@/features/relay/connection"; +import type { SpaceAccessHost } from "@/features/spaces/space-access"; import { VAULT_SPACE } from "@/features/sync/remote/space"; const state = vi.hoisted(() => ({ listener: {} as HubListener })); @@ -65,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/app/session-factory.test.ts b/packages/plugin/tests/app/session-factory.test.ts index 79d5914c..dad16ecf 100644 --- a/packages/plugin/tests/app/session-factory.test.ts +++ b/packages/plugin/tests/app/session-factory.test.ts @@ -4,7 +4,8 @@ import { createSessionOpeners, type SessionFactoryDeps, } from "@/app/session-factory"; -import { DEFAULT_SETTINGS, type MdsyncSettings } from "@/core/settings/model"; +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"; diff --git a/packages/plugin/tests/app/envelope.test.ts b/packages/plugin/tests/app/settings/envelope.test.ts similarity index 96% rename from packages/plugin/tests/app/envelope.test.ts rename to packages/plugin/tests/app/settings/envelope.test.ts index 60f3bc7e..8dbaca6f 100644 --- a/packages/plugin/tests/app/envelope.test.ts +++ b/packages/plugin/tests/app/settings/envelope.test.ts @@ -1,9 +1,10 @@ import { deviceKey, FakeSecretStorage } from "@tests/helpers/device-key"; import { link } from "@tests/helpers/shared-links"; import { describe, expect, it } from "vitest"; -import { SettingsEnvelope } from "@/app/settings-envelope"; +import { mergeSettings } from "@/app/settings"; +import { SettingsEnvelope } from "@/app/settings/envelope"; import { encryptJson } from "@/core/crypto/cipher"; -import { type MdsyncSettings, mergeSettings } from "@/core/settings/model"; +import type { MdsyncSettings } from "@/core/settings/model"; import { bytesToBase64 } from "@/core/utils/base64"; import { defaultS3Config } from "@/features/storage/backends/s3"; diff --git a/packages/plugin/tests/app/settings/index.test.ts b/packages/plugin/tests/app/settings/index.test.ts new file mode 100644 index 00000000..87542eaa --- /dev/null +++ b/packages/plugin/tests/app/settings/index.test.ts @@ -0,0 +1,241 @@ +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 "@/core/constants"; +import { defaultS3Config } from "@/features/storage/backends/s3"; +import { + EStorageBackend, + type StorageAdapterConfig, +} from "@/features/storage/config"; + +describe("mergeSettings", () => { + it("requires opt-in for every configuration category on a fresh device", () => { + expect(Object.values(mergeSettings(null).settingsSync)).toEqual([ + false, + false, + false, + false, + false, + false, + ]); + expect( + mergeSettings({ + settingsSync: { ...DEFAULT_SETTINGS.settingsSync, snippets: true }, + }).settingsSync.snippets, + ).toBe(true); + }); + it("defaults historyAutoRefresh to true when absent", () => { + expect(mergeSettings(null).historyAutoRefresh).toBe(true); + expect(mergeSettings({}).historyAutoRefresh).toBe(true); + }); + + it("preserves an explicit historyAutoRefresh: false", () => { + expect( + mergeSettings({ historyAutoRefresh: false }).historyAutoRefresh, + ).toBe(false); + }); + + it("shows file sizes by default and preserves an explicit false", () => { + expect(mergeSettings(null).showFileSizes).toBe(true); + expect(mergeSettings({ showFileSizes: false }).showFileSizes).toBe(false); + }); + + it("shows the open note by default and preserves an explicit false", () => { + expect(mergeSettings(null).showOpenNote).toBe(true); + expect(mergeSettings({ liveEditing: false }).showOpenNote).toBe(true); + expect(mergeSettings({ showOpenNote: false }).showOpenNote).toBe(false); + }); + + it("keeps only folder paths in the pending share moves", () => { + const localRoots = { a: "Team", b: "", c: 3 } as unknown as Record< + string, + string + >; + expect(mergeSettings({ localRoots }).localRoots).toEqual({ a: "Team" }); + expect(mergeSettings(null).localRoots).toEqual({}); + }); + + it("drops the retired relay and broker fields but keeps the relay config", () => { + const merged = mergeSettings({ + relayUrl: "https://relay.example", + relaySecret: "secret", + realtimeToken: "old-token", + shareBrokerAdminSecret: "old-admin", + } as Parameters[0]); + + expect(merged).toMatchObject({ + relayUrl: "https://relay.example", + relaySecret: "secret", + }); + expect(merged).not.toHaveProperty("realtimeToken"); + expect(merged).not.toHaveProperty("shareBrokerAdminSecret"); + }); + + it("backfills missing per-storage concurrency from backend defaults", () => { + const merged = mergeSettings({ + activeStorageKind: EStorageBackend.GoogleDrive, + storageConfigs: { + [EStorageBackend.GoogleDrive]: { + kind: EStorageBackend.GoogleDrive, + folderName: "ObsidianSync", + authServerUrl: "https://x", + accessToken: "", + refreshToken: "", + expiresAt: 0, + }, + [EStorageBackend.S3]: { + kind: EStorageBackend.S3, + endpoint: "", + region: "auto", + bucket: "b", + prefix: "", + accessKeyId: "", + secretAccessKey: "", + forcePathStyle: true, + }, + } as unknown as Record, + }); + expect( + merged.storageConfigs[EStorageBackend.GoogleDrive]?.concurrency, + ).toBe(8); + expect(merged.storageConfigs[EStorageBackend.S3]?.concurrency).toBe(4); + }); + + it("drops a storage config naming a backend this build no longer has", () => { + const merged = mergeSettings({ + activeStorageKind: "share-broker" as EStorageBackend, + storageConfigs: { + "share-broker": { kind: "share-broker", brokerUrl: "https://x" }, + } as unknown as Record, + }); + + expect(merged.storageConfigs).not.toHaveProperty("share-broker"); + expect(merged.activeStorageKind).toBe(EStorageBackend.S3); + }); + + it("survives stored configs that are not configs", () => { + const merged = mergeSettings({ + storageConfigs: { + constructor: {}, + toString: {}, + [EStorageBackend.WebDAV]: null, + [EStorageBackend.S3]: { ...defaultS3Config(), concurrency: 4 }, + } as unknown as Record, + }); + + expect(Object.keys(merged.storageConfigs)).toEqual([EStorageBackend.S3]); + }); + + it("replaces an invalid concurrency with the backend default", () => { + const merged = mergeSettings({ + activeStorageKind: EStorageBackend.S3, + storageConfigs: { + [EStorageBackend.S3]: { + kind: EStorageBackend.S3, + endpoint: "", + region: "auto", + bucket: "b", + prefix: "", + accessKeyId: "", + secretAccessKey: "", + forcePathStyle: true, + concurrency: 0, + }, + }, + }); + expect(merged.storageConfigs[EStorageBackend.S3]?.concurrency).toBe(4); + }); +}); + +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( + DEFAULT_SETTINGS.autoSyncIntervalMinutes, + ); + expect(merged.autoPushSettleSeconds).toBe( + 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", () => { + const merged = mergeSettings({ + maxFileBytes: Number.NaN, + autoSyncIntervalMinutes: "10" as unknown as number, + }); + + expect(merged.maxFileBytes).toBe(DEFAULT_SETTINGS.maxFileBytes); + expect(merged.autoSyncIntervalMinutes).toBe( + DEFAULT_SETTINGS.autoSyncIntervalMinutes, + ); + }); + + 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); + }); + + it("falls back on a negative deletion limit, keeps 0 and caps a greedy one", () => { + expect(mergeSettings({ bulkDeleteLimit: -1 }).bulkDeleteLimit).toBe( + DEFAULT_SETTINGS.bulkDeleteLimit, + ); + expect(mergeSettings({ bulkDeleteLimit: 0 }).bulkDeleteLimit).toBe(0); + expect(mergeSettings({ bulkDeleteLimit: 5000 }).bulkDeleteLimit).toBe( + BULK_DELETE_LIMIT_MAX, + ); + }); + + it("sends live edits balanced by default and takes only a preset speed", () => { + expect(DEFAULT_SETTINGS.liveSendMs).toBe(LIVE_SEND_MS.balanced); + expect(mergeSettings({ liveSendMs: 10 }).liveSendMs).toBe( + LIVE_SEND_MS.balanced, + ); + expect(mergeSettings({ liveSendMs: 500 }).liveSendMs).toBe( + LIVE_SEND_MS.balanced, + ); + expect( + mergeSettings({ liveSendMs: LIVE_SEND_MS.economical }).liveSendMs, + ).toBe(LIVE_SEND_MS.economical); + }); + + it("keeps a value that is already in range", () => { + expect( + mergeSettings({ autoSyncIntervalMinutes: 15 }).autoSyncIntervalMinutes, + ).toBe(15); + }); + + it("keeps an explicit autosync toggle and push preference", () => { + const merged = mergeSettings({ + autoSyncEnabled: false, + autoSyncIntervalMinutes: 30, + autoPushAfterSync: false, + }); + expect(merged.autoSyncEnabled).toBe(false); + expect(merged.autoPushAfterSync).toBe(false); + }); +}); 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..09d17c84 --- /dev/null +++ b/packages/plugin/tests/app/settings/store.test.ts @@ -0,0 +1,74 @@ +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("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/features/storage/storage-refused.test.ts b/packages/plugin/tests/app/storage-refused.test.ts similarity index 95% rename from packages/plugin/tests/features/storage/storage-refused.test.ts rename to packages/plugin/tests/app/storage-refused.test.ts index e0b2b06f..9234c2d3 100644 --- a/packages/plugin/tests/features/storage/storage-refused.test.ts +++ b/packages/plugin/tests/app/storage-refused.test.ts @@ -1,10 +1,10 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import type { PluginHost } from "@/app/host"; -import { mergeSettings } from "@/core/settings/model"; +import { mergeSettings } from "@/app/settings"; +import { createStorageRefused } from "@/app/storage-refused"; import { defaultGoogleDriveConfig } from "@/features/storage/backends/google-drive-auth"; import { defaultS3Config } from "@/features/storage/backends/s3"; import { EStorageBackend } from "@/features/storage/config"; -import { createStorageRefused } from "@/features/storage/storage-refused"; import { openStorageRefusedModal } from "@/features/storage/ui/storage-refused-modal"; import { VAULT_SPACE } from "@/features/sync/remote/space"; 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/core/settings/fields.test.ts b/packages/plugin/tests/core/settings/fields.test.ts index 882bf768..50b4711d 100644 --- a/packages/plugin/tests/core/settings/fields.test.ts +++ b/packages/plugin/tests/core/settings/fields.test.ts @@ -1,5 +1,6 @@ import type { Setting, SettingDefinitionRender } from "obsidian"; import { describe, expect, it, vi } from "vitest"; +import { EFieldKind } from "@/core/settings"; import { type FieldContext, @@ -9,7 +10,6 @@ import { renderDefinitions, type SettingsRow, } from "@/core/settings/fields"; -import { EFieldKind } from "@/features/storage/field-spec"; vi.mock("obsidian", () => ({ debounce: (fn: unknown) => fn, diff --git a/packages/plugin/tests/core/settings/model.test.ts b/packages/plugin/tests/core/settings/model.test.ts index 893d26a0..29d729bc 100644 --- a/packages/plugin/tests/core/settings/model.test.ts +++ b/packages/plugin/tests/core/settings/model.test.ts @@ -1,19 +1,5 @@ import { describe, expect, it } from "vitest"; -import { - AUTO_PUSH_SETTLE_MAX_SECONDS, - BULK_DELETE_LIMIT_MAX, - LIVE_SEND_MS, -} from "@/core/constants"; -import { - DEFAULT_SETTINGS, - isRelayConfigured, - mergeSettings, -} from "@/core/settings/model"; -import { defaultS3Config } from "@/features/storage/backends/s3"; -import { - EStorageBackend, - type StorageAdapterConfig, -} from "@/features/storage/config"; +import { isRelayConfigured } from "@/core/settings/model"; describe("isRelayConfigured", () => { const secret = "s3cret"; @@ -45,232 +31,3 @@ describe("isRelayConfigured", () => { ).toBe(false); }); }); - -describe("mergeSettings", () => { - it("requires opt-in for every configuration category on a fresh device", () => { - expect(Object.values(mergeSettings(null).settingsSync)).toEqual([ - false, - false, - false, - false, - false, - false, - ]); - expect( - mergeSettings({ - settingsSync: { ...DEFAULT_SETTINGS.settingsSync, snippets: true }, - }).settingsSync.snippets, - ).toBe(true); - }); - it("defaults historyAutoRefresh to true when absent", () => { - expect(mergeSettings(null).historyAutoRefresh).toBe(true); - expect(mergeSettings({}).historyAutoRefresh).toBe(true); - }); - - it("preserves an explicit historyAutoRefresh: false", () => { - expect( - mergeSettings({ historyAutoRefresh: false }).historyAutoRefresh, - ).toBe(false); - }); - - it("shows file sizes by default and preserves an explicit false", () => { - expect(mergeSettings(null).showFileSizes).toBe(true); - expect(mergeSettings({ showFileSizes: false }).showFileSizes).toBe(false); - }); - - it("shows the open note by default and preserves an explicit false", () => { - expect(mergeSettings(null).showOpenNote).toBe(true); - expect(mergeSettings({ liveEditing: false }).showOpenNote).toBe(true); - expect(mergeSettings({ showOpenNote: false }).showOpenNote).toBe(false); - }); - - it("keeps only folder paths in the pending share moves", () => { - const localRoots = { a: "Team", b: "", c: 3 } as unknown as Record< - string, - string - >; - expect(mergeSettings({ localRoots }).localRoots).toEqual({ a: "Team" }); - expect(mergeSettings(null).localRoots).toEqual({}); - }); - - it("drops the retired relay and broker fields but keeps the relay config", () => { - const merged = mergeSettings({ - relayUrl: "https://relay.example", - relaySecret: "secret", - realtimeToken: "old-token", - shareBrokerAdminSecret: "old-admin", - } as Parameters[0]); - - expect(merged).toMatchObject({ - relayUrl: "https://relay.example", - relaySecret: "secret", - }); - expect(merged).not.toHaveProperty("realtimeToken"); - expect(merged).not.toHaveProperty("shareBrokerAdminSecret"); - }); - - it("backfills missing per-storage concurrency from backend defaults", () => { - const merged = mergeSettings({ - activeStorageKind: EStorageBackend.GoogleDrive, - storageConfigs: { - [EStorageBackend.GoogleDrive]: { - kind: EStorageBackend.GoogleDrive, - folderName: "ObsidianSync", - authServerUrl: "https://x", - accessToken: "", - refreshToken: "", - expiresAt: 0, - }, - [EStorageBackend.S3]: { - kind: EStorageBackend.S3, - endpoint: "", - region: "auto", - bucket: "b", - prefix: "", - accessKeyId: "", - secretAccessKey: "", - forcePathStyle: true, - }, - } as unknown as Record, - }); - expect( - merged.storageConfigs[EStorageBackend.GoogleDrive]?.concurrency, - ).toBe(8); - expect(merged.storageConfigs[EStorageBackend.S3]?.concurrency).toBe(4); - }); - - it("drops a storage config naming a backend this build no longer has", () => { - const merged = mergeSettings({ - activeStorageKind: "share-broker" as EStorageBackend, - storageConfigs: { - "share-broker": { kind: "share-broker", brokerUrl: "https://x" }, - } as unknown as Record, - }); - - expect(merged.storageConfigs).not.toHaveProperty("share-broker"); - expect(merged.activeStorageKind).toBe(EStorageBackend.S3); - }); - - it("survives stored configs that are not configs", () => { - const merged = mergeSettings({ - storageConfigs: { - constructor: {}, - toString: {}, - [EStorageBackend.WebDAV]: null, - [EStorageBackend.S3]: { ...defaultS3Config(), concurrency: 4 }, - } as unknown as Record, - }); - - expect(Object.keys(merged.storageConfigs)).toEqual([EStorageBackend.S3]); - }); - - it("replaces an invalid concurrency with the backend default", () => { - const merged = mergeSettings({ - activeStorageKind: EStorageBackend.S3, - storageConfigs: { - [EStorageBackend.S3]: { - kind: EStorageBackend.S3, - endpoint: "", - region: "auto", - bucket: "b", - prefix: "", - accessKeyId: "", - secretAccessKey: "", - forcePathStyle: true, - concurrency: 0, - }, - }, - }); - expect(merged.storageConfigs[EStorageBackend.S3]?.concurrency).toBe(4); - }); -}); - -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( - DEFAULT_SETTINGS.autoSyncIntervalMinutes, - ); - expect(merged.autoPushSettleSeconds).toBe( - 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", () => { - const merged = mergeSettings({ - maxFileBytes: Number.NaN, - autoSyncIntervalMinutes: "10" as unknown as number, - }); - - expect(merged.maxFileBytes).toBe(DEFAULT_SETTINGS.maxFileBytes); - expect(merged.autoSyncIntervalMinutes).toBe( - DEFAULT_SETTINGS.autoSyncIntervalMinutes, - ); - }); - - 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); - }); - - it("falls back on a negative deletion limit, keeps 0 and caps a greedy one", () => { - expect(mergeSettings({ bulkDeleteLimit: -1 }).bulkDeleteLimit).toBe( - DEFAULT_SETTINGS.bulkDeleteLimit, - ); - expect(mergeSettings({ bulkDeleteLimit: 0 }).bulkDeleteLimit).toBe(0); - expect(mergeSettings({ bulkDeleteLimit: 5000 }).bulkDeleteLimit).toBe( - BULK_DELETE_LIMIT_MAX, - ); - }); - - it("sends live edits balanced by default and takes only a preset speed", () => { - expect(DEFAULT_SETTINGS.liveSendMs).toBe(LIVE_SEND_MS.balanced); - expect(mergeSettings({ liveSendMs: 10 }).liveSendMs).toBe( - LIVE_SEND_MS.balanced, - ); - expect(mergeSettings({ liveSendMs: 500 }).liveSendMs).toBe( - LIVE_SEND_MS.balanced, - ); - expect( - mergeSettings({ liveSendMs: LIVE_SEND_MS.economical }).liveSendMs, - ).toBe(LIVE_SEND_MS.economical); - }); - - it("keeps a value that is already in range", () => { - expect( - mergeSettings({ autoSyncIntervalMinutes: 15 }).autoSyncIntervalMinutes, - ).toBe(15); - }); - - it("keeps an explicit autosync toggle and push preference", () => { - const merged = mergeSettings({ - autoSyncEnabled: false, - autoSyncIntervalMinutes: 30, - autoPushAfterSync: false, - }); - expect(merged.autoSyncEnabled).toBe(false); - expect(merged.autoPushAfterSync).toBe(false); - }); -}); diff --git a/packages/plugin/tests/core/settings/number-field.test.ts b/packages/plugin/tests/core/settings/number-field.test.ts index b8a33ba3..ffdc05d0 100644 --- a/packages/plugin/tests/core/settings/number-field.test.ts +++ b/packages/plugin/tests/core/settings/number-field.test.ts @@ -1,12 +1,12 @@ import { Setting } from "obsidian"; import { describe, expect, it, vi } from "vitest"; +import { EFieldKind } from "@/core/settings"; import { type FieldContext, fieldRow, type NumberField, } from "@/core/settings/fields"; -import { EFieldKind } from "@/features/storage/field-spec"; vi.mock("obsidian", () => { class Setting { diff --git a/packages/plugin/tests/core/shared/offline.test.ts b/packages/plugin/tests/core/shared/offline.test.ts index 9b2080f5..98324dd4 100644 --- a/packages/plugin/tests/core/shared/offline.test.ts +++ b/packages/plugin/tests/core/shared/offline.test.ts @@ -9,7 +9,7 @@ import { import { StorageHttpError, StorageTimeoutError, -} from "@/features/storage/backends/util"; +} from "@/core/shared/transport-errors"; function browserOnline(online: boolean): void { vi.stubGlobal("navigator", { onLine: online }); diff --git a/packages/plugin/tests/features/diff/diff-operations.test.ts b/packages/plugin/tests/features/diff/diff-operations.test.ts index 453c4081..c93240be 100644 --- a/packages/plugin/tests/features/diff/diff-operations.test.ts +++ b/packages/plugin/tests/features/diff/diff-operations.test.ts @@ -104,7 +104,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("@/features/diff/restore-modal"); + const restoreMod = await import("@/features/diff/ui/restore-modal"); const spy = vi .spyOn(restoreMod, "confirmRestore") .mockResolvedValue(true); @@ -129,7 +129,7 @@ describe("DiffOperations.restoreVersion uses selected hash", () => { ); it("does not restore if confirmation is cancelled", async () => { - const restoreMod = await import("@/features/diff/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(); @@ -138,7 +138,7 @@ describe("DiffOperations.restoreVersion uses selected hash", () => { }); it("restores using the historyHash which is the selected version", async () => { - const restoreMod = await import("@/features/diff/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/features/diff/diff-view-status.test.ts b/packages/plugin/tests/features/diff/diff-view-status.test.ts index 6084b7ad..4c190776 100644 --- a/packages/plugin/tests/features/diff/diff-view-status.test.ts +++ b/packages/plugin/tests/features/diff/diff-view-status.test.ts @@ -15,9 +15,6 @@ vi.mock("@/core/ui/phone-change", () => ({ redrawOnPhoneChange: vi.fn() })); vi.mock("@/core/ui/modals/confirm-modal", () => ({ openConfirmModal: vi.fn(), })); -vi.mock("@/features/source-control/view", () => ({ - openSourceControlView: vi.fn(), -})); beforeAll(installElementMethods); diff --git a/packages/plugin/tests/core/utils/search.test.ts b/packages/plugin/tests/features/diff/lines/search.test.ts similarity index 90% rename from packages/plugin/tests/core/utils/search.test.ts rename to packages/plugin/tests/features/diff/lines/search.test.ts index 99d2ea41..6685951f 100644 --- a/packages/plugin/tests/core/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 "@/core/utils/search"; +import { firstIndex } from "@/features/diff/lines/search"; describe("firstIndex", () => { const values = [1, 3, 3, 7, 9]; diff --git a/packages/plugin/tests/features/diff/merge/edit-plan.test.ts b/packages/plugin/tests/features/diff/merge/edit-plan.test.ts new file mode 100644 index 00000000..e9ed0454 --- /dev/null +++ b/packages/plugin/tests/features/diff/merge/edit-plan.test.ts @@ -0,0 +1,194 @@ +import { Text } from "@codemirror/state"; +import { describe, expect, it } from "vitest"; +import { + applyPlan, + revertPlan, + type StatusPatch, + snapToLines, +} from "@/features/diff/merge/edit-plan"; +import type { MergeChange } from "@/features/sync/hunks/merge-model"; + +const doc = (text: string) => Text.of(text.split("\n")); + +function conflictAt( + from: number, + to: number, + status: StatusPatch = {}, +): MergeChange { + return { + index: 0, + conflict: true, + base: [1, 2], + endsAtEof: true, + local: [1, 2], + remote: [1, 2], + result: { from, to }, + taken: {}, + status: { local: "open", remote: "open", ...status }, + }; +} + +describe("applyPlan", () => { + it("replaces the base lines with the chosen side", () => { + const plan = applyPlan(doc("a\nb\nc"), conflictAt(2, 4), "local", [ + "L1", + "L2", + ]); + expect(plan).toEqual({ + from: 2, + to: 4, + insert: "L1\nL2\n", + result: { from: 2, to: 8 }, + taken: { local: { from: 2, to: 8 } }, + }); + }); + + it("appends the second side below the first, so click order is line order", () => { + const first = conflictAt(2, 8, { local: "applied" }); + const plan = applyPlan(doc("a\nL1\nL2\nc"), first, "remote", ["R"]); + expect(plan).toEqual({ + from: 8, + to: 8, + insert: "R\n", + result: { from: 2, to: 10 }, + taken: { remote: { from: 8, to: 10 } }, + }); + }); + + it("replaces rather than appends when the other side was ignored", () => { + const change = conflictAt(2, 4, { local: "ignored" }); + const plan = applyPlan(doc("a\nb\nc"), change, "remote", ["R"]); + expect(plan).toEqual({ + from: 2, + to: 4, + insert: "R\n", + result: { from: 2, to: 4 }, + taken: { remote: { from: 2, to: 4 } }, + }); + }); + + it("takes the newline before the last line along when deleting it", () => { + const plan = applyPlan(doc("a\nb"), conflictAt(2, 3), "local", []); + expect(plan).toEqual({ + from: 1, + to: 3, + insert: "", + result: { from: 1, to: 1 }, + taken: { local: { from: 1, to: 1 } }, + }); + }); + + it("inserts after a last line that has no newline", () => { + const plan = applyPlan(doc("a"), conflictAt(1, 1), "local", ["L"]); + expect(plan).toEqual({ + from: 1, + to: 1, + insert: "\nL", + result: { from: 2, to: 3 }, + taken: { local: { from: 2, to: 3 } }, + }); + }); + + it("deletes the entire document if it is replaced with empty", () => { + const plan = applyPlan(doc("a\nb\nc"), conflictAt(0, 5), "local", []); + expect(plan).toEqual({ + from: 0, + to: 5, + insert: "", + result: { from: 0, to: 0 }, + taken: { local: { from: 0, to: 0 } }, + }); + }); + + it("keeps the replaced span whole-line even after the span drifted mid-line", () => { + const plan = applyPlan(doc("a\nbcd\ne"), conflictAt(3, 4), "local", ["L"]); + expect(plan).toEqual({ + from: 2, + to: 6, + insert: "L\n", + result: { from: 2, to: 4 }, + taken: { local: { from: 2, to: 4 } }, + }); + }); +}); + +describe("revertPlan", () => { + it("reverts the chosen side back to base lines when the other side is open", () => { + const change = conflictAt(2, 8, { local: "applied" }); + change.taken = { local: { from: 2, to: 8 } }; + const plan = revertPlan(doc("a\nL1\nL2\nc"), change, "local", ["b"]); + expect(plan).toEqual({ + from: 2, + to: 8, + insert: "b\n", + result: { from: 2, to: 4 }, + taken: { local: null }, + }); + }); + + it("removes only the chosen side's lines when both sides are applied", () => { + const change = conflictAt(2, 10, { + local: "applied", + remote: "applied", + }); + change.taken = { local: { from: 2, to: 8 }, remote: { from: 8, to: 10 } }; + const plan = revertPlan(doc("a\nL1\nL2\nR\nc"), change, "local", ["b"]); + expect(plan).toEqual({ + from: 2, + to: 8, + insert: "", + taken: { local: null }, + }); + }); + + it("keeps the shared text when reverting one side of an identical change", () => { + const change: MergeChange = { + index: 0, + conflict: false, + base: [1, 2], + endsAtEof: false, + local: [1, 2], + remote: [1, 2], + result: { from: 2, to: 4 }, + taken: { local: { from: 2, to: 4 }, remote: { from: 2, to: 4 } }, + status: { local: "applied", remote: "applied" }, + }; + const plan = revertPlan(doc("a\nB\nc"), change, "local", ["b"]); + expect(plan).toEqual({ + from: 2, + to: 2, + insert: "", + taken: { local: null }, + }); + }); +}); + +describe("snapToLines", () => { + it("widens a span to whole lines", () => { + expect(snapToLines(doc("ab\ncd\nef"), { from: 1, to: 4 })).toEqual({ + from: 0, + to: 6, + }); + }); + + it("keeps an empty span at a line start where it is", () => { + expect(snapToLines(doc("ab\ncd"), { from: 3, to: 3 })).toEqual({ + from: 3, + to: 3, + }); + }); + + it("keeps an empty span after a last line without newline", () => { + expect(snapToLines(doc("ab\ncd"), { from: 5, to: 5 })).toEqual({ + from: 5, + to: 5, + }); + }); + + it("moves an empty mid-line span to the next line start", () => { + expect(snapToLines(doc("ab\ncd\nef"), { from: 1, to: 1 })).toEqual({ + from: 3, + to: 3, + }); + }); +}); diff --git a/packages/plugin/tests/features/diff/merge/merge-state.test.ts b/packages/plugin/tests/features/diff/merge/merge-state.test.ts index 344a0383..6cec6cfc 100644 --- a/packages/plugin/tests/features/diff/merge/merge-state.test.ts +++ b/packages/plugin/tests/features/diff/merge/merge-state.test.ts @@ -1,6 +1,7 @@ import { history, isolateHistory, redo, undo } from "@codemirror/commands"; import { EditorState, Transaction } from "@codemirror/state"; import { assert, describe, expect, it } from "vitest"; +import { applyPlan, revertPlan } from "@/features/diff/merge/edit-plan"; import { openedGapsField, toggleMergeGap, @@ -16,11 +17,9 @@ import { setChangeState, } from "@/features/diff/merge/merge-state"; import { - applyPlan, buildMergeSession, type EMergeSide, type MergeChange, - revertPlan, } from "@/features/sync/hunks/merge-model"; function open(base: string, local: string, remote: string): EditorState { diff --git a/packages/plugin/tests/features/links/link-broker.test.ts b/packages/plugin/tests/features/links/link-broker.test.ts index 785f3d85..24a2abae 100644 --- a/packages/plugin/tests/features/links/link-broker.test.ts +++ b/packages/plugin/tests/features/links/link-broker.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; +import { StorageHttpError } from "@/core/shared/transport-errors"; import { createLink, linkStatus, @@ -6,7 +7,6 @@ import { replaceLink, revokeLink, } from "@/features/links/link-broker"; -import { StorageHttpError } from "@/features/storage/backends/util"; import { StorageRequestError } from "@/features/storage/types"; interface Recorded { diff --git a/packages/plugin/tests/features/links/ui/link-actions.test.ts b/packages/plugin/tests/features/links/ui/link-actions.test.ts index a160e0f2..a24cb002 100644 --- a/packages/plugin/tests/features/links/ui/link-actions.test.ts +++ b/packages/plugin/tests/features/links/ui/link-actions.test.ts @@ -32,12 +32,6 @@ vi.mock("@/features/links/ui/link-menu", () => ({ openManageLinks: vi.fn(), openShareLink: vi.fn(), })); -vi.mock("@/features/source-control/view", () => ({ - openDiffView: vi.fn(), - openSourceControlDeleted: vi.fn(), - openSourceControlHistory: vi.fn(), - openSourceControlView: vi.fn(), -})); vi.mock("@/features/spaces/ui/invites/invite-action", () => ({ openInvite: vi.fn(), })); diff --git a/packages/plugin/tests/features/live/session/follower.test.ts b/packages/plugin/tests/features/live/session/follower.test.ts index 73c14c08..a7d4fe04 100644 --- a/packages/plugin/tests/features/live/session/follower.test.ts +++ b/packages/plugin/tests/features/live/session/follower.test.ts @@ -13,12 +13,12 @@ import { encodeAwarenessUpdate, } from "y-protocols/awareness"; import * as Y from "yjs"; +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"; -import type { SpaceFrame } from "@/features/relay/connection"; const live = useLiveRoom(); const { synced, roomState } = live; diff --git a/packages/plugin/tests/features/live/workspace/rename.test.ts b/packages/plugin/tests/features/live/workspace/rename.test.ts index e3628526..3718a6a7 100644 --- a/packages/plugin/tests/features/live/workspace/rename.test.ts +++ b/packages/plugin/tests/features/live/workspace/rename.test.ts @@ -3,9 +3,9 @@ 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 "@/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"; @@ -14,7 +14,6 @@ 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"; -import type { SpaceFrame, SpaceHub } from "@/features/relay/connection"; vi.mock("@/features/live/text/binding", () => ({ bindEditor: vi.fn(() => ({ detach: vi.fn(), showAuthors: vi.fn() })), diff --git a/packages/plugin/tests/features/relay/connection.test.ts b/packages/plugin/tests/features/relay/connection.test.ts index be8c13bf..04d124ca 100644 --- a/packages/plugin/tests/features/relay/connection.test.ts +++ b/packages/plugin/tests/features/relay/connection.test.ts @@ -7,9 +7,10 @@ import { shareChannel, } from "@mdsync/protocol"; import { beforeEach, describe, expect, it, vi } from "vitest"; +import { DEFAULT_SETTINGS } from "@/app/settings"; import type { HubLinkOptions } from "@/core/hub/link"; import type { LinkState } from "@/core/hub/status"; -import { DEFAULT_SETTINGS, type MdsyncSettings } from "@/core/settings/model"; +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"; diff --git a/packages/plugin/tests/core/cloudflare/relay-account.test.ts b/packages/plugin/tests/features/relay/deploy/relay-account.test.ts similarity index 100% rename from packages/plugin/tests/core/cloudflare/relay-account.test.ts rename to packages/plugin/tests/features/relay/deploy/relay-account.test.ts diff --git a/packages/plugin/tests/core/cloudflare/relay-deploy.test.ts b/packages/plugin/tests/features/relay/deploy/relay-deploy.test.ts similarity index 100% rename from packages/plugin/tests/core/cloudflare/relay-deploy.test.ts rename to packages/plugin/tests/features/relay/deploy/relay-deploy.test.ts diff --git a/packages/plugin/tests/features/relay/deploy/relay.test.ts b/packages/plugin/tests/features/relay/deploy/relay.test.ts index 4fd61a5c..765be0b2 100644 --- a/packages/plugin/tests/features/relay/deploy/relay.test.ts +++ b/packages/plugin/tests/features/relay/deploy/relay.test.ts @@ -7,7 +7,7 @@ import { } from "@tests/helpers/fake-cloudflare"; import { afterEach, describe, expect, it, vi } from "vitest"; import type { PluginHost } from "@/app/host"; -import { mergeSettings } from "@/core/settings/model"; +import { mergeSettings } from "@/app/settings"; import { activateRelay, deployOwnRelay, @@ -22,9 +22,9 @@ import { RELAY_VERSION, } from "@/features/relay/deploy/relay-account"; import { ERelayDeployStep } from "@/features/relay/deploy/relay-deploy"; -import { testRelay } from "@/features/storage/ui/connection-test"; +import { testRelay } from "@/features/relay/relay-test"; -vi.mock("@/features/storage/ui/connection-test", () => ({ +vi.mock("@/features/relay/relay-test", () => ({ testRelay: vi.fn(), })); diff --git a/packages/plugin/tests/features/storage/ui/connection-test.test.ts b/packages/plugin/tests/features/relay/relay-test.test.ts similarity index 98% rename from packages/plugin/tests/features/storage/ui/connection-test.test.ts rename to packages/plugin/tests/features/relay/relay-test.test.ts index 8b786dc5..2a020aff 100644 --- a/packages/plugin/tests/features/storage/ui/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 "@/features/storage/ui/connection-test"; +import { testRelay } from "@/features/relay/relay-test"; interface Reply { status: number; diff --git a/packages/plugin/tests/features/relay/ui/relay-section.test.ts b/packages/plugin/tests/features/relay/ui/relay-section.test.ts index 1d9ca787..c1797480 100644 --- a/packages/plugin/tests/features/relay/ui/relay-section.test.ts +++ b/packages/plugin/tests/features/relay/ui/relay-section.test.ts @@ -1,6 +1,7 @@ import type { Setting } from "obsidian"; import { beforeEach, describe, expect, it, vi } from "vitest"; 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", async (importOriginal) => ({ @@ -20,7 +21,8 @@ vi.mock("obsidian", async (importOriginal) => ({ } }, })); -vi.mock("@/core/settings/fields", () => ({ +vi.mock("@/core/settings/fields", async (importOriginal) => ({ + ...(await importOriginal>()), fieldRow: vi.fn(), checkRow: vi.fn(), group: (_heading: string, items: unknown[]) => ({ items }), @@ -63,7 +65,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/features/relay/update/relay-update.test.ts b/packages/plugin/tests/features/relay/update/relay-update.test.ts index f86a434c..c3922535 100644 --- a/packages/plugin/tests/features/relay/update/relay-update.test.ts +++ b/packages/plugin/tests/features/relay/update/relay-update.test.ts @@ -1,20 +1,20 @@ import type { Plugin } from "obsidian"; import { beforeEach, describe, expect, it, vi } from "vitest"; import type { PluginHost } from "@/app/host"; -import { mergeSettings } from "@/core/settings/model"; -import type { HubListener } from "@/features/relay/connection"; +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"; -import { testRelay } from "@/features/storage/ui/connection-test"; vi.mock("@/features/relay/update/relay-update-modal", () => ({ openRelayUpdateModal: vi.fn(async () => false), })); -vi.mock("@/features/storage/ui/connection-test", () => ({ +vi.mock("@/features/relay/relay-test", () => ({ testRelay: vi.fn(), })); vi.mock("@/features/relay/deploy/relay-account", async (original) => ({ diff --git a/packages/plugin/tests/features/setup/step-state.test.ts b/packages/plugin/tests/features/setup/step-state.test.ts index 98cf0bf6..cddd68c1 100644 --- a/packages/plugin/tests/features/setup/step-state.test.ts +++ b/packages/plugin/tests/features/setup/step-state.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from "vitest"; import type { PluginHost } from "@/app/host"; -import { type MdsyncSettings, mergeSettings } from "@/core/settings/model"; +import { mergeSettings } from "@/app/settings"; +import type { MdsyncSettings } from "@/core/settings/model"; import { ESetupPath, ESetupStep, diff --git a/packages/plugin/tests/features/setup/steps/relay-step.test.ts b/packages/plugin/tests/features/setup/steps/relay-step.test.ts index ca19d903..7f145e77 100644 --- a/packages/plugin/tests/features/setup/steps/relay-step.test.ts +++ b/packages/plugin/tests/features/setup/steps/relay-step.test.ts @@ -1,9 +1,9 @@ // @vitest-environment jsdom + import { installElementMethods } from "@tests/helpers/element-methods"; import { beforeEach, describe, expect, it, vi } from "vitest"; - import type { PluginHost } from "@/app/host"; -import { mergeSettings } from "@/core/settings/model"; +import { mergeSettings } from "@/app/settings"; import { activateRelay, deployOwnRelay, @@ -12,9 +12,9 @@ import { runningRelayDeploy, useRelay, } from "@/features/relay/deploy/deploy-flow"; +import { testRelay } from "@/features/relay/relay-test"; import { createRelayStep } from "@/features/setup/steps/relay-step"; import type { StepView, Wizard } from "@/features/setup/wizard"; -import { testRelay } from "@/features/storage/ui/connection-test"; installElementMethods(); @@ -74,7 +74,7 @@ vi.mock("obsidian", async (original) => { Setting, }; }); -vi.mock("@/features/storage/ui/connection-test", () => ({ +vi.mock("@/features/relay/relay-test", () => ({ testRelay: vi.fn(), })); vi.mock("@/features/storage/cloudflare/cloudflare-login", () => ({ diff --git a/packages/plugin/tests/features/source-control/timeline/timeline-actions.test.ts b/packages/plugin/tests/features/source-control/timeline/timeline-actions.test.ts index d7d516df..5ff97434 100644 --- a/packages/plugin/tests/features/source-control/timeline/timeline-actions.test.ts +++ b/packages/plugin/tests/features/source-control/timeline/timeline-actions.test.ts @@ -9,7 +9,7 @@ const { confirmRestore, notifyError, notifyInfo } = vi.hoisted(() => ({ notifyInfo: vi.fn(), })); -vi.mock("@/features/diff/restore-modal", () => ({ confirmRestore })); +vi.mock("@/features/diff/ui/restore-modal", () => ({ confirmRestore })); vi.mock("@/core/ui/notices", () => ({ notifyError, notifyInfo })); const before = { hash: "before", label: "Before push", size: 100 }; diff --git a/packages/plugin/tests/features/spaces/share-registration.test.ts b/packages/plugin/tests/features/spaces/share-registration.test.ts index 5e3a6ee8..098344f4 100644 --- a/packages/plugin/tests/features/spaces/share-registration.test.ts +++ b/packages/plugin/tests/features/spaces/share-registration.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import { DEFAULT_SETTINGS, type MdsyncSettings } from "@/core/settings/model"; +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"; diff --git a/packages/plugin/tests/features/spaces/space-access.test.ts b/packages/plugin/tests/features/spaces/space-access.test.ts index 42f1f6ee..1786e38c 100644 --- a/packages/plugin/tests/features/spaces/space-access.test.ts +++ b/packages/plugin/tests/features/spaces/space-access.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { DEFAULT_SETTINGS } from "@/app/settings"; import { deriveLiveKeys, type LiveKeys } from "@/core/crypto/live-keys"; -import { DEFAULT_SETTINGS, type MdsyncSettings } from "@/core/settings/model"; +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"; diff --git a/packages/plugin/tests/features/spaces/ui/shares-section.test.ts b/packages/plugin/tests/features/spaces/ui/shares-section.test.ts index 3185c8ca..edb1c22e 100644 --- a/packages/plugin/tests/features/spaces/ui/shares-section.test.ts +++ b/packages/plugin/tests/features/spaces/ui/shares-section.test.ts @@ -2,6 +2,7 @@ import type { SettingDefinitionPage } from "obsidian"; import { describe, expect, it, vi } from "vitest"; import type { FieldContext } from "@/core/settings/fields"; +import type { SpacesHost } from "@/features/spaces"; import { sharesSection } from "@/features/spaces/ui/shares-section"; vi.mock("@/core/settings/page", () => ({ imperativePage: 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/features/storage/backends/util.test.ts b/packages/plugin/tests/features/storage/backends/util.test.ts index 4c2b7116..5d993c63 100644 --- a/packages/plugin/tests/features/storage/backends/util.test.ts +++ b/packages/plugin/tests/features/storage/backends/util.test.ts @@ -1,11 +1,13 @@ 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, diff --git a/packages/plugin/tests/features/storage/cloudflare/r2-select.test.ts b/packages/plugin/tests/features/storage/cloudflare/r2-select.test.ts index 527101ea..a10d5305 100644 --- a/packages/plugin/tests/features/storage/cloudflare/r2-select.test.ts +++ b/packages/plugin/tests/features/storage/cloudflare/r2-select.test.ts @@ -6,10 +6,10 @@ import { } from "@tests/helpers/fake-cloudflare"; import { afterEach, describe, expect, it, vi } from "vitest"; import type { PluginHost } from "@/app/host"; +import { mergeSettings } from "@/app/settings"; import * as cloudflareModule from "@/core/cloudflare"; -import { mergeSettings } from "@/core/settings/model"; +import { StorageHttpError } from "@/core/shared/transport-errors"; import { defaultS3Config } from "@/features/storage/backends/s3"; -import { StorageHttpError } from "@/features/storage/backends/util"; import * as cloudflare from "@/features/storage/cloudflare/cloudflare-login"; import { R2NotEnabledError } from "@/features/storage/cloudflare/r2"; import { diff --git a/packages/plugin/tests/core/cloudflare/r2.test.ts b/packages/plugin/tests/features/storage/cloudflare/r2.test.ts similarity index 52% rename from packages/plugin/tests/core/cloudflare/r2.test.ts rename to packages/plugin/tests/features/storage/cloudflare/r2.test.ts index 2c21dbfa..e14e6885 100644 --- a/packages/plugin/tests/core/cloudflare/r2.test.ts +++ b/packages/plugin/tests/features/storage/cloudflare/r2.test.ts @@ -1,8 +1,6 @@ import { createHash } from "node:crypto"; 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"; import { ensureBucket, R2NotEnabledError, @@ -89,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/features/sync/auto-cycle.test.ts b/packages/plugin/tests/features/sync/auto-cycle.test.ts index 1c29bd29..9ace9215 100644 --- a/packages/plugin/tests/features/sync/auto-cycle.test.ts +++ b/packages/plugin/tests/features/sync/auto-cycle.test.ts @@ -1,11 +1,11 @@ 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 "@/core/crypto/cipher"; import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; import { OFFLINE_MESSAGE } from "@/core/shared/offline"; -import { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; import { SyncController } from "@/features/sync/controller"; import { pushPaths } from "@/features/sync/engine"; import { createScopePolicy } from "@/features/sync/scope/scope"; diff --git a/packages/plugin/tests/features/sync/automation/scheduler-interval.test.ts b/packages/plugin/tests/features/sync/automation/scheduler-interval.test.ts index 5e017ef7..9d68a169 100644 --- a/packages/plugin/tests/features/sync/automation/scheduler-interval.test.ts +++ b/packages/plugin/tests/features/sync/automation/scheduler-interval.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { DEFAULT_SETTINGS } from "@/app/settings"; -import { DEFAULT_SETTINGS } from "@/core/settings/model"; import { registerScheduler, SCHEDULER_HEARTBEAT_MS, diff --git a/packages/plugin/tests/features/sync/automation/scheduler-queued-push.test.ts b/packages/plugin/tests/features/sync/automation/scheduler-queued-push.test.ts index 27ffa3ef..254241b2 100644 --- a/packages/plugin/tests/features/sync/automation/scheduler-queued-push.test.ts +++ b/packages/plugin/tests/features/sync/automation/scheduler-queued-push.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { DEFAULT_SETTINGS } from "@/app/settings"; -import { DEFAULT_SETTINGS } from "@/core/settings/model"; import { registerScheduler, type SchedulerHost, diff --git a/packages/plugin/tests/features/sync/automation/scheduler-startup.test.ts b/packages/plugin/tests/features/sync/automation/scheduler-startup.test.ts index 071c5c5f..cae88eec 100644 --- a/packages/plugin/tests/features/sync/automation/scheduler-startup.test.ts +++ b/packages/plugin/tests/features/sync/automation/scheduler-startup.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { DEFAULT_SETTINGS } from "@/core/settings/model"; +import { DEFAULT_SETTINGS } from "@/app/settings"; import { registerScheduler, type SchedulerHost, diff --git a/packages/plugin/tests/features/sync/category-reset-roundtrip.test.ts b/packages/plugin/tests/features/sync/category-reset-roundtrip.test.ts index 83758373..10cd1c88 100644 --- a/packages/plugin/tests/features/sync/category-reset-roundtrip.test.ts +++ b/packages/plugin/tests/features/sync/category-reset-roundtrip.test.ts @@ -8,8 +8,8 @@ import { import { RevalidatingStorage } from "@tests/helpers/revalidating-storage"; import { useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; import { encryptJson } from "@/core/crypto/cipher"; -import { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; import { runCategoryResetFlow } from "@/features/sync/operations/config-reset"; import { EHunkPair, diff --git a/packages/plugin/tests/core/utils/file-concurrency.test.ts b/packages/plugin/tests/features/sync/changes/file-concurrency.test.ts similarity index 97% rename from packages/plugin/tests/core/utils/file-concurrency.test.ts rename to packages/plugin/tests/features/sync/changes/file-concurrency.test.ts index d1de04ef..54fd5bc3 100644 --- a/packages/plugin/tests/core/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 "@/core/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/engine-roundtrip.test.ts b/packages/plugin/tests/features/sync/engine-roundtrip.test.ts index 4bb5a3e2..6660a587 100644 --- a/packages/plugin/tests/features/sync/engine-roundtrip.test.ts +++ b/packages/plugin/tests/features/sync/engine-roundtrip.test.ts @@ -2,13 +2,11 @@ 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 { 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_MANIFEST_KEY, - REMOTE_OBJECTS_PREFIX, -} from "@/features/sync/constants"; +import { REMOTE_OBJECTS_PREFIX } from "@/features/sync/constants"; import { compare, type EngineDependencies, diff --git a/packages/plugin/tests/features/sync/hunks/merge-model.test.ts b/packages/plugin/tests/features/sync/hunks/merge-model.test.ts index 5d7ab813..fac3b5d9 100644 --- a/packages/plugin/tests/features/sync/hunks/merge-model.test.ts +++ b/packages/plugin/tests/features/sync/hunks/merge-model.test.ts @@ -1,36 +1,10 @@ -import { Text } from "@codemirror/state"; import { describe, expect, it } from "vitest"; import { - applyPlan, buildMergeSession, countUnresolved, - type MergeChange, - revertPlan, - type StatusPatch, - snapToLines, threeWayRegions, } from "@/features/sync/hunks/merge-model"; -const doc = (text: string) => Text.of(text.split("\n")); - -function conflictAt( - from: number, - to: number, - status: StatusPatch = {}, -): MergeChange { - return { - index: 0, - conflict: true, - base: [1, 2], - endsAtEof: true, - local: [1, 2], - remote: [1, 2], - result: { from, to }, - taken: {}, - status: { local: "open", remote: "open", ...status }, - }; -} - describe("threeWayRegions", () => { it("gives every region all three ranges; the unchanged side owns the base lines", () => { const regions = threeWayRegions( @@ -155,168 +129,3 @@ describe("buildMergeSession", () => { 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", [ - "L1", - "L2", - ]); - expect(plan).toEqual({ - from: 2, - to: 4, - insert: "L1\nL2\n", - result: { from: 2, to: 8 }, - taken: { local: { from: 2, to: 8 } }, - }); - }); - - it("appends the second side below the first, so click order is line order", () => { - const first = conflictAt(2, 8, { local: "applied" }); - const plan = applyPlan(doc("a\nL1\nL2\nc"), first, "remote", ["R"]); - expect(plan).toEqual({ - from: 8, - to: 8, - insert: "R\n", - result: { from: 2, to: 10 }, - taken: { remote: { from: 8, to: 10 } }, - }); - }); - - it("replaces rather than appends when the other side was ignored", () => { - const change = conflictAt(2, 4, { local: "ignored" }); - const plan = applyPlan(doc("a\nb\nc"), change, "remote", ["R"]); - expect(plan).toEqual({ - from: 2, - to: 4, - insert: "R\n", - result: { from: 2, to: 4 }, - taken: { remote: { from: 2, to: 4 } }, - }); - }); - - it("takes the newline before the last line along when deleting it", () => { - const plan = applyPlan(doc("a\nb"), conflictAt(2, 3), "local", []); - expect(plan).toEqual({ - from: 1, - to: 3, - insert: "", - result: { from: 1, to: 1 }, - taken: { local: { from: 1, to: 1 } }, - }); - }); - - it("inserts after a last line that has no newline", () => { - const plan = applyPlan(doc("a"), conflictAt(1, 1), "local", ["L"]); - expect(plan).toEqual({ - from: 1, - to: 1, - insert: "\nL", - result: { from: 2, to: 3 }, - taken: { local: { from: 2, to: 3 } }, - }); - }); - - it("deletes the entire document if it is replaced with empty", () => { - const plan = applyPlan(doc("a\nb\nc"), conflictAt(0, 5), "local", []); - expect(plan).toEqual({ - from: 0, - to: 5, - insert: "", - result: { from: 0, to: 0 }, - taken: { local: { from: 0, to: 0 } }, - }); - }); - - it("keeps the replaced span whole-line even after the span drifted mid-line", () => { - const plan = applyPlan(doc("a\nbcd\ne"), conflictAt(3, 4), "local", ["L"]); - expect(plan).toEqual({ - from: 2, - to: 6, - insert: "L\n", - result: { from: 2, to: 4 }, - taken: { local: { from: 2, to: 4 } }, - }); - }); -}); - -describe("revertPlan", () => { - it("reverts the chosen side back to base lines when the other side is open", () => { - const change = conflictAt(2, 8, { local: "applied" }); - change.taken = { local: { from: 2, to: 8 } }; - const plan = revertPlan(doc("a\nL1\nL2\nc"), change, "local", ["b"]); - expect(plan).toEqual({ - from: 2, - to: 8, - insert: "b\n", - result: { from: 2, to: 4 }, - taken: { local: null }, - }); - }); - - it("removes only the chosen side's lines when both sides are applied", () => { - const change = conflictAt(2, 10, { - local: "applied", - remote: "applied", - }); - change.taken = { local: { from: 2, to: 8 }, remote: { from: 8, to: 10 } }; - const plan = revertPlan(doc("a\nL1\nL2\nR\nc"), change, "local", ["b"]); - expect(plan).toEqual({ - from: 2, - to: 8, - insert: "", - taken: { local: null }, - }); - }); - - it("keeps the shared text when reverting one side of an identical change", () => { - const change: MergeChange = { - index: 0, - conflict: false, - base: [1, 2], - endsAtEof: false, - local: [1, 2], - remote: [1, 2], - result: { from: 2, to: 4 }, - taken: { local: { from: 2, to: 4 }, remote: { from: 2, to: 4 } }, - status: { local: "applied", remote: "applied" }, - }; - const plan = revertPlan(doc("a\nB\nc"), change, "local", ["b"]); - expect(plan).toEqual({ - from: 2, - to: 2, - insert: "", - taken: { local: null }, - }); - }); -}); - -describe("snapToLines", () => { - it("widens a span to whole lines", () => { - expect(snapToLines(doc("ab\ncd\nef"), { from: 1, to: 4 })).toEqual({ - from: 0, - to: 6, - }); - }); - - it("keeps an empty span at a line start where it is", () => { - expect(snapToLines(doc("ab\ncd"), { from: 3, to: 3 })).toEqual({ - from: 3, - to: 3, - }); - }); - - it("keeps an empty span after a last line without newline", () => { - expect(snapToLines(doc("ab\ncd"), { from: 5, to: 5 })).toEqual({ - from: 5, - to: 5, - }); - }); - - it("moves an empty mid-line span to the next line start", () => { - expect(snapToLines(doc("ab\ncd\nef"), { from: 1, to: 1 })).toEqual({ - from: 3, - to: 3, - }); - }); -}); diff --git a/packages/plugin/tests/features/sync/operations/lost-push.test.ts b/packages/plugin/tests/features/sync/operations/lost-push.test.ts index c6cf6a7c..856d4d36 100644 --- a/packages/plugin/tests/features/sync/operations/lost-push.test.ts +++ b/packages/plugin/tests/features/sync/operations/lost-push.test.ts @@ -1,8 +1,8 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { TestSession, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; import { encryptJson } from "@/core/crypto/cipher"; -import { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; import { pushPathsOp } from "@/features/sync/operations/push"; import { ConcurrentPushError, diff --git a/packages/plugin/tests/features/sync/remote/manifest-guard.test.ts b/packages/plugin/tests/features/sync/remote/manifest-guard.test.ts index af137934..44581d94 100644 --- a/packages/plugin/tests/features/sync/remote/manifest-guard.test.ts +++ b/packages/plugin/tests/features/sync/remote/manifest-guard.test.ts @@ -8,12 +8,12 @@ import { it, vi, } from "vitest"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; import { deriveKey, type EncryptionKey, encryptJson, } from "@/core/crypto/cipher"; -import { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; import { ConcurrentPushError, fetchRemoteManifest, diff --git a/packages/plugin/tests/features/sync/remote/manifest-revalidate.test.ts b/packages/plugin/tests/features/sync/remote/manifest-revalidate.test.ts index 59f09db5..19165794 100644 --- a/packages/plugin/tests/features/sync/remote/manifest-revalidate.test.ts +++ b/packages/plugin/tests/features/sync/remote/manifest-revalidate.test.ts @@ -1,13 +1,13 @@ 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 "@/core/crypto/cipher"; -import { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; import { advanceBaselineForPaths } from "@/features/sync/remote/baseline"; import { ConcurrentPushError, diff --git a/packages/plugin/tests/features/sync/remote/passphrase-manager.test.ts b/packages/plugin/tests/features/sync/remote/passphrase-manager.test.ts index 08985ba0..13eb309b 100644 --- a/packages/plugin/tests/features/sync/remote/passphrase-manager.test.ts +++ b/packages/plugin/tests/features/sync/remote/passphrase-manager.test.ts @@ -1,11 +1,13 @@ import type { DataAdapter } from "obsidian"; import { beforeEach, describe, expect, it, vi } from "vitest"; +import { DEFAULT_SETTINGS } from "@/app/settings"; import type { DeviceKey } from "@/core/crypto/device-key"; import { + clearCachedPassphrase, loadCachedPassphrase, saveCachedPassphrase, } from "@/core/crypto/passphrase-cache"; -import { DEFAULT_SETTINGS, type MdsyncSettings } from "@/core/settings/model"; +import type { MdsyncSettings } from "@/core/settings/model"; import { defaultS3Config } from "@/features/storage/backends/s3"; import type { ObjectStorage } from "@/features/storage/types"; import { @@ -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/features/sync/remote/passphrase-storage.test.ts b/packages/plugin/tests/features/sync/remote/passphrase-storage.test.ts index b912f8e3..c14b598b 100644 --- a/packages/plugin/tests/features/sync/remote/passphrase-storage.test.ts +++ b/packages/plugin/tests/features/sync/remote/passphrase-storage.test.ts @@ -1,7 +1,7 @@ import type { DataAdapter } from "obsidian"; import { describe, expect, it, vi } from "vitest"; +import { DEFAULT_SETTINGS } from "@/app/settings"; import type { DeviceKey } from "@/core/crypto/device-key"; -import { DEFAULT_SETTINGS } from "@/core/settings/model"; import { PassphraseManager } from "@/features/sync/remote/passphrase-manager"; const created = vi.hoisted(() => ({ changed: null as (() => void) | null })); diff --git a/packages/plugin/tests/features/sync/remote/reset.test.ts b/packages/plugin/tests/features/sync/remote/reset.test.ts index 9e56e30f..02bf9402 100644 --- a/packages/plugin/tests/features/sync/remote/reset.test.ts +++ b/packages/plugin/tests/features/sync/remote/reset.test.ts @@ -1,10 +1,10 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { beforeAll, describe, expect, it } 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 "@/features/sync/constants"; diff --git a/packages/plugin/tests/features/sync/remote/space-roundtrip.test.ts b/packages/plugin/tests/features/sync/remote/space-roundtrip.test.ts index 3b4dfd52..fc076680 100644 --- a/packages/plugin/tests/features/sync/remote/space-roundtrip.test.ts +++ b/packages/plugin/tests/features/sync/remote/space-roundtrip.test.ts @@ -1,7 +1,7 @@ import { TestSession, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; import { decryptJson } from "@/core/crypto/cipher"; -import { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; import { compare, pushPaths } from "@/features/sync/engine"; import { advanceSessionAfterPush } from "@/features/sync/remote/baseline"; import { diff --git a/packages/plugin/tests/features/sync/remote/spaces.test.ts b/packages/plugin/tests/features/sync/remote/spaces.test.ts index e9a6ba42..248e4096 100644 --- a/packages/plugin/tests/features/sync/remote/spaces.test.ts +++ b/packages/plugin/tests/features/sync/remote/spaces.test.ts @@ -1,6 +1,7 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; import { beforeAll, describe, expect, it, vi } from "vitest"; +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; import { decryptJson, deriveKey, @@ -8,7 +9,6 @@ import { } from "@/core/crypto/cipher"; import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; import type { VaultIndex } from "@/core/vault/file-index"; -import { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; import { SyncController } from "@/features/sync/controller"; import { nestedRoots, diff --git a/packages/plugin/tests/features/sync/runtime/operation-runner.test.ts b/packages/plugin/tests/features/sync/runtime/operation-runner.test.ts index 1124f16c..82708853 100644 --- a/packages/plugin/tests/features/sync/runtime/operation-runner.test.ts +++ b/packages/plugin/tests/features/sync/runtime/operation-runner.test.ts @@ -4,7 +4,7 @@ import { pairedSessions, useEncryptionKey } from "@tests/helpers/session"; import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest"; import { ESyncLogOperation } from "@/core/logs/store"; import { OFFLINE_MESSAGE } from "@/core/shared/offline"; -import { StorageHttpError } from "@/features/storage/backends/util"; +import { StorageHttpError } from "@/core/shared/transport-errors"; import { ShareRefusedError, StorageRequestError, diff --git a/packages/plugin/tests/features/sync/runtime/saved-refresh.test.ts b/packages/plugin/tests/features/sync/runtime/saved-refresh.test.ts index 5735610c..c4fac8a6 100644 --- a/packages/plugin/tests/features/sync/runtime/saved-refresh.test.ts +++ b/packages/plugin/tests/features/sync/runtime/saved-refresh.test.ts @@ -6,7 +6,7 @@ import { } from "@tests/helpers/session"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { LocalSession } from "@/app/session-factory"; +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"; diff --git a/packages/plugin/tests/features/sync/transfer-memory.test.ts b/packages/plugin/tests/features/sync/transfer-memory.test.ts index ff7527f3..e6f3bb21 100644 --- a/packages/plugin/tests/features/sync/transfer-memory.test.ts +++ b/packages/plugin/tests/features/sync/transfer-memory.test.ts @@ -1,7 +1,7 @@ import { pairedSessions, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it, vi } from "vitest"; -import { LARGE_FILE_BYTES } from "@/core/utils/file-concurrency"; 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/features/settings/sections/security-section.test.ts b/packages/plugin/tests/features/sync/ui/encryption-section.test.ts similarity index 93% rename from packages/plugin/tests/features/settings/sections/security-section.test.ts rename to packages/plugin/tests/features/sync/ui/encryption-section.test.ts index f3b1223a..038da081 100644 --- a/packages/plugin/tests/features/settings/sections/security-section.test.ts +++ b/packages/plugin/tests/features/sync/ui/encryption-section.test.ts @@ -1,18 +1,15 @@ import { Setting } from "obsidian"; import { beforeEach, describe, expect, it, vi } from "vitest"; - import type { PluginHost } from "@/app/host"; -import { isStorageConfigured } from "@/core/settings/model"; import { askNewPassphrase } from "@/core/ui/modals/passphrase-modal"; import { notifyInfo, reportError } from "@/core/ui/notices"; -import { securitySection } from "@/features/settings/sections/security"; +import { isStorageConfigured } from "@/features/storage"; +import { encryptionSection } from "@/features/sync/ui/encryption-section"; -vi.mock("@/core/settings/model", () => ({ +vi.mock("@/features/storage/settings", async (importOriginal) => ({ + ...(await importOriginal>()), isStorageConfigured: vi.fn(() => true), })); -vi.mock("@/core/crypto/passphrase-cache", () => ({ - clearCachedPassphrase: vi.fn(), -})); vi.mock("@/core/ui/modals/passphrase-modal", () => ({ askNewPassphrase: vi.fn(), })); @@ -21,7 +18,8 @@ vi.mock("@/core/ui/notices", () => ({ notifyError: vi.fn(), reportError: vi.fn(), })); -vi.mock("obsidian", () => ({ +vi.mock("obsidian", async (importOriginal) => ({ + ...(await importOriginal>()), Setting: class { name = ""; desc = ""; @@ -83,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/upload-listing.test.ts b/packages/plugin/tests/features/sync/upload-listing.test.ts index 83838bb9..38493d27 100644 --- a/packages/plugin/tests/features/sync/upload-listing.test.ts +++ b/packages/plugin/tests/features/sync/upload-listing.test.ts @@ -1,12 +1,10 @@ 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 { REMOTE_MANIFEST_KEY } from "@/core/constants"; import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; -import { - REMOTE_MANIFEST_KEY, - REMOTE_OBJECTS_PREFIX, -} from "@/features/sync/constants"; +import { REMOTE_OBJECTS_PREFIX } from "@/features/sync/constants"; import { compare, type EngineDependencies, diff --git a/packages/plugin/tests/features/transfer/transfer-controller.test.ts b/packages/plugin/tests/features/transfer/transfer-controller.test.ts index e0abd06e..f9056f76 100644 --- a/packages/plugin/tests/features/transfer/transfer-controller.test.ts +++ b/packages/plugin/tests/features/transfer/transfer-controller.test.ts @@ -2,7 +2,8 @@ import { deviceKey, FakeSecretStorage } from "@tests/helpers/device-key"; import { InMemoryAdapter } from "@tests/helpers/in-memory-adapter"; import type { App } from "obsidian"; import { describe, expect, it, vi } from "vitest"; -import { type MdsyncSettings, mergeSettings } from "@/core/settings/model"; +import { mergeSettings } from "@/app/settings"; +import type { MdsyncSettings } from "@/core/settings/model"; import type { LinkRecord } from "@/features/links/record"; import { defaultS3Config } from "@/features/storage/backends/s3"; import { PassphraseManager } from "@/features/sync/remote/passphrase-manager"; diff --git a/packages/plugin/tests/features/transfer/transfer.test.ts b/packages/plugin/tests/features/transfer/transfer.test.ts index 34cb95ff..18eff864 100644 --- a/packages/plugin/tests/features/transfer/transfer.test.ts +++ b/packages/plugin/tests/features/transfer/transfer.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; +import { DEFAULT_SETTINGS } from "@/app/settings"; import { sealLink } from "@/core/crypto/sealed-link"; -import { DEFAULT_SETTINGS, type MdsyncSettings } from "@/core/settings/model"; +import 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"; diff --git a/packages/plugin/tests/helpers/explorer-host.ts b/packages/plugin/tests/helpers/explorer-host.ts index 1c763a8f..27042515 100644 --- a/packages/plugin/tests/helpers/explorer-host.ts +++ b/packages/plugin/tests/helpers/explorer-host.ts @@ -1,5 +1,5 @@ import type { PluginHost } from "@/app/host"; -import { DEFAULT_SETTINGS } from "@/core/settings/model"; +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"; diff --git a/packages/plugin/tests/helpers/live-hub.ts b/packages/plugin/tests/helpers/live-hub.ts index a91ac0c4..caca8981 100644 --- a/packages/plugin/tests/helpers/live-hub.ts +++ b/packages/plugin/tests/helpers/live-hub.ts @@ -8,12 +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 "@/features/relay/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/manifest.ts b/packages/plugin/tests/helpers/manifest.ts index 1962a275..d07796c8 100644 --- a/packages/plugin/tests/helpers/manifest.ts +++ b/packages/plugin/tests/helpers/manifest.ts @@ -1,6 +1,6 @@ +import { REMOTE_MANIFEST_KEY } from "@/core/constants"; import { type EncryptionKey, encryptJson } from "@/core/crypto/cipher"; import type { ObjectStorage } from "@/features/storage/types"; -import { REMOTE_MANIFEST_KEY } from "@/features/sync/constants"; import type { Manifest } from "@/features/sync/types"; export async function publishManifest( diff --git a/packages/plugin/tests/helpers/presence-relay.ts b/packages/plugin/tests/helpers/presence-relay.ts index 62507547..c4715f5d 100644 --- a/packages/plugin/tests/helpers/presence-relay.ts +++ b/packages/plugin/tests/helpers/presence-relay.ts @@ -1,8 +1,7 @@ import { EFrame, OWNER, type ServerFrame } from "@mdsync/protocol"; - 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 { SpaceFrame, SpaceListener } from "@/features/relay/connection"; import { type Space, VAULT_SPACE } from "@/features/sync/remote/space"; /** Who the hub knows a socket as on a space's channel. */ diff --git a/packages/protocol/README.md b/packages/protocol/README.md index 3604d68c..8776eb8c 100644 --- a/packages/protocol/README.md +++ b/packages/protocol/README.md @@ -4,6 +4,7 @@ | File | Defines | |---|---| +| `packages/protocol/src/admin.ts` | `ADMIN_HEADER`, the request header that carries the relay secret | | `packages/protocol/src/frames.ts` | hub paths and query params, keepalive constants, `EFrame`, `ERefusal`, `ClientFrame` / `ServerFrame`, limits, `OWNER`, `CHANNEL_DOC` | | `packages/protocol/src/codec.ts` | `encodeClient` / `decodeClient`, `encodeServer` / `decodeServer`, `withSlot` | | `packages/protocol/src/bytes.ts` | `Writer` / `Reader` (u8, u32, length-prefixed text and blocks), base64url and hex | diff --git a/packages/protocol/src/admin.ts b/packages/protocol/src/admin.ts new file mode 100644 index 00000000..968318fd --- /dev/null +++ b/packages/protocol/src/admin.ts @@ -0,0 +1,2 @@ +/** Carries the relay secret on admin requests. */ +export const ADMIN_HEADER = "X-Mdsync-Admin"; diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.ts index e9fc1f6d..d25fb01b 100644 --- a/packages/protocol/src/index.ts +++ b/packages/protocol/src/index.ts @@ -1,3 +1,4 @@ +export { ADMIN_HEADER } from "./admin"; export { fromBase64Url, toBase64Url, toHex } from "./bytes"; export * from "./codec"; export * from "./frames"; diff --git a/packages/relay/src/index.ts b/packages/relay/src/index.ts index 469ae0f6..069ea694 100644 --- a/packages/relay/src/index.ts +++ b/packages/relay/src/index.ts @@ -1,3 +1,4 @@ +import { ADMIN_HEADER } from "@mdsync/protocol"; import { type GoogleOAuthEnv, handleAuthCallback, @@ -9,7 +10,7 @@ import { Link } from "./link/durable-object"; import { handleLinkRequest } from "./link/routes"; import { handleShellRequest, type ShellEnv } from "./link/shell"; import type { LinkEnv } from "./link/stub"; -import { ADMIN_HEADER, isAdmin } from "./secret"; +import { isAdmin } from "./secret"; import { handleShareRequest } from "./share/broker"; import type { ShareEnv } from "./share/kv"; diff --git a/packages/relay/src/secret.ts b/packages/relay/src/secret.ts index 4cd6a277..c0365bdf 100644 --- a/packages/relay/src/secret.ts +++ b/packages/relay/src/secret.ts @@ -1,8 +1,6 @@ /** The one deployment secret: admin auth for shares and the root of every hub channel grant. */ -import { toHex } from "@mdsync/protocol"; - -export const ADMIN_HEADER = "X-Mdsync-Admin"; +import { ADMIN_HEADER, toHex } from "@mdsync/protocol"; export interface SecretEnv { RELAY_SECRET?: string; diff --git a/tests/e2e/README.md b/tests/e2e/README.md index 7399716a..95d8684b 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -5,7 +5,9 @@ Scenarios run real processes (Obsidian, `wrangler dev`, headless Chrome, in-memo ## Prerequisites - **Obsidian** at the default Windows path, or set `OBSIDIAN_EXE`. On macOS: `OBSIDIAN_EXE=/Applications/Obsidian.app/Contents/MacOS/Obsidian pnpm e2e:live`. Each scenario starts a throwaway Obsidian (own `--user-data-dir`, temp vault, the trust modal clicked) with the built `packages/plugin/main.js`, `packages/plugin/styles.css` and `manifest.json`. -- **Ports** 8799 (relay), 8801 (WebDAV), 8802 (S3), 9223 and 9224 (CDP) must be free; a few scenarios use their own (listed below). A run killed midway can leave `wrangler dev` holding 8799: kill that tree. +- **Headless Chrome** for `links-obsidian` (`links` falls back to an installed Chrome): `pnpm exec playwright-core install chromium-headless-shell` once. +- Each Obsidian turns native menus off once the plugin loads: macOS defaults to them, and they never reach the DOM the scenarios read. +- **Ports** 8799 (relay), 8801 (WebDAV), 8802 (S3), 9223 and 9224 (CDP) must be free; a few scenarios use their own (listed below). A run killed midway can leave `wrangler dev` holding 8799 or an Obsidian holding its CDP port, and the next run attaches to the stale one: 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. - Several Obsidians need distinct CDP ports. On Windows they run on a desktop of their own (`tests/e2e/hidden-desktop.ps1`) and never take focus; `E2E_VISIBLE=1` shows them. `E2E_SHOTS=1` saves screenshots under `artifacts/e2e-shots/`. diff --git a/tests/e2e/live-drawing.ts b/tests/e2e/live-drawing.ts index ebb6a057..1772329f 100644 --- a/tests/e2e/live-drawing.ts +++ b/tests/e2e/live-drawing.ts @@ -4,7 +4,7 @@ */ import { excalidrawPlugin } from "./excalidraw"; -import { check, runScenario, sleep } from "./harness"; +import { check, poll, runScenario, sleep } from "./harness"; import { launchObsidian, type Obsidian } from "./obsidian"; import { type Relay, startRelay } from "./relay"; import { startWebDav } from "./webdav"; @@ -409,9 +409,18 @@ async function openDrawing( () => Boolean(app.plugins.plugins["obsidian-excalidraw-plugin"]), Boolean, ); - await device.evaluate(async (path) => { - await app.workspace.getLeaf(false).openFile(app.vault.getFileByPath(path)); - }, path); + // Excalidraw turns a markdown open into a drawing only once fully loaded, a moment after it appears. + await poll("drawing opened", () => + device.evaluate(async (path) => { + const leaf = app.workspace.getLeaf(false); + const { view } = leaf; + if (view.getViewType() === "excalidraw" && view.file?.path === path) { + return true; + } + await leaf.openFile(app.vault.getFileByPath(path)); + return undefined; + }, path), + ); try { await device.waitFor( "drawing bound", diff --git a/tests/e2e/obsidian.ts b/tests/e2e/obsidian.ts index 06f37bdc..b1d5827a 100644 --- a/tests/e2e/obsidian.ts +++ b/tests/e2e/obsidian.ts @@ -140,6 +140,8 @@ export async function launchObsidian(options: { ); return loaded || undefined; }); + // macOS defaults to native menus, which never reach the DOM the scenarios read. + await page.evaluate(() => app.vault.setConfig("nativeMenus", false)); return obsidian; } catch (error) { await stopProcess(); @@ -147,7 +149,10 @@ export async function launchObsidian(options: { } } -declare const app: { plugins: { plugins: Record } }; +declare const app: { + plugins: { plugins: Record }; + vault: { setConfig(key: string, value: unknown): void }; +}; async function attach(port: number) { const browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`); From ebb231671cb9b51d2fab3d517598c0e1d7d9ef24 Mon Sep 17 00:00:00 2001 From: kitbyte Date: Tue, 27 Oct 2026 20:18:51 +0200 Subject: [PATCH 03/26] perf(sync): gzip file blobs when smaller --- packages/plugin/src/core/crypto/cipher.ts | 65 +++++++++++++---- packages/plugin/src/core/crypto/constants.ts | 5 ++ packages/plugin/src/core/crypto/index.ts | 1 + packages/plugin/src/features/sync/README.md | 2 + packages/plugin/src/features/sync/engine.ts | 13 +++- .../tests/core/crypto/json-envelope.test.ts | 71 +++++++++++++++++-- 6 files changed, 136 insertions(+), 21 deletions(-) diff --git a/packages/plugin/src/core/crypto/cipher.ts b/packages/plugin/src/core/crypto/cipher.ts index 79546439..19774a4f 100644 --- a/packages/plugin/src/core/crypto/cipher.ts +++ b/packages/plugin/src/core/crypto/cipher.ts @@ -10,6 +10,8 @@ import { BLOB_VERSION_GZIP, GZIP_LENGTH_BYTES, GZIP_PAD_BYTES, + GZIP_SAMPLE_BYTES, + GZIP_SAMPLE_MAX_RATIO, IV_BYTES, JSON_GZIP_MIN_BYTES, KDF_ITERATIONS, @@ -148,10 +150,15 @@ export async function decryptBytes( return inflateBytes(unpad(plaintext), 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; @@ -175,30 +182,60 @@ 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 async function decryptJson( key: EncryptionKey, blob: Uint8Array, diff --git a/packages/plugin/src/core/crypto/constants.ts b/packages/plugin/src/core/crypto/constants.ts index f992bff5..97bc18bb 100644 --- a/packages/plugin/src/core/crypto/constants.ts +++ b/packages/plugin/src/core/crypto/constants.ts @@ -23,6 +23,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/core/crypto/index.ts b/packages/plugin/src/core/crypto/index.ts index d2f5daf3..c6971ade 100644 --- a/packages/plugin/src/core/crypto/index.ts +++ b/packages/plugin/src/core/crypto/index.ts @@ -4,6 +4,7 @@ export { deriveKey, type EncryptionKey, encryptBytes, + encryptCompressible, encryptJson, importAesKey, randomBytes, diff --git a/packages/plugin/src/features/sync/README.md b/packages/plugin/src/features/sync/README.md index 64bfdb2b..51edbf81 100644 --- a/packages/plugin/src/features/sync/README.md +++ b/packages/plugin/src/features/sync/README.md @@ -46,6 +46,8 @@ Accepted limit: a backend hiding our own write past the retries (WebDAV behind a 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: 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 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. + ## 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`). diff --git a/packages/plugin/src/features/sync/engine.ts b/packages/plugin/src/features/sync/engine.ts index b6305215..b3459257 100644 --- a/packages/plugin/src/features/sync/engine.ts +++ b/packages/plugin/src/features/sync/engine.ts @@ -1,6 +1,10 @@ import type { DataAdapter } from "obsidian"; import { DEFAULT_CONCURRENCY } from "@/core/constants"; -import { type EncryptionKey, encryptBytes, sha256Hex } from "@/core/crypto"; +import { + type EncryptionKey, + encryptCompressible, + sha256Hex, +} from "@/core/crypto"; import { sceneOfBytes } from "@/core/drawing"; import { reportWarning } from "@/core/shared"; import type { VaultIndex } from "@/core/vault"; @@ -211,7 +215,10 @@ export async function storeObject( ) { return hash; } - await deps.storage.put(objectKey(hash), await encryptBytes(deps.key, bytes)); + await deps.storage.put( + objectKey(hash), + await encryptCompressible(deps.key, bytes), + ); rememberUpload(deps.storage, hash); return hash; } @@ -343,7 +350,7 @@ async function uploadObject( if (verifyHash !== entry.hash) { throw new Error(`Hash mismatch while uploading ${entry.path}`); } - const blob = await encryptBytes(deps.key, plaintext); + const blob = await encryptCompressible(deps.key, plaintext); await deps.storage.put(objectKey(entry.hash), blob); rememberUpload(deps.storage, entry.hash); } diff --git a/packages/plugin/tests/core/crypto/json-envelope.test.ts b/packages/plugin/tests/core/crypto/json-envelope.test.ts index 645d212b..6ee68512 100644 --- a/packages/plugin/tests/core/crypto/json-envelope.test.ts +++ b/packages/plugin/tests/core/crypto/json-envelope.test.ts @@ -1,16 +1,19 @@ -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 "@/core/crypto/cipher"; import { BLOB_VERSION, BLOB_VERSION_GZIP, GZIP_PAD_BYTES, + GZIP_SAMPLE_BYTES, IV_BYTES, JSON_GZIP_MIN_BYTES, } from "@/core/crypto/constants"; @@ -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); + }); +}); From 438ad096e1856d95e22bfd173347f84a588983fb Mon Sep 17 00:00:00 2001 From: kitbyte Date: Tue, 27 Oct 2026 20:41:19 +0200 Subject: [PATCH 04/26] feat(history): remote history records, two-phase GC, Keep history for --- .claude/rules/history.md | 51 +- .claude/rules/settings-setup.md | 4 +- .claude/rules/spaces.md | 2 +- .claude/rules/sync-integrity.md | 8 +- README.md | 9 +- packages/plugin/src/app/session-factory.ts | 3 +- packages/plugin/src/core/constants.ts | 13 +- packages/plugin/src/core/settings/index.ts | 1 + packages/plugin/src/core/settings/model.ts | 19 +- .../features/settings/sections/automation.ts | 27 +- .../source-control/history/history-tab.ts | 2 +- .../source-control/timeline/timeline-tab.ts | 2 +- .../source-control/trash/trash-rows.ts | 39 +- .../source-control/trash/trash-tab.ts | 5 +- packages/plugin/src/features/spaces/README.md | 2 +- packages/plugin/src/features/storage/index.ts | 1 + packages/plugin/src/features/sync/README.md | 16 +- .../plugin/src/features/sync/constants.ts | 8 +- .../plugin/src/features/sync/controller.ts | 7 +- .../src/features/sync/history/changes.ts | 80 +- .../plugin/src/features/sync/history/gc.ts | 371 ++------ .../src/features/sync/history/legacy.ts | 43 + .../features/sync/history/model/activity.ts | 42 + .../src/features/sync/history/model/cover.ts | 243 ++++++ .../features/sync/history/model/periods.ts | 99 +++ .../src/features/sync/history/model/plan.ts | 241 ++++++ .../features/sync/history/model/records.ts | 82 ++ .../src/features/sync/history/model/types.ts | 50 ++ .../plugin/src/features/sync/history/pins.ts | 177 ++++ .../src/features/sync/history/publish.ts | 119 ++- .../plugin/src/features/sync/history/query.ts | 470 +++++------ .../src/features/sync/history/remote.ts | 269 ++++++ .../src/features/sync/history/replay.ts | 35 +- .../plugin/src/features/sync/history/store.ts | 242 ------ .../plugin/src/features/sync/history/sweep.ts | 183 ++++ .../plugin/src/features/sync/history/types.ts | 37 +- packages/plugin/src/features/sync/index.ts | 1 - .../features/sync/operations/config-reset.ts | 3 - .../src/features/sync/remote/manifest.ts | 2 +- .../plugin/src/features/sync/remote/reset.ts | 7 +- .../src/features/sync/remote/space-paths.ts | 44 +- .../features/sync/runtime/history-service.ts | 53 +- .../sync/runtime/maintenance-service.ts | 82 +- .../src/features/sync/runtime/maintenance.ts | 145 +--- .../features/sync/runtime/operation-runner.ts | 3 + .../plugin/src/features/transfer/transfer.ts | 2 +- .../plugin/tests/app/settings/index.test.ts | 20 +- .../timeline/timeline-rows.test.ts | 2 +- .../source-control/trash/trash-rows.test.ts | 115 ++- .../sync/category-reset-roundtrip.test.ts | 3 +- .../features/sync/engine-roundtrip.test.ts | 67 +- .../features/sync/history/compose.test.ts | 170 ++++ .../tests/features/sync/history/gc.test.ts | 293 +++++++ .../sync/history/history-deleted.test.ts | 540 +++++++----- .../features/sync/history/history-gc.test.ts | 789 ------------------ ...tory-log.test.ts => history-query.test.ts} | 366 ++++---- .../sync/history/history-read-cache.test.ts | 106 --- .../features/sync/history/legacy.test.ts | 67 ++ .../sync/history/model/activity.test.ts | 71 ++ .../features/sync/history/model/cover.test.ts | 201 +++++ .../sync/history/model/periods.test.ts | 80 ++ .../features/sync/history/model/plan.test.ts | 259 ++++++ .../sync/history/model/records.test.ts | 83 ++ .../tests/features/sync/history/pins.test.ts | 159 ++++ .../features/sync/history/publish.test.ts | 151 ++++ .../features/sync/history/remote.test.ts | 109 +++ .../sync/identity/manifest-device.test.ts | 15 + .../features/sync/remote/foreign.test.ts | 52 +- .../tests/features/sync/remote/reset.test.ts | 3 + .../features/sync/remote/space-paths.test.ts | 73 +- .../tests/features/sync/remote/spaces.test.ts | 2 +- .../runtime/history-service-scope.test.ts | 2 +- .../sync/runtime/maintenance-service.test.ts | 115 +++ .../features/sync/runtime/maintenance.test.ts | 215 +++-- .../sync/runtime/operation-runner.test.ts | 8 +- .../sync/runtime/saved-refresh.test.ts | 2 + .../tests/features/transfer/transfer.test.ts | 12 +- packages/plugin/tests/helpers/history-sim.ts | 181 ++++ packages/plugin/tests/helpers/history.ts | 83 ++ 79 files changed, 5007 insertions(+), 2751 deletions(-) create mode 100644 packages/plugin/src/features/sync/history/legacy.ts create mode 100644 packages/plugin/src/features/sync/history/model/activity.ts create mode 100644 packages/plugin/src/features/sync/history/model/cover.ts create mode 100644 packages/plugin/src/features/sync/history/model/periods.ts create mode 100644 packages/plugin/src/features/sync/history/model/plan.ts create mode 100644 packages/plugin/src/features/sync/history/model/records.ts create mode 100644 packages/plugin/src/features/sync/history/model/types.ts create mode 100644 packages/plugin/src/features/sync/history/pins.ts create mode 100644 packages/plugin/src/features/sync/history/remote.ts delete mode 100644 packages/plugin/src/features/sync/history/store.ts create mode 100644 packages/plugin/src/features/sync/history/sweep.ts create mode 100644 packages/plugin/tests/features/sync/history/compose.test.ts create mode 100644 packages/plugin/tests/features/sync/history/gc.test.ts delete mode 100644 packages/plugin/tests/features/sync/history/history-gc.test.ts rename packages/plugin/tests/features/sync/history/{history-log.test.ts => history-query.test.ts} (50%) delete mode 100644 packages/plugin/tests/features/sync/history/history-read-cache.test.ts create mode 100644 packages/plugin/tests/features/sync/history/legacy.test.ts create mode 100644 packages/plugin/tests/features/sync/history/model/activity.test.ts create mode 100644 packages/plugin/tests/features/sync/history/model/cover.test.ts create mode 100644 packages/plugin/tests/features/sync/history/model/periods.test.ts create mode 100644 packages/plugin/tests/features/sync/history/model/plan.test.ts create mode 100644 packages/plugin/tests/features/sync/history/model/records.test.ts create mode 100644 packages/plugin/tests/features/sync/history/pins.test.ts create mode 100644 packages/plugin/tests/features/sync/history/publish.test.ts create mode 100644 packages/plugin/tests/features/sync/history/remote.test.ts create mode 100644 packages/plugin/tests/features/sync/runtime/maintenance-service.test.ts create mode 100644 packages/plugin/tests/helpers/history-sim.ts create mode 100644 packages/plugin/tests/helpers/history.ts diff --git a/.claude/rules/history.md b/.claude/rules/history.md index 70dd7fb1..9854e307 100644 --- a/.claude/rules/history.md +++ b/.claude/rules/history.md @@ -10,23 +10,25 @@ paths: # File history, restore and GC -History is a change log, not an archive. 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`. +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`. -## Change log +## Records -- `history.json.enc` holds one record per push: the diff from that snapshot's parent, which is `compareResult.remote`, not `state.baseline` (they differ whenever another device pushed since the last compare). `publishManifestWithHistory` passes the remote as `parent`. -- 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 lost update leaves a detectable gap, not a corrupted chain. -- Walk the chain only while `entry.parentId === next.id` (`contiguousLength`), starting at HEAD (`walkableChain`); past a gap the log is not evidence of anything. Order by log position, never `createdAt` (clock skew). -- History is best-effort: a failed log update warns and never fails the push, and GC runs only for the guard's winner. A log that is there but unreadable, malformed or newer is an error, never read as empty (a fresh log would overwrite the real one and orphan its blobs): `readHistoryLog` asks twice before returning empty. -- Log writes go through `updateHistoryLog` (read, mutate, write, read back, redo once if the change did not survive): the manifest guard does not serialize them. Callers act on what it returns. -- Queue anything that rewrites the log on the operation queue (`setSnapshotPinned` does): a push or GC of this device rewrites it too. +- 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 key and vault and while every blob it names exists (`stillLands`): 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. +- 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. Within the horizon a GC build replaces only inputs the walk took whole (an off-walk part may be a sibling or lie behind a gap); a counts build takes its whole group. 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: `changes[snapshot].deleted` newest first, 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; those rows are `source: "pinned"` and say "last seen", never "deleted": a pin proves the file existed, not when it went. A pin clears the eviction `rank` only of the hash it holds. -- A log that lags HEAD sets `lagging` (and a gap `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. -- A snapshot is `restorable` only when replay reaches it from HEAD (`replayTo`) or it is pinned. `replayTo` returns null on any gap: a partial replay would invent a state. +- `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. +- 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. +- 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 @@ -37,15 +39,24 @@ History is a change log, not an archive. Model, publish order, windows and accep ## Pins -- Write the pin manifest under `pins/` before setting the flag (`setSnapshotPinned`): a flag without its manifest makes GC believe objects are protected that nothing references. A pin whose manifest cannot be read is replaced, never trusted. -- Unpinning removes the flag first; a leftover manifest is inert (GC reads only flagged pins; deep clean removes it). No rollback on failure. -- A pin keeps its own full manifest so it outlives the chain once the snapshots between HEAD and the pin are evicted. +- A pin is one object, `pins/.json.enc` (`features/sync/history/pins.ts`): `{ v: 1, manifest, label?, pinnedAt }` with the snapshot's full manifest, 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`). +- A listed pin that does not read (corrupt, or a 1.x bare manifest) is `unreadable` in `readPins`: what it holds is unknown. Decoded pins are cached only by etag: a timestamp may not move on a rewrite. ## GC and deep clean -- Never delete an object reachable from HEAD, from a retained change record (every version it names: `changeEntries`), or from a pinned snapshot's manifest. If any of those cannot be read, delete no objects at all (`skippedObjectSweep` in `collectGarbage`; deep clean and verify throw): a bounded blob leak is acceptable, a dangling reference is not. +- 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: `settledKeys` / `keysByAge` list them by age, `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). -- Evict a record only when it is past the limit, unpinned and at least `SETTLED_AFTER_MS` old (`evictable`); a record naming a blob still settling stays, or nothing would name that blob again. GC fires only past `gcExcessBuffer` (amortized). -- Order in `collectGarbage`: list ages, prune the log, re-read HEAD late, then sweep. Prune before sweeping: a crash between leaves orphan blobs deep clean collects, never log versions whose content is gone. An unreadable or moved HEAD, an unreadable kept record, or a snapshot pinned meanwhile (`pinnedAmong` checks storage, not just the log) withholds the sweep. -- Deep clean (`deepCleanOrphans` in `features/sync/runtime/maintenance.ts`) needs a published HEAD and a complete live set, deletes nothing written in the last day, and bails if HEAD or the pinned set changed while it listed (a pin does not move HEAD). -- GC, verify and deep clean list only `objects/` and `pins/` of their own space. +- 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 changed while 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. +- 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`; `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. `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/`, `pins/` and `history/` of its own space. + +## 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 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/settings-setup.md b/.claude/rules/settings-setup.md index 47f75407..2efcc8e0 100644 --- a/.claude/rules/settings-setup.md +++ b/.claude/rules/settings-setup.md @@ -15,7 +15,7 @@ Paths are relative to `packages/plugin/src/`. Wizard steps and modules: `feature - 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. -- `reset-remote-storage` stays confirmation-gated (`confirmRemoteReset`, `features/sync/ui/reset-modal.ts`). It deletes `manifest.json.enc`, `objects/`, `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. +- `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. ## Settings @@ -28,7 +28,7 @@ Paths are relative to `packages/plugin/src/`. Wizard steps and modules: `feature - 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. -- **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 it stamps the current manifest version so older clients refuse the cleared remote. +- **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/`) diff --git a/.claude/rules/spaces.md b/.claude/rules/spaces.md index 10bc8bdd..58fd4f38 100644 --- a/.claude/rules/spaces.md +++ b/.claude/rules/spaces.md @@ -45,7 +45,7 @@ Model, flows, accepted limits: `features/spaces/README.md`. What the engine does ## 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/` and `pins/`. +- `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/`, `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. diff --git a/.claude/rules/sync-integrity.md b/.claude/rules/sync-integrity.md index bc3d9a99..3fed7037 100644 --- a/.claude/rules/sync-integrity.md +++ b/.claude/rules/sync-integrity.md @@ -22,7 +22,7 @@ Breaking one of these silently corrupts user data or publishes remote deletions; - 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. -- 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; a reset manifest carries `MANIFEST_VERSION` 2 so older clients refuse it (`features/sync/operations/config-reset.ts`). +- 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. @@ -36,7 +36,7 @@ Breaking one of these silently corrupts user data or publishes remote deletions; ## 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 change record still lists them `deleted`, so history GC sweeps the blobs later; the Trash tab and a vault restore skip paths the vault no longer owns. +- 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. @@ -45,8 +45,8 @@ Breaking one of these silently corrupts user data or publishes remote deletions; - 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: manifest, history log and pin manifests are translated only in `features/sync/remote/space-paths.ts`, called from `features/sync/remote/manifest.ts` and `features/sync/history/store.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/` and `pins/`: 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. +- 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/`, `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 diff --git a/README.md b/README.md index 83b9ddf5..74b77f70 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ Under **Obsidian configuration scope** you choose what else to sync: core settin ## 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 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 @@ -336,7 +336,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 @@ -378,9 +378,8 @@ 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. +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/packages/plugin/src/app/session-factory.ts b/packages/plugin/src/app/session-factory.ts index 4a9a8596..f40720d3 100644 --- a/packages/plugin/src/app/session-factory.ts +++ b/packages/plugin/src/app/session-factory.ts @@ -1,4 +1,5 @@ import { type App, TFile } from "obsidian"; +import { HISTORY_KEEP_MS } from "@/core/constants"; import type { EncryptionKey } from "@/core/crypto"; import type { LogService } from "@/core/logs"; import { ESyncLogOperation } from "@/core/logs"; @@ -98,7 +99,7 @@ function sessionOpener( key: opened.key, concurrency: opened.concurrency, history: settings.fileHistoryEnabled - ? { maxSnapshots: settings.fileHistoryMaxSnapshots } + ? { horizon: HISTORY_KEEP_MS[settings.fileHistoryKeep] } : undefined, live: deps.liveNotes?.(space), author: opened.author, diff --git a/packages/plugin/src/core/constants.ts b/packages/plugin/src/core/constants.ts index f79dddc4..1ee5c5a4 100644 --- a/packages/plugin/src/core/constants.ts +++ b/packages/plugin/src/core/constants.ts @@ -19,9 +19,16 @@ export const BULK_DELETE_LIMIT_MIN = 0; export const BULK_DELETE_LIMIT_MAX = 1000; -export const FILE_HISTORY_MIN_SNAPSHOTS = 1; - -export const FILE_HISTORY_MAX_SNAPSHOTS = 1000; +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 SOURCE_CONTROL_VIEW_TYPE = "mdsync-source-control"; diff --git a/packages/plugin/src/core/settings/index.ts b/packages/plugin/src/core/settings/index.ts index 7a36ad7d..c66ec0dc 100644 --- a/packages/plugin/src/core/settings/index.ts +++ b/packages/plugin/src/core/settings/index.ts @@ -19,6 +19,7 @@ export { clamp, DEFAULT_CORE_SETTINGS, DEFAULT_SETTINGS_SYNC, + type HistoryKeep, isRelayConfigured, type MdsyncSettings, mergeCoreSettings, diff --git a/packages/plugin/src/core/settings/model.ts b/packages/plugin/src/core/settings/model.ts index de7d0ba5..b2e7f84b 100644 --- a/packages/plugin/src/core/settings/model.ts +++ b/packages/plugin/src/core/settings/model.ts @@ -5,15 +5,14 @@ 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 "@/core/constants"; import { isCleartextRemote } from "@/core/shared"; const DEFAULT_MAX_FILE_BYTES = 100 * 1024 * 1024; -const DEFAULT_FILE_HISTORY_MAX_SNAPSHOTS = 50; +export type HistoryKeep = keyof typeof HISTORY_KEEP_MS; export interface SettingsSyncCategories { coreSettings: boolean; @@ -52,7 +51,7 @@ export interface CoreSettings { confirmBulkDeletes: boolean; bulkDeleteLimit: number; fileHistoryEnabled: boolean; - fileHistoryMaxSnapshots: number; + fileHistoryKeep: HistoryKeep; historyAutoRefresh: boolean; realtimeSync: boolean; /** Notes open in the editor edit together across devices, over the relay. */ @@ -110,7 +109,7 @@ export const DEFAULT_CORE_SETTINGS: CoreSettings = { confirmBulkDeletes: true, bulkDeleteLimit: 5, fileHistoryEnabled: false, - fileHistoryMaxSnapshots: DEFAULT_FILE_HISTORY_MAX_SNAPSHOTS, + fileHistoryKeep: "quarter", historyAutoRefresh: true, realtimeSync: false, liveEditing: true, @@ -156,6 +155,7 @@ const RETIRED_KEYS = [ "shareBrokerAdminSecret", "sharedFolders", "shareStorageKind", + "fileHistoryMaxSnapshots", ] as const; /** Bounds for numeric settings. Clamping here prevents invalid values from files or tokens. */ @@ -173,10 +173,6 @@ export const NUMERIC_BOUNDS = { 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>; export interface Bounds { @@ -219,6 +215,11 @@ export function mergeCoreSettings( ) ? (stored?.liveSendMs as number) : 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 diff --git a/packages/plugin/src/features/settings/sections/automation.ts b/packages/plugin/src/features/settings/sections/automation.ts index b2298baf..90837574 100644 --- a/packages/plugin/src/features/settings/sections/automation.ts +++ b/packages/plugin/src/features/settings/sections/automation.ts @@ -6,8 +6,6 @@ import { AUTO_SYNC_MIN_MINUTES, BULK_DELETE_LIMIT_MAX, BULK_DELETE_LIMIT_MIN, - FILE_HISTORY_MAX_SNAPSHOTS, - FILE_HISTORY_MIN_SNAPSHOTS, LIVE_SEND_MS, } from "@/core/constants"; import type { RelayStatus } from "@/core/hub"; @@ -18,6 +16,7 @@ import { type FieldContext, fieldRow, group, + type HistoryKeep, isRelayConfigured, type SettingsField, type SettingsHost, @@ -26,7 +25,7 @@ import { import type { LiveSessions } from "@/features/live"; import type { People } from "@/features/presence"; import type { HubConnection } from "@/features/relay"; -import { clampMaxSnapshots, VAULT_SPACE } from "@/features/sync"; +import { VAULT_SPACE } from "@/features/sync"; import type { SettingsTabHost } from "../host"; /** The wizard shows these too, so they ask only what its host has. */ @@ -167,21 +166,27 @@ const AUTOMATION_FIELDS: ReadonlyArray> = [ }, { 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.", + name: "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.", 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.`, + 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, - get: (s) => String(s.fileHistoryMaxSnapshots), - parse: (raw) => clampMaxSnapshots(Number.parseInt(raw, 10)), - set: (v) => ({ fileHistoryMaxSnapshots: v }), + options: { + week: "1 week", + month: "1 month", + quarter: "3 months", + year: "1 year", + forever: "Forever", + } satisfies Record, + get: (s) => s.fileHistoryKeep, + set: (v) => ({ fileHistoryKeep: v as HistoryKeep }), }, { kind: EFieldKind.Toggle, diff --git a/packages/plugin/src/features/source-control/history/history-tab.ts b/packages/plugin/src/features/source-control/history/history-tab.ts index cfbfcb3e..33019d0d 100644 --- a/packages/plugin/src/features/source-control/history/history-tab.ts +++ b/packages/plugin/src/features/source-control/history/history-tab.ts @@ -74,7 +74,7 @@ export class HistoryTab { renderHistoryOff( pane, this.plugin.app, - "File version history is disabled. Enable it in settings.", + "History is off. Turn on History in MDSync settings.", ); return; } diff --git a/packages/plugin/src/features/source-control/timeline/timeline-tab.ts b/packages/plugin/src/features/source-control/timeline/timeline-tab.ts index 0edbaf79..893c8a18 100644 --- a/packages/plugin/src/features/source-control/timeline/timeline-tab.ts +++ b/packages/plugin/src/features/source-control/timeline/timeline-tab.ts @@ -102,7 +102,7 @@ export class TimelineTab { renderHistoryOff( pane, this.plugin.app, - "File version history is disabled. Enable it in settings to see the timeline.", + "History is off. Turn on History in MDSync settings to see the timeline.", ); return; } diff --git a/packages/plugin/src/features/source-control/trash/trash-rows.ts b/packages/plugin/src/features/source-control/trash/trash-rows.ts index 4133b431..59f886b2 100644 --- a/packages/plugin/src/features/source-control/trash/trash-rows.ts +++ b/packages/plugin/src/features/source-control/trash/trash-rows.ts @@ -12,7 +12,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 +23,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; @@ -66,20 +64,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); 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 +97,11 @@ 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, ): 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 in history until ${new Date(file.keptUntil).toLocaleDateString()}`; } diff --git a/packages/plugin/src/features/source-control/trash/trash-tab.ts b/packages/plugin/src/features/source-control/trash/trash-tab.ts index 89ee748d..90d03090 100644 --- a/packages/plugin/src/features/source-control/trash/trash-tab.ts +++ b/packages/plugin/src/features/source-control/trash/trash-tab.ts @@ -72,7 +72,7 @@ export class TrashTab implements SelectionSource { renderHistoryOff( pane, this.plugin.app, - "File version history is disabled, so deleted files are not recoverable. Enable it in settings.", + "History is off, so deleted files cannot be recovered. Turn on History in MDSync settings.", ); return; } @@ -144,7 +144,6 @@ 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, @@ -158,7 +157,7 @@ export class TrashTab implements SelectionSource { 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: "Nothing deleted within history. Deletions older than it are gone unless a pinned snapshot holds them.", }); } return; diff --git a/packages/plugin/src/features/spaces/README.md b/packages/plugin/src/features/spaces/README.md index f98763ec..b6b9bf8c 100644 --- a/packages/plugin/src/features/spaces/README.md +++ b/packages/plugin/src/features/spaces/README.md @@ -35,7 +35,7 @@ A share's location (endpoint, bucket, prefix) is pinned once: re-deriving it fro **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/` and `pins/`. 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. +**Broker signing.** The broker lets a participant into `shares//` only (`packages/relay/src/share/key.ts`); vault GC lists only `objects/`, `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 diff --git a/packages/plugin/src/features/storage/index.ts b/packages/plugin/src/features/storage/index.ts index 062b93ce..00281f73 100644 --- a/packages/plugin/src/features/storage/index.ts +++ b/packages/plugin/src/features/storage/index.ts @@ -48,6 +48,7 @@ export { } from "./settings"; export { type ConditionalRead, + type ListedObject, type ObjectStorage, ShareRefusedError, type StorageAdapter, diff --git a/packages/plugin/src/features/sync/README.md b/packages/plugin/src/features/sync/README.md index 51edbf81..abcced1c 100644 --- a/packages/plugin/src/features/sync/README.md +++ b/packages/plugin/src/features/sync/README.md @@ -16,7 +16,7 @@ File sync of the vault and of each shared folder (a "space") against object stor | `automation/` | `features/sync/automation/scheduler.ts` (timer, backoff), `features/sync/automation/auto-push.ts` (bulk-deletion hold) | | `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` | -| `history/` | change log, queries, replay, vault restore plan, GC | +| `history/` | push records, queries, replay, pins, vault restore plan, GC and sweep | | `ui/` | menu items, modals, the maintenance section | 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). @@ -44,7 +44,7 @@ A push publishes the remote's file map (`result.remote`) plus this push's change 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: 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. +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. @@ -60,7 +60,7 @@ Accepted limits: garbage that is no prefix reads as an edit; an edit since that ## 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 after the change record rolls off. 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. +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`). @@ -78,14 +78,16 @@ A hunk index means nothing without its two texts. The diff view, the gutter mark ## History -`history.json.enc` is one encrypted object: snapshot entries newest first plus a change record per snapshot (`added`, `modified {from, to}`, `deleted`), each the diff from that snapshot's parent. Both sides are stored so one version restores without replaying, and a lost update (log writes are read-modify-write, verified by `updateHistoryLog`, not serialized by the manifest guard) shows as a parent/child gap that `contiguousLength` stops at. Pins store a full manifest under `pins/`, so they outlive the chain. +Every push writes one encrypted record, `history/p/.enc`, before it publishes: the diff from that snapshot's parent (`added`, `modified {from, to}`, `deleted`). 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 a day later. -Windows: a blob younger than `SETTLED_AFTER_MS` (24 h) is never swept, a record younger than that is never evicted, deep clean deletes nothing written in the last day. 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. A push by another device that re-uploaded an old hash is covered only by those windows. +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. ## Other flows -- Reset and adopt (`features/sync/operations/flows.ts`): reset deletes the vault storage's manifest, log, 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 (`deep` also hashes it); deep clean removes unreachable settled objects and pins. +- 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 (`deep` also hashes it); deep clean removes unreachable settled objects. - 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. diff --git a/packages/plugin/src/features/sync/constants.ts b/packages/plugin/src/features/sync/constants.ts index 3b907d67..17d8f34f 100644 --- a/packages/plugin/src/features/sync/constants.ts +++ b/packages/plugin/src/features/sync/constants.ts @@ -2,9 +2,12 @@ export const REMOTE_OBJECTS_PREFIX = "objects/"; -/** 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/"; @@ -12,7 +15,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/controller.ts b/packages/plugin/src/features/sync/controller.ts index f48515a4..0184b118 100644 --- a/packages/plugin/src/features/sync/controller.ts +++ b/packages/plugin/src/features/sync/controller.ts @@ -170,6 +170,7 @@ export class SyncController { runtimeState: this.runtimeState, clearFileDiffs: () => this.fileDiffs.clear(), localRevision: () => this.localRevision, + onPublished: (space) => this.maintenance.afterPush(space), }); this.autoPushPaths = createAutoPushSelector( () => host.autoDeleteLimit?.() ?? null, @@ -201,10 +202,13 @@ export class SyncController { refresh: () => this.operations.refreshNow(), }); 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), }); } @@ -246,6 +250,7 @@ export class SyncController { dispose(): void { this.saved.dispose(); + this.maintenance.dispose(); this.runtimeState.dispose(); this.fileDiffs.clear(); clearRemoteTextCache(); diff --git a/packages/plugin/src/features/sync/history/changes.ts b/packages/plugin/src/features/sync/history/changes.ts index 9839e731..9e6f92a7 100644 --- a/packages/plugin/src/features/sync/history/changes.ts +++ b/packages/plugin/src/features/sync/history/changes.ts @@ -1,7 +1,7 @@ import { entryAt } from "../changes/records"; import type { Manifest, ManifestEntry } from "../types"; -import type { SnapshotChanges, SnapshotEntry } from "./types"; +import type { SnapshotChanges } from "./types"; function sameEntry(a: ManifestEntry, b: ManifestEntry): boolean { return ( @@ -65,27 +65,71 @@ export function changeEntries(changes: SnapshotChanges): ManifestEntry[] { ...Object.values(changes.added), ...Object.values(changes.modified).flatMap(({ from, to }) => [from, to]), ...Object.values(changes.deleted), + ...Object.values(changes.deletedLast ?? {}), ]; } -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. + * 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 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; +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; + } + } } - return length; + 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 index 498f34e8..18833fd4 100644 --- a/packages/plugin/src/features/sync/history/gc.ts +++ b/packages/plugin/src/features/sync/history/gc.ts @@ -1,303 +1,110 @@ -import { - FILE_HISTORY_MAX_SNAPSHOTS, - FILE_HISTORY_MIN_SNAPSHOTS, -} from "@/core/constants"; +import { DEFAULT_CONCURRENCY } from "@/core/constants"; import type { EncryptionKey } from "@/core/crypto"; -import { reportWarning } from "@/core/shared"; import { runWithConcurrency } from "@/core/utils"; import type { ObjectStorage } from "@/features/storage"; -import { REMOTE_OBJECTS_PREFIX } from "../constants"; -import { fetchRemoteManifest, objectKey } from "../remote/manifest"; -import { keysByAge, SETTLED_AFTER_MS } from "../remote/uploads"; +import { fetchRemoteManifest } from "../remote/manifest"; +import { SETTLED_AFTER_MS } from "../remote/uploads"; import type { Manifest } from "../types"; -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; -} +import { coverOf, type HistoryView } from "./model/cover"; +import { freedHashes, planGc } from "./model/plan"; +import { + type HistoryRead, + readHistory, + writeCandidates, + writeHistoryObject, +} from "./remote"; +import { isSettled, sweepObjects } from "./sweep"; +import type { HistoryConfig, SnapshotChanges } from "./types"; 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]; + /** History objects written. */ + written: number; + /** Push records and objects deleted. */ + retired: number; + /** File blobs deleted. */ + swept: number; } /** - * 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. + * 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. */ -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( +export async function collectHistoryGarbage( 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); + history: HistoryConfig, +): Promise { + const head = storage.listDetailed + ? await fetchRemoteManifest(storage, key, root) + : null; + if (!head) return { written: 0, retired: 0, swept: 0 }; + const read = await readHistory(storage, key, root); + const thinned = await thinHistory(storage, key, root, history, head, read); + const swept = read.candidates.some(isSettled) + ? await sweepObjects(storage, key, root, { freedOnly: true }) + : 0; + return { ...thinned, swept }; } -async function safeDelete( +/** Writes and verifies the planned objects, records what they freed, then retires what they replace. */ +async function thinHistory( storage: ObjectStorage, - storageKey: string, -): Promise { - try { - await storage.delete(storageKey); - return true; - } catch (err) { - reportWarning( - `Could not delete "${storageKey}" during history cleanup.`, - err, + 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.`, ); - return false; } + 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 }[] = []; + for (const build of plan.builds) { + 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 }; } -/** 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 }; - } +function changesOf( + view: HistoryView, + keys: readonly string[], +): { changes: SnapshotChanges }[] { + return keys.flatMap((storageKey): { changes: SnapshotChanges }[] => { + 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..9957b3a1 --- /dev/null +++ b/packages/plugin/src/features/sync/history/model/cover.ts @@ -0,0 +1,243 @@ +import { RESOLUTIONS } from "./periods"; +import { runsOf, storedRecord } from "./records"; +import type { HistoryObject, PushRecord, 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; +} + +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; + /** 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 }); + } + 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, rank: number, run: StoredRecord[]): void => { + const parentId = run[0]?.parentId ?? null; + let pushes = 0; + for (const [index, record] of run.entries()) { + pushes += record.pushes; + segments.push({ key, 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, 0, [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, RESOLUTIONS.indexOf(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..10a6dae8 --- /dev/null +++ b/packages/plugin/src/features/sync/history/model/periods.ts @@ -0,0 +1,99 @@ +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; +} + +/** `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; +} + +/** 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..c6c2e7e1 --- /dev/null +++ b/packages/plugin/src/features/sync/history/model/plan.ts @@ -0,0 +1,241 @@ +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, + 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[]; +} + +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 whole = wholeKeys(input); + const builds: Build[] = []; + for (const target of targets(input)) { + const build = buildOf(input, target, whole); + if (build) builds.push(build); + } + return { builds, deletes: [...deletes] }; +} + +/** Keys every record of which is on the walk. */ +function wholeKeys(input: PlanInput): (key: string) => boolean { + const taken = new Map(); + for (const { source } of input.cover.chain) { + taken.set(source, (taken.get(source) ?? 0) + 1); + } + return (key) => + (taken.get(key) ?? 0) === + (input.view.objects.get(key)?.object.records.length ?? 1); +} + +/** Versions the replaced records named that the new object no longer does: phase 1's sweep candidates. */ +export function freedHashes( + replaced: readonly 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) { + for (const { hash } of changeEntries(record.changes)) { + 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; +} + +function buildOf( + input: PlanInput, + target: Target, + whole: (key: string) => boolean, +): Build | null { + const { res, group } = target; + const rank = RESOLUTIONS.indexOf(res); + const walked = new Set(target.walked.map(({ source }) => source)); + const inputs = new Set(walked); + const sameGroup: HistoryObject[] = []; + for (const [key, { object }] of input.view.objects) { + if (input.cover.consumed.has(key) || object.vaultId !== input.vaultId) { + continue; + } + const objectRank = RESOLUTIONS.indexOf(object.res); + if (objectRank > rank || groupStart(res, object.group) !== group) continue; + inputs.add(key); + if (object.res === res) sameGroup.push(object); + } + // Within the horizon what the walk did not take whole may hold a sibling or lie behind a gap: it stays. + const replaced = res === "counts" ? [...inputs] : [...inputs].filter(whole); + 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; + + 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..09a74686 --- /dev/null +++ b/packages/plugin/src/features/sync/history/model/records.ts @@ -0,0 +1,82 @@ +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 { + return { + id: push.id, + parentId: push.parentId, + createdAt: push.createdAt, + deviceId: push.deviceId, + deviceName: push.deviceName, + changes: push.changes, + at, + firstAt: at, + pushes: 1, + activity: { [hourOf(at)]: [1, pathsChanged(push.changes)] }, + }; +} + +/** 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..627853c4 --- /dev/null +++ b/packages/plugin/src/features/sync/history/model/types.ts @@ -0,0 +1,50 @@ +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; +} + +/** 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..0815d52e --- /dev/null +++ b/packages/plugin/src/features/sync/history/pins.ts @@ -0,0 +1,177 @@ +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 "@/features/storage"; +import { REMOTE_PINS_PREFIX } from "../constants"; +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 only a few stay. */ +const PIN_CACHE_SIZE = 4; + +// A relabel rewrites the object, and only its etag proves it unchanged: a timestamp may not move within its resolution. +const pinCache = new WeakMap< + ObjectStorage, + { + key: EncryptionKey; + root: string; + pins: 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 async function readPins( + storage: ObjectStorage, + key: EncryptionKey, + root: string, + pick: (pin: Pin) => T, +): Promise> { + let cache = pinCache.get(storage); + if (cache?.key !== key || cache.root !== root) { + cache = { key, root, pins: new Map() }; + pinCache.set(storage, cache); + } + const { pins } = cache; + const listed = await listPins(storage); + const read: PinsRead["pins"] = []; + const unreadable: string[] = []; + await runWithConcurrency(listed, DEFAULT_CONCURRENCY, async (object) => { + const { etag } = object; + const hit = pins.get(object.key); + let pin = etag !== null && hit?.etag === etag ? hit.pin : null; + if (!pin) { + pin = await readPin(storage, key, root, object.key); + if (!pin) { + unreadable.push(object.key); + return; + } + if (etag !== null) remember(pins, object.key, { etag, pin }); + } + const { id, label, manifest } = pin; + const { createdAt, deviceId, deviceName } = manifest; + read.push({ + info: { id, label, createdAt, deviceId, deviceName }, + picked: pick(pin), + }); + }); + 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 readPin(storage, key, root, pinKey(snapshotId)); +} + +async function listPins(storage: ObjectStorage): Promise { + if (storage.listDetailed) return storage.listDetailed(REMOTE_PINS_PREFIX); + return (await storage.list(REMOTE_PINS_PREFIX)).map((key) => ({ + key, + etag: null, + modified: null, + })); +} + +async function readPin( + storage: ObjectStorage, + key: EncryptionKey, + root: string, + storageKey: string, +): Promise { + const blob = await storage.get(storageKey); + if (!blob) return null; + 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: { etag: string; pin: Pin }, +): void { + pins.delete(storageKey); + pins.set(storageKey, entry); + for (const oldest of pins.keys()) { + if (pins.size <= PIN_CACHE_SIZE) break; + pins.delete(oldest); + } +} diff --git a/packages/plugin/src/features/sync/history/publish.ts b/packages/plugin/src/features/sync/history/publish.ts index 620feea4..a9a69d27 100644 --- a/packages/plugin/src/features/sync/history/publish.ts +++ b/packages/plugin/src/features/sync/history/publish.ts @@ -1,19 +1,32 @@ +import { DEFAULT_CONCURRENCY } from "@/core/constants"; import type { EncryptionKey } from "@/core/crypto"; import { reportWarning } from "@/core/shared"; -import type { ObjectStorage } from "@/features/storage"; -import { publishManifestWithGuard } from "../remote/manifest"; +import { runWithConcurrency } from "@/core/utils"; +import type { StorageAdapter } from "@/features/storage"; +import { objectKey, publishManifestWithGuard } from "../remote/manifest"; import type { Manifest } from "../types"; -import { diffManifests } from "./changes"; -import { collectGarbage, shouldRunGc } from "./gc"; -import { prependSnapshot, updateHistoryLog } from "./store"; -import type { HistoryConfig, SnapshotEntry } from "./types"; +import { changeEntries, diffManifests } 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; + key: EncryptionKey; + 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>(); /** - * 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. + * 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: ObjectStorage, + storage: StorageAdapter, key: EncryptionKey, root: string, manifest: Manifest, @@ -21,6 +34,29 @@ export async function publishManifestWithHistory( history: HistoryConfig | undefined, baseline: Manifest | null = null, ): Promise { + if (history) { + const waiting = unwritten.get(storage.identity()) ?? new Map(); + unwritten.set(storage.identity(), waiting); + const changes = diffManifests(parent, manifest); + 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, + }), + key, + vaultId: manifest.vaultId, + hashes: [...new Set(changeEntries(changes).map(({ hash }) => hash))], + }; + waiting.set(pushKey(manifest.snapshotId), own); + await writeWaiting(storage, waiting, own); + } + // A failed publish keeps its record waiting: the manifest may have landed, and a sibling costs only GC. await publishManifestWithGuard( storage, key, @@ -29,37 +65,40 @@ export async function publishManifestWithHistory( 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, - }); +} + +/** Oldest first; stops at the first failure, as the rest would likely fail the same way. */ +async function writeWaiting( + storage: StorageAdapter, + waiting: Map, + own: Unwritten, +): Promise { + for (const [storageKey, record] of waiting) { + try { + if (record === own || (await stillLands(storage, record, own))) { + 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; } - } catch (err) { - reportWarning( - "File history could not be updated; the push itself succeeded.", - err, - ); } } + +/** A held-back record lands only in its own vault and while every blob it names survived a sweep or a reset. */ +async function stillLands( + storage: StorageAdapter, + record: Unwritten, + own: Unwritten, +): Promise { + if (record.key !== own.key || record.vaultId !== own.vaultId) return false; + let missing = false; + await runWithConcurrency(record.hashes, DEFAULT_CONCURRENCY, async (hash) => { + if (!(await storage.exists(objectKey(hash)))) missing = true; + }); + return !missing; +} diff --git a/packages/plugin/src/features/sync/history/query.ts b/packages/plugin/src/features/sync/history/query.ts index 24651fe4..12f72c09 100644 --- a/packages/plugin/src/features/sync/history/query.ts +++ b/packages/plugin/src/features/sync/history/query.ts @@ -1,349 +1,275 @@ import type { EncryptionKey } from "@/core/crypto"; -import { runWithConcurrency } from "@/core/utils"; 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 { contiguousLength, undoChangesForPath } from "./changes"; -import { readHistoryLog, readPinManifest } from "./store"; +import { undoChangesForPath } from "./changes"; +import { type Cover, coverOf } from "./model/cover"; +import { keptUntil } from "./model/periods"; +import { + deletePin, + type PinInfo, + readPinById, + readPins, + writePin, +} from "./pins"; +import { readHistory } from "./remote"; +import { replayTo } from "./replay"; 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 { +export interface HistoryQuery { storage: ObjectStorage; key: EncryptionKey; root: string; - path: string; + /** See `HistoryConfig.horizon`. */ + horizon: number | null; } -export interface DeletedFilesQuery { - storage: ObjectStorage; - key: EncryptionKey; - root: string; -} +type Source = Pick; -/** 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), +/** 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 }> { + const { storage, key, root } = source; + const [head, history] = await Promise.all([ fetchRemoteManifest(storage, key, root), + readHistory(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)), + const cover = coverOf( + history.view, + head && { + id: head.snapshotId, + parentId: head.parentSnapshotId, + vaultId: head.vaultId, + }, ); - return orderByChain(versions, log); + return { head, cover }; } -/** 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), +/** Distinct versions of one path, newest first; pinned ones follow. */ +export async function getFileHistory( + query: Source & { path: string }, +): Promise { + const { path } = query; + 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, ); -} - -/** - * 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 labels = new Map(pins.pins.map(({ info }) => [info.id, info.label])); const versions: FileVersion[] = []; - const visited = new Set(); + const visited = new Set([head.snapshotId]); 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), entry, labels)); + } let lastHash: string | null = null; - for (const meta of chain.length > 0 ? chain : [headEntry(head)]) { - visited.add(meta.id); + for (const { record } of chain) { + visited.add(record.id); if (entry === null) { lastHash = null; } else if (entry.hash !== lastHash) { - versions.push(toVersion(meta, entry)); + versions.push(toVersion(record, entry, labels)); lastHash = entry.hash; } - const changes = entryAt(log.changes, meta.id); - if (!changes) break; - entry = undoChangesForPath(entry, changes, path); + entry = undoChangesForPath(entry, record.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)); + for (const { info, picked } of pins.pins) { + if (picked && !visited.has(info.id)) { + versions.push(toVersion(info, picked, labels)); + } } 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. + * 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: DeletedFilesQuery, + query: HistoryQuery, ): Promise { - const { storage, key, root } = query; - const [log, head] = await Promise.all([ - readHistoryLog(storage, key, root), - fetchRemoteManifest(storage, key, root), - ]); + const { head, cover } = await readTimeline(query); 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; + // 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, - snapshotId: meta.id, + entry: entryAt(record.changes.deletedLast ?? {}, path) ?? from, + snapshotId: record.id, source: "deleted", - createdAt: meta.createdAt, - deviceId: meta.deviceId, - deviceName: meta.deviceName, - rank: meta.pinned ? null : rank, + createdAt: record.createdAt, + deviceId: record.deviceId, + deviceName: record.deviceName, + pinned: false, + keptUntil: keptUntil(record.at, query.horizon), }); } - if (!meta.pinned) rank++; + for (const changed of [added, modified, deleted]) { + for (const path of Object.keys(changed)) touched.add(path); + } } - return { found, walked }; + await applyPins(query, head, found); + return { + files: [...found.values()], + lagging: cover.lagging, + truncated: cover.truncated, + }; } /** - * Folds pinned manifests in: adds files no change record explains and clears the eviction countdown on files - * they hold. + * 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( - storage: ObjectStorage, - key: EncryptionKey, - root: string, - log: HistoryLog, + source: Source, 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( + const { pins } = await readPins( + source.storage, + source.key, + source.root, + (pin) => + Object.entries(pin.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] ?? []) { + for (const { info, picked } of pins) { + for (const [path, entry] of picked) { 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; + if (existing.entry.hash === entry.hash) { + existing.pinned = true; + existing.keptUntil = null; + } continue; } found.set(path, { path, entry, - snapshotId: meta.id, + snapshotId: info.id, source: "pinned", - label: meta.label, - createdAt: meta.createdAt, - deviceId: meta.deviceId, - deviceName: meta.deviceName, - rank: null, + label: info.label, + createdAt: info.createdAt, + deviceId: info.deviceId, + deviceName: info.deviceName, + pinned: true, + keptUntil: null, }); } } } -/** The vault's push timeline; file lists are the change records from the log already read for HEAD. */ +/** The vault's push timeline, newest first; a pin no longer on the walk follows. */ export async function listSnapshots( - query: DeletedFilesQuery, + query: HistoryQuery, ): Promise { - const { storage, key, root } = query; - const [log, head] = await Promise.all([ - readHistoryLog(storage, key, root), - fetchRemoteManifest(storage, key, root), - ]); + const { head, cover } = await readTimeline(query); 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), + const { pins } = await readPins( + query.storage, + query.key, + query.root, + () => null, ); - let rank = 0; - const snapshots = log.snapshots.map((meta) => { - const changes = entryAt(log.changes, meta.id); - const summary: SnapshotSummary = { + const pinned = new Map(pins.map(({ info }) => [info.id, info])); + const summary = ( + meta: Meta, + files: SnapshotSummary["files"], + kept: number | null, + ): SnapshotSummary => { + const pin = pinned.get(meta.id); + return { 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, + pinned: pin !== undefined, + label: pin?.label, + files, + keptUntil: pin ? null : kept, + restorable: !cover.lagging || pin !== undefined, isHead: meta.id === head.snapshotId, }; - if (!meta.pinned) rank++; - return summary; - }); - return { snapshots, lagging: chain.length === 0 }; + }; + const snapshots = cover.chain.map(({ record }) => + summary(record, record.changes, keptUntil(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, null, null)); + } + return { snapshots, lagging: cover.lagging }; +} + +/** Replay first; a pin's stored manifest covers snapshots the walk no longer reaches. */ +export async function resolveSnapshotManifest( + source: Source, + snapshotId: string, +): Promise { + const { head, cover } = await readTimeline(source); + const replayed = head ? replayTo(head, cover, snapshotId) : null; + if (replayed) return replayed; + const pin = await readPinById( + source.storage, + source.key, + source.root, + snapshotId, + ); + return pin?.manifest ?? null; } -/** 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; +/** + * Pinning stores the snapshot's whole manifest; 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, + snapshotId: string, + pinned: boolean, + label?: string, +): Promise { + const { storage, key, root } = source; + if (!pinned) { + await deletePin(storage, snapshotId); + return; } - return depth; + const existing = await readPinById(storage, key, root, snapshotId); + const manifest = + existing?.manifest ?? (await resolveSnapshotManifest(source, snapshotId)); + 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( @@ -357,3 +283,31 @@ export async function loadVersionBytes( } return plaintext; } + +function metaOf(manifest: Manifest): Meta { + return { + id: manifest.snapshotId, + createdAt: manifest.createdAt, + deviceId: manifest.deviceId, + deviceName: manifest.deviceName, + }; +} + +function toVersion( + meta: Meta, + entry: ManifestEntry, + labels: ReadonlyMap, +): 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: labels.has(meta.id), + label: labels.get(meta.id), + }; +} 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..059cb3c6 --- /dev/null +++ b/packages/plugin/src/features/sync/history/remote.ts @@ -0,0 +1,269 @@ +import { DEFAULT_CONCURRENCY } from "@/core/constants"; +import { + decryptJson, + type EncryptionKey, + encryptJson, + randomId, + sha256Hex, +} from "@/core/crypto"; +import { runWithConcurrency } from "@/core/utils"; +import type { ListedObject, 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 } +>(); + +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)); + if (!read || (await objectKeyOf(read)) !== storageKey) { + throw new Error( + `History object ${storageKey} did not read back as written.`, + ); + } + 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 { + let cache = caches.get(storage); + if (cache?.key !== key || cache.root !== root) { + cache = { key, root, entries: new Map() }; + caches.set(storage, cache); + } + const { entries } = cache; + let all = await listHistory(storage); + 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 listHistory(storage); + 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 listHistory(storage: ObjectStorage): Promise { + if (storage.listDetailed) return storage.listDetailed(REMOTE_HISTORY_PREFIX); + return (await storage.list(REMOTE_HISTORY_PREFIX)).map((key) => ({ + key, + etag: null, + modified: null, + })); +} + +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 { + const raw = await decryptJson>(key, blob); + 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 index 86b75c08..2c35ecd3 100644 --- a/packages/plugin/src/features/sync/history/replay.ts +++ b/packages/plugin/src/features/sync/history/replay.ts @@ -1,39 +1,32 @@ import type { Manifest } from "../types"; -import { contiguousLength, undoChanges } from "./changes"; -import type { HistoryLog } from "./types"; +import { undoChanges } from "./changes"; +import type { Cover } from "./model/cover"; /** - * 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. + * 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, - log: HistoryLog, + cover: Cover, snapshotId: string, ): Manifest | null { - const snapshots = log.snapshots; - if (snapshots[0]?.id !== head.snapshotId) return null; - const reachable = contiguousLength(snapshots); - + if (cover.lagging) return null; const files = { ...head.files }; - for (let index = 0; index < reachable; index++) { - const entry = snapshots[index]; - if (!entry) return null; - if (entry.id === snapshotId) { + for (const { record } of cover.chain) { + if (record.id === snapshotId) { return { version: head.version, vaultId: head.vaultId, - snapshotId: entry.id, - parentSnapshotId: entry.parentId, - createdAt: entry.createdAt, - deviceId: entry.deviceId, - deviceName: entry.deviceName, + snapshotId: record.id, + parentSnapshotId: record.parentId, + createdAt: record.createdAt, + deviceId: record.deviceId, + deviceName: record.deviceName, files, }; } - const changes = log.changes[entry.id]; - if (!changes) return null; - undoChanges(files, changes); + undoChanges(files, record.changes); } return null; } diff --git a/packages/plugin/src/features/sync/history/store.ts b/packages/plugin/src/features/sync/history/store.ts deleted file mode 100644 index cce0746e..00000000 --- a/packages/plugin/src/features/sync/history/store.ts +++ /dev/null @@ -1,242 +0,0 @@ -import { decryptJson, type EncryptionKey, encryptJson } from "@/core/crypto"; -import { errorMessage, reportWarning } from "@/core/shared"; -import type { ObjectStorage } from "@/features/storage"; -import { REMOTE_HISTORY_LOG_KEY, REMOTE_PINS_PREFIX } from "../constants"; -import { fetchRemoteManifest, readIfChanged } from "../remote/manifest"; -import { - historyLogToSpace, - historyLogToVault, - manifestToSpace, - manifestToVault, -} from "../remote/space-paths"; -import type { Manifest } from "../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/features/sync/history/sweep.ts b/packages/plugin/src/features/sync/history/sweep.ts new file mode 100644 index 00000000..f101e683 --- /dev/null +++ b/packages/plugin/src/features/sync/history/sweep.ts @@ -0,0 +1,183 @@ +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_OBJECTS_PREFIX, + REMOTE_PINS_PREFIX, +} from "../constants"; +import { fetchRemoteManifest, objectKey } from "../remote/manifest"; +import { SETTLED_AFTER_MS, settledKeys } 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. */ + 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. */ +export function isSettled({ modified }: ListedObject): boolean { + return modified !== null && modified < Date.now() - SETTLED_AFTER_MS; +} + +/** + * Deletes settled objects nothing reaches (HEAD, a history record, a pin), never one a GC run freed within the + * last day; 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.", + ); + } + + const objectKeys = await settledKeys(storage, REMOTE_OBJECTS_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) { + 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 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.", + ); + } + + const due = reachable.candidates.filter(isSettled); + const held = await readCandidates( + storage, + key, + reachable.candidates.filter((file) => !isSettled(file)), + ); + if (held.unreadable.length > 0) { + throw new Error( + "Some history records could not be read, so orphans cannot be identified safely. Try again later.", + ); + } + // An unreadable settled file only leaks its blobs to the next deep clean. + const freed = options.freedOnly + ? new Set( + [...(await readCandidates(storage, key, due)).hashes].map(objectKey), + ) + : null; + const kept = new Set( + [...reachable.hashes.keys(), ...held.hashes].map(objectKey), + ); + const orphans = objectKeys.filter( + (storageKey) => + !kept.has(storageKey) && (freed === null || freed.has(storageKey)), + ); + let done = 0; + await runWithConcurrency( + orphans, + options.concurrency ?? DEFAULT_CONCURRENCY, + async (storageKey) => { + await storage.delete(storageKey); + options.onProgress?.(++done, orphans.length); + }, + ); + await runWithConcurrency(due, DEFAULT_CONCURRENCY, (file) => + storage.delete(file.key), + ); + return orphans.length; +} + +function historyKeys(read: HistoryRead): string[] { + return [ + ...read.view.pushes.keys(), + ...read.view.objects.keys(), + ...read.unreadable, + ]; +} diff --git a/packages/plugin/src/features/sync/history/types.ts b/packages/plugin/src/features/sync/history/types.ts index 40e4e1d7..386d7e8b 100644 --- a/packages/plugin/src/features/sync/history/types.ts +++ b/packages/plugin/src/features/sync/history/types.ts @@ -1,18 +1,8 @@ import type { EFileKind, ManifestEntry } from "../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,14 +14,10 @@ export interface FileChange { export interface SnapshotChanges { added: Record; modified: Record; + /** The parent's entry, which replay restores. */ deleted: Record; -} - -export interface HistoryLog { - version: number; - /** Newest first. */ - snapshots: SnapshotEntry[]; - changes: Record; + /** A merged record's content right before the deletion, where it differs from `deleted`. */ + deletedLast?: Record; } export interface FileVersion { @@ -60,11 +46,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 { @@ -87,8 +72,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. */ diff --git a/packages/plugin/src/features/sync/index.ts b/packages/plugin/src/features/sync/index.ts index 3a409912..63041440 100644 --- a/packages/plugin/src/features/sync/index.ts +++ b/packages/plugin/src/features/sync/index.ts @@ -17,7 +17,6 @@ export { splitSpaceErrors, } from "./controller"; export type { CompareResult, EngineDependencies } from "./engine"; -export { clampMaxSnapshots } from "./history/gc"; export type { VaultRestorePlan } from "./history/restore-vault"; export type { DeletedFile, diff --git a/packages/plugin/src/features/sync/operations/config-reset.ts b/packages/plugin/src/features/sync/operations/config-reset.ts index 4da0bd48..276a3ba6 100644 --- a/packages/plugin/src/features/sync/operations/config-reset.ts +++ b/packages/plugin/src/features/sync/operations/config-reset.ts @@ -1,6 +1,5 @@ import { ESyncLogOperation } from "@/core/logs"; import type { SettingsSyncCategories } from "@/core/settings"; -import { MANIFEST_VERSION } from "../constants"; import { type CompareResult, compare, @@ -42,8 +41,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, diff --git a/packages/plugin/src/features/sync/remote/manifest.ts b/packages/plugin/src/features/sync/remote/manifest.ts index 824f455a..44641cc7 100644 --- a/packages/plugin/src/features/sync/remote/manifest.ts +++ b/packages/plugin/src/features/sync/remote/manifest.ts @@ -190,7 +190,7 @@ export function buildManifest( snapshot: Pick, ): Manifest { return { - version: parent?.version ?? 1, + version: MANIFEST_VERSION, vaultId, snapshotId: randomId(), parentSnapshotId: parent?.snapshotId ?? null, diff --git a/packages/plugin/src/features/sync/remote/reset.ts b/packages/plugin/src/features/sync/remote/reset.ts index d5c3bbe1..fd133b15 100644 --- a/packages/plugin/src/features/sync/remote/reset.ts +++ b/packages/plugin/src/features/sync/remote/reset.ts @@ -3,6 +3,7 @@ import { runWithConcurrency } from "@/core/utils"; import type { StorageAdapter } from "@/features/storage"; import { REMOTE_HISTORY_LOG_KEY, + REMOTE_HISTORY_PREFIX, REMOTE_OBJECTS_PREFIX, REMOTE_PINS_PREFIX, } from "../constants"; @@ -17,10 +18,11 @@ 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 [objectKeys, pinKeys, historyKeys] = await Promise.all([ storage.list(REMOTE_OBJECTS_PREFIX), storage.list(REMOTE_PINS_PREFIX), + storage.list(REMOTE_HISTORY_PREFIX), ]); const keys = Array.from( new Set([ @@ -28,6 +30,7 @@ export async function resetRemoteStorage( REMOTE_HISTORY_LOG_KEY, ...objectKeys, ...pinKeys, + ...historyKeys, ]), ); let done = 0; diff --git a/packages/plugin/src/features/sync/remote/space-paths.ts b/packages/plugin/src/features/sync/remote/space-paths.ts index 846f4e74..ed8f523f 100644 --- a/packages/plugin/src/features/sync/remote/space-paths.ts +++ b/packages/plugin/src/features/sync/remote/space-paths.ts @@ -3,7 +3,7 @@ * everything is vault paths. */ -import type { HistoryLog } from "../history/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/features/sync/runtime/history-service.ts b/packages/plugin/src/features/sync/runtime/history-service.ts index f3df4c1b..5636cf33 100644 --- a/packages/plugin/src/features/sync/runtime/history-service.ts +++ b/packages/plugin/src/features/sync/runtime/history-service.ts @@ -13,20 +13,19 @@ import { import { runWithFileConcurrency } from "../changes/file-concurrency"; import type { EngineDependencies } from "../engine"; import { + type HistoryQuery, loadVersionBytes, listDeletedFiles as queryDeletedFiles, getFileHistory as queryFileHistory, listSnapshots as querySnapshots, + resolveSnapshotManifest, + setSnapshotPinned as storeSetSnapshotPinned, } from "../history/query"; import { planVaultRestore, sameRestorePlan, type VaultRestorePlan, } from "../history/restore-vault"; -import { - resolveSnapshotManifest, - setSnapshotPinned as storeSetSnapshotPinned, -} from "../history/store"; import type { DeletedFilesResult, FileVersion, @@ -64,22 +63,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)), @@ -89,11 +79,7 @@ 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, - }); + return querySnapshots(queryOf(session)); } /** What a restore would change, computed against a fresh scan of the vault. */ @@ -168,12 +154,7 @@ export class HistoryService { 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.", @@ -182,7 +163,7 @@ 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. */ setSnapshotPinned( snapshotId: string, pinned: boolean, @@ -190,14 +171,7 @@ export class HistoryService { ): Promise { return this.deps.enqueue(async () => { const session = await this.requireSession(); - await storeSetSnapshotPinned( - session.storage, - session.key, - session.space.root, - snapshotId, - pinned, - label, - ); + await storeSetSnapshotPinned(queryOf(session), snapshotId, pinned, label); }); } @@ -271,6 +245,15 @@ export class HistoryService { } } +function queryOf(session: EngineDependencies): HistoryQuery { + return { + storage: session.storage, + key: session.key, + root: session.space.root, + horizon: session.history?.horizon ?? null, + }; +} + /** 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 index 93fcd4dc..62b16207 100644 --- a/packages/plugin/src/features/sync/runtime/maintenance-service.ts +++ b/packages/plugin/src/features/sync/runtime/maintenance-service.ts @@ -1,6 +1,10 @@ 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 Space, VAULT_SPACE } from "../remote/space"; import { type CleanResult, cleanSummary, @@ -9,22 +13,84 @@ import { 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: () => Promise; + openSession: (space: Space) => 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; + /** As `enqueue`, without showing the plugin busy. */ + enqueueQuiet: (task: () => Promise) => Promise; + logInfo: Log; + logWarn: Log; } 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, history on or off: a 1.x pin blocks every sweep. + if (!this.legacyCleared.has(space.id)) { + const removed = await clearLegacyHistory( + session.storage, + session.key, + ); + this.legacyCleared.add(space.id); + if (removed > 0) { + await this.deps.logInfo( + ESyncLogOperation.Push, + `Old-format file history removed (${removed} object(s)).`, + ); + } + } + if (!session.history) return; + const { written, retired, swept } = await collectHistoryGarbage( + session.storage, + session.key, + session.space.root, + session.history, + ); + 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(); + const session = await this.deps.openSession(VAULT_SPACE); if (!session) return null; const result = await verifyRemote( session.storage, @@ -42,7 +108,7 @@ export class MaintenanceService { deepCleanRemote(): Promise { return this.deps.enqueue(async () => { - const session = await this.deps.openSession(); + const session = await this.deps.openSession(VAULT_SPACE); if (!session) return null; const result = await deepCleanOrphans( session.storage, diff --git a/packages/plugin/src/features/sync/runtime/maintenance.ts b/packages/plugin/src/features/sync/runtime/maintenance.ts index 0a5e3654..61bf08a5 100644 --- a/packages/plugin/src/features/sync/runtime/maintenance.ts +++ b/packages/plugin/src/features/sync/runtime/maintenance.ts @@ -1,20 +1,15 @@ import { DEFAULT_CONCURRENCY } from "@/core/constants"; import { decryptBytes, type EncryptionKey, sha256Hex } from "@/core/crypto"; -import { runWithConcurrency } from "@/core/utils"; import type { StorageAdapter } from "@/features/storage"; import { runWithFileConcurrency } from "../changes/file-concurrency"; -import { REMOTE_OBJECTS_PREFIX, REMOTE_PINS_PREFIX } from "../constants"; -import { changeEntries } from "../history/changes"; -import { pinKey, readHistoryLog, readPinManifest } from "../history/store"; -import type { HistoryLog } from "../history/types"; -import { fetchRemoteManifest, objectKey } from "../remote/manifest"; -import { settledKeys } from "../remote/uploads"; -import type { Manifest, ManifestEntry } from "../types"; +import { + reachableHashes, + type SweepOptions, + sweepObjects, +} from "../history/sweep"; +import { objectKey } from "../remote/manifest"; -export interface MaintenanceOptions { - concurrency?: number; - onProgress?: (done: number, total: number) => void; -} +export type MaintenanceOptions = Omit; export interface VerifyResult { checked: number; @@ -24,54 +19,6 @@ export interface VerifyResult { 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. */ @@ -117,89 +64,17 @@ export async function verifyRemote( return { checked: list.length, missing, corrupt }; } -/** Removes objects and pin manifests unreachable from HEAD or the history log. Needs a backend that can list. */ +/** Removes every settled object nothing reaches. */ 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(","); + 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 { - const parts = [ - `${result.deletedObjects} object(s)`, - `${result.deletedPins} pinned snapshot(s)`, - ]; - return `removed ${parts.join(", ")}.`; + return `removed ${result.deletedObjects} object(s).`; } diff --git a/packages/plugin/src/features/sync/runtime/operation-runner.ts b/packages/plugin/src/features/sync/runtime/operation-runner.ts index 169d8b2d..af6135af 100644 --- a/packages/plugin/src/features/sync/runtime/operation-runner.ts +++ b/packages/plugin/src/features/sync/runtime/operation-runner.ts @@ -51,6 +51,8 @@ interface OperationRunnerDeps { runtimeState: SyncControllerRuntimeState; clearFileDiffs: () => void; localRevision?: () => number; + /** A push of this device published its manifest. */ + onPublished?: (space: Space) => void; } export class OperationRunner { @@ -422,6 +424,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/features/transfer/transfer.ts b/packages/plugin/src/features/transfer/transfer.ts index 96f5af20..f0390e2a 100644 --- a/packages/plugin/src/features/transfer/transfer.ts +++ b/packages/plugin/src/features/transfer/transfer.ts @@ -52,7 +52,7 @@ const TRANSFER_FIELDS = { pushSharesRightAway: "s", shareEditsWait: "w", fileHistoryEnabled: "h", - fileHistoryMaxSnapshots: "j", + fileHistoryKeep: "y", historyAutoRefresh: "r", }, l: { diff --git a/packages/plugin/tests/app/settings/index.test.ts b/packages/plugin/tests/app/settings/index.test.ts index 87542eaa..85b0ef3b 100644 --- a/packages/plugin/tests/app/settings/index.test.ts +++ b/packages/plugin/tests/app/settings/index.test.ts @@ -5,6 +5,7 @@ import { BULK_DELETE_LIMIT_MAX, LIVE_SEND_MS, } from "@/core/constants"; +import type { MdsyncSettings } from "@/core/settings"; import { defaultS3Config } from "@/features/storage/backends/s3"; import { EStorageBackend, @@ -156,7 +157,6 @@ describe("mergeSettings clamps", () => { autoSyncIntervalMinutes: -5, autoPushSettleSeconds: 0, maxFileBytes: 0, - fileHistoryMaxSnapshots: 0, }); expect(merged.autoSyncIntervalMinutes).toBe( @@ -166,21 +166,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", () => { @@ -195,6 +190,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/features/source-control/timeline/timeline-rows.test.ts b/packages/plugin/tests/features/source-control/timeline/timeline-rows.test.ts index 3155bcee..6b6d851c 100644 --- a/packages/plugin/tests/features/source-control/timeline/timeline-rows.test.ts +++ b/packages/plugin/tests/features/source-control/timeline/timeline-rows.test.ts @@ -37,7 +37,7 @@ 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, ...overrides, diff --git a/packages/plugin/tests/features/source-control/trash/trash-rows.test.ts b/packages/plugin/tests/features/source-control/trash/trash-rows.test.ts index 8aa6e009..1ada3de3 100644 --- a/packages/plugin/tests/features/source-control/trash/trash-rows.test.ts +++ b/packages/plugin/tests/features/source-control/trash/trash-rows.test.ts @@ -12,6 +12,7 @@ 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, }; } @@ -47,37 +49,40 @@ 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 })).toBe( + `Kept in history until ${new Date(KEPT_UNTIL).toLocaleDateString()}`, ); }); - 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 })).toBe( + `Kept in history until ${new Date(past).toLocaleDateString()}`, ); }); - 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 })).toBeNull(); }); it("says a pin holds the record", () => { - expect(retentionText(null, 50)).toBe("Kept by a pinned snapshot"); + expect(retentionText({ pinned: true, keptUntil: null })).toBe( + "Kept by a pinned snapshot", + ); + }); + + it("lets a pin win over a date", () => { + expect(retentionText({ pinned: true, keptUntil: KEPT_UNTIL })).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, }); @@ -86,7 +91,7 @@ describe("buildTrashRows", () => { expect(row?.hash).toBe("H1"); expect(row?.meta).toBe("deleted 3 days ago · Device device-a · 2.0 KB"); expect(row?.note).toEqual({ - text: "Drops out of history after 50 more pushes", + text: `Kept in history until ${new Date(KEPT_UNTIL).toLocaleDateString()}`, 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/features/sync/category-reset-roundtrip.test.ts b/packages/plugin/tests/features/sync/category-reset-roundtrip.test.ts index 10cd1c88..78aaf5ce 100644 --- a/packages/plugin/tests/features/sync/category-reset-roundtrip.test.ts +++ b/packages/plugin/tests/features/sync/category-reset-roundtrip.test.ts @@ -10,6 +10,7 @@ import { useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; 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, @@ -48,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/features/sync/engine-roundtrip.test.ts b/packages/plugin/tests/features/sync/engine-roundtrip.test.ts index 6660a587..8a69f23c 100644 --- a/packages/plugin/tests/features/sync/engine-roundtrip.test.ts +++ b/packages/plugin/tests/features/sync/engine-roundtrip.test.ts @@ -1,7 +1,7 @@ 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 { 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"; @@ -12,10 +12,10 @@ import { type EngineDependencies, pushPaths, } from "@/features/sync/engine"; -import { readHistoryLog } from "@/features/sync/history/store"; +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 { SETTLED_AFTER_MS } from "@/features/sync/remote/uploads"; import { createScopePolicy } from "@/features/sync/scope/scope"; import { EChangeType, type SessionState } from "@/features/sync/types"; @@ -43,7 +43,7 @@ function deps( adapter: InMemoryAdapter, storage: FakeStorage, state: SessionState, - history?: { maxSnapshots: number }, + history?: HistoryConfig, ): EngineDependencies { return { space: VAULT_SPACE, @@ -219,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/features/sync/history/compose.test.ts b/packages/plugin/tests/features/sync/history/compose.test.ts new file mode 100644 index 00000000..f4474080 --- /dev/null +++ b/packages/plugin/tests/features/sync/history/compose.test.ts @@ -0,0 +1,170 @@ +import { seeded } from "@tests/helpers/seeded"; +import { describe, expect, it } from "vitest"; +import { + changeEntries, + composeChanges, + diffManifests, + undoChanges, +} 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"]); + }); +}); + +/** 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..a90bc877 --- /dev/null +++ b/packages/plugin/tests/features/sync/history/gc.test.ts @@ -0,0 +1,293 @@ +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 { collectHistoryGarbage } from "@/features/sync/history/gc"; +import { publishManifestWithHistory } from "@/features/sync/history/publish"; +import { + listSnapshots, + resolveSnapshotManifest, +} from "@/features/sync/history/query"; +import { objectKey } from "@/features/sync/remote/manifest"; +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()).toEqual({ written: 0, retired: 0, swept: 0 }); + }); + + it("sweeps the versions it freed only a day 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).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 }); + }); + + 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 index 03cfc854..2e930ecb 100644 --- a/packages/plugin/tests/features/sync/history/history-deleted.test.ts +++ b/packages/plugin/tests/features/sync/history/history-deleted.test.ts @@ -1,17 +1,23 @@ 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, - encryptJson, -} from "@/core/crypto/cipher"; -import { diffManifests } from "@/features/sync/history/changes"; +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 { pinKey, writeHistoryLog } from "@/features/sync/history/store"; -import type { HistoryLog, SnapshotEntry } from "@/features/sync/history/types"; +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)); @@ -39,40 +45,30 @@ function manifest( }; } -/** Builds a log from an oldest-first chain, newest snapshot first. */ -function logOf( - chain: readonly Manifest[], - pinnedIds: string[] = [], -): HistoryLog { - const snapshots: SnapshotEntry[] = []; - const changes: HistoryLog["changes"] = {}; - for (const [index, current] of chain.entries()) { - snapshots.unshift({ - id: current.snapshotId, - parentId: current.parentSnapshotId, - createdAt: current.createdAt, - deviceId: current.deviceId, - deviceName: current.deviceName, - pinned: pinnedIds.includes(current.snapshotId) || undefined, - }); - changes[current.snapshotId] = diffManifests( - chain[index - 1] ?? null, - current, - ); - } - return { version: 2, snapshots, changes }; -} - async function seed( chain: readonly Manifest[], - pinnedIds: string[] = [], + skip: readonly string[] = [], ): Promise { const storage = new FakeStorage(); - await publishManifest(storage, key, chain[chain.length - 1] as Manifest); - await writeHistoryLog(storage, key, "", logOf(chain, pinnedIds)); + 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([ @@ -80,7 +76,7 @@ describe("listDeletedFiles", () => { manifest("s2", "s1", { keep: entry("K1") }, 200), ]); - const result = await listDeletedFiles({ storage, key, root: "" }); + const result = await deleted(storage); expect(result.lagging).toBe(false); expect(result.files).toHaveLength(1); @@ -91,7 +87,22 @@ describe("listDeletedFiles", () => { expect(file?.snapshotId).toBe("s2"); expect(file?.createdAt).toBe(200); expect(file?.source).toBe("deleted"); - expect(file?.rank).toBe(0); + 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 () => { @@ -101,9 +112,7 @@ describe("listDeletedFiles", () => { manifest("s3", "s2", { a: entry("A2") }, 300), ]); - expect((await listDeletedFiles({ storage, key, root: "" })).files).toEqual( - [], - ); + expect((await deleted(storage)).files).toEqual([]); }); it("reports the latest death of a recreated-then-deleted file", async () => { @@ -114,13 +123,29 @@ describe("listDeletedFiles", () => { manifest("d", "c", {}, 400), ]); - const result = await listDeletedFiles({ storage, key, root: "" }); + 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("orders by log position, not by device clock", async () => { + 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), @@ -128,106 +153,147 @@ describe("listDeletedFiles", () => { manifest("s3", "s2", {}, 200), ]); - const result = await listDeletedFiles({ storage, key, root: "" }); - expect(result.files.map((f) => f.path)).toEqual(["recent", "old"]); - expect(result.files.map((f) => f.rank)).toEqual([0, 1]); + 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 chain = [ - manifest("s1", null, { early: entry("E1"), late: entry("L1") }, 100), - manifest("s2", "s1", { early: entry("E1") }, 200), - manifest("s3", "s2", {}, 300), - ]; - const log = logOf(chain); - // Drop the middle record, as a lost best-effort history update would. - const changes = { ...log.changes }; - delete changes.s2; - const storage = new FakeStorage(); - await publishManifest(storage, key, chain[2] as Manifest); - await writeHistoryLog(storage, key, "", { ...log, changes }); + 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 listDeletedFiles({ storage, key, root: "" }); + const result = await deleted(storage); expect(result.files.map((f) => f.path)).toEqual(["early"]); + expect(result.files[0]?.snapshotId).toBe("s3"); }); - it("flags a log that has not caught up with HEAD", async () => { - const chain = [ - manifest("s1", null, { a: entry("A1") }, 100), - manifest("s2", "s1", {}, 200), - ]; - const storage = new FakeStorage(); - await publishManifest(storage, key, chain[1] as Manifest); - await writeHistoryLog(storage, key, "", logOf(chain.slice(0, 1))); + 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 listDeletedFiles({ storage, key, root: "" }); + 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 log = logOf(chain, ["s1"]); - const storage = new FakeStorage(); - await publishManifest(storage, key, chain[1] as Manifest); - // Only the pin survives: the chain is cut back to HEAD alone. - await writeHistoryLog(storage, key, "", { - ...log, - snapshots: [log.snapshots[0] as SnapshotEntry, ...log.snapshots.slice(1)], - changes: { s2: log.changes.s2 as HistoryLog["changes"][string] }, - }); - await storage.put( - pinKey("s1"), - await encryptJson(key, chain[0] as Manifest), - ); + const storage = await seed(chain); + await pinSnapshot(storage, key, chain[0] as Manifest); - const result = await listDeletedFiles({ storage, key, root: "" }); - // The chain still records the deletion, so that record wins over the pin. + 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 head = manifest("s9", "s8", { kept: entry("K1") }, 900); - const storage = new FakeStorage(); - await publishManifest(storage, key, head); - await writeHistoryLog(storage, key, "", { - version: 2, - snapshots: [ - { - id: "s9", - parentId: "s8", - createdAt: 900, - deviceId: "d", - deviceName: "Device", - }, - { - id: "old", - parentId: null, - createdAt: 100, - deviceId: "d", - deviceName: "Device", - pinned: true, - }, - ], - changes: { s9: { added: {}, modified: {}, deleted: {} } }, - }); - await storage.put( - pinKey("old"), - await encryptJson( - key, - manifest("old", null, { kept: entry("K0"), lost: entry("L1", 5) }, 100), - ), + 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 listDeletedFiles({ storage, key, root: "" }); + 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]?.rank).toBeNull(); + expect(result.files[0]?.pinned).toBe(true); + expect(result.files[0]?.keptUntil).toBeNull(); }); it("lists a deleted file named like an Object member", async () => { @@ -236,89 +302,78 @@ describe("listDeletedFiles", () => { manifest("s2", "s1", {}, 200), ]); - const result = await listDeletedFiles({ storage, key, root: "" }); + const result = await deleted(storage); expect(result.files.map((f) => f.path)).toEqual(["toString"]); }); - it("does not evict-count a pinned snapshot when ranking", async () => { - const storage = await seed( - [ - manifest("s1", null, { a: entry("A1"), b: entry("B1") }, 100), - manifest("s2", "s1", { a: entry("A1") }, 200), - manifest("s3", "s2", {}, 300), - ], - ["s3"], - ); - - const result = await listDeletedFiles({ storage, key, root: "" }); - // s3 is pinned, so nothing evicts the record it carries. - expect(result.files.map((f) => [f.path, f.rank])).toEqual([ - ["a", null], - ["b", 0], - ]); - }); - - it("reports a truncated walk when HEAD's own record is missing", async () => { + it("clears retention only for what a pin holds", async () => { const chain = [ - manifest("s1", null, { a: entry("A1") }, 100), - manifest("s2", "s1", {}, 200), + manifest("s1", null, { a: entry("A1"), b: entry("B1") }, 100), + manifest("s2", "s1", { a: entry("A1") }, 200), + manifest("s3", "s2", {}, 300), ]; - const log = logOf(chain); - const { s2: _dropped, ...changes } = log.changes; - const storage = new FakeStorage(); - await publishManifest(storage, key, chain[1] as Manifest); - await writeHistoryLog(storage, key, "", { ...log, changes }); + const storage = await seed(chain); + await pinSnapshot(storage, key, chain[1] as Manifest); - const result = await listDeletedFiles({ storage, key, root: "" }); - // The chain is not empty, so this must not read as a healthy empty trash. - expect(result.lagging).toBe(false); - expect(result.truncated).toBe(true); - expect(result.files).toEqual([]); + 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("still reaches a pin sitting past a gap in the chain", async () => { + it("keeps the countdown when a pin holds another version of the file", async () => { const chain = [ - manifest("p", null, { archived: entry("R1", 9) }, 100), - manifest("s2", "p", {}, 200), + manifest("p", null, { f: entry("F1") }, 100), + manifest("s2", "p", { f: entry("F2") }, 200), manifest("s3", "s2", {}, 300), ]; - const log = logOf(chain, ["p"]); - // Drop s2's record: the walk stops before it ever considers the pin. - const { s2: _dropped, ...changes } = log.changes; - const storage = new FakeStorage(); - await publishManifest(storage, key, chain[2] as Manifest); - await writeHistoryLog(storage, key, "", { ...log, changes }); - await storage.put( - pinKey("p"), - await encryptJson(key, chain[0] as Manifest), - ); + const storage = await seed(chain); + stamp(storage, ["p", "s2", "s3"]); + await pinSnapshot(storage, key, chain[0] as Manifest); - const result = await listDeletedFiles({ storage, key, root: "" }); - expect(result.truncated).toBe(true); - expect(result.files.map((f) => f.path)).toEqual(["archived"]); - expect(result.files[0]?.source).toBe("pinned"); + 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 eviction countdown when an older pin still holds the file", async () => { + 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 = new FakeStorage(); - await publishManifest(storage, key, chain[2] as Manifest); - await writeHistoryLog(storage, key, "", logOf(chain, ["p"])); - await storage.put( - pinKey("p"), - await encryptJson(key, chain[0] as Manifest), - ); + const storage = await seed(chain); + await pinSnapshot(storage, key, chain[0] as Manifest); - const result = await listDeletedFiles({ storage, key, root: "" }); + 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]?.rank).toBeNull(); + 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 () => { @@ -328,18 +383,11 @@ describe("listDeletedFiles", () => { manifest("p3", "p2", { f: entry("F3") }, 300), manifest("s4", "p3", {}, 400), ]; - const storage = new FakeStorage(); - await publishManifest(storage, key, chain[3] as Manifest); - const log = logOf(chain, ["p1", "p2", "p3"]); - // Without s4's record the walk stops, so the pins alone explain the files. - const { s4: _dropped, ...changes } = log.changes; - await writeHistoryLog(storage, key, "", { ...log, changes }); + // 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 [index, id] of ["p1", "p2", "p3"].entries()) { - await storage.put( - pinKey(id), - await encryptJson(key, chain[index] as Manifest), - ); + 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) => { @@ -348,19 +396,19 @@ describe("listDeletedFiles", () => { return get(path); }); - const result = await listDeletedFiles({ storage, key, root: "" }); + 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.rank === null)).toBe(true); + expect(result.files.every((file) => file.pinned)).toBe(true); }); it("returns nothing when no vault is published", async () => { const storage = new FakeStorage(); - const result = await listDeletedFiles({ storage, key, root: "" }); + const result = await deleted(storage); expect(result).toEqual({ files: [], lagging: false, truncated: false }); }); }); @@ -372,9 +420,10 @@ describe("listSnapshots", () => { manifest("s2", "s1", { a: entry("A2", 15), c: entry("C1", 5) }, 200), ]); - const result = await listSnapshots({ storage, key, root: "" }); + 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) }, @@ -387,84 +436,119 @@ describe("listSnapshots", () => { }); }); - it("marks only what a replay can actually reach as restorable", async () => { + 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 log = logOf(chain); - // Without s2's record the walk cannot step past s2 to reach s1. - const { s2: _dropped, ...changes } = log.changes; - const storage = new FakeStorage(); - await publishManifest(storage, key, chain[2] as Manifest); - await writeHistoryLog(storage, key, "", { ...log, changes }); + 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("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 result = await listSnapshots({ storage, key, root: "" }); + expect( + (await snapshots(storage)).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"); + }); + + 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([ - ["s3", true, true], - ["s2", true, false], + ["s2", false, true], ["s1", false, true], ]); }); - it("counts a pin as restorable even outside the replayable chain", async () => { + 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 log = logOf(chain, ["s1"]); - const { s2: _dropped, ...changes } = log.changes; - const storage = new FakeStorage(); - await publishManifest(storage, key, chain[1] as Manifest); - await writeHistoryLog(storage, key, "", { ...log, changes }); + const storage = await seed(chain, ["s2"]); + await pinSnapshot(storage, key, chain[0] as Manifest); - const result = await listSnapshots({ storage, key, root: "" }); + 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?.rank).toBeNull(); + expect(pinned?.keptUntil).toBeNull(); }); - it("flags a log that has not caught up with HEAD", async () => { - const chain = [ - manifest("s1", null, { a: entry("A1") }, 100), - manifest("s2", "s1", {}, 200), - ]; - const storage = new FakeStorage(); - await publishManifest(storage, key, chain[1] as Manifest); - await writeHistoryLog(storage, key, "", logOf(chain.slice(0, 1))); - - expect((await listSnapshots({ storage, key, root: "" })).lagging).toBe( - true, + 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, not log index", async () => { + 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 listSnapshots({ storage, key, root: "" }); + 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 when log lags behind remote", async () => { - const chain = [ - manifest("s1", null, { a: entry("A1") }, 100), - manifest("s2", "s1", {}, 200), - ]; - const storage = new FakeStorage(); - await publishManifest(storage, key, chain[1] as Manifest); - await writeHistoryLog(storage, key, "", logOf(chain.slice(0, 1))); + 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 listSnapshots({ storage, key, root: "" }); + const result = await snapshots(storage); expect(result.snapshots.every((s) => !s.isHead)).toBe(true); }); }); diff --git a/packages/plugin/tests/features/sync/history/history-gc.test.ts b/packages/plugin/tests/features/sync/history/history-gc.test.ts deleted file mode 100644 index 10e7800a..00000000 --- a/packages/plugin/tests/features/sync/history/history-gc.test.ts +++ /dev/null @@ -1,789 +0,0 @@ -import { FakeStorage } from "@tests/helpers/fake-storage"; -import { publishManifest } from "@tests/helpers/manifest"; -import { 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 { diffManifests } from "@/features/sync/history/changes"; -import { - clampMaxSnapshots, - collectGarbage, - gcExcessBuffer, - shouldRunGc, -} from "@/features/sync/history/gc"; -import { - pinKey, - readHistoryLog, - readPinManifest, - setSnapshotPinned, - writeHistoryLog, -} from "@/features/sync/history/store"; -import type { HistoryLog, SnapshotEntry } from "@/features/sync/history/types"; -import { objectKey } from "@/features/sync/remote/manifest"; -import type { EFileKind, Manifest } from "@/features/sync/types"; - -const DAY_MS = 24 * 60 * 60 * 1000; - -function manifest( - snapshotId: string, - parentSnapshotId: string | null, - files: Record, -): 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: 1, - vaultId: "v", - snapshotId, - parentSnapshotId, - createdAt: 1, - deviceId: "d", - files: entries, - }; -} - -/** Builds a log from an oldest-first manifest chain. */ -function logOf( - chain: readonly Manifest[], - pinnedIds: string[] = [], -): HistoryLog { - const snapshots: SnapshotEntry[] = []; - const changes: HistoryLog["changes"] = {}; - for (const [index, current] of chain.entries()) { - snapshots.unshift({ - id: current.snapshotId, - parentId: current.parentSnapshotId, - createdAt: index + 1, - deviceId: "d", - pinned: pinnedIds.includes(current.snapshotId) || undefined, - }); - changes[current.snapshotId] = diffManifests( - chain[index - 1] ?? null, - current, - ); - } - return { version: 2, snapshots, changes }; -} - -/** `count` unpinned records, all created at `createdAt`. */ -function logOfAge(count: number, createdAt: number): HistoryLog { - const snapshots = Array.from({ length: count }, (_, index) => ({ - id: `s${index}`, - parentId: null, - createdAt, - deviceId: "d", - })); - return { version: 2, snapshots, changes: {} }; -} - -async function key(): Promise { - return deriveKey("pw", new Uint8Array(16)); -} - -async function seedObjects( - storage: FakeStorage, - hashes: readonly string[], -): Promise { - for (const hash of hashes) { - await storage.put(objectKey(hash), new Uint8Array([1])); - } -} - -describe("file-history GC math", () => { - it("clampMaxSnapshots bounds and floors", () => { - expect(clampMaxSnapshots(Number.NaN)).toBe(1); - expect(clampMaxSnapshots(0)).toBe(1); - expect(clampMaxSnapshots(-7)).toBe(1); - expect(clampMaxSnapshots(5.9)).toBe(5); - expect(clampMaxSnapshots(10_000)).toBe(1000); - }); - - it("gcExcessBuffer is max(ratio, floor)", () => { - expect(gcExcessBuffer(50)).toBe(15); - expect(gcExcessBuffer(100)).toBe(30); - expect(gcExcessBuffer(5)).toBe(10); - expect(gcExcessBuffer(1)).toBe(10); - }); - - it("shouldRunGc only fires past the buffer", () => { - const now = 2 * DAY_MS; - expect(shouldRunGc(logOfAge(65, 0), 50, now)).toBe(false); - expect(shouldRunGc(logOfAge(66, 0), 50, now)).toBe(true); - expect(shouldRunGc(logOfAge(15, 0), 5, now)).toBe(false); - expect(shouldRunGc(logOfAge(16, 0), 5, now)).toBe(true); - }); - - it("shouldRunGc counts only records old enough to have settled", () => { - const now = 2 * DAY_MS; - expect(shouldRunGc(logOfAge(200, now - 60_000), 50, now)).toBe(false); - expect(shouldRunGc(logOfAge(200, now - DAY_MS), 50, now)).toBe(true); - }); -}); - -describe("collectGarbage (change log)", () => { - it("checks every evicted pin with bounded concurrency before deleting objects", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = Array.from({ length: 10 }, (_, index) => - manifest(`s${index}`, index === 0 ? null : `s${index - 1}`, { - a: `A${index}`, - }), - ); - const head = chain[9] as Manifest; - const log = logOf(chain); - await publishManifest(storage, k, head); - await writeHistoryLog(storage, k, "", log); - const checked: string[] = []; - let active = 0; - let peak = 0; - vi.spyOn(storage, "exists").mockImplementation(async (path) => { - checked.push(path); - peak = Math.max(peak, ++active); - await new Promise((resolve) => setTimeout(resolve, 0)); - active--; - return path === pinKey("s0"); - }); - const remove = vi.spyOn(storage, "delete"); - const result = await collectGarbage({ - storage, - key: k, - root: "", - log, - maxSnapshots: 1, - headManifest: head, - }); - expect(checked.sort()).toEqual( - chain - .slice(0, 9) - .map((entry) => pinKey(entry.snapshotId)) - .sort(), - ); - expect(peak).toBe(4); - expect(result.skippedObjectSweep).toBe(true); - expect(remove).not.toHaveBeenCalled(); - }); - - it("never sweeps after a failed pin check", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = [ - manifest("old", null, { a: "A" }), - manifest("head", "old", { a: "B" }), - ]; - const head = chain[1] as Manifest; - const log = logOf(chain); - await publishManifest(storage, k, head); - await writeHistoryLog(storage, k, "", log); - vi.spyOn(storage, "exists").mockRejectedValue(new Error("pin unavailable")); - const remove = vi.spyOn(storage, "delete"); - await expect( - collectGarbage({ - storage, - key: k, - root: "", - log, - maxSnapshots: 1, - headManifest: head, - }), - ).rejects.toThrow("pin unavailable"); - expect(remove).not.toHaveBeenCalled(); - }); - - it("sweeps only hashes unreachable from retained records and HEAD", async () => { - const storage = new FakeStorage(); - const k = await key(); - // s1..s5 oldest→newest. file "a": A1,A1,A2,A2,A3 - const chain = [ - manifest("s1", null, { a: "A1" }), - manifest("s2", "s1", { a: "A1" }), - manifest("s3", "s2", { a: "A2" }), - manifest("s4", "s3", { a: "A2" }), - manifest("s5", "s4", { a: "A3" }), - ]; - const head = chain[4] as Manifest; - await publishManifest(storage, k, head); - await seedObjects(storage, ["A1", "A2", "A3"]); - storage.age(DAY_MS + 1); - const log = logOf(chain); - await writeHistoryLog(storage, k, "", log); - - const res = await collectGarbage({ - storage, - key: k, - root: "", - log, - maxSnapshots: 2, - headManifest: head, - }); - - expect(res.skippedObjectSweep).toBe(false); - expect(res.deletedSnapshots).toBe(3); - expect(res.deletedObjects).toBe(1); - // A1 only lives in evicted records → swept. A2 is retained s4's `from`. A3 is HEAD. - expect(await storage.exists(objectKey("A1"))).toBe(false); - expect(await storage.exists(objectKey("A2"))).toBe(true); - expect(await storage.exists(objectKey("A3"))).toBe(true); - const next = await readHistoryLog(storage, k, ""); - expect(next.snapshots.map((e) => e.id)).toEqual(["s5", "s4"]); - expect(Object.keys(next.changes).sort()).toEqual(["s4", "s5"]); - }); - - it("keeps an orphan another device re-uploaded for a push not yet published", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = [ - manifest("s1", null, { a: "A1" }), - manifest("s2", "s1", { a: "A2" }), - manifest("s3", "s2", { a: "A3" }), - manifest("s4", "s3", { a: "A4" }), - ]; - const head = chain[3] as Manifest; - await publishManifest(storage, k, head); - await seedObjects(storage, ["A1", "A2", "A3", "A4"]); - storage.age(DAY_MS + 1); - await seedObjects(storage, ["A1"]); - const log = logOf(chain); - await writeHistoryLog(storage, k, "", log); - - const res = await collectGarbage({ - storage, - key: k, - root: "", - log, - maxSnapshots: 1, - headManifest: head, - }); - - // s1 and s2 name the settling A1, so they stay, and A2 with them; s3 holds nothing only it names. - expect(res.deletedObjects).toBe(0); - expect(res.log.snapshots.map((entry) => entry.id)).toEqual([ - "s4", - "s2", - "s1", - ]); - expect(await storage.exists(objectKey("A1"))).toBe(true); - expect(await storage.exists(objectKey("A2"))).toBe(true); - - storage.age(DAY_MS + 1); - const later = await collectGarbage({ - storage, - key: k, - root: "", - log: res.log, - maxSnapshots: 1, - headManifest: head, - }); - expect(later.log.snapshots.map((entry) => entry.id)).toEqual(["s4"]); - expect(await storage.exists(objectKey("A1"))).toBe(false); - expect(await storage.exists(objectKey("A2"))).toBe(false); - }); - - it("never evicts a record too young for its blobs to have settled", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = [ - manifest("s1", null, { a: "A1" }), - manifest("s2", "s1", { a: "A2" }), - ]; - const head = chain[1] as Manifest; - await publishManifest(storage, k, head); - await seedObjects(storage, ["A1", "A2"]); - const log = logOf(chain); - for (const entry of log.snapshots) entry.createdAt = Date.now(); - await writeHistoryLog(storage, k, "", log); - const list = vi.spyOn(storage, "listDetailed"); - - const res = await collectGarbage({ - storage, - key: k, - root: "", - log, - maxSnapshots: 1, - headManifest: head, - }); - - expect(res.log).toBe(log); - expect(list).not.toHaveBeenCalled(); - expect(await storage.exists(objectKey("A1"))).toBe(true); - }); - - it("counts only the blobs it could delete", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = [ - manifest("s1", null, { a: "A1" }), - manifest("s2", "s1", { a: "A2" }), - manifest("s3", "s2", { a: "A3" }), - ]; - const head = chain[2] as Manifest; - await publishManifest(storage, k, head); - await seedObjects(storage, ["A1", "A2", "A3"]); - storage.age(DAY_MS + 1); - const log = logOf(chain); - await writeHistoryLog(storage, k, "", log); - vi.spyOn(storage, "delete").mockRejectedValue(new Error("denied")); - - const res = await collectGarbage({ - storage, - key: k, - root: "", - log, - maxSnapshots: 1, - headManifest: head, - }); - - expect(res.deletedObjects).toBe(0); - expect(await storage.exists(objectKey("A1"))).toBe(true); - }); - - it("skips the object sweep when a pinned manifest is unreadable", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = [ - manifest("s1", null, { a: "A1" }), - manifest("s2", "s1", { a: "A2" }), - manifest("s3", "s2", { a: "A2" }), - manifest("s4", "s3", { a: "A2" }), - manifest("s5", "s4", { a: "A3" }), - ]; - const head = chain[4] as Manifest; - await publishManifest(storage, k, head); - await seedObjects(storage, ["A1", "A2", "A3"]); - const log = logOf(chain, ["s1"]); - await writeHistoryLog(storage, k, "", log); - // s1 is pinned but its manifest was never stored. - - const res = await collectGarbage({ - storage, - key: k, - root: "", - log, - maxSnapshots: 2, - headManifest: head, - }); - - expect(res.skippedObjectSweep).toBe(true); - expect(res.deletedObjects).toBe(0); - expect(await storage.exists(objectKey("A1"))).toBe(true); - // Log pruning still happens; only the sweep is withheld. - expect(res.deletedSnapshots).toBe(2); - const next = await readHistoryLog(storage, k, ""); - expect(next.snapshots.map((e) => e.id)).toEqual(["s5", "s4", "s1"]); - }); - - it("reads pinned manifests concurrently and warns once per missing pin", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = Array.from({ length: 8 }, (_, index) => - manifest(`s${index}`, index === 0 ? null : `s${index - 1}`, { - a: `A${index}`, - }), - ); - const head = chain[7] as Manifest; - const pinnedIds = ["s0", "s1", "s2", "s3", "s4", "s5"]; - const log = logOf(chain, pinnedIds); - await publishManifest(storage, k, head); - await seedObjects( - storage, - chain.map((_, index) => `A${index}`), - ); - storage.age(DAY_MS + 1); - await writeHistoryLog(storage, k, "", log); - for (const [index, id] of pinnedIds.entries()) { - if (id === "s2" || id === "s4") continue; - await storage.put( - pinKey(id), - await encryptJson(k, chain[index] as Manifest), - ); - } - const pinKeys = new Set(pinnedIds.map(pinKey)); - const get = storage.get.bind(storage); - let active = 0; - let peak = 0; - vi.spyOn(storage, "get").mockImplementation(async (path) => { - if (!pinKeys.has(path)) return get(path); - peak = Math.max(peak, ++active); - await new Promise((resolve) => setTimeout(resolve, 0)); - active--; - return get(path); - }); - const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); - - const res = await collectGarbage({ - storage, - key: k, - root: "", - log, - maxSnapshots: 1, - headManifest: head, - }); - - expect(peak).toBe(4); - const messages = warn.mock.calls.map((call) => String(call[0])); - expect( - messages.filter((m) => m.includes("has no stored manifest")), - ).toHaveLength(2); - expect(res.skippedObjectSweep).toBe(true); - expect(res.deletedObjects).toBe(0); - warn.mockRestore(); - }); - - it("withholds the sweep when a pin manifest exists without its flag", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = [ - manifest("s1", null, { a: "A1" }), - manifest("s2", "s1", { a: "A2" }), - manifest("s3", "s2", { a: "A3" }), - ]; - const head = chain[2] as Manifest; - await publishManifest(storage, k, head); - await seedObjects(storage, ["A1", "A2", "A3"]); - storage.age(DAY_MS + 1); - const log = logOf(chain); - await writeHistoryLog(storage, k, "", log); - // Another device wrote the manifest but has not flagged it yet, and our own - // log rewrite would drop the flag anyway - so storage is the only signal. - await storage.put(pinKey("s1"), await encryptJson(k, chain[0] as Manifest)); - - const res = await collectGarbage({ - storage, - key: k, - root: "", - log, - maxSnapshots: 1, - headManifest: head, - }); - - expect(res.skippedObjectSweep).toBe(true); - expect(res.deletedObjects).toBe(0); - expect(await storage.exists(objectKey("A1"))).toBe(true); - }); - - it("withholds the sweep when another device publishes while pruning", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = [ - manifest("s1", null, { a: "A1" }), - manifest("s2", "s1", { a: "A2" }), - manifest("s3", "s2", { a: "A3" }), - ]; - await publishManifest(storage, k, chain[2] as Manifest); - await seedObjects(storage, ["A1", "A2", "A3"]); - storage.age(DAY_MS + 1); - const log = logOf(chain); - await writeHistoryLog(storage, k, "", log); - - const res = await collectGarbage({ - storage, - key: k, - root: "", - log, - maxSnapshots: 1, - // We began against s2, but s3 is what is published now. - headManifest: chain[1] as Manifest, - }); - - expect(res.skippedObjectSweep).toBe(true); - expect(res.deletedObjects).toBe(0); - }); - - it("is a no-op when within the retention limit", async () => { - const storage = new FakeStorage(); - const k = await key(); - const log = logOf([manifest("s1", null, {})]); - const res = await collectGarbage({ - storage, - key: k, - root: "", - log, - maxSnapshots: 50, - headManifest: manifest("s1", null, {}), - }); - expect(res.deletedSnapshots).toBe(0); - expect(res.deletedObjects).toBe(0); - expect(res.log).toBe(log); - }); - - it("keeps a pinned snapshot and every object its manifest references", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = [ - manifest("s1", null, { a: "A1" }), - manifest("s2", "s1", { a: "A2" }), - manifest("s3", "s2", { a: "A3" }), - manifest("s4", "s3", { a: "A4" }), - manifest("s5", "s4", { a: "A5" }), - ]; - const head = chain[4] as Manifest; - await publishManifest(storage, k, head); - await seedObjects(storage, ["A1", "A2", "A3", "A4", "A5"]); - storage.age(DAY_MS + 1); - const log = logOf(chain, ["s1"]); - await writeHistoryLog(storage, k, "", log); - await storage.put(pinKey("s1"), await encryptJson(k, chain[0] as Manifest)); - - const res = await collectGarbage({ - storage, - key: k, - root: "", - log, - maxSnapshots: 2, - headManifest: head, - }); - - expect(res.skippedObjectSweep).toBe(false); - // kept: s5, s4 (newest 2 non-pinned) + s1 (pinned). evicted: s3, s2. - expect(res.log.snapshots.map((e) => e.id)).toEqual(["s5", "s4", "s1"]); - expect(res.deletedSnapshots).toBe(2); - // A1 survives only because the pinned manifest still names it. - expect(await storage.exists(objectKey("A1"))).toBe(true); - expect(await storage.exists(objectKey("A2"))).toBe(false); - expect(await storage.exists(objectKey("A4"))).toBe(true); - expect(await storage.exists(objectKey("A5"))).toBe(true); - }); - - it("withholds the sweep when HEAD cannot be re-read", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = [ - manifest("s1", null, { a: "A1" }), - manifest("s2", "s1", { a: "A2" }), - manifest("s3", "s2", { a: "A3" }), - ]; - // HEAD is never published, so the pre-sweep re-read finds nothing. - await seedObjects(storage, ["A1", "A2", "A3"]); - storage.age(DAY_MS + 1); - const log = logOf(chain); - await writeHistoryLog(storage, k, "", log); - - const res = await collectGarbage({ - storage, - key: k, - root: "", - log, - maxSnapshots: 1, - headManifest: chain[2] as Manifest, - }); - - expect(res.skippedObjectSweep).toBe(true); - expect(res.deletedObjects).toBe(0); - expect(await storage.exists(objectKey("A1"))).toBe(true); - }); - - it("keeps a snapshot another device pinned mid-run, and skips the sweep", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = [ - manifest("s1", null, { a: "A1" }), - manifest("s2", "s1", { a: "A2" }), - manifest("s3", "s2", { a: "A3" }), - ]; - const head = chain[2] as Manifest; - await publishManifest(storage, k, head); - await seedObjects(storage, ["A1", "A2", "A3"]); - storage.age(DAY_MS + 1); - const log = logOf(chain); - // Stored log already carries the other device's pin on the snapshot we evict. - await writeHistoryLog(storage, k, "", logOf(chain, ["s1"])); - - const res = await collectGarbage({ - storage, - key: k, - root: "", - log, - maxSnapshots: 1, - headManifest: head, - }); - - expect(res.skippedObjectSweep).toBe(true); - expect(res.deletedObjects).toBe(0); - expect(res.deletedSnapshots).toBe(1); - expect(await storage.exists(objectKey("A1"))).toBe(true); - const next = await readHistoryLog(storage, k, ""); - expect(next.snapshots.map((e) => e.id)).toEqual(["s3", "s1"]); - // Its change record must survive with it, or the pin loses its history. - expect(next.changes.s1).toBeDefined(); - }); - - it("is a no-op when only pinned snapshots exceed the limit", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = [ - manifest("s1", null, { a: "A1" }), - manifest("s2", "s1", { a: "A2" }), - manifest("s3", "s2", { a: "A3" }), - ]; - const log = logOf(chain, ["s3", "s2"]); - const res = await collectGarbage({ - storage, - key: k, - root: "", - log, - maxSnapshots: 2, - headManifest: chain[2] as Manifest, - }); - expect(res.deletedSnapshots).toBe(0); - expect(res.log).toBe(log); - }); -}); - -describe("setSnapshotPinned", () => { - it("stores a full manifest for the pin and flips the flag", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = [ - manifest("s1", null, { a: "A1" }), - manifest("s2", "s1", { a: "A2", b: "B1" }), - ]; - const head = chain[1] as Manifest; - await publishManifest(storage, k, head); - await writeHistoryLog(storage, k, "", logOf(chain)); - - await setSnapshotPinned(storage, k, "", "s1", true); - - const after = await readHistoryLog(storage, k, ""); - expect(after.snapshots.find((e) => e.id === "s1")?.pinned).toBe(true); - expect(after.snapshots.find((e) => e.id === "s2")?.pinned).toBe(undefined); - expect(await storage.exists(pinKey("s1"))).toBe(true); - }); - - it("keeps the pin manifest when the flag lands but its check fails", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = [ - manifest("s1", null, { a: "A1" }), - manifest("s2", "s1", { a: "A2" }), - ]; - await publishManifest(storage, k, chain[1] as Manifest); - await writeHistoryLog(storage, k, "", logOf(chain)); - const put = storage.put.bind(storage); - vi.spyOn(storage, "put").mockImplementation(async (objectKey, body) => { - await put(objectKey, body); - if (objectKey === REMOTE_HISTORY_LOG_KEY) - vi.spyOn(storage, "get").mockRejectedValueOnce(new Error("offline")); - }); - - await expect(setSnapshotPinned(storage, k, "", "s1", true)).rejects.toThrow( - "offline", - ); - - const after = await readHistoryLog(storage, k, ""); - expect(after.snapshots.find((e) => e.id === "s1")?.pinned).toBe(true); - expect(await storage.exists(pinKey("s1"))).toBe(true); - }); - - it("removes the pin manifest on unpin", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = [ - manifest("s1", null, { a: "A1" }), - manifest("s2", "s1", { a: "A2" }), - ]; - await publishManifest(storage, k, chain[1] as Manifest); - await writeHistoryLog(storage, k, "", logOf(chain)); - - await setSnapshotPinned(storage, k, "", "s1", true); - await setSnapshotPinned(storage, k, "", "s1", false); - - const after = await readHistoryLog(storage, k, ""); - expect(after.snapshots.find((e) => e.id === "s1")?.pinned).toBe(false); - expect(await storage.exists(pinKey("s1"))).toBe(false); - }); - - it("re-pins an already pinned snapshot without needing a replay", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = [ - manifest("s1", null, { a: "A1" }), - manifest("s2", "s1", { a: "A2" }), - manifest("s3", "s2", { a: "A3" }), - ]; - await publishManifest(storage, k, chain[2] as Manifest); - await writeHistoryLog(storage, k, "", logOf(chain)); - await setSnapshotPinned(storage, k, "", "s1", true); - - // GC later evicts the middle, so s1 is no longer reachable by replay. - const truncated = logOf(chain, ["s1"]); - await writeHistoryLog(storage, k, "", { - ...truncated, - snapshots: truncated.snapshots.filter((e) => e.id !== "s2"), - }); - - await expect( - setSnapshotPinned(storage, k, "", "s1", true), - ).resolves.toBeUndefined(); - expect(await storage.exists(pinKey("s1"))).toBe(true); - }); - - it("rewrites a pin whose stored manifest is unreadable", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = [ - manifest("s1", null, { a: "A1" }), - manifest("s2", "s1", { a: "A2" }), - ]; - await publishManifest(storage, k, chain[1] as Manifest); - await writeHistoryLog(storage, k, "", logOf(chain)); - // Garbage at the pin key must not be mistaken for a valid pin. - await storage.put(pinKey("s1"), new Uint8Array([1, 2, 3])); - - await setSnapshotPinned(storage, k, "", "s1", true); - - const stored = await readPinManifest(storage, k, "", "s1"); - expect(stored?.snapshotId).toBe("s1"); - }); - - it("refuses to pin a snapshot the chain can no longer reach", async () => { - const storage = new FakeStorage(); - const k = await key(); - const chain = [ - manifest("s1", null, { a: "A1" }), - manifest("s2", "s1", { a: "A2" }), - ]; - await publishManifest(storage, k, chain[1] as Manifest); - const log = logOf(chain); - // Drop the middle of the chain, as GC would after eviction. - await writeHistoryLog(storage, k, "", { - ...log, - snapshots: log.snapshots.filter((e) => e.id !== "s1"), - }); - - await expect(setSnapshotPinned(storage, k, "", "s1", true)).rejects.toThrow( - /can no longer be rebuilt/, - ); - expect(await storage.exists(pinKey("s1"))).toBe(false); - }); -}); - -describe("readHistoryLog", () => { - it("refuses a newer client's log rather than rewrite it", async () => { - const storage = new FakeStorage(); - const k = await key(); - const newer = { version: 3, snapshots: [], changes: {} }; - await storage.put(REMOTE_HISTORY_LOG_KEY, await encryptJson(k, newer)); - - await expect(readHistoryLog(storage, k, "")).rejects.toThrow(/newer/); - }); - - it("refuses a log that reads as missing but is there", async () => { - const storage = new FakeStorage(); - const k = await key(); - const log = { version: 2, snapshots: [], changes: {} }; - await storage.put(REMOTE_HISTORY_LOG_KEY, await encryptJson(k, log)); - vi.spyOn(storage, "get").mockResolvedValueOnce(null); - - await expect(readHistoryLog(storage, k, "")).rejects.toThrow(/refusing/); - }); - - it("reads a log that is not there as empty", async () => { - expect( - (await readHistoryLog(new FakeStorage(), await key(), "")).snapshots, - ).toEqual([]); - }); -}); diff --git a/packages/plugin/tests/features/sync/history/history-log.test.ts b/packages/plugin/tests/features/sync/history/history-query.test.ts similarity index 50% rename from packages/plugin/tests/features/sync/history/history-log.test.ts rename to packages/plugin/tests/features/sync/history/history-query.test.ts index cad336da..af8b559c 100644 --- a/packages/plugin/tests/features/sync/history/history-log.test.ts +++ b/packages/plugin/tests/features/sync/history/history-query.test.ts @@ -1,24 +1,11 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; -import { publishManifest } from "@tests/helpers/manifest"; +import { pinSnapshot, seedChain } from "@tests/helpers/history"; import { beforeAll, describe, expect, it } from "vitest"; -import { - deriveKey, - type EncryptionKey, - encryptJson, -} from "@/core/crypto/cipher"; -import { - contiguousLength, - diffManifests, - undoChanges, -} from "@/features/sync/history/changes"; -import { getFileHistory } from "@/features/sync/history/query"; +import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; +import { diffManifests, undoChanges } from "@/features/sync/history/changes"; +import { getFileHistory, readTimeline } from "@/features/sync/history/query"; +import { pushKey } from "@/features/sync/history/remote"; import { replayTo } from "@/features/sync/history/replay"; -import { - pinKey, - prependSnapshot, - writeHistoryLog, -} from "@/features/sync/history/store"; -import type { HistoryLog, SnapshotEntry } from "@/features/sync/history/types"; import type { EFileKind, Manifest, ManifestEntry } from "@/features/sync/types"; let key: EncryptionKey; @@ -48,30 +35,6 @@ function manifest( }; } -/** Builds a log from an oldest-first chain, newest snapshot first. */ -function logOf( - chain: readonly Manifest[], - pinnedIds: string[] = [], -): HistoryLog { - const snapshots: SnapshotEntry[] = []; - const changes: HistoryLog["changes"] = {}; - for (const [index, current] of chain.entries()) { - snapshots.unshift({ - id: current.snapshotId, - parentId: current.parentSnapshotId, - createdAt: current.createdAt, - deviceId: current.deviceId, - deviceName: current.deviceName, - pinned: pinnedIds.includes(current.snapshotId) || undefined, - }); - changes[current.snapshotId] = diffManifests( - chain[index - 1] ?? null, - current, - ); - } - return { version: 2, snapshots, changes }; -} - /** Deterministic chain: each step adds, edits and deletes a few paths. */ function generateChain(steps: number): Manifest[] { let seed = 42; @@ -104,6 +67,19 @@ function generateChain(steps: number): Manifest[] { 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") }); @@ -155,85 +131,123 @@ describe("diffManifests / undoChanges", () => { }); }); -describe("contiguousLength", () => { - it("counts the run that stays linked", () => { - expect(contiguousLength([])).toBe(0); - const chain = logOf(generateChain(5)).snapshots; - expect(contiguousLength(chain)).toBe(5); +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("stops at a parent/child mismatch", () => { - const snapshots = logOf(generateChain(5)).snapshots; - const broken = [...snapshots.slice(0, 2), ...snapshots.slice(3)]; - // s4,s3 link; s3 then points at the dropped s2. - expect(contiguousLength(broken)).toBe(2); + 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", () => { - it("reproduces every manifest in the chain", () => { + 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 head = chain[chain.length - 1] as Manifest; - const log = logOf(chain); + 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, log, target.snapshotId); + 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", () => { + it("does not hand back HEAD's own file map", async () => { const chain = generateChain(3); - const head = chain[2] as Manifest; - const replayed = replayTo(head, logOf(chain), head.snapshotId); + 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 when the log does not start at HEAD", () => { - const chain = generateChain(4); - const log = logOf(chain.slice(0, 3)); - expect(replayTo(chain[3] as Manifest, log, "s0")).toBeNull(); + 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 to replay past a gap", () => { - const chain = generateChain(5); - const head = chain[4] as Manifest; - const log = logOf(chain); - const broken: HistoryLog = { - ...log, - snapshots: log.snapshots.filter((s) => s.id !== "s2"), - }; - expect(replayTo(head, broken, "s3")).not.toBeNull(); - expect(replayTo(head, broken, "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", () => { - async function seed( - storage: FakeStorage, - chain: readonly Manifest[], - pinnedIds: string[] = [], - ): Promise { - await publishManifest(storage, key, chain[chain.length - 1] as Manifest); - await writeHistoryLog(storage, key, "", logOf(chain, pinnedIds)); - } - it("returns distinct versions newest first and skips unchanged pushes", async () => { - const storage = new FakeStorage(); - await seed(storage, [ + 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 getFileHistory({ - storage, - key, - root: "", - path: "a.md", - }); + const versions = await historyOf(storage, "a.md"); expect(versions.map((v) => v.hash)).toEqual(["A2", "A1"]); // The A1 version is attributed to the newest snapshot holding it. expect(versions.map((v) => v.snapshotId)).toEqual(["s3", "s2"]); @@ -241,185 +255,111 @@ describe("getFileHistory", () => { }); it("returns nothing for a path the history never saw", async () => { - const storage = new FakeStorage(); - await seed(storage, [manifest("s1", null, { "a.md": entry("A1") })]); - expect( - await getFileHistory({ storage, key, root: "", path: "b.md" }), - ).toEqual([]); + 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 = new FakeStorage(); - await seed(storage, [ + 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 getFileHistory({ - storage, - key, - root: "", - path: "gone.md", - }); + 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 = new FakeStorage(); - await seed(storage, [ + 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 getFileHistory({ - storage, - key, - root: "", - path: "a.md", - }); + 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 () => { - const storage = new FakeStorage(); // s2 is the child of s1 but carries an earlier timestamp, as a device with // a lagging clock would produce. - await seed(storage, [ + const storage = await seed([ manifest("s1", null, { "a.md": entry("A1") }, 5000), manifest("s2", "s1", { "a.md": entry("A2") }, 1000), ]); - const versions = await getFileHistory({ - storage, - key, - root: "", - path: "a.md", - }); + const versions = await historyOf(storage, "a.md"); expect(versions.map((v) => v.hash)).toEqual(["A2", "A1"]); }); - it("surfaces a pin sitting past a missing change record", async () => { - const storage = new FakeStorage(); + 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), ]; - await publishManifest(storage, key, chain[2] as Manifest); - const log = logOf(chain, ["s1"]); - // The pointer chain is intact, but s3's record was lost, so the walk stops - // there and must not claim to have covered s1. - const { s3: _dropped, ...changes } = log.changes; - await writeHistoryLog(storage, key, "", { ...log, changes }); - await storage.put( - pinKey("s1"), - await encryptJson(key, chain[0] as Manifest), - ); - - const versions = await getFileHistory({ - storage, - key, - root: "", - path: "a.md", - }); - expect(versions.map((v) => v.hash)).toEqual(["A3", "A1"]); - expect(versions[1]?.pinned).toBe(true); + 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.pinned, v.label])).toEqual([ + ["A3", false, undefined], + ["A2", true, "keeper"], + ["A1", false, undefined], + ]); }); - it("surfaces a pinned snapshot the chain can no longer reach", async () => { - const storage = new FakeStorage(); + 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), ]; - await publishManifest(storage, key, chain[2] as Manifest); - const log = logOf(chain, ["s1"]); - // GC evicted s2, so s1 is only reachable through its pin manifest. - await writeHistoryLog(storage, key, "", { - ...log, - snapshots: log.snapshots.filter((s) => s.id !== "s2"), - }); - await storage.put( - pinKey("s1"), - await encryptJson(key, chain[0] as Manifest), - ); + // 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 getFileHistory({ - storage, - key, - root: "", - path: "a.md", - }); + const versions = await historyOf(storage, "a.md"); expect(versions.map((v) => v.hash)).toEqual(["A3", "A1"]); + expect(versions[0]?.pinned).toBe(false); expect(versions[1]?.pinned).toBe(true); + expect(versions[1]?.snapshotId).toBe("s1"); }); - it("serves the current version when the log has fallen behind HEAD", async () => { - const storage = new FakeStorage(); + 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), ]; - await publishManifest(storage, key, chain[1] as Manifest); - // A best-effort log update was lost, so the log still ends at s1. - await writeHistoryLog(storage, key, "", logOf(chain.slice(0, 1))); - - const versions = await getFileHistory({ - storage, - key, - root: "", - path: "a.md", - }); - expect(versions.map((v) => v.hash)).toEqual(["A2"]); - expect(versions[0]?.snapshotId).toBe("s2"); - }); -}); - -describe("prependSnapshot", () => { - const at = (id: string, parentId: string | null): SnapshotEntry => ({ - id, - parentId, - createdAt: 1, - deviceId: "d", - }); - const none = { added: {}, modified: {}, deleted: {} }; - const idsOf = (log: HistoryLog) => log.snapshots.map((s) => s.id); - const logOf = (...entries: SnapshotEntry[]): HistoryLog => ({ - version: 2, - snapshots: entries, - changes: {}, - }); - - it("puts a push on top of its parent", () => { - const log = prependSnapshot(logOf(at("p", null)), at("x", "p"), none); - expect(idsOf(log)).toEqual(["x", "p"]); - }); - - it("keeps the chain when a push lands after the one that followed it", () => { - const log = prependSnapshot( - logOf(at("y", "x"), at("p", null)), - at("x", "p"), - none, + const storage = await seed(chain); + await storage.put( + pushKey("s2"), + crypto.getRandomValues(new Uint8Array(64)), ); - expect(idsOf(log)).toEqual(["y", "x", "p"]); - expect(contiguousLength(log.snapshots)).toBe(3); - }); - it("goes under a push that names it as parent when its own parent is unknown", () => { - const log = prependSnapshot(logOf(at("y", "x")), at("x", "p"), none); - expect(idsOf(log)).toEqual(["y", "x"]); + const versions = await historyOf(storage, "a.md"); + expect(versions.map((v) => v.hash)).toEqual(["A3"]); }); - it("replaces an entry it already holds instead of duplicating it", () => { - const log = prependSnapshot( - logOf(at("x", "p"), at("p", null)), - at("x", "p"), - none, + 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"], ); - expect(idsOf(log)).toEqual(["x", "p"]); + + 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/history-read-cache.test.ts b/packages/plugin/tests/features/sync/history/history-read-cache.test.ts deleted file mode 100644 index 0e5d45b9..00000000 --- a/packages/plugin/tests/features/sync/history/history-read-cache.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { FakeStorage } from "@tests/helpers/fake-storage"; -import { publishManifest } from "@tests/helpers/manifest"; -import { RevalidatingStorage } from "@tests/helpers/revalidating-storage"; -import { beforeAll, describe, expect, it } from "vitest"; -import { - deriveKey, - type EncryptionKey, - encryptJson, -} from "@/core/crypto/cipher"; -import { getFileHistory } from "@/features/sync/history/query"; -import { - pinKey, - readHistoryLog, - writeHistoryLog, -} from "@/features/sync/history/store"; -import type { HistoryLog } from "@/features/sync/history/types"; -import type { EFileKind, Manifest } from "@/features/sync/types"; - -let key: EncryptionKey; -let otherKey: EncryptionKey; -beforeAll(async () => { - key = await deriveKey("pw", new Uint8Array(16)); - otherKey = await deriveKey("pw", new Uint8Array(16)); -}); - -function logWith(...ids: string[]): HistoryLog { - return { - version: 2, - snapshots: ids.map((id) => ({ - id, - parentId: null, - createdAt: 1, - deviceId: "d", - deviceName: "D", - })), - changes: {}, - }; -} - -describe("readHistoryLog validator cache", () => { - it("reuses the cached log on 304", async () => { - const storage = new RevalidatingStorage(); - await writeHistoryLog(storage, key, "", logWith("s1")); - const first = await readHistoryLog(storage, key, ""); - const second = await readHistoryLog(storage, key, ""); - expect(second).toBe(first); - expect(storage.bodiesSent).toBe(1); - }); - - it("refetches under another key", async () => { - const storage = new RevalidatingStorage(); - await writeHistoryLog(storage, key, "", logWith("s1")); - await readHistoryLog(storage, key, ""); - await readHistoryLog(storage, otherKey, ""); - expect(storage.bodiesSent).toBe(2); - }); - - it("drops the entry on write", async () => { - const storage = new RevalidatingStorage(); - await writeHistoryLog(storage, key, "", logWith("s1")); - await readHistoryLog(storage, key, ""); - await writeHistoryLog(storage, key, "", logWith("s2", "s1")); - const log = await readHistoryLog(storage, key, ""); - expect(log.snapshots.map((s) => s.id)).toEqual(["s2", "s1"]); - expect(storage.bodiesSent).toBe(2); - }); -}); - -describe("pin manifest cache", () => { - it("downloads a pinned manifest once across queries", async () => { - const storage = new FakeStorage(); - const head: Manifest = { - version: 1, - vaultId: "v", - snapshotId: "h", - parentSnapshotId: null, - createdAt: 2, - deviceId: "d", - deviceName: "D", - files: {}, - }; - await publishManifest(storage, key, head); - const log = logWith("h", "p"); - const pin = log.snapshots[1]; - if (pin) pin.pinned = true; - await writeHistoryLog(storage, key, "", log); - const pinned: Manifest = { - ...head, - snapshotId: "p", - files: { - "a.md": { hash: "A", size: 1, mtime: 1, kind: "vault" as EFileKind }, - }, - }; - storage.map.set(pinKey("p"), await encryptJson(key, pinned)); - const pinGets = () => storage.getCalls; - - const query = { storage, key, root: "", path: "a.md" }; - const first = await getFileHistory(query); - const before = pinGets(); - const second = await getFileHistory(query); - expect(first.map((v) => v.snapshotId)).toEqual(["p"]); - expect(second).toEqual(first); - // Manifest and log are re-read; the pin is not. - expect(pinGets() - before).toBe(2); - }); -}); 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..f790f14f --- /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" }], + 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..e46000d7 --- /dev/null +++ b/packages/plugin/tests/features/sync/history/model/periods.test.ts @@ -0,0 +1,80 @@ +import { seeded } from "@tests/helpers/seeded"; +import { describe, expect, it } from "vitest"; +import { + dueResolution, + groupEnd, + groupStart, + isDue, + keepStart, + RESOLUTIONS, +} 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; + } + } + }); +}); 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..13725b68 --- /dev/null +++ b/packages/plugin/tests/features/sync/history/model/plan.test.ts @@ -0,0 +1,259 @@ +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 { planGc } from "@/features/sync/history/model/plan"; +import { storedRecord } from "@/features/sync/history/model/records"; +import type { HistoryObject } from "@/features/sync/history/model/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("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("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..c03a4d30 --- /dev/null +++ b/packages/plugin/tests/features/sync/history/model/records.test.ts @@ -0,0 +1,83 @@ +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 { 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("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..c2c01cb8 --- /dev/null +++ b/packages/plugin/tests/features/sync/history/pins.test.ts @@ -0,0 +1,159 @@ +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, + readPins, + writePin, +} from "@/features/sync/history/pins"; +import { 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("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); + }); +}); + +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("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("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..c4beb016 --- /dev/null +++ b/packages/plugin/tests/features/sync/history/publish.test.ts @@ -0,0 +1,151 @@ +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 { publishManifestWithHistory } from "@/features/sync/history/publish"; +import { pushKey, readHistory } from "@/features/sync/history/remote"; +import { objectKey } from "@/features/sync/remote/manifest"; +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("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("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("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/features/sync/identity/manifest-device.test.ts b/packages/plugin/tests/features/sync/identity/manifest-device.test.ts index 3ed5a254..905bb5a8 100644 --- a/packages/plugin/tests/features/sync/identity/manifest-device.test.ts +++ b/packages/plugin/tests/features/sync/identity/manifest-device.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "vitest"; +import { MANIFEST_VERSION } from "@/features/sync/constants"; import { defaultDeviceName } from "@/features/sync/identity/device"; import { buildManifest } from "@/features/sync/remote/manifest"; @@ -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/features/sync/remote/foreign.test.ts b/packages/plugin/tests/features/sync/remote/foreign.test.ts index 6131ac34..ee399744 100644 --- a/packages/plugin/tests/features/sync/remote/foreign.test.ts +++ b/packages/plugin/tests/features/sync/remote/foreign.test.ts @@ -1,8 +1,9 @@ import { TestSession, useEncryptionKey } from "@tests/helpers/session"; -import { describe, expect, it, vi } from "vitest"; +import { describe, expect, it } from "vitest"; import { DEFAULT_SETTINGS_SYNC } from "@/core/settings/model"; +import { REMOTE_HISTORY_PREFIX } from "@/features/sync/constants"; import { compare, pushPaths } from "@/features/sync/engine"; -import { readHistoryLog } from "@/features/sync/history/store"; +import { pushKey, readHistory } from "@/features/sync/history/remote"; import { advanceSessionAfterPush } from "@/features/sync/remote/baseline"; import { forgetDroppedForeign, @@ -11,6 +12,7 @@ import { } from "@/features/sync/remote/foreign"; import { objectKey } from "@/features/sync/remote/manifest"; 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, @@ -169,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(); @@ -177,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"]); }); @@ -203,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/features/sync/remote/reset.test.ts b/packages/plugin/tests/features/sync/remote/reset.test.ts index 02bf9402..63a81567 100644 --- a/packages/plugin/tests/features/sync/remote/reset.test.ts +++ b/packages/plugin/tests/features/sync/remote/reset.test.ts @@ -8,6 +8,7 @@ import { REMOTE_PINS_PREFIX, REMOTE_SALT_KEY, } from "@/features/sync/constants"; +import { pushKey } from "@/features/sync/history/remote"; import { objectKey } from "@/features/sync/remote/manifest"; import { resetRemoteStorage } from "@/features/sync/remote/reset"; @@ -24,6 +25,7 @@ function seed(): FakeStorage { storage.map.set(objectKey("bbb"), 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,6 +41,7 @@ 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); }); diff --git a/packages/plugin/tests/features/sync/remote/space-paths.test.ts b/packages/plugin/tests/features/sync/remote/space-paths.test.ts index 87a31b6c..a650c1df 100644 --- a/packages/plugin/tests/features/sync/remote/space-paths.test.ts +++ b/packages/plugin/tests/features/sync/remote/space-paths.test.ts @@ -1,11 +1,8 @@ import { describe, expect, it } from "vitest"; -import type { - HistoryLog, - SnapshotChanges, -} from "@/features/sync/history/types"; +import type { SnapshotChanges } from "@/features/sync/history/types"; import { - historyLogToSpace, - historyLogToVault, + changesToSpace, + changesToVault, manifestToSpace, manifestToVault, } from "@/features/sync/remote/space-paths"; @@ -51,38 +48,64 @@ describe("manifestToSpace / manifestToVault", () => { }); }); -describe("historyLogToSpace / historyLogToVault", () => { +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("G") }, - }; - const log: HistoryLog = { - version: 2, - snapshots: [{ id: "s1", parentId: null, createdAt: 1, deviceId: "d" }], - changes: { s1: changes }, + deleted: { "Shared/p/gone.md": entry("G1") }, + deletedLast: { "Shared/p/gone.md": entry("G2") }, }; it("translates change keys to root-relative", () => { - const spaced = historyLogToSpace(log, "Shared/p"); - const sc = spaced.changes.s1 as SnapshotChanges; - expect(Object.keys(sc.added)).toEqual(["new.md"]); - expect(Object.keys(sc.modified)).toEqual(["edit.md"]); - expect(Object.keys(sc.deleted)).toEqual(["gone.md"]); + 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 spaced = historyLogToSpace(log, "Shared/p"); - const back = historyLogToVault(spaced, "Shared/p"); - expect(Object.keys(back.changes.s1?.added ?? {})).toEqual([ - "Shared/p/new.md", - ]); + const back = changesToVault( + changesToSpace(changes, "Shared/p"), + "Shared/p", + ); + expect(back).toEqual(changes); }); it('returns the same object for root ""', () => { - expect(historyLogToSpace(log, "")).toBe(log); - expect(historyLogToVault(log, "")).toBe(log); + 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/features/sync/remote/spaces.test.ts b/packages/plugin/tests/features/sync/remote/spaces.test.ts index 248e4096..cefcbf74 100644 --- a/packages/plugin/tests/features/sync/remote/spaces.test.ts +++ b/packages/plugin/tests/features/sync/remote/spaces.test.ts @@ -77,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/runtime/history-service-scope.test.ts b/packages/plugin/tests/features/sync/runtime/history-service-scope.test.ts index 80ab02eb..42bda2c0 100644 --- a/packages/plugin/tests/features/sync/runtime/history-service-scope.test.ts +++ b/packages/plugin/tests/features/sync/runtime/history-service-scope.test.ts @@ -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 { 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..1c7ffe5f --- /dev/null +++ b/packages/plugin/tests/features/sync/runtime/maintenance-service.test.ts @@ -0,0 +1,115 @@ +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 queued: Promise[] = []; + const maintenance = new MaintenanceService({ + openSession: async (space) => + ({ + space, + 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, + }); + const settled = () => Promise.all(queued).then(() => undefined); + return { maintenance, logWarn, logInfo, settled }; +} + +beforeEach(() => { + vi.useFakeTimers({ toFake: ["Date"] }); + collect.mockReset(); + collect.mockResolvedValue({ written: 0, retired: 0, swept: 0 }); +}); +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("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("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 index 45653148..62cda5e3 100644 --- a/packages/plugin/tests/features/sync/runtime/maintenance.test.ts +++ b/packages/plugin/tests/features/sync/runtime/maintenance.test.ts @@ -1,19 +1,27 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; +import { + manifestOf, + pinSnapshot, + seedChain, + writePushRecord, +} from "@tests/helpers/history"; import { publishManifest } from "@tests/helpers/manifest"; import { beforeAll, describe, expect, it } from "vitest"; -import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; +import { + deriveKey, + type EncryptionKey, + encryptJson, +} from "@/core/crypto/cipher"; import { REMOTE_OBJECTS_PREFIX, REMOTE_PINS_PREFIX, } from "@/features/sync/constants"; -import { diffManifests } from "@/features/sync/history/changes"; -import { writeHistoryLog } from "@/features/sync/history/store"; import { objectKey } from "@/features/sync/remote/manifest"; import { deepCleanOrphans, verifyRemote, } from "@/features/sync/runtime/maintenance"; -import type { EFileKind, Manifest } from "@/features/sync/types"; +import type { Manifest } from "@/features/sync/types"; const DAY_MS = 24 * 60 * 60 * 1000; @@ -22,26 +30,10 @@ beforeAll(async () => { key = await deriveKey("pw", new Uint8Array(16)); }); -function manifest(snapshotId: string, files: Record): 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: 1, - vaultId: "v", - snapshotId, - parentSnapshotId: null, - createdAt: 1, - deviceId: "d", - files: entries, - }; -} - describe("verifyRemote", () => { it("passes on a complete remote and flags a missing object", async () => { const storage = new FakeStorage(); - const head = manifest("s1", { "a.md": "H1" }); + const head = manifestOf("s1", null, { "a.md": "H1" }); await publishManifest(storage, key, head); await storage.put(objectKey("H1"), new Uint8Array([1])); @@ -69,7 +61,7 @@ describe("verifyRemote", () => { await publishManifest( storage, key, - manifest("s1", { "a.md": "H1", "b.md": "H2" }), + 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])); @@ -80,97 +72,154 @@ describe("verifyRemote", () => { }); }); +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 reachable ones", async () => { + it("removes unreachable blobs, keeps those HEAD, a push record or a pin names", async () => { const storage = new FakeStorage(); - const head = manifest("s1", { "a.md": "H1" }); - await publishManifest(storage, key, head); - await storage.put(objectKey("H1"), new Uint8Array([1])); - await writeHistoryLog(storage, key, "", { - version: 2, - snapshots: [{ id: "s1", parentId: null, createdAt: 1, deviceId: "d" }], - changes: { s1: diffManifests(null, head) }, - }); - - await storage.put(objectKey("ORPHAN"), new Uint8Array([9])); + 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); - expect(res.deletedPins).toBe(0); - expect(await storage.exists(objectKey("H1"))).toBe(true); + 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 storage.list(REMOTE_PINS_PREFIX)).length).toBe(0); - - const again = await deepCleanOrphans(storage, key, ""); - expect(again.deletedObjects).toBe(0); - expect(again.deletedPins).toBe(0); + expect((await deepCleanOrphans(storage, key, "")).deletedObjects).toBe(0); }); - it("keeps what was written in the last day: another device's push, a pin before its flag", async () => { + it("refuses a HEAD below the fence: 1.x clients still sync and name what looks orphaned", async () => { const storage = new FakeStorage(); - const head = manifest("s1", { "a.md": "H1" }); - await publishManifest(storage, key, head); - await storage.put(objectKey("H1"), new Uint8Array([1])); - await writeHistoryLog(storage, key, "", { + await publishManifest(storage, key, { + ...manifestOf("s1", null, { "a.md": "H1" }), version: 2, - snapshots: [{ id: "s1", parentId: null, createdAt: 1, deviceId: "d" }], - changes: { s1: diffManifests(null, head) }, }); - await storage.put(objectKey("OLD"), new Uint8Array([9])); + await putObjects(storage, "H1", "OLD"); storage.age(DAY_MS + 1); - await storage.put(objectKey("UPLOADING"), new Uint8Array([9])); - await storage.put(`${REMOTE_PINS_PREFIX}s0.json.enc`, new Uint8Array([9])); - const res = await deepCleanOrphans(storage, key, ""); + await expect(deepCleanOrphans(storage, key, "")).rejects.toThrow( + /old file history format/, + ); + expect(await storage.exists(objectKey("OLD"))).toBe(true); + }); - expect(res).toEqual({ deletedObjects: 1, deletedPins: 0 }); + 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", () => { - it("bails when another device pins a snapshot while it lists", async () => { - // Pinning does not move HEAD, so only a log re-read can catch it. - class PinRacingStorage extends FakeStorage { - raceOnce: (() => Promise) | null = null; - override async list(prefix: string): Promise { - const keys = await super.list(prefix); - const race = this.raceOnce; + 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; - if (race) await race(); - return keys; + await race(); } + return listed; } + } - const storage = new PinRacingStorage(); - const head = manifest("s2", { "a.md": "H2" }); - await publishManifest(storage, key, head); - await storage.put(objectKey("H2"), new Uint8Array([1])); - const snapshots = [ - { id: "s2", parentId: "s1", createdAt: 2, deviceId: "d" }, - { id: "s1", parentId: null, createdAt: 1, deviceId: "d" }, + 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" }), ]; - const changes = { - s2: diffManifests(manifest("s1", { "a.md": "H1" }), head), - s1: diffManifests(null, manifest("s1", { "a.md": "H1" })), - }; - await writeHistoryLog(storage, key, "", { version: 2, snapshots, changes }); - - storage.raceOnce = async () => { - await writeHistoryLog(storage, key, "", { - version: 2, - snapshots: snapshots.map((entry) => - entry.id === "s1" ? { ...entry, pinned: true } : entry, - ), - changes, - }); - }; + 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/features/sync/runtime/operation-runner.test.ts b/packages/plugin/tests/features/sync/runtime/operation-runner.test.ts index 82708853..e8906fd7 100644 --- a/packages/plugin/tests/features/sync/runtime/operation-runner.test.ts +++ b/packages/plugin/tests/features/sync/runtime/operation-runner.test.ts @@ -24,12 +24,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 () => ({ @@ -40,11 +42,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, @@ -52,6 +55,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 () => { diff --git a/packages/plugin/tests/features/sync/runtime/saved-refresh.test.ts b/packages/plugin/tests/features/sync/runtime/saved-refresh.test.ts index c4fac8a6..d918cce2 100644 --- a/packages/plugin/tests/features/sync/runtime/saved-refresh.test.ts +++ b/packages/plugin/tests/features/sync/runtime/saved-refresh.test.ts @@ -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/features/transfer/transfer.test.ts b/packages/plugin/tests/features/transfer/transfer.test.ts index 18eff864..0ef4b28a 100644 --- a/packages/plugin/tests/features/transfer/transfer.test.ts +++ b/packages/plugin/tests/features/transfer/transfer.test.ts @@ -170,7 +170,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, @@ -211,9 +211,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); @@ -280,9 +278,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, ); 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, + }); +} From c4e4ef4a4e0c16374079d0acbb500cbff0ffa060 Mon Sep 17 00:00:00 2001 From: kitbyte Date: Wed, 28 Oct 2026 13:26:07 +0200 Subject: [PATCH 05/26] feat(ui): one change-state palette --- .claude/rules/structure.md | 2 +- .claude/rules/ui.md | 3 ++- packages/plugin/src/core/ui/styles/tokens.css | 21 ++++++++++++++++++- .../src/features/diff/styles/hunk-preview.css | 4 ++-- .../features/diff/styles/source-blocks.css | 4 ++-- .../plugin/src/features/diff/styles/tones.css | 6 +++--- .../src/features/editor-signs/hunk-popup.css | 14 ++++++------- .../src/features/editor-signs/signs.css | 12 +++++------ .../plugin/src/features/explorer/explorer.css | 10 ++++++--- .../source-control/styles/file-rows.css | 10 ++++----- 10 files changed, 55 insertions(+), 31 deletions(-) diff --git a/.claude/rules/structure.md b/.claude/rules/structure.md index 3e448fb8..54ffc60e 100644 --- a/.claude/rules/structure.md +++ b/.claude/rules/structure.md @@ -47,7 +47,7 @@ Paths in this file are relative to `packages/plugin/src/`. - 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, `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 bar is the tone change bar, the strong one the accent bar of a chosen side. +- 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 diff --git a/.claude/rules/ui.md b/.claude/rules/ui.md index ce474945..de9d6d6e 100644 --- a/.claude/rules/ui.md +++ b/.claude/rules/ui.md @@ -41,7 +41,8 @@ When one falls short, extend it in `core/ui` instead of writing a second. ## Style -- Obsidian variables and tokens first: colors `--color-*`, `--text-*`, `--background-*`; spacing, radii and fonts from Obsidian's scales. A hex is only a fallback inside `var(--color-x, #hex)`, or one fixed on-color text (`features/presence/ui/presence.css`). +- 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. diff --git a/packages/plugin/src/core/ui/styles/tokens.css b/packages/plugin/src/core/ui/styles/tokens.css index ef822066..95fe576f 100644 --- a/packages/plugin/src/core/ui/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/features/diff/styles/hunk-preview.css b/packages/plugin/src/features/diff/styles/hunk-preview.css index 1982b63e..9bc25677 100644 --- a/packages/plugin/src/features/diff/styles/hunk-preview.css +++ b/packages/plugin/src/features/diff/styles/hunk-preview.css @@ -31,11 +31,11 @@ /* 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); + background-color: rgba(var(--mdsync-added-rgb), 0.15); color: var(--text-normal); } .mdsync-unified-line.is-del { - background-color: rgba(var(--color-red-rgb), 0.15); + background-color: rgba(var(--mdsync-deleted-rgb), 0.15); color: var(--text-normal); } diff --git a/packages/plugin/src/features/diff/styles/source-blocks.css b/packages/plugin/src/features/diff/styles/source-blocks.css index 0fbd513c..2b1dffe8 100644 --- a/packages/plugin/src/features/diff/styles/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/features/diff/styles/tones.css b/packages/plugin/src/features/diff/styles/tones.css index 8606e646..425e350d 100644 --- a/packages/plugin/src/features/diff/styles/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/features/editor-signs/hunk-popup.css b/packages/plugin/src/features/editor-signs/hunk-popup.css index eadfac61..e867faa2 100644 --- a/packages/plugin/src/features/editor-signs/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/signs.css b/packages/plugin/src/features/editor-signs/signs.css index 2786fc21..2b54c3ff 100644 --- a/packages/plugin/src/features/editor-signs/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/features/explorer/explorer.css b/packages/plugin/src/features/explorer/explorer.css index 7655893c..89b97668 100644 --- a/packages/plugin/src/features/explorer/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/features/source-control/styles/file-rows.css b/packages/plugin/src/features/source-control/styles/file-rows.css index a8720c1d..0df4f65d 100644 --- a/packages/plugin/src/features/source-control/styles/file-rows.css +++ b/packages/plugin/src/features/source-control/styles/file-rows.css @@ -82,11 +82,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 +98,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 { From a3edcb2e3f3e2eaac5ae1ce3b8f8d6a41e136ae3 Mon Sep 17 00:00:00 2001 From: kitbyte Date: Wed, 28 Oct 2026 13:48:15 +0200 Subject: [PATCH 06/26] feat(history): Timeline, History and Deleted by age with activity calendar --- .claude/rules/history.md | 8 +- .claude/rules/structure.md | 2 +- .claude/rules/ui.md | 2 +- package.json | 1 + packages/plugin/src/app/bootstrap.ts | 6 + packages/plugin/src/app/host.ts | 4 +- packages/plugin/src/core/constants.ts | 9 + packages/plugin/src/core/hub/index.ts | 1 + packages/plugin/src/core/hub/relay-text.ts | 5 + packages/plugin/src/core/settings/model.ts | 2 + packages/plugin/src/core/shared/format.ts | 42 +- packages/plugin/src/core/shared/index.ts | 3 + .../src/features/settings/activity-card.ts | 42 ++ packages/plugin/src/features/settings/host.ts | 3 +- .../plugin/src/features/settings/overview.css | 13 +- .../plugin/src/features/settings/overview.ts | 2 + .../features/settings/sections/automation.ts | 65 +- .../source-control/history/age-groups.ts | 100 +++ .../source-control/history/day-groups.ts | 46 -- .../source-control/history/history-rows.ts | 36 +- .../source-control/history/history-tab.ts | 53 +- .../source-control/history/history.css | 58 +- .../src/features/source-control/index.ts | 1 + .../src/features/source-control/row-parts.ts | 15 + .../source-control/timeline/session-card.ts | 224 ++++++ .../source-control/timeline/session-rows.ts | 115 +++ .../source-control/timeline/sessions.ts | 82 +++ .../source-control/timeline/snapshot-menu.ts | 4 +- .../timeline/timeline-actions.ts | 38 +- .../source-control/timeline/timeline-rows.ts | 109 +-- .../source-control/timeline/timeline-tab.ts | 373 ++++++---- .../source-control/timeline/timeline.css | 135 ++++ .../source-control/trash/trash-rows.ts | 15 +- .../source-control/trash/trash-tab.ts | 88 ++- .../src/features/source-control/view.ts | 11 + .../src/features/source-control/workspace.ts | 16 +- packages/plugin/src/features/sync/README.md | 2 +- .../plugin/src/features/sync/controller.ts | 26 +- .../features/sync/history/activity-cache.ts | 57 ++ .../plugin/src/features/sync/history/gc.ts | 12 +- .../src/features/sync/history/model/cover.ts | 29 +- .../features/sync/history/model/periods.ts | 32 + .../plugin/src/features/sync/history/query.ts | 119 +++- .../plugin/src/features/sync/history/types.ts | 26 +- packages/plugin/src/features/sync/index.ts | 16 + .../features/sync/runtime/history-service.ts | 11 +- .../sync/runtime/maintenance-service.ts | 19 +- .../sync/ui/history/activity-calendar.css | 147 ++++ .../sync/ui/history/activity-calendar.ts | 133 ++++ .../src/features/sync/ui/history/calendar.ts | 211 ++++++ .../features/sync/ui/history/holds-row.css | 65 ++ .../src/features/sync/ui/history/holds-row.ts | 63 ++ .../plugin/src/features/transfer/transfer.ts | 1 + packages/plugin/src/main.ts | 9 +- packages/plugin/src/styles.css | 3 + .../plugin/tests/core/shared/format.test.ts | 41 +- .../source-control/history/age-groups.test.ts | 114 +++ .../source-control/history/day-groups.test.ts | 79 --- .../history/history-rows.test.ts | 56 +- .../timeline/session-rows.test.ts | 146 ++++ .../source-control/timeline/sessions.test.ts | 138 ++++ .../timeline/timeline-rows.test.ts | 108 +-- .../source-control/trash/trash-rows.test.ts | 22 +- .../sync/history/activity-cache.test.ts | 47 ++ .../tests/features/sync/history/gc.test.ts | 34 +- .../sync/history/history-deleted.test.ts | 36 +- .../sync/history/history-query.test.ts | 68 +- .../sync/history/model/activity.test.ts | 2 +- .../sync/history/model/periods.test.ts | 33 + .../runtime/history-service-scope.test.ts | 1 + .../sync/runtime/maintenance-service.test.ts | 24 +- .../features/sync/ui/history/calendar.test.ts | 268 +++++++ packages/plugin/tsconfig.json | 2 +- tests/e2e/README.md | 1 + tests/e2e/history.ts | 667 ++++++++++++++++++ 75 files changed, 4028 insertions(+), 569 deletions(-) create mode 100644 packages/plugin/src/features/settings/activity-card.ts create mode 100644 packages/plugin/src/features/source-control/history/age-groups.ts delete mode 100644 packages/plugin/src/features/source-control/history/day-groups.ts create mode 100644 packages/plugin/src/features/source-control/timeline/session-card.ts create mode 100644 packages/plugin/src/features/source-control/timeline/session-rows.ts create mode 100644 packages/plugin/src/features/source-control/timeline/sessions.ts create mode 100644 packages/plugin/src/features/sync/history/activity-cache.ts create mode 100644 packages/plugin/src/features/sync/ui/history/activity-calendar.css create mode 100644 packages/plugin/src/features/sync/ui/history/activity-calendar.ts create mode 100644 packages/plugin/src/features/sync/ui/history/calendar.ts create mode 100644 packages/plugin/src/features/sync/ui/history/holds-row.css create mode 100644 packages/plugin/src/features/sync/ui/history/holds-row.ts create mode 100644 packages/plugin/tests/features/source-control/history/age-groups.test.ts delete mode 100644 packages/plugin/tests/features/source-control/history/day-groups.test.ts create mode 100644 packages/plugin/tests/features/source-control/timeline/session-rows.test.ts create mode 100644 packages/plugin/tests/features/source-control/timeline/sessions.test.ts create mode 100644 packages/plugin/tests/features/sync/history/activity-cache.test.ts create mode 100644 packages/plugin/tests/features/sync/ui/history/calendar.test.ts create mode 100644 tests/e2e/history.ts diff --git a/.claude/rules/history.md b/.claude/rules/history.md index 9854e307..c9fa62e1 100644 --- a/.claude/rules/history.md +++ b/.claude/rules/history.md @@ -26,8 +26,12 @@ History is one encrypted record per push under `history/`, which GC thins into o - `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. +- `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 @@ -49,7 +53,7 @@ History is one encrypted record per push under `history/`, which GC thins into o - Sweep only blobs older than any push in flight: `settledKeys` / `keysByAge` list them by age, `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 changed while 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. - 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`; `forever` is `null`), read per session in `app/session-factory.ts`. Each device's GC applies its own, so the shortest wins. +- 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. `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. diff --git a/.claude/rules/structure.md b/.claude/rules/structure.md index 54ffc60e..4661cdec 100644 --- a/.claude/rules/structure.md +++ b/.claude/rules/structure.md @@ -31,7 +31,7 @@ Paths in this file are relative to `packages/plugin/src/`. - 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()`; `openDiffView` is the diff slice's. +- 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`) diff --git a/.claude/rules/ui.md b/.claude/rules/ui.md index de9d6d6e..9e5b3b5a 100644 --- a/.claude/rules/ui.md +++ b/.claude/rules/ui.md @@ -48,7 +48,7 @@ When one falls short, extend it in `core/ui` instead of writing a second. ## 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. +- 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. diff --git a/package.json b/package.json index 2db03497..37ee8d95 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,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/src/app/bootstrap.ts b/packages/plugin/src/app/bootstrap.ts index a436e7a1..83b8c981 100644 --- a/packages/plugin/src/app/bootstrap.ts +++ b/packages/plugin/src/app/bootstrap.ts @@ -24,6 +24,8 @@ import { } from "@/features/sync"; import { createSessionOpeners } from "./session-factory"; +const ACTIVITY_KEY = "mdsync-activity"; + export interface PluginRuntime { controller: SyncController; logs: LogService; @@ -135,6 +137,10 @@ export async function bootstrapPluginRuntime( }, openSession, openLocal, + activityStore: { + load: () => app.loadLocalStorage(ACTIVITY_KEY) as unknown, + save: (value) => app.saveLocalStorage(ACTIVITY_KEY, value), + }, persistState: (state) => statePersister.persist(state), getState: () => statePersister.state, logInfo: (op, msg, details) => logs.info(op, msg, details), diff --git a/packages/plugin/src/app/host.ts b/packages/plugin/src/app/host.ts index 507a0456..a6ed78da 100644 --- a/packages/plugin/src/app/host.ts +++ b/packages/plugin/src/app/host.ts @@ -42,9 +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/core/constants.ts b/packages/plugin/src/core/constants.ts index 1ee5c5a4..8ceb3f69 100644 --- a/packages/plugin/src/core/constants.ts +++ b/packages/plugin/src/core/constants.ts @@ -30,6 +30,15 @@ export const HISTORY_KEEP_MS = { forever: null, } as const; +/** 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"; export const DIFF_VIEW_TYPE = "mdsync-diff"; diff --git a/packages/plugin/src/core/hub/index.ts b/packages/plugin/src/core/hub/index.ts index 8631ee50..4a2fd617 100644 --- a/packages/plugin/src/core/hub/index.ts +++ b/packages/plugin/src/core/hub/index.ts @@ -1,5 +1,6 @@ export { type HubChannel, HubLink } from "./link"; export { + closePluginSettings, openPluginSettings, RELAY_TEXT, type RelayFix, diff --git a/packages/plugin/src/core/hub/relay-text.ts b/packages/plugin/src/core/hub/relay-text.ts index 48d7254f..cb5deba4 100644 --- a/packages/plugin/src/core/hub/relay-text.ts +++ b/packages/plugin/src/core/hub/relay-text.ts @@ -49,6 +49,7 @@ export function relayFixOf(status: RelayStatus): RelayFix | null { interface SettingsDialog { open(): void; + close(): void; openTabById(id: string): void; } @@ -57,3 +58,7 @@ export function openPluginSettings(app: App): void { setting?.open(); setting?.openTabById(PLUGIN_ID); } + +export function closePluginSettings(app: App): void { + (app as App & { setting?: SettingsDialog }).setting?.close(); +} diff --git a/packages/plugin/src/core/settings/model.ts b/packages/plugin/src/core/settings/model.ts index b2e7f84b..e0317f62 100644 --- a/packages/plugin/src/core/settings/model.ts +++ b/packages/plugin/src/core/settings/model.ts @@ -52,6 +52,7 @@ export interface CoreSettings { bulkDeleteLimit: number; fileHistoryEnabled: boolean; fileHistoryKeep: HistoryKeep; + fileHistoryActivity: boolean; historyAutoRefresh: boolean; realtimeSync: boolean; /** Notes open in the editor edit together across devices, over the relay. */ @@ -110,6 +111,7 @@ export const DEFAULT_CORE_SETTINGS: CoreSettings = { bulkDeleteLimit: 5, fileHistoryEnabled: false, fileHistoryKeep: "quarter", + fileHistoryActivity: true, historyAutoRefresh: true, realtimeSync: false, liveEditing: true, diff --git a/packages/plugin/src/core/shared/format.ts b/packages/plugin/src/core/shared/format.ts index 47f908c0..bb42806e 100644 --- a/packages/plugin/src/core/shared/format.ts +++ b/packages/plugin/src/core/shared/format.ts @@ -47,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. */ @@ -55,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); } -function startOfDay(ms: number): number { +/** "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, + }); +} + +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 index 594f92ef..d1fa52ae 100644 --- a/packages/plugin/src/core/shared/index.ts +++ b/packages/plugin/src/core/shared/index.ts @@ -3,10 +3,13 @@ export { reportWarning, setDiagnosticsSink } from "./diagnostics"; export { asError, errorMessage } from "./errors"; export { formatBytes, + formatDay, formatDayLabel, formatRelativeTime, formatTimestamp, pluralize, + startOfDay, + startOfWeek, sumBytes, withDevices, } from "./format"; 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..1bafc869 --- /dev/null +++ b/packages/plugin/src/features/settings/activity-card.ts @@ -0,0 +1,42 @@ +import { ButtonComponent } from "obsidian"; +import { closePluginSettings } from "@/core/hub"; +import { formatRelativeTime, pluralize } from "@/core/shared"; +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 index e74665db..1b33e9b5 100644 --- a/packages/plugin/src/features/settings/host.ts +++ b/packages/plugin/src/features/settings/host.ts @@ -21,5 +21,6 @@ export interface SettingsTabHost openSetup(step?: "relay"): void; refreshEditorSigns(enabled: boolean): void; refreshFileIndicators(enabled: boolean): void; - refreshSourceControlView(): void; + refreshSourceControlView(history?: boolean): void; + openTimeline(day?: number): Promise; } diff --git a/packages/plugin/src/features/settings/overview.css b/packages/plugin/src/features/settings/overview.css index 0876c726..2d84493f 100644 --- a/packages/plugin/src/features/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); } @@ -179,3 +179,14 @@ /* 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/features/settings/overview.ts b/packages/plugin/src/features/settings/overview.ts index 55f77732..fb215d5c 100644 --- a/packages/plugin/src/features/settings/overview.ts +++ b/packages/plugin/src/features/settings/overview.ts @@ -15,6 +15,7 @@ import { 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"; @@ -68,6 +69,7 @@ export function overviewGroup( renderCard(grid, relayCard(plugin)); }; draw(); + renderActivityCard(root, plugin); const { hub, people } = plugin.realtime; const stops = [ plugin.controller.subscribe(draw), diff --git a/packages/plugin/src/features/settings/sections/automation.ts b/packages/plugin/src/features/settings/sections/automation.ts index 90837574..ca009738 100644 --- a/packages/plugin/src/features/settings/sections/automation.ts +++ b/packages/plugin/src/features/settings/sections/automation.ts @@ -6,10 +6,12 @@ import { AUTO_SYNC_MIN_MINUTES, BULK_DELETE_LIMIT_MAX, BULK_DELETE_LIMIT_MIN, + HISTORY_KEEP_MS, + HISTORY_KEEP_TEXT, LIVE_SEND_MS, } from "@/core/constants"; import type { RelayStatus } from "@/core/hub"; -import { RELAY_TEXT } from "@/core/hub"; +import { closePluginSettings, RELAY_TEXT } from "@/core/hub"; import { DEFAULT_CORE_SETTINGS, EFieldKind, @@ -20,12 +22,13 @@ import { isRelayConfigured, type SettingsField, type SettingsHost, + type SettingsRow, SUB_SETTING_CLASS, } from "@/core/settings"; import type { LiveSessions } from "@/features/live"; import type { People } from "@/features/presence"; import type { HubConnection } from "@/features/relay"; -import { VAULT_SPACE } from "@/features/sync"; +import { renderHistoryHolds, VAULT_SPACE } from "@/features/sync"; import type { SettingsTabHost } from "../host"; /** The wizard shows these too, so they ask only what its host has. */ @@ -89,6 +92,20 @@ export const SETUP_FIELDS: ReadonlyArray> = [ LIVE_EDITING_FIELD, ]; +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 AUTOMATION_FIELDS: ReadonlyArray> = [ AUTOSYNC_FIELD, { @@ -172,21 +189,16 @@ const AUTOMATION_FIELDS: ReadonlyArray> = [ set: (v) => ({ fileHistoryEnabled: v }), rerender: true, }, + KEEP_HISTORY_FIELD, { - 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.", + 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, - options: { - week: "1 week", - month: "1 month", - quarter: "3 months", - year: "1 year", - forever: "Forever", - } satisfies Record, - get: (s) => s.fileHistoryKeep, - set: (v) => ({ fileHistoryKeep: v as HistoryKeep }), + get: (s) => s.fileHistoryActivity, + set: (v) => ({ fileHistoryActivity: v }), + after: (plugin) => plugin.refreshSourceControlView(), }, { kind: EFieldKind.Toggle, @@ -214,8 +226,12 @@ const AUTOMATION_FIELDS: ReadonlyArray> = [ export function automationSection( ctx: FieldContext, ): SettingDefinitionGroup { + const rows = AUTOMATION_FIELDS.map((field) => fieldRow(ctx, field)); + const keep = AUTOMATION_FIELDS.indexOf(KEEP_HISTORY_FIELD) + 1; return group("Automation", [ - ...AUTOMATION_FIELDS.map((field) => fieldRow(ctx, field)), + ...rows.slice(0, keep), + historyHoldsRow(ctx.plugin), + ...rows.slice(keep), { name: "Connected devices", visible: () => ctx.plugin.settings.realtimeSync, @@ -224,6 +240,25 @@ export function automationSection( ]); } +function historyHoldsRow(plugin: SettingsTabHost): 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: () => plugin.controller.history.listSnapshots(), + horizon: HISTORY_KEEP_MS[plugin.settings.fileHistoryKeep], + onPick: (day) => { + closePluginSettings(plugin.app); + void plugin.openTimeline(day.start); + }, + }); + }, + }; +} + function renderConnectedDevices( devicesSetting: Setting, plugin: SettingsTabHost, 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..a702c177 --- /dev/null +++ b/packages/plugin/src/features/source-control/history/age-groups.ts @@ -0,0 +1,100 @@ +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" && now - at < HOUR_MS) return "Last hour"; + return formatDayLabel(at, now); +} + +/** 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/features/source-control/history/day-groups.ts b/packages/plugin/src/features/source-control/history/day-groups.ts deleted file mode 100644 index 510f7205..00000000 --- a/packages/plugin/src/features/source-control/history/day-groups.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { formatDayLabel, formatRelativeTime } from "@/core/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/features/source-control/history/history-rows.ts b/packages/plugin/src/features/source-control/history/history-rows.ts index 30d02533..f345c1b9 100644 --- a/packages/plugin/src/features/source-control/history/history-rows.ts +++ b/packages/plugin/src/features/source-control/history/history-rows.ts @@ -1,7 +1,7 @@ -import { formatRelativeTime, formatTimestamp } from "@/core/shared"; -import type { FileVersion } from "@/features/sync"; +import { formatDay, formatRelativeTime, formatTimestamp } from "@/core/shared"; +import type { FileVersion, Resolution } from "@/features/sync"; import { deviceText } from "../changes/row-formatter"; -import { timeInDay } from "./day-groups"; +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; @@ -49,16 +54,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/features/source-control/history/history-tab.ts b/packages/plugin/src/features/source-control/history/history-tab.ts index 33019d0d..4eb379b5 100644 --- a/packages/plugin/src/features/source-control/history/history-tab.ts +++ b/packages/plugin/src/features/source-control/history/history-tab.ts @@ -1,5 +1,7 @@ import { Menu, setIcon } from "obsidian"; -import { pluralize } from "@/core/shared"; +import { HISTORY_KEEP_MS } from "@/core/constants"; +import { openPluginSettings } from "@/core/hub"; +import { formatDay, pluralize } from "@/core/shared"; import { appendIconButton, appendLabeledButton, @@ -10,9 +12,9 @@ import { } from "@/core/ui"; import type { HistoryDiffTarget } from "@/features/diff"; import { confirmRestore } from "@/features/diff"; -import type { FileVersion } from "@/features/sync"; +import { countsBefore, type FileVersion } from "@/features/sync"; import type { SourceControlHost } from "../host"; -import { renderSize } from "../row-parts"; +import { renderAgeHeader, renderSize } from "../row-parts"; import { renderEmptyState, renderHistoryOff, @@ -20,7 +22,7 @@ import { renderLoading, } from "../tab-states"; import { addSnapshotPinItems } from "../timeline/snapshot-menu"; -import { groupRows } from "./day-groups"; +import { groupByAge } from "./age-groups"; import { HistoryList } from "./history-list"; import { buildHistoryRows, type HistoryRow } from "./history-rows"; @@ -135,11 +137,35 @@ export class HistoryTab { const rows = buildHistoryRows(versions, { currentDevice: this.plugin.controller.currentDevice(), }); - 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.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 +194,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 +214,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 +259,13 @@ export class HistoryTab { ); } menu.addSeparator(); - addSnapshotPinItems(menu, this.plugin, row, this.onSnapshotsChanged); + addSnapshotPinItems( + menu, + this.plugin, + { ...row, snapshotId: row.pinId ?? row.snapshotId }, + this.onSnapshotsChanged, + row.replayable, + ); menu.showAtMouseEvent(event); } diff --git a/packages/plugin/src/features/source-control/history/history.css b/packages/plugin/src/features/source-control/history/history.css index 39a27f83..2366f05b 100644 --- a/packages/plugin/src/features/source-control/history/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/features/source-control/index.ts b/packages/plugin/src/features/source-control/index.ts index 284b0afd..068fd019 100644 --- a/packages/plugin/src/features/source-control/index.ts +++ b/packages/plugin/src/features/source-control/index.ts @@ -6,6 +6,7 @@ export { openSourceControlChanges, openSourceControlDeleted, openSourceControlHistory, + openSourceControlTimeline, openSourceControlView, refreshHistoryAfterPush, refreshSourceControlViews, diff --git a/packages/plugin/src/features/source-control/row-parts.ts b/packages/plugin/src/features/source-control/row-parts.ts index d2ac1b19..80ed3a3a 100644 --- a/packages/plugin/src/features/source-control/row-parts.ts +++ b/packages/plugin/src/features/source-control/row-parts.ts @@ -1,4 +1,19 @@ 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/features/source-control/timeline/session-card.ts b/packages/plugin/src/features/source-control/timeline/session-card.ts new file mode 100644 index 00000000..b1fbb330 --- /dev/null +++ b/packages/plugin/src/features/source-control/timeline/session-card.ts @@ -0,0 +1,224 @@ +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]) ?? "", + }); + for (const version of versions) renderVersion(body, version, 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) for (const version of versions) renderVersion(body, version, ctx); +} + +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..708ca53e --- /dev/null +++ b/packages/plugin/src/features/source-control/timeline/sessions.ts @@ -0,0 +1,82 @@ +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 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); +} + +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/features/source-control/timeline/snapshot-menu.ts b/packages/plugin/src/features/source-control/timeline/snapshot-menu.ts index 592737a5..621180c4 100644 --- a/packages/plugin/src/features/source-control/timeline/snapshot-menu.ts +++ b/packages/plugin/src/features/source-control/timeline/snapshot-menu.ts @@ -23,7 +23,7 @@ export function addSnapshotPinItems( label, ); onChanged(); - notifyInfo(pinned ? "Snapshot pinned." : "Snapshot unpinned."); + notifyInfo(pinned ? "Version pinned." : "Version unpinned."); } catch (error) { notifyError("Could not update pin", error); } @@ -31,7 +31,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/features/source-control/timeline/timeline-actions.ts b/packages/plugin/src/features/source-control/timeline/timeline-actions.ts index b281b60f..2a097f4b 100644 --- a/packages/plugin/src/features/source-control/timeline/timeline-actions.ts +++ b/packages/plugin/src/features/source-control/timeline/timeline-actions.ts @@ -2,6 +2,7 @@ import { Menu } from "obsidian"; import { notifyError, notifyInfo, openConfirmModal } from "@/core/ui"; import { confirmRestore } from "@/features/diff"; import type { SourceControlHost } from "../host"; +import type { SessionRow } from "./session-rows"; import { addSnapshotPinItems } from "./snapshot-menu"; import { describeRestorePlan, @@ -15,19 +16,36 @@ export class TimelineActions { 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)), @@ -35,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) => @@ -98,7 +112,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/features/source-control/timeline/timeline-rows.ts b/packages/plugin/src/features/source-control/timeline/timeline-rows.ts index 3ef37618..266cda6d 100644 --- a/packages/plugin/src/features/source-control/timeline/timeline-rows.ts +++ b/packages/plugin/src/features/source-control/timeline/timeline-rows.ts @@ -1,15 +1,15 @@ -import { formatRelativeTime, formatTimestamp, pluralize } from "@/core/shared"; +import { formatTimestamp, pluralize } from "@/core/shared"; import type { HistoryDiffTarget } from "@/features/diff"; import type { ChangeAction, HistoryVersionRef, ManifestEntry, + Resolution, SnapshotChanges, SnapshotSummary, VaultRestorePlan, } from "@/features/sync"; -import { deviceText } from "../changes/row-formatter"; -import { timeInDay } from "../history/day-groups"; +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: countsText(changes), + 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,11 @@ function fileRowsOf( function buildFileRows( changes: SnapshotChanges, - createdAt: number, + at: number, ): TimelineFileRow[] { const rows: TimelineFileRow[] = []; for (const [path, entry] of Object.entries(changes.added)) { - const after = versionRef(entry, createdAt, "after push"); + const after = versionRef(entry, at, "after push"); rows.push({ path, action: "add", @@ -112,8 +121,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, at, "before push"); + const after = versionRef(change.to, at, "after push"); rows.push({ path, action: "modify", @@ -125,14 +134,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, at, "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 +165,13 @@ function netBytes(changes: SnapshotChanges): number { function versionRef( entry: ManifestEntry, - createdAt: number, + at: number, suffix: string, ): HistoryVersionRef { return { hash: entry.hash, size: entry.size, - label: `${formatTimestamp(createdAt)} (${suffix})`, + label: `${formatTimestamp(at)} (${suffix})`, }; } @@ -170,9 +185,9 @@ 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]) => +export function countsText(changes: SnapshotChanges | null): string | null { + if (!changes) return null; + const parts = tallyOf(changes).map(([action, count]) => COUNT_WORDS[action](count), ); return parts.length > 0 ? parts.join(" · ") : "no file changes"; diff --git a/packages/plugin/src/features/source-control/timeline/timeline-tab.ts b/packages/plugin/src/features/source-control/timeline/timeline-tab.ts index 893c8a18..dfcdcac6 100644 --- a/packages/plugin/src/features/source-control/timeline/timeline-tab.ts +++ b/packages/plugin/src/features/source-control/timeline/timeline-tab.ts @@ -1,34 +1,35 @@ -import { setIcon } from "obsidian"; -import { formatBytes } from "@/core/shared"; +import { SearchComponent, setIcon } from "obsidian"; +import { formatDay, pluralize, startOfDay } from "@/core/shared"; import { appendIconButton, + appendLabeledButton, callout, makeActivatable, notifyError, - onLongPress, - renderPath, } from "@/core/ui"; import type { HistoryDiffTarget } from "@/features/diff"; -import type { SnapshotListResult } from "@/features/sync"; -import { STATUS_CLASSES, STATUS_LETTERS } from "../changes/row-formatter"; -import { groupRows } from "../history/day-groups"; +import { + type ActivityCalendar, + buildCalendar, + type CalendarDay, + renderActivityCalendar, + type SnapshotListResult, +} from "@/features/sync"; +import { ageTitle, groupByAge } from "../history/age-groups"; import { HistoryList } from "../history/history-list"; import { RowPager } from "../history/row-pager"; import type { SourceControlHost } from "../host"; -import { renderDelta } from "../row-parts"; +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 { - buildTimelineRows, - type TimelineFileRow, - type TimelineRow, - timelineDiffTarget, -} from "./timeline-rows"; +import { type TimelineFileRow, timelineDiffTarget } from "./timeline-rows"; export class TimelineTab { private readonly snapshots = new HistoryList(() => { @@ -37,11 +38,16 @@ export class TimelineTab { this.onRerender(); }); private openGeneration = 0; - private readonly expanded = new Set(); + private readonly open = new Set(); private readonly pages = new Map(); + private query = ""; + 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; @@ -58,7 +64,7 @@ export class TimelineTab { this.actions = new TimelineActions( plugin, onSnapshotsChanged, - (row, file, mode) => void this.openFile(row, file, mode), + (owner, file, mode) => void this.openFile(owner, file, mode), ); } @@ -92,6 +98,7 @@ export class TimelineTab { this.snapshots.clear(); this.openGeneration++; this.list = null; + this.redrawSessions = () => {}; } render(parent: HTMLElement, tools: HTMLElement): void { @@ -114,17 +121,14 @@ export class TimelineTab { }); 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; - } + 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; } } @@ -134,183 +138,242 @@ export class TimelineTab { } private renderBody(body: HTMLElement): void { - const { value: snapshots, error } = this.snapshots; + const { value: result, error } = this.snapshots; if (error) { renderLoadError(body, "Could not load the timeline", error, () => this.reload(), ); return; } - if (!snapshots) { + if (!result) { renderLoading(body); this.snapshots.load(() => this.plugin.controller.history.listSnapshots()); return; } - if (snapshots.lagging) { + if (result.lagging) { callout( body, "warning", - "History has not caught up with the latest push yet, so the newest snapshot is missing.", + "History has not caught up with the latest push yet, so the newest version is missing.", ); } - const rows = buildTimelineRows(snapshots.snapshots, { + const rows = buildSessionRows(result.snapshots, { currentDevice: this.plugin.controller.currentDevice(), }); - if (rows.length === 0 && !snapshots.lagging) { + if (rows.length === 0 && !result.lagging) { renderEmptyState(body, { icon: "clock-3", title: "No pushes yet", text: "No pushes recorded yet. The timeline fills up as you push.", }); + return; } - 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); - } + // Built while hidden too: a day picked in settings filters by it. + const calendar = buildCalendar(result.activity, result.snapshots); + // 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(); } - /** 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); + 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(); }); - 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); - }, + setIcon( + head.createSpan({ cls: "mdsync-timeline-icon" }), + this.activityOpen ? "chevron-down" : "chevron-right", ); - more.setAttr("data-timeline-focus", `${row.snapshotId}:menu`); - head.addEventListener("contextmenu", (event) => { - event.preventDefault(); - this.actions.showSnapshotMenu(event, row); + 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}`); }); - 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", + 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(); }); - meta.createSpan({ cls: "mdsync-timeline-device", text: row.meta }); - if (!row.tally) { - meta.createSpan({ text: "Change record unavailable" }); + } + + private renderSessions( + el: HTMLElement, + rows: readonly SessionRow[], + result: SnapshotListResult, + calendar: ActivityCalendar, + ): void { + const picked = this.picked; + if (picked?.res === "counts") { + this.renderCountsDay(el, picked, result, calendar); 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}`, + const query = this.query.trim().toLowerCase(); + const dayEnd = picked && new Date(picked.start); + dayEnd?.setDate(dayEnd.getDate() + 1); + const shown = rows.filter( + (row) => + (!query || row.versions.some((version) => touches(version, query))) && + (!dayEnd || (!row.pinned && 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() }, }); } - if (row.netDelta) renderDelta(meta, row.netDelta, "mdsync-timeline-net"); + const ctx = this.cardContext(query); + for (const group of groupByAge(shown)) { + renderAgeHeader(el, group); + for (const row of group.rows) renderSessionCard(el, row, ctx); + } + 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 renderFile( - parent: HTMLElement, - row: TimelineRow, - file: TimelineFileRow, + /** 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 key = JSON.stringify([row.snapshotId, file.path]); - const item = parent.createDiv({ - cls: "mdsync-file-row mdsync-timeline-file", + 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")}`, }); - 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 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 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); + 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:" or "all:" 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( - row: TimelineRow, + owner: string, file: TimelineFileRow, mode: "current" | "change" = "current", ): Promise { const generation = ++this.openGeneration; - this.selected = JSON.stringify([row.snapshotId, file.path]); + this.selected = JSON.stringify([owner, file.path]); this.opening = this.selected; this.onRerender(); try { diff --git a/packages/plugin/src/features/source-control/timeline/timeline.css b/packages/plugin/src/features/source-control/timeline/timeline.css index 942a8485..e99d97b9 100644 --- a/packages/plugin/src/features/source-control/timeline/timeline.css +++ b/packages/plugin/src/features/source-control/timeline/timeline.css @@ -250,3 +250,138 @@ .mdsync-diff-preview-body .cm-scroller { overflow: auto; } + +/* 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-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-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-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-timeline-more.mdsync-labeled-btn:hover { + text-decoration: underline; +} diff --git a/packages/plugin/src/features/source-control/trash/trash-rows.ts b/packages/plugin/src/features/source-control/trash/trash-rows.ts index 59f886b2..413675a2 100644 --- a/packages/plugin/src/features/source-control/trash/trash-rows.ts +++ b/packages/plugin/src/features/source-control/trash/trash-rows.ts @@ -1,4 +1,9 @@ -import { formatBytes, formatRelativeTime, normalizePath } from "@/core/shared"; +import { + formatBytes, + formatDay, + formatRelativeTime, + normalizePath, +} from "@/core/shared"; import type { DeletedFile } from "@/features/sync"; import { deviceText } from "../changes/row-formatter"; @@ -53,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) ? { @@ -71,7 +77,7 @@ export function buildTrashRows( } function retentionNote(file: DeletedFile, now: number): TrashNote | null { - const text = retentionText(file); + const text = retentionText(file, now); if (text === null) return null; if (file.pinned) return { text, tone: "pinned", icon: "pin" }; const soon = file.keptUntil !== null && file.keptUntil - now <= SOON_MS; @@ -100,8 +106,9 @@ export function resolveRestoreTarget(input: string): string | null { /** Retention promises "at least": GC may keep a version past this date, never drops it before. */ export function retentionText( file: Pick, + now: number, ): string | null { if (file.pinned) return "Kept by a pinned snapshot"; if (file.keptUntil === null) return null; - return `Kept in history until ${new Date(file.keptUntil).toLocaleDateString()}`; + return `Kept until ${formatDay(file.keptUntil, now, false)}`; } diff --git a/packages/plugin/src/features/source-control/trash/trash-tab.ts b/packages/plugin/src/features/source-control/trash/trash-tab.ts index 90d03090..6340def3 100644 --- a/packages/plugin/src/features/source-control/trash/trash-tab.ts +++ b/packages/plugin/src/features/source-control/trash/trash-tab.ts @@ -1,5 +1,12 @@ -import { Menu, Platform, setIcon, TFile, TFolder } from "obsidian"; -import { pluralize } from "@/core/shared"; +import { + Menu, + Platform, + SearchComponent, + setIcon, + TFile, + TFolder, +} from "obsidian"; +import { HISTORY_KEEP_TEXT } from "@/core/constants"; import { appendIconButton, attempt, @@ -39,7 +46,9 @@ 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; @@ -148,23 +157,80 @@ export class TrashTab implements SelectionSource { 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 within history. Deletions older than it are gone unless a pinned snapshot holds them.", + 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 { @@ -182,8 +248,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`, }); } diff --git a/packages/plugin/src/features/source-control/view.ts b/packages/plugin/src/features/source-control/view.ts index b31fe421..e121d180 100644 --- a/packages/plugin/src/features/source-control/view.ts +++ b/packages/plugin/src/features/source-control/view.ts @@ -192,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); } diff --git a/packages/plugin/src/features/source-control/workspace.ts b/packages/plugin/src/features/source-control/workspace.ts index c47aa3b7..bf76bb4d 100644 --- a/packages/plugin/src/features/source-control/workspace.ts +++ b/packages/plugin/src/features/source-control/workspace.ts @@ -16,6 +16,14 @@ export function openSourceControlDeleted( 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, @@ -94,8 +102,12 @@ export function refreshHistoryAfterPush(plugin: SourceControlHost): void { for (const view of openViews(plugin.app)) view.refreshHistory(); } -export function refreshSourceControlViews(app: App): void { - for (const view of openViews(app)) view.refreshDisplaySettings(); +/** `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[] { diff --git a/packages/plugin/src/features/sync/README.md b/packages/plugin/src/features/sync/README.md index abcced1c..a041a79a 100644 --- a/packages/plugin/src/features/sync/README.md +++ b/packages/plugin/src/features/sync/README.md @@ -78,7 +78,7 @@ A hunk index means nothing without its two texts. The diff view, the gutter mark ## 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`). 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 a day later. +Every push writes one encrypted record, `history/p/.enc`, before it publishes: the diff from that snapshot's parent (`added`, `modified {from, to}`, `deleted`). 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 a day later. 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. diff --git a/packages/plugin/src/features/sync/controller.ts b/packages/plugin/src/features/sync/controller.ts index 0184b118..d8ee0a17 100644 --- a/packages/plugin/src/features/sync/controller.ts +++ b/packages/plugin/src/features/sync/controller.ts @@ -6,6 +6,8 @@ import { } from "./automation/auto-push"; import { clearRemoteTextCache } from "./changes/content"; import type { EngineDependencies } from "./engine"; +import { ActivityCache, type ActivityStore } 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"; @@ -83,6 +85,8 @@ 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?: ActivityStore; /** 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; @@ -154,10 +158,16 @@ export class SyncController { private localRevision = 0; readonly history: HistoryService; readonly maintenance: MaintenanceService; + readonly activity: ActivityCache; constructor(host: SyncControllerHost) { this.host = host; this.runtimeState = new SyncControllerRuntimeState(); + this.activity = new ActivityCache( + host.activityStore ?? { load: () => null, save: () => {} }, + ); + 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)), @@ -200,6 +210,7 @@ export class SyncController { open(path === undefined ? VAULT_SPACE : this.spaceFor(path)), enqueue: (task) => this.runtimeState.enqueue(task), refresh: () => this.operations.refreshNow(), + remember, }); this.maintenance = new MaintenanceService({ openSession: open, @@ -209,6 +220,7 @@ export class SyncController { this.host.logInfo(operation, message, details), logWarn: (operation, message, details) => this.host.logWarn(operation, message, details), + remember, }); } @@ -340,9 +352,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( @@ -354,9 +369,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/features/sync/history/activity-cache.ts b/packages/plugin/src/features/sync/history/activity-cache.ts new file mode 100644 index 00000000..1d7e6342 --- /dev/null +++ b/packages/plugin/src/features/sync/history/activity-cache.ts @@ -0,0 +1,57 @@ +import type { Activity } from "./model/types"; + +/** Device-local and never synced: Obsidian's local storage for this vault. */ +export interface ActivityStore { + load(): unknown; + save(value: unknown): void; +} + +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: ActivityStore) {} + + /** 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/gc.ts b/packages/plugin/src/features/sync/history/gc.ts index 18833fd4..c261a476 100644 --- a/packages/plugin/src/features/sync/history/gc.ts +++ b/packages/plugin/src/features/sync/history/gc.ts @@ -5,8 +5,10 @@ import type { 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, @@ -23,6 +25,8 @@ export interface GcResult { retired: number; /** File blobs deleted. */ swept: number; + /** Pushes per hour as this run read them; null without a HEAD. */ + activity: Activity | null; } /** @@ -38,7 +42,7 @@ export async function collectHistoryGarbage( const head = storage.listDetailed ? await fetchRemoteManifest(storage, key, root) : null; - if (!head) return { written: 0, retired: 0, swept: 0 }; + 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(isSettled) @@ -96,7 +100,11 @@ async function thinHistory( await runWithConcurrency(gone, DEFAULT_CONCURRENCY, (storageKey) => storage.delete(storageKey), ); - return { written: written.size, retired: gone.length }; + return { + written: written.size, + retired: gone.length, + activity: activityOf(view, cover, head.vaultId), + }; } function changesOf( diff --git a/packages/plugin/src/features/sync/history/model/cover.ts b/packages/plugin/src/features/sync/history/model/cover.ts index 9957b3a1..87f1d539 100644 --- a/packages/plugin/src/features/sync/history/model/cover.ts +++ b/packages/plugin/src/features/sync/history/model/cover.ts @@ -1,6 +1,11 @@ import { RESOLUTIONS } from "./periods"; import { runsOf, storedRecord } from "./records"; -import type { HistoryObject, PushRecord, StoredRecord } from "./types"; +import type { + HistoryObject, + PushRecord, + Resolution, + StoredRecord, +} from "./types"; /** What storage holds, decoded; `at` is the listing's write time. */ export interface HistoryView { @@ -12,6 +17,8 @@ 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 { @@ -34,6 +41,7 @@ export interface Head { /** 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. */ @@ -76,7 +84,7 @@ export function coverOf(view: HistoryView, head: Head | null): Cover { 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 }); + chain.push({ record, source: segment.key, res: segment.res }); } at = segment.parentId; } @@ -128,23 +136,32 @@ function segmentsOf( ): Segment[] { const segments: Segment[] = []; // Every record ends a segment: a sibling may fork from inside a packed run. - const add = (key: string, rank: number, run: StoredRecord[]): void => { + 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, rank, run, length: index + 1, parentId, 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, 0, [storedRecord(push, at)]); + 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, RESOLUTIONS.indexOf(object.res), run); + add(key, object.res, run); } } return segments; diff --git a/packages/plugin/src/features/sync/history/model/periods.ts b/packages/plugin/src/features/sync/history/model/periods.ts index 10a6dae8..4e5426b8 100644 --- a/packages/plugin/src/features/sync/history/model/periods.ts +++ b/packages/plugin/src/features/sync/history/model/periods.ts @@ -65,6 +65,11 @@ export function keepStart(res: Resolution, at: number): number | null { 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, @@ -85,6 +90,33 @@ export function keptUntil(at: number, horizon: number | null): number | 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, diff --git a/packages/plugin/src/features/sync/history/query.ts b/packages/plugin/src/features/sync/history/query.ts index 12f72c09..513f0c92 100644 --- a/packages/plugin/src/features/sync/history/query.ts +++ b/packages/plugin/src/features/sync/history/query.ts @@ -5,7 +5,13 @@ import { entryAt } from "../changes/records"; import { fetchRemoteManifest } from "../remote/manifest"; import type { Manifest, ManifestEntry } from "../types"; import { undoChangesForPath } from "./changes"; -import { type Cover, coverOf } from "./model/cover"; +import { activityOf } from "./model/activity"; +import { + type Cover, + coverOf, + type HistoryView, + type WalkedRecord, +} from "./model/cover"; import { keptUntil } from "./model/periods"; import { deletePin, @@ -17,6 +23,7 @@ import { import { readHistory } from "./remote"; import { replayTo } from "./replay"; import type { + Dating, DeletedFile, DeletedFilesResult, FileVersion, @@ -40,7 +47,7 @@ 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 }> { +): Promise<{ head: Manifest | null; cover: Cover; view: HistoryView }> { const { storage, key, root } = source; const [head, history] = await Promise.all([ fetchRemoteManifest(storage, key, root), @@ -54,10 +61,13 @@ export async function readTimeline( vaultId: head.vaultId, }, ); - return { head, cover }; + return { head, cover, view: history.view }; } -/** Distinct versions of one path, newest first; pinned ones follow. */ +/** + * 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 & { path: string }, ): Promise { @@ -70,30 +80,53 @@ export async function getFileHistory( query.root, (pin) => entryAt(pin.manifest.files, path) ?? null, ); - const labels = new Map(pins.pins.map(({ info }) => [info.id, info.label])); + const pinOf: PinsByHash = new Map( + pins.pins.flatMap(({ info, picked }) => + picked ? [[picked.hash, info] as const] : [], + ), + ); const versions: FileVersion[] = []; - const visited = new Set([head.snapshotId]); 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), entry, labels)); + versions.push(toVersion(metaOf(head), undated(head), entry, pinOf)); } - let lastHash: string | null = null; - for (const { record } of chain) { - visited.add(record.id); - if (entry === null) { - lastHash = null; - } else if (entry.hash !== lastHash) { - versions.push(toVersion(record, entry, labels)); - lastHash = entry.hash; + for (const walked of chain) { + const before = undoChangesForPath(entry, walked.record.changes, path); + if (entry && before?.hash !== entry.hash) { + versions.push({ + ...toVersion(walked.record, datingOf(walked), entry, pinOf), + first: before === null, + replayable: true, + }); } - entry = undoChangesForPath(entry, record.changes, path); + 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 && !visited.has(info.id)) { - versions.push(toVersion(info, picked, labels)); - } + if (!picked || listed.has(picked.hash)) continue; + listed.add(picked.hash); + versions.push(toVersion(info, undated(info), picked, pinOf)); } return versions; } @@ -186,8 +219,9 @@ async function applyPins( export async function listSnapshots( query: HistoryQuery, ): Promise { - const { head, cover } = await readTimeline(query); - if (!head) return { snapshots: [], lagging: false }; + const { head, cover, view } = await readTimeline(query); + if (!head) + return { snapshots: [], lagging: false, truncated: false, activity: {} }; const { pins } = await readPins( query.storage, query.key, @@ -197,11 +231,13 @@ export async function listSnapshots( 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, @@ -214,14 +250,25 @@ export async function listSnapshots( isHead: meta.id === head.snapshotId, }; }; - const snapshots = cover.chain.map(({ record }) => - summary(record, record.changes, keptUntil(record.at, query.horizon)), + 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, null, null)); + if (!onChain.has(info.id)) + snapshots.push(summary(info, undated(info), null, null)); } - return { snapshots, lagging: cover.lagging }; + 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. */ @@ -293,12 +340,26 @@ function metaOf(manifest: Manifest): Meta { }; } +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, - labels: ReadonlyMap, + pinOf: PinsByHash, ): FileVersion { return { + ...dating, snapshotId: meta.id, hash: entry.hash, size: entry.size, @@ -307,7 +368,9 @@ function toVersion( createdAt: meta.createdAt, deviceId: meta.deviceId, deviceName: meta.deviceName, - pinned: labels.has(meta.id), - label: labels.get(meta.id), + 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/types.ts b/packages/plugin/src/features/sync/history/types.ts index 386d7e8b..fede001d 100644 --- a/packages/plugin/src/features/sync/history/types.ts +++ b/packages/plugin/src/features/sync/history/types.ts @@ -1,4 +1,5 @@ import type { EFileKind, ManifestEntry } from "../types"; +import type { Activity, Resolution } from "./model/types"; export interface HistoryConfig { /** ms past which only activity counts are kept; null keeps every tier forever. */ @@ -20,7 +21,17 @@ export interface SnapshotChanges { deletedLast?: Record; } -export interface FileVersion { +/** 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 extends Dating { snapshotId: string; hash: string; size: number; @@ -29,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 { @@ -63,7 +79,7 @@ export interface DeletedFilesResult { truncated: boolean; } -export interface SnapshotSummary { +export interface SnapshotSummary extends Dating { id: string; createdAt: number; deviceId: string; @@ -84,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/index.ts b/packages/plugin/src/features/sync/index.ts index 63041440..744e0789 100644 --- a/packages/plugin/src/features/sync/index.ts +++ b/packages/plugin/src/features/sync/index.ts @@ -17,8 +17,16 @@ export { 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, @@ -112,6 +120,14 @@ export { } from "./types"; 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 { renderHistoryHolds } from "./ui/history/holds-row"; export { addIgnoreMenuItem, carryVaultIgnores, diff --git a/packages/plugin/src/features/sync/runtime/history-service.ts b/packages/plugin/src/features/sync/runtime/history-service.ts index 5636cf33..6e15693a 100644 --- a/packages/plugin/src/features/sync/runtime/history-service.ts +++ b/packages/plugin/src/features/sync/runtime/history-service.ts @@ -12,6 +12,7 @@ import { } from "../changes/content"; import { runWithFileConcurrency } from "../changes/file-concurrency"; import type { EngineDependencies } from "../engine"; +import type { Activity } from "../history/model/types"; import { type HistoryQuery, loadVersionBytes, @@ -54,6 +55,8 @@ 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; } /** Reads and restores past file versions from the snapshot history. */ @@ -78,8 +81,12 @@ export class HistoryService { async listSnapshots(): Promise { const session = await this.deps.openSession(); - if (!session) return { snapshots: [], lagging: false }; - return querySnapshots(queryOf(session)); + 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. */ diff --git a/packages/plugin/src/features/sync/runtime/maintenance-service.ts b/packages/plugin/src/features/sync/runtime/maintenance-service.ts index 62b16207..388533e2 100644 --- a/packages/plugin/src/features/sync/runtime/maintenance-service.ts +++ b/packages/plugin/src/features/sync/runtime/maintenance-service.ts @@ -4,6 +4,7 @@ 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, @@ -30,6 +31,8 @@ interface MaintenanceServiceDeps { 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 { @@ -64,12 +67,16 @@ export class MaintenanceService { } } if (!session.history) return; - const { written, retired, swept } = await collectHistoryGarbage( - session.storage, - session.key, - session.space.root, - session.history, - ); + 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, 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..051a963f --- /dev/null +++ b/packages/plugin/src/features/sync/ui/history/activity-calendar.ts @@ -0,0 +1,133 @@ +import { Notice, Platform } from "obsidian"; +import { + type ActivityCalendar, + bandsOf, + type CalendarDay, + dayTooltip, + RESOLUTION_TEXT, +} from "./calendar"; + +/** Narrower bands leave their label out. */ +const LABELED_WEEKS = 4; +const TIP_MS = 4000; +/** 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"); + let tip: Notice | null = null; + const pick = (cell: HTMLElement): void => { + const day = days.get(cell.dataset.day ?? ""); + if (!day) return; + // A phone has no hover to show the tooltip. + if (Platform.isMobile) { + tip?.hide(); + tip = new Notice(cell.getAttribute("aria-label") ?? "", TIP_MS); + } + 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); + // Until it overflows: settings lay it out wide, then narrow it as the page opens. + const anchor = new ResizeObserver(() => { + if (!scroller.isConnected) return anchor.disconnect(); + scroller.scrollLeft = ringed + ? ringed.offsetLeft - scroller.clientWidth / 2 + : scroller.scrollWidth; + if (scroller.scrollWidth > scroller.clientWidth) anchor.disconnect(); + }); + anchor.observe(scroller); +} + +/** 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/holds-row.css b/packages/plugin/src/features/sync/ui/history/holds-row.css new file mode 100644 index 00000000..e5d588ea --- /dev/null +++ b/packages/plugin/src/features/sync/ui/history/holds-row.css @@ -0,0 +1,65 @@ +/* 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; +} + +.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); +} + +.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..97aa7aa5 --- /dev/null +++ b/packages/plugin/src/features/sync/ui/history/holds-row.ts @@ -0,0 +1,63 @@ +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) => { + 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/features/transfer/transfer.ts b/packages/plugin/src/features/transfer/transfer.ts index f0390e2a..c039d21b 100644 --- a/packages/plugin/src/features/transfer/transfer.ts +++ b/packages/plugin/src/features/transfer/transfer.ts @@ -53,6 +53,7 @@ const TRANSFER_FIELDS = { shareEditsWait: "w", fileHistoryEnabled: "h", fileHistoryKeep: "y", + fileHistoryActivity: "f", historyAutoRefresh: "r", }, l: { diff --git a/packages/plugin/src/main.ts b/packages/plugin/src/main.ts index f0243372..a9dcf3b7 100644 --- a/packages/plugin/src/main.ts +++ b/packages/plugin/src/main.ts @@ -40,6 +40,7 @@ import { } from "@/features/setup"; import { openSourceControlChanges, + openSourceControlTimeline, openSourceControlView, refreshSourceControlViews, } from "@/features/source-control"; @@ -241,8 +242,8 @@ export default class MdsyncPlugin extends Plugin implements PluginHost { this.fileIndicators?.refresh(enabled); } - refreshSourceControlView(): void { - refreshSourceControlViews(this.app); + refreshSourceControlView(history?: boolean): void { + refreshSourceControlViews(this.app, history); } openSetup(step?: ESetupStep): void { @@ -262,6 +263,10 @@ export default class MdsyncPlugin extends Plugin implements PluginHost { 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/styles.css b/packages/plugin/src/styles.css index 0e331538..fc288bb6 100644 --- a/packages/plugin/src/styles.css +++ b/packages/plugin/src/styles.css @@ -9,6 +9,9 @@ @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/settings/tabs-and-logs.css"; @import "./features/source-control/styles/shell.css"; diff --git a/packages/plugin/tests/core/shared/format.test.ts b/packages/plugin/tests/core/shared/format.test.ts index d97c9c03..766c8b33 100644 --- a/packages/plugin/tests/core/shared/format.test.ts +++ b/packages/plugin/tests/core/shared/format.test.ts @@ -1,8 +1,9 @@ -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it } from "vitest"; import { formatBytes, formatDayLabel, pluralize, + startOfWeek, withDevices, } from "@/core/shared/format"; @@ -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/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/features/source-control/history/day-groups.test.ts b/packages/plugin/tests/features/source-control/history/day-groups.test.ts deleted file mode 100644 index 2b05a606..00000000 --- a/packages/plugin/tests/features/source-control/history/day-groups.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { groupRows } from "@/features/source-control/history/day-groups"; - -const NOON = new Date(2024, 4, 15, 12).getTime(); -const DAY = 86_400_000; - -function row( - id: string, - createdAt: number, - pinned = false, -): { id: string; createdAt: number; pinned: boolean } { - return { id, createdAt, pinned }; -} - -describe("groupRows", () => { - it("keeps consecutive rows from one day together, in order", () => { - const groups = groupRows( - [ - row("a", NOON), - row("b", NOON - 60_000), - row("c", NOON - DAY), - row("d", NOON - 3 * DAY), - ], - NOON, - ); - expect(groups.map((group) => group.label)).toEqual([ - "Today", - "Yesterday", - new Date(NOON - 3 * DAY).toLocaleDateString(undefined, { - weekday: "long", - }), - ]); - expect(groups[0]?.rows.map((entry) => entry.id)).toEqual(["a", "b"]); - expect(groups[1]?.rows.map((entry) => entry.id)).toEqual(["c"]); - }); - - it("opens a fresh group when a day repeats out of order", () => { - const groups = groupRows( - [row("a", NOON), row("b", NOON - DAY), row("c", NOON)], - NOON, - ); - expect(groups.map((group) => group.label)).toEqual([ - "Today", - "Yesterday", - "Today", - ]); - }); - - it("lifts pinned rows into a leading group, out of their day", () => { - const groups = groupRows( - [ - row("a", NOON), - row("b", NOON - DAY, true), - row("c", NOON - DAY), - row("d", NOON - 3 * DAY, true), - ], - NOON, - ); - expect(groups.map((group) => group.label)).toEqual([ - "Pinned", - "Today", - "Yesterday", - ]); - expect(groups[0]?.rows.map((entry) => entry.id)).toEqual(["b", "d"]); - expect(groups[2]?.rows.map((entry) => entry.id)).toEqual(["c"]); - }); - - it("leaves no empty day behind when all its rows are pinned", () => { - const groups = groupRows( - [row("a", NOON), row("b", NOON - DAY, true)], - NOON, - ); - expect(groups.map((group) => group.label)).toEqual(["Pinned", "Today"]); - }); - - it("has no groups without rows", () => { - expect(groupRows([], NOON)).toEqual([]); - }); -}); diff --git a/packages/plugin/tests/features/source-control/history/history-rows.test.ts b/packages/plugin/tests/features/source-control/history/history-rows.test.ts index 6fd4c9a9..9d3a3b2b 100644 --- a/packages/plugin/tests/features/source-control/history/history-rows.test.ts +++ b/packages/plugin/tests/features/source-control/history/history-rows.test.ts @@ -1,4 +1,9 @@ import { describe, expect, it } from "vitest"; +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"; @@ -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", () => { @@ -69,20 +88,20 @@ describe("buildHistoryRows", () => { 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 +110,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 +125,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/timeline/session-rows.test.ts b/packages/plugin/tests/features/source-control/timeline/session-rows.test.ts new file mode 100644 index 00000000..fa499258 --- /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(), + 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 · 0 files", + 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..df0891e4 --- /dev/null +++ b/packages/plugin/tests/features/source-control/timeline/sessions.test.ts @@ -0,0 +1,138 @@ +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: {}, modified: {}, deleted: {} }, + keptUntil: null, + restorable: true, + isHead: false, + at, + firstAt: at, + pushes: 1, + res: "push", + ...overrides, + }; +} + +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("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/timeline-rows.test.ts b/packages/plugin/tests/features/source-control/timeline/timeline-rows.test.ts index 6b6d851c..439d9927 100644 --- a/packages/plugin/tests/features/source-control/timeline/timeline-rows.test.ts +++ b/packages/plugin/tests/features/source-control/timeline/timeline-rows.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "vitest"; +import { clockTime } from "@/features/source-control/history/age-groups"; import { buildTimelineRows, countsText, @@ -40,6 +41,10 @@ function snapshot(overrides: Partial = {}): SnapshotSummary { keptUntil: null, restorable: true, isHead: false, + at: NOW - DAY, + firstAt: NOW - DAY, + pushes: 1, + res: "push", ...overrides, }; } @@ -52,35 +57,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 +95,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 +120,7 @@ describe("buildTimelineRows", () => { }, }), ], - { now: NOW }, + NOW, ); expect(row?.tally).toEqual([ ["add", 1], @@ -136,7 +131,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 +139,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 +165,7 @@ describe("buildTimelineRows", () => { }), }), ], - { now: NOW }, + NOW, ); expect(row?.files).toHaveLength(3); const [first, second, third] = row?.files ?? []; @@ -201,6 +192,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 +223,7 @@ describe("buildTimelineRows", () => { }), }), ], - { now: NOW }, + NOW, ); const file = row?.files?.[0]; expect(file?.action).toBe("delete"); @@ -229,7 +241,7 @@ describe("buildTimelineRows", () => { }), }), ], - { now: NOW }, + NOW, ); const file = row?.files?.[0]; expect(file?.action).toBe("add"); @@ -247,7 +259,7 @@ describe("buildTimelineRows", () => { }), }), ], - { now: NOW }, + NOW, ); expect(row?.files?.[0]?.path).toBe("constructor"); }); @@ -264,7 +276,7 @@ describe("buildTimelineRows", () => { }), }), ], - { now: NOW }, + NOW, ); const file = row?.files?.[0]; expect(file?.before?.hash).toBe("OLD"); @@ -275,7 +287,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 +305,7 @@ describe("buildTimelineRows", () => { }), }), ], - { now: NOW }, + NOW, ); const [modified, deleted, added] = row?.files ?? []; expect(modified?.size).toBe(250); @@ -317,7 +329,7 @@ describe("buildTimelineRows", () => { }), }), ], - { now: NOW }, + NOW, ); // 3072 added, 1024 lost on the edit, 1024 removed. expect(row?.netDelta).toBe(1024); @@ -334,12 +346,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(); }); }); @@ -464,8 +474,8 @@ describe("buildTimelineRows file rows", () => { 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/trash/trash-rows.test.ts b/packages/plugin/tests/features/source-control/trash/trash-rows.test.ts index 1ada3de3..d8a5cd64 100644 --- a/packages/plugin/tests/features/source-control/trash/trash-rows.test.ts +++ b/packages/plugin/tests/features/source-control/trash/trash-rows.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { formatRelativeTime } from "@/core/shared/format"; +import { formatDay, formatRelativeTime } from "@/core/shared/format"; import { buildTrashRows, resolveRestoreTarget, @@ -40,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", () => { @@ -50,31 +50,31 @@ describe("formatRelativeTime", () => { describe("retentionText", () => { it("names the date history keeps the record until", () => { - expect(retentionText({ pinned: false, keptUntil: KEPT_UNTIL })).toBe( - `Kept in history until ${new Date(KEPT_UNTIL).toLocaleDateString()}`, + expect(retentionText({ pinned: false, keptUntil: KEPT_UNTIL }, NOW)).toBe( + `Kept until ${formatDay(KEPT_UNTIL, NOW, false)}`, ); }); 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 })).toBe( - `Kept in history until ${new Date(past).toLocaleDateString()}`, + expect(retentionText({ pinned: false, keptUntil: past }, NOW)).toBe( + `Kept until ${formatDay(past, NOW, false)}`, ); }); it("says nothing when no date applies", () => { - expect(retentionText({ pinned: false, keptUntil: null })).toBeNull(); + expect(retentionText({ pinned: false, keptUntil: null }, NOW)).toBeNull(); }); it("says a pin holds the record", () => { - expect(retentionText({ pinned: true, keptUntil: null })).toBe( + 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 })).toBe( + expect(retentionText({ pinned: true, keptUntil: KEPT_UNTIL }, NOW)).toBe( "Kept by a pinned snapshot", ); }); @@ -89,9 +89,9 @@ describe("buildTrashRows", () => { 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: `Kept in history until ${new Date(KEPT_UNTIL).toLocaleDateString()}`, + text: `Kept until ${formatDay(KEPT_UNTIL, NOW, false)}`, tone: "plain", icon: "hourglass", }); 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/gc.test.ts b/packages/plugin/tests/features/sync/history/gc.test.ts index a90bc877..c20b94c5 100644 --- a/packages/plugin/tests/features/sync/history/gc.test.ts +++ b/packages/plugin/tests/features/sync/history/gc.test.ts @@ -134,7 +134,32 @@ describe("collectHistoryGarbage", () => { expect(after.length).toBeLessThan(before.length + 1); expect(after[0]).toBe(device.head?.snapshotId); - expect(await device.gc()).toEqual({ written: 0, retired: 0, swept: 0 }); + expect(await device.gc()).toMatchObject({ + written: 0, + retired: 0, + swept: 0, + }); + }); + + 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 a day later, and leaves nothing dangling", async () => { @@ -267,7 +292,12 @@ describe("collectHistoryGarbage", () => { vi.setSystemTime(Date.now() + 2 * DAY); Object.assign(device.storage, { listDetailed: undefined }); - expect(await device.gc()).toEqual({ written: 0, retired: 0, swept: 0 }); + 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 () => { diff --git a/packages/plugin/tests/features/sync/history/history-deleted.test.ts b/packages/plugin/tests/features/sync/history/history-deleted.test.ts index 2e930ecb..4e503256 100644 --- a/packages/plugin/tests/features/sync/history/history-deleted.test.ts +++ b/packages/plugin/tests/features/sync/history/history-deleted.test.ts @@ -455,6 +455,28 @@ describe("listSnapshots", () => { 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), @@ -463,9 +485,11 @@ describe("listSnapshots", () => { ]; const storage = await seed(chain, ["s2"]); - expect( - (await snapshots(storage)).snapshots.map((s) => [s.id, s.restorable]), - ).toEqual([["s3", true]]); + 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); @@ -477,6 +501,12 @@ describe("listSnapshots", () => { ]); 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 () => { diff --git a/packages/plugin/tests/features/sync/history/history-query.test.ts b/packages/plugin/tests/features/sync/history/history-query.test.ts index af8b559c..dc3f5152 100644 --- a/packages/plugin/tests/features/sync/history/history-query.test.ts +++ b/packages/plugin/tests/features/sync/history/history-query.test.ts @@ -249,9 +249,47 @@ describe("getFileHistory", () => { const versions = await historyOf(storage, "a.md"); expect(versions.map((v) => v.hash)).toEqual(["A2", "A1"]); - // The A1 version is attributed to the newest snapshot holding it. - expect(versions.map((v) => v.snapshotId)).toEqual(["s3", "s2"]); - expect(versions.map((v) => v.createdAt)).toEqual([300, 200]); + // 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("returns nothing for a path the history never saw", async () => { @@ -308,10 +346,10 @@ describe("getFileHistory", () => { await pinSnapshot(storage, key, chain[1] as Manifest, "keeper"); const versions = await historyOf(storage, "a.md"); - expect(versions.map((v) => [v.hash, v.pinned, v.label])).toEqual([ - ["A3", false, undefined], - ["A2", true, "keeper"], - ["A1", false, undefined], + expect(versions.map((v) => [v.hash, v.pinId, v.label])).toEqual([ + ["A3", null, undefined], + ["A2", "s2", "keeper"], + ["A1", null, undefined], ]); }); @@ -327,10 +365,15 @@ describe("getFileHistory", () => { await pinSnapshot(storage, key, chain[0] as Manifest); const versions = await historyOf(storage, "a.md"); - expect(versions.map((v) => v.hash)).toEqual(["A3", "A1"]); - expect(versions[0]?.pinned).toBe(false); - expect(versions[1]?.pinned).toBe(true); - expect(versions[1]?.snapshotId).toBe("s1"); + // 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 () => { @@ -345,8 +388,9 @@ describe("getFileHistory", () => { 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"]); + expect(versions.map((v) => v.hash)).toEqual(["A3", "A2"]); }); it("serves the current version while HEAD has no record", async () => { diff --git a/packages/plugin/tests/features/sync/history/model/activity.test.ts b/packages/plugin/tests/features/sync/history/model/activity.test.ts index f790f14f..e66eceec 100644 --- a/packages/plugin/tests/features/sync/history/model/activity.test.ts +++ b/packages/plugin/tests/features/sync/history/model/activity.test.ts @@ -62,7 +62,7 @@ it("takes a record walked into counted hours as another view of the same pushes" objects: new Map([["b/1", counts(0, record.activity)]]), }; const cover = { - chain: [{ record, source: "b/week" }], + chain: [{ record, source: "b/week", res: "1w" as const }], lagging: false, truncated: false, consumed: new Set(), diff --git a/packages/plugin/tests/features/sync/history/model/periods.test.ts b/packages/plugin/tests/features/sync/history/model/periods.test.ts index e46000d7..0e77ced1 100644 --- a/packages/plugin/tests/features/sync/history/model/periods.test.ts +++ b/packages/plugin/tests/features/sync/history/model/periods.test.ts @@ -1,12 +1,15 @@ 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; @@ -77,4 +80,34 @@ describe("history periods", () => { } } }); + + 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/runtime/history-service-scope.test.ts b/packages/plugin/tests/features/sync/runtime/history-service-scope.test.ts index 42bda2c0..3a4685d4 100644 --- a/packages/plugin/tests/features/sync/runtime/history-service-scope.test.ts +++ b/packages/plugin/tests/features/sync/runtime/history-service-scope.test.ts @@ -38,6 +38,7 @@ function serviceFor(session: TestSession): HistoryService { }), enqueue: (task) => task(), refresh: async () => undefined, + remember: () => undefined, }); } diff --git a/packages/plugin/tests/features/sync/runtime/maintenance-service.test.ts b/packages/plugin/tests/features/sync/runtime/maintenance-service.test.ts index 1c7ffe5f..74f5f03f 100644 --- a/packages/plugin/tests/features/sync/runtime/maintenance-service.test.ts +++ b/packages/plugin/tests/features/sync/runtime/maintenance-service.test.ts @@ -19,6 +19,7 @@ function service( ) { const logWarn = vi.fn(() => Promise.resolve()); const logInfo = vi.fn(() => Promise.resolve()); + const remember = vi.fn(); const queued: Promise[] = []; const maintenance = new MaintenanceService({ openSession: async (space) => @@ -36,15 +37,21 @@ function service( }, logInfo, logWarn, + remember, }); const settled = () => Promise.all(queued).then(() => undefined); - return { maintenance, logWarn, logInfo, settled }; + return { maintenance, logWarn, logInfo, remember, settled }; } beforeEach(() => { vi.useFakeTimers({ toFake: ["Date"] }); collect.mockReset(); - collect.mockResolvedValue({ written: 0, retired: 0, swept: 0 }); + collect.mockResolvedValue({ + written: 0, + retired: 0, + swept: 0, + activity: null, + }); }); afterEach(() => { vi.useRealTimers(); @@ -61,6 +68,19 @@ describe("MaintenanceService.afterPush", () => { 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); 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/tsconfig.json b/packages/plugin/tsconfig.json index db43fff6..d59e384d 100644 --- a/packages/plugin/tsconfig.json +++ b/packages/plugin/tsconfig.json @@ -18,7 +18,7 @@ "noUncheckedIndexedAccess": true, "isolatedModules": true, "allowSyntheticDefaultImports": true, - "lib": ["DOM", "ES2018", "ES2022.Object"] + "lib": ["DOM", "ES2018", "ES2021.Intl", "ES2022.Object"] }, "include": ["src/**/*.ts", "tests/**/*.ts"] } diff --git a/tests/e2e/README.md b/tests/e2e/README.md index 95d8684b..51ad6d83 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -30,6 +30,7 @@ Scenarios run real processes (Obsidian, `wrangler dev`, headless Chrome, in-memo | `pnpm e2e:live-share` | owner and participant type into one note of a share in its room; the cursor carries the invited name, authors tint the other's text, the sync after is clean; presence reaches a device with no note open, the tree and window show who is where, follow cursor jumps and scrolls until the owner's wheel ends 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/`): shapes, concurrent edits and a deletion cross, the pointer shows, file sync of drawings with different zoom settles clean; with live off a saved drawing view takes what the sync writes under it | +| `pnpm e2e:history` | one Obsidian pushes six times to an in-memory S3 with History on and one version pinned, then opens Timeline in the right sidebar: activity calendar and its push count, Pinned and Last hour groups, a session card opened to its files and pushes, the path filter (keeps focus, empty state), a calendar day chip, the Show activity in Timeline setting, What history holds, and the settings root's Activity card (scrolled to today, opens Timeline). Ports 8850, 9250; `E2E_SHOTS=1` saves PNGs under `E2E_SHOTS_DIR` (default `temp/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 change signs of one note on the other, the header's live mark never drops, each note keeps its text | ## Writing a scenario diff --git a/tests/e2e/history.ts b/tests/e2e/history.ts new file mode 100644 index 00000000..c4038bf3 --- /dev/null +++ b/tests/e2e/history.ts @@ -0,0 +1,667 @@ +/** + * The reworked file history in a real Obsidian: pushes from one device on an in-memory S3, one pinned, + * then the Timeline tab (activity calendar, age groups, session cards, filter, day chip) and the setting + * that hides the calendar. + */ + +import { mkdirSync } from "node:fs"; +import { join } from "node:path"; + +import { chromium, type Page } from "playwright-core"; + +import { CLEAN, loaded, openSettings, sync, unlock } from "./device"; +import { check, poll, runScenario, sleep } from "./harness"; +import { launchObsidian, type Obsidian } from "./obsidian"; +import { startS3 } from "./s3"; + +// biome-ignore lint/suspicious/noExplicitAny: the renderer's app is untyped here. +declare const app: any; +declare const activeDocument: Document; + +const CDP_PORT = 9250; +const S3_PORT = 8850; +const PASSPHRASE = "e2e-passphrase"; +const PUSH_GAP_MS = 2500; +const BRIEF = "Projects/Alpha/Brief.md"; +const DAILY = "Daily/2026-10-28.md"; +const DRAFT = "Inbox/Draft.md"; +const ROADMAP = "Roadmap.md"; +const PIN_LABEL = "Release 1.4"; +const SHOTS_DIR = process.env.E2E_SHOTS_DIR ?? "temp/e2e-shots"; +/** Sidebar width the shots are taken at. */ +const SIDEBAR_PX = 400; +const CARD = ".mdsync-timeline-card"; +const FILTER = ".mdsync-timeline-filter input"; + +await runScenario("history e2e", async () => { + const s3 = await startS3(S3_PORT); + let device: Obsidian | undefined; + let browser: Awaited> | undefined; + try { + device = await launchObsidian({ + port: CDP_PORT, + settings: { + storageConfigs: { + s3: { + kind: "s3", + endpoint: s3.url, + region: "auto", + bucket: s3.bucket, + prefix: "vault", + accessKeyId: "e2e", + secretAccessKey: "e2e", + forcePathStyle: true, + concurrency: 4, + }, + }, + activeStorageKind: "s3", + }, + }); + await loaded(device); + await device.evaluate(async () => { + const plugin = app.plugins.plugins.mdsync; + plugin.settings.fileHistoryEnabled = true; + plugin.settings.fileHistoryActivity = true; + await plugin.saveSettings(); + }); + await unlock(device, PASSPHRASE); + check("the first sync is clean", await sync(device), CLEAN); + + browser = await chromium.connectOverCDP(`http://127.0.0.1:${CDP_PORT}`); + const page = await poll("the main window", async () => { + for (const candidate of browser?.contexts().flatMap((c) => c.pages()) ?? + []) { + if ((await candidate.locator(".workspace").count()) > 0) + return candidate; + } + return undefined; + }); + await page.setViewportSize({ width: 1280, height: 860 }); + + await pushes(device); + await pin(device); + await openTimeline(device, page); + await checkOverview(device, page); + await checkExpanded(device, page); + await checkFilter(device, page); + await checkDayChip(device, page); + await checkFileHistory(device, page); + await checkDeleted(device, page); + await checkActivitySetting(device, browser); + await checkHolds(device, browser); + await checkDashboard(device, browser); + } finally { + s3.stop(); + await browser?.close().catch(() => undefined); + await device?.stop(); + } +}); + +/** Six pushes, a few seconds apart: two adds and an edit, a second edit, a file that comes and goes, an edit. */ +async function pushes(device: Obsidian): Promise { + await create(device, BRIEF, "# Alpha brief\n\nv1\n"); + await create(device, DAILY, "# 2026-10-28\n\n- standup\n"); + await create(device, ROADMAP, "# Roadmap\n\n- Q4\n"); + check("push 1: three files added", await pushed(device), CLEAN); + await write(device, BRIEF, "# Alpha brief\n\nv2, scope agreed\n"); + check("push 2: brief edited", await pushed(device), CLEAN); + await write(device, BRIEF, "# Alpha brief\n\nv3, scope agreed\n\nBudget.\n"); + check("push 3: brief edited again", await pushed(device), CLEAN); + await create(device, DRAFT, "draft\n"); + check("push 4: draft added", await pushed(device), CLEAN); + await device.evaluate( + (path) => app.vault.delete(app.vault.getFileByPath(path)), + DRAFT, + ); + check("push 5: draft deleted", await pushed(device), CLEAN); + await write(device, ROADMAP, "# Roadmap\n\n- Q4\n- Q1\n"); + check("push 6: roadmap edited", await pushed(device), CLEAN); +} + +async function pushed( + device: Obsidian, +): Promise>> { + const result = await sync(device); + await sleep(PUSH_GAP_MS); + return result; +} + +function create(device: Obsidian, path: string, text: string): Promise { + return device.evaluate( + async ({ target, content }) => { + const folder = target.split("/").slice(0, -1).join("/"); + if (folder && !app.vault.getFolderByPath(folder)) { + await app.vault.createFolder(folder); + } + await app.vault.create(target, content); + }, + { target: path, content: text }, + ); +} + +function write(device: Obsidian, path: string, text: string): Promise { + return device.evaluate( + ([target, content]) => + app.vault.modify(app.vault.getFileByPath(target), content), + [path, text], + ); +} + +/** Pins the push that made the second edit of the brief: older than the newest ones, so it splits the sessions. */ +async function pin(device: Obsidian): Promise { + const listed = await poll("the pushes in history", async () => { + const rows = await device.evaluate(async () => { + const { snapshots } = + await app.plugins.plugins.mdsync.controller.history.listSnapshots(); + return snapshots.map( + (row: { id: string; pushes: number; pinned: boolean }) => ({ + id: row.id, + pushes: row.pushes, + pinned: row.pinned, + }), + ); + }); + return rows.length >= 4 ? rows : undefined; + }); + console.log(`snapshots, newest first: ${JSON.stringify(listed)}`); + const target = listed[3]; + if (!target) throw new Error("no fourth snapshot to pin"); + await device.evaluate( + ([id, label]) => + app.plugins.plugins.mdsync.controller.history.setSnapshotPinned( + id, + true, + label, + ), + [target.id, PIN_LABEL], + ); + check( + "the pin is listed", + await device.evaluate(async () => { + const { snapshots } = + await app.plugins.plugins.mdsync.controller.history.listSnapshots(); + return snapshots + .filter((row: { pinned: boolean }) => row.pinned) + .map((row: { label?: string }) => row.label); + }), + [PIN_LABEL], + ); +} + +/** The source control view in the right sidebar at `SIDEBAR_PX`, on its Timeline tab with the cards drawn. */ +async function openTimeline(device: Obsidian, page: Page): Promise { + await device.evaluate(() => + app.commands.executeCommandById("mdsync:open-source-control"), + ); + await device.waitFor( + "the source control view", + () => document.querySelector(".mdsync-source-control") !== null, + Boolean, + ); + await device.evaluate((width) => { + const split = app.workspace.rightSplit; + split.expand(); + split.setSize?.(width); + split.containerEl.style.width = `${width}px`; + app.workspace.onResize(); + }, SIDEBAR_PX); + await page.locator('[data-mdsync-tab="timeline"]').click(); + await device.waitFor( + "the timeline cards", + () => document.querySelectorAll(".mdsync-timeline-card").length, + (count: number) => count > 0, + ); + const width = await device.evaluate( + () => + document.querySelector(".mdsync-source-control") + ?.clientWidth ?? 0, + ); + console.log(`source control view is ${width}px wide`); + check("the view is sidebar-sized", width >= 360 && width <= 440, true); +} + +async function checkOverview(device: Obsidian, page: Page): Promise { + const seen = await device.evaluate(() => { + const text = (selector: string) => + [...document.querySelectorAll(selector)].map( + (el) => el.textContent ?? "", + ); + const firstUnpinned = [ + ...document.querySelectorAll(".mdsync-timeline-card"), + ] + .find((card) => !card.querySelector(".mdsync-history-pin")) + ?.querySelector(".mdsync-history-row-title")?.textContent; + return { + activity: document.querySelector(".mdsync-timeline-activity") + ?.textContent, + calendarDays: document.querySelectorAll(".mdsync-calendar-day").length, + groups: text(".mdsync-timeline-day"), + cards: document.querySelectorAll(".mdsync-timeline-card").length, + firstUnpinned, + }; + }); + console.log(`timeline: ${JSON.stringify(seen)}`); + check( + "the activity card counts pushes", + seen.activity?.includes("pushes since"), + true, + ); + check("the calendar draws a year of days", seen.calendarDays >= 300, true); + check( + "a Last hour group", + seen.groups.some((text) => text.toLowerCase().includes("last hour")), + true, + ); + check( + "a Pinned group", + seen.groups.some((text) => text.toLowerCase().startsWith("pinned")), + true, + ); + check("session cards are drawn", seen.cards > 0, true); + check( + "a session title carries its device and span", + seen.firstUnpinned?.includes(" · "), + true, + ); + await shot(page, "1-timeline"); +} + +async function checkExpanded(device: Obsidian, page: Page): Promise { + const index = await device.evaluate(() => + [...document.querySelectorAll(".mdsync-timeline-card")].findIndex( + (card) => !card.querySelector(".mdsync-history-pin"), + ), + ); + const card = page.locator(CARD).nth(index); + await card.locator(".mdsync-timeline-head").first().click(); + await poll("the card's files", async () => + (await card.locator(".mdsync-timeline-file").count()) > 0 + ? true + : undefined, + ); + check( + "an opened session lists its files", + (await card.locator(".mdsync-timeline-file").count()) > 0, + true, + ); + const more = card.locator(".mdsync-timeline-more"); + if ((await more.count()) > 0) { + console.log(`Show all: "${await more.first().textContent()}"`); + await more.first().click(); + await poll("the card's pushes", async () => + (await card.locator(".mdsync-timeline-version").count()) > 0 + ? true + : undefined, + ); + check( + "Show all lists the pushes", + (await card.locator(".mdsync-timeline-version").count()) > 0, + true, + ); + } else console.log("no Show all button on this card"); + await shot(page, "2-expanded"); +} + +async function checkFilter(device: Obsidian, page: Page): Promise { + const before = await page.locator(CARD).count(); + const input = page.locator(FILTER); + await input.click(); + await page.keyboard.type("Brief", { delay: 60 }); + await sleep(400); + check( + "the filter keeps focus while typing", + await filterFocused(device), + true, + ); + await poll("fewer cards", async () => + (await page.locator(CARD).count()) < before ? true : undefined, + ); + const shown = await page.locator(CARD).count(); + console.log(`cards: ${before} unfiltered, ${shown} for Brief`); + check("a filter leaves a card for Brief", shown >= 1, true); + // Opening every card shows the files it kept: all of them must be the filtered path. + for (let index = 0; index < shown; index++) { + const head = page.locator( + `${CARD} >> nth=${index} >> .mdsync-timeline-head`, + ); + const head0 = head.first(); + if ((await head0.getAttribute("aria-expanded")) !== "true") { + await head0.click(); + } + } + await sleep(400); + const files = await device.evaluate(() => + [...document.querySelectorAll(".mdsync-timeline-file")].map( + (el) => el.textContent ?? "", + ), + ); + console.log(`files under Brief: ${JSON.stringify(files)}`); + check("a file row is shown", files.length > 0, true); + check( + "every file row is Brief", + files.every((text) => text.toLowerCase().includes("brief")), + true, + ); + await shot(page, "3-filtered"); + + await input.fill(""); + await input.click(); + await page.keyboard.type("zzz-none", { delay: 60 }); + await sleep(400); + check("the filter keeps focus on a miss", await filterFocused(device), true); + const empty = await device.waitFor( + "the empty state", + () => + document.querySelector(".mdsync-timeline-sessions .mdsync-empty-state") + ?.textContent ?? "", + (text: string) => text !== "", + ); + check( + "a miss says no pushes touch it", + empty.includes("No pushes touch"), + true, + ); + check("a miss draws no card", await page.locator(CARD).count(), 0); +} + +function filterFocused(device: Obsidian): Promise { + return device.evaluate( + () => + document.activeElement?.matches(".mdsync-timeline-filter input") ?? false, + ); +} + +async function checkDayChip(device: Obsidian, page: Page): Promise { + await page.locator(FILTER).fill(""); + await poll("the cards back", async () => + (await page.locator(CARD).count()) > 0 ? true : undefined, + ); + check("clearing the filter brings the cards back", true, true); + const today = page.locator(".mdsync-calendar-day").last(); + await today.scrollIntoViewIfNeeded(); + await today.click(); + await poll("the day chip", async () => + (await page.locator(".mdsync-timeline-day-chip").count()) > 0 + ? true + : undefined, + ); + check( + "picking today shows a day chip", + await device.evaluate( + () => + document.querySelector(".mdsync-timeline-day-chip")?.textContent !== + undefined, + ), + true, + ); + console.log( + `day chip: ${await page.locator(".mdsync-timeline-day-chip").textContent()}, cards: ${await page.locator(CARD).count()}`, + ); + await shot(page, "4-day"); +} + +/** Brief.md on the History tab: its pinned version apart, the rest by age, the footer on what thins. */ +async function checkFileHistory(device: Obsidian, page: Page): Promise { + await device.evaluate(async () => { + const file = app.vault.getAbstractFileByPath("Projects/Alpha/Brief.md"); + await app.workspace.getLeaf(false).openFile(file); + }); + await page.locator('[data-mdsync-tab="history"]').click(); + await device.waitFor( + "the history rows", + () => document.querySelectorAll(".mdsync-history-row").length, + (count: number) => count > 0, + ); + const seen = await device.evaluate(() => { + const text = (selector: string) => + [...document.querySelectorAll(selector)].map( + (each) => each.textContent ?? "", + ); + return { + headers: text(".mdsync-history-pane .mdsync-timeline-day"), + meta: text(".mdsync-history-row .mdsync-history-row-meta"), + footer: text(".mdsync-history-footer").join(""), + tooltips: [...document.querySelectorAll(".mdsync-history-row")].map( + (row) => row.getAttribute("aria-label") ?? "", + ), + }; + }); + console.log(`history: ${JSON.stringify(seen)}`); + check( + "the pinned version leads", + seen.headers[0]?.toLowerCase().startsWith("pinned"), + true, + ); + check( + "the rest sit in the last hour", + seen.headers.some((header) => header.toLowerCase().includes("last hour")), + true, + ); + check( + "the oldest says it created the file", + seen.meta.some((meta) => meta.endsWith("first version")), + true, + ); + check( + "a tooltip carries the whole meta", + seen.tooltips.some((tooltip) => tooltip.endsWith("first version")), + true, + ); + check( + "the footer says what thins", + seen.footer.includes("only pinned versions and activity counts remain"), + true, + ); + await shot(page, "6-history"); +} + +/** Draft.md on the Deleted tab: how long history keeps it, and the path filter. */ +async function checkDeleted(device: Obsidian, page: Page): Promise { + await page.locator('[data-mdsync-tab="deleted"]').click(); + await device.waitFor( + "the deleted rows", + () => document.querySelectorAll(".mdsync-deleted-row").length, + (count: number) => count > 0, + ); + const seen = await device.evaluate(() => ({ + kept: document.querySelector(".mdsync-deleted-kept")?.textContent ?? "", + notes: [...document.querySelectorAll(".mdsync-deleted-note")].map( + (each) => each.textContent ?? "", + ), + })); + console.log(`deleted: ${JSON.stringify(seen)}`); + check("the head says how long", seen.kept, "Kept 3 months after deletion"); + check( + "the draft says until when", + seen.notes.some((note) => note.startsWith("Kept until")), + true, + ); + await shot(page, "7-deleted"); + const copyWidth = () => + device.evaluate( + () => document.querySelector(".mdsync-deleted-copy")?.clientWidth, + ); + const still = await copyWidth(); + await page.locator(".mdsync-deleted-row").first().hover(); + check("hovering a row reflows nothing", await copyWidth(), still); + check( + "hovering a row shows its actions", + await page.locator(".mdsync-deleted-row .mdsync-row-actions").isVisible(), + true, + ); + await shot(page, "7-deleted-hover"); + const input = page.locator( + ".mdsync-deleted-panel .mdsync-timeline-filter input", + ); + await input.click(); + await page.keyboard.type("zzz-none", { delay: 60 }); + await device.waitFor( + "the no-match state", + () => + document.querySelector(".mdsync-deleted-list .mdsync-empty-state") + ?.textContent ?? "", + (text: string) => text.includes("No deleted files match"), + ); + check( + "the filter keeps focus on a miss", + await device.evaluate( + () => + document.activeElement?.matches(".mdsync-deleted-panel input") ?? false, + ), + true, + ); + await input.fill("draft"); + await device.waitFor( + "the draft alone", + () => document.querySelectorAll(".mdsync-deleted-row").length, + (count: number) => count === 1, + ); +} + +/** The plugin's Sync page, scrolled to the toggle that hides the calendar. */ +async function checkActivitySetting( + device: Obsidian, + browser: NonNullable>>, +): Promise { + await openSettings(device, "Sync"); + const row = await device.evaluate(() => { + const found = [ + ...activeDocument.querySelectorAll( + ".mod-settings .setting-item", + ), + ].find( + (each) => + each.querySelector(".setting-item-name")?.textContent === + "Show activity in Timeline", + ); + if (!found) return null; + found.scrollIntoView({ block: "center" }); + const box = found.getBoundingClientRect(); + const height = activeDocument.defaultView?.innerHeight ?? 0; + return { + shown: found.checkVisibility(), + inView: box.top >= 0 && box.bottom <= height, + on: found.querySelector(".checkbox-container.is-enabled") !== null, + }; + }); + console.log(`Show activity in Timeline: ${JSON.stringify(row)}`); + check("the activity toggle is in the Sync page", row !== null, true); + check("the activity toggle is visible", row?.shown && row.inView, true); + check("the activity toggle is on", row?.on, true); + const page = await poll("the settings window", async () => { + for (const candidate of browser.contexts().flatMap((c) => c.pages())) { + if ((await candidate.locator(".mod-settings").count()) > 0) + return candidate; + } + return undefined; + }); + await shot(page, "5-activity-setting"); +} + +/** **What history holds** under **Keep history for**; a day opens the Timeline on it. */ +async function checkHolds( + device: Obsidian, + browser: NonNullable>>, +): Promise { + const ladder = await device.waitFor( + "the holds calendar", + () => { + const row = activeDocument.querySelector(".mdsync-holds"); + if (!row?.querySelector(".mdsync-calendar-day")) return null; + row.scrollIntoView({ block: "center" }); + return [...row.querySelectorAll(".mdsync-holds-step")].map((step) => + [...step.children].map((part) => part.textContent).join(""), + ); + }, + (steps: string[] | null) => steps !== null, + ); + console.log(`ladder: ${JSON.stringify(ladder)}`); + check("the ladder starts at every push", ladder?.[0], "Every pushLast hour"); + check( + "the ladder ends at activity only", + ladder?.at(-1), + "Activity onlyOlder", + ); + for (const candidate of browser.contexts().flatMap((c) => c.pages())) { + if ((await candidate.locator(".mdsync-holds").count()) === 0) continue; + await shot(candidate, "8-holds"); + await candidate + .locator(".mdsync-holds .mdsync-calendar-day") + .last() + .click(); + } + const chip = await device.waitFor( + "the Timeline on the picked day", + () => document.querySelector(".mdsync-timeline-day-chip")?.textContent, + (text: string | undefined) => Boolean(text), + ); + check("a day opens the Timeline on it", Boolean(chip), true); + check( + "the settings close", + await device.evaluate(() => !document.querySelector(".mod-settings")), + true, + ); +} + +/** The root page draws the activity the Timeline already read, then opens the Timeline. */ +async function checkDashboard( + device: Obsidian, + browser: NonNullable>>, +): Promise { + await openSettings(device); + const head = await device.waitFor( + "the dashboard activity", + () => { + const card = activeDocument.querySelector(".mdsync-overview-activity"); + if (!card?.querySelector(".mdsync-calendar-day")) return null; + return { + text: + card.querySelector(".mdsync-overview-card-lines")?.textContent ?? "", + bands: card.querySelector(".mdsync-calendar-bands") !== null, + today: (() => { + const scroller = card.querySelector( + ".mdsync-calendar", + ) as HTMLElement; + return ( + scroller.scrollLeft + scroller.clientWidth >= + scroller.scrollWidth - 1 + ); + })(), + }; + }, + (found: { text: string; bands: boolean; today: boolean } | null) => + found?.today === true, + ); + console.log(`dashboard: ${JSON.stringify(head)}`); + check("the dashboard counts pushes", /\d+ push/.test(head?.text ?? ""), true); + check("the dashboard names no resolutions", head?.bands, false); + for (const candidate of browser.contexts().flatMap((c) => c.pages())) { + if ((await candidate.locator(".mdsync-overview-activity").count()) === 0) + continue; + await shot(candidate, "9-dashboard"); + await candidate + .locator(".mdsync-overview-activity button", { hasText: "Open timeline" }) + .click(); + } + const shown = await device.waitFor( + "the Timeline from the dashboard", + () => + !document.querySelector(".mod-settings") && + document + .querySelector('[data-mdsync-tab="timeline"]') + ?.getAttribute("aria-selected") === "true", + (open: boolean) => open, + ); + check("Open timeline shows the Timeline", shown, true); +} + +async function shot(page: Page, name: string): Promise { + if (!process.env.E2E_SHOTS) return; + mkdirSync(SHOTS_DIR, { recursive: true }); + const path = join(SHOTS_DIR, `${name}.png`); + await page.screenshot({ + path, + style: ".notice-container { display: none; }", + }); + console.log(`shot ${path}`); +} From 24c581af6e1ac582ca6ccad48e9e18646b5b5868 Mon Sep 17 00:00:00 2001 From: kitbyte Date: Wed, 28 Oct 2026 18:03:24 +0200 Subject: [PATCH 07/26] perf(history): cached pins, parallel GC, paged lists --- .claude/rules/history.md | 6 +- .../features/settings/sections/automation.ts | 16 +- packages/plugin/src/features/settings/tab.ts | 31 +- .../source-control/history/age-groups.ts | 6 +- .../source-control/history/history-tab.ts | 12 +- .../source-control/history/row-pager.ts | 15 +- .../source-control/timeline/timeline-rows.ts | 24 +- .../source-control/timeline/timeline-tab.ts | 73 +++- .../source-control/trash/trash-tab.ts | 46 ++- packages/plugin/src/features/sync/README.md | 2 +- .../plugin/src/features/sync/history/gc.ts | 19 +- .../src/features/sync/history/model/plan.ts | 34 +- .../plugin/src/features/sync/history/pins.ts | 88 ++++- .../src/features/sync/history/publish.ts | 8 + .../plugin/src/features/sync/history/query.ts | 81 ++-- .../src/features/sync/history/remote.ts | 40 +- .../src/features/sync/history/replay.ts | 6 +- .../plugin/src/features/sync/history/sweep.ts | 47 ++- .../features/sync/runtime/history-service.ts | 29 +- .../src/features/sync/ui/history/holds-row.ts | 2 + .../tests/features/settings/tab.test.ts | 56 +++ .../history/history-tab.test.ts | 161 ++++++++ .../timeline/timeline-rows.test.ts | 69 +++- .../timeline/timeline-tab.test.ts | 350 ++++++++++++++++++ .../tests/features/sync/history/gc.test.ts | 21 +- .../sync/history/history-deleted.test.ts | 70 ++++ .../tests/features/sync/history/pins.test.ts | 172 ++++++++- .../features/sync/history/publish.test.ts | 50 +++ .../tests/features/sync/history/sweep.test.ts | 85 +++++ .../sync/runtime/history-service.test.ts | 106 ++++++ packages/plugin/tests/stubs/obsidian.ts | 4 +- 31 files changed, 1583 insertions(+), 146 deletions(-) create mode 100644 packages/plugin/tests/features/settings/tab.test.ts create mode 100644 packages/plugin/tests/features/source-control/history/history-tab.test.ts create mode 100644 packages/plugin/tests/features/source-control/timeline/timeline-tab.test.ts create mode 100644 packages/plugin/tests/features/sync/history/sweep.test.ts create mode 100644 packages/plugin/tests/features/sync/runtime/history-service.test.ts diff --git a/.claude/rules/history.md b/.claude/rules/history.md index c9fa62e1..7f64a47f 100644 --- a/.claude/rules/history.md +++ b/.claude/rules/history.md @@ -15,7 +15,7 @@ History is one encrypted record per push under `history/`, which GC thins into o ## 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 key and vault and while every blob it names exists (`stillLands`): 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. +- 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 key and vault and while every blob it names exists (`stillLands`; past a thousand blobs, checked against one listing of `objects/`): 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. - 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. @@ -45,7 +45,7 @@ History is one encrypted record per push under `history/`, which GC thins into o - A pin is one object, `pins/.json.enc` (`features/sync/history/pins.ts`): `{ v: 1, manifest, label?, pinnedAt }` with the snapshot's full manifest, 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`). -- A listed pin that does not read (corrupt, or a 1.x bare manifest) is `unreadable` in `readPins`: what it holds is unknown. Decoded pins are cached only by etag: a timestamp may not move on a rewrite. +- A listed pin that does not read (corrupt, or a 1.x bare manifest) is `unreadable` in `readPins`: what it holds is unknown. 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 @@ -55,7 +55,7 @@ History is one encrypted record per push under `history/`, which GC thins into o - 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. `readHistory` lists `history/g/` in its one call. +- 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/` 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/`, `pins/` and `history/` of its own space. diff --git a/packages/plugin/src/features/settings/sections/automation.ts b/packages/plugin/src/features/settings/sections/automation.ts index ca009738..5f86ec24 100644 --- a/packages/plugin/src/features/settings/sections/automation.ts +++ b/packages/plugin/src/features/settings/sections/automation.ts @@ -28,7 +28,11 @@ import { import type { LiveSessions } from "@/features/live"; import type { People } from "@/features/presence"; import type { HubConnection } from "@/features/relay"; -import { renderHistoryHolds, VAULT_SPACE } from "@/features/sync"; +import { + renderHistoryHolds, + type SnapshotListResult, + VAULT_SPACE, +} from "@/features/sync"; import type { SettingsTabHost } from "../host"; /** The wizard shows these too, so they ask only what its host has. */ @@ -225,12 +229,13 @@ const AUTOMATION_FIELDS: ReadonlyArray> = [ export function automationSection( ctx: FieldContext, + loadHistory: () => Promise, ): SettingDefinitionGroup { const rows = AUTOMATION_FIELDS.map((field) => fieldRow(ctx, field)); const keep = AUTOMATION_FIELDS.indexOf(KEEP_HISTORY_FIELD) + 1; return group("Automation", [ ...rows.slice(0, keep), - historyHoldsRow(ctx.plugin), + historyHoldsRow(ctx.plugin, loadHistory), ...rows.slice(keep), { name: "Connected devices", @@ -240,7 +245,10 @@ export function automationSection( ]); } -function historyHoldsRow(plugin: SettingsTabHost): SettingsRow { +function historyHoldsRow( + plugin: SettingsTabHost, + 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.", @@ -248,7 +256,7 @@ function historyHoldsRow(plugin: SettingsTabHost): SettingsRow { render: (setting) => { setting.settingEl.addClass(SUB_SETTING_CLASS); renderHistoryHolds(setting, { - load: () => plugin.controller.history.listSnapshots(), + load: loadHistory, horizon: HISTORY_KEEP_MS[plugin.settings.fileHistoryKeep], onPick: (day) => { closePluginSettings(plugin.app); diff --git a/packages/plugin/src/features/settings/tab.ts b/packages/plugin/src/features/settings/tab.ts index c0717412..637c6d94 100644 --- a/packages/plugin/src/features/settings/tab.ts +++ b/packages/plugin/src/features/settings/tab.ts @@ -8,12 +8,17 @@ import { type FieldContext, settleTyping } from "@/core/settings"; import { linksSection } from "@/features/links"; import { relaySection } from "@/features/relay"; import { sharesSection } from "@/features/spaces"; -import { backendSection } from "@/features/storage"; +import { + activeStorage, + backendSection, + storageIdentity, +} from "@/features/storage"; import { configurationScopeSection, encryptionSection, exclusionsSection, maintenanceSection, + type SnapshotListResult, } from "@/features/sync"; import { deviceTransferSection } from "@/features/transfer"; import type { SettingsTabHost } from "./host"; @@ -25,6 +30,12 @@ import { interfaceSection } from "./sections/interface"; 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); @@ -33,9 +44,25 @@ export class MdsyncSettingTab extends PluginSettingTab { 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, @@ -71,7 +98,7 @@ export class MdsyncSettingTab extends PluginSettingTab { return open ? `${open} shared` : ""; }, items: [ - automationSection(ctx), + automationSection(ctx, () => this.loadHistory()), sharesSection(ctx), linksSection(ctx), configurationScopeSection(ctx), diff --git a/packages/plugin/src/features/source-control/history/age-groups.ts b/packages/plugin/src/features/source-control/history/age-groups.ts index a702c177..530b9b7e 100644 --- a/packages/plugin/src/features/source-control/history/age-groups.ts +++ b/packages/plugin/src/features/source-control/history/age-groups.ts @@ -73,10 +73,14 @@ export function ageLabel( day: "numeric", }).formatRange(monday, sunday); } - if ((res ?? "push") === "push" && now - at < HOUR_MS) return "Last hour"; + 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, diff --git a/packages/plugin/src/features/source-control/history/history-tab.ts b/packages/plugin/src/features/source-control/history/history-tab.ts index 4eb379b5..9293faa0 100644 --- a/packages/plugin/src/features/source-control/history/history-tab.ts +++ b/packages/plugin/src/features/source-control/history/history-tab.ts @@ -25,6 +25,7 @@ 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; @@ -34,6 +35,7 @@ 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: SourceControlHost, @@ -62,6 +64,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 { @@ -137,11 +141,17 @@ export class HistoryTab { const rows = buildHistoryRows(versions, { currentDevice: this.plugin.controller.currentDevice(), }); - for (const group of groupByAge(rows)) { + // Pinned lead, as groupByAge orders them, so a page break never splits the pinned group. + const ordered = [ + ...rows.filter((row) => row.pinned), + ...rows.filter((row) => !row.pinned), + ]; + for (const group of groupByAge(this.pager.slice(ordered))) { 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); } diff --git a/packages/plugin/src/features/source-control/history/row-pager.ts b/packages/plugin/src/features/source-control/history/row-pager.ts index 6e79ab93..0271c891 100644 --- a/packages/plugin/src/features/source-control/history/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/timeline/timeline-rows.ts b/packages/plugin/src/features/source-control/timeline/timeline-rows.ts index 266cda6d..8065ec2e 100644 --- a/packages/plugin/src/features/source-control/timeline/timeline-rows.ts +++ b/packages/plugin/src/features/source-control/timeline/timeline-rows.ts @@ -83,7 +83,7 @@ export function summaryOf(changes: SnapshotChanges | null): ChangeSummary { return { counts: null, tally: null, netDelta: null, fileCount: null }; const tally = tallyOf(changes); return { - counts: countsText(changes), + counts: tallyText(tally), tally, netDelta: netBytes(changes) || null, fileCount: tally.reduce((sum, [, count]) => sum + count, 0), @@ -109,8 +109,9 @@ function buildFileRows( at: number, ): TimelineFileRow[] { const rows: TimelineFileRow[] = []; + const stamp = formatTimestamp(at); for (const [path, entry] of Object.entries(changes.added)) { - const after = versionRef(entry, at, "after push"); + const after = versionRef(entry, stamp, "after push"); rows.push({ path, action: "add", @@ -121,8 +122,8 @@ function buildFileRows( }); } for (const [path, change] of Object.entries(changes.modified)) { - const before = versionRef(change.from, at, "before push"); - const after = versionRef(change.to, at, "after push"); + const before = versionRef(change.from, stamp, "before push"); + const after = versionRef(change.to, stamp, "after push"); rows.push({ path, action: "modify", @@ -140,7 +141,7 @@ function buildFileRows( Object.hasOwn(changes.deletedLast, path) && changes.deletedLast[path]) || entry; - const before = versionRef(last, at, "before push"); + const before = versionRef(last, stamp, "before push"); rows.push({ path, action: "delete", @@ -165,13 +166,13 @@ function netBytes(changes: SnapshotChanges): number { function versionRef( entry: ManifestEntry, - at: number, + stamp: string, suffix: string, ): HistoryVersionRef { return { hash: entry.hash, size: entry.size, - label: `${formatTimestamp(at)} (${suffix})`, + label: `${stamp} (${suffix})`, }; } @@ -186,10 +187,11 @@ function tallyOf(changes: SnapshotChanges): Array<[ChangeAction, number]> { /** "+3 new · 2 changed · 1 removed", dropping the parts that are zero. */ export function countsText(changes: SnapshotChanges | null): string | null { - if (!changes) return null; - const parts = tallyOf(changes).map(([action, count]) => - COUNT_WORDS[action](count), - ); + 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"; } diff --git a/packages/plugin/src/features/source-control/timeline/timeline-tab.ts b/packages/plugin/src/features/source-control/timeline/timeline-tab.ts index dfcdcac6..03221a3a 100644 --- a/packages/plugin/src/features/source-control/timeline/timeline-tab.ts +++ b/packages/plugin/src/features/source-control/timeline/timeline-tab.ts @@ -15,7 +15,7 @@ import { renderActivityCalendar, type SnapshotListResult, } from "@/features/sync"; -import { ageTitle, groupByAge } from "../history/age-groups"; +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"; @@ -40,7 +40,20 @@ export class TimelineTab { 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; 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; @@ -157,9 +170,7 @@ export class TimelineTab { "History has not caught up with the latest push yet, so the newest version is missing.", ); } - const rows = buildSessionRows(result.snapshots, { - currentDevice: this.plugin.controller.currentDevice(), - }); + const rows = this.sessionRows(result); if (rows.length === 0 && !result.lagging) { renderEmptyState(body, { icon: "clock-3", @@ -187,6 +198,28 @@ export class TimelineTab { this.redrawSessions(); } + 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" }); @@ -249,11 +282,12 @@ export class TimelineTab { 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 query = this.query.trim().toLowerCase(); const dayEnd = picked && new Date(picked.start); dayEnd?.setDate(dayEnd.getDate() + 1); const shown = rows.filter( @@ -273,10 +307,20 @@ export class TimelineTab { }); } const ctx = this.cardContext(query); - for (const group of groupByAge(shown)) { + // 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, @@ -286,6 +330,23 @@ export class TimelineTab { ); } + 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, diff --git a/packages/plugin/src/features/source-control/trash/trash-tab.ts b/packages/plugin/src/features/source-control/trash/trash-tab.ts index 6340def3..b6219b9d 100644 --- a/packages/plugin/src/features/source-control/trash/trash-tab.ts +++ b/packages/plugin/src/features/source-control/trash/trash-tab.ts @@ -430,28 +430,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/features/sync/README.md b/packages/plugin/src/features/sync/README.md index a041a79a..6a765324 100644 --- a/packages/plugin/src/features/sync/README.md +++ b/packages/plugin/src/features/sync/README.md @@ -78,7 +78,7 @@ A hunk index means nothing without its two texts. The diff view, the gutter mark ## 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`). 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 a day later. 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 push writes one encrypted record, `history/p/.enc`, before it publishes: the diff from that snapshot's parent (`added`, `modified {from, to}`, `deleted`). 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. diff --git a/packages/plugin/src/features/sync/history/gc.ts b/packages/plugin/src/features/sync/history/gc.ts index c261a476..7e8cd05a 100644 --- a/packages/plugin/src/features/sync/history/gc.ts +++ b/packages/plugin/src/features/sync/history/gc.ts @@ -1,7 +1,7 @@ import { DEFAULT_CONCURRENCY } from "@/core/constants"; import type { EncryptionKey } from "@/core/crypto"; import { runWithConcurrency } from "@/core/utils"; -import type { ObjectStorage } from "@/features/storage"; +import type { ListedObject, ObjectStorage } from "@/features/storage"; import { fetchRemoteManifest } from "../remote/manifest"; import { SETTLED_AFTER_MS } from "../remote/uploads"; import type { Manifest } from "../types"; @@ -15,7 +15,7 @@ import { writeCandidates, writeHistoryObject, } from "./remote"; -import { isSettled, sweepObjects } from "./sweep"; +import { sweepObjects } from "./sweep"; import type { HistoryConfig, SnapshotChanges } from "./types"; export interface GcResult { @@ -45,12 +45,20 @@ export async function collectHistoryGarbage( 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(isSettled) + 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, @@ -82,12 +90,13 @@ async function thinHistory( const retire = new Set(plan.deletes); const written = new Set(); const kept: { changes: SnapshotChanges }[] = []; - for (const build of plan.builds) { + // 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) => diff --git a/packages/plugin/src/features/sync/history/model/plan.ts b/packages/plugin/src/features/sync/history/model/plan.ts index c6c2e7e1..cc2111b7 100644 --- a/packages/plugin/src/features/sync/history/model/plan.ts +++ b/packages/plugin/src/features/sync/history/model/plan.ts @@ -41,6 +41,11 @@ interface Target { 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()]); @@ -52,9 +57,10 @@ export function planGc(input: PlanInput): GcPlan { for (const key of expired(input)) deletes.add(key); const whole = wholeKeys(input); + const grouped = objectsByGroup(input); const builds: Build[] = []; for (const target of targets(input)) { - const build = buildOf(input, target, whole); + const build = buildOf(input, target, whole, grouped); if (build) builds.push(build); } return { builds, deletes: [...deletes] }; @@ -121,22 +127,34 @@ function oldestReached(cover: Cover): number { 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, whole: (key: string) => boolean, + grouped: ReadonlyMap, ): Build | null { const { res, group } = target; - const rank = RESOLUTIONS.indexOf(res); const walked = new Set(target.walked.map(({ source }) => source)); const inputs = new Set(walked); const sameGroup: HistoryObject[] = []; - for (const [key, { object }] of input.view.objects) { - if (input.cover.consumed.has(key) || object.vaultId !== input.vaultId) { - continue; - } - const objectRank = RESOLUTIONS.indexOf(object.res); - if (objectRank > rank || groupStart(res, object.group) !== group) continue; + for (const { key, object } of grouped.get(`${res} ${group}`) ?? []) { inputs.add(key); if (object.res === res) sameGroup.push(object); } diff --git a/packages/plugin/src/features/sync/history/pins.ts b/packages/plugin/src/features/sync/history/pins.ts index 0815d52e..6ae756f7 100644 --- a/packages/plugin/src/features/sync/history/pins.ts +++ b/packages/plugin/src/features/sync/history/pins.ts @@ -38,16 +38,25 @@ export interface PinsRead { unreadable: string[]; } -/** Manifests are big, so only a few stay. */ -const PIN_CACHE_SIZE = 4; +/** 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; + pins: Map; + infos: Map; } >(); @@ -82,23 +91,64 @@ export function deletePin( } /** Every listed pin, reduced by `pick` as it is read so no more than the cache's manifests are held at once. */ -export async function readPins( +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) => T, + 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() }; + cache = { key, root, pins: new Map(), infos: new Map() }; pinCache.set(storage, cache); } - const { pins } = cache; + const { pins, infos } = cache; const listed = await listPins(storage); + 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 = etag !== null && hit?.etag === etag ? hit.pin : null; if (!pin) { @@ -107,14 +157,16 @@ export async function readPins( unreadable.push(object.key); return; } - if (etag !== null) remember(pins, object.key, { etag, pin }); + 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; - read.push({ - info: { id, label, createdAt, deviceId, deviceName }, - picked: pick(pin), - }); + 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 }; @@ -164,14 +216,18 @@ async function readPin( } function remember( - pins: Map, + pins: Map, storageKey: string, - entry: { etag: string; pin: Pin }, + entry: CachedPin, ): void { pins.delete(storageKey); pins.set(storageKey, entry); - for (const oldest of pins.keys()) { - if (pins.size <= PIN_CACHE_SIZE) break; + let held = 0; + for (const { entries } of pins.values()) held += entries; + // The pin just read is last, so it stays even when it alone is over the bound. + for (const [oldest, { entries }] of pins) { + if (held <= PIN_CACHE_ENTRIES || pins.size === 1) break; pins.delete(oldest); + held -= entries; } } diff --git a/packages/plugin/src/features/sync/history/publish.ts b/packages/plugin/src/features/sync/history/publish.ts index a9a69d27..cc6f2ac9 100644 --- a/packages/plugin/src/features/sync/history/publish.ts +++ b/packages/plugin/src/features/sync/history/publish.ts @@ -3,6 +3,7 @@ import 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 } from "../constants"; import { objectKey, publishManifestWithGuard } from "../remote/manifest"; import type { Manifest } from "../types"; import { changeEntries, diffManifests } from "./changes"; @@ -21,6 +22,9 @@ interface Unwritten { // 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. @@ -96,6 +100,10 @@ async function stillLands( own: Unwritten, ): Promise { if (record.key !== own.key || record.vaultId !== own.vaultId) return false; + if (record.hashes.length > PROBE_LIMIT) { + const stored = new Set(await storage.list(REMOTE_OBJECTS_PREFIX)); + return record.hashes.every((hash) => stored.has(objectKey(hash))); + } let missing = false; await runWithConcurrency(record.hashes, DEFAULT_CONCURRENCY, async (hash) => { if (!(await storage.exists(objectKey(hash)))) missing = true; diff --git a/packages/plugin/src/features/sync/history/query.ts b/packages/plugin/src/features/sync/history/query.ts index 513f0c92..a7cc6821 100644 --- a/packages/plugin/src/features/sync/history/query.ts +++ b/packages/plugin/src/features/sync/history/query.ts @@ -17,6 +17,7 @@ import { deletePin, type PinInfo, readPinById, + readPinInfos, readPins, writePin, } from "./pins"; @@ -180,17 +181,17 @@ async function applyPins( head: Manifest, found: Map, ): Promise { - const { pins } = await readPins( - source.storage, - source.key, - source.root, - (pin) => - Object.entries(pin.manifest.files).filter( - ([path]) => !entryAt(head.files, path), - ), - ); - for (const { info, picked } of pins) { - for (const [path, entry] of picked) { + // 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) { @@ -199,19 +200,29 @@ async function applyPins( } continue; } - 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, - }); + // 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, + }); } } @@ -222,13 +233,8 @@ export async function listSnapshots( const { head, cover, view } = await readTimeline(query); if (!head) return { snapshots: [], lagging: false, truncated: false, activity: {} }; - const { pins } = await readPins( - query.storage, - query.key, - query.root, - () => null, - ); - const pinned = new Map(pins.map(({ info }) => [info.id, info])); + 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, @@ -259,7 +265,7 @@ export async function listSnapshots( ), ); const onChain = new Set(snapshots.map((snapshot) => snapshot.id)); - for (const { info } of pins) { + for (const info of pins) { if (!onChain.has(info.id)) snapshots.push(summary(info, undated(info), null, null)); } @@ -276,8 +282,7 @@ export async function resolveSnapshotManifest( source: Source, snapshotId: string, ): Promise { - const { head, cover } = await readTimeline(source); - const replayed = head ? replayTo(head, cover, snapshotId) : null; + const replayed = await replaySnapshot(source, snapshotId); if (replayed) return replayed; const pin = await readPinById( source.storage, @@ -288,6 +293,14 @@ export async function resolveSnapshotManifest( 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 whole manifest; a readable pin keeps its manifest and takes the new label. * `label` undefined keeps the pin's name, "" clears it. @@ -305,7 +318,7 @@ export async function setSnapshotPinned( } const existing = await readPinById(storage, key, root, snapshotId); const manifest = - existing?.manifest ?? (await resolveSnapshotManifest(source, snapshotId)); + existing?.manifest ?? (await replaySnapshot(source, snapshotId)); if (!manifest) { throw new Error( "That snapshot can no longer be rebuilt from history, so it cannot be pinned.", diff --git a/packages/plugin/src/features/sync/history/remote.ts b/packages/plugin/src/features/sync/history/remote.ts index 059cb3c6..e38e84ae 100644 --- a/packages/plugin/src/features/sync/history/remote.ts +++ b/packages/plugin/src/features/sync/history/remote.ts @@ -42,6 +42,19 @@ const caches = new WeakMap< { 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`; } @@ -84,11 +97,15 @@ export async function writeHistoryObject( ); const blob = await storage.get(storageKey); const read = blob && (await decryptJson(key, blob)); - if (!read || (await objectKeyOf(read)) !== storageKey) { + // 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 }; } @@ -140,12 +157,7 @@ export async function readHistory( key: EncryptionKey, root: string, ): Promise { - let cache = caches.get(storage); - if (cache?.key !== key || cache.root !== root) { - cache = { key, root, entries: new Map() }; - caches.set(storage, cache); - } - const { entries } = cache; + const entries = cacheOf(storage, key, root); let all = await listHistory(storage); let listed = all.filter(isRecordOrObject); let read = await decodeNew(storage, key, root, listed, entries); @@ -238,7 +250,19 @@ async function decode( storageKey: string, blob: Uint8Array, ): Promise { - const raw = await decryptJson>(key, blob); + 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; diff --git a/packages/plugin/src/features/sync/history/replay.ts b/packages/plugin/src/features/sync/history/replay.ts index 2c35ecd3..e8386907 100644 --- a/packages/plugin/src/features/sync/history/replay.ts +++ b/packages/plugin/src/features/sync/history/replay.ts @@ -11,7 +11,11 @@ export function replayTo( cover: Cover, snapshotId: string, ): Manifest | null { - if (cover.lagging) return 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) { diff --git a/packages/plugin/src/features/sync/history/sweep.ts b/packages/plugin/src/features/sync/history/sweep.ts index f101e683..33280ab5 100644 --- a/packages/plugin/src/features/sync/history/sweep.ts +++ b/packages/plugin/src/features/sync/history/sweep.ts @@ -109,6 +109,25 @@ export async function sweepObjects( ); } + // 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 + ? new Set( + [...(await readCandidates(storage, key, due)).hashes].map(objectKey), + ) + : null; + const kept = new Set([...reachable.hashes.keys()].map(objectKey)); + // Nothing but candidate files goes then, so the listing, young files and rechecks guard nothing. + if (freed && [...freed].every((storageKey) => kept.has(storageKey))) { + await deleteFiles(storage, due); + return 0; + } + const objectKeys = await settledKeys(storage, REMOTE_OBJECTS_PREFIX); // Another device publishing during the listing makes its new objects look like orphans: bail. @@ -135,26 +154,13 @@ export async function sweepObjects( ); } - const due = reachable.candidates.filter(isSettled); - const held = await readCandidates( - storage, - key, - reachable.candidates.filter((file) => !isSettled(file)), - ); + 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.", ); } - // An unreadable settled file only leaks its blobs to the next deep clean. - const freed = options.freedOnly - ? new Set( - [...(await readCandidates(storage, key, due)).hashes].map(objectKey), - ) - : null; - const kept = new Set( - [...reachable.hashes.keys(), ...held.hashes].map(objectKey), - ); + for (const hash of held.hashes) kept.add(objectKey(hash)); const orphans = objectKeys.filter( (storageKey) => !kept.has(storageKey) && (freed === null || freed.has(storageKey)), @@ -168,10 +174,17 @@ export async function sweepObjects( options.onProgress?.(++done, orphans.length); }, ); - await runWithConcurrency(due, DEFAULT_CONCURRENCY, (file) => + await deleteFiles(storage, due); + return orphans.length; +} + +function deleteFiles( + storage: ObjectStorage, + files: readonly ListedObject[], +): Promise { + return runWithConcurrency(files, DEFAULT_CONCURRENCY, (file) => storage.delete(file.key), ); - return orphans.length; } function historyKeys(read: HistoryRead): string[] { diff --git a/packages/plugin/src/features/sync/runtime/history-service.ts b/packages/plugin/src/features/sync/runtime/history-service.ts index 6e15693a..14461da6 100644 --- a/packages/plugin/src/features/sync/runtime/history-service.ts +++ b/packages/plugin/src/features/sync/runtime/history-service.ts @@ -192,13 +192,36 @@ export class HistoryService { async restoreFileVersion(path: string, hash: string): 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); 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; + }); + } + + /** The session is the path's own: a batch may span spaces. */ + private async writeVersion(path: string, hash: string): Promise { + const session = await this.requireSession(path); + const bytes = await loadVersionBytes(session.storage, session.key, hash); + await writeLocalFile(session, path, bytes); + } + async restoreHistoryHunks( path: string, hash: string, diff --git a/packages/plugin/src/features/sync/ui/history/holds-row.ts b/packages/plugin/src/features/sync/ui/history/holds-row.ts index 97aa7aa5..772b3e00 100644 --- a/packages/plugin/src/features/sync/ui/history/holds-row.ts +++ b/packages/plugin/src/features/sync/ui/history/holds-row.ts @@ -46,6 +46,8 @@ export function renderHistoryHolds( } load().then( (result) => { + // Settings may have redrawn or closed meanwhile. + if (!calendar.isConnected) return; calendar.empty(); renderActivityCalendar( calendar, 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/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..7d504471 --- /dev/null +++ b/packages/plugin/tests/features/source-control/history/history-tab.test.ts @@ -0,0 +1,161 @@ +// @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"; + +vi.mock("obsidian", async (importOriginal) => ({ + ...(await importOriginal()), + ButtonComponent: class { + readonly buttonEl: HTMLButtonElement; + disabled = false; + constructor(parent: HTMLElement) { + this.buttonEl = parent.createEl("button") as HTMLButtonElement; + } + setButtonText(text: string) { + this.buttonEl.textContent = text; + return this; + } + setDisabled(disabled: boolean) { + this.disabled = disabled; + this.buttonEl.disabled = disabled; + return this; + } + onClick(fn: () => void) { + this.buttonEl.addEventListener("click", fn); + return this; + } + }, +})); + +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/features/source-control/timeline/timeline-rows.test.ts b/packages/plugin/tests/features/source-control/timeline/timeline-rows.test.ts index 439d9927..99020f2a 100644 --- a/packages/plugin/tests/features/source-control/timeline/timeline-rows.test.ts +++ b/packages/plugin/tests/features/source-control/timeline/timeline-rows.test.ts @@ -1,10 +1,12 @@ -import { describe, expect, it } from "vitest"; +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 "@/features/source-control/timeline/timeline-rows"; @@ -15,6 +17,11 @@ import type { } 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; @@ -469,7 +476,67 @@ 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") } }), 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..781a0216 --- /dev/null +++ b/packages/plugin/tests/features/source-control/timeline/timeline-tab.test.ts @@ -0,0 +1,350 @@ +// @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"; + +const search = vi.hoisted(() => ({ change: (_value: string) => {} })); + +vi.mock("obsidian", async (importOriginal) => ({ + ...(await importOriginal()), + SearchComponent: class { + inputEl = document.createElement("input"); + setPlaceholder() { + return this; + } + setValue() { + return this; + } + onChange(fn: (value: string) => void) { + search.change = fn; + return this; + } + }, + ButtonComponent: class { + readonly buttonEl: HTMLButtonElement; + disabled = false; + constructor(parent: HTMLElement) { + this.buttonEl = parent.createEl("button") as HTMLButtonElement; + } + setButtonText(text: string) { + this.buttonEl.textContent = text; + return this; + } + setDisabled(disabled: boolean) { + this.disabled = disabled; + this.buttonEl.disabled = disabled; + return this; + } + onClick(fn: () => void) { + this.buttonEl.addEventListener("click", fn); + return this; + } + }, +})); +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 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("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 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. + search.change(".md"); + + 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/features/sync/history/gc.test.ts b/packages/plugin/tests/features/sync/history/gc.test.ts index c20b94c5..cdc24735 100644 --- a/packages/plugin/tests/features/sync/history/gc.test.ts +++ b/packages/plugin/tests/features/sync/history/gc.test.ts @@ -21,6 +21,7 @@ import { listSnapshots, resolveSnapshotManifest, } from "@/features/sync/history/query"; +import { readHistory } from "@/features/sync/history/remote"; import { objectKey } from "@/features/sync/remote/manifest"; import { deepCleanOrphans, @@ -141,6 +142,21 @@ describe("collectHistoryGarbage", () => { }); }); + 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); @@ -162,7 +178,7 @@ describe("collectHistoryGarbage", () => { for (const s of snapshots) expect(s.firstAt).toBeLessThanOrEqual(s.at); }); - it("sweeps the versions it freed only a day later, and leaves nothing dangling", async () => { + 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); @@ -176,6 +192,9 @@ describe("collectHistoryGarbage", () => { 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( diff --git a/packages/plugin/tests/features/sync/history/history-deleted.test.ts b/packages/plugin/tests/features/sync/history/history-deleted.test.ts index 4e503256..82bc02d3 100644 --- a/packages/plugin/tests/features/sync/history/history-deleted.test.ts +++ b/packages/plugin/tests/features/sync/history/history-deleted.test.ts @@ -406,6 +406,76 @@ describe("listDeletedFiles", () => { 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); diff --git a/packages/plugin/tests/features/sync/history/pins.test.ts b/packages/plugin/tests/features/sync/history/pins.test.ts index c2c01cb8..cb4442bc 100644 --- a/packages/plugin/tests/features/sync/history/pins.test.ts +++ b/packages/plugin/tests/features/sync/history/pins.test.ts @@ -11,10 +11,14 @@ import { import { pinKey, readPinById, + readPinInfos, readPins, writePin, } from "@/features/sync/history/pins"; -import { setSnapshotPinned } from "@/features/sync/history/query"; +import { + resolveSnapshotManifest, + setSnapshotPinned, +} from "@/features/sync/history/query"; import { pushKey } from "@/features/sync/history/remote"; import type { Manifest } from "@/features/sync/types"; @@ -89,6 +93,110 @@ describe("setSnapshotPinned", () => { ).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", () => { @@ -139,6 +247,68 @@ describe("readPins", () => { 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" }); diff --git a/packages/plugin/tests/features/sync/history/publish.test.ts b/packages/plugin/tests/features/sync/history/publish.test.ts index c4beb016..17a81715 100644 --- a/packages/plugin/tests/features/sync/history/publish.test.ts +++ b/packages/plugin/tests/features/sync/history/publish.test.ts @@ -117,6 +117,56 @@ describe("publishManifestWithHistory", () => { expect(await storage.list("history/")).toEqual([pushKey("s2")]); }); + it("checks a record naming more than a listing page with one listing, 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])); + } + 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(1); + 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(() => {}); 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..8ccfe8d8 --- /dev/null +++ b/packages/plugin/tests/features/sync/history/sweep.test.ts @@ -0,0 +1,85 @@ +import { FakeStorage } from "@tests/helpers/fake-storage"; +import { manifestOf, pinSnapshot, seedChain } from "@tests/helpers/history"; +import { beforeAll, describe, expect, it, vi } from "vitest"; +import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; +import { writeCandidates } from "@/features/sync/history/remote"; +import { sweepObjects } from "@/features/sync/history/sweep"; +import { objectKey } from "@/features/sync/remote/manifest"; +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); + }); +}); 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..a7b4c591 --- /dev/null +++ b/packages/plugin/tests/features/sync/runtime/history-service.test.ts @@ -0,0 +1,106 @@ +import { TestSession, useEncryptionKey } from "@tests/helpers/session"; +import { describe, expect, it, vi } from "vitest"; +import { sha256Hex } from "@/core/crypto"; +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); + let turns = 0; + const service = new HistoryService({ + openSession, + enqueue: (task) => { + turns++; + return task(); + }, + refresh, + remember: () => undefined, + }); + return { service, openSession, refresh, 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); + }); +}); diff --git a/packages/plugin/tests/stubs/obsidian.ts b/packages/plugin/tests/stubs/obsidian.ts index 2b8d2606..80b26722 100644 --- a/packages/plugin/tests/stubs/obsidian.ts +++ b/packages/plugin/tests/stubs/obsidian.ts @@ -41,7 +41,9 @@ class Stub {} export class Notice extends Stub {} export class Modal extends Stub {} export class Plugin extends Stub {} -export class PluginSettingTab extends Stub {} +export class PluginSettingTab extends Stub { + hide(): void {} +} export class Setting extends Stub {} export class ButtonComponent extends Stub {} export class ItemView extends Stub {} From 4196982eb2d7387dbdb01f35b9f9b9bb4ec3c8d1 Mon Sep 17 00:00:00 2001 From: kitbyte Date: Wed, 28 Oct 2026 20:37:50 +0200 Subject: [PATCH 08/26] feat(tools): pnpm measure:history, FastCDC chunker --- .claude/rules/structure.md | 2 +- .claude/rules/testing.md | 1 + package.json | 3 +- packages/plugin/src/core/chunking/fastcdc.ts | 74 ++++ packages/plugin/src/core/chunking/index.ts | 1 + .../tests/core/chunking/fastcdc.test.ts | 63 +++ tools/measure-history/measure.ts | 380 ++++++++++++++++++ tools/measure-history/run.mjs | 120 ++++++ tools/measure-history/tsconfig.json | 11 + tools/obsidian.mjs | 8 +- 10 files changed, 659 insertions(+), 4 deletions(-) create mode 100644 packages/plugin/src/core/chunking/fastcdc.ts create mode 100644 packages/plugin/src/core/chunking/index.ts create mode 100644 packages/plugin/tests/core/chunking/fastcdc.test.ts create mode 100644 tools/measure-history/measure.ts create mode 100644 tools/measure-history/run.mjs create mode 100644 tools/measure-history/tsconfig.json diff --git a/.claude/rules/structure.md b/.claude/rules/structure.md index 4661cdec..422def27 100644 --- a/.claude/rules/structure.md +++ b/.claude/rules/structure.md @@ -12,7 +12,7 @@ Paths in this file are relative to `packages/plugin/src/`. - `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: `cloudflare crypto drawing hub logs settings shared ui utils vault`, plus `core/constants.ts`. Code moves here when a second feature needs it and it knows no feature. +- `core/` - infra that knows no feature: `chunking cloudflare crypto drawing hub logs settings shared ui utils vault`, plus `core/constants.ts`. 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`). diff --git a/.claude/rules/testing.md b/.claude/rules/testing.md index 84b4d8b5..3f4d8727 100644 --- a/.claude/rules/testing.md +++ b/.claude/rules/testing.md @@ -39,5 +39,6 @@ Plugin source paths are relative to `packages/plugin/src/`. Run `pnpm test` (all ## 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/package.json b/package.json index 37ee8d95..e9fe2460 100644 --- a/package.json +++ b/package.json @@ -11,10 +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", 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/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/tools/measure-history/measure.ts b/tools/measure-history/measure.ts new file mode 100644 index 00000000..c380b6ba --- /dev/null +++ b/tools/measure-history/measure.ts @@ -0,0 +1,380 @@ +/** + * Runs inside Obsidian (run.mjs) on a vault already set up and unlocked: reads its history through the plugin's + * session, writes nothing itself and returns sizes only. Each changed version costs: as stored, sealed whole, or chunked (design 9.3). + */ + +import { compressToBase64, decompressFromBase64 } from "lz-string"; +import { type ChunkParams, chunkEnds, gearTable } from "@/core/chunking"; +import { + decryptBytes, + decryptJson, + type EncryptionKey, + encryptCompressible, + encryptJson, + sha256Hex, +} from "@/core/crypto"; +import { isDrawing } from "@/core/drawing"; +import { runWithConcurrency } from "@/core/utils"; +import type { ObjectStorage } from "@/features/storage"; +import { + REMOTE_HISTORY_LOG_KEY, + REMOTE_OBJECTS_PREFIX, +} from "@/features/sync/constants"; +import type { Activity } from "@/features/sync/history/model/types"; +import { readHistory } from "@/features/sync/history/remote"; +import type { SnapshotChanges } from "@/features/sync/history/types"; + +const KB = 1024; +const MB = 1024 * KB; +const SCHEMES = { + A: { threshold: 256 * KB, params: sizes(16, 64, 256) }, + B: { threshold: 64 * KB, params: sizes(8, 32, 128) }, + C: { threshold: 256 * KB, params: sizes(32, 128, 512) }, +}; +type Scheme = (typeof SCHEMES)[keyof typeof SCHEMES]; +/** Every scheme cuts 1 MB chunks past it, so a 100 MB file is ~100 objects, not ~1600. */ +const LARGE = { above: 16 * MB, params: sizes(256, 1024, 4096) }; +const BUCKETS: [number, string][] = [ + [16 * KB, "<16K"], + [64 * KB, "16-64K"], + [256 * KB, "64-256K"], + [MB, "256K-1M"], + [16 * MB, "1-16M"], + [Number.POSITIVE_INFINITY, ">16M"], +]; +const GEAR = gearTable(0x6d64); +const TEXT = /\.(md|canvas|json|txt|csv|tsv|xml|html|css|js|ts|ya?ml)$/i; +const COMPRESSED_SCENE = + /(## Drawing[ \t]*\r?\n)```compressed-json\r?\n([\s\S]*?)\r?\n```/; + +export interface Options { + /** Newest pairs kept. */ + maxPairs?: number; + /** A pair with a larger side is skipped. */ + maxBytes?: number; +} + +export interface Group { + kind: string; + bucket: string; + pairs: number; + /** The newer version's blob as stored now. */ + today: number; + /** Sealed whole by today's write path. */ + whole: number; + /** New chunks sealed plus the recipe, chunked against the older version only. */ + schemes: Record; + /** Scheme A over the scene stored as plain JSON (LZString drawings). */ + decoded?: number; +} + +export interface Report { + layout: string; + pushes: number; + days: number; + busiestDay: number; + historyKeys: number; + historyBytes: number | null; + pairs: number; + skipped: number; + drawings: { compressed: number; reproducible: number }; + groups: Group[]; +} + +interface Pair { + path: string; + from: string; + to: string; +} + +interface Version { + stored: number; + plain: Uint8Array; +} + +export async function run(options: Options = {}): Promise { + // biome-ignore lint/suspicious/noExplicitAny: plugin internals, reached at run time in any version. + const plugin = (window as any).app.plugins.plugins.mdsync; + const session = await plugin?.controller?.history?.deps?.openSession(); + if (!session) throw new Error("MDSync is not set up or is locked here."); + const storage: ObjectStorage = session.storage; + const key: EncryptionKey = session.key; + const source = await historyOf(storage, key); + const pairs = source.pairs.slice(0, options.maxPairs ?? source.pairs.length); + const limit = options.maxBytes ?? 64 * MB; + const groups = new Map(); + const drawings = { compressed: 0, reproducible: 0 }; + let skipped = 0; + let done = 0; + await runWithConcurrency(chainsOf(pairs), 4, async (chain) => { + // A chain runs newest first, so the next pair's newer side is this one's older side. + let loaded = new Map>(); + for (const pair of chain) { + const load = (hash: string) => + loaded.get(hash) ?? read(storage, key, hash); + const [from, to] = [load(pair.from), load(pair.to)]; + loaded = new Map([ + [pair.from, from], + [pair.to, to], + ]); + const [older, newer] = await Promise.all([from, to]); + if ( + !older || + !newer || + Math.max(older.plain.length, newer.plain.length) > limit + ) { + skipped++; + continue; + } + const text = TEXT.test(pair.path) + ? new TextDecoder().decode(newer.plain) + : ""; + const kind = kindOf(pair.path, text); + const group = groupOf(groups, kind, newer.plain.length); + group.pairs++; + group.today += newer.stored; + // Awaited first: `+=` would read the shared total before the await and drop another path's add. + const whole = (await encryptCompressible(key, newer.plain)).length; + group.whole += whole; + for (const [name, scheme] of Object.entries(SCHEMES)) { + const cost = await versionCost(key, older.plain, newer.plain, scheme); + group.schemes[name] = (group.schemes[name] ?? 0) + cost; + } + const after = kind === "drawing (LZString)" ? decoded(text) : null; + if (after) { + drawings.compressed++; + if (after.reproducible) drawings.reproducible++; + const before = + decoded(new TextDecoder().decode(older.plain))?.bytes ?? older.plain; + const cost = await versionCost(key, before, after.bytes, SCHEMES.A); + group.decoded = (group.decoded ?? 0) + cost; + } + if (++done % 50 === 0) console.log(`measured ${done}/${pairs.length}`); + } + }); + const days = perDay(source.pushes); + return { + layout: source.layout, + pushes: days.reduce((sum, count) => sum + count, 0), + days: days.length, + busiestDay: Math.max(0, ...days), + historyKeys: source.keys, + historyBytes: source.bytes, + pairs: pairs.length, + skipped, + drawings, + groups: [...groups.values()], + }; +} + +interface Source { + layout: string; + /** Newest first. */ + pairs: Pair[]; + /** [time, pushes]: a packed period reports its pushes per hour. */ + pushes: [number, number][]; + keys: number; + bytes: number | null; +} + +/** The 1.x log while it is there, else the records under `history/` that nothing consumed. */ +async function historyOf( + storage: ObjectStorage, + key: EncryptionKey, +): Promise { + const log = await storage.get(REMOTE_HISTORY_LOG_KEY); + if (log) { + const { snapshots, changes } = await decryptJson<{ + snapshots: { id: string; createdAt: number }[]; + changes: Record; + }>(key, log); + const newest = [...snapshots].sort((a, b) => b.createdAt - a.createdAt); + return { + layout: "1.x log", + pairs: newest.flatMap(({ id }) => pairsOf(changes[id])), + pushes: snapshots.map(({ createdAt }) => [createdAt, 1]), + keys: 1, + bytes: log.length, + }; + } + const { view } = await readHistory(storage, key, ""); + const consumed = new Set( + [...view.objects.values()].flatMap(({ object }) => object.consumed), + ); + const live = (map: ReadonlyMap) => + [...map].filter(([at]) => !consumed.has(at)).map(([, value]) => value); + const records = [ + ...live(view.pushes).map(({ push }) => push), + ...live(view.objects).flatMap(({ object }) => object.records), + ].sort((a, b) => b.createdAt - a.createdAt); + return { + layout: "history/ (a packed period is one pair per path)", + pairs: records.flatMap(({ changes }) => pairsOf(changes)), + pushes: [ + ...live(view.pushes).map(({ at }): [number, number] => [at, 1]), + ...live(view.objects).flatMap(({ object }) => + [ + object.activity ?? {}, + ...object.records.map((r) => r.activity), + ].flatMap(hoursOf), + ), + ], + keys: view.pushes.size + view.objects.size, + bytes: null, + }; +} + +function pairsOf(changes: SnapshotChanges | undefined): Pair[] { + return Object.entries(changes?.modified ?? {}) + .filter(([, { from, to }]) => from.hash !== to.hash) + .map(([path, { from, to }]) => ({ path, from: from.hash, to: to.hash })); +} + +/** Pairs per path, newest first, each pair once. */ +function chainsOf(pairs: readonly Pair[]): Pair[][] { + const chains = new Map>(); + for (const pair of pairs) { + const chain = chains.get(pair.path) ?? new Map(); + chain.set(`${pair.from}>${pair.to}`, pair); + chains.set(pair.path, chain); + } + return [...chains.values()].map((chain) => [...chain.values()]); +} + +/** Null when the blob is gone or unreadable: the pair is skipped, not the run. */ +async function read( + storage: ObjectStorage, + key: EncryptionKey, + hash: string, +): Promise { + try { + const blob = await storage.get(`${REMOTE_OBJECTS_PREFIX}${hash}`); + return ( + blob && { stored: blob.length, plain: await decryptBytes(key, blob) } + ); + } catch { + return null; + } +} + +/** Storing `to` once `from` is stored: its new chunks and a recipe, or the whole file under the threshold. */ +async function versionCost( + key: EncryptionKey, + from: Uint8Array, + to: Uint8Array, + { threshold, params }: Scheme, +): Promise { + if (to.length < threshold) return (await encryptCompressible(key, to)).length; + const cut = (size: number) => (size > LARGE.above ? LARGE.params : params); + // Below the threshold the older version was stored whole: no chunk of it exists to reuse. + const stored = + from.length < threshold ? [] : await chunksOf(from, cut(from.length)); + const known = new Set(stored.map(({ id }) => id)); + const recipe: [string, number][] = []; + let cost = 0; + for (const { id, bytes } of await chunksOf(to, cut(to.length))) { + recipe.push([id, bytes.length]); + if (known.has(id)) continue; + known.add(id); + cost += (await encryptCompressible(key, bytes)).length; + } + return cost + (await encryptJson(key, recipe)).length; +} + +async function chunksOf(bytes: Uint8Array, params: ChunkParams) { + const chunks: { id: string; bytes: Uint8Array }[] = []; + let start = 0; + for (const end of chunkEnds(bytes, params, GEAR)) { + const part = bytes.subarray(start, end); + chunks.push({ id: await sha256Hex(part), bytes: part }); + start = end; + } + return chunks; +} + +/** + * The drawing with its scene as plain JSON, the form a codec would store. `reproducible`: compressing the + * JSON again and rewrapping it like the file gives back the same text, so the codec can restore byte for byte. + */ +function decoded( + text: string, +): { bytes: Uint8Array; reproducible: boolean } | null { + const match = COMPRESSED_SCENE.exec(text); + const [whole, heading = "", body = ""] = match ?? []; + const json = match && unpack(body); + if (!match || !whole || !json) return null; + const [line = "", gap = ""] = + /^([^\r\n]*)(\r?\n(?:\r?\n)?)?/.exec(body)?.slice(1) ?? []; + const rewrapped = gap + ? compressToBase64(json).replace( + new RegExp(`(.{${line.length}})`, "g"), + `$1${gap}`, + ) + : compressToBase64(json); + const start = match.index + heading.length; + const plain = `${text.slice(0, start)}\`\`\`json\n${json}\n\`\`\`${text.slice(match.index + whole.length)}`; + return { + bytes: new TextEncoder().encode(plain), + reproducible: rewrapped === body, + }; +} + +function kindOf(path: string, text: string): string { + if (text && isDrawing(text)) + return COMPRESSED_SCENE.test(text) + ? "drawing (LZString)" + : "drawing (JSON)"; + if (path.endsWith(".md")) return "note"; + if (path.endsWith(".canvas")) return "canvas"; + if (path.endsWith(".pdf")) return "pdf"; + return text ? "other text" : "binary"; +} + +function groupOf( + groups: Map, + kind: string, + size: number, +): Group { + const bucket = BUCKETS.find(([below]) => size < below)?.[1] ?? ">16M"; + const id = `${kind} ${bucket}`; + const group = groups.get(id) ?? { + kind, + bucket, + pairs: 0, + today: 0, + whole: 0, + schemes: {}, + }; + groups.set(id, group); + return group; +} + +/** A damaged scene measures as plain bytes instead of stopping the run. */ +function unpack(body: string): string | null { + try { + return decompressFromBase64(body.replace(/\s/g, "")); + } catch { + return null; + } +} + +function hoursOf(activity: Activity): [number, number][] { + return Object.entries(activity).map(([hour, [pushes]]) => [ + Number(hour) * 3_600_000, + pushes, + ]); +} + +/** Pushes on each local day that had any. */ +function perDay(pushes: readonly [number, number][]): number[] { + const days = new Map(); + for (const [time, count] of pushes) { + const day = new Date(time).toDateString(); + days.set(day, (days.get(day) ?? 0) + count); + } + return [...days.values()].filter((count) => count > 0); +} + +function sizes(min: number, avg: number, max: number): ChunkParams { + return { min: min * KB, avg: avg * KB, max: max * KB }; +} diff --git a/tools/measure-history/run.mjs b/tools/measure-history/run.mjs new file mode 100644 index 00000000..b1cc6058 --- /dev/null +++ b/tools/measure-history/run.mjs @@ -0,0 +1,120 @@ +#!/usr/bin/env node +/** + * Measures what chunking would save on a real vault's history (design 9.3). Obsidian must run with the CDP + * port open (`node tools/obsidian.mjs launch`) and MDSync unlocked; nothing is written to the remote. + * + * pnpm measure:history [--max-pairs 500] [--max-mb 64] [--out report.json] + */ +import { writeFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { parseArgs } from "node:util"; +import esbuild from "esbuild"; +import { openApp } from "../obsidian.mjs"; + +const { values } = parseArgs({ + options: { + "max-pairs": { type: "string" }, + "max-mb": { type: "string", default: "64" }, + out: { type: "string" }, + }, +}); +const plugin = new URL("../../packages/plugin/", import.meta.url); +const { outputFiles } = await esbuild.build({ + entryPoints: [fileURLToPath(new URL("measure.ts", import.meta.url))], + alias: { "@": fileURLToPath(new URL("src", plugin)) }, + tsconfig: fileURLToPath(new URL("tsconfig.json", plugin)), + // core/crypto reaches core/vault, which uses the API only in functions this never calls. + plugins: [ + { + name: "obsidian-stub", + setup(build) { + build.onResolve({ filter: /^obsidian$/ }, () => ({ + path: "obsidian", + namespace: "stub", + })); + build.onLoad({ filter: /.*/, namespace: "stub" }, () => ({ + contents: "module.exports = {};", + })); + }, + }, + ], + bundle: true, + write: false, + format: "iife", + globalName: "mdsyncMeasure", + target: "es2020", +}); +const options = { + maxPairs: values["max-pairs"] ? Number(values["max-pairs"]) : undefined, + maxBytes: Number(values["max-mb"]) * 1024 * 1024, +}; + +const { browser, page } = await openApp(); +page.on("console", (message) => { + if (message.text().startsWith("measured ")) console.log(message.text()); +}); +try { + const report = await page.evaluate( + ([code, opts]) => + new Function(`${code}\nreturn mdsyncMeasure.run(arguments[0]);`)(opts), + [outputFiles[0].text, options], + ); + print(report); + if (values.out) writeFileSync(values.out, JSON.stringify(report, null, "\t")); +} finally { + await browser.close(); +} + +function print(report) { + const perDay = report.days ? (report.pushes / report.days).toFixed(1) : "0"; + console.log( + `${report.layout}: ${report.pushes} pushes over ${report.days} days (${perDay}/day, busiest ${report.busiestDay})`, + ); + const size = + report.historyBytes === null ? "" : `, ${kb(report.historyBytes)}`; + console.log(`history: ${report.historyKeys} keys${size}`); + console.log( + `pairs: ${report.pairs} measured, ${report.skipped} skipped (blob gone or too large)`, + ); + const { compressed, reproducible } = report.drawings; + if (compressed) + console.log( + `LZString drawings: ${reproducible}/${compressed} re-encode byte for byte`, + ); + const groups = report.groups.sort((a, b) => b.today - a.today); + const all = { + kind: "all", + bucket: "", + pairs: 0, + today: 0, + whole: 0, + schemes: { A: 0, B: 0, C: 0 }, + }; + for (const group of groups) { + for (const field of ["pairs", "today", "whole"]) all[field] += group[field]; + for (const name in all.schemes) all.schemes[name] += group.schemes[name]; + } + const rows = [...groups, all].map((group) => ({ + kind: group.kind, + size: group.bucket, + pairs: group.pairs, + today: kb(group.today), + whole: share(group.whole, group.today), + A: share(group.schemes.A, group.today), + B: share(group.schemes.B, group.today), + C: share(group.schemes.C, group.today), + "A decoded": + group.decoded === undefined ? "" : share(group.decoded, group.today), + })); + console.table(rows); +} + +function kb(bytes) { + return bytes < 1024 * 1024 + ? `${(bytes / 1024).toFixed(0)} KB` + : `${(bytes / 1024 / 1024).toFixed(1)} MB`; +} + +function share(bytes, of) { + return `${kb(bytes)} (${of ? Math.round((100 * bytes) / of) : 0}%)`; +} diff --git a/tools/measure-history/tsconfig.json b/tools/measure-history/tsconfig.json new file mode 100644 index 00000000..3b03d977 --- /dev/null +++ b/tools/measure-history/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../packages/plugin/tsconfig.json", + "compilerOptions": { + "baseUrl": ".", + "paths": { "@/*": ["../../packages/plugin/src/*"] }, + "lib": ["DOM", "ES2022"], + "types": ["node"], + "noEmit": true + }, + "include": ["measure.ts"] +} diff --git a/tools/obsidian.mjs b/tools/obsidian.mjs index 8296e220..8ede233b 100644 --- a/tools/obsidian.mjs +++ b/tools/obsidian.mjs @@ -13,6 +13,7 @@ * node tools/obsidian.mjs commands mdsync list command ids matching a term */ import { spawn } from "node:child_process"; +import { pathToFileURL } from "node:url"; import { chromium } from "playwright-core"; const PORT = Number(process.env.OBSIDIAN_CDP_PORT ?? 9222); @@ -20,7 +21,7 @@ const EXE = process.env.OBSIDIAN_EXE ?? "C:\\Program Files\\Obsidian\\Obsidian.exe"; const APP_URL = "app://obsidian.md"; -async function openApp() { +export async function openApp() { const browser = await chromium.connectOverCDP(`http://127.0.0.1:${PORT}`); for (const context of browser.contexts()) { for (const page of context.pages()) { @@ -116,7 +117,10 @@ async function run(fn, arg) { } const [action, ...args] = process.argv.slice(2); -if (action === "launch") { +const imported = import.meta.url !== pathToFileURL(process.argv[1] ?? "").href; +if (imported) { + // Only openApp is wanted. +} else if (action === "launch") { launch(); } else if (actions[action]) { await actions[action](args); From 01d742b05bcbb7fe0384b6dd931af253d5058797 Mon Sep 17 00:00:00 2001 From: kitbyte Date: Wed, 28 Oct 2026 20:56:34 +0200 Subject: [PATCH 09/26] feat(history): configuration folder kept out of history --- .claude/rules/history.md | 4 +- .../source-control/timeline/sessions.ts | 19 +++++- .../source-control/timeline/timeline-tab.ts | 4 +- packages/plugin/src/features/sync/README.md | 4 +- packages/plugin/src/features/sync/engine.ts | 2 + .../src/features/sync/history/changes.ts | 40 ++++++++++++ .../plugin/src/features/sync/history/gc.ts | 14 +++-- .../src/features/sync/history/model/plan.ts | 7 ++- .../features/sync/history/model/records.ts | 4 +- .../src/features/sync/history/model/types.ts | 2 + .../src/features/sync/history/publish.ts | 14 ++++- .../plugin/src/features/sync/history/query.ts | 17 ++++-- .../features/sync/history/restore-vault.ts | 6 +- .../features/sync/operations/config-reset.ts | 2 + .../features/sync/runtime/history-service.ts | 3 + .../timeline/session-rows.test.ts | 4 +- .../source-control/timeline/sessions.test.ts | 60 +++++++++++++++++- .../timeline/timeline-tab.test.ts | 25 ++++++++ .../features/sync/history/compose.test.ts | 61 +++++++++++++++++++ .../features/sync/history/model/plan.test.ts | 29 ++++++++- .../sync/history/model/records.test.ts | 38 +++++++++++- .../tests/features/sync/history/pins.test.ts | 27 ++++++++ .../features/sync/history/publish.test.ts | 55 +++++++++++++++++ .../sync/history/restore-vault.test.ts | 30 +++++++++ 24 files changed, 445 insertions(+), 26 deletions(-) diff --git a/.claude/rules/history.md b/.claude/rules/history.md index 7f64a47f..01449e38 100644 --- a/.claude/rules/history.md +++ b/.claude/rules/history.md @@ -16,6 +16,7 @@ History is one encrypted record per push under `history/`, which GC thins into o - 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 key and vault and while every blob it names exists (`stillLands`; past a thousand blobs, checked against one listing of `objects/`): 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. @@ -37,13 +38,14 @@ History is one encrypted record per push under `history/`, which GC thins into o ## 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`). - Restore dialogs promise "nothing is pushed until you say so" (`features/diff/ui/restore-modal.ts`); keep that true. ## Pins -- A pin is one object, `pins/.json.enc` (`features/sync/history/pins.ts`): `{ v: 1, manifest, label?, pinnedAt }` with the snapshot's full manifest, so it outlives the records it was replayed from. Nothing else flags it: a pin is on exactly while its object reads. +- 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`). - A listed pin that does not read (corrupt, or a 1.x bare manifest) is `unreadable` in `readPins`: what it holds is unknown. 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. diff --git a/packages/plugin/src/features/source-control/timeline/sessions.ts b/packages/plugin/src/features/source-control/timeline/sessions.ts index 708ca53e..ff60ebfd 100644 --- a/packages/plugin/src/features/source-control/timeline/sessions.ts +++ b/packages/plugin/src/features/source-control/timeline/sessions.ts @@ -31,7 +31,7 @@ export function sessionsOf( now: number = Date.now(), ): Session[] { const runs: SnapshotSummary[][] = []; - for (const version of versions) { + 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); @@ -40,6 +40,23 @@ export function sessionsOf( 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, diff --git a/packages/plugin/src/features/source-control/timeline/timeline-tab.ts b/packages/plugin/src/features/source-control/timeline/timeline-tab.ts index 03221a3a..9bf64315 100644 --- a/packages/plugin/src/features/source-control/timeline/timeline-tab.ts +++ b/packages/plugin/src/features/source-control/timeline/timeline-tab.ts @@ -171,7 +171,9 @@ export class TimelineTab { ); } const rows = this.sessionRows(result); - if (rows.length === 0 && !result.lagging) { + // 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", diff --git a/packages/plugin/src/features/sync/README.md b/packages/plugin/src/features/sync/README.md index 6a765324..ddcb10f5 100644 --- a/packages/plugin/src/features/sync/README.md +++ b/packages/plugin/src/features/sync/README.md @@ -78,11 +78,11 @@ A hunk index means nothing without its two texts. The diff view, the gutter mark ## 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`). 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 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. +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. ## Other flows diff --git a/packages/plugin/src/features/sync/engine.ts b/packages/plugin/src/features/sync/engine.ts index b3459257..05dd9383 100644 --- a/packages/plugin/src/features/sync/engine.ts +++ b/packages/plugin/src/features/sync/engine.ts @@ -16,6 +16,7 @@ import { runWithFileConcurrency } from "./changes/file-concurrency"; import { entryAt, sortedByPath } from "./changes/records"; import { skipUnholdableNames } from "./changes/remote-names"; import { REMOTE_OBJECTS_PREFIX } from "./constants"; +import { untrackedDir } from "./history/changes"; import { publishManifestWithHistory } from "./history/publish"; import type { HistoryConfig } from "./history/types"; import { attribute, publisher } from "./identity/authors"; @@ -281,6 +282,7 @@ export async function publishFileMap( compareResult.remote, deps.history, deps.state.baseline, + untrackedDir(deps), ); forgetUploads( deps.storage, diff --git a/packages/plugin/src/features/sync/history/changes.ts b/packages/plugin/src/features/sync/history/changes.ts index 9e6f92a7..38d72d95 100644 --- a/packages/plugin/src/features/sync/history/changes.ts +++ b/packages/plugin/src/features/sync/history/changes.ts @@ -33,6 +33,46 @@ export function diffManifests( 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, diff --git a/packages/plugin/src/features/sync/history/gc.ts b/packages/plugin/src/features/sync/history/gc.ts index 7e8cd05a..8c6b992d 100644 --- a/packages/plugin/src/features/sync/history/gc.ts +++ b/packages/plugin/src/features/sync/history/gc.ts @@ -119,9 +119,13 @@ async function thinHistory( function changesOf( view: HistoryView, keys: readonly string[], -): { changes: SnapshotChanges }[] { - return keys.flatMap((storageKey): { changes: SnapshotChanges }[] => { - const push = view.pushes.get(storageKey)?.push; - return push ? [push] : (view.objects.get(storageKey)?.object.records ?? []); - }); +): { 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/model/plan.ts b/packages/plugin/src/features/sync/history/model/plan.ts index cc2111b7..b17d584f 100644 --- a/packages/plugin/src/features/sync/history/model/plan.ts +++ b/packages/plugin/src/features/sync/history/model/plan.ts @@ -6,6 +6,7 @@ import { thin } from "./records"; import type { Activity, HistoryObject, + PushRecord, Resolution, StoredRecord, } from "./types"; @@ -79,7 +80,8 @@ function wholeKeys(input: PlanInput): (key: string) => boolean { /** Versions the replaced records named that the new object no longer does: phase 1's sweep candidates. */ export function freedHashes( - replaced: readonly Pick[], + replaced: readonly (Pick & + Pick)[], kept: readonly Pick[], ): Set { const keptHashes = new Set( @@ -87,7 +89,8 @@ export function freedHashes( ); const freed = new Set(); for (const record of replaced) { - for (const { hash } of changeEntries(record.changes)) { + const named = changeEntries(record.changes).map(({ hash }) => hash); + for (const hash of [...named, ...(record.released ?? [])]) { if (!keptHashes.has(hash)) freed.add(hash); } } diff --git a/packages/plugin/src/features/sync/history/model/records.ts b/packages/plugin/src/features/sync/history/model/records.ts index 09a74686..d5f1a15c 100644 --- a/packages/plugin/src/features/sync/history/model/records.ts +++ b/packages/plugin/src/features/sync/history/model/records.ts @@ -6,6 +6,7 @@ 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, @@ -16,7 +17,8 @@ export function storedRecord(push: PushRecord, at: number): StoredRecord { at, firstAt: at, pushes: 1, - activity: { [hourOf(at)]: [1, pathsChanged(push.changes)] }, + // A push of only the configuration folder is no activity in the vault. + activity: paths === 0 && push.released ? {} : { [hourOf(at)]: [1, paths] }, }; } diff --git a/packages/plugin/src/features/sync/history/model/types.ts b/packages/plugin/src/features/sync/history/model/types.ts index 627853c4..33f0411c 100644 --- a/packages/plugin/src/features/sync/history/model/types.ts +++ b/packages/plugin/src/features/sync/history/model/types.ts @@ -16,6 +16,8 @@ export interface PushRecord { 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. */ diff --git a/packages/plugin/src/features/sync/history/publish.ts b/packages/plugin/src/features/sync/history/publish.ts index cc6f2ac9..79a13213 100644 --- a/packages/plugin/src/features/sync/history/publish.ts +++ b/packages/plugin/src/features/sync/history/publish.ts @@ -6,7 +6,12 @@ import type { StorageAdapter } from "@/features/storage"; import { REMOTE_OBJECTS_PREFIX } from "../constants"; import { objectKey, publishManifestWithGuard } from "../remote/manifest"; import type { Manifest } from "../types"; -import { changeEntries, diffManifests } from "./changes"; +import { + changeEntries, + diffManifests, + historyTracks, + splitTracked, +} from "./changes"; import { pushKey, sealPushRecord } from "./remote"; import type { HistoryConfig } from "./types"; @@ -37,11 +42,15 @@ export async function publishManifestWithHistory( 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 = diffManifests(parent, manifest); + const { changes, released } = splitTracked( + diffManifests(parent, manifest), + historyTracks(configDir), + ); const own: Unwritten = { blob: await sealPushRecord(key, root, { v: 1, @@ -52,6 +61,7 @@ export async function publishManifestWithHistory( deviceId: manifest.deviceId, deviceName: manifest.deviceName, changes, + ...(released.length > 0 && { released }), }), key, vaultId: manifest.vaultId, diff --git a/packages/plugin/src/features/sync/history/query.ts b/packages/plugin/src/features/sync/history/query.ts index a7cc6821..74b31bc0 100644 --- a/packages/plugin/src/features/sync/history/query.ts +++ b/packages/plugin/src/features/sync/history/query.ts @@ -4,7 +4,7 @@ import { loadRemoteBytes } from "../changes/content"; import { entryAt } from "../changes/records"; import { fetchRemoteManifest } from "../remote/manifest"; import type { Manifest, ManifestEntry } from "../types"; -import { undoChangesForPath } from "./changes"; +import { historyTracks, pickPaths, undoChangesForPath } from "./changes"; import { activityOf } from "./model/activity"; import { type Cover, @@ -38,6 +38,8 @@ export interface HistoryQuery { root: string; /** See `HistoryConfig.horizon`. */ horizon: number | null; + /** Left out of history (`historyTracks`). */ + configDir?: string; } type Source = Pick; @@ -302,11 +304,11 @@ async function replaySnapshot( } /** - * Pinning stores the snapshot's whole manifest; a readable pin keeps its manifest and takes the new label. - * `label` undefined keeps the pin's name, "" clears it. + * 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, + source: Source & Pick, snapshotId: string, pinned: boolean, label?: string, @@ -317,8 +319,13 @@ export async function setSnapshotPinned( return; } const existing = await readPinById(storage, key, root, snapshotId); + const replayed = existing ? null : await replaySnapshot(source, snapshotId); const manifest = - existing?.manifest ?? (await replaySnapshot(source, snapshotId)); + 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.", diff --git a/packages/plugin/src/features/sync/history/restore-vault.ts b/packages/plugin/src/features/sync/history/restore-vault.ts index 9beb70c3..07f04b26 100644 --- a/packages/plugin/src/features/sync/history/restore-vault.ts +++ b/packages/plugin/src/features/sync/history/restore-vault.ts @@ -24,6 +24,8 @@ 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); const plan: VaultRestorePlan = { @@ -33,6 +35,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 +49,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/operations/config-reset.ts b/packages/plugin/src/features/sync/operations/config-reset.ts index 276a3ba6..ddd84298 100644 --- a/packages/plugin/src/features/sync/operations/config-reset.ts +++ b/packages/plugin/src/features/sync/operations/config-reset.ts @@ -5,6 +5,7 @@ import { compare, type EngineDependencies, } from "../engine"; +import { untrackedDir } from "../history/changes"; import { publishManifestWithHistory } from "../history/publish"; import { reconcileBaselineResetGenerations } from "../remote/config-reset"; import { buildManifest } from "../remote/manifest"; @@ -55,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/features/sync/runtime/history-service.ts b/packages/plugin/src/features/sync/runtime/history-service.ts index 14461da6..d0e0bda3 100644 --- a/packages/plugin/src/features/sync/runtime/history-service.ts +++ b/packages/plugin/src/features/sync/runtime/history-service.ts @@ -12,6 +12,7 @@ import { } from "../changes/content"; import { runWithFileConcurrency } from "../changes/file-concurrency"; import type { EngineDependencies } from "../engine"; +import { historyTracks, untrackedDir } from "../history/changes"; import type { Activity } from "../history/model/types"; import { type HistoryQuery, @@ -154,6 +155,7 @@ export class HistoryService { target, await scanLocal(session), (path) => session.scope.includes(path) && !diskRefuses(path), + historyTracks(untrackedDir(session)), ); } @@ -281,6 +283,7 @@ function queryOf(session: EngineDependencies): HistoryQuery { key: session.key, root: session.space.root, horizon: session.history?.horizon ?? null, + configDir: untrackedDir(session), }; } 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 index fa499258..59bca335 100644 --- a/packages/plugin/tests/features/source-control/timeline/session-rows.test.ts +++ b/packages/plugin/tests/features/source-control/timeline/session-rows.test.ts @@ -32,7 +32,7 @@ function version( deviceId: "phone", deviceName: "Phone", pinned: false, - files: changes(), + files: changes({ added: { "a.md": entry("a", 1) } }), keptUntil: null, restorable: true, isHead: false, @@ -89,7 +89,7 @@ describe("buildSessionRows", () => { ); // A picked day matches the session from its first push, not only its last. expect(row).toMatchObject({ - meta: "2 versions · 7 pushes · 0 files", + meta: "2 versions · 7 pushes · 1 file", everyPush: false, firstAt: NOW - 6 * HOUR, }); diff --git a/packages/plugin/tests/features/source-control/timeline/sessions.test.ts b/packages/plugin/tests/features/source-control/timeline/sessions.test.ts index df0891e4..8c180132 100644 --- a/packages/plugin/tests/features/source-control/timeline/sessions.test.ts +++ b/packages/plugin/tests/features/source-control/timeline/sessions.test.ts @@ -21,7 +21,7 @@ function version( createdAt: at, deviceId: "laptop", pinned: false, - files: { added: {}, modified: {}, deleted: {} }, + files: { added: { "a.md": entry("a") }, modified: {}, deleted: {} }, keptUntil: null, restorable: true, isHead: false, @@ -33,6 +33,8 @@ function version( }; } +const none = { added: {}, modified: {}, deleted: {} }; + const sizes = (list: ReturnType) => list.map((session) => session.versions.length); @@ -125,6 +127,62 @@ describe("sessionsOf", () => { }); }); + 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( [ 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 index 781a0216..bc1b7ae7 100644 --- a/packages/plugin/tests/features/source-control/timeline/timeline-tab.test.ts +++ b/packages/plugin/tests/features/source-control/timeline/timeline-tab.test.ts @@ -189,6 +189,31 @@ describe("TimelineTab session rows", () => { 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(); diff --git a/packages/plugin/tests/features/sync/history/compose.test.ts b/packages/plugin/tests/features/sync/history/compose.test.ts index f4474080..1529afba 100644 --- a/packages/plugin/tests/features/sync/history/compose.test.ts +++ b/packages/plugin/tests/features/sync/history/compose.test.ts @@ -4,7 +4,10 @@ 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"; @@ -97,6 +100,64 @@ describe("composeChanges", () => { }); }); +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); diff --git a/packages/plugin/tests/features/sync/history/model/plan.test.ts b/packages/plugin/tests/features/sync/history/model/plan.test.ts index 13725b68..c4952015 100644 --- a/packages/plugin/tests/features/sync/history/model/plan.test.ts +++ b/packages/plugin/tests/features/sync/history/model/plan.test.ts @@ -3,9 +3,10 @@ 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 { planGc } from "@/features/sync/history/model/plan"; +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 { @@ -117,6 +118,32 @@ describe("history GC plan over a simulated vault", () => { }); }); +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); diff --git a/packages/plugin/tests/features/sync/history/model/records.test.ts b/packages/plugin/tests/features/sync/history/model/records.test.ts index c03a4d30..051e21e4 100644 --- a/packages/plugin/tests/features/sync/history/model/records.test.ts +++ b/packages/plugin/tests/features/sync/history/model/records.test.ts @@ -1,7 +1,10 @@ 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 { StoredRecord } from "@/features/sync/history/model/types"; +import type { + PushRecord, + StoredRecord, +} from "@/features/sync/history/model/types"; import type { EFileKind, ManifestEntry } from "@/features/sync/types"; const MINUTE = 60_000; @@ -38,6 +41,39 @@ function pushes( ); } +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]); diff --git a/packages/plugin/tests/features/sync/history/pins.test.ts b/packages/plugin/tests/features/sync/history/pins.test.ts index cb4442bc..e887398b 100644 --- a/packages/plugin/tests/features/sync/history/pins.test.ts +++ b/packages/plugin/tests/features/sync/history/pins.test.ts @@ -49,6 +49,33 @@ describe("setSnapshotPinned", () => { 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: "" }; diff --git a/packages/plugin/tests/features/sync/history/publish.test.ts b/packages/plugin/tests/features/sync/history/publish.test.ts index 17a81715..7c27d6f4 100644 --- a/packages/plugin/tests/features/sync/history/publish.test.ts +++ b/packages/plugin/tests/features/sync/history/publish.test.ts @@ -193,6 +193,61 @@ describe("publishManifestWithHistory", () => { 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); diff --git a/packages/plugin/tests/features/sync/history/restore-vault.test.ts b/packages/plugin/tests/features/sync/history/restore-vault.test.ts index 16e54de6..3385db51 100644 --- a/packages/plugin/tests/features/sync/history/restore-vault.test.ts +++ b/packages/plugin/tests/features/sync/history/restore-vault.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "vitest"; +import { historyTracks } from "@/features/sync/history/changes"; import { planVaultRestore } from "@/features/sync/history/restore-vault"; import type { EFileKind, @@ -117,6 +118,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") }), From 913411ee4ecbe8b0c89835cb42ae4c6c156c213a Mon Sep 17 00:00:00 2001 From: kitbyte Date: Wed, 28 Oct 2026 22:35:10 +0200 Subject: [PATCH 10/26] feat(sync): content owner, Excalidraw stored decoded, chunked file reads --- .claude/rules/history.md | 11 +- .claude/rules/security.md | 5 + .claude/rules/structure.md | 2 +- .claude/rules/sync-integrity.md | 3 +- packages/plugin/src/core/crypto/cipher.ts | 80 +++- packages/plugin/src/core/crypto/constants.ts | 9 + packages/plugin/src/core/crypto/index.ts | 3 + packages/plugin/src/core/drawing/codec.ts | 114 ++++++ packages/plugin/src/core/drawing/format.ts | 11 +- packages/plugin/src/core/drawing/index.ts | 6 + packages/plugin/src/core/drawing/scene.ts | 9 +- packages/plugin/src/features/spaces/README.md | 2 +- packages/plugin/src/features/sync/README.md | 7 +- .../plugin/src/features/sync/apply/pull.ts | 11 +- .../src/features/sync/changes/content.ts | Bin 9388 -> 9113 bytes .../plugin/src/features/sync/constants.ts | 3 + .../src/features/sync/content/closure.ts | 54 +++ .../src/features/sync/content/header.ts | 44 +++ .../plugin/src/features/sync/content/keys.ts | 41 +++ .../plugin/src/features/sync/content/load.ts | 172 +++++++++ .../plugin/src/features/sync/content/store.ts | 32 ++ packages/plugin/src/features/sync/engine.ts | 17 +- .../src/features/sync/history/publish.ts | 22 +- .../plugin/src/features/sync/history/sweep.ts | 121 ++++-- .../src/features/sync/remote/manifest.ts | 6 +- .../plugin/src/features/sync/remote/reset.ts | 28 +- .../src/features/sync/remote/uploads.ts | 27 +- .../src/features/sync/runtime/maintenance.ts | 53 ++- .../core/crypto/described-envelope.test.ts | 175 +++++++++ .../tests/core/crypto/failed-batch.test.ts | 2 +- .../plugin/tests/core/drawing/codec.test.ts | 180 +++++++++ .../features/sync/apply/pull-hint.test.ts | 2 +- .../sync/changes/content-cache.test.ts | 7 +- .../tests/features/sync/content/load.test.ts | 347 ++++++++++++++++++ .../features/sync/content/roundtrip.test.ts | 86 +++++ .../tests/features/sync/content/store.test.ts | 90 +++++ .../tests/features/sync/history/gc.test.ts | 2 +- .../features/sync/history/publish.test.ts | 21 +- .../tests/features/sync/history/sweep.test.ts | 112 +++++- .../features/sync/remote/foreign.test.ts | 2 +- .../tests/features/sync/remote/reset.test.ts | 21 +- .../features/sync/runtime/maintenance.test.ts | 139 ++++++- packages/plugin/tests/helpers/drawing-file.ts | 96 +++++ packages/plugin/tests/helpers/recipes.ts | 70 ++++ 44 files changed, 2099 insertions(+), 146 deletions(-) create mode 100644 packages/plugin/src/core/drawing/codec.ts create mode 100644 packages/plugin/src/features/sync/content/closure.ts create mode 100644 packages/plugin/src/features/sync/content/header.ts create mode 100644 packages/plugin/src/features/sync/content/keys.ts create mode 100644 packages/plugin/src/features/sync/content/load.ts create mode 100644 packages/plugin/src/features/sync/content/store.ts create mode 100644 packages/plugin/tests/core/crypto/described-envelope.test.ts create mode 100644 packages/plugin/tests/core/drawing/codec.test.ts create mode 100644 packages/plugin/tests/features/sync/content/load.test.ts create mode 100644 packages/plugin/tests/features/sync/content/roundtrip.test.ts create mode 100644 packages/plugin/tests/features/sync/content/store.test.ts create mode 100644 packages/plugin/tests/helpers/drawing-file.ts create mode 100644 packages/plugin/tests/helpers/recipes.ts diff --git a/.claude/rules/history.md b/.claude/rules/history.md index 01449e38..ed55211f 100644 --- a/.claude/rules/history.md +++ b/.claude/rules/history.md @@ -15,7 +15,7 @@ History is one encrypted record per push under `history/`, which GC thins into o ## 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 key and vault and while every blob it names exists (`stillLands`; past a thousand blobs, checked against one listing of `objects/`): 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. +- 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 key 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. @@ -52,14 +52,15 @@ History is one encrypted record per push under `history/`, which GC thins into o ## 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: `settledKeys` / `keysByAge` list them by age, `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 changed while 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. +- 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 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/` 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. +- 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/`, `pins/` and `history/` of its own space. +- Maintenance lists only `objects/`, `recipes/`, `chunks/`, `pins/` and `history/` of its own space; a reset deletes chunks after every root. ## Format fence diff --git a/.claude/rules/security.md b/.claude/rules/security.md index 5ec01bf9..c48f7e2d 100644 --- a/.claude/rules/security.md +++ b/.claude/rules/security.md @@ -35,6 +35,11 @@ Follows Obsidian's Developer Policies and Plugin Guidelines. Link model and limi - 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`). diff --git a/.claude/rules/structure.md b/.claude/rules/structure.md index 422def27..4f97f629 100644 --- a/.claude/rules/structure.md +++ b/.claude/rules/structure.md @@ -12,7 +12,7 @@ Paths in this file are relative to `packages/plugin/src/`. - `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`. Code moves here when a second feature needs it and it knows no feature. +- `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`). diff --git a/.claude/rules/sync-integrity.md b/.claude/rules/sync-integrity.md index 3fed7037..e371700c 100644 --- a/.claude/rules/sync-integrity.md +++ b/.claude/rules/sync-integrity.md @@ -15,6 +15,7 @@ Breaking one of these silently corrupts user data or publishes remote 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. - Upload before publish: a manifest naming objects never uploaded dangles, so a cancelled push publishes nothing (`pushPaths`; uploaded blobs stay). ## Scope and unreadable @@ -46,7 +47,7 @@ Breaking one of these silently corrupts user data or publishes remote deletions; - 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/`, `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. +- 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 diff --git a/packages/plugin/src/core/crypto/cipher.ts b/packages/plugin/src/core/crypto/cipher.ts index 19774a4f..acfa1526 100644 --- a/packages/plugin/src/core/crypto/cipher.ts +++ b/packages/plugin/src/core/crypto/cipher.ts @@ -7,7 +7,9 @@ import { } from "@/core/utils"; import { BLOB_VERSION, + BLOB_VERSION_DESCRIBED, BLOB_VERSION_GZIP, + DESCRIBED_HEADER_BYTES, GZIP_LENGTH_BYTES, GZIP_PAD_BYTES, GZIP_SAMPLE_BYTES, @@ -119,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", @@ -141,13 +154,15 @@ 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 { @@ -236,6 +251,61 @@ async function compressible(bytes: Uint8Array): Promise { ); } +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/core/crypto/constants.ts b/packages/plugin/src/core/crypto/constants.ts index 97bc18bb..714e6f8a 100644 --- a/packages/plugin/src/core/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). diff --git a/packages/plugin/src/core/crypto/index.ts b/packages/plugin/src/core/crypto/index.ts index c6971ade..cd3fd875 100644 --- a/packages/plugin/src/core/crypto/index.ts +++ b/packages/plugin/src/core/crypto/index.ts @@ -1,12 +1,15 @@ export { decryptBytes, + decryptDescribed, decryptJson, deriveKey, type EncryptionKey, encryptBytes, encryptCompressible, + encryptDescribed, encryptJson, importAesKey, + isDescribed, randomBytes, randomId, randomSecret, 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/core/drawing/format.ts b/packages/plugin/src/core/drawing/format.ts index 7442ed26..42807c0a 100644 --- a/packages/plugin/src/core/drawing/format.ts +++ b/packages/plugin/src/core/drawing/format.ts @@ -28,9 +28,12 @@ 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; export function isDrawing(text: string): boolean { if (!text.startsWith("---")) return false; @@ -40,9 +43,9 @@ export function isDrawing(text: string): boolean { 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 index fb6e340d..a5e5c05a 100644 --- a/packages/plugin/src/core/drawing/index.ts +++ b/packages/plugin/src/core/drawing/index.ts @@ -1,3 +1,9 @@ +export { + type DrawingCodec, + decodeDrawing, + encodeDrawing, + isDrawingCodec, +} from "./codec"; export { isDrawing, isElement, readDrawing, type SceneElement } from "./format"; export { mergeDrawings, mergeElements, wins } from "./merge"; export { sceneOfBytes } from "./scene"; diff --git a/packages/plugin/src/core/drawing/scene.ts b/packages/plugin/src/core/drawing/scene.ts index 6c4de091..924822e1 100644 --- a/packages/plugin/src/core/drawing/scene.ts +++ b/packages/plugin/src/core/drawing/scene.ts @@ -1,11 +1,14 @@ 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 diff --git a/packages/plugin/src/features/spaces/README.md b/packages/plugin/src/features/spaces/README.md index b6b9bf8c..463577e9 100644 --- a/packages/plugin/src/features/spaces/README.md +++ b/packages/plugin/src/features/spaces/README.md @@ -35,7 +35,7 @@ A share's location (endpoint, bucket, prefix) is pinned once: re-deriving it fro **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/`, `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. +**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 diff --git a/packages/plugin/src/features/sync/README.md b/packages/plugin/src/features/sync/README.md index ddcb10f5..4b9841e8 100644 --- a/packages/plugin/src/features/sync/README.md +++ b/packages/plugin/src/features/sync/README.md @@ -16,6 +16,7 @@ File sync of the vault and of each shared folder (a "space") against object stor | `automation/` | `features/sync/automation/scheduler.ts` (timer, backoff), `features/sync/automation/auto-push.ts` (bulk-deletion hold) | | `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 maintenance section | @@ -48,6 +49,10 @@ Uploads: the head vouches for a blob; this device's own unpublished uploads coun 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`); the upload-trust decisions stay in `engine.ts`. `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. + +A file of `CHUNK_THRESHOLD` (256 KB) or more may be stored in chunks: `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. + ## 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`). @@ -87,7 +92,7 @@ Windows: a blob younger than `SETTLED_AFTER_MS` (24 h) is never swept, GC sweeps ## 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 (`deep` also hashes it); deep clean removes unreachable settled objects. +- 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. diff --git a/packages/plugin/src/features/sync/apply/pull.ts b/packages/plugin/src/features/sync/apply/pull.ts index 927372be..31fdcbdc 100644 --- a/packages/plugin/src/features/sync/apply/pull.ts +++ b/packages/plugin/src/features/sync/apply/pull.ts @@ -6,12 +6,12 @@ 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 { objectKey } from "../remote/manifest"; import { EChangeType, type Manifest, type ManifestEntry } from "../types"; import { pullMoves, syncFolders } from "./pull-moves"; @@ -88,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/features/sync/changes/content.ts b/packages/plugin/src/features/sync/changes/content.ts index 6b04748ec31d8a3c8bc9bd1ec377c7525dce5994..4b4cb051bf15276dcdf0acae843aed1cfd6d7e8a 100644 GIT binary patch delta 107 zcmZ4EIn#ZD*+v&dM%8MCoczQT=lr~q)VvafT7|Tt{9FYkJw5$oh>$)=dU7;l(&o2} vEgX{@C50z069B6!4*?y-a#A}Lbn zd)`oDDhP)u%Xox}wqM5UQFC#6(k!fG9g0j51c?a12UajnFvDDViiBiy^yWx*N3~<7 zV#fu=pV7IpOdf&V(^&^3(o$xSEt8~u*i-X_@r-aq|ImNlw(ePb3oPATzXtAePbhg* zb|DqB%h7m(E4u^!mLD#Az7IP!s4UZ@Sc(ENEZ{~;A?@j;wT6_dlu;N%BxGx=Cu!#z Y=)GW2>2y8S*xE7=f9cw`-`4xt55`P`X#fBK diff --git a/packages/plugin/src/features/sync/constants.ts b/packages/plugin/src/features/sync/constants.ts index 17d8f34f..a18e6435 100644 --- a/packages/plugin/src/features/sync/constants.ts +++ b/packages/plugin/src/features/sync/constants.ts @@ -1,6 +1,9 @@ /** Remote object layout and engine-wide limits. */ 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/"; /** The 1.x change log: deleted after the first v3 push (`clearLegacyHistory`), never read. */ export const REMOTE_HISTORY_LOG_KEY = "history.json.enc"; 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..7a75df1e --- /dev/null +++ b/packages/plugin/src/features/sync/content/closure.ts @@ -0,0 +1,54 @@ +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[]; +} + +/** 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/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..992df26e --- /dev/null +++ b/packages/plugin/src/features/sync/content/load.ts @@ -0,0 +1,172 @@ +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 { type ChunkRef, type ContentHeader, readHeader } from "./header"; +import { chunkKey, isRecipeKey, readOrder } from "./keys"; + +export interface ContentSource { + storage: ObjectStorage; + key: EncryptionKey; +} + +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>(); + +/** + * 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, +): Promise { + const root = await fetchRoot(source.storage, hash, size); + return root && openContent(source, root.blob, hash, root.storageKey); +} + +/** 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, +): Promise { + const { codec, chunks, payload } = await content(() => + openRoot(source.key, blob, isRecipeKey(storageKey)), + ); + const stored = chunks ? await readChunks(source, chunks) : 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[], +): Promise { + const parts: Uint8Array[] = new Array(chunks.length); + await runWithConcurrency(chunks, CHUNK_READS, async ([id, size], index) => { + 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..4ec5677a --- /dev/null +++ b/packages/plugin/src/features/sync/content/store.ts @@ -0,0 +1,32 @@ +import { encryptCompressible, encryptDescribed } from "@/core/crypto"; +import { encodeDrawing } from "@/core/drawing"; +import { objectKey } from "./keys"; +import type { ContentSource } from "./load"; + +/** PUTs `bytes` as the object named `hash`. Whether the storage already holds it is the caller's call. */ +export async function storeContent( + source: ContentSource, + hash: string, + bytes: Uint8Array, +): Promise { + await source.storage.put(objectKey(hash), await seal(source.key, bytes)); +} + +async function seal( + key: ContentSource["key"], + bytes: Uint8Array, +): Promise { + const drawing = encodeDrawing(bytes); + if (drawing) { + try { + return await encryptDescribed( + key, + { codec: drawing.codec }, + drawing.stored, + ); + } catch { + // No CompressionStream here: a plain blob is one every peer reads. + } + } + return encryptCompressible(key, bytes); +} diff --git a/packages/plugin/src/features/sync/engine.ts b/packages/plugin/src/features/sync/engine.ts index 05dd9383..b1b25e3e 100644 --- a/packages/plugin/src/features/sync/engine.ts +++ b/packages/plugin/src/features/sync/engine.ts @@ -1,10 +1,6 @@ import type { DataAdapter } from "obsidian"; import { DEFAULT_CONCURRENCY } from "@/core/constants"; -import { - type EncryptionKey, - encryptCompressible, - sha256Hex, -} from "@/core/crypto"; +import { type EncryptionKey, sha256Hex } from "@/core/crypto"; import { sceneOfBytes } from "@/core/drawing"; import { reportWarning } from "@/core/shared"; import type { VaultIndex } from "@/core/vault"; @@ -16,6 +12,8 @@ import { runWithFileConcurrency } from "./changes/file-concurrency"; import { entryAt, sortedByPath } from "./changes/records"; import { skipUnholdableNames } from "./changes/remote-names"; import { REMOTE_OBJECTS_PREFIX } from "./constants"; +import { objectKey } from "./content/keys"; +import { storeContent } from "./content/store"; import { untrackedDir } from "./history/changes"; import { publishManifestWithHistory } from "./history/publish"; import type { HistoryConfig } from "./history/types"; @@ -29,7 +27,6 @@ import { ownedFiles } from "./remote/foreign"; import { buildManifest, fetchRemoteManifest, - objectKey, reconcileRemoteAgainstBaseline, } from "./remote/manifest"; import { assertSpacePresent, type Space } from "./remote/space"; @@ -216,10 +213,7 @@ export async function storeObject( ) { return hash; } - await deps.storage.put( - objectKey(hash), - await encryptCompressible(deps.key, bytes), - ); + await storeContent(deps, hash, bytes); rememberUpload(deps.storage, hash); return hash; } @@ -352,8 +346,7 @@ async function uploadObject( if (verifyHash !== entry.hash) { throw new Error(`Hash mismatch while uploading ${entry.path}`); } - const blob = await encryptCompressible(deps.key, plaintext); - await deps.storage.put(objectKey(entry.hash), blob); + await storeContent(deps, entry.hash, plaintext); rememberUpload(deps.storage, entry.hash); } diff --git a/packages/plugin/src/features/sync/history/publish.ts b/packages/plugin/src/features/sync/history/publish.ts index 79a13213..66200da3 100644 --- a/packages/plugin/src/features/sync/history/publish.ts +++ b/packages/plugin/src/features/sync/history/publish.ts @@ -3,8 +3,9 @@ import 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 } from "../constants"; -import { objectKey, publishManifestWithGuard } from "../remote/manifest"; +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, @@ -110,13 +111,24 @@ async function stillLands( own: Unwritten, ): Promise { if (record.key !== own.key || record.vaultId !== own.vaultId) 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 stored = new Set(await storage.list(REMOTE_OBJECTS_PREFIX)); - return record.hashes.every((hash) => stored.has(objectKey(hash))); + 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) => { - if (!(await storage.exists(objectKey(hash)))) missing = true; + 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/sweep.ts b/packages/plugin/src/features/sync/history/sweep.ts index 33280ab5..85c84ce2 100644 --- a/packages/plugin/src/features/sync/history/sweep.ts +++ b/packages/plugin/src/features/sync/history/sweep.ts @@ -4,11 +4,15 @@ 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 { fetchRemoteManifest, objectKey } from "../remote/manifest"; -import { SETTLED_AFTER_MS, settledKeys } from "../remote/uploads"; +import { chunksNamed } 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"; @@ -80,8 +84,8 @@ export function isSettled({ modified }: ListedObject): boolean { } /** - * Deletes settled objects nothing reaches (HEAD, a history record, a pin), never one a GC run freed within the - * last day; needs a backend that can list. + * 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, @@ -117,27 +121,95 @@ export async function sweepObjects( } // An unreadable settled file only leaks its blobs to the next deep clean. const freed = options.freedOnly - ? new Set( - [...(await readCandidates(storage, key, due)).hashes].map(objectKey), - ) + ? (await readCandidates(storage, key, due)).hashes : null; - const kept = new Set([...reachable.hashes.keys()].map(objectKey)); + 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((storageKey) => kept.has(storageKey))) { + if (freed && [...freed].every((hash) => kept.has(hash))) { await deleteFiles(storage, due); return 0; } - const objectKeys = await settledKeys(storage, REMOTE_OBJECTS_PREFIX); + const [objects, recipes, chunks] = await Promise.all([ + listDated(storage, REMOTE_OBJECTS_PREFIX), + listDated(storage, REMOTE_RECIPES_PREFIX), + listDated(storage, REMOTE_CHUNKS_PREFIX), + ]); + + 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; +} - // Another device publishing during the listing makes its new objects look like orphans: bail. +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) { + 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 during the listing needs its own check. + // 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( @@ -153,29 +225,6 @@ export async function sweepObjects( "Another device wrote file history while cleaning; nothing was deleted. Try again.", ); } - - 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(objectKey(hash)); - const orphans = objectKeys.filter( - (storageKey) => - !kept.has(storageKey) && (freed === null || freed.has(storageKey)), - ); - let done = 0; - await runWithConcurrency( - orphans, - options.concurrency ?? DEFAULT_CONCURRENCY, - async (storageKey) => { - await storage.delete(storageKey); - options.onProgress?.(++done, orphans.length); - }, - ); - await deleteFiles(storage, due); - return orphans.length; } function deleteFiles( diff --git a/packages/plugin/src/features/sync/remote/manifest.ts b/packages/plugin/src/features/sync/remote/manifest.ts index 44641cc7..35584997 100644 --- a/packages/plugin/src/features/sync/remote/manifest.ts +++ b/packages/plugin/src/features/sync/remote/manifest.ts @@ -6,7 +6,7 @@ import { randomId, } from "@/core/crypto"; import type { ConditionalRead, ObjectStorage } from "@/features/storage"; -import { MANIFEST_VERSION, REMOTE_OBJECTS_PREFIX } from "../constants"; +import { MANIFEST_VERSION } from "../constants"; import { defaultDeviceName } from "../identity/device"; import type { LocalSnapshot, Manifest } from "../types"; import { manifestToSpace, manifestToVault } from "./space-paths"; @@ -204,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/features/sync/remote/reset.ts b/packages/plugin/src/features/sync/remote/reset.ts index fd133b15..59107c07 100644 --- a/packages/plugin/src/features/sync/remote/reset.ts +++ b/packages/plugin/src/features/sync/remote/reset.ts @@ -2,10 +2,12 @@ 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_HISTORY_PREFIX, REMOTE_OBJECTS_PREFIX, REMOTE_PINS_PREFIX, + REMOTE_RECIPES_PREFIX, } from "../constants"; import type { EngineDependencies } from "../engine"; @@ -19,25 +21,25 @@ export async function resetRemoteStorage( onProgress?: (done: number, total: number) => void, ): Promise { // History must go with its objects: records and pins left behind would name what is gone. - const [objectKeys, pinKeys, historyKeys] = await Promise.all([ + 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, - ...historyKeys, - ]), + 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/features/sync/remote/uploads.ts b/packages/plugin/src/features/sync/remote/uploads.ts index 19bbeaaf..f94a4323 100644 --- a/packages/plugin/src/features/sync/remote/uploads.ts +++ b/packages/plugin/src/features/sync/remote/uploads.ts @@ -1,4 +1,4 @@ -import type { ObjectStorage } from "@/features/storage"; +import type { ListedObject, ObjectStorage } from "@/features/storage"; /** * Blobs uploaded here but not yet in a published manifest, so an unpublished push resumes. Any other non-head @@ -37,32 +37,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( +export async function listDated( 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( - 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/features/sync/runtime/maintenance.ts b/packages/plugin/src/features/sync/runtime/maintenance.ts index 61bf08a5..87e8c8b7 100644 --- a/packages/plugin/src/features/sync/runtime/maintenance.ts +++ b/packages/plugin/src/features/sync/runtime/maintenance.ts @@ -1,13 +1,21 @@ import { DEFAULT_CONCURRENCY } from "@/core/constants"; -import { decryptBytes, type EncryptionKey, sha256Hex } from "@/core/crypto"; +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"; -import { objectKey } from "../remote/manifest"; export type MaintenanceOptions = Omit; @@ -37,26 +45,41 @@ export async function verifyRemote( ); } - const list = [...reachable.hashes.keys()]; + 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; - storage.prepareReads?.(list.map(objectKey)); + await prepareContent(source, list); 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); + (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); }, 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/core/crypto/failed-batch.test.ts b/packages/plugin/tests/core/crypto/failed-batch.test.ts index f0aa09c0..c422ece6 100644 --- a/packages/plugin/tests/core/crypto/failed-batch.test.ts +++ b/packages/plugin/tests/core/crypto/failed-batch.test.ts @@ -9,8 +9,8 @@ import { afterEach, describe, expect, it, vi } from "vitest"; 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"; -import { objectKey } from "@/features/sync/remote/manifest"; useEncryptionKey(); afterEach(() => vi.restoreAllMocks()); 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/features/sync/apply/pull-hint.test.ts b/packages/plugin/tests/features/sync/apply/pull-hint.test.ts index b674ce11..e429af2f 100644 --- a/packages/plugin/tests/features/sync/apply/pull-hint.test.ts +++ b/packages/plugin/tests/features/sync/apply/pull-hint.test.ts @@ -2,8 +2,8 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; import { TestSession, useEncryptionKey } from "@tests/helpers/session"; import { describe, expect, it } from "vitest"; import { pullPaths } from "@/features/sync/apply/pull"; +import { objectKey } from "@/features/sync/content/keys"; import { compare, pushPaths } from "@/features/sync/engine"; -import { objectKey } from "@/features/sync/remote/manifest"; class HintedStorage extends FakeStorage { readonly hints: string[][] = []; diff --git a/packages/plugin/tests/features/sync/changes/content-cache.test.ts b/packages/plugin/tests/features/sync/changes/content-cache.test.ts index ac5327d6..44171f16 100644 --- a/packages/plugin/tests/features/sync/changes/content-cache.test.ts +++ b/packages/plugin/tests/features/sync/changes/content-cache.test.ts @@ -11,7 +11,7 @@ import { loadRemoteText, textToBytes, } from "@/features/sync/changes/content"; -import { objectKey } from "@/features/sync/remote/manifest"; +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/features/sync/content/load.test.ts b/packages/plugin/tests/features/sync/content/load.test.ts new file mode 100644 index 00000000..be1ea439 --- /dev/null +++ b/packages/plugin/tests/features/sync/content/load.test.ts @@ -0,0 +1,347 @@ +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 { beforeAll, describe, expect, it, vi } from "vitest"; +import { + 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"; + +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); + }); +}); 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..6a5b3760 --- /dev/null +++ b/packages/plugin/tests/features/sync/content/store.test.ts @@ -0,0 +1,90 @@ +import { + bytesOf, + compressedDrawing, + plainDrawing, +} from "@tests/helpers/drawing-file"; +import { FakeStorage } from "@tests/helpers/fake-storage"; +import { afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { + decryptDescribed, + deriveKey, + type EncryptionKey, + encryptCompressible, + sha256Hex, +} from "@/core/crypto"; +import { objectKey } from "@/features/sync/content/keys"; +import { loadContent } from "@/features/sync/content/load"; +import { storeContent } from "@/features/sync/content/store"; + +let key: EncryptionKey; +beforeAll(async () => { + key = await deriveKey("pw", new Uint8Array(16)); +}); +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); + }); +}); diff --git a/packages/plugin/tests/features/sync/history/gc.test.ts b/packages/plugin/tests/features/sync/history/gc.test.ts index cdc24735..25f3f3be 100644 --- a/packages/plugin/tests/features/sync/history/gc.test.ts +++ b/packages/plugin/tests/features/sync/history/gc.test.ts @@ -15,6 +15,7 @@ import { 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 { @@ -22,7 +23,6 @@ import { resolveSnapshotManifest, } from "@/features/sync/history/query"; import { readHistory } from "@/features/sync/history/remote"; -import { objectKey } from "@/features/sync/remote/manifest"; import { deepCleanOrphans, verifyRemote, diff --git a/packages/plugin/tests/features/sync/history/publish.test.ts b/packages/plugin/tests/features/sync/history/publish.test.ts index 7c27d6f4..be527c32 100644 --- a/packages/plugin/tests/features/sync/history/publish.test.ts +++ b/packages/plugin/tests/features/sync/history/publish.test.ts @@ -3,9 +3,9 @@ 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 { objectKey } from "@/features/sync/remote/manifest"; import { resetRemoteStorage } from "@/features/sync/remote/reset"; let key: EncryptionKey; @@ -117,13 +117,28 @@ describe("publishManifestWithHistory", () => { expect(await storage.list("history/")).toEqual([pushKey("s2")]); }); - it("checks a record naming more than a listing page with one listing, not a probe per blob", async () => { + 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, @@ -139,7 +154,7 @@ describe("publishManifestWithHistory", () => { await publishManifestWithHistory(storage, key, "", next, big, history); expect(storage.existsCalls).toBe(0); - expect(storage.listCalls).toBe(1); + expect(storage.listCalls).toBe(2); expect(storage.map.has(pushKey("big1"))).toBe(true); expect(storage.map.has(pushKey("big2"))).toBe(true); }); diff --git a/packages/plugin/tests/features/sync/history/sweep.test.ts b/packages/plugin/tests/features/sync/history/sweep.test.ts index 8ccfe8d8..08d12327 100644 --- a/packages/plugin/tests/features/sync/history/sweep.test.ts +++ b/packages/plugin/tests/features/sync/history/sweep.test.ts @@ -1,10 +1,11 @@ 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 { objectKey } from "@/features/sync/remote/manifest"; import { SETTLED_AFTER_MS } from "@/features/sync/remote/uploads"; let key: EncryptionKey; @@ -83,3 +84,112 @@ describe("sweepObjects freedOnly", () => { expect([...storage.map.keys()].sort()).toEqual(before); }); }); + +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/features/sync/remote/foreign.test.ts b/packages/plugin/tests/features/sync/remote/foreign.test.ts index ee399744..258b5dfa 100644 --- a/packages/plugin/tests/features/sync/remote/foreign.test.ts +++ b/packages/plugin/tests/features/sync/remote/foreign.test.ts @@ -2,6 +2,7 @@ import { TestSession, useEncryptionKey } from "@tests/helpers/session"; 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"; @@ -10,7 +11,6 @@ import { heldShareBases, ownedFiles, } from "@/features/sync/remote/foreign"; -import { objectKey } from "@/features/sync/remote/manifest"; import { SETTLED_AFTER_MS } from "@/features/sync/remote/uploads"; import { deepCleanOrphans } from "@/features/sync/runtime/maintenance"; import { createScopePolicy } from "@/features/sync/scope/scope"; diff --git a/packages/plugin/tests/features/sync/remote/reset.test.ts b/packages/plugin/tests/features/sync/remote/reset.test.ts index 63a81567..78657159 100644 --- a/packages/plugin/tests/features/sync/remote/reset.test.ts +++ b/packages/plugin/tests/features/sync/remote/reset.test.ts @@ -1,5 +1,5 @@ import { FakeStorage } from "@tests/helpers/fake-storage"; -import { beforeAll, describe, expect, it } from "vitest"; +import { beforeAll, describe, expect, it, vi } from "vitest"; import { REMOTE_MANIFEST_KEY } from "@/core/constants"; import { deriveKey, type EncryptionKey } from "@/core/crypto/cipher"; import { @@ -8,8 +8,8 @@ import { REMOTE_PINS_PREFIX, REMOTE_SALT_KEY, } from "@/features/sync/constants"; +import { chunkKey, objectKey, recipeKey } from "@/features/sync/content/keys"; import { pushKey } from "@/features/sync/history/remote"; -import { objectKey } from "@/features/sync/remote/manifest"; import { resetRemoteStorage } from "@/features/sync/remote/reset"; let key: EncryptionKey; @@ -23,6 +23,8 @@ 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); @@ -45,6 +47,21 @@ describe("resetRemoteStorage", () => { 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/runtime/maintenance.test.ts b/packages/plugin/tests/features/sync/runtime/maintenance.test.ts index 62cda5e3..24551f6c 100644 --- a/packages/plugin/tests/features/sync/runtime/maintenance.test.ts +++ b/packages/plugin/tests/features/sync/runtime/maintenance.test.ts @@ -1,3 +1,4 @@ +import { bytesOf, compressedDrawing } from "@tests/helpers/drawing-file"; import { FakeStorage } from "@tests/helpers/fake-storage"; import { manifestOf, @@ -6,17 +7,27 @@ import { 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 { objectKey } from "@/features/sync/remote/manifest"; +import { + CHUNK_THRESHOLD, + chunkKey, + objectKey, +} from "@/features/sync/content/keys"; +import { storeContent } from "@/features/sync/content/store"; import { deepCleanOrphans, verifyRemote, @@ -72,6 +83,132 @@ describe("verifyRemote", () => { }); }); +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[] 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/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 `