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/CLAUDE.md b/CLAUDE.md index 615d694f..5dcc437f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,6 +1,6 @@ # CLAUDE.md -Guidance for Claude Code in this repository. `docs/architecture/` is the detailed reference, a wiki of pages by area whose home (`README.md` there) says what each page holds; a section is named by its heading after an arrow, unique across the pages, and `scripts/architecture-links.mjs` checks every such name: read the relevant section before a structural change and keep it in sync. Not this file, not the README. The decisions taken for the egui application (D1–D33) are its `decisions.md`; a decision is changed there first, never silently in code. +Guidance for Claude Code in this repository. `docs/architecture/` is the detailed reference, a wiki of pages by area whose home (`README.md` there) says what each page holds; a section is named by its heading after an arrow, unique across the pages, and `scripts/architecture-links.mjs` checks every such name: read the relevant section before a structural change and keep it in sync. Not this file, not the README. The decisions taken for the egui application (D1–D36) are its `decisions.md`; a decision is changed there first, never silently in code. ## Project @@ -58,7 +58,7 @@ Principles: - **Tools**: a pure Rust function each, called on the `compute` queue; `result` is an output, never an input; secrets are plain values. → "The tools: one contract…". - ⚠️ **The identity tool's lists are compiled in**: `crates/engine/resources/identity/` is `include_str!`-ed by `tools/identity/data.rs` (the standalone executable is one file) and each list is held whole by a test, not checked at run time. ⚠️ The names are **one list** (`names.txt`): never sort people's names by origin or by country — not in data, file names, order, code or tests. A new country is a file of places there, named in `data.rs`. → "The identity tool is that design…". - ⚠️ **Request scripts run in the app relaunched as a script host** (`--script-host`, read in `main` before any window): QuickJS, one host per request, a phase at a time; `pm.sendRequest` is sent by the parent. What `require` finds is bundled by `crates/engine/sandbox/build.mjs` into the committed `sandbox/dist/`. → "Request scripts, in a process of their own". -- **JSON explorer/visualiser**: inputs only; Rust owns the model (`explore_json`, nesting capped at 256, node/row caps). → "Exploring a JSON snippet", "The JSON visualiser's model". +- **JSON explorer/visualiser**: inputs only; Rust owns the model (`json::model::explore`, nesting capped at 256, node/row caps). → "Exploring a JSON snippet", "The JSON visualiser's model". - `closed_enum!` declares enums once. **Imports degrade rather than fail**, in one transaction; an added variant does not bump `FORMAT_VERSION`. → "Import, export and copying out". - ⚠️ **Every name of the application is `brand`'s** (D36): six values of the root `Cargo.toml`'s `[workspace.metadata]`; never type the name, the slug, the identifier, the extension or the site. Other metadata is read from `Cargo.toml` at compile time; the changelog is baked in (`include_str!`). → "The application's names". @@ -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/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..4c7c18d4 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -1,52 +1,106 @@ # Architecture -How DevNotes is put together, and the conventions to follow when extending it. -For build/run instructions see [CONTRIBUTING](../../CONTRIBUTING.md). +How DevNotes is put together, and the rules to keep when you change it. To build and run it, see +[CONTRIBUTING](../../CONTRIBUTING.md). + +DevNotes is **one Rust process**: an egui window over a core that owns the data. The window +never waits; the core does the work, on one database thread, and answers. + +```mermaid +flowchart LR + person(("person")) --> ui["ui
the egui window
state · actions · widgets"] + ui -- "ui::api → three queues" --> engine["engine
the core
db thread · notes index"] + engine --> disk[("library
SQLite, sealed values,
attachments")] + engine -- "network queue" --> net(("HTTP, WebSocket")) + engine -. "relaunched" .-> host["script host
QuickJS"] + ui --> platform["platform
tray · keys · dialogs
clipboard · updater"] +``` + +## Where to look + +| You want to… | Read | +| ---------------------------------------------- | ----------------------------------------------------------------------- | +| find your way around the crates | [Overview](overview.md) | +| add a feature end to end | [Overview](overview.md), then [Backend and events](interface/backend.md) | +| call the core from a screen | [Backend and events](interface/backend.md) | +| change a screen, a widget or a key | [Interface](interface/frame.md), [The window and its menus](interface/window.md) | +| change the schema or a query | [The core](core/engine.md) | +| touch encryption, a library, a backup, an export | [Libraries](core/libraries.md) | +| work on a kind of note | [Kinds of note](notes/kinds.md) | +| work on the list, a card, the board | [Cards and lists](notes/cards.md), [The board](notes/board.md) | +| work on the editor, the trash, the tags | [Editing notes](notes/editing.md) | +| work on the HTTP client | [Requests](http/requests.md), [Environments and scripts](http/environments-and-scripts.md), [On screen](http/drawn.md) | +| add a tool | [Tools](tools/tools.md) | +| ask the operating system something | [The binary and the desktop](interface/desktop.md) | +| add a string, a colour, a size | [Language, accessibility and theming](interface/look.md) | +| write a log line | [Logs](project/logs.md) | +| write a test or a journey | [Testing](project/testing.md) | +| release, package, update | [Updates and releases](project/releasing.md) | +| change the website | [The website](project/website.md) | +| know why something is the way it is | [Decisions](decisions.md), D1 to D36 | ## The pages -| Page | What it holds | Read it before changing | -| ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | -| [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 | -| [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 | -| [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 | - -The procedure of a release is [docs/releasing.md](../releasing.md); what the person reads is -[docs/content/](../content/). +**Start here** — [Overview](overview.md): the crates, feature-first, the application's names · +[Decisions](decisions.md): what is decided, and stays so. + +**The core** (`crates/engine`) — [The core](core/engine.md): the engine, its db thread, the notes +index, SQLite · [Libraries](core/libraries.md): encryption, the gate, several libraries, +preferences, backups, attachments, import and export. -## How to read them +**The interface** (`crates/ui`, `app`, `platform`) — [Interface](interface/frame.md): where a file +goes, state and actions, rendering, the keyboard, highlighting, Prettier · +[Backend and events](interface/backend.md): the queues, the widget kit, errors, the service +functions · [The binary and the desktop](interface/desktop.md): one instance, the window, the tray, +the global keys, quitting · [The window and its menus](interface/window.md): title bar, palette, +preferences, shortcuts, help · [Look](interface/look.md): translations, accessibility, theme. + +**Notes** — [Kinds](notes/kinds.md): snippet, Note, list, Calcul, Dessin · +[Cards and lists](notes/cards.md): the canvas, a card, the editor beside it · +[Editing](notes/editing.md): drafts, revisions, trash, bulk actions, fields, tags, attachments · +[The board](notes/board.md): spaces, folders, the board. + +**HTTP** — [Requests and answers](http/requests.md) · +[Environments, code and scripts](http/environments-and-scripts.md) · +[The area on screen](http/drawn.md). + +**Tools** — [The tools](tools/tools.md) · [The identity tool](tools/identity.md) · +[The JSON explorer](tools/json.md). + +**The project** — [Logs](project/logs.md) · [Testing](project/testing.md) · +[Updates and releases](project/releasing.md) · [The website](project/website.md). + +The procedure of a release is [docs/releasing.md](../releasing.md); what a person reads is +[docs/content/](../content/). -A section is named by its heading, after an arrow (→ "The concurrency rules"), never by a page -and a line: a heading is unique across these pages, so its name finds it wherever it stands. A -name may stop where its heading goes on after a comma, a colon or a bracket (→ "A card is two -layers"), and may name the bold words that open a paragraph (→ "Closing is not quitting"). +## The rules that bite -`scripts/architecture-links.mjs` reads every such name in the repository — Markdown, Rust, TOML, -YAML and the scripts — and every relative link into or between these pages, and fails when one -finds nothing or more than one section. CI runs it with the other script tests -(`node --test "scripts/*.test.mjs"`). +1. **The core decides, the window draws.** Filtering, sorting, grouping, counting: Rust. The + interface describes what was asked and draws what comes back (→ "Feature-first, not + layer-first"). +2. **The window never waits.** Every call goes `ui::api` → a queue → a `Pending` polled each frame + (→ "The concurrency rules"). +3. **One db thread, in order.** A write goes through `Engine::write` and says what it changed, or + the index lies (→ "The notes index"). +4. **Typed and answered is sealed** (→ "What is sealed, and what is not"); a passphrase is never in + a `TextEdit`, a log or a commit. +5. **Writes are not optimistic**: persist, adopt the answer, bump the revision (→ "State between + frames"). +6. **No string in Rust, no literal in a screen**: words are translation keys, sizes and colours are + theme tokens (→ "Theming"). -## Where a new section goes +## Reading and writing these pages -On the page of its area, beside the sections it leans on, under a heading no other page has. A -page past ~600 lines is split into a folder of its own, as `notes/` and `http/` are. A new page -opens with its title, a line on what it covers and a link home, and gets its row above. A -heading renamed is a reference broken: the check names every one to repoint. A decision is -written in [Decisions](decisions.md) before the code changes. +- **Each page opens on « In short »**, a few lines; the sections follow, short paragraphs, lists + and tables. +- **A section is named by its heading, after an arrow** (→ "The concurrency rules"), never by a page + and a line: a heading is unique across the pages. A name may stop where its heading goes on after + a comma, a colon or a bracket, and may name the bold words that open a paragraph. +- **`scripts/architecture-links.mjs` checks every such name** in the repository, and every link + between the pages; CI runs it with the script tests (`node --test "scripts/*.test.mjs"`). A + heading renamed is a reference broken: the check names every one to repoint. +- **A new section goes on the page of its area**, under a heading no other page has. A page past + ~600 lines is split; a new page gets its line above. A decision is written in + [Decisions](decisions.md) before the code changes. +- **These pages say what is, not how it came to be**: no issue numbers, no « used to ». A rejected + approach is worth a line when it would otherwise be tried again. diff --git a/docs/architecture/backend.md b/docs/architecture/backend.md deleted file mode 100644 index eecd698c..00000000 --- a/docs/architecture/backend.md +++ /dev/null @@ -1,330 +0,0 @@ -# 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. - -## 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. - -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. -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. -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. -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. - -## 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: - -- **`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. -- **`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. - -## 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. - -**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. - -## 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. - -## 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. - -## 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. - -## 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). - -## 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. -- 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. -- `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. - -## 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. diff --git a/docs/architecture/core/engine.md b/docs/architecture/core/engine.md new file mode 100644 index 00000000..a165f3ec --- /dev/null +++ b/docs/architecture/core/engine.md @@ -0,0 +1,193 @@ +# The core + +`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 + +`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 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| …)`. 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) + +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 new file mode 100644 index 00000000..5840c784 --- /dev/null +++ b/docs/architecture/core/libraries.md @@ -0,0 +1,302 @@ +# Libraries + +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 the passphrase unwraps once a launch. Nothing is kept of the +phrase: no keychain, no « remember me », no recovery. + +### Why not SQLCipher + +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`: a column added there is added here. + +| Table | Sealed | Plain | +| --------------------- | --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `spaces` | `name` | `id`, `pinned` | +| `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` | +| `note_items` | `text` | `note_id`, `position`, `done` | +| `note_revisions` | `content` | `id`, `note_id`, `taken_at` | +| `note_placeholders` | `value` | `note_id`, `name` | +| `global_placeholders` | `value` | `name` | +| `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` | +| `http_history` | `summary` (name, URL, method, status, time, size, failure, environment), `record` | `id`, `sent_at`, `request_id` | +| `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, 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/storage.rs`) and +`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 + +**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 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 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 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`), 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**: 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, 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` (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. + +⚠️ **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. + +- 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 + +``` +/ (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/ + / + .sqlite3 vault.json preferences.json + attachments/ backups/ damaged/ archived/ replaced/ +``` + +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**: ⚠️ **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). + +| 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 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 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`). + +## The copies, and putting one back + +`backup::copies::rotate` takes a copy at unlock, before the sweeps, into `backups//`: + +- 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`). + +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. + +`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`). + +**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). + +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`, 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`, 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/engine.md b/docs/architecture/engine.md deleted file mode 100644 index 8ec8632c..00000000 --- a/docs/architecture/engine.md +++ /dev/null @@ -1,418 +0,0 @@ -# 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 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. - -**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. - -**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`). - -## 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"). diff --git a/docs/architecture/http/drawn.md b/docs/architecture/http/drawn.md index f8c749c9..d44eccd9 100644 --- a/docs/architecture/http/drawn.md +++ b/docs/architecture/http/drawn.md @@ -1,229 +1,168 @@ # HTTP: the area on screen -How the HTTP area is drawn, and what the window asks before unsaved requests are lost. [Home](../README.md) - -## The HTTP area, drawn - -`ui::http` draws the area (`area-http`); `state::http::HttpState` holds the tree, a `QueryCell` -over `http_tree` asked again under the area's own `Revision` — a request renamed does not ask -the notes again — and read the first time the area is shown. The library rail is one for the -two areas: shown or hidden and its width are the application's settings, drawn by -`widgets::RailWidth`, which takes a setting changed in the other area since its edge last -moved; `Ctrl+B` is the area's key (`keys::HTTP`). `state::http::tree::rail_rows` lays the -tree flat once per answer or fold, not per frame (2,000 rows), and the rail draws the rows in -view alone (`widgets::virtual_list`): 8 px a level with a line a level in the indent, a -twisty on a collection or a folder only, a request after its method in its colour -(`http::rail::row::badge_hue`, `Badge::short` for `DEL` and `OPT`, `GQL`, `WS`), whose -accessible name is the method then the name. What is folded is the library's -(`devnotes.notes.http.collapsed`), a list of ids; anything else folds nothing. - -A row's `⋯` (`http-node-menu`) sits over the end of its name, inked only on hover or focus, -and opens `widgets::menu`: « Nouvelle requête › » keeps the three kinds behind one entry, then a -folder, rename, duplicate and delete; a request is only renamed, duplicated or deleted. ⚠️ The -menu closes on a click outside or on the entry picked, never on any click: an entry that opens a -sub-menu would close the menu it opens from. Creating and renaming are a field in place -(`http::rail::forms`): the field left for anything else keeps what was typed, left empty it -closes, Escape cancels. A deletion asks once Rust has counted what goes with it -(`count_http_contents`, `HttpState::ask_delete`), the question opened under the row. What -opens under a row is measured as it is drawn and the rows below it move down by that much: the -rows are placed by hand (`ScrollArea::show_viewport`), the ones in view alone. ⚠️ Each row's -`Ui` takes an explicit id (`UiBuilder::scope_id`), not a salt: a salted child's widgets take -their ids from its rank, and a row moved with the keys lost its focus. A click focuses the name, -as a button in a browser is: `F2` renames, `Delete` asks, `Alt` and an arrow move -(`state::http::moves`: `key_move`, `drop_move`, `refusal`). A move made with the keys is read -back from the tree Rust answers (`landing`), marked on the row and what now holds it for -`MARK_SECONDS`, scrolled into view and said in a live region (`http-rail-moved`); a refusal is -said there too. A drag lands before or after a row, or inside a folder or a collection when let go -mid-row. Every write bumps the area's revision; one into a folded parent unfolds it. - -`state::http::tabs::Tabs` holds the open requests, one tab each: a `Draft` (name, kind, method, -document) beside what Rust holds, modified while the two differ (`PartialEq`, where the reference -compared JSON). A request begun from « New request » — one click for HTTP, the chevron for GraphQL -or a WebSocket, or the empty workspace's three buttons — is a draft alone (`draft-n`), written -nowhere until saved. `Ctrl+S` (`keys::HTTP`) writes the draft in front whole -(`save_http_request`); typing during the write keeps what was typed. Closing a modified tab asks -first (`http::close`: cancel, close without saving, save — save waits for the first save's -dialog on a draft); the middle button closes a tab as in a browser, a press that moved too when -it is let go on the tab. A tab is dragged along the strip (`Tabs::move_to`, a gap between two -tabs), an amber bar where it would land, the rail's drop bar upright; held at an end, the strip -scrolls. Its keyboard twin is `Alt` and ← or → on the tab with the keys (`Tabs::nudge`); each -tab is drawn under a scope id of its key, so the keys stay on it as it moves. ⚠️ A tab follows every tree -that is read: a request deleted closes its tab, one moved takes its new place, one renamed takes -the name in what is saved and in what is edited, so the next save does not write the old one -back. The rail lights the request in front, and its deletion question names the open tabs it -would close with changes (`tree::requests_under`, `Tabs::unsaved_among`): Rust counts what is -deleted, only the interface what is typed. Which requests were open, in the strip's order, and which was in front is the -library's (`devnotes.notes.http.tabs`), read once the area is shown and written, with the folds, -whenever either changes (`HttpState::remember`). - -`http::request` draws the tab in front: its name, the method — or the kind, said where a method -would be chosen and no control — the URL and « Save », the `{{variables}}` it uses as chips, and -its parts a tab each. A field edits the draft directly: its text is -the draft's each frame, and a change is a `DraftEdit` applied at the end of the frame — no -buffer of the view's to keep in step. The URL and the parameters' table follow each other -through the core's `query::sync` (the side edited wins), called directly (D12). The URL's -variables are lit by a `TextEdit` layouter from `variables::spans` — what a variable is and -where it stands is the core's — in the colour of where each resolves from -(`http_variables`, asked with the draft, its place and the area's revision), red when nothing -sets it, amber until Rust has said. `http::request::table` is the key/value table: a blank row -at the end becomes a row once typed in; as headers, a row that cannot be sent is marked with why -(`header_faults`), `Name: value` typed in a name is split into its two cells, the caret moving -to the value (`headers_from_text`), and lines pasted in a name fill a row each. The headers -sent unasked are listed above the table with where each comes from -(`implied_http_headers`): Rust composes the request, so Rust says. ⚠️ The header names a key -field proposed came from the HTTP-headers tool's data: they return with the tools (phase 7). - -`http::request::body` draws the body by its kind. Another kind sets the one left aside, by tab -(`state::http::bodies`), and it comes back as it was: « Switch to None » on a `GET` would -otherwise cost the text it warns about; JSON and plain text share theirs. Never written: a -request saves the body it shows. What the body implies, whether a JSON one reads and whether its -method seldom carries one are one answer (`describe_http_body`), also read from the other tabs -for the mark on « Body ». A multipart row (`http::request::parts`) is a text or a file by its -path; the system's dialog opens off the frame (`HttpState::pick_file`), and its answer is -dropped if the body changed kind meanwhile. `http::request::graphql` lays its two boxes out in -rows of two cells, so that they start on one line whatever is said above each. These boxes are -the text core's `Editor`, the only fields here with a buffer of their own: the view holds those -of the tab in front (`TextBoxes`), the draft's text wins when the two differ, and what the core -rewrites — Prettier's format, the `null`s of « Add » — reaches them through the draft, unless -typing moved on since it was asked (`HttpState::rewrite`). ⚠️ `Ctrl+Enter` in a box sends: the -editor leaves it to `keys::dispatch` instead of writing a line. - -`http::request::auth` holds a request's auth: the secret half masked until asked for, and -« Inherited » saying what it takes and from where (`inherited_http_settings`, a `QueryCell` on the -place of the tab in front), the secret masked unless it is a `{{variable}}`. A draft has no place -yet, so it says so. `http::request::transport` lays the settings out with what each unset field -takes beside it; a number is settled once its field is left, since a timeout typed digit by -digit passes through values the floor would raise. `http::variables_table` is the table of a -request's variables, and of the environments' to come. `http::extract` is « Extract to a -variable », opened from the explorer under an answer: the path, the name proposed and whether it -reads as a secret are the core's (`extract::{body_path, variable_name_of, looks_secret}`, called -directly, D12). A rule is a part of the draft, saved with the request; `http::request::extractions` -reads and removes them, under « Scripts », where the scripts join them. `http::environment_picker` -is at the end of the tabs' strip: the active environment is the library's -(`devnotes.notes.http.environment`), one deleted since it was chosen is none, and a send and the -variables' chips both resolve from it (`state::http::environments`). ⚠️ JetBrains Mono and Inter -have no `→` and no fullwidth `+`: egui panics on a missing glyph in a test, so an arrow is an -`Icon` and a plus is a plain `+`. - -`state::http::Page` is what the workspace shows: the open requests, or a page from the rail's -foot, one at a time; a request opened from the rail leaves it. `http::environments` is the page -of the globals and the environments. Its table keeps the rows as typed and writes them once the -keys rest (`SAVE_AFTER`), on another set chosen and on leaving the page, then drops them once -what is read back holds them; typing during a write keeps what was typed. Every write of this -page bumps a revision of its own, so that a key typed does not read the tree again; a send that -ends bumps the area's, since an extraction or a script may have written a variable. A secret -shown in one set is masked in the next. Under a protected environment, what could change -something waits for a yes under the request line (`environments::asks_before_sending`), and the -yes goes to the core with the send (`confirmed`), a script then being free to change the -environment. A chip nothing sets is a click from a row of its own on the page, in the active -environment or the globals. - -`http::cookie_jar` lists what answers set, by domain, and throws it away: a cookie, a domain, or -the whole jar once Rust has counted it (`state::http::cookies`). `http::container_settings` is a -collection's or a folder's variables, auth, headers and transport, opened from its row's menu. -The draft is the state's and is written whole on « Save »; a folder's « Inherited » reads from its -parent, what it sets itself not being what it inherits. It shares the request's editors, which -take a value and answer the value edited: `Inherit` on a collection is no auth at all, and reads -as « None ». `http::modal` is the frame of the area's dialogs. ⚠️ A dialog centres itself again -when its height changes: what clicks in a test settles first, a pointer aimed at the old place -hits nothing. - -`http::code` is « Generate code »: Rust writes the request for a target (`generate_http_code`, -asked again whenever the draft, the place, the environment, the target or a switch changes), the -dialog names the targets, a `match` a new target will not compile without, and says what was -left as a variable. « Include secrets » asks every time it is switched on, never when off. The -target last chosen stays for the session. `response::body::TextLines` is the text read by lines -it shares with the answer's body. `http::save_request` asks where a draft goes the first time it -is saved, from `Ctrl+S`, « Save » or the close question, and creates what it lacks in one write -(`create_http_request_in`): refused, it leaves no empty collection behind. The tab then takes the -request's id for its key, and what is kept by key follows it (`Answered::rekeyed`). ⚠️ -`Ui::allocate_ui` keeps the parent's layout: in a `horizontal`, what is inside runs on a line -until it is given a `vertical`. - -`http::history` is the page of what was sent, a `Page` as the environments are: the sends by -local day, in rows drawn only in view, beside the entry chosen, read through -`response::recorded`, the answer's parts without a tab to clear it from. It is read again when a -send ends. A send is deleted unasked and comes back from the bar under the list for -`UNDO_WINDOW`; emptying it says how many go first. « Reopen » puts a send back onto the request -it came from, as changes to save or not (`http_history_onto_request`, `Tabs::open_with`), asking -before it writes over a tab's own; the request gone, or the send made from a draft, it is a -draft named after the send and its time. The core keeps `KEPT_AT_MOST` sends, so the list holds -500 rows at most. - -A WebSocket's tab holds a composer above and a log below. `state::http::sockets` keeps where each -socket stands and its last `LOG_KEPT` events, under the id it was connected with: the core's -`EngineEvent::Socket` names that id, so a draft saved meanwhile is rekeyed and an event from a -socket replaced since is dropped. Connecting asks as a send does under a protected environment. -`Ctrl+Enter` in the message sends it and is taken there, the area answering the same key by -connecting; on a closed socket it says so and connects nothing. The log draws its rows in view -alone, so a message reads on one line, whole in its tooltip. Closing a live socket's tab asks -first, and a closed tab closes its socket. - -`http::scripts` is the script editor of a request, a folder or a collection: the text core's -`Editor` by phase, each with its history, JavaScript coloured as a snippet is, a menu of examples -written at the end of the script, and for a request the order the scripts run in, a level above -a click from its settings on the same script. The extractions stand among the scripts after the -answer. What runs them is the application relaunched as their host: a kittest bench is not that -binary, so running them is journey 10's. A script that stopped before the send stands in place -of the answer, read back from its error's params (`ScriptStop::of_params`); after it, above the -answer that came. « Open the script » goes to the request's own, or to the settings of what -holds it, on the phase, the line marked until the next edit (`HttpState::script_focus`). - -`http::console` sits under the answer: `EngineEvent::Console` names a send, `Sends::key_of` its -tab, and each tab keeps its last `LINES_KEPT` lines for the session, never written. Rust masks what -it says; `console::secret_segments` cuts a text where a secret stands as its `{{name}}`, to set it -apart. Folded it says how much it holds; unfolded it filters, by rows drawn in view alone. The -Tests part of an answer groups them by whose they are, a line a click from the script. An answer -goes to a file whole, from Rust and not from what is shown, or to a note: `http::save_as_note` asks -where, `state::http::kept` holds what is on its way, and the core masks what the request sent -before the dialog even opens (`http_response_note`). Generated code takes the same dialog. - -`http::runner` is the area's fourth page: a collection or a folder run, over iterations or the rows -of a data file. `state::http::runner` holds how, in which order and the report of the last run, -for the session; Rust runs and says its steps as `EngineEvent::Run`, and the order follows the -tree, kept with the collection (`http_run_order`). Its report is a list of lines of one height, -drawn in view alone, summed up by `RunSummary`; the kept answer last unfolded reads beneath it. A -run's sends are named `run:#…` (`runner::run_of`), and so its console has a key of its own, -forgotten when the next run starts. - -Closing the window, or Quit, goes through `AppState::may_close`: with a tab modified, `http::leave` -asks first, over any area, and « Save all » walks the tabs, a request never saved asked its place. -A write that fails or a place refused leaves the question out. A note open closes by its own path, -which writes its drafts, and the window follows it. Then the window hides, `on_exit` queues what -waits, stops the network behind it and drains the queue (30 s at most). - -A send leaves on the network queue (`Backend::spawn`, `send_http_request`) and never holds the db -queue; `state::http::send::Sends` keeps one a tab, under a send id fixed at the send -(`#`), so a draft saved meanwhile changes its tab's key, not that. Its start is egui's -time, so the count under way survives leaving the tab. « Send » turns into « Cancel » while it -runs (`cancel_http_send`), `Ctrl+Enter` sends the tab in front, and a closed tab or « Clear » -lets Rust forget the body it kept (`forget_http_response`). `http::response` draws the answer: -the status on a tint of its family (`2xx` green, `3xx` blue, `4xx` amber, the rest red), time -and size, then the body, headers, cookies and the exchange as it went (redirects, request, -response). The body is cut into lines once per send and view and drawn by rows, a line-number -gutter beside it, coloured window by window by `services::highlight::Colouring` (a 785 KB answer -is laid out in under 150 ms, a frame of scrolling stays under a millisecond); a JSON answer is -also explored as a graph or a tree — the explorer of the notes, without its « show in the -code » (`ExplorerView::with_code(false)`), asked through `HttpState::explore` — and an image is -decoded once from its `data:` URL into a texture. The line between the request and its answer is -the application's `devnotes.httpRequestShare` (tenths of a percent here, a percent in the file): -left automatic, the request takes what it holds up to 60 %; dragged, the share is written once -let go; a double click or Enter makes it automatic again. +How the HTTP area is drawn — the rail, the tabs, the request, its pages, the answer — and what the +window asks before unsaved requests are lost. [Home](../README.md) + +**In short** + +- `ui::http` draws; `state::http` holds the tree, the tabs, the sends, the sockets and the pages. +- Long lists (the rail, the history, the console, the socket log, the runner's report, a body) draw + only the rows in view. +- A field edits the tab's draft directly; the draft is what is saved, whole. +- Nothing waits in the frame: a send is on the network queue, the tree is a `QueryCell`. + +## The rail + +`state::http::HttpState` holds the tree, a `QueryCell` over `http_tree` asked again under the +area's own `Revision` (a request renamed does not ask the notes again), read the first time the +area is shown. The rail's shown state and width are the library rail's settings +(`widgets::RailWidth`); `Ctrl+B` is the area's key (`keys::HTTP`). + +- `state::http::tree::rail_rows` lays the tree flat once per answer or fold, not per frame, and the + rail draws the rows in view alone (`widgets::virtual_list`): 8 px a level with a line a level, a + twisty on a container only, a request after its method in its hue (`http::rail::row::badge_hue`, + `Badge::short`), its accessible name the method then the name. +- **A row's ⋯** (`http-node-menu`) opens `widgets::menu`; ⚠️ it closes on a click outside or on the + entry picked, never on any click, or an entry opening a sub-menu would close its own menu. + Creating and renaming are a field in place (`http::rail::forms`). A deletion asks once Rust has + counted what goes (`HttpState::ask_delete`), under the row. +- ⚠️ **Each row's `Ui` takes an explicit id** (`UiBuilder::scope_id`), not a salt: a salted + child's widgets take their ids from its rank, and a row moved with the keys lost its focus. +- **Keys on a focused row**: `F2` renames, `Delete` asks, `Alt` and an arrow move + (`state::http::moves`: `key_move`, `drop_move`, `refusal`). A move is read back from the tree + Rust answers (`landing`), marked for `MARK_SECONDS`, scrolled into view and said + (`http-rail-moved`). Every write bumps the area's revision; one into a folded parent unfolds it. + +## The tabs + +`state::http::tabs::Tabs` holds the open requests: a `Draft` (name, kind, method, document) beside +what Rust holds, modified while the two differ (`PartialEq`). + +- **« New request »**: one click for HTTP, the chevron for GraphQL or a WebSocket. A draft alone + (`draft-n`) is written nowhere until saved. +- **`Ctrl+S`** writes the draft in front whole (`save_http_request`); typing during the write keeps + what was typed. A draft's first save asks where it goes (`http::save_request`), creating what is + missing in one write (`create_http_request_in`); the tab then takes the request's id for its key, + and what is kept by key follows it (`rekey`). +- **Closing a modified tab asks** (`http::close`: cancel, close without saving, save). The middle + button closes a tab, as in a browser. +- **A tab is dragged along the strip** (`Tabs::move_to`, an amber bar where it would land; held at + an end, the strip scrolls), or moved by `Alt` and ← → (`Tabs::nudge`). Each tab is drawn under a + scope id of its key, so the keys stay on it as it moves. +- ⚠️ **A tab follows every tree read**: a request deleted closes its tab, one moved takes its new + place, one renamed takes the name in what is saved and in what is edited. The rail's deletion + question names the open tabs it would close with changes (`tree::requests_under`, + `Tabs::unsaved_among`). +- The tabs left open, in order, and the one in front are the library's (`notes.http.tabs`), + written with the folds whenever either changes (`HttpState::remember`). + +## The request + +`http::request` draws the tab in front: its name, the method (or the kind, where a method would +be), the URL and « Save », the `{{variables}}` it uses as chips, and its parts a tab each. + +- **A field edits the draft directly**: its text is the draft's each frame, a change is a + `DraftEdit` applied at the end of the frame — no buffer of the view's to keep in step. +- **The URL and the parameters' table follow each other** through `query::sync`, called directly + (D12). The URL's variables are lit from `variables::spans`, in the colour of where each resolves + from (`http_variables`), red when nothing sets it, amber until Rust has said. +- **`http::request::table`** is the key/value table: a blank row at the end becomes a row once typed + in; as headers, a row that cannot be sent is marked with why (`header_faults`), `Name: value` + typed in a name is split (`headers_from_text`), lines pasted fill a row each. The headers sent + unasked are listed above it (`implied_http_headers`). +- **`http::request::body`**: another kind sets the one left aside, by tab (`state::http::bodies`); + JSON and plain text share theirs. A multipart row (`http::request::parts`) is a text or a file by + its path; the dialog opens off the frame (`HttpState::pick_file`), its answer dropped if the body + changed kind meanwhile. +- **`http::request::graphql`**: two boxes in rows of two cells, so they start on one line. They are + the text core's `Editor`, the only fields here with a buffer of their own (`TextBoxes`): the + draft's text wins when the two differ, and what the core rewrites (a format, « Add ») reaches + them through the draft unless typing moved on (`HttpState::rewrite`). ⚠️ `Ctrl+Enter` in a box + sends. +- **`http::request::auth`**: the secret half masked until asked for, « Inherited » saying what it + takes and from where (`inherited_http_settings`, a `QueryCell` on the tab's place). +- **`http::request::transport`**: each unset field shows what it takes; a number is settled once + its field is left, since a timeout typed digit by digit passes through values the floor would + raise. +- **`http::variables_table`**: a request's variables, and an environment's. +- **`http::extract`**, « Extract to a variable », from the explorer under an answer: the path, the + name proposed and whether it reads as a secret are the core's (`extract::body_path`, + `variable_name_of`, `looks_secret`, called directly). A rule is part of the draft, listed under + « Scripts » (`http::request::extractions`). +- ⚠️ The embedded faces have no `→` and no fullwidth `+`, and egui panics on a missing glyph in a + test: an arrow is an `Icon`, a plus a plain `+`. + +## The workspace's pages + +`state::http::Page` is what the workspace shows: the open requests, or a page from the rail's foot, +one at a time; a request opened from the rail leaves it. + +| Page | Holds | +| ------------------------------------- | ---------------------------------------------------------------------------------------------- | +| environments (`http::environments`) | the globals and the sets; a table written once the keys rest (`SAVE_AFTER`) and on leaving; a secret shown in one set masked in the next | +| history (`http::history`) | the sends by local day, beside the entry read through `response::recorded`; a send deleted comes back from the undo bar for `UNDO_WINDOW`; « Reopen » onto its request (`Tabs::open_with`) | +| runner (`http::runner`) | how and in which order a collection or folder is run, and the report of the last run (`RunSummary`), its console keyed `run:#…` (`runner::run_of`) | + +Beside them: `http::cookie_jar` (by domain; a cookie, a domain or all, once Rust has counted), +`http::container_settings` (a collection's or folder's variables, auth, headers, transport, opened +from its row; a folder's « Inherited » reads from its parent), `http::code` (« Generate code », +the target last chosen kept for the session), `http::environment_picker` at the end of the strip. +`http::modal` frames the area's dialogs; ⚠️ a dialog centres itself again when its height changes, +so a test's pointer settles first. + +- Under a protected environment, what could change something waits for a yes under the request line + (`environments::asks_before_sending`), and the yes goes to the core with the send (`confirmed`). +- A page's writes bump a revision of their own, so a key typed does not read the tree again; a send + that ends bumps the area's, since an extraction or a script may have written a variable. + +## Sending, and the answer + +A send leaves on the network queue (`Backend::spawn`) and never holds the db queue. +`state::http::send::Sends` keeps one a tab under a send id fixed at the send (`#`), so a +draft saved meanwhile changes its tab's key, not that; its start is egui's time, so the count +survives leaving the tab. « Send » turns into « Cancel » (`cancel_http_send`); a closed tab or +« Clear » lets Rust forget the body it kept (`forget_http_response`). + +- **`http::response`**: the status on a tint of its family (`2xx` green, `3xx` blue, `4xx` amber, + the rest red), time and size, then the body, headers, cookies and the exchange. +- **The body** is cut into lines once per send and view (`response::body::TextLines`) and drawn by + rows with a gutter, coloured window by window (`services::highlight::Colouring`): a 785 KB answer + lays out in under 150 ms, a frame of scrolling under a millisecond. A JSON answer is also explored + as a graph or a tree — the notes' explorer, without « show in the code » + (`ExplorerView::with_code(false)`, through `HttpState::explore`); an image is decoded once into a + texture. +- **The line between request and answer** is `httpRequestShare` (tenths of a percent on screen, a + percent in the file): automatic, the request takes what it holds up to 60 %; dragged, written once + let go; a double click or Enter makes it automatic again. +- **A WebSocket's tab** is a composer above a log below (`http::socket_log`). + `state::http::sockets` keeps where each socket stands and its last `LOG_KEPT` events, under the + id it was connected with, so an event from a socket replaced since is dropped. Connecting asks as + a send does under a protected environment. +- **The console** (`http::console`) sits under the answer: `Sends::key_of` finds the tab an event + names, each tab keeps its last `LINES_KEPT` lines, and `console::secret_segments` sets apart a + secret written as its `{{name}}`. The Tests part groups results by holder, each a click from its + script. +- **The scripts** (`http::scripts`): the text core's `Editor` by phase, JavaScript coloured, a menu + of examples, and for a request the order its scripts run in. A script that stopped before the send + stands in place of the answer (`ScriptStop::of_params`). « Open the script » marks the line until + the next edit (`HttpState::script_focus`). Running them is journey 10's: a kittest bench is not + the binary that hosts them. +- **An answer goes to a file** whole, from Rust, or **to a note** (`http::save_as_note`, + `state::http::kept`), the core masking what the request sent before the dialog opens + (`http_response_note`). ## Leaving with requests not saved -A request typed in a tab and never saved, or a saved one with changes, does not survive a -restart: the tabs keep the ids of the saved requests that are open, nothing else. The window -**asks before they are lost** (`state::http::leave`, drawn by `ui::http::leave`, since any area -can be the one on screen). - -- **Everything that takes the window away asks first**: « Quit » (the File menu, the tray, the - close button when it does not hide), a library opened or created, a backup restored, an update - installed. What waits for the answer is a `libraries::Goal`. ⚠️ Nothing is asked when no tab is - modified: leaving stays instant. -- **One dialog**: how many requests, their names under the dot a modified tab wears, a sentence - for the WebSockets that will be cut, then « Cancel », « … without saving » and « Save all ». - That last one writes the requests that have a place, then walks those never saved through the - save dialog, one at a time; a place not given comes back to the question, and a write that - fails leaves it standing. -- A hidden window draws nothing, so a quit held for the question brings the window up first. +A request typed and never saved, or a saved one with changes, does not survive a restart: the tabs +keep only the ids of saved requests. The window **asks before they are lost** (`state::http::leave`, +drawn by `http::leave`, since any area can be the one on screen). + +- **Everything that takes the window away asks first** (`AppState::may_close`): « Quit », a library + opened or created, a backup restored, an update installed. What waits for the answer is a + `libraries::Goal`. ⚠️ Nothing is asked when no tab is modified: leaving stays instant. +- **One dialog**: how many requests, their names, a sentence for the WebSockets that will be cut, + then « Cancel », « … without saving » and « Save all », which writes those with a place, then walks + those never saved through the save dialog; a place not given or a write that fails leaves the + question standing. +- A hidden window draws nothing, so a quit held for the question brings it up first. A note open + closes by its own path, which writes its drafts, and the window follows. diff --git a/docs/architecture/http/environments-and-scripts.md b/docs/architecture/http/environments-and-scripts.md index daf28e1b..a00ff678 100644 --- a/docs/architecture/http/environments-and-scripts.md +++ b/docs/architecture/http/environments-and-scripts.md @@ -1,245 +1,183 @@ # HTTP: environments, code and scripts -Environments and globals, where a variable resolves from, the code generated from a request, and request scripts in a process of their own. [Home](../README.md) +Environments and globals, where a variable resolves from, the code generated from a request, and +request scripts in a process of their own. [Home](../README.md) + +**In short** + +- One environment is active for the whole area; the globals are always there. +- A `{{name}}` is resolved by Rust at send, nearest level first; a name nothing sets refuses the + send. +- « Code » is written by Rust, one module a target, each held by golden files. +- Scripts run in the application started again as a script host (QuickJS), never in the window's + process. ## Environments and the globals -**A request is sent with one environment, picked for the whole area** (#485): the globals, -shared by every collection, and the environments — Local, Staging, Production — each a set of -variables with a name, one of the folders' five colours and a protection. They are the -library's, beside the collections (`http_environments`, migration 18, `http/environments.rs` -and its `store.rs`): one row a set, the document sealed whole, the globals the one row of -their kind. Names are compared in Rust, case aside (`duplicateEnvironmentName`); a copy is -named by the front and sits right after its original, secrets included. - -- **A variable is a name, a value and a type** — Text, Number, Secret. A table keeps its rows - as typed; `environments::variable_faults` answers each row's fault (a name a `{{…}}` cannot hold, - one set twice in the table, a number that does not read), the table marks it and says why, - as the headers' table does. A secret's value is a password field, shown one row at a time. -- **The page is the workspace's, as the history is** (`HttpWorkspaceStore.page`: requests, - history or environments, one at a time; a request opened from the tree leaves either). The - globals first, then each environment with its counts; the one shown on the right, its name - written on leaving the field. ⚠️ Its table is written once the keys rest - (`VARIABLES_SAVE_MS`) and on every way out (`HttpEnvironmentsStore.flush`): the rows as - typed are a draft keyed by the set, shown until Rust has written them. -- **The active one is the library's preference** (`devnotes.notes.http.environment`), picked - at the end of the tab bar (`EnvironmentPickerComponent`), « Aucun » meaning the globals alone - — and the answer for one deleted since. -- ⚠️ **A protected environment asks before anything but a `GET`, a `HEAD` or an `OPTIONS` - leaves, and before a WebSocket opens** (`asksBeforeSending`, the front's alone: Rust sends - what it is given). `HttpSendStore.send` and `HttpSocketsStore.connect` both ask - `HttpEnvironmentsStore.mayLeave`, so `Ctrl+Enter` cannot go round it; the question is a line - under the request's, the rail's idiom for a deletion, its one red the button. +**A request is sent with one environment, picked for the whole area**: the globals, shared by +every collection, and the environments — Local, Staging, Production — each a set of variables +with a name, one of the folders' five colours and a protection. They are the library's +(`http_environments`, `http/environments.rs`): one row a set, sealed whole, the globals the one +row of their kind. Names are compared in Rust, case aside (`DuplicateEnvironmentName`); a copy +sits right after its original. + +- **A variable is a name, a value and a type** — Text, Number, Secret. A table keeps its rows as + typed; `environments::variable_faults` answers each row's fault (a name a `{{…}}` cannot hold, + one set twice, a number that does not read), which the table marks, as the headers' table does. + A secret's value is shown one row at a time. +- **The page** (`http::environments`, `state::http::environments`) replaces the requests while it + is open, as the history does: the sets on the left, the one chosen on the right. ⚠️ A table is + written once the keys rest (0.4 s) and on every way out; the rows as typed are a draft shown + until Rust has written them. +- **The active one is the library's** (`notes.http.environment`), picked at the end of the tab + strip (`http::environment_picker`); « None » means the globals alone, and is the answer for one + deleted since. +- ⚠️ **A protected environment asks before anything leaves that is not a `GET`, `HEAD` or + `OPTIONS`** (`HttpMethod::changes_nothing`), and before a WebSocket opens. The send and the + socket both ask the same state, so `Ctrl+Enter` cannot go round it. Rust asks again after the + scripts (below): a method a script changed is refused until confirmed. ## Variables, and where each resolves from -**A `{{name}}` is resolved by Rust when the request is sent, and nowhere else** (#486, -`http/variables.rs`): `send_http_request` and `connect_websocket` read, under the lock, the -levels in force — the request's own variables (`RequestDocument.variables`), its folders' and -its collection's (`ContainerSettings.variables`, laid nearest first in `Inherited.variables`), -the environment the front names (`environmentId`; one gone since counts as none), the globals -— and fill the URL, the parameters, the headers, the body, the auth and the GraphQL query and -variables before `compose`. The nearest level wins; a row switched off or one its table marks -is left out; a value naming another is filled again, eight times at most. - +**A `{{name}}` is resolved by Rust when the request is sent, and nowhere else** +(`http/variables.rs`): `send_http_request` and `connect_websocket` read, in a db job, the levels in +force and fill the URL, the parameters, the headers, the body, the auth and the GraphQL query and +variables before `compose`. + +| Level (nearest first) | Held in | Chip colour | +| --------------------- | ----------------------------------------------------------------- | ----------- | +| the request | `RequestDocument.variables` | green | +| its folders | `ContainerSettings.variables` (`Inherited.variables`, nearest first) | teal | +| its collection | `ContainerSettings.variables` | blue | +| the environment | the active set | amber | +| the globals | the globals' row | pink | +| dynamic | made at the send: `{{$guid}}`, `{{$randomUUID}}`, `{{$timestamp}}`, `{{$isoTimestamp}}`, `{{$randomInt}}` | purple | + +- The nearest level wins; a row switched off or marked is left out; a value naming another is + filled again, eight times at most. A dynamic value is new each place it is written + (`variables::is_dynamic`); no level can set one, `$` being no letter of a name. - ⚠️ **Not `notes::placeholder`.** A snippet's `{{field}}` looks alike; the two resolvers never - meet. The grammar is the same — `[A-Za-z0-9_-]` — and `http::variables::names_in` is the - HTTP side's only reader, header names judged by `as_letters` included. -- **A name nothing sets refuses the send** (fork C): `compose` finds the first `{{name}}` left - in what `variables::texts` lists — what leaves, nothing that does not — and answers - `httpVariable` with it. Nothing is sent as typed. -- **The editor asks Rust what each name resolves to** (`http_variables`, the same layers and - texts as a send): a chip a name under the URL, in the colour of its level — the request - green, a folder teal, the collection blue, the environment amber, the globals pink, red when - nothing sets it — and the URL's copy in the same hues. Pointed at or focused, a chip opens its - card (`http::request::chips`, kept open while the pointer is on it), which says from where, the value (a secret's masked until « Afficher », masked again once left) and the - levels it hides; a name nothing sets offers « Définir dans … », which opens the environment - — the globals with none — on a row of that name. The answer is asked again when the request, - its place, the environment or a set changes, the last one kept while the next is read. -- A send first writes what an environment's table still holds (`HttpEnvironmentsStore.flush`): - it resolves from what Rust has. -- **`{{$guid}}`, `{{$randomUUID}}`, `{{$timestamp}}`, `{{$isoTimestamp}}` and `{{$randomInt}}` are - made at the send** (`variables::is_dynamic`), a new value each place one is written; no level - can set one, `$` being no letter of a name. The editor's chip says so in the purple of - `VariableScope::Dynamic`. The `$random…` names that invent people, places or words are not - among them: each would be a list to compile in. + meet. The grammar is the same (`[A-Za-z0-9_-]`) and `http::variables::names_in` is the HTTP + side's only reader. +- **A name nothing sets refuses the send**: `compose` finds the first `{{name}}` left in what + leaves (`variables::texts`) and answers `HttpVariable` with it. Nothing is sent as typed. +- **The editor asks Rust what each name resolves to** (`http_variables`, the same layers): a chip + a name under the URL in its level's colour, red when nothing sets it. A chip opens its card + (`http::request::chips`): from where, the value (a secret masked until « Show »), the levels it + hides; a name nothing sets offers « Define in … », which opens the environment on a row of that + name. A send first writes what an environment's table still holds. ## Generating code from a request -**« Code » writes the request for another tool, and Rust writes it** (#488, -`http/codegen.rs`, `generate_http_code`): the same layers a send resolves from, then one -shape every target reads — `CodeRequest`, built by `request_of` from what a send would write -(`send::written_for_code`: the headers `compose` writes, but the application's own -`User-Agent` and `Accept` — the program names itself —, a Basic auth kept apart for each -target to write its own way, and a multipart form's type, whose boundary the tool chooses) — -and one module a target, each held by golden files (`codegen/golden/-.txt`, -written again with `GOLDEN_WRITE=1`, then read before they are kept). - -- **The four switches**: « Résoudre les variables » (off, every `{{name}}` is written as typed), - « Inclure les secrets » — off, a secret is resolved by none of the layers and stays its - `{{name}}`; on, it is written in clear, and the dialog asks every time it is switched on —, - « Sur plusieurs lignes » and « Suivre les redirections ». Rust answers the code, its language, - the secrets left as variables and the names nothing sets: the dialog says them, each name as - a parameter, never inside a translated sentence (Transloco would empty it). -- **A target Rust cannot fully write says so by a code** (`CodeNotice`): wget sends no multipart - form. -- **The JavaScript and TypeScript targets** (#489) share `codegen/javascript.rs` — strings (a - template literal for a text of several lines, so a JSON body stays laid out), bare or quoted - keys, object literals. `fetch`, axios and undici run under Node and read a file with - `openAsBlob`; Angular's `HttpClient` runs in a browser, which reads no path: a file part is a - `File` the code declares. A program is laid out whatever « Sur plusieurs lignes » says — the - switch only cuts a command line, and is greyed for the others. -- **The twelve others** (#490) — Python's requests and httpx, Go's net/http, Rust's reqwest, Java's - `HttpClient`, Kotlin's OkHttp, C#'s `HttpClient`, PHP's Guzzle, Ruby's `Net::HTTP`, Swift's - `URLSession`, Dart's http, Elixir's Req — each write their own literals (`codegen/source.rs`: - Kotlin escapes `$`, Elixir `#{`, PHP and Ruby take single quotes). Java's client and - `URLSession` build no multipart body, as wget does not (`CodeTarget::sends_multipart`), and - Ruby's `Net::HTTP` and `URLSession` follow redirects as they do whatever is asked. Kotlin, Ruby, - Swift, Dart and Elixir joined the snippet languages (fork E), each with a scorer and a corpus - snippet, so the code is saved in its language. -- **The list is the front's** (`CODE_TARGETS`, a `Record` on the generated `CodeTarget`, so a - target added in Rust breaks the build until it is named), grouped and filtered on its name and - library — the tools' catalogue's exception. Names like cURL or PowerShell are proper names and - are not translated. -- **« Enregistrer comme snippet »** opens the save-as-note dialog with the code, its language - (`sh`, `ps1` — PowerShell joined the languages for it, chosen and never detected) and `http` - proposed as its tag. +**« Code » writes the request for another tool, and Rust writes it** (`http/codegen.rs`, +`generate_http_code`, drawn by `http::code`): the layers a send resolves from, then one shape every +target reads, `CodeRequest` (`request_of`, from `send::written_for_code`: the headers `compose` +writes, less the application's own `User-Agent` and `Accept`; a Basic auth kept apart for each +target to write its way; a multipart's type, whose boundary the tool chooses). One module a +target, each held by golden files (`codegen/golden/-.txt`, rewritten with +`GOLDEN_WRITE=1`, then read before they are kept). + +- **Four switches**: resolve the variables (off, every `{{name}}` written as typed); include the + secrets (off, a secret stays its `{{name}}`; on, written in clear, and asked every time it is + switched on); on several lines; follow redirects. Rust answers the code, its language, the secrets + left as variables and the names nothing sets, which the dialog lists — each name a parameter, + never inside a translated sentence. +- **A target that cannot fully write the request says so by a code** (`CodeNotice`): wget sends no + multipart, nor do Java's client and `URLSession` (`CodeTarget::sends_multipart`). +- **The targets**: shell ones (cURL, wget, HTTPie, PowerShell…); JavaScript and TypeScript sharing + `codegen/javascript.rs` (`fetch`, axios, undici under Node, Angular's `HttpClient` in a browser); + and Python's requests and httpx, Go, Rust's reqwest, Java, Kotlin's OkHttp, C#, PHP's Guzzle, + Ruby, Swift, Dart, Elixir's Req, each writing its own literals (`codegen/source.rs`). A program + is laid out whatever « several lines » says: the switch only cuts a command line. +- **The list is matched exhaustively** on `CodeTarget` in the interface, so a target added in Rust + does not compile until it is named. Proper names are not translated. +- « Save as a snippet » opens the save-as-note dialog with the code, its language and `http` as + its tag. ## Request scripts, in a process of their own **A script is JavaScript run by QuickJS in a script host: the application started again** -(#492, `http/scripts/`). The WebView cannot run it — its CSP forbids `eval`, and should — and the -application's own process holds the library's key and every note: an engine bug there reaches -them. So `ScriptProcess::start` (`process.rs`) launches `current_exe()` with -`--script-host`, which `main` reads **before Tauri** (no window, no single instance, no -library), its environment cleared but for what loads the executable (`SystemRoot`, -`LD_LIBRARY_PATH`). The host (`child.rs`) reads one JSON message a line on its standard input and -answers on its standard output. - -- **One host for one request**, given a phase at a time (`Job`, `model.rs`): before the send, - then after it — the second reads what the first left in `pm.variables`. A phase has - `PHASE_TIME` (30 s), its sends included: past it QuickJS's interrupt handler stops the script - (an endless loop ends as `FailureKind::Timeout`, never as a frozen window), and 2 s later the - application kills the host, which is never given another phase. 128 MB of heap; QuickJS's - stack limit is 8 MB on a 16 MB thread — Ajv's schema compiler needs more than the default - megabyte. -- **The engine** (`engine.rs`) compiles each script as the body of an async function under its - own name (`script-3`), so a stack names the script and the user's line, and an `await` reads at - its top level. It then drives the phase: the promises' jobs, then the prelude's timers - (`nextTimer`, `fireTimers`), until the phase's promise settles; a wait nothing can end — no job, - no timer — is said rather than waited for. Timers due together fire by deadline, then by - creation, as in Node: Windows wakes a 5 ms sleep about 15 ms later, so several are often due at - once. -- **The API is the prelude's** (`prelude.js`, JavaScript over four natives: `call`, `log`, - `random`, `module`): `req`, `res`, `env`, `test`, `expect`, `console`, the timers, and - Postman's `pm` (request, response, environment, globals, collection variables, variables, - iteration data, cookies and their jar, `sendRequest`, `execution`) with its older names - (`tests[…]`, `postman.*`, `responseBody`, `xml2Json`…). `pm.visualizer` draws nothing and says - so; `pm.require` and `pm.vault` have nothing behind them. +(`http/scripts/`). The application's own process holds the library's key and every note; an engine +bug there would reach them. So `ScriptProcess::start` (`process.rs`) launches the current +executable with `--script-host`, which `main` reads **before anything else** (no window, no +instance, no library, no log), its environment cleared but for what loads the executable. The host +(`child.rs`) reads one JSON message a line on its standard input and answers on its output. + +- **One host for one request**, given a phase at a time (`Job`): before the send, then after it — + the second reads what the first left in `pm.variables`. A phase has `PHASE_TIME` (30 s), its sends + included: past it QuickJS's interrupt handler stops the script (`FailureKind::Timeout`), and 2 s + later the application kills the host. 128 MB of heap; an 8 MB stack limit on a 16 MB thread (Ajv + needs more than a megabyte). +- **The engine** (`engine.rs`) compiles each script as the body of an async function under its own + name (`script-3`), so a stack names the script and the line, and a top-level `await` reads. It + drives the promises' jobs, then the prelude's timers, until the phase settles; a wait nothing can + end is said rather than waited for. Timers due together fire by deadline, then by creation. +- **The API is the prelude's** (`prelude.js`, over four natives: `call`, `log`, `random`, + `module`): `req`, `res`, `env`, `test`, `expect`, `console`, the timers, and Postman's `pm` + (request, response, environment, globals, collection variables, variables, iteration data, + cookies, `sendRequest`, `execution`) with its older names (`tests[…]`, `postman.*`, + `responseBody`, `xml2Json`…). `pm.visualizer`, `pm.require` and `pm.vault` have nothing behind + them and say so. - **`expect` is chai's, with Jest's words on the same object** (`toBe`, `toEqual`, `toContain`, - `toMatch`, `toHaveProperty`…, `.not` included) and Postman's response assertions - (`pm.response.to.have.status(200)`, `.be.ok` for a response only). A failure carries what was - expected and what came, written by the prelude (a text quoted, the rest as JSON). -- **`env.set` and `env.secret` write the active environment, the globals with « Aucun »**; a - phase answers what it wrote (`VariableWrite`), the request as changed (`ScriptRequest`, Postman's - shape — `ScriptRequest::onto` writes it back, a method Rust does not send refused by name), its - tests and its failure. -- **`require` is a list compiled in** (`libraries.rs`): lodash, moment, chai, crypto-js, uuid, - Ajv, tv4, xml2js, cheerio (its slim build), csv-parse, and Node's assert, buffer, events, path, - punycode, querystring, stream, string_decoder, timers, url, util as their browser polyfills — - about 1 MB, each evaluated on its first `require`. They are bundled by - `crates/engine/sandbox/build.mjs` from its own `package.json` (not the application's: none of it - reaches the WebView) into `sandbox/dist/`, which is committed with a manifest and the - libraries' licences; `libraries::tests` holds the table to the manifest. Dependabot watches - that folder, and the Script libraries job of `security-npm.yml` audits it and fails when a - rebuild changes `dist/`. Node's modules are - left out of the other bundles, so one copy serves them all. Nothing else is found: `fs`, - `child_process`, `net` answer `MODULE_NOT_FOUND`. -- ⚠️ **The network is this process's, not the script's** (`network.rs`): `pm.sendRequest` and - `pm.cookies.jar()` are calls the host makes and waits for. A send is composed by `compose` - with nothing inherited, sent by `send::alone` with the transport of the request carrying the - script, on the copy of the jar that request's send works on; what it did to the jar joins the - changes merged under the lock afterwards, and it is not written in the history. On a protected - environment nobody confirmed, a send that is not a `GET`, `HEAD` or `OPTIONS` is refused - (`httpScriptProtected`), and the script's `Error` says so. -- ⚠️ **An imported script runs with the user's secrets and the network**: the import review - (#618) lists the scripts a collection carries before anything is written. - -**Around a send** (#493). A request, a folder and a collection each hold `RequestScripts` -(`before`, `after`), sealed with the document or the settings that carry them. `Around::of` -(`around.rs`) lists what one send runs: before it leaves the collection's script, each folder's, -then the request's; once answered, the other way round; a blank one is not run. -`send_http_request` is a `Flight` (`http/flight.rs`; a run's steps in `http/collection_run.rs`), one host for both phases (`session.rs`): - -- What it inherits, the levels it resolves from, the environment and a copy of the jar are read - under the lock; the phase runs on a blocking thread, the lock free. « Annuler » kills the host - (`Sending::watch`) and answers `httpCancelled`. -- What a phase wrote is kept under the lock at once (`keep_writes`: the active environment, - the globals, the collection's variables — a run's data row is none of them) and applied to the - levels in memory, so the send resolves from it. `pm.variables` as the phase before left them - is the nearest level. `ScriptRequest::onto` writes back what the script changed. -- ⚠️ **Rust asks the protected environment's question again after the script**: the front asked - about the method it saw; one the script made a change, unconfirmed, is `httpScriptProtected` - (`method`, `environment`), and the pane asks with « Envoyer quand même », which sends again, - scripts included, with `confirmed`. -- ⚠️ **A file a script asks to send waits for a yes, path by path** (`SendRequest.files`): a - `file` body or a file part the scripts before the send added — compared with what the - request's own rows read, variables resolved before any script — and any file a - `pm.sendRequest` names. Refused, the send answers `httpScriptFile` (`path`) and the pane asks - « Envoyer le fichier », which sends again with that path added to the ones already allowed. - A collection run asks nothing halfway: the step fails. Every file a send reads is capped at - `SENT_FILE_MEGABYTES` (64), checked before it is read (`httpFileTooLarge`). -- A script before the send that fails keeps the request in: `httpScript` carries how - (`failure`), whose script (`level`, `name`, `owner`), the `line` and — for a throw or a syntax - error only — the script's own `message`. `skipRequest()` is `httpScriptSkipped`; a method Rust - does not send, `httpScriptMethod`. Nothing is written in the history: nothing left. -- The phase after runs on an answer only; what stops it is `SentResponse.scripts.failure`, - shown above the answer, which stays. **The tests are a third script** (`RequestScripts.tests`, - #494) run in that phase after the scripts after the answer, request › folder › collection; a - `pm.test` in a script after the answer counts too. `TestResult::placed` names whose test it - is and the line of code that failed, as written; secrets are written as their `{{name}}`, and - the results are kept with the history entry. The response's Tests tab groups them by holder. The console's lines cross once, each secret in force - written as its `{{name}}`; `history::record_of` drops them. `scripts.wrote` makes the front - read the environments and the settings again; a script error does too. -- **An extraction is a rule of the request, not a script** (`RequestDocument.extractions`, - #495): after the scripts and the tests, `extract::extract` reads its path from the JSON body — - `body.access_token`, `body.items[0]`, `body['a key']`, the response explorer's own way of - writing a path from `body` — and the value goes into the active environment, the globals with - « Aucun ». A path that leads nowhere leaves the variable as it was and is said in - `scripts.extracted`. Every variable a send writes, by a rule or by `env.set`, carries - `filled_by` — the request's id and name —, which the environment page shows as « remplie par - Login » and opens. The response explorer's right-click menu and its selection panel offer - « Extraire vers une variable… » on an answer only (`extractable`). -- **The console is events, not an answer** (`http/console.rs`, #497): a `Flight` says each - line as it goes — the request leaving and its answer or failure, a phase's logs and - `pm.sendRequest`s in the order they happened, the tests that failed, what stopped, an - extraction that led nowhere — as `HTTP_CONSOLE_EVENT`, under the send's id, so a script that - stops the send still has its logs shown. Each secret in force is written as its name and an - auth or a cookie header masked (`history::shown`); the phase after is said once the - extractions ran, so a value one makes a secret is hidden in what was logged before. The front - keeps them per tab for the session (`HttpConsoleStore`, 500 lines, never written), folded - under the answer until unfolded; its height is the application's (`httpConsoleShare`). -- **A run is sends, not a history** (`http/runner.rs`, `run_http_collection`, #496): the - requests under a collection or a folder, in the order the page set, one after the other, each a - `Flight` with `record` off — no history entry — and, when the variables are not kept, - `persist` off: what its scripts and extractions write lives in the run's `overlay`, laid over - the levels each next request reads. A data file (`read_data`: a CSV with its header, or a JSON - array of objects) is an iteration a row, the row `pm.iterationData` and the nearest level. - `pm.execution.setNextRequest` goes to the request of that name, `null` ends the run; a skipped - request neither fails nor stops it. Each step is `HTTP_RUN_EVENT` (`Started`, `Ended` with its - `RunResult`, `Finished`); `cancel_http_run` cancels the send under way and the delay. The lock is - taken for the tree and each request read, never across a send. Its console lines are under - `run:#…`, one console for the run. A protected environment is asked once by the page, - counting the requests that could change it; the yes is the run's `confirmed`. -- **The order the page sets is kept with the collection or the folder** (`run_order` in its - `ContainerSettings`, `save_http_run_order` at each move or tick): `http_run_order` answers it - less the requests gone since, then those added since in the tree's order (`runner::run_order`). - The runner reads it on « Exécuter… » and again when the tree changes. The settings dialog does - not hold it: `save_http_settings` keeps the stored one. -- ⚠️ A test's executable is its harness, not the application: `process::host_from` points the - hosts at `CARGO_BIN_EXE_devnotes` (`tests/commands/http_scripts.rs`). - -On screen, the Scripts tab and the settings dialog's section are one `ScriptEditorComponent` -(`http/ui/`), the snippets' code editor rendered without being owned. « Ouvrir le script » -goes through `HttpScriptFocusStore`: the request's own tab, or the settings of the folder or -collection that holds the script (`HttpCollectionsStore.settingsOpen`), on the line that stopped. + `toMatch`, `.not`…) and Postman's response assertions (`pm.response.to.have.status(200)`). +- **`env.set` and `env.secret` write the active environment**, the globals with « None »; a phase + answers what it wrote (`VariableWrite`), the request as changed (`ScriptRequest`, written back by + `ScriptRequest::onto`), its tests and its failure. +- **`require` is a list compiled in** (`libraries.rs`): lodash, moment, chai, crypto-js, uuid, Ajv, + tv4, xml2js, cheerio, csv-parse, and Node's assert, buffer, events, path, punycode, querystring, + stream, string_decoder, timers, url, util as browser polyfills — about 1 MB, each evaluated on its + first `require`. Bundled by `crates/engine/sandbox/build.mjs` from its own `package.json` into the + committed `sandbox/dist/` (with a manifest and the licences, which `libraries::tests` holds); the + security workflow audits it and fails when a rebuild changes it. `fs`, `child_process`, `net` + answer `MODULE_NOT_FOUND`. +- ⚠️ **The network is the application's, not the script's** (`network.rs`): `pm.sendRequest` and + `pm.cookies.jar()` are calls the host makes and waits for, composed with nothing inherited, sent + by `send::alone` with the request's transport, on the jar copy that send works on; not written in + the history. Under a protected environment nobody confirmed, a send that changes something is + refused (`HttpScriptProtected`). +- ⚠️ **An imported script runs with the person's secrets and the network**: the import review lists + the scripts a collection carries before anything is written. + +### Around a send + +A request, a folder and a collection each hold `RequestScripts` (`before`, `after`, `tests`), +sealed with what carries them. `Around::of` (`around.rs`) lists what one send runs: before it, the +collection's, each folder's, then the request's; once answered, the other way round; a blank one is +skipped. A send is a `Flight` (`http/flight.rs`), one host for both phases (`session.rs`): + +- What it inherits, the variables' levels and a copy of the jar are read in a db job; a phase runs on + a blocking thread. « Cancel » kills the host and answers `HttpCancelled`. +- What a phase wrote is kept at once (`keep_writes`: the environment, the globals, the collection's + variables) and laid over the levels in memory, so the send resolves from it. +- ⚠️ **A file a script asks to send waits for a yes, path by path** (`SendRequest.files`): a file + the scripts added, or one `pm.sendRequest` names. Refused, the send answers `HttpScriptFile` and + the pane asks « Send the file ». Every file read is capped at `SENT_FILE_MEGABYTES` (64). +- **A script before the send that fails keeps the request in**: `HttpScript` carries how, whose + script (`level`, `name`), the `line` and — for a throw or a syntax error — the script's message. + `skipRequest()` is `HttpScriptSkipped`. Nothing is written in the history. +- **The phase after runs on an answer only**; what stops it shows above the answer, which stays. + **The tests are a third script** run after the scripts after the answer, request › folder › + collection; each result names its holder and the failing line (`TestResult::placed`), secrets + written as their `{{name}}`, and is kept with the history entry. +- **An extraction is a rule, not a script** (`RequestDocument.extractions`, offered by « Extract to + a variable », `http::extract`): after the tests, `extract::extract` reads a path of the JSON body + (`body.access_token`, `body.items[0]`) into the active environment; a path that leads nowhere + leaves the variable and is said. A variable a send writes carries `filled_by`, which the + environment page shows (« filled by Login »). +- **The console is events** (`http/console.rs`, `EngineEvent::Console`): each line as it goes — the + request leaving, its answer, a phase's logs and sends, the tests that failed, what stopped — under + the send's id, each secret written as its name. The interface keeps them per tab for the session + (`state::http::console`, `LINES_KEPT`, 500), folded under the answer. +- **A run is sends, not a history** (`http/runner.rs`, `run_http_collection`; `http::runner`): the + requests under a collection or a folder in the order set, each a `Flight` with no history entry + and, unless the variables are kept, writing into the run's `overlay`. A data file (CSV, or a JSON + array) is an iteration a row (`pm.iterationData`). `pm.execution.setNextRequest` jumps by name, + `null` ends the run. Each step is `EngineEvent::Run`; `cancel_http_run` cancels the send under way + and the delay. The order is kept with the container (`save_http_run_order`, `http_run_order`). + A protected environment is asked once, counting the requests that could change it. +- ⚠️ A test's executable is its harness, not the application: the engine's tests point the hosts at + the `script-host` binary of `crates/engine/src/bin` (`CARGO_BIN_EXE_script-host`). + +On screen, the Scripts tab of a request and the scripts of a folder or collection are one editor +(`http::scripts`), the snippets' code editor; « Open the script » goes to the request's tab, or to +the container that holds the script, on the line that stopped. diff --git a/docs/architecture/http/requests.md b/docs/architecture/http/requests.md index 50c21324..61768abe 100644 --- a/docs/architecture/http/requests.md +++ b/docs/architecture/http/requests.md @@ -1,475 +1,269 @@ # HTTP: requests and their answers -The HTTP rail, a request in its tab, sending it and reading its answer, the history, GraphQL, WebSocket, the cookie jar, and how collections are stored. [Home](../README.md) +The HTTP area: the rail, a request in its tab, sending it and reading its answer, the history, +GraphQL, WebSocket, the cookie jar, and how collections are stored. [Home](../README.md) -## The HTTP rail - -The third area (`Ctrl+3`, `http/`) opens on the collections of the library: `HttpRailComponent` -in the library rail's frame — its width, its hidden state, the titlebar carrying the switch -while it is hidden — and the open request beside it. ⚠️ Its rows are compact so that the rail's -floor of 160px is enough, not merely allowed: 8px a level (`--indent`), nothing held on a -request's row for a caret it does not have, the long methods in three letters (`shortBadge`: -`DEL`, `OPT`, in the tabs too), and `⋯` drawn over the end of the row on hover or focus -instead of holding its width at rest — the row says when through `--node-menu-opacity`, since -its stylesheet cannot reach into the menu's. The tree is Rust's (`http_tree`); the rail lays it -flat (`railRows`, `core/services/http/http-tree.ts`), each row at its depth, a request after its -method in its colour (`http-method-hues`), `GQL` for GraphQL and `WS` for a WebSocket. +**In short** -- **A row's `⋯` is a component of its own** (`HttpNodeMenuComponent`, `MenuTriggerDirective` as a - host directive), so a row listens to the document only while its menu is open. Creating and - renaming are a field in place; deleting first shows what goes with it, counted by Rust — - and, **counted by the front**, the open tabs it would close with changes not saved - (`requestsUnder` in the tree, `HttpTabsStore.unsavedAmong`): Rust knows what is deleted, - only the front what is typed. One question, one more sentence, read as the question stands. - ⚠️ Its panel is `position: fixed`, measured from the viewport: nothing between it and the - page may carry a `transform`, which would become the box it is measured from — the host is - centred on its row with a flex box for that reason. -- **A name field left keeps what was typed**, as a file explorer does: `focusout` on the form, - for anything outside it, creates or renames; left empty or with the same name, it closes and - writes nothing; Escape cancels. ⚠️ Enter, the form's button and the field left can each arrive - for one name — a field removed while focused loses its focus too — so `settleCreate` and - `settleRename` take the form before they await anything, and act only for the form that is - still the open one. From the field to its own button is not leaving. -- **Two things are begun here, and neither behind a bare « + »**: they were a few pixels - apart, the same glyph at the same size. The rail's head draws what it makes (`folder-plus`) - and names it, « + Collection », once the rail is wide enough to hold it beside the title - (`WORDED_FROM_PX`); an empty rail offers « Nouvelle collection » as a button rather than - pointing at a glyph; and the tab bar ends with « + Nouvelle requête ». -- **A row's menu keeps the three kinds of request behind one entry**, « Nouvelle requête › », - and a submenu beside the panel — the idiom of a card's « Priorité › »: a sibling panel, so - the first one's arrows do not walk into it, opened by the pointer resting on its entry, a - click or `→`, folded by `←` and first on Escape (`MenuTriggerDirective.handleEscape`). - Listed flat they made eight entries of a menu opened to rename something. -- **Moving is pointer events and `Alt` with the arrows**, never HTML5 drag and drop. `↑`/`↓` - within the parent, `→` into the folder above, `←` out of the folder; a drag lands before or - after a row, or inside a folder or a collection when it is let go mid-row. Both turn into one - `RailMove` (`keyMove`, `dropMove`), refused when it would change nothing or put a folder into - itself — Rust refuses that too. The click that ends a drag opens nothing. -- **A move made with the keys is shown and said.** The pointer shows where a drop would land; - the keys showed nothing, and at 8px a level a row above a folder looks like a row inside it. - After each one, `landing` (`http-tree.ts`) reads the tree **as Rust answered it** — never the - move that was asked — and the rail marks the row and what now holds it (`data-moved="row"`, - `"parent"`) for `MARK_MS`, scrolls the row into view, and says where it went in a live - region (`role="status"`, kept in the page so that its change is announced): « … est - maintenant dans Auth », « … à la racine de API », « … avant Login ». A move that cannot be - made is said the same way (`refusal`). ⚠️ The mark is a style the fade comes down to, so it - shows where animations are cut short; and a row moved twice keeps its attribute, so the - tree's `data-beat` swaps the animation's name — the only thing that starts one again. -- **A line a level** is drawn in each row's indent (`.node-row::before`), so depth is read at - rest and not only during a move. -- **What is folded is the library's**, in its preferences (`devnotes.notes.http.collapsed`), and - read the way a file written by hand is read: anything but a list of ids folds nothing. -- Every write is persisted, then the tree read again: a move or a copy renumbers what it touched, - and the front never guesses the order. +- Collections belong to the library; a request's document is sealed whole. +- Rust composes, sends, follows redirects, keeps the cookie jar and reads the answer; a send + **never holds the lock**. +- A tab edits a draft; saving writes it whole. +- The history masks every secret it knows before sealing. +- A WebSocket lives in a task of its own; its traffic comes as events. -## A request in its tab +## The HTTP rail -Opening a request gives it a tab (`HttpTabsStore`, `http/request/`): its method and name, a dot -while modified, a `×`. A tab edits a **draft** — name, method and the request's parts — beside -what Rust holds; modified is the two differing, and saving (`Ctrl+S`) writes the draft whole. A -request made from « Nouvelle requête » is a draft alone, like a new note: it writes nothing until -it is saved, and the first save asks where it goes — and **creates what that place lacks** -(`SaveRequestDialogComponent`): with no collection the place is a name to type, the menu of -places ends with « Nouvelle collection… », and a folder can be named under the place chosen. -⚠️ One write, `create_http_request_in` (`store::create_request_in`, one transaction, every -name checked before it): a request that is refused leaves no empty collection behind it. The -tab takes the place Rust answers, and `HttpCollectionsStore.reveal` unfolds what would hide it. Closing a modified tab asks first. Which requests -were open, and which was in front, is the library's (`devnotes.notes.http.tabs`), reopened at -the next launch without those deleted since. +The third area (`Ctrl+3`) opens on the library's collections: `http::rail`, in the library rail's +frame (its width, its hidden state), beside the open requests. The tree is Rust's (`http_tree`, +requests without their document); `state::http` holds it, and **every write is persisted, then the +tree read again**: a move or a copy renumbers what it touched, and the interface never guesses. + +- **Only the rows in view are drawn**: a library holds thousands of requests. A request's row + shows its method in its hue (`DEL`, `OPT` short), `GQL` for GraphQL and `WS` for a WebSocket; a + line a level marks the depth. +- **A row's ⋯** creates (the three kinds behind « New request › », a sub-menu), renames in place, + copies, deletes. Deleting first says what goes, counted by Rust (`count_http_contents`), and the + open tabs with changes it would close, counted by the interface: only Rust knows what is + deleted, only the interface what is typed. +- **A name field left keeps what was typed**, as a file explorer does; left empty or unchanged it + writes nothing; Escape cancels. Enter, the button and the field left can each arrive for one + name: one write. +- **Moving is a pointer drag or `Alt` with the arrows** (`state::http::moves`): `↑`/`↓` within the + parent, `→` into the folder above, `←` out of the folder; a drop lands before, after or inside. + Rust refuses a folder into itself. ⚠️ **A move made with the keys is shown and said**: the row + and what now holds it are marked for `motion::MARK`, read from the tree **as Rust answered it**, + and a sentence says where it went (« … is now in Auth »). +- **What is folded is the library's** (`notes.http.collapsed`), read as a file written by hand is + read: anything but a list of ids folds nothing. +- The rail's head makes a collection; an empty rail offers « New collection » as a button; the tab + bar ends with « New request ». -⚠️ **A saved request's name and place are the tree's, and a tab follows it.** The rail renames, -moves and deletes in the tree; a tab that kept the name it was opened with showed the old one -after a rename from the rail, and its next save — which writes the draft whole — put it back -over the new one. `HttpTabsStore` follows every tree that is read (an effect on -`HttpCollectionsStore.tree`, once `loaded`, the tabs read untracked): a request gone closes its -tab, one moved inherits from where it now sits, one renamed takes the name in what is saved -_and_ in what is being edited, the rest of the draft untouched. The other way, a save reads the -tree again, since the rail shows the name and the method. Renaming a folder or a collection -bumps `settingsRevision`: its name is in what its requests inherit « from ». +## A request in its tab -- **The query and its table are kept in step by Rust** (`query::sync`, `http/query.rs`): - the side that was edited wins, nothing is decoded — `{{page}}` and `%20` read back as typed — - a disabled row stays in the table and out of the URL, and a description follows its key. The - answer is applied only if nothing was typed meanwhile. -- **The URL is a real input drawn transparent over a copy that lights its `{{variables}}`** - (`UrlFieldComponent`): caret, selection and undo stay the browser's. ⚠️ Both layers carry the - same metrics, declared after `text-field`, whose `all: unset` would otherwise zero the field's - padding and put every glyph a padding off the copy. -- ⚠️ **A request is created as what it is — HTTP, GraphQL, a WebSocket — and stays so.** The two - others were the last entries of the method menu, a kind filed among verbs, and were not - found. The kind is chosen where a request begins: « + Nouvelle requête » at the end of the - tab bar (`NewRequestMenuComponent`, a split button as the notes' « Nouvelle note » is — - HTTP in one click, the three kinds behind its chevron, each with its badge and a line that - says what it is for; ⚠️ in the surface colour, not the amber fill: here that one is - « Envoyer »), a collection's or a folder's menu, the buttons of the empty workspace. `kind` is not in - `HttpRequestPatch`: an update has nothing to change it by, so there is nothing to refuse. The - method menu holds methods and shows on an HTTP request alone; the two others say their kind - in its place, a label. A copy keeps it, and so does a send reopened as a draft - (`HistorySummary::kind`). -- The headers' names are proposed from the HTTP headers reference, those a server alone writes - left out. Settings, scripts and tests join the tabs with their tickets. -- ⚠️ **A header that cannot be sent is refused where it is typed.** Nothing checked a name: key - `X-Recette: 1` in a folder's settings was stored as typed, and every request under the folder - failed « this URL cannot be sent » — the client's builder says so for a header it refuses. - The rule is the model's (`http::model::header_fault`): a name is an HTTP token, a value holds - no line break nor control character, a `{{variable}}` stands for a letter until it is filled, - and a row switched off is not judged. Three places apply it: - - `KeyValueTableComponent` as `headers` asks `model::header_faults` and marks the row, with the - reason under the table; a parameter or a form field takes any character and is asked - nothing. `Nom: valeur` typed in a name is split by `model::headers_from_text` — what follows the - first colon goes to the value when there is none, and the caret with it — and several lines - pasted there fill a row each (the field alone would take them on one line). ⚠️ Every change - starts from `latest`, what the table last emitted, not from its `rows` input: the input - only follows at the next change detection, and a value typed right after the split — or an - answer from Rust arriving before the screen — started from a row already replaced and put - the colon back in the name; - - `save_http_settings` refuses it: stored, it failed requests one by one. A request's own - rows are saved as typed — a tab is a draft, and it shows the mark; - - `compose` checks every header before the client builds it and answers `SendError::Header`, - with who wrote it: its own code (`httpHeaderName`, `httpHeaderValue`), the sentence picked - by `source` as for a timeout — « L'en-tête « X-Recette: 1 », hérité du dossier « Recette » ». +Opening a request gives it a tab (`http::tabs`, `state::http::tabs`): its method and name, a dot +while modified, a ×. Tabs are dragged along the strip, or moved by `Alt` and an arrow. + +- **A tab edits a draft** beside what Rust holds; modified is the two differing, and saving + (`Ctrl+S`) writes the draft whole. A request begun from « New request » is a draft alone, like a + new note: the first save asks where it goes (`http::save_request`) and **creates what that place + lacks** — a collection, a folder — in one write (`create_http_request_in`, every name checked + before), so a refusal leaves no empty collection behind. +- **Closing a tab with changes asks first** (`http::close`). The tabs left open, and the one in + front, are the library's (`notes.http.tabs`), reopened at the next launch. +- ⚠️ **A saved request's name and place are the tree's, and a tab follows it.** The rail renames, + moves and deletes in the tree; a tab follows each tree read — a request gone closes its tab, one + renamed takes the name in what is saved and in what is edited. A tab that kept the name it was + opened with would write the old one back at its next save. +- **A request is created as what it is — HTTP, GraphQL, a WebSocket — and stays so**: `kind` is + not in `HttpRequestPatch`. The method menu shows on an HTTP request alone. +- **The query and its table are kept in step by Rust** (`http::query::sync`): the side edited + wins, nothing is decoded (`{{page}}` and `%20` read back as typed), a disabled row stays in the + table and out of the URL. An answer is applied only if nothing was typed meanwhile. +- **The URL lights its `{{variables}}`** (`http::request::url`), and the variables a request uses + are listed beside it. +- ⚠️ **A header that cannot be sent is refused where it is typed.** The rule is the model's + (`http::model::header_fault`): a name is an HTTP token, a value holds no line break nor control + character, a `{{variable}}` stands for a letter until filled, a row switched off is not judged. + Three places apply it: the headers' table marks the row (`header_faults`; `Name: value` typed + in a name is split by `headers_from_text`, several lines pasted fill a row each); + `save_http_settings` refuses it; `compose` checks every header before sending and answers + `SendError::Header` with who wrote it (« the header X-Recette: 1, inherited from the folder + Recette »). - **A body is a kind and its content** — none, JSON, text, a form, multipart, a file. A file is a - **path**, read by Rust when the request is sent: its bytes never enter the library. - `describe_http_body` answers the `Content-Type` the body implies and, for JSON, why it does - not read (the JSON explorer's own parser and words). Prettier formats it, as it does a snippet. -- **A body is sent whatever the method, and a `GET` that carries one says so.** A `POST` switched - to `GET` keeps its body and sends it — some APIs do read one — and nothing said it. - `describe_http_body` is asked with the method and answers `unusual` - (`RequestBody::is_unusual_on`: a `GET` or a `HEAD`, and something that leaves — a kind chosen - and left empty is no body; `DELETE` and `OPTIONS` do not warn): the rule is Rust's, the editor - keeps no list of methods. It shows as a line above the body, with « Passer à Aucun », and as a - mark on the « Corps » tab — the method changes while another tab is in front. -- **Choosing another kind of body empties none** (`HttpTabsStore.chooseBodyKind`): the one left - is set aside by tab and comes back as it was — « Passer à Aucun » would otherwise cost the - text it warns about. A text is kept under JSON and plain alike, so it still travels between - the two. For as long as the tab is open, never written: a request saves the body it shows. -- **What leaves without a row of its own is listed above the headers' table, and the list is - Rust's** (`implied_http_headers` → `send::implied`): the body's `Content-Type`, the headers - handed down with where from, the application's `User-Agent` and `Accept` « par défaut », the - `Host` « d'après l'URL ». It is read from the very function `compose` writes the headers with - (`written`, each header with who wrote it), so the list cannot say something a send does not - do — it once was decided in the editor, from the body alone. Asked again when the kind, the - URL, a header, the auth, the body's kind or the place changes, not at each key of the body; - the last answer stays on screen while the next is read (`RequestEditorComponent.lastOf`, a - `linkedSignal` by tab, which the body's answer goes through too), or the table under it would - jump. The auth's own header is not in it: its tab says it, and it is a secret. -- **An auth is inherited by default.** A collection and a folder carry settings of their own — - an auth and headers, sealed like a request's document — and `inherited_http_settings` resolves - what a request at a place gets: the nearest auth set, every header above, a folder's overriding - its collection's by name, each with **where it comes from**. Saving settings moves - `HttpCollectionsStore.settingsRevision`, so an open tab reads it again. The secret half of an - auth is masked until asked for, and in a summary unless it is a `{{variable}}`. + **path**, read by Rust at send (`SENT_FILE_MEGABYTES`, 64): its bytes never enter the library. + `describe_http_body` answers the `Content-Type` it implies and, for JSON, why it does not read; + Prettier formats it. Choosing another kind empties none: the one left comes back as it was, + for as long as the tab is open. +- **A `GET` that carries a body says so**: `describe_http_body` is asked with the method and + answers `unusual` (`RequestBody::is_unusual_on`), shown above the body with « Switch to None » + and as a mark on the Body tab. +- **What leaves without a row of its own is listed above the headers, and the list is Rust's** + (`implied_http_headers` → `send::implied`): the body's `Content-Type`, the headers handed down + and from where, the application's `User-Agent` and `Accept`, the `Host`. It is read from the + function that writes the headers (`written`), so it cannot say something a send does not do. The + auth's header is not in it: it is a secret. +- **An auth is inherited by default.** A collection and a folder carry settings of their own (an + auth, headers, transport, scripts), sealed; `inherited_http_settings` resolves what a request + gets — the nearest auth set, every header above (a folder's overriding its collection's by name), + each with **where it comes from**. The secret half of an auth is masked until asked for. ## Sending a request, and its answer -**Rust sends; the WebView never will** — `connect-src` allows the IPC and nothing else. -`send_http_request` (`http/send.rs`) reads what the request inherits under the lock, reads its -files outside it, and sends with `reqwest` on rustls (the `ring` provider the updater already -brings, the system's roots through the platform verifier): ⚠️ **a send never holds the lock**, -or a 30-second request would stall every command. +`send_http_request` (`http/send.rs`) reads what the request inherits in a db job, reads its files +outside it, and sends with `reqwest` on rustls (the platform's verifier, the system's roots). +⚠️ **A send never holds the lock**, or a 30-second request would stall every other call +(→ "The concurrency rules"). -- **The height is shared between a request and what answers it, from the line between them** - (`SplitHandleComponent`, `shared/layout/split-handle/`): a separator that takes the focus — - pointer events, the arrows, `Home`/`End` to either floor — which measures its parent and - the pane before it, and emits a share it does not keep. The share is the area's, not a - tab's (`AppSettings.httpRequestShare`, a percentage; the WebSocket log has the same line): - `0` is « automatic », the request taking what it holds up to 60% as it always did, and it is - where a double-click or Enter puts the line back. ⚠️ Each side has a floor — the request line - and its tabs, the status line and a few lines of body — written twice: `floors` in - `HttpPageComponent` for the line, `min-height` in the stylesheets for a window that shrinks. -- **« Effacer » clears the pane, not the record**: `HttpSendStore.forget`, what closing the tab - does — the state goes, Rust lets go of the body it kept, and the history keeps the send. A - failure and a cancelled send stay on screen as an answer does, and are put away the same way. -- **A status is drawn to be read as a signal**: `@mixin status-badge`, twice the fill of a - tint, a ring in the hue, the text at full strength — `palette.test.mjs` holds that text to - 4.5:1 on the four fills in both themes — and `data-family` (`2xx`…`5xx`) says it to what - cannot read a colour. - **What leaves is composed first** (`compose`, tested without a network): the inherited headers, its own over them by name, the auth — Basic, Bearer, a key in a header or the query — unless an - `Authorization` is typed, the body and the `Content-Type` it implies. A URL without a scheme is - sent over `http://`. A `{{variable}}` no level sets stops it, by name (→ "Variables, and where - each resolves from"). -- **A request names the application**: `User-Agent: DevNotes/` (`send::USER_AGENT`, the - version read from `Cargo.toml`) unless a `User-Agent` row is written — `reqwest` adds none, and - many APIs answer 403 to a request without. An enabled row, the request's own or one handed - down, replaces it; a row **switched off**, in the request or at any level above - (`Inherited::user_agent_off`), sends none at all — though never at the expense of one a level - sets, which leaves like any inherited header. `Accept: */*` is written the same way, though - the client would add it by itself, so that the history and the timeline show it as sent. A - WebSocket's handshake is composed by the same function and carries both. -- ⚠️ **The redirects are followed by `send`, one request a hop, not by the client** - (`Policy::none()`). `reqwest` has no jar: followed by it, a cookie set on a 302 — nearly every - login — was neither kept nor sent to the page it leads to, the jar being filled from the last - answer's headers alone. Each hop's `Set-Cookie` goes through the jar's rules as it arrives - (`cookies::received`, then `cookies::apply` on the copy the command read under the lock), - and each hop is sent the line the jar gives **for its own URL** (`Hop::cookie`); what the - hops did to the jar comes back beside the answer (`Sending::run`) and is merged under the - lock afterwards, even when the chain ended on a failure. What the client did is kept in - `Hop::after`, tested one rule a line: a 301, 302 or 303 becomes a `GET` without its body, a - 307 or 308 sends both again; another host or port gets neither `Authorization` nor a typed - `Cookie`; a `Location` is read against the URL that answered; a `Referer` names the page - left, never from `https` to `http`. The delay is the whole chain's (each hop is given what is - left of it), « Redirections au plus » is counted here, and a cancel aborts the task between - two hops as anywhere. `Redirect` carries where it came from and what it set, `Cookie::from` - the hop that set it: the « Cookies » tab says « Posé par », the timeline shows the - `Set-Cookie` under its redirect. + `Authorization` is typed, the body and its `Content-Type`. A URL without a scheme goes over + `http://`. A `{{variable}}` no level sets stops it, by name (→ "Variables, and where each + resolves from"). +- **A request names the application**: `User-Agent: /` (`send::USER_AGENT`) unless + a row writes one; many APIs answer 403 without. A row **switched off**, in the request or above + (`Inherited::user_agent_off`), sends none. `Accept: */*` is written the same way, so the history + shows it as sent. +- ⚠️ **Redirects are followed by `send`, one request a hop**, not by the client (`Policy::none()`): + `reqwest` has no jar, so a cookie set on a 302 — nearly every login — would be lost. Each hop's + `Set-Cookie` goes through the jar's rules as it arrives (`cookies::received`, `cookies::apply` + on the copy read in the job), and each hop is sent the line the jar gives **for its own URL**. + `Hop::after` holds what a browser does, one rule a test: 301/302/303 become a `GET` without a + body, 307/308 send both again; another host or port gets no `Authorization` nor typed `Cookie`; a + `Referer` never goes from `https` to `http`. The delay is the whole chain's. - **A failure is a code** — the variable, the URL, the name not resolving, refused, TLS, timeout, - too many redirects, an unreadable file, cancelled — read off reqwest's error and the chain - under it. ⚠️ `io::Error::source` skips the error it wraps, where rustls puts its own: the - walk follows `get_ref`. -- **A timeout and a redirect too many carry the value in force, and who set it** - (`transport::Limit`): no number is written in a translation, which used to state the - defaults whatever the request was sent with. The delay crosses as `amount` and `unit`, the - largest SI unit that says it whole (`readable_delay`); the redirects as `count`, a plural. - `source` — `request`, `folder`, `collection` or `default` — picks the sentence - (`errorKeyOf`: the sub-key `errors.httpTimeout.`) and `name` is the folder or the - collection: the Réglages tab shows an inherited value greyed, and its cause is one level up. - The history keeps those values beside the code (`HistorySummary::failure_params`). -- **A send runs as a task of its own, under an id the front chose** (`HttpSendStore`: the tab's - key and a counter), which `cancel_http_send` aborts. The answer's text crosses up to 1 MB; the - bytes, up to 64 MB, stay in Rust under that id, for **Enregistrer dans un fichier** - (`save_http_response`, staged then renamed), until the tab closes or sends again. -- **`Ctrl+Enter` sends the tab in front**, and **Envoyer** becomes **Annuler** while it waits. - Below the request, `ResponsePaneComponent` shows the status coloured by its class, the time, - the size, and the answer in four tabs — or why there is none. -- **A request on its way says so in three places**: a spinner and the time elapsed in the pane, - a spinner in **Annuler**, and one on its tab. A still sentence made a slow server and a frozen - window look the same. The count starts at `SendState.startedAt`, the store's and not the - pane's, so coming back to the tab does not restart it; it ticks only while a send is under - way, and is `aria-hidden` in a pane that is a live region. - -**Reading the answer is Rust's too** (`http/response.rs`). The body's language comes from its -`Content-Type` (or, without one, from reading as JSON); the cookies are the `Set-Cookie` -headers parsed; the exchange is the request as composed. JSON is laid out by **re-indenting its -tokens**, never by re-serialising: `serde_json` would round `12345678901234567890` and write -`1.10` as `1.1`. - -- **Corps**: formatted (coloured by the shared `CodeViewerComponent`, plain past 256 KB), raw, - and for JSON the visualiser's graph and tree — the explorer's store provided by - `ResponseBodyComponent`, explored only once asked. An image comes back from Rust as a - `data:` URI (`http_response_image`, 10 MB at most), which the CSP's `img-src` allows. -- **En-têtes**, **Cookies** with their counts, and **Chronologie**: the redirects, then the - request as it left and the response as it came, as text. Not a DNS, connect and TLS - breakdown: reqwest measures none. -- **Copier** copies the body as it came; **Enregistrer comme note** opens the tools' dialog with a - snippet in the body's language, laid out. - -The view of an answer is `ResponseViewComponent` (`http/ui/`): the response pane draws it for a -tab's last send, the history for an entry. - -**A GraphQL request says what it can before it is sent, and its errors when it is answered.** -One pass over the query (`graphql::scan`, past strings, block strings and comments) reads its -operations with the variables each declares, and the first brace, parenthesis or string that -does not pair, by line and column. `describe_graphql` answers it with each keystroke: - -- ⚠️ **Above each box, not under it**: the editor is taller than what the response pane leaves - of the window, and a line under a box was out of sight — the very thing being fixed. The two - boxes share one grid, what is said of each in a row of its own that keeps two lines whether - or not something is said: a line that comes and goes with each brace typed would push the - text being typed. -- **For the query**, the sign at fault and where. It warns and stops nothing — the server - stays the judge of the schema; only « Formater » waits for a query that pairs. -- **For the variables**, what they are (« Un objet JSON : une valeur pour chaque `$variable` - de la requête »), why they do not read, and how they compare with the operation sent — the - one named, else the first: « Sans valeur » for a variable declared without a default and - given none, with « Ajouter » (`add_graphql_variables` writes a `null` for each at the end of - the object **as typed**, its numbers untouched), and the keys the operation does not declare. -- « Formater » on both boxes is Prettier's, as for a snippet. -- **An answer that is errors and no data opens on « Erreurs »** (`ResponseViewComponent.chosen`, - a `linkedSignal` on the answer): on « Corps » it read `null`, the errors in a tab nothing - pointed to. With data it opens on the body, the tab's count in red. A badge beside the status - counts the errors whatever the status: a 200 that carries some is no success. + too many redirects, an unreadable file, cancelled — read off reqwest's error and its chain of + causes (`send::cause_of`). ⚠️ `io::Error::source` skips the error it wraps, where rustls puts its + own: the walk follows `get_ref`. A timeout and a redirect too many carry the value in force and + who set it (`transport::Limit`: request, folder, collection or default), so the sentence names + the level to change. +- **A send runs as a task, under an id the interface chose** (`state::http::send`), which + `cancel_http_send` aborts. The answer's text crosses up to 1 MB (`SHOWN_LIMIT`); the bytes, up to + 64 MB (`KEPT_LIMIT`), stay in Rust under that id for « Save to a file » (`save_http_response`, + staged then renamed), until the tab closes or sends again. +- **`Ctrl+Enter` sends the tab in front**, and Send becomes Cancel. A send on its way shows a + spinner and the time elapsed, counted from the send's start, not from when the tab was shown. +- **The height is shared between the request and its answer** from the line between them + (`widgets::split_handle`: a drag, the arrows, Home/End; `httpRequestShare`, the area's, 0 for + automatic). + +**Reading the answer is Rust's too** (`http/response.rs`, drawn by `http::response`): the body's +language comes from its `Content-Type`; the cookies are the `Set-Cookie` headers parsed; the +exchange is the request as composed. JSON is laid out by **re-indenting its tokens**, never by +re-serialising: `serde_json` would round `12345678901234567890` and write `1.10` as `1.1`. + +| Tab | Shows | +| ------------- | ------------------------------------------------------------------------------------------- | +| Body | formatted (coloured, plain past 256 KB), raw, and for JSON the visualiser's graph and tree; an image from Rust (`http_response_image`, 10 MB at most) | +| Headers | as received, with their count | +| Cookies | what the answer set, and by which hop | +| Timeline | the redirects, then the request as it left and the response as it came; no DNS or TLS timings (reqwest measures none) | +| Errors | a GraphQL answer's errors, with their path and location | + +The status is drawn by family (`2xx`…`5xx`), at a contrast held by the theme's test. « Copy » +copies the body as it came; « Save as a note » makes a snippet in the body's language. « Clear » +clears the pane, not the history. ## The history of what was sent -**Every send that left is written** (`http_history`, migration 15), after the answer and under -the lock again; a request refused before leaving — a `{{variable}}`, a bad URL — and a cancelled -one are not. A failed send is kept with its code. The write never costs the answer: a failure -is logged. +**Every send that left is written** (`http_history`), after the answer, in a job; a request refused +before leaving, or cancelled, is not. The write never costs the answer: a failure is logged, and +the interface is told (`SendNotKept`). - **Sealed, in two parts**: the summary a list shows (name, URL, method, status, time, size, - failure) and the record an entry opens (the exchange, and the answer with its body cut to - 256 KB). Only the instant and the request it came from stay in the clear, for the order and - the retention; `request_id` is `ON DELETE SET NULL`. ⚠️ The method and the status were - columns of their own until migration 17, which drops them. SQL holds no key to move them - under: an entry recorded before it reads as a `GET` with no status until the retention lets - go of it — thirty days at most, on an application nobody runs yet. -- ⚠️ **Secrets are masked before they are sealed**, on both sides of the exchange. Sent - (`history::mask`): `Authorization` keeps its scheme (`Bearer ••••••••`), - `Proxy-Authorization` and `Cookie` lose their value, so does the API key, by the name - `compose` hands on (`Outgoing::secrets`), in a header or the query, and the password of a - URL's user (`https://ada:••••••••@host`). Answered (`masked_answer`): a `Set-Cookie` keeps its - name and its attributes, a cookie its name, and every URL the answer names again — where it - came from, a `Location`, each hop of the redirects — is masked like the one sent. What an - answer sets is what the next request sends: kept whole, it was the `Cookie` the other side - masks. The live timeline shows what really left; only the history masks. -- **A secret variable shows by its name once the request left** (#487): `Outgoing.secret_values` - holds the values of the secrets in force (`Resolver::secrets`), and `send::exchange` — the - live timeline — writes each as its `{{name}}`, as typed and as a query encodes it - (`variables::hide`). `history::record_of` does it again over the request and over the whole - answer — its URL, headers, body, layout, redirects and GraphQL errors — so a server echoing a - token keeps none in the history. A value under three characters is not looked for. The entry - also keeps the environment it left with, its name and colour then (`HistorySummary::environment`, - sealed with the rest), shown on its row. « Rouvrir » puts the `{{name}}` back, which resolves - again. -- **What the request sent as a secret is masked where the answer says it back**: the token of - its auth (and the whole header), each cookie value, the API key (`history::sent_secrets`). An - echo service answering `Authorization: Bearer …` keeps `••••••••` in the history. A note made - of an answer goes through the same (`http_response_note`: the answer kept under the send's id - for its secret variables, its exchange for the rest) and says so; the answer shown is left as it came. -- ⚠️ **The limit of the mask**: it knows the secrets a request _declares_. A token typed by - hand as a parameter or in a body, or one a server answers in its body, is kept as it is — - sealed like the rest of the record, and shown to whoever opens the entry. A test a secret - in `http/history.rs`, and one that asserts this limit rather than leaving it to be found. -- **Kept 30 days and 500 entries**, purged as each is written and at launch - (`history::sweep_at_startup`). « Vider l'historique » asks Rust how many it removes first. -- **A row ends on what tells it from the next.** Fourteen sends to one host read alike, each - URL cut at its end. Rust answers the URL in two parts (`history::url_parts`: the host, then - the path and the query) and the row lets the first give way, the second stay; the whole URL - is the row's `title`. The list is `RailFrameComponent` again — dragged from its edge or moved - with the arrows, its width an application setting (`historyListWidth`). -- **One send is deleted without being asked, and put back from the bar that follows** - (`delete_http_history_entry` answers the entry whole, `restore_http_history_entry` writes it - back under its id and at its instant): no trash and no column for it — what is handed back - is what the front could read anyway. The offer lasts as long as a note's. « Vider - l'historique » keeps its confirmation. -- ⚠️ **« Rouvrir » puts a send back onto the request it came from** (`http_history_onto_request` - → `history::onto`), in that request's **own tab**, as changes not saved: it used to open a - stranger, a draft with no tie to it. What was sent — method, URL, parameters, headers, body, - or a GraphQL send read back into its query and variables — goes over what the request holds, - which keeps its auth, its settings and **every secret**: a header the record holds masked - takes the request's own row of that name back, never the dots as a value, and one handed - down today with the value that was sent is no change of the request's. A tab already open - with changes of its own is asked about first. The request gone, or the send made from a - draft, it is a draft named after the send and its time; the button says which it will be. -- **Listed by local day** (`by_day`, the offset the notes send), newest first. A draft - asks Rust for the request rebuilt (`http_history_draft`): the masked values left - out, and what is written again by itself — the implied `Content-Type`, the application's own - `User-Agent` and `Accept` (`send::is_default`), which as rows would name this version for - ever — the parameters read off the URL: a new draft tab, to send again or save into a - collection. -- The history replaces the workspace while open (`HttpHistoryStore.isOpen`, from the rail's - foot), and closes for a request opened from the tree. It reads again whenever a send ends - (`HttpSendStore.sent`). + failure, environment) and the record an entry opens (the exchange, the answer cut to 256 KB). + Only the instant and the request id stay plain (`ON DELETE SET NULL`). +- ⚠️ **Secrets are masked before they are sealed**, both ways. Sent (`history::mask`): + `Authorization` keeps its scheme (`Bearer ••••••••`), `Proxy-Authorization` and `Cookie` lose + their value, an API key by the name `compose` hands on, a URL's password. Answered + (`masked_answer`): a `Set-Cookie` keeps its name and attributes, every URL the answer names is + masked like the one sent. +- **A secret variable shows by its name** (`Outgoing.secret_values`, `variables::hide`): the live + timeline and the history write each secret's value as its `{{name}}`, over the request and the + whole answer, so a server echoing a token keeps none. A value under three characters is not + looked for. « Reopen » puts the `{{name}}` back, which resolves again. +- **What the request sent as a secret is masked where the answer says it back** + (`history::sent_secrets`); a note made of an answer goes through the same + (`http_response_note`). +- ⚠️ **The limit of the mask**: it knows the secrets a request **declares**. A token typed by hand + in a body, or answered in a body, is kept as it is — sealed, and shown to whoever opens the entry. + A test asserts that limit. +- **Kept 30 days and 500 entries** (`RETENTION_DAYS`, `KEPT_AT_MOST`), purged at each write and at + unlock (`history::sweep_at_startup`). « Clear the history » asks Rust how many it removes first. +- **One send is deleted without being asked** and put back from the undo bar + (`delete_http_history_entry` answers it whole, `restore_http_history_entry` writes it back under + its id and instant). +- ⚠️ **« Reopen » puts a send back onto the request it came from** (`http_history_onto_request` → + `history::onto`), in its own tab, as changes not saved: method, URL, parameters, headers, body, + over what the request holds, which keeps its auth, its settings and **every secret** (a header + held masked takes the request's own row back, never the dots). The request gone, it is a draft + named after the send (`http_history_draft`, without what is written again by itself: + `send::is_default`). +- **Listed by local day** (`by_day`), newest first; a row shows the host, then the path that tells + it from the next (`history::url_parts`). The list's width is a setting (`httpHistoryListWidth`). The + history replaces the workspace while open (`http::history`, `state::http::history`), and reads + again whenever a send ends. ## A GraphQL request **A GraphQL request is an HTTP one whose body Rust writes** (`http/graphql.rs`). Its document -carries a `graphql` part — the query, the variables as typed, the operation chosen, and whether -it goes as a GET — read only when the request's kind is `graphql`; `kind` now crosses in the -patch, chosen from the method menu (« GraphQL » beside the methods). - -- **Sent as a POST with a JSON body**, or as a GET with `query`, `variables` and - `operationName` in the query string. ⚠️ The variables are copied into the body as typed - (`RawValue`), never re-serialised: a number past `f64` would come out rounded. They must be - a JSON object, or the send fails with `httpGraphqlVariables`. -- **`describe_graphql` reads the document**: its named operations, past strings, comments and - selections — a menu appears when there are several — and why the variables do not parse. -- **The answer is read apart** (`SentResponse::graphql`): **Corps** lays out `data`, an - **Erreurs** tab lists the errors with their path and location; **Brut** keeps the whole - answer. -- `{{variables}}` in the query and the variables resolve like anywhere else, and stop the send - when nothing sets them. Introspection and completion from the schema are out of scope. +carries the query, the variables as typed, the operation chosen, and whether it goes as a GET. + +- **Sent as a POST with a JSON body**, or as a GET with `query`, `variables` and `operationName` in + the query string. ⚠️ The variables are copied as typed (`RawValue`), never re-serialised: a number + past `f64` would be rounded. Not a JSON object, the send fails (`HttpGraphqlVariables`). +- **It says what it can before it is sent** (`describe_graphql`, at each keystroke, one pass of + `graphql::scan` past strings, block strings and comments): its operations and the variables each + declares, the first sign that does not pair, by line and column — **above** each box, on a line + kept whether or not something is said, so the text typed never jumps. It warns and stops nothing. + For the variables: what they are, why they do not read, those declared without a value + (« Add » writes a `null` for each, `add_graphql_variables`, the object kept as typed), and the + keys no operation declares. +- **An answer of errors and no data opens on « Errors »**; with data, on the body, the tab's count + in red. A badge counts the errors whatever the status: a 200 that carries some is no success. +- Introspection and completion from a schema are out of scope. ## A WebSocket -**The socket lives in Rust** (`http/websocket.rs`, `tokio-tungstenite` on rustls with the same -platform verifier as reqwest), a task a socket, under an id the front chose -(`HttpSocketsStore`: the tab's key and a counter). The document carries a `websocket` part — -the subprotocols asked for, and the messages kept to send again. - -- **Connecting reuses `compose`**: the URL is read as `http(s)` and sent back on `ws(s)`, so the - headers inherited, the auth and the `{{variable}}` check are a request's. `connect_websocket` - answers once the handshake did; a refusal crosses as `httpWebsocketRefused` with its - `status`, the rest as a send's codes. -- **A socket opens on `ws://` or `wss://`, or on a bare host** (`websocket::socket_url`): any - other scheme is refused before anything is tried (`httpWebsocketScheme`). `https://` used - to be dialled as `wss://` without a word; it is now said, with its twin on a socket's scheme - (`twin`) a click away in the log. -- ⚠️ **A failure is read by one function for a request and for a socket** (`send::cause_of`, - the chain of causes walked whoever built it): a host that does not resolve read « Erreur - réseau » from a socket and « Le nom d'hôte ne se résout pas » from a request. By its code - before its words — Windows words its errors in the system's language, and « Hôte inconnu » - matches no wording (`WSAHOST_NOT_FOUND` and its three neighbours). When « network » is all - that can be said, the last cause's own words cross as `cause` and are shown after the - sentence, for a request too. -- **`Ctrl+Entrée` in the message sends the message** (`WebsocketComposerComponent`, which stops - the key: the page answers it by connecting, whatever holds the focus). On a socket that is - not open it says « Connectez le WebSocket pour envoyer » and connects nothing; Enter alone - stays a new line. -- **Closing the tab of a socket that is open or opening asks first** - (`HttpSocketsStore.isLive`, `CloseRequestDialogComponent`): one dialog, which says the - unsaved changes too when there are some, never two in a row. -- **What follows comes as events, on one topic** (`WEBSOCKET_EVENT`, its payload generated, like - `GlobalAction`): opened (with the subprotocol taken), sent, received (cut at 64 KB, a binary - message only sized), closed, failed. The front listens through `WEBSOCKET_SUBSCRIBER`, a - token a spec replaces to play events. -- **Writing goes through a channel** to the task, which writes and says so (`sent`) only once - the frame left. A close asked for ends the task after 3 s whatever the server answers, and - a server cutting it short still reads as closed. -- ⚠️ **Closing the tab closes the socket, and switching library closes them all** - (`open_library` calls `Sockets::close_all`): the page reloads, but the tasks are Rust's. -- The lower half is a **log** (`SocketLogComponent`): each event's time, direction and size, - filterable, the newest 500 kept. +**The socket lives in Rust** (`http/websocket.rs`, `tokio-tungstenite` on rustls), a task a socket, +under an id the interface chose (`state::http::sockets`). The document carries the subprotocols +asked for and the messages kept to send again. + +- **Connecting reuses `compose`**: the inherited headers, the auth and the `{{variable}}` check are + a request's. A refusal is `HttpWebsocketRefused` with its status. +- **It opens on `ws://`, `wss://` or a bare host** (`websocket::socket_url`); any other scheme is + refused before anything is tried (`HttpWebsocketScheme`), with its `twin` on a socket's scheme a + click away in the log. +- ⚠️ **A failure is read by one function for a request and a socket** (`send::cause_of`), by its + code before its words: Windows words its errors in the system's language. +- **`Ctrl+Enter` in the message sends it**; on a socket that is not open it says so and connects + nothing. Enter alone is a new line. +- **What follows comes as events** (`EngineEvent::Socket`): opened (with the subprotocol taken), + sent (once the frame left), received (cut at 64 KB; a binary message only sized), closed, failed. + A close asked for ends the task after 3 s whatever the server answers. +- ⚠️ **Closing the tab closes the socket; opening another library closes them all** + (`Sockets::close_all`). Closing a live socket's tab asks first, in the same question as unsaved + changes. +- The lower half is the **log** (`http::socket_log`): each event's time, direction and size, + filterable, only the rows in view drawn, the newest 500 kept. ## How a request travels, and the cookie jar -**Transport settings inherit field by field** (`http/transport.rs`): a collection, its folders -and the request each hold a `TransportSettings` whose fields are optional, and -`transport::resolve` lays them over `Transport::default()` (crossing as `DEFAULT_TRANSPORT`) -from the collection down. `compose` resolves them, and `send` reads them: the timeout (never -under 100 ms) is the whole chain's, redirects are followed or not and how many, TLS is verified -or not, the jar is used or not. The Réglages tab (`TransportEditorComponent`) shows beside each unset field -what it takes from above. `settings::inherit` also answers which level set the timeout and the -redirects (`Inherited::limits`, kept off the wire), for the failure that names it. A -WebSocket's handshake waits the same timeout. +**Transport settings inherit field by field** (`http/transport.rs`): a collection, its folders and +the request each hold a `TransportSettings` of optional fields, which `transport::resolve` lays +over `Transport::default()` from the collection down — the timeout (never under 100 ms, the whole +chain's), redirects followed or not and how many, TLS verified or not, the jar used or not. The +Settings tab shows beside each unset field what it takes from above. `Inherited::limits` says +which level set the timeout and the redirects, for the failure that names it. **The jar is the library's, sealed whole** (`http_cookies`, `http/cookies.rs`): the domain is -sealed with the rest — which sites one talks to is not for the file to say — so matching -(domain, path, `Secure`, expiry) runs in Rust over the jar read entire, and only `expires_at` -stays clear for the purge. The jar is read under the lock before the send, handed to it as a -copy the hops read and fill (→ "Sending a request, and its answer"), and what they did to it is -written with the history after it; a `Cookie` header typed by hand wins over the jar, for the -host it was typed for. - -- **A `Domain` is refused where a browser refuses it** (#705): another site's, a public suffix - (`co.uk`, `github.io`, a bare top-level domain — the `psl` crate, its list compiled in, about - 0.7 MB of the binary), and any domain above an IP address, which has none. The host itself, - named, is a host-only cookie, as without the attribute. -- **Of two paths of one length, the older cookie is sent first** (RFC 6265, 5.4): `JarCookie::created`, - sealed with the rest — nothing in SQL orders on it —, set by an answer a microsecond apart a - line, and kept by a cookie that replaces it. The jar is read in id order, a random UUID, which - decided it before. -- **`Expires` is read as RFC 6265, 5.1.1 reads it** (`cookie_date`): tokens, the first time, day, - month and year found, a two-digit year taken to 1970–2069 — RFC 1123, RFC 850, asctime and - what servers write between. One that does not read lasts the session. -- **Reading the whole jar under the lock was measured, not optimised**: 0.48 ms at 500 cookies - (`cookie jar` in `benches/commands.rs`), a third of an `update_note`. A keyed hash of the domain - in the clear, to read only the candidates, waits for a jar that makes it show. - -The manager -(`CookieJarDialogComponent`, from the rail's foot) lists by domain and deletes one, a domain's -or all, the count asked of Rust first. +sealed too — which sites one talks to is not for the file to say — so matching (domain, path, +`Secure`, expiry) runs in Rust over the jar read whole, and only `expires_at` stays plain for the +purge. A `Cookie` header typed by hand wins over the jar for its host. + +- **A `Domain` is refused where a browser refuses it**: another site's, a public suffix (the `psl` + crate, its list compiled in), any domain above an IP address. +- **Of two paths of one length, the older cookie is sent first** (RFC 6265 § 5.4, + `JarCookie::created`, sealed with the rest). +- **`Expires` is read as RFC 6265 § 5.1.1 reads it** (`cookie_date`); one that does not read lasts + the session. +- **Reading the whole jar was measured**: 0.48 ms at 500 cookies (`benches/commands.rs`), a third of + an `update_note`. +- **The manager** (`http::cookie_jar`, from the rail's foot) lists by domain and deletes one, a + domain's or all, the count asked of Rust first. ## HTTP collections in the library -The HTTP client's requests live in collections that belong to the **library**, not to a space -(`http/`, migration `000014`): `http_collections`, `http_folders` nested by `parent_id`, and -`http_requests` in a collection and possibly a folder. Sealed: every name, a request's -**document** — its URL and, ticket by ticket, its parameters, headers, body, auth and settings — -and a collection's or folder's **settings**, what its requests inherit. Each is one JSON document -whose every field is `#[serde(default)]`, so a part added later needs no migration. In the clear: -ids, parents, positions, the request's kind (`http`, `graphql`, `websocket`) and method, instants. - -- **One order under a parent.** Folders and requests under the same parent share `position`, so a - folder can sit between two requests; a move or a copy renumbers the parent it touches, never - the others. `http_tree` answers the whole tree, built in Rust, requests without their - document, which `get_http_request` reads when one opens. -- **What goes with a deletion is `ON DELETE CASCADE`** — a collection's folders and requests, a - folder's subfolders and theirs — and `count_http_contents` says it first. A folder cannot move - into itself or below itself, nor a request into another collection's folder: both are refused - as `invalidInput` on `folderId`, rules that need the database (`StorageError::Invalid`). -- **A copy is named by the front** (« (copie) » is a word, never Rust's) and lands right after its - original, a folder or a collection with everything below it. -- The launch copy and a restore carry them, being in the database; the library export - (`transfer::Bundle`) does not — a collection travels in a file of its own. +The requests live in collections that belong to the **library**, not to a space: +`http_collections`, `http_folders` nested by `parent_id`, `http_requests` in a collection and +possibly a folder (→ "What is sealed, and what is not"). A request's **document** and a container's +**settings** are each one JSON document whose every field is `#[serde(default)]`, so a part added +later needs no migration. + +- **One order under a parent**: folders and requests under the same parent share `position`, so a + folder can sit between two requests; a move or a copy renumbers the parent it touches. +- **A deletion cascades** — a collection's folders and requests, a folder's sub-folders — and + `count_http_contents` says it first. A folder never moves into itself, nor a request into another + collection's folder (`InvalidInput`). +- **A copy is named by the interface** (« (copy) » is a word) and lands right after its original. +- The launch copy and a restore carry them; a notes export does not. diff --git a/docs/architecture/interface.md b/docs/architecture/interface.md deleted file mode 100644 index 3f5461f1..00000000 --- a/docs/architecture/interface.md +++ /dev/null @@ -1,233 +0,0 @@ -# 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) - -`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. - -## 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. - -| Question | Answer | -| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | -| Where is it drawn? | `notes/`, `http/`, `tools/`, `titlebar/`, `banners/`, `gate/`, `palette/` | -| Inside the notes area: beside, above, among, over the cards? | `notes/sidebar/`, `notes/header/`, `notes/canvas/`, `notes/overlays/` | -| What a screen remembers between frames? | `state/.rs` | -| Something with no place on screen (preferences, time, notifiers, shortcuts, updates)? | `services/.rs` | -| A call to the core? | `api/.rs`, the only files that name `engine` | -| 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`). - -⚠️ **"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`). - -## 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"). - -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. - -**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 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). - -`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"). -The widgets that draw them, `widgets::editor` and `widgets::rich`, are `ui`'s: what a field or a -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: - -- **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. -- **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. - -## 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. - -## 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. - -- **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. - -## 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. -`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. diff --git a/docs/architecture/interface/backend.md b/docs/architecture/interface/backend.md new file mode 100644 index 00000000..d9f6c9ae --- /dev/null +++ b/docs/architecture/interface/backend.md @@ -0,0 +1,267 @@ +# Backend and events (interface ↔ core) + +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. 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 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 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 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 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. 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 — 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. Not wiped byte by + byte: the threat model says why. + +## A frame, its actions and its keys + +`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 (→ "Closing is not quitting"). + +## Preferences, settings and the notifiers + +- **`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`, 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`. 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` (`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, …)`, 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 + `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. + +| 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: 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/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. diff --git a/docs/architecture/interface/frame.md b/docs/architecture/interface/frame.md new file mode 100644 index 00000000..b96523a0 --- /dev/null +++ b/docs/architecture/interface/frame.md @@ -0,0 +1,204 @@ +# Interface (egui) + +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) + +**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. + +| Question | Answer | +| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| Where is it drawn? | `notes/`, `http/`, `tools/`, `titlebar/`, `banners/`, `gate/`, `palette/` | +| Inside the notes area: beside, above, among, over the cards? | `notes/sidebar/`, `notes/header/`, `notes/canvas/`, `notes/overlays/` | +| What a screen remembers between frames? | `state/.rs` | +| Something with no place on screen (preferences, time, notifiers, shortcuts, updates)? | `services/.rs` | +| A call to the core? | `api/.rs`, the only files that name `engine` | +| A control two areas draw? | `widgets/`, which reads the theme and no state | +| A colour, a gap, a duration, a font, an icon? | `theme/` | + +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 +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. 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). Anything 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, 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 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: + +| 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"). +The widgets that draw them, `widgets::editor` and `widgets::rich`, are `ui`'s: what a field or a +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 a frame costs what is on screen: + +- **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 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"): + +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'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 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 + +« 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 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/i18n-accessibility-theming.md b/docs/architecture/interface/look.md similarity index 70% rename from docs/architecture/i18n-accessibility-theming.md rename to docs/architecture/interface/look.md index 8c615946..d1dfc021 100644 --- a/docs/architecture/i18n-accessibility-theming.md +++ b/docs/architecture/interface/look.md @@ -1,11 +1,19 @@ # 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) + +**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 new file mode 100644 index 00000000..c75386a1 --- /dev/null +++ b/docs/architecture/interface/window.md @@ -0,0 +1,226 @@ +# The window and its menus + +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` 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 + +« 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 + +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 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 + +`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 ». diff --git a/docs/architecture/libraries.md b/docs/architecture/libraries.md deleted file mode 100644 index 813ac282..00000000 --- a/docs/architecture/libraries.md +++ /dev/null @@ -1,567 +0,0 @@ -# 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) - -## 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. - -### 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. - -### 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. - -| Table | Sealed | Plain | -| --------------------- | --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `spaces` | `name` | `id`, `pinned` | -| `folders` | `name` | `id`, `space_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` | -| `note_items` | `text` | `note_id`, `position`, `done` | -| `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` | -| `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` | -| `http_history` | `summary` (name, URL, method, status, time, size, failure, environment), `record` | `id`, `sent_at`, `request_id` | -| `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: -`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. - -### 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. - -### 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. - -### 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. - -⚠️ **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. - -### 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. - -**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. - -⚠️ **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. - -### 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. - -## Several libraries, and the registry beside them - -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. - -``` -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 - libraries/ - / - devnotes.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. - -## 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.** - -| | 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 | - -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. - -**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. - -⚠️ `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. - -⚠️ `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. - -⚠️ 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. - -⚠️ 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". - -⚠️ `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. - -## The copies, and putting one back - -`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. - -## 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. - -## 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`. diff --git a/docs/architecture/notes/board.md b/docs/architecture/notes/board.md new file mode 100644 index 00000000..63bf3a84 --- /dev/null +++ b/docs/architecture/notes/board.md @@ -0,0 +1,218 @@ +# Spaces, folders and the board + +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) + +**In short** + +- A library holds spaces; a space holds folders, nested, and notes filed in one folder or none. +- Every rule about nesting is `folders::model::Lineage`. +- The board is a second view of a space: folders as zones, loose cards placed freely. It **dims** + what the criteria leave out, never narrows. +- Its geometry lives in columns no model carries, so an export never moves anyone's board. +- Every gesture commits on release, snapped to a 20 px grid, saved after a pause, with a keyboard + twin. + +## The library rail + +`notes::sidebar` draws the library as a tree — every space, its folders nested under it — left of +the canvas. A row says where to go; `AppState` turns it into the space and the folder shown +(`state::spaces`, `state::folders`, both asked again with the revision and remembered in the +library's preferences, `activeSpace` and `activeFolder`). + +- **Shown or hidden is one setting for the three areas** (`showLibraryRail`, `Ctrl+B`, movable); + while it is hidden, the area switch comes to the title bar, and the space and folder switchers + take the rail's place in the notes header (`notes::panel`, shared with the rail). +- **Its width** (`libraryRailWidth`, 160–520) is dragged from its edge, or moved by the arrows on + it, written once it rests, clamped on the way in and out. +- **A row's ⋯ opens its panel under it** (`notes::panel`, one at a time): a space is pinned, + renamed (written when the field is left, or on Enter) and deleted with a refuge; a folder is + recoloured, renamed, given a sub-folder and deleted. Names are written on leaving the field. +- **Siblings are sorted by name** (`view::fold`) and have no order of their own, so a folder + dropped on a row goes **inside** it; a drop on its space's row brings it to the top. It moves by + a drag, or by `Alt+←` (up a level) and `Alt+→` (into the sibling above). Whether it may go there + is `Lineage::check_move` and the space; a refusal is said, never written. The undo puts it back + (`move_folder_back`). +- **A card dragged on the board and let go over a row** is filed there, at any depth + (`BoardGesture::FileOnRail`), the row lit while it is over it. +- An id no space or folder answers to any more reads as « every space » or « every folder ». + +## Managing spaces from the switcher + +A space's panel (the rail's ⋯, or the header's switcher when the rail is put away) holds pin, +rename and delete. Each panel **replaces** the menu rather than nesting a field in it. + +- **Deleting says what goes before the first click**: `count_space_contents` answers the live + notes and folders, worded with the refuge chosen. **The notes are kept or trashed** + (`notes::model::HeldNotes`): trashed, they still go to the refuge, which a restore brings them + back into. With a single space there is nothing to delete into, and the panel says so. +- A folder's panel offers the same choice, counted by `count_folder_contents` (its live notes and + sub-folders, all the way down). Either deletion reports how many notes went where. +- **Pinning is the only order a person chooses** (`spaces.pinned`): pinned spaces first, then by + name, case aside — ordered in Rust, since names are sealed. An order the person maintains would + be a second thing to keep consistent on every insert and delete. + +## Folders inside a space + +A **folder** cuts a space into named, coloured regions; a note belongs to one or to none. + +| Piece | Where it lives | +| -------------------------- | ----------------------------------------------------------- | +| name, colour, owning space | the `folders` table: it travels with an export | +| the folder it is in | `folders.parent_id`, nullable, in the same space | +| which folder a note is in | `notes.folder_id`, nullable, `ON DELETE SET NULL` | + +- ⚠️ **`SET NULL`, never `CASCADE`**: deleting a folder never deletes a note. What it held goes to + **its parent** — its notes filed there, its sub-folders each to a free slot on that board — in + Rust, in one transaction, before the row goes. With `HeldNotes::Trash` it takes its whole + sub-tree: every note under it is trashed first. +- **Every rule is `folders::model::Lineage`**, built from ids and parents alone, so no name is + opened to answer one: the sub-tree, the path, the depth, where a note sits on a board (`Seat`), + and what a move may do — never into itself or what it holds, within `MAX_DEPTH` (8; + `check_arrival` for a sub-tree coming from another space). +- **A name is unique among its siblings**: two folders may each hold a « Perf ». +- **`move_folder` takes the target space**: into another space, the folder takes its sub-tree and + every note filed in it, trashed ones too, in one transaction, `updated_at` untouched. It answers + where the folder was, which `move_folder_back` puts back. In the rail that is a drop on another + space's row; `Alt+←/→` stay inside a space. +- ⚠️ **A note is never filed across spaces**: `file_many` narrows to the folder's own space, and + `NotePatch::apply` clears `folder_id` whenever `space_id` moves. +- **The colour is assigned**: `FolderColour` (five theme accents) rotates by how many folders the + space holds, so two made in a row differ; it is changed from the folder's panel. +- **Filing is a batch** (`file_notes`), answering the `NoteFiling`s it changed (the folder each + note left), which `file_notes_back` undoes exactly. +- **A card says where its note lives, and the core resolved it**: the deepest folder and its path + (`NoteFolder.path`), filled by `view::Decorations` in the pass that counts the attachments. + Which chip a card keeps is the view's: none for the folder opened (`view::keeps_chip`), none for + the zone a card sits in (`BoardView::keep_chips_from_below`). ⚠️ The chip is a square swatch on + a neutral pill, never a coloured pill (that is a tag); a loose note gets no chip at all. + +## The board: the second view of a space + +A switch in the header chooses **List** or **Board**, remembered **per space** +(`notes.view.`, `state::board::Mode`). ⚠️ It is disabled on « all spaces », where a folder +belongs to no board. `AppState::board_place` is the one place that says whether the board is on +screen: the space's, or the open folder's when it holds folders. + +**The board has a query of its own** (`board_view`, `state::board::BoardState`, a `QueryCell` with +the list's criteria among its parameters), and draws **one level**: `BoardQuery.root_id` is the +folder whose board it is (`None` for the space's); its **children are the zones**, each gathering +its whole sub-tree; what is filed in the root itself sits free on the ground. A zone lists its +sub-folders as chips; opening one opens that folder's board. It reads the whole space and marks +each note `matches`: the search, the quick filter and the facets **dim** on the board, never +reflow it — the spatial memory is the point. + +| What | Where it is stored | +| ------------------- | --------------------------------------------------------------------------- | +| a zone's frame | `folders.x/y/w/h`, nullable, moving together, on its parent's board | +| a free card's place | `note_positions`, one row a note, on the board of **its own** folder | +| a card in a zone | nowhere: it flows, in canvas order | + +- ⚠️ A `note_positions` row means « placed on the board of its own folder ». `file_many` deletes + the row of every note it files, and `save_board_layout` keeps a place only for a note filed in + the root of the board the gesture was made on. +- **The first layout is written, not computed on the fly** (`store::board::geometry`): a read + that writes a place for anything never laid out, once, against the zones of this board alone. + A place computed and not stored would let the first drag land beside cards that have none. +- **The rules are `folders::board`**, egui-free: `arrange_zones` flows zones three across, + `arrange_loose` the loose cards four across under them, `surface` sizes the ground (never under + 960 × 540). A card never placed takes `free_slot_from` — the first seat nothing stands on, + tested by rectangle against cards and zones. +- ⚠️ **A zone grows to fit and never shrinks** (`store::board::grow_to_fit`, from `file_many` and + the undo, for the folder filed into and every folder above it). Shrinking would move the board + under the pointer each time a card is taken out. +- **A card's height is the library's** (`PreviewLines::card_height`, 120, 140 or 160 px), so every + geometry call is told it; loose cards stored at an older height may overlap until « Align ». +- ⚠️ **A zone's cards flow in the columns `columns_in` counts**: the Rust that sizes a zone lays it + out too, and egui's scroll bars float over the body, so a zone never loses a column to them. + +## The board, drawn + +`notes::canvas::board`: a dotted ground (`GRID_PX`, 20 px) that pans both ways and never zooms, at +least as large as what is seen, so it takes the pointer past the content; zones from their frames +(`board::zone`), the same cards as the list's, full size; loose cards where they were left. + +- **Only what crosses the viewport is drawn**: zones and loose cards by their rectangle, a zone's + cards by the rows its body shows. Every card's `Ui` is salted with its note's id, so what scrolls + in and out moves no other id. +- **What the criteria leave out is drawn at a third of its opacity in its seat** (`board::seated`), + never reflowed, and its node says it is disabled (the journeys read that). +- While the board shows, the selection, the arrows (zone by zone, then the ground) and the search's + count read the board's cards, dimmed ones included. +- A zone's title and chips open their folder; its ⋯ opens the folder's panel, which can tick every + card of the zone. + +## Arranging the board + +Four gestures, pointer drags read by `board::Hand`, never egui's drag and drop; the arithmetic is +`board::gesture`, egui-free. + +| Gesture | Started from | Ends as | +| ------------- | ----------------------------- | ----------------------------------------------------------- | +| move a card | anywhere on the card | `file_notes`: the zone under its corner, or the board's root | +| move a zone | its header's grip | a frame | +| resize a zone | its corner | a frame | +| draw a zone | the left button on the ground | a new folder, named in a prompt, at that frame | +| sweep | the right button anywhere | the cards drawn under the band, ticked | + +- **A card is its own handle**: its seat senses the drag, the card under it the click, and egui + gives each to its own, so a card dragged is never also opened. +- ⚠️ **A gesture commits on release alone** (`follow`), as one `notes::BoardGesture`; nothing moves + before the pointer travels `DRAG_THRESHOLD_PX` (4). The pointer is read before anything is drawn + (`track`). +- **Everything lands on the grid**: a drawn band snaps both corners, a resize snaps before it + clamps to the minimum. +- **Membership comes from the drop, and from nothing else**: moving a zone carries its cards + (they have no coordinates), stretching one captures nothing. Refiling what a frame overlaps was + refused: it would refile notes the day a frame is stretched. +- **A filed card dragged out** leaves its seat faded and travels as a ghost above the board; the + zone it would land in says so. +- **One write per gesture**: `BoardState` stages what moved and lays it over the view, written + after `motion::LAYOUT_SAVE` (0.4 s) as one `save_board_layout`. ⚠️ The overlay is let go of when + a view **carries** the same value, never when the write returns (the view drawn then is the one + read before the gesture); a failed write keeps it. A membership the core refused is let go of + where a refused place is kept. +- **The keyboard twins**: a focused grip or corner moves or resizes its zone a dot per arrow; a + card is filed from the selection; a folder is made from the rail. +- **Tidying is two gestures** (`board::tidy`, `arrange_board` over a `BoardScope`): « Align » (and + `A`) flows the loose cards only — often, and nothing anyone chose is lost; the chevron offers + « Rearrange N folders and M cards », which also lays the zones out again, and names what it + touches. The answer (`BoardArrangement`: what moved and the layout it **replaced**) is the undo, + `Reversible::Arrangement`, put back through `save_board_layout`; a board already in order opens + no undo. ⚠️ The ground **pans home** after an arrangement and back after its undo + (`BoardState::pans` counts both), or the result would land off screen. + +## Descending into a folder + +**Choosing a folder is opening it**: one piece of state, from the rail, a zone's title or a +switcher. While one is open, its breadcrumb (`Space / ● Base › ● Perf`, each step a level up) +replaces the switchers. + +- **A folder that holds folders opens on a board of its own; one that holds none is a flat grid.** + In the list view an open folder is the flat grid of its whole sub-tree, read in Rust (`folder_id + IN` the sub-tree, bound up to `BIND_AT_MOST`). `notes::view::build` counts an open folder as + filtering, so it comes back as one `results` section. +- **A note created here arrives filed** — with a drop on the board, the only two places that file + a new note. The palette does not: it is used mid-task from elsewhere. +- **Escape falls through**: the selection, then the search and the facets, then up a level, then + out at the top. ⚠️ The middle rung asks whether the person filtered, not whether the view is + filtering — inside a folder the view always is. +- Deleting from the breadcrumb goes up a level, to the parent that now holds what it held. + +## A folder travels; its coordinates do not + +- **Out**: the bundle carries the folders the notes cite, **with the folders above them**, and each + note its `folderId`; a folder carries `parentId` with `#[serde(default)]`, so an older file reads + flat, and no `FORMAT_VERSION` moves. +- ⚠️ **No coordinates, and nothing was stripped to achieve it**: `Folder` carries no geometry. A + test reads the written file to prove no `x` reaches it. +- **In**: a folder is matched **by name under the same parent** in the destination space, + case-insensitively, and created when absent; spaces first, parents before children. What a file + cannot hold degrades: a parent it does not carry, a cycle, a tree past `MAX_DEPTH` — that folder + lands at the top. A note's `folderId` is remapped, and dropped when the file did not carry the + folder. `ImportReport` counts `folders_created`. +- ⚠️ **An attachment's id is remapped too**, for a harder reason: it is half of + `attachments::model::stored_name`, which decides a write path. `restore_attachments` gives every + incoming record a fresh id (the bytes taken from the archive first, keyed by the sending + library's name), and `stored_name` itself keeps only `[A-Za-z0-9-_]`, so it can never return a + path that leaves the folder — whoever calls it. diff --git a/docs/architecture/notes/cards.md b/docs/architecture/notes/cards.md index a9502123..1ecaeb95 100644 --- a/docs/architecture/notes/cards.md +++ b/docs/architecture/notes/cards.md @@ -1,12 +1,22 @@ # Cards and lists -How the notes are listed: the state behind the canvas, its sections, a card and its menu, the header row, the canvas and its keyboard. [Home](../README.md) +How the notes are listed: the state behind the canvas, the sections, a card, the header, the +editor beside the cards, the selection, the undo, the trash and the canvas's keys. +[Home](../README.md) + +**In short** + +- The canvas draws the core's `NotesView` and decides nothing: sections, order, counts and what + a card's footer says are the core's. +- A list carries previews; a note opened is always read whole by id. +- Writes are not optimistic: persist, adopt the answer, bump the `Revision`. +- A card is two layers: a click surface under it, its controls over it. +- The canvas's keys are one table (`notes::canvas::shortcuts::CANVAS`). ## State -`ui::state` holds what the interface remembers between frames, one module per subject, all -fields of `AppState` (→ "State between frames" for `QueryCell`, `Revision` and `LibraryCaches`). -The notes are held by modules split by the question they answer: +`ui::state` holds what the interface remembers between frames (→ "State between frames"). The +notes are held by modules split by the question they answer: | Module | Answers | | ------------------- | ---------------------------------------------------------------- | @@ -18,599 +28,219 @@ The notes are held by modules split by the question they answer: | `undo` | the last write that can be put back, and its bar | | `spaces`, `folders` | the library's spaces and folders, and which one narrows the view | -Beside them, one module per screen or job that is not the canvas: `trash` (loaded when its panel -opens, not by a permanent query), `tags` (global management: nothing runs before the core has -counted what it touches), `transfer` (import, export and share, each reporting), `palette`, -`attachments`, `placeholder_fill`, `note_revisions`, `formatting`, `calc_sheets`, -`drawing_pictures`, `explored`, `libraries`, `backups`, `security`, `help`, `tools`, `http/`. +Beside them, one module a screen or job: `trash` (loaded when its panel opens), `tags`, +`transfer`, `palette`, `attachments`, `placeholder_fill`, `note_revisions`, `formatting`, +`calc_sheets`, `drawing_pictures`, `explored`, `libraries`, `backups`, `security`, `help`, +`tools`, `http/`. -`notes_query` holds the **query** — search text, quick filter, tags, languages — and the -`NotesView` the core answered. It does no filtering, sorting or grouping: those are -`query_notes`'s, and everything the canvas draws is read from the view. +`notes_query` holds the **query** — search, quick filter, facets, arrangement — and the +`NotesView` the core answered. It filters, sorts and groups nothing. -- **The search is debounced** (`DEBOUNCE`, 150 ms): the field takes every keystroke, the query - is asked once the typing pauses. +- **The search is debounced** (`motion::TYPING`, 150 ms, a deadline in egui's time): a burst of + keys asks once. - **The last view stays while the next loads**, and after an error: a keystroke never blanks the - canvas. One query in flight, the latest waiting — a burst asks the one in flight and the - newest, never one per pause (the core computes a query to its end once asked). -- **Its parameters are compared by value**, and they include the local **day**, not the instant: - a clock tick asks nothing again; midnight does, through `request_repaint_after`. -- **The space is a filter, not a label.** `None` means « all spaces » and is a choice, not a - loading state; an id matching no known space falls back to `None`. The space also scopes the - facet rails: a tag that filters nothing in the space is not offered. - -Creating a note files it in the active space, the first one in « all spaces »; with no space at -all creation is refused with a translated message. + canvas. One query in flight, the latest waiting. +- **Its parameters are compared by value**: the space, the folder, the **local day** (midnight + asks again, through `request_repaint_after`; a clock tick does not), the `Revision`, and how far + the index has filled. +- **The space is a filter, not a label**: `None` is « all spaces », a choice; an id no space + answers reads as `None`. The space scopes the facets too. Rules of the house: -- **The core is authoritative; writes are not optimistic.** A write persists, its answer is - adopted, and the `Revision` is bumped, so every view that reads notes — the list and the board - alike — asks again. Nothing is applied locally first, so nothing is rolled back on a failure: - the `ErrorNotifier` says it and the screen shows what is stored. ⚠️ A write that reloaded one - view only is what once left a todo list ticked on the board and unticked in the list. +- **Writes are not optimistic.** A write persists, its answer is adopted, and the `Revision` is + bumped, so the list and the board ask again together; a failure is said by `ErrorNotifier`. - **One function writes a note's fields** (`state::notes`, with a `NotePatch` whose `None` is « untouched »); closing the editor on an untouched note writes nothing. -- **Ids, instants and normalisation come from the core**, never from the interface; time comes - from the injectable clock (`services::time`). -- **The board dims where the list narrows**: a card there can be ticked, moved or deleted while - its note is outside the list's view, so a gesture resolves its note through the view on screen. +- **Ids, instants and normalisation come from the core**; time from the injectable clock. +- **The board dims where the list narrows**: a gesture resolves its note through the view on + screen. ## Display sections -Sections are built in Rust (`crates/engine/src/notes/view.rs`) and arrive ready to render. -The front-end preserves the order it receives and never drops or merges a section. - -The classification into `pinned`, `today`, `week` and `older` is **exhaustive**: apart from -pinned notes, each note falls into exactly one section — a note belonging to no section is -unreachable in the UI, search included. An unparseable `created_at` lands in `older` rather -than disappearing. The `week` section is always present because it hosts the "paste or -create" ghost card. - -As soon as a search query, a tag selection or an opened folder is active, the view collapses -into a single flat `results` section. Spreading search results across date sections dilutes -them and hides matches at the bottom of the page. A quick filter (`pinned` / `untriaged`) -does **not** trigger this: it narrows a view that stays chronological. - -⚠️ `build_sections` takes `Option` rather than a bare `is_filtering`: `None` is the -chronological sections, `Some(ghost)` the flat list, and `ghost` says whether it is somewhere -a note can be **created**. The inside of a folder is — a note made there arrives filed, and it -is the one place where creating one files it — so the flat view keeps the ghost when the -folder is the whole reason it is flat. A result list is a list of what already matched, not a -place, so a search or a facet takes it away. +Sections are built in Rust (`notes::view`) and arrive ready to draw, in order, none dropped. -Day boundaries are **local**, so the query carries `tzOffsetMinutes` alongside `now`. Without -it a note created at 23:00 would be filed under the wrong day. Beware the sign: JavaScript's -`getTimezoneOffset()` returns −120 for UTC+2, the opposite of what chrono's `FixedOffset` -expects. - -A section's key **is** its translation key (`'sections.' + key`), which is why the Rust enum -serialises to `"pinned"` / `"today"` / … and no user-visible label ever crosses the bridge. +- **Exhaustive**: apart from the pinned, each note falls in exactly one of `today`, `week`, + `older`; a note in no section would be unreachable. The `week` section is always there: it + holds the « paste or create » card. +- **A search, a facet or an opened folder makes one flat `results` section**: results spread over + dates would hide matches at the bottom. A quick filter (pinned, untriaged) does not. +- `build_sections` takes `Option`: `None` for the dated sections, `Some(ghost)` for the flat + list, `ghost` saying whether a note can be **created** there — inside a folder yes, a search no. +- **Day boundaries are local**: the query carries `tz_offset_minutes` with `now`. +- A section's key is its translation key (`sections.`): no label comes from the core. ## What a card's footer shows -The footer carries one of three things, and which one is a **product rule**, so it is decided -in `notes::model` and arrives as a tagged `footer` field: - -| variant | when | rendered as | -| -------- | ----------------------- | -------------------------- | -| `expiry` | the note has a deadline | `expiryRef(at, now)` | -| `source` | it has a context | the first path segment | -| `age` | everything else | `relativeTimeRef(at, now)` | - -The dated variants carry a **date, not a label**: formatting stays on the front so "4 min ago" -keeps ageing on screen without a round trip. That is the line — the back decides _what_ to -show, the front decides _how_. - -`expiringSoon` comes with it, computed against a single threshold in `notes::model`. It -previously lived only on the front (`isExpiringSoon`, 3 days) while the back separately -computed `has_expiring_notes` — two definitions of "soon" behind a hint that reads "to triage -soon". The section flag now derives from the same per-note value. - -## "Untriaged" — the ephemeral note +Which date or context a card shows is a **product rule**, decided in `notes::model` +(`NoteFooter`): -In the product model, a note carrying a deadline is a note whose fate has not been decided -yet: that is what the `untriaged` quick filter selects, what the `⏳` lifecycle badge shows, -and what the "to triage soon" section hint counts. All of it hangs on one field, `lifecycle`. +| Variant | When | Drawn as | +| --------- | --------------------------------- | ------------------------------ | +| `Expiry` | the note has a deadline | the time left, red when near | +| `Source` | it has a context | the context | +| `Created` | the list is sorted by creation | the age since it was made | +| `Age` | everything else | the age since the last edit | -The deadline is set from the editor's date field, next to the badge: an empty field means -permanent, a date means expiring. The value is turned into the **end of the local day** -(`endOfLocalDay`), not midnight — a note dated today would otherwise be expired the moment it -was set — and the reverse conversion is local too, or the field would show the previous day -west of Greenwich. This is the same class of exception as relative-time formatting: an -`` value is a UI representation, not a business rule. +The dated variants carry a **date, not a label**: the interface formats it, so « 4 min ago » ages +on screen. `expiring_soon` comes with it, from one threshold (`expires_soon`). -Until that field existed, every note was created permanent and nothing could ever change it, -so the filter, the badge and the section hint were all reachable but permanently empty. +**« Untriaged » is a note with a deadline**: what the quick filter selects and the ⏳ badge shows, +all hung on `lifecycle`. The deadline is set from the editor's date field and stored as the **end +of the local day** (`end_of_local_day`), so a note dated today is not expired the moment it is set. ## A list sends previews, and the body is read by id -A card shows each body cut to its room — `notes::model::PREVIEW_LINES` lines, and at most -`PREVIEW_CHARS` characters, since a minified file is one line — and says so with -`DisplayNote.truncated`. `query_notes` answers no copy at all: its sections hold -`view::Card`s, the index's own `Arc` entries with the quote of what the search -found, and `NotesView::display(card)` computes what one card draws (footer, fields, chip, -counter, preview) for the cards on screen only. The cut is its **last** pass, as it is of -`board::build`: the fields, the matching and the search excerpt read the whole body first, so a -list still knows a snippet has a `{{field}}` on its fortieth line, and still quotes the line a -search found there. - -⚠️ **A note from a list is never edited.** `NotesStore.openNote` takes an id and reads the note -with `get_note`, every time: a draft seeded from a preview would write the first lines back -over the body on the first commit. Every other way into the open note is a write's answer, -which is the whole row, so the editor holds a whole note by construction. A later open, a new -note or a close while the read is on its way wins over it. - -A copy or a fill of a card goes through `NotesRepository.whole`, which reads the note only when -it is `truncated`: the card's copy button takes a function and asks at the click, and the ⚡ -form and the palette fill the whole body. A todo list is never cut — it has no body — and -copies its `copyText` without a round trip. - -The palette used to hand the note itself to the editor (#280), because nothing on the bridge -could read one the canvas filters hid. `get_note` is that read, so it passes the id like the -canvas does. The trash still sends whole bodies: it is not on the keystroke path, and nothing -in it is copied. - -## A card is two layers, and the click surface is the lower one - -A `