From 8d668d2bf201f5603c34453c1a3050aa5a8eb181 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 22:40:08 +0000 Subject: [PATCH 1/8] Architecture: the pages grouped in folders by area of the code `core/` for the engine and the libraries, `interface/` for the ui crate (the frame, the backend, the window, the look), `notes/`, `http/` and `tools/` for the features, `project/` for the logs, the tests, the releases and the site. Moved with `git mv`; every link and path to a page follows. No text changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BbVs5tCyTr9AasGra3Zzg3 --- .claude/skills/desktop-e2e-testing/SKILL.md | 2 +- .../skills/devnotes-security-review/SKILL.md | 2 +- .claude/skills/egui-ui/SKILL.md | 2 +- .claude/skills/performance-profiling/SKILL.md | 2 +- .claude/skills/platform-integration/SKILL.md | 2 +- .github/workflows/ci.yml | 2 +- .github/workflows/website.yml | 2 +- CONTRIBUTING.md | 4 +-- Cargo.toml | 2 +- crates/ui/src/app/perf.rs | 2 +- docs/architecture/README.md | 26 +++++++++---------- docs/architecture/{ => core}/engine.md | 4 +-- docs/architecture/{ => core}/libraries.md | 2 +- docs/architecture/{ => interface}/backend.md | 2 +- .../{interface.md => interface/frame.md} | 2 +- .../look.md} | 2 +- docs/architecture/{ => interface}/window.md | 2 +- .../board.md} | 2 +- docs/architecture/overview.md | 4 +-- docs/architecture/{ => project}/logs.md | 2 +- docs/architecture/{ => project}/releasing.md | 2 +- docs/architecture/{ => project}/testing.md | 2 +- docs/architecture/{ => project}/website.md | 2 +- docs/architecture/{ => tools}/tools.md | 2 +- docs/releasing.md | 4 +-- 25 files changed, 41 insertions(+), 41 deletions(-) rename docs/architecture/{ => core}/engine.md (99%) rename docs/architecture/{ => core}/libraries.md (99%) rename docs/architecture/{ => interface}/backend.md (99%) rename docs/architecture/{interface.md => interface/frame.md} (99%) rename docs/architecture/{i18n-accessibility-theming.md => interface/look.md} (99%) rename docs/architecture/{ => interface}/window.md (99%) rename docs/architecture/{spaces-folders-board.md => notes/board.md} (99%) rename docs/architecture/{ => project}/logs.md (99%) rename docs/architecture/{ => project}/releasing.md (99%) rename docs/architecture/{ => project}/testing.md (99%) rename docs/architecture/{ => project}/website.md (99%) rename docs/architecture/{ => tools}/tools.md (99%) diff --git a/.claude/skills/desktop-e2e-testing/SKILL.md b/.claude/skills/desktop-e2e-testing/SKILL.md index 01b56360..93615b41 100644 --- a/.claude/skills/desktop-e2e-testing/SKILL.md +++ b/.claude/skills/desktop-e2e-testing/SKILL.md @@ -5,7 +5,7 @@ description: Use when writing, running or debugging an end-to-end journey of the # Desktop e2e -`CONTRIBUTING.md` → "The end-to-end journeys" says how to run, watch, mend and extend them; `docs/architecture/testing.md` → "The journeys, on the assembled window" lists the fourteen and what the driver does. What is worth knowing before touching one: +`CONTRIBUTING.md` → "The end-to-end journeys" says how to run, watch, mend and extend them; `docs/architecture/project/testing.md` → "The journeys, on the assembled window" lists the fourteen and what the driver does. What is worth knowing before touching one: - Build the flavour first, every time `crates/` changed: `cargo build -p app --features e2e --target-dir target/e2e` (its own target directory: no other build overwrites it). Then `cargo test -p e2e --test NN_name` for one journey, `cargo test -p e2e` for all — what CI runs on each OS. `cargo test --workspace` runs with `--exclude e2e`. - A journey is `e2e/tests/NN_name.rs`: one `#[test]` of named `step`s, what the person does then what they see. A nominal path goes into the journey it belongs to, as a step; a new file only for a new goal (15 at most). Branches, edge cases and error codes are unit tests'. diff --git a/.claude/skills/devnotes-security-review/SKILL.md b/.claude/skills/devnotes-security-review/SKILL.md index ddd72012..bd0028de 100644 --- a/.claude/skills/devnotes-security-review/SKILL.md +++ b/.claude/skills/devnotes-security-review/SKILL.md @@ -17,4 +17,4 @@ Checklist on the change (`git diff main...`, and `git diff HEAD` for what is not 6. **Dependencies**: see `dependency-audit` if `Cargo.toml`/`package.json` changed. 7. Report findings by severity with file:line; state what you did not check. Do not auto-fix crypto findings. -Reference: `docs/architecture/libraries.md` → "Encryption at rest". +Reference: `docs/architecture/core/libraries.md` → "Encryption at rest". diff --git a/.claude/skills/egui-ui/SKILL.md b/.claude/skills/egui-ui/SKILL.md index 4c69b2bb..4e3853a0 100644 --- a/.claude/skills/egui-ui/SKILL.md +++ b/.claude/skills/egui-ui/SKILL.md @@ -19,7 +19,7 @@ D32): read a screen's component and its SCSS before changing it, and its capture or the index (reads included); `compute` for pure work; `spawn` for the network (D11). Never `block_on`, never a lock taken while drawing. Only exception: a pure core function whose input the screen bounds, under 1 ms, called directly but still through `api/` (D12). Every concurrency - rule is in `docs/architecture/backend.md` → "The concurrency rules"; one that is not there does not exist. + rule is in `docs/architecture/interface/backend.md` → "The concurrency rules"; one that is not there does not exist. - A data rule (what a `{{field}}`, a variable name, a heading is) belongs to the core: `text`, `richtext`, `drawing` take its result as an argument and never redefine it (D10). - Drawing reads a screen's state (`&…State`) and may change its view (`&mut …View`: text being diff --git a/.claude/skills/performance-profiling/SKILL.md b/.claude/skills/performance-profiling/SKILL.md index 910ddac5..229aa73c 100644 --- a/.claude/skills/performance-profiling/SKILL.md +++ b/.claude/skills/performance-profiling/SKILL.md @@ -9,4 +9,4 @@ description: Use when a DevNotes operation feels slow (query_notes, search, boar 2. Known facts: one lock serialises commands, and `query_notes` holds it for ~90 % of its cost; lists send previews (`PREVIEW_LINES`); side tables are read by bound ids up to 500, else by subquery; decrypting sealed fields dominates. 3. Fix at the owning layer (the core for data; a `QueryCell` compared by value, one call in flight; virtualise past ~100 rows; cache a costly `LayoutJob`; nothing costly in the frame). 4. Keep `autobenches = false`, `bench = false` and no `Drop` on `Corpus` (load-bearing). -5. Report before/after numbers on the same machine; update the table in `docs/architecture/testing.md` → "Benchmarks" only for durable changes. +5. Report before/after numbers on the same machine; update the table in `docs/architecture/project/testing.md` → "Benchmarks" only for durable changes. diff --git a/.claude/skills/platform-integration/SKILL.md b/.claude/skills/platform-integration/SKILL.md index a8bd2639..23618929 100644 --- a/.claude/skills/platform-integration/SKILL.md +++ b/.claude/skills/platform-integration/SKILL.md @@ -15,4 +15,4 @@ description: Use when adding or changing what DevNotes asks of the operating sys 6. **The `e2e` flavour** (`--features e2e`) adds eframe's inspection port, the software adapter and two doors — `--action ` and `DEVNOTES_E2E_DIALOG` — and nothing else; it takes no global key. A release build of it does not compile. Never widen it. 7. Test in the module: a temporary directory for anything on disk; a real second process only where the subject is processes (`instance`). -**Verify**: `cargo clippy --workspace --all-targets --all-features -- -D warnings`, `cargo test --workspace --exclude e2e`, then run the app on a temporary profile (`cargo run -p app -- --profile `) on each OS the change touches, and say which ones did not run. Reference: `docs/architecture/engine.md` → "The binary, its profile and its window". +**Verify**: `cargo clippy --workspace --all-targets --all-features -- -D warnings`, `cargo test --workspace --exclude e2e`, then run the app on a temporary profile (`cargo run -p app -- --profile `) on each OS the change touches, and say which ones did not run. Reference: `docs/architecture/core/engine.md` → "The binary, its profile and its window". diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5312b059..d8f0aba7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -99,7 +99,7 @@ jobs: - *stop-the-run - # The showcase site (docs/architecture/website.md → "The website"): its own project and lockfile. The + # The showcase site (docs/architecture/project/website.md → "The website"): its own project and lockfile. The # build fetches the latest release and asks GitHub for every download link. website: name: Website diff --git a/.github/workflows/website.yml b/.github/workflows/website.yml index 0a945a8b..4075cc7f 100644 --- a/.github/workflows/website.yml +++ b/.github/workflows/website.yml @@ -2,7 +2,7 @@ name: Website # devnotes.fr: the site built from `website/` and `docs/content/`, pushed as the whole content of # one commit to the `main` of `vmillet-dev/devnotes-website`, whose webhook deploys it -# (docs/architecture/website.md → "The website"). Two things change what it shows: a push to `main` that +# (docs/architecture/project/website.md → "The website"). Two things change what it shows: a push to `main` that # touches its sources, and a release, whose files the download page names. The second needs the # run that follows `Release`: what that workflow pushes with its own token triggers nothing. on: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8227f66f..1edb9b5c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -30,7 +30,7 @@ A debug build writes its log on the terminal from `debug` up, a release from `in the profile's `logs/` keeps warnings and errors, each after the lines that led to it. `DEVNOTES_LOG` changes the levels for one run, in `flexi_logger`'s syntax (`DEVNOTES_LOG=engine=trace,ui::backend=debug cargo run -p app -- …`); what a line may say is in -[docs/architecture/logs.md](docs/architecture/logs.md). +[docs/architecture/project/logs.md](docs/architecture/project/logs.md). Node.js 24 runs the release scripts, which have no dependency; nothing is installed at the root. The website has its own project in `website/`. @@ -128,7 +128,7 @@ a third time, never for one step. A control without an `author_id` gets one thro | ---------------------------------- | ---------------------------------------------------------------------------- | | `node --test "scripts/*.test.mjs"` | The release scripts' tests, and the architecture wiki's references and links | | `node scripts/prettier.mjs` | Copies the Prettier compiled in into `crates/text/prettier` | -| `cargo bench -p engine` | The core's benchmarks (not in CI; see `docs/architecture/testing.md`) | +| `cargo bench -p engine` | The core's benchmarks (not in CI; see `docs/architecture/project/testing.md`) | | `cargo run -p app --example icons` | Redraws `crates/app/icons/` from `devnotes.svg` | ## The layout diff --git a/Cargo.toml b/Cargo.toml index f18a6882..f79be74e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -130,7 +130,7 @@ opt-level = 3 # Speed first: "s" or 2 make the binary smaller and the core slower (a query over 8000 notes # +37 % or +7 %), and per-crate levels do not reach Rust code under fat LTO. No unwinding: a -# panic ends the process from its hook (D18). The figures: `docs/architecture/releasing.md` +# panic ends the process from its hook (D18). The figures: `docs/architecture/project/releasing.md` # → "The release binary". [profile.release] lto = true diff --git a/crates/ui/src/app/perf.rs b/crates/ui/src/app/perf.rs index 32222a6f..864bee7f 100644 --- a/crates/ui/src/app/perf.rs +++ b/crates/ui/src/app/perf.rs @@ -1,4 +1,4 @@ -//! The journeys `docs/architecture/testing.md` keeps the figures of (« The window on the reference +//! The journeys `docs/architecture/project/testing.md` keeps the figures of (« The window on the reference //! corpora ») through the real application, without a window: a frame here is the pass and its //! tessellation, CPU only, the AccessKit tree a person without a screen reader never pays included. //! Nothing runs unless `DEVNOTES_PERF` names a profile written by the `reference_profile` bench; it diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 25abce70..e5f27ed0 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -9,27 +9,27 @@ For build/run instructions see [CONTRIBUTING](../../CONTRIBUTING.md). | ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | | [Overview](overview.md) | the crates, the source tree, a feature laid out across them | a crate, a module, where a feature goes | | [Decisions](decisions.md) | D1 onwards, in force | anything a decision names | -| [Interface (egui)](interface.md) | where a file goes, no router, drawing, state and actions, the editing core, rendering, the keyboard, highlighting, Prettier | a screen, a widget, a key | -| [Backend and events](backend.md) | `ui::api`, the three queues, a frame and its actions, the notifiers, the widget kit, errors, the language, service functions, validation | a call to the core, a service function | +| [Interface (egui)](interface/frame.md) | where a file goes, no router, drawing, state and actions, the editing core, rendering, the keyboard, highlighting, Prettier | a screen, a widget, a key | +| [Backend and events](interface/backend.md) | `ui::api`, the three queues, a frame and its actions, the notifiers, the widget kit, errors, the language, service functions, validation | a call to the core, a service function | | [Kinds of note](notes/kinds.md) | snippet, Note, todo list, Calcul sheet, Dessin | what a kind stores or shows | | [Cards and lists](notes/cards.md) | the notes' state, sections, a card and its menu, the header row, the canvas and its keyboard | the canvas or a card | | [Editing notes](notes/editing.md) | the editor, creation, revisions, the trash and undo, bulk actions, reordering, `{{fields}}`, tags, attachments | the editor, an operation on notes | -| [Spaces, folders and the board](spaces-folders-board.md) | the library rail, the space switcher, folders, the board, descending into a folder | the rail, a folder, the board | +| [Spaces, folders and the board](notes/board.md) | the library rail, the space switcher, folders, the board, descending into a folder | the rail, a folder, the board | | [HTTP: requests and their answers](http/requests.md) | the rail, a request's tab, sending and the answer, history, GraphQL, WebSocket, the cookie jar, collections on the disk | a request or its answer | | [HTTP: environments, code and scripts](http/environments-and-scripts.md) | environments and globals, variables, generated code, request scripts | a variable, a script, a code target | | [HTTP: the area on screen](http/drawn.md) | how the HTTP area is drawn, leaving with requests not saved | the HTTP area's layout | -| [Tools](tools.md) | the tools' contract, the JSON explorer and visualiser | a tool | -| [The window and its menus](window.md) | the title bar, the chrome, motion, the theme, the palette, « Fichier », preferences, shortcuts, help, the first launch, the update prompt | anything around the areas | -| [Libraries](libraries.md) | encryption at rest and the gate, several libraries, the two preference scopes, the copies, attachments, import and export | the vault, a library, a backup, a transfer | -| [The core](engine.md) | the engine and its binary, the notes index, persistence, the shared services | the engine, the schema, the index | -| [Language, accessibility and theming](i18n-accessibility-theming.md) | translations, the accessibility floor, the theme tokens | a string, a colour, a size | -| [Updates and releases](releasing.md) | the updater, the release workflow, the release binary, how far back an upgrade reaches | a release, a package, the updater | -| [Logs](logs.md) | the three outputs and their levels, what a line may say, `DEVNOTES_LOG` | a log line, a level | -| [Testing](testing.md) | benchmarks and their figures, the Rust tests, the interface tests, the journeys | a test, a benchmark | -| [The website](website.md) | devnotes.fr, its pages and how it is published | the site | +| [Tools](tools/tools.md) | the tools' contract, the JSON explorer and visualiser | a tool | +| [The window and its menus](interface/window.md) | the title bar, the chrome, motion, the theme, the palette, « Fichier », preferences, shortcuts, help, the first launch, the update prompt | anything around the areas | +| [Libraries](core/libraries.md) | encryption at rest and the gate, several libraries, the two preference scopes, the copies, attachments, import and export | the vault, a library, a backup, a transfer | +| [The core](core/engine.md) | the engine and its binary, the notes index, persistence, the shared services | the engine, the schema, the index | +| [Language, accessibility and theming](interface/look.md) | translations, the accessibility floor, the theme tokens | a string, a colour, a size | +| [Updates and releases](project/releasing.md) | the updater, the release workflow, the release binary, how far back an upgrade reaches | a release, a package, the updater | +| [Logs](project/logs.md) | the three outputs and their levels, what a line may say, `DEVNOTES_LOG` | a log line, a level | +| [Testing](project/testing.md) | benchmarks and their figures, the Rust tests, the interface tests, the journeys | a test, a benchmark | +| [The website](project/website.md) | devnotes.fr, its pages and how it is published | the site | The procedure of a release is [docs/releasing.md](../releasing.md); what the person reads is -[docs/content/](../content/). +[docs/content/](../content). ## How to read them diff --git a/docs/architecture/engine.md b/docs/architecture/core/engine.md similarity index 99% rename from docs/architecture/engine.md rename to docs/architecture/core/engine.md index 8ec8632c..998ba415 100644 --- a/docs/architecture/engine.md +++ b/docs/architecture/core/engine.md @@ -1,6 +1,6 @@ # The core -The engine and the binary that hosts it, the in-memory index of notes, persistence in SQLite, and the services every feature shares. [Home](README.md) +The engine and the binary that hosts it, the in-memory index of notes, persistence in SQLite, and the services every feature shares. [Home](../README.md) ## The engine and its host @@ -374,7 +374,7 @@ colour, created_at)` and `notes.folder_id` points into it. ⚠️ The column was impossible to order. - **Deletion is a column, not a `DELETE`.** `notes.deleted_at` (the `trash_and_attachments` migration) is `NULL` for a live note, which lets the index be partial and every read filter - on `deleted_at IS NULL`. See [The trash](notes/editing.md#the-trash-and-undoing-a-deletion) for what that + on `deleted_at IS NULL`. See [The trash](../notes/editing.md#the-trash-and-undoing-a-deletion) for what that costs and buys. - **Attachment bytes are not in the database.** The `attachments` table holds a record; the file sits in the library's `attachments/`. A base growing by 10 MB per screenshot would diff --git a/docs/architecture/libraries.md b/docs/architecture/core/libraries.md similarity index 99% rename from docs/architecture/libraries.md rename to docs/architecture/core/libraries.md index 813ac282..38646d2b 100644 --- a/docs/architecture/libraries.md +++ b/docs/architecture/core/libraries.md @@ -1,6 +1,6 @@ # Libraries -A library on the disk: encryption at rest and its gate, several libraries and their registry, the two scopes of preference, the copies, attachments and import/export. [Home](README.md) +A library on the disk: encryption at rest and its gate, several libraries and their registry, the two scopes of preference, the copies, attachments and import/export. [Home](../README.md) ## Encryption at rest diff --git a/docs/architecture/backend.md b/docs/architecture/interface/backend.md similarity index 99% rename from docs/architecture/backend.md rename to docs/architecture/interface/backend.md index eecd698c..8b0112d2 100644 --- a/docs/architecture/backend.md +++ b/docs/architecture/interface/backend.md @@ -1,6 +1,6 @@ # Backend and events (interface ↔ core) -How the window calls the core and gets its answers: the three queues, frames and actions, notifiers, the widget kit, errors, the language, service functions and validation. [Home](README.md) +How the window calls the core and gets its answers: the three queues, frames and actions, notifiers, the widget kit, errors, the language, service functions and validation. [Home](../README.md) The interface calls the core in the same process, through **one façade**, `ui::api` — the only place that names an engine function, one file per feature, each function choosing its queue diff --git a/docs/architecture/interface.md b/docs/architecture/interface/frame.md similarity index 99% rename from docs/architecture/interface.md rename to docs/architecture/interface/frame.md index 3f5461f1..4e99f1c9 100644 --- a/docs/architecture/interface.md +++ b/docs/architecture/interface/frame.md @@ -1,6 +1,6 @@ # Interface (egui) -How `crates/ui` is laid out and draws: where a file goes, no router, state and actions, the editing core, rendering, the keyboard, highlighting and Prettier. [Home](README.md) +How `crates/ui` is laid out and draws: where a file goes, no router, state and actions, the editing core, rendering, the keyboard, highlighting and Prettier. [Home](../README.md) `crates/ui` is the window: the frame, its state, its screens and its widgets. It is the shape of the screen, and it calls the core through `ui::api` alone (→ "Backend and events"). Each diff --git a/docs/architecture/i18n-accessibility-theming.md b/docs/architecture/interface/look.md similarity index 99% rename from docs/architecture/i18n-accessibility-theming.md rename to docs/architecture/interface/look.md index 8c615946..9dca54ee 100644 --- a/docs/architecture/i18n-accessibility-theming.md +++ b/docs/architecture/interface/look.md @@ -1,6 +1,6 @@ # Language, accessibility and theming -The translations, the accessibility floor, and the theme tokens every screen reads. [Home](README.md) +The translations, the accessibility floor, and the theme tokens every screen reads. [Home](../README.md) ## i18n diff --git a/docs/architecture/window.md b/docs/architecture/interface/window.md similarity index 99% rename from docs/architecture/window.md rename to docs/architecture/interface/window.md index 572a5535..4b3da6f3 100644 --- a/docs/architecture/window.md +++ b/docs/architecture/interface/window.md @@ -1,6 +1,6 @@ # The window and its menus -What surrounds the areas: the title bar and its bands, the chrome, motion, the theme, the palette, the « Fichier » menu, preferences, shortcuts, help, the first launch and the update prompt. [Home](README.md) +What surrounds the areas: the title bar and its bands, the chrome, motion, the theme, the palette, the « Fichier » menu, preferences, shortcuts, help, the first launch and the update prompt. [Home](../README.md) ## The title bar, and the two bands under it diff --git a/docs/architecture/spaces-folders-board.md b/docs/architecture/notes/board.md similarity index 99% rename from docs/architecture/spaces-folders-board.md rename to docs/architecture/notes/board.md index 393520b9..8f160f66 100644 --- a/docs/architecture/spaces-folders-board.md +++ b/docs/architecture/notes/board.md @@ -1,6 +1,6 @@ # Spaces, folders and the board -The library rail and the space switcher, folders inside a space, and the board: its behaviour, its arrangement and its drawing. [Home](README.md) +The library rail and the space switcher, folders inside a space, and the board: its behaviour, its arrangement and its drawing. [Home](../README.md) ## The library rail diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index def2cb4d..3bcc5ff1 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -99,12 +99,12 @@ database — the repository's `CHANGELOG.md` is baked into the binary by `includ parsed by `changelog/model.rs`. It keeps the convention all the same, the service function in the file and the rules in the module, which is what lets the parser be tested on its own. `json.rs` is the other one without a table: it takes a text and answers what the JSON -visualiser draws — see [The JSON visualiser's model](tools.md#the-json-visualisers-model). +visualiser draws — see [The JSON visualiser's model](tools/tools.md#the-json-visualisers-model). `transfer` is the one without a `store.rs`: import and export read and write **whole libraries**, so they compose the two other stores rather than owning a table. That is also why it is the only feature allowed a `notes::store::all` — a raw note list, which no service function ever -returns to the interface (see [Data access](backend.md#data-access)). Its rules sit in two modules of its +returns to the interface (see [Data access](interface/backend.md#data-access)). Its rules sit in two modules of its own instead: `transfer/bundle.rs` (what travels with an export, how an import merges) and `transfer/file.rs` (reading and writing the file, staged then renamed). diff --git a/docs/architecture/logs.md b/docs/architecture/project/logs.md similarity index 99% rename from docs/architecture/logs.md rename to docs/architecture/project/logs.md index 169f48ba..5f4c9e92 100644 --- a/docs/architecture/logs.md +++ b/docs/architecture/project/logs.md @@ -1,6 +1,6 @@ # Logs -What the application writes about itself, where, at which level, and what a line may say (D35). [Home](README.md) +What the application writes about itself, where, at which level, and what a line may say (D35). [Home](../README.md) ## The three outputs diff --git a/docs/architecture/releasing.md b/docs/architecture/project/releasing.md similarity index 99% rename from docs/architecture/releasing.md rename to docs/architecture/project/releasing.md index 6aebc947..bfa84679 100644 --- a/docs/architecture/releasing.md +++ b/docs/architecture/project/releasing.md @@ -1,6 +1,6 @@ # Updates and releases -How the application updates itself, how a release is built, what the release binary is, and how far back an upgrade reaches. The procedure is `docs/releasing.md`. [Home](README.md) +How the application updates itself, how a release is built, what the release binary is, and how far back an upgrade reaches. The procedure is `docs/releasing.md`. [Home](../README.md) ## Application updates diff --git a/docs/architecture/testing.md b/docs/architecture/project/testing.md similarity index 99% rename from docs/architecture/testing.md rename to docs/architecture/project/testing.md index eeabbd50..9a36495f 100644 --- a/docs/architecture/testing.md +++ b/docs/architecture/project/testing.md @@ -1,6 +1,6 @@ # Testing -The benchmarks and their figures, the Rust tests, the interface tests and the journeys. [Home](README.md) +The benchmarks and their figures, the Rust tests, the interface tests and the journeys. [Home](../README.md) ## Benchmarks diff --git a/docs/architecture/website.md b/docs/architecture/project/website.md similarity index 99% rename from docs/architecture/website.md rename to docs/architecture/project/website.md index f7172317..7d33ae7d 100644 --- a/docs/architecture/website.md +++ b/docs/architecture/project/website.md @@ -1,6 +1,6 @@ # The website -devnotes.fr: its project, its pages and how it is published. [Home](README.md) +devnotes.fr: its project, its pages and how it is published. [Home](../README.md) The showcase site, devnotes.fr, lives in `website/`: an Angular project of its own, outside the Cargo workspace, with its own `package.json` and lockfile (`npm ci` from `website/`). There is diff --git a/docs/architecture/tools.md b/docs/architecture/tools/tools.md similarity index 99% rename from docs/architecture/tools.md rename to docs/architecture/tools/tools.md index c563985c..31df0e39 100644 --- a/docs/architecture/tools.md +++ b/docs/architecture/tools/tools.md @@ -1,6 +1,6 @@ # Tools -The tools and their one contract, and the JSON explorer and visualiser. [Home](README.md) +The tools and their one contract, and the JSON explorer and visualiser. [Home](../README.md) ## The tools: one contract, and the rest written once diff --git a/docs/releasing.md b/docs/releasing.md index 217402c6..8435d523 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -7,7 +7,7 @@ system with it, then commits, tags and publishes — there is no step to do by h **The irreversible comes last**: nothing is pushed until every package is built, signed and checked, so a release that stops before that leaves nothing to clean up. What these steps rest on — the updater, the workflow, the release binary — is -[docs/architecture/releasing.md](architecture/releasing.md). +[docs/architecture/project/releasing.md](architecture/project/releasing.md). ## The steps @@ -35,7 +35,7 @@ on — the updater, the workflow, the release binary — is publishes the site again: its download page offers the files of the latest release, whose version, sizes and SHA-256 `website/scripts/fetch-release.mjs` reads at build time. A dry run does not start it. → "The website" in - `docs/architecture/website.md`. + `docs/architecture/project/website.md`. ## A version on a branch of its own From 1f4597872ea5f44d378426f89014ebb00a22102c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 22:43:59 +0000 Subject: [PATCH 2/8] Architecture: the core's pages checked against the code `core/engine.md` and `core/libraries.md` rewritten from the code as it is: each opens on what matters in a few lines, tables where a list of facts was a paragraph, and nothing of the earlier application (its stores, its components, the WebView, the issue numbers). What was wrong is corrected: `Paths` holds the profile alone, `SendNotKept` is an event, the gate's four states and its panels are the egui ones, the library's preferences are read on each open (no adoption of old keys). The binary and the desktop (`crates/app`, `crates/platform`) move to a page of their own, `interface/desktop.md`: what `main` does in order, the `Desktop` the platform answers, Linux desktop by desktop, and what `on_exit` does in order. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BbVs5tCyTr9AasGra3Zzg3 --- docs/architecture/core/engine.md | 587 +++++++------------- docs/architecture/core/libraries.md | 709 ++++++++----------------- docs/architecture/interface/desktop.md | 129 +++++ 3 files changed, 532 insertions(+), 893 deletions(-) create mode 100644 docs/architecture/interface/desktop.md diff --git a/docs/architecture/core/engine.md b/docs/architecture/core/engine.md index 998ba415..a165f3ec 100644 --- a/docs/architecture/core/engine.md +++ b/docs/architecture/core/engine.md @@ -1,418 +1,193 @@ # The core -The engine and the binary that hosts it, the in-memory index of notes, persistence in SQLite, and the services every feature shares. [Home](../README.md) +`crates/engine`: the `Engine`, its one database thread, the in-memory index of notes, and how +SQLite is used. [Home](../README.md) + +**In short** + +- One `Engine` per process, shared as an `Arc`; no library is open until + `vault::unlock` fills its `Db` slot. +- Every data function runs on **one db thread**, in the order the calls arrive. The network + runs beside it, on the shell's tokio runtime, and never holds the lock. +- Lists, boards and tags are read from **`index::NoteIndex`**, the open library decrypted in + memory. A write declares what it changed, and the index follows. +- SQLite through Diesel, bundled in the binary; migrations are append-only SQL files. +- The engine names no egui, eframe or platform crate. ## The engine and its host -The core (`crates/engine`) owns its state in one `Engine`, which the shell creates once and -manages as an `Arc`: the `Db` slot (empty until `vault::unlock`), the sends, runs and -sockets under way, the restore set aside. It asks the shell for two things only (`host.rs`): - -- **`Paths`**, a plain struct resolved before the engine exists: `profile` (the registry, - `libraries/`, the application's `preferences.json`, `open/`) and `resources` (the identity - lists). A struct, not a trait: every host only fills in two paths. -- **`EventSink`**, the one trait: what the core says unasked, as an `EngineEvent` (a socket's - traffic, a script's console, a run's steps, the index filling). The interface's `Inbox` posts - each on its input channel and wakes the window; tests keep them in a `RecordingSink`. - -What reaches the platform stays out of the core's work: the clipboard is read before an -attachment is stored and written after a QR code is drawn, and a decrypted attachment is opened -once its copy is written — by the interface, not by the core. Opening a library or -restoring a copy closes the sockets and cancels the sends and runs first -(`Engine::let_go_of_the_network`). Nothing in `crates/engine` names egui or Tauri. - -### The binary, its profile and its window - -`crates/app` builds `devnotes`. `main` reads `--script-host` before anything else -(the core's `serve_scripts`: no window, no log), then `--profile `, which puts the -whole profile, its logs and the window's geometry in that directory — tests and development -only. Without it, `platform::paths::Locations::installed` resolves the profile -`com.devnotes.app`, the packages' identifier (`com.devnotes.app.dev` until 1.0.0, D16): roaming data on -Windows, `$XDG_DATA_HOME` and `$XDG_CONFIG_HOME` on Linux, the logs under the local data -directory. Nothing else is read beside the executable: the identity tool's lists are compiled in. - -**One application per profile (D16).** Before the log, `platform::instance::claim` binds a local socket named after a digest of the canonical profile path (a named pipe on Windows, the abstract namespace on Linux). A second launch that cannot bind it connects, sends `reveal` — or `action ` for `devnotes --action ` (`palette`, `capture`, `new-note`, `quit`: what a shortcut of the desktop's runs, and a scenario's way to press a global key) — and exits; the first hears it on a thread of its own and brings its window forward, or does what was asked. ⚠️ Any user of the machine reaches a socket of the abstract namespace: the first reads who connected (`SO_PEERCRED`) and hears its own user alone, or another could open the palette or capture the clipboard into a note. Windows lets other users read the pipe, never write to it. ⚠️ Windows answers a pipe already taken with « access denied », not « address in use ». A claim that fails otherwise stops the launch: a second writer would leave the index silently wrong. Two profiles never collide, so a scenario never meets a development instance. - -**A panic ends the process (D18)**, on whatever thread. The hook is installed first in `main`, -before the script host returns: it logs where and on which thread, **never the message** — a -panic slicing a string quotes it —, flushes the log, tells the person in a system dialog (in -their language, naming the log's folder; set once the preferences are read, never in the -`e2e` flavour) and exits with 101. Nothing is caught and nothing carries on: a job that panicked -halfway leaves state no one can vouch for, and SQLite's journal keeps what was committed, which -the next open checks (`db::quick_check`, the gate). The release is `panic = "abort"`: no -unwinding tables, and `exit` before the abort keeps the open library's memory out of the -system's crash reports. A second panic, in the dialog, exits at once. No thread is an exception: -the tray of Linux opens no library at run time any more (D29). - -The log (`flexi_logger`, `devnotes.log`, three files of 5 MB) starts before the window: the -terminal from `debug` in a debug build and from `info` in a release, the file warnings and errors -alone (D35, → "The three outputs"). What libraries write themselves on stderr (Mesa, -libxkbcommon, GTK) goes around the log, and is fixed where it comes from. Then the input channel and its `Waker` are made, and -eframe opens the window **hidden** at the geometry `platform::window` read back (size, place, -maximised; never whether it was visible), with eframe's persistence off: it would write egui's -state, text fields included, in clear on disk. **It draws through one graphics API** -(`app::renderer`): eframe's own setup opens Vulkan, DX12 and OpenGL together, and each keeps -every GPU's driver loaded for the life of the process (~55 MB of RAM on a machine with two -GPUs). On Windows DX12 alone is opened when a GPU (not the software adapter) answers it, asked -of a throwaway instance first; otherwise, and whenever `WGPU_BACKEND` is set, eframe chooses -among them all, OpenGL before WARP. The device reserves memory by small blocks -(`MemoryHints::MemoryUsage`, 8 MB of video memory and 4 MB of RAM a block against wgpu's 128 -and 64): a window of text fills neither. The creation closure fills the `Waker` and -creates the tokio runtime and the `Engine` (D20); `App::logic`, which runs while the window is -hidden, shows it on the first frame. Under Linux, X11 is taken whenever `DISPLAY` exists -(D15). The geometry is written on exit, the size the window had unmaximised kept under a -maximised one, a full screen never. - -**What the desktop answers** is one value, `ui::Desktop`, built by `crates/app/src/desktop.rs` -on the thread the window's loop will run on: under Windows that loop serves the tray and the -keys. Its `Default` answers nothing, so no test touches the session. Each subject is a module of -`platform` with a trait a test fakes; what only a real desktop can run sits in its `system.rs` -(and that file's submodules, as the shortcuts' Wayland ways) and is answered for by the manual -checklist (`docs/recette/recette.html`), not by coverage. - -- `tray`: the icon and its menu, translated in Rust and rebuilt when the language moves. Under - Linux a StatusNotifierItem over D-Bus (D29), registered on a thread of its own and reached by - message; where no host watches items (GNOME without its AppIndicator extension) it answers - `exists() == false`, and it follows the watcher: one that starts after us (a session's - autostart before the panel), restarts or is turned on later gets the item again - (`assume_sni_available`, `watcher_online` / `watcher_offline`). Windows and macOS keep `tray-icon`; both draw the menu of `tray::entries`. -- `shortcuts`: the three global keys, first come first served. `GlobalKeys` takes them from the - saved settings, says what another application holds, and lets go while a field listens; under - Wayland the desktop holds them (below), and the preferences say who does. -- `autostart`: the system is read at the launch and the preference follows; the switch is pushed - only when it differs. -- `notify`: a toast, never load-bearing. A palette copy over another application is its one use. -- `dialog`: under Linux the portal is asked for first, or `rfd` answers `None` like a cancel. -- `links`: `http` and `https` only. -- `updater`: see below. - -The `e2e` flavour takes no global key and writes no autostart entry. - -**What Linux offers, desktop by desktop.** The tray's icon is a StatusNotifierItem: KDE Plasma, -XFCE, Cinnamon, MATE and Budgie show it; GNOME only with its AppIndicator extension, which Ubuntu -installs and Debian offers (`gnome-shell-extension-appindicator`). Without it `exists()` stays -false, and a closed window hides all the same. Global keys are X11's grab, which under a Wayland -session (the default of Ubuntu, Debian and Fedora) fires only while a window of XWayland has the -focus: there, whenever `WAYLAND_DISPLAY` is set, the desktop holds them for us (`Holder`), found -on a thread of its own in this order. **The global-shortcuts portal** (KDE Plasma from 5.27, GNOME -from 48): a session bound once per change of the keys, the desktop asking the person in a dialog of -its own and sending `Activated`; the key is written `CTRL+ALT+p` (`shortcuts::notation`). **GNOME's -own settings** without it (Ubuntu 24.04's GNOME 46): a custom shortcut `devnotes-` per key, -named « DevNotes — » and running `devnotes --action `, written with `gsettings` as -the Keyboard settings would and rewritten with the preference; the person's own are left alone, and -ours stay if DevNotes is uninstalled, which no package's removal script could reach. **Nobody** -elsewhere: Preferences → Shortcuts shows the three commands to bind by hand. Neither way lets go -while a field listens: the desktop would take the key first, and asking again would ask the person -again. - -**Closing is not quitting.** The close button hides the window when « Close to tray » is on, -whether the desktop shows the icon or not: the process stays to answer the global keys, and a -second launch (the menu's entry, or a shortcut of the desktop's running `devnotes --action`) brings -the window back. Off, it ends the application, as « Quit » always does (`AppState::quitting`). The -preferences say which: `AppState::tray_shown` is read from the tray each frame, and a desktop that -shows no icon gets a note of its own. -⚠️ A hidden window draws nothing, so a close held for a question or for the editor brings it up -first. `on_exit` runs in this order: the sends cancelled, the plain copies swept and the db queue -drained (D19, 30 s at most), the keys released, the tray removed, the geometry written, and last -an update installed. ⚠️ Under Windows the update client ends the process there and then, so a -download only asks to quit: nothing may follow that line. Under Linux a detached shell waits for -the process to be gone before starting the `AppImage` again: beside it, the new one would find -the profile taken. - -An update comes from `latest.json` (D26), checked against the minisign key before it is kept. -Only an `AppImage` or a folder holding the NSIS uninstaller offers one. - -### The notes index - -`index::NoteIndex`, in the `Engine` and touched on the db thread alone, holds the live notes of -the open library decrypted, with their folded text (`view::Folded`: title, tags, body, items, -source), and the decorations a card needs (attachment counts, every folder's chip, the global -`{{field}}` values). An entry is an `Arc` never changed in place, and wipes its texts when it -goes (`zeroize`); nothing of the index reaches the disk. - -It fills after an unlock (`index::fill`, spawned by the shell's `unlock_vault` and -`create_vault`): newest first, a slice of 2 000 notes a job of the queue, opened and folded in -parallel (rayon), `IndexProgress` after each slice and `IndexReady` at the end. ⚠️ A slice is -read in the order of `notes_updated_at` (`store::newest`, a keyset on `updated_at` then `id`): -sorting itself, SQLite would read every sealed body before the first row. A slice read for a -library closed since stops (`Library::number`); opening a library or restoring a copy empties -the index first. +`Engine::new(paths, events, runtime)` starts the db thread and holds, behind its own locks: + +| Field | What it is | +| ----------------------------- | -------------------------------------------------------------------------- | +| `db` | `Db = Mutex>`: the open library's connection and key | +| `index` | `NoteIndex`, the open library's notes decrypted (below) | +| `queue` | the db thread (`db::queue::DbQueue`) | +| `sending`, `runs`, `sockets` | the HTTP sends, collection runs and WebSockets under way | +| `launch_copies` | whether an unlock takes the day's copy: a setting the interface hands over | +| `paths`, `events`, `runtime` | what the shell gave (`host.rs`) | + +The core asks its shell for two things only (`host.rs`): + +- **`Paths`**: `profile`, the folder of the registry, `libraries/` and the application's + `preferences.json`. Nothing else is read beside the executable: the identity tool's lists are + compiled in. +- **`EventSink`**: what the core says unasked, as an `EngineEvent` — a socket's traffic, a + script's console, a run's steps, the index filling (`IndexProgress`, `IndexReady`), a send + whose history could not be written (`SendNotKept`). The interface's `Inbox` posts each on its + input channel and wakes the window; tests keep them in a `RecordingSink`. + +What reaches the operating system stays in the interface: the clipboard is read before an +attachment is stored and written after a QR code is drawn, a decrypted attachment is opened once +its copy is written. Opening a library or restoring a copy first closes the sockets and cancels +the sends and runs (`Engine::let_go_of_the_network`). + +## The notes index + +`index::NoteIndex` holds the live notes of the open library, decrypted, with their folded text +(`view::Folded`: title, tags, body, items, source) and what a card needs beside them (attachment +counts, every folder's chip, the global `{{field}}` values). An entry is an `Arc` never changed +in place, and wipes its texts when it goes (`zeroize`). Nothing of the index reaches the disk. + +**Filling it.** After an unlock, `index::fill` reads the notes newest first, 2 000 a job of the +queue (`SLICE`), opens and folds each slice in parallel (rayon), and says `IndexProgress` after +each and `IndexReady` at the end. ⚠️ A slice is read in the order of `notes_updated_at` +(`store::newest`, a keyset on `updated_at` then `id`): asked to sort, SQLite would read every +sealed body before the first row. A slice read for a library closed since stops +(`Library::number`); opening a library or restoring a copy empties the index first. **Who reads it.** `query_notes` (the list and the palette), `board_view` and `list_tags` read the -index, never a sealed column: `NoteIndex::select` keeps what `store::fetch` kept (space, -folders, quick filter, rails) in the same order, `facets` counts what the SQL counted, -`index::search` runs `view::answers` over the folded text in parallel and answers shared cards, -and `view::arrange` is `view::build` past its search — the one definition of sections, ranking -and quotes. A view holds its `Arc`s, so it is drawn without any lock, and an entry a write -replaced is freed (and wiped) when the last view holding it goes. Only the -folders under an opened one are still asked of SQLite (plain ids). A read waits for no slice: -one that arrives while the index fills finishes it first (`NoteIndex::ready`), since the views -cannot yet say they are partial. ⚠️ Tags that differ only in case count as one, as under -`COLLATE NOCASE`, named by their smallest spelling. `count_notes_tagged` stays in SQL: it counts -the trashed notes too, which a rename touches. The path the index replaced (SQL, every body -opened, `view::build`) is kept as a `#[cfg(test)]` oracle: `index/oracle.rs` chains random -writes through the service functions and compares both answers to random queries after each. +index, never a sealed column: + +- `NoteIndex::select` keeps what SQL would keep (space, folders, quick filter, rails), in the + same order; `facets` counts what SQL would count; +- `index::search` runs `view::answers` over the folded text in parallel; +- `view::arrange` places the answers in sections: one definition of sections, ranking and quotes. + +A view holds its `Arc`s, so it is drawn without a lock. A read that comes while the index fills +waits for it (`NoteIndex::ready`): a view cannot say it is partial. Only the folders under an +opened one are still asked of SQLite, as plain ids. `count_notes_tagged` stays in SQL: it counts +the trashed notes too, which a rename touches. ⚠️ Tags that differ only in case count as one, as +under `COLLATE NOCASE`, named by their smallest spelling. **One path keeps it true.** A service function that writes what the index holds goes through -`Engine::write(|db| …)`, whose closure answers its value and an `index::Changed`: the notes it -touched (re-read, or dropped when no longer live), and whether the attachment counts, the -folders or the global values moved. `write` refreshes the index once the closure returned — -its transactions committed. A corpus-wide write (renaming or dropping a tag, deleting a space or -a folder, an import, the first launch's samples) says `Changed::everything()`: the index is -emptied and the next read builds it whole. No service function refreshes the index itself. -⚠️ A write that forgets to declare leaves the index silently wrong: `tests/commands/index.rs` -checks the index against one rebuilt from the database right after each write -(`Engine::index_matches_library`). +`Engine::write(|db| …)`. Its closure answers its value and an `index::Changed`: the notes touched +(read again, or dropped when no longer live), and whether the attachment counts, the folders or +the global values moved. `write` refreshes the index once the closure returned, its transactions +committed. A corpus-wide write (a tag renamed or dropped, a space or folder deleted, an import, +the first launch's samples) says `Changed::everything()`: the index is emptied and the next read +builds it whole. + +⚠️ A write that forgets to declare leaves the index silently wrong. Two tests watch for it: +`tests/commands/index.rs` compares the index with one rebuilt from the database after each write +(`Engine::index_matches_library`), and `index/oracle.rs` chains random writes and compares the +index's answers with SQL's to random queries. ## Persistence (Rust) -Storage is **SQLite**, queried through **Diesel** and embedded via `libsqlite3-sys` with the -`bundled` feature — SQLite is compiled from source and statically linked, so nothing has to be -installed or shipped alongside the executable. The database file lives under the profile -(`Paths::profile`, the profile `platform::paths` resolves). - -- **The store is plain functions.** `notes::store` and `spaces::store` take a - `&mut SqliteConnection`; the service functions sit on top. That is what makes persistence - testable against `SqliteConnection::establish(":memory:")` without an engine. A store - holds **no business rule** — it reads and writes the model defined in its sibling - `model.rs`, which it depends on. What a write needs decided is asked of the model: - `revision::worth_keeping` for a kept body, `Note::normalized` for an imported note, - `NotesQuery::selected_tags` for a query, `name::is_taken` for a duplicate name. No - `store.rs` calls a `normalize_*` function. -- **One row type per table, opened in one place.** `NoteRow`, `SpaceRow` and `FolderRow` - each carry an `open(vault)`, and a write that answers the entity reads it back with the - same `find` — which is also what answers an id that matched nothing, so no store checks - `exists` before updating. -- **`db/schema.rs` is the typed mirror of the schema**, written by hand rather than - produced by `diesel print-schema`, which would make `cargo check` depend on an up-to-date - database sitting outside the repository. What it deliberately does not model — `CHECK` - constraints, `ON DELETE CASCADE`, and the `NOCASE` collation on `note_tags.tag` — stays in - the migration SQL. Diesel obeys those; it does not own them. Adding a column means editing **both** the migration and this file; `check_for_backend` on - `NoteRow` turns a divergence into a compile error. -- **Concurrency.** A `SqliteConnection` is not `Sync`, and Diesel takes it exclusively for - every query, reads included. A single connection is held by the `Engine` - (`Db = Mutex>`, the connection and the key together) — never a global, and - empty until the library is unlocked. Each service function holds `db::lock` from its - first read to its last write, so a check and the write that depends on it cannot be - interleaved. A read lets it go before the work that needs no more rows: `view::build`, - `board::build`, reading an attachment's file. Whether one lock is enough was measured rather - than assumed: see "Who holds the lock" under Benchmarks. -- **⚠️ Every data function runs on the engine's one db thread** (D11). `engine::db::submit` - queues a job on it, which the interface does at the call (`Backend::db`), and `db::run_here` - is what a test or the queue itself calls. A job that panics ends the process (D18): no lock - is ever found poisoned. - - **One thread, in order.** The queue is one thread that runs its jobs in the order they - arrive: two writes sent one after the other land in that order , and the `Mutex` is never contended. ⚠️ `db::lock` asserts - in debug builds that it runs on that thread; the crate's unit tests, which lock in-memory - libraries on their own thread, are exempt. A job never waits on another job, nor on the - network. Async code that holds the engine reaches the queue through `db::run`. Sends - and sockets run on the runtime the shell passes to `Engine::new`. - - **A send in three steps.** It _reads_ in a job (inheritance, variables, the jar, and the - number of the library open), _sends_ on the runtime without coming back to the queue, then - _writes_ in a job: history, cookies, the variables the scripts wrote — merged into what is - there by then, never overwritten, so two sends at once keep both. Each `Library` gets a - number from a process counter when it is opened (`Library::number`); the write step goes - through `db::lock_library` and writes nothing, and says so in the log, if another library was - opened since the read. - -- **Migrations.** They live as SQL files in `crates/engine/migrations/`, are compiled into the - binary by `embed_migrations!`, and are tracked in the `__diesel_schema_migrations` table. - Evolving the model means adding a `YYYY-MM-DD-HHMMSS_name/` directory — never editing a - shipped migration, it has already run on user machines. Each migration is atomic. A database - carrying a migration this binary does not know is refused rather than misread. -- **The board geometry is columns nothing else reads.** `folders.x/y/w/h` are nullable and - move together — `NULL` means "never laid out", which every folder made before the board - existed is. `note_positions` is keyed on `note_id` alone and holds a row only for an - **unfiled** note; filing one deletes its row. ⚠️ None of it is on the `Note` or `Folder` - model, and that is what makes `#134` free: `transfer::Bundle` deserialises both, so a - coordinate there would travel in every export and land on top of the arrangement the - receiving machine already has. -- **A folder is a row, and membership is a column.** `folders` holds `(id, space_id, name, -colour, created_at)` and `notes.folder_id` points into it. ⚠️ The column was added with no - `DEFAULT`, because SQLite only accepts an added `REFERENCES` column whose default is `NULL` - — which is what every existing note needs anyway. `folders.name` is sealed like - `spaces.name`, so uniqueness leaves SQL exactly as it did there: two seals of the same name - differ, and a unique index on ciphertext catches nothing. The order does not move — - `created_at` stays in the clear, and reading order is the order a board lays its zones out - in. `colour` carries no `CHECK`, following `language`: the list lives in the domain, and a - value a build cannot name degrades to the default rather than failing the read. -- **A checklist's items are a child table, not a serialised column.** `note_items` is keyed - `(note_id, position)` and written by wiping the note's rows and re-inserting them in order — - the same shape as `note_tags`, for the same reason. It is _not_ read back after writing, and - that asymmetry with tags is deliberate: `position` orders numerically, which the insertion - order reproduces exactly, whereas `note_tags.tag` is `COLLATE NOCASE` and only a read gives - its order. `notes.kind` carries no `CHECK`, following `language` rather than `lifecycle_kind`: - the list of kinds lives in the domain and can move between versions. Its `DEFAULT 'snippet'` - is not a convenience either — SQLite refuses an `ADD COLUMN NOT NULL` without one, and it is - what gives every note already in the database its value. -- **Filled `{{fields}}` are a child table too.** `note_placeholders` is keyed `(note_id, name)` - and rewritten whole, like `note_tags` and `note_items` — what is no longer sent is what the - user cleared, and a partial write would leave an emptied value still filling the text. Its - key is **case-sensitive**, unlike `note_tags.tag`: `notes::placeholder` distinguishes - `{{Host}}` from `{{host}}` in the text, and folding here would fill one with the other's value. -- **Schema choices that made filtering movable to the back-end.** `lifecycle` is split into - `lifecycle_kind` + `lifecycle_expires_at` columns rather than stored as JSON, and tags live - in their own `note_tags` table rather than in a serialised column. Both exist so that - filtering by tag, or querying what expires before a date, is a `WHERE` clause instead of a - full re-read — which is why `query_notes` needed no migration. `PRAGMA foreign_keys` is set - per connection, which is what makes the `ON DELETE CASCADE` on notes and tags actually fire. -- **The five pragmas in `db::configure` are each a decision, and each has a test.** - `foreign_keys` because the cascades are inert without it; `journal_mode = WAL` so a reader - never blocks the writer; `busy_timeout = 5000` because SQLite's own default is **zero**, - which turns a file another process holds for twenty milliseconds — a checkpoint, an - antivirus, a second instance — into a storage error on the first write; and - ⚠️ `synchronous = NORMAL`, WAL's default, written down because it is a durability choice: - a power cut can cost the last committed transaction and cannot corrupt the file. `FULL` - would fsync every commit to protect a note the user can retype. `mmap_size = 1 GiB`, 64 MiB once the - index is whole, reads pages in place rather than copying each one through SQLite's 2 MB cache: against the same - build without it, `list_tags` and a pinned-only query halve and the whole-corpus queries - gain 7–13 % at 8000 notes. ⚠️ An I/O error or a truncation under the mapping is a `SIGBUS`, - not an error code: a library's files live in the profile, and nothing moves them while its - connection is open (`recovery::set_aside` refuses an open library, a restore empties the - `Mutex` first). -- **Every open runs `PRAGMA quick_check`, and a damaged file is its own answer.** Nothing - checked the database was still readable, so the first symptom was a query failing somewhere - in the interface, reported as a storage error — "try again" about a file that will never get - better on its own. `db::quick_check` runs in `db::open` ⚠️ **before the migrations**: they - write, and running them over a damaged file is how a salvageable database becomes an - unsalvageable one. `quick_check` and not `integrity_check` — the quick one skips the most - expensive cross-checks and reads the file once, milliseconds at this size; the full check - belongs behind a button, never on the path to a window. SQLite answers a single `ok`, or one - row per problem, and those rows become `StorageError::Damaged` → `ErrorCode::LibraryDamaged`. -- **Detecting it without a way out would be a loop.** An application that refuses to start and - explains why, every launch, leaves deleting a file by hand as the only move — so - `recovery::set_aside` is the other half of the check. It tries `VACUUM INTO` first (best - effort, and deliberately so: a partly readable database usually gives most of itself back, - and a failure there must not stop the user getting a working application), then moves the - database, its `-wal` / `-shm` sidecars and ⚠️ **`attachments/`** into `damaged//`. - The attachments are not a detail: a fresh library calls every file there an orphan, so the - next launch's sweep would delete the pictures of the notes just set aside — the one way this - recovery could destroy what it exists to save. ⚠️ `vault.json` stays where it is. The - passphrase does not change, the rescued copy needs that exact key, and asking someone to - choose a new passphrase in the middle of losing their library would be its own small cruelty. - `set_aside_damaged_library` refuses while the library is open — moving the file under a live - connection is how a damaged database becomes a lost one — and answers the folder it wrote, - because "set aside" is only true if the user can be told where. -- **A forgotten passphrase is final, and the gate now says so with something to do about - it.** It used to offer nothing but the field: the phrase wraps the library's key, - opening `vault.json` is the only check there is, and the only way past was finding the - profile directory in `%APPDATA%` and moving files by hand. `recovery::Reason` is what - splits the two cases, because ⚠️ **the answers are opposite and getting either wrong - loses the library for good**: - - | | `vault.json` | rescue | goes to | - | ----------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------- | - | `Damaged` | **stays** — the phrase still works and the rescued copy needs that exact key | `VACUUM INTO`, best effort | `damaged//` | - | `Forgotten` | **travels** — it is the only thing that phrase would ever open again | none: the file is sealed and SQLite has nothing to give without the key | `archived//` | - - `attachments/` goes along either way, for the same reason as before. `archive_locked_library` - refuses on an open library like its neighbour, and answers where it wrote. - - ⚠️ With the key file gone, `vault_state` answers `absent` rather than `locked`, which is - what turns the gate into the one that asks for a **new** phrase — a gate still asking for - the old one would be the same dead end with extra steps. `VaultStore.moveAside` re-reads - the state rather than assuming it, and forgets `devnotes.notes.samplesSeeded` so the fresh - library seeds. - - On screen it is a small, quiet link under the unlock button, ⚠️ shown only on a library - that exists — a fresh one has no phrase to have forgotten. It opens a panel **instead of** - the form, never beside it: the field is the one thing that cannot help, and an offer to - give up standing next to it reads as a shortcut. The panel names what is lost — the notes - are not recovered, they leave sealed and unreadable — and ⚠️ its confirm is `destructive` - rather than the amber fill, which is the button you are _meant_ to press. - - ⚠️ `24-forgotten-passphrase.e2e.ts` runs **after `23-backups`** and depends on it: that - one ends by restoring a copy, which closes the library and leaves the gate on screen. - There is no other way to meet a locked gate inside one run — the unlocked state lives in - the process, and the process outlives every page reload. Nothing may be filed after it. - -- **Ordering is the back-end's call.** `notes::store::fetch` orders by `updated_at DESC, id`; - the front-end preserves the order it receives, so this one query decides what the user sees - first. Note the deliberate asymmetry: the order is by `updated_at` while sections group by - `created_at`. The section answers "when was this note born", the order within it answers - "which did I touch last", so an old note reopened today tops the "older" section. -- **Querying splits the work by what each tool does well.** SQL handles what it indexes — - space, pin state, lifecycle, language, and tag membership through a `note_tags` subquery - (`notes::id.eq_any(...)`). The conditional criteria are assembled on a Diesel `into_boxed()` - query, which is what replaced hand-numbered `?N` placeholders and their bound-parameter - bookkeeping. - Full-text - matching is done **in Rust** (`notes::view`), because SQLite's `LOWER()` only folds ASCII - without ICU, so `Étape` would not match `étape`. Grouping is `notes::view`, which - touches no connection and is therefore testable without a database. -- **The search fold drops the accents as well as the case, on both sides.** `view::fold` - lowercases and strips the combining marks, so `etape` finds `Étape` and `Étape` finds - `etape` — the needle goes through the same function as every haystack. It decomposes one - character at a time (`unicode_normalization::char::decompose_canonical`) rather than - streaming the whole string through `nfd()`: on 800 notes of 13 kB of accented text, in - release, that is 15 ms against 76 ms, and against 27 ms for the `to_lowercase()` it - replaces — which folded no accent at all. Pure ASCII, which is what a snippet of code is, - never leaves the fast path. Only what a **canonical** decomposition separates is folded: - `ø` and `ß` are letters in their own right and stay. ⚠️ Tag normalisation - (`notes::model::normalize_tags`) deliberately does **not** fold accents — `Étape` and - `etape` are two tags, and merging them would lose one. -- **Tag normalisation lives in `notes::model::normalize_tags`, and only there.** Trimming, - stripping leading `#`, dropping blanks and collapsing case-insensitive duplicates (first - spelling wins) all happen on write, so the front sends what the user typed. The returned - tags are sorted to match what a read gives back — otherwise a note's tags would reorder - themselves on the next reload. -- **Tag case folds at the storage level too.** `note_tags.tag` is `COLLATE NOCASE` - (the `fold_tag_case` migration). Without it `normalize` only deduplicated _within_ one note: `Urgent` and - `urgent` carried by two different notes produced two facets in the rail, of which - `tag IN (…)` — running in BINARY — matched only one, while the text search confused them. - Three behaviours for one concept. -- **`notes.language` is indexed** (the `index_language` migration), since it became a filtering facet: both - `language IN (…)` and the `SELECT DISTINCT language` that feeds the rail would otherwise - scan the table on every query. No `CHECK` constraint on the column, though — the list of - known languages lives in `notes::language` and moves between versions; freezing it in the - schema would mean a migration per addition. -- **Timestamps are injected, not read.** `notes::store` takes `now` as a parameter and the - command passes `Utc::now()` — the same reason `ClockService` exists on the front. - Millisecond precision is deliberate: two notes saved within one second would otherwise be - impossible to order. -- **Deletion is a column, not a `DELETE`.** `notes.deleted_at` (the `trash_and_attachments` - migration) is `NULL` for a live note, which lets the index be partial and every read filter - on `deleted_at IS NULL`. See [The trash](../notes/editing.md#the-trash-and-undoing-a-deletion) for what that - costs and buys. -- **Attachment bytes are not in the database.** The `attachments` table holds a record; the - file sits in the library's `attachments/`. A base growing by 10 MB per screenshot would - make every note read slower, for data no query ever looks inside. -- **`updated_at` is not touched by operations the user did not aim at a note.** Deleting a - space moves its notes, a global retag rewrites their tags, restoring pulls one back out of - the trash, filling a `{{field}}` records a value — none of the four refreshes it. The canvas - sorts on that column, and touching it would float notes nobody reopened to the top. It is - also why the field values are a command of their own rather than a `NotePatch` field: the - patch path exists to refresh that column. A patch that changes nothing refreshes nothing - (`NotePatch::apply` compares the note before and after): closing the editor sends a body - compared with the list's preview of it, once the note it held is gone, and a drawing's - pictures may be taken of a scene left as it was. - -## Cross-cutting services - -What has no place on screen is `ui::services`, one module per subject, and what is asked of the -operating system is `platform`, one module per subject with a trait a test fakes -(→ "The binary, its profile and its window"): - -- **`services::time`** — an injectable `Clock` and `relative(at, clock)`, which answers the label - and **how long it holds**: the next frame is asked for exactly then, so « 4 min ago » ages on - its own and nothing repaints every frame. -- **`services::preferences`** and **`services::settings`** — the two `preferences.json` and the - typed settings over them (→ "Preferences, settings and the notifiers"). A key this version does - not know is kept and written back; the files are written staged then renamed, on the db queue. -- **`services::errors::ErrorNotifier`** and **`services::status::StatusNotifier`** — the banner's - failure and the toast's report. On a desktop application the log is not an interface: a failed - write has to be visible, or the window just looks unresponsive. A panic is logged without its - message, said in a dialog, and ends the process (D18). -- **`platform::clipboard`** — what the clipboard holds beyond the text egui hands a field (a - page's HTML, for a paste into a Note); a clipboard that cannot be opened answers `None`, and a - copy that failed only withholds its acknowledgement. ⚠️ It reaches `AppState` through - `ui::Desktop`, like the opener: `AppState::new` starts with `NoClipboard` and `NoOpener`, so a - screen test never pastes the machine's clipboard nor starts one of its programs. -- **`platform::dialog`** — the file dialog: `None` covers a cancel **and** a dialog the desktop - could not show, since there is nothing to open either way. Under Linux the XDG portal is asked - first (D29). -- **Closing and quitting** stay distinct: the close button **hides** while « Close to tray » is - on, tray icon or not, the palette hides after copying, and « Quit » is the only path that ends - the process (→ "Closing is not quitting"). +SQLite, queried through Diesel, compiled in (`libsqlite3-sys` with `bundled`): nothing to install +beside the executable. A library's database is `.sqlite3` in its folder under the profile +(→ "Several libraries, and the registry beside them"). + +### Stores, rows and the schema + +- **A store is plain functions** taking a `&mut SqliteConnection`, so it is tested against an + in-memory database without an engine. It holds no rule: what a write needs decided is asked of + the model (`revision::worth_keeping`, `Note::normalized`, `NotesQuery::selected_tags`, + `name::is_taken`). +- **One row type per table, opened in one place.** `NoteRow`, `SpaceRow` and `FolderRow` each + have an `open(vault)`; a write that answers the entity reads it back with the same `find`, which + also answers an id that matched nothing. +- **`db/schema.rs` is written by hand**, so that `cargo check` needs no database. What it does + not model — `CHECK`, `ON DELETE CASCADE`, `COLLATE NOCASE` — stays in the migrations' SQL. + Adding a column means editing both; `check_for_backend` on `NoteRow` turns a divergence into a + compile error. +- **Migrations** are SQL folders in `crates/engine/migrations/` (`YYYY-MM-DD-HHMMSS_name/`), + compiled in by `embed_migrations!`. ⚠️ Never edit one that shipped: it already ran on someone's + machine. A database carrying a migration this binary does not know is refused, not misread + (→ "How far back an upgrade reaches"). + +### One thread, one lock + +The connection is not `Sync`, and Diesel takes it for every query, reads included. One +connection is held by the `Engine`, empty until the library is unlocked. + +- ⚠️ **Every data function runs on the engine's one db thread** (D11): the interface queues it + there (`Backend::db` → `db::submit`), tests call `db::run_here`. The jobs run in the order they + arrive, so two writes sent one after the other land in that order and the `Mutex` is never + contended. `db::lock` asserts in debug builds that it runs on that thread (the crate's unit + tests are exempt). +- A service function holds `db::lock` from its first read to its last write, so a check and the + write that depends on it cannot be interleaved. A read lets go before work that needs no more + rows (`view::build`, `board::build`, reading an attachment's file). +- A job never waits on another job, nor on the network. A job that panics ends the process + (D18), so no lock is ever found poisoned. +- **A send in three steps** (`Arc`, on the runtime): it _reads_ in a job (inheritance, + variables, the jar, the open library's number), _sends_ without coming back to the queue, then + _writes_ in a job — history, cookies, the variables its scripts set, merged into what is there + by then. The write goes through `db::lock_library` and writes nothing, and says so, if another + library was opened since the read (`Library::number`). + +Whether one lock is enough was measured, not assumed (→ "Who holds the lock"). + +### The schema's choices + +| Choice | Why | +| ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | +| tags in `note_tags`, lifecycle in two columns | filtering by tag or by expiry is a `WHERE`, not a re-read | +| `note_tags.tag` is `COLLATE NOCASE` | `Urgent` and `urgent` on two notes are one tag in the rail, in `IN (…)` and in the search alike | +| `note_items (note_id, position)`, `note_placeholders (note_id, name)` | child tables rewritten whole, like the tags; ⚠️ a field's name is case-sensitive (`{{Host}}` ≠ `{{host}}`) | +| `notes.language`, `notes.kind`, `folders.colour` carry no `CHECK` | the lists live in the model and move between versions; a value a build cannot name degrades to the default | +| `notes.deleted_at` | the trash is a column: every read filters `deleted_at IS NULL` (→ "The trash, and undoing a deletion") | +| board geometry (`folders.x/y/w/h`, `note_positions`) off `Note`/`Folder` | an export carries no coordinate onto the receiving machine's board (→ "A folder travels; its coordinates do not") | +| attachment bytes in `attachments/`, not in the database | a library growing by 10 MB a screenshot would slow every read (→ "Attachments") | +| instants as TEXT with milliseconds (`db::iso8601`) | two notes saved within a second still order | +| `folders.name`, `spaces.name` sealed | uniqueness is checked in the model: two seals of one name differ | + +**`updated_at` moves only when the person edited the note.** Deleting a space, a retag, a +restore, a field filled, a priority: none touches it, since the canvas sorts on it. A +`NotePatch` that changes nothing refreshes nothing (`NotePatch::apply` compares before and after). + +### The connection + +`db::configure` sets five pragmas, each held by a test: + +| Pragma | Why | +| ------------------------------------- | -------------------------------------------------------------------------------------------- | +| `foreign_keys = ON` | per connection; without it the cascades never fire | +| `journal_mode = WAL` | a reader never blocks the writer | +| `busy_timeout = 5000` | SQLite's default is zero: a checkpoint or an antivirus would fail the first write | +| `synchronous = NORMAL` | a power cut can cost the last transaction, never the file | +| `mmap_size` 1 GiB, 64 MiB once filled | pages read in place; ⚠️ a file truncated under the mapping is a `SIGBUS`, so nothing moves a library's files while it is open | + +⚠️ **Every open runs `db::quick_check` before the migrations**: they write, and writing over a +damaged file is how a salvageable one is lost. A failure is `ErrorCode::LibraryDamaged`, and the +gate offers to set the library aside (→ "Damaged or forgotten: a library set aside"). + +### Reading notes: order, search, tags + +- **The order is the core's.** `updated_at DESC, id` within a section, while sections group by + `created_at`: « when was it born » places it, « which did I touch last » orders it. +- **The search folds in Rust** (`view::fold`): lowercase, combining marks stripped, one character + at a time, ASCII on a fast path; the needle goes through the same function. `etape` finds + `Étape`. Only canonical decompositions fold: `ø` and `ß` stay letters. +- **Tags are normalised in `notes::model::normalize_tags` alone**, on write: trimmed, leading `#` + dropped, blanks dropped, case-insensitive duplicates collapsed (the first spelling wins), + sorted as a read gives them back. ⚠️ Accents are kept: `Étape` and `etape` are two tags. +- **Time is passed in**, never read by a store: the service function takes `now`. + +## Damaged or forgotten: a library set aside + +`recovery::set_aside` moves a library out of the way, for one of two reasons with opposite +needs (`recovery::Reason`): + +| | the key file `vault.json` | rescue | goes to | +| ----------- | ------------------------------------------------------------- | ---------------------- | ----------------------- | +| `Damaged` | **stays**: the phrase still works, the rescued copy needs it | `VACUUM INTO`, best effort | `damaged//` | +| `Forgotten` | **travels**: only that phrase could ever open it again | none: it is sealed | `archived//` | + +⚠️ `attachments/` goes along either way: a fresh library would call every file there an orphan, +and the next sweep would delete them. Both service functions (`set_aside_damaged_library`, +`archive_locked_library`) refuse an open library and answer the folder they wrote, which the +gate shows. With the key file gone, `vault_state` answers `absent`, so the gate asks for a +**new** phrase; the interface forgets `notes.samplesSeeded` so the fresh library is seeded. diff --git a/docs/architecture/core/libraries.md b/docs/architecture/core/libraries.md index 38646d2b..26984a2d 100644 --- a/docs/architecture/core/libraries.md +++ b/docs/architecture/core/libraries.md @@ -1,35 +1,38 @@ # Libraries -A library on the disk: encryption at rest and its gate, several libraries and their registry, the two scopes of preference, the copies, attachments and import/export. [Home](../README.md) +A library on the disk: how it is sealed and opened, several of them and their registry, the two +scopes of preference, the copies, attachments, import and export. [Home](../README.md) + +**In short** + +- A library is a folder: its database, its key file, its attachments and its copies. +- Values typed or answered are **sealed** (AES-256-GCM); what SQL filters on stays plain. +- The passphrase **wraps** a random key: changing it rewrites a hundred bytes, not the library. +- Nothing answers until the gate unlocks a library; switching library is a full teardown. +- Every file is written staged, flushed and renamed (`engine::durable`). ## Encryption at rest -The library is sealed with a key derived from a passphrase typed once per launch. Nothing -is kept of it: no keychain, no "remember me", no recovery — the semantics of a KeePass file, -and the same consequence. +The library is sealed with a key the passphrase unwraps once a launch. Nothing is kept of the +phrase: no keychain, no « remember me », no recovery. ### Why not SQLCipher -Measured rather than assumed. SQLCipher encrypts every 4 KiB page with AES-256-CBC and -authenticates it with HMAC-SHA512; on the 8000-note benchmark corpus that costs ~112 ms on -`query_notes`, 88% of it in the HMAC. It also has to be built — the crate wants a vendored -OpenSSL, which means a C toolchain in CI on every platform, for every build. - -Sealing values instead costs ~28 ms on the same corpus, four times less, because it seals -what a reader would want rather than every byte the file system moves. The crates are pure -Rust (`aes-gcm`, `argon2`, `getrandom`, `zeroize`): no `build.rs`, no C, nothing added to a -CI build. On a realistic library (~2 MB) the sealing costs well under a millisecond. +Measured. SQLCipher encrypts and authenticates every 4 KiB page: ~112 ms on `query_notes` over +the 8 000-note corpus, 88 % of it in the HMAC, and a vendored OpenSSL to build on every CI +system. Sealing values costs ~28 ms on the same corpus, in pure Rust (`aes-gcm`, `argon2`, +`getrandom`, `zeroize`): no C, no `build.rs`. ### What is sealed, and what is not **Sealed is what was typed or answered; plain is what SQL filters, sorts, groups and joins on.** Sealing the second would move every query into Rust over the whole corpus. The table is every -column of `db/schema.rs`, read one by one: a column added there is added here. +column of `db/schema.rs`: a column added there is added here. | Table | Sealed | Plain | | --------------------- | --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | `spaces` | `name` | `id`, `pinned` | -| `folders` | `name` | `id`, `space_id`, `colour`, `created_at`, the board's `x`, `y`, `w`, `h` | +| `folders` | `name` | `id`, `space_id`, `parent_id`, `colour`, `created_at`, the board's `x`, `y`, `w`, `h` | | `notes` | `title`, `content`, `source` | `id`, `space_id`, `folder_id`, `kind`, `language`, `priority`, `pinned`, `created_at`, `updated_at`, `deleted_at`, `lifecycle_kind`, `lifecycle_expires_at` | | `note_positions` | — | `note_id`, `x`, `y` | | `note_tags` | — | `note_id`, `tag` | @@ -37,7 +40,8 @@ column of `db/schema.rs`, read one by one: a column added there is added here. | `note_revisions` | `content` | `id`, `note_id`, `taken_at` | | `note_placeholders` | `value` | `note_id`, `name` | | `global_placeholders` | `value` | `name` | -| `attachments` | `file_name`, and the file itself, bytes and all | `id`, `note_id`, `mime_type`, `byte_size`, `created_at` | +| `drawing_pictures` | `thumbnail`, `picture` | `note_id` | +| `attachments` | `file_name`, and the file itself | `id`, `note_id`, `mime_type`, `byte_size`, `created_at` | | `http_collections` | `name`, `settings` (auth, headers, transport) | `id`, `position`, `created_at` | | `http_folders` | `name`, `settings` | `id`, `collection_id`, `parent_id`, `position`, `created_at` | | `http_requests` | `name`, `document` (URL, parameters, headers, body, auth, and the rest) | `id`, `collection_id`, `folder_id`, `position`, `created_at`, `updated_at`, and ⚠️ `kind`, `method` | @@ -45,523 +49,254 @@ column of `db/schema.rs`, read one by one: a column added there is added here. | `http_cookies` | `cookie` (name, value, domain, path, flags) | `id`, `expires_at` | | `http_environments` | `document` (name, colour, protection, variables and their values) | `id`, `kind` (`globals` or `environment`), `position`, `created_at` | -⚠️ **What a reader of the raw file learns, with no key.** Of the notes: their number and the -shape of the spaces and folders they hang in, every instant, each note's language, kind, pin -and item states, every tag and `{{field}}` name, each attachment's type and size. Of the HTTP -side: how many collections, folders and requests there are, how they nest and in which order, -when each was created and each request last saved, and each request's kind and method; when -each send was made and from which request — not to where, nor how it ended; how many cookies -the jar holds and when each expires — not for which site; how many environments there are -and when each was made — not their names nor what they hold. And everywhere the **length** of -every sealed value: AES-GCM hides no length. `docs/security.md` lists it for the people deciding -what to keep here. - -⚠️ **`http_requests.kind` and `.method` are plain for no query**: the tree is read whole and -ordered in Rust. Sealing them is moving them into `document`, and the rows already written -cannot follow by SQL, which holds no key: it is a pass in Rust at unlock, over every request. -Left as it is, and written here so that it is a decision: what the two give away is « four -`POST`s and a WebSocket in this folder ». The history's method and status were the same case -with a cost of nothing — a history is thirty days of sends — and are sealed (migration 17). - -**Beside the database.** `libraries.json` (the libraries' names) and both `preferences.json` -are plain. A preference holds a setting or an id, never what a note or a request holds: -`devnotes.notes.http.tabs` is the ids of the requests left open — one never saved has no id -and is not written at all —, `devnotes.notes.http.collapsed` those of the folded rows, -`recentTools` those of the tools; a tool keeps none of its inputs. The logs carry no URL, no -header, no body and no cookie; a failure names its code. An answer's body stays in memory: the -only file is the one « Enregistrer dans un fichier » is asked for, staged beside it and removed -when the write fails. A backup is the library copied: nothing more in the clear than in it. A -`.devnotes` archive holds the notes, not the HTTP side. - -Two tests read the file rather than the API, and assert exactly this split: +⚠️ **What a reader of the raw file learns, without the key**: how many notes, spaces, folders, +requests, cookies and environments there are and how they nest; every instant; each note's +language, kind, priority, pin and item states; every tag and `{{field}}` name; each attachment's +type and size; each request's kind and method; when each send was made and from which request +(not to where, nor how it ended). And everywhere the **length** of each sealed value: AES-GCM +hides none. `docs/security.md` says it to the people deciding what to keep here. + +⚠️ `http_requests.kind` and `.method` are plain for no query (the tree is read whole and ordered +in Rust). Sealing them means moving them into `document` by a pass over every request at unlock, +since SQL holds no key. Left as it is, deliberately: they give away « four `POST`s and a +WebSocket in this folder ». + +**Beside the database**, plain: `libraries.json` (the libraries' names) and both +`preferences.json`. A preference holds a setting or an id, never what a note or a request holds +(`notes.http.tabs` is the ids of the requests left open; a tool keeps none of its inputs). The +logs carry no URL, header, body nor cookie. An answer's body stays in memory unless « Save to a +file » is asked. An archive holds the notes, not the HTTP side. + +Two tests read the raw file and hold this split, with a marker in every string written: `a_note_is_not_readable_in_the_file_it_was_written_to` (`tests/notes.rs`) and -`nothing_typed_or_answered_is_readable_in_the_file_it_was_written_to` (`tests/http.rs`) — a -collection, a folder, a request for each kind of auth, a send with its answer and a cookie, -every string of which carries one marker the raw bytes must not hold. -`http-tabs.store.spec.ts` holds the same for the preferences. +`nothing_typed_or_answered_is_readable_in_the_file_it_was_written_to` (`tests/http.rs`). +Journey 14 does the same on the whole profile. ### What this protects against, and what it does not -The threat is a file read at rest: a stolen laptop, a copied profile directory, a backup -that ended up somewhere it should not have. Against that, a value is unreadable and a -tampered one is refused rather than decrypted into nonsense. - -⚠️ It is **not** a defence against someone who can write to the file while you are away. -A sealed value is authenticated on its own and not bound to the row it sits in — no -associated data — so a value could be moved from one row to another and its tag would -still verify. Binding it would mean threading the row identity through every seal and open -call in the stores; it buys nothing against the threat above, where the attacker reads the -file rather than edits it and hands it back. - -⚠️ Nor is it a defence against a machine already compromised while DevNotes runs. Since the -notes index (« The notes index »), **the whole open library is in memory in the clear** for as -long as it is open: every note's title, body, source, tags, items and field values, their folded -copies, the folder names and the global `{{field}}` values. That changes nothing at rest — no -index is ever written to disk, and a cache sealed on disk would be a new file format — but it -changes what a read of the process's memory reveals: no longer the notes a search happened to -open, but all of them. What is done about it: - -- an index entry wipes its texts when it is dropped (`zeroize`), and so do the folder names - and global values the index replaces or drops; -- the index is emptied when another library is opened, when a copy is restored, and when the - application exits (`Engine::wipe_index`, queued by `App::on_exit` behind the last write); -- nothing of it is logged, nor sent in an event (`IndexProgress` carries two counts). - -What is not: the copies a view makes are ordinary `String`s, dropped unwiped, as before the -index — the notes `query_notes` matched and the previews it sent, the note open in the editor. -Pages of the heap can reach swap, a hibernation image or a crash dump, wiped or not, and a -process killed before its exit frees its memory without wiping it. The key is in the -process's memory for the length of the session. **There is no « lock » action, and the -migration adds none**: the vault has `vault_state`, `create_vault`, `unlock_vault` and -`change_passphrase`, nothing that closes a library short of opening another or quitting. +**Against**: a file read at rest — a stolen laptop, a copied profile, a backup left somewhere. +A value is unreadable, and a tampered one is refused rather than decrypted into nonsense. + +**Not against**: + +- ⚠️ someone who can **write** the file while you are away: a sealed value is not bound to its + row (no associated data), so it can be moved to another row and still verify; +- ⚠️ a machine compromised **while the application runs**: the index holds the whole open + library in the clear for as long as it is open (→ "The notes index"). An entry wipes its texts + when dropped (`zeroize`); the index is emptied when another library opens, a copy is restored, + or the application exits (`Engine::wipe_index`). The copies a view makes are ordinary + `String`s, the key stays in memory for the session, and pages can reach swap or a crash dump. + There is no « lock » action: a library closes when another opens or the application quits. ### The pieces -- **`vault/key.rs`** — `Vault`: the key, and the two operations. Argon2id (`Cost`: 64 MiB, - 3 passes, 1 lane — 1.16 s on the development machine, which is the point of it) and - AES-256-GCM with a fresh 96-bit nonce per write, laid out `nonce || ciphertext || tag`, - base64 for a TEXT column and raw bytes for a file. The key is a `Zeroizing<[u8; 32]>` and - the hand-written `Debug` prints `Vault(…)`, so it cannot reach a log line. -- **`vault/file.rs`** — `vault.json` beside the database: format version, KDF parameters, - salt, and **the library's key sealed under the phrase**. ⚠️ The phrase does not derive the - key the notes are sealed with, it wraps it: the key is random, and a new phrase re-wraps - the same one. That is what makes a passphrase change a hundred bytes of rewriting rather - than re-encrypting every note and every attachment — an operation that could not be - atomic across the database and the files, and would leave a half-readable library if it - stopped halfway. Opening the wrapped key is also the check: a phrase that fails to open - it is the wrong phrase, said by the authentication tag, so there is no separate check - value to attack. Written staged-then-renamed, and `create` refuses to overwrite one. - - ⚠️ The other side of that coin, and the reason it is worth writing down: changing the - passphrase answers a phrase somebody **learned**, never a key somebody **took**. Whoever - got hold of the unwrapped key keeps it, exactly as with LUKS or KeePass. - -- **`create_vault` refuses a database it finds without a key file.** That is a library - that lost its key — or one written in the clear before 0.2.0, which is no longer sealed in - place (see "How far back an upgrade reaches"). A new key over it would open nothing it - holds, so it answers `LibraryDamaged`, which the gate offers to set aside. -- **`db.rs`** — `Library` carries the `SqliteConnection` **and** the `Vault`, and derefs to - the connection so the store functions did not have to grow an argument. `split()` hands - the two fields over separately where the borrow checker needs both at once, and - `Db = Mutex>` is empty until `unlock_vault` fills it — a command that - runs before the unlock answers `StorageError::Locked` rather than reading a database - nobody opened. +- **`vault/key.rs`** — `Vault`, the key and its two operations: Argon2id (`Cost`: 64 MiB, 3 + passes, 1 lane, about a second) and AES-256-GCM with a fresh 96-bit nonce a write, laid out + `nonce ‖ ciphertext ‖ tag` (base64 in a TEXT column, raw bytes in a file). The key is a + `Zeroizing<[u8; 32]>`, and `Debug` prints `Vault(…)`. +- **`vault/file.rs`** — `vault.json` beside the database: format version, KDF parameters, salt, + and **the library's key wrapped under the phrase**. ⚠️ The phrase does not derive the key the + notes are sealed with, it wraps it: the key is random, so a new phrase rewrites the key file + alone. Opening the wrapped key is the check — a wrong phrase fails its tag, and no separate + check value exists to attack. `create` never overwrites one. +- **The cost is bounded before anything is derived** (`vault::file::bounded`: at most 1 GiB, 16 + passes, 16 lanes). A key file or an export's recipe is a file someone can forge. +- **`Library`** (`db.rs`) carries the connection **and** the `Vault`, and derefs to the + connection; `split()` hands both where the borrow checker needs them at once. ### The gate -`vault_state` answers `absent` / `locked` / `unlocked` / `keyMissing`; `startApplication()` awaits it before the -first render and `app.component.html` puts `VaultGateComponent` in front of the notes page. -⚠️ It does not hide the page, it never creates it — which is what keeps every store free of a -"locked" branch: the canvas queries notes the moment it mounts, and nothing would be there -to answer. - -⚠️ The unlocked state lives in Rust and not in the front end: a page reload must not ask -again for a library this process already has open. That is also what keeps `reopenSession()` -working in the end-to-end suite, where the front end reboots and the process does not. - -⚠️ **A database without its key file is `keyMissing`, never `absent`.** The file can go missing -in ordinary ways — copied without it, dropped by a sync client — and `absent` would send the -gate to ask for a new phrase over notes no new key opens. The gate shows a panel of its own -instead: put a copy of `vault.json` back, or set the library aside (`set_aside_damaged_library`, -which leaves the key file alone and so comes back `absent`). `vault::create` refuses the same -case on its own, a command being reachable from more than the gate. - -Every passphrase field is `autocomplete="off"`: a WebView carries no password manager to fill -or save one — they are browser extensions — so `new-password` / `current-password` would -promise what nothing delivers. A phrase kept in a manager is pasted. One "Afficher" toggle (`aria-pressed`, the -input's `type` flipped rather than a second plain-text field) shows both fields at once, and -on creation the minimum is the field's description from the start rather than a complaint -after the first character. - -**The cost in a key file, or in a protected export's recipe, is bounded before anything is -derived** (`vault::file::bounded`: at most 1 GiB, 16 passes, 16 lanes). They are the inputs an -attacker can write, and read unbounded one is a multi-gigabyte allocation or an hour of hashing on -the database thread, at every unlock or at the import of a forged file. - -### The gate, drawn - -`ui::gate` is the first screen of a launch and of every library switch: nothing else is drawn -until the library is open. `Gate` asks the vault's state and the registry, and draws one panel -in the middle of the window (`surface`, 420 px, 28 px inside), naming its library — a choice menu -when there are several — then asking what it needs: a phrase **twice, held to -`vault::MINIMUM_LENGTH` (12)** for a library that has none yet; the phrase **at any length** to -unlock one; nothing but « set it aside » for a damaged or keyless one; a confirmation before -archiving one whose phrase is forgotten. A wrong phrase says so on the problem line, whose room -is kept so the button never moves; `LibraryDamaged` turns the form into the damaged panel. -Opening another library re-asks everything and resets the library scope. +`vault_state` answers one of four states, and `ui::gate::Gate` draws one panel for it in the +middle of the window (420 px), naming its library — a choice menu when there are several: + +| `VaultState` | The gate asks | Service function | +| ------------ | --------------------------------------------------------- | ---------------------- | +| `Absent` | a new phrase, twice, at least 12 characters | `create_vault` | +| `Locked` | the phrase, any length | `unlock_vault` | +| `KeyMissing` | nothing: put `vault.json` back, or set the library aside | `set_aside_damaged_library` | +| `Unlocked` | nothing: the gate gives way | — | + +- `LibraryDamaged` (from an open's `quick_check`) turns the form into « set it aside ». +- « Forgotten your phrase? », only on a library that exists, asks for a confirmation in place of + the form, then archives it sealed (`archive_locked_library`, → "Damaged or forgotten: a library + set aside"). +- ⚠️ **A database without its key file is `KeyMissing`, never `Absent`**: a copy made without + it, a sync that dropped it. `Absent` would ask for a new phrase over notes no new key opens; + `create_vault` refuses that case on its own too. +- A wrong phrase says so on the problem line, whose room is kept so the button never moves. +- The index fills behind the gate after an unlock; `Gate` keeps how far it got. ⚠️ **The phrase is typed into `gate::passphrase::PassphraseField`, never egui's `TextEdit`**, -which keeps an undo history in egui's memory. The field keeps nothing of its own: the text is a -`Zeroizing` the gate's view owns, typed at its end (letters, a paste, an input method's -committed text, Backspace; Enter submits), and `passphrase::take` hands it to the core and -leaves the field empty — the core wipes it once used. A test types a phrase and looks for it in -egui's memory and in the AccessKit tree. `gate::prompt` is the same field in a modal on the -`Passphrase` rung, for a file sealed with a phrase of its own (protect: the floor and twice; -unlock: any length). - -The index fills behind the gate after an unlock (`IndexProgress`, `IndexReady`), and `Gate` keeps -how far it got: the views say they are partial until it is whole. +which keeps an undo history in egui's memory. The text is a `Zeroizing` the gate's view +owns; `passphrase::take` hands it to the core and empties the field, and the core wipes it once +used. A test types a phrase and looks for it in egui's memory and in the AccessKit tree. +`gate::prompt` is the same field in a modal, for a file sealed with a phrase of its own. ### The floor -**Twelve characters, for a phrase being chosen.** `vault::MINIMUM_LENGTH` crosses as -`MINIMUM_PASSPHRASE_LENGTH`, and `vault::validate` holds it in Rust for a new library, a -changed phrase and a protected export — the export being the one file meant to travel, it faces -the same offline guessing. A length and nothing else: composition rules push people towards one -memorable pattern, and a strength meter is a dependency and a chunk of bundle. +**Twelve characters, for a phrase being chosen** (`vault::MINIMUM_LENGTH`), held in Rust for a +new library, a changed phrase and a protected export. A length and nothing else: composition +rules push people towards one memorable pattern. -**Not at unlock.** The gate and the import prompt check nothing but emptiness: a wrong phrase -is the key file's to refuse whatever its length, and a length hint on a phrase the user already -has is noise. +**Not at unlock**: a wrong phrase is the key file's to refuse, whatever its length. ⚠️ **The floor is a length, not a `Cost`.** Argon2id makes each guess expensive; only the length -makes the guesses many, and only the second grows exponentially. At 64 MiB a GPU runs about -VRAM ÷ 64 MiB guesses in parallel — on the order of a thousand a second on one consumer card, an -estimate from memory bandwidth rather than a measurement — against the 25–30 bits a human-chosen -eight characters really carries: days, not years. The parameters travel in the key file so that -they can be raised later; re-keying is a different job. +makes the guesses many, exponentially. At 64 MiB a consumer GPU tries on the order of a thousand +phrases a second, against the 25–30 bits a human-chosen eight characters carry: days, not years. ### Changing the passphrase -`change_passphrase` (from Préférences → Sécurité) unlocks with the current phrase, then -rewrites the key file with a fresh salt and the same library key wrapped under the new -one. ⚠️ It refuses before writing anything when the current phrase is wrong — a change -that took it on trust would lock the library behind a phrase nobody chose. The open -session is untouched: the key in memory is the one that was already there. - -⚠️ The command asks for the connection only to check that the library is open, then -releases it: holding the mutex across the derivations would freeze every other command. - -⚠️ **Rewriting the live key file alone revoked nothing**, which is the whole of #157. A -change is the gesture somebody makes when they think the old phrase leaked — and every -retained backup kept a key file of its own, still wrapped under it, inside the same profile -directory the library is in. Whoever copied the profile copied every phrase the user had -ever retired, and the envelope means **one master key for the life of the library**, so any -key file ever written is a permanent escrow for it. A note written _after_ the change opened -under a phrase abandoned before it. - -So `backup::copies::rewrap` is the second half, and `vault::gate::change` is the one place that holds -both. Three things decide its shape: - -- It writes the key it is **given** rather than opening each copy with the phrase being - retired. A backup's file wraps that same master key whatever phrase was current when it - was taken, so this retires **every** abandoned phrase at once — including one from three - changes ago, which could never have been opened with the current phrase to be rewrapped - the obvious way. -- **The live file first.** If it cannot be written the whole change fails having touched - nothing; it is the only one whose loss is fatal. Each copy then goes through the same - staged-then-renamed write, so a copy is atomic for itself even though the set is not. -- A copy it cannot rewrite is **counted, not fatal**. Refusing to rotate the phrase because - one backup's file is locked would block the revocation at the moment it is asked for. - `PassphraseChange { backupsRewrapped, backupsLeft }` crosses the bridge and `VaultStore` - turns it into one of three sentences — the report comes from the store and not from the - dialog, which closes on the click. - -⚠️ `damaged/` is deliberately absent: `recovery::set_aside` leaves `vault.json` where it is, -so a set-aside library has no wrapping of its own to retire and opens under the new phrase -like the live one. And the dialog says the part the application cannot act on — a key file -the user copied elsewhere still opens with the old phrase, and only the user knows about it. +`change_passphrase` (Preferences → Security) unlocks with the current phrase, then rewraps the +same key under the new one with a fresh salt. ⚠️ It refuses before writing anything when the +current phrase is wrong. The open session is untouched, and the connection is held only to check +that the library is open: the derivations run outside the lock. -## Several libraries, and the registry beside them +⚠️ **Every retained copy's key file is rewrapped too** (`backup::copies::rewrap`, called by +`vault::gate::change`). A change is what someone does when they think the old phrase leaked, and +every copy kept a key file wrapping the same key under an older phrase — one key for the life of +the library, so any key file ever written opens it. -There used to be exactly one library and its address was compiled in. `app_data_dir()` for -the directory, `devnotes.sqlite3` for the database, `attachments/` and `backups/` beside -it — four names that are the **address of a library** rather than decoration. +- It writes the key it is **given**, so it retires every abandoned phrase at once. +- **The live file first**: if it fails, nothing was touched. Each copy is then written staged and + renamed. +- A copy it cannot rewrite is **counted, not fatal** (`PassphraseChange`): refusing the rotation + over one locked file would block it when it is asked for. + +⚠️ It answers a phrase somebody **learned**, never a key somebody **took**. A key file copied +elsewhere still opens with the old phrase; the dialog says so. + +## Several libraries, and the registry beside them ``` -data_dir()/com.devnotes.app/ - libraries.json ← the registry: the list, and which one is open - preferences.json ← the application's preferences - open/ ← decrypted attachment copies, every library's +/ (com.devnotes.app, D16) + libraries.json the registry: the list, and which one is open + preferences.json the application's preferences + open/ decrypted attachment copies, every library's libraries/ / - devnotes.sqlite3 vault.json preferences.json + .sqlite3 vault.json preferences.json attachments/ backups/ damaged/ archived/ replaced/ ``` -⚠️ **The registry is beside the libraries and no library owns it.** One that is deleted, -moved by hand or sealed under a forgotten passphrase takes nothing else with it — which is -exactly the situation #252 is about, seen from the other end. - -⚠️ **Every library has the same shape**, including the one that was already there: -`libraries::registry::gather` moves it — database, sidecars, key file, attachments and the four -directories a library accumulates — into `libraries//` the first time the registry is -read. That move is best effort and never fatal, and the same move runs again over whatever -is left, so a half-finished one is picked up by the next launch. Uniformity is what makes -the first library deletable like any other and keeps the profile root down to two files. - -**An open library carries its own directory.** `db::open` receives the database path, so -`Library::directory()` is its parent, and every command behind the gate — attachments, -export and import, the trash purge, the backups, the passphrase change — asks the library it -already locked. ⚠️ `libraries::open_directory(app)` reads and parses `libraries.json` on -every call, so it is kept for what runs while **no** library is open: `vault_state`, -`create_vault`, `unlock_vault` and the recovery commands. Reading the thumbnail of a -screenshot used to pay that lookup plus two `create_dir_all`; `attachments/` is now created -once, by `vault::gate::install`. A module that reaches for `Paths::profile` directly writes -into the profile, which holds no library. The one directory that lives there on purpose is -`open/`, the decrypted attachment copies: they are ephemeral and swept wholesale, and one -directory means one sweep catches every library's leftovers. - -**Switching is a full teardown.** `open_library` empties the connection `Mutex` under the same -lock every other command takes, then `AppState::reset_library_scope` drops what belonged to the -library, panels included. The vault state lives in the core, so the window comes back on the gate -of the library just opened. ⚠️ The other -library has its own passphrase, and asking for it is the only proof the right one is open. - -⚠️ **A reload, not a gate over the same stores.** Destroying the notes page is not enough: every -store is `providedIn: 'root'` and outlives it. `SpacesStore` loads once and nothing -reloaded it on a switch, so going back to a library that was already seeded left the rail -listing the other library's spaces and the board asking this database about a space it had -never held (#318) — with the selection, the retained views and the undo record behind them. -Resetting each store by hand was the alternative and was refused: a dozen stores to wire, -and the next one to forget brings the bug back. The cost is the reload itself, and the dark -base showing for as long as it does at every launch. - -⚠️ **The gate says which library it asks for, and offers the others.** The File menu is -gated on an open library, so before this the gate asked for _a_ phrase and the only way to -another library was to open the wrong one first. A line at the head of every panel — form, -forgotten phrase, damaged file — names it; with several, that line is a choice menu calling -`openLibrary`, which reloads like any other switch. The one library that predates names -gets no line: "Library: Library" says nothing. - -⚠️ **Creating opens.** One gesture rather than two: you have just named it, so you want to -be in it, and the gate then asks for a phrase exactly as a first launch does. The surprise -would be staying where you were. - -⚠️ **Neither the open library nor the last one can be deleted**, refused in Rust _and_ in -the store — a command is reachable from more than the interface. Deleting files under a -live connection is how a library that was merely unwanted takes the process down; deleting -the last leaves the gate with nothing to offer, and the next read of the registry would -adopt an empty profile as a library nobody asked for. The deletion itself gets the -treatment emptying the trash gets: a sentence naming what goes, and a confirm somewhere -other than the button that fired it. - -⚠️ The registry is **written durably**, like an export file and the key file -(`engine::durable`): staged, flushed to the disk, renamed, then its folder flushed on Unix. -`fs::write` truncates first, so a disk that fills mid-write would leave a registry naming no -libraries at all; and without the flush, a power cut can leave the renamed file empty. -⚠️ **A registry that does not read is never written over** (`registry::rebuilt`): an absent -file is a first launch, an unreadable one is moved aside as `libraries.json.unreadable-` -and the list made again from the folders under `libraries/` that hold one. Their names were in -the file: they come back unnamed. +The names come from `layout.rs`, and the database's from the slug (D36): they are the address +of an installed library (→ "The application's names"). + +- ⚠️ **The registry is beside the libraries; no library owns it.** One deleted, moved by hand or + archived takes nothing else with it. +- **An open library carries its own folder** (`Library::directory()`), and everything behind the + gate asks it. ⚠️ `libraries::open_directory` reads the registry on every call: it is for what + runs while **no** library is open (the vault state, create, unlock, recovery). +- ⚠️ **The registry is written durably** (`engine::durable`): staged, flushed, renamed, its + folder flushed on Unix. **One that does not read is never written over** + (`registry::rebuilt`): it is moved aside as `libraries.json.unreadable-` and the list is + made again from the folders under `libraries/`, unnamed. +- **Switching is a full teardown.** `open_library` empties the connection `Mutex` and the index, + `AppState::reset_library_scope` drops everything that belonged to the library (→ "State + between frames"), and the gate asks for the other library's phrase — the only proof the right + one is open. +- **Creating opens**: the gate then asks for a phrase, as a first launch does. +- ⚠️ **Neither the open library nor the last one can be deleted**, refused in Rust. Deleting + under a live connection takes the process down; deleting the last leaves the gate nothing to + offer. ## Two scopes of preference, one prefix apart -A preference belongs to the **application** or to the **library**, and the line is one -prefix: ⚠️ **`devnotes.notes.*` is the library's, everything else is the application's.** +A preference belongs to the **application** or to the **library**: ⚠️ **keys under `notes.` are +the library's, the rest the application's**. The code names a key without the slug; the file +holds it under it (`devnotes.notes.activeSpace`, D36). -| | file | holds | -| --------------------------- | ------------------------------------------- | ---------------------------------------------------------------------------------------------------- | -| `PreferencesService` | `preferences.json`, at the profile root | theme, language, density, the keys, the tray, autostart, the window, `automaticBackups` | -| `LibraryPreferencesService` | `preferences.json`, inside the open library | the samples marker, the space and folder it was left on, each space's view, the cards' preview lines | +| Scope | File | Holds | +| ----------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------- | +| application | `preferences.json` at the profile root | theme, language, density, the keys, the tray, autostart, the window, the area, `automaticBackups` | +| library | `preferences.json` in the open library | the samples mark, the space and folder it was left on, each space's view, preview lines, open requests | -Both extend `KeyValueStore`, which holds the synchronous cache and the plugin's own -loading — the API stays synchronous where the plugin's is not, because a preference is read -when a component is constructed and an async read would show the interface in one state -then the other. +Both are `services::preferences::Preferences` (→ "Preferences, settings and the notifiers"): +the application's is read by `main` before the window, the library's on the db queue each time +a library opens, so a space id never crosses into another library and a samples mark never +leaves a fresh library without a space. -**The space and the folder a library was left on** (`devnotes.notes.activeSpace`, -`devnotes.notes.activeFolder`) are written on every choice and read when the notes page opens — -before, the library's file is not open, and the title bar has already built `SpacesStore`. A -space or a folder gone since falls back on « Tous les espaces » or every note by itself. The -first launch's own pick of the seeded space is shown, not remembered: nothing was chosen yet. +- **The space and folder a library was left on** (`notes.activeSpace`, `notes.activeFolder`) + are written at every choice; one gone since falls back on all spaces, or every note. +- ⚠️ `automaticBackups` stays with the application: copying at launch is a habit, not a property + of a corpus. The interface hands the core a plain flag (`Engine::keep_launch_copies`). -⚠️ `automaticBackups` stays with the application deliberately: "copy my libraries at -launch" is a habit rather than a property of one corpus. The interface reads it with the -others and hands the core a plain flag (`Engine::keep_launch_copies`) at start and at each -apply, before any unlock reads it: the core reads no file whose format is the interface's. +## The copies, and putting one back -⚠️ `LibraryPreferencesService` is re-opened on **every** switch, where the application's is -opened once. A space id means nothing in another library, and a samples marker carried -across would leave a fresh library empty with no way to create a note — a note needs a -space. +`backup::copies::rotate` takes a copy at unlock, before the sweeps, into `backups//`: -⚠️ It also **adopts** the library-scoped keys out of the application's file, once. Every -install before the registry kept both scopes in one, and without the adoption the first -launch after the upgrade re-seeds a library that is full. +- a `VACUUM INTO` of the database, its key file, and `attachments/` **hard-linked** + (`backup::copies::link_files`) — sealed under the key the copied `vault.json` wraps, so nothing + is re-sealed; +- at most one a day, the last three kept (`KEEP`). -⚠️ The word "library" was already taken on screen: the sidebar rail was labelled -_Bibliothèque_ while listing **spaces**. It now says _Espaces_, which is what it lists, and -the name is free for what the whole codebase already calls a library — the database, the -vault, "the library is locked". +A link is safe because an attachment is **never rewritten**: a new one is a new id, a purge only +unlinks. A file system that refuses links (FAT32, exFAT, some shares) gets a copy. ⚠️ A name +already in the target is left alone: `std::fs::copy` onto a link to its own source truncates +it. -⚠️ `25-libraries.e2e.ts` is **last**, after `24-forgotten-passphrase`: that one archives -the library and leaves the gate asking for a phrase on a fresh one, which is the state this -file needs. It ends on a gate too, so nothing may be filed after it. +`list_backups` answers each `Backup { id, taken_at, bytes, openable }`, newest first. `bytes` is +the database alone (the attachments are shared). ⚠️ A copy without its key file is listed, never +offered (`openable`). -## The copies, and putting one back +**Restoring replaces a whole corpus**, and is built like it: + +- ⚠️ `restore_backup` empties the connection `Mutex` and the index **before a file moves**. +- ⚠️ The live database, `vault.json` and `attachments/` go into `replaced//`, and come + back if the copy fails: a failed restore never leaves no library. Nothing is deleted. +- ⚠️ `vault.json` travels with the copy (unlike a library set aside): a database from one + wrapping with a key from another opens nothing. +- The id is matched against the listing, never joined onto `backups/` (`../…` would escape it). -`backup::copies::rotate` takes one at unlock, before the sweeps, into `backups//`: a -`VACUUM INTO` of the database plus its key file and `attachments/`, at most one a day, the -last `KEEP` kept. The attachments are **hard-linked** (`backup::copies::link_files`), sealed under the -key the copied `vault.json` wraps, so nothing is re-sealed. The copy runs inside -`unlock_vault`, under the lock: duplicating the bytes there would hold the gate for as long -as they take, and make `backups/` `KEEP` times the attachments. A link is free and -safe because an attachment is **never rewritten**: a new one is a new id, an import remaps the -id, and a purge or the orphan sweep only unlinks — so a file deleted from the library stays -whole in the copies. `backups/` sits inside the library's directory, on the same volume; a -file system that refuses a link (FAT32, exFAT, some network shares) gets a copy instead. -⚠️ A name already in the target is **left alone**, never copied over: it is the same -attachment and often the very same file, and `std::fs::copy` onto a link to its own source -truncates the bytes it is about to read. A restore that could not move the live -`attachments/` aside links into it, which is when that happens. What a link does not do is -protect against the file being damaged on disk; a copy on the same disk barely did either. -None of that used to be visible. There was no list, no date, no size, no way to put one -back, and the switch that controls it stood with nothing beside it — a safety net nobody -can see is one nobody trusts, and one nobody can use. - -The **Sécurité** page now says it where the application can be read from: what the copies -are, where they live, how many are kept, and what they do **not** cover — a copy inside -the profile answers an emptied trash, a botched update or a slip of the hand, not a dead -disk — and that the attached files are linked rather than duplicated. - -`list_backups` answers `Backup { id, takenAt, bytes, openable }`, newest first. `bytes` is -the database alone: the attachments are shared with the library and the other copies, and -counting them in each would make three copies look like three times the disk. ⚠️ -`openable` is the key file: a copy without one opens for nobody, so it is **listed and -never offered** — proposing it would be proposing to lose the library for nothing. ⚠️ -`bytes` crosses as `f64`, which specta types as nullable because JSON cannot carry `NaN`; -`backups.repository.ts` puts that back, alongside the ISO instant. - -**Restoring is the one gesture in the application that replaces a whole corpus**, and it -is built like it. - -- ⚠️ `restore_backup` empties the connection `Mutex` **before a single file moves**, under - the same lock every other command takes. Renaming a database out from under a live - connection is how a working library becomes a lost one. -- ⚠️ `backup::copies::replace` moves the live database **and** `vault.json` into - `replaced//` before copying the chosen pair in, and moves them back if the - copy fails. A failed restore must never leave no library at all. Nothing is deleted: a - folder with a date on it is the difference between a mistake and a loss. -- ⚠️ `vault.json` travels, unlike `recovery::set_aside` where it deliberately stays. The - copy brings its own wrapping, and a database from one wrapping with a key from another - opens nothing. -- ⚠️ `attachments/` follows the copy. The live directory goes into - `replaced//` with the database — an attachment added since is kept there, not - lost — and the copy's is linked back. -- ⚠️ The id is matched against the listing rather than joined onto `backups/`. It comes - from the front end, and `../2026-01-01_00-00-00` joins to a path outside the directory - whose file name still parses as a stamp. - -Afterwards every command answers `Locked`, and the page reloads to the gate, as opening -another library does: a `VaultStore.load()` over the same stores, all `providedIn: 'root'`, -carried the replaced library's notes, undo record and open Preferences past the unlock. The -restored copy needs a passphrase, and asking for it is the only proof the right file is in -place. Where the replaced files went is what `restore_backup` answers: the gate says it. - -⚠️ `BackupsState` follows the shape the tag manager and the trash already use: `ask()` -only **proposes**, `pending()` names which copy, and the confirmation is what writes. A library -archived, set aside or restored loses its samples mark: its successor holds no space, where no -note can be created, and the next open seeds only where there is none. The trigger is replaced by that sentence and the confirm sits somewhere else -— a second click on the button that fired it is the guard a double click defeats. The -strip scrolls itself into view, because it replaces a trigger further down a panel that -scrolls and would otherwise appear below the fold. - -Journey 12 goes through that gate for real: it replaces the library, unlocks the copy, and finds -the note erased and nothing written after the copy. +Afterwards the gate asks for the copy's phrase and says where the replaced files went. +`BackupsState` proposes (`ask`), names the copy (`pending`) and writes only on a confirmation +placed elsewhere than the button that asked. A library archived, set aside or restored loses its +samples mark, so the next open seeds where no space exists. Journey 12 restores for real. ## Attachments, and the one plaintext copy -The bytes are sealed on the way in (`attachments::files::store_new`) and opened in memory -on the way out: `read_attachment` decrypts into the `data:` URI the preview already used, -and `save_attachment` writes plaintext where the user chose to put it. The three read commands -hold the lock for the lookup alone (`attachments::files::read_outside_lock`): the file is read -and opened after it, the key travelling as `Library::shared_vault`, since up to 10 MiB read -and decrypted is time every other command would spend waiting. - -⚠️ `open_attachment` is the exception, and a deliberate one: the program that opens a -document reads it from disk, so DevNotes writes a decrypted copy under `app_data_dir()/open/` -and opens that — one click, as before. The copy is `/` (`Attachment::opened_copy`): -the viewer shows the name the user knows, and two of one name do not meet. Those copies are swept on the way out -(`App::on_exit`) and again at every launch, which is what covers one another application -still held, and a crash. ⚠️ The profile and **not** the OS temporary directory: that one is -shared with every account on the machine, where the copy would be readable by all of them -and a directory somebody else created first would be theirs rather than ours. +The bytes are sealed on the way in (`attachments::files::store_new`, up to `MAX_BYTES`, 10 MiB), +written **before** the record (a file without a record is swept at the next launch; a record +without a file would be a broken thumbnail), and opened in memory on the way out. The read +service functions hold the lock for the lookup alone and read and open the file after it, the +key travelling as `Library::shared_vault`. + +⚠️ **`open_attachment` writes a decrypted copy**, because the program that opens a document reads +it from disk: `/open//` (`Attachment::opened_copy`). The copies are swept +at exit and at every launch, which covers a program still holding one, and a crash. ⚠️ The +profile, not the system's temporary folder: that one is shared with every account on the machine. ## Import, export and copying out -- **Export writes an archive**, `.devnotes`, which is a zip: `bundle.json` at the root - (`transfer::model::Bundle` — a version, an instant, the spaces cited, the notes and the - attachment records) and one entry per attachment under `attachments/`, named by its - `stored_name`. The bundle is deflated, being repetitive text; the attachments are stored as - they are, a PNG being compressed already. The format reuses the domain types rather than - duplicating them, so a field added to `Note` is exported without anyone thinking about it. - Only the spaces actually cited travel: exporting one space should not recreate a whole tree - on the other side. -- **The file is written and read off the db queue** (1.0.2): an export reads its rows there, - then opens, seals and zips every attachment on a blocking thread with the key alone - (`Library::shared_vault`); an import reads and opens the file there before it merges on the - queue; adding an attachment reads its source there. A large export held every other command - for its length (20 s for 160 MB in a debug build). `export_notes`, `import_notes` and - `attach_file` are therefore network-shaped (`Arc`, `Backend::spawn`). The file is - staged then renamed, so a window closed in the middle leaves no half export. -- **⚠️ An export can be sealed, and with a key of its own.** The library key is derived - from the passphrase typed at launch and never leaves the machine; an export is the one - file meant to reach another one, so `transfer/protect.rs` derives a second key from a - phrase the user gives that file, and writes the recipe (version, algorithm, cost, salt) - in the clear beside the payload — a salt is not a secret, and a reader has to know how - to derive before it can ask anything else. The sealed `bundle.sealed` **replaces** - `bundle.json` rather than sitting beside it, or a reader that could not open it would - quietly fall back on a bundle in the clear. Attachments are opened under the library key - and resealed under the export’s, so the file is openable by whoever was given the - phrase and by nobody else. -- **⚠️ An unprotected export is still written, and is still plaintext.** Refusing one would - break the portability the exchange format exists for. What the interface owes the user - instead is to ask which of the two it is about to write (`PassphrasePromptComponent`, - with the warning beside the button) and to say which one it wrote — `ExportReport.protected` - picks the message. On the way in, `export_is_protected` is what lets the prompt appear - before the import starts rather than as a failure after it; a refused phrase asks again - rather than failing, since it is the ordinary answer to a typo. -- **⚠️ Base64 inside the JSON was the obvious alternative and was refused.** It costs a third - more bytes, and the import path holds the file as a `String`, then a `serde_json::Value`, - then a `Bundle` — three copies of every screenshot in memory, which a library of a hundred - captures turns into a gigabyte. `file::Payload` hands entries over one at a time instead. -- **⚠️ A new DevNotes reads an old file; an old DevNotes does not read a new one.** `file::read` - sniffs the zip magic and falls back to parsing the whole file as JSON, so every `.json` - export written before the archive still imports. The picker keeps `json` among its - extensions on the way in for exactly that reason, and offers only `devnotes` on the way out. - `FORMAT_VERSION` is untouched: the container changed, the data shape did not. -- **Import merges, it never replaces.** Spaces are matched by name, case-insensitively, and a - note whose id is already taken is counted as skipped rather than overwritten — so the same - file can be imported twice without duplicating anything. A bundle from a newer format - version is refused outright rather than half-read. -- **An attachment comes back only with a note that actually arrived.** One belonging to a - skipped note is already in the library. ⚠️ The file is written **before** the record, the - rule `attachments.rs` already holds — a record without a file is a broken thumbnail, where - a file without a record is swept at the next startup, which is also what collects these if - the transaction rolls back. A record the archive names but does not carry is counted in - `attachments_missing` rather than swallowed: the note arrives with a preview that will stay - empty, and the report is the only thing that explains it. -- **What arrives is sealed and measured, never trusted.** The bytes go through - `sealed::write_sealed` like every other writer on that directory — in the clear it would - sit readable beside a sealed library, and never open — and the record's `byte_size` is the - length that arrived, not the one the file declared. -- **An archive entry is read under a ceiling.** `bundle.json` and the recipe may expand to a - hundred times their compressed size, with a 64 MiB floor so a small entry is never refused over - its ratio: a guard against a decompression bomb, not against a large export, which grows - with the corpus. An attachment is read up to `MAX_BYTES` (plus the seal's overhead when the - file is protected); past it, it is counted in `attachments_missing` and the note still - arrives. -- **Copying out stops at the clipboard.** `share_notes` renders the selection as Markdown - (heading, space, context, tags, then a fenced block). The fence is longer than the longest - run of backticks in the content, otherwise a note that already contains a Markdown block - would cut its own in half. The menu entry names the format — "Copier la sélection en - Markdown" — because a format nobody asked for is a surprise, not a feature. - -⚠️ **Every one of these reports, including when it changed nothing.** Exporting then -re-importing at once is the first thing anyone tries, and it legitimately imports zero notes: -every id is already there. Without a message that outcome is indistinguishable from a -failure, so `TransferStore` pushes a distinct `file.importedNothing` for it, and an export -names the file it wrote. **An export of nothing is said first**: `count_export` answers how many notes -the scope holds before the save dialog, so an empty space asks for no place and no phrase, and -`export_notes` writes no file for a bundle with no note. The report goes to `StatusNotifier` (`core/services/notifications/`), rendered -under the titlebar by `StatusToastComponent` — not inside the menu, which closes on the click -and which a native file dialog covers anyway. - -`transfer::collect` and `transfer::merge` take a `&mut SqliteConnection` rather than living -inside the commands, which is what makes the round trip testable (`tests/transfer.rs`) without -a Tauri runtime. - -The file itself is written and read **in Rust**: the serialisation is the domain's, and -sending it across the bridge to be reassembled in TypeScript would mean a second format to -keep in step. The front-end only picks a path, through `FileDialogService`. +- **Export writes an archive** (`.devnotes`, from `file-extension`), a zip: `bundle.json` + (`transfer::model::Bundle` — version, instant, the spaces cited, the notes, the attachment + records) and one entry an attachment under `attachments/`. Only the spaces cited travel. The + format reuses the model's types: a field added to `Note` is exported with it. +- **Off the db queue**: an export reads its rows in a job, then opens, seals and zips the + attachments on a blocking thread with the key alone; an import reads the file there before it + merges in a job. `export_notes`, `import_notes` and `attach_file` are network-shaped + (`Arc`, `Backend::spawn`). The file is staged then renamed. +- **⚠️ An export can be sealed with a phrase of its own** (`transfer/protect.rs`): the recipe + (version, algorithm, cost, salt) in the clear, and `bundle.sealed` **in place of** + `bundle.json`, never beside it. Attachments are resealed under the export's key. +- **⚠️ An unprotected export is still written, in the clear.** The interface asks which one it + is about to write (`gate::prompt`) and the report says which it wrote. `export_is_protected` + lets the import ask for the phrase before it starts; a refused phrase asks again. +- **Old files still import**: `file::read` sniffs the zip magic and falls back on a whole-file + JSON, so the import's picker offers `json` beside the extension. `FORMAT_VERSION` moves only + when the data's shape does; a newer one is refused, not half-read. +- **Import merges, never replaces.** Spaces match by name, case-insensitively; a note whose id + is taken is skipped, so importing a file twice duplicates nothing. An attachment comes back + only with a note that arrived; one the archive names but does not carry is counted + (`attachments_missing`). +- **What arrives is measured, never trusted**: sealed like every other write, its `byte_size` + the length that arrived. An entry is read under a ceiling (a hundred times its compressed + size, 64 MiB at least; an attachment up to `MAX_BYTES`). +- **Copying out stops at the clipboard**: `share_notes` renders the selection as Markdown, its + fence longer than the longest run of backticks inside. + +⚠️ **Every one of these reports, even when nothing changed.** Re-importing a file just exported +imports zero notes, which must not look like a failure; an export names the file it wrote. **An +export of nothing is said first**: `count_export` answers before the save dialog, and no file is +written for a bundle without a note. The reports go to the status toast (`StatusNotifier`). +`transfer::bundle::collect` and `transfer::bundle::merge` take a `Library`, so the round trip is +tested without an engine (`tests/transfer.rs`). diff --git a/docs/architecture/interface/desktop.md b/docs/architecture/interface/desktop.md new file mode 100644 index 00000000..fcdaa2c3 --- /dev/null +++ b/docs/architecture/interface/desktop.md @@ -0,0 +1,129 @@ +# The binary and the desktop + +`crates/app`, the binary, and `crates/platform`, what is asked of the operating system: the +profile, one instance, the window, the tray, the global keys, closing and quitting. +[Home](../README.md) + +**In short** + +- One process per profile, claimed before anything else is written. +- A panic is logged without its message, said in a dialog, and ends the process (D18). +- Every desktop subject is a trait in `platform` with a fake for tests; what only a real desktop + can run sits in a `system.rs` and is checked by hand (`docs/recette/recette.html`). +- The close button hides the window; « Quit » alone ends the process. + +## The binary, its profile and its window + +`main` (`crates/app/src/main.rs`), in order: + +1. **The panic hook** (`logging::install_panic_hook`), first, for the script host too. +2. **`--script-host`**: the binary relaunched to run a request's scripts serves them and exits — + no window, no log (→ "Request scripts, in a process of their own"). +3. **The arguments**: `--profile ` puts the whole profile, its logs and the window's + geometry in that folder (tests and development); `--action ` asks the running instance + for `palette`, `capture`, `new-note` or `quit`. Without `--profile`, + `platform::paths::Locations::installed` resolves the profile named by the `identifier` + (`com.devnotes.app`, D16): roaming data on Windows, `$XDG_DATA_HOME` and `$XDG_CONFIG_HOME` + on Linux, the logs under the local data folder. +4. **The claim** (`platform::instance::claim`), before the log: a second launch writes nothing. +5. **The log** (→ "The three outputs"), then a check that what winit needs is installed + (`libxkbcommon-x11` under X11). +6. **The window**, opened **hidden** at the geometry `platform::window` read back, drawn on the + first frame. Its creation closure starts the tokio runtime and the `Engine` (D20). eframe's + persistence stays off: it would write egui's state, text fields included, in clear. + +**One application per profile (D16).** `instance::claim` binds a local socket named after a +digest of the profile's canonical path (a named pipe on Windows, the abstract namespace on +Linux). A second launch that cannot bind it connects, sends `reveal` or `action `, and +exits; the first hears it on a thread of its own. Two profiles never collide, so a journey never +meets a development instance. A claim that fails otherwise stops the launch: a second writer +would leave the index silently wrong. + +- ⚠️ Any user of the machine reaches the abstract namespace: the first instance reads who + connected (`peer_creds`) and listens to its own user alone. +- ⚠️ Windows answers a pipe already taken with « access denied », not « address in use ». + +**A panic ends the process (D18)**, whatever the thread. The hook logs where and on which +thread, **never the message** (a panic slicing a string quotes it), flushes the log, tells the +person in a system dialog in their language naming the log's folder (never in the `e2e` +flavour), and exits with 101. Nothing is caught: a job that panicked halfway leaves state no one +can vouch for, and SQLite's journal keeps what was committed, which the next open checks. The +release is `panic = "abort"`. + +**One graphics API** (`app::renderer`). eframe's own setup opens Vulkan, DX12 and OpenGL +together, each keeping every GPU's driver loaded (~55 MB on a machine with two GPUs). On Windows +DX12 alone is opened when a real GPU answers it; otherwise, and whenever `WGPU_BACKEND` is set, +eframe chooses. The device reserves memory by small blocks (`MemoryHints::MemoryUsage`). Under +Linux, X11 (XWayland) is taken whenever `DISPLAY` exists (D15). + +**The geometry** is written on exit: size, place, maximised (the size before maximising kept +under it), never whether the window was visible, never a full screen. + +## What the desktop answers + +`ui::Desktop`, built by `crates/app/src/desktop.rs` on the thread the window's loop will run on +(under Windows that loop serves the tray and the keys). Its `Default` answers nothing, so no test +touches the session. + +| Field | `platform` module | What it does | +| ----------- | ----------------- | ----------------------------------------------------------------------------------------------------- | +| `tray` | `tray` | the icon and its menu (`tray::entries`), translated, rebuilt when the language moves | +| `shortcuts` | `shortcuts` | the three global keys, first come first served; let go while a field listens (→ "Shortcuts: two vocabularies, two storage paths") | +| `autostart` | `autostart` | read at the launch; the switch pushed only when it differs | +| `notifier` | `notify` | a toast, never load-bearing: a palette copy over another application | +| `dialog` | `dialog` | the file dialog; `None` for a cancel **and** for a dialog that could not open; the XDG portal first under Linux (D29) | +| `updater` | `updater` | checks and installs (→ "Application updates") | +| `clipboard` | `clipboard` | what egui's text does not carry (a page's HTML, an image); a clipboard that cannot open answers `None` | +| `opener` | `desktop` | opens an attachment's copy with the system's program | + +`platform::links` opens `http` and `https` links only. The `e2e` flavour takes no global key, +writes no autostart entry, opens no program (`desktop::from_scenario`) and is updated by its own +server (`updater::from_scenario`). + +⚠️ `AppState::new` starts with `NoClipboard` and `NoOpener`: a screen test never pastes the +machine's clipboard nor starts one of its programs. + +## What Linux offers, desktop by desktop + +| Desktop | Tray icon | Global keys | +| ----------------------------------------------- | ------------------------------------------------------------ | --------------------------------------------------------------------------- | +| KDE Plasma, XFCE, Cinnamon, MATE, Budgie | StatusNotifierItem over D-Bus (D29) | X11's grab; under Wayland the global-shortcuts portal (Plasma ≥ 5.27) | +| GNOME ≥ 48 | with the AppIndicator extension only | the global-shortcuts portal | +| GNOME 46 (Ubuntu 24.04) | with the AppIndicator extension only | GNOME's own custom shortcuts, written with `gsettings` | +| anything else under Wayland | — | nobody: Preferences → Shortcuts shows the three commands to bind by hand | + +- **The tray** registers on a thread of its own and follows the watcher: a panel that starts + after us, restarts or is turned on later gets the item again. Without a watcher it answers + `exists() == false`, and a closed window hides all the same. Windows and macOS use + `tray-icon`. +- **Under Wayland** (whenever `WAYLAND_DISPLAY` is set) X11's grab fires only while one of our + windows has the focus, so the desktop holds the keys (`Holder`), found in this order: + - *the portal*: a session bound once per change of the keys, the desktop asking the person + and sending `Activated`; keys written `CTRL+ALT+p` (`shortcuts::notation`); + - *GNOME's settings*: a custom shortcut `-` a key, running ` --action + `; the person's own are left alone, and ours stay if the application is uninstalled; + - *nobody*. + + Neither way lets go while a field listens: the desktop would take the key first. + +## Closing is not quitting + +The close button **hides** the window while « Close to tray » is on, whether the desktop shows +the icon or not: the process stays to answer the global keys, and a second launch (the menu +entry, or a desktop shortcut running `--action`) brings it back. Off, it ends the application, +as « Quit » always does (`AppState::quitting`). The preferences say which, and a desktop that +shows no icon gets a note (`AppState::tray_shown`, read from the tray each frame). + +⚠️ A hidden window draws nothing, so a close held for a question (requests not saved, the +editor's draft) brings the window up first. + +`App::on_exit`, in this order: + +1. the HTTP sends cancelled; +2. the plain copies of attachments swept, the index wiped; +3. the db queue drained (D19, 30 s at most); +4. the global keys released, the tray removed; +5. the geometry written; +6. last, an update installed. ⚠️ Under Windows the update client ends the process there, so + nothing may follow; under Linux a detached shell waits for the process to be gone before + starting the new `AppImage`, which would otherwise find the profile taken. From 51387637f751e9e39e7e1e456b14be6ee7de951d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 22:48:13 +0000 Subject: [PATCH 3/8] Architecture: the interface's pages checked against the code `interface/frame.md`, `backend.md`, `window.md` and `look.md` follow the egui code as it is. Each opens on what matters; facts that were paragraphs are tables (the queues, the widget kit, the movable keys, the motion constants, the preference pages). What described the earlier application is gone: its stores, services, stylesheets, mixins and tests, the WebView, the issue numbers. Corrected from the code: the service functions (some twenty missing, five gone), the error codes, the fifteen keys that can be moved and where each is stored, the About menu's four panels, reduced motion read from the system, the format functions, the accent's `Palette` fields. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BbVs5tCyTr9AasGra3Zzg3 --- docs/architecture/interface/backend.md | 501 +++++++-------- docs/architecture/interface/frame.md | 321 +++++----- docs/architecture/interface/look.md | 88 +-- docs/architecture/interface/window.md | 812 +++++++------------------ 4 files changed, 620 insertions(+), 1102 deletions(-) diff --git a/docs/architecture/interface/backend.md b/docs/architecture/interface/backend.md index 8b0112d2..d9f6c9ae 100644 --- a/docs/architecture/interface/backend.md +++ b/docs/architecture/interface/backend.md @@ -1,330 +1,267 @@ # Backend and events (interface ↔ core) -How the window calls the core and gets its answers: the three queues, frames and actions, notifiers, the widget kit, errors, the language, service functions and validation. [Home](../README.md) - -The interface calls the core in the same process, through **one façade**, `ui::api` — the only -place that names an engine function, one file per feature, each function choosing its queue -once — and **one backend**, `ui::Backend`, which owns the `Arc` and its tokio runtime. -The UI thread does no I/O, crypto or waiting: every call returns a `Pending`, polled each -frame (`poll` answers once), and the worker that resolves it wakes the window. - -| Queue | For | Runs on | -| --------- | ------------------------------------------------------ | ------------------------------ | -| `db` | anything touching the database or the index, reads too | the core's one db thread (D11) | -| `compute` | pure work: formatting, a tool, highlighting, decoding | rayon's pool | -| `spawn` | the network, and what chains db jobs around it | tokio | - -⚠️ `Backend::db` **queues at the call** (`engine::db::submit`), on the UI thread: two writes sent -one after the other run in that order. Handing the job to a task that queued it later let two -of them swap. A panic ends the process (D18), so no queue answers for one; an `Answer` -dropped without a word — a task dropped as the runtime stops — still answers `Unavailable`, -so **no `Pending` is ever left unanswered**. Dropping a `Pending` does not stop work begun on the database. -Every call, on any queue, is logged as it answers (→ "What the core was asked"). - -Creating or unlocking a library is a `spawn` that runs the vault's db job and then starts -`index::fill`, which fills the index a slice a job behind the gate. What the core says unasked -(`EngineEvent`) and what a second launch asks arrive on the input channel, drained at the start -of each frame. State tests run against the real core on a temporary profile and wait with -`Backend::settle()` — a condition, never a duration (`ui::testing`). - -## Data access - -**Nothing but `ui::api` names an engine function.** One file per feature (`api/notes.rs`, -`api/spaces.rs`, `api/http.rs`…), each function choosing its queue once and answering a -`Pending` (→ "Backend and events"); states call `api`, screens call neither. A state test runs -those functions against the real core on a temporary library, so there is no repository to fake -and no double to keep in step: only the platform is faked. - -There is deliberately **no function returning the raw list of notes** — offering one would invite -a caller to filter it again. That holds even for export: `export_notes` returns a _count_, and -the note list it assembled never leaves the core. - -Deleting a space takes a **refuge** rather than an id alone: a one-argument signature would make -data loss the default, since the schema cascades. Moving a single note goes through `move_notes` -like a selection, so the card menu and the editor offer the same undo; `space_id` stays in -`NotePatch` for a draft, which has no row to batch. A space deleted bumps the `Revision`, so the -canvas asks again even when its query did not mention that space. +How the window calls the core and gets its answers: the three queues, frames and actions, state +between frames, the notifiers, the widget kit, errors, and the service functions. +[Home](../README.md) + +**In short** + +- `ui::api` is the only place that names an engine function; `ui::Backend` owns the + `Arc` and its runtime. +- Every call answers a `Pending`, polled each frame; the UI thread never waits. +- Three queues: `db` (in order, one thread), `compute` (pure work), `spawn` (the network). +- A service function validates, locks, delegates and translates its error into a code. +- The interface translates every code by an exhaustive `match`: a new code does not compile + until both languages have its sentence. + +## Backend and events + +The UI thread does no I/O, crypto or waiting (D11, D12): every call returns a `Pending`, +polled each frame (`poll` answers once), and the worker that resolves it wakes the window. + +| Queue | For | Runs on | +| --------- | ------------------------------------------------------- | ------------------------------- | +| `db` | anything touching the database or the index, reads too | the core's one db thread (D11) | +| `compute` | pure work: formatting, a tool, highlighting, decoding | rayon's pool | +| `spawn` | the network, and what chains db jobs around it | tokio | + +- ⚠️ `Backend::db` **queues at the call** (`engine::db::submit`), on the UI thread: two writes + sent one after the other run in that order. +- **No `Pending` is ever left unanswered**: a panic ends the process (D18), and an answer dropped + without a word (a task dropped as the runtime stops) answers `Unavailable`. Dropping a + `Pending` does not stop work begun on the database. +- Every call is logged as it answers (→ "What the core was asked"). +- Creating or unlocking a library is a `spawn` that runs the vault's db job, then starts + `index::fill` behind the gate. +- What the core says unasked (`EngineEvent`) and what a second launch asks arrive on the input + channel, drained at the start of each frame. +- State tests run against the real core on a temporary profile and wait with + `Backend::settle()`: a condition, never a duration (`ui::testing`). + +### Data access + +**Nothing but `ui::api` names an engine function**: one file per feature (`api/notes.rs`, +`api/http.rs`…), each function choosing its queue once. States call `api`; screens call +neither. A state test runs those functions against the real core, so there is no repository to +fake: only the platform is. + +- There is **no function returning the raw list of notes**: offering one would invite a caller + to filter it again. Even export answers a count; the list never leaves the core. +- Moving a single note goes through `move_notes`, like a selection, so the card menu and the + editor offer the same undo. A space deleted bumps the `Revision`, so the canvas asks again even + when its query did not name that space. +- A pure core function whose input the screen bounds, under a millisecond, may be called + directly — still through `api/` (detecting the language of a paste, + `notes::language::from_content`). ## The concurrency rules -These are all of them: one that is not here does not exist. There is one user and one process per -profile (D16), so what runs at once is the interface, which must never wait; two writes sent close -together; HTTP sends; and a library changed while something runs. +These are all of them: one that is not here does not exist. One user, one process per profile +(D16); what runs at once is the interface (which never waits), writes sent close together, HTTP +sends, and a library changed while something runs. 1. **One worker for the database** (D11). Everything that touches the database or the index goes - through the queue, in the order it was sent: from the interface by `Backend::db`, from a send by - `db::run`. A job of the queue never waits for another one, which would lock both, nor for the - network. + through the queue, in the order it was sent: from the interface by `Backend::db`, from a send + by `db::run`. A job never waits for another job, nor for the network. 2. **A long operation holds the queue, not the interface.** Export, import, backup, restore and a - change of passphrase take the time they take; a search typed meanwhile answers after. The index - is filled by slices, between which a search slips in. -3. **Snapshots are not changed in place.** The index holds `Arc`s, and a write replaces - one. A view keeps the ones it was given, and is drawn without a lock. -4. **A send is three steps**: read (a db job: inheritance, variables, environment, a copy of the - cookie jar, the library's number), send (on tokio, never through the queue), write (a db job: - history, cookies, variables). The last **merges**: cookies are replayed as changes on the jar of - the moment, variables read again before their writes are applied, so two sends at once lose - nothing. + change of passphrase take the time they take; a search typed meanwhile answers after. The + index fills by slices, between which a search slips in. +3. **Snapshots are not changed in place.** The index holds `Arc`s, a write replaces + one, and a view keeps the ones it was given: it is drawn without a lock. +4. **A send is three steps**: read (a db job), send (on tokio), write (a db job). The write + **merges**: cookies replayed on the jar of the moment, variables read again before they are + written, so two sends at once lose nothing. 5. **The library's number** (D30): a send that ends in another library writes nothing. Opening a library or restoring a copy empties the `Mutex` and the index, closes the sockets and cancels - sends and runs before it touches the files. + sends and runs before it touches a file. 6. **Writes are not optimistic**: persist, adopt the answer, bump `Revision`. A stale search is dropped (`QueryCell`). 7. **The UI thread waits once**: at exit, the window hidden, for the queue to drain (D19). -Left out on purpose: an asynchronous database, a connection pool, a version number per row, an actor -framework, the cancelling of a db job that has begun, and a parallel read path while no measure asks -for one. +Left out on purpose: an asynchronous database, a connection pool, a version per row, an actor +framework, cancelling a db job that has begun, a parallel read path no measure asks for. ## State between frames -`ui::state::AppState` is the root of what the interface remembers; each screen's state joins it -as the screen is ported. Three pieces replace the reference's `resource()`, `linkedSignal`, -`OneInFlight`, `NotesRevision` and the reload of the page: +`ui::state::AppState` is the root of what the interface remembers. Three pieces carry it: -- **`QueryCell`**: a value asked of the core again whenever its parameters change, compared - by value. `want(params)` records what the screen depends on; `update(launch)`, once a frame, - adopts the answer that arrived — unless newer parameters were wanted since, a stale search is - dropped — and asks for what is wanted when nothing is in flight. **One call in flight, the - latest waiting**; the last value stays while the next loads, and after an error. +- **`QueryCell`**: a value asked of the core again whenever its parameters change, + compared by value. `want(params)` records what the screen depends on; `update(launch)`, once a + frame, adopts the answer that arrived — unless newer parameters were wanted since — and asks + for what is wanted when nothing is in flight. **One call in flight, the latest waiting**; the + last value stays while the next loads, and after an error. - **`Revision`**: bumped after every write the interface adopts, and part of the parameters of every query that reads notes, so the list and the board ask again together. - **`LibraryCaches`**: the one field holding every cache of a library's content (D17). - `AppState::reset_library_scope` empties it and **egui's whole widget memory** — a text field's - undo history holds what was typed — then puts the application's look back, which outlives a - switch. Not wiped byte by byte: the threat model says so. + `AppState::reset_library_scope` empties it and **egui's whole widget memory** (a text field's + undo history holds what was typed), then puts the application's look back. Not wiped byte by + byte: the threat model says why. ## A frame, its actions and its keys -`App` does the same thing every frame, in this order: `logic` drains the -inputs (engine events, a second launch's `reveal` or `action `), adopts the answers that -arrived and asks the `QueryCell`s again; `ui` draws, then reads the keys the widgets left, then -applies the actions. **Drawing never changes the state**: it reads a screen's state, may change -its view (text being typed, a menu open, a scroll), and pushes `Action`s — `Action::App` for the -frame (an area, the look), `Action::Global` for what comes from outside the window (capture, new -note, palette, quit); each area's own variant joins when the area is ported. `AppState::apply` -runs them at the end of the frame, in the order pushed. - -**One order for the keyboard** (D14, `ui::keys`). An input method composing keeps every key; the -focused widget consumes what it handles while drawing; then `keys::dispatch` reads what is left -by level — the top modal, then the area on screen, then the application (`keys::APPLICATION`: -`Ctrl+1/2/3`) — and the first level that knows the key takes it and consumes it. While a text -field has the focus, only the entries marked `while_typing` are read: the « editable target » -guards of the reference, written table by table. A binding reads its key **by position** (a W3C -`code`: on AZERTY the key that types « & » is still `Ctrl+1`) or **by character** (the canvas's -keys), and its modifiers exactly. egui's keyboard zoom is off, as the WebView's was; Tab keeps -egui's focus navigation. +`App`, every frame, in this order: + +1. `logic` drains the inputs (engine events, a second launch's `reveal` or `action `, the + tray, a global key), adopts the answers that arrived and asks the `QueryCell`s again; +2. `ui` draws — reading state, changing views, pushing `Action`s; +3. reads the keys the widgets left (→ "The keyboard"); +4. applies the actions in the order pushed, through `AppState::act`. + +An `Action` is `App` (an area, the look, the rails), `Gate`, `Notes`, `Http`, `Tools`, `Menu`, +`Palette` or `Global` (what comes from outside the window: capture, new note, palette, quit). +egui's keyboard zoom is off; Tab keeps egui's focus navigation. **At the exit** the db queue is drained — the one wait the UI thread is allowed (D19): -`Backend::drain` queues a last job and waits up to 30 s for it, so everything sent before it -(drafts, an import, a restore) has run; then the geometry is written. +`Backend::drain` queues a last job and waits up to 30 s for it (→ "Closing is not quitting"). ## Preferences, settings and the notifiers -The two `preferences.json` keep the reference's format — one flat object of `devnotes.*` keys, -each a string. -`services::preferences::Preferences` keeps every key it read, those this version does not know -included, and is written staged then renamed. The code names a key without its prefix -(`"notes.activeSpace"`): `Preferences` puts the slug before it (D36). The application's file is read by `main` before -the window exists; the open library's (`devnotes.notes.*`) is read again on the db queue each -time a library opens (`AppState::reset_library_scope`). Both are written on the db queue, so two -changes in a row land in that order. - -`services::settings::Settings` is the typed part (locale, theme, density, the last area), read -with defaults for anything unknown and written back without touching the rest; a setting joins -it with the screen that reads it. `SettingsDraft` is what the preferences panel edits: only the -theme and the density are previewed before « Apply », and the native side reads the applied -settings, never the draft. - -`services::time`: an injectable `Clock` (`SystemClock`, a `FakeClock` in tests) and -`relative(at, clock)`, which answers the label and **how long it holds**, the next frame asked -for exactly then. `services::status::StatusNotifier` keeps the toasts' last reports, numbered so -the same words said twice show twice; `services::errors::ErrorNotifier` the last failures, the -same one once: the sentence its code says (an exhaustive `match` on `ErrorCode`, a code with variants -choosing its sub-key by one parameter), or the action's own when the code says nothing better. -⚠️ The error's `detail` never goes to the screen, and to the log only through `AppError::for_log`: -the code alone, its detail too where no variant carries a name, a file, a URL or a script's words. +- **`services::preferences::Preferences`**: a `preferences.json`, one flat object of string + values. It keeps every key it read, those this version does not know included, and is written + staged then renamed on the db queue. The code names a key without its prefix + (`"notes.activeSpace"`); `Preferences` puts the slug before it (D36). The application's file is + read by `main` before the window; the open library's on the db queue each time a library opens + (→ "Two scopes of preference, one prefix apart"). +- **`services::settings::Settings`**: the typed part (locale, theme, density, the area, the + rails…), read with defaults for anything unknown and written without touching the rest. + `SettingsDraft` is what the preferences panel edits: only the theme and the density preview + before « Apply », and the desktop reads the applied settings, never the draft. +- **`services::time`**: an injectable `Clock` (`SystemClock`, `FakeClock`) and + `relative(at, clock)`, which answers the label and **how long it holds**: the next frame is + asked for exactly then, so « 4 min ago » ages without repainting every frame. +- **`services::status::StatusNotifier`**: the toasts' last reports, numbered so the same words + said twice show twice. +- **`services::errors::ErrorNotifier`**: the last failures, each once — the sentence its code + says, or the action's own when the code says nothing better (below). ## The widget kit -`ui::widgets` replaces the reference's `shared/`: components painted by hand after its CSS, -reading the theme and nothing else. **Every one goes through `widgets::interact`**, which -allocates at least 24 × 24 px for anything clickable (WCAG 2.5.8), gives the AccessKit node its -role and name, sets its `author_id` — the `data-testid` its Angular twin had, which kittest and -the e2e driver find it by — and paints the focus ring. `egui::Ui::interact` is refused -elsewhere by `disallowed-methods` (`crates/ui/clippy.toml`), which is what `focus-rings.test.mjs` -checked. A text field carries its accessible name apart from its hint: kittest refuses a field -without one. - -- `Button`: `Outline` (a dialog's action — `surface` at 6 px, 6 × 12, 12 px, amber under the - pointer), `Filled` (the primary, solid amber), `Quiet` (text alone, filled when pressed), - `Destructive` (**red at rest**, `bg-3` and a red edge when armed or hovered); `.large()` is the - gate's submit. `IconButton`, `SplitButton`, `RailToggle` (32 px). -- `Chip`, `priority_dot`, `hue_badge` (the hue in the label, a neutral fill, a hairline in the - hue), `Kbd`, `spinner`. A note's kind is not a badge: `notes::ui::kind_icon` is its icon on a - tile of its hue (Snippet olive, the one hue no language uses), named for the screen reader, and - `kind_tile` the same drawing wherever a kind is chosen beside its word (« New note », the - palette). -- `Segmented` (the segment on is filled, its label bright), `TextField` (the reference's - `.input`: 9 × 11 on `bg-1`, red when refused), `SearchField`, `Checkbox`. A segment of a - `Segmented`, as an entry of a `ChoiceMenu`, wears `{author_id}-{key}` once the control is - `keyed` — the stored spelling of its value, or `widgets::variant` (`http-auth-kind-bearer`) —, and - its place among the options otherwise: a menu reordered then keeps what a test picks. - -- `menu` (an `egui::Popup` on the reference's surface: `bg-2`, 8 px, 4 px inside, the dropdown's - shadow): the first entry takes the focus, egui's arrow navigation walks the rest, → opens a - sub-menu and ← comes back, Escape closes. ⚠️ egui keeps **one** popup in its memory — the parent — - so a sub-menu keeps its open state apart. `ChoiceMenu` names its value (`Naming::Value`) or its - own label, and from `FILTER_FROM` (9) entries puts a filter on top that takes the focus. -- `DialogStack` and `dialog`: one rung per layer of `dialog.model.ts` (editor … passphrase), the - higher drawn over the lower and served first by Escape; an `egui::Modal` blocks what is under it - and keeps Tab inside; the fitted frame is `bg-1`, 14 px, `line`, the overlay's shadow, 480 px, - over a solid scrim. The focus goes back to the opener — **the frame after**, once no modal - layer blocks it (`DialogStack::begin_frame`), since egui drops a focus given while one does. -- `virtual_list` (uniform rows, only those in view drawn — 30 000 rows draw fewer than twenty), - `code_viewer` (read-only, numbered in `line_no`), `rail_frame` and `split_handle` (a drag or the - arrows, 16 px a press, within bounds), `tooltip` (drawn), `release_notes` (the core's runs: - plain, strong, code). - -Hover colours ease over `motion::FAST`; a disabled control is drawn at half strength. -`DEVNOTES_LOOK= cargo test -p ui widgets::tests::look` renders the kit in both themes, to -look at. +`ui::widgets`, painted by hand, reading the theme and nothing else. **Every control goes through +`widgets::interact`**, which: + +- allocates at least 24 × 24 px for anything clickable (WCAG 2.5.8); +- gives the AccessKit node its role and name; +- sets its `author_id` — the name kittest and the e2e driver find it by; +- paints the focus ring. + +`egui::Ui::interact` is refused elsewhere by `disallowed-methods` (`crates/ui/clippy.toml`). A +text field carries its accessible name apart from its hint: kittest refuses a field without one. + +| Family | Widgets | +| ---------- | ------------------------------------------------------------------------------------------------------------- | +| buttons | `Button` (`Outline`, `Filled`, `Quiet`, `Destructive` — **red at rest**; `.large()` for the gate), `IconButton`, `SquareButton`, `SplitButton` | +| marks | `Chip`, `priority_dot`, `hue_badge`, `Kbd`, `spinner`; a note's kind is `notes::ui::kind_icon` on a tile of its hue | +| fields | `TextField` (red when refused), `SearchField`, `DateField`, `Checkbox`, `Segmented` | +| menus | `menu`, `ChoiceMenu` (a filter on top from `FILTER_FROM`, 9, entries), `place_picker` | +| dialogs | `DialogStack`, `dialog`, `framed_dialog`, `ask_in_place`, `empty_state` | +| layout | `virtual_list`, `code_viewer`, `area_room`, `RailWidth`, `split_handle`, `tooltip` | +| text | `widgets::editor` (code), `widgets::rich` (a Note), `json_explorer`, `release_notes` | + +- A segment of a `Segmented`, like an entry of a `ChoiceMenu`, wears `{author_id}-{key}` once + the control is `keyed` (the stored spelling of its value), and its place among the options + otherwise. +- **`menu`**: the first entry takes the focus, arrows walk the rest, → opens a sub-menu and ← + comes back, Escape closes. ⚠️ egui keeps **one** popup in its memory (the parent), so a + sub-menu keeps its open state apart. +- **`DialogStack`**: one rung per layer (editor … passphrase), the higher drawn over the lower and + served first by Escape; an `egui::Modal` blocks what is under it and keeps Tab inside. The + focus goes back to the opener **the frame after**, once no modal blocks it + (`DialogStack::begin_frame`): egui drops a focus given while one does. +- Hover colours ease over `motion::FAST`; a disabled control is drawn at half strength. ## Errors are codes -A service function returns `Result`, never `Result`. An `AppError` -(`crates/engine/src/error.rs`) carries a stable **code**, its interpolation **params** and a -technical **detail**: - -```json -{ "code": "duplicateSpaceName", "params": { "name": "Perso" }, "detail": "Un espace nommé …" } -``` - -Business rules live in the core, and a message written there would be one language in an -interface showing another; branching on a cause would mean parsing a sentence that breaks at -the first rewording. - -**`AppError` appears in service signatures and nowhere else.** Helpers answer `StorageError` or -`ValidationError`, and the service function's `?` is the one translation. A file failure is -named after what it was about through `error::FileContext` — -`fs::write(&path, bytes).context(path.display())?` — which builds the `": "` -detail every `StorageError::File` carries. - -**The interface translates by an exhaustive `match`** on `ErrorCode` -(`ui::services::errors::ErrorNotifier`), so a code added in the core does not compile until it -has its key in both locales. A named cause wins over the attempted action — « this note no longer -exists » beats « could not save the note », which would leave the user retrying something that -can never succeed; the action's own sentence is the fallback when the cause adds nothing -actionable. ⚠️ The `detail` never goes to the screen; the log has it through `AppError::for_log`, for -the codes that carry nothing typed. - -Three codes exist for what happens **outside** the database: `attachmentNotFound`, `fileAccess` -(reading, copying or writing a file — attachments, export and import all land there) and -`importFormat` (a file offered as a bundle that is not one, or one written by a newer version). -Each has a different thing to tell the user, and only `importFormat` means « choose another -file ». A schema too recent for the binary has no code: it can only happen while a library -opens, and the gate says it. +A service function returns `Result`. An `AppError` (`crates/engine/src/error.rs`) +carries a stable **code** (`ErrorCode`), its **params** and a technical **detail**. A message +written in the core would be one language in an interface showing another, and branching on a +sentence breaks at the first rewording. + +- **`AppError` appears in service signatures and nowhere else.** Helpers answer `StorageError` + or `ValidationError`, and the service function's `?` is the one translation. A file failure + names its path through `error::FileContext` (`fs::write(&path, …).context(path.display())?`). +- **The interface translates by an exhaustive `match`** on `ErrorCode` + (`services::errors::ErrorNotifier`): a code added does not compile until it has its key in + both locales. A named cause wins over the attempted action (« this note no longer exists » + beats « could not save the note »); the action's sentence is the fallback. +- ⚠️ The `detail` never goes to the screen, and to the log only through `AppError::for_log`: the + code, and its detail only where nothing typed is in it. +- Three codes are for what happens **outside** the database: `AttachmentNotFound`, `FileAccess` + (reading, copying or writing a file) and `ImportFormat` (a file that is not a bundle, or a + newer one). Only the last means « choose another file ». A schema too recent has no code: the + gate says it. ## The language is detected, not asked for -`notes/language.rs` (`Language`, a `closed_enum!`) is the known list; the interface's table of -labels, hues and grammars (`ui::notes::language`) is an exhaustive `match` on it. An unknown -value read from disk degrades to `txt` instead of failing the load. - -Detection reads the content and returns one of the languages; without it every note is born -`txt` and the format rail only serves people who remember to touch the select. - -- `txt` doubles as **« nothing chosen »**, and detection runs on the moments a snippet acquires - its first content: `language::for_draft` on a draft that reaches `create_note` as `txt` (the - capture shortcut, which pastes and creates in one go, and a new snippet whose body is committed - before its title); `language::after_patch`, when a patch fills the empty body of a snippet left - `txt`; `detect_language`, asked when text is **pasted** into an empty Note: code turns it into - a snippet, written with the content and the kind in one patch. -- **A Note is never read for a language.** It is where prose is typed. Once a snippet has - content, nothing is guessed either: re-detecting on every write would take the select back - from the user. -- The heuristics are cheap and **allowed to be wrong**: the result is a starting value the editor - can change (→ "Syntax highlighting" for how it scores). +`notes::language` (`Language`, a `closed_enum!`) is the known list; the interface's table of +labels, hues and grammars (`ui::notes::language`) is an exhaustive `match` on it. An unknown value +read from disk degrades to `txt`. + +- `txt` doubles as **« nothing chosen »**. Detection runs when a snippet gets its first content: + `language::for_draft` on a draft created as `txt` (the capture shortcut, a body committed + before its title), `language::after_patch` when a patch fills the empty body of a snippet left + `txt`, and `from_content` on a text **pasted** into an empty Note (code turns it into a + snippet, kind and content in one patch). +- **A Note is never read for a language**, and a snippet that has content is never guessed + again: re-detecting on every write would take the select back from the person. +- The heuristics are allowed to be wrong: the result is a starting value (→ "Detecting a + language"). ## The service functions -- **Three families**: a **data** function (`fn name(engine: &Engine, …)`, - synchronous, run on the db queue), a **network** one (`async fn name(engine: Arc, …)`, - which reaches the queue through `db::run` and never holds the lock while it waits), and a pure - **tool**, run on `compute`. `ui::api` gives each its queue once. +- **Three families**: a **data** function (`fn name(engine: &Engine, …)`, run on the db queue), a + **network** one (`async fn name(engine: Arc, …)`, which reaches the queue through + `db::run` and never holds the lock while it waits), and a pure **tool**, run on `compute`. - A module holding service functions is `pub`; everything else is `pub(crate)` or narrower, so - that `dead_code` and `unreachable_pub` still have something to say. -- They are **adapters**: validate the input, lock, delegate, translate the error. One that grows - is a sign a rule was written in the wrong place. + `dead_code` and `unreachable_pub` still have something to say. +- They are **adapters**: validate, lock, delegate, translate. One that grows is a rule written in + the wrong place. - `crates/engine/tests/` calls them on an engine over a temporary profile, the way the interface does. -The service functions, grouped by the feature that owns them (`crates/engine/src/.rs`): - -| Feature | Functions | -| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `notes` | `count_notes_tagged`, `create_note`, `delete_notes`, `delete_tags`, `empty_trash`, `fill_placeholders`, `get_note`, `list_global_placeholders`, `list_revisions`, `list_tags`, `list_trash`, `move_notes`, `move_notes_back`, `purge_notes`, `query_notes`, `rename_tags`, `restore_notes`, `restore_revision`, `revision_diff`, `seed_samples`, `set_global_placeholders`, `set_placeholder_values`, `tag_notes`, `untag_notes`, `update_note` | -| `spaces` | `count_space_contents`, `create_space`, `delete_space`, `list_spaces`, `pin_space`, `rename_space` | -| `folders` | `arrange_board`, `board_view`, `count_folder_contents`, `create_folder`, `delete_folder`, `file_notes`, `file_notes_back`, `list_folders`, `recolour_folder`, `rename_folder`, `save_board_layout` | -| `attachments` | `attach_clipboard_image`, `attach_file`, `delete_attachment`, `list_attachments`, `open_attachment`, `read_attachment`, `save_attachment` | -| `transfer` | `count_export`, `export_is_protected`, `export_notes` (over an `ExportScope`: the library, a space or a selection), `import_notes`, `share_notes` | -| `vault` | `change_passphrase`, `create_vault`, `unlock_vault`, `vault_state` | -| `libraries` | `create_library`, `delete_library`, `list_libraries`, `open_library`, `rename_library` | -| `backup` | `list_backups`, `restore_backup` | -| `recovery` | `archive_locked_library`, `set_aside_damaged_library` | -| `changelog` | `app_changelog` | -| `desktop` | `hold_quit`, `set_global_shortcuts`, `release_global_shortcuts`, `set_window_behavior`, `sync_tray` | - -The guarantees the interface relies on (persisted value returned, `Err` on an unknown id, -"absent field means unchanged" for patches) are implemented in each feature, and tested there. -The batch functions return what they changed rather than a `Result` per note: a selection can hold an -id that has gone stale, and failing the whole batch for one of them would be worse than a -partial result. - -`fill_placeholders` is pure (called on `compute`), so the palette can fill an unsaved draft as -easily as the note it just opened. - -`delete_space` takes a **refuge** (`target_space_id`). The refuge is not optional: `notes.space_id` carries an `ON DELETE CASCADE`, so a bare delete would take -the notes with it. `spaces::store::delete` moves them and drops the space in one -transaction, in that order — with `HeldNotes::Trash`, the live notes are trashed before the move, -or the refuge's own would be among them — and deliberately leaves `updated_at` alone — the canvas orders on -that column, and refreshing it would float the whole absorbed space to the top as if every -note had just been edited. A space cannot be its own refuge (`spaces::model::validate_move_target`); -the cascade would take the notes back out one statement after the move. - -`query_notes` takes a `NotesQuery` (space, search, quick filter, tags, languages, `now`, -`tz_offset_minutes`) and returns a `NotesView` (sections, `available_tags`, -`available_languages`, `is_filtering`, `matched`), shared as an `Arc` snapshot. The pair `is_filtering` + `matched` is what lets the UI distinguish -"no results" from "this space is empty" without recomputing anything. It reads the in-memory index -(`index::NoteIndex`), never a sealed column, and `notes::view::build` applies the rules. - -**Tags and languages are both facet rails**, and behave identically: union semantics (a note -passes if it carries _at least one_ of the selected values), facets scoped to the space rather -than to the current filter, and a selection counts as `is_filtering` — which collapses the -canvas into a single flat `results` section. The quick filters (pinned / untriaged) do not: -they narrow a view that stays chronological. One asymmetry: selected tags go through -`notes::model::normalize_tags` before they are compared, selected languages do not — a language is picked -from a closed list, not typed, and `notes::language` compares it exactly. - -**The JSON shape that is still written** — the export bundle, the stored preferences, a -request's document — is pinned by tests in the models (`notes/model.rs`, `spaces/model.rs`, -`tests/formats.rs`): camelCase keys, a lifecycle as `{"kind":"expires","at":…}`. A serde -attribute deleted by accident fails `cargo test`. Only what is written derives serde: a type the -interface receives as a Rust value has no JSON shape. +| Feature | Service functions (`crates/engine/src/.rs`) | +| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `notes` | `query_notes`, `get_note`, `create_note`, `update_note`, `convert_note`, `duplicate_note`, `present_note`, `set_pinned`, `set_priority`, `restore_priorities`, `move_notes`, `move_notes_back`, `delete_notes`, `restore_notes`, `list_trash`, `restore_trash`, `purge_notes`, `empty_trash`, `list_tags`, `count_notes_tagged`, `tag_notes`, `untag_notes`, `rename_tags`, `delete_tags`, `remove_tag`, `restore_tags`, `fill_placeholders`, `set_placeholder_values`, `list_global_placeholders`, `set_global_placeholders`, `list_revisions`, `revision_diff`, `restore_revision`, `list_drawings`, `drawing_thumbnail`, `drawing_picture`, `seed_samples` | +| `spaces` | `list_spaces`, `create_space`, `rename_space`, `pin_space`, `count_space_contents`, `delete_space` | +| `folders` | `list_folders`, `create_folder`, `rename_folder`, `recolour_folder`, `move_folder`, `move_folder_back`, `count_folder_contents`, `delete_folder`, `file_notes`, `file_notes_back`, `move_notes_into`, `board_view`, `save_board_layout`, `arrange_board` | +| `attachments` | `list_attachments`, `attach_file`, `attach_image`, `read_attachment`, `save_attachment`, `decrypted_copy`, `delete_attachment`, `sweep_copies` | +| `transfer` | `count_export`, `export_notes` (over an `ExportScope`: the library, a space, a selection), `export_is_protected`, `import_notes`, `share_notes` | +| `vault` | `vault_state`, `create_vault`, `unlock_vault`, `change_passphrase` | +| `libraries` | `list_libraries`, `create_library`, `rename_library`, `open_library`, `open_library_directory`, `delete_library` | +| `backup` | `list_backups`, `restore_backup` | +| `recovery` | `set_aside_damaged_library`, `archive_locked_library` | +| `changelog` | `app_changelog`, `release_notes` | +| `docs` | `docs_index`, `docs_page` | +| `tools`, `http` | → "The tools: one contract…", "HTTP: requests and their answers" | + +- **The batch functions answer what they changed**, not a `Result` per note: a selection can hold + a stale id, and failing the whole batch for one would be worse (→ "Multiple selection and bulk + actions"). +- **`delete_space` takes a refuge** (`target_space_id`): `notes.space_id` cascades, so a bare + delete would take the notes with it. `spaces::store::delete` moves them (or trashes them first, + `HeldNotes::Trash`) and drops the space in one transaction, leaving `updated_at` alone. A space + cannot be its own refuge (`spaces::model::validate_move_target`). +- **`query_notes`** takes a `NotesQuery` (space, folder, search, quick filter, tags, languages, + kinds, priorities, order, grouping, `now`, `tz_offset_minutes`, pinned first) and answers a + `NotesView` (sections, the facets and their counts, `is_filtering`, `matched`, the card + decorations), shared as an `Arc`. `is_filtering` with `matched` tells « no results » from + « this space is empty ». +- **The facet rails** (tags, languages, kinds, priorities) behave alike: a note passes if it + carries **at least one** selected value, the counts are scoped to the space rather than to the + filter, and a selection makes `is_filtering`. Selected tags go through `normalize_tags` before + they are compared; a language is picked from a closed list and compared exactly. +- **What is written as JSON** — the export bundle, a request's document — is pinned by tests + (`notes/model.rs`, `spaces/model.rs`, `tests/formats.rs`): camelCase keys, a lifecycle as + `{"kind":"expires","at":…}`. Only what is written derives serde. ## Input validation -The core validates what the interface already constrains, because a rule held only by a form -is not held at all. `error.rs` defines a `ValidationError` carrying the offending -`field`; service functions call `draft.validate()` / `draft.validated_name()` before touching the -connection, and `AppError` turns the refusal into `invalidInput` with `{{field}}`. ⚠️ That field -is a name of the code: the interface never shows it, and an `invalidInput` falls back on the action's -own message. What a person can actually run into gets a code of its own — a file past what an -attachment may weigh is `fileTooLarge`, with its name and the limit in megabytes -(`ATTACHMENT_MAX_MEGABYTES`, which the attachment strip also says). - -What is checked: `language` against the known list (an arbitrary value would be unreadable by an -older build), a space name trimmed and non-empty (`COLLATE NOCASE` folds case but not -whitespace, so `"Personal "` would otherwise sit beside `"Personal"`, identical on screen), and -`NotesQuery.now` as a parseable instant — falling back to another clock would silently -re-cut every section on a different day. +The core validates what the interface already constrains: a rule held only by a form is not held. +A service function calls `draft.validate()` or `draft.validated_name()` before it locks, and a +`ValidationError` names its `field`. + +- `InvalidInput` and its field are for the code: the interface never shows the field, and falls + back on the action's own sentence. +- What a person can run into gets a code of its own: an attachment past `MAX_MEGABYTES` (10) is + `FileTooLarge`, with its name and the limit. +- What is checked: a `language` against the known list, a name trimmed and non-empty + (`COLLATE NOCASE` folds case, not whitespace), a passphrase being chosen (→ "The floor"). diff --git a/docs/architecture/interface/frame.md b/docs/architecture/interface/frame.md index 4e99f1c9..b96523a0 100644 --- a/docs/architecture/interface/frame.md +++ b/docs/architecture/interface/frame.md @@ -1,17 +1,24 @@ # Interface (egui) -How `crates/ui` is laid out and draws: where a file goes, no router, state and actions, the editing core, rendering, the keyboard, highlighting and Prettier. [Home](../README.md) +How `crates/ui` is laid out and draws: where a file goes, state and actions, the editing core, +rendering, the keyboard, highlighting and Prettier. [Home](../README.md) -`crates/ui` is the window: the frame, its state, its screens and its widgets. It is the shape of -the screen, and it calls the core through `ui::api` alone (→ "Backend and events"). Each -screen keeps the look and the behaviour of its Angular twin at the `angular-reference` tag -(D32); the subsections below describe that behaviour, and name the egui module that draws -it. +**In short** + +- The folder tree is the shape of the screen; what has no place on screen is filed by subject. +- Drawing reads state and pushes `Action`s; `AppState::apply` applies them at the end of the + frame (D13). +- Only `ui::api` names the core, and nothing costly runs in the frame (→ "Backend and events"). +- Long lists are virtualised; a frame costs what is on screen, never what is stored. +- One keyboard order (D14), and bindings are tables. + +A screen that existed in the reference application keeps its look and behaviour (D32): the tag +`angular-reference` and its captures are the specification, read when a screen is changed. ## Where a file goes -> **A folder's path is its place on screen**. What draws sits where it is drawn; -> what has no place on screen sits apart, filed by subject. +> **A folder's path is its place on screen.** What draws sits where it is drawn; what has no +> place on screen sits apart, filed by subject. | Question | Answer | | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | @@ -23,63 +30,61 @@ it. | A control two areas draw? | `widgets/`, which reads the theme and no state | | A colour, a gap, a duration, a font, an icon? | `theme/` | -`backend.rs` owns the engine and the queues, `keys.rs` the keyboard's order, `action.rs` the -actions a frame applies, `inputs.rs` what arrives from outside the frame (the core's events, a -second launch, the tray, a global shortcut). A screen that grows is cut into named drawing -functions, not into layers; a helper, a trait or a generic waits for its second real use -(`CLAUDE.md`). +Beside them: `backend.rs` (the engine and the queues), `keys.rs` (the keyboard's order), +`action.rs` (the actions a frame applies), `inputs.rs` (what arrives from outside the frame: the +core's events, a second launch, the tray, a global key). A screen that grows is cut into named +drawing functions, not layers; a helper, trait or generic waits for its second real use. -⚠️ **"Library" means two things.** In the interface it is the registry of libraries (the File +⚠️ **« Library » means two things.** In the interface it is the registry of libraries (the File menu's dialog, `state::libraries`); in the core it is the open database and its key (`db::Library`). Moving notes in and out of a file is `state::transfer`. ## No router -The areas, the list view and the board are **state**, not routes: there is no URL in a window. -The area is an application preference (`devnotes.area`), so the window reopens on it; the list -view or board is remembered per space (`state::board`). Every area's state lives in `AppState` -whether the area is drawn or not, so an area left keeps its scroll, its focus and its drafts, -and a native action (capture, new note, the palette) brings the notes back before it opens -anything. **One key per area**, `Ctrl+1/2/3`, read by physical key (`keys::APPLICATION`; on -AZERTY the digit row types `&é"`). The switch heads each area's rail and comes to the title bar -while the rail is put away (`titlebar::area_switch`). +The areas, the list view and the board are **state**, not routes. The area is an application +preference (`area`), so the window reopens on it; list or board is remembered per space +(`state::board`). Every area's state lives in `AppState` whether it is drawn or not, so an area +left keeps its scroll, focus and drafts, and a global action (capture, new note, the palette) +brings the notes back before it opens anything. + +**One key per area**, `Ctrl+1/2/3`, read by physical key (`keys::APPLICATION`; on AZERTY the digit +row types `&é"`). The switch heads each area's rail, and comes to the title bar while the rail is +put away (`titlebar::area_switch`). ## Drawing, state and actions A screen's drawing reads its **state** (`&…State`) and may change its **view** (`&mut …View`: -text being typed, editor buffers, open menus, scroll, gestures); everything else it wants done -is an `Action` it pushes, applied by `AppState::apply` at the end of the frame (D13). Data flows -down as arguments, so a screen is tested with a literal; an action goes straight to the state -that owns it rather than up through its parents. `widgets/` is the exception that pushes nothing -and reads no state: it is the kit (→ "The widget kit"). The frame's loop, the tray and a second -launch hand each action to `AppState::act`, which logs its name and number, then applies it -(→ "What the person did"). +text being typed, editor buffers, open menus, scroll, gestures). Anything else it wants done is +an `Action` it pushes, applied by `AppState::apply` at the end of the frame (D13). -A card cannot decide what its own click means — ticking, extending a range or opening depends on -the visible list — so it answers what was pressed and the canvas decides. +- Data flows down as arguments, so a screen is tested with a literal. +- An action goes straight to the state that owns it, not up through its parents. +- The frame's loop, the tray and a second launch hand each action to `AppState::act`, which logs + its name and number, then applies it (→ "What the person did"). +- `widgets/` pushes nothing and reads no state: it is the kit (→ "The widget kit"). +- A card cannot decide what its own click means (tick, extend a range, open): it answers what was + pressed, and the canvas decides. **Menus, dialogs and their stacking** are one implementation each, in `widgets/`: `menu` (focus on -the first entry, arrows, sub-menus, Escape) and `DialogStack`, whose rungs are the reference's -`dialog.model.ts` in back-to-front order — the index is both the drawing order and the order -Escape follows. A dialog opened by another one (the fields form, from the palette) is drawn in -front of it whatever the order they opened in. The two banners are drawn under the title bar, -outside the stack, so a modal never covers them. +the first entry, arrows, sub-menus, Escape) and `DialogStack`, whose rungs are in back-to-front +order — the drawing order and the order Escape follows. A dialog opened by another one (the +fields form, from the palette) is drawn in front of it. The two banners are drawn under the +title bar, outside the stack, so a modal never covers them. ## The editing core `crates/text` is under every editor that is not a one-line field, and knows no egui: -- **`Buffer`** — the text, a rope (`ropey`), and its selection. Every edit goes through - `Buffer::replace`, which records it for undo and says from which line the text changed: what - the highlighter and the layout throw away starts there. Offsets are `char`s, everywhere in the - crate; the caret moves by grapheme, word and line. -- **`history`** — undo and redo by steps: one keystroke, one paste, one indent, one « replace - all ». Typing joins the step before it while it goes on where it left off, so one undo takes - back a word typed, not a letter. -- **`indent`** (Tab, Shift+Tab, a whole text swapped as one edit), **`search`** (a text or an - expression, case, whole words), **`diff`** (which lines a format or a revision changed), - **`words`** (a Note's words as it reads), **`shield`** (every `{{…}}` kept from a formatter's - reach), **`highlight`** and **`format`** (→ the two subsections below). +| Module | Holds | +| -------------------- | ---------------------------------------------------------------------------------------------- | +| `Buffer` | the text (a `ropey` rope) and its selection; every edit goes through `Buffer::replace`, which records it and says from which line the text changed. Offsets are `char`s; the caret moves by grapheme, word and line | +| `history` | undo and redo by steps: a keystroke, a paste, an indent, a « replace all »; typing joins the step before it while it goes on where it left off | +| `indent` | Tab, Shift+Tab, a whole text swapped as one edit | +| `search` | a text or an expression, case, whole words | +| `diff` | which lines a format or a revision changed | +| `words` | a Note's words as it reads | +| `shield` | every `{{…}}` kept out of a formatter's reach | +| `highlight`, `format`| below | `crates/richtext` is the same for a Note: its document, blocks and marks, read from Markdown and written back, its edits and its undo (→ "A Note is written formatted, and stored as Markdown"). @@ -88,146 +93,112 @@ heading **is** stays the core's, handed to them as ranges (D10). ## Rendering and virtualisation -egui draws the whole window every frame it repaints, so what a frame costs is what is on screen, -never what is stored: +egui draws the whole window every frame it repaints, so a frame costs what is on screen: -- **Anything that can run to thousands of rows is virtualised**: `widgets::list` (uniform rows, - only those in the viewport drawn), the canvas (`notes::canvas::rows`: the view flattened into - rows of one height — a heading, then a row of cards — since cards are a fixed height in an - auto-filled grid), the code (`widgets::editor`, only the lines on screen laid out), the HTTP - history, console and socket log, the runner's results, the diffs. 30 000 rows draw fewer than - twenty. +- **Anything that can run to thousands of rows is virtualised**: `widgets::list` (uniform rows), + the canvas (`notes::canvas::rows`: the view flattened into rows of one height — a heading, then + a row of cards), the code (`widgets::editor`), the HTTP history, console and socket log, the + runner's results, the diffs. 30 000 rows draw fewer than twenty. - **What is costly to lay out is kept**: a `LayoutJob` in egui's galley cache, a card's - highlighted lines in its frame cache, a Dessin's picture as a texture in - `LibraryCaches` (bounded, emptied with the library scope, D17). -- **Nothing costly runs in the frame**: highlighting a long text, formatting, a - picture, a Calcul sheet and a JSON document are computed on `compute` or a thread of their own, - and the frame draws the last answer meanwhile. -- **The window repaints when something changed**, not continuously: an answer wakes it (the - `Waker`), a relative time asks for the instant its label changes (`request_repaint_after`), an - animation for its own frames; at rest the window costs nothing. + highlighted lines in its frame cache, a drawing's picture as a texture in `LibraryCaches` + (bounded, emptied with the library scope, D17). +- **Nothing costly runs in the frame**: highlighting a long text, formatting, a picture, a Calcul + sheet and a JSON document are computed on `compute` or a thread of their own, and the frame + draws the last answer meanwhile. +- **The window repaints when something changed**: an answer wakes it (the `Waker`), a relative + time asks for the instant its label changes (`request_repaint_after`), an animation for its own + frames. At rest the window costs nothing. ## The keyboard -**One order** (D14, `ui::keys`, → "A frame, its actions and its keys"): an input method composing -keeps every key; the focused widget consumes what it handles; then `keys::dispatch` reads what is -left by level — the top modal, the area on screen, the application — and the first that knows the -key takes it. Bindings are **tables**, one per level (`keys::APPLICATION`, the canvas's -`notes::canvas::shortcuts`…), from which the shortcut sheet is drawn, so a key cannot be bound and left -undocumented. A key is read **by position** (a W3C `code`, so `Ctrl+1` is the same key on AZERTY) -or **by character**; a global shortcut as the system hears it, by character, by position on macOS -(→ "Shortcuts: two vocabularies, two storage paths"). While a text field has the focus only the -entries marked `while_typing` are read. Every drag has its keyboard twin. +**One order** (D14, `ui::keys`, → "A frame, its actions and its keys"): + +1. an input method composing keeps every key; +2. the focused widget consumes what it handles; +3. `keys::dispatch` reads what is left by level — the top modal, the area on screen, the + application — and the first that knows the key takes it. + +- Bindings are **tables**, one per level (`keys::APPLICATION`, the canvas's + `notes::canvas::shortcuts`…), and the shortcut sheet is drawn from them: a key cannot be bound + and left undocumented. +- A key is read **by position** (a W3C `code`, so `Ctrl+1` is the same key on AZERTY) or **by + character**; a global key as the system hears it (→ "Shortcuts: two vocabularies, two storage + paths"). +- While a text field has the focus, only the entries marked `while_typing` are read. +- Every drag has its keyboard twin. ## Syntax highlighting -Every coloured code — a card excerpt, the editor, a Note's code block, an HTTP answer, generated -code — is coloured by **one grammar per language**: TextMate grammars run by `syntect`, the set -`bat` maintains (`two-face`), regular expressions by `onig` (D22), plus a Prisma grammar -of ours (`crates/text/syntaxes/`). `text::highlight` answers a line's stretches as the -reference's classes (`Token`: keyword, string, literal, name, property, meta, comment…), and -`ui::services::highlight::colour` gives each its colour from the theme — the reference's -`_code-theme.scss`, one for one. +Every coloured code — a card's excerpt, the editor, a Note's code block, an HTTP answer, +generated code — is coloured by **one grammar per language**: TextMate grammars run by `syntect` +(the set `two_face` ships, regular expressions by `onig`, D22), plus a Prisma grammar of ours +(`crates/text/syntaxes/`). `text::highlight` answers a line's stretches as `Token`s (keyword, +string, literal, name, property, meta, comment…), and `ui::services::highlight::colour` gives +each its colour from the theme. - **Which grammar a language takes is one table**, `ui::notes::language::syntax`, an exhaustive - `match` on the core's `Language`: a variant added in `closed_enum!` does not compile until it - has a grammar or `None` (plain text alone has none). Beside it in the same file: the label, the - name, the hue of the badge, the line-comment marker, the Prettier parser and the indent unit. - Adding a language is the variant and those arms — no migration: the column stores the literal - and carries no `CHECK`. -- **The grammars load on a thread at startup** (`text::highlight::warm`, a few hundred ms); until - then nothing is coloured, and the interface never waits for them. -- **Never in the frame.** A card's few lines are coloured at once and kept in egui's frame cache - while drawn; a long text is coloured by windows on a thread of its own, which keeps the - parser's state every `EVERY` (128) lines so an edit throws away only what follows it — a line - not reached yet is drawn plain meanwhile. 1 MB of TypeScript shows its first screen in ~25 ms - and is coloured whole in ~2 s, off the frame (`cargo test -p text --release budget -- --ignored`). -- **A line is a line.** A stretch that spans lines (a block comment, a string) is cut at each - line break, so a viewer's gutter and an editor's row draw one line each, nothing left open. -- The code is never interpreted: colouring only reads it. - -**Detection scores, and can say it does not know.** `from_content` guessed by _first match -wins_, down a hand-ordered chain of `if`s, and the order **was** the priority: a Rust -snippet carrying a match arm came back `js`, because `is_javascript` matched `=>` anywhere -in the text and sat near the end of the chain — which made JavaScript the default answer -rather than an answer. Fixing that meant finding the right slot in a list, and the next -language would need someone to find one again. - -Every language scores itself and the highest score wins. Three weights and no more: -`SIGNATURE` (nothing else writes it), `STRONG` (strongly associated, occasionally shared), -`WEAK` (many languages write it). A scale with ten steps would be the same invisible -ordering written differently — the point is that a marker declares how much it _proves_. - -⚠️ The two facts the old order encoded are weights rather than positions now: `` is the weakest marker in the file. - -⚠️ **It can abstain, and that is a behaviour change.** Below `MIN_CONFIDENCE` — one weak -marker — or on a **tie**, the answer is `txt`. `class Note { }` used to come back `js` and -is left alone now: it is written the same way in six of these languages, and a wrong answer -costs more than none, since it colours the body, badges the card and files the note under a -facet in the rail. Some notes that were coloured before are not any more. - -⚠️ `score_typescript` deliberately does **not** inherit JavaScript's markers: inheriting -them would make TypeScript score at least as much as JavaScript on every file, and a tie is -no answer. `score_scss` follows the same rule with CSS: a variable, a Sass at-rule or a line -opening on `&` is a signature, and a stylesheet with none of them is CSS. GraphQL's -`type User {` is TypeScript's shape too, so a definition is weak and a non-null type -(`ID!`, `[String!]!`), which TypeScript never writes after a name, is what outweighs it. - -**Most languages are chosen, not guessed.** Of the 142, detection answers 76 (`detectable`): -the first 26, and the 50 others that write something nothing else does — a Dockerfile's `FROM` -with its instructions, Terraform's `resource "…" "…" {`, `syntax = "proto3"`, nginx's -`proxy_pass`, a diff's hunk. The rest are only ever picked from the menu. ⚠️ **A language -added since is guessed on a signature or not at all** (`signed`): what else it writes only -adds to the signature, so none of them can tie an older language on a shared marker and turn -its answer into `txt` — `return ` scored Cypher three without one, and every Python function -came back as prose. A language that is another one plus something (TSX over TypeScript, -Cython over Python, JSON-LD over JSON, a Vue or Angular template over its HTML) adds to the -other's score, so it always outscores it once its own sign is there. A shebang names its -interpreter (`python3`, `node`, `perl`…), any other being a shell as before. - -⚠️ **`crates/engine/tests/corpus/` is what says whether this is better rather than differently -wrong.** One file per case, named `[-].txt`, read from disk and asserted -in bulk — adding a case is adding a file. Every detectable language has one, and each language -added since has a `txt-weak-.txt` holding only what it shares with others, which must -stay plain text (or what the older language makes of it: `html-weak-jsx.txt`). It earned its -keep immediately: CSS's "a selector and a declaration" scored a signature on -`export interface Note {` with `id: string;` inside it, **and** on PHP's `foreach (…) {` with -an `echo …;` inside it, so both tied at six and came back as prose. That shape is strong -evidence now, not proof; a unit or a custom property is what makes it a stylesheet. + `match` on the core's `Language`: a variant added does not compile until it has a grammar or + `None`. Beside it: the label, the name, the badge's hue, the line-comment marker, the Prettier + parser and the indent unit. Adding a language is the variant and those arms, no migration. +- **The grammars load on a thread at startup** (`text::highlight::warm`); until then nothing is + coloured, and nothing waits for them. +- **Never in the frame.** A card's few lines are coloured at once and kept in the frame cache; a + long text is coloured by windows on a thread, keeping the parser's state every `EVERY` (128) + lines, so an edit throws away only what follows it. 1 MB of TypeScript shows its first screen + in ~25 ms and is coloured whole in ~2 s (`cargo test -p text --release budget -- --ignored`). +- **A line is a line**: a stretch spanning lines (a block comment) is cut at each break. + +### Detecting a language + +`notes::language::from_content` reads the first 64 KB of a text. **Every detectable language +scores itself, and the highest score wins**, with three weights: + +| Weight | Meaning | Example | +| ----------- | ---------------------------------------- | ----------------------------------------- | +| `SIGNATURE` | nothing else writes it | `` | + +- ⚠️ **It can abstain.** Below `MIN_CONFIDENCE` (one weak marker), or on a **tie**, the answer is + `txt`: a wrong guess colours the body, badges the card and files it under a facet, which costs + more than none. +- **Most languages are chosen, not guessed**: of the 142, 76 are detectable (`detectable`, the + `SCORERS` table). ⚠️ A language added to them is guessed **on a signature or not at all** + (`signed`), so it can never tie an older one on a shared marker. +- A language that is another plus something (TSX over TypeScript, JSON-LD over JSON, a Vue + template over HTML) adds to the other's score, so it wins once its own sign is there; but + `score_typescript` does not inherit JavaScript's markers, nor `score_scss` CSS's, or every file + would tie. A shebang names its interpreter. +- ⚠️ **`crates/engine/tests/corpus/` says whether a change is better or differently wrong**: one + file per case (`[-].txt`), asserted in bulk. Every detectable language has + one, and each newer one a `txt-weak-.txt` holding only what it shares with others, which + must stay plain text. ## Formatting a snippet with Prettier -"Formater" (Shift+Alt+F) runs Prettier itself — 3.9.10, as `scripts/prettier.mjs` pins it — on the -editor's draft, **in QuickJS** (D1): `golden/format` holds its answers, byte for byte. +« Format » (Shift+Alt+F) runs Prettier itself — the version `scripts/prettier.mjs` pins — on the +editor's draft, **in QuickJS** (D1); `golden/format` holds its answers byte for byte. `text::format` holds all of it; the editor asks through `FormattingState`, on `compute`. -- **One host, started by the first format and kept** (`text::format::host`): a thread of its - own with one QuickJS runtime — a runtime is not shared between threads — in which - `standalone.js` and nine plugins are evaluated once. `node scripts/prettier.mjs` copies them into - `crates/text/prettier/` after a bump; they are compiled in (2.4 MB). A host that cannot start - answers every format `Failed`. -- **Only text crosses**: the draft, the caret and Prettier's options, never code. The answer is - `Formatted` (the text, the caret, the changed lines), `Unchanged`, `Syntax` (Prettier's - one-based line and column), `Fields` or `Failed` — never a panic. Prettier counts the caret in - UTF-16 units, the editor in `char`s: converted on the way in and out. -- **Every `{{…}}` is shielded** (`text::shield`): read as code, `{{db_host}}` is two nested - blocks in JavaScript and a flow mapping in YAML. Each becomes an identifier of its own - length, made of a two-letter marker absent from the text, and comes back in order afterwards. - One missing, copied or moved past another and the answer is `Fields`: nothing is applied. -- **The snippet keeps its own shape:** `endOfLine: 'auto'` (Prettier's `lf` would rewrite a - CRLF snippet), and no final newline added where there was none. -- **Through the editor's own history**: `Editor::replace_all` is one step, so Ctrl+Z undoes a - format and the notice's "Annuler" is the same step (`Editor::undo`). The lines it changed are - marked in the gutter until the next keystroke. An answer about a text typed over meanwhile is - dropped. -- **The style is the library's** (`notes::prettier`, under `devnotes.notes.prettier`, read as - the reference wrote it), set from the button's chevron and applied as it is chosen. Its - indentation is by default "Éditeur", the Tab key's own level (`language::indent_unit`). -- **Formatting on save** (off by default): a snippet's body that changed is held back from the - save and written once formatted — or as typed if Prettier refuses it — so the revisions keep - one body, not two. Written after the editor closed, it goes by id; still open, the field - follows unless it was typed into since. A draft never written is saved as it is. -- The button stays drawn, disabled, on a language Prettier does not read - (`language::formatter`), its tooltip naming the language. +- **One host, started by the first format and kept** (`text::format::host`): a thread with one + QuickJS runtime, `standalone.js` and nine plugins evaluated once, compiled in (2.4 MB, copied + into `crates/text/prettier/` by `node scripts/prettier.mjs`). A host that cannot start answers + every format `Failed`. +- **Only text crosses**: the draft, the caret and the options. The answer is `Formatted` (text, + caret, changed lines), `Unchanged`, `Syntax` (line and column), `Fields` or `Failed` — never a + panic. Prettier counts the caret in UTF-16 units, the editor in `char`s: converted both ways. +- **Every `{{…}}` is shielded** (`text::shield`): it becomes an identifier of its own length and + comes back in order afterwards. One missing, copied or moved, and the answer is `Fields`: + nothing is applied. +- **The snippet keeps its shape**: `endOfLine: 'auto'`, no final newline added where there was + none. +- **Through the editor's history**: `Editor::replace_all` is one step, so Ctrl+Z undoes a format. + The lines it changed are marked in the gutter until the next keystroke. An answer about a text + typed over meanwhile is dropped. +- **The style is the library's** (`notes::prettier`, under `notes.prettier`), set from the + button's chevron. Its indentation defaults to the Tab key's own level + (`language::indent_unit`). +- **Formatting on save** (off by default): a changed body is held back and written once + formatted — or as typed if Prettier refuses it — so the revisions keep one body, not two. +- On a language Prettier does not read, the button stays drawn, disabled, its tooltip naming the + language (`language::formatter`). diff --git a/docs/architecture/interface/look.md b/docs/architecture/interface/look.md index 9dca54ee..d1dfc021 100644 --- a/docs/architecture/interface/look.md +++ b/docs/architecture/interface/look.md @@ -2,10 +2,18 @@ The translations, the accessibility floor, and the theme tokens every screen reads. [Home](../README.md) +**In short** + +- Strings live in `crates/i18n/translations/{fr,en}.json`; every key is a constant checked at + build time, and code returns a `Message`, never a sentence. +- Formats, plurals and ageing labels are written by hand, for two languages (D21). +- Every control goes through `widgets::interact`: a role, a name, a focus ring, 24 × 24 px. +- Every colour, gap, radius, text size and duration is a token of `ui::theme`; tests refuse a + literal anywhere else and hold every text colour at 4.5:1. + ## i18n -The interface's strings are `crates/i18n/translations/{fr,en}.json`, in the format the -reference wrote them. The `i18n` crate embeds both and **generates one constant +The interface's strings are `crates/i18n/translations/{fr,en}.json`. The `i18n` crate embeds both and **generates one constant per key at build time** (`build.rs`, from `fr.json`): `vault.unlockTitle` is `i18n::keys::vault::UNLOCK_TITLE`, a segment that is a Rust keyword takes `r#`, `fr-FR` becomes `FR_FR`. A misspelled key does not compile; two segments that would make the same name stop the @@ -16,26 +24,27 @@ does not exist — an enum of the cases, matched once, is better wherever the se is drawn, by `Message::text(language)` or `i18n::translate`. Nothing user-visible is written in Rust outside the two files: a new note has an empty title, and the interface draws a translated placeholder. -- **Plurals** are the reference's ICU subset, ported (`i18n::plural`): `{name, plural, =N {…} one -{…} other {…}}`, `#`, no `select`, no nesting; an exact `=N` wins over a category (French calls +- **Plurals** are a subset of ICU's (`i18n::plural`): `{name, plural, =N {…} one {…} other + {…}}`, `#`, no `select`, no nesting; an exact `=N` wins over a category (French calls zero `one`), and the categories are CLDR's for the two languages — French `one` for an integer part of 0 or 1 (1.5 included), `many` for a whole million. A test reads every plural of both files: each closes, and has an `other` branch. -- Then `{{name}}` is filled; ⚠️ **a parameter not given is left empty**, as Transloco did — so - no translated string can carry a snippet's `{{fields}}`, and user content is never interpolated +- Then `{{name}}` is filled; ⚠️ **a parameter not given is left empty** — so no translated + string can carry a snippet's `{{fields}}`, and user content is never interpolated into a template. `{{app}}` is the application's name, `brand::NAME` (→ "The application's names"): no translation spells it out (a test refuses it), and none hedges a plural with « (s) ». - Both files have the same keys, and a name one language fills in, the other reads too, filled in or counted (« il y a {{count}} mois » counts in English): two tests. - **Localised formats are written by hand** (D21, `i18n::format`): one function per pattern the - interface uses, named by its use — `date_short` (« 25 juil. 2026 »), `time_millis` (« 11:05:07,123 »), - `fixed`, `at_most`, `signed`, `ungrouped`, `and_list`, `or_list`, `country` (the IBAN - registry's countries only)… A date arrives as the wall-clock value to show; the caller puts it + interface uses, named by its use — `number`, `fixed`, `at_most`, `exact`, `date_numeric`, + `date_short` (« 25 juil. 2026 »), `date_long`, `date_with_weekday`, `day_month`, + `time_seconds_24h`, `and_list`, `or_list`, `country` (the IBAN registry's countries only). A date arrives as the wall-clock value to show; the caller puts it in the local zone, or in UTC where the screen says so. Numbers round the shortest decimal half away from zero, as ICU does (12.345 is 12.35 at two digits), and French groups with a narrow no-break space. `golden/intl` — every pattern at its edge values — is read back by a test. No ICU. -- **Ageing labels** are `i18n::time`: `relative` (« il y a 3 min »), `expiry` (in local calendar - days: an expiry is the end of its day), `span` (« dans 2 jours », the largest whole unit). They +- **Ageing labels** are `i18n::time`: `relative` (« il y a 3 min ») and `short`, `expiry` and + `short_expiry` (in local calendar days: an expiry is the end of its day), `span` (« dans 2 + jours », the largest whole unit). They answer a `Message`, `now` given; `golden/relative-time` is read back by a test. - **The language** is a preference (`system` / `fr` / `en`); `system` is `Language::of_system()`, the first of the system's preferred languages (`sys-locale`) whose @@ -76,14 +85,14 @@ the widget rather than of each screen: ## Theming -Every colour, shadow, gap and duration of the interface is a token of `ui::theme`, copied one -for one from the reference's `styles.scss` (`src/styles/` at the `angular-reference` tag): `tokens::DARK` and +Every colour, shadow, gap and duration of the interface is a token of `ui::theme`, copied from +the reference's `styles.scss` (D32): `tokens::DARK` and `tokens::LIGHT` (a `Palette` each), `tokens::COMFORTABLE` and `tokens::COMPACT` (a `Spacing`), `tokens::TITLEBAR_HEIGHT`, and the durations of `theme::motion`. A widget reads them through -`theme::palette(ctx)` and `theme::spacing(ctx)`, never a literal. The CSS `--*-rgb` triplets are -gone: a tint is the colour itself at an alpha. +`theme::palette(ctx)` and `theme::spacing(ctx)`, never a literal. A tint is the colour itself at +an alpha. -The reference had no scale for the rest, so the egui application defines one by role: +The rest is a scale by role: `tokens::font` (`BADGE`, `CAPTION`, `META`, `CONTROL`, `LABEL`, `BODY`, `READING`, `SUBTITLE`, `TITLE`, `HEADING`, `DISPLAY`, `HERO`), `tokens::gap` (`HAIRLINE`, `LINE`, `TIGHT`, `SNUG`, `CONTROLS`, `INSET`, `GROUPS`, `BLOCKS`, `PANEL`, `PAGE`; `gap::margin` for a frame) and @@ -102,48 +111,43 @@ and the window is created hidden, so nothing flashes before the first frame. egu widgets are restyled from the palette (`Visuals`); the visible components are painted by hand from it. -**Type.** Inter and JetBrains Mono are embedded as the variable TrueType files the reference -loaded (Latin and Latin Extended, `theme::fonts`), so the CSS weights, 650 included, apply as -written; Noto Emoji, monochrome, comes next, so an emoji is drawn the same on every +**Type.** Inter and JetBrains Mono are embedded as variable TrueType files (Latin and Latin +Extended, `theme::fonts`), so every weight applies, 650 included; Noto Emoji, monochrome, comes next, so an emoji is drawn the same on every machine; eframe's `system_fonts` finds the rest (CJK) on demand. egui's own fonts are not compiled in. The body is 14 px. Licences and sources: `crates/ui/assets/README.md`. **Icons** are Lucide's paths (`theme::icons::Icon`), rasterised by resvg into a white alpha mask at the size asked × `pixels_per_point`, cached per size in the context's memory, and tinted by -the colour they are painted in — `currentColor`. The interface draws no emoji of its own any -more: 📎 ⏳ are `Paperclip`, `Hourglass`. +the colour they are painted in. The interface draws no emoji of its own: 📎 ⏳ are `Paperclip`, +`Hourglass`. -**Motion** is `theme::motion`: `FAST` (120 ms, what follows the pointer, also egui's own -`animation_time`), `TURN` (a spinner's 800 ms), `MARK` (2 s, a mark fading). **One switch**, `motion::set_reduced`, cuts all of it — -the system's wish read by `platform::motion` (the registry under Windows, `gsettings` under -GNOME), as the reference's `prefers-reduced-motion` was: there is no setting of its own. A test sweeps `crates/ui/src` for a duration typed anywhere -else, as `motion.test.mjs` did. +**Motion** is `theme::motion` (→ "Motion"): every duration named there, and one switch, +`motion::set_reduced`, set from the system's wish (`platform::motion`; there is no setting of its +own). A test sweeps `crates/ui/src` for a duration typed anywhere else. **The focus ring** (`theme::focus`) is 2 px of `amber_edge`, 2 px outside the control, and shows only after the keyboard moved: `focus::track` reads, once a frame, whether the last input that moves around was a key (Tab, arrows, Enter, Space, Escape…) or a pointer press — typing does not count. Scrollbars are 9 px. -**Contrast is a Rust test** (`theme::tokens::tests`, which replaced `palette.test.mjs`): every +**Contrast is a Rust test** (`theme::tokens::tests`): every text colour at 4.5:1 on the four surfaces, a badge's label on the strongest tint (0.15) and a status on its fill (0.3), the edge at 3:1, the ink on solid amber. The palette is destructured without `..` there: a colour added to it does not compile until it is given a role. -**The accent is three variables, one per job.** `#e8a33d` on white is 2.16:1, and what that -rules out depends entirely on what it is being used for — a surface only has to carry the ink -drawn on it, a hairline has to be found against the page, and a label has to be read. - -| | job | bar | dark | light | -| -------------- | ------------------------------ | --------------------- | ------------------- | ------------------------ | -| `--amber-fill` | a solid button, a tick, a tint | 3:1 for the ink on it | `#e8a33d` | **the same declaration** | -| `--amber-edge` | a border, a focus ring | 3:1 on the surface | `var(--amber-fill)` | `#cf6a08` | -| `--amber-text` | a label | 4.5:1 on the surface | `var(--amber-fill)` | `#a8500f` | - -⚠️ `--amber-fill` is declared **once**, in the dark base, and the light block does not -redefine it — which is what makes the dark theme provably unmoved by the split, and what lets -the light theme show the same amber everywhere it is a surface. Only the line and the word step -down. One token doing all three meant drawing the whole accent at the _label's_ darkness, which -is where a warm hue lands at 4.5:1 on white, and which read as mustard. +**The accent is three colours, one per job.** `#e8a33d` on white is 2.16:1, and what that +rules out depends on the use — a surface only carries the ink drawn on it, a hairline has to be +found against the page, a label has to be read. + +| `Palette` field | Job | Bar | Dark | Light | +| --------------- | ------------------------------ | --------------------- | --------- | --------- | +| `amber_fill` | a solid button, a tick, a tint | 3:1 for the ink on it | `#e8a33d` | the same | +| `amber_edge` | a border, a focus ring | 3:1 on the surface | the fill | `#cf6a08` | +| `amber_text` | a label | 4.5:1 on the surface | the fill | `#a8500f` | + +⚠️ The fill is the **same in both themes**, so the light theme shows the same amber wherever it +is a surface; only the line and the word step down. One colour doing all three jobs would draw +the whole accent at the label's darkness, which on white reads as mustard. `amber_dim` is the softer hairline a hover draws, and `amber_ink` the text laid on the fill; with the same fill in both themes there is one of each. The contrast test holds each of the three to diff --git a/docs/architecture/interface/window.md b/docs/architecture/interface/window.md index 4b3da6f3..c75386a1 100644 --- a/docs/architecture/interface/window.md +++ b/docs/architecture/interface/window.md @@ -1,620 +1,226 @@ # The window and its menus -What surrounds the areas: the title bar and its bands, the chrome, motion, the theme, the palette, the « Fichier » menu, preferences, shortcuts, help, the first launch and the update prompt. [Home](../README.md) - -## The title bar, and the two bands under it - -The window has no decorations from the system (D34): `ui::titlebar` is its title bar, the same -on every system, 38 px on `bg-0`: the menus on the left, the application's name centred on the -window, the theme toggle on the right, then the window's controls (`titlebar::window`) — -minimise, maximise or restore (named for what it does), close — flat cells the bar's height, -46 px wide, `bg-2` under the pointer and the close `red-fill`. They ask what the system's buttons -did: the close sends `ViewportCommand::Close`, which comes back as the close button's event, so -`close_asked` decides as before (the tray, the requests left unsaved), and the minimise goes -through `follow_the_minimize`. The bar's empty space, allocated before what is drawn on it, moves -the window on a press that moves (`StartDrag`) and maximises or restores it on a double click; a -band of 4 px along the edges, 8 px squares at the corners, resizes it from the press on -(`BeginResize`, the cursor saying which way) unless it fills the screen. Moving and resizing are -handed to the system, which snaps and tiles the window as any other. ⚠️ The controls and the -edges are drawn in areas of their own above every modal (`Order::Tooltip`), as the system's frame -was: a dialog open does not hold the window. Each edge is an area: one covering the window would -take the pointer from everything under it. While another window has the focus, the bar is drawn -at half its opacity. **macOS** keeps its three buttons: the content runs under a transparent -title bar (`with_fullsize_content_view`), the system draws them over the bar's left end, which -keeps 78 px for them, and its frame resizes; the bar's empty space still moves the window there. -`crates/app`'s `own_title_bar` sets the window up for either. The area switch (`titlebar::area_switch`) heads each area's rail, three columns of an -icon over its name, and comes to the bar, icons alone, only while the rail is put away: nothing -else then leads to the other areas. It is drawn only once the library is open — every area acts -on it. Its options are named for the screen reader and the tooltip (`area-option-notes`, `-tools`, -`-http`), in the order of `Ctrl+1/2/3`, which `keys::APPLICATION` reads by position. The toggle -names what it switches **to**, its icon and its label alike, and writes the appearance like the -preferences panel does. Until the screens arrive, an area is an empty room addressed -`area-notes`, `area-tools` or `area-http`. - -`ui::banners::toasts` stacks in the bottom right corner, above every modal and clear of the undo -bar, what was done and what failed, each whole on as many lines as it takes, the latest on top. The -`StatusNotifier`'s reports (green, announced politely, `status-toast`) go by their X or after -`motion::REPORT` seconds, counted while the pointer is away from them (`DismissStatus`). The -`ErrorNotifier`'s failures (red, announced assertively, `error-banner`) stand under them until -their X is pressed (`DismissError`), the same one once. Past `notices::KEPT` of a kind the oldest -makes room. - -## Nothing wears the operating system's chrome, except one popup - -The application draws every one of its own surfaces, and then **eight** controls came from -the operating system and brought its chrome with them: a different border, a different -radius, a different arrow, a different focus ring and, on Windows, a different font. - -Two of them were worse than a mismatch — the selection bar's "Déplacer vers" and "Ranger -dans" were a `` brings a -calendar, a localised format and keyboard entry that a hand-rolled picker has to earn back — -so its **box** is the application's and only its popup is the system's. Its picker icon is -painted by the engine and follows `color-scheme`, which `:root` sets per theme; the invert -filter is therefore dark-only, and it lives in `styles.scss` rather than in the editor's own -stylesheet because the rule has to open on `:root`, which emulated encapsulation rewrites -into a form that never matches ``. - -## Motion, and the one block that stops it - -There were **four** `transition` declarations in the whole of `src/`, across roughly 225 -style rules, and three of them had already drifted to three different durations. Nothing on -a card's hover moved, no menu or dialog opened, no transient bar arrived — every state -change was a hard cut. That is not a defect; it is the difference a reader registers between -"quick" and "finished". - -**Two durations, and they are variables.** `--motion-fast` (120ms) is what follows the -pointer — hover fills, chip states, the card's action pill. `--motion` (160ms) is what -**enters**: a menu, a dialog, the selection bar, the undo banner, the status toast. - -**One motion lasts: the spinner's turn** (`--motion-turn`, the `turn` keyframes, `app-spinner` -in `shared/spinner/`), shown while something is waited for — a request on its way, a socket -connecting. One shared piece, sized by `--spinner-size` and coloured by the text. The -reduced-motion block below stops it without naming it; what says "alive" then is whatever -ticks beside it. - -**One mark fades** (`--motion-mark`, 2000ms): what a keyboard move leaves on a row of the HTTP -rail and on what now holds it. It is a colour coming down to a style that is already the mark, -on two rows, not a motion — the reduced-motion block cuts the fade and leaves the mark. - -⚠️ **`transform` and `opacity` only.** A transition on `height`, `width` or a colour over -a list of cards is what makes a canvas feel heavy, and this canvas renders every note with -no virtualisation. `@mixin eases` therefore names its properties and never takes `all`. - -⚠️ **An animation, not a transition, for what arrives.** Menus, dialogs and the bars are -`@if`-rendered: there is no previous state to transition _from_, because the element did -not exist a frame ago. `@mixin enters` picks one of three shared `@keyframes` -(`enter-rise`, `enter-lift`, `enter-fade`), which live in `styles.scss` because keyframe -names are global whatever the component encapsulation says. - -⚠️ **`prefers-reduced-motion` is one block, and it has to stay the only one.** It reduces -every duration and every animation without naming any of them, which is the whole reason -the durations are variables and the entrances are three shared keyframes: motion added -later is turned off by it for free. `scripts/motion.test.mjs` holds all three rules -against the shipped stylesheets — no duration written out in a component, no -`transition: all`, and exactly one reduced-motion block. - -⚠️ The card's action pill keeps its entrance to **opacity**. `note-card.component.spec.ts` -and two e2e scenarios read its box while it is at `opacity: 0`, which works because opacity -does not affect layout; a `transform` there would move what they measure. And ⚠️ its -`opacity` pair has to stay **after** `unstyled-control` wherever it is written — that mixin -expands to `all: unset`, which resets both. - -## The theme is one gesture - -The theme is a choice made more than once, so besides its row behind File → Préférences → -Apparence it has a control in the titlebar, and that control is a **toggle between light and -dark** rather than a cycle through the three `THEME_CHOICES`: a click on "system" usually -changes nothing on screen, the one thing a click there is expected to do. Following the -system is chosen in the panel, which keeps its three rows. - -The language has no control there: it is chosen once, in the panel. Nor does the titlebar -draw window controls; the native frame has its own. - -⚠️ The control reads `resolvedTheme`, **what is on screen**, not the setting: on "system" it -shows what the machine resolved, and a press writes the explicit opposite. It writes -`SettingsStore.theme`, the **same signal** the panel writes, so the two cannot disagree. -⚠️ Icon and label both name the **action** — a moon on a light screen, "Passer au thème -sombre" — the convention a toggle follows. An icon rather than a word: a label would be -the widest thing in a bar whose middle is the application's name. +What surrounds the areas: the title bar, the toasts, motion and the theme toggle, the palette, +the File menu, the preferences, the shortcuts, the About menu, the first launch and the update +prompt. [Home](../README.md) + +**In short** + +- The window draws its own title bar on every system but macOS (D34). +- What was done and what failed are toasts in the bottom right corner, above every modal. +- One palette (`Ctrl+Alt+P`) finds notes, requests, tools and spaces, and runs commands. +- Preferences edit a draft; only theme and density preview before « Apply ». +- Fifteen keys can be moved: three global, eleven on the canvas, one for the rail. + +## The title bar, and the toasts + +`ui::titlebar` is the window's title bar, the same on every system (D34): 38 px on `bg-0`, +the menus on the left, the application's name centred, the theme toggle on the right, then the +window's controls (`titlebar::window`). What was just done takes the name's place a while. + +- **The controls** — minimise, maximise or restore (named for what it does), close — are flat + cells 46 px wide, `bg-2` under the pointer, the close `red-fill`. The close sends + `ViewportCommand::Close`, which comes back as the system's close event, so one path decides + (the tray, the requests left unsaved; → "Closing is not quitting"). +- **Moving and resizing are handed to the system** (`StartDrag`, `BeginResize`), which snaps and + tiles the window as any other: the bar's empty space moves it and a double click maximises; a + 4 px band along the edges (8 px squares at the corners) resizes it. +- ⚠️ The controls and the edges are drawn above every modal (`Order::Tooltip`): a dialog open + does not hold the window. Each edge is an area of its own, or one covering the window would + take the pointer from everything under it. +- **macOS** keeps its three buttons: the content runs under a transparent title bar, the bar + keeps 78 px at its left end for them, and the system's frame resizes. `crates/app`'s + `own_title_bar` sets the window up for either. +- While another window has the focus, the bar is drawn at half its opacity. +- **The area switch** (`titlebar::area_switch`) heads each area's rail and comes to the bar, + icons alone, only while the rail is put away. It is drawn once a library is open. +- **The theme toggle** switches between light and dark, never through « system »: a click on + « system » would usually change nothing on screen. It reads what is **on screen**, writes the + explicit opposite as the preferences do, and its icon and label name the action (a moon on a + light screen). + +**The toasts** (`banners::toasts`) stack in the bottom right corner, above every modal and clear +of the undo bar, the latest on top: + +| Kind | From | Colour, announced | Goes | +| -------- | -------------------------- | -------------------- | ----------------------------------------------------------------- | +| a report | `StatusNotifier` | green, politely | by its cross, or after `motion::REPORT` (6 s) away from the pointer | +| a failure| `ErrorNotifier` | red, assertively | by its cross only; the same failure shown once | + +Past `notices::KEPT` of a kind, the oldest makes room. + +## Motion + +`ui::theme::motion` holds every duration, and nothing else in the interface writes one: + +| Constant | Seconds | For | +| ---------------- | ------- | ------------------------------------------------------------------ | +| `FAST` | 0.12 | what follows the pointer: a hover fill, a chip, egui's animations | +| `TURN` | 0.8 | a spinner's turn, the one motion that lasts | +| `MARK` | 2 | how long a mark left by an action takes to fade (the HTTP rail) | +| `REPORT` | 6 | how long a report stays | +| `TYPING`, `TYPING_HEAVY` | 0.15, 0.25 | how long a search or a live tool waits after the last key | +| `LAYOUT_SAVE` | 0.4 | how long the board waits before it saves a layout | + +⚠️ **One switch stops all of it**: `motion::set_reduced`, set from the system's preference +(`platform::motion::system_prefers_reduced`: the registry under Windows, `gsettings` under +GNOME). It sets egui's animation time to zero and cuts every fade, so motion added later is cut +without being named. A mark stays; only its fade goes. ## The palette -`Ctrl+Alt+P` — the one shortcut — reveals the window and posts an action; `ui::palette`, drawn -over whichever area is on screen, opens with `state::palette`. -It finds **notes, HTTP requests, tools and spaces**, and runs commands. Rust says which action -it was: `palette` when the window was not in front (another application had the keyboard, or the -tray asked), `palette-here` when it was. Only over another application does copying a note put -the window away again; in front, the palette just closes and `StatusNotifier` says what was -copied. - -It searches **every space and ignores the canvas filters**: when you recall a snippet you do not -remember which space you filed it in. It keeps its own state rather than reusing the canvas's -query, whose search would otherwise change what the canvas shows behind it. - -**What the core answers, and what the interface reads.** The notes come from `query_notes` asked -`ranked`: by how the title answers what is typed — all of it, its start, the start of a word, -anywhere — then a match in the body, the tags or the context, the last edit breaking ties -(`view::rank_notes`); by date alone, `psql` opened a note holding it in its body. The -requests come from `search_http_requests`, which ranks them in Rust (`http::search`): a name -starting with what is typed, then a word of the name, then the name, the URL as typed — read from each -sealed document — and the collection › folders; nothing typed lists the requests edited last. -The tools, the spaces and the commands are matched in the interface, as the tools' home matches -its catalogue: their words are translations, which Rust does not know. The tools and the spaces -are ranked there by the same order, on their name (by name), before the cap of each -kind: « json » kept « Diff » and « JWT » and cut the tool named JSON. The groups come in a -fixed order — notes, requests, tools, spaces — each with its heading and count when more than -one answers, and share the screen (`palette::options`: five notes and three of the others, -eight for a kind alone). An empty field lists a few recent things of each kind and a line naming -the prefixes. - -**Prefixes become chips.** `@` lists where to search — `@notes`, `@outils`, `@requêtes`, -`@espaces`, in either language whatever the one on screen, and `@` for a space's notes — -and Tab or Enter turns the choice into a chip in the field. Kinds add up; a space or a tag -narrows to notes; a second space takes the place of the first; ⌫ in an empty field removes the -last chip. `#` lists the tags with how many notes carry each. `>` lists the commands -(`palette::commands`): a new snippet, Note or todo list (their keys read from the bindings, so a -rebound key shows as bound), a new request, a new folder in the space open (asked by the folder -prompt), an area (its keys from `keys::APPLICATION`), the preferences and the shortcut sheet. - -**Each kind has its mark**, in one column so that the titles align: a note's kind icon and a -snippet's format, a -request's method in its hue, a tool's category icon in its hue, a space's dot — the switcher's: a space has no colour of -its own — and `>`. The highlighted row says what Enter does in place of its context, and so -does the line under the list. - -**Enter opens**: the note in the notes, the request in its tab (the tabs left open last time -restored first, so it is the one in front), the tool, the space; it runs a command and creates -the note named after what was typed from the « créer une note » row, which comes **after** the -results while notes are searched. What each kind does is an `Action` the palette pushes; the -state it reaches is the area's. - -A snippet with fields goes through the fill form first — copying `psql -h {{host}}` verbatim -gives an unusable command. The form (`notes::overlays::placeholder_form`, which the notes' own -copy uses too) is drawn **in front of** the palette, on the rung above it. - -⚠️ **A click on a row opens; it does not copy.** Copying may hide the window, and a window that -disappears on a click reads as the application crashing. The paste path has a control of its -own beside a note's row (which copies, like `Ctrl+C`). The keyboard is untouched: it is the fast -path and the muscle memory is the feature. - -⚠️ **A copy over another application is acknowledged on the desktop, not in the window**, because -the window is what the gesture takes away: the palette copies, closes, hides the window, and only -then asks `platform::notify` to say which note it took. Without a word from the desktop the window -simply vanished, and it read as the application crashing on a copy that had in fact worked. -`platform::notify` is **never load-bearing**: what it says has already happened, so a refused -permission or a desktop that drops the toast change nothing. Its words come translated from the -interface: the platform crate holds no user-visible string. - -The palette is an overlay in the main window rather than a second window: the window is already -warm behind the global shortcut. - -**The field keeps the focus from start to finish**: the arrows move a highlight, not the focus, -which would lose the query being typed — one current row, which Enter or a click opens, and -which the screen reader is told of. ⚠️ **Tab is an arrow here** — except on a chip `@` or `#` -offers, which it chooses —, so the field is the only stop in the panel: two notions of « the -current row », one of them invisible, was a bug the reference had to fix twice. - -## The "Fichier" menu, and where the rest lives - -The titlebar carries a **File menu** next to "À propos" — the convention of a desktop -application. It holds import, export, "copy the selection as Markdown", the preferences and -quitting. - -**The menu owns its entries**: `titlebar/file_menu.rs` lists them in the order on screen, and an -entry with nothing to act on stays, muted: "Exporter la sélection" follows what is checked at -that instant. The menu exists only while a library is open, every entry acting on it. - -**One operation at a time, in `state/transfer.rs`.** Its stages say where it stands: counted -before any dialog, placed, protected, written; picked, probed, unlocked, read. The file dialogs -block until answered, so they run on the pool. The passphrase prompt follows the stage and stays -up, working, while the key is derived; a refused phrase comes back to it rather than failing the -import. The phrase reaches `AppState::apply` through the bar's view, never through an `Action`. - -There used to be a contribution registry here — three of them, in fact, one per extension -point — so the chrome could stay ignorant of a feature it might not have. That indirection had -exactly one purpose, a second tool, and [#23](https://github.com/vmillet-dev/devnotes-rs/issues/23) -decided there would not be one. With a single feature it protected nothing and cost a real -detour: reading what a menu entry did meant opening the notes page. They are gone. - -Two things deliberately did **not** go in that menu, because they are views on the notes and -not operations on a file: - -- **The trash** sits next to the quick filters in the notes topbar — it is one more way of - looking at the notes. -- **Tag management** sits at the end of the tag rail, which is exactly what it acts on. The - rail disappears when no tag exists, and so does the button: there is nothing to manage. +`Ctrl+Alt+P` reveals the window and opens `ui::palette` over whichever area is on screen +(`state::palette`). It finds **notes, requests, tools and spaces**, and runs commands. + +- **Two actions**: `Global::Palette` when the window was not in front (another application had + the keyboard, or the tray asked), `Global::PaletteHere` when it was. Only over another + application does a copy put the window away again. +- **It searches every space and ignores the canvas's filters**: a snippet recalled is rarely in + the space on screen. It keeps its own state, so the canvas behind does not change. +- **What the core answers**: the notes from `query_notes` asked `ranked` (by how the title + answers what is typed — all of it, its start, a word's start, anywhere — then the body, tags + or source, the last edit breaking ties); the requests from `search_http_requests`, ranked in + Rust. The tools, the spaces and the commands are matched in the interface, which knows their + translated words, by the same order. +- **The groups** come in a fixed order — notes, requests, tools, spaces — with a heading and a + count only when more than one kind answers, sharing the screen (`palette::options`). An empty + field lists a few recent things of each kind and the prefixes. +- **Prefixes become chips**: `@` chooses where to search (`state::palette::SCOPES`, and a space for its + notes), `#` lists the tags with their counts, `>` lists the commands (`palette::commands`: new + notes of each kind, a new request, a new folder, an area, the preferences, the shortcut sheet — + each naming its key from the table that binds it). Tab or Enter turns a choice into a chip; ⌫ + in an empty field removes the last. +- **Enter opens** — the note, the request in its tab, the tool, the space — runs a command, or + creates the note named after what was typed from the « create » row, which comes **after** the + results. A snippet with fields goes through the fill form first, drawn in front of the palette. +- ⚠️ **A click on a row opens; it never copies.** Copying may hide the window, and a window that + vanishes on a click reads as a crash. A note's row has a copy control of its own, like + `Ctrl+C`. +- ⚠️ **A copy over another application is acknowledged by the desktop** (`platform::notify`), + since the window is what the gesture takes away. It is never load-bearing: what it says has + already happened. +- **The field keeps the focus from start to finish**: the arrows move a highlight, so there is one + current row, which Enter or a click opens. ⚠️ **Tab is an arrow here**, except on a chip a + prefix offers, which it chooses. + +## The File menu + +`titlebar::file_menu`, there only while a library is open: import, export (the library, a +space, the selection), « copy the selection as Markdown », the libraries, the preferences and +« Quit ». An entry with nothing to act on stays, muted. + +**One transfer at a time** (`state::transfer`). Its stages say where it stands: counted before +any dialog, placed, protected, written; picked, probed, unlocked, read. The file dialogs run on +the pool. The passphrase prompt follows the stage and stays up, working, while the key is +derived; a refused phrase comes back to it. The phrase reaches the state through the prompt's +view, never through an `Action` (→ "Import, export and copying out"). + +The trash and the tag manager are **not** here: they are views on the notes, in the notes' +header and at the end of the tag rail. ## Preferences -"Préférences…" opens `titlebar/preferences/`: a rail of pages on the left, the chosen page on the -right, and Annuler / Appliquer / OK at the bottom. The draft is the bar's view: the controls edit -it where they are drawn, and `AppState` adopts it on a button. Autostart and the tray's two -switches are stored and read by nothing until the platform phase. - -**Appliquer, Annuler, OK — and a draft under them.** Every control used to write straight -into `SettingsStore`, which was written down as a decision rather than an oversight. The -counter-argument turned out to be stronger: a shortcut is _captured_, not typed, so a -half-entered one was registered with the operating system for as long as it took to -finish; a theme flipped under the cursor; and there was no way back from a change other -than remembering what it was. - -So the panel edits `SettingsDraft` (`ui/src/services/settings.rs`), and Appliquer or OK -writes it through. ⚠️ It stages **both paths a preference can take**, because the panel -edits both: a setting, and a shortcut binding. A draft covering only the first -would make OK mean two different things on two pages. - -**A setting is one line.** `SettingsStore.setting(key, codec)` builds the signal, its restore -step and its write-through together, and `SETTINGS_KEYS` is derived from `keyof AppSettings` -(`devnotes.${key}`). Adding a setting is a field on `AppSettings` plus that line; one key per -setting, never one serialised object, so a setting added later cannot make an older file -unreadable. - -⚠️ **The three services that push to the native side read `SettingsStore`, never the -draft.** That is the point of the layer: nothing reaches `set_global_shortcuts`, -`set_window_behavior` or the autostart plugin until the button is pressed. - -**What "immediately" was buying is kept where it means something.** The theme and the -density show on screen while they are being chosen — nobody picks a theme without seeing -it — through `SettingsStore.preview`, which feeds `shownTheme` / `shownDensity` and -therefore the `data-theme` / `data-density` attributes. ⚠️ A preview is **not** a write: -nothing reaches `preferences.json`, and Annuler clears it with nothing to roll back. -Everything else waits for the button, because nothing else has a preview that means -anything. - -⚠️ **Closing with unapplied changes has to say so**, or Escape and the backdrop become a -silent Annuler — the one outcome nobody would have chosen on purpose. Neither produces a -click, so the footer swaps its buttons for a sentence naming how many changes are waiting -and two answers: "Fermer sans appliquer" and "Appliquer et fermer". Every way out of the -panel passes through `finish()` after an apply or a cancel, so the draft is always empty -when it reopens. - -⚠️ **The variables page is corpus data, and it is under the same footer anyway.** -`VariablesStore` writes through the IPC bridge rather than through `PreferencesService`, -so the draft does not hold it — `SettingsDialogComponent` does, reading -`VariablesStore.isDirty()` beside `SettingsDraftStore.isDirty()` and committing both. -A panel where one page wrote on blur and three waited for a button would be worse than -either rule on its own. The store's `load()` refuses to run over edits in hand, because -the page is recreated every time the rail changes section. - -⚠️ **One rule, two readers.** `refuseBinding` and `conflictsAmong` (in -`shortcut-bindings.store.ts`) take a `BindingReader`, so the store answers from what is -stored and the draft from what is staged. A check living in only one of them would let -the panel offer a key the store is about to refuse. - -**The pages are a list in the panel**: "Général", "Raccourcis", "Sécurité" and "Variables", -each in its own folder beside the dialog, rendered through `NgComponentOutlet` so the rail -stays one loop over one array. The order on screen is the order of the list. - -The split is the shape of the subject rather than of the file it came from. "Général" keeps -what the application looks like and how it behaves; the keys moved out because there are -eleven of them and they needed room; and "Sécurité" holds the two things that decide who can -read the library — the passphrase that unwraps its key, and whether a copy is taken at launch. -⚠️ Those two belong on **one** page: the copies are wrapped under the phrase too, so a page -carrying only one of them would let someone change the phrase without meeting what the change -reaches. - -⚠️ Each page's stylesheet is `@include settings-page;` and its own extras. A component's SCSS -is out of reach of its neighbours, so the groups, their titles and the four things a row is -made of live in a mixin — otherwise the three pages would carry the same thirty lines three -times, which is also what the duplication gate would have said. - -`SettingsStore` holds one signal per setting — the interface language, the theme, the density, -the tray behaviour, the three global accelerators — backed by `PreferencesService`: one key per -setting, not one serialised object, so a setting added later cannot make a file written by the -previous version unreadable. `restore()` runs from the app initializer, after -`PreferencesService.hydrate()` and before the first render. - -**Three services read those signals and push them to the native side**, rather than the store -reaching for the IPC itself — a preferences store has to stay readable outside Tauri: - -| Service | Effect | Native side | -| ------------------------ | ---------------------------------------------- | ----------------------------------- | -| `GlobalShortcutsService` | `set_global_shortcuts` on every change | re-registers, returns what is taken | -| `WindowBehaviorService` | `set_window_behavior` | what close and minimise do | -| `AutostartService` | `tauri-plugin-autostart` (`autostart:default`) | the system's own startup entry | - -Each starts from the app initializer, and each builds its `effect` with an **explicit -injector**: they are started outside a constructor, where `effect()` would have nothing to -attach to. For the same reason the initializer injects **everything before its first `await`** — -an `inject()` after one is outside the injection context, and the whole bootstrap fails with -NG0203 and a black window. - -⚠️ The native side has shortcut defaults of its own, and must: it takes the shortcuts before -the front has started, and without them `Ctrl+Alt+P` would be dead for the length of the first -render — exactly the second one uses it from another application. They are declared once, -though: `ShortcutBindings::defaults()` crosses as the `DEFAULT_SHORTCUTS` constant, next to -`GLOBAL_ACTION_EVENT` and `APP_METADATA`, and the front re-exports it rather than retyping it. - -`AutostartService` reads the system **first** and aligns the preference on what it finds: -turning the entry off from the task manager has to uncheck the box, not see DevNotes put it back. - -**What the settings actually change** - -- **Theme** — `system` / `dark` / `light`, resolved into a `data-theme` attribute on - `` (see _Theming_). `system` follows `prefers-color-scheme` live. -- **Density** — `data-density`, which swaps four spacing variables. -- **Start with the system, minimise to tray, close to tray** — the last one was the application's fixed - behaviour and stays the default; both tray settings are still refused when there is no tray - (`desktop::hides_on_close` / `hides_on_minimize`), since hiding a window nothing can call - back is worse than closing it. -- **Quick paste** — "show pinned first", the only consumer of `NotesQuery.pinnedFirst` that - ever sends `false`. The palette's accelerator used to sit here and now lives on the - Shortcuts page, with the ten others. -- **Copy confirmation** — the acknowledgement lives in `ClipboardService` itself rather than in - its five callers, four of which show nothing today: copying from the canvas with `Ctrl+C` - said not a word. Callers with something better to say — "3 notes copied as Markdown" — speak - after, and the banner keeps the last message. +« Preferences… » opens `titlebar::preferences`: a rail of pages, the page chosen, and Cancel / +Apply / OK under them. + +| Page | Holds | +| ----------- | ---------------------------------------------------------------------------------------------- | +| General | the look (theme, density, language), the behaviour (tray, autostart, quick paste, the editor), what it says (copy confirmation, update notices) | +| Shortcuts | the fifteen keys that can be moved, and who holds the global ones under Wayland | +| Security | the passphrase and its change, the copies at launch: ⚠️ on **one** page, since the copies are wrapped under the phrase too | +| Variables | the global `{{field}}` values: corpus data, under the same footer all the same | + +- **The controls edit `SettingsDraft`** (`services::settings`); Apply or OK writes it through. + ⚠️ It stages **both paths a preference takes**, a setting and a key binding, or OK would mean + two things on two pages. +- **Only the theme and the density show while they are chosen** — nobody picks a theme without + seeing it. ⚠️ A preview is not a write: Cancel clears it with nothing to roll back. +- ⚠️ **The desktop reads the applied settings, never the draft**: the global keys + (`services::global_keys`), the tray, the autostart (`services::autostart`) change only on a + button. Autostart reads the system first and the preference follows: an entry removed from the + task manager unticks the box. +- ⚠️ **Closing with changes not applied says so**: the footer swaps its buttons for a sentence + counting them and two answers, « Close without applying » and « Apply and close ». +- **A setting is one key**, never one serialised object, so a setting added later cannot make an + older file unreadable. +- The tray's switches carry a note of their own where the desktop shows no icon + (`AppState::tray_shown`): the window hides all the same, and a second launch brings it back. ## Shortcuts: two vocabularies, two storage paths -Eleven actions can be moved: the three **global** ones registered with the operating system, -and the eight **canvas** keys. Everything else on the read-only sheet is documented and fixed — -the arrows are the grid's own navigation, Escape is the way out of every other thing on -screen, Tab is how the window is crossed, and the Ctrl/Shift clicks are not keys at all. -`isCanvasAccelerator` refuses those by name, which is what keeps a library you can still get -out of. - -**A canvas key is declared where it is bound.** `CANVAS_KEYS`, which `CanvasKeyboardDirective` -binds, grew an `id` and an `accelerator` on the entries that can move; the caps the sheet draws are -derived from that accelerator, so a key is spelled once. Two constants come out of the same -table — `CANVAS_SHORTCUT_GROUP` for the sheet, `CANVAS_ACTIONS` for the panel — and a key -cannot be documented, bound or made movable without the other two following. - -**`Bindings` (`ui/src/services/shortcuts.rs`) reads both paths as one table.** The global -three are stored as `devnotes.Shortcut`, because the native side takes them as a block; a -canvas key is one preference of its own, `devnotes.shortcut.`. ⚠️ Only the keys moved are -held: a `Rebindable` carries its own fallback, so there is no third place to add a key to. Reading both halves together is also what makes a collision _between_ them -something the panel can say out loud. - -⚠️ **A global key is read as the system will hear it, a canvas key as it is printed.** - -| | reads | may be bare | why | -| ------ | ---------------------------------------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -| global | the **printed** character; the **position** on macOS | no | the system hears a keysym or a virtual key, the layout's, and a key code on macOS; a shortcut with no modifier would swallow that key in every application | -| canvas | the **printed** character | yes | `C` is read off the keycap by someone looking at this window, and the key answers only while the canvas has the keyboard | - -On AZERTY the position `KeyA` is the key labelled `Q`. Recorded by position where the system hears -characters, a global key answered on the key labelled `Q` when the one labelled `A` was pressed: -`services::shortcuts::capture` reads it as `platform::shortcuts::BY_POSITION` says. ⚠️ macOS -names it by its QWERTY place — the key labelled `A` is shown `Q`, and answers — since naming a -position by the layout's character takes a system call (no `unsafe`, D7). ⚠️ On Windows a -punctuation mark is heard where the layout puts its virtual key (`VK_OEM_*`), where it is printed -only on US-like layouts; a mark with no name here (AZERTY's `:`) is refused. -`canvasKeystrokeFromEvent` upper-cases a single character, so a caps-locked keyboard answers the same key as a bare one, and folds the Command key into `Ctrl`: `Super` means -something of its own only where a shortcut leaves the window. - -⚠️ **Not every `keydown` is a keystroke.** A suggestion picked from a `` — the -names of a request's headers — or from an autofill makes Chromium fire a bare `Event` named -`keydown` on the field, without `key`, `code` or modifier, and it bubbles to the document. -`isKeystroke` says so, and a listener on the document that reads `event.key` before anything -else asks it first: `canvasKeystrokeFromEvent` answers `null`, the identifiers tool's `R` -draws nothing. Read as a keystroke, it threw « reading 'length' » at every pick. - -**A refusal is a reason, not a boolean.** `rebind` answers `null`, `{ kind: 'illegal' }` or -`{ kind: 'taken', by }`, and the page turns that into the sentence under the field. Deciding it -twice — once in the store, once in the panel — is how the two drift. `conflicts(among)` exists -for what `rebind` cannot refuse: a preferences file edited by hand, and a shipped default -landing on a key someone had already taken. - -⚠️ `aliases` on an entry fire it whatever it is bound to. Backspace has trashed a note since -before the key could be moved, and making the key movable is no reason to take that away. - -The read-only sheet in the About menu keeps existing — it is the one reachable with the -keyboard while working — and every row that can be moved now resolves its caps through the -store, so it shows what is bound rather than what shipped. - -## Help: what's new, getting started, shortcuts - -**The written guide is a walk, not a wall.** It was ten chapters of prose in one scrolling -panel — roughly 3 400 characters, all of it true and none of it looked at, which is the -worst return a help surface can have. One chapter is on screen at a time now: a schematic of -the screen it is about, and two sentences beside it. The bodies came down to about 2 000 -characters in total, because the figure carries the arrangement and the words only have to -say what it is _for_. - -⚠️ **Inline SVG and not an image.** The CSP is `script-src 'self'` with nothing remote, and -a PNG would need one file per theme; the figures are drawn from the palette's own custom -properties, so they follow the theme for free. ⚠️ Schematic on purpose — boxes where the -cards are, a bar where the rail is: a screenshot would be a fourth thing to keep in step -with the interface, and it is the _arrangement_ they have to show. They are `aria-hidden`, -and every chapter says in words what its figure shows. - -⚠️ **It opens at a chapter.** An empty canvas offers the chapter about notes and an empty board -the one about folders — reaching help from the thing it explains, neither of which is anywhere -near the titlebar. `Panel::Guide` carries the chapter, and `guide::CHAPTERS` is the one list of -ids, so a link cannot point at nothing. The figures and the shortcut sheet are data beside the -code (`services/guide_figures.json`, `services/shortcut_sheet.json`). - -⚠️ "Fermer" is on **every** chapter, not only the last: a walk you can only leave by -finishing it is a wall with extra steps. ⚠️ The figure band is a fixed height, or a chapter -two lines shorter than the last would make the dialog jump under the cursor on every step — -the same trap the update prompt's notes block had. - -The titlebar's **"À propos" menu** carries the update check, three help panels and the card -itself, separated into those three groups. They share one signal (`AboutMenuComponent.panel`) -rather than a boolean each: they sit on the same backdrop rung (55), only one is ever wanted at -a time, and four flags would allow a state where two of them are stacked and the focus trap of -the loser keeps the keyboard. - -- **"Nouveautés"** renders `CHANGELOG.md`, the repository's own, **embedded in the binary** by - `include_str!` (`crates/engine/src/changelog.rs`) and read through `app_changelog`. The Markdown - is parsed **in Rust** (`changelog/model.rs`) into releases, categories and entries, so the - front renders a typed structure with the components it already has: no Markdown renderer to - pull in, no `innerHTML`, nothing for the CSP to forbid. The grammar is deliberately thin — - `## ` a release, `### ` a category, `- ` an entry, an indented line continues the one above — - and the file is written to match it; a shipped file that no longer parses fails a test rather - than emptying the panel in silence. - An entry is not a string but a list of **typed runs** (`ChangelogSpan`: plain, strong, code), - which the panel draws with a `switch` and three elements — still no `innerHTML`. That grammar - is two markers, `**` and a backtick, paired and on one line, and an unclosed one is text, so - an entry about `5 * 3` stays readable. ⚠️ A continuation line is re-cut with the line it - continues, or a marker opened on the first would never find its close. The trailing `(#123)` - a squashed pull request leaves behind is dropped when the entry is **read**, never when the - file is written: the number is what makes the release on github.com navigable, and noise on - a panel with no links in it. The newest section is **generated** by the release - workflow from the pull requests merged since the last tag (see "Releasing"), which is also - where a category's icon comes from: `### ✨ Added` is the heading in the file, so nothing on - the front end decides what a category looks like and a new one needs no code. The changelog - is **not translated**, on purpose and like - the release notes the updater hands over: one changelog, written once, rather than two that - drift apart. The panel marks the release the running binary is, and its footer opens the - repository's releases page through the `opener` plugin. -- **"Documentation"** reads the pages of `docs/content` (→ "The website"), compiled in - (`engine::docs`): their list, a search answered by the core section by section, and the page, - drawn block by block (`about_menu/docs`). It is not drawn by the Note's reader - (`widgets::rich`): a page holds what a Note cannot — key caps, notes, captions, links between - pages — and a Note holds what a page cannot. A page is read the first time it is asked for, on - the frame: a few kilobytes. ⚠️ A combination of several keys is drawn as it is **really bound**: - a page quoting the one that shipped would be wrong for anyone who changed it. A letter alone is - left as it is written, for it means something else in another place. The canvas and the board - with nothing to show open the page that explains them. -- **"Raccourcis clavier"** is a read-only sheet. Read-only because the one shortcut that can be - changed is changed in the preferences, and a second editor for it would be a second place to - keep in step. - -The groups of the notes — the canvas arrows, `X` to check a card, `Alt+↑` to reorder a -checklist item — come from `shortcuts-dialog/notes-shortcuts.ts`, which the sheet imports. -They live with the notes rather than in the sheet because the canvas group is **derived from -the key table that binds them** (`CANVAS_SHORTCUT_GROUP`, from `notes/canvas-keys.ts`): a -key documented but not bound, or the reverse, is not possible. The **HTTP** group -(`http-shortcuts.ts`, beside it) is documentation only, as the editor's and the palette's are: -sending, saving, and what a row of the rail does under `Alt` and the arrows, `F2` and `Delete`. - -The **global** group is the exception and is built by the dialog itself: those three -combinations are the application's, they work with the window closed, and the quick-paste one -follows a preference — the sheet reads `SettingsStore` so it shows the key that is really bound -rather than the one that shipped. A shortcut is spelled as one `` per key -(`acceleratorKeys`), the `+` drawn between the caps and `aria-hidden`: inside a cap it reads as -a key to look for on the keyboard. What is not a key press — `Ctrl` + click to check a card — is -said in the label rather than drawn as a cap. - -The three panels share their frame through mixins in `src/styles/_mixins.scss` -(`help-panel`, `help-header`, `help-body`, `help-actions`, `key-cap`) rather than through a -common component: a component's SCSS is out of reach of its neighbours, and three panels that do -not look alike would read as three unrelated windows. +Fifteen actions can be moved (`services::shortcuts::every`): the three **global** keys taken +from the whole machine, the eleven **canvas** keys, and the rail's. Everything else on the sheet +is fixed — the arrows, Escape, Tab, the clicks. + +| Scope | Stored under | Reads | May be bare | Why | +| ------ | ---------------------------- | ----------------------------------------------------- | ----------- | -------------------------------------------------------------------------------- | +| global | `Shortcut` | the **printed** character; the **position** on macOS | no | the system hears the layout's key; a bare key would be swallowed everywhere | +| canvas | `shortcut.` | the **printed** character | yes | read off the keycap by someone looking at this window | +| areas | `shortcut.` | the printed character | no | it acts in the three areas | + +- **A `Rebindable` carries its own fallback**: only keys moved are stored, so there is no + second place to add a key to. `Bindings` reads both paths as one table, which is what lets the + panel say when a global key and a canvas key collide. +- **A key is captured, not typed** (`services::shortcuts::capture`): a modifier alone is a + combination still being typed, Tab goes on, a first Escape stops listening. A global key is + read as `platform::shortcuts::BY_POSITION` says the system hears it. ⚠️ On AZERTY the position + `KeyA` is the key labelled `Q`; macOS names a key by its QWERTY place (naming it by the + layout's character needs a system call, D7). +- **A refusal is a reason** (`Refused`: `NeedsModifier`, `Reserved`, `Unknown`, `Taken { by }`), + turned into the sentence under the field. `conflicts` reports what a refusal cannot prevent: a file edited by hand, a + shipped default landing on a key someone took. +- The sheet (About → Keyboard shortcuts, `services::shortcut_sheet`) shows every row that can be + moved with the key **really bound**. + +## The About menu + +`titlebar::about_menu` reads nothing of the library, so it is there at the gate too. It opens one +panel at a time (`Panel`): + +- **What's new** — `CHANGELOG.md`, compiled in (`include_str!`, `engine::changelog`) and parsed + **in Rust** into releases, categories and entries of typed runs (plain, strong, code), drawn + without a Markdown renderer. The grammar is thin — `## ` a release, `### ` a category, `- ` an + entry, an indented line continues it, `**` and a backtick paired on one line — and a shipped + file that no longer parses fails a test. The trailing `(#123)` is dropped when read. The + sections for the site and the documentation are left out (`NOT_IN_THE_APP`). Not translated: + one changelog, written once. +- **Documentation** — the pages of `docs/content`, compiled in (`engine::docs`): their list, a + search answered by the core, and the page drawn block by block (`about_menu::docs`). A key + combination is drawn as it is **really bound**. An empty canvas and an empty board open the page + that explains them. +- **Keyboard shortcuts** — the read-only sheet, every key by where it is live. +- **About** — the application, its version and its author (`about_menu::card`). ## The first launch -A brand-new library opens on **sample notes**, in a space of their own -(`ui::services::samples`, seeded from `AppState` once the library's preferences are read). This -is not decoration: a virgin database has -no space, and creating a note with nowhere to file it is refused on purpose — so without them -the first screen is empty, silent, and offers a "+ Nouvelle note" button that does nothing. - -Six notes, one feature each, none longer than a screen: a pinned welcome Note (the three -areas and the keys that matter, as a table), a shell snippet carrying `{{fields}}`, a JSON -snippet to open as a graph, a Note with tasks, a table and a code block, a todo list with a -deadline and a priority — which lights the ⏳ badge and gives the "à trier" filter something to -find, and is left loose on purpose — and a TypeScript line for Prettier to lay out. They are -ordinary notes: editing or trashing them is the point, and the written guide behind -"Prise en main" is what survives the day they go. - -**The content comes from the front end**, not from a seed in Rust, for the reason no -user-facing string ever comes out of the back end: it would ship French into an English -interface. It also means the samples arrive in the language the application starts in. The two -snippet bodies are the exception and are hard-coded in the service — they are _code_ and -_data_, so they are not translated, and the fields could not be: a translation reads `{{name}}` -as one of its parameters and would replace a snippet's fields with empty strings on the way out. - -⚠️ **Two guards decide a first launch, not one.** A preference marker -(`devnotes.notes.samplesSeeded`) alone would re-seed anyone whose preferences file went missing; -"no space at all" alone would re-seed the day the last space disappears. Together they only ever -match a database that has never been written to: the marker is read with the library's -preferences, and the space is counted on the db queue just before `seed_samples`, in the same -job. Nothing reads notes meanwhile, so the canvas never shows the empty library first. The marker -is written **after** the seeding, -because the seeding is one write: `seed_samples` creates the space and its notes in a -single transaction, so there is no halfway. ⚠️ It used to be six round trips, and a process -killed between any two left a space standing with nothing in it — which both guards then read -as "already seeded", leaving that install with an empty canvas for good. A library that has a -space and no marker is marked as skipped, so the check stops running on every open. A failure is -silent (a line in the log): the canvas reports its own, and a second banner about samples nobody -asked for would only add noise. - -## What a first launch teaches - -A virgin database has no space, so `SampleNotesService` seeds one — and since the folders -milestone, **it arrives already arranged**: two folders, three of the four notes filed, and -one deliberately left loose. Without that the board opens empty on a fresh install, and the -one screen that explains what a folder is for shows no folder. - -⚠️ **The folders are written in the same transaction as the space and the notes.** The two -guards in `seedIfFirstRun` only both say "virgin" for a database that has never been -written to; a seeding that created the space and the notes but not the folders would leave -a space standing, which both guards then read as "already seeded". It would never run again. - -⚠️ **Each seeded row is stamped a millisecond apart**, and in opposite directions: -`folders::list` orders `created_at` **ascending**, the canvas orders `updated_at` -**descending**. Sharing one instant left both orders falling back to `id` — a random UUID — -so the zones and the sample cards came out arranged differently on each install. - -⚠️ **`seed_samples` answers the space it made**, and the page selects it. With exactly one -space, "all spaces" is a distinction without a difference — and it is the one state in which -the board cannot be shown at all, so a first launch would have hidden the feature behind a -disabled button. - -A note names its folder by **index** into the folders the same command creates: they have no -id until the transaction that writes them is under way. - -The written guide ("À propos → Prise en main") has a chapter per subject, listed in -`getting-started-dialog.component.ts`. ⚠️ A chapter that names a key receives it as an -interpolation — Transloco replaces an unknown `{{name}}` with the empty string, so a body -cannot spell one out. `CHECK_KEY` is exported from the canvas keyboard directive for that: -the table that binds it and the chapter that names it read the same constant. +A new library opens on **samples** (`services::samples`): a space, two folders and six notes, one +feature each — a pinned welcome Note, a shell snippet with `{{fields}}`, a JSON snippet to open as +a graph, a Note with tasks and a table, a todo list with a deadline and a priority (left loose on +purpose), and a TypeScript line for Prettier. They are ordinary notes, made to be edited or +trashed. A virgin library has no space, and a note needs one: without the samples, « New note » +would do nothing. + +- **The texts come from the interface**, translated in the language the application opens in; + the two snippet bodies are code and data, never translated (a translation would read their + `{{fields}}` as its own parameters). +- **The core writes them in one transaction** (`seed_samples`): the space, its folders (named by + index, having no id yet) and the notes, each stamped a millisecond apart so the board's and the + canvas's orders never fall back on a random id. It answers the space, which is selected. +- ⚠️ **Two guards decide a first launch**: the library's mark `notes.samplesSeeded`, and no space + at all, counted in the same db job as the seeding. Either alone would re-seed a library whose + preferences went missing, or one whose last space was deleted. A library with a space and no + mark is marked, so the check stops. ## The update prompt shows the release's notes -`update-prompt` has rendered `update.notes` since it was written, and `latest.json` never -carried the key — so the block was dead markup that looked like a shipped feature, and -`update.body` was `undefined` at every release. - -`scripts/release-notes.mjs extract` writes two files from the section at the tag: the whole of it, -for the GitHub release body, and the prompt's (`--prompt-out`), for the manifest. **The prompt keeps -what the user will notice**: the summary, additions, changes, fixes, removals and security. The -technical work and the dependencies stay in `CHANGELOG.md`, on the release page and in "What's new". -The documentation and the site have sections of their own (📖 Documentation, 🌐 Website), for the -release page alone: "What's new" leaves them out as well (`changelog::model::NOT_IN_THE_APP`, held -against the script's headings by a test). Which section is shown is said beside its labels, in -`SECTIONS`. ⚠️ It is filtered in the manifest, not in the application: the prompt is drawn -by the version already installed. A release with nothing left to show says so in one line. - -⚠️ **Shown open, at a fixed height.** Behind a `
` it was installed without being -read — and worse, opening it _changed the dialog's height_: the body is bounded at 160px but -a collapsed summary is one line, so the panel grew under the cursor and moved "Install now" -out from under the mouse. The prompt is a `fitted` dialog, sized by its content, so a -**fixed** block is precisely what makes its geometry independent of a two-line release versus -a forty-line one. It scrolls inside. - -It stays untranslated, like `CHANGELOG.md` and the "Nouveautés" panel that reads it: a -release note in one language beats no release note. **Rust reads it with the panel's grammar** -(`changelog::model::parse_section`, the `release_notes` command): the section alone, its -`### ` categories, entries and spans, and a line outside the grammar as an entry of its own, so -free text never leaves the prompt empty. Both draw it with `app-release-notes` (`shared/`), -three spans over a `@switch` and no `innerHTML`; without the bridge the prompt shows the text -as written. +`banners::update_prompt` offers a new version found by `services::updates` (→ "Application +updates"). Nothing installs without an explicit gesture. + +- **The notes are the manifest's**: `scripts/release-notes.mjs extract` writes the prompt's part + of the section (`--prompt-out`) — the summary, additions, changes, fixes, removals and security + (`SECTIONS`) — and the core parses it with the changelog's grammar + (`changelog::model::parse_section`). A release with nothing left to show says so in one line. +- **Shown open, in a block of fixed height** that scrolls: the dialog's geometry does not depend + on a two-line release against a forty-line one, and « Install now » stays under the pointer. +- Once installing starts, it cannot be dismissed: files are being replaced. +- Not translated, like « What's new ». From 931e0641f2da9e4c8989af30b20ad696a06987cf Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 22:52:57 +0000 Subject: [PATCH 4/8] Architecture: the notes' pages checked against the code `notes/kinds.md`, `cards.md`, `editing.md` and `board.md` follow the egui code as it is. Each opens on what matters; the Calcul grammar is a table of forms and examples, the card's bands, the canvas keys, the board's storage and gestures are tables. What described the earlier application is gone: its components, stores, directives, stylesheets, the WebView's drag and drop, the issue numbers, the measurements of a DOM. Corrected from the code: the footer's four variants, the board's pan counters, the undo window, the draft created once, the find bar's options (not remembered), the canvas key table's name (also in CLAUDE.md). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BbVs5tCyTr9AasGra3Zzg3 --- CLAUDE.md | 2 +- docs/architecture/notes/board.md | 804 +++++++---------------------- docs/architecture/notes/cards.md | 782 ++++++++-------------------- docs/architecture/notes/editing.md | 598 +++++++-------------- docs/architecture/notes/kinds.md | 627 +++++++--------------- 5 files changed, 762 insertions(+), 2051 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 615d694f..3e2a0610 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -89,7 +89,7 @@ Read at the `angular-reference` tag; the egui mechanism is in `docs/architecture - No router: areas, list view and board are state; an area keeps its state when not shown. Area keys are read by physical key (AZERTY). → "No router". - `null` space = "all spaces". Nothing corpus-wide runs before saying what it touches (count from Rust). Sections are exhaustive and local-day based; search debounce 150 ms; "À trier" ends at `endOfLocalDay`; `pinnedFirst` is the user's choice. - Every library operation reports through the status notifier, even when nothing changed. -- A card is two layers (→ "A card is two layers"). Every drag is a pointer gesture plus a keyboard twin. The board dims, never narrows; gestures commit on release, snapped to `GRID_PX`, saved debounced. Escape falls through modal → overlay → selection → search → up a folder level. The canvas keyboard is one table (`CANVAS_KEYS`); arrangement is the library's (`devnotes.notes.arrangement`). → "The board: the second view of a space", "Descending into a folder". +- A card is two layers (→ "A card is two layers"). Every drag is a pointer gesture plus a keyboard twin. The board dims, never narrows; gestures commit on release, snapped to `GRID_PX`, saved debounced. Escape falls through modal → overlay → selection → search → up a folder level. The canvas keyboard is one table (`notes::canvas::shortcuts::CANVAS`); arrangement is the library's (`devnotes.notes.arrangement`). → "The board: the second view of a space", "Descending into a folder". - A preference is applied on a button (only theme and density preview before Apply). Global shortcuts are first come, first served, stored under W3C `code` names and recorded as the system hears them (the character typed, the position on macOS). The window starts hidden and is shown when ready; its geometry is remembered without visibility. A silenced update is a version written down (`skippedUpdate`). → "Preferences", "Shortcuts: two vocabularies, two storage paths", "The binary, its profile and its window". - Theming: `ui::theme::tokens` (copied from the reference's `styles.scss`; text sizes, gaps and radii are its role scales `font`, `gap`, `radius`, each role defined once), read through `theme::palette(ctx)` / `theme::spacing(ctx)`; no colour, gap, radius, text-size or duration literal elsewhere (held by sweep tests). Dark the base, light with its own amber; text ≥ 4.5:1, held by a Rust test. Accessibility: 24×24 targets, destructive controls red at rest, modals stacked by the rungs of `dialog.model.ts`. → "Theming", "Accessibility", "The widget kit". diff --git a/docs/architecture/notes/board.md b/docs/architecture/notes/board.md index 8f160f66..63bf3a84 100644 --- a/docs/architecture/notes/board.md +++ b/docs/architecture/notes/board.md @@ -1,666 +1,218 @@ # Spaces, folders and the board -The library rail and the space switcher, folders inside a space, and the board: its behaviour, its arrangement and its drawing. [Home](../README.md) +The library rail, managing spaces, folders inside a space, and the board: what it stores, how it +is drawn, its gestures, opening a folder, and what an export carries. [Home](../README.md) -## The library rail - -Navigating used to take two dropdowns that knew nothing about each other: the space switcher -listed the spaces, and beside it the folder switcher listed the folders of whichever space was -active. The two lists are a **tree**, and they were drawn as two flat menus opened one after -the other. `notes/sidebar/library-tree/` draws that tree instead — every space, its folders -under it, the way an editor holds a project — and the toolbar keeps the toggle that shows and -hides it. - -⚠️ **Shown or hidden is one state for the three areas.** The tools drew their rail whatever had -been chosen, and HTTP honoured the choice with no control to undo it. `showLibraryRail` now -hides the rail in the notes, the tools and HTTP alike; the titlebar carries the switch between -areas whenever it is hidden; and the same button (`app-rail-toggle`, `shared/controls/`) sits -at the left end of each area's top bar — the notes' header, the tools' home and frame, HTTP's -tab bar and history — under a test id of its own page, since the notes page stays in the -document behind the others. Its key, `Ctrl+B`, is answered once, by `AreaKeysDirective` -(`RAIL_ACTION`, rebindable, listed under « Zones » in the sheet and the preferences): from a -field too when it carries a modifier, never from an editor that formats with it. A tools home -held to one category while its rail is hidden says so in its top bar, with the way back. - -⚠️ **The rail replaces the two switchers while it is open**, and they come back when it is -closed. Two places to change space is how a tree and a dropdown drift apart; the `@if` in the -page's template is what keeps there being one. - -**Nothing moved house.** A space row keeps its `⋯` — pin, rename, delete-with-refuge — and a -folder row keeps its own — rename, recolour, delete. Those panels are `space-editor/` and -`folder-editor/`, projected by whoever shows them; extracting the first one out of the -switcher is what let the rail have it without a copy. Creating a space sits at the head of the -rail, creating a folder under the active space alone — a folder is made in the space one is -in, and the row above is one click away from making that so. - -**The rail asks for a destination; the page turns it into state.** `folderOpened` carries the -whole `Folder` rather than an id, because opening one in another space means switching space -_first_: `FoldersStore.activeFolder` resolves against the active space's folders, and the two -signals settle in that order. Choosing a space leaves whatever folder was open — the row means -the space itself. - -⚠️ **`FoldersStore` holds every space's folders**, not the active space's. The rail needs the -whole library, and partitioning a list already in hand is what lets a folder in another space -be opened without a round trip in between; `folders()` narrows to the active space for the -switcher and the selection bar, `foldersOf(id)` for anyone who names one. - -Shown or hidden is `AppSettings.showLibraryRail`, and how wide is `libraryRailWidth` — one -line each in `SettingsStore`, restored at launch like every other preference, and deliberately -absent from the preferences panel: they are states the window is in, not decisions to go and -make. ⚠️ The width is dragged from the rail's edge with **pointer events**, like every other -drag in this application — HTML5 drag and drop does not work in this WebView — and the edge is -a `role="slider"` so the arrow keys move it too. It is clamped on the way in _and_ on the -way out (`RAIL_WIDTH`), because a preferences file written by hand is an input like any other. - -⚠️ **One frame for the three rails** (`app-rail-frame`, `shared/layout/rail-frame/`): the -width, the background and the edge that drags it, drawn once. It takes a width and its bounds -and emits the new one — it injects nothing — and each rail (`library-tree`, `tools-rail`, -`http-rail`) holds its `