@eloxiv/registry 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,415 @@
1
+ {
2
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
3
+ "name": "desktop-rune",
4
+ "title": "Rune desktop host",
5
+ "description": "A native desktop host on Rune (Rust): its own window over the app's daemon through LocalClient v1 (sign-in in the system browser, organisations, live queries, optimistic writes, the agent's chat with consent and approval prompts, MAKE views drawn natively), the daemon started as its sidecar with a per-launch host secret.",
6
+ "dependencies": [
7
+ "@eloxiv/contracts@^0.1.0",
8
+ "@eloxiv/daemon@^0.1.0"
9
+ ],
10
+ "devDependencies": [
11
+ "@tauri-apps/cli@2.12.4"
12
+ ],
13
+ "registryDependencies": [],
14
+ "files": [
15
+ {
16
+ "path": "app/desktop-rune/README.md",
17
+ "content": "# Desktop host (Rune)\n\nThe app's native desktop host (decision 14): a [Rune](https://github.com/anomalyco/rune) window, in Rust, over the app's own daemon. The daemon holds the client core (the person's session, the selected organisation, the replica, the named queries and the optimistic writes) and serves it as [LocalClient v1](../../../docs/contracts/local-client.md) on loopback; this host draws what its events say and asks it for what the person does. It never sees a kernel credential or the person's password. The app owns this folder; change it freely. It builds on Linux, macOS and Windows.\n\nThis is a minimal reference (decision 11), not a product: sign-in, the organisation switcher, a live list (hello's greetings), an optimistic write and a refused one, the agent's chat (when the app has the agent), a MAKE view, sign-out, light and dark, left to right or right to left.\n\n## Layout\n\nA Cargo workspace of its own (Rune asks the consumer's workspace root to repeat its `[patch.crates-io]`, which Cargo never takes from a dependency):\n\n- `Cargo.toml`: the workspace, Rune pinned at `eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90` with its five patches (`winit`, `parley_engine`, `wgpu-hal`, `accesskit_windows`, `accesskit_macos`) at that revision, and Rune's debug-info settings (dependencies without debug info, the workspace with line tables: full debug info took 18–23 GB of RAM for one Rune test build). When Rune is bumped, take its root `Cargo.toml` at the new revision and use that same `rev` for `rune` and every patch.\n- `app/`: the host (`eloxiv-desktop-rune`): `src/sidecar.rs` (the daemon as its sidecar), `src/backend.rs` (every request on a worker thread, the event stream on its own), `src/model.rs` (the session, generations, rows and writes, pure), `src/chat.rs` (the chat screen's state, pure), `src/outstanding.rs` (the person's outstanding sends, kept per person and organisation in the data directory), `src/ui.rs` (the state on the UI thread), `src/view.rs` (the screens), `src/make/` (MAKE views, natively); `src/config.rs` (the app's identity and host settings, `app.json`), `src/launch.rs` (the launch probe); the Host contract: `src/links.rs` and `src/routing.rs` (deep links), `src/keychain.rs` (secure storage), `src/updates.rs` and `src/services.rs` (updates, and the host's work off the UI thread), `src/host.rs` (capabilities and errors).\n- `crates/eloxiv-local-client/`: LocalClient v1 (1.1.0) for Rust. Its protocol and MAKE view types (`src/generated.rs`) are **generated** with [typify](https://github.com/oxidecomputer/typify) from `@eloxiv/contracts`' code generation bundles `schema/codegen/LocalClient.json` and `schema/codegen/Sandbox.json` (every type named there, nothing renamed here); a blocking client of every route ([ureq](https://crates.io/crates/ureq)) with typed refusals; the event stream on a thread over a socket it owns, so cancelling ends a blocked read at once.\n- `crates/eloxiv-update/`: signed updates: the manifest, minisign verification, downloads, archives, and the `eloxiv-update` command that makes the keys, signs a release and writes its manifest.\n- `app.json`: the app's identity and host settings (below), with `app-icon.svg`; `entitlements.plist` (macOS signing); `scripts/package.ts` and `scripts/measure-launch.ts` (installers and the launch measurement).\n- `crates/eloxiv-local-client-codegen/`: the generator. `cargo run -p eloxiv-local-client-codegen` writes `generated.rs` again; its test regenerates and fails while the checked-in file differs. It finds the schemas in `node_modules/@eloxiv/contracts/schema` (or this repository's `packages/contracts/schema`, or `ELOXIV_CONTRACTS_SCHEMA`); without them the test skips, unless `ELOXIV_REQUIRE_SCHEMAS=1`. After updating `@eloxiv/contracts`, run the generator.\n\n## The sidecar\n\nThe generic daemon knows no app: the host's sidecar is the app's own daemon entry, which composes the daemon with the app's sync schema, named queries, mutators and module contracts (`clientApp`, [Daemon](../../../docs/contracts/daemon.md)). This item ships it, `sidecar/daemon.ts` (Bun; `sidecar/daemon-node.ts` is the same on Node), over the composition files the CLI regenerates whenever a module is added or updated:\n\n```ts\nimport { runMain } from \"@eloxiv/daemon/runtime/bun\"\nimport { contracts } from \"../../eloxiv.modules.ts\"\nimport { mutators, queries, schema } from \"../../eloxiv.sync.ts\"\n\nrunMain(process.argv.slice(2), process.env, { clientApp: { modules: contracts, schema, queries, mutators } })\n```\n\n`node desktop-rune/scripts/build-sidecar.ts` (from the app root; Node, Bun and Rust on PATH, `--target <triple>` to cross-compile) compiles it with Bun into `desktop-rune/target/sidecar/eloxiv-daemon[.exe]`. `scripts/package.ts` puts it in the installers (see Packaging). `ELOXIV_KERNEL_URL` and `ELOXIV_ZERO_URL` tell it the kernel and zero-cache (the host sets them from `app.json`'s `servers` when the environment does not); a desktop sign-in opens the web shell's approval page, `<ELOXIV_SHELL_URL>/desktop/sign-in` (default `http://localhost:5173`, the shell's development server; `ELOXIV_SIGN_IN_PAGE` names another page).\n\nOn launch the host (`src/main.rs`, `src/sidecar.rs`):\n\n1. makes a **host secret** for this launch: 36 random bytes from the OS, base64url (48 characters; the daemon needs at least 32), kept in this process's memory only;\n2. starts the sidecar, the first found of: `ELOXIV_DAEMON_BIN`; a package's `<binaryName>-daemon[.exe]` beside the executable or in `../libexec/` (Linux), else `eloxiv-daemon[.exe]` beside it; `target/sidecar/eloxiv-daemon[.exe]` of the workspace the executable was built in (`cargo run`, debug or release); else, in development, `sidecar/daemon.ts` from source with `bun`. It passes `--port <port> --stdin-lifeline` (`ELOXIV_DAEMON_PORT`; else a free port when packaged, 4191 in development: see \"Two apps on one machine\"), a packaged sidecar's `--state-dir`, `ELOXIV_DAEMON_HOST_SECRET` and the app's servers (`ELOXIV_DAEMON_ARGS` goes before them), its stdin a pipe the host holds: if the host dies, the pipe closes and the daemon exits;\n3. opens the window at once and, off the UI thread, waits for `GET /health` (30 s), reads `hello` (refusing another major version of the protocol), opens the event stream, whose first event is the session (no separate read, whose late answer could overwrite a newer session; one of an older generation is ignored);\n4. on exit closes the pipe, waits 2 s for the daemon to end, then kills it, and waits.\n\n`ELOXIV_DAEMON_URL` with `ELOXIV_DAEMON_HOST_SECRET` attach to a daemon that is already running instead (development, the journey): nothing is started.\n\n## Build and run\n\nNeeds Rust (1.97 or later; mise pins 1.99.1). Linux needs `libxkbcommon-dev` and `libwayland-dev` to build (Debian and Ubuntu; Fedora `libxkbcommon-devel wayland-devel`; Arch `libxkbcommon wayland`), and `libxkbcommon-x11-0` to open a window on X11. From `desktop-rune/`:\n\n```sh\ncargo run --release # the window (the sidecar built, run from source with Bun, or ELOXIV_DAEMON_URL set)\ncargo test # the headless tests: no window, no GPU\ncargo run -p eloxiv-local-client-codegen # after @eloxiv/contracts changed\n```\n\n## What it does\n\n- **Networking off the UI thread.** Every request runs on a worker thread; the event stream has a thread of its own. Their answers go into an inbox that Rune's `poll` drains on the UI thread each frame, woken by Rune's waker. The window opens before the daemon answers.\n- **One generation at a time.** Every `rows` and `write` event names its generation. A `context` event (another organisation, sign-out, the sync server refusing the session) raises it, and the host drops every row, write and MAKE view of the older ones; until the signed-in session of the new generation arrives (LocalClient sends it after the `context` event), the session it kept describes the previous context, so nothing is subscribed, written, sent, decided or restored from the outstanding store, whose sends are then restored for that session's person and organisation; a late event or answer of an older generation changes nothing. An organisation switch or sign-out clears the screen from the intent on, before the daemon answers.\n- **Subscriptions** are named by the host (`id`), so a snapshot that arrives before the answer to `POST /subscriptions` is already the host's; a daemon that answers an id of its own is handled too (the early snapshot is kept until the answer). A dropped stream is opened again, the session read and the list subscribed again (v1 has no resume).\n- **Writes** go through the daemon's mutators (`POST /client/v1/writes`, a host-chosen id): the prediction shows at once (the daemon's replica has it), then `confirmed`, `rejected` with its typed error after the rollback, or `notConfirmed` while offline. The host never predicts or rolls back anything itself.\n- **Sign-in** opens the app's web sign-in page in the system browser (`POST /client/v1/sign-in`); the daemon receives the redirect, redeems the code and the session event follows. **Sign-out** waits for the kernel to confirm the revocation.\n- **The agent's chat** (an app with the kernel's agent: `hello` names `agent.conversations`, `agent.messages`, `agent.runs` and `approvals.requests`, and the feature `runEvents`): the latest conversation opens (or a new one); its stored messages come from those named queries; a send is `agent.send` through `POST /client/v1/actions/agent.send` under a key made for it and with the generation it was made in (the daemon runs it in no other organisation); it is recorded before it leaves in the outstanding store, per person and organisation, in `outstanding-sends.json` in the host's data directory (`ELOXIV_RUNE_DATA_DIR`, else the platform's per-user application data directory, under the app's identifier (`app.json`); its text, conversation and key only, readable by the person only; hosts sharing the data directory share it: each change is made under an advisory lock of `outstanding-sends.json.lock` to the file as it is then, and Send reads it again first, so no host overwrites another's sends or resends one another settled), and leaves it when an answer settles it, whatever is shown by then; one whose answer was lost is resent under the same key, which the kernel answers with a replay, never a second run, also after an organisation switch and back, a sign-out and in, or a restart of the host; a retry refused after a lost answer (a policy or credential change) proves nothing about the first attempt, so the send stays, shown as possibly sent, under its key: the next Send resends it under that key (a replay if it ran: LocalClient has no receipt lookup), and Discard forgets it; the run is followed through a run subscription (`POST /client/v1/runs`), its streamed text shown by model step until the replica holds that step's stored answer, which replaces it, `run-finished` freeing the composer at once; a consent the run asks for is a prompt the person allows or declines (`consent.approve` or `consent.reject` under `consent:<id>:<decision>:`), and approval requests someone else made are prompts too (`approvals.approve` or `approvals.reject` under `approval:<id>:<decision>`). While the daemon says the agent is not set up (`GET /client/v1/agent/readiness`: `missing` or `unavailable`) the screen says why and keeps the draft without sending, and the host asks again every 10 s until the agent can answer (a model set up meanwhile, in the web shell, enables Send with the draft kept). Nothing of the conversation survives an organisation switch or a sign-out, but the person's outstanding sends; no unsent draft does either, whoever made the change (this host, another local client of the daemon, or a revoked session).\n- **Accessibility**: every control has a role and a name (AccessKit: UI Automation, NSAccessibility, AT-SPI). **Right to left** through `El::dir`: rows, alignment and padding mirror. **Light and dark**, or the system's.\n\n## MAKE views, natively\n\nA MAKE view's code never runs here: each step is `make.renderView` in the kernel's sandbox, through `POST /client/v1/actions/make.renderView`. The host (`src/make/`) keeps the view's state between steps, runs **one step at a time**, each from the state the one before returned, makes the calls a step asks for **only for the actions `make.view` listed** (any other is answered `{ ok: false, error: { _tag: \"Forbidden\" } }` here, with no request), under `make-view:<mount>:<key>` (the view's key, or a fresh UUID), and drops every answer for a view that is gone (another organisation, sign-out, the screen closed, reopened). It refuses a step over 4 MiB, a tree past 5,000 nodes or 64 levels, and anything that does not decode as the contract's tree, and stops the view.\n\nThe vocabulary is closed (the contract's tags and props, decoded into generated types before anything is drawn); nothing names a URL, loads an image or runs code; no URL is ever opened.\n\n| Tag | Native |\n| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `div` `section` `header` `footer` `p` `label` `li` `td` `th` `thead` `tbody` | a column; runs of text-level children (text, `span` `strong` `em` `small` `code` `br`) become one wrapped paragraph, with HTML's whitespace collapsing |\n| `h1`–`h4` | a heading (role `heading` with its level) |\n| `ul` `ol` | a list, each `li` with a bullet or its number |\n| `table` `tr` `th` `td` | rows of equal-width cells; **`colspan` and `rowspan` are ignored** |\n| `pre` | monospaced, its whitespace kept |\n| `hr` | a rule (decoration to assistive technology) |\n| `form` | a group whose fields its controls send; never submitted |\n| `button` `link` | a focusable control sending its `on` event with `data` and the fields of its nearest form (or the whole view's); disabled ones send nothing |\n| `input` | a text field (`text` `email` `search` `tel` `date` `time` `datetime-local` `color` as text; `number` keeping to a number's characters), a checkbox, a radio button (grouped by name within its form), a slider (`range`: `min`, `max`, `step`, from the midpoint), or, for `hidden`, nothing drawn but still a field; any other type is `text` |\n| `textarea` | a multi-line text field (`rows` sets its height) |\n| `select` `option` | an inline list box of the options (an option's value is its text, as the web host draws it) |\n\nFields follow the web host exactly: `fields` maps each named field to its text (a number field's too), a checkbox to `true`/`false`, a radio group to its checked button's value or `\"\"`; a later field of a name overwrites an earlier one; what the person typed is kept across a redraw for a field of the same name the tree gives no value (radio buttons excepted). A watched field (`on`) sends its event when it changes, with `value`.\n\n`class` is inert, as on the web. `title` describes its element. `style` is first held to the web's filter (the same properties, plain values, the same functions, `var()` naming only theme variables, 200 characters a value and 4,000 in all), then the **native subset** is drawn and everything else ignored: `color`, `background-color` (`#rgb`, `#rrggbb`, `#rrggbbaa`, `rgb()`/`rgba()`, a few names, `var(--<theme colour>)`), `font-weight`, `font-style`, `font-size`, `text-align` (`left` and `right` physical), `margin` and `padding` with their sides (physical: in a right-to-left view `left` is still the left), `border` (one width and colour), `border-width`, `border-color`, `border-radius`, `display` (`flex`, `none`, else a block), `flex-direction`, `gap`, `align-items`, `justify-content`, `width`, `height` and their `min-`/`max-` (`px`, `rem`, `em`; `100%` fills), `opacity`. Not drawn natively: `calc()` and the other functions, percentages other than 100%, `line-height`, `letter-spacing`, `text-decoration`, `text-transform`, `white-space`, `vertical-align`, `list-style-type`, `border-style`, `border-collapse`, per-side borders, `flex`, `flex-wrap`, `grid-template-columns`, `overflow`.\n\n## The app's identity and host settings: `app.json`\n\nOne file, the app's to edit, read by packaging (`scripts/package.ts`), by the host (compiled in: `src/config.rs`) and by the release signer (`eloxiv-update release --config app.json`), so the installers, the running app and its update manifests always agree:\n\n```json\n{\n \"name\": \"Acme CRM\",\n \"identifier\": \"com.acme.crm\",\n \"binaryName\": \"acme-crm\",\n \"version\": \"1.2.0\",\n \"description\": \"Acme's CRM\",\n \"publisher\": \"Acme\",\n \"copyright\": \"\",\n \"category\": \"Productivity\",\n \"icon\": \"app-icon.svg\",\n \"urlScheme\": \"acme-crm\",\n \"deepLinks\": { \"register\": true },\n \"servers\": {\n \"kernelUrl\": \"https://api.acme.example\",\n \"zeroUrl\": \"https://sync.acme.example\",\n \"shellUrl\": \"https://app.acme.example\"\n },\n \"updates\": {\n \"url\": \"https://updates.acme.example/{channel}/{platform}-{kind}.json\",\n \"publicKey\": \"RWQ…\",\n \"channel\": \"stable\"\n }\n}\n```\n\n| Field | Meaning |\n| ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `name` | The window title and the installed app's name. |\n| `identifier` | Reverse DNS, unique per app: the window's app id (Wayland `app_id`, X11 `WM_CLASS`), the bundle id, the host's data directory and the packaged daemon's state directory, the single-instance name, the keychain namespace. |\n| `binaryName` | The installed executable (lower case, digits, `-`); the sidecar is installed as `<binaryName>-daemon`. |\n| `version` | This build (semver). Updates move only to a newer one. |\n| `description`, `publisher`, `copyright`, `category`, `icon` | For the installers; `icon` is `app-icon.svg` or a square PNG of at least 512 px. |\n| `urlScheme` | Deep links (`<scheme>://open/<path>`), registered by the installers. Not one the system owns (`http`, `file`, …). |\n| `deepLinks.register` | Register the scheme at launch where no installer did (an AppImage, a development build). Default `true`. |\n| `servers.kernelUrl`, `zeroUrl`, `shellUrl` | What the packaged app reaches: the host gives them to its sidecar as `ELOXIV_KERNEL_URL`, `ELOXIV_ZERO_URL` and `ELOXIV_SHELL_URL` (the shell's `/desktop/sign-in` approves a desktop sign-in). Empty: the daemon's own (the app's `clientApp`, else its development defaults). No app edits `sidecar/daemon.ts` for this. |\n| `updates.url`, `publicKey`, `channel` | The update manifest's URL (`{channel}`, `{platform}`, `{kind}`, `{app}`, `{current}` filled in) and the app's minisign public key; without both, updates are unsupported. `channel` defaults to `stable`. |\n\nUnknown fields are refused, as is any value that is not valid; the host's tests and `package.ts` refuse a broken file before anything is built. At run time the environment overrides each field: `ELOXIV_APP_ID`, `ELOXIV_APP_NAME`, `ELOXIV_APP_SCHEME`, `ELOXIV_APP_VERSION`, `ELOXIV_UPDATE_URL`, `ELOXIV_UPDATE_PUBLIC_KEY`, `ELOXIV_UPDATE_CHANNEL`, `ELOXIV_REGISTER_SCHEME` (`0`: never register), `ELOXIV_KERNEL_URL`, `ELOXIV_ZERO_URL`, `ELOXIV_SHELL_URL`; `ELOXIV_HOST_CONFIG` names another `app.json` to use whole. An override that is not valid is logged and the compiled value kept.\n\n## Two apps on one machine\n\nA packaged sidecar (installed beside the host or in `../libexec`) keeps its state in the app's own directory, `<state base>/<identifier>/daemon` (Linux `$XDG_STATE_HOME` or `~/.local/state`; macOS `~/Library/Application Support`; Windows `%APPDATA%`), not the daemon's shared default, and listens on a free loopback port chosen at each launch (the kernel takes a desktop sign-in's loopback redirect on any port), so two Eloxiv apps, or two copies of one, never meet. `ELOXIV_DAEMON_PORT`, `ELOXIV_DAEMON_STATE_DIR` or `--state-dir` in `ELOXIV_DAEMON_ARGS` fix them instead. A development build (`cargo run`) keeps the daemon's defaults: port 4191 and its own state directory.\n\n## Packaging\n\n```sh\ncargo install cargo-packager --version 0.11.8 --locked # once\nnode desktop-rune/scripts/package.ts # from the app root: this system's installers\n```\n\n[cargo-packager](https://github.com/crabnebula-dev/cargo-packager) makes every format of the three systems from one configuration, which `scripts/package.ts` writes from `app.json` (`target/package/packager.json`): it checks `app.json`, builds the sidecar for the target and the host in release mode (which compiles `app.json` in), stages them under the app's names, makes the icons from `icon` (the Tauri CLI's generator) and runs cargo-packager. Into `target/package/out/`, listed in `installers.json`:\n\n| System | Installers (default) | Where the sidecar goes |\n| ------- | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| macOS | `<name>.app`, `<name>_<version>_<arch>.dmg` | `Contents/MacOS/<binaryName>-daemon`, beside the host |\n| Windows | `<name>_<version>_<arch>-setup.exe` (NSIS, per user; `--formats nsis,wix` adds an `.msi`) | beside the host |\n| Linux | `<binaryName>_<version>_<arch>.deb`, `.AppImage` | `/usr/libexec/<binaryName>-daemon` (an internal executable; the AppImage's linuxdeploy rewrites everything in `usr/bin`, which breaks a Bun-compiled executable) |\n\nEach installer registers `urlScheme`: the `.deb`'s desktop entry (`MimeType=x-scheme-handler/<scheme>`), the NSIS installer under `HKCU\\Software\\Classes\\<scheme>` (removed by its uninstaller), the bundle's `Info.plist` (`CFBundleURLTypes`). The packaged host then leaves the registration to them; it registers the scheme itself only from an AppImage, which no installer registers, and from a development build.\n\nDownloaded tools are pinned. cargo-packager's AppImage step would fetch AppRun, linuxdeploy and linuxdeploy's AppImage plugin from moving `continuous` builds without a check; `package.ts` fetches exact versions instead (linuxdeploy `1-alpha-20251107-1`, the plugin `1-alpha-20250213-1`, AppRun from `apprun-old`), checks each against its SHA-256 (`PINNED_APPIMAGE_TOOLS`), keeps them in `target/package-tools/` and copies them fresh into cargo-packager's tools directory, so it downloads none itself. The NSIS ApplicationID plugin, which cargo-packager fetches unchecked, is checked against its SHA-256 before the installer is accepted. cargo-packager checks its own NSIS, WiX and NSIS-utils downloads, and takes create-dmg at a fixed commit.\n\n`--target <triple>` packages for another target where the toolchains allow it, `--formats` picks formats, `--skip-build` packages what is built. Signing runs only with credentials in the environment, else the installers are unsigned and the script says so (and records it in `installers.json`):\n\n- macOS: `APPLE_SIGNING_IDENTITY` (with `APPLE_CERTIFICATE`, a base64 `.p12`, and `APPLE_CERTIFICATE_PASSWORD` when it is not in the keychain) signs the app, its sidecar and the dmg with the hardened runtime and `entitlements.plist` (Bun's JIT); `APPLE_ID`, `APPLE_PASSWORD` and `APPLE_TEAM_ID`, or `APPLE_API_KEY`, `APPLE_API_ISSUER` and `APPLE_API_KEY_PATH`, notarise it.\n- Windows: `WINDOWS_CERTIFICATE_THUMBPRINT` (a certificate in the store; `WINDOWS_TIMESTAMP_URL`) through signtool, or `WINDOWS_SIGN_COMMAND` with `%1` for the file (Azure Trusted Signing, a key vault), signs the sidecar, the host and the installer.\n- Linux: nothing is signed.\n\n## Launch to interactive\n\nThe host prints `ELOXIV_DESKTOP_INTERACTIVE ms=<since main> source=frame screen=<signed-out|signed-in> clock=main` once (`src/launch.rs`, on only in the executable): at the start of the frame after the first frame that drew the screen the daemon's session calls for, with what it needs from the daemon (`/health`, `hello` and the event stream; signed out, the sign-in screen; signed in, the list's first snapshot). The packaged host is measured whole: single instance, the host's services (the views asked of the sidecar, the scheme registration, the keychain, the updater) and the sidecar on its free port. `scripts/measure-launch.ts --app <executable> --runs 20` launches it, reads the sidecar's port from the host's `[eloxiv-daemon] spawned` line (`--port` fixes one), measures spawn to the probe line on its own clock, checks the sidecar answers and stops with the host (quit, and `--crash` killed outright), and asserts the p95 against \"Desktop launch to interactive ≤ 1.5 s\" (decision 7's budgets). Each launch starts signed out (fresh daemon and host directories). On Linux and macOS quitting is SIGTERM, which ends the host at once; the daemon then exits through its stdin lifeline.\n\n## Deep links and one process\n\n- `main` claims the app's single instance (Rune's `single_instance`, by the identifier) before it starts the sidecar. A later launch (`gio open example://open/hello`, a click in a browser, a second start) hands its arguments to the running process and exits at once: Linux through a Unix socket in `$XDG_RUNTIME_DIR`, Windows through a named pipe per user and session; macOS keeps one process and sends links as Apple events. Rune gives every link, the launching one included, to `App::on_open_url`.\n- A link is read with the View contract's `parseLink`, ported to Rust (`src/links.rs`): a link in the app's scheme with host `open`, or a shell path; anything else is refused with `InvalidLink` and its reason, and changes nothing. Its views are the app's (asked of the sidecar once per launch, off the UI thread: `<sidecar> --print-views`, or `ELOXIV_RUNE_VIEWS`, a JSON file of `{ id, route, title }`) and the host's own screens at the web shell's routes (`/agent/conversation`, `/make/<module>`).\n- The link waits for the views and a signed-in session (through sign-in), switches to the organisation it names when the person belongs to it (asked once; another is ignored, as the web shell does), then opens its screen: hello's greetings, the agent's conversation, or the MAKE screen with the module filled in. A MAKE view is not opened by a link: its first step may call the module's actions, so it runs only when the person presses Open. A view of the app with no screen here says so. A link only navigates; it never runs an action.\n- Registration at run time, off the UI thread, only where no installer registered the scheme (an AppImage, a development build) and `deepLinks.register` allows it: Linux writes `$XDG_DATA_HOME/applications/<identifier>.desktop` (`MimeType=x-scheme-handler/<scheme>`, hidden from menus, `Exec` the AppImage when running from one) and makes it the default with `xdg-mime`; Windows writes `HKCU\\Software\\Classes\\<scheme>` with the command `\"<exe>\" --open-url \"%1\"`. macOS registers what the bundle's `Info.plist` declares.\n- A link launch is exactly one link: `<exe> <link>` or `<exe> --open-url <link>`. A launch that carries a link with anything else (a link that closes Windows' quotes to add arguments) is refused before anything starts, and Rune never reads the process's arguments as its own flags (`App::args`), except a development build's without a link (Rune's tooling).\n\n## Secure storage\n\n`src/keychain.rs`: the host's own small secrets (at most 16 KiB, keys `^[a-z0-9][a-z0-9._-]{0,127}$`) in the OS credential store through the `keyring` crate (Keychain Services, the Credential Manager, the Secret Service), namespaced `<identifier>.eloxiv-host` as the Tauri host does. Only a secret that is not there reads as absent; a store that fails (locked, no Secret Service) is an error. The person's session is not here: the daemon keeps it.\n\n## Updates\n\n- **Keys and releases** (`crates/eloxiv-update`, from `desktop-rune/`):\n\n ```sh\n cargo run -p eloxiv-update -- keygen --out keys/ # keys/update.key (secret), keys/update.pub; prints the public key for app.json\n cargo run -p eloxiv-update -- pack <install dir> dist/app-1.2.0.tar.gz # the archive kind\n ELOXIV_UPDATE_SECRET_KEY=\"$(cat keys/update.key)\" cargo run -p eloxiv-update -- release --config app.json \\\n --artifact linux-x86_64:appimage:dist/Acme_1.2.0_x86_64.AppImage --out dist/linux-x86_64-appimage.json\n ```\n\n `--config app.json` takes the app (`identifier`), the version and the channel (`updates.channel`) from the same file the host was built from; `--app`, `--version` and `--channel` override them. `ELOXIV_UPDATE_KEY_PASSWORD` encrypts (keygen) and opens (release) the secret key; unset, the key is unencrypted, and keygen says so. Each artifact is signed with minisign (Ed25519, prehashed) under the trusted comment `eloxiv-update app=<id> channel=<c> version=<v> platform=<p> kind=<k>`; `release` writes `<artifact>.minisig` and the manifest (`version`, `app` and `channel` (both required), `notes`, and per `<platform>-<kind>` the `url`, relative to the manifest, its `size` and its `signature`), adding to an existing manifest of the same release (one platform per CI runner). Upload the artifacts and the manifest where `updates.url` points.\n\n- **Checking**: once the window is interactive, and on the person's request, off the UI thread. The manifest must be HTTPS (plain HTTP on loopback only; every redirect is held to the same rule, so an HTTPS host cannot hand it to plain HTTP), for this app and channel, and newer than this build (semver: never a downgrade); its entry is this platform's (`linux-x86_64`, `macos-aarch64`, `windows-x86_64`) and this install's kind: an `appimage` (`$APPIMAGE`), an `archive` (a macOS `.app` bundle's contents, or a Linux install directory dedicated to the app: the sidecar beside the executable and a `.eloxiv-install` file reading `app=<identifier>`, which the update's archive must carry too; a folder without it, such as `~/bin` the app was unpacked into, is never replaced and reports updates unsupported), an `installer` (Windows: `.msi` or NSIS `.exe`).\n- **Downloading** stages the build beside the install (the same filesystem), exactly the manifest's size (an interrupted or overlong download is refused and leaves nothing), verified against `publicKey` (another key, changed bytes, a missing or legacy signature, or a trusted comment naming another app, version, platform or kind is refused), an archive unpacked and checked to contain the executable; then the staged build is asked its version (`<exe> --print-version`, the version compiled in from its `app.json`), which must be the signed one, so a build whose `app.json` says another version is refused instead of being offered the same update again after it starts (an installer, which cannot be asked, is checked by its signature only).\n- **Applying**: \"Restart to update\" closes the window; once the sidecar stopped (Rune's `fast_exit` hook: nothing after its loop runs), the install is renamed aside, the staged build renamed into place, the single instance released, and the new build started with `ELOXIV_UPDATE_TRIAL`. It writes that marker once it is interactive (its window drawn, its daemon answering); within `ELOXIV_UPDATE_TRIAL_SECONDS` (60) the old build is removed and the window says \"Updated from … to …\". A build that exits or hangs is stopped, the old one renamed back and started again, and its window says why; the version that failed is remembered (`update-failed-version` in the host's data directory) and not offered again until a newer one is published. While an update is applied a journal (`.<install>.eloxiv-apply`: the applying process, the versions) sits beside the install; if that process dies before the outcome is known (killed between the renames or during the trial, the session ended), the next start restores the previous build from its backup, remembers the version as failed and starts the restored build. An AppImage is replaced by a single rename, so its path is never empty. Windows downloads the installer into a new folder of its own under the temporary directory (named at random), verifies it again against the signature right before it runs it, and starts it directly, each argument its own: an NSIS `.exe` with `/S /R` (silent, it closes the app and starts it again when done), an `.msi` with `msiexec /i <file> /passive` (the person starts the app again); rolling back there is the installer's own.\n- **Unsupported**, with the reason shown in the window: no update host configured, a development build (no packaged sidecar beside the executable), a system package (`.deb`: update it with the package manager, or use the AppImage), or an install the person cannot replace.\n\n## Tests\n\n`cargo test` runs everything headless with Rune's `Runtime` (no window, no GPU) against a fake `/client/v1` (`app/tests/support`: HTTP and a chunked SSE stream):\n\n- `screens`: sign-in through the system browser, the live list, an optimistic write confirmed, a refused one shown then rolled back with `Forbidden`, an organisation switch showing no row of the old one (late events of its generation included), sign-out (the connection status gone with the session), a dropped stream reopened, a wrong token refused;\n- `make_view`: every tag with its role, fields by name per form, watched fields, typed values kept, calls only for listed actions and their results, steps one at a time, malformed, oversized and too-deep trees, a version no longer installed, late answers after a switch, `class` inert and the style subset, no URL opened;\n- `chat`: an agent turn (the send under its key, the run followed, the consent prompt allowed under the decision's key, streamed text replaced by the stored answer), the engine not set up holding the send but not the draft (and sending once a model is set up meanwhile), approval prompts decided under their keys, a lost send resent under its key (a refused retry keeping it unconfirmed under that key; after an organisation switch and back, and after a restart, from the outstanding store; an answer after its organisation was left still settling it), a send made in one organisation never run in the next, a restored send waiting for the session of a new context (another client's switch, its `context` event before the session), a send another host sharing the data directory settled not resent under its key, no draft across a reset the daemon made, nothing of the conversation after an organisation switch (late run events of the old generation included);\n- `rtl_a11y`: right to left mirroring the window (the chat's composer and prompts too), a view's physical sides, light and dark, every control named on every screen;\n- `links`: links opening their screens (the MAKE screen with the module filled in and no action run until Open is pressed, greetings in the organisation the link names, an organisation the person is not in ignored, a view with no screen here), links that are not the app's refused with no request made, a link waiting for the views and for sign-in; the window showing why updates are unavailable;\n- `single_instance` (Linux, with a display; `ELOXIV_RUNE_WINDOW_TESTS=1` requires one): the real binary twice, the second launch handing its link to the first and exiting at once, the first opening its screen;\n- the library's own tests: `parseLink`'s port against the View kit's shell fixture, the per-OS scheme registration builders and when the host registers at all, `app.json` and its overrides, the sidecar's port and state directory, the keychain's rules and a real round trip through the OS store where one answers (`ELOXIV_REQUIRE_KEYCHAIN=1` requires it), and the update apply step with scripts standing in for builds (one that starts kept, one that exits or hangs rolled back and the old one started again, an AppImage swapped as a file, never a downgrade, a failed version not offered again until a newer one);\n- `crates/eloxiv-update`: the updater against a local update server: a good update, bad signatures (another key, changed bytes, unsigned, undecodable, a validly signed older build replayed under a newer version), downgrades, interrupted and overlong downloads, an unreachable or broken manifest, an encrypted key;\n- `journey` (skipped without `ELOXIV_JOURNEY_DAEMON_URL`): the same app against a real daemon, kernel and zero-cache a runner started; see its header for the variables and checks.\n\n## Not done here\n\nPush and file pickers ([Host](../../../docs/contracts/host.md) capabilities this host reports unsupported). On macOS and Windows the installers are built, installed and launched by CI, and the scheme registration, single instance, keychain and update apply steps are unit-tested there, but a deep link and an update into an installed copy have been shown on Linux only. Window-level tests beyond the single-instance hand-over (the screens' tests drive Rune's Runtime, not OS input).\n",
18
+ "type": "registry:file",
19
+ "target": "desktop-rune/README.md"
20
+ },
21
+ {
22
+ "path": "app/desktop-rune/.gitignore",
23
+ "content": "/target/\n",
24
+ "type": "registry:file",
25
+ "target": "desktop-rune/.gitignore"
26
+ },
27
+ {
28
+ "path": "app/desktop-rune/Cargo.toml",
29
+ "content": "# The Rune desktop host's own workspace: the app (`app/`) and the LocalClient v1 protocol crate\n# (`crates/eloxiv-local-client`). It is the consumer workspace root Rune asks for: Cargo applies\n# `[patch.crates-io]` only from the root, never from a dependency, so the five patches Rune's own root\n# carries at the pinned revision are repeated here. When Rune is bumped, take its root Cargo.toml at the\n# new revision and use that same rev for `rune`, `rune-kit` and every patch.\n[workspace]\nresolver = \"3\"\nmembers = [\n \"app\",\n \"crates/eloxiv-local-client\",\n \"crates/eloxiv-local-client-codegen\",\n \"crates/eloxiv-mac-notifications\",\n \"crates/eloxiv-update\",\n]\n\n[workspace.package]\nedition = \"2024\"\nrust-version = \"1.97\"\nlicense = \"MIT\"\npublish = false\n\n[workspace.dependencies]\nrune = { git = \"https://github.com/anomalyco/rune\", rev = \"eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\" }\neloxiv-local-client = { path = \"crates/eloxiv-local-client\" }\nserde = { version = \"1.0.200\", features = [\"derive\"] }\nserde_json = \"1.0.120\"\nureq = { version = \"3\", default-features = false, features = [\"json\"] }\n\n[patch.crates-io]\nwinit = { git = \"https://github.com/anomalyco/rune\", rev = \"eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\" }\nparley_engine = { git = \"https://github.com/anomalyco/rune\", rev = \"eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\" }\nwgpu-hal = { git = \"https://github.com/anomalyco/rune\", rev = \"eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\" }\naccesskit_windows = { git = \"https://github.com/anomalyco/rune\", rev = \"eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\" }\naccesskit_macos = { git = \"https://github.com/anomalyco/rune\", rev = \"eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\" }\n\n# Rune's own settings: full debug info for a Rune test build used 18-23 GB of RAM; line tables keep\n# backtraces and file:line in panics at a fraction of that, and dependencies carry none.\n[profile.dev]\ndebug = \"line-tables-only\"\n\n[profile.dev.package.\"*\"]\ndebug = false\n\n[profile.release]\ncodegen-units = 16\nstrip = true\n\n[workspace.lints.rust]\nunsafe_code = \"forbid\"\nunused_must_use = \"deny\"\n\n[workspace.lints.clippy]\ndbg_macro = \"deny\"\ntodo = \"deny\"\nunwrap_used = \"warn\"\n",
30
+ "type": "registry:file",
31
+ "target": "desktop-rune/Cargo.toml"
32
+ },
33
+ {
34
+ "path": "app/desktop-rune/Cargo.lock",
35
+ "content": "# This file is automatically @generated by Cargo.\n# It is not intended for manual editing.\nversion = 4\n\n[[package]]\nname = \"accesskit\"\nversion = \"0.25.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"4e883d1d28c5fd5568c79ed2d2bd48d9f2fd3945c8974ed0f53690ceddb051be\"\ndependencies = [\n \"uuid\",\n]\n\n[[package]]\nname = \"accesskit_atspi_common\"\nversion = \"0.21.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"24f5baf62e34a4a6c30e3d697e4782f821a7337049c44c3b40576a27dfbb580d\"\ndependencies = [\n \"accesskit\",\n \"accesskit_consumer\",\n \"atspi-common\",\n \"phf\",\n \"serde\",\n \"zvariant\",\n]\n\n[[package]]\nname = \"accesskit_consumer\"\nversion = \"0.39.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f3da8f27636015191b2264ee1df681503170a632cafd832fdc1edfdd4e3a2fd3\"\ndependencies = [\n \"accesskit\",\n \"hashbrown 0.17.1\",\n]\n\n[[package]]\nname = \"accesskit_macos\"\nversion = \"0.27.2\"\nsource = \"git+https://github.com/anomalyco/rune?rev=eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90#eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\"\ndependencies = [\n \"accesskit\",\n \"accesskit_consumer\",\n \"hashbrown 0.17.1\",\n \"objc2 0.5.3\",\n \"objc2-app-kit 0.2.2\",\n \"objc2-foundation 0.2.2\",\n]\n\n[[package]]\nname = \"accesskit_unix\"\nversion = \"0.24.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"30d5192871228c54f1b0fb4a85cef000e11a3804f25d2165f14afa0daa67f3f6\"\ndependencies = [\n \"accesskit\",\n \"accesskit_atspi_common\",\n \"async-channel\",\n \"async-executor\",\n \"async-task\",\n \"atspi\",\n \"futures-lite\",\n \"futures-util\",\n \"serde\",\n \"zbus 5.19.0\",\n]\n\n[[package]]\nname = \"accesskit_windows\"\nversion = \"0.35.2\"\nsource = \"git+https://github.com/anomalyco/rune?rev=eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90#eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\"\ndependencies = [\n \"accesskit\",\n \"accesskit_consumer\",\n \"hashbrown 0.17.1\",\n \"static_assertions\",\n \"windows\",\n \"windows-core\",\n]\n\n[[package]]\nname = \"adler2\"\nversion = \"2.0.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa\"\n\n[[package]]\nname = \"aes\"\nversion = \"0.9.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1\"\ndependencies = [\n \"cipher 0.5.2\",\n \"cpubits\",\n \"cpufeatures 0.3.1\",\n]\n\n[[package]]\nname = \"ahash\"\nversion = \"0.8.12\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75\"\ndependencies = [\n \"cfg-if\",\n \"getrandom 0.3.4\",\n \"once_cell\",\n \"version_check\",\n \"zerocopy\",\n]\n\n[[package]]\nname = \"aho-corasick\"\nversion = \"1.1.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba\"\ndependencies = [\n \"memchr\",\n]\n\n[[package]]\nname = \"allocator-api2\"\nversion = \"0.2.21\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923\"\n\n[[package]]\nname = \"android-activity\"\nversion = \"0.6.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd\"\ndependencies = [\n \"android-properties\",\n \"bitflags 2.13.2\",\n \"cc\",\n \"jni\",\n \"libc\",\n \"log\",\n \"ndk\",\n \"ndk-context\",\n \"ndk-sys\",\n \"num_enum\",\n \"thiserror 2.0.21\",\n]\n\n[[package]]\nname = \"android-properties\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04\"\n\n[[package]]\nname = \"android_system_properties\"\nversion = \"0.1.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc\"\ndependencies = [\n \"libc\",\n]\n\n[[package]]\nname = \"apple-native-keyring-store\"\nversion = \"1.0.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"2b350bfd03649e07aa05c0a81b3e15934374e585c98204a57e20b9d49f49bb9a\"\ndependencies = [\n \"keyring-core\",\n \"log\",\n \"security-framework\",\n]\n\n[[package]]\nname = \"arboard\"\nversion = \"3.7.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917\"\ndependencies = [\n \"clipboard-win\",\n \"image\",\n \"log\",\n \"objc2 0.6.5\",\n \"objc2-app-kit 0.3.2\",\n \"objc2-core-foundation\",\n \"objc2-core-graphics\",\n \"objc2-foundation 0.3.2\",\n \"parking_lot\",\n \"percent-encoding\",\n \"windows-sys 0.61.2\",\n \"wl-clipboard-rs\",\n \"x11rb\",\n]\n\n[[package]]\nname = \"arrayref\"\nversion = \"0.3.9\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb\"\n\n[[package]]\nname = \"arrayvec\"\nversion = \"0.7.8\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56\"\n\n[[package]]\nname = \"as-raw-xcb-connection\"\nversion = \"1.0.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b\"\n\n[[package]]\nname = \"ash\"\nversion = \"0.38.0+1.3.281\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f\"\ndependencies = [\n \"libloading\",\n]\n\n[[package]]\nname = \"async-broadcast\"\nversion = \"0.7.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532\"\ndependencies = [\n \"event-listener\",\n \"event-listener-strategy\",\n \"futures-core\",\n \"pin-project-lite\",\n]\n\n[[package]]\nname = \"async-channel\"\nversion = \"2.5.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2\"\ndependencies = [\n \"concurrent-queue\",\n \"event-listener-strategy\",\n \"futures-core\",\n \"pin-project-lite\",\n]\n\n[[package]]\nname = \"async-executor\"\nversion = \"1.14.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37\"\ndependencies = [\n \"async-task\",\n \"concurrent-queue\",\n \"fastrand\",\n \"futures-lite\",\n \"pin-project-lite\",\n \"slab\",\n]\n\n[[package]]\nname = \"async-io\"\nversion = \"2.6.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc\"\ndependencies = [\n \"autocfg\",\n \"cfg-if\",\n \"concurrent-queue\",\n \"futures-io\",\n \"futures-lite\",\n \"parking\",\n \"polling\",\n \"rustix 1.1.6\",\n \"slab\",\n \"windows-sys 0.61.2\",\n]\n\n[[package]]\nname = \"async-lock\"\nversion = \"3.5.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f\"\ndependencies = [\n \"event-listener\",\n \"event-listener-strategy\",\n \"pin-project-lite\",\n]\n\n[[package]]\nname = \"async-process\"\nversion = \"2.5.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75\"\ndependencies = [\n \"async-channel\",\n \"async-io\",\n \"async-lock\",\n \"async-signal\",\n \"async-task\",\n \"blocking\",\n \"cfg-if\",\n \"event-listener\",\n \"futures-lite\",\n \"rustix 1.1.6\",\n]\n\n[[package]]\nname = \"async-recursion\"\nversion = \"1.2.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n]\n\n[[package]]\nname = \"async-signal\"\nversion = \"0.2.14\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485\"\ndependencies = [\n \"async-io\",\n \"async-lock\",\n \"atomic-waker\",\n \"cfg-if\",\n \"futures-core\",\n \"futures-io\",\n \"rustix 1.1.6\",\n \"signal-hook-registry\",\n \"slab\",\n \"windows-sys 0.61.2\",\n]\n\n[[package]]\nname = \"async-task\"\nversion = \"4.7.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de\"\n\n[[package]]\nname = \"async-trait\"\nversion = \"0.1.92\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n]\n\n[[package]]\nname = \"atomic-waker\"\nversion = \"1.1.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0\"\n\n[[package]]\nname = \"atspi\"\nversion = \"0.29.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c77886257be21c9cd89a4ae7e64860c6f0eefca799bb79127913052bd0eefb3d\"\ndependencies = [\n \"atspi-common\",\n \"atspi-proxies\",\n]\n\n[[package]]\nname = \"atspi-common\"\nversion = \"0.13.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"20c5617155740c98003016429ad13fe43ce7a77b007479350a9f8bf95a29f63d\"\ndependencies = [\n \"enumflags2\",\n \"serde\",\n \"static_assertions\",\n \"zbus 5.19.0\",\n \"zbus-lockstep\",\n \"zbus-lockstep-macros\",\n \"zbus_names\",\n \"zvariant\",\n]\n\n[[package]]\nname = \"atspi-proxies\"\nversion = \"0.13.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc\"\ndependencies = [\n \"atspi-common\",\n \"serde\",\n \"zbus 5.19.0\",\n]\n\n[[package]]\nname = \"autocfg\"\nversion = \"1.5.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53\"\n\n[[package]]\nname = \"base64\"\nversion = \"0.22.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6\"\n\n[[package]]\nname = \"base64\"\nversion = \"0.23.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5\"\n\n[[package]]\nname = \"bit-set\"\nversion = \"0.10.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d\"\ndependencies = [\n \"bit-vec\",\n]\n\n[[package]]\nname = \"bit-vec\"\nversion = \"0.9.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51\"\n\n[[package]]\nname = \"bitflags\"\nversion = \"1.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a\"\n\n[[package]]\nname = \"bitflags\"\nversion = \"2.13.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06\"\n\n[[package]]\nname = \"blake3\"\nversion = \"1.8.7\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae\"\ndependencies = [\n \"arrayvec\",\n \"cc\",\n \"cfg-if\",\n \"constant_time_eq\",\n \"cpufeatures 0.3.1\",\n]\n\n[[package]]\nname = \"block-buffer\"\nversion = \"0.10.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71\"\ndependencies = [\n \"generic-array\",\n]\n\n[[package]]\nname = \"block-buffer\"\nversion = \"0.12.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa\"\ndependencies = [\n \"hybrid-array\",\n]\n\n[[package]]\nname = \"block-padding\"\nversion = \"0.4.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b\"\ndependencies = [\n \"hybrid-array\",\n]\n\n[[package]]\nname = \"block2\"\nversion = \"0.5.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f\"\ndependencies = [\n \"objc2 0.5.3\",\n]\n\n[[package]]\nname = \"block2\"\nversion = \"0.6.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5\"\ndependencies = [\n \"objc2 0.6.5\",\n]\n\n[[package]]\nname = \"blocking\"\nversion = \"1.7.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa\"\ndependencies = [\n \"async-channel\",\n \"async-task\",\n \"futures-io\",\n \"futures-lite\",\n \"piper\",\n]\n\n[[package]]\nname = \"bumpalo\"\nversion = \"3.20.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db\"\n\n[[package]]\nname = \"bytemuck\"\nversion = \"1.25.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797\"\ndependencies = [\n \"bytemuck_derive\",\n]\n\n[[package]]\nname = \"bytemuck_derive\"\nversion = \"1.12.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n]\n\n[[package]]\nname = \"byteorder\"\nversion = \"1.5.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b\"\n\n[[package]]\nname = \"byteorder-lite\"\nversion = \"0.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495\"\n\n[[package]]\nname = \"bytes\"\nversion = \"1.12.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04\"\n\n[[package]]\nname = \"calloop\"\nversion = \"0.13.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"log\",\n \"polling\",\n \"rustix 0.38.44\",\n \"slab\",\n \"thiserror 1.0.69\",\n]\n\n[[package]]\nname = \"calloop-wayland-source\"\nversion = \"0.3.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20\"\ndependencies = [\n \"calloop\",\n \"rustix 0.38.44\",\n \"wayland-backend\",\n \"wayland-client\",\n]\n\n[[package]]\nname = \"cbc\"\nversion = \"0.2.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896\"\ndependencies = [\n \"cipher 0.5.2\",\n]\n\n[[package]]\nname = \"cc\"\nversion = \"1.11.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45\"\ndependencies = [\n \"find-msvc-tools\",\n \"jobserver\",\n \"libc\",\n \"shlex\",\n]\n\n[[package]]\nname = \"cfg-if\"\nversion = \"1.0.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600\"\n\n[[package]]\nname = \"cfg_aliases\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527\"\n\n[[package]]\nname = \"cipher\"\nversion = \"0.4.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad\"\ndependencies = [\n \"crypto-common 0.1.7\",\n \"inout 0.1.4\",\n]\n\n[[package]]\nname = \"cipher\"\nversion = \"0.5.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c\"\ndependencies = [\n \"crypto-common 0.2.2\",\n \"inout 0.2.6\",\n]\n\n[[package]]\nname = \"clipboard-win\"\nversion = \"5.4.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a\"\ndependencies = [\n \"error-code\",\n]\n\n[[package]]\nname = \"cmov\"\nversion = \"0.5.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a\"\n\n[[package]]\nname = \"codespace\"\nversion = \"0.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5ad2220b174fd87f25c53717f0cfd18eb43b9cb69c67ca43176d3e9c50865a08\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"semver\",\n \"syn 3.0.10\",\n \"version-ranges\",\n]\n\n[[package]]\nname = \"codespan-reporting\"\nversion = \"0.13.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681\"\ndependencies = [\n \"serde\",\n \"termcolor\",\n \"unicode-width\",\n]\n\n[[package]]\nname = \"color_quant\"\nversion = \"1.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b\"\n\n[[package]]\nname = \"combine\"\nversion = \"4.6.9\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92\"\ndependencies = [\n \"bytes\",\n \"memchr\",\n]\n\n[[package]]\nname = \"concurrent-queue\"\nversion = \"2.5.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973\"\ndependencies = [\n \"crossbeam-utils\",\n]\n\n[[package]]\nname = \"console_error_panic_hook\"\nversion = \"0.1.7\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc\"\ndependencies = [\n \"cfg-if\",\n \"wasm-bindgen\",\n]\n\n[[package]]\nname = \"const-oid\"\nversion = \"0.10.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a\"\n\n[[package]]\nname = \"constant_time_eq\"\nversion = \"0.4.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b\"\n\n[[package]]\nname = \"cookie\"\nversion = \"0.18.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87\"\ndependencies = [\n \"percent-encoding\",\n \"time\",\n \"version_check\",\n]\n\n[[package]]\nname = \"cookie_store\"\nversion = \"0.22.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206\"\ndependencies = [\n \"cookie\",\n \"document-features\",\n \"idna\",\n \"indexmap\",\n \"log\",\n \"serde\",\n \"serde_derive\",\n \"serde_json\",\n \"time\",\n \"url\",\n]\n\n[[package]]\nname = \"core-foundation\"\nversion = \"0.9.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f\"\ndependencies = [\n \"core-foundation-sys\",\n \"libc\",\n]\n\n[[package]]\nname = \"core-foundation\"\nversion = \"0.10.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6\"\ndependencies = [\n \"core-foundation-sys\",\n \"libc\",\n]\n\n[[package]]\nname = \"core-foundation-sys\"\nversion = \"0.8.7\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b\"\n\n[[package]]\nname = \"core-graphics\"\nversion = \"0.23.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081\"\ndependencies = [\n \"bitflags 1.3.2\",\n \"core-foundation 0.9.4\",\n \"core-graphics-types\",\n \"foreign-types\",\n \"libc\",\n]\n\n[[package]]\nname = \"core-graphics-types\"\nversion = \"0.1.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf\"\ndependencies = [\n \"bitflags 1.3.2\",\n \"core-foundation 0.9.4\",\n \"libc\",\n]\n\n[[package]]\nname = \"core_detect\"\nversion = \"1.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48\"\n\n[[package]]\nname = \"cpubits\"\nversion = \"0.1.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae\"\n\n[[package]]\nname = \"cpufeatures\"\nversion = \"0.2.17\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280\"\ndependencies = [\n \"libc\",\n]\n\n[[package]]\nname = \"cpufeatures\"\nversion = \"0.3.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566\"\ndependencies = [\n \"libc\",\n]\n\n[[package]]\nname = \"crc32fast\"\nversion = \"1.5.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64\"\ndependencies = [\n \"cfg-if\",\n]\n\n[[package]]\nname = \"crossbeam-utils\"\nversion = \"0.8.23\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6\"\n\n[[package]]\nname = \"crunchy\"\nversion = \"0.2.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5\"\n\n[[package]]\nname = \"crypto-common\"\nversion = \"0.1.7\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a\"\ndependencies = [\n \"generic-array\",\n \"typenum\",\n]\n\n[[package]]\nname = \"crypto-common\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453\"\ndependencies = [\n \"hybrid-array\",\n]\n\n[[package]]\nname = \"ct-codecs\"\nversion = \"1.1.8\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"8fd9f3db6f2cfef61c10613071955154ffdc9e515daebff26de4b54e35038fdd\"\n\n[[package]]\nname = \"ctutils\"\nversion = \"0.4.8\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f\"\ndependencies = [\n \"cmov\",\n]\n\n[[package]]\nname = \"cursor-icon\"\nversion = \"1.2.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f\"\n\n[[package]]\nname = \"data-url\"\nversion = \"0.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376\"\n\n[[package]]\nname = \"deranged\"\nversion = \"0.5.9\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e\"\n\n[[package]]\nname = \"digest\"\nversion = \"0.10.7\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292\"\ndependencies = [\n \"block-buffer 0.10.4\",\n \"crypto-common 0.1.7\",\n \"subtle\",\n]\n\n[[package]]\nname = \"digest\"\nversion = \"0.11.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2\"\ndependencies = [\n \"block-buffer 0.12.1\",\n \"const-oid\",\n \"crypto-common 0.2.2\",\n \"ctutils\",\n]\n\n[[package]]\nname = \"dispatch\"\nversion = \"0.2.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b\"\n\n[[package]]\nname = \"dispatch2\"\nversion = \"0.3.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"objc2 0.6.5\",\n]\n\n[[package]]\nname = \"displaydoc\"\nversion = \"0.2.7\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n]\n\n[[package]]\nname = \"dlib\"\nversion = \"0.5.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a\"\ndependencies = [\n \"libloading\",\n]\n\n[[package]]\nname = \"document-features\"\nversion = \"0.2.12\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61\"\ndependencies = [\n \"litrs\",\n]\n\n[[package]]\nname = \"downcast-rs\"\nversion = \"1.2.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2\"\n\n[[package]]\nname = \"dpi\"\nversion = \"0.1.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76\"\n\n[[package]]\nname = \"dyn-clone\"\nversion = \"1.0.20\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555\"\n\n[[package]]\nname = \"eloxiv-desktop-rune\"\nversion = \"0.1.0\"\ndependencies = [\n \"eloxiv-local-client\",\n \"eloxiv-mac-notifications\",\n \"eloxiv-update\",\n \"getrandom 0.3.4\",\n \"keyring\",\n \"rune\",\n \"rune-notify\",\n \"semver\",\n \"serde\",\n \"serde_json\",\n \"ureq\",\n \"url\",\n \"windows\",\n \"winreg\",\n \"zbus 5.19.0\",\n]\n\n[[package]]\nname = \"eloxiv-local-client\"\nversion = \"0.1.0\"\ndependencies = [\n \"serde\",\n \"serde_json\",\n \"ureq\",\n]\n\n[[package]]\nname = \"eloxiv-local-client-codegen\"\nversion = \"0.1.0\"\ndependencies = [\n \"prettyplease\",\n \"schemars\",\n \"serde_json\",\n \"syn 2.0.119\",\n \"typify\",\n]\n\n[[package]]\nname = \"eloxiv-mac-notifications\"\nversion = \"0.1.0\"\ndependencies = [\n \"block2 0.5.1\",\n \"objc2 0.5.3\",\n]\n\n[[package]]\nname = \"eloxiv-update\"\nversion = \"0.1.0\"\ndependencies = [\n \"flate2\",\n \"minisign\",\n \"semver\",\n \"serde\",\n \"serde_json\",\n \"tar\",\n \"ureq\",\n \"url\",\n]\n\n[[package]]\nname = \"encoding_rs\"\nversion = \"0.8.44\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5\"\ndependencies = [\n \"cfg-if\",\n \"core_detect\",\n \"multiversion_no_op\",\n \"rustversion\",\n \"scopeguard\",\n \"simdutf8\",\n]\n\n[[package]]\nname = \"endi\"\nversion = \"1.1.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099\"\n\n[[package]]\nname = \"enumflags2\"\nversion = \"0.7.12\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef\"\ndependencies = [\n \"enumflags2_derive\",\n \"serde\",\n]\n\n[[package]]\nname = \"enumflags2_derive\"\nversion = \"0.7.12\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 2.0.119\",\n]\n\n[[package]]\nname = \"equivalent\"\nversion = \"1.0.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826\"\n\n[[package]]\nname = \"errno\"\nversion = \"0.3.15\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776\"\ndependencies = [\n \"libc\",\n \"windows-sys 0.61.2\",\n]\n\n[[package]]\nname = \"error-code\"\nversion = \"3.4.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7\"\n\n[[package]]\nname = \"euclid\"\nversion = \"0.22.14\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06\"\ndependencies = [\n \"num-traits\",\n]\n\n[[package]]\nname = \"event-listener\"\nversion = \"5.4.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2\"\ndependencies = [\n \"parking\",\n \"pin-project-lite\",\n]\n\n[[package]]\nname = \"event-listener-strategy\"\nversion = \"0.5.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93\"\ndependencies = [\n \"event-listener\",\n \"pin-project-lite\",\n]\n\n[[package]]\nname = \"fastrand\"\nversion = \"2.5.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223\"\n\n[[package]]\nname = \"fax\"\nversion = \"0.2.7\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a\"\n\n[[package]]\nname = \"fdeflate\"\nversion = \"0.3.7\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c\"\ndependencies = [\n \"simd-adler32\",\n]\n\n[[package]]\nname = \"filetime\"\nversion = \"0.2.30\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7\"\ndependencies = [\n \"cfg-if\",\n \"libc\",\n]\n\n[[package]]\nname = \"find-msvc-tools\"\nversion = \"0.1.15\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48\"\n\n[[package]]\nname = \"fixedbitset\"\nversion = \"0.5.9\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175\"\n\n[[package]]\nname = \"flate2\"\nversion = \"1.1.11\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4\"\ndependencies = [\n \"crc32fast\",\n \"miniz_oxide 0.9.1\",\n \"zlib-rs\",\n]\n\n[[package]]\nname = \"float-cmp\"\nversion = \"0.9.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4\"\n\n[[package]]\nname = \"foldhash\"\nversion = \"0.1.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2\"\n\n[[package]]\nname = \"foldhash\"\nversion = \"0.2.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb\"\n\n[[package]]\nname = \"font-types\"\nversion = \"0.12.7\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d\"\ndependencies = [\n \"bytemuck\",\n]\n\n[[package]]\nname = \"fontique\"\nversion = \"0.12.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"bbf1df16263783918b7da396077521f92b729ef7c429444dfcf03581f1448b77\"\ndependencies = [\n \"hashbrown 0.17.1\",\n \"linebender_resource_handle\",\n \"memmap2\",\n \"objc2 0.6.5\",\n \"objc2-core-foundation\",\n \"objc2-core-text\",\n \"objc2-foundation 0.3.2\",\n \"parlance\",\n \"read-fonts\",\n \"roxmltree 0.21.2\",\n \"smallvec\",\n \"windows\",\n \"windows-core\",\n \"yeslogic-fontconfig-sys\",\n]\n\n[[package]]\nname = \"foreign-types\"\nversion = \"0.5.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965\"\ndependencies = [\n \"foreign-types-macros\",\n \"foreign-types-shared\",\n]\n\n[[package]]\nname = \"foreign-types-macros\"\nversion = \"0.2.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n]\n\n[[package]]\nname = \"foreign-types-shared\"\nversion = \"0.3.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b\"\n\n[[package]]\nname = \"form_urlencoded\"\nversion = \"1.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf\"\ndependencies = [\n \"percent-encoding\",\n]\n\n[[package]]\nname = \"futures-core\"\nversion = \"0.3.34\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e\"\n\n[[package]]\nname = \"futures-io\"\nversion = \"0.3.34\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed\"\n\n[[package]]\nname = \"futures-lite\"\nversion = \"2.6.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad\"\ndependencies = [\n \"fastrand\",\n \"futures-core\",\n \"futures-io\",\n \"parking\",\n \"pin-project-lite\",\n]\n\n[[package]]\nname = \"futures-macro\"\nversion = \"0.3.34\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n]\n\n[[package]]\nname = \"futures-task\"\nversion = \"0.3.34\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd\"\n\n[[package]]\nname = \"futures-util\"\nversion = \"0.3.34\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc\"\ndependencies = [\n \"futures-core\",\n \"futures-macro\",\n \"futures-task\",\n \"pin-project-lite\",\n \"slab\",\n]\n\n[[package]]\nname = \"generic-array\"\nversion = \"0.14.7\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a\"\ndependencies = [\n \"typenum\",\n \"version_check\",\n]\n\n[[package]]\nname = \"gethostname\"\nversion = \"1.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8\"\ndependencies = [\n \"rustix 1.1.6\",\n \"windows-link\",\n]\n\n[[package]]\nname = \"getrandom\"\nversion = \"0.2.17\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0\"\ndependencies = [\n \"cfg-if\",\n \"js-sys\",\n \"libc\",\n \"wasi\",\n \"wasm-bindgen\",\n]\n\n[[package]]\nname = \"getrandom\"\nversion = \"0.3.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd\"\ndependencies = [\n \"cfg-if\",\n \"libc\",\n \"r-efi 5.3.0\",\n \"wasip2\",\n]\n\n[[package]]\nname = \"getrandom\"\nversion = \"0.4.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099\"\ndependencies = [\n \"cfg-if\",\n \"libc\",\n \"r-efi 6.0.0\",\n]\n\n[[package]]\nname = \"gif\"\nversion = \"0.14.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159\"\ndependencies = [\n \"color_quant\",\n \"weezl\",\n]\n\n[[package]]\nname = \"gpu-allocator\"\nversion = \"0.28.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795\"\ndependencies = [\n \"ash\",\n \"hashbrown 0.16.1\",\n \"log\",\n \"presser\",\n \"thiserror 2.0.21\",\n \"windows\",\n]\n\n[[package]]\nname = \"half\"\nversion = \"2.7.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b\"\ndependencies = [\n \"cfg-if\",\n \"crunchy\",\n \"num-traits\",\n \"zerocopy\",\n]\n\n[[package]]\nname = \"harfrust\"\nversion = \"0.12.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"bytemuck\",\n \"read-fonts\",\n \"smallvec\",\n]\n\n[[package]]\nname = \"hashbrown\"\nversion = \"0.15.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1\"\ndependencies = [\n \"foldhash 0.1.5\",\n]\n\n[[package]]\nname = \"hashbrown\"\nversion = \"0.16.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100\"\ndependencies = [\n \"allocator-api2\",\n \"equivalent\",\n \"foldhash 0.2.0\",\n]\n\n[[package]]\nname = \"hashbrown\"\nversion = \"0.17.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a\"\ndependencies = [\n \"foldhash 0.2.0\",\n]\n\n[[package]]\nname = \"heck\"\nversion = \"0.5.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea\"\n\n[[package]]\nname = \"hermit-abi\"\nversion = \"0.5.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284\"\n\n[[package]]\nname = \"hex\"\nversion = \"0.4.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70\"\n\n[[package]]\nname = \"hkdf\"\nversion = \"0.13.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018\"\ndependencies = [\n \"hmac 0.13.0\",\n]\n\n[[package]]\nname = \"hmac\"\nversion = \"0.12.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e\"\ndependencies = [\n \"digest 0.10.7\",\n]\n\n[[package]]\nname = \"hmac\"\nversion = \"0.13.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f\"\ndependencies = [\n \"digest 0.11.3\",\n]\n\n[[package]]\nname = \"http\"\nversion = \"1.5.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0\"\ndependencies = [\n \"bytes\",\n \"itoa\",\n]\n\n[[package]]\nname = \"httparse\"\nversion = \"1.10.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87\"\n\n[[package]]\nname = \"hybrid-array\"\nversion = \"0.4.15\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17\"\ndependencies = [\n \"typenum\",\n]\n\n[[package]]\nname = \"icu_collections\"\nversion = \"2.4.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd\"\ndependencies = [\n \"displaydoc\",\n \"potential_utf\",\n \"utf8_iter\",\n \"yoke\",\n \"zerofrom\",\n \"zerovec\",\n]\n\n[[package]]\nname = \"icu_locale_core\"\nversion = \"2.4.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0\"\ndependencies = [\n \"displaydoc\",\n \"litemap\",\n \"serde\",\n \"tinystr\",\n \"writeable\",\n \"zerovec\",\n]\n\n[[package]]\nname = \"icu_locale_fallback\"\nversion = \"2.4.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c\"\ndependencies = [\n \"icu_locale_core\",\n \"icu_locale_fallback_data\",\n \"icu_provider\",\n \"potential_utf\",\n \"tinystr\",\n \"zerovec\",\n]\n\n[[package]]\nname = \"icu_locale_fallback_data\"\nversion = \"2.4.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c\"\n\n[[package]]\nname = \"icu_normalizer\"\nversion = \"2.4.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599\"\ndependencies = [\n \"icu_collections\",\n \"icu_normalizer_data\",\n \"icu_properties\",\n \"icu_provider\",\n \"smallvec\",\n \"zerovec\",\n]\n\n[[package]]\nname = \"icu_normalizer_data\"\nversion = \"2.4.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc\"\n\n[[package]]\nname = \"icu_properties\"\nversion = \"2.4.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f\"\ndependencies = [\n \"displaydoc\",\n \"icu_collections\",\n \"icu_locale_core\",\n \"icu_properties_data\",\n \"icu_provider\",\n \"zerotrie\",\n \"zerovec\",\n]\n\n[[package]]\nname = \"icu_properties_data\"\nversion = \"2.4.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf\"\n\n[[package]]\nname = \"icu_provider\"\nversion = \"2.4.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514\"\ndependencies = [\n \"displaydoc\",\n \"icu_locale_core\",\n \"serde\",\n \"stable_deref_trait\",\n \"writeable\",\n \"yoke\",\n \"zerofrom\",\n \"zerotrie\",\n \"zerovec\",\n]\n\n[[package]]\nname = \"icu_segmenter\"\nversion = \"2.4.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"61b195dc605f81aa181bec9b3bd14e26cc71b903e4644f6af578ca9772c7a710\"\ndependencies = [\n \"icu_collections\",\n \"icu_locale_fallback\",\n \"icu_provider\",\n \"icu_segmenter_data\",\n \"potential_utf\",\n \"smallvec\",\n \"utf8_iter\",\n \"zerotrie\",\n \"zerovec\",\n]\n\n[[package]]\nname = \"icu_segmenter_data\"\nversion = \"2.4.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3\"\n\n[[package]]\nname = \"idna\"\nversion = \"1.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de\"\ndependencies = [\n \"idna_adapter\",\n \"smallvec\",\n \"utf8_iter\",\n]\n\n[[package]]\nname = \"idna_adapter\"\nversion = \"1.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714\"\ndependencies = [\n \"icu_normalizer\",\n \"icu_properties\",\n]\n\n[[package]]\nname = \"image\"\nversion = \"0.25.10\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104\"\ndependencies = [\n \"bytemuck\",\n \"byteorder-lite\",\n \"color_quant\",\n \"gif\",\n \"image-webp\",\n \"moxcms\",\n \"num-traits\",\n \"png 0.18.1\",\n \"tiff\",\n \"zune-core\",\n \"zune-jpeg\",\n]\n\n[[package]]\nname = \"image-webp\"\nversion = \"0.2.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3\"\ndependencies = [\n \"byteorder-lite\",\n \"quick-error\",\n]\n\n[[package]]\nname = \"imagesize\"\nversion = \"0.13.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285\"\n\n[[package]]\nname = \"indexmap\"\nversion = \"2.14.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855\"\ndependencies = [\n \"equivalent\",\n \"hashbrown 0.17.1\",\n]\n\n[[package]]\nname = \"inout\"\nversion = \"0.1.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01\"\ndependencies = [\n \"generic-array\",\n]\n\n[[package]]\nname = \"inout\"\nversion = \"0.2.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9\"\ndependencies = [\n \"block-padding\",\n \"hybrid-array\",\n]\n\n[[package]]\nname = \"itoa\"\nversion = \"1.0.19\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4\"\n\n[[package]]\nname = \"jni\"\nversion = \"0.22.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498\"\ndependencies = [\n \"cfg-if\",\n \"combine\",\n \"jni-macros\",\n \"jni-sys 0.4.1\",\n \"log\",\n \"simd_cesu8\",\n \"thiserror 2.0.21\",\n \"walkdir\",\n \"windows-link\",\n]\n\n[[package]]\nname = \"jni-macros\"\nversion = \"0.22.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"rustc_version\",\n \"simd_cesu8\",\n \"syn 2.0.119\",\n]\n\n[[package]]\nname = \"jni-sys\"\nversion = \"0.3.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258\"\ndependencies = [\n \"jni-sys 0.4.1\",\n]\n\n[[package]]\nname = \"jni-sys\"\nversion = \"0.4.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2\"\ndependencies = [\n \"jni-sys-macros\",\n]\n\n[[package]]\nname = \"jni-sys-macros\"\nversion = \"0.4.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264\"\ndependencies = [\n \"quote\",\n \"syn 2.0.119\",\n]\n\n[[package]]\nname = \"jobserver\"\nversion = \"0.1.35\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3\"\ndependencies = [\n \"getrandom 0.4.3\",\n \"libc\",\n]\n\n[[package]]\nname = \"js-sys\"\nversion = \"0.3.107\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a\"\ndependencies = [\n \"cfg-if\",\n \"futures-util\",\n \"wasm-bindgen\",\n]\n\n[[package]]\nname = \"keyring\"\nversion = \"4.2.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"2270074a3d26bcac93c1dc5d2845eb4c089e8d761ccf6e0ea266a16004640627\"\ndependencies = [\n \"apple-native-keyring-store\",\n \"keyring-core\",\n \"windows-native-keyring-store\",\n \"zbus-secret-service-keyring-store\",\n]\n\n[[package]]\nname = \"keyring-core\"\nversion = \"1.0.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"29fbf4b551298c67925f38cf341a1ada797a75f1837bdf8ae1fc8e2ebc6efb59\"\ndependencies = [\n \"log\",\n]\n\n[[package]]\nname = \"kurbo\"\nversion = \"0.11.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62\"\ndependencies = [\n \"arrayvec\",\n \"euclid\",\n \"smallvec\",\n]\n\n[[package]]\nname = \"lazy_static\"\nversion = \"1.5.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb\"\n\n[[package]]\nname = \"libc\"\nversion = \"0.2.191\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a\"\n\n[[package]]\nname = \"libloading\"\nversion = \"0.8.9\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55\"\ndependencies = [\n \"cfg-if\",\n \"windows-link\",\n]\n\n[[package]]\nname = \"libm\"\nversion = \"0.2.16\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981\"\n\n[[package]]\nname = \"libredox\"\nversion = \"0.1.25\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"libc\",\n \"plain\",\n \"redox_syscall 0.9.5\",\n]\n\n[[package]]\nname = \"linebender_resource_handle\"\nversion = \"0.1.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4\"\n\n[[package]]\nname = \"linux-raw-sys\"\nversion = \"0.4.15\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab\"\n\n[[package]]\nname = \"linux-raw-sys\"\nversion = \"0.12.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53\"\n\n[[package]]\nname = \"litemap\"\nversion = \"0.8.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae\"\n\n[[package]]\nname = \"litrs\"\nversion = \"1.0.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70\"\n\n[[package]]\nname = \"lock_api\"\nversion = \"0.4.14\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965\"\ndependencies = [\n \"scopeguard\",\n]\n\n[[package]]\nname = \"log\"\nversion = \"0.4.35\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c\"\n\n[[package]]\nname = \"memchr\"\nversion = \"2.8.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98\"\n\n[[package]]\nname = \"memmap2\"\nversion = \"0.9.12\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157\"\ndependencies = [\n \"libc\",\n]\n\n[[package]]\nname = \"memoffset\"\nversion = \"0.9.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a\"\ndependencies = [\n \"autocfg\",\n]\n\n[[package]]\nname = \"minisign\"\nversion = \"0.7.9\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"26541387415a1e829df5d532aad019fb11bc723e2b5bc99edefa4cf5bfad0de7\"\ndependencies = [\n \"ct-codecs\",\n \"getrandom 0.2.17\",\n \"rpassword\",\n \"scrypt\",\n]\n\n[[package]]\nname = \"miniz_oxide\"\nversion = \"0.8.9\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316\"\ndependencies = [\n \"adler2\",\n \"simd-adler32\",\n]\n\n[[package]]\nname = \"miniz_oxide\"\nversion = \"0.9.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c\"\ndependencies = [\n \"adler2\",\n \"simd-adler32\",\n]\n\n[[package]]\nname = \"mio\"\nversion = \"1.2.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a\"\ndependencies = [\n \"libc\",\n \"wasi\",\n \"windows-sys 0.61.2\",\n]\n\n[[package]]\nname = \"moxcms\"\nversion = \"0.8.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b\"\ndependencies = [\n \"num-traits\",\n \"pxfm\",\n]\n\n[[package]]\nname = \"multiversion_no_op\"\nversion = \"1.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d\"\n\n[[package]]\nname = \"naga\"\nversion = \"30.0.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"fd0dd362bf26c0ffdd143df6da66a25d287e196eff482f117771010b207ad163\"\ndependencies = [\n \"arrayvec\",\n \"bit-set\",\n \"bitflags 2.13.2\",\n \"cfg-if\",\n \"cfg_aliases\",\n \"codespan-reporting\",\n \"half\",\n \"hashbrown 0.17.1\",\n \"indexmap\",\n \"libm\",\n \"log\",\n \"naga-types\",\n \"num-traits\",\n \"once_cell\",\n \"rustc-hash 1.1.0\",\n \"spirv\",\n \"thiserror 2.0.21\",\n \"unicode-ident\",\n]\n\n[[package]]\nname = \"naga-types\"\nversion = \"30.0.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"14474170feb673cfb18b3565111a9869797cc1d290fb9ec969c53f5e1e231c6d\"\ndependencies = [\n \"hashbrown 0.17.1\",\n \"indexmap\",\n \"rustc-hash 1.1.0\",\n \"thiserror 2.0.21\",\n]\n\n[[package]]\nname = \"ndk\"\nversion = \"0.9.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"jni-sys 0.3.1\",\n \"log\",\n \"ndk-sys\",\n \"num_enum\",\n \"raw-window-handle\",\n \"thiserror 1.0.69\",\n]\n\n[[package]]\nname = \"ndk-context\"\nversion = \"0.1.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b\"\n\n[[package]]\nname = \"ndk-sys\"\nversion = \"0.6.0+11769913\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873\"\ndependencies = [\n \"jni-sys 0.3.1\",\n]\n\n[[package]]\nname = \"nom\"\nversion = \"8.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405\"\ndependencies = [\n \"memchr\",\n]\n\n[[package]]\nname = \"num\"\nversion = \"0.4.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23\"\ndependencies = [\n \"num-bigint\",\n \"num-complex\",\n \"num-integer\",\n \"num-iter\",\n \"num-rational\",\n \"num-traits\",\n]\n\n[[package]]\nname = \"num-bigint\"\nversion = \"0.4.8\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367\"\ndependencies = [\n \"num-integer\",\n \"num-traits\",\n]\n\n[[package]]\nname = \"num-complex\"\nversion = \"0.4.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495\"\ndependencies = [\n \"num-traits\",\n]\n\n[[package]]\nname = \"num-conv\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441\"\n\n[[package]]\nname = \"num-integer\"\nversion = \"0.1.47\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b\"\ndependencies = [\n \"num-traits\",\n]\n\n[[package]]\nname = \"num-iter\"\nversion = \"0.1.46\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b\"\ndependencies = [\n \"num-integer\",\n \"num-traits\",\n]\n\n[[package]]\nname = \"num-rational\"\nversion = \"0.4.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824\"\ndependencies = [\n \"num-bigint\",\n \"num-integer\",\n \"num-traits\",\n]\n\n[[package]]\nname = \"num-traits\"\nversion = \"0.2.19\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841\"\ndependencies = [\n \"autocfg\",\n \"libm\",\n]\n\n[[package]]\nname = \"num_enum\"\nversion = \"0.7.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26\"\ndependencies = [\n \"num_enum_derive\",\n \"rustversion\",\n]\n\n[[package]]\nname = \"num_enum_derive\"\nversion = \"0.7.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8\"\ndependencies = [\n \"proc-macro-crate\",\n \"proc-macro2\",\n \"quote\",\n \"syn 2.0.119\",\n]\n\n[[package]]\nname = \"objc-sys\"\nversion = \"0.3.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310\"\n\n[[package]]\nname = \"objc2\"\nversion = \"0.5.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b\"\ndependencies = [\n \"objc-sys\",\n \"objc2-encode\",\n]\n\n[[package]]\nname = \"objc2\"\nversion = \"0.6.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8\"\ndependencies = [\n \"objc2-encode\",\n]\n\n[[package]]\nname = \"objc2-app-kit\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"block2 0.5.1\",\n \"libc\",\n \"objc2 0.5.3\",\n \"objc2-core-data\",\n \"objc2-core-image\",\n \"objc2-foundation 0.2.2\",\n \"objc2-quartz-core 0.2.2\",\n]\n\n[[package]]\nname = \"objc2-app-kit\"\nversion = \"0.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"objc2 0.6.5\",\n \"objc2-core-graphics\",\n \"objc2-foundation 0.3.2\",\n]\n\n[[package]]\nname = \"objc2-av-foundation\"\nversion = \"0.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"478ae33fcac9df0a18db8302387c666b8ef08a3e2d62b510ca4fc278a384b6c0\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"objc2 0.6.5\",\n \"objc2-core-foundation\",\n \"objc2-core-graphics\",\n \"objc2-core-media\",\n \"objc2-core-video\",\n \"objc2-foundation 0.3.2\",\n]\n\n[[package]]\nname = \"objc2-cloud-kit\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"block2 0.5.1\",\n \"objc2 0.5.3\",\n \"objc2-core-location\",\n \"objc2-foundation 0.2.2\",\n]\n\n[[package]]\nname = \"objc2-contacts\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889\"\ndependencies = [\n \"block2 0.5.1\",\n \"objc2 0.5.3\",\n \"objc2-foundation 0.2.2\",\n]\n\n[[package]]\nname = \"objc2-core-audio\"\nversion = \"0.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2\"\ndependencies = [\n \"dispatch2\",\n \"objc2 0.6.5\",\n \"objc2-core-audio-types\",\n \"objc2-core-foundation\",\n]\n\n[[package]]\nname = \"objc2-core-audio-types\"\nversion = \"0.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"objc2 0.6.5\",\n]\n\n[[package]]\nname = \"objc2-core-data\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"block2 0.5.1\",\n \"objc2 0.5.3\",\n \"objc2-foundation 0.2.2\",\n]\n\n[[package]]\nname = \"objc2-core-foundation\"\nversion = \"0.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"block2 0.6.2\",\n \"dispatch2\",\n \"libc\",\n \"objc2 0.6.5\",\n]\n\n[[package]]\nname = \"objc2-core-graphics\"\nversion = \"0.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"dispatch2\",\n \"objc2 0.6.5\",\n \"objc2-core-foundation\",\n \"objc2-io-surface\",\n]\n\n[[package]]\nname = \"objc2-core-image\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80\"\ndependencies = [\n \"block2 0.5.1\",\n \"objc2 0.5.3\",\n \"objc2-foundation 0.2.2\",\n \"objc2-metal 0.2.2\",\n]\n\n[[package]]\nname = \"objc2-core-location\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781\"\ndependencies = [\n \"block2 0.5.1\",\n \"objc2 0.5.3\",\n \"objc2-contacts\",\n \"objc2-foundation 0.2.2\",\n]\n\n[[package]]\nname = \"objc2-core-media\"\nversion = \"0.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"05ec576860167a15dd9fce7fbee7512beb4e31f532159d3482d1f9c6caedf31d\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"dispatch2\",\n \"objc2 0.6.5\",\n \"objc2-core-audio\",\n \"objc2-core-audio-types\",\n \"objc2-core-foundation\",\n \"objc2-core-video\",\n]\n\n[[package]]\nname = \"objc2-core-text\"\nversion = \"0.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"objc2-core-foundation\",\n]\n\n[[package]]\nname = \"objc2-core-video\"\nversion = \"0.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"block2 0.6.2\",\n \"objc2 0.6.5\",\n \"objc2-core-foundation\",\n \"objc2-core-graphics\",\n \"objc2-io-surface\",\n \"objc2-metal 0.3.2\",\n]\n\n[[package]]\nname = \"objc2-encode\"\nversion = \"4.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33\"\n\n[[package]]\nname = \"objc2-foundation\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"block2 0.5.1\",\n \"dispatch\",\n \"libc\",\n \"objc2 0.5.3\",\n]\n\n[[package]]\nname = \"objc2-foundation\"\nversion = \"0.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"objc2 0.6.5\",\n \"objc2-core-foundation\",\n]\n\n[[package]]\nname = \"objc2-io-surface\"\nversion = \"0.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"libc\",\n \"objc2 0.6.5\",\n \"objc2-core-foundation\",\n \"objc2-foundation 0.3.2\",\n]\n\n[[package]]\nname = \"objc2-link-presentation\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398\"\ndependencies = [\n \"block2 0.5.1\",\n \"objc2 0.5.3\",\n \"objc2-app-kit 0.2.2\",\n \"objc2-foundation 0.2.2\",\n]\n\n[[package]]\nname = \"objc2-metal\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"block2 0.5.1\",\n \"objc2 0.5.3\",\n \"objc2-foundation 0.2.2\",\n]\n\n[[package]]\nname = \"objc2-metal\"\nversion = \"0.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"block2 0.6.2\",\n \"dispatch2\",\n \"objc2 0.6.5\",\n \"objc2-core-foundation\",\n \"objc2-foundation 0.3.2\",\n]\n\n[[package]]\nname = \"objc2-quartz-core\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"block2 0.5.1\",\n \"objc2 0.5.3\",\n \"objc2-foundation 0.2.2\",\n \"objc2-metal 0.2.2\",\n]\n\n[[package]]\nname = \"objc2-quartz-core\"\nversion = \"0.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"objc2 0.6.5\",\n \"objc2-core-foundation\",\n \"objc2-core-graphics\",\n \"objc2-foundation 0.3.2\",\n \"objc2-metal 0.3.2\",\n]\n\n[[package]]\nname = \"objc2-symbols\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc\"\ndependencies = [\n \"objc2 0.5.3\",\n \"objc2-foundation 0.2.2\",\n]\n\n[[package]]\nname = \"objc2-ui-kit\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"block2 0.5.1\",\n \"objc2 0.5.3\",\n \"objc2-cloud-kit\",\n \"objc2-core-data\",\n \"objc2-core-image\",\n \"objc2-core-location\",\n \"objc2-foundation 0.2.2\",\n \"objc2-link-presentation\",\n \"objc2-quartz-core 0.2.2\",\n \"objc2-symbols\",\n \"objc2-uniform-type-identifiers\",\n \"objc2-user-notifications\",\n]\n\n[[package]]\nname = \"objc2-uniform-type-identifiers\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe\"\ndependencies = [\n \"block2 0.5.1\",\n \"objc2 0.5.3\",\n \"objc2-foundation 0.2.2\",\n]\n\n[[package]]\nname = \"objc2-user-notifications\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"block2 0.5.1\",\n \"objc2 0.5.3\",\n \"objc2-core-location\",\n \"objc2-foundation 0.2.2\",\n]\n\n[[package]]\nname = \"once_cell\"\nversion = \"1.21.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50\"\n\n[[package]]\nname = \"opuscule\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"418827b94acaa183462024021324b6e733086466375604eb60e584c7acd4462c\"\n\n[[package]]\nname = \"orbclient\"\nversion = \"0.3.55\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747\"\ndependencies = [\n \"libc\",\n \"libredox\",\n]\n\n[[package]]\nname = \"ordered-float\"\nversion = \"5.5.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab\"\ndependencies = [\n \"num-traits\",\n]\n\n[[package]]\nname = \"ordered-stream\"\nversion = \"0.2.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50\"\ndependencies = [\n \"futures-core\",\n \"pin-project-lite\",\n]\n\n[[package]]\nname = \"os_pipe\"\nversion = \"1.2.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967\"\ndependencies = [\n \"libc\",\n \"windows-sys 0.61.2\",\n]\n\n[[package]]\nname = \"parking\"\nversion = \"2.2.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba\"\n\n[[package]]\nname = \"parking_lot\"\nversion = \"0.12.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a\"\ndependencies = [\n \"lock_api\",\n \"parking_lot_core\",\n]\n\n[[package]]\nname = \"parking_lot_core\"\nversion = \"0.9.12\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1\"\ndependencies = [\n \"cfg-if\",\n \"libc\",\n \"redox_syscall 0.5.18\",\n \"smallvec\",\n \"windows-link\",\n]\n\n[[package]]\nname = \"parlance\"\nversion = \"0.1.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"73072a9470554c8e794778acece2312661218aaabb635600957d952cf01c716e\"\n\n[[package]]\nname = \"parley\"\nversion = \"0.12.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"61bd0c0c1737f0b3d3726dc06b225083af213b61913e4fbae1670613a106c6ce\"\ndependencies = [\n \"fontique\",\n \"hashbrown 0.17.1\",\n \"linebender_resource_handle\",\n \"parlance\",\n \"parley_engine\",\n \"smallvec\",\n]\n\n[[package]]\nname = \"parley_data\"\nversion = \"0.12.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c43b63f808f6cc8f4a3b07de0d62a977bddd2e0bb5c232bd9e93ba8ef92e5e4b\"\ndependencies = [\n \"icu_collections\",\n \"icu_properties\",\n]\n\n[[package]]\nname = \"parley_emoji\"\nversion = \"0.12.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"9c4482d912d7671a7cd2089794f90ef3bb5f5f8c738230fb0fcd50fa020f0ed3\"\n\n[[package]]\nname = \"parley_engine\"\nversion = \"0.12.0\"\nsource = \"git+https://github.com/anomalyco/rune?rev=eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90#eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\"\ndependencies = [\n \"fontique\",\n \"harfrust\",\n \"hashbrown 0.17.1\",\n \"icu_locale_core\",\n \"icu_normalizer\",\n \"icu_properties\",\n \"icu_segmenter\",\n \"linebender_resource_handle\",\n \"parlance\",\n \"parley_data\",\n \"parley_emoji\",\n \"skrifa\",\n]\n\n[[package]]\nname = \"pbkdf2\"\nversion = \"0.12.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2\"\ndependencies = [\n \"digest 0.10.7\",\n \"hmac 0.12.1\",\n]\n\n[[package]]\nname = \"percent-encoding\"\nversion = \"2.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220\"\n\n[[package]]\nname = \"petgraph\"\nversion = \"0.8.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455\"\ndependencies = [\n \"fixedbitset\",\n \"hashbrown 0.15.5\",\n \"indexmap\",\n]\n\n[[package]]\nname = \"phf\"\nversion = \"0.14.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6\"\ndependencies = [\n \"phf_macros\",\n \"phf_shared\",\n \"serde\",\n]\n\n[[package]]\nname = \"phf_generator\"\nversion = \"0.14.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100\"\ndependencies = [\n \"fastrand\",\n \"phf_shared\",\n]\n\n[[package]]\nname = \"phf_macros\"\nversion = \"0.14.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085\"\ndependencies = [\n \"phf_generator\",\n \"phf_shared\",\n \"proc-macro2\",\n \"quote\",\n \"syn 2.0.119\",\n]\n\n[[package]]\nname = \"phf_shared\"\nversion = \"0.14.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89\"\ndependencies = [\n \"siphasher\",\n]\n\n[[package]]\nname = \"pico-args\"\nversion = \"0.5.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315\"\n\n[[package]]\nname = \"pin-project\"\nversion = \"1.1.13\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924\"\ndependencies = [\n \"pin-project-internal\",\n]\n\n[[package]]\nname = \"pin-project-internal\"\nversion = \"1.1.13\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 2.0.119\",\n]\n\n[[package]]\nname = \"pin-project-lite\"\nversion = \"0.2.17\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd\"\n\n[[package]]\nname = \"piper\"\nversion = \"0.2.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1\"\ndependencies = [\n \"atomic-waker\",\n \"fastrand\",\n \"futures-io\",\n]\n\n[[package]]\nname = \"pkg-config\"\nversion = \"0.3.34\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548\"\n\n[[package]]\nname = \"plain\"\nversion = \"0.2.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6\"\n\n[[package]]\nname = \"png\"\nversion = \"0.17.16\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526\"\ndependencies = [\n \"bitflags 1.3.2\",\n \"crc32fast\",\n \"fdeflate\",\n \"flate2\",\n \"miniz_oxide 0.8.9\",\n]\n\n[[package]]\nname = \"png\"\nversion = \"0.18.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"crc32fast\",\n \"fdeflate\",\n \"flate2\",\n \"miniz_oxide 0.8.9\",\n]\n\n[[package]]\nname = \"polling\"\nversion = \"3.11.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218\"\ndependencies = [\n \"cfg-if\",\n \"concurrent-queue\",\n \"hermit-abi\",\n \"pin-project-lite\",\n \"rustix 1.1.6\",\n \"windows-sys 0.61.2\",\n]\n\n[[package]]\nname = \"pollster\"\nversion = \"1.0.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336\"\n\n[[package]]\nname = \"portable-atomic\"\nversion = \"1.15.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85\"\n\n[[package]]\nname = \"portable-atomic-util\"\nversion = \"0.2.8\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715\"\ndependencies = [\n \"portable-atomic\",\n]\n\n[[package]]\nname = \"potential_utf\"\nversion = \"0.1.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661\"\ndependencies = [\n \"serde_core\",\n \"writeable\",\n \"zerovec\",\n]\n\n[[package]]\nname = \"powerfmt\"\nversion = \"0.2.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958\"\n\n[[package]]\nname = \"presser\"\nversion = \"0.3.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa\"\n\n[[package]]\nname = \"prettyplease\"\nversion = \"0.2.37\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b\"\ndependencies = [\n \"proc-macro2\",\n \"syn 2.0.119\",\n]\n\n[[package]]\nname = \"proc-macro-crate\"\nversion = \"3.5.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f\"\ndependencies = [\n \"toml_edit\",\n]\n\n[[package]]\nname = \"proc-macro2\"\nversion = \"1.0.107\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9\"\ndependencies = [\n \"unicode-ident\",\n]\n\n[[package]]\nname = \"profiling\"\nversion = \"1.0.18\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5\"\n\n[[package]]\nname = \"pxfm\"\nversion = \"0.1.30\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea\"\n\n[[package]]\nname = \"quick-error\"\nversion = \"2.0.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3\"\n\n[[package]]\nname = \"quick-xml\"\nversion = \"0.41.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1\"\ndependencies = [\n \"memchr\",\n]\n\n[[package]]\nname = \"quote\"\nversion = \"1.0.47\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001\"\ndependencies = [\n \"proc-macro2\",\n]\n\n[[package]]\nname = \"r-efi\"\nversion = \"5.3.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f\"\n\n[[package]]\nname = \"r-efi\"\nversion = \"6.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf\"\n\n[[package]]\nname = \"range-alloc\"\nversion = \"0.1.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08\"\n\n[[package]]\nname = \"raw-window-handle\"\nversion = \"0.6.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539\"\n\n[[package]]\nname = \"raw-window-metal\"\nversion = \"1.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135\"\ndependencies = [\n \"objc2 0.6.5\",\n \"objc2-core-foundation\",\n \"objc2-foundation 0.3.2\",\n \"objc2-quartz-core 0.3.2\",\n]\n\n[[package]]\nname = \"read-fonts\"\nversion = \"0.41.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709\"\ndependencies = [\n \"bytemuck\",\n \"font-types\",\n \"once_cell\",\n]\n\n[[package]]\nname = \"redox_syscall\"\nversion = \"0.4.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa\"\ndependencies = [\n \"bitflags 1.3.2\",\n]\n\n[[package]]\nname = \"redox_syscall\"\nversion = \"0.5.18\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d\"\ndependencies = [\n \"bitflags 2.13.2\",\n]\n\n[[package]]\nname = \"redox_syscall\"\nversion = \"0.9.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd\"\ndependencies = [\n \"bitflags 2.13.2\",\n]\n\n[[package]]\nname = \"regex\"\nversion = \"1.13.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857\"\ndependencies = [\n \"aho-corasick\",\n \"memchr\",\n \"regex-automata\",\n \"regex-syntax\",\n]\n\n[[package]]\nname = \"regex-automata\"\nversion = \"0.4.19\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158\"\ndependencies = [\n \"aho-corasick\",\n \"memchr\",\n \"regex-syntax\",\n]\n\n[[package]]\nname = \"regex-syntax\"\nversion = \"0.8.12\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6\"\n\n[[package]]\nname = \"regress\"\nversion = \"0.12.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"32eef8b209c3c1c15dbad02c1f30f9539f00dc7253e0cbcdaae442a50a09d7c1\"\ndependencies = [\n \"memchr\",\n]\n\n[[package]]\nname = \"renderdoc-sys\"\nversion = \"1.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832\"\n\n[[package]]\nname = \"resvg\"\nversion = \"0.45.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43\"\ndependencies = [\n \"log\",\n \"pico-args\",\n \"rgb\",\n \"svgtypes\",\n \"tiny-skia\",\n \"usvg\",\n]\n\n[[package]]\nname = \"rgb\"\nversion = \"0.8.53\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4\"\ndependencies = [\n \"bytemuck\",\n]\n\n[[package]]\nname = \"ring\"\nversion = \"0.17.14\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7\"\ndependencies = [\n \"cc\",\n \"cfg-if\",\n \"getrandom 0.2.17\",\n \"libc\",\n \"untrusted\",\n \"windows-sys 0.52.0\",\n]\n\n[[package]]\nname = \"roxmltree\"\nversion = \"0.20.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97\"\n\n[[package]]\nname = \"roxmltree\"\nversion = \"0.21.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907\"\ndependencies = [\n \"memchr\",\n]\n\n[[package]]\nname = \"rpassword\"\nversion = \"7.5.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"1fa2c5d9304b618df61ff17f3d3485c6e1854a3d94902a49abbb8d43dfbe0464\"\ndependencies = [\n \"libc\",\n \"rtoolbox\",\n \"windows-sys 0.61.2\",\n]\n\n[[package]]\nname = \"rtoolbox\"\nversion = \"0.0.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d\"\ndependencies = [\n \"libc\",\n \"windows-sys 0.61.2\",\n]\n\n[[package]]\nname = \"rune\"\nversion = \"0.0.1\"\nsource = \"git+https://github.com/anomalyco/rune?rev=eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90#eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\"\ndependencies = [\n \"accesskit\",\n \"accesskit_macos\",\n \"accesskit_unix\",\n \"accesskit_windows\",\n \"arboard\",\n \"blake3\",\n \"block2 0.5.1\",\n \"block2 0.6.2\",\n \"bytemuck\",\n \"console_error_panic_hook\",\n \"fontique\",\n \"futures-util\",\n \"half\",\n \"icu_properties\",\n \"icu_segmenter\",\n \"image\",\n \"js-sys\",\n \"libc\",\n \"libloading\",\n \"objc2 0.5.3\",\n \"objc2 0.6.5\",\n \"objc2-app-kit 0.2.2\",\n \"objc2-av-foundation\",\n \"objc2-core-foundation\",\n \"objc2-core-graphics\",\n \"objc2-core-media\",\n \"objc2-core-text\",\n \"objc2-core-video\",\n \"objc2-foundation 0.2.2\",\n \"objc2-foundation 0.3.2\",\n \"objc2-io-surface\",\n \"objc2-metal 0.3.2\",\n \"objc2-quartz-core 0.3.2\",\n \"opuscule\",\n \"parking_lot\",\n \"parley\",\n \"parley_engine\",\n \"png 0.18.1\",\n \"pollster\",\n \"portable-atomic\",\n \"raw-window-handle\",\n \"raw-window-metal\",\n \"resvg\",\n \"rune-motion\",\n \"rune-staging\",\n \"rune-taffy\",\n \"rustc-demangle\",\n \"rustc-hash 2.1.3\",\n \"serde\",\n \"serde_json\",\n \"skrifa\",\n \"spellbook\",\n \"swash\",\n \"symphonia\",\n \"taffy\",\n \"tiny-skia-path 0.11.4 (git+https://github.com/anomalyco/rune?rev=eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90)\",\n \"tokio\",\n \"unicode-segmentation\",\n \"wasm-bindgen\",\n \"wasm-bindgen-futures\",\n \"wayland-backend\",\n \"wayland-client\",\n \"wayland-protocols\",\n \"wayland-protocols-wlr\",\n \"web-sys\",\n \"web-time\",\n \"wgpu\",\n \"wgpu-core\",\n \"wgpu-hal\",\n \"wgpu-naga-bridge\",\n \"windows\",\n \"windows-core\",\n \"windows-sys 0.59.0\",\n \"winit\",\n \"x11rb\",\n \"xkbcommon\",\n \"zbus 6.3.0\",\n \"zeroize\",\n]\n\n[[package]]\nname = \"rune-motion\"\nversion = \"0.1.0\"\nsource = \"git+https://github.com/anomalyco/rune?rev=eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90#eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\"\n\n[[package]]\nname = \"rune-notify\"\nversion = \"0.0.1\"\nsource = \"git+https://github.com/anomalyco/rune?rev=eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90#eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\"\ndependencies = [\n \"block2 0.5.1\",\n \"objc2 0.5.3\",\n \"windows\",\n \"windows-core\",\n \"windows-registry\",\n]\n\n[[package]]\nname = \"rune-staging\"\nversion = \"0.0.1\"\nsource = \"git+https://github.com/anomalyco/rune?rev=eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90#eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\"\ndependencies = [\n \"wgpu\",\n]\n\n[[package]]\nname = \"rune-taffy\"\nversion = \"0.0.1\"\nsource = \"git+https://github.com/anomalyco/rune?rev=eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90#eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\"\ndependencies = [\n \"taffy\",\n]\n\n[[package]]\nname = \"rustc-demangle\"\nversion = \"0.1.28\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb\"\n\n[[package]]\nname = \"rustc-hash\"\nversion = \"1.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2\"\n\n[[package]]\nname = \"rustc-hash\"\nversion = \"2.1.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d\"\n\n[[package]]\nname = \"rustc_version\"\nversion = \"0.4.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92\"\ndependencies = [\n \"semver\",\n]\n\n[[package]]\nname = \"rustix\"\nversion = \"0.38.44\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"errno\",\n \"libc\",\n \"linux-raw-sys 0.4.15\",\n \"windows-sys 0.59.0\",\n]\n\n[[package]]\nname = \"rustix\"\nversion = \"1.1.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"errno\",\n \"libc\",\n \"linux-raw-sys 0.12.1\",\n \"windows-sys 0.61.2\",\n]\n\n[[package]]\nname = \"rustls\"\nversion = \"0.23.46\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf\"\ndependencies = [\n \"log\",\n \"once_cell\",\n \"ring\",\n \"rustls-pki-types\",\n \"rustls-webpki\",\n \"subtle\",\n \"zeroize\",\n]\n\n[[package]]\nname = \"rustls-pki-types\"\nversion = \"1.16.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb\"\ndependencies = [\n \"zeroize\",\n]\n\n[[package]]\nname = \"rustls-webpki\"\nversion = \"0.103.17\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5\"\ndependencies = [\n \"ring\",\n \"rustls-pki-types\",\n \"untrusted\",\n]\n\n[[package]]\nname = \"rustversion\"\nversion = \"1.0.23\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f\"\n\n[[package]]\nname = \"salsa20\"\nversion = \"0.10.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213\"\ndependencies = [\n \"cipher 0.4.4\",\n]\n\n[[package]]\nname = \"same-file\"\nversion = \"1.0.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502\"\ndependencies = [\n \"winapi-util\",\n]\n\n[[package]]\nname = \"schemars\"\nversion = \"0.8.22\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615\"\ndependencies = [\n \"dyn-clone\",\n \"schemars_derive\",\n \"serde\",\n \"serde_json\",\n]\n\n[[package]]\nname = \"schemars_derive\"\nversion = \"0.8.22\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"serde_derive_internals\",\n \"syn 2.0.119\",\n]\n\n[[package]]\nname = \"scoped-tls\"\nversion = \"1.0.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294\"\n\n[[package]]\nname = \"scopeguard\"\nversion = \"1.2.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49\"\n\n[[package]]\nname = \"scrypt\"\nversion = \"0.11.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f\"\ndependencies = [\n \"pbkdf2\",\n \"salsa20\",\n \"sha2 0.10.9\",\n]\n\n[[package]]\nname = \"sctk-adwaita\"\nversion = \"0.10.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec\"\ndependencies = [\n \"log\",\n \"smithay-client-toolkit\",\n \"tiny-skia\",\n]\n\n[[package]]\nname = \"secret-service\"\nversion = \"5.2.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8\"\ndependencies = [\n \"aes\",\n \"cbc\",\n \"futures-util\",\n \"getrandom 0.4.3\",\n \"hkdf\",\n \"hybrid-array\",\n \"num\",\n \"once_cell\",\n \"serde\",\n \"sha2 0.11.1\",\n \"zbus 5.19.0\",\n]\n\n[[package]]\nname = \"security-framework\"\nversion = \"3.7.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"core-foundation 0.10.1\",\n \"core-foundation-sys\",\n \"libc\",\n \"security-framework-sys\",\n]\n\n[[package]]\nname = \"security-framework-sys\"\nversion = \"2.17.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3\"\ndependencies = [\n \"core-foundation-sys\",\n \"libc\",\n]\n\n[[package]]\nname = \"semver\"\nversion = \"1.0.28\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd\"\n\n[[package]]\nname = \"serde\"\nversion = \"1.0.229\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba\"\ndependencies = [\n \"serde_core\",\n \"serde_derive\",\n]\n\n[[package]]\nname = \"serde_core\"\nversion = \"1.0.229\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48\"\ndependencies = [\n \"serde_derive\",\n]\n\n[[package]]\nname = \"serde_derive\"\nversion = \"1.0.229\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n]\n\n[[package]]\nname = \"serde_derive_internals\"\nversion = \"0.29.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 2.0.119\",\n]\n\n[[package]]\nname = \"serde_json\"\nversion = \"1.0.154\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6\"\ndependencies = [\n \"itoa\",\n \"memchr\",\n \"serde\",\n \"serde_core\",\n \"zmij\",\n]\n\n[[package]]\nname = \"serde_repr\"\nversion = \"0.1.21\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n]\n\n[[package]]\nname = \"serde_tokenstream\"\nversion = \"0.3.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"db95b8acf6eca5bc1bc771a7d7fb1a0d1485bdef0c46eec2f573bbaf4b4118f8\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"serde\",\n \"syn 3.0.10\",\n]\n\n[[package]]\nname = \"sha2\"\nversion = \"0.10.9\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283\"\ndependencies = [\n \"cfg-if\",\n \"cpufeatures 0.2.17\",\n \"digest 0.10.7\",\n]\n\n[[package]]\nname = \"sha2\"\nversion = \"0.11.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19\"\ndependencies = [\n \"cfg-if\",\n \"cpufeatures 0.3.1\",\n \"digest 0.11.3\",\n]\n\n[[package]]\nname = \"shlex\"\nversion = \"2.0.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba\"\n\n[[package]]\nname = \"signal-hook-registry\"\nversion = \"1.4.8\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b\"\ndependencies = [\n \"errno\",\n \"libc\",\n]\n\n[[package]]\nname = \"simd-adler32\"\nversion = \"0.3.10\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea\"\n\n[[package]]\nname = \"simd_cesu8\"\nversion = \"1.2.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520\"\ndependencies = [\n \"rustc_version\",\n \"simdutf8\",\n]\n\n[[package]]\nname = \"simdutf8\"\nversion = \"0.1.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e\"\n\n[[package]]\nname = \"simplecss\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c\"\ndependencies = [\n \"log\",\n]\n\n[[package]]\nname = \"siphasher\"\nversion = \"1.0.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256\"\n\n[[package]]\nname = \"skrifa\"\nversion = \"0.44.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68\"\ndependencies = [\n \"bytemuck\",\n \"read-fonts\",\n]\n\n[[package]]\nname = \"slab\"\nversion = \"0.4.12\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5\"\n\n[[package]]\nname = \"slotmap\"\nversion = \"1.1.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038\"\ndependencies = [\n \"version_check\",\n]\n\n[[package]]\nname = \"smallvec\"\nversion = \"1.16.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46\"\n\n[[package]]\nname = \"smithay-client-toolkit\"\nversion = \"0.19.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"calloop\",\n \"calloop-wayland-source\",\n \"cursor-icon\",\n \"libc\",\n \"log\",\n \"memmap2\",\n \"rustix 0.38.44\",\n \"thiserror 1.0.69\",\n \"wayland-backend\",\n \"wayland-client\",\n \"wayland-csd-frame\",\n \"wayland-cursor\",\n \"wayland-protocols\",\n \"wayland-protocols-wlr\",\n \"wayland-scanner\",\n \"xkeysym\",\n]\n\n[[package]]\nname = \"smol_str\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead\"\ndependencies = [\n \"serde\",\n]\n\n[[package]]\nname = \"socket2\"\nversion = \"0.6.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4\"\ndependencies = [\n \"libc\",\n \"windows-sys 0.61.2\",\n]\n\n[[package]]\nname = \"spellbook\"\nversion = \"0.4.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"0d204abcbdf8e88729306a8d0ca01a79d8a49969fe1f84696909d6dbc4321c1a\"\ndependencies = [\n \"foldhash 0.2.0\",\n \"hashbrown 0.17.1\",\n]\n\n[[package]]\nname = \"spirv\"\nversion = \"0.4.0+sdk-1.4.341.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f\"\ndependencies = [\n \"bitflags 2.13.2\",\n]\n\n[[package]]\nname = \"stable_deref_trait\"\nversion = \"1.2.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596\"\n\n[[package]]\nname = \"static_assertions\"\nversion = \"1.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f\"\n\n[[package]]\nname = \"strict-num\"\nversion = \"0.1.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731\"\ndependencies = [\n \"float-cmp\",\n]\n\n[[package]]\nname = \"strum\"\nversion = \"0.28.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd\"\ndependencies = [\n \"strum_macros\",\n]\n\n[[package]]\nname = \"strum_macros\"\nversion = \"0.28.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664\"\ndependencies = [\n \"heck\",\n \"proc-macro2\",\n \"quote\",\n \"syn 2.0.119\",\n]\n\n[[package]]\nname = \"subtle\"\nversion = \"2.6.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292\"\n\n[[package]]\nname = \"svgtypes\"\nversion = \"0.15.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc\"\ndependencies = [\n \"kurbo\",\n \"siphasher\",\n]\n\n[[package]]\nname = \"swash\"\nversion = \"0.2.10\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6c2499c2d826531388872b2268718aed907a39bd785ab0dcfe57fab26283f92e\"\ndependencies = [\n \"skrifa\",\n \"yazi\",\n \"zeno\",\n]\n\n[[package]]\nname = \"symphonia\"\nversion = \"0.5.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5773a4c030a19d9bfaa090f49746ff35c75dfddfa700df7a5939d5e076a57039\"\ndependencies = [\n \"lazy_static\",\n \"symphonia-codec-vorbis\",\n \"symphonia-core\",\n \"symphonia-format-mkv\",\n \"symphonia-format-ogg\",\n \"symphonia-metadata\",\n]\n\n[[package]]\nname = \"symphonia-codec-vorbis\"\nversion = \"0.5.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f025837c309cd69ffef572750b4a2257b59552c5399a5e49707cc5b1b85d1c73\"\ndependencies = [\n \"log\",\n \"symphonia-core\",\n \"symphonia-utils-xiph\",\n]\n\n[[package]]\nname = \"symphonia-core\"\nversion = \"0.5.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ea00cc4f79b7f6bb7ff87eddc065a1066f3a43fe1875979056672c9ef948c2af\"\ndependencies = [\n \"arrayvec\",\n \"bitflags 1.3.2\",\n \"bytemuck\",\n \"lazy_static\",\n \"log\",\n]\n\n[[package]]\nname = \"symphonia-format-mkv\"\nversion = \"0.5.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"122d786d2c43a49beb6f397551b4a050d8229eaa54c7ddf9ee4b98899b8742d0\"\ndependencies = [\n \"lazy_static\",\n \"log\",\n \"symphonia-core\",\n \"symphonia-metadata\",\n \"symphonia-utils-xiph\",\n]\n\n[[package]]\nname = \"symphonia-format-ogg\"\nversion = \"0.5.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"2b4955c67c1ed3aa8ae8428d04ca8397fbef6a19b2b051e73b5da8b1435639cb\"\ndependencies = [\n \"log\",\n \"symphonia-core\",\n \"symphonia-metadata\",\n \"symphonia-utils-xiph\",\n]\n\n[[package]]\nname = \"symphonia-metadata\"\nversion = \"0.5.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"36306ff42b9ffe6e5afc99d49e121e0bd62fe79b9db7b9681d48e29fa19e6b16\"\ndependencies = [\n \"encoding_rs\",\n \"lazy_static\",\n \"log\",\n \"symphonia-core\",\n]\n\n[[package]]\nname = \"symphonia-utils-xiph\"\nversion = \"0.5.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ee27c85ab799a338446b68eec77abf42e1a6f1bb490656e121c6e27bfbab9f16\"\ndependencies = [\n \"symphonia-core\",\n \"symphonia-metadata\",\n]\n\n[[package]]\nname = \"syn\"\nversion = \"2.0.119\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"unicode-ident\",\n]\n\n[[package]]\nname = \"syn\"\nversion = \"3.0.10\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"unicode-ident\",\n]\n\n[[package]]\nname = \"synstructure\"\nversion = \"0.14.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n]\n\n[[package]]\nname = \"taffy\"\nversion = \"0.15.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"31f7bd2d97198df05186f93a3a3c306845f40e8b3c22bf9279cdd7e5cf5fea7d\"\ndependencies = [\n \"serde\",\n \"slotmap\",\n \"smallvec\",\n]\n\n[[package]]\nname = \"tar\"\nversion = \"0.4.46\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840\"\ndependencies = [\n \"filetime\",\n \"libc\",\n \"xattr\",\n]\n\n[[package]]\nname = \"tempfile\"\nversion = \"3.27.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd\"\ndependencies = [\n \"fastrand\",\n \"getrandom 0.4.3\",\n \"once_cell\",\n \"rustix 1.1.6\",\n \"windows-sys 0.61.2\",\n]\n\n[[package]]\nname = \"termcolor\"\nversion = \"1.4.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755\"\ndependencies = [\n \"winapi-util\",\n]\n\n[[package]]\nname = \"thiserror\"\nversion = \"1.0.69\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52\"\ndependencies = [\n \"thiserror-impl 1.0.69\",\n]\n\n[[package]]\nname = \"thiserror\"\nversion = \"2.0.21\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e\"\ndependencies = [\n \"thiserror-impl 2.0.21\",\n]\n\n[[package]]\nname = \"thiserror-impl\"\nversion = \"1.0.69\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 2.0.119\",\n]\n\n[[package]]\nname = \"thiserror-impl\"\nversion = \"2.0.21\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n]\n\n[[package]]\nname = \"tiff\"\nversion = \"0.11.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52\"\ndependencies = [\n \"fax\",\n \"flate2\",\n \"half\",\n \"quick-error\",\n \"weezl\",\n \"zune-jpeg\",\n]\n\n[[package]]\nname = \"time\"\nversion = \"0.3.55\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134\"\ndependencies = [\n \"deranged\",\n \"num-conv\",\n \"powerfmt\",\n \"serde_core\",\n \"time-core\",\n \"time-macros\",\n]\n\n[[package]]\nname = \"time-core\"\nversion = \"0.1.9\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109\"\n\n[[package]]\nname = \"time-macros\"\nversion = \"0.2.32\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85\"\ndependencies = [\n \"num-conv\",\n \"time-core\",\n]\n\n[[package]]\nname = \"tiny-skia\"\nversion = \"0.11.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab\"\ndependencies = [\n \"arrayref\",\n \"arrayvec\",\n \"bytemuck\",\n \"cfg-if\",\n \"log\",\n \"png 0.17.16\",\n \"tiny-skia-path 0.11.4 (registry+https://github.com/rust-lang/crates.io-index)\",\n]\n\n[[package]]\nname = \"tiny-skia-path\"\nversion = \"0.11.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93\"\ndependencies = [\n \"arrayref\",\n \"bytemuck\",\n \"strict-num\",\n]\n\n[[package]]\nname = \"tiny-skia-path\"\nversion = \"0.11.4\"\nsource = \"git+https://github.com/anomalyco/rune?rev=eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90#eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\"\ndependencies = [\n \"arrayref\",\n \"bytemuck\",\n \"strict-num\",\n]\n\n[[package]]\nname = \"tinystr\"\nversion = \"0.8.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a\"\ndependencies = [\n \"displaydoc\",\n \"serde_core\",\n \"zerovec\",\n]\n\n[[package]]\nname = \"tokio\"\nversion = \"1.54.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3\"\ndependencies = [\n \"bytes\",\n \"libc\",\n \"mio\",\n \"pin-project-lite\",\n \"signal-hook-registry\",\n \"socket2\",\n \"tokio-macros\",\n \"windows-sys 0.61.2\",\n]\n\n[[package]]\nname = \"tokio-macros\"\nversion = \"2.7.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n]\n\n[[package]]\nname = \"toml_datetime\"\nversion = \"1.1.3+spec-1.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49\"\ndependencies = [\n \"serde_core\",\n]\n\n[[package]]\nname = \"toml_edit\"\nversion = \"0.25.19+spec-1.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218\"\ndependencies = [\n \"indexmap\",\n \"toml_datetime\",\n \"toml_parser\",\n \"winnow\",\n]\n\n[[package]]\nname = \"toml_parser\"\nversion = \"1.1.5+spec-1.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c\"\ndependencies = [\n \"winnow\",\n]\n\n[[package]]\nname = \"tracing\"\nversion = \"0.1.44\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100\"\ndependencies = [\n \"pin-project-lite\",\n \"tracing-attributes\",\n \"tracing-core\",\n]\n\n[[package]]\nname = \"tracing-attributes\"\nversion = \"0.1.31\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 2.0.119\",\n]\n\n[[package]]\nname = \"tracing-core\"\nversion = \"0.1.36\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a\"\ndependencies = [\n \"once_cell\",\n]\n\n[[package]]\nname = \"tree_magic_mini\"\nversion = \"3.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6\"\ndependencies = [\n \"memchr\",\n \"nom\",\n \"petgraph\",\n]\n\n[[package]]\nname = \"typenum\"\nversion = \"1.20.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20\"\n\n[[package]]\nname = \"typespace\"\nversion = \"0.1.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3827ec138743b6fd27eb2bfb2d063c5e11b1956555bb6719491e8c17077cda23\"\ndependencies = [\n \"codespace\",\n \"heck\",\n \"log\",\n \"proc-macro2\",\n \"quote\",\n \"schemars\",\n \"serde\",\n \"serde_json\",\n \"strum\",\n \"syn 3.0.10\",\n \"thiserror 2.0.21\",\n]\n\n[[package]]\nname = \"typify\"\nversion = \"0.10.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"19f174e99e1652ac0b6110431a2f9312cbfb6c618c74f3f235821e3ff0f63e9c\"\ndependencies = [\n \"typify-impl\",\n \"typify-macro\",\n]\n\n[[package]]\nname = \"typify-impl\"\nversion = \"0.10.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"82ce9c7f17c54101c576f7cee9b10390d690146a1dfa56da2deb4a4dfd8828c4\"\ndependencies = [\n \"heck\",\n \"log\",\n \"proc-macro2\",\n \"quote\",\n \"regress\",\n \"schemars\",\n \"semver\",\n \"serde\",\n \"serde_json\",\n \"syn 3.0.10\",\n \"thiserror 2.0.21\",\n \"typespace\",\n \"unicode-ident\",\n]\n\n[[package]]\nname = \"typify-macro\"\nversion = \"0.10.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"45eea4112276f9efa20180747926641bfc0a470ff8839dc56c6b7a07e82d1267\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"schemars\",\n \"semver\",\n \"serde\",\n \"serde_json\",\n \"serde_tokenstream\",\n \"syn 3.0.10\",\n \"typify-impl\",\n]\n\n[[package]]\nname = \"uds_windows\"\nversion = \"1.2.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e\"\ndependencies = [\n \"memoffset\",\n \"tempfile\",\n \"windows-sys 0.61.2\",\n]\n\n[[package]]\nname = \"unicode-ident\"\nversion = \"1.0.27\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563\"\n\n[[package]]\nname = \"unicode-segmentation\"\nversion = \"1.13.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8\"\n\n[[package]]\nname = \"unicode-width\"\nversion = \"0.2.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557\"\n\n[[package]]\nname = \"untrusted\"\nversion = \"0.9.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1\"\n\n[[package]]\nname = \"ureq\"\nversion = \"3.5.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d\"\ndependencies = [\n \"base64 0.23.1\",\n \"cookie_store\",\n \"log\",\n \"percent-encoding\",\n \"rustls\",\n \"rustls-pki-types\",\n \"serde\",\n \"serde_json\",\n \"ureq-proto\",\n \"utf8-zero\",\n \"webpki-roots\",\n]\n\n[[package]]\nname = \"ureq-proto\"\nversion = \"0.7.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3\"\ndependencies = [\n \"base64 0.23.1\",\n \"http\",\n \"httparse\",\n \"log\",\n]\n\n[[package]]\nname = \"url\"\nversion = \"2.5.8\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed\"\ndependencies = [\n \"form_urlencoded\",\n \"idna\",\n \"percent-encoding\",\n \"serde\",\n]\n\n[[package]]\nname = \"usvg\"\nversion = \"0.45.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef\"\ndependencies = [\n \"base64 0.22.1\",\n \"data-url\",\n \"flate2\",\n \"imagesize\",\n \"kurbo\",\n \"log\",\n \"pico-args\",\n \"roxmltree 0.20.0\",\n \"simplecss\",\n \"siphasher\",\n \"strict-num\",\n \"svgtypes\",\n \"tiny-skia-path 0.11.4 (registry+https://github.com/rust-lang/crates.io-index)\",\n \"xmlwriter\",\n]\n\n[[package]]\nname = \"utf8-zero\"\nversion = \"0.8.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e\"\n\n[[package]]\nname = \"utf8_iter\"\nversion = \"1.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0\"\ndependencies = [\n \"utf_types\",\n]\n\n[[package]]\nname = \"utf_types\"\nversion = \"1.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6\"\n\n[[package]]\nname = \"uuid\"\nversion = \"1.29.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64\"\ndependencies = [\n \"js-sys\",\n \"serde_core\",\n \"wasm-bindgen\",\n]\n\n[[package]]\nname = \"version-ranges\"\nversion = \"0.1.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"31e9bd4e9c9ff6a2a9b5969462ba26216af3e010df0377dad8320ab515262ef8\"\ndependencies = [\n \"semver\",\n \"smallvec\",\n]\n\n[[package]]\nname = \"version_check\"\nversion = \"0.9.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a\"\n\n[[package]]\nname = \"walkdir\"\nversion = \"2.5.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b\"\ndependencies = [\n \"same-file\",\n \"winapi-util\",\n]\n\n[[package]]\nname = \"wasi\"\nversion = \"0.11.1+wasi-snapshot-preview1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b\"\n\n[[package]]\nname = \"wasip2\"\nversion = \"1.0.4+wasi-0.2.12\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487\"\ndependencies = [\n \"wit-bindgen\",\n]\n\n[[package]]\nname = \"wasm-bindgen\"\nversion = \"0.2.130\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c\"\ndependencies = [\n \"cfg-if\",\n \"rustversion\",\n \"wasm-bindgen-macro\",\n \"wasm-bindgen-shared\",\n]\n\n[[package]]\nname = \"wasm-bindgen-futures\"\nversion = \"0.4.80\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501\"\ndependencies = [\n \"js-sys\",\n \"tokio\",\n \"wasm-bindgen\",\n]\n\n[[package]]\nname = \"wasm-bindgen-macro\"\nversion = \"0.2.130\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9\"\ndependencies = [\n \"quote\",\n \"wasm-bindgen-macro-support\",\n]\n\n[[package]]\nname = \"wasm-bindgen-macro-support\"\nversion = \"0.2.130\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a\"\ndependencies = [\n \"bumpalo\",\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n \"wasm-bindgen-shared\",\n]\n\n[[package]]\nname = \"wasm-bindgen-shared\"\nversion = \"0.2.130\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e\"\ndependencies = [\n \"unicode-ident\",\n]\n\n[[package]]\nname = \"wayland-backend\"\nversion = \"0.3.17\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078\"\ndependencies = [\n \"cc\",\n \"downcast-rs\",\n \"rustix 1.1.6\",\n \"scoped-tls\",\n \"smallvec\",\n \"wayland-sys\",\n]\n\n[[package]]\nname = \"wayland-client\"\nversion = \"0.31.15\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"rustix 1.1.6\",\n \"wayland-backend\",\n \"wayland-scanner\",\n]\n\n[[package]]\nname = \"wayland-csd-frame\"\nversion = \"0.3.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"cursor-icon\",\n \"wayland-backend\",\n]\n\n[[package]]\nname = \"wayland-cursor\"\nversion = \"0.31.14\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d\"\ndependencies = [\n \"rustix 1.1.6\",\n \"wayland-client\",\n \"xcursor\",\n]\n\n[[package]]\nname = \"wayland-protocols\"\nversion = \"0.32.13\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"wayland-backend\",\n \"wayland-client\",\n \"wayland-scanner\",\n]\n\n[[package]]\nname = \"wayland-protocols-plasma\"\nversion = \"0.3.12\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"wayland-backend\",\n \"wayland-client\",\n \"wayland-protocols\",\n \"wayland-scanner\",\n]\n\n[[package]]\nname = \"wayland-protocols-wlr\"\nversion = \"0.3.12\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"wayland-backend\",\n \"wayland-client\",\n \"wayland-protocols\",\n \"wayland-scanner\",\n]\n\n[[package]]\nname = \"wayland-scanner\"\nversion = \"0.31.11\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0\"\ndependencies = [\n \"proc-macro2\",\n \"quick-xml\",\n \"quote\",\n]\n\n[[package]]\nname = \"wayland-sys\"\nversion = \"0.31.11\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be\"\ndependencies = [\n \"dlib\",\n \"log\",\n \"once_cell\",\n \"pkg-config\",\n]\n\n[[package]]\nname = \"web-sys\"\nversion = \"0.3.107\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88\"\ndependencies = [\n \"js-sys\",\n \"wasm-bindgen\",\n]\n\n[[package]]\nname = \"web-time\"\nversion = \"1.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb\"\ndependencies = [\n \"js-sys\",\n \"wasm-bindgen\",\n]\n\n[[package]]\nname = \"webpki-roots\"\nversion = \"1.0.12\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297\"\ndependencies = [\n \"rustls-pki-types\",\n]\n\n[[package]]\nname = \"weezl\"\nversion = \"0.1.12\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88\"\n\n[[package]]\nname = \"wgpu\"\nversion = \"30.0.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"146fc3d654250e6207921a66c87534c621bc886c70df83dcf466c1d66813810e\"\ndependencies = [\n \"arrayvec\",\n \"bitflags 2.13.2\",\n \"bytemuck\",\n \"cfg-if\",\n \"cfg_aliases\",\n \"document-features\",\n \"hashbrown 0.17.1\",\n \"js-sys\",\n \"log\",\n \"naga\",\n \"parking_lot\",\n \"portable-atomic\",\n \"profiling\",\n \"raw-window-handle\",\n \"smallvec\",\n \"static_assertions\",\n \"wasm-bindgen\",\n \"wasm-bindgen-futures\",\n \"web-sys\",\n \"wgpu-core\",\n \"wgpu-hal\",\n \"wgpu-types\",\n]\n\n[[package]]\nname = \"wgpu-core\"\nversion = \"30.0.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ad661da2ee99f208c30090b585284b2ab5b8bf2358ddf2d2215592808ec62f1a\"\ndependencies = [\n \"arrayvec\",\n \"bit-set\",\n \"bit-vec\",\n \"bitflags 2.13.2\",\n \"bytemuck\",\n \"cfg_aliases\",\n \"document-features\",\n \"hashbrown 0.17.1\",\n \"indexmap\",\n \"log\",\n \"naga\",\n \"naga-types\",\n \"once_cell\",\n \"parking_lot\",\n \"portable-atomic\",\n \"profiling\",\n \"raw-window-handle\",\n \"rustc-hash 1.1.0\",\n \"smallvec\",\n \"thiserror 2.0.21\",\n \"wgpu-core-deps-apple\",\n \"wgpu-core-deps-windows-linux-android\",\n \"wgpu-hal\",\n \"wgpu-naga-bridge\",\n \"wgpu-types\",\n]\n\n[[package]]\nname = \"wgpu-core-deps-apple\"\nversion = \"30.0.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"7d3f2f24aee039ffe9ef527300daf6b7428c58edeefdaa1700f4fa0fd754df16\"\ndependencies = [\n \"wgpu-hal\",\n]\n\n[[package]]\nname = \"wgpu-core-deps-windows-linux-android\"\nversion = \"30.0.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"1331b08fa2362c5d454eccc4448e6e4f01eccfea569a00e310adbfc4415f2bdc\"\ndependencies = [\n \"wgpu-hal\",\n]\n\n[[package]]\nname = \"wgpu-hal\"\nversion = \"30.0.1\"\nsource = \"git+https://github.com/anomalyco/rune?rev=eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90#eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\"\ndependencies = [\n \"android_system_properties\",\n \"arrayvec\",\n \"ash\",\n \"bit-set\",\n \"bitflags 2.13.2\",\n \"block2 0.6.2\",\n \"bytemuck\",\n \"cfg-if\",\n \"cfg_aliases\",\n \"gpu-allocator\",\n \"hashbrown 0.17.1\",\n \"libc\",\n \"libloading\",\n \"log\",\n \"naga\",\n \"naga-types\",\n \"objc2 0.6.5\",\n \"objc2-core-foundation\",\n \"objc2-core-graphics\",\n \"objc2-foundation 0.3.2\",\n \"objc2-metal 0.3.2\",\n \"objc2-quartz-core 0.3.2\",\n \"once_cell\",\n \"ordered-float\",\n \"parking_lot\",\n \"portable-atomic\",\n \"portable-atomic-util\",\n \"profiling\",\n \"range-alloc\",\n \"raw-window-handle\",\n \"raw-window-metal\",\n \"renderdoc-sys\",\n \"smallvec\",\n \"static_assertions\",\n \"thiserror 2.0.21\",\n \"wgpu-naga-bridge\",\n \"wgpu-types\",\n \"windows\",\n \"windows-core\",\n]\n\n[[package]]\nname = \"wgpu-naga-bridge\"\nversion = \"30.0.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"44a62ead68aad7cd40ac9e2cd2b8ec64f32dfbad2765f429b9fb74b8b735869f\"\ndependencies = [\n \"naga\",\n \"wgpu-types\",\n]\n\n[[package]]\nname = \"wgpu-types\"\nversion = \"30.0.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a9f6ee0bd50f5ab79fb8c25e3f33afb27126f034af4ba5909c7a0967058659e6\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"bytemuck\",\n \"js-sys\",\n \"log\",\n \"naga-types\",\n \"raw-window-handle\",\n \"static_assertions\",\n \"web-sys\",\n]\n\n[[package]]\nname = \"winapi-util\"\nversion = \"0.1.11\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22\"\ndependencies = [\n \"windows-sys 0.61.2\",\n]\n\n[[package]]\nname = \"windows\"\nversion = \"0.62.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580\"\ndependencies = [\n \"windows-collections\",\n \"windows-core\",\n \"windows-future\",\n \"windows-numerics\",\n]\n\n[[package]]\nname = \"windows-collections\"\nversion = \"0.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610\"\ndependencies = [\n \"windows-core\",\n]\n\n[[package]]\nname = \"windows-core\"\nversion = \"0.62.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb\"\ndependencies = [\n \"windows-implement\",\n \"windows-interface\",\n \"windows-link\",\n \"windows-result\",\n \"windows-strings\",\n]\n\n[[package]]\nname = \"windows-future\"\nversion = \"0.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb\"\ndependencies = [\n \"windows-core\",\n \"windows-link\",\n \"windows-threading\",\n]\n\n[[package]]\nname = \"windows-implement\"\nversion = \"0.60.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 2.0.119\",\n]\n\n[[package]]\nname = \"windows-interface\"\nversion = \"0.59.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 2.0.119\",\n]\n\n[[package]]\nname = \"windows-link\"\nversion = \"0.2.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5\"\n\n[[package]]\nname = \"windows-native-keyring-store\"\nversion = \"1.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"063426e76fdec7438d56bb777f67e318a84a25c707b07e575cb8b78e10c028f8\"\ndependencies = [\n \"byteorder\",\n \"keyring-core\",\n \"regex\",\n \"windows-sys 0.61.2\",\n \"zeroize\",\n]\n\n[[package]]\nname = \"windows-numerics\"\nversion = \"0.3.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26\"\ndependencies = [\n \"windows-core\",\n \"windows-link\",\n]\n\n[[package]]\nname = \"windows-registry\"\nversion = \"0.6.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720\"\ndependencies = [\n \"windows-link\",\n \"windows-result\",\n \"windows-strings\",\n]\n\n[[package]]\nname = \"windows-result\"\nversion = \"0.4.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5\"\ndependencies = [\n \"windows-link\",\n]\n\n[[package]]\nname = \"windows-strings\"\nversion = \"0.5.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091\"\ndependencies = [\n \"windows-link\",\n]\n\n[[package]]\nname = \"windows-sys\"\nversion = \"0.52.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d\"\ndependencies = [\n \"windows-targets\",\n]\n\n[[package]]\nname = \"windows-sys\"\nversion = \"0.59.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b\"\ndependencies = [\n \"windows-targets\",\n]\n\n[[package]]\nname = \"windows-sys\"\nversion = \"0.61.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc\"\ndependencies = [\n \"windows-link\",\n]\n\n[[package]]\nname = \"windows-targets\"\nversion = \"0.52.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973\"\ndependencies = [\n \"windows_aarch64_gnullvm\",\n \"windows_aarch64_msvc\",\n \"windows_i686_gnu\",\n \"windows_i686_gnullvm\",\n \"windows_i686_msvc\",\n \"windows_x86_64_gnu\",\n \"windows_x86_64_gnullvm\",\n \"windows_x86_64_msvc\",\n]\n\n[[package]]\nname = \"windows-threading\"\nversion = \"0.2.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37\"\ndependencies = [\n \"windows-link\",\n]\n\n[[package]]\nname = \"windows_aarch64_gnullvm\"\nversion = \"0.52.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3\"\n\n[[package]]\nname = \"windows_aarch64_msvc\"\nversion = \"0.52.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469\"\n\n[[package]]\nname = \"windows_i686_gnu\"\nversion = \"0.52.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b\"\n\n[[package]]\nname = \"windows_i686_gnullvm\"\nversion = \"0.52.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66\"\n\n[[package]]\nname = \"windows_i686_msvc\"\nversion = \"0.52.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66\"\n\n[[package]]\nname = \"windows_x86_64_gnu\"\nversion = \"0.52.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78\"\n\n[[package]]\nname = \"windows_x86_64_gnullvm\"\nversion = \"0.52.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d\"\n\n[[package]]\nname = \"windows_x86_64_msvc\"\nversion = \"0.52.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec\"\n\n[[package]]\nname = \"winit\"\nversion = \"0.30.13\"\nsource = \"git+https://github.com/anomalyco/rune?rev=eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90#eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\"\ndependencies = [\n \"ahash\",\n \"android-activity\",\n \"atomic-waker\",\n \"bitflags 2.13.2\",\n \"block2 0.5.1\",\n \"bytemuck\",\n \"calloop\",\n \"cfg_aliases\",\n \"concurrent-queue\",\n \"core-foundation 0.9.4\",\n \"core-graphics\",\n \"cursor-icon\",\n \"dpi\",\n \"js-sys\",\n \"libc\",\n \"memmap2\",\n \"ndk\",\n \"objc2 0.5.3\",\n \"objc2-app-kit 0.2.2\",\n \"objc2-foundation 0.2.2\",\n \"objc2-ui-kit\",\n \"orbclient\",\n \"percent-encoding\",\n \"pin-project\",\n \"raw-window-handle\",\n \"redox_syscall 0.4.1\",\n \"rustix 0.38.44\",\n \"sctk-adwaita\",\n \"smithay-client-toolkit\",\n \"smol_str\",\n \"tracing\",\n \"unicode-segmentation\",\n \"wasm-bindgen\",\n \"wasm-bindgen-futures\",\n \"wayland-backend\",\n \"wayland-client\",\n \"wayland-protocols\",\n \"wayland-protocols-plasma\",\n \"web-sys\",\n \"web-time\",\n \"windows-sys 0.52.0\",\n \"x11-dl\",\n \"x11rb\",\n \"xkbcommon-dl\",\n]\n\n[[package]]\nname = \"winnow\"\nversion = \"1.0.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef\"\ndependencies = [\n \"memchr\",\n]\n\n[[package]]\nname = \"winreg\"\nversion = \"0.56.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10\"\ndependencies = [\n \"cfg-if\",\n \"windows-sys 0.61.2\",\n]\n\n[[package]]\nname = \"wit-bindgen\"\nversion = \"0.57.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e\"\n\n[[package]]\nname = \"wl-clipboard-rs\"\nversion = \"0.9.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"959c7ac3b8afde864f7a7448ac16f29b2b83350b7eccbf77fb781c3999aa6848\"\ndependencies = [\n \"libc\",\n \"log\",\n \"os_pipe\",\n \"rustix 1.1.6\",\n \"thiserror 2.0.21\",\n \"tree_magic_mini\",\n \"wayland-backend\",\n \"wayland-client\",\n \"wayland-protocols\",\n \"wayland-protocols-wlr\",\n]\n\n[[package]]\nname = \"writeable\"\nversion = \"0.6.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc\"\n\n[[package]]\nname = \"x11-dl\"\nversion = \"2.21.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f\"\ndependencies = [\n \"libc\",\n \"once_cell\",\n \"pkg-config\",\n]\n\n[[package]]\nname = \"x11rb\"\nversion = \"0.13.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414\"\ndependencies = [\n \"as-raw-xcb-connection\",\n \"gethostname\",\n \"libc\",\n \"libloading\",\n \"once_cell\",\n \"rustix 1.1.6\",\n \"x11rb-protocol\",\n]\n\n[[package]]\nname = \"x11rb-protocol\"\nversion = \"0.13.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd\"\n\n[[package]]\nname = \"xattr\"\nversion = \"1.7.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"963d6fab92d5504b971dc8bd90ca743c2575e590bc8071ea5bc571598667ae08\"\ndependencies = [\n \"libc\",\n \"rustix 1.1.6\",\n]\n\n[[package]]\nname = \"xcursor\"\nversion = \"0.3.11\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23\"\n\n[[package]]\nname = \"xkbcommon\"\nversion = \"0.9.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a7a974f48060a14e95705c01f24ad9c3345022f4d97441b8a36beb7ed5c4a02d\"\ndependencies = [\n \"libc\",\n \"memmap2\",\n \"xkeysym\",\n]\n\n[[package]]\nname = \"xkbcommon-dl\"\nversion = \"0.4.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5\"\ndependencies = [\n \"bitflags 2.13.2\",\n \"dlib\",\n \"log\",\n \"once_cell\",\n \"xkeysym\",\n]\n\n[[package]]\nname = \"xkeysym\"\nversion = \"0.2.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56\"\n\n[[package]]\nname = \"xmlwriter\"\nversion = \"0.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9\"\n\n[[package]]\nname = \"yazi\"\nversion = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ac366ea532fa8ee6a992cec9dea525b1dc284e69702f36c2ab5fbebadc81ec86\"\n\n[[package]]\nname = \"yeslogic-fontconfig-sys\"\nversion = \"6.0.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"1d8b8abf912b9a29ff112e1671c97c33636903d13a69712037190e6805af4f76\"\ndependencies = [\n \"dlib\",\n \"once_cell\",\n \"pkg-config\",\n]\n\n[[package]]\nname = \"yoke\"\nversion = \"0.8.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3\"\ndependencies = [\n \"stable_deref_trait\",\n \"yoke-derive\",\n \"zerofrom\",\n]\n\n[[package]]\nname = \"yoke-derive\"\nversion = \"0.8.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n \"synstructure\",\n]\n\n[[package]]\nname = \"zbus\"\nversion = \"5.19.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907\"\ndependencies = [\n \"async-broadcast\",\n \"async-executor\",\n \"async-io\",\n \"async-lock\",\n \"async-process\",\n \"async-recursion\",\n \"async-task\",\n \"async-trait\",\n \"blocking\",\n \"enumflags2\",\n \"event-listener\",\n \"futures-core\",\n \"futures-lite\",\n \"hex\",\n \"libc\",\n \"ordered-stream\",\n \"rustix 1.1.6\",\n \"serde\",\n \"serde_repr\",\n \"tracing\",\n \"uds_windows\",\n \"uuid\",\n \"windows-sys 0.61.2\",\n \"winnow\",\n \"zbus_macros 5.19.0\",\n \"zbus_names\",\n \"zvariant\",\n]\n\n[[package]]\nname = \"zbus\"\nversion = \"6.3.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6b4aae740b23927ceabed962431abab2cdefb9f7f885e5bbab062da09bf580e4\"\ndependencies = [\n \"async-trait\",\n \"bitflags 2.13.2\",\n \"endi\",\n \"futures-core\",\n \"hex\",\n \"libc\",\n \"ordered-stream\",\n \"rustix 1.1.6\",\n \"serde\",\n \"serde_repr\",\n \"socket2\",\n \"tokio\",\n \"uds_windows\",\n \"uuid\",\n \"windows-sys 0.61.2\",\n \"winnow\",\n \"zbus_macros 6.3.0\",\n \"zbus_utils\",\n \"zcheapstr\",\n \"zruntime\",\n]\n\n[[package]]\nname = \"zbus-lockstep\"\nversion = \"0.5.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863\"\ndependencies = [\n \"zbus_xml\",\n \"zvariant\",\n]\n\n[[package]]\nname = \"zbus-lockstep-macros\"\nversion = \"0.5.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 2.0.119\",\n \"zbus-lockstep\",\n \"zbus_xml\",\n \"zvariant\",\n]\n\n[[package]]\nname = \"zbus-secret-service-keyring-store\"\nversion = \"1.0.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a\"\ndependencies = [\n \"keyring-core\",\n \"secret-service\",\n \"zbus 5.19.0\",\n]\n\n[[package]]\nname = \"zbus_macros\"\nversion = \"5.19.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40\"\ndependencies = [\n \"proc-macro-crate\",\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n \"zbus_names\",\n \"zvariant\",\n \"zvariant_utils\",\n]\n\n[[package]]\nname = \"zbus_macros\"\nversion = \"6.3.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"37c9dd4beaf145c16fcb2902862f50da86e54aed13dd368ddf64a1d17e6b8529\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n \"zbus_utils\",\n]\n\n[[package]]\nname = \"zbus_names\"\nversion = \"4.3.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd\"\ndependencies = [\n \"serde\",\n \"winnow\",\n \"zvariant\",\n]\n\n[[package]]\nname = \"zbus_utils\"\nversion = \"6.1.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"serde\",\n \"syn 3.0.10\",\n \"winnow\",\n]\n\n[[package]]\nname = \"zbus_xml\"\nversion = \"5.2.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a\"\ndependencies = [\n \"serde\",\n \"winnow\",\n \"zbus_names\",\n \"zvariant\",\n]\n\n[[package]]\nname = \"zcheapstr\"\nversion = \"1.2.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920\"\ndependencies = [\n \"serde\",\n]\n\n[[package]]\nname = \"zeno\"\nversion = \"0.3.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524\"\n\n[[package]]\nname = \"zerocopy\"\nversion = \"0.8.63\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8\"\ndependencies = [\n \"zerocopy-derive\",\n]\n\n[[package]]\nname = \"zerocopy-derive\"\nversion = \"0.8.63\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 2.0.119\",\n]\n\n[[package]]\nname = \"zerofrom\"\nversion = \"0.1.8\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272\"\ndependencies = [\n \"zerofrom-derive\",\n]\n\n[[package]]\nname = \"zerofrom-derive\"\nversion = \"0.1.8\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n \"synstructure\",\n]\n\n[[package]]\nname = \"zeroize\"\nversion = \"1.9.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879\"\n\n[[package]]\nname = \"zerotrie\"\nversion = \"0.2.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f\"\ndependencies = [\n \"displaydoc\",\n \"yoke\",\n \"zerofrom\",\n \"zerovec\",\n]\n\n[[package]]\nname = \"zerovec\"\nversion = \"0.11.9\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40\"\ndependencies = [\n \"serde\",\n \"yoke\",\n \"zerofrom\",\n \"zerovec-derive\",\n]\n\n[[package]]\nname = \"zerovec-derive\"\nversion = \"0.11.7\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n]\n\n[[package]]\nname = \"zlib-rs\"\nversion = \"0.6.8\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112\"\n\n[[package]]\nname = \"zmij\"\nversion = \"1.0.23\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b\"\n\n[[package]]\nname = \"zruntime\"\nversion = \"0.2.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ce6a55d4f521760475a30f7b96779508fe8c40dc834478709454dd1d5f0ebc72\"\ndependencies = [\n \"futures-core\",\n \"futures-io\",\n]\n\n[[package]]\nname = \"zune-core\"\nversion = \"0.5.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b\"\n\n[[package]]\nname = \"zune-jpeg\"\nversion = \"0.5.15\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296\"\ndependencies = [\n \"zune-core\",\n]\n\n[[package]]\nname = \"zvariant\"\nversion = \"5.15.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7\"\ndependencies = [\n \"endi\",\n \"enumflags2\",\n \"serde\",\n \"winnow\",\n \"zcheapstr\",\n \"zvariant_derive\",\n \"zvariant_utils\",\n]\n\n[[package]]\nname = \"zvariant_derive\"\nversion = \"5.15.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d\"\ndependencies = [\n \"proc-macro-crate\",\n \"proc-macro2\",\n \"quote\",\n \"syn 3.0.10\",\n \"zvariant_utils\",\n]\n\n[[package]]\nname = \"zvariant_utils\"\nversion = \"4.2.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3\"\ndependencies = [\n \"proc-macro2\",\n \"quote\",\n \"serde\",\n \"syn 3.0.10\",\n \"winnow\",\n]\n",
36
+ "type": "registry:file",
37
+ "target": "desktop-rune/Cargo.lock"
38
+ },
39
+ {
40
+ "path": "app/desktop-rune/rustfmt.toml",
41
+ "content": "# Wide lines, as Rune writes view code; the generated protocol types are skipped (see crates/eloxiv-local-client/src/lib.rs).\nmax_width = 120\nuse_small_heuristics = \"Max\"\n",
42
+ "type": "registry:file",
43
+ "target": "desktop-rune/rustfmt.toml"
44
+ },
45
+ {
46
+ "path": "app/desktop-rune/app.json",
47
+ "content": "{\n \"name\": \"Eloxiv\",\n \"identifier\": \"dev.eloxiv.desktop-rune\",\n \"binaryName\": \"eloxiv-app\",\n \"version\": \"0.1.0\",\n \"description\": \"An Eloxiv app\",\n \"publisher\": \"Eloxiv\",\n \"copyright\": \"\",\n \"category\": \"Productivity\",\n \"icon\": \"app-icon.svg\",\n \"urlScheme\": \"eloxiv\",\n \"deepLinks\": { \"register\": true },\n \"servers\": { \"kernelUrl\": \"\", \"zeroUrl\": \"\", \"shellUrl\": \"\" },\n \"updates\": { \"url\": \"\", \"publicKey\": \"\", \"channel\": \"stable\" }\n}\n",
48
+ "type": "registry:file",
49
+ "target": "desktop-rune/app.json"
50
+ },
51
+ {
52
+ "path": "app/desktop-rune/entitlements.plist",
53
+ "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<!-- The hardened runtime's exceptions a signed package needs (scripts/package.ts, only when signing): the app's daemon\n sidecar is a Bun-compiled executable, whose JavaScript engine compiles code at run time. -->\n<plist version=\"1.0\">\n<dict>\n <key>com.apple.security.cs.allow-jit</key>\n <true/>\n <key>com.apple.security.cs.allow-unsigned-executable-memory</key>\n <true/>\n <key>com.apple.security.cs.disable-library-validation</key>\n <true/>\n</dict>\n</plist>\n",
54
+ "type": "registry:file",
55
+ "target": "desktop-rune/entitlements.plist"
56
+ },
57
+ {
58
+ "path": "app/desktop-rune/sidecar/daemon.ts",
59
+ "content": "/**\n * The app's daemon sidecar (decision 14): the generic Eloxiv daemon composed with this app's sync schema, named\n * queries, mutators and module contracts (`clientApp`), so it serves LocalClient (`/client/v1`) to the Rune host.\n * The CLI regenerates the files it imports (`eloxiv.modules.ts`, `eloxiv.sync.ts`) whenever a module is added or\n * updated, so the sidecar always carries the app's current composition. On Bun, as the sidecar ships\n * (`desktop-rune/scripts/build-sidecar.ts` compiles it); `daemon-node.ts` is the same on Node.\n *\n * The kernel, zero-cache and the web page that approves a desktop sign-in come from `ELOXIV_KERNEL_URL`,\n * `ELOXIV_ZERO_URL` and `ELOXIV_SIGN_IN_PAGE` (or `ELOXIV_SHELL_URL`, whose `/desktop/sign-in` it then is).\n *\n * bun desktop-rune/sidecar/daemon.ts --port 4191 # from source, from the app root\n */\nimport { runMain } from \"@eloxiv/daemon/runtime/bun\"\nimport { contracts } from \"../../eloxiv.modules.ts\"\nimport { mutators, queries, schema } from \"../../eloxiv.sync.ts\"\n\n// `--print-views`: the app's views (id, route, title, and the module and entity a record view shows) for the Rune\n// host's deep links (its `parseLink`, and `recordLink` for a notification's record), then nothing else; the host asks\n// once per launch, off its UI thread.\nif (process.argv.includes(\"--print-views\")) {\n const views = contracts.flatMap((m) =>\n Object.entries(m.views ?? {}).map(([id, view]) => ({\n id,\n route: view.route,\n title: view.title,\n module: m.name,\n // Absent (undefined, which JSON leaves out) for a view of a query view.\n entity: \"entity\" in view.shows ? view.shows.entity : undefined,\n })),\n )\n process.stdout.write(`${JSON.stringify(views)}\\n`)\n} else {\n runMain(process.argv.slice(2), process.env, { clientApp: { modules: contracts, schema, queries, mutators } })\n}\n",
60
+ "type": "registry:file",
61
+ "target": "desktop-rune/sidecar/daemon.ts"
62
+ },
63
+ {
64
+ "path": "app/desktop-rune/sidecar/daemon-node.ts",
65
+ "content": "/** The app's daemon sidecar (`daemon.ts`) on Node, the fallback runtime: `node desktop-rune/sidecar/daemon-node.ts`. */\nimport { runMain } from \"@eloxiv/daemon/runtime/node\"\nimport { contracts } from \"../../eloxiv.modules.ts\"\nimport { mutators, queries, schema } from \"../../eloxiv.sync.ts\"\n\n// `--print-views`: the app's views (id, route, title, and the module and entity a record view shows) for the Rune\n// host's deep links (its `parseLink`, and `recordLink` for a notification's record), then nothing else; the host asks\n// once per launch, off its UI thread.\nif (process.argv.includes(\"--print-views\")) {\n const views = contracts.flatMap((m) =>\n Object.entries(m.views ?? {}).map(([id, view]) => ({\n id,\n route: view.route,\n title: view.title,\n module: m.name,\n // Absent (undefined, which JSON leaves out) for a view of a query view.\n entity: \"entity\" in view.shows ? view.shows.entity : undefined,\n })),\n )\n process.stdout.write(`${JSON.stringify(views)}\\n`)\n} else {\n runMain(process.argv.slice(2), process.env, { clientApp: { modules: contracts, schema, queries, mutators } })\n}\n",
66
+ "type": "registry:file",
67
+ "target": "desktop-rune/sidecar/daemon-node.ts"
68
+ },
69
+ {
70
+ "path": "app/desktop-rune/scripts/build-sidecar.ts",
71
+ "content": "/**\n * Builds the app's own daemon sidecar for the Rune host: `sidecar/daemon.ts` compiled with Bun by `@eloxiv/daemon`'s\n * build script into `desktop-rune/target/sidecar/eloxiv-daemon[.exe]`, where the host finds it when it runs from\n * this workspace (`cargo run`, debug or release). For a package, copy that file beside the host's executable.\n *\n * node desktop-rune/scripts/build-sidecar.ts [--target <rust-triple>] # from the app root\n *\n * Needs Node 24, Bun and Rust (`rustc -vV` names this machine's triple) on PATH. Works on Linux, macOS and Windows.\n */\nimport { spawnSync } from \"node:child_process\"\nimport { copyFileSync, mkdirSync, rmSync } from \"node:fs\"\nimport { join, resolve } from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\n\nconst desktopRune = resolve(import.meta.dirname, \"..\")\nconst args = process.argv.slice(2)\nconst flag = (name: string): string | undefined => {\n const index = args.indexOf(name)\n return index >= 0 ? args[index + 1] : args.find((arg) => arg.startsWith(`${name}=`))?.slice(name.length + 1)\n}\n\nconst run = (command: string, commandArgs: ReadonlyArray<string>): string => {\n console.log(`$ ${command} ${commandArgs.join(\" \")}`)\n const result = spawnSync(command, commandArgs, { cwd: desktopRune, stdio: [\"ignore\", \"pipe\", \"inherit\"] })\n if (result.error !== undefined) throw result.error\n process.stdout.write(result.stdout)\n if (result.status !== 0) throw new Error(`${command} exited with ${result.status}`)\n return result.stdout.toString()\n}\n\nconst hostTriple = (): string => {\n const host = /^host:\\s*(\\S+)$/mu.exec(run(\"rustc\", [\"-vV\"]))?.[1]\n if (host === undefined) throw new Error(\"Could not read the host triple from `rustc -vV`\")\n return host\n}\n\nconst triple = flag(\"--target\") ?? hostTriple()\nconst extension = triple.includes(\"windows\") ? \".exe\" : \"\"\nconst outDir = join(desktopRune, \"target\", \"sidecar\")\nmkdirSync(outDir, { recursive: true })\nconst script = fileURLToPath(import.meta.resolve(\"@eloxiv/daemon/build-sidecar\"))\nrun(\"bun\", [\n script,\n \"--entry\",\n join(desktopRune, \"sidecar\", \"daemon.ts\"),\n \"--name\",\n \"eloxiv-daemon\",\n \"--out-dir\",\n outDir,\n \"--target\",\n triple,\n])\n// The build script names it for Tauri (`eloxiv-daemon-<triple>`); the Rune host looks for `eloxiv-daemon`.\nconst built = join(outDir, `eloxiv-daemon-${triple}${extension}`)\nconst sidecar = join(outDir, `eloxiv-daemon${extension}`)\ncopyFileSync(built, sidecar)\nrmSync(built)\nconsole.log(`sidecar: ${sidecar}`)\n",
72
+ "type": "registry:file",
73
+ "target": "desktop-rune/scripts/build-sidecar.ts"
74
+ },
75
+ {
76
+ "path": "app/desktop-rune/scripts/package.ts",
77
+ "content": "/**\n * Packages the Rune host with the app's daemon sidecar into installers, with the app's identity and host settings\n * (`desktop-rune/app.json`, the one file the app edits; the host compiles in the same file, `app/src/config.rs`):\n *\n * node desktop-rune/scripts/package.ts [--target <rust-triple>] [--formats deb,appimage] [--skip-build] # app root\n *\n * - macOS: `<name>.app` and `.dmg`; Windows: an NSIS installer (`.exe`; `--formats nsis,wix` adds an `.msi`); Linux:\n * `.deb` and AppImage. Written to `desktop-rune/target/package/out/`, with `installers.json` listing them.\n * - The tool is [cargo-packager](https://github.com/crabnebula-dev/cargo-packager) (`cargo install cargo-packager\n * --version 0.11.8 --locked`): one configuration for every format of the three systems, the sidecar as an external\n * binary placed beside the host, the URL scheme registered by each format, Apple and Windows signing.\n * - Steps: `app.json` checked (as the host checks it), the sidecar for the target (`build-sidecar.ts`), the host\n * (`cargo build --release`, which compiles `app.json` in: identity, servers, update host), both staged under the\n * app's names (`<binaryName>` and `<binaryName>-daemon`, where the host looks first: beside it on macOS and\n * Windows, `/usr/libexec/` on Linux), then cargo-packager with a configuration written from `app.json`\n * (`target/package/packager.json`). `--skip-build` packages what was built.\n * - The URL scheme (`urlScheme`) is registered by the `.deb`'s desktop entry, the NSIS installer (and removed by its\n * uninstaller) and the bundle's Info.plist; the host leaves those alone at run time and registers it itself only\n * from an AppImage or a development build.\n * - Downloaded tools are pinned: the AppImage step's AppRun, linuxdeploy and its AppImage plugin are fetched here at\n * exact versions, checked against SHA-256 sums ([`PINNED_APPIMAGE_TOOLS`]) and placed where cargo-packager looks\n * (so it downloads nothing itself); the NSIS ApplicationID plugin cargo-packager fetches unchecked is checked\n * against its sum before the installer is accepted. cargo-packager checks its own NSIS, WiX and Tauri-utils\n * downloads, and fetches create-dmg at a fixed commit.\n *\n * Signing runs only when its credentials are in the environment, else the installers are unsigned and this says so:\n *\n * - macOS: `APPLE_SIGNING_IDENTITY` (a \"Developer ID Application: ...\" identity in the keychain, or with\n * `APPLE_CERTIFICATE` (a base64 .p12) and `APPLE_CERTIFICATE_PASSWORD`, imported into a temporary keychain) signs the\n * app, its sidecar and the dmg with the hardened runtime and `entitlements.plist` (Bun's JIT); notarisation follows\n * with `APPLE_ID`, `APPLE_PASSWORD` (an app-specific password) and `APPLE_TEAM_ID`, or `APPLE_API_KEY`,\n * `APPLE_API_ISSUER` and `APPLE_API_KEY_PATH`.\n * - Windows: `WINDOWS_CERTIFICATE_THUMBPRINT` (a certificate in the store; `WINDOWS_TIMESTAMP_URL`, default\n * DigiCert's) through signtool, or `WINDOWS_SIGN_COMMAND`, a command with `%1` for the file (Azure Trusted Signing,\n * a key vault), signs the sidecar, the host and the installer.\n * - Linux: nothing to sign.\n *\n * Needs Node 24, Bun and Rust on PATH, and cargo-packager (`CARGO_PACKAGER`, else `cargo packager`). Linux needs\n * `libxkbcommon-dev` and `libwayland-dev` to build; the AppImage step downloads linuxdeploy.\n */\nimport { spawnSync } from \"node:child_process\"\nimport { createHash } from \"node:crypto\"\nimport {\n chmodSync,\n copyFileSync,\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { dirname, isAbsolute, join, resolve } from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\n\nconst desktopRune = resolve(import.meta.dirname, \"..\")\nconst args = process.argv.slice(2)\nconst flag = (name: string): string | undefined => {\n const index = args.indexOf(name)\n return index >= 0 ? args[index + 1] : args.find((arg) => arg.startsWith(`${name}=`))?.slice(name.length + 1)\n}\n\n/**\n * `app.json`: the app's identity and host settings. The host compiles in the same file and checks it the same way\n * (`app/src/config.rs`); the release signer reads it too (`eloxiv-update release --config app.json`).\n */\nexport interface Identity {\n readonly name: string\n readonly identifier: string\n readonly binaryName: string\n readonly version: string\n readonly urlScheme: string\n readonly description?: string\n readonly publisher?: string\n readonly copyright?: string\n readonly category?: string\n /** The app's icon, an SVG or a square PNG of at least 512 px, from which every size the installers need is made. */\n readonly icon?: string\n /** Register the scheme at launch where no installer did (an AppImage, a development build). Default true. */\n readonly deepLinks?: { readonly register?: boolean }\n /** What a packaged app reaches, given to its sidecar; empty: the daemon's defaults. */\n readonly servers?: { readonly kernelUrl?: string; readonly zeroUrl?: string; readonly shellUrl?: string }\n /** The update manifest's URL and the minisign public key; without both, updates are unsupported. */\n readonly updates?: { readonly url?: string; readonly publicKey?: string; readonly channel?: string }\n}\n\nconst FIELDS: Readonly<Record<string, ReadonlyArray<string> | null>> = {\n name: null,\n identifier: null,\n binaryName: null,\n version: null,\n urlScheme: null,\n description: null,\n publisher: null,\n copyright: null,\n category: null,\n icon: null,\n deepLinks: [\"register\"],\n servers: [\"kernelUrl\", \"zeroUrl\", \"shellUrl\"],\n updates: [\"url\", \"publicKey\", \"channel\"],\n}\nconst RESERVED_SCHEMES = new Set([\n \"http\",\n \"https\",\n \"file\",\n \"ftp\",\n \"mailto\",\n \"javascript\",\n \"data\",\n \"about\",\n \"blob\",\n \"ws\",\n \"wss\",\n \"tel\",\n \"sms\",\n])\nconst SEGMENT = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/u\nconst SEMVER = /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$/u\nconst httpUrl = (value: string) => {\n try {\n const url = new URL(value)\n return (url.protocol === \"http:\" || url.protocol === \"https:\") && url.hostname !== \"\"\n } catch {\n return false\n }\n}\n\n/** Every problem of an `app.json`'s content, as the host's `config::parse` reports them (none: valid). */\nexport const configProblems = (config: Record<string, unknown>): ReadonlyArray<string> => {\n const problems: Array<string> = []\n const text = (key: string) => (typeof config[key] === \"string\" ? config[key] : \"\")\n for (const [key, value] of Object.entries(config)) {\n const nested = FIELDS[key]\n if (nested === undefined) problems.push(`unknown field ${JSON.stringify(key)}`)\n else if (nested === null && typeof value !== \"string\") problems.push(`${key} is not a string`)\n else if (nested !== null) {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) problems.push(`${key} is not an object`)\n else\n for (const inner of Object.keys(value))\n if (!nested.includes(inner)) problems.push(`unknown field ${JSON.stringify(`${key}.${inner}`)}`)\n }\n }\n if (text(\"name\").trim() === \"\") problems.push(\"name is empty\")\n const id = text(\"identifier\")\n const segments = id.split(\".\")\n if (id.length > 255 || segments.length < 2 || !segments.every((s) => SEGMENT.test(s)))\n problems.push(`identifier ${JSON.stringify(config[\"identifier\"])} is not reverse-DNS (com.example.app)`)\n if (!/^[a-z0-9][a-z0-9-]*$/u.test(text(\"binaryName\")))\n problems.push(`binaryName ${JSON.stringify(config[\"binaryName\"])}: lower case letters, digits and -`)\n if (!SEMVER.test(text(\"version\").trim()))\n problems.push(`version ${JSON.stringify(config[\"version\"])} is not major.minor.patch`)\n const scheme = text(\"urlScheme\")\n if (!/^[a-z][a-z0-9+.-]{1,63}$/u.test(scheme) || RESERVED_SCHEMES.has(scheme))\n problems.push(\n `urlScheme ${JSON.stringify(config[\"urlScheme\"])} is not a URL scheme this app may own (lower case, not http, file, …)`,\n )\n const section = (key: string) => (config[key] ?? {}) as Record<string, unknown>\n const register = section(\"deepLinks\")[\"register\"]\n if (register !== undefined && typeof register !== \"boolean\") problems.push(\"deepLinks.register is not true or false\")\n for (const key of [\"kernelUrl\", \"zeroUrl\", \"shellUrl\"]) {\n const value = section(\"servers\")[key]\n if (value !== undefined && typeof value !== \"string\") problems.push(`servers.${key} is not a string`)\n else if (typeof value === \"string\" && value.trim() !== \"\" && !httpUrl(value.trim()))\n problems.push(`servers.${key} ${JSON.stringify(value)} is not an http(s) URL`)\n }\n const updates = section(\"updates\")\n for (const key of [\"url\", \"publicKey\", \"channel\"])\n if (updates[key] !== undefined && typeof updates[key] !== \"string\") problems.push(`updates.${key} is not a string`)\n const filled = (value: unknown) => typeof value === \"string\" && value.trim() !== \"\"\n if (filled(updates[\"url\"]) && !filled(updates[\"publicKey\"]))\n problems.push(\"updates.url is set without updates.publicKey: updates stay off\")\n return problems\n}\n\n/** Reads and checks `app.json`; throws with every problem. */\nexport const readIdentity = (file: string): Identity => {\n const config = JSON.parse(readFileSync(file, \"utf8\")) as unknown\n if (typeof config !== \"object\" || config === null || Array.isArray(config)) throw new Error(`${file}: not an object`)\n const problems = configProblems(config as Record<string, unknown>)\n if (problems.length > 0) throw new Error(`${file}: ${problems.join(\"; \")}`)\n return config as Identity\n}\n\n/** A tool the AppImage step needs, at an exact version, with its SHA-256. */\nexport interface PinnedTool {\n /** The file name cargo-packager looks for in its tools directory (`<cache>/.cargo-packager/AppImage/`). */\n readonly name: string\n readonly url: string\n readonly sha256: string\n}\n\n/**\n * The AppImage step's tools, per architecture: AppRun (tauri-apps/binary-releases `apprun-old`), linuxdeploy\n * `1-alpha-20251107-1` and linuxdeploy-plugin-appimage `1-alpha-20250213-1` (cargo-packager 0.11.8 would fetch the\n * moving `continuous` builds, unchecked). Change a version and its sum together.\n */\nexport const PINNED_APPIMAGE_TOOLS: Readonly<Record<string, ReadonlyArray<PinnedTool>>> = {\n x86_64: [\n {\n name: \"AppRun-x86_64\",\n url: \"https://github.com/tauri-apps/binary-releases/releases/download/apprun-old/AppRun-x86_64\",\n sha256: \"f30140a43a0a59e46db21bdefdf749b9e9f2c6946e92afabbacf98b8ae73fb4f\",\n },\n {\n name: \"linuxdeploy-x86_64.AppImage\",\n url: \"https://github.com/linuxdeploy/linuxdeploy/releases/download/1-alpha-20251107-1/linuxdeploy-x86_64.AppImage\",\n sha256: \"c20cd71e3a4e3b80c3483cef793cda3f4e990aca14014d23c544ca3ce1270b4d\",\n },\n {\n name: \"linuxdeploy-plugin-appimage.AppImage\",\n url: \"https://github.com/linuxdeploy/linuxdeploy-plugin-appimage/releases/download/1-alpha-20250213-1/linuxdeploy-plugin-appimage-x86_64.AppImage\",\n sha256: \"992d502a248e14ab185448ddf6f6e7d25558cb84d4623c354c3af350c25fccb3\",\n },\n ],\n aarch64: [\n {\n name: \"AppRun-aarch64\",\n url: \"https://github.com/tauri-apps/binary-releases/releases/download/apprun-old/AppRun-aarch64\",\n sha256: \"072f17c0895a85c490282fe5395c5007e5fc75da727e553b3b8fb680feb11578\",\n },\n {\n name: \"linuxdeploy-aarch64.AppImage\",\n url: \"https://github.com/linuxdeploy/linuxdeploy/releases/download/1-alpha-20251107-1/linuxdeploy-aarch64.AppImage\",\n sha256: \"620095110d693282b8ebeb244a95b5e911cf8f65f76c88b4b47d16ae6346fcff\",\n },\n {\n name: \"linuxdeploy-plugin-appimage.AppImage\",\n url: \"https://github.com/linuxdeploy/linuxdeploy-plugin-appimage/releases/download/1-alpha-20250213-1/linuxdeploy-plugin-appimage-aarch64.AppImage\",\n sha256: \"83c292149274965a865dcd44c135cfca8ba28c6b7de3eb628d4b8b5f248af17c\",\n },\n ],\n}\n\n/**\n * The NSIS ApplicationID plugin cargo-packager downloads without a check (tauri-apps/binary-releases\n * `nsis-plugins-v0`, `ReleaseUnicode/ApplicationID.dll`): checked before an installer that embeds it is accepted.\n */\nexport const NSIS_APPLICATION_ID_SHA256 = \"f6851dcbf0a39edecd8a46564bc455e5273736c3dbcb02b954c201c79ccdf117\"\n\nexport const sha256Of = (file: string) => createHash(\"sha256\").update(readFileSync(file)).digest(\"hex\")\n\n/** cargo-packager's tools directory: `dirs::cache_dir()/.cargo-packager`. */\nexport const packagerTools = (env: Readonly<Record<string, string | undefined>>, platform = process.platform) => {\n if (platform === \"win32\") return join(env[\"LOCALAPPDATA\"] ?? join(homedir(), \"AppData\", \"Local\"), \".cargo-packager\")\n if (platform === \"darwin\") return join(homedir(), \"Library\", \"Caches\", \".cargo-packager\")\n const xdg = env[\"XDG_CACHE_HOME\"]\n return join(xdg !== undefined && isAbsolute(xdg) ? xdg : join(homedir(), \".cache\"), \".cargo-packager\")\n}\n\n/**\n * Each pinned tool, downloaded once into `downloads` and checked against its sum (also on every later use), copied\n * fresh into cargo-packager's `AppImage` tools directory (its script patches linuxdeploy in place, so a copy kept\n * there is never trusted).\n */\nconst pinAppImageTools = async (arch: string, downloads: string, tools: string) => {\n const pinned = PINNED_APPIMAGE_TOOLS[arch]\n if (pinned === undefined) throw new Error(`no pinned AppImage tools for ${arch}: add them to PINNED_APPIMAGE_TOOLS`)\n mkdirSync(downloads, { recursive: true })\n mkdirSync(tools, { recursive: true })\n for (const tool of pinned) {\n const file = join(downloads, `${tool.sha256.slice(0, 16)}-${tool.name}`)\n if (!existsSync(file) || sha256Of(file) !== tool.sha256) {\n console.log(`downloading ${tool.url}`)\n const response = await fetch(tool.url, { redirect: \"follow\" })\n if (!response.ok) throw new Error(`${tool.url}: HTTP ${response.status}`)\n const bytes = Buffer.from(await response.arrayBuffer())\n const got = createHash(\"sha256\").update(bytes).digest(\"hex\")\n if (got !== tool.sha256) throw new Error(`${tool.url}: SHA-256 ${got}, expected ${tool.sha256}: refused`)\n writeFileSync(file, bytes)\n }\n const target = join(tools, tool.name)\n rmSync(target, { force: true })\n copyFileSync(file, target)\n chmodSync(target, 0o755)\n console.log(`pinned: ${tool.name} (sha256 ${tool.sha256})`)\n }\n}\n\n/** The NSIS ApplicationID plugin in cargo-packager's tools, if there: true when it matches its sum. */\nconst nsisPluginOk = (tools: string): boolean | undefined => {\n const dll = join(tools, \"NSIS\", \"Plugins\", \"x86-unicode\", \"ApplicationID.dll\")\n return existsSync(dll) ? sha256Of(dll) === NSIS_APPLICATION_ID_SHA256 : undefined\n}\n\n/**\n * The environment children get, without variables set to the empty string: CI passes a secret that is not set as an\n * empty value, and cargo-packager (or a signer) would read an empty `APPLE_ID` or certificate as a credential.\n */\nexport const childEnv = (env: NodeJS.ProcessEnv): NodeJS.ProcessEnv =>\n Object.fromEntries(Object.entries(env).filter(([, value]) => value !== undefined && value !== \"\"))\n\nconst run = (command: string, commandArgs: ReadonlyArray<string>, options: { readonly capture?: boolean } = {}) => {\n console.log(`$ ${command} ${commandArgs.join(\" \")}`)\n const result = spawnSync(command, commandArgs, {\n cwd: desktopRune,\n env: childEnv(process.env),\n stdio: options.capture === true ? [\"ignore\", \"pipe\", \"inherit\"] : \"inherit\",\n encoding: \"utf8\",\n })\n if (result.error !== undefined) throw result.error\n if (result.status !== 0) throw new Error(`${command} ${commandArgs.join(\" \")} exited with ${result.status}`)\n return result.stdout ?? \"\"\n}\n\nconst hostTriple = (): string => {\n const host = /^host:\\s*(\\S+)$/mu.exec(run(\"rustc\", [\"-vV\"], { capture: true }))?.[1]\n if (host === undefined) throw new Error(\"Could not read the host triple from `rustc -vV`\")\n return host\n}\n\nexport type Os = \"macos\" | \"windows\" | \"linux\"\nexport const osOf = (triple: string): Os =>\n triple.includes(\"apple\") ? \"macos\" : triple.includes(\"windows\") ? \"windows\" : \"linux\"\n\nexport interface Signing {\n readonly macos?: { readonly signingIdentity: string }\n readonly windows?:\n | { readonly signCommand: string }\n | {\n readonly certificateThumbprint: string\n readonly digestAlgorithm: string\n readonly timestampUrl: string\n readonly tsp: boolean\n }\n /** Whether the installers are signed. */\n readonly signed: boolean\n /** What is signed and notarised, and what is not and why: printed and kept in installers.json. */\n readonly notes: ReadonlyArray<string>\n}\n\n/** Which signing the environment allows, and what it leaves out (said, never silent). */\nexport const signingOf = (env: Readonly<Record<string, string | undefined>>, os: Os): Signing => {\n const value = (name: string) => ((env[name] ?? \"\") === \"\" ? undefined : env[name])\n if (os === \"macos\") {\n const identity = value(\"APPLE_SIGNING_IDENTITY\")\n if (identity === undefined)\n return {\n signed: false,\n notes: [\n \"unsigned: APPLE_SIGNING_IDENTITY is not set (the app and the dmg are not code-signed; Gatekeeper refuses a downloaded copy)\",\n \"not notarised: nothing is signed\",\n ],\n }\n const notarise =\n (value(\"APPLE_ID\") && value(\"APPLE_PASSWORD\") && value(\"APPLE_TEAM_ID\")) ||\n (value(\"APPLE_API_KEY\") && value(\"APPLE_API_ISSUER\") && value(\"APPLE_API_KEY_PATH\"))\n return {\n macos: { signingIdentity: identity },\n signed: true,\n notes: [\n `signed as ${JSON.stringify(identity)} with the hardened runtime and entitlements.plist`,\n notarise\n ? \"notarised by Apple's notary service (credentials from the environment)\"\n : \"not notarised: neither APPLE_ID, APPLE_PASSWORD and APPLE_TEAM_ID nor APPLE_API_KEY, APPLE_API_ISSUER and APPLE_API_KEY_PATH are set\",\n ],\n }\n }\n if (os === \"windows\") {\n const command = value(\"WINDOWS_SIGN_COMMAND\")\n if (command !== undefined)\n return { windows: { signCommand: command }, signed: true, notes: [\"signed with WINDOWS_SIGN_COMMAND\"] }\n const thumbprint = value(\"WINDOWS_CERTIFICATE_THUMBPRINT\")\n if (thumbprint !== undefined)\n return {\n windows: {\n certificateThumbprint: thumbprint,\n digestAlgorithm: \"sha256\",\n timestampUrl: value(\"WINDOWS_TIMESTAMP_URL\") ?? \"http://timestamp.digicert.com\",\n tsp: true,\n },\n signed: true,\n notes: [`signed with the certificate ${thumbprint} (signtool)`],\n }\n return {\n signed: false,\n notes: [\n \"unsigned: neither WINDOWS_CERTIFICATE_THUMBPRINT nor WINDOWS_SIGN_COMMAND is set (SmartScreen warns on a downloaded copy)\",\n ],\n }\n }\n return { signed: false, notes: [\"Linux packages are not signed\"] }\n}\n\n/** The formats each system builds by default. */\nexport const DEFAULT_FORMATS: Readonly<Record<Os, ReadonlyArray<string>>> = {\n macos: [\"app\", \"dmg\"],\n windows: [\"nsis\"],\n linux: [\"deb\", \"appimage\"],\n}\n\n/** cargo-packager's configuration for the staged binaries (pure; `paths` are absolute). */\nexport const packagerConfig = (input: {\n readonly identity: Identity\n readonly triple: string\n readonly formats: ReadonlyArray<string>\n readonly paths: {\n readonly icons: ReadonlyArray<string>\n readonly stage: string\n /** The staged sidecar. */\n readonly sidecar: string\n readonly out: string\n readonly desktopTemplate: string\n }\n readonly signing: Signing\n}) => {\n const { identity, paths, signing } = input\n return {\n name: identity.binaryName,\n productName: identity.name,\n version: identity.version,\n identifier: identity.identifier,\n ...(identity.description ? { description: identity.description } : {}),\n ...(identity.publisher ? { publisher: identity.publisher } : {}),\n ...(identity.copyright ? { copyright: identity.copyright } : {}),\n ...(identity.category ? { category: identity.category } : {}),\n icons: paths.icons,\n outDir: paths.out,\n binariesDir: paths.stage,\n targetTriple: input.triple,\n formats: input.formats,\n binaries: [{ path: identity.binaryName, main: true }],\n // macOS and Windows: `<binaryName>-daemon-<triple>[.exe]` in the stage, installed beside the host as\n // `<binaryName>-daemon[.exe]`. Linux: `/usr/libexec/<binaryName>-daemon` (an internal executable, not a command;\n // and the AppImage's linuxdeploy rewrites every executable in usr/bin, which breaks a Bun-compiled one).\n ...(osOf(input.triple) === \"linux\"\n ? {}\n : { externalBinaries: [join(paths.stage, `${identity.binaryName}-daemon`)] }),\n deepLinkProtocols: [{ schemes: [identity.urlScheme], role: \"viewer\" }],\n linux: { generateDesktopEntry: true },\n deb: {\n // Rune links libxkbcommon and libwayland-client (an X11 session needs libxkbcommon-x11 too) and draws through\n // Vulkan, else OpenGL ES (EGL).\n depends: [\"libxkbcommon0\", \"libxkbcommon-x11-0\", \"libwayland-client0\", \"libvulkan1 | libegl1\"],\n packageName: identity.binaryName,\n desktopTemplate: paths.desktopTemplate,\n section: \"utils\",\n files: { [paths.sidecar]: `/usr/libexec/${identity.binaryName}-daemon` },\n },\n appimage: { files: { [paths.sidecar]: `/usr/libexec/${identity.binaryName}-daemon` } },\n macos: {\n minimumSystemVersion: \"11.0\",\n ...(signing.macos === undefined\n ? {}\n : { ...signing.macos, entitlements: join(desktopRune, \"entitlements.plist\") }),\n },\n ...(signing.windows === undefined ? {} : { windows: signing.windows }),\n // Per user: no administrator prompt, installed under %LOCALAPPDATA%.\n nsis: { installMode: \"currentUser\" },\n }\n}\n\n/**\n * The Linux desktop entry: cargo-packager's own, with `StartupWMClass` the app's identifier (the window's app id), so\n * the desktop matches the running window to this entry and its icon.\n */\nexport const desktopTemplate = (identity: Identity) =>\n [\n \"[Desktop Entry]\",\n \"Categories={{categories}}\",\n \"{{#if comment}}\",\n \"Comment={{comment}}\",\n \"{{/if}}\",\n \"Exec={{exec}} {{exec_arg}}\",\n \"Icon={{icon}}\",\n \"Name={{name}}\",\n `StartupWMClass=${identity.identifier}`,\n \"Terminal=false\",\n \"Type=Application\",\n \"{{#if mime_type}}\",\n \"MimeType={{mime_type}}\",\n \"{{/if}}\",\n \"\",\n ].join(\"\\n\")\n\n/** The installers' icons, made from the app's icon by the Tauri CLI's icon generator (absolute paths). */\nconst makeIcons = (identity: Identity, dir: string): ReadonlyArray<string> => {\n if (identity.icon === undefined) return []\n // The CLI package (main.js), resolved from the app, as build-sidecar.ts resolves the daemon's build script.\n const cli = dirname(fileURLToPath(import.meta.resolve(\"@tauri-apps/cli\")))\n run(process.execPath, [join(cli, \"tauri.js\"), \"icon\", join(desktopRune, identity.icon), \"--output\", dir])\n return [\"32x32.png\", \"64x64.png\", \"128x128.png\", \"icon.png\", \"icon.icns\", \"icon.ico\"]\n .map((name) => join(dir, name))\n .filter((file) => existsSync(file))\n}\n\n/**\n * signtool.exe: `SIGNTOOL` when set, else the newest Windows Kits 10 copy for this machine's architecture (the hosted\n * Windows runners have it there, not on PATH), else whatever PATH finds.\n */\nexport const signtool = (\n env: NodeJS.ProcessEnv,\n kits = join(env[\"ProgramFiles(x86)\"] ?? \"C:\\\\Program Files (x86)\", \"Windows Kits\", \"10\", \"bin\"),\n): string => {\n if (env[\"SIGNTOOL\"]) return env[\"SIGNTOOL\"]\n const arch = process.arch === \"arm64\" ? \"arm64\" : \"x64\"\n const versions = existsSync(kits)\n ? readdirSync(kits)\n .filter((name) => /^10\\.\\d+\\.\\d+\\.\\d+$/.test(name) && existsSync(join(kits, name, arch, \"signtool.exe\")))\n .sort((a, b) => {\n const pa = a.split(\".\").map(Number)\n const pb = b.split(\".\").map(Number)\n for (let i = 0; i < 4; i++) if (pa[i] !== pb[i]) return pb[i]! - pa[i]!\n return 0\n })\n : []\n return versions[0] === undefined ? \"signtool\" : join(kits, versions[0], arch, \"signtool.exe\")\n}\n\n/** Sign one file the way the environment says (Windows: cargo-packager signs the host and installer, not a sidecar). */\nconst signFile = (windows: NonNullable<Signing[\"windows\"]>, file: string) => {\n if (\"signCommand\" in windows) {\n const [command, ...rest] = windows.signCommand.split(\" \").filter(Boolean)\n run(\n command!,\n rest.map((part) => part.replaceAll(\"%1\", file)),\n )\n } else\n run(signtool(process.env), [\n \"sign\",\n \"/fd\",\n windows.digestAlgorithm,\n \"/sha1\",\n windows.certificateThumbprint,\n \"/tr\",\n windows.timestampUrl,\n \"/td\",\n windows.digestAlgorithm,\n file,\n ])\n}\n\nconst main = async () => {\n const identity = readIdentity(join(desktopRune, \"app.json\"))\n const explicit = flag(\"--target\")\n const triple = explicit ?? hostTriple()\n const os = osOf(triple)\n const exe = os === \"windows\" ? \".exe\" : \"\"\n const formats = flag(\"--formats\")?.split(\",\").filter(Boolean) ?? [...DEFAULT_FORMATS[os]]\n const packageDir = join(desktopRune, \"target\", \"package\")\n const stage = join(packageDir, \"stage\")\n const out = join(packageDir, \"out\")\n\n if (!args.includes(\"--skip-build\")) {\n run(process.execPath, [join(desktopRune, \"scripts\", \"build-sidecar.ts\"), \"--target\", triple])\n // The host's own triple without --target, so the build is the one `cargo build --release` makes.\n run(\"cargo\", [\n \"build\",\n \"--release\",\n \"--locked\",\n \"-p\",\n \"eloxiv-desktop-rune\",\n ...(explicit ? [\"--target\", triple] : []),\n ])\n }\n const built = join(desktopRune, \"target\", ...(explicit ? [triple] : []), \"release\", `eloxiv-desktop-rune${exe}`)\n const sidecar = join(desktopRune, \"target\", \"sidecar\", `eloxiv-daemon${exe}`)\n for (const file of [built, sidecar]) if (!existsSync(file)) throw new Error(`${file} is missing: build it first`)\n\n rmSync(packageDir, { recursive: true, force: true })\n mkdirSync(stage, { recursive: true })\n copyFileSync(built, join(stage, `${identity.binaryName}${exe}`))\n const stagedSidecar = join(stage, `${identity.binaryName}-daemon-${triple}${exe}`)\n copyFileSync(sidecar, stagedSidecar)\n\n const signing = signingOf(process.env, os)\n for (const note of signing.notes) console.log(`signing: ${note}`)\n if (signing.windows !== undefined) signFile(signing.windows, stagedSidecar)\n\n const icons = makeIcons(identity, join(packageDir, \"icons\"))\n const template = join(packageDir, \"app.desktop\")\n writeFileSync(template, desktopTemplate(identity))\n const config = packagerConfig({\n identity,\n triple,\n formats,\n paths: { icons, stage, sidecar: stagedSidecar, out, desktopTemplate: template },\n signing,\n })\n const configFile = join(packageDir, \"packager.json\")\n writeFileSync(configFile, `${JSON.stringify(config, null, 2)}\\n`)\n const tools = packagerTools(process.env)\n if (formats.includes(\"appimage\"))\n await pinAppImageTools(triple.split(\"-\")[0]!, join(desktopRune, \"target\", \"package-tools\"), join(tools, \"AppImage\"))\n // A plugin that does not match: removed with its toolset, which cargo-packager then fetches again.\n if (formats.includes(\"nsis\") && nsisPluginOk(tools) === false)\n rmSync(join(tools, \"NSIS\"), { recursive: true, force: true })\n const packager = process.env[\"CARGO_PACKAGER\"]\n if (packager) run(packager, [\"--config\", configFile])\n else run(\"cargo\", [\"packager\", \"--config\", configFile])\n if (formats.includes(\"nsis\") && nsisPluginOk(tools) !== true) {\n rmSync(out, { recursive: true, force: true })\n throw new Error(\n `the NSIS ApplicationID plugin in ${tools} does not match its SHA-256 (${NSIS_APPLICATION_ID_SHA256}): installers removed`,\n )\n }\n\n // What was made: every entry cargo-packager wrote at the top of the out directory (an .app is a directory).\n const installers = readdirSync(out)\n .filter((name) => !name.startsWith(\".\"))\n .map((name) => ({ name, path: join(out, name), directory: statSync(join(out, name)).isDirectory() }))\n const manifest = {\n identity: {\n name: identity.name,\n identifier: identity.identifier,\n version: identity.version,\n binaryName: identity.binaryName,\n },\n triple,\n formats,\n signed: signing.signed,\n signing: signing.notes,\n installers,\n }\n writeFileSync(join(out, \"installers.json\"), `${JSON.stringify(manifest, null, 2)}\\n`)\n console.log(`installers (${triple}, ${signing.signed ? \"signed\" : \"unsigned\"}):`)\n for (const installer of installers) console.log(` ${installer.path}`)\n}\n\nif (import.meta.main) await main()\n",
78
+ "type": "registry:file",
79
+ "target": "desktop-rune/scripts/package.ts"
80
+ },
81
+ {
82
+ "path": "app/desktop-rune/scripts/measure-launch.ts",
83
+ "content": "/**\n * Launch the Rune host (a packaged, installed copy, or a release build) several times and measure launch to\n * interactive, checking its sidecar each time: the daemon answers /health while the app runs and is gone once the\n * app has exited.\n *\n * node desktop-rune/scripts/measure-launch.ts --app <executable> [--runs 20] [--port <n>] [--budget 1500]\n * [--crash] [--json <file>]\n *\n * The daemon's port is the host's own choice (a packaged app's: a free port each launch; a development build's:\n * 4191), read from the host's `[eloxiv-daemon] spawned pid=<pid> port=<port>` line; `--port` fixes it instead\n * (`ELOXIV_DAEMON_PORT`).\n *\n * Interactive is the host's own probe line (`app/src/launch.rs`): the start of the frame after the first frame that\n * drew the screen the daemon's session calls for (the sign-in screen, or the signed-in screen with its list), the\n * daemon having answered /health, hello and opened the event stream. The budget is measured on this harness's clock,\n * from spawning the process to that line, so it counts everything before the host's `main` too. Each launch starts\n * signed out: a fresh daemon state directory and host data directory for the whole measurement (the daemon's sign-in\n * needs a browser); the daemon reaches the kernel and sync server through `ELOXIV_KERNEL_URL` and `ELOXIV_ZERO_URL`\n * (or the app's clientApp).\n *\n * Needs a display (on Linux `DISPLAY` or `WAYLAND_DISPLAY`, for example Xvfb). Each run stops the app the way the\n * operating system asks an app to quit (SIGTERM on Linux and macOS; on Windows a close request to its window,\n * `taskkill` without `/F`) and checks the daemon stopped with it. `--crash` adds one run that kills the host outright\n * (SIGKILL, `taskkill /F`) and checks the daemon exits through its stdin lifeline. Exits non-zero if a check fails or\n * the p95 exceeds `--budget`.\n */\nimport { spawn, spawnSync, type ChildProcess } from \"node:child_process\"\nimport { mkdtempSync, rmSync, writeFileSync } from \"node:fs\"\nimport { get } from \"node:http\"\nimport { tmpdir } from \"node:os\"\nimport { join, resolve } from \"node:path\"\n\nconst args = process.argv.slice(2)\nconst option = (name: string, fallback: string) => {\n const index = args.indexOf(name)\n return index >= 0 && args[index + 1] !== undefined ? args[index + 1]! : fallback\n}\nconst windows = process.platform === \"win32\"\nconst app = resolve(option(\"--app\", \"\"))\nconst runs = Number(option(\"--runs\", \"20\"))\n/** A fixed daemon port (`--port`), else the one the host chose, read from its output per launch. */\nconst fixedPort = option(\"--port\", \"\") === \"\" ? undefined : Number(option(\"--port\", \"\"))\nconst budget = Number(option(\"--budget\", \"1500\"))\nconst crash = args.includes(\"--crash\")\n/** Write the spawn-to-interactive samples (ms) as a JSON array, for the benchmark runner. */\nconst json = option(\"--json\", \"\")\nif (option(\"--app\", \"\") === \"\") throw new Error(\"usage: measure-launch.ts --app <executable> [--runs 20] ...\")\n\nconst sleep = (ms: number) => new Promise((done) => setTimeout(done, ms))\n\n/** GET /health with node:http (no host secret needed). */\nconst health = (port: number): Promise<{ status?: string; runtime?: string } | undefined> =>\n new Promise((done) => {\n const request = get({ host: \"127.0.0.1\", port, path: \"/health\", timeout: 1000 }, (response) => {\n let body = \"\"\n response.setEncoding(\"utf8\")\n response.on(\"data\", (chunk: string) => (body += chunk))\n response.on(\"end\", () => {\n let parsed: { status?: string; runtime?: string } | undefined\n try {\n parsed = response.statusCode === 200 ? JSON.parse(body) : undefined\n } catch {\n parsed = undefined\n }\n done(parsed)\n })\n })\n request.on(\"timeout\", () => request.destroy())\n request.on(\"error\", () => done(undefined))\n })\n\nconst waitFor = async (check: () => boolean | Promise<boolean>, timeoutMs: number, what: string) => {\n const deadline = performance.now() + timeoutMs\n while (performance.now() < deadline) {\n if (await check()) return\n await sleep(10)\n }\n throw new Error(`timed out waiting for ${what}`)\n}\n\nconst alive = (pid: number) => {\n try {\n process.kill(pid, 0)\n return true\n } catch {\n return false\n }\n}\n\nconst exited = (child: ChildProcess) =>\n new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((done) => {\n if (child.exitCode !== null || child.signalCode !== null) done({ code: child.exitCode, signal: child.signalCode })\n else child.once(\"exit\", (code, signal) => done({ code, signal }))\n })\n\n/** Ask the app to quit (`quit`) or kill it outright (`kill`). */\nconst stop = (child: ChildProcess, mode: \"quit\" | \"kill\") => {\n if (!windows) {\n child.kill(mode === \"quit\" ? \"SIGTERM\" : \"SIGKILL\")\n return\n }\n // Node's kill() is TerminateProcess on Windows; `taskkill` without /F posts WM_CLOSE to the app's window.\n spawnSync(\"taskkill\", [\"/pid\", String(child.pid), ...(mode === \"kill\" ? [\"/F\"] : [])], { stdio: \"ignore\" })\n}\n\ninterface Run {\n /** Spawn to the probe line, on this harness's clock: the budget's measure. */\n readonly externalMs: number\n /** The host's own clock, from `main`. */\n readonly interactiveMs: number\n readonly screen: string\n /** Spawn to the daemon's ready line. */\n readonly daemonReadyMs: number\n}\n\nconst state = mkdtempSync(join(tmpdir(), \"eloxiv-rune-launch-\"))\nconst env = {\n ...process.env,\n ...(fixedPort === undefined ? {} : { ELOXIV_DAEMON_PORT: String(fixedPort) }),\n ELOXIV_DAEMON_STATE_DIR: join(state, \"daemon\"),\n ELOXIV_RUNE_DATA_DIR: join(state, \"host\"),\n}\nif (fixedPort === undefined) delete env[\"ELOXIV_DAEMON_PORT\"]\n\nconst launch = async (index: number, mode: \"quit\" | \"kill\"): Promise<Run> => {\n if (fixedPort !== undefined && (await health(fixedPort)))\n throw new Error(`port ${fixedPort} is already serving /health before launch`)\n const started = performance.now()\n const child = spawn(app, [], { stdio: [\"ignore\", \"pipe\", \"pipe\"], env })\n let output = \"\"\n let interactive: { ms: number; screen: string; at: number } | undefined\n let daemonReadyAt: number | undefined\n let daemonPid: number | undefined\n let port = fixedPort\n const read = (chunk: string) => {\n output += chunk\n const now = performance.now()\n const line = /^ELOXIV_DESKTOP_INTERACTIVE ms=(\\d+) source=frame screen=([\\w-]+) /mu.exec(output)\n if (line && interactive === undefined) interactive = { ms: Number(line[1]), screen: line[2]!, at: now }\n if (daemonReadyAt === undefined && /ELOXIV_DAEMON_READY port=\\d+/u.test(output)) daemonReadyAt = now\n const pid = /\\[eloxiv-daemon\\] spawned pid=(\\d+) port=(\\d+)/u.exec(output)\n if (pid) {\n daemonPid = Number(pid[1])\n port = Number(pid[2])\n }\n }\n child.stdout.setEncoding(\"utf8\").on(\"data\", read)\n child.stderr.setEncoding(\"utf8\").on(\"data\", read)\n try {\n await waitFor(\n () => interactive !== undefined && daemonReadyAt !== undefined,\n 20_000,\n \"interactive and daemon ready\",\n )\n if (port === undefined) throw new Error(\"the host did not say which port its sidecar listens on\")\n const body = await health(port)\n if (body?.status !== \"ok\") throw new Error(`unexpected /health: ${JSON.stringify(body)}`)\n if (daemonPid === undefined || !alive(daemonPid)) throw new Error(\"the sidecar is not running\")\n } catch (error) {\n child.kill(\"SIGKILL\")\n if (daemonPid !== undefined && alive(daemonPid)) process.kill(daemonPid, \"SIGKILL\")\n throw new Error(`run ${index}: ${(error as Error).message}\\n${output}`, { cause: error })\n }\n\n stop(child, mode)\n const exit = await exited(child)\n await waitFor(\n async () => !(await health(port!)) && (daemonPid === undefined || !alive(daemonPid)),\n 5_000,\n `the daemon (pid ${daemonPid}) to stop with the host`,\n ).catch((error: Error) => {\n if (daemonPid !== undefined && alive(daemonPid)) process.kill(daemonPid, \"SIGKILL\")\n throw new Error(`run ${index}: ${error.message}\\n${output}`, { cause: error })\n })\n // Quitting: the host ends cleanly (Windows, a close request) or by the signal that asked it to (Unix).\n if (mode === \"quit\" && !(exit.code === 0 || exit.signal === \"SIGTERM\"))\n throw new Error(`run ${index}: host exited with ${JSON.stringify(exit)}\\n${output}`)\n const run = {\n externalMs: Math.round(interactive!.at - started),\n interactiveMs: interactive!.ms,\n screen: interactive!.screen,\n daemonReadyMs: Math.round(daemonReadyAt! - started),\n }\n console.log(\n `run ${index} (${mode}): spawn-to-interactive ms=${run.externalMs} (host main ms=${run.interactiveMs}, screen=${run.screen}) daemon-ready ms=${run.daemonReadyMs} port=${port} health=ok host-exit=${JSON.stringify(exit)} daemon-stopped=yes`,\n )\n return run\n}\n\nconst percentile = (values: ReadonlyArray<number>, p: number) => {\n const sorted = [...values].sort((a, b) => a - b)\n const rank = Math.ceil((p / 100) * sorted.length) - 1\n return sorted[Math.min(sorted.length - 1, Math.max(0, rank))]!\n}\n\nconsole.log(`app: ${app}`)\nconsole.log(\n `display: ${process.env[\"WAYLAND_DISPLAY\"] ?? process.env[\"DISPLAY\"] ?? \"(default)\"} runs: ${runs} daemon port: ${fixedPort ?? \"the host's choice\"}`,\n)\nconst results: Array<Run> = []\ntry {\n for (let i = 1; i <= runs; i++) results.push(await launch(i, \"quit\"))\n if (crash) {\n await launch(runs + 1, \"kill\")\n console.log(`run ${runs + 1}: host killed outright; the daemon exited through its stdin lifeline`)\n }\n} finally {\n rmSync(state, { recursive: true, force: true })\n}\n\nconst summary = (label: string, values: ReadonlyArray<number>) =>\n `${label}: median=${percentile(values, 50)} p95=${percentile(values, 95)} min=${Math.min(...values)} max=${Math.max(...values)}`\nconst external = results.map((r) => r.externalMs)\nconsole.log(summary(\"spawn to interactive ms (harness clock)\", external))\nconsole.log(\n summary(\n \"ELOXIV_DESKTOP_INTERACTIVE ms (host clock, from main)\",\n results.map((r) => r.interactiveMs),\n ),\n)\nconsole.log(\n summary(\n \"spawn to daemon ready ms (harness clock)\",\n results.map((r) => r.daemonReadyMs),\n ),\n)\nconst p95 = percentile(external, 95)\nconsole.log(`budget: p95 ${p95} ms against ${budget} ms: ${p95 <= budget ? \"within\" : \"OVER\"}`)\nif (json !== \"\") writeFileSync(json, JSON.stringify(external))\nif (p95 > budget) process.exit(1)\n",
84
+ "type": "registry:file",
85
+ "target": "desktop-rune/scripts/measure-launch.ts"
86
+ },
87
+ {
88
+ "path": "app/desktop-rune/app-icon.svg",
89
+ "content": "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1024 1024\" width=\"1024\" height=\"1024\">\n <rect x=\"64\" y=\"64\" width=\"896\" height=\"896\" rx=\"200\" fill=\"#18181b\"/>\n <path d=\"M352 288h336v96H464v80h192v96H464v80h224v96H352z\" fill=\"#fafafa\"/>\n</svg>\n",
90
+ "type": "registry:file",
91
+ "target": "desktop-rune/app-icon.svg"
92
+ },
93
+ {
94
+ "path": "app/desktop-rune/app/Cargo.toml",
95
+ "content": "[package]\nname = \"eloxiv-desktop-rune\"\nversion = \"0.1.0\"\ndescription = \"Eloxiv desktop host on Rune: a native window over LocalClient v1, the app's daemon as its sidecar\"\nedition.workspace = true\nrust-version.workspace = true\nlicense.workspace = true\npublish.workspace = true\n\n[lib]\nname = \"eloxiv_desktop_rune\"\n\n[[bin]]\nname = \"eloxiv-desktop-rune\"\npath = \"src/main.rs\"\n\n[dependencies]\nrune.workspace = true\neloxiv-local-client.workspace = true\nserde.workspace = true\nserde_json.workspace = true\ngetrandom = \"0.3\"\n# The host's own services: updates (signed, verified), deep links, the OS keychain; the app's identity is app.json.\neloxiv-update = { path = \"../crates/eloxiv-update\", default-features = false }\nsemver = \"1.0.28\"\nurl = \"2.5.8\"\nkeyring = \"=4.2.0\"\n\n[target.'cfg(windows)'.dependencies]\n# Registering the deep-link scheme under HKEY_CURRENT_USER.\nwinreg = \"0.56.0\"\n# The app's toast setting, read for the notification permission the host reports (the windows crate rune-notify uses).\nwindows = { version = \"0.62\", features = [\"UI_Notifications\"] }\n\n# OS notifications while the app runs (`notices`): rune-notify on macOS and Windows (the Rune revision the workspace\n# pins), the freedesktop notification service over D-Bus elsewhere on Unix (the zbus the keychain already uses).\n[target.'cfg(any(target_os = \"macos\", target_os = \"windows\"))'.dependencies]\nrune-notify = { git = \"https://github.com/anomalyco/rune\", rev = \"eb5ae6c9f77b1a0051d8e1e5ee936ebea086bb90\" }\n\n# macOS: the UserNotifications calls the host makes itself (authorisation, scheduling, withdrawal), the only `unsafe`\n# code, in a crate of its own.\n[target.'cfg(target_os = \"macos\")'.dependencies]\neloxiv-mac-notifications = { path = \"../crates/eloxiv-mac-notifications\" }\n\n[target.'cfg(all(unix, not(target_os = \"macos\")))'.dependencies]\nzbus = { version = \"=5.19.0\", default-features = false, features = [\"async-io\", \"blocking-api\"] }\n\n[dev-dependencies]\n# The signer, to sign test installers (updates::installer_tests).\neloxiv-update = { path = \"../crates/eloxiv-update\" }\n# The journey's browser helper (an HTTP endpoint the runner serves).\nureq.workspace = true\n\n[lints]\nworkspace = true\n",
96
+ "type": "registry:file",
97
+ "target": "desktop-rune/app/Cargo.toml"
98
+ },
99
+ {
100
+ "path": "app/desktop-rune/app/src/backend.rs",
101
+ "content": "//! Networking off the UI thread. Every request runs on a worker thread of its own; its answer goes into the\n//! app's inbox, and the waker asks Rune for a frame, whose `poll` drains the inbox on the UI thread. The event\n//! stream has its own thread ([`eloxiv_local_client::EventStream`]) and lands its items the same way.\n\nuse std::sync::mpsc::{Receiver, Sender, channel};\nuse std::sync::{Arc, RwLock};\nuse std::time::{Duration, Instant};\n\nuse eloxiv_local_client::{\n ClientError, EngineReadiness, EventStream, GenerationAnswer, Hello, LocalClient, OkAnswer, SignInStarted,\n StreamItem, Subscribed, WriteAccepted,\n};\nuse serde_json::{Value, json};\n\nuse crate::make;\nuse crate::outstanding::Scope;\n\n/// What the UI asks for.\n#[derive(Clone, Debug)]\npub enum Job {\n /// Wait for the daemon's `/health` (up to the deadline), then its `hello`.\n Start {\n timeout: Duration,\n },\n SignIn,\n SelectOrg(String),\n SignOut,\n Subscribe {\n generation: i64,\n query: String,\n args: Value,\n id: String,\n },\n Unsubscribe(String),\n /// An optimistic write, made in `generation` (refused, unwritten, in another).\n Write {\n generation: i64,\n id: String,\n mutator: String,\n input: Value,\n },\n /// A MAKE view's request, made in `generation` (refused, not run, in another).\n Make {\n generation: i64,\n request: make::Request,\n },\n /// Whether the agent can answer (`GET /client/v1/agent/readiness`), asked after `after` (zero: at once).\n Readiness {\n generation: i64,\n after: Duration,\n },\n /// Follow a run's events (`POST /client/v1/runs`) under the host's `id`.\n FollowRun {\n generation: i64,\n id: String,\n run_id: String,\n after: i64,\n },\n /// Stop following a run; nothing waits for it.\n UnfollowRun(String),\n /// `agent.send` under the send's key, made in `generation` (the daemon refuses it, unrun, in another).\n Send {\n /// Whose send (the outstanding store's scope): its outcome is recorded there whatever is shown by then.\n scope: Scope,\n generation: i64,\n key: String,\n text: String,\n conversation_id: Option<String>,\n },\n /// A decision (`consent.approve`, `approvals.reject`, ...) on `id`, under its key, made in `generation`.\n Decide {\n generation: i64,\n id: String,\n action: String,\n key: String,\n },\n /// Reopen the stream after a pause.\n Reconnect {\n after: Duration,\n },\n}\n\n/// What comes back, on the UI thread.\n#[derive(Debug)]\npub enum Reply {\n Started(Result<Hello, ClientError>),\n SignIn(Result<SignInStarted, ClientError>),\n Org(Result<GenerationAnswer, ClientError>),\n SignedOut(Result<OkAnswer, ClientError>),\n Subscribed {\n generation: i64,\n id: String,\n result: Result<Subscribed, ClientError>,\n },\n Readiness {\n generation: i64,\n /// Asked again after a pause (a check while the agent was blocked).\n delayed: bool,\n result: Result<EngineReadiness, ClientError>,\n },\n Followed {\n generation: i64,\n id: String,\n result: Result<Subscribed, ClientError>,\n },\n Sent {\n scope: Scope,\n generation: i64,\n key: String,\n result: Result<Value, ClientError>,\n },\n Decided {\n generation: i64,\n id: String,\n result: Result<Value, ClientError>,\n },\n Wrote {\n id: String,\n result: Result<WriteAccepted, ClientError>,\n },\n MakeView {\n mount: u64,\n result: Result<Value, String>,\n },\n MakeStep {\n mount: u64,\n result: Result<Value, String>,\n },\n MakeCall {\n mount: u64,\n id: String,\n result: Result<Value, Value>,\n },\n Reconnect,\n /// A request nothing waits for finished.\n Done,\n Stream(StreamItem),\n}\n\npub type Wake = Arc<dyn Fn() + Send + Sync>;\n\n/// The worker side: a client of the daemon, the inbox's sender, and the stream.\npub struct Backend {\n client: LocalClient,\n replies: Sender<Reply>,\n /// Shared, so a request started before Rune handed over its waker (the first, from `Ui::new`) still wakes the\n /// loop with it when it answers.\n wake: Arc<RwLock<Wake>>,\n stream: Option<EventStream>,\n}\n\nimpl Backend {\n /// A backend for the daemon `client` talks to, and the inbox its replies arrive in.\n pub fn new(client: LocalClient) -> (Backend, Receiver<Reply>) {\n let (replies, inbox) = channel();\n let none: Wake = Arc::new(|| {});\n (Backend { client, replies, wake: Arc::new(RwLock::new(none)), stream: None }, inbox)\n }\n\n /// The waker Rune gave the app (`AppSpec::setup`): called after every reply.\n pub fn set_wake(&mut self, wake: Wake) {\n if let Ok(mut current) = self.wake.write() {\n *current = wake;\n }\n }\n\n pub fn client(&self) -> &LocalClient {\n &self.client\n }\n\n /// Opens the event stream (a new one replaces the old one, which is cancelled first).\n pub fn open_stream(&mut self) {\n if let Some(mut old) = self.stream.take() {\n old.cancel();\n }\n let (replies, wake) = (self.replies.clone(), self.wake.clone());\n self.stream = Some(self.client.events(move |item| {\n let _ = replies.send(Reply::Stream(item));\n wake_with(&wake);\n }));\n }\n\n /// Ends the stream (sign-out does not: the stream outlives a session; the app's exit does).\n pub fn close_stream(&mut self) {\n if let Some(mut s) = self.stream.take() {\n s.cancel();\n }\n }\n\n /// Runs `job` on a worker thread.\n pub fn run(&self, job: Job) {\n let (client, replies, wake) = (self.client.clone(), self.replies.clone(), self.wake.clone());\n let spawned = std::thread::Builder::new().name(\"eloxiv-request\".into()).spawn(move || {\n let reply = execute(&client, job);\n let _ = replies.send(reply);\n wake_with(&wake);\n });\n if spawned.is_err() {\n eprintln!(\"eloxiv-desktop-rune: could not start a request thread\");\n }\n }\n}\n\n/// Calls the waker as it is now.\nfn wake_with(wake: &RwLock<Wake>) {\n let current = wake.read().map(|w| w.clone()).ok();\n if let Some(w) = current {\n w();\n }\n}\n\nimpl Drop for Backend {\n fn drop(&mut self) {\n self.close_stream();\n }\n}\n\nfn envelope_output(answer: Result<Value, ClientError>) -> Result<Value, String> {\n match answer {\n Ok(envelope) => match envelope.get(\"output\") {\n Some(output) => Ok(output.clone()),\n None => Err(format!(\"unexpected answer: {envelope}\")),\n },\n Err(e) => Err(e.to_string()),\n }\n}\n\nfn execute(client: &LocalClient, job: Job) -> Reply {\n match job {\n Job::Start { timeout } => {\n let deadline = Instant::now() + timeout;\n while !client.health() {\n if Instant::now() > deadline {\n return Reply::Started(Err(ClientError::Transport(format!(\n \"the daemon at {} did not answer /health within {} s\",\n client.base(),\n timeout.as_secs()\n ))));\n }\n std::thread::sleep(Duration::from_millis(50));\n }\n Reply::Started(client.hello())\n }\n Job::SignIn => Reply::SignIn(client.sign_in()),\n Job::SelectOrg(org) => Reply::Org(client.select_org(&org)),\n Job::SignOut => Reply::SignedOut(client.sign_out()),\n Job::Subscribe { generation, query, args, id } => {\n Reply::Subscribed { generation, result: client.subscribe(&query, args, Some(&id)), id }\n }\n Job::Readiness { generation, after } => {\n if !after.is_zero() {\n std::thread::sleep(after);\n }\n Reply::Readiness { generation, delayed: !after.is_zero(), result: client.agent_readiness() }\n }\n Job::FollowRun { generation, id, run_id, after } => {\n Reply::Followed { generation, result: client.follow_run(&run_id, after, Some(&id)), id }\n }\n Job::UnfollowRun(id) => {\n // Nothing waits for it: a run subscription the daemon may already have ended.\n let _ = client.unfollow_run(&id);\n Reply::Done\n }\n Job::Send { scope, generation, key, text, conversation_id } => {\n let mut input = json!({ \"text\": text });\n if let Some(c) = conversation_id {\n input[\"conversationId\"] = Value::String(c);\n }\n let result = client.action(\"agent.send\", input, Some(&key), Some(generation));\n Reply::Sent { scope, generation, result, key }\n }\n Job::Decide { generation, id, action, key } => {\n let result = client.action(&action, json!({ \"id\": id }), Some(&key), Some(generation));\n Reply::Decided { generation, result, id }\n }\n Job::Unsubscribe(id) => {\n // Nothing waits for it: a subscription of an older generation the daemon may already have dropped.\n let _ = client.unsubscribe(&id);\n Reply::Done\n }\n Job::Write { generation, id, mutator, input } => {\n Reply::Wrote { result: client.write(&mutator, input, Some(&id), Some(generation)), id }\n }\n Job::Make { generation, request: make::Request::View { mount, module } } => Reply::MakeView {\n mount,\n result: envelope_output(client.action(\"make.view\", json!({ \"module\": module }), None, Some(generation))),\n },\n Job::Make { generation, request: make::Request::Step { mount, module, version, state, message } } => {\n Reply::MakeStep {\n mount,\n result: envelope_output(client.action(\n \"make.renderView\",\n json!({ \"module\": module, \"version\": version, \"state\": state, \"message\": message }),\n None,\n Some(generation),\n )),\n }\n }\n Job::Make { generation, request: make::Request::Call { mount, id, action, input, key } } => Reply::MakeCall {\n mount,\n id,\n result: client.action(&action, input, Some(&key), Some(generation)).map_err(|e| e.to_view_error()),\n },\n Job::Reconnect { after } => {\n std::thread::sleep(after);\n Reply::Reconnect\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::sync::atomic::{AtomicUsize, Ordering};\n\n #[test]\n fn a_request_started_before_the_waker_wakes_with_it() {\n let (mut backend, inbox) = Backend::new(LocalClient::new(\"http://127.0.0.1:9\", \"t\"));\n // Started first, as Ui::new does, before Rune's setup gives the waker.\n backend.run(Job::Reconnect { after: Duration::from_millis(100) });\n let woken = Arc::new(AtomicUsize::new(0));\n let counter = woken.clone();\n backend.set_wake(Arc::new(move || {\n counter.fetch_add(1, Ordering::SeqCst);\n }));\n assert!(matches!(inbox.recv_timeout(Duration::from_secs(5)), Ok(Reply::Reconnect)));\n std::thread::sleep(Duration::from_millis(20));\n assert_eq!(woken.load(Ordering::SeqCst), 1);\n }\n}\n",
102
+ "type": "registry:file",
103
+ "target": "desktop-rune/app/src/backend.rs"
104
+ },
105
+ {
106
+ "path": "app/desktop-rune/app/src/chat.rs",
107
+ "content": "//! The chat screen's state, pure (the chat SDK's guarantees, `@eloxiv/client/chat`, kept minimally on this side of\n//! LocalClient 1.1.0): the conversation's rows come from named-query subscriptions (`agent.conversations`,\n//! `agent.messages`, `agent.runs`, `approvals.requests`), the active run's events from a run subscription\n//! (`POST /client/v1/runs`), and sends and decisions go as actions under the chat SDK's idempotency keys. Nothing\n//! here touches the network or the UI: transitions take what arrived and return what to do next.\n//!\n//! - **One conversation, its own rows.** The transcript holds the shown conversation's stored messages, in order,\n//! then the active run's streamed text by model step: a step's text shows until the replica holds that step's\n//! stored answer, which replaces it; another model call of the step (`attempt`) replaces the earlier call's text.\n//! - **Events only from the run followed.** A run event counts only for the subscription following the shown\n//! conversation's active run; each stored event once (by `seq`); `run-finished` ends the run at once.\n//! - **A send is one send.** The composer sends a non-empty draft only when nothing is in flight, no run is going\n//! and the engine is not known to be blocked; each send has its key, and one whose answer was lost is resent under\n//! it (a retry is a replay, never a second run). A refusal is kept with the draft. The person's outstanding sends\n//! are the outstanding store's ([`crate::outstanding`]), which outlives this state: a new state takes them\n//! ([`Chat::with_outstanding`]), so a send whose answer was lost is resent under its key after an organisation\n//! switch and back, a sign-out and in, or a restart.\n//! - **Decisions are the person's**, each under its own key (`consent:<id>:<decision>:`, `approval:<id>:<decision>`).\n//! - **Nothing outlives the generation.** A context reset drops it all (the daemon ends every subscription too).\n\nuse eloxiv_local_client::{AgentRunEvent, EngineReadiness, EngineReadinessState, RunEventKind};\nuse serde_json::Value;\n\nuse crate::outstanding::{self, Outcome, OutstandingSend, SendState};\n\npub const CONVERSATIONS_QUERY: &str = \"agent.conversations\";\npub const MESSAGES_QUERY: &str = \"agent.messages\";\npub const RUNS_QUERY: &str = \"agent.runs\";\npub const APPROVALS_QUERY: &str = \"approvals.requests\";\n/// The named queries the chat screen subscribes to, each generation.\npub const CHAT_QUERIES: [&str; 4] = [CONVERSATIONS_QUERY, MESSAGES_QUERY, RUNS_QUERY, APPROVALS_QUERY];\n\n/// The key a decision is made under: the same for every retry of it (the chat SDK's `decisionKey`).\npub fn consent_key(consent_id: &str, decision: Decision) -> String {\n format!(\"consent:{consent_id}:{}:\", decision.word())\n}\npub fn approval_key(approval_id: &str, decision: Decision) -> String {\n format!(\"approval:{approval_id}:{}\", decision.word())\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum Decision {\n Approve,\n Reject,\n}\n\nimpl Decision {\n pub fn word(self) -> &'static str {\n match self {\n Decision::Approve => \"approve\",\n Decision::Reject => \"reject\",\n }\n }\n}\n\n#[derive(Clone, Debug, PartialEq)]\npub struct Message {\n pub id: String,\n pub conversation_id: String,\n pub run_id: Option<String>,\n pub seq: f64,\n pub role: String,\n pub text: String,\n pub covered_by: Option<String>,\n}\n\n#[derive(Clone, Debug, PartialEq)]\npub struct Run {\n pub id: String,\n pub conversation_id: String,\n pub status: String,\n pub created_at: f64,\n}\n\n#[derive(Clone, Debug, PartialEq)]\npub struct Conversation {\n pub id: String,\n pub title: String,\n}\n\n/// A readable form of an action's name, for a request that carries no title (an older kernel's): the local part split\n/// into words, sentence-cased, with the module in parentheses (`mail.send` is \"Send (mail)\"). `@eloxiv/contracts`'\n/// `readableActionName` gives the same words; never the raw id.\npub fn readable_action_name(name: &str) -> String {\n let (module, local) = match name.find('.') {\n Some(dot) => (&name[..dot], &name[dot + 1..]),\n None => (\"\", name),\n };\n let words = readable_words(local);\n let phrase = if words.is_empty() { name.to_owned() } else { words };\n if module.is_empty() { phrase } else { format!(\"{phrase} ({module})\") }\n}\n\n/// An action's local name as sentence-cased words (`moveResources` is \"Move resources\"), or \"\" when it has none.\nfn readable_words(local: &str) -> String {\n let mut words = String::new();\n let mut prev: Option<char> = None;\n for c in local.chars() {\n if matches!(c, '.' | '_' | '-') {\n if !words.ends_with(' ') {\n words.push(' ');\n }\n } else {\n if c.is_ascii_uppercase() && prev.is_some_and(|p| p.is_ascii_lowercase() || p.is_ascii_digit()) {\n words.push(' ');\n }\n words.push(c.to_ascii_lowercase());\n }\n prev = Some(c);\n }\n let words = words.trim();\n let mut chars = words.chars();\n match chars.next() {\n Some(first) => first.to_uppercase().chain(chars).collect::<String>(),\n None => String::new(),\n }\n}\n\n/// The most characters an action's label may have (`ACTION_TITLE_MAX` in @eloxiv/contracts).\nconst ACTION_TITLE_MAX: usize = 80;\n\n/// A MAKE module's action as a person deciding on it sees it called, computed from its id alone: the module's id\n/// first, never cut, then the action's readable words (`mk_todos.urgent` is \"mk_todos: Urgent\"), only the words cut\n/// with an ellipsis to fit 80 characters. `makeDecisionLabel` in @eloxiv/contracts gives the same words.\npub fn make_decision_label(action: &str) -> String {\n let (module, local) = match action.find('.') {\n Some(dot) => (&action[..dot], &action[dot + 1..]),\n None => (action, \"\"),\n };\n let words = readable_words(local);\n let room = ACTION_TITLE_MAX.saturating_sub(module.chars().count() + 2);\n if words.is_empty() || room < 2 {\n return module.to_owned();\n }\n let fitted = if words.chars().count() <= room {\n words\n } else {\n let cut: String = words.chars().take(room - 1).collect();\n format!(\"{}…\", cut.trim_end())\n };\n format!(\"{module}: {fitted}\")\n}\n\n/// What a person deciding on a call of `action` sees it called: `action_label`, except for a MAKE module's action\n/// (`mk_…`), whose label comes from its id whatever title a row or event carries (the module's own words, or a label\n/// recorded before). `decisionLabel` in @eloxiv/contracts.\npub fn decision_label(action: &str, title: Option<&str>) -> String {\n if action.starts_with(\"mk_\") { make_decision_label(action) } else { action_label(action, title) }\n}\n\n/// What people see an action called: the title the kernel recorded when it held the call, or its readable name.\npub fn action_label(action: &str, title: Option<&str>) -> String {\n match title.map(str::trim) {\n Some(t) if !t.is_empty() => t.to_owned(),\n _ => readable_action_name(action),\n }\n}\n\n#[derive(Clone, Debug, PartialEq)]\npub struct Approval {\n pub id: String,\n pub requester_id: String,\n pub action: String,\n /// What people see the action called (the row's `title`, or the action's readable name).\n pub title: String,\n pub status: String,\n pub created_at: f64,\n}\n\n/// A tool call the run holds for the person's consent (from its `consent-required` event).\n#[derive(Clone, Debug, PartialEq)]\npub struct Consent {\n pub consent_id: String,\n pub run_id: String,\n pub action: String,\n /// What people see the action called (the event's `title`, or the action's readable name).\n pub title: String,\n}\n\n#[derive(Clone, Debug, PartialEq)]\npub struct StreamedStep {\n pub step: i64,\n pub attempt: Option<String>,\n pub text: String,\n}\n\n/// What the followed run's stream delivered that the replica may not hold yet.\n#[derive(Clone, Debug, PartialEq)]\npub struct Live {\n pub run_id: String,\n /// The last stored event's `seq` seen.\n pub after: i64,\n /// How many model steps the stream reported done (text naming no step is the next one's).\n pub steps: i64,\n pub streamed: Vec<StreamedStep>,\n}\n\n/// A send: its text, the conversation it was sent from (None: a new one), its idempotency key and the generation it\n/// was made in (the daemon runs it in no other; a retry keeps it).\n#[derive(Clone, Debug, PartialEq)]\npub struct Send {\n pub key: String,\n pub text: String,\n pub conversation_id: Option<String>,\n pub generation: i64,\n}\n\n/// The run subscription following the active run (its host-chosen id).\n#[derive(Clone, Debug, PartialEq)]\npub struct Followed {\n pub id: String,\n pub run_id: String,\n}\n\n/// One line of the transcript: a stored message, or a model step's streamed text.\n#[derive(Clone, Debug, PartialEq)]\npub struct Entry {\n pub id: String,\n pub role: String,\n pub text: String,\n pub live: bool,\n}\n\n/// What a transition asks the host to do.\n#[derive(Clone, Debug, PartialEq)]\npub enum ChatEffect {\n /// Follow `run_id` after the stored event `after`.\n Follow { run_id: String, after: i64 },\n /// Stop the run subscription `id`.\n Unfollow { id: String },\n}\n\n#[derive(Clone, Debug, Default)]\npub struct Chat {\n pub generation: i64,\n /// The host-chosen subscription id of each chat query, for this generation.\n pub subscriptions: Vec<(String, String)>,\n /// None until the first snapshot of `agent.conversations`.\n pub conversations: Option<Vec<Conversation>>,\n pub messages: Vec<Message>,\n pub runs: Vec<Run>,\n pub approvals: Vec<Approval>,\n pub conversation_id: Option<String>,\n /// The person chose a new conversation: the latest is not opened for them.\n pub chose_new: bool,\n /// The run a send started, until the replica has it.\n pub pending_run: Option<Run>,\n pub live: Option<Live>,\n /// Runs whose stream said they ended (`run-finished`), whatever the replica says yet.\n pub ended: Vec<String>,\n pub consents: Vec<Consent>,\n pub followed: Option<Followed>,\n /// The send in flight.\n pub sending: Option<Send>,\n /// The person's outstanding sends in this organisation, every conversation's, as the outstanding store keeps\n /// them (with this state's own changes): one whose answer was lost is resent under its key by the next send.\n pub outstanding: Vec<OutstandingSend>,\n /// Why the last send or decision failed: its `_tag` and message.\n pub error: Option<(String, String)>,\n /// What the daemon said about the agent (None: not asked yet, which holds nothing back).\n pub engine: Option<EngineReadiness>,\n /// Decisions in flight (consent or approval ids).\n pub deciding: Vec<String>,\n /// Streamed text deltas the transcript took for the followed runs (an empty one or one of a step already done is\n /// not counted; diagnostics: the journey reports them).\n pub deltas: u64,\n}\n\nconst ACTIVE: [&str; 3] = [\"queued\", \"running\", \"waiting\"];\nconst ENDED_KEPT: usize = 32;\n\nfn str_of(row: &Value, field: &str) -> Option<String> {\n row.get(field).and_then(Value::as_str).map(str::to_owned)\n}\nfn num_of(row: &Value, field: &str) -> f64 {\n row.get(field).and_then(Value::as_f64).unwrap_or(0.0)\n}\n\nimpl Chat {\n /// A chat for `generation` (a new context: nothing of the previous one).\n pub fn new(generation: i64) -> Chat {\n Chat { generation, ..Chat::default() }\n }\n\n /// Whether `id` is one of this generation's chat subscriptions.\n pub fn query_of(&self, subscription: &str) -> Option<&str> {\n self.subscriptions.iter().find(|(_, id)| id == subscription).map(|(q, _)| q.as_str())\n }\n\n /// The chat queries are being subscribed under these ids.\n pub fn subscribing(&mut self, query: &str, id: String) {\n self.subscriptions.retain(|(q, _)| q != query);\n self.subscriptions.push((query.to_owned(), id));\n }\n\n fn known(&self) -> impl Iterator<Item = &Run> {\n self.pending_run.iter().chain(self.runs.iter())\n }\n\n /// The shown conversation's run still going (queued, running or waiting, not ended by its stream).\n pub fn active_run(&self) -> Option<&Run> {\n let conversation = self.conversation_id.as_deref()?;\n self.known().find(|r| {\n r.conversation_id == conversation && ACTIVE.contains(&r.status.as_str()) && !self.ended.contains(&r.id)\n })\n }\n\n /// Whether the agent is known not to be able to answer (no model set up, or one that cannot be used).\n pub fn engine_blocked(&self) -> bool {\n matches!(\n self.engine.as_ref().map(|e| e.state),\n Some(EngineReadinessState::Missing | EngineReadinessState::Unavailable)\n )\n }\n\n /// Whether the composer may send `draft` now.\n pub fn can_send(&self, draft: &str) -> bool {\n !self.engine_blocked()\n && self.sending.is_none()\n && self.active_run().is_none()\n && (!draft.trim().is_empty() || self.unresolved_here().is_some())\n }\n\n /// The shown conversation's send whose answer was lost (or that an earlier state or run of the host sent without\n /// hearing back), which the next send resends under its key, in this state's generation.\n pub fn unresolved_here(&self) -> Option<Send> {\n self.outstanding.iter().find(|s| s.conversation_id == self.conversation_id && self.resendable(s)).map(|s| {\n Send {\n key: s.key.clone(),\n text: s.text.clone(),\n conversation_id: s.conversation_id.clone(),\n generation: self.generation,\n }\n })\n }\n\n /// Whether `send` is to be resent: its answer was lost, or it was in flight for a request this state does not have\n /// (an earlier state's, or a run of the host that ended before it answered).\n fn resendable(&self, send: &OutstandingSend) -> bool {\n match send.state {\n SendState::Uncertain | SendState::Unconfirmed => true,\n SendState::Sending => self.sending.as_ref().is_none_or(|own| own.key != send.key),\n }\n }\n\n /// The person's outstanding sends in this organisation as the outstanding store has them now: they replace this\n /// state's, but for its own send in flight, which stays while its request is out.\n pub fn with_outstanding(&mut self, sends: Vec<OutstandingSend>) {\n let own = self.sending.as_ref().and_then(|s| self.outstanding.iter().find(|o| o.key == s.key).cloned());\n self.outstanding = sends;\n if let Some(own) = own\n && !self.outstanding.iter().any(|s| s.key == own.key)\n {\n self.outstanding.push(own);\n }\n }\n\n /// The outstanding send under `key`, as this state has it (what to record in the store).\n pub fn outstanding_send(&self, key: &str) -> Option<&OutstandingSend> {\n self.outstanding.iter().find(|s| s.key == key)\n }\n\n /// The conversation's title as shown (a new one has none yet).\n pub fn title(&self) -> Option<String> {\n let id = self.conversation_id.as_deref()?;\n let title = self.conversations.as_ref()?.iter().find(|c| c.id == id).map(|c| c.title.clone());\n Some(title.filter(|t| !t.trim().is_empty()).unwrap_or_else(|| \"Conversation\".to_owned()))\n }\n\n /// The transcript: the conversation's stored messages in order (an answer with no text, a tool call, a summary\n /// and a message left after a restored checkpoint are not lines), then each model step's streamed text the\n /// replica does not hold the stored answer of yet.\n pub fn transcript(&self) -> Vec<Entry> {\n let Some(conversation) = self.conversation_id.as_deref() else { return Vec::new() };\n let mut stored: Vec<&Message> = self\n .messages\n .iter()\n .filter(|m| m.conversation_id == conversation)\n .filter(|m| m.role != \"summary\" && m.role != \"tool\" && !(m.role == \"assistant\" && m.text.is_empty()))\n .filter(|m| !m.covered_by.as_deref().is_some_and(|c| c.starts_with(\"restore:\")))\n .collect();\n stored.sort_by(|a, b| a.seq.total_cmp(&b.seq));\n let mut out: Vec<Entry> = stored\n .into_iter()\n .map(|m| Entry { id: m.id.clone(), role: m.role.clone(), text: m.text.clone(), live: false })\n .collect();\n if let Some(live) = &self.live {\n // The run's model steps each store one answer, in order: the replica holds the first `answered`.\n let answered = self\n .messages\n .iter()\n .filter(|m| m.run_id.as_deref() == Some(live.run_id.as_str()) && m.role == \"assistant\")\n .count() as i64;\n let mut streaming: Vec<&StreamedStep> =\n live.streamed.iter().filter(|s| s.step >= answered && !s.text.is_empty()).collect();\n streaming.sort_by_key(|s| s.step);\n out.extend(streaming.into_iter().map(|s| Entry {\n id: format!(\"live-{}-{}\", live.run_id, s.step),\n role: \"assistant\".into(),\n text: s.text.clone(),\n live: true,\n }));\n }\n out\n }\n\n /// Approval requests someone else made that the person may decide (`user_id`'s own wait), oldest first.\n pub fn approvals_to_decide(&self, user_id: &str) -> Vec<&Approval> {\n let mut pending: Vec<&Approval> =\n self.approvals.iter().filter(|a| a.status == \"pending\" && a.requester_id != user_id).collect();\n pending.sort_by(|a, b| a.created_at.total_cmp(&b.created_at));\n pending\n }\n\n /// A snapshot of one of the chat subscriptions.\n pub fn rows(&mut self, subscription: &str, rows: &[Value]) -> Vec<ChatEffect> {\n let Some(query) = self.query_of(subscription).map(str::to_owned) else { return Vec::new() };\n match query.as_str() {\n CONVERSATIONS_QUERY => {\n let list: Vec<Conversation> = rows\n .iter()\n .filter_map(|r| {\n Some(Conversation { id: str_of(r, \"id\")?, title: str_of(r, \"title\").unwrap_or_default() })\n })\n .collect();\n // On the first snapshot, open the latest (the query is newest first), unless the person chose a new\n // conversation or is sending.\n // A send to start a new conversation whose answer was lost stays shown, to be resent.\n if self.conversations.is_none()\n && self.conversation_id.is_none()\n && !self.chose_new\n && self.sending.is_none()\n && self.unresolved_here().is_none()\n {\n self.conversation_id = list.first().map(|c| c.id.clone());\n }\n self.conversations = Some(list);\n }\n MESSAGES_QUERY => {\n self.messages = rows\n .iter()\n .filter_map(|r| {\n Some(Message {\n id: str_of(r, \"id\")?,\n conversation_id: str_of(r, \"conversationId\")?,\n run_id: str_of(r, \"runId\"),\n seq: num_of(r, \"seq\"),\n role: str_of(r, \"role\")?,\n text: str_of(r, \"text\").unwrap_or_default(),\n covered_by: str_of(r, \"coveredBy\"),\n })\n })\n .collect();\n }\n RUNS_QUERY => {\n self.runs = rows\n .iter()\n .filter_map(|r| {\n Some(Run {\n id: str_of(r, \"id\")?,\n conversation_id: str_of(r, \"conversationId\")?,\n status: str_of(r, \"status\")?,\n created_at: num_of(r, \"createdAt\"),\n })\n })\n .collect();\n if let Some(p) = &self.pending_run\n && self.runs.iter().any(|r| r.id == p.id)\n {\n self.pending_run = None;\n }\n // A run the replica reports ended needs its stream's word no longer.\n let runs = self.runs.clone();\n self.ended.retain(|id| !runs.iter().any(|r| r.id == *id && !ACTIVE.contains(&r.status.as_str())));\n let live_ended = self.live.as_ref().is_some_and(|l| {\n self.known().find(|r| r.id == l.run_id).is_some_and(|r| !ACTIVE.contains(&r.status.as_str()))\n });\n if live_ended {\n // Its stored answers are in the replica by now.\n self.live = None;\n }\n let active = self.active_run().map(|r| r.id.clone());\n self.consents.retain(|c| Some(&c.run_id) == active.as_ref());\n }\n APPROVALS_QUERY => {\n self.approvals = rows\n .iter()\n .filter_map(|r| {\n Some(Approval {\n id: str_of(r, \"id\")?,\n requester_id: str_of(r, \"requesterId\").unwrap_or_default(),\n action: str_of(r, \"action\").unwrap_or_default(),\n title: decision_label(\n &str_of(r, \"action\").unwrap_or_default(),\n str_of(r, \"title\").as_deref(),\n ),\n status: str_of(r, \"status\").unwrap_or_default(),\n created_at: num_of(r, \"createdAt\"),\n })\n })\n .collect();\n }\n _ => {}\n }\n self.wanted()\n }\n\n /// Follow the shown conversation's active run when nothing follows it (a conversation opened with a run going,\n /// a send's run, a stream reopened); stop following one that is not the active run any more.\n pub fn wanted(&mut self) -> Vec<ChatEffect> {\n let active = self.active_run().map(|r| r.id.clone());\n let mut effects = Vec::new();\n if let Some(f) = &self.followed\n && Some(&f.run_id) != active.as_ref()\n && !self.ended.contains(&f.run_id)\n {\n effects.push(ChatEffect::Unfollow { id: f.id.clone() });\n self.followed = None;\n }\n if let Some(run_id) = active\n && self.followed.is_none()\n {\n let after = self.live.as_ref().filter(|l| l.run_id == run_id).map_or(-1, |l| l.after);\n effects.push(ChatEffect::Follow { run_id, after });\n }\n effects\n }\n\n /// The run subscription `id` is following `run_id` (asked; the daemon's answer may follow its first event).\n pub fn following(&mut self, id: String, run_id: String) {\n self.followed = Some(Followed { id, run_id });\n }\n\n /// Following failed (refused): forget it, so a later snapshot may follow again.\n pub fn follow_failed(&mut self, id: &str, tag: String, message: String) {\n if self.followed.as_ref().is_some_and(|f| f.id == id) {\n self.followed = None;\n self.error = Some((tag, message));\n }\n }\n\n /// One event of a run subscription (or the refusal that ended it).\n pub fn run_event(\n &mut self,\n subscription: &str,\n event: Option<&AgentRunEvent>,\n error: Option<(String, String)>,\n ) -> Vec<ChatEffect> {\n let Some(followed) = self.followed.clone().filter(|f| f.id == subscription) else { return Vec::new() };\n let Some(event) = event else {\n // Refused: the subscription ended.\n self.followed = None;\n self.error = error;\n return Vec::new();\n };\n if event.run_id != followed.run_id {\n return Vec::new();\n }\n let run_id = followed.run_id.clone();\n let mut live = self.live.clone().filter(|l| l.run_id == run_id).unwrap_or(Live {\n run_id,\n after: -1,\n steps: 0,\n streamed: Vec::new(),\n });\n let data = &event.data;\n let step_of = |v: Option<&Value>| v.and_then(Value::as_i64).filter(|s| *s >= 0);\n if event.type_ == RunEventKind::TextDelta {\n let text = data.get(\"delta\").and_then(Value::as_str).unwrap_or(\"\");\n let step = step_of(data.get(\"step\")).unwrap_or(live.steps);\n if text.is_empty() || step < live.steps {\n return Vec::new();\n }\n self.deltas += 1;\n let attempt = data.get(\"attempt\").and_then(Value::as_str).map(str::to_owned);\n match live.streamed.iter_mut().find(|s| s.step == step) {\n Some(s) if s.attempt == attempt => s.text.push_str(text),\n Some(s) => *s = StreamedStep { step, attempt, text: text.to_owned() },\n None => live.streamed.push(StreamedStep { step, attempt, text: text.to_owned() }),\n }\n self.live = Some(live);\n return Vec::new();\n }\n if event.seq <= live.after {\n return Vec::new();\n }\n live.after = event.seq;\n match event.type_ {\n RunEventKind::ConsentRequired => {\n if let Some(id) = data.get(\"consentId\").and_then(Value::as_str)\n && !self.consents.iter().any(|c| c.consent_id == id)\n {\n self.consents.push(Consent {\n consent_id: id.to_owned(),\n run_id: live.run_id.clone(),\n action: data.get(\"action\").and_then(Value::as_str).unwrap_or(\"\").to_owned(),\n title: decision_label(\n data.get(\"action\").and_then(Value::as_str).unwrap_or(\"\"),\n data.get(\"title\").and_then(Value::as_str),\n ),\n });\n }\n }\n RunEventKind::ConsentDecided => {\n let id = data.get(\"consentId\").and_then(Value::as_str).unwrap_or(\"\");\n self.consents.retain(|c| c.consent_id != id);\n }\n RunEventKind::ModelStep => {\n // The step is done: its text is the stored one.\n let step = step_of(data.get(\"step\")).unwrap_or(live.steps);\n let text = data.get(\"text\").and_then(Value::as_str).unwrap_or(\"\").to_owned();\n live.streamed.retain(|s| s.step != step);\n live.streamed.push(StreamedStep { step, attempt: None, text });\n live.steps = live.steps.max(step + 1);\n }\n RunEventKind::ReplyDiscarded => {\n if let Some(step) = step_of(data.get(\"step\")) {\n live.streamed.retain(|s| s.step != step);\n }\n }\n RunEventKind::RunFinished => {\n // Ended: it holds the composer no longer, whatever the replica says yet.\n self.consents.clear();\n self.ended.retain(|id| *id != live.run_id);\n self.ended.push(live.run_id.clone());\n if self.ended.len() > ENDED_KEPT {\n self.ended.remove(0);\n }\n self.followed = None;\n }\n _ => {}\n }\n self.live = Some(live);\n Vec::new()\n }\n\n /// The person sends: the shown conversation's unresolved send under its own key, else `draft` under `key`.\n /// None when the composer may not send.\n pub fn submit(&mut self, draft: &str, key: String) -> Option<Send> {\n if !self.can_send(draft) {\n return None;\n }\n let send = match self.unresolved_here() {\n Some(retry) => retry,\n None => Send {\n key,\n text: draft.trim().to_owned(),\n conversation_id: self.conversation_id.clone(),\n generation: self.generation,\n },\n };\n // Recorded (the host writes it to the store before the request leaves); a retry (an attempt was made under its\n // key already) may have run.\n let record = OutstandingSend {\n text: send.text.clone(),\n conversation_id: send.conversation_id.clone(),\n key: send.key.clone(),\n state: SendState::Sending,\n doubtful: self.outstanding.iter().any(|s| s.key == send.key),\n };\n outstanding::put(&mut self.outstanding, record);\n self.sending = Some(send.clone());\n self.error = None;\n Some(send)\n }\n\n /// The send under `key` was accepted: its conversation and run. True when the draft is to be cleared.\n pub fn sent(&mut self, key: &str, conversation_id: String, run_id: String) -> (bool, Vec<ChatEffect>) {\n outstanding::settle(&mut self.outstanding, key, &Outcome::Ran);\n let Some(send) = self.sending.take_if(|s| s.key == key) else { return (false, Vec::new()) };\n if send.conversation_id != self.conversation_id {\n return (false, Vec::new());\n }\n self.conversation_id = Some(conversation_id.clone());\n self.chose_new = false;\n if !self.runs.iter().any(|r| r.id == run_id) {\n self.pending_run =\n Some(Run { id: run_id.clone(), conversation_id, status: \"queued\".into(), created_at: 0.0 });\n }\n self.live = Some(Live { run_id, after: -1, steps: 0, streamed: Vec::new() });\n (true, self.wanted())\n }\n\n /// The send under `key` was a replay of one already made (its first answer was lost): it ran then. Its run and\n /// conversation reach the screen through the replica; a first send's conversation is the newest, which is shown.\n /// True when the draft is to be cleared.\n pub fn replayed(&mut self, key: &str) -> (bool, Vec<ChatEffect>) {\n outstanding::settle(&mut self.outstanding, key, &Outcome::Ran);\n let Some(send) = self.sending.take_if(|s| s.key == key) else { return (false, Vec::new()) };\n if send.conversation_id != self.conversation_id {\n return (false, Vec::new());\n }\n if self.conversation_id.is_none() {\n self.conversation_id = self.conversations.as_ref().and_then(|c| c.first()).map(|c| c.id.clone());\n self.chose_new = false;\n }\n (true, self.wanted())\n }\n\n /// The send under `key` failed: refused (`definitive`) at its first and only attempt, it did not run and its\n /// error shows with the draft; refused after an attempt that went unanswered, it is kept `unconfirmed` under its\n /// key; its answer lost, it is kept to be resent under its key.\n pub fn send_failed(&mut self, key: &str, tag: String, message: String, definitive: bool) {\n outstanding::settle(&mut self.outstanding, key, &if definitive { Outcome::Refused } else { Outcome::Lost });\n if self.sending.take_if(|s| s.key == key).is_none() {\n return;\n }\n self.error = Some((tag, message));\n }\n\n /// The person gives up on the outstanding send under `key`.\n pub fn discard(&mut self, key: &str) {\n outstanding::settle(&mut self.outstanding, key, &Outcome::Discarded);\n }\n\n /// Show a new conversation (the first send starts it): nothing of the previous one but the composer.\n pub fn open_new(&mut self) -> Vec<ChatEffect> {\n self.conversation_id = None;\n self.chose_new = true;\n self.live = None;\n self.consents.clear();\n self.error = None;\n let mut effects = Vec::new();\n if let Some(f) = self.followed.take() {\n effects.push(ChatEffect::Unfollow { id: f.id });\n }\n effects\n }\n\n /// Shows conversation `id` (a link or a notification named it): its active run is followed.\n pub fn open(&mut self, id: &str) -> Vec<ChatEffect> {\n if self.conversation_id.as_deref() == Some(id) {\n return Vec::new();\n }\n let mut effects = self.open_new();\n self.conversation_id = Some(id.to_owned());\n self.chose_new = false;\n effects.extend(self.wanted());\n effects\n }\n\n /// The conversation whose run holds the call `consent_id` waits on: its run's, when the followed run reported it;\n /// otherwise (consent requests are not synced, so the replica does not say which run holds it) the conversation of\n /// the newest run waiting. None when no run waits.\n pub fn conversation_for_consent(&self, consent_id: &str) -> Option<String> {\n if let Some(c) = self.consents.iter().find(|c| c.consent_id == consent_id) {\n return self.known().find(|r| r.id == c.run_id).map(|r| r.conversation_id.clone());\n }\n self.runs\n .iter()\n .filter(|r| r.status == \"waiting\" && !self.ended.contains(&r.id))\n .max_by(|a, b| a.created_at.total_cmp(&b.created_at))\n .map(|r| r.conversation_id.clone())\n }\n\n /// A decision (consent or approval `id`) is on its way.\n pub fn deciding(&mut self, id: &str) {\n if !self.deciding.iter().any(|d| d == id) {\n self.deciding.push(id.to_owned());\n }\n self.error = None;\n }\n\n /// A decision answered: refused, its error shows (the prompt stays until the run or the replica says otherwise).\n pub fn decided(&mut self, id: &str, refused: Option<(String, String)>) {\n self.deciding.retain(|d| d != id);\n if refused.is_some() {\n self.error = refused;\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use serde_json::json;\n\n fn ev(run: &str, seq: i64, kind: &str, data: Value) -> AgentRunEvent {\n serde_json::from_value(json!({ \"runId\": run, \"seq\": seq, \"type\": kind, \"data\": data, \"at\": \"\" }))\n .expect(\"event\")\n }\n\n fn chat() -> Chat {\n let mut c = Chat::new(1);\n for q in CHAT_QUERIES {\n c.subscribing(q, format!(\"s-{q}\"));\n }\n c\n }\n\n #[test]\n fn a_send_follows_its_run_and_the_stored_answer_replaces_the_streamed_one() {\n let mut c = chat();\n c.rows(\"s-agent.conversations\", &[]);\n assert!(c.conversation_id.is_none());\n let send = c.submit(\" hello \", \"k1\".into()).expect(\"a send\");\n assert_eq!(send, Send { key: \"k1\".into(), text: \"hello\".into(), conversation_id: None, generation: 1 });\n assert!(c.submit(\"again\", \"k2\".into()).is_none(), \"one send at a time\");\n let (clear, effects) = c.sent(\"k1\", \"c1\".into(), \"r1\".into());\n assert!(clear);\n assert_eq!(effects, vec![ChatEffect::Follow { run_id: \"r1\".into(), after: -1 }]);\n c.following(\"f1\".into(), \"r1\".into());\n assert!(!c.can_send(\"next\"), \"the run holds the composer\");\n c.run_event(\n \"f1\",\n Some(&ev(\"r1\", -1, \"text-delta\", json!({ \"delta\": \"Hel\", \"step\": 0, \"attempt\": \"a\" }))),\n None,\n );\n c.run_event(\"f1\", Some(&ev(\"r1\", -1, \"text-delta\", json!({ \"delta\": \"lo\", \"step\": 0, \"attempt\": \"a\" }))), None);\n // Another subscription's event (an old one) changes nothing.\n c.run_event(\"f0\", Some(&ev(\"r1\", -1, \"text-delta\", json!({ \"delta\": \"stale\", \"step\": 0 }))), None);\n c.rows(\n \"s-agent.messages\",\n &[json!({ \"id\": \"m1\", \"conversationId\": \"c1\", \"runId\": \"r1\", \"seq\": 1, \"role\": \"user\", \"text\": \"hello\" })],\n );\n let t = c.transcript();\n assert_eq!(\n t.iter().map(|e| (e.text.as_str(), e.live)).collect::<Vec<_>>(),\n [(\"hello\", false), (\"Hello\", true)]\n );\n assert_eq!(c.deltas, 2);\n c.run_event(\"f1\", Some(&ev(\"r1\", 3, \"run-finished\", json!({ \"status\": \"succeeded\" }))), None);\n assert!(c.followed.is_none() && c.active_run().is_none());\n assert!(c.can_send(\"next\"), \"the stream's end frees the composer before the replica says so\");\n c.rows(\"s-agent.messages\", &[\n json!({ \"id\": \"m1\", \"conversationId\": \"c1\", \"runId\": \"r1\", \"seq\": 1, \"role\": \"user\", \"text\": \"hello\" }),\n json!({ \"id\": \"m2\", \"conversationId\": \"c1\", \"runId\": \"r1\", \"seq\": 2, \"role\": \"assistant\", \"text\": \"Hello.\" }),\n ]);\n let t = c.transcript();\n assert_eq!(\n t.iter().map(|e| (e.text.as_str(), e.live)).collect::<Vec<_>>(),\n [(\"hello\", false), (\"Hello.\", false)]\n );\n }\n\n #[test]\n fn only_streamed_text_the_transcript_took_counts_and_a_stored_step_is_not_streamed_text() {\n let mut c = chat();\n c.rows(\"s-agent.conversations\", &[]);\n c.submit(\"hi\", \"k1\".into());\n c.sent(\"k1\", \"c1\".into(), \"r1\".into());\n c.following(\"f1\".into(), \"r1\".into());\n c.run_event(\"f1\", Some(&ev(\"r1\", 1, \"model-step\", json!({ \"step\": 0, \"text\": \"Done.\" }))), None);\n // Two deltas of the step already done (obsolete), and an empty one: none reaches the transcript.\n for delta in [\"Do\", \"ne.\", \"\"] {\n c.run_event(\"f1\", Some(&ev(\"r1\", -1, \"text-delta\", json!({ \"delta\": delta, \"step\": 0 }))), None);\n }\n assert_eq!(c.deltas, 0);\n c.run_event(\"f1\", Some(&ev(\"r1\", -1, \"text-delta\", json!({ \"delta\": \"Next\", \"step\": 1 }))), None);\n assert_eq!(c.deltas, 1);\n }\n\n #[test]\n fn consent_comes_from_the_followed_run_once_and_leaves_when_decided() {\n let mut c = chat();\n c.rows(\"s-agent.conversations\", &[json!({ \"id\": \"c1\", \"title\": \"Notes\" })]);\n assert_eq!(c.conversation_id.as_deref(), Some(\"c1\"), \"the latest is opened\");\n let effects = c.rows(\n \"s-agent.runs\",\n &[json!({ \"id\": \"r1\", \"conversationId\": \"c1\", \"status\": \"waiting\", \"createdAt\": 1 })],\n );\n assert_eq!(effects, vec![ChatEffect::Follow { run_id: \"r1\".into(), after: -1 }]);\n c.following(\"f1\".into(), \"r1\".into());\n let asked = ev(\"r1\", 2, \"consent-required\", json!({ \"consentId\": \"k1\", \"action\": \"agent.moveResources\" }));\n c.run_event(\"f1\", Some(&asked), None);\n c.run_event(\"f1\", Some(&asked), None);\n assert_eq!(c.consents.len(), 1);\n assert_eq!(consent_key(\"k1\", Decision::Approve), \"consent:k1:approve:\");\n c.run_event(\"f1\", Some(&ev(\"r1\", 3, \"consent-decided\", json!({ \"consentId\": \"k1\" }))), None);\n assert!(c.consents.is_empty());\n }\n\n #[test]\n fn a_lost_answer_is_resent_under_its_key_and_a_refusal_keeps_the_draft() {\n let mut c = chat();\n c.rows(\"s-agent.conversations\", &[]);\n let first = c.submit(\"hi\", \"k1\".into()).expect(\"send\");\n c.send_failed(&first.key, \"Transport\".into(), \"no answer\".into(), false);\n let retry = c.submit(\"\", \"k2\".into()).expect(\"a resend, with an empty draft\");\n assert_eq!(retry.key, \"k1\");\n // The retry is refused (the policy changed): that says nothing about the first attempt, which may have run.\n c.send_failed(\"k1\", \"Forbidden\".into(), \"no\".into(), true);\n assert_eq!(c.error, Some((\"Forbidden\".into(), \"no\".into())));\n assert_eq!(c.outstanding_send(\"k1\").map(|s| s.state), Some(SendState::Unconfirmed));\n let next = c.submit(\"hi\", \"k3\".into()).expect(\"a send\");\n assert_eq!(next.key, \"k1\", \"kept under its own key, never sent again under a new one\");\n c.send_failed(\"k1\", \"Forbidden\".into(), \"no\".into(), true);\n c.discard(\"k1\");\n assert!(c.unresolved_here().is_none(), \"until the person discards it\");\n // Refused at its first and only attempt: it did not run, and goes.\n let first = c.submit(\"hi\", \"k4\".into()).expect(\"a send\");\n c.send_failed(&first.key, \"Forbidden\".into(), \"no\".into(), true);\n assert!(c.outstanding.is_empty());\n }\n\n #[test]\n fn the_engine_not_set_up_holds_the_send_but_not_the_draft() {\n let mut c = chat();\n c.engine = Some(EngineReadiness {\n state: EngineReadinessState::Missing,\n provider: None,\n model: None,\n detail: \"Set up a model\".into(),\n });\n assert!(c.engine_blocked());\n assert!(c.submit(\"hello\", \"k\".into()).is_none());\n }\n\n #[test]\n fn approvals_to_decide_are_someone_elses_pending_requests() {\n let mut c = chat();\n c.rows(\n \"s-approvals.requests\",\n &[\n json!({ \"id\": \"a1\", \"requesterId\": \"u-ben\", \"action\": \"x.pay\", \"status\": \"pending\", \"createdAt\": 2 }),\n json!({ \"id\": \"a2\", \"requesterId\": \"u-ada\", \"action\": \"x.pay\", \"status\": \"pending\", \"createdAt\": 1 }),\n json!({ \"id\": \"a3\", \"requesterId\": \"u-ben\", \"action\": \"x.pay\", \"status\": \"approved\", \"createdAt\": 3 }),\n ],\n );\n assert_eq!(c.approvals_to_decide(\"u-ada\").iter().map(|a| a.id.as_str()).collect::<Vec<_>>(), [\"a1\"]);\n assert_eq!(approval_key(\"a1\", Decision::Reject), \"approval:a1:reject\");\n }\n}\n\n#[cfg(test)]\nmod label_tests {\n use super::{action_label, decision_label, make_decision_label, readable_action_name};\n\n #[test]\n fn an_action_is_named_by_its_title_or_its_readable_name_never_its_id() {\n // The same words as `readableActionName` in @eloxiv/contracts.\n assert_eq!(readable_action_name(\"mail.send\"), \"Send (mail)\");\n assert_eq!(readable_action_name(\"agent.moveResources\"), \"Move resources (agent)\");\n assert_eq!(readable_action_name(\"calendar.freeBusy\"), \"Free busy (calendar)\");\n assert_eq!(readable_action_name(\"mk_tasks.addTask\"), \"Add task (mk_tasks)\");\n assert_eq!(readable_action_name(\"x.y\"), \"Y (x)\");\n assert_eq!(action_label(\"mail.send\", Some(\"Send an email\")), \"Send an email\");\n assert_eq!(action_label(\"mail.send\", Some(\" \")), \"Send (mail)\");\n assert_eq!(action_label(\"mail.send\", None), \"Send (mail)\");\n }\n\n #[test]\n fn a_make_action_is_named_by_its_module_first_never_its_own_title() {\n assert_eq!(decision_label(\"mk_todos.urgent\", Some(\"Tidy up your list\")), \"mk_todos: Urgent\");\n assert_eq!(decision_label(\"mk_todos.addItem\", None), \"mk_todos: Add item\");\n assert_eq!(decision_label(\"mail.send\", Some(\"Send an email\")), \"Send an email\", \"other titles stay\");\n // A long action key: only its words are cut; the module stays whole.\n let long = format!(\"mk_todos.{}\", \"really_long_words_\".repeat(8));\n let label = make_decision_label(&long);\n assert!(label.starts_with(\"mk_todos: Really long words\"), \"{label}\");\n assert!(label.ends_with('…') && label.chars().count() <= 80, \"{label}\");\n let module = format!(\"mk_{}\", \"m\".repeat(80));\n assert_eq!(make_decision_label(&format!(\"{module}.go\")), module, \"a module never cut\");\n }\n}\n",
108
+ "type": "registry:file",
109
+ "target": "desktop-rune/app/src/chat.rs"
110
+ },
111
+ {
112
+ "path": "app/desktop-rune/app/src/config.rs",
113
+ "content": "//! The app's identity and host settings: `desktop-rune/app.json`, the one file the app edits. Packaging\n//! (`scripts/package.ts`), this host and the release signer (`eloxiv-update release --config app.json`) read the same\n//! file, so the installers, the running window and the update manifests always agree. It is compiled in: a packaged\n//! build carries its own identity and settings, and an update replaces them with the new build's.\n//!\n//! ```json\n//! {\n//! \"name\": \"Example\", // the window title and the installed app's name\n//! \"identifier\": \"com.example.app\", // reverse DNS: window app id, data directories, single instance, keychain\n//! \"binaryName\": \"example\", // the installed executable; its sidecar is example-daemon\n//! \"version\": \"1.2.0\", // this build (semver): updates only move to a newer one\n//! \"description\": \"…\", \"publisher\": \"…\", \"copyright\": \"…\", \"category\": \"Productivity\", \"icon\": \"app-icon.svg\",\n//! \"urlScheme\": \"example\", // deep links: example://open/<path>, registered by the installers\n//! \"deepLinks\": { \"register\": true }, // register the scheme at launch where no installer did (AppImage, dev)\n//! \"servers\": { // what a packaged app reaches (given to its sidecar)\n//! \"kernelUrl\": \"https://api.example.com\",\n//! \"zeroUrl\": \"https://sync.example.com\",\n//! \"shellUrl\": \"https://app.example.com\"\n//! },\n//! \"updates\": { // without a url and a publicKey, updates are unsupported\n//! \"url\": \"https://updates.example.com/{channel}/{platform}-{kind}.json\",\n//! \"publicKey\": \"RWQ…\", // minisign public key (`eloxiv-update keygen`)\n//! \"channel\": \"stable\"\n//! }\n//! }\n//! ```\n//!\n//! Over the compiled file: `ELOXIV_HOST_CONFIG` (a path to another `app.json`, read whole, for tests and trying a\n//! configuration without rebuilding), then each environment variable overrides its field: `ELOXIV_APP_ID`,\n//! `ELOXIV_APP_NAME`, `ELOXIV_APP_SCHEME`, `ELOXIV_APP_VERSION`, `ELOXIV_UPDATE_URL`, `ELOXIV_UPDATE_PUBLIC_KEY`,\n//! `ELOXIV_UPDATE_CHANNEL`, `ELOXIV_REGISTER_SCHEME` (`0` or `false`: never register the scheme), `ELOXIV_KERNEL_URL`,\n//! `ELOXIV_ZERO_URL`, `ELOXIV_SHELL_URL` (the names the daemon reads). An override that is not valid is refused with the\n//! reason and the compiled value kept. The compiled file itself must be valid: its tests and `package.ts` refuse a\n//! broken one before it is built.\n\nuse std::path::PathBuf;\nuse std::sync::OnceLock;\n\nuse serde::Deserialize;\n\n/// The host's configuration.\n#[derive(Clone, Debug, PartialEq)]\npub struct HostConfig {\n pub app_id: String,\n pub name: String,\n /// The installed executable's file name; its sidecar is `<binary_name>-daemon`.\n pub binary_name: String,\n pub scheme: String,\n pub version: semver::Version,\n pub updates: Option<UpdatesConfig>,\n pub register_scheme: bool,\n pub servers: Servers,\n /// The file it was read from, when not the compiled one (`ELOXIV_HOST_CONFIG`).\n pub file: Option<PathBuf>,\n /// Overrides refused while reading it, for the log.\n pub problems: Vec<String>,\n}\n\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct UpdatesConfig {\n pub url: String,\n pub public_key: String,\n pub channel: String,\n}\n\n/// The servers a packaged app reaches, given to its sidecar (`ELOXIV_KERNEL_URL`, `ELOXIV_ZERO_URL`,\n/// `ELOXIV_SHELL_URL`). None: the daemon's own default (the app's `clientApp`, else its development defaults).\n#[derive(Clone, Debug, Default, PartialEq, Eq)]\npub struct Servers {\n pub kernel_url: Option<String>,\n pub zero_url: Option<String>,\n pub shell_url: Option<String>,\n}\n\nimpl Servers {\n /// The sidecar's environment for them.\n pub fn env(&self) -> Vec<(&'static str, String)> {\n [\n (\"ELOXIV_KERNEL_URL\", &self.kernel_url),\n (\"ELOXIV_ZERO_URL\", &self.zero_url),\n (\"ELOXIV_SHELL_URL\", &self.shell_url),\n ]\n .into_iter()\n .filter_map(|(name, value)| value.clone().map(|v| (name, v)))\n .collect()\n }\n}\n\n/// The app's `app.json`, compiled in.\npub const APP_JSON: &str = include_str!(\"../../app.json\");\n\n#[derive(Debug, Deserialize)]\n#[serde(rename_all = \"camelCase\", deny_unknown_fields)]\nstruct File {\n name: String,\n identifier: String,\n binary_name: String,\n version: String,\n url_scheme: String,\n // For the installers only (`package.ts`).\n #[serde(default)]\n #[allow(dead_code)]\n description: Option<String>,\n #[serde(default)]\n #[allow(dead_code)]\n publisher: Option<String>,\n #[serde(default)]\n #[allow(dead_code)]\n copyright: Option<String>,\n #[serde(default)]\n #[allow(dead_code)]\n category: Option<String>,\n #[serde(default)]\n #[allow(dead_code)]\n icon: Option<String>,\n #[serde(default)]\n deep_links: DeepLinksSection,\n #[serde(default)]\n servers: ServersSection,\n #[serde(default)]\n updates: UpdatesSection,\n}\n\n#[derive(Debug, Default, Deserialize)]\n#[serde(rename_all = \"camelCase\", deny_unknown_fields)]\nstruct DeepLinksSection {\n register: Option<bool>,\n}\n\n#[derive(Debug, Default, Deserialize)]\n#[serde(rename_all = \"camelCase\", deny_unknown_fields)]\nstruct ServersSection {\n kernel_url: Option<String>,\n zero_url: Option<String>,\n shell_url: Option<String>,\n}\n\n#[derive(Debug, Default, Deserialize)]\n#[serde(rename_all = \"camelCase\", deny_unknown_fields)]\nstruct UpdatesSection {\n url: Option<String>,\n public_key: Option<String>,\n channel: Option<String>,\n}\n\n/// An app identifier: reverse DNS (`com.example.app`): at least two dot-separated segments of ASCII letters,\n/// digits and inner hyphens, at most 255 characters (Tauri's rule, which the keychain namespace shares).\npub fn valid_app_id(id: &str) -> bool {\n let segment = |s: &str| {\n !s.is_empty()\n && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')\n && !s.starts_with('-')\n && !s.ends_with('-')\n };\n let segments: Vec<&str> = id.split('.').collect();\n id.len() <= 255 && segments.len() >= 2 && segments.iter().all(|s| segment(s))\n}\n\n/// A deep-link scheme: a URL scheme (RFC 3986: a letter, then letters, digits, `+`, `-`, `.`), lower case, at\n/// least two characters (a Windows drive letter is not one), and none the system or browsers own.\npub fn valid_scheme(scheme: &str) -> bool {\n const RESERVED: &[&str] =\n &[\"http\", \"https\", \"file\", \"ftp\", \"mailto\", \"javascript\", \"data\", \"about\", \"blob\", \"ws\", \"wss\", \"tel\", \"sms\"];\n scheme.len() >= 2\n && scheme.len() <= 64\n && scheme.starts_with(|c: char| c.is_ascii_lowercase())\n && scheme.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '+' | '-' | '.'))\n && !RESERVED.contains(&scheme)\n}\n\n/// An executable name: lower case letters, digits and `-`, starting with a letter or digit.\npub fn valid_binary_name(name: &str) -> bool {\n name.starts_with(|c: char| c.is_ascii_lowercase() || c.is_ascii_digit())\n && name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')\n}\n\n/// A server's URL: absolute `http` or `https`.\npub fn valid_server_url(value: &str) -> bool {\n url::Url::parse(value).is_ok_and(|u| matches!(u.scheme(), \"http\" | \"https\") && u.host().is_some())\n}\n\nfn version(v: &str) -> Result<semver::Version, String> {\n semver::Version::parse(v.trim()).map_err(|e| format!(\"version {v:?} is not major.minor.patch ({e})\"))\n}\n\nfn non_empty(v: Option<String>) -> Option<String> {\n v.map(|v| v.trim().to_owned()).filter(|v| !v.is_empty())\n}\n\nfn updates(url: Option<String>, key: Option<String>, channel: Option<String>) -> Result<Option<UpdatesConfig>, String> {\n let channel = non_empty(channel).unwrap_or_else(|| \"stable\".into());\n match (non_empty(url), non_empty(key)) {\n (Some(url), Some(public_key)) => Ok(Some(UpdatesConfig { url, public_key, channel })),\n (Some(_), None) => Err(\"updates.url is set without updates.publicKey: updates stay off\".into()),\n _ => Ok(None),\n }\n}\n\n/// Reads and checks an `app.json`: every problem, or the configuration.\npub fn parse(json: &str) -> Result<HostConfig, String> {\n let file: File = serde_json::from_str(json).map_err(|e| e.to_string())?;\n let mut problems = Vec::new();\n if file.name.trim().is_empty() {\n problems.push(\"name is empty\".to_owned());\n }\n if !valid_app_id(&file.identifier) {\n problems.push(format!(\"identifier {:?} is not reverse-DNS (com.example.app)\", file.identifier));\n }\n if !valid_binary_name(&file.binary_name) {\n problems.push(format!(\"binaryName {:?}: lower case letters, digits and -\", file.binary_name));\n }\n let parsed_version = version(&file.version).map_err(|e| problems.push(e)).ok();\n if !valid_scheme(&file.url_scheme) {\n problems.push(format!(\n \"urlScheme {:?} is not a URL scheme this app may own (lower case, not http, file, …)\",\n file.url_scheme\n ));\n }\n let mut servers = Servers::default();\n for (field, value, slot) in [\n (\"servers.kernelUrl\", file.servers.kernel_url, &mut servers.kernel_url),\n (\"servers.zeroUrl\", file.servers.zero_url, &mut servers.zero_url),\n (\"servers.shellUrl\", file.servers.shell_url, &mut servers.shell_url),\n ] {\n match non_empty(value) {\n Some(v) if valid_server_url(&v) => *slot = Some(v),\n Some(v) => problems.push(format!(\"{field} {v:?} is not an http(s) URL\")),\n None => {}\n }\n }\n let updates =\n updates(file.updates.url, file.updates.public_key, file.updates.channel).map_err(|e| problems.push(e)).ok();\n match (parsed_version, updates) {\n (Some(version), Some(updates)) if problems.is_empty() => Ok(HostConfig {\n app_id: file.identifier,\n name: file.name,\n binary_name: file.binary_name,\n scheme: file.url_scheme,\n version,\n updates,\n register_scheme: file.deep_links.register.unwrap_or(true),\n servers,\n file: None,\n problems: Vec::new(),\n }),\n _ => Err(problems.join(\"; \")),\n }\n}\n\n/// This process's configuration, read once ([`HostConfig::load`]).\npub fn current() -> &'static HostConfig {\n static CURRENT: OnceLock<HostConfig> = OnceLock::new();\n CURRENT.get_or_init(HostConfig::load)\n}\n\nimpl HostConfig {\n /// The compiled `app.json`.\n pub fn compiled() -> HostConfig {\n match parse(APP_JSON) {\n Ok(config) => config,\n // The tests and the packaging script refuse such a file first; a build from an edited, broken one says why.\n Err(why) => panic!(\"desktop-rune/app.json: {why}\"),\n }\n }\n\n /// The compiled file, `ELOXIV_HOST_CONFIG` instead when set (and valid), then the environment's overrides.\n pub fn load() -> HostConfig {\n let mut config = HostConfig::compiled();\n if let Some(path) = std::env::var_os(\"ELOXIV_HOST_CONFIG\").filter(|p| !p.is_empty()).map(PathBuf::from) {\n match std::fs::read_to_string(&path).map_err(|e| e.to_string()).and_then(|t| parse(&t)) {\n Ok(other) => config = HostConfig { file: Some(path), ..other },\n Err(e) => config.problems.push(format!(\"{} (ELOXIV_HOST_CONFIG): {e}\", path.display())),\n }\n }\n config.apply_env(|name| std::env::var(name).ok());\n config\n }\n\n /// Applies the environment's overrides (`var` reads one).\n pub fn apply_env(&mut self, var: impl Fn(&str) -> Option<String>) {\n if let Some(id) = var(\"ELOXIV_APP_ID\") {\n if valid_app_id(&id) {\n self.app_id = id;\n } else {\n self.problems.push(format!(\"ELOXIV_APP_ID {id:?} is not an app identifier (reverse DNS)\"));\n }\n }\n if let Some(name) = non_empty(var(\"ELOXIV_APP_NAME\")) {\n self.name = name;\n }\n if let Some(scheme) = var(\"ELOXIV_APP_SCHEME\") {\n if valid_scheme(&scheme) {\n self.scheme = scheme;\n } else {\n self.problems.push(format!(\"ELOXIV_APP_SCHEME {scheme:?} is not a deep-link scheme this app may own\"));\n }\n }\n if let Some(v) = var(\"ELOXIV_APP_VERSION\") {\n match version(&v) {\n Ok(v) => self.version = v,\n Err(e) => self.problems.push(format!(\"ELOXIV_APP_VERSION: {e}\")),\n }\n }\n let (url, key, channel) =\n (var(\"ELOXIV_UPDATE_URL\"), var(\"ELOXIV_UPDATE_PUBLIC_KEY\"), var(\"ELOXIV_UPDATE_CHANNEL\"));\n if url.is_some() || key.is_some() || channel.is_some() {\n let current = self.updates.clone();\n match updates(\n url.or_else(|| current.as_ref().map(|u| u.url.clone())),\n key.or_else(|| current.as_ref().map(|u| u.public_key.clone())),\n channel.or_else(|| current.as_ref().map(|u| u.channel.clone())),\n ) {\n Ok(u) => self.updates = u,\n Err(e) => self.problems.push(e),\n }\n }\n if let Some(v) = var(\"ELOXIV_REGISTER_SCHEME\") {\n self.register_scheme = !matches!(v.trim(), \"0\" | \"false\" | \"no\" | \"off\");\n }\n for (name, slot) in [\n (\"ELOXIV_KERNEL_URL\", &mut self.servers.kernel_url),\n (\"ELOXIV_ZERO_URL\", &mut self.servers.zero_url),\n (\"ELOXIV_SHELL_URL\", &mut self.servers.shell_url),\n ] {\n match non_empty(var(name)) {\n Some(v) if valid_server_url(&v) => *slot = Some(v),\n Some(v) => self.problems.push(format!(\"{name} {v:?} is not an http(s) URL\")),\n None => {}\n }\n }\n }\n}\n\nimpl Default for HostConfig {\n /// The compiled configuration, without the environment (tests).\n fn default() -> HostConfig {\n HostConfig::compiled()\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n fn with(edit: impl FnOnce(&mut serde_json::Value)) -> Result<HostConfig, String> {\n let mut json: serde_json::Value = serde_json::from_str(APP_JSON).expect(\"app.json\");\n edit(&mut json);\n parse(&json.to_string())\n }\n\n #[test]\n fn the_checked_in_app_json_is_valid() {\n let config = parse(APP_JSON).expect(\"app.json\");\n assert_eq!(config, HostConfig::compiled());\n assert!(config.problems.is_empty());\n }\n\n #[test]\n fn identity_servers_and_updates_come_from_app_json() {\n let config = with(|j| {\n j[\"identifier\"] = \"com.acme.crm\".into();\n j[\"name\"] = \"Acme CRM\".into();\n j[\"binaryName\"] = \"acme-crm\".into();\n j[\"urlScheme\"] = \"acme-crm\".into();\n j[\"version\"] = \"2.3.4\".into();\n j[\"deepLinks\"] = serde_json::json!({ \"register\": false });\n j[\"servers\"] =\n serde_json::json!({ \"kernelUrl\": \"https://api.acme.com\", \"zeroUrl\": \"https://sync.acme.com\" });\n j[\"updates\"] = serde_json::json!({ \"url\": \"https://u.acme.com/{channel}.json\", \"publicKey\": \"RWQkey\" });\n })\n .expect(\"valid\");\n assert_eq!((config.app_id.as_str(), config.name.as_str()), (\"com.acme.crm\", \"Acme CRM\"));\n assert_eq!((config.binary_name.as_str(), config.scheme.as_str()), (\"acme-crm\", \"acme-crm\"));\n assert_eq!(config.version, semver::Version::new(2, 3, 4));\n assert!(!config.register_scheme);\n assert_eq!(\n config.updates,\n Some(UpdatesConfig {\n url: \"https://u.acme.com/{channel}.json\".into(),\n public_key: \"RWQkey\".into(),\n channel: \"stable\".into()\n })\n );\n assert_eq!(\n config.servers.env(),\n vec![\n (\"ELOXIV_KERNEL_URL\", \"https://api.acme.com\".into()),\n (\"ELOXIV_ZERO_URL\", \"https://sync.acme.com\".into())\n ]\n );\n }\n\n #[test]\n fn a_malformed_app_json_is_refused_with_why() {\n let field = |name: &str, value: &str| {\n let (name, value) = (name.to_owned(), value.to_owned());\n with(move |j| j[name] = value.into())\n };\n assert!(field(\"identifier\", \"app\").expect_err(\"refused\").contains(\"reverse-DNS\"));\n assert!(field(\"identifier\", \"com..app\").is_err());\n assert!(field(\"identifier\", \"com.example/app\").is_err());\n assert!(field(\"binaryName\", \"Hello App\").expect_err(\"refused\").contains(\"binaryName\"));\n assert!(field(\"binaryName\", \"-x\").is_err());\n assert!(field(\"version\", \"1.0\").expect_err(\"refused\").contains(\"major.minor.patch\"));\n assert!(field(\"urlScheme\", \"My App\").expect_err(\"refused\").contains(\"urlScheme\"));\n assert!(field(\"urlScheme\", \"https\").is_err());\n assert!(field(\"name\", \" \").is_err());\n assert!(parse(\"{}\").is_err());\n assert!(with(|j| j[\"servers\"] = serde_json::json!({ \"kernelUrl\": \"localhost:4200\" })).is_err());\n let refused = with(|j| j[\"updates\"] = serde_json::json!({ \"url\": \"https://x\" })).expect_err(\"refused\");\n assert!(refused.contains(\"publicKey\"), \"{refused}\");\n assert!(with(|j| j[\"unknown\"] = 1.into()).expect_err(\"refused\").contains(\"unknown\"), \"a typo is reported\");\n assert!(with(|j| j[\"updates\"] = serde_json::json!({ \"public_key\": \"k\" })).is_err(), \"camelCase only\");\n let two = with(|j| {\n j[\"identifier\"] = \"app\".into();\n j[\"version\"] = \"one\".into();\n })\n .expect_err(\"refused\");\n assert_eq!(two.split(\"; \").count(), 2, \"every problem at once: {two}\");\n }\n\n #[test]\n fn the_environment_overrides_each_field_and_refuses_invalid_values() {\n let mut c = with(|j| j[\"updates\"] = serde_json::json!({ \"url\": \"https://u/x.json\", \"publicKey\": \"RWQkey\" }))\n .expect(\"valid\");\n let env = |name: &str| match name {\n \"ELOXIV_UPDATE_CHANNEL\" => Some(\"beta\".into()),\n \"ELOXIV_APP_VERSION\" => Some(\"2.4.0\".into()),\n \"ELOXIV_REGISTER_SCHEME\" => Some(\"0\".into()),\n \"ELOXIV_KERNEL_URL\" => Some(\"http://127.0.0.1:4200\".into()),\n \"ELOXIV_ZERO_URL\" => Some(\"not a url\".into()),\n \"ELOXIV_APP_ID\" => Some(\"app\".into()),\n _ => None,\n };\n c.apply_env(env);\n assert_eq!(c.updates.as_ref().map(|u| u.channel.as_str()), Some(\"beta\"));\n assert_eq!(c.updates.as_ref().map(|u| u.public_key.as_str()), Some(\"RWQkey\"), \"kept\");\n assert_eq!(c.version, semver::Version::new(2, 4, 0));\n assert!(!c.register_scheme);\n assert_eq!(c.servers.kernel_url.as_deref(), Some(\"http://127.0.0.1:4200\"));\n assert_eq!(c.servers.zero_url, None, \"refused\");\n assert_eq!(c.app_id, HostConfig::compiled().app_id, \"refused, the compiled one kept\");\n assert_eq!(c.problems.len(), 2, \"{:?}\", c.problems);\n }\n\n #[test]\n fn schemes_and_identifiers() {\n for ok in [\"eloxiv\", \"acme-crm\", \"x.y+z\", \"app2\"] {\n assert!(valid_scheme(ok), \"{ok}\");\n }\n for bad in [\"\", \"c\", \"Eloxiv\", \"2app\", \"a b\", \"https\", \"file\", \"javascript\", \"a:b\"] {\n assert!(!valid_scheme(bad), \"{bad}\");\n }\n for ok in [\"dev.eloxiv.app\", \"com.acme.crm-2\"] {\n assert!(valid_app_id(ok), \"{ok}\");\n }\n for bad in [\"\", \"app\", \"com..app\", \"com.-app\", \"com.app-\", \"com/app\", \"com.a pp\"] {\n assert!(!valid_app_id(bad), \"{bad}\");\n }\n }\n}\n",
114
+ "type": "registry:file",
115
+ "target": "desktop-rune/app/src/config.rs"
116
+ },
117
+ {
118
+ "path": "app/desktop-rune/app/src/host.rs",
119
+ "content": "//! The Host contract (decision 7; docs/contracts/host.md) as this native host implements it: deep links\n//! ([`crate::links`]), secure storage ([`crate::keychain`]) and updates ([`crate::updates`]); push and file access\n//! are not implemented and fail with [`HostError::Unsupported`], as does any capability this install cannot do\n//! (updates without an update host configured, or on an install the host cannot replace).\n//!\n//! Push, as the contract means it, is a subscription a NotificationChannel delivers to (Web Push, APNs, FCM): this\n//! host has none, so `push` stays unsupported. What it does instead is show the person's in-app notifications as OS\n//! notifications **while it runs** ([`crate::notices`]), which `HostServices::notifications` reports with its\n//! backend and the OS permission it maps to.\n\n/// A Host operation's failure, as the contract names them.\n#[derive(Clone, Debug, PartialEq, Eq)]\npub enum HostError {\n /// The capability is not available here (`HostUnsupported { capability }`), with why.\n Unsupported {\n capability: Capability,\n reason: String,\n },\n PermissionDenied(String),\n Cancelled,\n Failure(String),\n}\n\nimpl std::fmt::Display for HostError {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n match self {\n HostError::Unsupported { capability, reason } => {\n write!(f, \"HostUnsupported: {} ({reason})\", capability.name())\n }\n HostError::PermissionDenied(m) => write!(f, \"HostPermissionDenied: {m}\"),\n HostError::Cancelled => f.write_str(\"HostCancelled\"),\n HostError::Failure(m) => write!(f, \"HostFailure: {m}\"),\n }\n }\n}\n\nimpl std::error::Error for HostError {}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum Capability {\n DeepLinks,\n Push,\n SecureStorage,\n Updates,\n Files,\n}\n\nimpl Capability {\n /// Its name in the contract.\n pub fn name(self) -> &'static str {\n match self {\n Capability::DeepLinks => \"deepLinks\",\n Capability::Push => \"push\",\n Capability::SecureStorage => \"secureStorage\",\n Capability::Updates => \"updates\",\n Capability::Files => \"files\",\n }\n }\n}\n\n/// `capabilities()`: each `supported` or `unsupported`.\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub struct Capabilities {\n pub deep_links: bool,\n pub push: bool,\n pub secure_storage: bool,\n pub updates: bool,\n pub files: bool,\n}\n\nimpl Capabilities {\n /// As the contract's record: `{ host, deepLinks, push, secureStorage, updates, files }`.\n pub fn to_json(self) -> serde_json::Value {\n let s = |b: bool| if b { \"supported\" } else { \"unsupported\" };\n serde_json::json!({\n \"host\": \"desktop-rune\",\n \"deepLinks\": s(self.deep_links),\n \"push\": s(self.push),\n \"secureStorage\": s(self.secure_storage),\n \"updates\": s(self.updates),\n \"files\": s(self.files),\n })\n }\n}\n\n/// Push: no push subscription here (`pushPermission`, `pushSubscribe` and `pushUnsubscribe` all fail so).\npub fn push_permission() -> Result<(), HostError> {\n Err(HostError::Unsupported {\n capability: Capability::Push,\n reason: \"this host holds no push subscription: it shows the app's notifications as OS notifications only while it runs\".into(),\n })\n}\n\n/// File pickers: not implemented by this host.\npub fn open_files() -> Result<(), HostError> {\n Err(HostError::Unsupported { capability: Capability::Files, reason: \"this host has no file pickers yet\".into() })\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn unsupported_capabilities_say_so_by_name() {\n let caps = Capabilities { deep_links: true, push: false, secure_storage: true, updates: false, files: false };\n assert_eq!(caps.to_json()[\"push\"], \"unsupported\");\n assert_eq!(caps.to_json()[\"deepLinks\"], \"supported\");\n assert!(matches!(push_permission(), Err(HostError::Unsupported { capability: Capability::Push, .. })));\n assert!(matches!(open_files(), Err(HostError::Unsupported { capability: Capability::Files, .. })));\n assert!(push_permission().expect_err(\"refused\").to_string().starts_with(\"HostUnsupported: push\"));\n }\n}\n",
120
+ "type": "registry:file",
121
+ "target": "desktop-rune/app/src/host.rs"
122
+ },
123
+ {
124
+ "path": "app/desktop-rune/app/src/keychain.rs",
125
+ "content": "//! Secure storage (the Host contract's `secretGet`, `secretSet`, `secretDelete`): the host's own small secrets in\n//! the OS credential store through the `keyring` crate's native APIs (Keychain Services on macOS, the Credential\n//! Manager on Windows, the Secret Service over D-Bus on Linux): no tool is run, nothing is prompted for, and any\n//! value (empty, multi-line) is kept as it is. Secrets are namespaced by the app's identifier (`app.json`'s\n//! `identifier`), so two apps built from this host never see each other's. Only a secret that is not there reads as\n//! absent; a store that fails (locked, no Secret Service running) is an error, never \"absent\". The person's session\n//! is not here: the daemon keeps it in its own SecretStore.\n\nuse keyring::{Entry, Error};\n\nuse crate::config::valid_app_id;\nuse crate::host::{Capability, HostError};\n\n/// The most a secret may hold (the contract's 16 KiB).\npub const MAX_SECRET_BYTES: usize = 16_384;\n\n/// Secure-storage keys, as the contract allows them: `^[a-z0-9][a-z0-9._-]{0,127}$`.\npub fn valid_key(key: &str) -> bool {\n let mut chars = key.chars();\n matches!(chars.next(), Some(c) if c.is_ascii_lowercase() || c.is_ascii_digit())\n && key.len() <= 128\n && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-'))\n}\n\n/// Where one app's secrets live in the credential store: a service named after the app's identifier.\n#[derive(Debug, Clone, PartialEq, Eq)]\npub struct Namespace {\n service: String,\n}\n\nimpl Namespace {\n pub fn for_app(identifier: &str) -> Result<Namespace, HostError> {\n if !valid_app_id(identifier) {\n return Err(HostError::Failure(format!(\n \"{identifier:?} is not an app identifier (reverse DNS, such as com.example.app)\"\n )));\n }\n // The Tauri host's naming, so a person moving between the two hosts of one app keeps the same namespace.\n Ok(Namespace { service: format!(\"{identifier}.eloxiv-host\") })\n }\n\n pub fn service(&self) -> &str {\n &self.service\n }\n}\n\n/// A credential store: the OS's ([`OsKeychain`]), or a test's. `get` is `None` only for a secret that is not there.\npub trait Keychain: Send + Sync {\n fn get(&self, service: &str, account: &str) -> Result<Option<String>, String>;\n fn set(&self, service: &str, account: &str, value: &str) -> Result<(), String>;\n /// Deleting a secret that is not there succeeds; any other failure is an error.\n fn delete(&self, service: &str, account: &str) -> Result<(), String>;\n}\n\n/// The OS credential store.\npub struct OsKeychain;\n\nfn entry(service: &str, account: &str) -> Result<Entry, String> {\n Entry::new(service, account).map_err(|e| format!(\"the credential store is not available: {e}\"))\n}\n\nimpl Keychain for OsKeychain {\n fn get(&self, service: &str, account: &str) -> Result<Option<String>, String> {\n match entry(service, account)?.get_password() {\n Ok(value) => Ok(Some(value)),\n Err(Error::NoEntry) => Ok(None),\n Err(e) => Err(format!(\"reading {account} failed: {e}\")),\n }\n }\n fn set(&self, service: &str, account: &str, value: &str) -> Result<(), String> {\n entry(service, account)?.set_password(value).map_err(|e| format!(\"storing {account} failed: {e}\"))\n }\n fn delete(&self, service: &str, account: &str) -> Result<(), String> {\n match entry(service, account)?.delete_credential() {\n Ok(()) | Err(Error::NoEntry) => Ok(()),\n Err(e) => Err(format!(\"deleting {account} failed: {e}\")),\n }\n }\n}\n\nfn checked(key: &str) -> Result<&str, HostError> {\n if valid_key(key) { Ok(key) } else { Err(HostError::Failure(format!(\"{key:?} is not a secure-storage key\"))) }\n}\n\n/// The app's secure storage over a credential store. Its operations may block (a locked keychain): call them off\n/// the UI thread.\npub struct SecureStorage {\n store: Box<dyn Keychain>,\n app: Option<Namespace>,\n}\n\nimpl SecureStorage {\n /// The OS store, namespaced by `app_id`. An identifier that is not valid leaves the capability unsupported.\n pub fn os(app_id: &str) -> SecureStorage {\n SecureStorage::over(Box::new(OsKeychain), app_id)\n }\n\n pub fn over(store: Box<dyn Keychain>, app_id: &str) -> SecureStorage {\n SecureStorage { store, app: Namespace::for_app(app_id).ok() }\n }\n\n pub fn supported(&self) -> bool {\n self.app.is_some()\n }\n\n fn app(&self) -> Result<&Namespace, HostError> {\n self.app.as_ref().ok_or_else(|| HostError::Unsupported {\n capability: Capability::SecureStorage,\n reason: \"the app has no valid identifier to namespace its secrets\".into(),\n })\n }\n\n pub fn get(&self, key: &str) -> Result<Option<String>, HostError> {\n let app = self.app()?;\n self.store.get(app.service(), checked(key)?).map_err(HostError::Failure)\n }\n\n pub fn set(&self, key: &str, value: &str) -> Result<(), HostError> {\n let app = self.app()?;\n let key = checked(key)?;\n if value.len() > MAX_SECRET_BYTES {\n return Err(HostError::Failure(\"a secret holds at most 16 KiB\".into()));\n }\n self.store.set(app.service(), key, value).map_err(HostError::Failure)\n }\n\n pub fn delete(&self, key: &str) -> Result<(), HostError> {\n let app = self.app()?;\n self.store.delete(app.service(), checked(key)?).map_err(HostError::Failure)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use std::collections::HashMap;\n use std::sync::{Arc, Mutex};\n\n /// A credential store in memory, keyed as the OS's is (service and account), shared between handles.\n #[derive(Default, Clone)]\n struct Memory(Arc<Mutex<HashMap<(String, String), String>>>);\n impl Keychain for Memory {\n fn get(&self, service: &str, account: &str) -> Result<Option<String>, String> {\n Ok(self.0.lock().expect(\"the lock\").get(&(service.into(), account.into())).cloned())\n }\n fn set(&self, service: &str, account: &str, value: &str) -> Result<(), String> {\n self.0.lock().expect(\"the lock\").insert((service.into(), account.into()), value.into());\n Ok(())\n }\n fn delete(&self, service: &str, account: &str) -> Result<(), String> {\n self.0.lock().expect(\"the lock\").remove(&(service.into(), account.into()));\n Ok(())\n }\n }\n\n /// A credential store that refuses everything (a locked keychain, no Secret Service).\n struct Locked;\n impl Keychain for Locked {\n fn get(&self, _: &str, _: &str) -> Result<Option<String>, String> {\n Err(\"the keychain is locked\".into())\n }\n fn set(&self, _: &str, _: &str, _: &str) -> Result<(), String> {\n Err(\"the keychain is locked\".into())\n }\n fn delete(&self, _: &str, _: &str) -> Result<(), String> {\n Err(\"the keychain is locked\".into())\n }\n }\n\n #[test]\n fn keys_are_the_contracts() {\n for key in [\"session\", \"device.credential\", \"a\", \"0-x_y.z\"] {\n assert!(valid_key(key), \"{key}\");\n }\n for key in [\"\", \"../escape\", \"UPPER\", \"a b\", \"-lead\", &\"x\".repeat(129)] {\n assert!(!valid_key(key), \"{key}\");\n }\n }\n\n #[test]\n fn two_apps_never_see_each_others_secrets() {\n let memory = Memory::default();\n let crm = SecureStorage::over(Box::new(memory.clone()), \"com.acme.crm\");\n let mail = SecureStorage::over(Box::new(memory.clone()), \"com.acme.mail\");\n crm.set(\"session\", \"crm token\").expect(\"as the test set it up\");\n assert_eq!(mail.get(\"session\").expect(\"as the test set it up\"), None);\n mail.set(\"session\", \"mail token\").expect(\"as the test set it up\");\n assert_eq!(crm.get(\"session\").expect(\"as the test set it up\").as_deref(), Some(\"crm token\"));\n mail.delete(\"session\").expect(\"as the test set it up\");\n assert_eq!(crm.get(\"session\").expect(\"as the test set it up\").as_deref(), Some(\"crm token\"));\n assert_eq!(\n Namespace::for_app(\"com.acme.crm\").expect(\"as the test set it up\").service(),\n \"com.acme.crm.eloxiv-host\"\n );\n }\n\n #[test]\n fn absent_is_none_and_a_failing_store_is_an_error_never_absence_or_success() {\n let memory = SecureStorage::over(Box::new(Memory::default()), \"com.acme.crm\");\n assert_eq!(memory.get(\"never-set\").expect(\"as the test set it up\"), None, \"absent\");\n memory.delete(\"never-set\").expect(\"as the test set it up\");\n let locked = SecureStorage::over(Box::new(Locked), \"com.acme.crm\");\n assert!(matches!(locked.get(\"session\"), Err(HostError::Failure(_))));\n assert!(matches!(locked.set(\"session\", \"x\"), Err(HostError::Failure(_))));\n assert!(matches!(locked.delete(\"session\"), Err(HostError::Failure(_))));\n }\n\n #[test]\n fn refuses_malformed_keys_oversized_values_and_an_app_without_an_identifier() {\n let memory = Memory::default();\n let crm = SecureStorage::over(Box::new(memory.clone()), \"com.acme.crm\");\n assert!(crm.get(\"BAD KEY\").expect_err(\"refused\").to_string().contains(\"not a secure-storage key\"));\n assert!(crm.set(\"big\", &\"x\".repeat(MAX_SECRET_BYTES + 1)).is_err());\n crm.set(\"exact\", &\"x\".repeat(MAX_SECRET_BYTES)).expect(\"as the test set it up\");\n let nameless = SecureStorage::over(Box::new(memory), \"app\");\n assert!(!nameless.supported());\n assert!(matches!(\n nameless.get(\"session\"),\n Err(HostError::Unsupported { capability: Capability::SecureStorage, .. })\n ));\n }\n\n /// The real credential store (the Secret Service on this Linux desktop, the Keychain, the Credential Manager):\n /// runs where it answers, skipped elsewhere (a CI runner without a Secret Service), unless\n /// `ELOXIV_REQUIRE_KEYCHAIN=1`.\n #[test]\n fn secrets_round_trip_through_the_os_store_per_app() {\n let probe = SecureStorage::os(\"dev.eloxiv.rune-host-test-probe\");\n if let Err(e) = probe.set(\"probe\", \"probe\") {\n assert!(std::env::var(\"ELOXIV_REQUIRE_KEYCHAIN\").as_deref() != Ok(\"1\"), \"no credential store: {e}\");\n eprintln!(\"no credential store here ({e}); skipped\");\n return;\n }\n probe.delete(\"probe\").expect(\"as the test set it up\");\n let (one, two) =\n (SecureStorage::os(\"dev.eloxiv.rune-host-test-one\"), SecureStorage::os(\"dev.eloxiv.rune-host-test-two\"));\n assert_eq!(one.get(\"value\").expect(\"as the test set it up\"), None, \"absent before\");\n for value in [\"a value ✓ مرحبا\", \"\", \"line one\\nline two\\n\"] {\n one.set(\"value\", value).expect(\"as the test set it up\");\n assert_eq!(one.get(\"value\").expect(\"as the test set it up\").as_deref(), Some(value), \"{value:?}\");\n }\n assert_eq!(two.get(\"value\").expect(\"as the test set it up\"), None);\n two.set(\"value\", \"two's\").expect(\"as the test set it up\");\n assert_eq!(one.get(\"value\").expect(\"as the test set it up\").as_deref(), Some(\"line one\\nline two\\n\"));\n one.delete(\"value\").expect(\"as the test set it up\");\n assert_eq!(one.get(\"value\").expect(\"as the test set it up\"), None, \"absent after delete\");\n one.delete(\"value\").expect(\"as the test set it up\");\n assert_eq!(two.get(\"value\").expect(\"as the test set it up\").as_deref(), Some(\"two's\"));\n two.delete(\"value\").expect(\"as the test set it up\");\n }\n}\n",
126
+ "type": "registry:file",
127
+ "target": "desktop-rune/app/src/keychain.rs"
128
+ },
129
+ {
130
+ "path": "app/desktop-rune/app/src/launch.rs",
131
+ "content": "//! The launch probe: one stdout line, once per process, when the window has first drawn a screen the person can\n//! use, for the launch-to-interactive budget (`scripts/measure-launch.ts`, decision 7's \"Desktop launch to\n//! interactive ≤ 1.5 s\"). Off unless the executable turns it on ([`enable`], from `main`), so the headless tests\n//! print nothing.\n//!\n//! Interactive is the Tauri host's probe (\"first content after the next frame\") made exact for a native window: the\n//! first frame that draws the screen the daemon's session calls for, with what that screen needs from the daemon:\n//!\n//! - the daemon answered `/health` and `hello` and the event stream is open;\n//! - signed out (or signing in): its session event arrived, so the sign-in screen and its button are drawn;\n//! - signed in: the session of the current generation arrived and, with an organisation selected, the live list's\n//! first snapshot too (an organisation not yet chosen: the picker is the screen).\n//!\n//! Rune calls `poll` at the start of a frame, before the view is built and drawn. The poll in which the state\n//! first qualifies marks it and asks for one more frame; the next poll, at the start of the frame after the one that\n//! drew the screen (so that frame was rendered and handed to the compositor), prints\n//!\n//! ```text\n//! ELOXIV_DESKTOP_INTERACTIVE ms=<since main> source=frame screen=<signed-out|signed-in> clock=main\n//! ```\n//!\n//! The budget itself is the harness's clock (spawn to this line), which also counts the time before `main`.\n\nuse std::sync::atomic::{AtomicU8, Ordering};\nuse std::sync::{Mutex, OnceLock};\nuse std::time::Instant;\n\nuse crate::model::{Model, Session};\nuse crate::ui::{Startup, Ui};\n\nconst OFF: u8 = 0;\nconst WAITING: u8 = 1;\nconst DRAWN: u8 = 2;\nconst REPORTED: u8 = 3;\n\nstatic PHASE: AtomicU8 = AtomicU8::new(OFF);\nstatic STARTED: OnceLock<Instant> = OnceLock::new();\nstatic SCREEN: OnceLock<&'static str> = OnceLock::new();\nstatic WAKER: Mutex<Option<rune::Waker>> = Mutex::new(None);\n\n/// Turns the probe on and starts its clock: call first thing in `main`.\npub fn enable() {\n let _ = STARTED.set(Instant::now());\n let _ = PHASE.compare_exchange(OFF, WAITING, Ordering::SeqCst, Ordering::SeqCst);\n}\n\n/// Rune's waker (`AppSpec::setup`), to ask for the frame after the one that drew the screen.\npub fn set_waker(waker: rune::Waker) {\n if let Ok(mut slot) = WAKER.lock() {\n *slot = Some(waker);\n }\n}\n\n/// The screen the person can use now, if any (pure).\npub fn screen(startup: &Startup, stream_open: bool, model: &Model) -> Option<&'static str> {\n if *startup != Startup::Ready || !stream_open {\n return None;\n }\n match &model.session {\n Session::SignedOut | Session::SigningIn => Some(\"signed-out\"),\n Session::SignedIn { org_id, .. } if model.usable() && (org_id.is_none() || model.list.status.is_some()) => {\n Some(\"signed-in\")\n }\n _ => None,\n }\n}\n\n/// Called from `poll` after the replies landed, every frame.\npub fn frame(ui: &Ui) {\n match PHASE.load(Ordering::SeqCst) {\n WAITING => {\n if let Some(screen) = screen(&ui.startup, ui.stream_open, &ui.model) {\n let _ = SCREEN.set(screen);\n PHASE.store(DRAWN, Ordering::SeqCst);\n // This frame draws it; the next one's poll reports it.\n let waker = WAKER.lock().ok().and_then(|w| w.clone());\n if let Some(wake) = waker {\n wake();\n }\n }\n }\n DRAWN => {\n PHASE.store(REPORTED, Ordering::SeqCst);\n let ms = STARTED.get().map_or(0, |s| s.elapsed().as_millis());\n let screen = SCREEN.get().copied().unwrap_or(\"unknown\");\n println!(\"ELOXIV_DESKTOP_INTERACTIVE ms={ms} source=frame screen={screen} clock=main\");\n }\n _ => {}\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use eloxiv_local_client::{RowsStatus, User};\n\n #[test]\n fn interactive_is_the_screen_the_session_calls_for_with_what_it_needs() {\n let mut model = Model::default();\n assert_eq!(screen(&Startup::Starting, false, &model), None, \"the daemon is starting\");\n assert_eq!(screen(&Startup::Ready, false, &model), None, \"no event stream yet\");\n assert_eq!(screen(&Startup::Ready, true, &model), None, \"no session yet (Connecting…)\");\n assert_eq!(screen(&Startup::Failed(\"x\".into()), true, &model), None);\n\n model.session = Session::SignedOut;\n assert_eq!(screen(&Startup::Ready, true, &model), Some(\"signed-out\"));\n model.session = Session::SigningOut;\n assert_eq!(screen(&Startup::Ready, true, &model), None);\n\n let user = User { id: \"u1\".into(), email: \"a@example.com\".into(), name: \"A\".into() };\n model.session = Session::SignedIn { user, organizations: Vec::new(), org_id: Some(\"acme\".into()) };\n model.generation = 2;\n model.session_generation = Some(1);\n assert_eq!(screen(&Startup::Ready, true, &model), None, \"the session of an older generation\");\n model.session_generation = Some(2);\n assert_eq!(screen(&Startup::Ready, true, &model), None, \"the list's first snapshot has not arrived\");\n model.list.status = Some(RowsStatus::Complete);\n assert_eq!(screen(&Startup::Ready, true, &model), Some(\"signed-in\"));\n if let Session::SignedIn { org_id, .. } = &mut model.session {\n *org_id = None;\n }\n model.list.status = None;\n assert_eq!(screen(&Startup::Ready, true, &model), Some(\"signed-in\"), \"the organisation picker\");\n }\n}\n",
132
+ "type": "registry:file",
133
+ "target": "desktop-rune/app/src/launch.rs"
134
+ },
135
+ {
136
+ "path": "app/desktop-rune/app/src/lib.rs",
137
+ "content": "//! The Eloxiv desktop host on Rune: a native window over the app's daemon (LocalClient v1, `/client/v1`).\n//!\n//! The daemon owns the session, the replica, the named queries and the optimistic writes (one client core,\n//! decision 14); this host draws what its events say and asks it for what the person does. Networking runs on\n//! worker threads ([`backend`]) and lands on the UI thread through Rune's `poll`.\n\npub mod backend;\npub mod chat;\npub mod config;\npub mod host;\npub mod keychain;\npub mod launch;\npub mod links;\npub mod make;\npub mod model;\npub mod notices;\npub mod outstanding;\npub mod routing;\npub mod services;\npub mod sidecar;\npub mod ui;\npub mod updates;\npub mod view;\n\nuse std::path::PathBuf;\nuse std::time::Duration;\n\nuse eloxiv_local_client::LocalClient;\nuse rune::{App, AppSpec};\n\npub use ui::{Launch, Ui};\n\n/// A random id (16 hex digits) for a write or a MAKE mount.\npub fn random_id() -> String {\n let mut raw = [0u8; 8];\n if getrandom::fill(&mut raw).is_err() {\n // Only uniqueness within this process matters here.\n let n = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());\n raw = (n as u64).to_le_bytes();\n }\n raw.iter().map(|b| format!(\"{b:02x}\")).collect()\n}\n\n/// A random UUID (v4), for a MAKE call that names no key of its own.\npub fn random_uuid() -> String {\n let mut b = [0u8; 16];\n let _ = getrandom::fill(&mut b);\n b[6] = (b[6] & 0x0f) | 0x40;\n b[8] = (b[8] & 0x3f) | 0x80;\n let h: String = b.iter().map(|x| format!(\"{x:02x}\")).collect();\n format!(\"{}-{}-{}-{}-{}\", &h[0..8], &h[8..12], &h[12..16], &h[16..20], &h[20..32])\n}\n\nfn poll(s: &mut Ui, _t: f64, tx: &mut rune::Tx) -> bool {\n let changed = s.drain(tx);\n launch::frame(s);\n changed\n}\n\nfn setup(s: &mut Ui, waker: rune::Waker) {\n launch::set_waker(waker.clone());\n s.host.set_wake(waker.clone());\n s.backend.set_wake(waker);\n}\n\n/// The app over the daemon at `url` with the local token `token` (the host secret), its outstanding sends kept in\n/// the host's data directory ([`outstanding::default_data_dir`]).\npub fn app(url: String, token: String) -> App<Ui> {\n app_in(url, token, outstanding::default_data_dir())\n}\n\n/// The app with its data directory `data_dir` (None: the outstanding sends are kept in memory only).\npub fn app_in(url: String, token: String, data_dir: Option<PathBuf>) -> App<Ui> {\n app_with(url, token, data_dir, services::HostServices::default)\n}\n\n/// The app with the host's services `host` makes (configuration, deep links, updates, secure storage).\npub fn app_with(\n url: String,\n token: String,\n data_dir: Option<PathBuf>,\n host: impl FnOnce() -> services::HostServices + 'static,\n) -> App<Ui> {\n let spec = AppSpec {\n poll: Some(poll),\n setup: Some(setup),\n ..AppSpec::new(\n config::current().name.as_str(),\n (900.0, 660.0),\n || unreachable!(\"App::init gives the state\"),\n view::view,\n )\n };\n let app = App::new(spec);\n // For a notification's click: the window comes forward.\n let handle = app.handle();\n app.init(move || {\n let mut ui = Ui::new(Launch {\n client: LocalClient::new(url.clone(), token.clone()),\n timeout: Duration::from_secs(30),\n data_dir: data_dir.clone(),\n })\n .with_services(host());\n ui.app = Some(handle.clone());\n ui\n })\n .on_open_url(routing::on_open_url)\n}\n",
138
+ "type": "registry:file",
139
+ "target": "desktop-rune/app/src/lib.rs"
140
+ },
141
+ {
142
+ "path": "app/desktop-rune/app/src/links.rs",
143
+ "content": "//! Deep links (the Host contract's `deepLinks`): the app's own `<scheme>://open/<path>` links, read with the View\n//! contract's `parseLink` and routed to the screen that shows them.\n//!\n//! - **One process**: `main` claims the app's single instance (Rune's `single_instance`, named by the app id) before\n//! it starts the sidecar. A later launch hands its arguments to the running process (Linux: a Unix socket in\n//! `$XDG_RUNTIME_DIR`; Windows: a named pipe per user and session) and exits; macOS keeps one process itself and\n//! sends links as Apple events. Rune gives each link, the launching one included, to `App::on_open_url`.\n//! - **Reading a link**: [`ViewTable::parse_link`] is `shellRegistry(…).parseLink` (`@eloxiv/shell-core`) in Rust,\n//! over the app's views (their ids and routes, from the sidecar: `eloxiv-daemon --print-views`) and the host's own\n//! screens that are not manifest views (the agent's conversation at `/agent/conversation`, a MAKE module's view\n//! at `/make/<module>`, as the web shell routes them). It accepts a shell path or a link in the app's scheme\n//! whose host is `open`, and refuses everything else (`InvalidLink` with the contract's reasons): another scheme,\n//! any `http(s)` URL (this host has no web origin), another host, a path no view serves. A link only navigates.\n//! - **Registering the scheme** with the OS: [`register`] at launch, off the UI thread, when `app.json` allows it and no\n//! installer registered it ([`registers_itself`]; Linux: a desktop entry in `$XDG_DATA_HOME/applications` with `MimeType=x-scheme-handler/<scheme>`, made the\n//! default handler with `xdg-mime`; Windows: `HKCU\\Software\\Classes\\<scheme>`). macOS registers what the bundle's\n//! `Info.plist` declares ([`macos_url_types`], written by packaging); nothing is done at run time there.\n\nuse std::collections::{BTreeMap, HashMap};\nuse std::path::{Path, PathBuf};\n\nuse serde::{Deserialize, Serialize};\nuse url::Url;\n\nuse crate::config::HostConfig;\n\n/// The host part of a custom-scheme deep link: `<scheme>://open/<path>`.\npub const SCHEME_HOST: &str = \"open\";\n\n/// A view: its id (`hello.greetings`), route (`/hello`) and title, and, for a view that shows an entity's records,\n/// its module and that entity (`shows: { entity }`), which notification clicks open records in (`recordLink`).\n#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]\npub struct ViewEntry {\n pub id: String,\n pub route: String,\n #[serde(default)]\n pub title: String,\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n pub module: Option<String>,\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n pub entity: Option<String>,\n}\n\n/// The host's own screens that are not manifest views, at the web shell's routes.\npub const CHAT_VIEW: &str = \"agent.conversation\";\n/// The conversation link's parameters naming the request whose card to show (`?consent=<id>`, `?approval=<id>`).\npub const CONSENT_PARAM: &str = \"consent\";\npub const APPROVAL_PARAM: &str = \"approval\";\npub const MAKE_VIEW: &str = \"make\";\npub fn host_screens() -> Vec<ViewEntry> {\n vec![\n ViewEntry {\n id: CHAT_VIEW.into(),\n route: \"/agent/conversation\".into(),\n title: \"Agent\".into(),\n ..ViewEntry::default()\n },\n ViewEntry { id: MAKE_VIEW.into(), route: \"/make\".into(), title: \"MAKE view\".into(), ..ViewEntry::default() },\n ]\n}\n\n/// `DeepLink`: a view, and optionally a record, an organisation and plain string parameters.\n#[derive(Clone, Debug, Default, PartialEq, Eq)]\npub struct DeepLink {\n pub view: String,\n pub record: Option<String>,\n pub org: Option<String>,\n pub params: BTreeMap<String, String>,\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum Reason {\n ForeignOrigin,\n Scheme,\n Malformed,\n UnknownView,\n}\n\nimpl Reason {\n pub fn name(self) -> &'static str {\n match self {\n Reason::ForeignOrigin => \"foreign-origin\",\n Reason::Scheme => \"scheme\",\n Reason::Malformed => \"malformed\",\n Reason::UnknownView => \"unknown-view\",\n }\n }\n}\n\n/// `InvalidLink { url, reason }`.\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct InvalidLink {\n pub reason: Reason,\n pub message: String,\n}\n\nimpl std::fmt::Display for InvalidLink {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n write!(f, \"InvalidLink ({}): {}\", self.reason.name(), self.message)\n }\n}\n\n/// The views a link may name, by id and by route.\n#[derive(Clone, Debug, Default)]\npub struct ViewTable {\n views: Vec<ViewEntry>,\n by_route: HashMap<String, usize>,\n}\n\nfn normalise(path: &str) -> String {\n if path.len() > 1 && path.ends_with('/') { path[..path.len() - 1].to_owned() } else { path.to_owned() }\n}\n\n/// `decodeURIComponent`: `%XX` sequences decoded, none when one is malformed or the bytes are not UTF-8.\npub fn decode_component(s: &str) -> Option<String> {\n let bytes = s.as_bytes();\n let mut out = Vec::with_capacity(bytes.len());\n let mut i = 0;\n while i < bytes.len() {\n if bytes[i] == b'%' {\n let hex = s.get(i + 1..i + 3)?;\n out.push(u8::from_str_radix(hex, 16).ok().filter(|_| hex.bytes().all(|b| b.is_ascii_hexdigit()))?);\n i += 3;\n } else {\n out.push(bytes[i]);\n i += 1;\n }\n }\n String::from_utf8(out).ok()\n}\n\n/// `encodeURIComponent`: everything but `A-Z a-z 0-9 - _ . ! ~ * ' ( )` percent-encoded, as UTF-8.\npub fn encode_component(s: &str) -> String {\n let mut out = String::with_capacity(s.len());\n for b in s.bytes() {\n if b.is_ascii_alphanumeric() || b\"-_.!~*'()\".contains(&b) {\n out.push(b as char);\n } else {\n out.push_str(&format!(\"%{b:02X}\"));\n }\n }\n out\n}\n\n/// `?org=…&k=v`: `org` apart, the first of a repeated key wins, `+` is a space, undecodable pairs are skipped.\nfn parse_query(search: &str) -> (Option<String>, BTreeMap<String, String>) {\n let (mut org, mut params) = (None, BTreeMap::new());\n for pair in search.strip_prefix('?').unwrap_or(search).split('&') {\n if pair.is_empty() {\n continue;\n }\n let (k, v) = pair.split_once('=').unwrap_or((pair, \"\"));\n let (Some(k), Some(v)) = (decode_component(&k.replace('+', \" \")), decode_component(&v.replace('+', \" \")))\n else {\n continue;\n };\n if k == \"org\" {\n org.get_or_insert(v);\n } else {\n params.entry(k).or_insert(v);\n }\n }\n (org, params)\n}\n\nimpl ViewTable {\n /// The table of `views`; the host's own screens are added where no view has their id or route. A duplicate id\n /// or route among `views` is refused, as `shellRegistry` refuses it.\n pub fn new(views: Vec<ViewEntry>) -> Result<ViewTable, String> {\n let mut table = ViewTable::default();\n for v in views {\n table.add(v)?;\n }\n for v in host_screens() {\n if !table.views.iter().any(|w| w.id == v.id) && !table.by_route.contains_key(&normalise(&v.route)) {\n table.add(v)?;\n }\n }\n Ok(table)\n }\n\n fn add(&mut self, mut v: ViewEntry) -> Result<(), String> {\n v.route = normalise(&v.route);\n if self.views.iter().any(|w| w.id == v.id) {\n return Err(format!(\"View {} is declared twice\", v.id));\n }\n if let Some(&i) = self.by_route.get(&v.route) {\n return Err(format!(\"Views {} and {} share the route {}\", self.views[i].id, v.id, v.route));\n }\n self.by_route.insert(v.route.clone(), self.views.len());\n self.views.push(v);\n Ok(())\n }\n\n pub fn views(&self) -> &[ViewEntry] {\n &self.views\n }\n\n pub fn view(&self, id: &str) -> Option<&ViewEntry> {\n self.views.iter().find(|v| v.id == id)\n }\n\n /// `resolve`: the view a shell path opens (the route equal to the path, or followed by one more segment, the\n /// record), with `org` and the other query parameters; none otherwise.\n pub fn resolve(&self, path: &str) -> Option<DeepLink> {\n let at = path.find(['?', '#']);\n let pathname = normalise(at.map_or(path, |i| &path[..i]));\n let search = at.map_or(\"\", |i| &path[i..]);\n let search = search.find('#').map_or(search, |h| &search[..h]);\n if !pathname.starts_with('/') || pathname.starts_with(\"//\") {\n return None;\n }\n let (org, params) = parse_query(search);\n if let Some(&i) = self.by_route.get(&pathname) {\n return Some(DeepLink { view: self.views[i].id.clone(), record: None, org, params });\n }\n let cut = pathname.rfind('/')?;\n let parent = if cut == 0 { \"/\" } else { &pathname[..cut] };\n let &i = self.by_route.get(parent)?;\n let record = decode_component(&pathname[cut + 1..]).filter(|r| !r.is_empty())?;\n Some(DeepLink { view: self.views[i].id.clone(), record: Some(record), org, params })\n }\n\n /// `link`'s path: `<route>[/<record>][?org=<org>&<params sorted>]`. A record whose segment would spell another\n /// view's route has its first character percent-encoded, so it still names the record; `.` and `..` cannot be\n /// linked (URLs resolve them away). None for an unknown view.\n pub fn link_path(&self, target: &DeepLink) -> Option<String> {\n let view = self.view(&target.view)?;\n let base = if view.route == \"/\" && target.record.is_some() { \"\" } else { view.route.as_str() };\n let mut segment = String::new();\n if let Some(record) = &target.record {\n if record.is_empty() || record == \".\" || record == \"..\" {\n return None;\n }\n segment = format!(\"/{}\", encode_component(record));\n if self.by_route.contains_key(&format!(\"{base}{segment}\")) {\n let first = record.chars().next().map(|c| c.len_utf8()).unwrap_or(0);\n let head: String = record[..first].bytes().map(|b| format!(\"%{b:02X}\")).collect();\n segment = format!(\"/{head}{}\", encode_component(&record[first..]));\n }\n }\n let mut pairs: Vec<(String, String)> = Vec::new();\n if let Some(org) = &target.org {\n pairs.push((\"org\".into(), org.clone()));\n }\n pairs.extend(target.params.iter().filter(|(k, _)| *k != \"org\").map(|(k, v)| (k.clone(), v.clone())));\n let query = if pairs.is_empty() {\n String::new()\n } else {\n let joined: Vec<String> =\n pairs.iter().map(|(k, v)| format!(\"{}={}\", encode_component(k), encode_component(v))).collect();\n format!(\"?{}\", joined.join(\"&\"))\n };\n Some(format!(\"{base}{segment}{query}\"))\n }\n\n /// `link`'s URL in the app's `scheme`: `<scheme>://open<path>`.\n pub fn link(&self, target: &DeepLink, scheme: &str) -> Option<String> {\n Some(format!(\"{scheme}://{SCHEME_HOST}{}\", self.link_path(target)?))\n }\n\n /// `recordLink`: the link that opens record `id` of `module`'s `entity` in the first view that shows that entity\n /// (the order the sidecar listed them in), in organisation `org`; None when no view shows it.\n pub fn record_link(&self, module: &str, entity: &str, id: &str, org: Option<&str>, scheme: &str) -> Option<String> {\n let view =\n self.views.iter().find(|v| v.module.as_deref() == Some(module) && v.entity.as_deref() == Some(entity))?;\n let target = DeepLink {\n view: view.id.clone(),\n record: Some(id.to_owned()),\n org: org.map(str::to_owned),\n params: BTreeMap::new(),\n };\n self.link(&target, scheme)\n }\n\n /// `parseLink`: a shell path, a URL on `origin` (none for this host), or a link in `scheme` whose host is `open`.\n pub fn parse_link(&self, url: &str, scheme: &str, origin: Option<&str>) -> Result<DeepLink, InvalidLink> {\n let refuse = |reason, message: String| InvalidLink { reason, message };\n let path = if url.starts_with('/') && !url.starts_with(\"//\") {\n url.to_owned()\n } else {\n let parsed = Url::parse(url)\n .map_err(|_| refuse(Reason::Malformed, format!(\"{url} is not a URL or a shell path\")))?;\n let protocol = parsed.scheme();\n if protocol == \"https\" || protocol == \"http\" {\n let ours = origin.and_then(|o| Url::parse(o).ok()).map(|o| o.origin());\n if ours.is_none_or(|o| o != parsed.origin()) {\n return Err(refuse(\n Reason::ForeignOrigin,\n format!(\"{} is not this app's origin\", parsed.origin().ascii_serialization()),\n ));\n }\n } else if protocol != scheme.to_ascii_lowercase() {\n return Err(refuse(Reason::Scheme, format!(\"{protocol}: links do not open this app\")));\n } else if parsed.host_str() != Some(SCHEME_HOST) || parsed.port().is_some() {\n return Err(refuse(\n Reason::Malformed,\n format!(\"{scheme} links have the form {scheme}://{SCHEME_HOST}/<path>\"),\n ));\n }\n let pathname = if parsed.path().is_empty() { \"/\" } else { parsed.path() };\n match parsed.query() {\n Some(q) if !q.is_empty() => format!(\"{pathname}?{q}\"),\n _ => pathname.to_owned(),\n }\n };\n self.resolve(&path).ok_or_else(|| refuse(Reason::UnknownView, format!(\"No view is at {path}\")))\n }\n}\n\n/// Where a link takes the host.\n#[derive(Clone, Debug, PartialEq, Eq)]\npub enum Route {\n Greetings,\n Chat,\n /// A MAKE module's view (`None`: the screen, no module named).\n Make(Option<String>),\n /// A view of the app this host has no screen for (its title).\n Unavailable(String),\n}\n\n/// The host's screen for `link` (hello's greetings, the agent's conversation, a MAKE view), or none.\npub fn route(table: &ViewTable, link: &DeepLink) -> Route {\n match link.view.as_str() {\n crate::model::GREETINGS_QUERY => Route::Greetings,\n CHAT_VIEW => Route::Chat,\n MAKE_VIEW => Route::Make(link.record.clone()),\n other => Route::Unavailable(\n table\n .view(other)\n .map_or(other.to_owned(), |v| if v.title.is_empty() { v.id.clone() } else { v.title.clone() }),\n ),\n }\n}\n\n/// The app's views from its sidecar: `ELOXIV_RUNE_VIEWS` (a JSON file), else `<sidecar> --print-views`.\npub fn load_views(launch: Option<&crate::sidecar::Launch>) -> Result<Vec<ViewEntry>, String> {\n if let Some(file) = std::env::var_os(\"ELOXIV_RUNE_VIEWS\") {\n let text = std::fs::read_to_string(&file).map_err(|e| format!(\"{}: {e}\", Path::new(&file).display()))?;\n return serde_json::from_str(&text).map_err(|e| format!(\"ELOXIV_RUNE_VIEWS: {e}\"));\n }\n let launch = launch.ok_or(\"no sidecar to ask for the app's views\")?;\n let output = std::process::Command::new(&launch.program)\n .args(&launch.args)\n .arg(\"--print-views\")\n .stdin(std::process::Stdio::null())\n .stderr(std::process::Stdio::null())\n .output()\n .map_err(|e| format!(\"{}: {e}\", launch.program.display()))?;\n if !output.status.success() {\n return Err(format!(\"{} --print-views exited with {}\", launch.program.display(), output.status));\n }\n serde_json::from_slice(&output.stdout).map_err(|e| format!(\"the sidecar's views do not decode: {e}\"))\n}\n\n// Registering the scheme with the OS.\n\n/// A desktop entry's `Exec` argument, escaped at both levels the Desktop Entry Specification asks: quoted, with `\"`,\n/// `` ` ``, `$` and `\\` backslash-escaped (the Exec key's quoting) and `%` doubled (field codes); then, the value\n/// being a string, every backslash escaped again and control characters written as `\\n`, `\\t`, `\\r` (the key-file\n/// level, which a reader undoes first). So `$` is written `\\\\$` and `\\` is written `\\\\\\\\`.\npub fn exec_quote(arg: &str) -> String {\n let mut quoted = String::from(\"\\\"\");\n for c in arg.chars() {\n match c {\n '\"' | '`' | '$' | '\\\\' => {\n quoted.push('\\\\');\n quoted.push(c);\n }\n '%' => quoted.push_str(\"%%\"),\n c => quoted.push(c),\n }\n }\n quoted.push('\"');\n let mut out = String::with_capacity(quoted.len());\n for c in quoted.chars() {\n match c {\n '\\\\' => out.push_str(\"\\\\\\\\\"),\n '\\n' => out.push_str(\"\\\\n\"),\n '\\t' => out.push_str(\"\\\\t\"),\n '\\r' => out.push_str(\"\\\\r\"),\n c => out.push(c),\n }\n }\n out\n}\n\n/// The desktop entry that makes `exec` the handler of the app's scheme (Linux). Hidden from menus: the app's menu\n/// entry is packaging's.\npub fn desktop_entry(config: &HostConfig, exec: &Path) -> String {\n let name = config.name.replace(['\\n', '\\r'], \" \");\n format!(\n \"[Desktop Entry]\\nType=Application\\nName={name}\\nExec={} %u\\nTerminal=false\\nNoDisplay=true\\nMimeType=x-scheme-handler/{};\\nX-Eloxiv-App={}\\n\",\n exec_quote(&exec.to_string_lossy()),\n config.scheme,\n config.app_id,\n )\n}\n\n/// The desktop entry's file name: `<app id>.desktop`.\npub fn desktop_file_name(config: &HostConfig) -> String {\n format!(\"{}.desktop\", config.app_id)\n}\n\n/// One registry value (Windows): under `HKEY_CURRENT_USER\\<key>`, `name` (None: the key's default value).\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct RegValue {\n pub key: String,\n pub name: Option<String>,\n pub value: String,\n}\n\n/// What registers the app's scheme for the person (Windows, `HKCU\\Software\\Classes\\<scheme>`), opening `exe` with\n/// the link as its argument.\npub fn windows_entries(config: &HostConfig, exe: &Path) -> Vec<RegValue> {\n let base = format!(r\"Software\\Classes\\{}\", config.scheme);\n let exe = exe.to_string_lossy();\n let v = |key: String, name: Option<&str>, value: String| RegValue { key, name: name.map(str::to_owned), value };\n vec![\n v(base.clone(), None, format!(\"URL:{} link\", config.name)),\n v(base.clone(), Some(\"URL Protocol\"), String::new()),\n v(format!(r\"{base}\\DefaultIcon\"), None, format!(\"\\\"{exe}\\\",0\")),\n // `--open-url` before the link: a launch is a link launch only as `<exe> --open-url <link>`, exactly\n // ([`launch_link`]); a link that closes the quote to add arguments makes the launch refused.\n v(format!(r\"{base}\\shell\\open\\command\"), None, format!(\"\\\"{exe}\\\" --open-url \\\"%1\\\"\")),\n ]\n}\n\n/// The `Info.plist` entry that declares the app's scheme (macOS), for packaging to put in the bundle.\npub fn macos_url_types(config: &HostConfig) -> String {\n let esc = |s: &str| s.replace('&', \"&amp;\").replace('<', \"&lt;\").replace('>', \"&gt;\");\n format!(\n \"<key>CFBundleURLTypes</key>\\n<array>\\n <dict>\\n <key>CFBundleURLName</key>\\n <string>{}</string>\\n <key>CFBundleURLSchemes</key>\\n <array>\\n <string>{}</string>\\n </array>\\n </dict>\\n</array>\\n\",\n esc(&config.app_id),\n esc(&config.scheme)\n )\n}\n\n/// A launch's own arguments (the program's name not included): a link launch is exactly `[<link>]` (Linux's\n/// desktop entry, macOS) or `[\"--open-url\", <link>]` (Windows' registry command). Ok(Some(link)) for one, Ok(None)\n/// for a launch without a link; a launch that carries a link (or `--open-url`) with anything else is refused, so a\n/// crafted link can never add arguments.\npub fn launch_link(args: &[String]) -> Result<Option<String>, String> {\n let is_link = |a: &str| a.split_once(\"://\").is_some_and(|(scheme, _)| valid_link_scheme(scheme));\n match args {\n [] => Ok(None),\n [link] if is_link(link) => Ok(Some(link.clone())),\n [flag, link] if flag == \"--open-url\" && is_link(link) => Ok(Some(link.clone())),\n _ if args.iter().any(|a| a == \"--open-url\" || is_link(a)) => {\n Err(format!(\"a link launch with other arguments ({} in all) is refused\", args.len()))\n }\n _ => Ok(None),\n }\n}\n\n/// What Rune may read as its own flags (`App::args`): nothing in a release build or a link launch; a development\n/// build's arguments otherwise (Rune's tooling: `--snap`, `--trace`, ...).\npub fn rune_args(args: &[String], development: bool) -> Vec<String> {\n let link_launch = !matches!(launch_link(args), Ok(None));\n if development && !link_launch { args.to_vec() } else { Vec::new() }\n}\n\nfn valid_link_scheme(scheme: &str) -> bool {\n scheme.len() >= 2\n && scheme.starts_with(|c: char| c.is_ascii_alphabetic())\n && scheme.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))\n}\n\n/// What [`register`] did.\n#[derive(Clone, Debug, PartialEq, Eq)]\npub enum Registered {\n /// Written now (the path or key).\n Written(String),\n /// Already registered as it would be.\n Unchanged(String),\n /// Not done: what does it instead, or why not.\n Skipped(String),\n}\n\n/// The executable a link should start: the AppImage when running from one (its mount point changes each run).\npub fn launcher() -> Option<PathBuf> {\n std::env::var_os(\"APPIMAGE\").map(PathBuf::from).or_else(|| std::env::current_exe().ok())\n}\n\n/// Whether this launch registers the scheme itself: not when its installer did. The `.deb`, the NSIS installer\n/// and the macOS bundle register it (packaging's `deepLinkProtocols`; the installer's uninstaller removes it), so a\n/// packaged install (`packaged`: its sidecar installed beside it) leaves it to them, except an AppImage\n/// (`appimage`), which no installer registers. A development build registers it.\npub fn registers_itself(packaged: bool, appimage: bool) -> bool {\n !packaged || appimage\n}\n\n/// Registers the app's scheme with the OS for this person (call it off the UI thread), unless `app.json` turns\n/// it off or the installer registered it ([`registers_itself`]).\npub fn register(config: &HostConfig, packaged: bool) -> Result<Registered, String> {\n if !config.register_scheme {\n return Ok(Registered::Skipped(\"app.json's deepLinks.register is false\".into()));\n }\n if !registers_itself(packaged, std::env::var_os(\"APPIMAGE\").is_some()) {\n return Ok(Registered::Skipped(\"the installer registered the scheme\".into()));\n }\n let exe = launcher().ok_or(\"this executable's path is unknown\")?;\n register_for(config, &exe)\n}\n\n#[cfg(target_os = \"linux\")]\nfn register_for(config: &HostConfig, exe: &Path) -> Result<Registered, String> {\n let data = std::env::var_os(\"XDG_DATA_HOME\")\n .map(PathBuf::from)\n .filter(|p| p.is_absolute())\n .or_else(|| std::env::var_os(\"HOME\").map(|h| PathBuf::from(h).join(\".local\").join(\"share\")))\n .ok_or(\"neither XDG_DATA_HOME nor HOME is set\")?;\n register_linux(config, exe, &data.join(\"applications\"), true)\n}\n\n/// Writes the desktop entry into `applications` (when it differs) and, with `run_tools`, makes it the scheme's\n/// default handler (`xdg-mime default`) and refreshes the MIME cache (`update-desktop-database`, when present).\n#[cfg(target_os = \"linux\")]\npub fn register_linux(\n config: &HostConfig,\n exe: &Path,\n applications: &Path,\n run_tools: bool,\n) -> Result<Registered, String> {\n let file = applications.join(desktop_file_name(config));\n let entry = desktop_entry(config, exe);\n let unchanged = std::fs::read_to_string(&file).is_ok_and(|t| t == entry);\n if !unchanged {\n std::fs::create_dir_all(applications).map_err(|e| format!(\"{}: {e}\", applications.display()))?;\n std::fs::write(&file, &entry).map_err(|e| format!(\"{}: {e}\", file.display()))?;\n }\n if run_tools {\n let handler = format!(\"x-scheme-handler/{}\", config.scheme);\n let current = std::process::Command::new(\"xdg-mime\")\n .args([\"query\", \"default\", &handler])\n .output()\n .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned())\n .unwrap_or_default();\n if !unchanged || current != desktop_file_name(config) {\n let _ = std::process::Command::new(\"update-desktop-database\").arg(applications).output();\n let status = std::process::Command::new(\"xdg-mime\")\n .args([\"default\", &desktop_file_name(config), &handler])\n .status()\n .map_err(|e| format!(\"xdg-mime: {e}\"))?;\n if !status.success() {\n return Err(format!(\"xdg-mime default exited with {status}\"));\n }\n return Ok(Registered::Written(file.display().to_string()));\n }\n }\n Ok(if unchanged {\n Registered::Unchanged(file.display().to_string())\n } else {\n Registered::Written(file.display().to_string())\n })\n}\n\n#[cfg(target_os = \"windows\")]\nfn register_for(config: &HostConfig, exe: &Path) -> Result<Registered, String> {\n use winreg::RegKey;\n use winreg::enums::HKEY_CURRENT_USER;\n let hkcu = RegKey::predef(HKEY_CURRENT_USER);\n let entries = windows_entries(config, exe);\n let unchanged = entries.iter().all(|e| {\n hkcu.open_subkey(&e.key)\n .and_then(|k| k.get_value::<String, _>(e.name.as_deref().unwrap_or(\"\")))\n .is_ok_and(|v| v == e.value)\n });\n let key = format!(r\"HKCU\\Software\\Classes\\{}\", config.scheme);\n if unchanged {\n return Ok(Registered::Unchanged(key));\n }\n for e in &entries {\n let (k, _) = hkcu.create_subkey(&e.key).map_err(|err| format!(\"{}: {err}\", e.key))?;\n k.set_value(e.name.as_deref().unwrap_or(\"\"), &e.value).map_err(|err| format!(\"{}: {err}\", e.key))?;\n }\n Ok(Registered::Written(key))\n}\n\n#[cfg(target_os = \"macos\")]\nfn register_for(_: &HostConfig, _: &Path) -> Result<Registered, String> {\n Ok(Registered::Skipped(\"macOS registers the scheme from the bundle's Info.plist (CFBundleURLTypes)\".into()))\n}\n\n#[cfg(not(any(target_os = \"linux\", target_os = \"windows\", target_os = \"macos\")))]\nfn register_for(_: &HostConfig, _: &Path) -> Result<Registered, String> {\n Ok(Registered::Skipped(\"this platform has no scheme registration here\".into()))\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n /// The View conformance kit's shell fixture (`atlas` with `/atlas`, `/atlas/archive` and `/atlas/cards`, and\n /// `almanac`), plus hello's greetings.\n fn table() -> ViewTable {\n let v = |id: &str, route: &str| ViewEntry {\n id: id.into(),\n route: route.into(),\n title: id.into(),\n ..ViewEntry::default()\n };\n ViewTable::new(vec![\n v(\"atlas.list\", \"/atlas\"),\n v(\"atlas.archive\", \"/atlas/archive\"),\n v(\"atlas.cards\", \"/atlas/cards/\"),\n v(\"almanac.home\", \"/almanac\"),\n v(\"hello.greetings\", \"/hello\"),\n ])\n .expect(\"as the test set it up\")\n }\n\n fn link(view: &str, record: Option<&str>, org: Option<&str>, params: &[(&str, &str)]) -> DeepLink {\n DeepLink {\n view: view.into(),\n record: record.map(str::to_owned),\n org: org.map(str::to_owned),\n params: params.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(),\n }\n }\n\n fn parse(url: &str) -> Result<DeepLink, Reason> {\n table().parse_link(url, \"atlas\", None).map_err(|e| e.reason)\n }\n\n #[test]\n fn links_in_the_apps_scheme_resolve_like_the_shell() {\n assert_eq!(parse(\"atlas://open/hello\"), Ok(link(\"hello.greetings\", None, None, &[])));\n assert_eq!(parse(\"atlas://open/atlas/c-1?org=acme\"), Ok(link(\"atlas.list\", Some(\"c-1\"), Some(\"acme\"), &[])));\n assert_eq!(\n parse(\"ATLAS://open/atlas/archive\"),\n Ok(link(\"atlas.archive\", None, None, &[])),\n \"longest route wins\"\n );\n assert_eq!(parse(\"atlas://open/atlas/cards/\"), Ok(link(\"atlas.cards\", None, None, &[])), \"trailing slash\");\n assert_eq!(\n parse(\"atlas://open/atlas/%61rchive?org=a&org=b&x=1&x=2&y=a+b&action=delete#frag\"),\n Ok(link(\"atlas.list\", Some(\"archive\"), Some(\"a\"), &[(\"x\", \"1\"), (\"y\", \"a b\"), (\"action\", \"delete\")])),\n \"a percent-encoded record, the first of a repeated key, + as a space, an action only a parameter\"\n );\n assert_eq!(parse(\"atlas://open/atlas/caf%C3%A9\"), Ok(link(\"atlas.list\", Some(\"café\"), None, &[])));\n assert_eq!(parse(\"/almanac?org=acme\"), Ok(link(\"almanac.home\", None, Some(\"acme\"), &[])), \"a shell path\");\n assert_eq!(parse(\"atlas://open/agent/conversation\"), Ok(link(CHAT_VIEW, None, None, &[])), \"a host screen\");\n assert_eq!(parse(\"atlas://open/make/mk_board\"), Ok(link(MAKE_VIEW, Some(\"mk_board\"), None, &[])));\n }\n\n #[test]\n fn only_the_apps_own_links_are_read() {\n for (url, reason) in [\n (\"https://app.example.com/atlas\", Reason::ForeignOrigin),\n (\"http://localhost/atlas\", Reason::ForeignOrigin),\n (\"other://open/atlas\", Reason::Scheme),\n (\"atlasx://open/atlas\", Reason::Scheme),\n (\"javascript:alert(1)\", Reason::Scheme),\n (\"data:text/html,x\", Reason::Scheme),\n (\"file:///etc/passwd\", Reason::Scheme),\n (\"atlas://evil/atlas\", Reason::Malformed),\n (\"atlas://open:8080/atlas\", Reason::Malformed),\n (\"atlas:open/atlas\", Reason::Malformed),\n (\"//host/atlas\", Reason::Malformed),\n (\"not a link\", Reason::Malformed),\n (\"atlas://open/nowhere\", Reason::UnknownView),\n (\"atlas://open/atlas/a/b\", Reason::UnknownView),\n (\"atlas://open/atlas/%E0%A4%A\", Reason::UnknownView),\n (\"atlas://open/\", Reason::UnknownView),\n ] {\n assert_eq!(parse(url), Err(reason), \"{url}\");\n }\n // With a web origin (not this host's case), links on it are read and look-alikes are not.\n let t = table();\n assert!(t.parse_link(\"https://app.example.com/atlas\", \"atlas\", Some(\"https://app.example.com\")).is_ok());\n for foreign in [\"http://app.example.com/atlas\", \"https://app.example.com.evil.io/atlas\"] {\n assert_eq!(\n t.parse_link(foreign, \"atlas\", Some(\"https://app.example.com\")).map_err(|e| e.reason),\n Err(Reason::ForeignOrigin),\n \"{foreign}\"\n );\n }\n }\n\n #[test]\n fn duplicate_views_are_refused_and_host_screens_yield_to_the_apps() {\n let v = |id: &str, route: &str| ViewEntry { id: id.into(), route: route.into(), ..ViewEntry::default() };\n assert!(ViewTable::new(vec![v(\"a.x\", \"/x\"), v(\"a.x\", \"/y\")]).is_err());\n assert!(ViewTable::new(vec![v(\"a.x\", \"/x\"), v(\"a.y\", \"/x/\")]).is_err());\n let t = ViewTable::new(vec![v(\"mine.make\", \"/make\")]).expect(\"as the test set it up\");\n assert_eq!(t.resolve(\"/make\").map(|l| l.view), Some(\"mine.make\".into()), \"the app's view keeps its route\");\n assert!(t.view(MAKE_VIEW).is_none());\n assert!(t.view(CHAT_VIEW).is_some());\n }\n\n #[test]\n fn written_links_read_back_and_records_open_in_the_view_that_shows_them() {\n let t = table();\n for target in [\n link(\"atlas.list\", Some(\"c-1\"), Some(\"acme\"), &[]),\n link(\"atlas.list\", Some(\"archive\"), None, &[]),\n link(\"atlas.list\", Some(\"café / ü?#&\"), Some(\"a b\"), &[(\"x\", \"1\"), (\"action\", \"delete\")]),\n link(\"hello.greetings\", None, Some(\"org&1\"), &[(\"q\", \"a=b\")]),\n link(CHAT_VIEW, None, Some(\"acme\"), &[]),\n ] {\n let url = t.link(&target, \"atlas\").expect(\"a known view\");\n assert_eq!(t.parse_link(&url, \"atlas\", None), Ok(target.clone()), \"{url}\");\n let path = t.link_path(&target).expect(\"a known view\");\n assert_eq!(t.parse_link(&path, \"atlas\", None), Ok(target), \"{path}\");\n }\n assert_eq!(t.link_path(&link(\"atlas.list\", Some(\"archive\"), None, &[])).as_deref(), Some(\"/atlas/%61rchive\"));\n assert!(t.link_path(&link(\"atlas.list\", Some(\"..\"), None, &[])).is_none());\n assert!(t.link_path(&link(\"nowhere\", None, None, &[])).is_none());\n let shows = |id: &str, route: &str, module: &str, entity: &str| ViewEntry {\n id: id.into(),\n route: route.into(),\n module: Some(module.into()),\n entity: Some(entity.into()),\n ..ViewEntry::default()\n };\n let t = ViewTable::new(vec![\n shows(\"hello.greetings\", \"/hello\", \"hello\", \"greeting\"),\n shows(\"hello.wall\", \"/wall\", \"hello\", \"greeting\"),\n shows(\"notes.list\", \"/notes\", \"notes\", \"note\"),\n ])\n .expect(\"as the test set it up\");\n assert_eq!(\n t.record_link(\"hello\", \"greeting\", \"g 1\", Some(\"acme\"), \"atlas\").as_deref(),\n Some(\"atlas://open/hello/g%201?org=acme\"),\n \"the first view that shows the entity\"\n );\n assert_eq!(t.record_link(\"notes\", \"greeting\", \"g1\", None, \"atlas\"), None, \"another module's entity\");\n assert_eq!(t.record_link(\"approvals\", \"request\", \"r1\", None, \"atlas\"), None);\n }\n\n #[test]\n fn links_route_to_the_hosts_screens() {\n let t = table();\n let r = |url: &str| route(&t, &t.parse_link(url, \"atlas\", None).expect(\"as the test set it up\"));\n assert_eq!(r(\"atlas://open/hello\"), Route::Greetings);\n assert_eq!(r(\"atlas://open/agent/conversation\"), Route::Chat);\n assert_eq!(r(\"atlas://open/make/mk_board\"), Route::Make(Some(\"mk_board\".into())));\n assert_eq!(r(\"atlas://open/make\"), Route::Make(None));\n assert_eq!(r(\"atlas://open/almanac\"), Route::Unavailable(\"almanac.home\".into()));\n }\n\n fn config() -> HostConfig {\n HostConfig {\n app_id: \"com.acme.crm\".into(),\n name: \"Acme CRM\".into(),\n scheme: \"acme-crm\".into(),\n ..HostConfig::default()\n }\n }\n\n #[test]\n fn the_linux_desktop_entry_handles_the_scheme() {\n let entry = desktop_entry(&config(), Path::new(\"/opt/Acme CRM/acme$1\"));\n assert!(entry.contains(\"MimeType=x-scheme-handler/acme-crm;\\n\"), \"{entry}\");\n assert!(entry.contains(\"Exec=\\\"/opt/Acme CRM/acme\\\\\\\\$1\\\" %u\\n\"), \"{entry}\");\n assert!(entry.contains(\"NoDisplay=true\\n\"));\n assert_eq!(desktop_file_name(&config()), \"com.acme.crm.desktop\");\n assert_eq!(exec_quote(\"50%\\\"`\\\\\"), r#\"\"50%%\\\\\"\\\\`\\\\\\\\\"\"#);\n // A reader undoes the key-file escapes, then the Exec quoting: every path comes back as it was.\n fn read_exec(value: &str) -> String {\n let mut string = String::new();\n let mut chars = value.chars();\n while let Some(c) = chars.next() {\n match (c, c == '\\\\') {\n (_, true) => match chars.next() {\n Some('\\\\') => string.push('\\\\'),\n Some('n') => string.push('\\n'),\n Some('t') => string.push('\\t'),\n Some('r') => string.push('\\r'),\n Some('s') => string.push(' '),\n other => panic!(\"an escape a key-file reader refuses: \\\\{other:?} in {value}\"),\n },\n (c, false) => string.push(c),\n }\n }\n let inner = string.strip_prefix('\"').and_then(|s| s.strip_suffix('\"')).expect(\"quoted\");\n let (mut arg, mut chars) = (String::new(), inner.chars());\n while let Some(c) = chars.next() {\n match c {\n '\\\\' => {\n let next = chars.next().expect(\"an escaped character\");\n assert!(\"\\\"`$\\\\\".contains(next), \"only these are escaped inside quotes: {next}\");\n arg.push(next);\n }\n '\"' | '`' | '$' => panic!(\"unescaped {c} inside quotes: {inner}\"),\n c => arg.push(c),\n }\n }\n arg.replace(\"%%\", \"%\")\n }\n for path in [\"/opt/Acme CRM/acme$1\", \"/home/u/a\\\"b/app\", \"/x/`id`/a\\\\b\", \"/50%/app\", \"/plain/app\", \"/tab\\there\"]\n {\n assert_eq!(read_exec(&exec_quote(path)), path, \"{path}\");\n }\n }\n\n #[test]\n fn a_link_launch_is_exactly_one_link_and_rune_never_reads_its_arguments() {\n let a = |v: &[&str]| v.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();\n assert_eq!(launch_link(&a(&[])), Ok(None));\n assert_eq!(launch_link(&a(&[\"acme-crm://open/x\"])), Ok(Some(\"acme-crm://open/x\".into())));\n assert_eq!(launch_link(&a(&[\"--open-url\", \"acme-crm://open/x\"])), Ok(Some(\"acme-crm://open/x\".into())));\n // Windows substitutes %1 verbatim: `acme-crm://open/x\" --native --trace \"C:\\...\\thesis.docx` closes the\n // quote and adds Rune's flags as arguments of their own. The launch is refused, and Rune reads none of them.\n let injected = a(&[\"--open-url\", \"acme-crm://open/x\", \"--native\", \"--trace\", r\"C:\\Users\\me\\thesis.docx\"]);\n assert!(launch_link(&injected).is_err());\n assert_eq!(rune_args(&injected, true), Vec::<String>::new());\n assert!(launch_link(&a(&[\"acme-crm://open/x\", \"--snap\", \"out.png\"])).is_err());\n assert!(launch_link(&a(&[\"--open-url\"])).is_err());\n assert!(launch_link(&a(&[\"--open-url\", \"not a link\"])).is_err());\n // A release build gives Rune nothing; a development build its own tooling flags, never with a link.\n assert_eq!(rune_args(&a(&[\"--snap\", \"out.png\"]), false), Vec::<String>::new());\n assert_eq!(rune_args(&a(&[\"--snap\", \"out.png\"]), true), a(&[\"--snap\", \"out.png\"]));\n assert_eq!(rune_args(&a(&[\"acme-crm://open/x\"]), true), Vec::<String>::new());\n }\n\n #[test]\n fn the_windows_registry_entries_open_the_executable_with_the_link() {\n let entries = windows_entries(&config(), Path::new(r\"C:\\Users\\p\\AppData\\Local\\Acme\\acme.exe\"));\n let find = |key: &str, name: Option<&str>| {\n entries.iter().find(|e| e.key == key && e.name.as_deref() == name).map(|e| e.value.clone())\n };\n assert_eq!(find(r\"Software\\Classes\\acme-crm\", None), Some(\"URL:Acme CRM link\".into()));\n assert_eq!(find(r\"Software\\Classes\\acme-crm\", Some(\"URL Protocol\")), Some(String::new()));\n assert_eq!(\n find(r\"Software\\Classes\\acme-crm\\shell\\open\\command\", None),\n Some(r#\"\"C:\\Users\\p\\AppData\\Local\\Acme\\acme.exe\" --open-url \"%1\"\"#.into())\n );\n assert!(find(r\"Software\\Classes\\acme-crm\\DefaultIcon\", None).is_some());\n }\n\n #[test]\n fn the_macos_info_plist_declares_the_scheme() {\n let plist = macos_url_types(&config());\n assert!(plist.contains(\"<key>CFBundleURLSchemes</key>\"));\n assert!(plist.contains(\"<string>acme-crm</string>\"));\n assert!(plist.contains(\"<string>com.acme.crm</string>\"));\n }\n\n #[cfg(target_os = \"linux\")]\n #[test]\n fn the_linux_registration_writes_once() {\n let dir = std::env::temp_dir().join(format!(\"eloxiv-rune-register-{}\", crate::random_id()));\n struct Gone(PathBuf);\n impl Drop for Gone {\n fn drop(&mut self) {\n let _ = std::fs::remove_dir_all(&self.0);\n }\n }\n let _gone = Gone(dir.clone());\n let exe = Path::new(\"/opt/acme/acme\");\n assert!(matches!(register_linux(&config(), exe, &dir, false), Ok(Registered::Written(_))));\n assert!(\n std::fs::read_to_string(dir.join(\"com.acme.crm.desktop\"))\n .expect(\"as the test set it up\")\n .contains(\"x-scheme-handler/acme-crm\")\n );\n assert!(matches!(register_linux(&config(), exe, &dir, false), Ok(Registered::Unchanged(_))));\n assert!(matches!(register_linux(&config(), Path::new(\"/elsewhere\"), &dir, false), Ok(Registered::Written(_))));\n let off = HostConfig { register_scheme: false, ..config() };\n assert!(matches!(register(&off, false), Ok(Registered::Skipped(_))));\n // An installer registered it (a .deb, NSIS, a bundle): the host does not write over it; an AppImage and a\n // development build register it themselves.\n assert!(!registers_itself(true, false));\n assert!(registers_itself(true, true));\n assert!(registers_itself(false, false));\n }\n}\n",
144
+ "type": "registry:file",
145
+ "target": "desktop-rune/app/src/links.rs"
146
+ },
147
+ {
148
+ "path": "app/desktop-rune/app/src/main.rs",
149
+ "content": "//! `eloxiv-desktop-rune` (installed as the app's `binaryName`): starts the app's daemon as its sidecar, then the\n//! window, under the app's identity. The launch probe ([`launch`]) prints when it is interactive.\n//!\n//! - The app's identity, servers and update host come from `app.json` (compiled in) and the environment\n//! ([`config`]); a second launch of the app hands its links to the running one and exits before anything starts\n//! (Rune's `single_instance`).\n//! - `ELOXIV_DAEMON_URL` and `ELOXIV_DAEMON_HOST_SECRET` attach to a daemon already running (development and the\n//! journey): nothing is started.\n//! - Otherwise the sidecar ([`sidecar::default_launch`]: `ELOXIV_DAEMON_BIN`, `<executable>-daemon` beside this\n//! executable or in `../libexec`, `eloxiv-daemon` beside it, the workspace's `target/sidecar/eloxiv-daemon`, else\n//! `sidecar/daemon.ts` with Bun) starts with a new host secret and the stdin lifeline, the app's servers in its\n//! environment (`ELOXIV_KERNEL_URL`, `ELOXIV_ZERO_URL`, `ELOXIV_SHELL_URL`), on `ELOXIV_DAEMON_PORT`, else a free\n//! port when packaged, else 4191; a packaged sidecar keeps its state in the app's own directory\n//! ([`sidecar::state_dir_args`]). `ELOXIV_DAEMON_ARGS` (whitespace-separated) go before the host's arguments. It\n//! stops when the window closes.\n//! - When the person restarted into a downloaded update, it is applied once the window has closed and the sidecar\n//! stopped ([`updates`]). Rune ends the process at once when its loop ends (`fast_exit`): nothing after `run`\n//! runs, so stopping the sidecar and applying the update are its `last` step.\n//!\n//! [`config`]: eloxiv_desktop_rune::config\n//! [`launch`]: eloxiv_desktop_rune::launch\n//! [`updates`]: eloxiv_desktop_rune::updates\n\nuse eloxiv_desktop_rune::services::HostServices;\nuse eloxiv_desktop_rune::sidecar::{self, Sidecar};\nuse eloxiv_desktop_rune::{config, launch, links, outstanding, updates};\n\nuse std::sync::Mutex;\n\n/// The sidecar this process started, stopped in Rune's last step before the process ends.\nstatic SIDECAR: Mutex<Option<Sidecar>> = Mutex::new(None);\n\nfn main() {\n // `--print-version`: the version compiled in (app.json), asked by an updater of a build it staged.\n if std::env::args().skip(1).eq([\"--print-version\"]) {\n println!(\"{}\", config::HostConfig::compiled().version);\n return;\n }\n launch::enable();\n // A link launch is exactly one link (`links::launch_link`): one a crafted link added arguments to is refused before\n // anything starts, and Rune never reads process arguments as its flags outside a development build.\n let argv: Vec<String> = std::env::args().skip(1).collect();\n if let Err(why) = links::launch_link(&argv) {\n eprintln!(\"eloxiv-desktop-rune: {why}\");\n std::process::exit(2);\n }\n let rune_args = links::rune_args(&argv, cfg!(debug_assertions));\n let config = config::current().clone();\n for problem in &config.problems {\n eprintln!(\"eloxiv-desktop-rune: app.json: {problem}\");\n }\n // An update whose applying process died before it knew the outcome: the build before it is put back and started.\n if std::env::var_os(updates::TRIAL_ENV).is_none() {\n let install = updates::Install::detect();\n let dir = outstanding::default_data_dir().unwrap_or_else(std::env::temp_dir);\n if let Some(why) = updates::recover(&install, &dir) {\n eprintln!(\"eloxiv-desktop-rune: {why}; the previous build is restored\");\n if let Some(exe) = install.executable() {\n let _ = std::process::Command::new(exe).env(updates::ROLLED_BACK_ENV, &why).spawn();\n return;\n }\n }\n }\n // One process per app: a later launch's links went to the running one, which shows them.\n if !rune::single_instance(&config.app_id) {\n return;\n }\n let attached = std::env::var(\"ELOXIV_DAEMON_URL\").ok().zip(std::env::var(\"ELOXIV_DAEMON_HOST_SECRET\").ok());\n // Also what the app's views are asked of (deep links).\n let launch = sidecar::default_launch();\n let (url, token) = match attached {\n Some((url, secret)) => (url, secret),\n None => {\n let Some(launch) = launch.clone() else {\n eprintln!(\n \"eloxiv-desktop-rune: no daemon sidecar (build it: node desktop-rune/scripts/build-sidecar.ts; or set ELOXIV_DAEMON_BIN, or put eloxiv-daemon beside this executable)\"\n );\n std::process::exit(1);\n };\n let port = sidecar::daemon_port(std::env::var(\"ELOXIV_DAEMON_PORT\").ok().as_deref(), launch.packaged);\n let mut args: Vec<String> = std::env::var(\"ELOXIV_DAEMON_ARGS\")\n .map(|a| a.split_whitespace().map(str::to_owned).collect())\n .unwrap_or_default();\n args.extend(sidecar::state_dir_args(&launch, &config.app_id, &args, |name| std::env::var(name).ok()));\n match Sidecar::start_with(&launch, port, &args, &config.servers.env()) {\n Ok(s) => {\n let pair = (s.url(), s.secret().to_owned());\n *SIDECAR.lock().unwrap_or_else(|e| e.into_inner()) = Some(s);\n pair\n }\n Err(e) => {\n eprintln!(\"eloxiv-desktop-rune: could not start {}: {e}\", launch.program.display());\n std::process::exit(1);\n }\n }\n }\n };\n rune::set_app_id(Box::leak(config.app_id.clone().into_boxed_str()));\n // Windows: the identity its toasts post under, before the window opens.\n eloxiv_desktop_rune::notices::register_identity(&config.app_id, &config.name);\n let host = move || HostServices::start(config, launch);\n rune::fast_exit(last);\n eloxiv_desktop_rune::app_with(url, token, outstanding::default_data_dir(), host).args(rune_args).run();\n // Reached only if the loop returns (an orderly exit).\n last();\n}\n\n/// After the window closed: the sidecar stops with the host, then the update the person restarted into is applied.\nfn last() {\n // The OS notifications still shown are withdrawn (nothing of this run is left in the system's list).\n eloxiv_desktop_rune::notices::shutdown();\n drop(SIDECAR.lock().unwrap_or_else(|e| e.into_inner()).take());\n if let Some(staged) = updates::take_pending() {\n apply_update(&staged);\n }\n}\n\n/// Applies the build the person restarted into, and starts it (or the old one again, if it does not start).\nfn apply_update(staged: &updates::Staged) {\n // The new build claims the app's single instance.\n rune::release_instance();\n // The new build starts without this launch's arguments (a link was handled; nothing else is the host's).\n let args: Vec<std::ffi::OsString> = Vec::new();\n let dir = outstanding::default_data_dir().unwrap_or_else(std::env::temp_dir);\n let _ = std::fs::create_dir_all(&dir);\n match updates::apply(staged, &args, &dir, updates::trial_window()) {\n Ok(applied) => eprintln!(\"eloxiv-desktop-rune: update to {}: {applied:?}\", staged.version),\n Err(e) => eprintln!(\"eloxiv-desktop-rune: the update to {} was not applied: {e}\", staged.version),\n }\n}\n",
150
+ "type": "registry:file",
151
+ "target": "desktop-rune/app/src/main.rs"
152
+ },
153
+ {
154
+ "path": "app/desktop-rune/app/src/make/fields.rs",
155
+ "content": "//! A MAKE view's fields, natively: what the web host keeps in the frame's DOM, kept here.\n//!\n//! The rules are the web host's (`mountMakeView` in shell-foldkit's `makeView.ts`):\n//!\n//! - A field is an `input`, `textarea` or `select`. Its identity across a redraw is its **name**; a field whose\n//! tree gives `value` (or `checked`) is the view's, otherwise what the person typed into the field of that name\n//! is kept (radio buttons excepted: their checked state is the tree's).\n//! - `fields` in an event: the named fields of the activated control's nearest `form`, or of the whole view\n//! outside one, in tree order; a later field of a name overwrites an earlier one, disabled and hidden fields\n//! included. Checkboxes give `true`/`false`; a radio group gives its checked button's value, or `\"\"` when none\n//! is; everything else gives its text (a number field too).\n//! - An `option`'s value is its text (the web host draws no `value` attribute on an option), and a `select`\n//! with no `selected` option and no `value` shows its first option.\n\nuse std::collections::HashMap;\n\nuse eloxiv_local_client::{MakeViewElement, MakeViewElementTag as Tag, MakeViewNode, MakeViewPropValue};\nuse rune::TextEdit;\nuse serde_json::{Map, Value};\n\n/// The input types a view may give (`MAKE_VIEW_INPUT_TYPES`); any other is `text`, as on the web.\npub const INPUT_TYPES: &[&str] = &[\n \"text\",\n \"number\",\n \"email\",\n \"date\",\n \"time\",\n \"datetime-local\",\n \"search\",\n \"tel\",\n \"checkbox\",\n \"radio\",\n \"range\",\n \"color\",\n \"hidden\",\n];\n\n#[derive(Clone, Debug, PartialEq)]\npub enum FieldValue {\n Text(String),\n Bool(bool),\n}\n\nimpl FieldValue {\n pub fn to_json(&self) -> Value {\n match self {\n FieldValue::Text(t) => Value::String(t.clone()),\n FieldValue::Bool(b) => Value::Bool(*b),\n }\n }\n pub fn text(&self) -> String {\n match self {\n FieldValue::Text(t) => t.clone(),\n FieldValue::Bool(b) => b.to_string(),\n }\n }\n}\n\n#[derive(Clone, Debug, PartialEq)]\npub enum Kind {\n /// One line of text; `numeric` keeps to a number's characters (`type: number`), `input_type` is the type the\n /// view gave (`email`, `date`, ...), all drawn as a text field.\n Line {\n numeric: bool,\n input_type: String,\n },\n Area {\n rows: u32,\n },\n Checkbox,\n /// Its value (`value`, else `\"on\"`).\n Radio {\n value: String,\n },\n Range {\n min: f64,\n max: f64,\n step: f64,\n },\n Select {\n options: Vec<String>,\n },\n Hidden,\n}\n\n#[derive(Clone, Debug, PartialEq)]\npub struct Field {\n /// The element's key (its place in the tree).\n pub key: String,\n pub name: Option<String>,\n pub kind: Kind,\n /// The key of its nearest `form`, if any.\n pub form: Option<String>,\n pub disabled: bool,\n /// What assistive technology calls it: `ariaLabel`, else its `label`'s text, else `placeholder`, `title`,\n /// its name, its type.\n pub label: String,\n /// `on` and `data`, when it reports changes.\n pub on: Option<(String, Option<Value>)>,\n}\n\n/// The fields of the tree drawn now, and their values.\n#[derive(Default)]\npub struct Fields {\n pub list: Vec<Field>,\n pub values: HashMap<String, FieldValue>,\n /// The editors of text fields, by key.\n pub edits: HashMap<String, TextEdit>,\n}\n\npub fn prop<'a>(e: &'a MakeViewElement, name: &str) -> Option<&'a MakeViewPropValue> {\n let p = e.props.as_ref()?;\n match name {\n \"class\" => p.class.as_ref(),\n \"title\" => p.title.as_ref(),\n \"style\" => p.style.as_ref(),\n \"placeholder\" => p.placeholder.as_ref(),\n \"value\" => p.value.as_ref(),\n \"checked\" => p.checked.as_ref(),\n \"selected\" => p.selected.as_ref(),\n \"disabled\" => p.disabled.as_ref(),\n \"name\" => p.name.as_ref(),\n \"type\" => p.type_.as_ref(),\n \"min\" => p.min.as_ref(),\n \"max\" => p.max.as_ref(),\n \"step\" => p.step.as_ref(),\n \"rows\" => p.rows.as_ref(),\n \"colspan\" => p.colspan.as_ref(),\n \"rowspan\" => p.rowspan.as_ref(),\n \"ariaLabel\" => p.aria_label.as_ref(),\n _ => None,\n }\n}\n\n/// A prop as the DOM would read it: `String(value)`.\npub fn prop_text(e: &MakeViewElement, name: &str) -> Option<String> {\n prop(e, name).map(|v| match v {\n MakeViewPropValue::String(s) => s.clone(),\n MakeViewPropValue::Number(n) => js_number(*n),\n MakeViewPropValue::Boolean(b) => b.to_string(),\n })\n}\n\n/// `true` only for the boolean `true` (the web host's `props.disabled === true`, `props.checked === true`).\npub fn prop_true(e: &MakeViewElement, name: &str) -> bool {\n matches!(prop(e, name), Some(MakeViewPropValue::Boolean(true)))\n}\n\n/// A number as JavaScript's `String(n)` writes it, for the integers and plain decimals views use.\npub fn js_number(n: f64) -> String {\n if n.fract() == 0.0 && n.abs() < 1e21 { format!(\"{}\", n as i64) } else { format!(\"{n}\") }\n}\n\n/// The input type a view gave, held to the allowed ones.\npub fn input_type(e: &MakeViewElement) -> String {\n let t = prop_text(e, \"type\").unwrap_or_default();\n if INPUT_TYPES.contains(&t.as_str()) { t } else { \"text\".into() }\n}\n\n/// The text of a subtree (strings and numbers), as `textContent` reads it.\npub fn text_of(node: &MakeViewNode) -> String {\n let mut out = String::new();\n collect_text(node, &mut out);\n out\n}\n\nfn collect_text(node: &MakeViewNode, out: &mut String) {\n match node {\n MakeViewNode::String(s) => out.push_str(s),\n MakeViewNode::Number(n) => out.push_str(&js_number(*n)),\n MakeViewNode::MakeViewElement(e) => e.children.iter().for_each(|c| collect_text(c, out)),\n _ => {}\n }\n}\n\n/// An element's key from its place in the tree.\npub fn key_of(path: &[usize]) -> String {\n let mut key = String::from(\"mk:\");\n for (i, p) in path.iter().enumerate() {\n if i > 0 {\n key.push('.');\n }\n key.push_str(&p.to_string());\n }\n if path.is_empty() {\n key.push('r');\n }\n key\n}\n\n/// A field as drawn first, before what the person typed is restored.\nstruct Drawn {\n field: Field,\n given: bool,\n initial: FieldValue,\n}\n\nimpl Fields {\n /// The fields of a new tree, keeping what the person typed (by name) where the tree gives no value.\n pub fn rebuild(&mut self, tree: &MakeViewNode) {\n let mut typed: HashMap<String, FieldValue> = HashMap::new();\n for f in &self.list {\n if let (Some(name), false) = (&f.name, matches!(f.kind, Kind::Radio { .. }))\n && let Some(v) = self.current(f)\n {\n typed.insert(name.clone(), v);\n }\n }\n let mut drawn = Vec::new();\n walk(tree, &mut Vec::new(), None, None, &mut drawn);\n let old_edits = std::mem::take(&mut self.edits);\n self.list.clear();\n self.values.clear();\n for d in drawn {\n let mut value = d.initial;\n if !d.given\n && let Some(name) = &d.field.name\n && let Some(t) = typed.get(name)\n {\n value = match (&d.field.kind, t) {\n (Kind::Checkbox, FieldValue::Bool(b)) => FieldValue::Bool(*b),\n (Kind::Checkbox, FieldValue::Text(_)) => value,\n (Kind::Select { options }, FieldValue::Text(s)) => {\n if options.contains(s) {\n t.clone()\n } else {\n FieldValue::Text(String::new())\n }\n }\n (_, FieldValue::Text(s)) => FieldValue::Text(s.clone()),\n (_, FieldValue::Bool(_)) => value,\n };\n }\n if matches!(d.field.kind, Kind::Line { .. } | Kind::Area { .. }) {\n let text = value.text();\n // The same editor when its text is unchanged keeps the caret, selection and focus.\n let edit = match old_edits.get(&d.field.key) {\n Some(old) if old.text == text => old.clone(),\n Some(old) => {\n let mut e = TextEdit::new(text);\n e.focused = old.focused;\n e\n }\n None => TextEdit::new(text),\n };\n self.edits.insert(d.field.key.clone(), edit);\n }\n self.values.insert(d.field.key.clone(), value);\n self.list.push(d.field);\n }\n }\n\n pub fn field(&self, key: &str) -> Option<&Field> {\n self.list.iter().find(|f| f.key == key)\n }\n\n /// A field's value now (a text field's from its editor).\n pub fn current(&self, f: &Field) -> Option<FieldValue> {\n match self.edits.get(&f.key) {\n Some(edit) => Some(FieldValue::Text(edit.text.clone())),\n None => self.values.get(&f.key).cloned(),\n }\n }\n\n /// The `fields` of an event from the control at `key`: its form's named fields, or the whole view's.\n pub fn collect(&self, form: Option<&str>) -> Map<String, Value> {\n let mut out = Map::new();\n for f in &self.list {\n let Some(name) = f.name.as_ref().filter(|n| !n.is_empty()) else { continue };\n // Under the form: its own fields and those of forms inside it, as `querySelectorAll` finds them. A form\n // at the root of the tree (`mk:r`) holds every field: its children's keys carry no prefix of its own.\n if let Some(form) = form\n && form != key_of(&[])\n && !f.key.starts_with(&format!(\"{form}.\"))\n {\n continue;\n }\n match &f.kind {\n Kind::Radio { value } => {\n if self.values.get(&f.key) == Some(&FieldValue::Bool(true)) {\n out.insert(name.clone(), Value::String(value.clone()));\n } else if !out.contains_key(name) {\n out.insert(name.clone(), Value::String(String::new()));\n }\n }\n _ => {\n if let Some(v) = self.current(f) {\n out.insert(name.clone(), v.to_json());\n }\n }\n }\n }\n out\n }\n\n /// A field's value as its own `on` event reports it (`value`): a checkbox's or radio's checked state, else\n /// its text.\n pub fn event_value(&self, f: &Field) -> Value {\n match (&f.kind, self.values.get(&f.key)) {\n (Kind::Checkbox | Kind::Radio { .. }, Some(FieldValue::Bool(b))) => Value::Bool(*b),\n _ => self.current(f).map_or(Value::String(String::new()), |v| v.to_json()),\n }\n }\n\n /// The person toggled a checkbox.\n pub fn toggle(&mut self, key: &str) -> bool {\n let next = !matches!(self.values.get(key), Some(FieldValue::Bool(true)));\n self.values.insert(key.to_owned(), FieldValue::Bool(next));\n next\n }\n\n /// The person chose a radio button: it is checked, and the others of its name in its form are not.\n pub fn choose_radio(&mut self, key: &str) {\n let Some(chosen) = self.field(key).cloned() else { return };\n for f in &self.list {\n if matches!(f.kind, Kind::Radio { .. }) && f.name == chosen.name && f.form == chosen.form {\n self.values.insert(f.key.clone(), FieldValue::Bool(f.key == key));\n }\n }\n }\n\n /// The person set a field's value (a select's option, a range's number).\n pub fn set(&mut self, key: &str, value: FieldValue) {\n self.values.insert(key.to_owned(), value);\n }\n\n /// A text field's editor changed: its value follows (a number field keeps a number's characters only).\n pub fn edited(&mut self, key: &str) {\n let numeric = matches!(self.field(key).map(|f| &f.kind), Some(Kind::Line { numeric: true, .. }));\n if let Some(edit) = self.edits.get_mut(key) {\n if numeric && !edit.text.chars().all(|c| c.is_ascii_digit() || matches!(c, '-' | '+' | '.' | 'e' | 'E')) {\n let kept: String = edit\n .text\n .chars()\n .filter(|c| c.is_ascii_digit() || matches!(c, '-' | '+' | '.' | 'e' | 'E'))\n .collect();\n let focused = edit.focused;\n *edit = TextEdit::new(kept);\n edit.focused = focused;\n }\n let text = edit.text.clone();\n self.values.insert(key.to_owned(), FieldValue::Text(text));\n }\n }\n}\n\nfn walk(node: &MakeViewNode, path: &mut Vec<usize>, form: Option<&str>, label: Option<&str>, out: &mut Vec<Drawn>) {\n let MakeViewNode::MakeViewElement(e) = node else { return };\n let key = key_of(path);\n let own_form = if e.tag == Tag::Form { Some(key.as_str()) } else { form };\n let label_text;\n let own_label = if e.tag == Tag::Label {\n label_text = e\n .children\n .iter()\n .filter(|c| !matches!(c, MakeViewNode::MakeViewElement(x) if matches!(x.tag, Tag::Input | Tag::Textarea | Tag::Select)))\n .map(text_of)\n .collect::<String>();\n Some(label_text.trim())\n } else {\n label\n };\n if matches!(e.tag, Tag::Input | Tag::Textarea | Tag::Select) {\n out.push(drawn(e, key.clone(), own_form.map(str::to_owned), own_label));\n // A field's children are not drawn (an input has none; a select's options are its own).\n return;\n }\n for (i, child) in e.children.iter().enumerate() {\n path.push(i);\n walk(child, path, own_form, own_label, out);\n path.pop();\n }\n}\n\nfn number_prop(e: &MakeViewElement, name: &str) -> Option<f64> {\n match prop(e, name)? {\n MakeViewPropValue::Number(n) => Some(*n),\n MakeViewPropValue::String(s) => s.trim().parse().ok(),\n MakeViewPropValue::Boolean(_) => None,\n }\n .filter(|n: &f64| n.is_finite())\n}\n\nfn drawn(e: &MakeViewElement, key: String, form: Option<String>, label: Option<&str>) -> Drawn {\n let name = prop_text(e, \"name\");\n let given = prop(e, \"value\").is_some() || prop(e, \"checked\").is_some();\n let value = prop_text(e, \"value\");\n let (kind, initial) = match e.tag {\n Tag::Textarea => {\n let rows = number_prop(e, \"rows\").map_or(2, |r| r.clamp(1.0, 40.0) as u32);\n (Kind::Area { rows }, FieldValue::Text(value.unwrap_or_default()))\n }\n Tag::Select => {\n let options: Vec<(String, bool)> = e\n .children\n .iter()\n .filter_map(|c| match c {\n MakeViewNode::MakeViewElement(o) if o.tag == Tag::Option => {\n Some((text_of(c), prop_true(o, \"selected\")))\n }\n _ => None,\n })\n .collect();\n let texts: Vec<String> = options.iter().map(|(t, _)| t.clone()).collect();\n let chosen = match value {\n Some(v) if texts.contains(&v) => v,\n Some(_) => String::new(),\n None => options\n .iter()\n .rev()\n .find(|(_, s)| *s)\n .or(options.first())\n .map(|(t, _)| t.clone())\n .unwrap_or_default(),\n };\n (Kind::Select { options: texts }, FieldValue::Text(chosen))\n }\n _ => match input_type(e).as_str() {\n \"checkbox\" => (Kind::Checkbox, FieldValue::Bool(prop_true(e, \"checked\"))),\n \"radio\" => {\n (Kind::Radio { value: value.unwrap_or_else(|| \"on\".into()) }, FieldValue::Bool(prop_true(e, \"checked\")))\n }\n \"range\" => {\n let min = number_prop(e, \"min\").unwrap_or(0.0);\n let max = number_prop(e, \"max\").unwrap_or(100.0).max(min);\n let step = number_prop(e, \"step\").filter(|s| *s > 0.0).unwrap_or(1.0);\n // The DOM's default is the midpoint.\n let start = value.unwrap_or_else(|| js_number(min + ((max - min) / 2.0 / step).round() * step));\n (Kind::Range { min, max, step }, FieldValue::Text(start))\n }\n \"hidden\" => (Kind::Hidden, FieldValue::Text(value.unwrap_or_default())),\n t => (\n Kind::Line { numeric: t == \"number\", input_type: t.to_owned() },\n FieldValue::Text(value.unwrap_or_default()),\n ),\n },\n };\n let label = prop_text(e, \"ariaLabel\")\n .or_else(|| label.filter(|l| !l.is_empty()).map(str::to_owned))\n .or_else(|| prop_text(e, \"placeholder\"))\n .or_else(|| prop_text(e, \"title\"))\n .or_else(|| name.clone())\n .unwrap_or_else(|| match &kind {\n Kind::Select { .. } => \"Choice\".into(),\n Kind::Area { .. } => \"Text\".into(),\n _ => input_type(e),\n });\n let on = e.on.clone().map(|n| (n, e.data.clone()));\n Drawn { field: Field { key, name, kind, form, disabled: prop_true(e, \"disabled\"), label, on }, given, initial }\n}\n",
156
+ "type": "registry:file",
157
+ "target": "desktop-rune/app/src/make/fields.rs"
158
+ },
159
+ {
160
+ "path": "app/desktop-rune/app/src/make/mod.rs",
161
+ "content": "//! MAKE views, natively (docs/contracts/sandbox.md, \"The view runtime\"; \"Native hosts\").\n//!\n//! A view's code never runs here: each step is `make.renderView` in the kernel's sandbox, reached through the\n//! daemon's `/client/v1/actions`. This module is the host's side, as the web host (`mountMakeView`) is the\n//! shell's: it holds the view's state between steps, runs **one step at a time** in order, makes the calls a\n//! step asks for **only for actions `make.view` listed** (any other is answered `Forbidden` here, with no\n//! request), sends each result back as the next step's message, and drops every answer that arrives for a\n//! mount that is gone (another organisation, sign-out, the screen closed, the view reopened).\n//!\n//! [`render`] draws the tree with Rune elements from the closed vocabulary only: no URL is ever opened (no\n//! element names one, and nothing here calls `open_url`), no image is drawn, `class` is inert.\n\npub mod fields;\npub mod render;\npub mod style;\n\nuse std::collections::VecDeque;\n\nuse eloxiv_local_client::{MakeViewNode, MakeViewStep};\nuse rune::TextEdit;\nuse serde_json::{Value, json};\n\nuse fields::{Fields, Kind};\n\n/// The sandbox's bounds on a tree, held again here: a tree past them fails the view.\npub const MAX_NODES: usize = 5_000;\npub const MAX_DEPTH: usize = 64;\n/// The longest step answer read (its JSON), before it is decoded.\npub const MAX_STEP_BYTES: usize = 4 * 1024 * 1024;\n\n/// What the host asks the daemon for; the app's worker makes each request and answers with the mount it was for.\n#[derive(Clone, Debug, PartialEq)]\npub enum Request {\n /// `make.view { module }`.\n View { mount: u64, module: String },\n /// `make.renderView { module, version, state, message }`.\n Step { mount: u64, module: String, version: String, state: Value, message: Value },\n /// A call the view asked for, of a listed action, under `make-view:<instance>:<key>`.\n Call { mount: u64, id: String, action: String, input: Value, key: String },\n}\n\n/// A view opened for one mount.\npub struct View {\n pub mount: u64,\n /// New for each mount; namespaces the view's idempotency keys.\n pub instance: String,\n pub module: String,\n pub version: String,\n pub title: String,\n /// The actions it may call (`capabilities.view`, from `make.view`).\n pub actions: Vec<String>,\n pub state: Value,\n pub tree: MakeViewNode,\n pub fields: Fields,\n queue: VecDeque<Value>,\n in_flight: bool,\n /// Steps run so far.\n pub steps: u64,\n /// Calls made (listed actions), and results the view was given (refusals included).\n pub calls: u64,\n pub results: u64,\n}\n\n#[derive(Clone, Debug, PartialEq)]\npub enum Phase {\n Closed,\n Loading { module: String },\n Shown,\n Failed { module: String, message: String },\n}\n\n/// The MAKE screen's host.\npub struct Host {\n pub phase: Phase,\n pub view: Option<View>,\n /// The module to open (the screen's field).\n pub module_input: TextEdit,\n /// Requests for the worker, drained by the app.\n pub outbox: Vec<Request>,\n mount: u64,\n /// An editor handed out when a field's own is gone (a handler of a torn-down view).\n pub scratch: TextEdit,\n /// Makes each mount's instance id.\n pub ids: fn() -> String,\n}\n\nimpl Default for Host {\n fn default() -> Self {\n Host {\n phase: Phase::Closed,\n view: None,\n module_input: TextEdit::new(\"\"),\n outbox: Vec::new(),\n mount: 0,\n scratch: TextEdit::new(\"\"),\n ids: crate::random_id,\n }\n }\n}\n\nfn error_message(error: &Value) -> Value {\n json!({\n \"_tag\": error.get(\"_tag\").and_then(Value::as_str).unwrap_or(\"ActionFailed\"),\n \"message\": error.get(\"message\").and_then(Value::as_str).unwrap_or(\"\"),\n })\n}\n\n/// Counts a raw tree's nodes and depth, stopping past the bounds.\nfn within_bounds(tree: &Value) -> bool {\n fn walk(node: &Value, depth: usize, count: &mut usize) -> bool {\n *count += 1;\n if *count > MAX_NODES || depth > MAX_DEPTH {\n return false;\n }\n match node.get(\"children\").and_then(Value::as_array) {\n Some(children) => children.iter().all(|c| walk(c, depth + 1, count)),\n None => true,\n }\n }\n walk(tree, 1, &mut 0)\n}\n\nimpl Host {\n /// Opens `module`'s view: reads `make.view` (only that; no action runs until the view's own `init` asks).\n pub fn open(&mut self, module: &str) {\n let module = module.trim().to_owned();\n if module.is_empty() {\n return;\n }\n self.mount += 1;\n self.view = None;\n self.phase = Phase::Loading { module: module.clone() };\n self.outbox.push(Request::View { mount: self.mount, module });\n }\n\n /// Everything of the view goes (an organisation switch, sign-out, the screen closed): later answers for it\n /// are dropped.\n pub fn teardown(&mut self) {\n self.mount += 1;\n self.view = None;\n self.phase = Phase::Closed;\n self.outbox.retain(|r| !matches!(r, Request::Step { .. } | Request::Call { .. } | Request::View { .. }));\n }\n\n pub fn current_mount(&self) -> u64 {\n self.mount\n }\n\n fn fail(&mut self, message: String) {\n let module = self.view.as_ref().map(|v| v.module.clone()).unwrap_or_else(|| match &self.phase {\n Phase::Loading { module } | Phase::Failed { module, .. } => module.clone(),\n _ => String::new(),\n });\n self.view = None;\n self.mount += 1;\n self.phase = Phase::Failed { module, message };\n }\n\n /// `make.view` answered (its output: `{ module, version, view: { title } | null, actions }`).\n pub fn viewed(&mut self, mount: u64, answer: Result<Value, String>) {\n if mount != self.mount || !matches!(self.phase, Phase::Loading { .. }) {\n return;\n }\n let output = match answer {\n Ok(o) => o,\n Err(message) => return self.fail(message),\n };\n let Phase::Loading { module } = &self.phase else { return };\n let module = module.clone();\n let title = output.pointer(\"/view/title\").and_then(Value::as_str).map(str::to_owned);\n let version = output.get(\"version\").and_then(Value::as_str).map(str::to_owned);\n let (Some(title), Some(version)) = (title, version) else {\n return self.fail(format!(\"{module} has no view\"));\n };\n let actions = output\n .get(\"actions\")\n .and_then(Value::as_array)\n .map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect())\n .unwrap_or_default();\n self.view = Some(View {\n mount,\n instance: (self.ids)(),\n module,\n version,\n title,\n actions,\n state: Value::Null,\n tree: MakeViewNode::Null,\n fields: Fields::default(),\n queue: VecDeque::new(),\n in_flight: false,\n steps: 0,\n calls: 0,\n results: 0,\n });\n self.phase = Phase::Shown;\n // Opening runs only `init`.\n self.send(Value::Null);\n }\n\n /// Queues one step's message (`null` for `init`): steps run one at a time, each from the state the one before\n /// returned.\n pub fn send(&mut self, message: Value) {\n let Some(view) = self.view.as_mut() else { return };\n if message.get(\"type\").and_then(Value::as_str) == Some(\"result\") {\n view.results += 1;\n }\n view.queue.push_back(message);\n self.pump();\n }\n\n fn pump(&mut self) {\n let Some(view) = self.view.as_mut() else { return };\n if view.in_flight {\n return;\n }\n let Some(message) = view.queue.pop_front() else { return };\n view.in_flight = true;\n self.outbox.push(Request::Step {\n mount: view.mount,\n module: view.module.clone(),\n version: view.version.clone(),\n state: view.state.clone(),\n message,\n });\n }\n\n /// `make.renderView` answered (its output, a `MakeViewStep`).\n pub fn stepped(&mut self, mount: u64, answer: Result<Value, String>) {\n let Some(view) = self.view.as_mut().filter(|v| v.mount == mount) else { return };\n view.in_flight = false;\n let output = match answer {\n Ok(o) => o,\n Err(message) => return self.fail(message),\n };\n if serde_json::to_vec(&output).map_or(true, |b| b.len() > MAX_STEP_BYTES) {\n return self.fail(\"The view's step is too large\".into());\n }\n if !output.get(\"tree\").is_some_and(within_bounds) {\n return self.fail(format!(\"The view's tree has more than {MAX_NODES} nodes or {MAX_DEPTH} levels\"));\n }\n let step: MakeViewStep = match serde_json::from_value(output) {\n Ok(s) => s,\n Err(e) => return self.fail(format!(\"The view's step is not a view tree: {e}\")),\n };\n let Some(view) = self.view.as_mut() else { return };\n view.steps += 1;\n view.state = step.state;\n view.fields.rebuild(&step.tree);\n view.tree = step.tree;\n let mut refused = Vec::new();\n for call in step.calls {\n if view.actions.iter().any(|a| a == &call.action) {\n let key = match call.key.as_deref().filter(|k| valid_key(k)) {\n Some(k) => format!(\"make-view:{}:{k}\", view.instance),\n None => format!(\"make-view:{}:{}\", view.instance, crate::random_uuid()),\n };\n let input = if call.input.is_null() { json!({}) } else { call.input };\n view.calls += 1;\n self.outbox.push(Request::Call { mount, id: call.id, action: call.action, input, key });\n } else {\n refused.push(json!({\n \"type\": \"result\",\n \"id\": call.id,\n \"ok\": false,\n \"error\": { \"_tag\": \"Forbidden\", \"message\": format!(\"The view may not call {}\", call.action) },\n }));\n }\n }\n for message in refused {\n self.send(message);\n }\n self.pump();\n }\n\n /// A call answered: its result envelope, or its error (`{ _tag, message, ... }`).\n pub fn called(&mut self, mount: u64, id: String, answer: Result<Value, Value>) {\n if self.view.as_ref().is_none_or(|v| v.mount != mount) {\n return;\n }\n let message = match answer {\n Ok(result) => json!({ \"type\": \"result\", \"id\": id, \"ok\": true, \"result\": result }),\n Err(error) => json!({ \"type\": \"result\", \"id\": id, \"ok\": false, \"error\": error_message(&error) }),\n };\n self.send(message);\n }\n\n /// The person activated the button or link at `key`.\n pub fn activate(&mut self, key: &str) {\n let Some(view) = self.view.as_ref() else { return };\n let Some((on, data, form)) = render::control(&view.tree, key) else { return };\n let mut message =\n json!({ \"type\": \"event\", \"name\": on, \"fields\": Value::Object(view.fields.collect(form.as_deref())) });\n if let Some(d) = data {\n message[\"data\"] = d;\n }\n self.send(message);\n }\n\n /// The field at `key` changed: a watched one (`on`) reports it with its value.\n pub fn changed(&mut self, key: &str) {\n let Some(view) = self.view.as_ref() else { return };\n let Some(field) = view.fields.field(key) else { return };\n let Some((on, data)) = field.on.clone() else { return };\n let value = view.fields.event_value(field);\n let form = field.form.clone();\n let mut message = json!({ \"type\": \"event\", \"name\": on, \"value\": value, \"fields\": Value::Object(view.fields.collect(form.as_deref())) });\n if let Some(d) = data {\n message[\"data\"] = d;\n }\n self.send(message);\n }\n\n /// The person toggled the checkbox, chose the radio button or option, or stepped the range at `key`.\n pub fn input(&mut self, key: &str, change: Change) {\n let Some(view) = self.view.as_mut() else { return };\n let Some(field) = view.fields.field(key).cloned() else { return };\n if field.disabled {\n return;\n }\n match (change, &field.kind) {\n (Change::Toggle, Kind::Checkbox) => {\n view.fields.toggle(key);\n }\n (Change::Toggle, Kind::Radio { .. }) => {\n if view.fields.values.get(key) == Some(&fields::FieldValue::Bool(true)) {\n return;\n }\n view.fields.choose_radio(key);\n }\n (Change::Choose(option), Kind::Select { options }) => {\n if !options.contains(&option) {\n return;\n }\n view.fields.set(key, fields::FieldValue::Text(option));\n }\n (Change::Step(steps), Kind::Range { min, max, step }) => {\n let now =\n view.fields.values.get(key).map(|v| v.text()).and_then(|t| t.parse::<f64>().ok()).unwrap_or(*min);\n let next = (now + f64::from(steps) * step).clamp(*min, *max);\n view.fields.set(key, fields::FieldValue::Text(fields::js_number(next)));\n }\n (Change::Edited, Kind::Line { .. } | Kind::Area { .. }) => view.fields.edited(key),\n _ => return,\n }\n self.changed(key);\n }\n\n /// The editor of the text field at `key` (the scratch one when it is gone).\n pub fn edit(&mut self, key: &str) -> &mut TextEdit {\n match self.view.as_mut().and_then(|v| v.fields.edits.get_mut(key)) {\n Some(edit) => edit,\n None => &mut self.scratch,\n }\n }\n}\n\n/// A field change from the person.\n#[derive(Clone, Debug, PartialEq)]\npub enum Change {\n Toggle,\n Choose(String),\n Step(i32),\n Edited,\n}\n\n/// `MAKE_VIEW_KEY`: 1 to 128 of `A-Za-z0-9_-`.\npub fn valid_key(key: &str) -> bool {\n (1..=128).contains(&key.len()) && key.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')\n}\n",
162
+ "type": "registry:file",
163
+ "target": "desktop-rune/app/src/make/mod.rs"
164
+ },
165
+ {
166
+ "path": "app/desktop-rune/app/src/make/render.rs",
167
+ "content": "//! The tree, drawn with Rune elements. The vocabulary is closed (the contract's tags and props, decoded into\n//! generated types before anything is drawn), and nothing here names a URL, loads anything or runs code.\n//!\n//! | Tag | Native |\n//! | --- | --- |\n//! | `div` `section` `header` `footer` `p` `label` `li` `td` `th` `thead` `tbody` | a column of its children; runs of text-level children (text, `span` `strong` `em` `small` `code` `br`) become one wrapped paragraph |\n//! | `h1`–`h4` | a heading (role `heading`, its level) |\n//! | `ul` `ol` | a list (role `list`), each `li` with a bullet or its number |\n//! | `table` `tr` `th` `td` | rows of equal-width cells (roles `table`, `row`, `columnheader`, `cell`); `colspan` and `rowspan` ignored |\n//! | `pre` | monospaced text, its whitespace kept |\n//! | `hr` | a separator |\n//! | `form` | a group (role `form`) whose fields a control inside it sends; never submitted |\n//! | `button` `link` | a focusable control (role `button` or `link`) that sends its `on` event; no URL, ever |\n//! | `input` | a text field (`text` `email` `search` `tel` `date` `time` `datetime-local` `color`, and `number` keeping to a number's characters), a checkbox, a radio button, a slider (`range`), or nothing (`hidden`, still a field) |\n//! | `textarea` | a multi-line text field |\n//! | `select` `option` | a list box of its options (role `listbox`, each `option`) |\n//!\n//! `class` is inert, as on the web. `title` describes its element. `style` is [`super::style`]'s subset.\n\nuse eloxiv_local_client::{MakeViewElement, MakeViewElementTag as Tag, MakeViewNode};\nuse rune::tok::{Theme, type_};\nuse rune::{Align, Color, Direction, El, Span, TextStyle, col, el, rich, row, text, text_input};\nuse serde_json::Value;\n\nuse super::fields::{self, FieldValue, Kind, key_of, prop_text, prop_true, text_of};\nuse super::style::{self, Axis, Display, Length, Paint, Place, TextAlign};\nuse super::{Change, Host, View};\n\n/// The colours a view is drawn in: the app's theme, for the ThemeTokens names a `var(...)` may use.\n#[derive(Clone, Copy, Debug)]\npub struct Palette {\n pub background: Color,\n pub foreground: Color,\n pub muted: Color,\n pub card: Color,\n pub border: Color,\n pub input: Color,\n pub primary: Color,\n pub primary_foreground: Color,\n pub secondary: Color,\n pub secondary_foreground: Color,\n pub accent: Color,\n pub destructive: Color,\n pub ring: Color,\n}\n\nimpl Palette {\n pub fn new(dark: bool) -> Palette {\n let t: Theme = rune::tok::theme(dark);\n let accent = rune::tok::accent(0, dark);\n Palette {\n background: t.bg,\n foreground: t.text,\n muted: t.text_secondary,\n card: t.card,\n border: t.text_secondary.alpha(0.45),\n input: t.text_secondary.alpha(0.6),\n primary: accent,\n primary_foreground: Color::WHITE,\n secondary: t.control_off,\n secondary_foreground: t.text,\n accent,\n destructive: rune::oklch(0.62, 0.2, 25.0),\n ring: accent,\n }\n }\n\n fn token(&self, name: &str) -> Option<Color> {\n Some(match name {\n \"background\" | \"popover\" => self.background,\n \"foreground\" | \"card-foreground\" | \"popover-foreground\" | \"accent-foreground\" | \"secondary-foreground\" => {\n self.foreground\n }\n \"card\" => self.card,\n \"primary\" => self.primary,\n \"primary-foreground\" | \"destructive-foreground\" => self.primary_foreground,\n \"secondary\" | \"muted\" => self.secondary,\n \"muted-foreground\" => self.muted,\n \"accent\" => self.accent,\n \"destructive\" => self.destructive,\n \"border\" => self.border,\n \"input\" => self.input,\n \"ring\" => self.ring,\n _ => return None,\n })\n }\n\n pub fn paint(&self, p: &Paint) -> Option<Color> {\n match p {\n Paint::Token(name) => self.token(name),\n Paint::Rgba([r, g, b, a]) => {\n let hex = format!(\n \"#{:02x}{:02x}{:02x}\",\n (r * 255.0).round() as u8,\n (g * 255.0).round() as u8,\n (b * 255.0).round() as u8\n );\n rune::color::hex(&hex).map(|c| c.alpha(*a))\n }\n }\n }\n}\n\n/// What a subtree inherits from its ancestors (CSS's inherited properties, as far as the subset goes).\n#[derive(Clone, Copy)]\nstruct Inherit {\n color: Color,\n font: TextStyle,\n italic: bool,\n mono: bool,\n align: Option<TextAlign>,\n pre: bool,\n}\n\nstruct Cx<'a, S: 'static> {\n view: &'a View,\n lens: fn(&mut S) -> &mut Host,\n palette: Palette,\n rtl: bool,\n}\n\n/// The view's tree as Rune elements, in a group named by its title, in `direction`.\npub fn view<S: 'static>(view: &View, lens: fn(&mut S) -> &mut Host, palette: Palette, direction: Direction) -> El {\n let cx = Cx { view, lens, palette, rtl: direction == Direction::Rtl };\n let inherit =\n Inherit { color: palette.foreground, font: type_::BODY, italic: false, mono: false, align: None, pre: false };\n let body = node(&cx, &view.tree, &mut Vec::new(), inherit).unwrap_or_else(|| el().key(\"mk:empty\"));\n col()\n .key(\"make-view\")\n .role(\"group\")\n .label(view.title.clone())\n .dir(direction)\n .w_full()\n .padding(8.0)\n .gap(6.0)\n .child(body)\n}\n\nfn is_inline(node: &MakeViewNode) -> bool {\n match node {\n MakeViewNode::String(_) | MakeViewNode::Number(_) => true,\n MakeViewNode::Null | MakeViewNode::Boolean(_) => true,\n MakeViewNode::MakeViewElement(e) => {\n matches!(e.tag, Tag::Span | Tag::Strong | Tag::Em | Tag::Small | Tag::Code | Tag::Br)\n && e.children.iter().all(is_inline)\n }\n }\n}\n\nfn node<S: 'static>(cx: &Cx<'_, S>, n: &MakeViewNode, path: &mut Vec<usize>, inherit: Inherit) -> Option<El> {\n match n {\n MakeViewNode::Null | MakeViewNode::Boolean(_) => None,\n MakeViewNode::String(_) | MakeViewNode::Number(_) => {\n paragraph(cx, std::slice::from_ref(n), &key_of(path), inherit)\n }\n MakeViewNode::MakeViewElement(e) => element(cx, e, path, inherit),\n }\n}\n\nfn element<S: 'static>(cx: &Cx<'_, S>, e: &MakeViewElement, path: &mut Vec<usize>, inherit: Inherit) -> Option<El> {\n let key = key_of(path);\n let st = prop_text(e, \"style\").map(|s| style::parse(&s)).unwrap_or_default();\n if st.display == Some(Display::None) {\n return None;\n }\n let mut inherit = inherit;\n if let Some(c) = st.color.as_ref().and_then(|p| cx.palette.paint(p)) {\n inherit.color = c;\n }\n if let Some(w) = st.weight {\n inherit.font.weight = w;\n }\n if let Some(s) = st.size {\n inherit.font.size = s;\n inherit.font.line_height = 0.0;\n }\n if let Some(i) = st.italic {\n inherit.italic = i;\n }\n if st.align.is_some() {\n inherit.align = st.align;\n }\n let built = match e.tag {\n Tag::Button | Tag::Link => Some(draw_control(cx, e, &key, inherit)),\n Tag::Input | Tag::Textarea | Tag::Select => field(cx, e, &key, inherit),\n Tag::Option => None,\n Tag::Hr => Some(el().key(key.clone()).role(\"separator\").h(1.0).w_full().fill(cx.palette.border)),\n Tag::Br => Some(el().key(key.clone()).h(inherit.font.size)),\n Tag::Span | Tag::Strong | Tag::Em | Tag::Small | Tag::Code\n if is_inline(&MakeViewNode::MakeViewElement(e.clone())) =>\n {\n paragraph(cx, std::slice::from_ref(&MakeViewNode::MakeViewElement(e.clone())), &key, inherit)\n }\n _ => Some(container(cx, e, path, &key, inherit, &st)),\n }?;\n let mut built = apply_box(built, &st, &cx.palette, cx.rtl);\n if let Some(title) = prop_text(e, \"title\").filter(|t| !t.is_empty()) {\n built = built.description(title);\n }\n Some(built)\n}\n\nfn container<S: 'static>(\n cx: &Cx<'_, S>,\n e: &MakeViewElement,\n path: &mut Vec<usize>,\n key: &str,\n mut inherit: Inherit,\n st: &style::Style,\n) -> El {\n let horizontal = e.tag == Tag::Tr || (st.display == Some(Display::Flex) && st.direction != Some(Axis::Column));\n let mut out = if horizontal { row() } else { col() }.key(key.to_owned());\n out = match e.tag {\n Tag::H1 | Tag::H2 | Tag::H3 | Tag::H4 => {\n let (size, level) = match e.tag {\n Tag::H1 => (24.0, 1),\n Tag::H2 => (20.0, 2),\n Tag::H3 => (17.0, 3),\n _ => (15.0, 4),\n };\n if st.size.is_none() {\n inherit.font = TextStyle::new(size, inherit.font.weight.max(650.0));\n }\n out.role(\"heading\").level(level).label(text_of(&MakeViewNode::MakeViewElement(e.clone())).trim().to_owned())\n }\n Tag::Ul | Tag::Ol => out.role(\"list\").gap(2.0),\n Tag::Li => out.role(\"listitem\"),\n Tag::Table => out.role(\"table\").gap(0.0),\n Tag::Thead | Tag::Tbody => out.role(\"rowgroup\").gap(0.0),\n Tag::Tr => out.role(\"row\").gap(0.0).w_full(),\n Tag::Th => {\n inherit.font.weight = inherit.font.weight.max(600.0);\n out.role(\"columnheader\").grow(1.0).px(8.0).py(4.0)\n }\n Tag::Td => out.role(\"cell\").grow(1.0).px(8.0).py(4.0),\n Tag::Form => out.role(\"form\").gap(6.0),\n Tag::Pre => {\n inherit.mono = true;\n inherit.pre = true;\n out\n }\n Tag::Code => {\n inherit.mono = true;\n out\n }\n _ => out.gap(4.0),\n };\n if horizontal {\n out = out.gap(st.gap.unwrap_or(if e.tag == Tag::Tr { 0.0 } else { 6.0 }));\n } else if let Some(g) = st.gap {\n out = out.gap(g);\n }\n out = place(out, st);\n let ordered = e.tag == Tag::Ol;\n let mut items = 0;\n let mut run: Vec<MakeViewNode> = Vec::new();\n let mut run_start = 0;\n let flush = |out: El, run: &mut Vec<MakeViewNode>, start: usize| -> El {\n if run.is_empty() {\n return out;\n }\n let k = format!(\"{key}~t{start}\");\n let p = paragraph(cx, run, &k, inherit);\n run.clear();\n match p {\n Some(p) => out.child(p),\n None => out,\n }\n };\n for (i, child) in e.children.iter().enumerate() {\n if is_inline(child) {\n if run.is_empty() {\n run_start = i;\n }\n run.push(child.clone());\n continue;\n }\n out = flush(out, &mut run, run_start);\n path.push(i);\n let drawn = node(cx, child, path, inherit);\n path.pop();\n let Some(mut drawn) = drawn else { continue };\n if matches!(e.tag, Tag::Ul | Tag::Ol) && matches!(child, MakeViewNode::MakeViewElement(c) if c.tag == Tag::Li) {\n items += 1;\n let marker = if ordered { format!(\"{items}.\") } else { \"•\".to_owned() };\n drawn = row()\n .key(format!(\"{}~li\", key_of(&[path.as_slice(), &[i]].concat())))\n .gap(6.0)\n .child(text(marker).font(inherit.font).color(inherit.color).a11y_hidden())\n .child(drawn.grow(1.0));\n }\n out = out.child(drawn);\n }\n flush(out, &mut run, run_start)\n}\n\nfn place(mut out: El, st: &style::Style) -> El {\n out = match st.align_items {\n Some(Place::Center) => out.items_center(),\n Some(Place::End) => out.items_end(),\n Some(Place::Start) => out.items_start(),\n Some(Place::Stretch) => out.items_stretch(),\n _ => out,\n };\n match st.justify {\n Some(Place::Center) => out.justify_center(),\n Some(Place::End) => out.justify_end(),\n Some(Place::Between) => out.justify_between(),\n Some(Place::Around) => out.justify_around(),\n Some(Place::Evenly) => out.justify_evenly(),\n Some(Place::Start) => out.justify_start(),\n _ => out,\n }\n}\n\n/// Margins, padding, borders, sizes, background and opacity. CSS's `left` and `right` are physical, Rune's sides\n/// logical: in a right-to-left view they swap.\nfn apply_box(mut out: El, st: &style::Style, palette: &Palette, rtl: bool) -> El {\n let (start, end) = if rtl { (1, 3) } else { (3, 1) };\n if let Some(v) = st.margin[0] {\n out = out.mt(v);\n }\n if let Some(v) = st.margin[2] {\n out = out.mb(v);\n }\n if let Some(v) = st.margin[start] {\n out = out.ml(v);\n }\n if let Some(v) = st.margin[end] {\n out = out.mr(v);\n }\n if let Some(v) = st.padding[0] {\n out = out.pt(v);\n }\n if let Some(v) = st.padding[2] {\n out = out.pb(v);\n }\n if let Some(v) = st.padding[start] {\n out = out.pl(v);\n }\n if let Some(v) = st.padding[end] {\n out = out.pr(v);\n }\n if let Some(bg) = st.background.as_ref().and_then(|p| palette.paint(p)) {\n out = out.fill(bg);\n }\n if let Some(w) = st.border_width.filter(|w| *w > 0.0) {\n let c = st.border_color.as_ref().and_then(|p| palette.paint(p)).unwrap_or(palette.border);\n out = out.border(w, c);\n }\n if let Some(r) = st.radius {\n out = out.radius(r);\n }\n out = match st.width {\n Some(Length::Points(p)) => out.w(p),\n Some(Length::Percent(p)) if p >= 100.0 => out.w_full(),\n _ => out,\n };\n out = match st.height {\n Some(Length::Points(p)) => out.h(p),\n Some(Length::Percent(p)) if p >= 100.0 => out.h_full(),\n _ => out,\n };\n if let Some(v) = st.min_width {\n out = out.min_w(v);\n }\n if let Some(v) = st.max_width {\n out = out.max_w(v);\n }\n if let Some(v) = st.min_height {\n out = out.min_h(v);\n }\n if let Some(v) = st.max_height {\n out = out.max_h(v);\n }\n if let Some(o) = st.opacity {\n out = out.opacity(o);\n }\n out\n}\n\n/// HTML's whitespace collapsing outside `pre`.\nfn collapse(text: &str, last_space: &mut bool) -> String {\n let mut out = String::with_capacity(text.len());\n for c in text.chars() {\n if c.is_whitespace() {\n if !*last_space {\n out.push(' ');\n }\n *last_space = true;\n } else {\n out.push(c);\n *last_space = false;\n }\n }\n out\n}\n\nstruct Runs {\n text: String,\n spans: Vec<Span>,\n last_space: bool,\n}\n\nfn inline<S: 'static>(cx: &Cx<'_, S>, n: &MakeViewNode, inherit: Inherit, base: &Inherit, runs: &mut Runs) {\n let push = |runs: &mut Runs, s: &str, inh: &Inherit| {\n let piece = if inh.pre { s.to_owned() } else { collapse(s, &mut runs.last_space) };\n if piece.is_empty() {\n return;\n }\n let start = runs.text.len();\n runs.text.push_str(&piece);\n let end = runs.text.len();\n let differs = inh.color != base.color\n || inh.font.weight != base.font.weight\n || inh.font.size != base.font.size\n || inh.italic != base.italic\n || inh.mono != base.mono;\n if differs {\n let mut span = Span::new(start, end);\n if inh.font.weight != base.font.weight {\n span = span.weight(inh.font.weight);\n }\n if inh.font.size != base.font.size {\n span = span.size(inh.font.size);\n }\n if inh.color != base.color {\n span = span.color(inh.color);\n }\n if inh.italic {\n span = span.italic();\n }\n if inh.mono {\n span = span.mono();\n }\n runs.spans.push(span);\n }\n };\n match n {\n MakeViewNode::String(s) => push(runs, s, &inherit),\n MakeViewNode::Number(x) => push(runs, &fields::js_number(*x), &inherit),\n MakeViewNode::MakeViewElement(e) => {\n let st = prop_text(e, \"style\").map(|s| style::parse(&s)).unwrap_or_default();\n if st.display == Some(Display::None) {\n return;\n }\n let mut inh = inherit;\n match e.tag {\n Tag::Br => {\n runs.text.push('\\n');\n runs.last_space = true;\n return;\n }\n Tag::Strong => inh.font.weight = inh.font.weight.max(700.0),\n Tag::Em => inh.italic = true,\n Tag::Small => inh.font.size = (inh.font.size * 0.85).round(),\n Tag::Code => inh.mono = true,\n _ => {}\n }\n if let Some(c) = st.color.as_ref().and_then(|p| cx.palette.paint(p)) {\n inh.color = c;\n }\n if let Some(w) = st.weight {\n inh.font.weight = w;\n }\n if let Some(s) = st.size {\n inh.font.size = s;\n }\n if let Some(i) = st.italic {\n inh.italic = i;\n }\n for c in &e.children {\n inline(cx, c, inh, base, runs);\n }\n }\n _ => {}\n }\n}\n\n/// A run of text-level nodes as one wrapped paragraph.\nfn paragraph<S: 'static>(cx: &Cx<'_, S>, nodes: &[MakeViewNode], key: &str, inherit: Inherit) -> Option<El> {\n let mut runs = Runs { text: String::new(), spans: Vec::new(), last_space: true };\n for n in nodes {\n inline(cx, n, inherit, &inherit, &mut runs);\n }\n let text = if inherit.pre { runs.text } else { runs.text.trim_end().to_owned() };\n if text.trim().is_empty() {\n return None;\n }\n let mut font = inherit.font;\n if inherit.mono {\n font.family = rune::Family::SystemMono;\n }\n font.italic = inherit.italic;\n let mut p = rich(text, runs.spans).key(key.to_owned()).font(font).color(inherit.color);\n if let Some(a) = inherit.align {\n p = p.align(align(a, cx.rtl));\n }\n Some(p)\n}\n\nfn align(a: TextAlign, rtl: bool) -> Align {\n match (a, rtl) {\n (TextAlign::Center, _) => Align::Center,\n (TextAlign::Start, _) | (TextAlign::Left, false) | (TextAlign::Right, true) => Align::Start,\n (TextAlign::End, _) | (TextAlign::Right, false) | (TextAlign::Left, true) => Align::End,\n }\n}\n\nfn draw_control<S: 'static>(cx: &Cx<'_, S>, e: &MakeViewElement, key: &str, inherit: Inherit) -> El {\n let label = prop_text(e, \"ariaLabel\")\n .or_else(|| {\n Some(text_of(&MakeViewNode::MakeViewElement(e.clone())).trim().to_owned()).filter(|t| !t.is_empty())\n })\n .or_else(|| prop_text(e, \"title\"))\n .unwrap_or_else(|| if e.tag == Tag::Link { \"Link\".into() } else { \"Button\".into() });\n let disabled = prop_true(e, \"disabled\");\n let link = e.tag == Tag::Link;\n let shown = text_of(&MakeViewNode::MakeViewElement(e.clone())).split_whitespace().collect::<Vec<_>>().join(\" \");\n let ink = if link { cx.palette.primary } else { cx.palette.secondary_foreground };\n let shown = if shown.is_empty() { label.clone() } else { shown };\n let underline = if link { vec![Span::new(0, shown.len()).underline(ink)] } else { Vec::new() };\n let face = rich(shown, underline).font(inherit.font).color(ink).a11y_hidden();\n let mut out = row().key(key.to_owned()).role(if link { \"link\" } else { \"button\" }).label(label).center_y();\n out = if link {\n out\n } else {\n out.px(12.0).py(4.0).radius(6.0).fill(cx.palette.secondary).border(1.0, cx.palette.border)\n };\n out = out.child(face);\n if disabled {\n return out.disabled(true).opacity(0.5);\n }\n out = out.focusable(true).hover(cx.palette.foreground.alpha(0.06)).press(cx.palette.foreground.alpha(0.12));\n if e.on.is_some() {\n let (lens, k) = (cx.lens, key.to_owned());\n out = out.on_press(move |s: &mut S| lens(s).activate(&k));\n }\n out\n}\n\nfn field<S: 'static>(cx: &Cx<'_, S>, e: &MakeViewElement, key: &str, inherit: Inherit) -> Option<El> {\n let f = cx.view.fields.field(key)?.clone();\n let lens = cx.lens;\n let value = cx.view.fields.values.get(key).cloned();\n let p = cx.palette;\n let disabled = f.disabled;\n let out = match &f.kind {\n Kind::Hidden => return None,\n Kind::Line { .. } | Kind::Area { .. } => {\n let edit = cx.view.fields.edits.get(key)?;\n let mut input = text_input(edit, inherit.font)\n .key(key.to_owned())\n .label(f.label.clone())\n .color(p.foreground)\n .px(8.0)\n .py(5.0)\n .radius(6.0)\n .border(1.0, p.input)\n .fill(p.background)\n .w_full();\n if let Some(ph) = prop_text(e, \"placeholder\") {\n input = input.placeholder(ph, p.muted);\n }\n if let Kind::Area { rows } = f.kind {\n input = input.min_h(rows as f32 * inherit.font.size * 1.4 + 10.0);\n } else {\n input = input.single_line();\n }\n if disabled {\n input.disabled(true).read_only(true).opacity(0.6)\n } else {\n let (k1, k2) = (key.to_owned(), key.to_owned());\n input\n .on_edit(move |s: &mut S| lens(s).edit(&k1))\n .on_input_change(move |s: &mut S, _| lens(s).input(&k2, Change::Edited))\n }\n }\n Kind::Checkbox | Kind::Radio { .. } => {\n let on = value == Some(FieldValue::Bool(true));\n let radio = matches!(f.kind, Kind::Radio { .. });\n let mut mark =\n el().size(16.0, 16.0).radius(if radio { 8.0 } else { 4.0 }).border(1.5, p.input).a11y_hidden();\n if on {\n mark = mark.fill(p.primary).border(1.5, p.primary);\n }\n let mut out = row()\n .key(key.to_owned())\n .role(if radio { \"radio\" } else { \"checkbox\" })\n .label(f.label.clone())\n .checked(on)\n .gap(6.0)\n .center_y()\n .child(mark);\n if disabled {\n out = out.disabled(true).opacity(0.6);\n } else {\n let k = key.to_owned();\n out = out.focusable(true).on_press(move |s: &mut S| lens(s).input(&k, Change::Toggle));\n }\n out\n }\n Kind::Range { min, max, step } => {\n let now = value.map(|v| v.text()).and_then(|t| t.parse::<f64>().ok()).unwrap_or(*min);\n let share = if max > min { ((now - min) / (max - min)) as f32 } else { 0.0 };\n let mut out = el()\n .key(key.to_owned())\n .role(\"slider\")\n .label(f.label.clone())\n .range_value(now, *min, *max)\n .range_step(*step)\n .a11y_value(fields::js_number(now))\n .size(180.0, 18.0)\n .child(el().size(180.0, 4.0).absolute(0.0, 7.0).radius(2.0).fill(p.secondary).a11y_hidden())\n .child(el().size(180.0 * share, 4.0).absolute(0.0, 7.0).radius(2.0).fill(p.primary).a11y_hidden());\n if disabled {\n out = out.disabled(true).opacity(0.6);\n } else {\n let k = key.to_owned();\n out = out.focusable(true).on_step(move |s: &mut S, steps, _| lens(s).input(&k, Change::Step(steps)));\n }\n out\n }\n Kind::Select { options } => {\n let chosen = value.map(|v| v.text()).unwrap_or_default();\n let mut list = col()\n .key(key.to_owned())\n .role(\"listbox\")\n .label(f.label.clone())\n .focus_group()\n .radius(6.0)\n .border(1.0, p.input)\n .padding(2.0);\n for (i, option) in options.iter().enumerate() {\n let selected = *option == chosen;\n let mut row_ = row()\n .key(format!(\"{key}~o{i}\"))\n .role(\"option\")\n .label(option.clone())\n .focus_selected(selected)\n .px(8.0)\n .py(3.0)\n .radius(4.0)\n .child(text(option.clone()).font(inherit.font).color(p.foreground).a11y_hidden());\n if selected {\n row_ = row_.fill(p.primary.alpha(0.18));\n }\n if disabled {\n row_ = row_.disabled(true);\n } else {\n let (k, o) = (key.to_owned(), option.clone());\n row_ = row_.focusable(true).on_press(move |s: &mut S| lens(s).input(&k, Change::Choose(o.clone())));\n }\n list = list.child(row_);\n }\n if disabled { list.disabled(true).opacity(0.6) } else { list }\n }\n };\n Some(out)\n}\n\nfn path_of(key: &str) -> Option<Vec<usize>> {\n let rest = key.strip_prefix(\"mk:\")?;\n if rest == \"r\" {\n return Some(Vec::new());\n }\n rest.split('.').map(|p| p.parse().ok()).collect()\n}\n\n/// The control at `key`, if it is an enabled `button` or `link` with `on`: its event, data and nearest form.\npub fn control(tree: &MakeViewNode, key: &str) -> Option<(String, Option<Value>, Option<String>)> {\n let path = path_of(key)?;\n let mut node = tree;\n let mut form = None;\n let mut walked = Vec::new();\n for i in &path {\n let MakeViewNode::MakeViewElement(e) = node else { return None };\n if e.tag == Tag::Form {\n form = Some(key_of(&walked));\n }\n node = e.children.get(*i)?;\n walked.push(*i);\n }\n let MakeViewNode::MakeViewElement(e) = node else { return None };\n if !matches!(e.tag, Tag::Button | Tag::Link) || prop_true(e, \"disabled\") {\n return None;\n }\n Some((e.on.clone()?, e.data.clone(), form))\n}\n",
168
+ "type": "registry:file",
169
+ "target": "desktop-rune/app/src/make/render.rs"
170
+ },
171
+ {
172
+ "path": "app/desktop-rune/app/src/make/style.rs",
173
+ "content": "//! A MAKE view's `style`, natively.\n//!\n//! First the web host's filter, exactly (`safeStyle` in shell-foldkit's `makeView.ts`): a style over 4,000\n//! characters is dropped whole; each declaration must name one of the web's properties and have a plain value\n//! of 1 to 200 characters (words, numbers, units, `#`, `%`, `.`, `,`, `(`, `)`, `/`; no quotes, escapes, colons\n//! or URLs), calling only `rgb rgba hsl hsla calc min max clamp repeat minmax var`, with `var(...)` naming only\n//! a theme variable. Then the **native subset**, mapped to Rune; every other property, and every value the\n//! subset does not read (a `calc()`, a unit other than `px`, `rem`, `em` or `%`), is ignored:\n//!\n//! | Property | Native |\n//! | --- | --- |\n//! | `color`, `background-color` | `#rgb`, `#rrggbb`, `#rrggbbaa`, `rgb()`/`rgba()` with numbers, `transparent`, a few names, `var(--<theme colour>)` |\n//! | `font-weight` | `normal`, `bold`, `100`–`900` |\n//! | `font-style` | `italic`, `oblique`, `normal` |\n//! | `font-size` | a length |\n//! | `text-align` | `left`, `right` (physical: mirrored in a right-to-left view), `center`, `start`, `end` |\n//! | `margin`, `padding` (1–4 values) and their `-top`, `-right`, `-bottom`, `-left` | lengths; `left` and `right` are physical |\n//! | `border` (`<width> <style> <colour>` in any order), `border-width`, `border-color`, `border-radius` | one width, one colour, one radius |\n//! | `display` | `flex` (a row unless `flex-direction` says otherwise), `none` (not drawn), others as blocks |\n//! | `flex-direction`, `gap`, `align-items`, `justify-content` | on a `display: flex` element |\n//! | `width`, `height`, `min-*`, `max-*` | a length; `100%` fills the parent |\n//! | `opacity` | a number from 0 to 1 |\n//!\n//! Lengths (counted, as the web counts them, in UTF-16 units for the limits) are CSS pixels taken as points (`1rem` and `1em` are 14, the frame's base font size).\n\n/// The web host's property allow-list (`STYLE_PROPERTIES`).\npub const WEB_PROPERTIES: &[&str] = &[\n \"color\",\n \"background-color\",\n \"font-weight\",\n \"font-style\",\n \"font-size\",\n \"text-align\",\n \"text-decoration\",\n \"text-transform\",\n \"line-height\",\n \"letter-spacing\",\n \"white-space\",\n \"vertical-align\",\n \"list-style-type\",\n \"margin\",\n \"margin-top\",\n \"margin-right\",\n \"margin-bottom\",\n \"margin-left\",\n \"padding\",\n \"padding-top\",\n \"padding-right\",\n \"padding-bottom\",\n \"padding-left\",\n \"border\",\n \"border-top\",\n \"border-right\",\n \"border-bottom\",\n \"border-left\",\n \"border-color\",\n \"border-width\",\n \"border-style\",\n \"border-radius\",\n \"border-collapse\",\n \"display\",\n \"flex\",\n \"flex-direction\",\n \"flex-wrap\",\n \"align-items\",\n \"justify-content\",\n \"gap\",\n \"grid-template-columns\",\n \"width\",\n \"min-width\",\n \"max-width\",\n \"height\",\n \"min-height\",\n \"max-height\",\n \"opacity\",\n \"overflow\",\n];\n\nconst FUNCTIONS: &[&str] = &[\"rgb\", \"rgba\", \"hsl\", \"hsla\", \"calc\", \"min\", \"max\", \"clamp\", \"repeat\", \"minmax\", \"var\"];\n\n/// The ThemeTokens colour variables (and the few others) a `var(...)` may name (`MAKE_VIEW_THEME_VARIABLES`).\npub const THEME_VARIABLES: &[&str] = &[\n \"--background\",\n \"--foreground\",\n \"--card\",\n \"--card-foreground\",\n \"--popover\",\n \"--popover-foreground\",\n \"--primary\",\n \"--primary-foreground\",\n \"--secondary\",\n \"--secondary-foreground\",\n \"--muted\",\n \"--muted-foreground\",\n \"--accent\",\n \"--accent-foreground\",\n \"--destructive\",\n \"--destructive-foreground\",\n \"--border\",\n \"--input\",\n \"--ring\",\n \"--radius\",\n \"--spacing\",\n \"--font-sans\",\n \"--font-mono\",\n];\n\npub const STYLE_MAX: usize = 4_000;\npub const VALUE_MAX: usize = 200;\n/// The frame's base font size, in points: what `1rem` and `1em` are.\npub const BASE_FONT: f32 = 14.0;\n\nfn plain(value: &str) -> bool {\n value.chars().all(|c| {\n c.is_ascii_alphanumeric()\n || c == '_'\n || c.is_whitespace()\n || matches!(c, '-' | '#' | '%' | '.' | ',' | '(' | ')' | '/')\n })\n}\n\nfn calls_only_allowed(value: &str) -> bool {\n let (mut name, mut after_name) = (String::new(), false);\n for c in value.chars() {\n if c.is_ascii_alphabetic() || c == '-' {\n if after_name {\n name.clear();\n }\n after_name = false;\n name.push(c);\n } else if c == ' ' || c == '\\t' || c == '\\n' {\n if !name.is_empty() {\n after_name = true;\n }\n } else if c == '(' {\n if !name.is_empty() && !FUNCTIONS.contains(&name.to_ascii_lowercase().as_str()) {\n return false;\n }\n name.clear();\n after_name = false;\n } else {\n name.clear();\n after_name = false;\n }\n }\n true\n}\n\nfn vars_only_theme(value: &str) -> bool {\n let lower = value.to_ascii_lowercase();\n let mut rest = lower.as_str();\n while let Some(at) = rest.find(\"var\") {\n let after = rest[at + 3..].trim_start();\n if let Some(inner) = after.strip_prefix('(') {\n let Some(close) = inner.find(')') else { return false };\n if !THEME_VARIABLES.contains(&inner[..close].trim()) {\n return false;\n }\n rest = &inner[close + 1..];\n } else {\n rest = &rest[at + 3..];\n }\n }\n true\n}\n\n/// The web host's `safeStyle`: the declarations kept, as `(property, value)` in order.\npub fn safe_declarations(style: &str) -> Vec<(String, String)> {\n if style.encode_utf16().count() > STYLE_MAX {\n return Vec::new();\n }\n style\n .split(';')\n .filter_map(|declaration| {\n let (property, value) = declaration.split_once(':')?;\n let property = property.trim().to_ascii_lowercase();\n let value = value.trim();\n let length = value.encode_utf16().count();\n if !WEB_PROPERTIES.contains(&property.as_str()) || length == 0 || length > VALUE_MAX {\n return None;\n }\n if !plain(value) || !calls_only_allowed(value) || !vars_only_theme(value) {\n return None;\n }\n Some((property, value.to_owned()))\n })\n .collect()\n}\n\n/// A colour a declaration names, as sRGB components with alpha (0 to 1), or a theme token.\n#[derive(Clone, Debug, PartialEq)]\npub enum Paint {\n Rgba([f32; 4]),\n Token(String),\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum TextAlign {\n Start,\n Center,\n End,\n /// Physical left and right: mirrored by the renderer in a right-to-left view.\n Left,\n Right,\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum Display {\n Block,\n Flex,\n None,\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum Axis {\n Row,\n Column,\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum Place {\n Start,\n Center,\n End,\n Stretch,\n Between,\n Around,\n Evenly,\n}\n\n/// A length: points, or a share of the parent.\n#[derive(Clone, Copy, Debug, PartialEq)]\npub enum Length {\n Points(f32),\n Percent(f32),\n}\n\nimpl Length {\n pub fn points(self) -> Option<f32> {\n match self {\n Length::Points(p) => Some(p),\n Length::Percent(_) => None,\n }\n }\n}\n\n/// The native subset of one element's `style`.\n#[derive(Clone, Debug, Default, PartialEq)]\npub struct Style {\n pub color: Option<Paint>,\n pub background: Option<Paint>,\n pub weight: Option<f32>,\n pub italic: Option<bool>,\n pub size: Option<f32>,\n pub align: Option<TextAlign>,\n /// Top, right, bottom, left (physical).\n pub margin: [Option<f32>; 4],\n pub padding: [Option<f32>; 4],\n pub border_width: Option<f32>,\n pub border_color: Option<Paint>,\n pub radius: Option<f32>,\n pub display: Option<Display>,\n pub direction: Option<Axis>,\n pub gap: Option<f32>,\n pub align_items: Option<Place>,\n pub justify: Option<Place>,\n pub width: Option<Length>,\n pub height: Option<Length>,\n pub min_width: Option<f32>,\n pub max_width: Option<f32>,\n pub min_height: Option<f32>,\n pub max_height: Option<f32>,\n pub opacity: Option<f32>,\n}\n\npub fn parse_length(value: &str) -> Option<Length> {\n let v = value.trim().to_ascii_lowercase();\n if v == \"0\" {\n return Some(Length::Points(0.0));\n }\n let number = |s: &str| s.parse::<f32>().ok().filter(|n| n.is_finite() && *n >= 0.0 && *n <= 10_000.0);\n if let Some(n) = v.strip_suffix(\"px\") {\n return number(n).map(Length::Points);\n }\n if let Some(n) = v.strip_suffix(\"rem\").or_else(|| v.strip_suffix(\"em\")) {\n return number(n).map(|n| Length::Points(n * BASE_FONT));\n }\n if let Some(n) = v.strip_suffix('%') {\n return number(n).filter(|n| *n <= 100.0).map(Length::Percent);\n }\n None\n}\n\nfn points(value: &str) -> Option<f32> {\n parse_length(value).and_then(Length::points)\n}\n\nfn channel(s: &str) -> Option<f32> {\n let s = s.trim();\n if let Some(p) = s.strip_suffix('%') {\n return p.trim().parse::<f32>().ok().filter(|n| n.is_finite()).map(|n| (n / 100.0).clamp(0.0, 1.0));\n }\n s.parse::<f32>().ok().filter(|n| n.is_finite()).map(|n| (n / 255.0).clamp(0.0, 1.0))\n}\n\npub fn parse_paint(value: &str) -> Option<Paint> {\n let v = value.trim().to_ascii_lowercase();\n if let Some(inner) = v.strip_prefix(\"var(\").and_then(|r| r.strip_suffix(')')) {\n let name = inner.trim();\n return THEME_VARIABLES.contains(&name).then(|| Paint::Token(name.trim_start_matches(\"--\").to_owned()));\n }\n if let Some(hex) = v.strip_prefix('#') {\n let digit = |i: usize, n: usize| u8::from_str_radix(hex.get(i..i + n)?, 16).ok();\n let rgba = match hex.len() {\n 3 => [digit(0, 1)? * 17, digit(1, 1)? * 17, digit(2, 1)? * 17, 255],\n 6 => [digit(0, 2)?, digit(2, 2)?, digit(4, 2)?, 255],\n 8 => [digit(0, 2)?, digit(2, 2)?, digit(4, 2)?, digit(6, 2)?],\n _ => return None,\n };\n return Some(Paint::Rgba(rgba.map(|c| f32::from(c) / 255.0)));\n }\n let function = v.strip_prefix(\"rgba(\").or_else(|| v.strip_prefix(\"rgb(\")).and_then(|r| r.strip_suffix(')'));\n if let Some(inner) = function {\n let parts: Vec<&str> = inner.split([',', '/', ' ']).filter(|p| !p.is_empty()).collect();\n if parts.len() < 3 || parts.len() > 4 {\n return None;\n }\n let alpha = match parts.get(3) {\n Some(a) => {\n let a = a.trim();\n match a.strip_suffix('%') {\n Some(p) => p.parse::<f32>().ok()? / 100.0,\n None => a.parse::<f32>().ok()?,\n }\n }\n None => 1.0,\n };\n if !alpha.is_finite() {\n return None;\n }\n return Some(Paint::Rgba([channel(parts[0])?, channel(parts[1])?, channel(parts[2])?, alpha.clamp(0.0, 1.0)]));\n }\n let named = match v.as_str() {\n \"transparent\" => [0.0, 0.0, 0.0, 0.0],\n \"black\" => [0.0, 0.0, 0.0, 1.0],\n \"white\" => [1.0, 1.0, 1.0, 1.0],\n \"red\" => [1.0, 0.0, 0.0, 1.0],\n \"green\" => [0.0, 128.0 / 255.0, 0.0, 1.0],\n \"blue\" => [0.0, 0.0, 1.0, 1.0],\n \"gray\" | \"grey\" => [128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0],\n \"orange\" => [1.0, 165.0 / 255.0, 0.0, 1.0],\n _ => return None,\n };\n Some(Paint::Rgba(named))\n}\n\nfn place(value: &str) -> Option<Place> {\n Some(match value.trim().to_ascii_lowercase().as_str() {\n \"flex-start\" | \"start\" | \"left\" | \"baseline\" => Place::Start,\n \"center\" => Place::Center,\n \"flex-end\" | \"end\" | \"right\" => Place::End,\n \"stretch\" => Place::Stretch,\n \"space-between\" => Place::Between,\n \"space-around\" => Place::Around,\n \"space-evenly\" => Place::Evenly,\n _ => return None,\n })\n}\n\n/// 1 to 4 lengths as CSS's shorthand gives them: top, right, bottom, left.\nfn sides(value: &str) -> Option<[f32; 4]> {\n let v: Vec<f32> = value.split_whitespace().map(points).collect::<Option<_>>()?;\n Some(match v.as_slice() {\n [a] => [*a, *a, *a, *a],\n [a, b] => [*a, *b, *a, *b],\n [a, b, c] => [*a, *b, *c, *b],\n [a, b, c, d] => [*a, *b, *c, *d],\n _ => return None,\n })\n}\n\n/// The native subset of `style` (after the web's filter).\npub fn parse(style: &str) -> Style {\n let mut s = Style::default();\n for (property, value) in safe_declarations(style) {\n let v = value.as_str();\n let lower = v.to_ascii_lowercase();\n match property.as_str() {\n \"color\" => s.color = parse_paint(v).or(s.color),\n \"background-color\" => s.background = parse_paint(v).or(s.background),\n \"font-weight\" => {\n s.weight = match lower.as_str() {\n \"normal\" => Some(400.0),\n \"bold\" | \"bolder\" => Some(700.0),\n \"lighter\" => Some(300.0),\n n => n.parse::<f32>().ok().filter(|w| (100.0..=900.0).contains(w)),\n }\n .or(s.weight)\n }\n \"font-style\" => {\n s.italic = match lower.as_str() {\n \"italic\" | \"oblique\" => Some(true),\n \"normal\" => Some(false),\n _ => s.italic,\n }\n }\n \"font-size\" => s.size = points(v).filter(|p| *p >= 6.0 && *p <= 96.0).or(s.size),\n \"text-align\" => {\n s.align = match lower.as_str() {\n \"left\" => Some(TextAlign::Left),\n \"right\" => Some(TextAlign::Right),\n \"center\" => Some(TextAlign::Center),\n \"start\" | \"justify\" => Some(TextAlign::Start),\n \"end\" => Some(TextAlign::End),\n _ => s.align,\n }\n }\n \"margin\" | \"padding\" => {\n if let Some(four) = sides(v) {\n let target = if property == \"margin\" { &mut s.margin } else { &mut s.padding };\n *target = four.map(Some);\n }\n }\n p if p.starts_with(\"margin-\") || p.starts_with(\"padding-\") => {\n let (box_, side) = p.split_once('-').unwrap_or((\"\", \"\"));\n let index = match side {\n \"top\" => 0,\n \"right\" => 1,\n \"bottom\" => 2,\n \"left\" => 3,\n _ => continue,\n };\n if let Some(n) = points(v) {\n let target = if box_ == \"margin\" { &mut s.margin } else { &mut s.padding };\n target[index] = Some(n);\n }\n }\n \"border\" => {\n for part in v.split_whitespace() {\n if let Some(w) = points(part) {\n s.border_width = Some(w.min(32.0));\n } else if let Some(c) = parse_paint(part) {\n s.border_color = Some(c);\n } else if part.eq_ignore_ascii_case(\"none\") {\n s.border_width = Some(0.0);\n }\n }\n }\n \"border-width\" => s.border_width = points(v).map(|w| w.min(32.0)).or(s.border_width),\n \"border-color\" => s.border_color = parse_paint(v).or(s.border_color.clone()),\n \"border-radius\" => s.radius = points(v).or(s.radius),\n \"display\" => {\n s.display = Some(match lower.as_str() {\n \"flex\" | \"inline-flex\" => Display::Flex,\n \"none\" => Display::None,\n _ => Display::Block,\n })\n }\n \"flex-direction\" => {\n s.direction = match lower.as_str() {\n \"row\" | \"row-reverse\" => Some(Axis::Row),\n \"column\" | \"column-reverse\" => Some(Axis::Column),\n _ => s.direction,\n }\n }\n \"gap\" => s.gap = v.split_whitespace().next().and_then(points).or(s.gap),\n \"align-items\" => s.align_items = place(v).or(s.align_items),\n \"justify-content\" => s.justify = place(v).or(s.justify),\n \"width\" => s.width = parse_length(v).or(s.width),\n \"height\" => s.height = parse_length(v).or(s.height),\n \"min-width\" => s.min_width = points(v).or(s.min_width),\n \"max-width\" => s.max_width = points(v).or(s.max_width),\n \"min-height\" => s.min_height = points(v).or(s.min_height),\n \"max-height\" => s.max_height = points(v).or(s.max_height),\n \"opacity\" => s.opacity = v.parse::<f32>().ok().filter(|o| o.is_finite()).map(|o| o.clamp(0.0, 1.0)),\n _ => {}\n }\n }\n s\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn the_web_filter_keeps_only_plain_allowed_declarations() {\n let kept = safe_declarations(\n \"color: red; background-image: url(x); width: calc(100% - 2px); height: calc(1px + 2px); position: fixed; \\\n color: expression(x); font-weight: bold; content: 'x'; margin: var(--evil); padding: var(--spacing)\",\n );\n assert_eq!(\n kept,\n vec![\n (\"color\".into(), \"red\".into()),\n (\"width\".into(), \"calc(100% - 2px)\".into()),\n (\"font-weight\".into(), \"bold\".into()),\n (\"padding\".into(), \"var(--spacing)\".into()),\n ]\n );\n assert!(safe_declarations(&\"color: red;\".repeat(400)).is_empty(), \"over 4,000 characters: dropped whole\");\n // `+` is not in the web pattern, so `calc(1px + 2px)` goes, as on the web.\n assert!(safe_declarations(&format!(\"color: {}\", \"a\".repeat(201))).is_empty());\n assert!(safe_declarations(\"color: u\\\\72l(x)\").is_empty(), \"no escapes\");\n }\n\n #[test]\n fn the_native_subset_maps_lengths_colours_and_flex() {\n let s = parse(\n \"color: #ff0000; background-color: rgba(0, 0, 255, 0.5); font-weight: 700; font-style: italic; \\\n font-size: 1rem; text-align: right; margin: 4px 8px; padding-left: 2px; border: 1px solid #000; \\\n border-radius: 6px; display: flex; flex-direction: column; gap: 10px; align-items: center; \\\n justify-content: space-between; width: 100%; max-width: 300px; opacity: 0.5\",\n );\n assert_eq!(s.color, Some(Paint::Rgba([1.0, 0.0, 0.0, 1.0])));\n assert_eq!(s.background, Some(Paint::Rgba([0.0, 0.0, 1.0, 0.5])));\n assert_eq!((s.weight, s.italic, s.size), (Some(700.0), Some(true), Some(14.0)));\n assert_eq!(s.align, Some(TextAlign::Right));\n assert_eq!(s.margin, [Some(4.0), Some(8.0), Some(4.0), Some(8.0)]);\n assert_eq!(s.padding, [None, None, None, Some(2.0)]);\n assert_eq!((s.border_width, s.radius), (Some(1.0), Some(6.0)));\n assert_eq!(s.border_color, Some(Paint::Rgba([0.0, 0.0, 0.0, 1.0])));\n assert_eq!((s.display, s.direction, s.gap), (Some(Display::Flex), Some(Axis::Column), Some(10.0)));\n assert_eq!((s.align_items, s.justify), (Some(Place::Center), Some(Place::Between)));\n assert_eq!((s.width, s.max_width, s.opacity), (Some(Length::Percent(100.0)), Some(300.0), Some(0.5)));\n }\n\n #[test]\n fn unsupported_values_are_ignored() {\n let s = parse(\"width: calc(100% - 2px); color: hsl(0, 0%, 0%); font-size: 900px; text-decoration: underline\");\n assert_eq!(s, Style::default());\n assert_eq!(parse(\"color: var(--primary)\").color, Some(Paint::Token(\"primary\".into())));\n }\n}\n",
174
+ "type": "registry:file",
175
+ "target": "desktop-rune/app/src/make/style.rs"
176
+ },
177
+ {
178
+ "path": "app/desktop-rune/app/src/model.rs",
179
+ "content": "//! What the host knows of the client runtime, kept from the daemon's answers and events: the session, the\n//! generation, the live list's rows and the writes. Pure: [`Model::apply`] takes an event and returns what to do\n//! next; nothing here touches the network or the UI.\n//!\n//! The one rule it enforces: **nothing of an older generation is shown**. A `context` event raises the\n//! generation and drops every row, write and MAKE view of the ones before; a late `rows` or `write` event, or a\n//! late answer, of an older generation changes nothing. The chat screen's state ([`Chat`]) lives here too, so it\n//! goes with every reset.\n\nuse crate::chat::{Chat, ChatEffect};\nuse crate::notices::{Decidable, DecisionKind, Feed, NoticeEffect, decidable_approvals};\nuse eloxiv_local_client::{\n ConnectionState, ContextReason, Event, InvocationError, Organization, RowsStatus, SessionState, User, WritePhase,\n};\nuse serde_json::Value;\n\n/// The named query the reference list shows (hello's greetings), and the mutator its form writes through.\npub const GREETINGS_QUERY: &str = \"hello.greetings\";\npub const GREET_MUTATOR: &str = \"hello.greet\";\n\n/// The session as the screens use it.\n#[derive(Clone, Debug)]\npub enum Session {\n /// Not read yet (the daemon is starting).\n Unknown,\n SignedOut,\n SigningIn,\n SignedIn {\n user: User,\n organizations: Vec<Organization>,\n org_id: Option<String>,\n },\n SigningOut,\n}\n\nimpl Session {\n pub fn from_state(state: &SessionState) -> (Session, Option<i64>) {\n match state {\n SessionState::SignedOut(_) => (Session::SignedOut, None),\n SessionState::SigningIn(_) => (Session::SigningIn, None),\n SessionState::SigningOut(_) => (Session::SigningOut, None),\n SessionState::SignedIn(s) => (\n Session::SignedIn {\n user: s.user.clone(),\n organizations: s.organizations.clone(),\n org_id: s.org_id.clone(),\n },\n Some(s.generation),\n ),\n }\n }\n\n pub fn org_id(&self) -> Option<&str> {\n match self {\n Session::SignedIn { org_id, .. } => org_id.as_deref(),\n _ => None,\n }\n }\n}\n\n/// The live list: one subscription of [`GREETINGS_QUERY`] for the current generation.\n#[derive(Clone, Debug, Default, PartialEq)]\npub struct LiveList {\n /// Asked for, for this generation (its id once the daemon answered).\n pub requested: Option<i64>,\n pub subscription: Option<String>,\n pub status: Option<RowsStatus>,\n pub rows: Vec<Value>,\n pub error: Option<String>,\n /// `rows` events of this generation for a subscription whose id has not been answered yet: the stream and\n /// the answer to `POST /subscriptions` arrive on different connections, so the first snapshot can come first.\n pub early: Vec<(String, RowsStatus, Vec<Value>, Option<String>)>,\n /// The daemon answered the subscription request.\n pub answered: bool,\n}\n\n/// One optimistic write the person made, as its events report it.\n#[derive(Clone, Debug, PartialEq)]\npub struct WriteView {\n pub id: String,\n pub message: String,\n pub generation: i64,\n /// None until the first `write` event.\n pub phase: Option<WritePhase>,\n /// A rejected write's (or a refused request's) typed error: its `_tag` and message.\n pub error: Option<(String, String)>,\n}\n\n/// What [`Model::apply`] asks the host to do.\n#[derive(Clone, Debug, PartialEq)]\npub enum Effect {\n /// Subscribe the live list for this generation.\n Subscribe { generation: i64 },\n /// Every MAKE view and anything else of older generations goes.\n Teardown { generation: i64, reason: Option<ContextReason> },\n /// Subscribe the chat's queries for this generation, and ask whether the agent can answer.\n SubscribeChat { generation: i64 },\n /// What the chat asks for (follow or stop following a run).\n Chat(ChatEffect),\n /// Subscribe the person's notifications for this generation (shown as OS notifications while the app runs).\n SubscribeNotices { generation: i64 },\n /// Show or withdraw OS notifications.\n Notices(Vec<NoticeEffect>),\n}\n\n#[derive(Clone, Debug)]\npub struct Model {\n pub session: Session,\n /// The generation the signed-in session was given for. A `context` event raises the generation before its\n /// session arrives: until a signed-in session of that generation does, the session kept is the previous\n /// context's and nothing bound to the context is asked or offered ([`Model::usable`]).\n pub session_generation: Option<i64>,\n /// The generation now current: rows, writes and views of older ones are never shown.\n pub generation: i64,\n pub connection: Option<ConnectionState>,\n /// An offline start (LocalClient 1.2.0): the daemon could not reach the kernel to check the stored session, so\n /// what shows is the replica on this device, for the person and organisation it remembered.\n pub offline: bool,\n pub list: LiveList,\n pub writes: Vec<WriteView>,\n /// The last event's sequence number (events are numbered per stream).\n pub last_seq: u64,\n /// The chat screen's state, for the current generation.\n pub chat: Chat,\n /// Whether the app has the agent (its `hello` names the chat's queries and the daemon follows runs).\n pub chat_enabled: bool,\n /// The generation the chat's queries were asked for.\n pub chat_requested: Option<i64>,\n /// The person's notifications of the current generation, as OS notifications ([`crate::notices`]).\n pub notices: Feed,\n /// Whether the app has the notifications query and the host can show OS notifications.\n pub notices_enabled: bool,\n}\n\nimpl Default for Model {\n fn default() -> Self {\n Model {\n session: Session::Unknown,\n session_generation: None,\n generation: 0,\n connection: None,\n offline: false,\n list: LiveList::default(),\n writes: Vec::new(),\n last_seq: 0,\n chat: Chat::default(),\n chat_enabled: false,\n chat_requested: None,\n notices: Feed::default(),\n notices_enabled: false,\n }\n }\n}\n\n/// An invocation error's `_tag` and `message`, read from its JSON form so it holds for every variant.\npub fn error_parts(error: &InvocationError) -> (String, String) {\n let v = serde_json::to_value(error).unwrap_or(Value::Null);\n let tag = v.get(\"_tag\").and_then(Value::as_str).unwrap_or(\"Error\").to_owned();\n let msg = v.get(\"message\").and_then(Value::as_str).unwrap_or(\"\").to_owned();\n (tag, msg)\n}\n\n/// A failed snapshot's error as the list shows it: `Tag: message`.\nfn error_text(error: &InvocationError) -> String {\n let (tag, message) = error_parts(error);\n if message.is_empty() { tag } else { format!(\"{tag}: {message}\") }\n}\n\nimpl Model {\n /// The session as a `session` event gives it. A signed-in session of an older generation than the current one\n /// is stale (its organisation is not the one shown) and changes nothing.\n pub fn set_session(&mut self, state: &SessionState) -> Vec<Effect> {\n let (session, generation) = Session::from_state(state);\n let mut effects = Vec::new();\n if let Some(g) = generation {\n if g < self.generation {\n return effects;\n }\n if g > self.generation {\n effects.extend(self.reset(g, None));\n }\n }\n let signed_in_now = matches!(session, Session::SignedIn { .. });\n if !signed_in_now {\n // Signed out (or on the way): nothing of the person's stays on screen, nor a replica's connection.\n self.list = LiveList::default();\n self.writes.clear();\n self.connection = None;\n self.chat = Chat::new(self.generation);\n self.chat_requested = None;\n let withdrawn = self.notices.reset(self.generation);\n if !withdrawn.is_empty() {\n effects.push(Effect::Notices(withdrawn));\n }\n }\n self.offline = matches!(state, SessionState::SignedIn(s) if s.offline == Some(true));\n self.session = session;\n self.session_generation = generation;\n effects.extend(self.wanted());\n effects\n }\n\n /// One event from the stream.\n pub fn apply(&mut self, event: &Event) -> Vec<Effect> {\n self.last_seq = self.last_seq.max(event.seq());\n match event {\n Event::SessionEvent(e) => self.set_session(&e.session),\n Event::ContextEvent(e) => {\n if e.generation < self.generation {\n return Vec::new();\n }\n let mut effects = self.reset(e.generation, Some(e.reason));\n effects.extend(self.wanted());\n effects\n }\n Event::RowsEvent(e) => {\n if e.generation != self.generation {\n return Vec::new();\n }\n if self.notices.subscription.as_deref() == Some(e.subscription.as_str()) {\n let decidable = self.decidable();\n let Session::SignedIn { user, org_id: Some(org), .. } = &self.session else { return Vec::new() };\n if !self.usable() {\n return Vec::new();\n }\n let effects = self.notices.rows(e.status, &e.rows, &user.id, org, &decidable);\n return if effects.is_empty() { Vec::new() } else { vec![Effect::Notices(effects)] };\n }\n if self.notices.requests_subscription.as_deref() == Some(e.subscription.as_str()) {\n self.notices.requests_rows(e.status, &e.rows);\n return self.notices_refreshed();\n }\n if self.chat.query_of(&e.subscription).is_some() {\n let mut effects: Vec<Effect> =\n self.chat.rows(&e.subscription, &e.rows).into_iter().map(Effect::Chat).collect();\n effects.extend(self.notices_refreshed());\n return effects;\n }\n // A daemon that answers an id of its own (not the host's): its first snapshot can beat the answer.\n if self.list.subscription.as_deref() != Some(e.subscription.as_str())\n && self.list.requested == Some(self.generation)\n && !self.list.answered\n {\n self.list.early.retain(|(id, ..)| *id != e.subscription);\n let error = e.error.as_ref().map(error_text);\n self.list.early.push((e.subscription.clone(), e.status, e.rows.clone(), error));\n return Vec::new();\n }\n if self.list.subscription.as_deref() != Some(e.subscription.as_str()) {\n return Vec::new();\n }\n self.list.status = Some(e.status);\n self.list.rows = e.rows.clone();\n self.list.error = e.error.as_ref().map(error_text);\n Vec::new()\n }\n Event::WriteEvent(e) => {\n if e.generation != self.generation {\n return Vec::new();\n }\n if let Some(w) = self.writes.iter_mut().find(|w| w.id == e.id) {\n w.phase = Some(e.phase);\n w.error = e.error.as_ref().map(error_parts);\n }\n Vec::new()\n }\n Event::ConnectionEvent(e) => {\n self.connection = Some(e.state);\n Vec::new()\n }\n Event::RunEvent(e) => {\n if e.generation != self.generation {\n return Vec::new();\n }\n let error = e.error.as_ref().map(error_parts);\n let mut effects: Vec<Effect> = self\n .chat\n .run_event(&e.subscription, e.event.as_ref(), error)\n .into_iter()\n .map(Effect::Chat)\n .collect();\n effects.extend(self.notices_refreshed());\n effects\n }\n }\n }\n\n /// The requests the person can decide now, by the authoritative rows of the current context: the approval\n /// requests the feed follows (pending, unexpired, someone else's) and the consent requests the followed run holds,\n /// but for those being decided now (from the chat or a notification). None outside a usable signed-in session.\n pub fn decidable(&self) -> Vec<Decidable> {\n let Session::SignedIn { user, .. } = &self.session else { return Vec::new() };\n if !self.usable() {\n return Vec::new();\n }\n let now =\n std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64);\n let mut decidable =\n self.notices.requests.as_deref().map(|r| decidable_approvals(r, &user.id, now)).unwrap_or_default();\n decidable.extend(self.chat.consents.iter().map(|c| Decidable {\n kind: DecisionKind::Consent,\n id: c.consent_id.clone(),\n action: c.action.clone(),\n title: c.title.clone(),\n }));\n decidable.retain(|d| !self.chat.deciding.contains(&d.id));\n decidable\n }\n\n /// The shown notifications' decisions, as the authoritative rows have them now ([`Feed::refresh`]).\n pub fn notices_refreshed(&mut self) -> Vec<Effect> {\n let effects = self.notices.refresh(&self.decidable());\n if effects.is_empty() { Vec::new() } else { vec![Effect::Notices(effects)] }\n }\n\n /// `POST /client/v1/subscriptions` answered for `generation`: the list's id, if that generation is still\n /// current (a late answer of an older one is dropped; the caller unsubscribes it).\n pub fn subscribed(&mut self, generation: i64, id: String) -> bool {\n if generation != self.generation || self.list.requested != Some(generation) {\n return false;\n }\n self.list.answered = true;\n if self.list.subscription.as_deref() == Some(id.as_str()) {\n self.list.early.clear();\n return true;\n }\n if let Some(at) = self.list.early.iter().position(|(early, ..)| *early == id) {\n let (_, status, rows, error) = self.list.early.remove(at);\n self.list.status = Some(status);\n self.list.rows = rows;\n self.list.error = error;\n }\n self.list.early.clear();\n self.list.subscription = Some(id);\n true\n }\n\n /// The live list is being subscribed under the host's own `id`: its snapshots are accepted from now on.\n pub fn subscribing(&mut self, generation: i64, id: String) {\n if generation == self.generation && self.list.requested == Some(generation) {\n self.list.subscription = Some(id);\n }\n }\n\n /// A subscription request failed.\n pub fn subscribe_failed(&mut self, generation: i64, message: String) {\n if generation == self.generation {\n self.list.requested = None;\n self.list.subscription = None;\n self.list.error = Some(message);\n }\n }\n\n /// The person wrote `message` as write `id` in the current generation.\n pub fn wrote(&mut self, id: String, message: String) {\n self.writes.push(WriteView { id, message, generation: self.generation, phase: None, error: None });\n // Keep the panel short.\n if self.writes.len() > 20 {\n self.writes.remove(0);\n }\n }\n\n /// A write request was refused before it was queued (`InvalidInput`, `NotSignedIn`, ...).\n pub fn write_refused(&mut self, id: &str, tag: String, message: String) {\n if let Some(w) = self.writes.iter_mut().find(|w| w.id == id) {\n w.phase = Some(WritePhase::Rejected);\n w.error = Some((tag, message));\n }\n }\n\n /// A newer generation: drop everything of the older ones (its replica's connection state too: the new\n /// context's replica reports its own).\n fn reset(&mut self, generation: i64, reason: Option<ContextReason>) -> Vec<Effect> {\n self.generation = generation;\n self.connection = None;\n self.list = LiveList::default();\n self.chat = Chat::new(generation);\n self.chat_requested = None;\n self.writes.retain(|w| w.generation >= generation);\n let withdrawn = self.notices.reset(generation);\n let mut effects = vec![Effect::Teardown { generation, reason }];\n if !withdrawn.is_empty() {\n effects.push(Effect::Notices(withdrawn));\n }\n effects\n }\n\n /// Whether the session describes the current context: signed in, by a session of the current generation.\n pub fn usable(&self) -> bool {\n matches!(self.session, Session::SignedIn { .. }) && self.session_generation == Some(self.generation)\n }\n\n /// What to subscribe now (something the session alone does not change became possible: the OS notifier is ready).\n pub fn wanted_now(&mut self) -> Vec<Effect> {\n self.wanted()\n }\n\n /// The live list, when signed in with an organisation (by the current context's session) and none was asked for\n /// this generation.\n fn wanted(&mut self) -> Vec<Effect> {\n let mut effects = Vec::new();\n if !self.usable() {\n return effects;\n }\n if self.session.org_id().is_some() && self.list.requested != Some(self.generation) {\n self.list.requested = Some(self.generation);\n effects.push(Effect::Subscribe { generation: self.generation });\n }\n if self.chat_enabled && self.session.org_id().is_some() && self.chat_requested != Some(self.generation) {\n self.chat_requested = Some(self.generation);\n effects.push(Effect::SubscribeChat { generation: self.generation });\n }\n if self.notices_enabled && self.session.org_id().is_some() && self.notices.requested != Some(self.generation) {\n self.notices.requested = Some(self.generation);\n effects.push(Effect::SubscribeNotices { generation: self.generation });\n }\n effects\n }\n\n /// The event stream was opened again: its subscriptions (rows and runs) are new too. The chat keeps what it\n /// shows; its queries are asked again with the next session event and its run followed again from the last\n /// stored event it saw.\n pub fn stream_reopened(&mut self) {\n self.list = LiveList::default();\n self.chat_requested = None;\n self.chat.subscriptions.clear();\n self.chat.followed = None;\n self.notices.stream_reopened();\n }\n\n /// The rows as the list shows them: newest first, as the query orders them.\n pub fn greeting_texts(&self) -> Vec<(String, String)> {\n self.list\n .rows\n .iter()\n .enumerate()\n .map(|(i, row)| {\n let id = row.get(\"id\").and_then(Value::as_str).map_or_else(|| format!(\"row-{i}\"), str::to_owned);\n let text = row.get(\"message\").and_then(Value::as_str).map_or_else(|| row.to_string(), str::to_owned);\n (id, text)\n })\n .collect()\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use serde_json::json;\n\n fn event(v: Value) -> Event {\n serde_json::from_value(v).expect(\"an event\")\n }\n\n fn signed_in(generation: i64, org: &str) -> SessionState {\n serde_json::from_value(json!({ \"state\": \"signedIn\", \"user\": { \"id\": \"u\", \"email\": \"a@x\", \"name\": \"A\" },\n \"organizations\": [{ \"orgId\": \"acme\", \"name\": \"Acme\", \"roles\": [] }, { \"orgId\": \"globex\", \"name\": \"Globex\", \"roles\": [] }],\n \"orgId\": org, \"generation\": generation }))\n .expect(\"a session\")\n }\n\n #[test]\n fn a_snapshot_that_beats_a_daemon_chosen_id_is_kept_until_the_answer() {\n let mut m = Model::default();\n assert_eq!(\n m.set_session(&signed_in(1, \"acme\")),\n vec![Effect::Teardown { generation: 1, reason: None }, Effect::Subscribe { generation: 1 }]\n );\n m.subscribing(1, \"mine\".into());\n m.apply(&event(json!({ \"seq\": 2, \"type\": \"rows\", \"subscription\": \"theirs\", \"generation\": 1, \"status\": \"complete\", \"rows\": [{ \"id\": \"a\", \"message\": \"hi\" }] })));\n assert!(m.list.rows.is_empty());\n assert!(m.subscribed(1, \"theirs\".into()));\n assert_eq!(m.greeting_texts(), vec![(\"a\".to_owned(), \"hi\".to_owned())]);\n }\n\n #[test]\n fn nothing_of_an_older_generation_lands() {\n let mut m = Model::default();\n m.set_session(&signed_in(1, \"acme\"));\n m.subscribing(1, \"s1\".into());\n m.wrote(\"w1\".into(), \"hello\".into());\n let effects = m.apply(&event(json!({ \"seq\": 3, \"type\": \"context\", \"generation\": 2, \"reason\": \"org\" })));\n assert_eq!(effects[0], Effect::Teardown { generation: 2, reason: Some(ContextReason::Org) });\n assert!(m.writes.is_empty() && m.list.subscription.is_none());\n m.apply(&event(json!({ \"seq\": 4, \"type\": \"rows\", \"subscription\": \"s1\", \"generation\": 1, \"status\": \"complete\", \"rows\": [{ \"message\": \"late\" }] })));\n m.apply(&event(json!({ \"seq\": 5, \"type\": \"write\", \"id\": \"w1\", \"generation\": 1, \"phase\": \"confirmed\" })));\n m.apply(&event(json!({ \"seq\": 6, \"type\": \"context\", \"generation\": 1, \"reason\": \"org\" })));\n assert!(m.list.rows.is_empty() && m.writes.is_empty());\n assert_eq!(m.generation, 2);\n assert!(!m.subscribed(1, \"s1\".into()), \"an older generation's answer is refused (the host unsubscribes it)\");\n assert_eq!(m.last_seq, 6);\n }\n\n #[test]\n fn nothing_is_asked_in_a_new_context_until_its_session_arrives() {\n let mut m = Model::default();\n m.set_session(&signed_in(1, \"acme\"));\n assert!(m.usable());\n let effects = m.apply(&event(json!({ \"seq\": 2, \"type\": \"context\", \"generation\": 2, \"reason\": \"org\" })));\n assert_eq!(effects, vec![Effect::Teardown { generation: 2, reason: Some(ContextReason::Org) }]);\n assert!(!m.usable(), \"the session kept is acme's, of generation 1\");\n assert_eq!(m.set_session(&signed_in(2, \"globex\")), vec![Effect::Subscribe { generation: 2 }]);\n assert!(m.usable());\n }\n\n #[test]\n fn a_session_of_an_older_generation_changes_nothing() {\n let mut m = Model::default();\n m.set_session(&signed_in(2, \"globex\"));\n m.subscribing(2, \"s2\".into());\n assert!(m.set_session(&signed_in(1, \"acme\")).is_empty());\n assert_eq!(m.generation, 2);\n assert_eq!(m.session.org_id(), Some(\"globex\"));\n assert_eq!(m.list.subscription.as_deref(), Some(\"s2\"));\n }\n}\n",
180
+ "type": "registry:file",
181
+ "target": "desktop-rune/app/src/model.rs"
182
+ },
183
+ {
184
+ "path": "app/desktop-rune/app/src/notices.rs",
185
+ "content": "//! The person's notifications as OS notifications, **while the app runs**: in-app notification records (the inbox's\n//! `notifications.mine` named query, synced into the daemon's replica and observed through LocalClient) surfaced\n//! natively. This is not provider push: nothing reaches the person when the app is closed, and a notification is\n//! shown because the replica changed, not because a push service delivered it.\n//!\n//! - **Which rows**: only notifications that arrive after the watch began. The first complete snapshot of each\n//! generation is the baseline (shown never); after it, a complete snapshot's row is shown when it is new, unread,\n//! not dismissed, the person's own, in the organisation shown, and not older than the watch's start (the host's\n//! clock, less [`CLOCK_ALLOWANCE`]) or the person's newest row in the baseline; once per person, organisation and id\n//! in a run of the host, across generations. A row read or dismissed elsewhere is taken back out of the system's\n//! list. Failed, cached and unknown snapshots show and withdraw nothing.\n//! - **Generations**: an organisation switch or a sign-out the person asks for withdraws every notification shown\n//! and suspends the feed from that moment (rows arriving meanwhile are seen, never shown; a switch refused resumes\n//! it); a `context` event (the switch done, a sign-out, a revoked session) starts the next generation's feed. A\n//! click or button on a notification withdrawn, of another generation, or while a switch or sign-out is on its way\n//! does nothing.\n//! - **Clicks** open the record through the host's deep links ([`crate::routing`]): the first view that shows the\n//! record's entity (the View contract's `recordLink`), or the agent's conversation for an approval or consent\n//! request (where their cards are); otherwise the app only comes forward.\n//! - **Approve / Reject** show only on a notification whose linked request the authoritative rows say the person can\n//! decide now: a pending approval request someone else made, from the `approvals.requests` rows the feed follows\n//! itself, or a consent request the person's followed run holds (its `consent-required` event; consent requests are\n//! not synced). The notification's words then come from the request (its action), never from the notification's\n//! own title, body or category, which anyone who can notify the person chooses; every other notification only\n//! navigates. The buttons call `approvals.approve|reject` or `consent.approve|reject` through LocalClient with the\n//! person's session, the current generation and the chat SDK's decision key, exactly as the chat's cards do.\n//! Showing or clicking a notification never decides.\n//! - **Backends** ([`select`]): on macOS UNUserNotificationCenter (a bundled app only), driven by the host so that the\n//! person's authorisation is asked apart from posting and nothing withdrawn meanwhile is scheduled ([`AuthQueue`]),\n//! with rune-notify delivering the clicks; on Windows `rune-notify` (toasts under the app's AppUserModelID); the\n//! freedesktop notification service over D-Bus elsewhere on Unix, probed off the UI thread. The permission reported\n//! is the OS's own (macOS's authorisation status, Windows's toast setting), or none where the OS does not say\n//! (freedesktop). Tests use [`Notifier::memory`].\n\nuse std::collections::{HashSet, VecDeque};\nuse std::sync::mpsc::{Receiver, Sender, channel};\nuse std::sync::{Arc, Mutex, RwLock};\n\nuse eloxiv_local_client::RowsStatus;\nuse serde_json::Value;\n\nuse crate::backend::Wake;\nuse crate::chat::Decision;\n\n/// The named query whose rows are the person's notifications (the inbox's `inboxQueries`).\npub const NOTIFICATIONS_QUERY: &str = \"notifications.mine\";\n/// The named query whose rows are the approval requests the person made or may decide (the authority for buttons).\npub const REQUESTS_QUERY: &str = \"approvals.requests\";\n/// The kernel's consent notification category (its body, the held call's input, is not shown outside the app).\npub const CONSENT_CATEGORY: &str = \"consent.requested\";\n/// The modules of the requests a decision notification links (`<module>` / `request`).\npub const APPROVALS_MODULE: &str = \"approvals\";\npub const CONSENT_MODULE: &str = \"consent\";\n/// What a consent notification says on screen: the held call's input is not shown outside the app.\npub const CONSENT_BODY: &str = \"Open the app to review the details.\";\n/// The words of a notification that offers a decision, from the request (a consent's title ends with what people see\n/// its action called; an approval's body is that).\npub const APPROVAL_TITLE: &str = \"Approval needed\";\npub const CONSENT_TITLE: &str = \"Your agent wants to:\";\n/// The button ids a decision notification carries.\npub const APPROVE: &str = \"approve\";\npub const REJECT: &str = \"reject\";\n/// Notifications kept on screen per generation (the oldest goes first).\npub const MAX_SHOWN: usize = 20;\n/// How far the server's clock may be behind the host's (ms): rows created up to this long before the watch began\n/// can still show, so a slow server clock does not hide new ones.\npub const CLOCK_ALLOWANCE: i64 = 5 * 60 * 1000;\n/// How many shown notifications the host remembers, so none shows twice in a run.\nconst SURFACED_KEPT: usize = 1000;\n\n/// A record a notification links (`EntityReference`).\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct Reference {\n pub module: String,\n pub entity: String,\n pub id: String,\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum DecisionKind {\n Approval,\n Consent,\n}\n\n/// A request the person can decide now, by the authoritative rows: its kind, its id and the action it asks for.\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct Decidable {\n pub kind: DecisionKind,\n pub id: String,\n pub action: String,\n /// What people see the action called, as the kernel recorded it with the request (or its readable name).\n pub title: String,\n}\n\n/// One notification the host shows.\n#[derive(Clone, Debug, PartialEq)]\npub struct Notice {\n /// The notification record's id.\n pub id: String,\n pub generation: i64,\n pub org_id: String,\n pub category: String,\n pub title: String,\n pub body: String,\n pub link: Option<Reference>,\n /// An approval or consent request the person may decide from the notification (its id).\n pub decision: Option<(DecisionKind, String)>,\n}\n\n/// A click on a shown notification (`action`: a decision button; None: the notification itself).\n#[derive(Clone, Debug, PartialEq)]\npub struct Click {\n pub notice: String,\n pub generation: i64,\n pub action: Option<Decision>,\n /// The activation token the notification service gave for the click (freedesktop), to bring the window forward.\n pub token: Option<String>,\n}\n\n/// What the feed asks the host to do.\n#[derive(Clone, Debug, PartialEq)]\npub enum NoticeEffect {\n Post(Box<Notice>),\n /// Take the notification with this record id back out of the system's list.\n Withdraw(String),\n}\n\n/// A notification row as the replica has it (`notificationTable`).\n#[derive(Clone, Debug, PartialEq)]\nstruct Row {\n id: String,\n org_id: String,\n recipient_id: String,\n category: String,\n title: String,\n body: String,\n link: Option<Reference>,\n created_at: i64,\n open: bool,\n}\n\nfn row(v: &Value) -> Option<Row> {\n let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_owned);\n let set = |k: &str| v.get(k).is_some_and(|x| !x.is_null());\n let link = match (s(\"linkModule\"), s(\"linkEntity\"), s(\"linkId\")) {\n (Some(module), Some(entity), Some(id)) => Some(Reference { module, entity, id }),\n _ => None,\n };\n Some(Row {\n id: s(\"id\")?,\n org_id: s(\"orgId\").unwrap_or_default(),\n recipient_id: s(\"recipientId\").unwrap_or_default(),\n category: s(\"category\").unwrap_or_default(),\n title: s(\"title\").unwrap_or_default(),\n body: s(\"body\").unwrap_or_default(),\n link,\n created_at: v.get(\"createdAt\").and_then(Value::as_f64).map_or(0, |n| n as i64),\n open: !set(\"readAt\") && !set(\"dismissedAt\"),\n })\n}\n\n/// The kind of request a notification links, if it links one (`approvals` or `consent`, entity `request`).\npub fn request_of(link: Option<&Reference>) -> Option<(DecisionKind, &str)> {\n let link = link.filter(|l| l.entity == \"request\")?;\n match link.module.as_str() {\n APPROVALS_MODULE => Some((DecisionKind::Approval, link.id.as_str())),\n CONSENT_MODULE => Some((DecisionKind::Consent, link.id.as_str())),\n _ => None,\n }\n}\n\n/// The decision a notification offers: the request it links, when the authoritative rows say the person can decide it.\nfn decision_of(link: Option<&Reference>, decidable: &[Decidable]) -> Option<Decidable> {\n let (kind, id) = request_of(link)?;\n decidable.iter().find(|d| d.kind == kind && d.id == id).cloned()\n}\n\n/// A notification offering `decision`: the request's words (its action), not the notification's.\nfn with_decision(mut notice: Notice, decision: Option<Decidable>) -> Notice {\n match decision {\n Some(d) => {\n (notice.title, notice.body) = match d.kind {\n DecisionKind::Approval => (APPROVAL_TITLE.to_owned(), d.title),\n DecisionKind::Consent => (format!(\"{CONSENT_TITLE} {}\", d.title), CONSENT_BODY.to_owned()),\n };\n notice.decision = Some((d.kind, d.id));\n }\n None => notice.decision = None,\n }\n notice\n}\n\n/// The approval requests the person may decide now, from `approvals.requests` rows: pending, not expired at\n/// `now_ms`, made by someone else (the kernel's read policy leaves only those the person made or may decide).\npub fn decidable_approvals(rows: &[Value], user: &str, now_ms: i64) -> Vec<Decidable> {\n rows.iter()\n .filter_map(|r| {\n let s = |k: &str| r.get(k).and_then(Value::as_str);\n let expired = r.get(\"expiresAt\").and_then(Value::as_f64).is_some_and(|at| (at as i64) <= now_ms);\n let id = s(\"id\")?.to_owned();\n (s(\"status\")? == \"pending\" && s(\"requesterId\")? != user && !expired).then(|| Decidable {\n kind: DecisionKind::Approval,\n id,\n action: s(\"action\").unwrap_or_default().to_owned(),\n title: crate::chat::decision_label(s(\"action\").unwrap_or_default(), s(\"title\")),\n })\n })\n .collect()\n}\n\n/// The notification subscription of the current generation and what it has shown.\n#[derive(Clone, Debug, Default)]\npub struct Feed {\n pub generation: i64,\n /// Asked for, for this generation.\n pub requested: Option<i64>,\n /// The subscription's id (the host's own, or the daemon's answer).\n pub subscription: Option<String>,\n /// The host's id of the subscription asked for now: only its answer counts (one from before the stream opened\n /// again names a subscription that ended with it).\n asked: Option<String>,\n /// The `approvals.requests` subscription's id: the authority for approval buttons.\n pub requests_subscription: Option<String>,\n requests_asked: Option<String>,\n /// Its last complete rows (None: none yet).\n pub requests: Option<Vec<Value>>,\n /// The first complete snapshot arrived: rows after it are new.\n baselined: bool,\n /// The later of the session's start ([`Feed::starting`]) and the person's newest row in the baseline\n /// (`createdAt`, ms): nothing older is shown.\n floor: i64,\n /// When this generation's watch began, less [`CLOCK_ALLOWANCE`] (ms, the host's clock): None in tests that set none.\n since: Option<i64>,\n /// The notifications this run of the host has shown, by person, organisation and id: a row shown once is never\n /// shown again, also after a switch away and back or a fresh baseline that missed it (kept across generations).\n surfaced: VecDeque<String>,\n /// Every row id this generation has seen (shown once at most).\n seen: HashSet<String>,\n /// Shown now, oldest first.\n shown: Vec<Notice>,\n /// An organisation switch or a sign-out was asked for: nothing is shown until it is refused (or the next\n /// generation's feed starts).\n suspended: bool,\n}\n\nimpl Feed {\n pub fn new(generation: i64) -> Feed {\n Feed { generation, ..Feed::default() }\n }\n\n /// A switch or sign-out was asked for: everything shown is withdrawn and nothing is shown until [`Feed::resume`].\n pub fn suspend(&mut self) -> Vec<NoticeEffect> {\n self.suspended = true;\n self.shown.drain(..).map(|n| NoticeEffect::Withdraw(n.id)).collect()\n }\n\n /// The switch or sign-out was refused: rows new from now on are shown; nothing seen is shown again.\n pub fn resume(&mut self) {\n self.suspended = false;\n }\n\n pub fn suspended(&self) -> bool {\n self.suspended\n }\n\n /// The baseline arrived: a row after it is new.\n pub fn watching(&self) -> bool {\n self.baselined\n }\n\n /// Shown now, oldest first.\n pub fn shown(&self) -> &[Notice] {\n &self.shown\n }\n\n pub fn find(&self, id: &str) -> Option<&Notice> {\n self.shown.iter().find(|n| n.id == id)\n }\n\n /// A newer generation (or the person signed out): everything shown is withdrawn, and the watch begins again\n /// (what was shown stays shown once).\n pub fn reset(&mut self, generation: i64) -> Vec<NoticeEffect> {\n let withdrawn = self.shown.drain(..).map(|n| NoticeEffect::Withdraw(n.id)).collect();\n let surfaced = std::mem::take(&mut self.surfaced);\n *self = Feed::new(generation);\n self.surfaced = surfaced;\n withdrawn\n }\n\n /// The watch of this generation begins at `now_ms` (the host's clock): nothing created before it, less\n /// [`CLOCK_ALLOWANCE`] for the server's clock, is shown, even if the baseline was empty and it synced late.\n pub fn starting(&mut self, now_ms: i64) {\n if self.since.is_none() {\n self.since = Some(now_ms - CLOCK_ALLOWANCE);\n }\n }\n\n /// The subscription is being made under the host's `id`.\n pub fn subscribing(&mut self, generation: i64, id: String) {\n if generation == self.generation && self.requested == Some(generation) {\n self.asked = Some(id.clone());\n self.subscription = Some(id);\n }\n }\n\n /// The daemon answered the subscription asked for under the host's `asked` with `id`, for `generation`: false\n /// when that generation is gone or another subscription was asked for since (the caller lets `id` go).\n pub fn subscribed(&mut self, generation: i64, asked: &str, id: String) -> bool {\n if generation != self.generation || self.requested != Some(generation) || self.asked.as_deref() != Some(asked) {\n return false;\n }\n self.subscription = Some(id);\n true\n }\n\n /// The subscription asked for under `asked` failed: asked again with the next session, unless it is not the one\n /// asked for now.\n pub fn subscribe_failed(&mut self, generation: i64, asked: &str) {\n if generation == self.generation && self.asked.as_deref() == Some(asked) {\n self.requested = None;\n self.subscription = None;\n self.asked = None;\n }\n }\n\n /// The `approvals.requests` subscription is being made under the host's `id`.\n pub fn subscribing_requests(&mut self, generation: i64, id: String) {\n if generation == self.generation && self.requested == Some(generation) {\n self.requests_asked = Some(id.clone());\n self.requests_subscription = Some(id);\n }\n }\n\n /// The daemon answered the `approvals.requests` subscription asked for under `asked` with `id`: false when that\n /// generation is gone or another was asked for since.\n pub fn subscribed_requests(&mut self, generation: i64, asked: &str, id: String) -> bool {\n if generation != self.generation\n || self.requested != Some(generation)\n || self.requests_asked.as_deref() != Some(asked)\n {\n return false;\n }\n self.requests_subscription = Some(id);\n true\n }\n\n /// A snapshot of the `approvals.requests` rows.\n pub fn requests_rows(&mut self, status: RowsStatus, rows: &[Value]) {\n if status == RowsStatus::Complete {\n self.requests = Some(rows.to_vec());\n }\n }\n\n /// The event stream was opened again: the subscription is gone (asked again), what was seen stays seen.\n pub fn stream_reopened(&mut self) {\n self.requested = None;\n self.subscription = None;\n self.asked = None;\n self.requests_subscription = None;\n self.requests_asked = None;\n }\n\n /// What the authoritative rows say now (`decidable`): a shown notification whose request can no longer be decided\n /// (decided, deciding, expired) is withdrawn; one whose request can be decided now offers it (posted again, with\n /// the request's words).\n pub fn refresh(&mut self, decidable: &[Decidable]) -> Vec<NoticeEffect> {\n let mut effects = Vec::new();\n let mut gone = Vec::new();\n for n in &mut self.shown {\n let now = decision_of(n.link.as_ref(), decidable);\n let offered = n.decision.clone();\n match (offered, &now) {\n (Some(_), None) => gone.push(n.id.clone()),\n (Some((kind, id)), Some(d)) if kind == d.kind && id == d.id => {}\n (_, None) => {}\n (_, Some(_)) => {\n *n = with_decision(n.clone(), now);\n effects.push(NoticeEffect::Post(Box::new(n.clone())));\n }\n }\n }\n for id in gone {\n effects.extend(self.settle(&id));\n }\n effects\n }\n\n /// The person acted on notification `id` (a click or a button): it leaves the list.\n pub fn settle(&mut self, id: &str) -> Vec<NoticeEffect> {\n let before = self.shown.len();\n self.shown.retain(|n| n.id != id);\n if self.shown.len() == before { Vec::new() } else { vec![NoticeEffect::Withdraw(id.to_owned())] }\n }\n\n /// A snapshot of the subscription's rows, for the signed-in `user` in organisation `org`.\n pub fn rows(\n &mut self,\n status: RowsStatus,\n rows: &[Value],\n user: &str,\n org: &str,\n decidable: &[Decidable],\n ) -> Vec<NoticeEffect> {\n // Only the server's word counts: a failed, cached or unknown snapshot neither shows nor withdraws anything\n // (before the baseline, a cached one's rows are old, as the baseline's are).\n if status == RowsStatus::Error || (self.baselined && status != RowsStatus::Complete) {\n return Vec::new();\n }\n let rows: Vec<Row> = rows.iter().filter_map(row).collect();\n if !self.baselined {\n // Before the first complete snapshot every row is old: what the replica had, or what synced in with it.\n self.seen.extend(rows.iter().map(|r| r.id.clone()));\n if status == RowsStatus::Complete {\n self.baselined = true;\n // Nothing older than the session's start, or than the person's newest row in the baseline.\n let newest =\n rows.iter().filter(|r| r.recipient_id == user && r.org_id == org).map(|r| r.created_at).max();\n self.floor = newest.unwrap_or(i64::MIN).max(self.since.unwrap_or(i64::MIN));\n }\n return Vec::new();\n }\n let mut effects = Vec::new();\n // Read, dismissed or gone (elsewhere: the web shell, another device): taken back out of the system's list.\n let open: HashSet<&str> = rows.iter().filter(|r| r.open).map(|r| r.id.as_str()).collect();\n let mut gone = Vec::new();\n self.shown.retain(|n| {\n let keep = open.contains(n.id.as_str());\n if !keep {\n gone.push(n.id.clone());\n }\n keep\n });\n effects.extend(gone.into_iter().map(NoticeEffect::Withdraw));\n if self.suspended {\n // Of the context being left: seen, so a refused switch does not show them afterwards.\n self.seen.extend(rows.iter().map(|r| r.id.clone()));\n return effects;\n }\n // Oldest first, so the system's list keeps the query's order.\n let mut fresh: Vec<&Row> = rows.iter().filter(|r| !self.seen.contains(&r.id)).collect();\n fresh.sort_by_key(|r| r.created_at);\n for r in fresh {\n self.seen.insert(r.id.clone());\n let key = format!(\"{user}\\u{0}{org}\\u{0}{}\", r.id);\n if !r.open\n || r.created_at < self.floor\n || r.recipient_id != user\n || r.org_id != org\n || self.surfaced.contains(&key)\n {\n continue;\n }\n self.surfaced.push_back(key);\n if self.surfaced.len() > SURFACED_KEPT {\n self.surfaced.pop_front();\n }\n let body = if r.category == CONSENT_CATEGORY { CONSENT_BODY.to_owned() } else { r.body.clone() };\n let notice = Notice {\n id: r.id.clone(),\n generation: self.generation,\n org_id: r.org_id.clone(),\n category: r.category.clone(),\n title: r.title.clone(),\n body,\n link: r.link.clone(),\n decision: None,\n };\n let notice = with_decision(notice, decision_of(r.link.as_ref(), decidable));\n self.shown.push(notice.clone());\n effects.push(NoticeEffect::Post(Box::new(notice)));\n if self.shown.len() > MAX_SHOWN {\n let oldest = self.shown.remove(0);\n effects.push(NoticeEffect::Withdraw(oldest.id));\n }\n }\n effects\n }\n}\n\n// The OS side.\n\n/// Which OS notification service the host uses.\n#[derive(Clone, Debug, PartialEq, Eq)]\npub enum BackendKind {\n /// `rune-notify`: UNUserNotificationCenter (macOS) or toast notifications (Windows).\n RuneNotify,\n /// The freedesktop notification service (`org.freedesktop.Notifications` on the session bus).\n Freedesktop,\n /// In memory (tests).\n Memory,\n /// Being asked for, off the UI thread (the freedesktop service is probed on a thread of its own).\n Probing,\n /// None here, and why.\n Unavailable(String),\n}\n\n/// The person's permission for the app's notifications, as the Host contract words it.\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum Permission {\n Granted,\n Denied,\n Prompt,\n}\n\nimpl Permission {\n pub fn name(self) -> &'static str {\n match self {\n Permission::Granted => \"granted\",\n Permission::Denied => \"denied\",\n Permission::Prompt => \"prompt\",\n }\n }\n}\n\n/// The backend for `os` (`std::env::consts::OS`), given whether `rune-notify` can post (a bundled app on macOS, a\n/// registered identity on Windows) and how the freedesktop service answered (None: not asked).\npub fn select(os: &str, rune_notify: bool, freedesktop: Option<Result<(), String>>) -> BackendKind {\n match os {\n \"macos\" if rune_notify => BackendKind::RuneNotify,\n \"macos\" => BackendKind::Unavailable(\"macOS shows notifications only from the bundled app (.app)\".into()),\n \"windows\" if rune_notify => BackendKind::RuneNotify,\n \"windows\" => BackendKind::Unavailable(\"the app's notification identity is not registered\".into()),\n \"linux\" | \"freebsd\" | \"openbsd\" | \"netbsd\" | \"dragonfly\" => match freedesktop {\n Some(Ok(())) => BackendKind::Freedesktop,\n Some(Err(e)) => BackendKind::Unavailable(format!(\"no notification service on the session bus: {e}\")),\n None => BackendKind::Unavailable(\"the notification service was not asked\".into()),\n },\n other => BackendKind::Unavailable(format!(\"no notification service on {other}\")),\n }\n}\n\nimpl BackendKind {\n /// Whether it can show notifications (found, and not still being asked for).\n pub fn available(&self) -> bool {\n matches!(self, BackendKind::RuneNotify | BackendKind::Freedesktop | BackendKind::Memory)\n }\n}\n\n/// macOS's `UNAuthorizationStatus` as the Host contract words it: not determined (`prompt`), denied, authorized,\n/// provisional or ephemeral (`granted`); None for a value the host does not know.\npub fn mac_permission(status: isize) -> Option<Permission> {\n match status {\n 0 => Some(Permission::Prompt),\n 1 => Some(Permission::Denied),\n 2..=4 => Some(Permission::Granted),\n _ => None,\n }\n}\n\n/// Windows's `NotificationSetting` for the app's toasts: enabled (`granted`), or disabled for the app, for the user,\n/// by group policy or by the manifest (`denied`).\npub fn toast_permission(setting: i32) -> Permission {\n if setting == 0 { Permission::Granted } else { Permission::Denied }\n}\n\n/// What the host can do with notifications, for its capabilities: the backend, and the person's permission as the\n/// OS reports it (None: the OS does not say, as with the freedesktop service, or has not said yet).\n#[derive(Clone, Debug, PartialEq)]\npub struct Support {\n pub backend: BackendKind,\n pub permission: Option<Permission>,\n}\n\nimpl Support {\n /// Whether a notification can be shown: a backend found, and the person has not turned them off.\n pub fn can_post(&self) -> bool {\n self.backend.available() && self.permission != Some(Permission::Denied)\n }\n\n /// `{ shown: \"while-running\" | \"never\", backend, permission?, reason? }`, for an app that follows the person's\n /// notifications (`app_follows`: its daemon has the `notifications.mine` query) or not. `permission` is left out\n /// when the OS does not say.\n pub fn to_json(&self, app_follows: bool) -> Value {\n let backend = match &self.backend {\n BackendKind::RuneNotify => \"rune-notify\",\n BackendKind::Freedesktop => \"freedesktop\",\n BackendKind::Memory => \"memory\",\n BackendKind::Probing => \"probing\",\n BackendKind::Unavailable(_) => \"none\",\n };\n let mut v = serde_json::json!({\n \"shown\": if self.can_post() && app_follows { \"while-running\" } else { \"never\" },\n \"backend\": backend,\n });\n if let Some(p) = self.permission {\n v[\"permission\"] = Value::String(p.name().into());\n }\n let reason = match &self.backend {\n BackendKind::Unavailable(reason) => Some(reason.clone()),\n BackendKind::Probing => Some(\"the notification service has not answered yet\".into()),\n _ if self.permission == Some(Permission::Denied) => {\n Some(\"the person turned the app's notifications off\".into())\n }\n _ if !app_follows => {\n Some(format!(\"the app does not follow the person's notifications ({NOTIFICATIONS_QUERY})\"))\n }\n _ => None,\n };\n if let Some(reason) = reason {\n v[\"reason\"] = Value::String(reason);\n }\n v\n }\n}\n\n/// What an OS backend does.\ntrait Backend: Send {\n fn post(&mut self, notice: &Notice);\n fn withdraw(&mut self, id: &str);\n /// The person's permission as the OS reports it now (None: it does not say).\n fn permission(&self) -> Option<Permission> {\n None\n }\n}\n\n/// Posts, withdrawals and clicks recorded in memory (tests).\n#[derive(Clone, Default)]\npub struct Memory {\n pub log: Arc<Mutex<MemoryLog>>,\n}\n\n#[derive(Clone, Debug, Default)]\npub struct MemoryLog {\n pub posted: Vec<Notice>,\n pub withdrawn: Vec<String>,\n}\n\nimpl Memory {\n pub fn posted(&self) -> Vec<Notice> {\n self.log.lock().map(|l| l.posted.clone()).unwrap_or_default()\n }\n pub fn withdrawn(&self) -> Vec<String> {\n self.log.lock().map(|l| l.withdrawn.clone()).unwrap_or_default()\n }\n}\n\nimpl Backend for Memory {\n fn post(&mut self, notice: &Notice) {\n if let Ok(mut l) = self.log.lock() {\n l.posted.push(notice.clone());\n }\n }\n fn withdraw(&mut self, id: &str) {\n if let Ok(mut l) = self.log.lock() {\n l.withdrawn.push(id.to_owned());\n }\n }\n fn permission(&self) -> Option<Permission> {\n Some(Permission::Granted)\n }\n}\n\nstruct Nothing;\n\nimpl Backend for Nothing {\n fn post(&mut self, _: &Notice) {}\n fn withdraw(&mut self, _: &str) {}\n}\n\n/// Clicks from the OS (any thread) to the UI thread: sent, then the loop woken.\n#[derive(Clone)]\npub struct ClickSink {\n tx: Sender<Click>,\n wake: Arc<RwLock<Wake>>,\n}\n\nimpl ClickSink {\n pub fn send(&self, click: Click) {\n let _ = self.tx.send(click);\n let current = self.wake.read().map(|w| w.clone()).ok();\n if let Some(w) = current {\n w();\n }\n }\n}\n\n/// A backend found off the UI thread, and what it is.\ntype Probed = (Box<dyn Backend>, BackendKind);\n\n/// The host's notifier: one backend, the clicks it reports.\npub struct Notifier {\n backend: Box<dyn Backend>,\n kind: BackendKind,\n sink: ClickSink,\n clicks: Receiver<Click>,\n memory: Option<Memory>,\n /// The backend being found off the UI thread ([`Notifier::poll`] installs it).\n probe: Option<Receiver<Probed>>,\n}\n\nimpl Notifier {\n fn with(backend: Box<dyn Backend>, kind: BackendKind, sink: ClickSink, clicks: Receiver<Click>) -> Notifier {\n Notifier { backend, kind, sink, clicks, memory: None, probe: None }\n }\n\n /// A notifier whose backend `find` finds on a thread of its own (connecting to a service, asking it who it is),\n /// so the first frame never waits for it: nothing is shown until [`Notifier::poll`] installs it.\n fn probing(\n sink: ClickSink,\n clicks: Receiver<Click>,\n find: impl FnOnce(ClickSink) -> Probed + Send + 'static,\n ) -> Notifier {\n let (found, probe) = channel();\n let mut n = Notifier::with(Box::new(Nothing), BackendKind::Probing, sink.clone(), clicks);\n let wake = sink.wake.clone();\n let spawned = std::thread::Builder::new().name(\"eloxiv-notify-probe\".into()).spawn(move || {\n let _ = found.send(find(sink));\n let current = wake.read().map(|w| w.clone()).ok();\n if let Some(w) = current {\n w();\n }\n });\n if spawned.is_ok() {\n n.probe = Some(probe);\n } else {\n n.kind = BackendKind::Unavailable(\"could not start a thread\".into());\n }\n n\n }\n\n /// A notifier that records in memory, ready only after `delay` (tests: a slow notification service).\n pub fn memory_after(wake: Arc<RwLock<Wake>>, delay: std::time::Duration) -> Notifier {\n let (tx, clicks) = channel();\n let memory = Memory::default();\n let backend = memory.clone();\n let mut n = Notifier::probing(ClickSink { tx, wake }, clicks, move |_| {\n std::thread::sleep(delay);\n (Box::new(backend), BackendKind::Memory)\n });\n n.memory = Some(memory);\n n\n }\n\n /// Installs the backend found off the UI thread, once it is: true when it was installed now.\n pub fn poll(&mut self) -> bool {\n let Some(found) = self.probe.as_ref().and_then(|p| p.try_recv().ok()) else { return false };\n self.probe = None;\n let (backend, kind) = found;\n self.backend = backend;\n self.kind = kind;\n eprintln!(\"eloxiv-desktop-rune: notifications: {}\", self.support().to_json(true));\n true\n }\n\n /// A notifier that records in memory (the default for tests and an attached host's services).\n pub fn memory(wake: Arc<RwLock<Wake>>) -> Notifier {\n let (tx, clicks) = channel();\n let memory = Memory::default();\n let mut n = Notifier::with(Box::new(memory.clone()), BackendKind::Memory, ClickSink { tx, wake }, clicks);\n n.memory = Some(memory);\n n\n }\n\n /// The OS's notifier for the app named `name` with id `app_id` (its desktop entry on Linux), chosen by [`select`].\n /// Call it on the main thread at launch (macOS installs its delegate there).\n pub fn os(name: &str, app_id: &str, wake: Arc<RwLock<Wake>>) -> Notifier {\n let (tx, clicks) = channel();\n let sink = ClickSink { tx, wake };\n let os = std::env::consts::OS;\n #[cfg(target_os = \"macos\")]\n {\n let _ = (name, app_id);\n let kind = select(os, rune_notify::available(), None);\n if kind == BackendKind::RuneNotify {\n native::listen_clicks(sink.clone());\n return Notifier::with(Box::new(mac::Mac::start()), kind, sink, clicks);\n }\n Notifier::with(Box::new(Nothing), kind, sink, clicks)\n }\n #[cfg(target_os = \"windows\")]\n {\n let _ = name;\n let kind = select(os, rune_notify::available(), None);\n if kind == BackendKind::RuneNotify {\n return Notifier::with(Box::new(native::RuneNotify::start(sink.clone(), app_id)), kind, sink, clicks);\n }\n Notifier::with(Box::new(Nothing), kind, sink, clicks)\n }\n #[cfg(all(unix, not(target_os = \"macos\")))]\n {\n // The session bus and the service's answers (up to a second each) are asked off the UI thread.\n let (name, app_id) = (name.to_owned(), app_id.to_owned());\n Notifier::probing(sink, clicks, move |sink| match freedesktop::Freedesktop::start(&name, &app_id, sink) {\n Ok(backend) => (Box::new(backend) as Box<dyn Backend>, select(os, false, Some(Ok(())))),\n Err(e) => (Box::new(Nothing), select(os, false, Some(Err(e)))),\n })\n }\n #[cfg(not(any(unix, target_os = \"windows\")))]\n {\n let _ = (name, app_id);\n Notifier::with(Box::new(Nothing), select(os, false, None), sink, clicks)\n }\n }\n\n /// The backend and the person's permission as the OS reports it now.\n pub fn support(&self) -> Support {\n let permission = if self.kind.available() { self.backend.permission() } else { None };\n Support { backend: self.kind.clone(), permission }\n }\n\n /// Whether anything can be shown.\n pub fn can_post(&self) -> bool {\n self.support().can_post()\n }\n\n /// The memory backend's record (tests).\n pub fn memory_log(&self) -> Option<&Memory> {\n self.memory.as_ref()\n }\n\n /// Where clicks go: the OS backend's threads, or a test playing one.\n pub fn click_sink(&self) -> ClickSink {\n self.sink.clone()\n }\n\n pub fn apply(&mut self, effect: &NoticeEffect) {\n match effect {\n NoticeEffect::Post(n) => self.backend.post(n),\n NoticeEffect::Withdraw(id) => self.backend.withdraw(id),\n }\n }\n\n /// The clicks that arrived since the last call.\n pub fn take_clicks(&self) -> Vec<Click> {\n self.clicks.try_iter().collect()\n }\n}\n\n/// Windows: gives the process the app's notification identity (its AppUserModelID, name and icon under\n/// `HKEY_CURRENT_USER`), before any window opens. Elsewhere nothing.\npub fn register_identity(app_id: &str, name: &str) {\n #[cfg(target_os = \"windows\")]\n if let Err(e) = rune_notify::register(&rune_notify::Identity::new(app_id, name)) {\n eprintln!(\"eloxiv-desktop-rune: notifications: the identity could not be registered: {e}\");\n }\n let _ = (app_id, name);\n}\n\n/// The button a click names (`approve`, `reject`), if it is one.\npub fn decision_of_action(action: &str) -> Option<Decision> {\n match action {\n APPROVE => Some(Decision::Approve),\n REJECT => Some(Decision::Reject),\n _ => None,\n }\n}\n\ntype Hook = Box<dyn FnOnce() + Send>;\n\nfn hooks() -> &'static Mutex<Vec<Hook>> {\n static HOOKS: std::sync::OnceLock<Mutex<Vec<Hook>>> = std::sync::OnceLock::new();\n HOOKS.get_or_init(|| Mutex::new(Vec::new()))\n}\n\n/// What a backend does at exit ([`shutdown`]).\n#[cfg_attr(not(any(unix, target_os = \"windows\")), allow(dead_code))]\nfn on_shutdown(hook: impl FnOnce() + Send + 'static) {\n hooks().lock().unwrap_or_else(|e| e.into_inner()).push(Box::new(hook));\n}\n\n/// At exit (the window closed, or Rune's fast-exit hook): every OS notification the host still shows is withdrawn\n/// (a persistent notification service or the system's history would keep it otherwise) and the backends' threads\n/// stop. Call it once, last.\npub fn shutdown() {\n let hooks = std::mem::take(&mut *hooks().lock().unwrap_or_else(|e| e.into_inner()));\n for hook in hooks {\n hook();\n }\n}\n\n/// This run of the host (random): a native notification's click names it, so a notification left in the system's\n/// history by an earlier run (one that crashed before withdrawing it) does nothing in this one.\npub fn launch_id() -> &'static str {\n static LAUNCH: std::sync::OnceLock<String> = std::sync::OnceLock::new();\n LAUNCH.get_or_init(crate::random_id)\n}\n\n/// Joins `handle`, waiting at most `within`: false when it did not end in time (left running).\n#[cfg_attr(not(all(unix, not(target_os = \"macos\"))), allow(dead_code))]\nfn join_within(handle: std::thread::JoinHandle<()>, within: std::time::Duration) -> bool {\n let (done, ended) = channel();\n let joiner = std::thread::Builder::new().name(\"eloxiv-notify-join\".into()).spawn(move || {\n let _ = handle.join();\n let _ = done.send(());\n });\n joiner.is_ok() && ended.recv_timeout(within).is_ok()\n}\n\n/// macOS's authorisation, asked once and apart from posting: notifications posted before the person answered wait\n/// here, a withdrawn one leaves, and only those still waiting when the answer is \"allowed\" are scheduled (by the\n/// caller, under the same lock as withdrawals).\n#[cfg_attr(not(target_os = \"macos\"), allow(dead_code))]\n#[derive(Debug, Default)]\npub struct AuthQueue {\n state: AuthState,\n waiting: Vec<Notice>,\n}\n\n#[cfg_attr(not(target_os = \"macos\"), allow(dead_code))]\n#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]\npub enum AuthState {\n #[default]\n Unasked,\n Asking,\n Granted,\n Denied,\n}\n\n/// What a post asks the caller to do.\n#[cfg_attr(not(target_os = \"macos\"), allow(dead_code))]\n#[derive(Debug, PartialEq)]\npub enum AuthStep {\n /// Ask the person (once); the notification waits for the answer.\n Ask,\n /// Schedule it now (allowed already).\n Show(Box<Notice>),\n}\n\n#[cfg_attr(not(target_os = \"macos\"), allow(dead_code))]\nimpl AuthQueue {\n pub fn post(&mut self, notice: Notice) -> Option<AuthStep> {\n match self.state {\n AuthState::Granted => Some(AuthStep::Show(Box::new(notice))),\n AuthState::Denied => None,\n AuthState::Unasked | AuthState::Asking => {\n self.waiting.retain(|n| n.id != notice.id);\n self.waiting.push(notice);\n (self.state == AuthState::Unasked).then(|| {\n self.state = AuthState::Asking;\n AuthStep::Ask\n })\n }\n }\n }\n\n pub fn withdraw(&mut self, id: &str) {\n self.waiting.retain(|n| n.id != id);\n }\n\n /// The person answered: the notifications still waiting, to schedule now (none when they declined).\n pub fn answered(&mut self, granted: bool) -> Vec<Notice> {\n self.state = if granted { AuthState::Granted } else { AuthState::Denied };\n let waiting = std::mem::take(&mut self.waiting);\n if granted { waiting } else { Vec::new() }\n }\n\n /// The system's settings say `permission` before anything was asked: an answer given before needs no asking.\n pub fn known(&mut self, permission: Option<Permission>) {\n if self.state == AuthState::Unasked {\n match permission {\n Some(Permission::Granted) => self.state = AuthState::Granted,\n Some(Permission::Denied) => self.state = AuthState::Denied,\n _ => {}\n }\n }\n }\n\n #[cfg(test)]\n pub fn state(&self) -> AuthState {\n self.state\n }\n}\n\n/// A notification's text as literal text for the freedesktop service: a service that reads markup in bodies\n/// (`body-markup`) gets `&`, `<` and `>` escaped, so a body never carries a link, an image or formatting the service\n/// would act on; one that does not reads it as it is.\npub fn plain_text(body: &str, markup: bool) -> String {\n if !markup {\n return body.to_owned();\n }\n let mut out = String::with_capacity(body.len());\n for c in body.chars() {\n match c {\n '&' => out.push_str(\"&amp;\"),\n '<' => out.push_str(\"&lt;\"),\n '>' => out.push_str(\"&gt;\"),\n c => out.push(c),\n }\n }\n out\n}\n\n/// The freedesktop service's ids for the host's notifications, bound to the instance of the service that gave them\n/// (its unique bus name): a notification service that restarts (a new owner of `org.freedesktop.Notifications`, with a\n/// fresh counter) cannot map a click to one of the host's notifications by an id the old one gave. Every post's\n/// buttons carry a nonce of their own (`approve:<nonce>`), so a reused id cannot press another post's button either.\n#[derive(Debug, Default)]\npub struct ServiceIds {\n /// The notifications the host wants shown now (posted, not withdrawn): a post still queued or on its way when\n /// its notification is withdrawn is not sent, or is closed as soon as it is answered.\n live: HashSet<String>,\n owner: Option<String>,\n by_server: std::collections::HashMap<u32, Posted>,\n by_notice: std::collections::HashMap<String, u32>,\n tokens: std::collections::HashMap<u32, String>,\n}\n\n#[derive(Clone, Debug)]\nstruct Posted {\n notice: String,\n generation: i64,\n nonce: String,\n}\n\nimpl ServiceIds {\n /// The host posts `notice` (queued for the worker).\n pub fn want(&mut self, notice: &str) {\n self.live.insert(notice.to_owned());\n }\n\n /// The host withdraws `notice`: a post of it still queued is not sent.\n pub fn unwant(&mut self, notice: &str) {\n self.live.remove(notice);\n }\n\n /// Whether the host still wants `notice` shown.\n pub fn wanted(&self, notice: &str) -> bool {\n self.live.contains(notice)\n }\n\n /// Everything shown, to withdraw at exit (the owner and its ids); nothing is wanted any more.\n pub fn drain(&mut self) -> Vec<(String, u32)> {\n self.live.clear();\n self.by_notice.clear();\n self.tokens.clear();\n let owner = self.owner.clone().unwrap_or_default();\n let mut shown: Vec<(String, u32)> = self.by_server.drain().map(|(server, _)| (owner.clone(), server)).collect();\n shown.sort();\n shown\n }\n\n /// The id to replace when posting `notice` again (0: none).\n pub fn replaces(&self, notice: &str) -> u32 {\n self.by_notice.get(notice).copied().unwrap_or(0)\n }\n\n /// The service `owner` answered a post of `notice` (of `generation`, buttons under `nonce`) with `server`: false\n /// when the host withdrew it meanwhile (the caller closes it at once). A new owner (the service restarted) forgets\n /// every id of the one before.\n pub fn posted(&mut self, owner: &str, server: u32, notice: &str, generation: i64, nonce: &str) -> bool {\n if self.owner.as_deref() != Some(owner) {\n self.by_server.clear();\n self.by_notice.clear();\n self.tokens.clear();\n self.owner = Some(owner.to_owned());\n }\n if !self.live.contains(notice) {\n return false;\n }\n if let Some(old) = self.by_notice.insert(notice.to_owned(), server)\n && old != server\n {\n self.by_server.remove(&old);\n self.tokens.remove(&old);\n }\n self.by_server.insert(server, Posted { notice: notice.to_owned(), generation, nonce: nonce.to_owned() });\n true\n }\n\n /// Where `notice` is shown (the owner and its id), to withdraw it: forgotten here.\n pub fn take(&mut self, notice: &str) -> Option<(String, u32)> {\n let server = self.by_notice.remove(notice)?;\n self.by_server.remove(&server);\n self.tokens.remove(&server);\n Some((self.owner.clone()?, server))\n }\n\n /// `ActivationToken` from `sender` for `server`.\n pub fn token(&mut self, sender: &str, server: u32, token: String) {\n if self.owner.as_deref() == Some(sender) && self.by_server.contains_key(&server) {\n self.tokens.insert(server, token);\n }\n }\n\n /// `ActionInvoked` from `sender`: the click it stands for, if `sender` is the service that posted `server` and\n /// `key` is that post's (`default`, or a button under its nonce).\n pub fn action(&mut self, sender: &str, server: u32, key: &str) -> Option<Click> {\n if self.owner.as_deref() != Some(sender) {\n return None;\n }\n let posted = self.by_server.get(&server)?;\n let action = if key == \"default\" {\n None\n } else {\n let (verb, nonce) = key.split_once(':')?;\n if nonce != posted.nonce {\n return None;\n }\n Some(decision_of_action(verb)?)\n };\n let (notice, generation) = (posted.notice.clone(), posted.generation);\n Some(Click { notice, generation, action, token: self.tokens.remove(&server) })\n }\n\n /// `NotificationClosed` from `sender` for `server`.\n pub fn closed(&mut self, sender: &str, server: u32) {\n if self.owner.as_deref() == Some(sender)\n && let Some(posted) = self.by_server.remove(&server)\n {\n self.by_notice.remove(&posted.notice);\n self.tokens.remove(&server);\n }\n }\n}\n\n#[cfg(target_os = \"macos\")]\n#[path = \"notices_mac.rs\"]\nmod mac;\n\n#[cfg(any(target_os = \"macos\", target_os = \"windows\"))]\nmod native {\n //! `rune-notify`: clicks on both systems (the notice's record id, generation and this run's id ride in the\n //! notification's user info), and Windows's toasts.\n use super::*;\n\n /// Windows: the OS ids of the notifications shown now (withdrawn at exit), and the app's id (whose toast setting is\n /// read).\n #[cfg(target_os = \"windows\")]\n pub struct RuneNotify {\n shown: Arc<Mutex<Vec<String>>>,\n app_id: String,\n }\n\n /// Windows: the app's toast setting (Settings › System › Notifications), read now.\n #[cfg(target_os = \"windows\")]\n fn toast_setting(app_id: &str) -> Option<Permission> {\n use windows::UI::Notifications::ToastNotificationManager;\n let notifier =\n ToastNotificationManager::CreateToastNotifierWithId(&windows::core::HSTRING::from(app_id)).ok()?;\n Some(toast_permission(notifier.Setting().ok()?.0))\n }\n\n /// Clicks on the app's notifications, from rune-notify (macOS's delegate, Windows's activations).\n pub fn listen_clicks(sink: ClickSink) {\n rune_notify::on_click(move |click| {\n let (Some(notice), Some(generation)) =\n (click.get(\"notice\"), click.get(\"generation\").and_then(|g| g.parse::<i64>().ok()))\n else {\n return;\n };\n // A notification of an earlier run of the host, left in the system's history: not this run's.\n if click.get(\"launch\") != Some(launch_id()) {\n return;\n }\n let action = match click.action() {\n None => None,\n Some(a) => match decision_of_action(a) {\n Some(d) => Some(d),\n // A button the host never posted: nothing.\n None => return,\n },\n };\n sink.send(Click { notice: notice.to_owned(), generation, action, token: None });\n });\n }\n\n #[cfg(target_os = \"windows\")]\n impl RuneNotify {\n pub fn start(sink: ClickSink, app_id: &str) -> RuneNotify {\n listen_clicks(sink);\n let shown = Arc::new(Mutex::new(Vec::<String>::new()));\n let at_exit = shown.clone();\n on_shutdown(move || {\n let ids = std::mem::take(&mut *at_exit.lock().unwrap_or_else(|e| e.into_inner()));\n let ids: Vec<&str> = ids.iter().map(String::as_str).collect();\n rune_notify::remove(&ids);\n });\n RuneNotify { shown, app_id: app_id.to_owned() }\n }\n }\n\n #[cfg(target_os = \"windows\")]\n fn os_id(id: &str) -> String {\n format!(\"eloxiv-notification-{id}\")\n }\n\n #[cfg(target_os = \"windows\")]\n impl Backend for RuneNotify {\n fn post(&mut self, n: &Notice) {\n let mut note = rune_notify::Notification::new(os_id(&n.id), n.title.clone())\n .body(n.body.clone())\n .info(\"notice\", n.id.clone())\n .info(\"generation\", n.generation.to_string())\n .info(\"launch\", launch_id());\n if n.decision.is_some() {\n note = note.action(APPROVE, \"Approve\").action(REJECT, \"Reject\");\n }\n if !rune_notify::post(&note) {\n eprintln!(\"eloxiv-desktop-rune: notifications: the system refused a notification\");\n }\n let mut shown = self.shown.lock().unwrap_or_else(|e| e.into_inner());\n let id = os_id(&n.id);\n if !shown.contains(&id) {\n shown.push(id);\n }\n }\n fn withdraw(&mut self, id: &str) {\n let id = os_id(id);\n self.shown.lock().unwrap_or_else(|e| e.into_inner()).retain(|s| *s != id);\n rune_notify::remove(&[id.as_str()]);\n }\n fn permission(&self) -> Option<Permission> {\n toast_setting(&self.app_id)\n }\n }\n}\n\n#[cfg(all(unix, not(target_os = \"macos\")))]\nmod freedesktop {\n //! The freedesktop notification service (Desktop Notifications Specification 1.2) over the session bus: `Notify`\n //! with the actions `default` (a click on the notification), `approve:<nonce>` and `reject:<nonce>`;\n //! `CloseNotification` to withdraw one, sent to the instance of the service that showed it; the `ActivationToken`,\n //! `ActionInvoked` and `NotificationClosed` signals for clicks, counted only from that instance ([`ServiceIds`]).\n //! Bodies go as literal text ([`plain_text`]). Posting runs on a thread of its own (the UI thread never waits on\n //! the bus); the signals on another.\n use super::*;\n use std::collections::HashMap as Map;\n use zbus::blocking::{Connection, Proxy};\n use zbus::zvariant::Value as Variant;\n\n const SERVICE: &str = \"org.freedesktop.Notifications\";\n const PATH: &str = \"/org/freedesktop/Notifications\";\n\n enum Command {\n Post(Box<Notice>),\n Withdraw(String),\n /// Withdraw everything shown and stop.\n Shutdown,\n }\n\n pub struct Freedesktop {\n ids: Arc<Mutex<Ids>>,\n stopper: Arc<Stopper>,\n }\n\n /// Stops the backend's threads (once): the worker withdraws what is shown and ends, then the connection closes,\n /// which ends the signal listener.\n struct Stopper {\n commands: Mutex<Option<Sender<Command>>>,\n worker: Mutex<Option<std::thread::JoinHandle<()>>>,\n listener: Mutex<Option<std::thread::JoinHandle<()>>>,\n conn: Connection,\n }\n\n impl Stopper {\n fn send(&self, command: Command) {\n if let Some(commands) = self.commands.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {\n let _ = commands.send(command);\n }\n }\n\n /// True when both threads ended within their time.\n fn stop(&self) -> bool {\n let within = std::time::Duration::from_secs(3);\n let commands = self.commands.lock().unwrap_or_else(|e| e.into_inner()).take();\n let Some(commands) = commands else { return true };\n let _ = commands.send(Command::Shutdown);\n drop(commands);\n let worker = self.worker.lock().unwrap_or_else(|e| e.into_inner()).take();\n let worker_ended = worker.is_none_or(|w| join_within(w, within));\n let _ = self.conn.clone().close();\n let listener = self.listener.lock().unwrap_or_else(|e| e.into_inner()).take();\n let listener_ended = listener.is_none_or(|l| join_within(l, within));\n worker_ended && listener_ended\n }\n }\n\n impl Drop for Freedesktop {\n fn drop(&mut self) {\n self.stopper.stop();\n }\n }\n\n fn proxy(conn: &Connection) -> Result<Proxy<'static>, String> {\n Proxy::new(conn, SERVICE, PATH, SERVICE).map_err(|e| e.to_string())\n }\n\n /// Withdraws notification `server` from the instance of the service `owner` that showed it.\n fn close(conn: &Connection, owner: &str, server: u32) {\n if let Ok(p) = Proxy::new(conn, owner.to_owned(), PATH, SERVICE) {\n let _ = p.call::<_, _, ()>(\"CloseNotification\", &(server,));\n }\n }\n\n impl Freedesktop {\n /// Connects to the session bus and asks the service who it is (an error: none here).\n pub fn start(name: &str, app_id: &str, sink: ClickSink) -> Result<Freedesktop, String> {\n // A service that does not answer within a second counts as none.\n let conn = zbus::blocking::connection::Builder::session()\n .map(|b| b.method_timeout(std::time::Duration::from_secs(1)))\n .and_then(|b| b.build())\n .map_err(|e| e.to_string())?;\n let p = proxy(&conn)?;\n let (server, vendor, version, spec): (String, String, String, String) =\n p.call(\"GetServerInformation\", &()).map_err(|e| e.to_string())?;\n let caps: Vec<String> = p.call(\"GetCapabilities\", &()).unwrap_or_default();\n let markup = caps.iter().any(|c| c == \"body-markup\");\n eprintln!(\n \"eloxiv-desktop-rune: notifications: {server} ({vendor} {version}, spec {spec}){}\",\n if caps.iter().any(|c| c == \"actions\") { \"\" } else { \", without buttons\" }\n );\n let ids = Arc::new(Mutex::new(ServiceIds::default()));\n let (commands, inbox) = channel::<Command>();\n let (app_name, entry) = (name.to_owned(), app_id.to_owned());\n let (post_conn, post_ids) = (conn.clone(), ids.clone());\n let worker = std::thread::Builder::new()\n .name(\"eloxiv-notify\".into())\n .spawn(move || {\n let Ok(p) = proxy(&post_conn) else { return };\n for command in inbox {\n match command {\n Command::Post(n) => post(&p, &post_conn, &post_ids, &app_name, &entry, markup, &n),\n Command::Withdraw(id) => {\n let shown = post_ids.lock().ok().and_then(|mut i| i.take(&id));\n if let Some((owner, server)) = shown {\n close(&post_conn, &owner, server);\n }\n }\n Command::Shutdown => {\n let shown = post_ids.lock().map(|mut i| i.drain()).unwrap_or_default();\n for (owner, server) in shown {\n close(&post_conn, &owner, server);\n }\n return;\n }\n }\n }\n })\n .map_err(|e| e.to_string())?;\n let (listen_conn, listen_ids) = (conn.clone(), ids.clone());\n let listener = std::thread::Builder::new()\n .name(\"eloxiv-notify-signals\".into())\n .spawn(move || listen(&listen_conn, &listen_ids, &sink))\n .map_err(|e| e.to_string())?;\n let stopper = Arc::new(Stopper {\n commands: Mutex::new(Some(commands)),\n worker: Mutex::new(Some(worker)),\n listener: Mutex::new(Some(listener)),\n conn,\n });\n let at_exit = stopper.clone();\n on_shutdown(move || {\n at_exit.stop();\n });\n Ok(Freedesktop { ids, stopper })\n }\n\n /// Stops it now (as at exit): what it shows is withdrawn, its threads end. True when they ended in time.\n #[cfg_attr(not(test), allow(dead_code))]\n pub fn stop(&self) -> bool {\n self.stopper.stop()\n }\n }\n\n fn post(p: &Proxy<'_>, conn: &Connection, ids: &Mutex<Ids>, app_name: &str, entry: &str, markup: bool, n: &Notice) {\n let Ok(replaces) = ids.lock().map(|i| i.wanted(&n.id).then(|| i.replaces(&n.id))) else { return };\n // Withdrawn while it waited in the queue (a switch, a sign-out): not sent.\n let Some(replaces) = replaces else { return };\n // The buttons are this post's own: a click on another post's (an id the service reused) is not one of them.\n let nonce = crate::random_id();\n let (approve, reject) = (format!(\"{APPROVE}:{nonce}\"), format!(\"{REJECT}:{nonce}\"));\n let mut actions = vec![\"default\", \"Open\"];\n if n.decision.is_some() {\n actions.extend([approve.as_str(), \"Approve\", reject.as_str(), \"Reject\"]);\n }\n let mut hints: Map<&str, Variant<'_>> = Map::new();\n hints.insert(\"desktop-entry\", Variant::from(entry));\n hints.insert(\"urgency\", Variant::from(1u8));\n hints.insert(\"category\", Variant::from(\"im.received\"));\n let body = plain_text(&n.body, markup);\n let answer =\n p.call_method(\"Notify\", &(app_name, replaces, \"\", n.title.as_str(), body.as_str(), actions, hints, -1i32));\n let answer = answer.map_err(|e| e.to_string()).and_then(|m| {\n let owner = m.header().sender().map(|s| s.to_string()).ok_or(\"an answer from no one\")?;\n let server: u32 = m.body().deserialize().map_err(|e| e.to_string())?;\n Ok((owner, server))\n });\n match answer {\n Ok((owner, server)) => {\n let wanted = ids.lock().is_ok_and(|mut i| i.posted(&owner, server, &n.id, n.generation, &nonce));\n if !wanted {\n // Withdrawn while the service answered: taken back at once.\n close(conn, &owner, server);\n }\n }\n Err(e) => eprintln!(\"eloxiv-desktop-rune: notifications: Notify failed: {e}\"),\n }\n }\n\n type Ids = ServiceIds;\n\n fn listen(conn: &Connection, ids: &Mutex<Ids>, sink: &ClickSink) {\n let Ok(p) = proxy(conn) else { return };\n let Ok(signals) = p.receive_all_signals() else {\n eprintln!(\"eloxiv-desktop-rune: notifications: clicks cannot be heard\");\n return;\n };\n for message in signals {\n let header = message.header();\n let (Some(member), Some(sender)) = (header.member(), header.sender()) else { continue };\n let sender = sender.to_string();\n let body = message.body();\n match member.as_str() {\n \"ActivationToken\" => {\n if let (Ok((server, token)), Ok(mut i)) = (body.deserialize::<(u32, String)>(), ids.lock()) {\n i.token(&sender, server, token);\n }\n }\n \"ActionInvoked\" => {\n let Ok((server, key)) = body.deserialize::<(u32, String)>() else { continue };\n let click = ids.lock().ok().and_then(|mut i| i.action(&sender, server, &key));\n if let Some(click) = click {\n sink.send(click);\n }\n }\n \"NotificationClosed\" => {\n if let (Ok((server, _reason)), Ok(mut i)) = (body.deserialize::<(u32, u32)>(), ids.lock()) {\n i.closed(&sender, server);\n }\n }\n _ => {}\n }\n }\n }\n\n impl Backend for Freedesktop {\n fn post(&mut self, n: &Notice) {\n if let Ok(mut i) = self.ids.lock() {\n i.want(&n.id);\n }\n self.stopper.send(Command::Post(Box::new(n.clone())));\n }\n fn withdraw(&mut self, id: &str) {\n // At once, so a post of it still queued is not sent.\n if let Ok(mut i) = self.ids.lock() {\n i.unwant(id);\n }\n self.stopper.send(Command::Withdraw(id.to_owned()));\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use serde_json::json;\n\n fn n(id: &str, at: i64) -> Value {\n json!({ \"id\": id, \"orgId\": \"acme\", \"recipientId\": \"u-alice\", \"category\": \"hello.greeted\", \"title\": format!(\"t {id}\"),\n \"body\": \"b\", \"createdAt\": at, \"readAt\": null, \"dismissedAt\": null })\n }\n\n fn posted(effects: &[NoticeEffect]) -> Vec<String> {\n effects\n .iter()\n .filter_map(|e| match e {\n NoticeEffect::Post(n) => Some(n.id.clone()),\n NoticeEffect::Withdraw(_) => None,\n })\n .collect()\n }\n\n #[test]\n fn only_rows_after_the_baseline_are_shown_once() {\n let mut f = Feed::new(1);\n let old = [n(\"n1\", 100), n(\"n2\", 200)];\n // A cached snapshot first, then the complete one: both old.\n assert!(f.rows(RowsStatus::Cached, &old[..1], \"u-alice\", \"acme\", &[]).is_empty());\n assert!(f.rows(RowsStatus::Complete, &old, \"u-alice\", \"acme\", &[]).is_empty());\n let new = [n(\"n3\", 300), n(\"n1\", 100), n(\"n2\", 200)];\n assert_eq!(posted(&f.rows(RowsStatus::Complete, &new, \"u-alice\", \"acme\", &[])), [\"n3\"]);\n assert!(f.rows(RowsStatus::Complete, &new, \"u-alice\", \"acme\", &[]).is_empty(), \"deduplicated by id\");\n // Older than the baseline (synced late), read, someone else's, another organisation's: never shown.\n let mut read = n(\"n5\", 400);\n read[\"readAt\"] = json!(401);\n let mut theirs = n(\"n6\", 400);\n theirs[\"recipientId\"] = json!(\"u-bob\");\n let mut other_org = n(\"n7\", 400);\n other_org[\"orgId\"] = json!(\"globex\");\n let rows = [n(\"n4\", 150), read, theirs, other_org, n(\"n3\", 300)];\n assert!(posted(&f.rows(RowsStatus::Complete, &rows, \"u-alice\", \"acme\", &[])).is_empty());\n assert_eq!(f.shown().iter().map(|s| s.id.as_str()).collect::<Vec<_>>(), [\"n3\"]);\n }\n\n #[test]\n fn a_row_read_elsewhere_is_withdrawn_and_a_reset_withdraws_everything() {\n let mut f = Feed::new(1);\n f.rows(RowsStatus::Complete, &[], \"u-alice\", \"acme\", &[]);\n f.rows(RowsStatus::Complete, &[n(\"a\", 1), n(\"b\", 2)], \"u-alice\", \"acme\", &[]);\n let mut a = n(\"a\", 1);\n a[\"readAt\"] = json!(5);\n assert_eq!(\n f.rows(RowsStatus::Complete, &[a, n(\"b\", 2)], \"u-alice\", \"acme\", &[]),\n vec![NoticeEffect::Withdraw(\"a\".into())]\n );\n assert_eq!(f.reset(2), vec![NoticeEffect::Withdraw(\"b\".into())]);\n assert!(f.shown().is_empty() && f.generation == 2);\n // The new generation has its own baseline: b is old there.\n assert!(f.rows(RowsStatus::Complete, &[n(\"b\", 2)], \"u-alice\", \"acme\", &[]).is_empty());\n }\n\n fn linking(id: &str, at: i64, category: &str, module: &str, record: &str) -> Value {\n let mut v = n(id, at);\n v[\"category\"] = json!(category);\n v[\"title\"] = json!(\"Pay Mallory now\");\n v[\"body\"] = json!(\"{\\\"to\\\":\\\"everyone\\\"}\");\n v[\"linkModule\"] = json!(module);\n v[\"linkEntity\"] = json!(\"request\");\n v[\"linkId\"] = json!(record);\n v\n }\n\n fn approval(id: &str, action: &str) -> Decidable {\n Decidable {\n kind: DecisionKind::Approval,\n id: id.into(),\n action: action.into(),\n title: crate::chat::readable_action_name(action),\n }\n }\n\n #[test]\n fn decisions_come_only_from_the_authoritative_requests_with_their_words() {\n let mut f = Feed::new(1);\n f.rows(RowsStatus::Complete, &[], \"u-alice\", \"acme\", &[]);\n let consent = Decidable {\n kind: DecisionKind::Consent,\n id: \"cns_1\".into(),\n action: \"agent.moveResources\".into(),\n title: \"Move agent resources\".into(),\n };\n let decidable = [approval(\"apr_1\", \"people.offboard\"), consent];\n let rows = [\n // A request the rows say the person can decide, from the kernel's notification.\n linking(\"na\", 10, \"approvals.requested\", \"approvals\", \"apr_1\"),\n // Any notification linking a decidable request offers it, in the request's words (not the title).\n linking(\"nh\", 11, \"hello.greeted\", \"approvals\", \"apr_1\"),\n linking(\"nc\", 12, CONSENT_CATEGORY, \"consent\", \"cns_1\"),\n // A reserved-looking category whose request the rows do not have: it only navigates.\n linking(\"nf\", 13, \"approvals.requested\", \"approvals\", \"apr_forged\"),\n linking(\"ng\", 14, \"approvals.requested\", \"hello\", \"g1\"),\n ];\n f.rows(RowsStatus::Complete, &rows, \"u-alice\", \"acme\", &decidable);\n let shown = f.shown();\n assert_eq!(shown[0].decision, Some((DecisionKind::Approval, \"apr_1\".into())));\n assert_eq!((shown[0].title.as_str(), shown[0].body.as_str()), (APPROVAL_TITLE, \"Offboard (people)\"));\n assert_eq!(shown[1].decision, Some((DecisionKind::Approval, \"apr_1\".into())));\n assert_eq!(shown[1].title, APPROVAL_TITLE, \"never the notification's own words beside the buttons\");\n assert_eq!(shown[2].decision, Some((DecisionKind::Consent, \"cns_1\".into())));\n assert_eq!(shown[2].title, format!(\"{CONSENT_TITLE} Move agent resources\"), \"the request's words\");\n assert_eq!(shown[2].body, CONSENT_BODY, \"a held call's input is not shown\");\n assert_eq!(shown[3].decision, None, \"no request in the rows: no buttons\");\n assert_eq!(shown[3].title, \"Pay Mallory now\");\n assert_eq!(shown[4].decision, None);\n\n // The request synced after the notification: offered then, in its words; decided elsewhere: withdrawn.\n let later = [approval(\"apr_1\", \"people.offboard\"), approval(\"apr_forged\", \"people.hire\")];\n let effects = f.refresh(&later);\n assert_eq!(posted(&effects), [\"nf\"]);\n assert!(effects.contains(&NoticeEffect::Withdraw(\"nc\".into())), \"the consent is no longer held\");\n assert_eq!(f.find(\"nf\").map(|n| n.title.as_str()), Some(APPROVAL_TITLE));\n let gone = f.refresh(&[approval(\"apr_forged\", \"people.hire\")]);\n assert_eq!(gone, vec![NoticeEffect::Withdraw(\"na\".into()), NoticeEffect::Withdraw(\"nh\".into())]);\n }\n\n #[test]\n fn approvals_the_person_may_decide_are_pending_unexpired_and_someone_elses() {\n let rows = [\n json!({ \"id\": \"a1\", \"requesterId\": \"u-ben\", \"action\": \"x.pay\", \"status\": \"pending\", \"expiresAt\": null }),\n json!({ \"id\": \"a2\", \"requesterId\": \"u-alice\", \"action\": \"x.pay\", \"status\": \"pending\" }),\n json!({ \"id\": \"a3\", \"requesterId\": \"u-ben\", \"action\": \"x.pay\", \"status\": \"approved\" }),\n json!({ \"id\": \"a4\", \"requesterId\": \"u-ben\", \"action\": \"x.pay\", \"status\": \"pending\", \"expiresAt\": 1_000 }),\n json!({ \"id\": \"a5\", \"requesterId\": \"u-ben\", \"action\": \"x.pay\", \"status\": \"pending\", \"expiresAt\": 9_000 }),\n ];\n let ids: Vec<String> = decidable_approvals(&rows, \"u-alice\", 5_000).into_iter().map(|d| d.id).collect();\n assert_eq!(ids, [\"a1\", \"a5\"]);\n }\n\n #[test]\n fn a_make_action_s_request_is_offered_in_words_from_its_id_never_its_stored_title() {\n let rows = [\n json!({ \"id\": \"a1\", \"requesterId\": \"u-ben\", \"action\": \"mk_pay.send\", \"title\": \"Tidy up your list\", \"status\": \"pending\" }),\n json!({ \"id\": \"a2\", \"requesterId\": \"u-ben\", \"action\": \"people.offboard\", \"title\": \"Offboard a person\", \"status\": \"pending\" }),\n ];\n let titles: Vec<String> = decidable_approvals(&rows, \"u-alice\", 0).into_iter().map(|d| d.title).collect();\n assert_eq!(titles, [\"mk_pay: Send\", \"Offboard a person\"]);\n }\n\n #[test]\n fn only_complete_snapshots_show_or_withdraw() {\n let mut f = Feed::new(1);\n f.rows(RowsStatus::Complete, &[], \"u-alice\", \"acme\", &[]);\n f.rows(RowsStatus::Complete, &[n(\"a\", 1)], \"u-alice\", \"acme\", &[]);\n assert_eq!(f.shown().len(), 1);\n // A failed snapshot has no rows: it says nothing about what was read.\n assert!(f.rows(RowsStatus::Error, &[], \"u-alice\", \"acme\", &[]).is_empty());\n // A cached or unknown one is not the server's word: nothing new is inferred from it, nothing withdrawn.\n assert!(f.rows(RowsStatus::Cached, &[n(\"b\", 2)], \"u-alice\", \"acme\", &[]).is_empty());\n assert!(f.rows(RowsStatus::Unknown, &[], \"u-alice\", \"acme\", &[]).is_empty());\n assert_eq!(f.shown().len(), 1);\n assert_eq!(posted(&f.rows(RowsStatus::Complete, &[n(\"b\", 2), n(\"a\", 1)], \"u-alice\", \"acme\", &[])), [\"b\"]);\n }\n\n #[test]\n fn the_baselines_newest_row_counts_only_in_the_scope_shown() {\n let mut f = Feed::new(1);\n // Another organisation's row with a later time in the baseline does not hide the person's later rows.\n let mut other = n(\"o\", 900);\n other[\"orgId\"] = json!(\"globex\");\n f.rows(RowsStatus::Complete, &[n(\"a\", 100), other], \"u-alice\", \"acme\", &[]);\n assert_eq!(posted(&f.rows(RowsStatus::Complete, &[n(\"b\", 500), n(\"a\", 100)], \"u-alice\", \"acme\", &[])), [\"b\"]);\n }\n\n #[test]\n fn only_the_answer_to_the_subscription_asked_for_now_counts() {\n let mut f = Feed::new(1);\n f.requested = Some(1);\n f.subscribing(1, \"a\".into());\n f.subscribing_requests(1, \"ra\".into());\n // The stream opened again: asked again, under new ids.\n f.stream_reopened();\n f.requested = Some(1);\n f.subscribing(1, \"b\".into());\n f.subscribing_requests(1, \"rb\".into());\n assert!(!f.subscribed(1, \"a\", \"a\".into()), \"the old answer is let go\");\n assert!(!f.subscribed_requests(1, \"ra\", \"ra\".into()));\n f.subscribe_failed(1, \"a\");\n assert_eq!((f.subscription.as_deref(), f.requested), (Some(\"b\"), Some(1)), \"an old failure changes nothing\");\n assert!(f.subscribed(1, \"b\", \"b\".into()) && f.subscribed_requests(1, \"rb\", \"rb\".into()));\n assert_eq!(f.requests_subscription.as_deref(), Some(\"rb\"));\n }\n\n #[test]\n fn freedesktop_bodies_are_literal_text() {\n let body = \"<a href=\\\"https://x.test\\\">pay</a> & <img src=\\\"file:///etc/passwd\\\"/>\";\n assert_eq!(\n plain_text(body, true),\n \"&lt;a href=\\\"https://x.test\\\"&gt;pay&lt;/a&gt; &amp; &lt;img src=\\\"file:///etc/passwd\\\"/&gt;\"\n );\n assert_eq!(plain_text(body, false), body, \"a service that reads no markup shows it as it is\");\n }\n\n #[test]\n fn a_restarted_notification_service_cannot_click_the_hosts_notifications() {\n let mut ids = ServiceIds::default();\n for notice in [\"n-apr\", \"n-new\", \"n-x\"] {\n ids.want(notice);\n }\n ids.posted(\":1.10\", 7, \"n-apr\", 3, \"nonce-a\");\n ids.token(\":1.10\", 7, \"tok\".into());\n assert_eq!(\n ids.action(\":1.10\", 7, \"approve:nonce-a\"),\n Some(Click {\n notice: \"n-apr\".into(),\n generation: 3,\n action: Some(Decision::Approve),\n token: Some(\"tok\".into())\n })\n );\n // The service restarts (a new owner, its counter from 1 again) and gives the same id to another app's\n // notification: its signals are not the host's.\n assert_eq!(ids.action(\":1.42\", 7, \"default\"), None);\n assert_eq!(ids.action(\":1.42\", 7, \"approve:nonce-a\"), None);\n // A button key of another post (a reused id under the same owner) is not this post's.\n assert_eq!(ids.action(\":1.10\", 7, \"approve:nonce-b\"), None);\n assert_eq!(ids.action(\":1.10\", 7, \"approve\"), None);\n // The host posts through the new owner: the old one's ids are forgotten.\n ids.posted(\":1.42\", 1, \"n-new\", 4, \"nonce-c\");\n assert_eq!(ids.action(\":1.10\", 7, \"default\"), None);\n assert_eq!(ids.replaces(\"n-apr\"), 0);\n assert_eq!(ids.take(\"n-new\"), Some((\":1.42\".into(), 1)), \"withdrawn from the instance that showed it\");\n assert_eq!(ids.take(\"n-new\"), None);\n // Closed by the service: forgotten.\n ids.posted(\":1.42\", 2, \"n-x\", 4, \"nonce-d\");\n ids.closed(\":1.10\", 2);\n assert_eq!(ids.replaces(\"n-x\"), 2, \"only the instance that showed it closes it\");\n ids.closed(\":1.42\", 2);\n assert_eq!(ids.action(\":1.42\", 2, \"default\"), None);\n }\n\n #[test]\n fn a_post_withdrawn_before_it_goes_or_while_it_is_answered_is_not_left_shown() {\n let mut ids = ServiceIds::default();\n // A burst of posts, then the switch's withdrawals, all queued for the worker.\n for notice in [\"a\", \"b\", \"c\"] {\n ids.want(notice);\n }\n ids.unwant(\"a\");\n ids.unwant(\"b\");\n assert!(!ids.wanted(\"a\") && !ids.wanted(\"b\"), \"the worker skips their posts\");\n // b's post was already on its way: answered after its withdrawal, it is closed at once (false).\n assert!(!ids.posted(\":1.5\", 11, \"b\", 1, \"n1\"));\n assert!(ids.posted(\":1.5\", 12, \"c\", 1, \"n2\"));\n assert_eq!(ids.take(\"b\"), None, \"never mapped\");\n // At exit: everything still shown is withdrawn.\n assert_eq!(ids.drain(), vec![(\":1.5\".to_owned(), 12)]);\n assert!(!ids.wanted(\"c\"));\n }\n\n /// The real freedesktop service on this desktop (`cargo test -- --ignored`, with a session bus and a notification\n /// service): a notification shown, then the backend stopped as at exit: it is withdrawn and both threads end.\n #[cfg(all(unix, not(target_os = \"macos\")))]\n #[test]\n #[ignore = \"needs a session bus with a notification service\"]\n fn the_real_freedesktop_backend_withdraws_and_stops_at_exit() {\n let (tx, _clicks) = channel();\n let none: crate::backend::Wake = Arc::new(|| {});\n let sink = ClickSink { tx, wake: Arc::new(RwLock::new(none)) };\n let mut backend = freedesktop::Freedesktop::start(\"Eloxiv test\", \"eloxiv-test\", sink).expect(\"a service\");\n let notice = Notice {\n id: \"real-1\".into(),\n generation: 1,\n org_id: \"acme\".into(),\n category: \"hello.greeted\".into(),\n title: \"Eloxiv notification test\".into(),\n body: \"<b>not bold</b> & withdrawn at exit\".into(),\n link: None,\n decision: Some((DecisionKind::Approval, \"apr-1\".into())),\n };\n backend.post(&notice);\n std::thread::sleep(std::time::Duration::from_millis(1500));\n let started = std::time::Instant::now();\n assert!(backend.stop(), \"both threads ended\");\n assert!(started.elapsed() < std::time::Duration::from_secs(4));\n assert!(backend.stop(), \"stopping again does nothing\");\n }\n\n fn notice(id: &str) -> Notice {\n Notice {\n id: id.into(),\n generation: 1,\n org_id: \"acme\".into(),\n category: \"hello.greeted\".into(),\n title: id.into(),\n body: String::new(),\n link: None,\n decision: None,\n }\n }\n\n #[test]\n fn macos_schedules_only_what_is_still_wanted_when_the_person_allows_notifications() {\n let mut q = AuthQueue::default();\n assert_eq!(q.post(notice(\"a\")), Some(AuthStep::Ask), \"the person is asked once, apart from posting\");\n assert_eq!(q.post(notice(\"b\")), None, \"waits for the same answer\");\n // Withdrawn while the system's prompt is open (a switch, a sign-out, read elsewhere).\n q.withdraw(\"a\");\n let shown: Vec<String> = q.answered(true).into_iter().map(|n| n.id).collect();\n assert_eq!(shown, [\"b\"], \"a is never scheduled\");\n assert_eq!(q.post(notice(\"c\")), Some(AuthStep::Show(Box::new(notice(\"c\")))));\n // Declined: nothing waiting is scheduled, and nothing later.\n let mut q = AuthQueue::default();\n q.post(notice(\"a\"));\n assert!(q.answered(false).is_empty());\n assert_eq!(q.post(notice(\"b\")), None);\n // Allowed before (the settings say so): nothing to ask.\n let mut q = AuthQueue::default();\n q.known(Some(Permission::Granted));\n assert_eq!(q.post(notice(\"a\")), Some(AuthStep::Show(Box::new(notice(\"a\")))));\n let mut q = AuthQueue::default();\n q.known(Some(Permission::Prompt));\n assert_eq!((q.post(notice(\"a\")), q.state()), (Some(AuthStep::Ask), AuthState::Asking));\n }\n\n #[test]\n fn the_backend_is_chosen_per_system_and_its_permission_said_honestly() {\n assert_eq!(select(\"macos\", true, None), BackendKind::RuneNotify);\n assert!(matches!(select(\"macos\", false, None), BackendKind::Unavailable(_)));\n assert_eq!(select(\"windows\", true, None), BackendKind::RuneNotify);\n assert!(matches!(select(\"windows\", false, None), BackendKind::Unavailable(_)));\n assert_eq!(select(\"linux\", false, Some(Ok(()))), BackendKind::Freedesktop);\n assert_eq!(select(\"freebsd\", false, Some(Ok(()))), BackendKind::Freedesktop);\n assert!(\n matches!(select(\"linux\", true, Some(Err(\"no service\".into()))), BackendKind::Unavailable(r) if r.contains(\"no service\"))\n );\n assert!(matches!(select(\"ios\", true, Some(Ok(()))), BackendKind::Unavailable(_)));\n // The OS's own answer, mapped: macOS's authorization status, Windows's toast setting.\n assert_eq!(mac_permission(0), Some(Permission::Prompt));\n assert_eq!(mac_permission(1), Some(Permission::Denied));\n assert_eq!([2, 3, 4].map(mac_permission), [Some(Permission::Granted); 3]);\n assert_eq!(mac_permission(7), None);\n assert_eq!(toast_permission(0), Permission::Granted);\n assert_eq!([1, 2, 3, 4].map(toast_permission), [Permission::Denied; 4]);\n // The freedesktop service has no permission to read: none is claimed.\n let freedesktop = Support { backend: BackendKind::Freedesktop, permission: None };\n assert_eq!(freedesktop.to_json(true), json!({ \"shown\": \"while-running\", \"backend\": \"freedesktop\" }));\n // An app whose daemon does not follow the person's notifications shows none.\n assert_eq!(\n freedesktop.to_json(false),\n json!({ \"shown\": \"never\", \"backend\": \"freedesktop\",\n \"reason\": \"the app does not follow the person's notifications (notifications.mine)\" })\n );\n let denied = Support { backend: BackendKind::RuneNotify, permission: Some(Permission::Denied) };\n assert!(!denied.can_post());\n assert_eq!(\n denied.to_json(true),\n json!({ \"shown\": \"never\", \"backend\": \"rune-notify\", \"permission\": \"denied\",\n \"reason\": \"the person turned the app's notifications off\" })\n );\n let prompt = Support { backend: BackendKind::RuneNotify, permission: Some(Permission::Prompt) };\n assert_eq!(\n prompt.to_json(true),\n json!({ \"shown\": \"while-running\", \"backend\": \"rune-notify\", \"permission\": \"prompt\" })\n );\n let none = Support { backend: BackendKind::Unavailable(\"no service\".into()), permission: None };\n assert_eq!(none.to_json(true), json!({ \"shown\": \"never\", \"backend\": \"none\", \"reason\": \"no service\" }));\n let probing = Support { backend: BackendKind::Probing, permission: None };\n assert!(!probing.can_post());\n assert_eq!(decision_of_action(\"approve\"), Some(Decision::Approve));\n assert_eq!(decision_of_action(\"default\"), None);\n }\n}\n",
186
+ "type": "registry:file",
187
+ "target": "desktop-rune/app/src/notices.rs"
188
+ },
189
+ {
190
+ "path": "app/desktop-rune/app/src/notices_mac.rs",
191
+ "content": "//! macOS: the host drives `UNUserNotificationCenter` itself (rune-notify still delivers the clicks, through its\n//! delegate). The person's authorisation is asked once, apart from posting, and a notification is scheduled only once\n//! it is granted and only if it is still wanted then: the check, the scheduling and every withdrawal happen under one\n//! lock ([`AuthQueue`]), so a notification withdrawn while the system's prompt was open (an organisation switch, a\n//! sign-out, read elsewhere) is never shown afterwards. rune-notify's own `post` would keep it in the authorisation\n//! callback and schedule it when the person allows notifications.\n\nuse std::sync::{Arc, Mutex, MutexGuard};\n\nuse eloxiv_mac_notifications as un;\n\nuse super::{\n APPROVE, AuthQueue, AuthStep, Backend, Notice, Permission, REJECT, launch_id, mac_permission, on_shutdown,\n};\n\n/// The category of a notification offering a decision (its Approve and Reject buttons).\nconst DECISION_CATEGORY: &str = \"eloxiv.decision\";\n\nstruct State {\n queue: AuthQueue,\n /// The OS ids scheduled now (withdrawn at exit).\n shown: Vec<String>,\n /// The person's answer as the system reports it (None: not read yet).\n permission: Option<Permission>,\n}\n\npub struct Mac {\n state: Arc<Mutex<State>>,\n}\n\nfn lock(state: &Mutex<State>) -> MutexGuard<'_, State> {\n state.lock().unwrap_or_else(|e| e.into_inner())\n}\n\nfn os_id(id: &str) -> String {\n format!(\"eloxiv-notification-{id}\")\n}\n\nimpl Mac {\n pub fn start() -> Mac {\n let state = Arc::new(Mutex::new(State { queue: AuthQueue::default(), shown: Vec::new(), permission: None }));\n // What the system's settings say now: an answer given before needs no asking.\n let read = state.clone();\n read_settings(move |permission| {\n let mut s = lock(&read);\n s.permission = permission;\n s.queue.known(permission);\n });\n let at_exit = state.clone();\n on_shutdown(move || {\n let ids = std::mem::take(&mut lock(&at_exit).shown);\n remove(&ids);\n });\n Mac { state }\n }\n}\n\nimpl Backend for Mac {\n fn post(&mut self, n: &Notice) {\n let mut s = lock(&self.state);\n match s.queue.post(n.clone()) {\n Some(AuthStep::Show(n)) => {\n schedule(&n);\n s.shown.push(os_id(&n.id));\n }\n Some(AuthStep::Ask) => {\n drop(s);\n let state = self.state.clone();\n request_authorization(move |granted| {\n let mut s = lock(&state);\n s.permission = Some(if granted { Permission::Granted } else { Permission::Denied });\n // Only what is still wanted now, under the lock withdrawals take.\n for n in s.queue.answered(granted) {\n schedule(&n);\n s.shown.push(os_id(&n.id));\n }\n });\n }\n None => {}\n }\n }\n\n fn withdraw(&mut self, id: &str) {\n let mut s = lock(&self.state);\n s.queue.withdraw(id);\n let os = os_id(id);\n s.shown.retain(|x| *x != os);\n remove(&[os]);\n }\n\n fn permission(&self) -> Option<Permission> {\n lock(&self.state).permission\n }\n}\n\n/// `getNotificationSettingsWithCompletionHandler:`: the authorisation status, mapped ([`mac_permission`]).\nfn read_settings(done: impl Fn(Option<Permission>) + 'static) {\n un::read_settings(move |status| done(mac_permission(status)));\n}\n\n/// `requestAuthorizationWithOptions:completionHandler:` (banners): asks the person once; answers at once after that.\nfn request_authorization(done: impl Fn(bool) + 'static) {\n un::request_authorization(done);\n}\n\n/// Schedules `n` now: its record id, generation and this run's id in the user info (what a click hands back), and for a\n/// decision the category with Approve and Reject (neither brings the app forward).\nfn schedule(n: &Notice) {\n let generation = n.generation.to_string();\n let info = [(\"notice\", n.id.as_str()), (\"generation\", generation.as_str()), (\"launch\", launch_id())];\n let decision =\n un::Decision { category: DECISION_CATEGORY, approve: (APPROVE, \"Approve\"), reject: (REJECT, \"Reject\") };\n un::schedule(&os_id(&n.id), &n.title, &n.body, &info, n.decision.is_some().then_some(&decision));\n}\n\n/// Takes these OS ids out of Notification Center, delivered or still scheduled.\nfn remove(ids: &[String]) {\n un::remove(ids);\n}\n",
192
+ "type": "registry:file",
193
+ "target": "desktop-rune/app/src/notices_mac.rs"
194
+ },
195
+ {
196
+ "path": "app/desktop-rune/app/src/outstanding.rs",
197
+ "content": "//! The person's outstanding sends: chat SDK guarantee 4 (`outstandingStore`, `@eloxiv/client/chat`) on this side of\n//! LocalClient. A send's identity is its idempotency key, and it must outlive any screen that made it, so it is kept\n//! here, outside the chat's state ([`crate::chat::Chat`] is dropped with every context reset):\n//!\n//! - **Written ahead.** A send is recorded before its request leaves, and whatever answers it is recorded when it\n//! comes, whether or not the generation or screen that made it still exists.\n//! - **Settled only by a definitive outcome for its key**: an answer, a replay of its receipt, a refusal of its\n//! first and only attempt, or the person discarding it. Its answer lost, it is kept, to be resent under its key; a\n//! refusal after that (a policy or credential change) proves nothing about the earlier attempt, so it is kept as\n//! `unconfirmed` under its key: resending it under that key replays its receipt if it ran (LocalClient has no\n//! receipt lookup), and the person may discard it.\n//! - **Scoped to the person and the organisation**, across organisation switches, sign-outs (for the same person's\n//! next sign-in) and restarts of the host: kept in a small JSON file in the host's data directory\n//! (`outstanding-sends.json`, readable by the person only). Only what identifies a send is kept (its text,\n//! conversation and key), never a credential.\n\nuse std::collections::BTreeMap;\nuse std::path::{Path, PathBuf};\n\nuse serde::{Deserialize, Serialize};\n\n/// The file the sends are kept in, in the host's data directory.\npub const FILE: &str = \"outstanding-sends.json\";\n\n/// Where an outstanding send stands (the chat SDK's `SendState`, as far as this host goes).\n#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]\n#[serde(rename_all = \"kebab-case\")]\npub enum SendState {\n /// An attempt is in flight. Kept from a run of the host that ended before it answered, it may have run.\n Sending,\n /// Its answer was lost: it may have run, and is resent under its key.\n Uncertain,\n /// It may have run, and a later attempt was refused: kept under its key until an answer settles it (a resend under\n /// the key replays its receipt if it ran) or the person discards it.\n Unconfirmed,\n}\n\n/// One send whose outcome is not settled: the chat SDK's `OutstandingSend`, the same JSON.\n#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]\n#[serde(rename_all = \"camelCase\")]\npub struct OutstandingSend {\n pub text: String,\n /// The conversation it was sent from (None: a new one).\n pub conversation_id: Option<String>,\n /// Its idempotency key: its identity, the same on every attempt.\n pub key: String,\n pub state: SendState,\n /// Whether it may have run (an attempt went unanswered).\n pub doubtful: bool,\n}\n\n/// What became of an attempt of a send.\n#[derive(Clone, Debug, PartialEq)]\npub enum Outcome {\n /// It ran: an answer, or a replay of its receipt.\n Ran,\n /// The daemon or the kernel answered with a refusal: nothing ran.\n Refused,\n /// No answer, or one that may hide a send that ran.\n Lost,\n /// The person gave up on it.\n Discarded,\n}\n\n/// The sends once `outcome` is known for the one under `key` (unchanged when none has that key).\npub fn settle(sends: &mut Vec<OutstandingSend>, key: &str, outcome: &Outcome) {\n let Some(at) = sends.iter().position(|s| s.key == key) else { return };\n match outcome {\n // A refusal of the first and only attempt: nothing ran.\n Outcome::Refused if !sends[at].doubtful => {\n sends.remove(at);\n }\n // After an attempt that went unanswered, a refusal proves nothing about it.\n Outcome::Refused => sends[at].state = SendState::Unconfirmed,\n Outcome::Ran | Outcome::Discarded => {\n sends.remove(at);\n }\n Outcome::Lost => {\n let send = &mut sends[at];\n send.state = SendState::Uncertain;\n send.doubtful = true;\n }\n }\n}\n\n/// `send` in place of the one under its key, or added.\npub fn put(sends: &mut Vec<OutstandingSend>, send: OutstandingSend) {\n match sends.iter_mut().find(|s| s.key == send.key) {\n Some(known) => *known = send,\n None => sends.push(send),\n }\n}\n\n/// Whose sends: a person, in an organisation.\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct Scope {\n pub user_id: String,\n pub org_id: String,\n}\n\n/// The file's content: every person's sends, by organisation.\n#[derive(Debug, Default, Serialize, Deserialize)]\nstruct Kept {\n version: u32,\n people: BTreeMap<String, BTreeMap<String, Vec<OutstandingSend>>>,\n}\n\n/// The outstanding sends, per person and organisation: in [`FILE`] under `dir` when the host has a data directory,\n/// else in memory. Hosts sharing the data directory share the file: every read and change is made under an advisory\n/// lock of its own file ([`LOCK`]; released when its holder exits, so a host that died holds nothing), and a change is\n/// applied to the file as it is then, rewritten whole. A file that cannot be parsed is started afresh; one that cannot\n/// be read, written or locked leaves the store in memory for the rest of the run (logged).\n#[derive(Debug, Default)]\npub struct Store {\n path: Option<PathBuf>,\n /// The sends when kept in memory (no data directory, or the file could not be kept).\n kept: Kept,\n}\n\n/// The lock file next to [`FILE`].\npub const LOCK: &str = \"outstanding-sends.json.lock\";\n\nimpl Store {\n /// The store kept under `dir` (None: in memory only).\n pub fn open(dir: Option<&Path>) -> Store {\n Store { path: dir.map(|d| d.join(FILE)), kept: Kept::default() }\n }\n\n /// The scope's sends, in the order they were made, as the file has them now.\n pub fn list(&self, scope: &Scope) -> Vec<OutstandingSend> {\n let read = self.path.as_deref().map(|path| locked(path).and_then(|_lock| load(path)));\n let of = |kept: &Kept| {\n kept.people.get(&scope.user_id).and_then(|orgs| orgs.get(&scope.org_id)).cloned().unwrap_or_default()\n };\n match read {\n Some(Ok(kept)) => of(&kept),\n Some(Err(e)) => {\n eprintln!(\"eloxiv-desktop-rune: could not read the outstanding sends: {e}\");\n of(&self.kept)\n }\n None => of(&self.kept),\n }\n }\n\n /// Record a send (before its request leaves), or its new state.\n pub fn put(&mut self, scope: &Scope, send: OutstandingSend) {\n self.change(scope, |sends| put(sends, send));\n }\n\n /// Record what became of the send under `key` (nothing when none has it now).\n pub fn settle(&mut self, scope: &Scope, key: &str, outcome: &Outcome) {\n self.change(scope, |sends| settle(sends, key, outcome));\n }\n\n /// Apply `f` to the scope's sends as the file has them now, under its lock, and write the file again.\n fn change(&mut self, scope: &Scope, f: impl FnOnce(&mut Vec<OutstandingSend>)) {\n let opened = self.path.clone().map(|path| locked(&path).and_then(|lock| Ok((load(&path)?, path, lock))));\n let (mut kept, file) = match opened {\n Some(Ok((kept, path, lock))) => (kept, Some((path, lock))),\n Some(Err(e)) => {\n self.in_memory(&e);\n (std::mem::take(&mut self.kept), None)\n }\n None => (std::mem::take(&mut self.kept), None),\n };\n let orgs = kept.people.entry(scope.user_id.clone()).or_default();\n let sends = orgs.entry(scope.org_id.clone()).or_default();\n f(sends);\n if sends.is_empty() {\n orgs.remove(&scope.org_id);\n }\n if orgs.is_empty() {\n kept.people.remove(&scope.user_id);\n }\n if let Some((path, _lock)) = file {\n match save(&path, &mut kept) {\n Ok(()) => return,\n Err(e) => self.in_memory(&e),\n }\n }\n self.kept = kept;\n }\n\n /// The file could not be kept: the sends stay in memory for as long as the host runs.\n fn in_memory(&mut self, e: &std::io::Error) {\n if let Some(path) = self.path.take() {\n eprintln!(\"eloxiv-desktop-rune: could not keep the outstanding sends in {}: {e}\", path.display());\n if let Ok(kept) = load(&path) {\n self.kept = kept;\n }\n }\n }\n}\n\n/// The lock of the file at `path`, held until the returned file is dropped.\nfn locked(path: &Path) -> std::io::Result<std::fs::File> {\n if let Some(dir) = path.parent() {\n std::fs::create_dir_all(dir)?;\n }\n let file = open_private(&path.with_file_name(LOCK))?;\n file.lock()?;\n Ok(file)\n}\n\n/// The file's content: none when there is no file, afresh when it cannot be parsed.\nfn load(path: &Path) -> std::io::Result<Kept> {\n match std::fs::read(path) {\n Ok(raw) => Ok(serde_json::from_slice::<Kept>(&raw).unwrap_or_default()),\n Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Kept::default()),\n Err(e) => Err(e),\n }\n}\n\n/// Write the file again (a new file renamed over the old, readable by the person only), or remove it when nothing is\n/// outstanding. Called under the lock.\nfn save(path: &Path, kept: &mut Kept) -> std::io::Result<()> {\n kept.version = 1;\n if kept.people.is_empty() {\n return match std::fs::remove_file(path) {\n Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),\n _ => Ok(()),\n };\n }\n let text = serde_json::to_vec_pretty(kept).map_err(std::io::Error::other)?;\n let next = path.with_extension(\"json.next\");\n write_private(&next, &text)?;\n std::fs::rename(&next, path)\n}\n\n#[cfg(unix)]\nfn open_private(path: &Path) -> std::io::Result<std::fs::File> {\n use std::os::unix::fs::OpenOptionsExt;\n std::fs::OpenOptions::new().write(true).create(true).truncate(false).mode(0o600).open(path)\n}\n\n#[cfg(not(unix))]\nfn open_private(path: &Path) -> std::io::Result<std::fs::File> {\n std::fs::OpenOptions::new().write(true).create(true).truncate(false).open(path)\n}\n\n#[cfg(unix)]\nfn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {\n use std::io::Write;\n use std::os::unix::fs::OpenOptionsExt;\n let mut file = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(path)?;\n file.write_all(bytes)?;\n file.sync_all()\n}\n\n#[cfg(not(unix))]\nfn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {\n // The data directory is the person's own (per-user application data).\n std::fs::write(path, bytes)\n}\n\n/// The host's data directory: `ELOXIV_RUNE_DATA_DIR`, else the platform's per-user application data directory\n/// (`$XDG_DATA_HOME` or `~/.local/share` on Linux, `~/Library/Application Support` on macOS, `%APPDATA%` on Windows)\n/// with the app's identifier (`app.json`) under it; None when there is none (kept in memory only).\npub fn default_data_dir() -> Option<PathBuf> {\n if let Some(dir) = std::env::var_os(\"ELOXIV_RUNE_DATA_DIR\").filter(|d| !d.is_empty()) {\n return Some(PathBuf::from(dir));\n }\n let home = || std::env::var_os(\"HOME\").filter(|h| !h.is_empty()).map(PathBuf::from);\n let base = if cfg!(target_os = \"windows\") {\n std::env::var_os(\"APPDATA\").map(PathBuf::from)\n } else if cfg!(target_os = \"macos\") {\n home().map(|h| h.join(\"Library\").join(\"Application Support\"))\n } else {\n std::env::var_os(\"XDG_DATA_HOME\")\n .filter(|d| !d.is_empty())\n .map(PathBuf::from)\n .or_else(|| home().map(|h| h.join(\".local\").join(\"share\")))\n };\n base.map(|b| b.join(&crate::config::current().app_id))\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n fn send(key: &str) -> OutstandingSend {\n OutstandingSend {\n text: \"hi\".into(),\n conversation_id: None,\n key: key.into(),\n state: SendState::Sending,\n doubtful: false,\n }\n }\n\n struct Gone(PathBuf);\n impl Drop for Gone {\n fn drop(&mut self) {\n let _ = std::fs::remove_dir_all(&self.0);\n }\n }\n\n fn temp_dir() -> (PathBuf, Gone) {\n let dir = std::env::temp_dir().join(format!(\"eloxiv-outstanding-{}\", crate::random_id()));\n (dir.clone(), Gone(dir))\n }\n\n fn keys(sends: &[OutstandingSend]) -> Vec<&str> {\n sends.iter().map(|s| s.key.as_str()).collect()\n }\n\n #[test]\n fn two_hosts_sharing_the_data_directory_keep_each_others_sends() {\n let (dir, _gone) = temp_dir();\n let scope = Scope { user_id: \"u\".into(), org_id: \"acme\".into() };\n // Both open the store while it is empty, then record their own sends one after the other.\n let mut a = Store::open(Some(&dir));\n let mut b = Store::open(Some(&dir));\n a.put(&scope, send(\"key-a\"));\n b.put(&scope, send(\"key-b\"));\n assert_eq!(keys(&Store::open(Some(&dir)).list(&scope)), [\"key-a\", \"key-b\"]);\n // What one settles, the other neither offers nor writes back.\n b.settle(&scope, \"key-a\", &Outcome::Discarded);\n assert_eq!(keys(&a.list(&scope)), [\"key-b\"]);\n a.settle(&scope, \"key-b\", &Outcome::Lost);\n assert_eq!(keys(&Store::open(Some(&dir)).list(&scope)), [\"key-b\"]);\n assert_eq!(b.list(&scope)[0].state, SendState::Uncertain);\n }\n\n #[test]\n fn sends_are_kept_per_person_and_organisation_across_a_restart_and_leave_on_a_definitive_outcome() {\n let (dir, _gone) = temp_dir();\n let (acme, globex) = (\n Scope { user_id: \"u\".into(), org_id: \"acme\".into() },\n Scope { user_id: \"u\".into(), org_id: \"globex\".into() },\n );\n let mut store = Store::open(Some(&dir));\n store.put(&acme, send(\"k1\"));\n store.put(&globex, send(\"k2\"));\n store.settle(&acme, \"k1\", &Outcome::Lost);\n let again = Store::open(Some(&dir));\n assert_eq!(\n again.list(&acme).iter().map(|s| (s.key.as_str(), s.state)).collect::<Vec<_>>(),\n [(\"k1\", SendState::Uncertain)]\n );\n assert_eq!(again.list(&globex).len(), 1);\n let raw = std::fs::read_to_string(dir.join(FILE)).unwrap_or_default();\n assert!(raw.contains(\"\\\"conversationId\\\"\") && !raw.to_lowercase().contains(\"token\"));\n #[cfg(unix)]\n {\n use std::os::unix::fs::PermissionsExt;\n let mode = std::fs::metadata(dir.join(FILE)).map(|m| m.permissions().mode() & 0o777).unwrap_or(0);\n assert_eq!(mode, 0o600);\n }\n store.settle(&acme, \"k1\", &Outcome::Ran);\n store.settle(&globex, \"k2\", &Outcome::Refused);\n assert!(!dir.join(FILE).exists(), \"nothing outstanding: no file\");\n }\n}\n",
198
+ "type": "registry:file",
199
+ "target": "desktop-rune/app/src/outstanding.rs"
200
+ },
201
+ {
202
+ "path": "app/desktop-rune/app/src/routing.rs",
203
+ "content": "//! A deep link, from `App::on_open_url` to a screen: read with the View contract's `parseLink` ([`crate::links`]),\n//! kept until it can be honoured (the app's views known, a signed-in session of the current generation), its\n//! organisation switched to when the person belongs to it (asked once; one they do not belong to is ignored, as the\n//! web shell does), then routed to the host's screen for its view. A link only navigates: nothing in it is sent,\n//! written or run. A MAKE view it names is not opened: the MAKE screen shows with the module filled in, and the\n//! view (whose first step may call the module's actions) runs only when the person presses Open.\n\nuse rune::{TextEdit, Tx};\n\nuse crate::links::{self, Route};\nuse crate::model::Session;\nuse crate::ui::{Screen, Ui};\n\n/// `App::on_open_url`: each link the system opens the app with (the launching one, and every later launch's).\npub fn on_open_url(s: &mut Ui, url: &str, _tx: &mut Tx) {\n s.open_link(url);\n}\n\nimpl Ui {\n /// Opens `url`, now or once it can be honoured. A newer link replaces one still waiting.\n pub fn open_link(&mut self, url: &str) {\n // Not the link itself: it may name a record.\n eprintln!(\"eloxiv-desktop-rune: link received\");\n self.host.pending_link = Some(url.to_owned());\n self.host.pending_link_generation = None;\n self.host.link_org_asked = None;\n self.route_pending();\n }\n\n /// Opens `url` from a notification of `generation`: in that generation, or not at all.\n pub fn open_notice_link(&mut self, url: &str, generation: i64) {\n eprintln!(\"eloxiv-desktop-rune: link received from a notification\");\n self.host.pending_link = Some(url.to_owned());\n self.host.pending_link_generation = Some(generation);\n self.host.link_org_asked = None;\n self.route_pending();\n }\n\n /// A switch or sign-out was asked for: a notification's link waiting to open goes (its generation is ending).\n pub(crate) fn drop_notice_link(&mut self) {\n if self.host.pending_link_generation.take().is_some() {\n self.host.pending_link = None;\n self.host.link_org_asked = None;\n }\n }\n\n /// Routes the waiting link if it can be now. True when anything changed.\n pub(crate) fn route_pending(&mut self) -> bool {\n if self.host.pending_link_generation.is_some_and(|g| g != self.model.generation) {\n // A notification's link of a generation that ended.\n self.host.pending_link = None;\n self.host.pending_link_generation = None;\n return true;\n }\n let (Some(url), Some(table)) = (self.host.pending_link.clone(), self.host.views.as_ref()) else {\n return false;\n };\n let link = match table.parse_link(&url, &self.host.config.scheme, None) {\n Ok(link) => link,\n Err(e) => {\n eprintln!(\"eloxiv-desktop-rune: link refused: {}\", e.reason.name());\n self.host.pending_link = None;\n self.host.pending_link_generation = None;\n self.notice = Some(format!(\"This link does not open anything in this app: {e}\"));\n return true;\n }\n };\n let route = links::route(table, &link);\n let title = table.view(&link.view).map(|v| v.title.clone()).filter(|t| !t.is_empty());\n // Screens need a signed-in session of the current generation; the link waits for one (through sign-in).\n let Session::SignedIn { organizations, org_id, .. } = &self.model.session else { return false };\n if !self.model.usable() || self.busy.is_some() {\n return false;\n }\n if let Some(org) = &link.org {\n let member = organizations.iter().any(|o| &o.org_id == org);\n if member && org_id.as_deref() != Some(org.as_str()) && self.host.link_org_asked.as_deref() != Some(org) {\n self.host.link_org_asked = Some(org.clone());\n let org = org.clone();\n self.select_org(&org);\n return true;\n }\n }\n self.host.pending_link = None;\n self.host.pending_link_generation = None;\n self.host.link_org_asked = None;\n eprintln!(\"eloxiv-desktop-rune: link opened: view {}\", link.view);\n self.host.link_status = Some(format!(\"Opened from a link: {}\", title.as_deref().unwrap_or(&link.view)));\n self.focused_record = None;\n match route {\n Route::Greetings => {\n self.screen = Screen::Greetings;\n // The greeting it names is selected there.\n self.focused_record = link.record.clone();\n }\n Route::Chat if self.model.chat_enabled => {\n self.screen = Screen::Chat;\n // A consent request's card shows in the conversation whose run holds it.\n let conversation =\n link.params.get(links::CONSENT_PARAM).and_then(|id| self.model.chat.conversation_for_consent(id));\n if let Some(conversation) = conversation {\n for effect in self.model.chat.open(&conversation) {\n self.chat_effect(effect);\n }\n }\n }\n Route::Chat => {\n self.host.link_status = None;\n self.notice = Some(\"The agent's conversation is not available in this app.\".into());\n }\n Route::Make(module) => {\n // Filled in, not opened: a link never runs a view's step (its calls run the module's actions).\n self.screen = Screen::Make;\n if let Some(module) = module {\n self.make.module_input = TextEdit::new(module);\n }\n }\n Route::Unavailable(title) => {\n self.host.link_status = None;\n self.notice = Some(format!(\"{title} has no screen in the desktop app yet.\"));\n }\n }\n true\n }\n}\n",
204
+ "type": "registry:file",
205
+ "target": "desktop-rune/app/src/routing.rs"
206
+ },
207
+ {
208
+ "path": "app/desktop-rune/app/src/services.rs",
209
+ "content": "//! The host's own services on the UI thread: its configuration, the app's views for deep links, the updater's\n//! state and secure storage. Their blocking work (asking the sidecar for the views, registering the scheme, checking\n//! and downloading updates) runs on worker threads, whose answers land here through Rune's waker as the backend's do.\n\nuse std::sync::mpsc::{Receiver, Sender, channel};\nuse std::sync::{Arc, RwLock};\n\nuse eloxiv_update::Offer;\n\nuse crate::backend::Wake;\nuse crate::config::HostConfig;\nuse crate::host::{Capabilities, HostError};\nuse crate::keychain::SecureStorage;\nuse crate::links::{self, ViewEntry, ViewTable};\nuse crate::notices::Notifier;\nuse crate::updates::{self, Install, Staged, Updater};\n\n/// What the updater is doing, for the window.\n#[derive(Clone, Debug, PartialEq)]\npub enum UpdateState {\n /// Updates are not available here, and why (`HostUnsupported`).\n Unsupported(String),\n Idle,\n Checking,\n UpToDate,\n Available(Offer),\n Downloading {\n version: String,\n got: u64,\n total: u64,\n },\n /// Verified and staged: applied when the person restarts.\n Ready(Staged),\n Failed(String),\n}\n\nenum Reply {\n Views(Result<Vec<ViewEntry>, String>),\n Registered(Result<links::Registered, String>),\n Checked(Result<Option<Offer>, HostError>),\n Progress { version: String, got: u64, total: u64 },\n Staged(Result<Staged, HostError>),\n}\n\npub struct HostServices {\n pub config: HostConfig,\n /// The views links may name; None until the sidecar answered.\n pub views: Option<ViewTable>,\n /// A link waiting for the views, a session or an organisation switch.\n pub pending_link: Option<String>,\n /// The generation a waiting link from a notification's click belongs to: it opens in that generation or never.\n pub pending_link_generation: Option<i64>,\n /// The organisation a pending link asked to switch to (asked once).\n pub link_org_asked: Option<String>,\n /// What the last link did, for the window.\n pub link_status: Option<String>,\n pub update: UpdateState,\n /// What a restart did (updated, rolled back), for the window.\n pub update_notice: Option<String>,\n updater: Option<Arc<Updater>>,\n /// The person asked to restart into the staged build: the loop quits at its next turn.\n pub quit_requested: bool,\n checked_once: bool,\n started_marked: bool,\n pub secure_storage: Arc<SecureStorage>,\n /// OS notifications for the person's notification records, while the app runs ([`crate::notices`]).\n pub notifier: Notifier,\n replies: Sender<Reply>,\n inbox: Receiver<Reply>,\n wake: Arc<RwLock<Wake>>,\n}\n\nimpl Default for HostServices {\n /// No update host, the host's own screens as the only views, the default identity (tests, an attached host).\n fn default() -> HostServices {\n HostServices::new(HostConfig::default(), None)\n }\n}\n\nimpl HostServices {\n /// The services for `config`, updates through `updater` (None: unsupported, with the configuration's reason).\n pub fn new(config: HostConfig, updater: Option<Updater>) -> HostServices {\n let (replies, inbox) = channel();\n let none: Wake = Arc::new(|| {});\n let wake = Arc::new(RwLock::new(none));\n let update = match updater.as_ref().map(Updater::supported) {\n Some(Ok(())) => UpdateState::Idle,\n Some(Err(HostError::Unsupported { reason, .. })) => UpdateState::Unsupported(reason),\n Some(Err(e)) => UpdateState::Unsupported(e.to_string()),\n None => UpdateState::Unsupported(\"no update host is configured\".into()),\n };\n HostServices {\n secure_storage: Arc::new(SecureStorage::os(&config.app_id)),\n update_notice: updates::restart_notice(&config.version),\n config,\n views: ViewTable::new(Vec::new()).ok(),\n pending_link: None,\n pending_link_generation: None,\n link_org_asked: None,\n link_status: None,\n update,\n updater: updater.map(Arc::new),\n quit_requested: false,\n checked_once: false,\n started_marked: false,\n notifier: Notifier::memory(wake.clone()),\n replies,\n inbox,\n wake,\n }\n }\n\n /// The services of this launch: the configuration's updater for this install, the app's views asked of the\n /// sidecar `views_from`, and the scheme registered with the OS, both off the UI thread.\n pub fn start(config: HostConfig, views_from: Option<crate::sidecar::Launch>) -> HostServices {\n let updater = Updater::new(&config, Install::detect()).remembering(crate::outstanding::default_data_dir());\n let packaged = views_from.as_ref().is_some_and(|l| l.packaged);\n let mut s = HostServices::new(config, Some(updater));\n // Returns at once: a service that must be asked (freedesktop) is asked off the UI thread.\n s.notifier = Notifier::os(&s.config.name, &s.config.app_id, s.wake.clone());\n if s.notifier.poll() || s.notifier.support().backend != crate::notices::BackendKind::Probing {\n eprintln!(\"eloxiv-desktop-rune: notifications: {}\", s.notifier.support().to_json(true));\n }\n // The host's own screens route at once; the app's views replace them when the sidecar answers.\n s.views = None;\n s.spawn(move || Reply::Views(links::load_views(views_from.as_ref())));\n let register = s.config.clone();\n s.spawn(move || Reply::Registered(links::register(&register, packaged)));\n s\n }\n\n /// Notifications recorded in memory, ready only after `delay` (tests: a notification service slow to answer).\n pub fn notifier_ready_after(&mut self, delay: std::time::Duration) {\n self.notifier = Notifier::memory_after(self.wake.clone(), delay);\n }\n\n /// The waker Rune gave the app.\n pub fn set_wake(&mut self, wake: Wake) {\n if let Ok(mut w) = self.wake.write() {\n *w = wake;\n }\n }\n\n fn spawn(&self, job: impl FnOnce() -> Reply + Send + 'static) {\n let (replies, wake) = (self.replies.clone(), self.wake.clone());\n let spawned = std::thread::Builder::new().name(\"eloxiv-host\".into()).spawn(move || {\n let _ = replies.send(job());\n if let Ok(w) = wake.read() {\n w();\n }\n });\n if spawned.is_err() {\n eprintln!(\"eloxiv-desktop-rune: could not start a host thread\");\n }\n }\n\n /// What the host does with notifications: OS notifications while it runs, for an app that follows the person's\n /// notifications (`app_follows`), with the backend and the permission the OS reports (`{ shown, backend,\n /// permission?, reason? }`). Not a push subscription: [`crate::host::push_permission`].\n pub fn notifications(&self, app_follows: bool) -> serde_json::Value {\n self.notifier.support().to_json(app_follows)\n }\n\n /// `capabilities()`.\n pub fn capabilities(&self) -> Capabilities {\n Capabilities {\n deep_links: true,\n push: false,\n secure_storage: self.secure_storage.supported(),\n updates: !matches!(self.update, UpdateState::Unsupported(_)),\n files: false,\n }\n }\n\n /// Lands the workers' answers; `ready`: the window is drawn and the daemon answered. True when anything changed.\n pub fn drain(&mut self, ready: bool) -> bool {\n let mut changed = false;\n if ready && !self.started_marked {\n self.started_marked = true;\n // A build started to try an update tells the build it replaced that it is up.\n updates::mark_started();\n if !self.checked_once && matches!(self.update, UpdateState::Idle) {\n self.checked_once = true;\n self.check_update();\n }\n changed = true;\n }\n while let Ok(reply) = self.inbox.try_recv() {\n changed = true;\n match reply {\n Reply::Views(Ok(views)) => match ViewTable::new(views) {\n Ok(table) => self.views = Some(table),\n Err(e) => {\n eprintln!(\n \"eloxiv-desktop-rune: the app's views are refused ({e}); links open the host's screens only\"\n );\n self.views = ViewTable::new(Vec::new()).ok();\n }\n },\n Reply::Views(Err(e)) => {\n eprintln!(\n \"eloxiv-desktop-rune: the app's views are unknown ({e}); links open the host's screens only\"\n );\n self.views = ViewTable::new(Vec::new()).ok();\n }\n Reply::Registered(Ok(r)) => {\n eprintln!(\"eloxiv-desktop-rune: deep links ({}://): {r:?}\", self.config.scheme)\n }\n Reply::Registered(Err(e)) => {\n eprintln!(\"eloxiv-desktop-rune: the {}:// scheme could not be registered: {e}\", self.config.scheme)\n }\n Reply::Checked(Ok(Some(offer))) => self.update = UpdateState::Available(offer),\n Reply::Checked(Ok(None)) => self.update = UpdateState::UpToDate,\n Reply::Checked(Err(HostError::Unsupported { reason, .. })) => {\n self.update = UpdateState::Unsupported(reason)\n }\n Reply::Checked(Err(e)) => self.update = UpdateState::Failed(e.to_string()),\n Reply::Progress { version, got, total } => {\n if matches!(self.update, UpdateState::Downloading { .. }) {\n self.update = UpdateState::Downloading { version, got, total };\n }\n }\n Reply::Staged(Ok(staged)) => self.update = UpdateState::Ready(staged),\n Reply::Staged(Err(e)) => self.update = UpdateState::Failed(e.to_string()),\n }\n }\n changed\n }\n\n /// `checkUpdate`, off the UI thread.\n pub fn check_update(&mut self) {\n let Some(updater) = self.updater.clone() else { return };\n if matches!(self.update, UpdateState::Unsupported(_) | UpdateState::Checking | UpdateState::Downloading { .. })\n {\n return;\n }\n self.update = UpdateState::Checking;\n self.spawn(move || Reply::Checked(updater.check()));\n }\n\n /// Downloads, verifies and stages the offered build, off the UI thread (`applyUpdate`'s first half).\n pub fn download_update(&mut self) {\n let (Some(updater), UpdateState::Available(offer)) = (self.updater.clone(), self.update.clone()) else {\n return;\n };\n let version = offer.version.to_string();\n self.update = UpdateState::Downloading { version: version.clone(), got: 0, total: offer.size };\n let (replies, wake) = (self.replies.clone(), self.wake.clone());\n self.spawn(move || {\n let mut last = 0u64;\n let mut progress = |got: u64| {\n // A frame per 1 % is plenty.\n if got - last > offer.size / 100 || got == offer.size {\n last = got;\n let _ = replies.send(Reply::Progress { version: version.clone(), got, total: offer.size });\n if let Ok(w) = wake.read() {\n w();\n }\n }\n };\n Reply::Staged(updater.stage(&offer, &mut progress))\n });\n }\n\n /// `applyUpdate`'s second half: the staged build is applied once the window closes, and the loop asked to quit.\n pub fn restart_to_update(&mut self) {\n if let UpdateState::Ready(staged) = &self.update {\n updates::set_pending(staged.clone());\n self.quit_requested = true;\n }\n }\n}\n",
210
+ "type": "registry:file",
211
+ "target": "desktop-rune/app/src/services.rs"
212
+ },
213
+ {
214
+ "path": "app/desktop-rune/app/src/sidecar.rs",
215
+ "content": "//! The app's daemon, run as this host's sidecar.\n//!\n//! - **A host secret per launch**: 36 random bytes from the OS (`getrandom`), base64url, 48 characters (the\n//! daemon needs at least 32), given to the sidecar as `ELOXIV_DAEMON_HOST_SECRET` (the daemon removes it from\n//! its own environment after reading it) and kept by this process only, in memory. It is the bearer of every\n//! `/client/v1` request; nothing writes it anywhere.\n//! - **The stdin lifeline** (`--stdin-lifeline`): the sidecar's stdin is a pipe this process holds; if the host\n//! dies, the pipe closes and the daemon exits.\n//! - **Stopping**: closing the pipe asks the daemon to exit; after 2 s it is killed. Either way the host waits\n//! for it.\n\nuse std::path::{Path, PathBuf};\nuse std::process::{Child, ChildStdin, Command, Stdio};\nuse std::time::{Duration, Instant};\n\n/// The daemon's default loopback port.\npub const DEFAULT_PORT: u16 = 4191;\n\n/// A random secret: `bytes` random bytes, base64url without padding.\npub fn random_secret(bytes: usize) -> String {\n let mut raw = vec![0u8; bytes];\n // An OS without a random source cannot run the host safely.\n if getrandom::fill(&mut raw).is_err() {\n panic!(\"no random source for the host secret\");\n }\n base64url(&raw)\n}\n\n/// A per-launch host secret (48 characters).\npub fn host_secret() -> String {\n random_secret(36)\n}\n\npub fn base64url(raw: &[u8]) -> String {\n const ALPHABET: &[u8; 64] = b\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n let mut out = String::with_capacity(raw.len().div_ceil(3) * 4);\n for chunk in raw.chunks(3) {\n let n = chunk.iter().enumerate().fold(0u32, |n, (i, b)| n | u32::from(*b) << (16 - 8 * i));\n let chars = chunk.len() + 1;\n for i in 0..chars {\n out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char);\n }\n }\n out\n}\n\n/// How to start the sidecar: a program and the arguments that go before the host's own.\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct Launch {\n pub program: PathBuf,\n pub args: Vec<String>,\n /// Installed by a package beside the host (or in `../libexec`), not a development build's: such a sidecar gets\n /// the app's own state directory and a free port ([`daemon_port`], [`state_dir_args`]).\n pub packaged: bool,\n}\n\nimpl Launch {\n fn new(program: PathBuf, args: Vec<String>, packaged: bool) -> Launch {\n Launch { program, args, packaged }\n }\n}\n\nconst SIDECAR: &str = if cfg!(windows) { \"eloxiv-daemon.exe\" } else { \"eloxiv-daemon\" };\n\n/// Where the sidecar is, first found:\n///\n/// 1. `ELOXIV_DAEMON_BIN`;\n/// 2. a package's: `<executable>-daemon[.exe]` beside this executable (macOS, Windows), or in `../libexec/` (Linux:\n/// `/usr/libexec/<binaryName>-daemon`), the names `scripts/package.ts` installs it under (so apps installed side by\n/// side never share a file); else `eloxiv-daemon[.exe]` beside it;\n/// 3. `target/sidecar/eloxiv-daemon[.exe]` of the workspace this executable was built in (`cargo run`, debug or\n/// release, any target: `scripts/build-sidecar.ts` writes it there);\n/// 4. from source: `sidecar/daemon.ts` of that workspace with `bun` (development without a build; the condition\n/// `@eloxiv/source` lets it run Eloxiv's workspace packages from source, and changes nothing elsewhere).\npub fn default_launch() -> Option<Launch> {\n if let Some(bin) = std::env::var_os(\"ELOXIV_DAEMON_BIN\") {\n return Some(Launch::new(PathBuf::from(bin), Vec::new(), false));\n }\n let exe = std::env::current_exe().ok()?;\n launch_for(&exe, find_on_path(\"bun\"))\n}\n\n/// [`default_launch`] for an executable at `exe`, with `bun` found at `bun` (pure, tested).\npub fn launch_for(exe: &Path, bun: Option<PathBuf>) -> Option<Launch> {\n let dir = exe.parent()?;\n let own = exe.file_stem().map(|stem| {\n let mut name = stem.to_os_string();\n name.push(if cfg!(windows) { \"-daemon.exe\" } else { \"-daemon\" });\n name\n });\n let packaged = own\n .iter()\n .flat_map(|name| [dir.join(name), dir.join(\"..\").join(\"libexec\").join(name)])\n .chain([dir.join(SIDECAR)]);\n if let Some(beside) = packaged.into_iter().find(|p| p.is_file()) {\n return Some(Launch::new(beside, Vec::new(), true));\n }\n // target/<profile>/exe or target/<triple>/<profile>/exe: the workspace is the parent of `target`.\n let workspace = exe\n .ancestors()\n .skip(1)\n .take(3)\n .find(|a| a.file_name().is_some_and(|n| n == \"target\"))\n .and_then(Path::parent)?;\n let built = workspace.join(\"target\").join(\"sidecar\").join(SIDECAR);\n if built.is_file() {\n return Some(Launch::new(built, Vec::new(), false));\n }\n let source = workspace.join(\"sidecar\").join(\"daemon.ts\");\n match (source.is_file(), bun) {\n (true, Some(bun)) => Some(Launch::new(\n bun,\n vec![\"--conditions=@eloxiv/source\".into(), source.to_string_lossy().into_owned()],\n false,\n )),\n _ => None,\n }\n}\n\n/// The daemon's port: `ELOXIV_DAEMON_PORT` (`env_port`) when set; else, for a packaged sidecar, a free loopback\n/// port chosen now (so two installed Eloxiv apps, or two copies of one, never meet on one port; the kernel accepts a\n/// desktop sign-in's loopback redirect on any port), falling back to [`DEFAULT_PORT`]; else (development)\n/// [`DEFAULT_PORT`].\npub fn daemon_port(env_port: Option<&str>, packaged: bool) -> u16 {\n if let Some(port) = env_port.and_then(|p| p.trim().parse::<u16>().ok()) {\n return port;\n }\n if packaged { free_port().unwrap_or(DEFAULT_PORT) } else { DEFAULT_PORT }\n}\n\n/// A port nothing listens on now: the OS's pick for `127.0.0.1:0`, released for the daemon to bind.\npub fn free_port() -> Option<u16> {\n std::net::TcpListener::bind((\"127.0.0.1\", 0)).and_then(|l| l.local_addr()).map(|a| a.port()).ok()\n}\n\n/// The daemon's state directory for the app `app_id`, under the platform's per-user state base (Linux\n/// `$XDG_STATE_HOME` or `~/.local/state`; macOS `~/Library/Application Support`; Windows `%APPDATA%`):\n/// `<base>/<app_id>/daemon`. The daemon's own default (`…/eloxiv/daemon`) is shared by every app; this is not.\npub fn app_state_dir(app_id: &str, var: impl Fn(&str) -> Option<String>) -> Option<PathBuf> {\n let home = || var(\"HOME\").or_else(|| var(\"USERPROFILE\")).filter(|h| !h.is_empty()).map(PathBuf::from);\n let base = if cfg!(windows) {\n var(\"APPDATA\")\n .filter(|d| !d.is_empty())\n .map(PathBuf::from)\n .or_else(|| home().map(|h| h.join(\"AppData\").join(\"Roaming\")))\n } else if cfg!(target_os = \"macos\") {\n home().map(|h| h.join(\"Library\").join(\"Application Support\"))\n } else {\n var(\"XDG_STATE_HOME\")\n .map(PathBuf::from)\n .filter(|p| p.is_absolute())\n .or_else(|| home().map(|h| h.join(\".local\").join(\"state\")))\n };\n base.map(|b| b.join(app_id).join(\"daemon\"))\n}\n\n/// `--state-dir <the app's>` for a packaged sidecar, unless the state directory is given already\n/// (`ELOXIV_DAEMON_STATE_DIR`, or `--state-dir` among `args`). A development sidecar keeps the daemon's default.\npub fn state_dir_args(\n launch: &Launch,\n app_id: &str,\n args: &[String],\n var: impl Fn(&str) -> Option<String>,\n) -> Vec<String> {\n let given = var(\"ELOXIV_DAEMON_STATE_DIR\").is_some_and(|d| !d.is_empty())\n || args.iter().any(|a| a == \"--state-dir\" || a.starts_with(\"--state-dir=\"));\n if !launch.packaged || given {\n return Vec::new();\n }\n match app_state_dir(app_id, var) {\n Some(dir) => vec![\"--state-dir\".into(), dir.to_string_lossy().into_owned()],\n None => Vec::new(),\n }\n}\n\nfn find_on_path(program: &str) -> Option<PathBuf> {\n let name = if cfg!(windows) { format!(\"{program}.exe\") } else { program.to_owned() };\n std::env::split_paths(&std::env::var_os(\"PATH\")?).map(|d| d.join(&name)).find(|p| p.is_file())\n}\n\n/// The running sidecar.\npub struct Sidecar {\n child: Option<Child>,\n lifeline: Option<ChildStdin>,\n pub port: u16,\n secret: String,\n}\n\nimpl std::fmt::Debug for Sidecar {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"Sidecar\").field(\"port\", &self.port).finish_non_exhaustive()\n }\n}\n\nimpl Sidecar {\n /// Starts the sidecar on `port` with a new host secret and the lifeline; `args` are passed before them\n /// (`--state-dir`, a kernel URL), after the launch's own.\n pub fn start(launch: &Launch, port: u16, args: &[String]) -> std::io::Result<Sidecar> {\n Sidecar::start_with(launch, port, args, &[])\n }\n\n /// [`Sidecar::start`] with more environment for the daemon (`env`: the app's servers).\n pub fn start_with(launch: &Launch, port: u16, args: &[String], env: &[(&str, String)]) -> std::io::Result<Sidecar> {\n let secret = host_secret();\n let mut child = Command::new(&launch.program)\n .args(&launch.args)\n .args(args)\n .args([\"--port\", &port.to_string(), \"--stdin-lifeline\"])\n .envs(env.iter().map(|(k, v)| (*k, v.as_str())))\n .env(\"ELOXIV_DAEMON_HOST_SECRET\", &secret)\n .stdin(Stdio::piped())\n .stdout(Stdio::inherit())\n .stderr(Stdio::inherit())\n .spawn()?;\n let lifeline = child.stdin.take();\n eprintln!(\"[eloxiv-daemon] spawned pid={} port={port}\", child.id());\n Ok(Sidecar { child: Some(child), lifeline, port, secret })\n }\n\n /// The daemon's address on loopback.\n pub fn url(&self) -> String {\n format!(\"http://127.0.0.1:{}\", self.port)\n }\n\n /// The host secret, for this process's own client.\n pub fn secret(&self) -> &str {\n &self.secret\n }\n\n /// Whether the sidecar is still running.\n pub fn running(&mut self) -> bool {\n self.child.as_mut().is_some_and(|c| matches!(c.try_wait(), Ok(None)))\n }\n\n /// Stops the sidecar: the lifeline closes (the daemon exits on its own), then a kill after 2 s; waits for it.\n pub fn stop(&mut self) {\n drop(self.lifeline.take());\n let Some(mut child) = self.child.take() else { return };\n let deadline = Instant::now() + Duration::from_secs(2);\n loop {\n match child.try_wait() {\n Ok(Some(_)) => return,\n Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(25)),\n _ => break,\n }\n }\n let _ = child.kill();\n let _ = child.wait();\n }\n}\n\nimpl Drop for Sidecar {\n fn drop(&mut self) {\n self.stop();\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn host_secrets_are_long_random_and_url_safe() {\n let (a, b) = (host_secret(), host_secret());\n assert_eq!(a.len(), 48);\n assert_ne!(a, b);\n assert!(a.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_'));\n assert_eq!(base64url(b\"\\xfb\\xff\"), \"-_8\");\n assert_eq!(base64url(b\"Man\"), \"TWFu\");\n }\n\n #[test]\n fn the_sidecar_is_found_beside_the_host_then_in_its_workspace_then_from_source() {\n // Removed when the test ends, passing or not.\n struct Dir(PathBuf);\n impl Drop for Dir {\n fn drop(&mut self) {\n let _ = std::fs::remove_dir_all(&self.0);\n }\n }\n let dir = Dir(std::env::temp_dir().join(format!(\"eloxiv-rune-sidecar-{}\", random_secret(6))));\n let root = &dir.0;\n let release = root.join(\"target\").join(\"x86_64-unknown-linux-gnu\").join(\"release\");\n std::fs::create_dir_all(&release).expect(\"a release directory\");\n let exe = release.join(\"eloxiv-desktop-rune\");\n let bun = PathBuf::from(\"/usr/bin/bun\");\n let found = |bun: Option<PathBuf>| launch_for(&exe, bun);\n\n assert_eq!(found(Some(bun.clone())), None, \"nothing to start\");\n std::fs::create_dir_all(root.join(\"sidecar\")).expect(\"a sidecar directory\");\n std::fs::write(root.join(\"sidecar\").join(\"daemon.ts\"), \"\").expect(\"the entry\");\n let source = found(Some(bun.clone())).expect(\"the entry from source\");\n assert_eq!(source.program, bun);\n assert!(source.args.last().is_some_and(|a| a.ends_with(\"daemon.ts\")));\n assert_eq!(found(None), None, \"from source needs bun\");\n\n std::fs::create_dir_all(root.join(\"target\").join(\"sidecar\")).expect(\"target/sidecar\");\n std::fs::write(root.join(\"target\").join(\"sidecar\").join(SIDECAR), \"\").expect(\"the built sidecar\");\n assert_eq!(found(None).map(|l| l.program), Some(root.join(\"target\").join(\"sidecar\").join(SIDECAR)));\n\n std::fs::write(release.join(SIDECAR), \"\").expect(\"the packaged sidecar\");\n assert_eq!(found(None), Some(Launch::new(release.join(SIDECAR), Vec::new(), true)));\n assert!(!source.packaged);\n\n // A package installs it under the app's executable name, `<binaryName>-daemon`: in `../libexec/` (Linux)\n // or beside the host, found first.\n let installed = release.join(if cfg!(windows) { \"hello-app.exe\" } else { \"hello-app\" });\n let name = if cfg!(windows) { \"hello-app-daemon.exe\" } else { \"hello-app-daemon\" };\n assert_eq!(launch_for(&installed, None).map(|l| l.program), Some(release.join(SIDECAR)));\n let libexec = release.join(\"..\").join(\"libexec\");\n std::fs::create_dir_all(&libexec).expect(\"libexec\");\n std::fs::write(libexec.join(name), \"\").expect(\"the Linux package's sidecar\");\n assert_eq!(launch_for(&installed, None).map(|l| l.program), Some(libexec.join(name)));\n std::fs::write(release.join(name), \"\").expect(\"the app's own sidecar beside it\");\n assert_eq!(launch_for(&installed, None), Some(Launch::new(release.join(name), Vec::new(), true)));\n }\n\n #[test]\n fn a_packaged_sidecar_gets_the_apps_own_state_and_a_free_port_development_keeps_the_defaults() {\n let packaged = Launch::new(PathBuf::from(\"/opt/acme/acme-daemon\"), Vec::new(), true);\n let dev = Launch::new(PathBuf::from(\"/w/target/sidecar/eloxiv-daemon\"), Vec::new(), false);\n let home = |name: &str| match name {\n \"HOME\" | \"USERPROFILE\" => Some(\"/home/p\".to_owned()),\n \"APPDATA\" => Some(\"/home/p/AppData/Roaming\".to_owned()),\n _ => None,\n };\n let dir = app_state_dir(\"com.acme.crm\", home).expect(\"a state directory\");\n assert!(dir.ends_with(Path::new(\"com.acme.crm\").join(\"daemon\")), \"{}\", dir.display());\n if cfg!(target_os = \"linux\") {\n assert_eq!(dir, PathBuf::from(\"/home/p/.local/state/com.acme.crm/daemon\"));\n }\n assert_eq!(\n state_dir_args(&packaged, \"com.acme.crm\", &[], home),\n vec![\"--state-dir\".to_owned(), dir.to_string_lossy().into_owned()]\n );\n assert_eq!(\n state_dir_args(&dev, \"com.acme.crm\", &[], home),\n Vec::<String>::new(),\n \"development: the daemon's default\"\n );\n let given = vec![\"--state-dir\".to_owned(), \"/x\".to_owned()];\n assert_eq!(state_dir_args(&packaged, \"com.acme.crm\", &given, home), Vec::<String>::new());\n let env_given =\n |name: &str| (name == \"ELOXIV_DAEMON_STATE_DIR\").then(|| \"/y\".to_owned()).or_else(|| home(name));\n assert_eq!(state_dir_args(&packaged, \"com.acme.crm\", &[], env_given), Vec::<String>::new());\n // Two apps never share it.\n assert_ne!(app_state_dir(\"com.acme.crm\", home), app_state_dir(\"com.acme.books\", home));\n\n assert_eq!(daemon_port(Some(\"4300\"), true), 4300, \"ELOXIV_DAEMON_PORT wins\");\n assert_eq!(daemon_port(None, false), DEFAULT_PORT, \"development keeps 4191\");\n let chosen = daemon_port(None, true);\n assert_ne!(chosen, 0);\n assert!(std::net::TcpListener::bind((\"127.0.0.1\", chosen)).is_ok(), \"a port nothing holds\");\n }\n}\n",
216
+ "type": "registry:file",
217
+ "target": "desktop-rune/app/src/sidecar.rs"
218
+ },
219
+ {
220
+ "path": "app/desktop-rune/app/src/ui.rs",
221
+ "content": "//! The app's state on the UI thread: the model of the daemon's client runtime, what the screens edit, and the\n//! replies landing from the worker (drained in `poll`, every frame).\n\nuse std::path::PathBuf;\nuse std::sync::mpsc::Receiver;\nuse std::time::Duration;\n\nuse eloxiv_local_client::{ClientError, Hello, LocalClient, StreamEnd, StreamItem};\nuse rune::{Direction, TextEdit, Tx};\nuse serde_json::json;\n\nuse crate::backend::{Backend, Job, Reply};\nuse crate::chat::{self, CHAT_QUERIES, Chat, ChatEffect, Decision};\nuse crate::make;\nuse crate::model::{Effect, GREET_MUTATOR, GREETINGS_QUERY, Model, Session};\nuse crate::notices::{self, Click, DecisionKind, NOTIFICATIONS_QUERY, NoticeEffect, REQUESTS_QUERY};\nuse crate::outstanding::{self, Outcome, Scope};\nuse crate::services::HostServices;\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum Appearance {\n System,\n Light,\n Dark,\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum Screen {\n Greetings,\n Chat,\n Make,\n}\n\n#[derive(Clone, Debug, PartialEq)]\npub enum Startup {\n /// Waiting for the daemon's `/health`.\n Starting,\n Ready,\n Failed(String),\n}\n\n/// How the host reaches its daemon.\npub struct Launch {\n pub client: LocalClient,\n /// How long to wait for `/health`.\n pub timeout: Duration,\n /// Where the host keeps the person's outstanding sends (None: in memory only).\n pub data_dir: Option<PathBuf>,\n}\n\npub struct Ui {\n pub model: Model,\n pub backend: Backend,\n inbox: Receiver<Reply>,\n pub startup: Startup,\n pub hello: Option<Hello>,\n pub stream_open: bool,\n pub screen: Screen,\n pub greeting: TextEdit,\n /// The chat's composer.\n pub chat_input: TextEdit,\n pub make: make::Host,\n pub appearance: Appearance,\n pub direction: Direction,\n /// The last refusal or failure, for the person.\n pub notice: Option<String>,\n /// The sign-in page this host opened in the system browser.\n pub sign_in_url: Option<String>,\n /// A request is on its way (sign-in, org switch, sign-out): its control is busy.\n pub busy: Option<&'static str>,\n /// The person's outstanding sends, per person and organisation: they outlive the chat's state and the host.\n pub outstanding: outstanding::Store,\n /// How long to wait before asking again whether the agent can answer, while it cannot (a model being set up).\n pub readiness_recheck: Duration,\n /// The generation a delayed readiness check is on its way for.\n rechecking: Option<i64>,\n writes: u64,\n /// The host's own services: configuration, deep links, updates, secure storage.\n pub host: HostServices,\n /// Decisions made from an OS notification's button, waiting for their answer (request ids).\n pub notice_decisions: Vec<String>,\n /// The running app, to bring its window forward for a notification's click (None headless before `run`).\n pub app: Option<rune::AppHandle<Ui>>,\n /// The record a link opened on the greetings screen (selected there).\n pub focused_record: Option<String>,\n /// A notification clicked before the app's views were known: opened once they are, in its generation.\n pending_notice: Option<notices::Notice>,\n}\n\nimpl Ui {\n pub fn new(launch: Launch) -> Ui {\n let (backend, inbox) = Backend::new(launch.client);\n backend.run(Job::Start { timeout: launch.timeout });\n Ui {\n model: Model::default(),\n backend,\n inbox,\n startup: Startup::Starting,\n hello: None,\n stream_open: false,\n screen: Screen::Greetings,\n greeting: TextEdit::new(\"\"),\n chat_input: TextEdit::new(\"\"),\n make: make::Host::default(),\n appearance: Appearance::System,\n direction: Direction::Ltr,\n notice: None,\n sign_in_url: None,\n busy: None,\n outstanding: outstanding::Store::open(launch.data_dir.as_deref()),\n readiness_recheck: READINESS_RECHECK,\n rechecking: None,\n writes: 0,\n host: HostServices::default(),\n notice_decisions: Vec::new(),\n app: None,\n focused_record: None,\n pending_notice: None,\n }\n }\n\n /// The host's services of this launch (its configuration, the app's views, the updater).\n pub fn with_services(mut self, host: HostServices) -> Ui {\n self.host = host;\n self\n }\n\n /// Lands every reply that arrived (Rune's `poll`, on the UI thread). True when anything changed.\n pub fn drain(&mut self, tx: &mut Tx) -> bool {\n let mut changed = false;\n while let Ok(reply) = self.inbox.try_recv() {\n self.land(reply, tx);\n changed = true;\n }\n changed |= self.flush_make();\n changed |= self.host.drain(self.startup == Startup::Ready);\n if self.host.notifier.poll() {\n // The OS notification service answered: the watch starts if the daemon is ready too.\n changed = true;\n self.notices_ready();\n }\n for click in self.host.notifier.take_clicks() {\n changed |= self.notice_clicked(click);\n }\n if self.pending_notice.is_some() && self.host.views.is_some() {\n let notice = self.pending_notice.take().expect(\"checked\");\n if notice.generation == self.model.generation && self.busy.is_none() {\n self.open_notice(&notice);\n changed = true;\n }\n }\n if self.host.pending_link.is_some() {\n changed |= self.route_pending();\n }\n if self.host.quit_requested {\n self.host.quit_requested = false;\n tx.quit();\n }\n changed\n }\n\n /// Sends the MAKE host's requests to the worker.\n fn flush_make(&mut self) -> bool {\n let requests = std::mem::take(&mut self.make.outbox);\n let any = !requests.is_empty();\n for request in requests {\n self.backend.run(Job::Make { generation: self.model.generation, request });\n }\n any\n }\n\n fn refused(&mut self, what: &str, e: &ClientError) {\n self.notice = Some(format!(\"{what}: {e}\"));\n }\n\n fn effects(&mut self, effects: Vec<Effect>) {\n for effect in effects {\n match effect {\n Effect::Subscribe { generation } => {\n // The id is the host's own, so the first snapshot is ours whichever arrives first.\n let id = format!(\"greetings-{generation}-{}\", crate::random_id());\n self.model.subscribing(generation, id.clone());\n self.backend.run(Job::Subscribe { generation, query: GREETINGS_QUERY.into(), args: json!({}), id })\n }\n Effect::Teardown { .. } => self.make.teardown(),\n Effect::SubscribeChat { generation } => {\n for query in CHAT_QUERIES {\n let id = format!(\"chat-{query}-{generation}-{}\", crate::random_id());\n self.model.chat.subscribing(query, id.clone());\n self.backend.run(Job::Subscribe { generation, query: query.into(), args: json!({}), id });\n }\n self.backend.run(Job::Readiness { generation, after: Duration::ZERO });\n }\n Effect::Chat(effect) => self.chat_effect(effect),\n Effect::SubscribeNotices { generation } => {\n let id = format!(\"{NOTICES_PREFIX}{generation}-{}\", crate::random_id());\n let now = std::time::SystemTime::now()\n .duration_since(std::time::UNIX_EPOCH)\n .map_or(0, |d| d.as_millis() as i64);\n self.model.notices.starting(now);\n self.model.notices.subscribing(generation, id.clone());\n self.backend.run(Job::Subscribe {\n generation,\n query: NOTIFICATIONS_QUERY.into(),\n args: json!({}),\n id,\n });\n // The authority for approval buttons: the approval requests the person may decide.\n if self.hello.as_ref().is_some_and(|h| h.app.queries.iter().any(|q| q == REQUESTS_QUERY)) {\n let id = format!(\"{NOTICES_REQUESTS_PREFIX}{generation}-{}\", crate::random_id());\n self.model.notices.subscribing_requests(generation, id.clone());\n self.backend.run(Job::Subscribe {\n generation,\n query: REQUESTS_QUERY.into(),\n args: json!({}),\n id,\n });\n }\n }\n Effect::Notices(effects) => {\n for effect in &effects {\n if let NoticeEffect::Post(n) = effect {\n // Not its text: it may name a record.\n eprintln!(\"eloxiv-desktop-rune: notification shown: {}\", n.category);\n }\n self.host.notifier.apply(effect);\n }\n }\n }\n }\n }\n\n pub(crate) fn chat_effect(&mut self, effect: ChatEffect) {\n let generation = self.model.generation;\n match effect {\n ChatEffect::Follow { run_id, after } => {\n let id = format!(\"run-{generation}-{}\", crate::random_id());\n self.model.chat.following(id.clone(), run_id.clone());\n self.backend.run(Job::FollowRun { generation, id, run_id, after });\n }\n ChatEffect::Unfollow { id } => self.backend.run(Job::UnfollowRun(id)),\n }\n }\n\n fn land(&mut self, reply: Reply, tx: &mut Tx) {\n match reply {\n Reply::Started(Ok(hello)) => {\n // The chat needs the agent's queries and run subscriptions (LocalClient 1.1.0).\n self.model.chat_enabled = CHAT_QUERIES.iter().all(|q| hello.app.queries.iter().any(|h| h == q))\n && hello.features.iter().any(|f| f == \"runEvents\");\n self.hello = Some(hello);\n self.model.notices_enabled = self.notices_possible();\n self.startup = Startup::Ready;\n self.backend.open_stream();\n }\n Reply::Started(Err(e)) => self.startup = Startup::Failed(e.to_string()),\n Reply::Stream(StreamItem::Open) => {\n self.stream_open = true;\n // The stream is new: its subscriptions are too. Its first event is the current session (LocalClient's\n // contract), which subscribes again; no separate read, whose late answer could overwrite a newer one.\n self.model.stream_reopened();\n }\n Reply::Stream(StreamItem::Event(event)) => {\n let before = (self.model.generation, self.scope());\n let effects = self.model.apply(&event);\n if (self.model.generation, self.scope()) != before {\n // Another context (the daemon's own sign-out, a revoked session, another client's switch): no\n // unsent draft of the person or organisation before goes with it.\n self.chat_input = TextEdit::new(\"\");\n self.greeting = TextEdit::new(\"\");\n }\n // A new context's chat takes the person's outstanding sends there.\n self.restore_outstanding();\n if !matches!(self.model.session, Session::SignedOut | Session::SigningIn) {\n self.sign_in_url = None;\n }\n self.effects(effects);\n }\n Reply::Stream(StreamItem::Unknown(_)) => {}\n Reply::Stream(StreamItem::End(end)) => {\n self.stream_open = false;\n match end {\n StreamEnd::Cancelled => {}\n StreamEnd::Refused(e) => {\n self.refused(\"The event stream was refused\", &e);\n self.backend.run(Job::Reconnect { after: Duration::from_secs(2) });\n }\n _ => self.backend.run(Job::Reconnect { after: Duration::from_millis(500) }),\n }\n }\n Reply::Reconnect => self.backend.open_stream(),\n Reply::Done => {}\n Reply::SignIn(Ok(started)) => {\n self.busy = None;\n // The system browser: the page signs in and redirects to the daemon, which redeems the code.\n match tx.open_url(&started.url) {\n Ok(()) => self.sign_in_url = Some(started.url),\n Err(e) => self.notice = Some(format!(\"Could not open the browser: {e:?}\")),\n }\n }\n Reply::SignIn(Err(e)) => {\n self.busy = None;\n self.refused(\"Sign-in could not start\", &e);\n }\n Reply::Org(result) => {\n self.busy = None;\n if let Err(e) = result {\n self.refused(\"Switching organisation failed\", &e);\n // Still in the organisation: its feed resumes (nothing seen is shown again).\n self.model.notices.resume();\n }\n }\n Reply::SignedOut(result) => {\n self.busy = None;\n if let Err(e) = result {\n self.refused(\"Sign-out is not confirmed yet\", &e);\n self.model.notices.resume();\n }\n }\n Reply::Subscribed { generation, id, result } if id.starts_with(NOTICES_REQUESTS_PREFIX) => match result {\n Ok(s) => {\n if !self.model.notices.subscribed_requests(s.generation.max(generation), &id, s.id.clone()) {\n self.backend.run(Job::Unsubscribe(s.id));\n }\n }\n Err(e) => eprintln!(\"eloxiv-desktop-rune: approval requests could not be followed: {}\", e.tag()),\n },\n Reply::Subscribed { generation, id, result } if id.starts_with(NOTICES_PREFIX) => match result {\n Ok(s) => {\n if !self.model.notices.subscribed(s.generation.max(generation), &id, s.id.clone()) {\n self.backend.run(Job::Unsubscribe(s.id));\n }\n }\n Err(e) => {\n eprintln!(\"eloxiv-desktop-rune: notifications could not be followed: {}\", e.tag());\n self.model.notices.subscribe_failed(generation, &id);\n }\n },\n Reply::Subscribed { generation, id, result } if self.model.chat.query_of(&id).is_some() => {\n if let Err(e) = result {\n self.refused(\"The conversation could not be loaded\", &e);\n } else if generation != self.model.generation {\n self.backend.run(Job::Unsubscribe(id));\n }\n }\n Reply::Subscribed { generation, id: _, result } => match result {\n Ok(s) => {\n if !self.model.subscribed(s.generation.max(generation), s.id.clone()) {\n // Of an older generation: not ours to show.\n self.backend.run(Job::Unsubscribe(s.id));\n }\n }\n Err(e) => self.model.subscribe_failed(generation, e.to_string()),\n },\n Reply::Readiness { generation, delayed, result } => {\n if delayed && self.rechecking == Some(generation) {\n self.rechecking = None;\n }\n if generation == self.model.generation {\n // A failed probe is not a missing setup: it holds nothing back.\n if let Ok(engine) = result {\n self.model.chat.engine = Some(engine);\n }\n // Blocked (no model set up yet, or none usable): asked again until it can answer, while this\n // generation lasts (a check of an older one lands here, changes nothing and is not repeated).\n if self.model.chat.engine_blocked() && self.rechecking != Some(generation) {\n self.rechecking = Some(generation);\n self.backend.run(Job::Readiness { generation, after: self.readiness_recheck });\n }\n }\n }\n Reply::Followed { generation, id, result } => match result {\n Err(e) if generation == self.model.generation => {\n self.model.chat.follow_failed(&id, e.tag(), e.message())\n }\n Ok(_) if generation != self.model.generation => self.backend.run(Job::UnfollowRun(id)),\n _ => {}\n },\n Reply::Sent { scope, generation, key, result } => {\n // Recorded whatever is shown now: the send is the person's, in the organisation it was made in.\n let outcome = match &result {\n Ok(_) => Outcome::Ran,\n Err(e) if definitive(e, generation) => Outcome::Refused,\n Err(_) => Outcome::Lost,\n };\n self.outstanding.settle(&scope, &key, &outcome);\n if generation != self.model.generation {\n self.restore_outstanding();\n return;\n }\n match result {\n Ok(envelope) => {\n let output = envelope.get(\"output\");\n let ids =\n output.and_then(|o| Some((o.get(\"conversationId\")?.as_str()?, o.get(\"runId\")?.as_str()?)));\n let clear = match (envelope.get(\"kind\").and_then(|k| k.as_str()), ids) {\n (Some(\"output\"), Some((conversation, run))) => {\n let (clear, effects) = self.model.chat.sent(&key, conversation.into(), run.into());\n for effect in effects {\n self.chat_effect(effect);\n }\n clear\n }\n // A replay of a send already made (its first answer was lost): its run reaches the\n // screen through the replica, as any run does.\n _ => {\n let (clear, effects) = self.model.chat.replayed(&key);\n for effect in effects {\n self.chat_effect(effect);\n }\n clear\n }\n };\n if clear {\n self.chat_input = TextEdit::new(\"\");\n }\n }\n Err(e) => {\n let definitive = definitive(&e, generation);\n self.model.chat.send_failed(&key, e.tag(), e.message(), definitive);\n }\n }\n }\n Reply::Decided { generation, id, result } => {\n if let Some(at) = self.notice_decisions.iter().position(|d| *d == id) {\n self.notice_decisions.remove(at);\n match &result {\n Ok(_) => eprintln!(\"eloxiv-desktop-rune: a decision from a notification was made\"),\n // What the kernel answered stays out of sight (it may be raw): the person is told what to do.\n Err(_) if generation == self.model.generation => {\n self.notice = Some(\n \"Couldn't save your decision from the notification. Open the request in the app to try again.\"\n .into(),\n )\n }\n Err(_) => {}\n }\n }\n if generation == self.model.generation {\n self.model.chat.decided(&id, result.err().map(|e| (e.tag(), e.message())));\n }\n }\n Reply::Wrote { id, result } => {\n if let Err(e) = result {\n self.model.write_refused(&id, e.tag(), e.message());\n }\n }\n Reply::MakeView { mount, result } => self.make.viewed(mount, result),\n Reply::MakeStep { mount, result } => self.make.stepped(mount, result),\n Reply::MakeCall { mount, id, result } => self.make.called(mount, id, result),\n }\n }\n\n /// OS notifications need the inbox's notifications query and a system that shows them (its service found).\n fn notices_possible(&self) -> bool {\n self.app_follows_notices() && self.host.notifier.can_post()\n }\n\n /// Whether the app's daemon follows the person's notifications (its `hello` names the inbox's query).\n fn app_follows_notices(&self) -> bool {\n self.hello.as_ref().is_some_and(|h| h.app.queries.iter().any(|q| q == NOTIFICATIONS_QUERY))\n }\n\n /// What the host does with notifications here ([`HostServices::notifications`] for this app).\n pub fn notifications(&self) -> serde_json::Value {\n self.host.notifications(self.app_follows_notices())\n }\n\n /// The notifier became ready (after the daemon, or before it answered): the watch starts when both are.\n fn notices_ready(&mut self) {\n self.model.notices_enabled = self.notices_possible();\n let effects = self.model.wanted_now();\n self.effects(effects);\n }\n\n // What the screens do.\n\n pub fn sign_in(&mut self) {\n self.notice = None;\n self.busy = Some(\"sign-in\");\n self.backend.run(Job::SignIn);\n }\n\n pub fn select_org(&mut self, org: &str) {\n if self.model.session.org_id() == Some(org) {\n return;\n }\n self.notice = None;\n self.busy = Some(\"org\");\n self.suspend_notices();\n // Nothing of the old organisation is shown from the intent on: the daemon's `context` event confirms it.\n self.model.list = Default::default();\n self.model.writes.clear();\n self.clear_chat();\n self.make.teardown();\n self.backend.run(Job::SelectOrg(org.to_owned()));\n }\n\n /// From an organisation switch's or a sign-out's intent on, no OS notification of the context being left is shown\n /// or acts, and no link from one waits to open.\n fn suspend_notices(&mut self) {\n for effect in self.model.notices.suspend() {\n self.host.notifier.apply(&effect);\n }\n self.drop_notice_link();\n self.pending_notice = None;\n }\n\n /// Nothing of the conversation is shown from an organisation switch's or a sign-out's intent on.\n fn clear_chat(&mut self) {\n self.model.chat = Chat::new(self.model.generation);\n self.model.chat_requested = None;\n self.chat_input = TextEdit::new(\"\");\n }\n\n /// Whose outstanding sends the screens show: the signed-in person in the selected organisation, by the session of\n /// the current context (None from a `context` event until that session arrives: nothing is sent or restored).\n pub fn scope(&self) -> Option<Scope> {\n if !self.model.usable() {\n return None;\n }\n match &self.model.session {\n Session::SignedIn { user, org_id: Some(org), .. } => {\n Some(Scope { user_id: user.id.clone(), org_id: org.clone() })\n }\n _ => None,\n }\n }\n\n /// The chat takes the person's outstanding sends in the organisation, as the store has them now.\n fn restore_outstanding(&mut self) {\n let sends = self.scope().map(|scope| self.outstanding.list(&scope)).unwrap_or_default();\n self.model.chat.with_outstanding(sends);\n }\n\n /// Sends the composer's draft (or resends the conversation's send whose answer was lost, under its key).\n pub fn send_message(&mut self) {\n let Some(scope) = self.scope() else { return };\n // As the store has them now: another host sharing the data directory may have settled or discarded one.\n self.restore_outstanding();\n let draft = self.chat_input.text.clone();\n if let Some(send) = self.model.chat.submit(&draft, crate::random_uuid()) {\n // Recorded before the request leaves, so its identity outlives this screen, the generation and the host.\n if let Some(record) = self.model.chat.outstanding_send(&send.key) {\n self.outstanding.put(&scope, record.clone());\n }\n // Made in the send's own generation (a retry keeps it): the daemon runs it in no other.\n self.backend.run(Job::Send {\n scope,\n generation: send.generation,\n key: send.key,\n text: send.text,\n conversation_id: send.conversation_id,\n });\n }\n }\n\n /// The person gives up on the outstanding send under `key` (one that could not be confirmed).\n pub fn discard_send(&mut self, key: &str) {\n if let Some(scope) = self.scope() {\n self.outstanding.settle(&scope, key, &Outcome::Discarded);\n }\n self.model.chat.discard(key);\n }\n\n /// Shows a new conversation (the first send starts it).\n pub fn new_conversation(&mut self) {\n for effect in self.model.chat.open_new() {\n self.chat_effect(effect);\n }\n }\n\n /// One decision at a time per request, whichever surface it comes from (the chat's card or an OS notification): false\n /// when the request is being decided already (in this generation) or nothing can be decided now. The OS\n /// notification offering it is withdrawn as deciding starts, and does not offer it again.\n fn start_deciding(&mut self, id: &str) -> bool {\n if !self.model.usable() || self.model.chat.deciding.iter().any(|d| d == id) {\n return false;\n }\n self.model.chat.deciding(id);\n let effects = self.model.notices_refreshed();\n self.effects(effects);\n true\n }\n\n /// The person's decision on a held tool call (`consent.approve` or `consent.reject`), under its own key.\n pub fn decide_consent(&mut self, consent_id: &str, decision: Decision) {\n if !self.start_deciding(consent_id) {\n return;\n }\n self.backend.run(Job::Decide {\n generation: self.model.generation,\n id: consent_id.to_owned(),\n action: format!(\"consent.{}\", decision.word()),\n key: chat::consent_key(consent_id, decision),\n });\n }\n\n /// The person's decision on an approval request (`approvals.approve` or `approvals.reject`), under its own key.\n pub fn decide_approval(&mut self, approval_id: &str, decision: Decision) {\n if !self.start_deciding(approval_id) {\n return;\n }\n self.backend.run(Job::Decide {\n generation: self.model.generation,\n id: approval_id.to_owned(),\n action: format!(\"approvals.{}\", decision.word()),\n key: chat::approval_key(approval_id, decision),\n });\n }\n\n /// A click on one of the host's OS notifications: on the notification, its record opens through the deep links\n /// (and the window comes forward); on Approve or Reject, the request is decided as the chat's cards decide it. A\n /// click on a notification of an older generation, or one no longer shown, does nothing. True when it acted.\n pub fn notice_clicked(&mut self, click: Click) -> bool {\n let Some(notice) = self.model.notices.find(&click.notice).cloned() else {\n eprintln!(\"eloxiv-desktop-rune: a click on a notification no longer shown\");\n return false;\n };\n // The context must be the notification's and known to be current: no switch or sign-out on its way, the event\n // stream open (it reports a context change), the feed not suspended.\n if click.generation != self.model.generation\n || notice.generation != self.model.generation\n || !self.model.usable()\n || self.busy.is_some()\n || !self.stream_open\n || self.model.notices.suspended()\n {\n return false;\n }\n for effect in self.model.notices.settle(&notice.id) {\n self.host.notifier.apply(&effect);\n }\n match click.action {\n None => {\n if let Some(app) = &self.app {\n match click.token.clone() {\n Some(token) => app.activate(token),\n None => app.focus(),\n }\n }\n if self.host.views.is_none() {\n // The app's views are not known yet: opened once they are, if this generation lasts.\n self.pending_notice = Some(notice);\n } else {\n self.open_notice(&notice);\n }\n }\n Some(decision) => {\n let Some((kind, request)) = notice.decision.clone() else {\n // A button on a notification that offers none: nothing is decided.\n return false;\n };\n // Decidable now, by the authoritative rows (not only when it was shown).\n if !self.model.decidable().iter().any(|d| d.kind == kind && d.id == request) {\n return false;\n }\n self.notice_decisions.push(request.clone());\n match kind {\n DecisionKind::Approval => self.decide_approval(&request, decision),\n DecisionKind::Consent => self.decide_consent(&request, decision),\n }\n }\n }\n true\n }\n\n /// Opens what notification `notice` links (in its generation), or says what it was.\n fn open_notice(&mut self, notice: &notices::Notice) {\n match self.notice_link(notice) {\n Some(url) => self.open_notice_link(&url, notice.generation),\n None => self.host.link_status = Some(format!(\"Notification: {}\", notice.title)),\n }\n }\n\n /// The link a notification opens: its record in the first view that shows the record's entity; an approval or\n /// consent request in the agent's conversation (where its card is, named by `approval` or `consent`), when the app\n /// has it; None otherwise.\n pub fn notice_link(&self, notice: &notices::Notice) -> Option<String> {\n let table = self.host.views.as_ref()?;\n let scheme = &self.host.config.scheme;\n let link = notice.link.as_ref()?;\n if let Some(url) = table.record_link(&link.module, &link.entity, &link.id, Some(&notice.org_id), scheme) {\n return Some(url);\n }\n if let Some((kind, id)) = notices::request_of(notice.link.as_ref())\n && self.model.chat_enabled\n {\n let name = match kind {\n DecisionKind::Approval => crate::links::APPROVAL_PARAM,\n DecisionKind::Consent => crate::links::CONSENT_PARAM,\n };\n let target = crate::links::DeepLink {\n view: crate::links::CHAT_VIEW.into(),\n org: Some(notice.org_id.clone()),\n params: [(name.to_owned(), id.to_owned())].into(),\n ..Default::default()\n };\n return table.link(&target, scheme);\n }\n None\n }\n\n pub fn sign_out(&mut self) {\n self.notice = None;\n self.busy = Some(\"sign-out\");\n self.suspend_notices();\n self.model.list = Default::default();\n self.model.writes.clear();\n self.model.connection = None;\n self.model.offline = false;\n self.clear_chat();\n self.make.teardown();\n self.backend.run(Job::SignOut);\n }\n\n /// Posts `message` through `hello.greet`: predicted at once in the daemon's replica, then confirmed or\n /// rejected (rolled back) by the kernel.\n pub fn greet(&mut self, message: String) {\n let message = message.trim().to_owned();\n if message.is_empty() || !self.model.usable() {\n return;\n }\n self.writes += 1;\n let id = format!(\"w{}-{}\", self.writes, crate::random_id());\n self.model.wrote(id.clone(), message.clone());\n self.backend.run(Job::Write {\n generation: self.model.generation,\n id,\n mutator: GREET_MUTATOR.into(),\n input: json!({ \"message\": message }),\n });\n }\n\n pub fn dark(&self, system_dark: bool) -> bool {\n match self.appearance {\n Appearance::System => system_dark,\n Appearance::Light => false,\n Appearance::Dark => true,\n }\n }\n}\n\n/// The prefixes of the notification subscriptions' ids (the host's own): the notifications, the approval requests.\nconst NOTICES_PREFIX: &str = \"notices-\";\nconst NOTICES_REQUESTS_PREFIX: &str = \"notices-requests-\";\n\n/// How long the host waits before asking again whether the agent can answer, while it cannot.\npub const READINESS_RECHECK: Duration = Duration::from_secs(10);\n\n/// Whether a failed request made in `generation` was answered definitively: the daemon answered with a refusal (a 4xx\n/// but 408, not a wait for an approval or consent, and not `StaleGeneration` naming `generation`: the context changed\n/// while it ran). No answer or a server's error may hide a send that ran: it is resent under its key.\nfn definitive(error: &ClientError, generation: i64) -> bool {\n if error.tag() == \"StaleGeneration\" {\n return error.not_run_in(generation);\n }\n let status = match error {\n ClientError::Refused { status, .. } | ClientError::RefusedOther { status, .. } => *status,\n ClientError::Transport(_) | ClientError::Decode(_) => return false,\n };\n (400..500).contains(&status)\n && status != 408\n && !matches!(error.tag().as_str(), \"ApprovalRequired\" | \"ConsentRequired\")\n}\n",
222
+ "type": "registry:file",
223
+ "target": "desktop-rune/app/src/ui.rs"
224
+ },
225
+ {
226
+ "path": "app/desktop-rune/app/src/updates.rs",
227
+ "content": "//! Updates (the Host contract's `checkUpdate`, `applyUpdate`): signed builds from the app's update host\n//! ([`eloxiv_update`]: the manifest, minisign verification against the app's public key, never a downgrade),\n//! applied per install, restarted, and rolled back when the new build does not start.\n//!\n//! - **The install** ([`Install::detect`]): an AppImage (`$APPIMAGE`, Linux), a macOS `.app` bundle, a packaged\n//! install directory (Linux: the app's sidecar `<executable>-daemon` beside the executable), or an installed\n//! Windows app (its sidecar beside it: updated by running the new installer). A development build (`cargo run`: no\n//! packaged sidecar beside it), a system package (Linux: the sidecar in `../libexec`, a `.deb`: update it with the\n//! package manager) and a directory the person cannot write report updates unsupported, with the reason.\n//! - **Staging**, off the UI thread: the build is downloaded next to the install (the same filesystem, so the swap\n//! is a rename), verified, and an archive unpacked; nothing is touched until the person restarts.\n//! - **Applying**, after the window closed and the sidecar stopped: the install is renamed aside\n//! (`.<name>.eloxiv-previous`), the staged build renamed into its place, the single-instance name released, and the\n//! new build started with `ELOXIV_UPDATE_TRIAL` naming a marker file. The old process waits (at most\n//! `ELOXIV_UPDATE_TRIAL_SECONDS`, default 60) for the new one to write it, which it does once it is interactive\n//! (its window drawn and its daemon answering). Written: the old build is removed. Not written (the new build\n//! exited, or hangs): it is stopped, the old build renamed back and started again with `ELOXIV_UPDATE_ROLLED_BACK`\n//! saying why, which the window shows. The version that failed is remembered (`update-failed-version` in the\n//! host's data directory) and never offered again; a newer one is.\n//! - **Windows** runs the installer (`.msi` with `msiexec /passive`, else an NSIS `.exe` with `/S`) once this\n//! process has exited, then starts the app; rolling back is the installer's own, not this host's.\n\nuse std::ffi::OsString;\nuse std::path::{Path, PathBuf};\nuse std::process::{Child, Command};\nuse std::sync::Mutex;\nuse std::time::{Duration, Instant};\n\nuse eloxiv_update::{self as up, Kind, Offer, Version};\n\nuse crate::config::HostConfig;\nuse crate::host::{Capability, HostError};\n\n/// Names the marker file a new build writes once it is interactive.\npub const TRIAL_ENV: &str = \"ELOXIV_UPDATE_TRIAL\";\n/// Tells a build started again after a failed update what happened.\npub const ROLLED_BACK_ENV: &str = \"ELOXIV_UPDATE_ROLLED_BACK\";\n/// Tells a new build the version it replaced.\npub const UPDATED_FROM_ENV: &str = \"ELOXIV_UPDATE_FROM\";\n\n/// What this install is, for updating it.\n#[derive(Clone, Debug, PartialEq, Eq)]\npub enum Install {\n AppImage {\n file: PathBuf,\n },\n /// A macOS bundle (`<dir>` is the `.app`), started through `Contents/MacOS/<exe>`.\n Bundle {\n dir: PathBuf,\n exe: OsString,\n },\n /// A packaged install directory (Linux), started through `<dir>/<exe>`.\n Directory {\n dir: PathBuf,\n exe: OsString,\n },\n /// An installed Windows app, updated by its installer.\n Installer {\n exe: PathBuf,\n },\n Unsupported(String),\n}\n\nimpl Install {\n /// This process's install.\n pub fn detect() -> Install {\n match std::env::current_exe() {\n Ok(exe) => Install::detect_for(&exe, std::env::var_os(\"APPIMAGE\").map(PathBuf::from), std::env::consts::OS),\n Err(e) => Install::Unsupported(format!(\"this executable's path is unknown: {e}\")),\n }\n }\n\n /// The install of `exe` on `os`, `appimage` being `$APPIMAGE`.\n pub fn detect_for(exe: &Path, appimage: Option<PathBuf>, os: &str) -> Install {\n let Some(dir) = exe.parent() else { return Install::Unsupported(\"the executable has no folder\".into()) };\n let Some(name) = exe.file_name().map(|n| n.to_owned()) else {\n return Install::Unsupported(\"the executable has no name\".into());\n };\n if os == \"linux\"\n && let Some(file) = appimage.filter(|p| p.is_absolute())\n {\n return Install::AppImage { file };\n }\n if os == \"macos\" && dir.file_name().is_some_and(|n| n == \"MacOS\") {\n let contents = dir.parent();\n let bundle = contents.filter(|c| c.file_name().is_some_and(|n| n == \"Contents\")).and_then(Path::parent);\n if let Some(bundle) = bundle.filter(|b| b.extension().is_some_and(|e| e == \"app\")) {\n return Install::Bundle { dir: bundle.to_path_buf(), exe: name };\n }\n }\n // A package installs the app's sidecar under the executable's name: beside it, or (a Linux system package)\n // in ../libexec.\n let stem = exe.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();\n let sidecar = format!(\"{stem}-daemon{}\", if os == \"windows\" { \".exe\" } else { \"\" });\n if os == \"linux\" && dir.join(\"..\").join(\"libexec\").join(&sidecar).is_file() {\n return Install::Unsupported(\n \"installed by a system package: update it with its package manager (or use the AppImage)\".into(),\n );\n }\n if !dir.join(&sidecar).is_file() {\n return Install::Unsupported(format!(\n \"a development build: no packaged sidecar ({sidecar}) beside the executable\"\n ));\n }\n // A folder is replaced whole on update, so only one dedicated to the app is: it carries the marker naming the\n // app. A folder the app was merely unpacked into (~/bin, ~/Applications) is never replaced.\n if os == \"linux\" && marker_app(dir).is_none() {\n return Install::Unsupported(format!(\n \"{} is not a dedicated install directory (no {INSTALL_MARKER} naming the app): the host never replaces a folder it did not install\",\n dir.display()\n ));\n }\n match os {\n \"windows\" => Install::Installer { exe: exe.to_path_buf() },\n \"linux\" => Install::Directory { dir: dir.to_path_buf(), exe: name },\n other => Install::Unsupported(format!(\"updates are not implemented on {other}\")),\n }\n }\n\n /// The artifact kind it takes.\n pub fn kind(&self) -> Option<Kind> {\n match self {\n Install::AppImage { .. } => Some(Kind::Appimage),\n Install::Bundle { .. } | Install::Directory { .. } => Some(Kind::Archive),\n Install::Installer { .. } => Some(Kind::Installer),\n Install::Unsupported(_) => None,\n }\n }\n\n /// What is swapped: the AppImage, the bundle, the install directory.\n pub fn target(&self) -> Option<&Path> {\n match self {\n Install::AppImage { file } => Some(file),\n Install::Bundle { dir, .. } | Install::Directory { dir, .. } => Some(dir),\n Install::Installer { .. } | Install::Unsupported(_) => None,\n }\n }\n\n /// The executable that starts the build at the target.\n pub fn executable(&self) -> Option<PathBuf> {\n match self {\n Install::AppImage { file } => Some(file.clone()),\n Install::Bundle { dir, exe } => Some(dir.join(\"Contents\").join(\"MacOS\").join(exe)),\n Install::Directory { dir, exe } => Some(dir.join(exe)),\n Install::Installer { exe } => Some(exe.clone()),\n Install::Unsupported(_) => None,\n }\n }\n}\n\n/// The file that marks a Linux install directory as the app's own (`app=<identifier>`): only such a folder is\n/// replaced by an update, and the update must carry the same marker.\npub const INSTALL_MARKER: &str = \".eloxiv-install\";\n\n/// The app a directory's [`INSTALL_MARKER`] names, if it has one.\npub fn marker_app(dir: &Path) -> Option<String> {\n let text = std::fs::read_to_string(dir.join(INSTALL_MARKER)).ok()?;\n text.lines().find_map(|l| l.trim().strip_prefix(\"app=\")).map(|a| a.trim().to_owned()).filter(|a| !a.is_empty())\n}\n\n/// A directory install may be replaced by `staged` only when both carry the marker naming the same app.\npub fn check_markers(install: &Path, staged: &Path) -> Result<(), String> {\n match (marker_app(install), marker_app(staged)) {\n (Some(a), Some(b)) if a == b => Ok(()),\n (None, _) => Err(format!(\n \"{} is not a dedicated install directory (no {INSTALL_MARKER}): it is never replaced\",\n install.display()\n )),\n (Some(a), b) => Err(format!(\"the update's {INSTALL_MARKER} names {b:?}, not {a}\")),\n }\n}\n\n/// A path beside `target` named `.<target's name>.<suffix>` (the same filesystem, so a rename moves it).\nfn beside(target: &Path, suffix: &str) -> PathBuf {\n let name = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();\n target.with_file_name(format!(\".{name}.{suffix}\"))\n}\n\nfn remove(path: &Path) {\n if path.is_dir() {\n let _ = std::fs::remove_dir_all(path);\n } else {\n let _ = std::fs::remove_file(path);\n }\n}\n\n/// Whether this process may create files in `dir`.\nfn writable(dir: &Path) -> bool {\n let probe = dir.join(format!(\".eloxiv-write-probe-{}\", std::process::id()));\n let ok = std::fs::write(&probe, b\"\").is_ok();\n let _ = std::fs::remove_file(&probe);\n ok\n}\n\n/// The app's updater: its update host and this install.\n#[derive(Clone, Debug)]\npub struct Updater {\n source: Option<up::Source>,\n pub install: Install,\n reason: Option<String>,\n /// Where a version that failed to start is remembered ([`remember_failed`]), never offered again.\n data_dir: Option<PathBuf>,\n}\n\n/// The file in the host's data directory naming the last version that was rolled back.\nconst FAILED_FILE: &str = \"update-failed-version\";\n\n/// Remembers that `version` did not start and was rolled back.\npub fn remember_failed(data_dir: &Path, version: &Version) {\n if let Err(e) =\n std::fs::create_dir_all(data_dir).and_then(|()| std::fs::write(data_dir.join(FAILED_FILE), version.to_string()))\n {\n eprintln!(\"eloxiv-desktop-rune: could not remember that {version} failed: {e}\");\n }\n}\n\n/// The version that last failed to start, if any.\npub fn failed_version(data_dir: &Path) -> Option<Version> {\n std::fs::read_to_string(data_dir.join(FAILED_FILE)).ok().and_then(|t| Version::parse(t.trim()).ok())\n}\n\n/// Forgets it (a newer build started).\npub fn forget_failed(data_dir: &Path) {\n let _ = std::fs::remove_file(data_dir.join(FAILED_FILE));\n}\n\n/// A verified build, ready to apply.\n#[derive(Clone, Debug, PartialEq)]\npub struct Staged {\n pub version: Version,\n pub current: Version,\n pub install: Install,\n /// The staged AppImage, unpacked archive or downloaded installer.\n pub path: PathBuf,\n /// What verifies it again right before it runs (an installer, which may ask to elevate).\n pub recheck: Option<Recheck>,\n}\n\n/// A staged file's signature, checked again against the app's key right before it is run.\n#[derive(Clone, Debug, PartialEq, Eq)]\npub struct Recheck {\n pub public_key: String,\n pub signature: String,\n pub trusted_comment: String,\n}\n\n/// Verifies `staged` again (an installer kept since its download): its bytes must still be the signed ones.\npub fn recheck(staged: &Staged) -> Result<(), String> {\n let Some(r) = &staged.recheck else { return Ok(()) };\n let key = up::public_key(&r.public_key).map_err(|e| e.to_string())?;\n up::verify_file(&key, &staged.path, &r.signature, &r.trusted_comment)\n .map_err(|e| format!(\"the downloaded installer no longer matches its signature: {e}\"))\n}\n\n/// How an installer is started: an `.msi` through `msiexec /i <file> /passive`; an NSIS `.exe` itself with `/S`\n/// (silent: it closes the running app) and `/R` (it starts the app again when done). Each argument is its own, no\n/// shell in between.\npub fn installer_command(installer: &Path) -> (OsString, Vec<OsString>) {\n if installer.extension().is_some_and(|e| e.eq_ignore_ascii_case(\"msi\")) {\n (\"msiexec\".into(), vec![\"/i\".into(), installer.as_os_str().to_owned(), \"/passive\".into()])\n } else {\n (installer.as_os_str().to_owned(), vec![\"/S\".into(), \"/R\".into()])\n }\n}\n\nimpl Updater {\n pub fn new(config: &HostConfig, install: Install) -> Updater {\n let kind = install.kind();\n let (source, reason) = match (&config.updates, kind) {\n (None, _) => {\n (None, Some(\"no update host is configured (app.json updates.url and updates.publicKey)\".into()))\n }\n (Some(_), None) => {\n let Install::Unsupported(why) = &install else { unreachable!(\"every other install has a kind\") };\n (None, Some(why.clone()))\n }\n (Some(u), Some(kind)) => (\n Some(up::Source {\n manifest_url: u.url.clone(),\n public_key: u.public_key.clone(),\n channel: u.channel.clone(),\n app: config.app_id.clone(),\n current: config.version.clone(),\n kind,\n platform: up::platform(),\n }),\n None,\n ),\n };\n let mut updater = Updater { source, install, reason, data_dir: None };\n if let Install::Directory { dir, .. } = &updater.install\n && marker_app(dir).as_deref() != Some(config.app_id.as_str())\n {\n updater.reason = Some(format!(\"{} is another app's install directory ({INSTALL_MARKER})\", dir.display()));\n updater.source = None;\n }\n updater\n }\n\n /// Remembers failed versions in `data_dir` (the host's data directory): an offer of one is not an update.\n pub fn remembering(self, data_dir: Option<PathBuf>) -> Updater {\n Updater { data_dir, ..self }\n }\n\n /// This build's version.\n pub fn current(&self) -> Option<&Version> {\n self.source.as_ref().map(|s| &s.current)\n }\n\n fn source(&self) -> Result<&up::Source, HostError> {\n self.source.as_ref().ok_or_else(|| HostError::Unsupported {\n capability: Capability::Updates,\n reason: self.reason.clone().unwrap_or_default(),\n })\n }\n\n pub fn supported(&self) -> Result<(), HostError> {\n self.source().map(|_| ())\n }\n\n /// `checkUpdate`: the newer build the update host offers for this install (None: this one is the newest).\n pub fn check(&self) -> Result<Option<Offer>, HostError> {\n let source = self.source()?;\n if let Some(target) = self.install.target()\n && !target.parent().is_some_and(writable)\n {\n return Err(HostError::Unsupported {\n capability: Capability::Updates,\n reason: format!(\n \"{} cannot be replaced by this user: update it with its package manager\",\n target.display()\n ),\n });\n }\n let offer = up::check(source).map_err(failure)?;\n Ok(offer.filter(|o| self.offerable(&o.version)))\n }\n\n /// Whether `version` may be offered: newer than any version that failed to start here.\n pub fn offerable(&self, version: &Version) -> bool {\n match self.data_dir.as_deref().and_then(failed_version) {\n Some(failed) if !up::newer(version, &failed) => {\n eprintln!(\n \"eloxiv-desktop-rune: {version} is not offered: {failed} failed to start here; waiting for a newer build\"\n );\n false\n }\n _ => true,\n }\n }\n\n /// Downloads, verifies and stages `offer` (blocking: off the UI thread). `progress` gets the bytes so far.\n pub fn stage(&self, offer: &Offer, progress: &mut dyn FnMut(u64)) -> Result<Staged, HostError> {\n let source = self.source()?;\n let staged = |path: PathBuf| Staged {\n version: offer.version.clone(),\n current: source.current.clone(),\n install: self.install.clone(),\n path,\n recheck: None,\n };\n match &self.install {\n Install::AppImage { file } => {\n let path = beside(file, \"eloxiv-update\");\n remove(&path);\n up::download(source, offer, &path, progress).map_err(failure)?;\n #[cfg(unix)]\n {\n use std::os::unix::fs::PermissionsExt;\n std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))\n .map_err(|e| HostError::Failure(e.to_string()))?;\n }\n if let Err(e) = check_staged_version(&path, &offer.version) {\n remove(&path);\n return Err(HostError::Failure(e));\n }\n Ok(staged(path))\n }\n Install::Bundle { dir, exe } | Install::Directory { dir, exe } => {\n let (archive, path) = (beside(dir, \"eloxiv-update.tar.gz\"), beside(dir, \"eloxiv-update\"));\n remove(&archive);\n remove(&path);\n up::download(source, offer, &archive, progress).map_err(failure)?;\n let unpacked = up::archive::unpack(&archive, &path);\n remove(&archive);\n unpacked.map_err(|e| HostError::Failure(format!(\"the update does not unpack: {e}\")))?;\n let s = staged(path);\n if let Install::Directory { dir, .. } = &self.install\n && let Err(e) = check_markers(dir, &s.path)\n {\n remove(&s.path);\n return Err(HostError::Failure(e));\n }\n // The staged build must start the way this one does.\n let probe = match &self.install {\n Install::Bundle { .. } => s.path.join(\"Contents\").join(\"MacOS\").join(exe),\n _ => s.path.join(exe),\n };\n if !probe.is_file() {\n remove(&s.path);\n return Err(HostError::Failure(format!(\"the update has no {}\", exe.to_string_lossy())));\n }\n if let Err(e) = check_staged_version(&probe, &offer.version) {\n remove(&s.path);\n return Err(HostError::Failure(e));\n }\n Ok(s)\n }\n Install::Installer { .. } => {\n let ext = if offer.url.to_ascii_lowercase().ends_with(\".msi\") { \"msi\" } else { \"exe\" };\n // A folder of its own, named at random and created here (never one that exists): its path cannot\n // be guessed and prepared by another process.\n let dir = private_dir().map_err(|e| HostError::Failure(format!(\"a folder for the update: {e}\")))?;\n let path = dir.join(format!(\"{}-{}-setup.{ext}\", source.app, offer.version));\n up::download(source, offer, &path, progress).map_err(|e| {\n remove(&dir);\n failure(e)\n })?;\n Ok(Staged {\n recheck: Some(Recheck {\n public_key: source.public_key.clone(),\n signature: offer.signature.clone(),\n trusted_comment: up::trusted_comment(\n &source.app,\n &source.channel,\n &offer.version,\n &offer.platform,\n offer.kind,\n ),\n }),\n ..staged(path)\n })\n }\n Install::Unsupported(why) => {\n Err(HostError::Unsupported { capability: Capability::Updates, reason: why.clone() })\n }\n }\n }\n}\n\n/// The version a staged build says it is (`<exe> --print-version`: the version compiled into it from `app.json`),\n/// asked with at most `within` to answer.\npub fn staged_version(exe: &Path, within: Duration) -> Result<Version, String> {\n let mut child = Command::new(exe)\n .arg(\"--print-version\")\n // An AppImage without FUSE unpacks itself instead; the environment's overrides are not the build's.\n .env(\"APPIMAGE_EXTRACT_AND_RUN\", \"1\")\n .env_remove(\"ELOXIV_APP_VERSION\")\n .env_remove(\"ELOXIV_HOST_CONFIG\")\n .stdin(std::process::Stdio::null())\n .stdout(std::process::Stdio::piped())\n .stderr(std::process::Stdio::null())\n .spawn()\n .map_err(|e| format!(\"the update could not be asked its version: {e}\"))?;\n let deadline = Instant::now() + within;\n loop {\n match child.try_wait() {\n Ok(Some(_)) => break,\n Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(20)),\n _ => {\n let _ = child.kill();\n let _ = child.wait();\n return Err(\"the update did not say its version\".into());\n }\n }\n }\n let mut out = String::new();\n if let Some(mut stdout) = child.stdout.take() {\n use std::io::Read;\n let _ = stdout.read_to_string(&mut out);\n }\n let line = out.lines().map(str::trim).rfind(|l| !l.is_empty()).unwrap_or_default();\n Version::parse(line).map_err(|_| format!(\"the update says its version is {line:?}\"))\n}\n\n/// The staged build must be the version that was signed and offered: one whose `app.json` says another would be\n/// offered the same update again after it started, forever.\npub fn check_staged_version(exe: &Path, offered: &Version) -> Result<(), String> {\n let built = staged_version(exe, Duration::from_secs(20))?;\n if built.cmp_precedence(offered) == std::cmp::Ordering::Equal {\n Ok(())\n } else {\n Err(format!(\"the update was signed as {offered} but the build says it is {built}: refused\"))\n }\n}\n\n/// A new folder under the temporary directory, named at random, readable by this user only (Unix).\nfn private_dir() -> std::io::Result<PathBuf> {\n let dir = std::env::temp_dir().join(format!(\"eloxiv-update-{}\", crate::random_id()));\n #[cfg(unix)]\n {\n use std::os::unix::fs::DirBuilderExt;\n std::fs::DirBuilder::new().mode(0o700).create(&dir)?;\n }\n #[cfg(not(unix))]\n std::fs::DirBuilder::new().create(&dir)?;\n Ok(dir)\n}\n\nfn failure(e: up::Error) -> HostError {\n HostError::Failure(e.to_string())\n}\n\n// The build to apply when the window closes (`applyUpdate` asks for it, then quits the loop).\n\nstatic PENDING: Mutex<Option<Staged>> = Mutex::new(None);\n\n/// Applies `staged` once the window has closed.\npub fn set_pending(staged: Staged) {\n *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some(staged);\n}\n\n/// The build to apply, if the person asked for one.\npub fn take_pending() -> Option<Staged> {\n PENDING.lock().unwrap_or_else(|e| e.into_inner()).take()\n}\n\n/// The new build tells the old one it started (its window drawn and its daemon answering). Once per process.\npub fn mark_started() {\n static DONE: std::sync::Once = std::sync::Once::new();\n DONE.call_once(|| {\n if let Some(marker) = std::env::var_os(TRIAL_ENV)\n && let Err(e) = std::fs::write(&marker, b\"started\")\n {\n eprintln!(\"eloxiv-desktop-rune: could not tell the previous build this one started: {e}\");\n }\n });\n}\n\n/// What the old build saw of the new one's start.\n#[derive(Debug, PartialEq, Eq)]\npub enum Trial {\n Started,\n Exited(String),\n TimedOut,\n}\n\n/// Waits for `child` to write `marker`, for at most `window`; a child that exits or hangs is a failed start (a hung\n/// one is stopped).\npub fn supervise(child: &mut Child, marker: &Path, window: Duration) -> Trial {\n let deadline = Instant::now() + window;\n loop {\n if std::fs::read(marker).is_ok_and(|b| b == b\"started\") {\n return Trial::Started;\n }\n match child.try_wait() {\n Ok(Some(status)) => {\n // It may have written the marker just before it exited.\n if std::fs::read(marker).is_ok_and(|b| b == b\"started\") {\n return Trial::Started;\n }\n return Trial::Exited(status.to_string());\n }\n Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(25)),\n _ => {\n let _ = child.kill();\n let _ = child.wait();\n return Trial::TimedOut;\n }\n }\n }\n}\n\n/// What applying did.\n#[derive(Debug, PartialEq, Eq)]\npub enum Applied {\n /// The new build started; the old one is gone.\n Updated,\n /// The new build did not start; the old one is back and was started again.\n RolledBack(String),\n /// The installer was started (Windows); it starts the app when done.\n InstallerStarted,\n}\n\n/// Beside the install while an update is applied: `pid=`, `from=`, `to=` lines.\nconst JOURNAL: &str = \"eloxiv-apply\";\n\n/// Whether the process `pid` is running (Unix: `kill -0`; elsewhere unknown, taken as running).\nfn alive(pid: u32) -> bool {\n if cfg!(unix) {\n Command::new(\"kill\")\n .args([\"-0\", &pid.to_string()])\n .stderr(std::process::Stdio::null())\n .status()\n .map(|s| s.success())\n .unwrap_or(true)\n } else {\n true\n }\n}\n\n/// At start (not as a build under trial): an update whose applying process died before it settled the outcome\n/// (killed between the renames, or during the trial) left a journal beside the install. Its backup is put back,\n/// the version it tried remembered as failed, and the reason returned, for the caller to start the restored build\n/// with. A journal whose process still runs (it is supervising a trial) is left alone.\npub fn recover(install: &Install, data_dir: &Path) -> Option<String> {\n let target = install.target()?;\n let journal = beside(target, JOURNAL);\n let text = std::fs::read_to_string(&journal).ok()?;\n let field = |name: &str| text.lines().find_map(|l| l.strip_prefix(name)).map(str::trim);\n if field(\"pid=\").and_then(|p| p.parse::<u32>().ok()).is_some_and(alive) {\n return None;\n }\n let backup = beside(target, \"eloxiv-previous\");\n if !backup.exists() {\n // The outcome was settled (the backup removed after a start, or put back) before the journal went.\n let _ = std::fs::remove_file(&journal);\n return None;\n }\n remove(target);\n if let Err(e) = std::fs::rename(&backup, target) {\n eprintln!(\"eloxiv-desktop-rune: restoring {} after an interrupted update: {e}\", target.display());\n return None;\n }\n let _ = std::fs::remove_file(&journal);\n let to = field(\"to=\").unwrap_or(\"the update\").to_owned();\n if let Ok(v) = Version::parse(&to) {\n remember_failed(data_dir, &v);\n }\n Some(format!(\"the update to {to} was interrupted before it was known to start\"))\n}\n\n/// How long a new build has to start.\npub fn trial_window() -> Duration {\n let secs = std::env::var(\"ELOXIV_UPDATE_TRIAL_SECONDS\").ok().and_then(|s| s.parse::<u64>().ok()).unwrap_or(60);\n Duration::from_secs(secs.max(1))\n}\n\n/// Applies `staged` and starts the result with `args` (this launch's arguments, links removed): see the module.\n/// `marker_dir` holds the trial's marker. Call it after the window closed, the sidecar stopped and the\n/// single-instance name was released.\npub fn apply(staged: &Staged, args: &[OsString], marker_dir: &Path, window: Duration) -> Result<Applied, String> {\n if !up::newer(&staged.version, &staged.current) {\n remove(&staged.path);\n return Err(format!(\"{} is not newer than {}: never a downgrade\", staged.version, staged.current));\n }\n if let Install::Installer { .. } = &staged.install {\n recheck(staged)?;\n return run_installer(&staged.path).map(|()| Applied::InstallerStarted);\n }\n let (Some(target), Some(exe)) = (staged.install.target(), staged.install.executable()) else {\n return Err(\"this install cannot be updated\".into());\n };\n // Never a folder the app did not install: it is renamed aside and removed whole below.\n if let Install::Directory { dir, .. } = &staged.install {\n check_markers(dir, &staged.path)?;\n }\n let backup = beside(target, \"eloxiv-previous\");\n remove(&backup);\n // The journal names this process and the backup until the outcome is settled: if this process dies (killed, the\n // session ends) before then, the next start restores the backup ([`recover`]).\n let journal = beside(target, JOURNAL);\n std::fs::write(&journal, format!(\"pid={}\\nfrom={}\\nto={}\\n\", std::process::id(), staged.current, staged.version))\n .map_err(|e| format!(\"writing {}: {e}\", journal.display()))?;\n let swapped = if target.is_file() {\n // A file (the AppImage): the backup is a second name for it, then the new build replaces it in one rename, so\n // the launcher's path is never empty.\n std::fs::hard_link(target, &backup)\n .or_else(|_| std::fs::copy(target, &backup).map(|_| ()))\n .map_err(|e| format!(\"keeping {} aside: {e}\", target.display()))\n .and_then(|()| {\n std::fs::rename(&staged.path, target).map_err(|e| format!(\"putting the update in place: {e}\"))\n })\n } else {\n std::fs::rename(target, &backup).map_err(|e| format!(\"moving {} aside: {e}\", target.display())).and_then(|()| {\n std::fs::rename(&staged.path, target).map_err(|e| {\n let _ = std::fs::rename(&backup, target);\n format!(\"putting the update in place: {e}\")\n })\n })\n };\n if let Err(e) = swapped {\n remove(&backup);\n let _ = std::fs::remove_file(&journal);\n return Err(e);\n }\n let marker = marker_dir.join(format!(\"update-trial-{}.started\", std::process::id()));\n let _ = std::fs::remove_file(&marker);\n let started = Command::new(&exe)\n .args(args)\n .env(TRIAL_ENV, &marker)\n .env(UPDATED_FROM_ENV, staged.current.to_string())\n .env_remove(ROLLED_BACK_ENV)\n .spawn();\n let trial = match started {\n Ok(mut child) => supervise(&mut child, &marker, window),\n Err(e) => Trial::Exited(format!(\"it could not be started: {e}\")),\n };\n let _ = std::fs::remove_file(&marker);\n if trial == Trial::Started {\n // The journal goes first: once it is gone the new build is the install, and a backup left half-deleted by an\n // interrupted cleanup is only stale files. The other order lets a restore at the next start put that\n // half-deleted backup in place of the working build.\n let _ = std::fs::remove_file(&journal);\n remove(&backup);\n forget_failed(marker_dir);\n return Ok(Applied::Updated);\n }\n let why = match trial {\n Trial::Exited(status) => format!(\"{} exited before it was ready ({status})\", staged.version),\n _ => format!(\"{} was not ready within {} s\", staged.version, window.as_secs()),\n };\n remember_failed(marker_dir, &staged.version);\n // A file is replaced by the rename itself (its path never empty); a folder must go first.\n if !target.is_file() {\n remove(target);\n }\n std::fs::rename(&backup, target).map_err(|e| format!(\"{why}; putting {} back failed: {e}\", staged.current))?;\n let _ = std::fs::remove_file(&journal);\n Command::new(&exe)\n .args(args)\n .env(ROLLED_BACK_ENV, &why)\n .env_remove(TRIAL_ENV)\n .spawn()\n .map_err(|e| format!(\"{why}; {} is back but could not be started: {e}\", staged.current))?;\n Ok(Applied::RolledBack(why))\n}\n\n/// Starts the installer directly ([`installer_command`]); this process exits right after (Rune's last step), and\n/// NSIS closes it anyway before it replaces its files.\n#[cfg(windows)]\nfn run_installer(installer: &Path) -> Result<(), String> {\n let (program, args) = installer_command(installer);\n Command::new(program).args(args).spawn().map(|_| ()).map_err(|e| format!(\"the installer: {e}\"))\n}\n\n#[cfg(not(windows))]\nfn run_installer(_: &Path) -> Result<(), String> {\n Err(\"installers are applied on Windows only\".into())\n}\n\n/// After a restart: what the previous process did, for the window.\npub fn restart_notice(current: &Version) -> Option<String> {\n if let Ok(why) = std::env::var(ROLLED_BACK_ENV) {\n return Some(format!(\"The update did not start ({why}); still on {current}.\"));\n }\n std::env::var(UPDATED_FROM_ENV).ok().map(|from| format!(\"Updated from {from} to {current}.\"))\n}\n\n#[cfg(all(test, unix))]\nmod tests {\n use super::*;\n use std::os::unix::fs::PermissionsExt;\n\n struct Dir(PathBuf);\n impl Dir {\n fn new(name: &str) -> Dir {\n let d = std::env::temp_dir().join(format!(\"eloxiv-rune-update-{name}-{}\", crate::random_id()));\n std::fs::create_dir_all(&d).expect(\"a test directory\");\n Dir(d)\n }\n }\n impl Drop for Dir {\n fn drop(&mut self) {\n let _ = std::fs::remove_dir_all(&self.0);\n }\n }\n\n fn script(path: &Path, body: &str) {\n std::fs::write(path, format!(\"#!/bin/sh\\n{body}\\n\")).expect(\"a test file\");\n std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).expect(\"as the test set it up\");\n }\n\n fn v(s: &str) -> Version {\n Version::parse(s).expect(\"a version\")\n }\n\n /// The old build: when started again it records why.\n const OLD: &str = \"echo \\\"old $ELOXIV_UPDATE_ROLLED_BACK\\\" > \\\"$(dirname \\\"$0\\\")/../ran\\\"\";\n\n fn directory_install(root: &Path) -> (Install, PathBuf) {\n let dir = root.join(\"app\");\n std::fs::create_dir_all(&dir).expect(\"a test directory\");\n std::fs::write(dir.join(\"eloxiv-desktop-rune-daemon\"), \"\").expect(\"a test file\");\n std::fs::write(dir.join(INSTALL_MARKER), \"app=dev.eloxiv.desktop-rune\\n\").expect(\"a test file\");\n script(&dir.join(\"eloxiv-desktop-rune\"), OLD);\n let install = Install::detect_for(&dir.join(\"eloxiv-desktop-rune\"), None, \"linux\");\n assert_eq!(install, Install::Directory { dir: dir.clone(), exe: \"eloxiv-desktop-rune\".into() });\n let staged = beside(&dir, \"eloxiv-update\");\n std::fs::create_dir_all(&staged).expect(\"a test directory\");\n std::fs::write(staged.join(\"eloxiv-desktop-rune-daemon\"), \"\").expect(\"a test file\");\n std::fs::write(staged.join(INSTALL_MARKER), \"app=dev.eloxiv.desktop-rune\\n\").expect(\"a test file\");\n (install, staged)\n }\n\n fn ran(root: &Path) -> String {\n let deadline = Instant::now() + Duration::from_secs(5);\n loop {\n if let Ok(t) = std::fs::read_to_string(root.join(\"ran\")) {\n return t.trim().to_owned();\n }\n assert!(Instant::now() < deadline, \"the restarted build never ran\");\n std::thread::sleep(Duration::from_millis(20));\n }\n }\n\n #[test]\n fn installs_are_detected_per_platform() {\n let root = Dir::new(\"detect\");\n let exe = root.0.join(\"eloxiv-desktop-rune\");\n assert!(matches!(Install::detect_for(&exe, None, \"linux\"), Install::Unsupported(_)), \"a development build\");\n assert_eq!(\n Install::detect_for(&exe, Some(\"/home/p/Apps/Example.AppImage\".into()), \"linux\"),\n Install::AppImage { file: \"/home/p/Apps/Example.AppImage\".into() }\n );\n let mac = Path::new(\"/Applications/Example.app/Contents/MacOS/example\");\n assert_eq!(\n Install::detect_for(mac, None, \"macos\"),\n Install::Bundle { dir: \"/Applications/Example.app\".into(), exe: \"example\".into() }\n );\n std::fs::write(root.0.join(\"eloxiv-desktop-rune-daemon.exe\"), \"\").expect(\"a test file\");\n assert_eq!(Install::detect_for(&exe, None, \"windows\"), Install::Installer { exe: exe.clone() });\n std::fs::write(root.0.join(\"eloxiv-desktop-rune-daemon\"), \"\").expect(\"a test file\");\n std::fs::write(root.0.join(INSTALL_MARKER), \"app=dev.eloxiv.desktop-rune\\n\").expect(\"a test file\");\n assert!(matches!(Install::detect_for(&exe, None, \"linux\"), Install::Directory { .. }));\n // A system package: /usr/bin/<app> with /usr/libexec/<app>-daemon.\n let bin = root.0.join(\"usr\").join(\"bin\");\n let libexec = root.0.join(\"usr\").join(\"libexec\");\n std::fs::create_dir_all(&bin).expect(\"a test directory\");\n std::fs::create_dir_all(&libexec).expect(\"a test directory\");\n std::fs::write(libexec.join(\"acme-daemon\"), \"\").expect(\"a test file\");\n let system = Install::detect_for(&bin.join(\"acme\"), None, \"linux\");\n assert!(matches!(&system, Install::Unsupported(why) if why.contains(\"package manager\")), \"{system:?}\");\n let none = Updater::new(&HostConfig::default(), Install::detect_for(&exe, None, \"linux\"));\n assert!(matches!(none.check(), Err(HostError::Unsupported { capability: Capability::Updates, .. })));\n }\n\n #[test]\n fn a_build_that_starts_replaces_the_old_one() {\n let root = Dir::new(\"good\");\n let (install, staged) = directory_install(&root.0);\n script(\n &staged.join(\"eloxiv-desktop-rune\"),\n \"printf started > \\\"$ELOXIV_UPDATE_TRIAL\\\"; echo new > \\\"$(dirname \\\"$0\\\")/../ran\\\"\",\n );\n let s = Staged {\n version: v(\"1.1.0\"),\n current: v(\"1.0.0\"),\n install: install.clone(),\n path: staged.clone(),\n recheck: None,\n };\n assert_eq!(apply(&s, &[], &root.0, Duration::from_secs(10)), Ok(Applied::Updated));\n assert_eq!(ran(&root.0), \"new\");\n let exe =\n std::fs::read_to_string(root.0.join(\"app\").join(\"eloxiv-desktop-rune\")).expect(\"as the test set it up\");\n assert!(exe.contains(\"printf started\"), \"the new build is in place\");\n assert!(!beside(&root.0.join(\"app\"), \"eloxiv-previous\").exists(), \"the old build is gone\");\n assert!(!staged.exists());\n }\n\n #[test]\n fn a_build_that_exits_is_rolled_back_and_the_old_one_started_again() {\n let root = Dir::new(\"exits\");\n let (install, staged) = directory_install(&root.0);\n script(&staged.join(\"eloxiv-desktop-rune\"), \"exit 3\");\n let s = Staged { version: v(\"1.1.0\"), current: v(\"1.0.0\"), install, path: staged, recheck: None };\n let applied = apply(&s, &[], &root.0, Duration::from_secs(10)).expect(\"as the test set it up\");\n let Applied::RolledBack(why) = applied else { panic!(\"{applied:?}\") };\n assert!(why.contains(\"1.1.0 exited before it was ready\"), \"{why}\");\n assert_eq!(failed_version(&root.0), Some(v(\"1.1.0\")), \"the failed version is remembered\");\n assert_eq!(ran(&root.0), format!(\"old {why}\"), \"the old build, told why\");\n let exe =\n std::fs::read_to_string(root.0.join(\"app\").join(\"eloxiv-desktop-rune\")).expect(\"as the test set it up\");\n assert!(exe.contains(\"old $ELOXIV_UPDATE_ROLLED_BACK\"), \"the old build is back\");\n assert!(!beside(&root.0.join(\"app\"), \"eloxiv-previous\").exists());\n }\n\n #[test]\n fn a_build_that_hangs_is_stopped_and_rolled_back() {\n let root = Dir::new(\"hangs\");\n let (install, staged) = directory_install(&root.0);\n script(&staged.join(\"eloxiv-desktop-rune\"), \"exec sleep 30\");\n let s = Staged { version: v(\"1.1.0\"), current: v(\"1.0.0\"), install, path: staged, recheck: None };\n let started = Instant::now();\n let applied = apply(&s, &[], &root.0, Duration::from_millis(400)).expect(\"as the test set it up\");\n assert!(matches!(applied, Applied::RolledBack(ref why) if why.contains(\"not ready\")), \"{applied:?}\");\n assert!(started.elapsed() < Duration::from_secs(10), \"it was stopped, not waited for\");\n assert!(ran(&root.0).starts_with(\"old \"));\n }\n\n #[test]\n fn an_appimage_is_swapped_and_rolled_back_as_a_file() {\n let root = Dir::new(\"appimage\");\n let file = root.0.join(\"apps\").join(\"Example.AppImage\");\n std::fs::create_dir_all(file.parent().expect(\"a test directory\")).expect(\"as the test set it up\");\n script(&file, OLD);\n let install = Install::AppImage { file: file.clone() };\n let staged = beside(&file, \"eloxiv-update\");\n script(&staged, \"exit 1\");\n let s = Staged {\n version: v(\"2.0.0\"),\n current: v(\"1.0.0\"),\n install: install.clone(),\n path: staged.clone(),\n recheck: None,\n };\n assert!(matches!(apply(&s, &[], &root.0, Duration::from_secs(10)), Ok(Applied::RolledBack(_))));\n assert!(\n std::fs::read_to_string(&file).expect(\"as the test set it up\").contains(\"old\"),\n \"the old AppImage is back\"\n );\n // The old build, started again, has run before the file is replaced once more.\n assert!(ran(&root.0).starts_with(\"old \"));\n script(&staged, \"printf started > \\\"$ELOXIV_UPDATE_TRIAL\\\"\");\n assert_eq!(apply(&s, &[], &root.0, Duration::from_secs(10)), Ok(Applied::Updated));\n assert!(std::fs::read_to_string(&file).expect(\"as the test set it up\").contains(\"printf started\"));\n }\n\n #[test]\n fn never_applies_a_downgrade() {\n let root = Dir::new(\"downgrade\");\n let (install, staged) = directory_install(&root.0);\n script(&staged.join(\"eloxiv-desktop-rune\"), \"printf started > \\\"$ELOXIV_UPDATE_TRIAL\\\"\");\n for version in [\"1.0.0\", \"0.9.0\", \"1.0.0+rebuild\"] {\n std::fs::create_dir_all(&staged).expect(\"a test directory\");\n let s = Staged {\n version: v(version),\n current: v(\"1.0.0\"),\n install: install.clone(),\n path: staged.clone(),\n recheck: None,\n };\n assert!(\n apply(&s, &[], &root.0, Duration::from_secs(1)).expect_err(\"refused\").contains(\"never a downgrade\")\n );\n }\n let exe =\n std::fs::read_to_string(root.0.join(\"app\").join(\"eloxiv-desktop-rune\")).expect(\"as the test set it up\");\n assert!(exe.contains(\"old\"), \"nothing moved\");\n }\n\n #[test]\n fn a_version_that_failed_to_start_is_not_offered_again_until_a_newer_one() {\n let root = Dir::new(\"failed\");\n let config = HostConfig {\n updates: Some(crate::config::UpdatesConfig {\n url: \"http://127.0.0.1:9/m.json\".into(),\n public_key: \"RWQ\".into(),\n channel: \"stable\".into(),\n }),\n ..HostConfig::default()\n };\n let updater = Updater::new(&config, Install::AppImage { file: root.0.join(\"A.AppImage\") })\n .remembering(Some(root.0.clone()));\n assert!(updater.offerable(&v(\"1.1.0\")), \"nothing failed yet\");\n remember_failed(&root.0, &v(\"1.1.0\"));\n assert!(!updater.offerable(&v(\"1.1.0\")), \"the version that was rolled back\");\n assert!(!updater.offerable(&v(\"1.0.5\")));\n assert!(!updater.offerable(&v(\"1.1.0+rebuild\")), \"the same version with build metadata\");\n assert!(updater.offerable(&v(\"1.1.1\")), \"a newer build is offered\");\n forget_failed(&root.0);\n assert!(updater.offerable(&v(\"1.1.0\")));\n // A build that starts forgets an older failure.\n let (install, staged) = directory_install(&root.0);\n remember_failed(&root.0, &v(\"1.0.5\"));\n script(&staged.join(\"eloxiv-desktop-rune\"), \"printf started > \\\"$ELOXIV_UPDATE_TRIAL\\\"\");\n let s = Staged { version: v(\"1.1.0\"), current: v(\"1.0.0\"), install, path: staged, recheck: None };\n assert_eq!(apply(&s, &[], &root.0, Duration::from_secs(10)), Ok(Applied::Updated));\n assert_eq!(failed_version(&root.0), None);\n }\n\n #[test]\n fn a_shared_folder_the_app_was_unpacked_into_is_never_replaced() {\n let root = Dir::new(\"shared\");\n // ~/bin: the app, its sidecar and someone else's files, no marker.\n let bin = root.0.join(\"bin\");\n std::fs::create_dir_all(&bin).expect(\"a test directory\");\n script(&bin.join(\"eloxiv-desktop-rune\"), OLD);\n std::fs::write(bin.join(\"eloxiv-desktop-rune-daemon\"), \"\").expect(\"a test file\");\n std::fs::write(bin.join(\"someone-elses-notes.txt\"), \"keep me\").expect(\"a test file\");\n let detected = Install::detect_for(&bin.join(\"eloxiv-desktop-rune\"), None, \"linux\");\n assert!(\n matches!(&detected, Install::Unsupported(why) if why.contains(\"not a dedicated install directory\")),\n \"{detected:?}\"\n );\n let updater = Updater::new(\n &HostConfig {\n updates: Some(crate::config::UpdatesConfig {\n url: \"http://127.0.0.1:9/m\".into(),\n public_key: \"RWQ\".into(),\n channel: \"stable\".into(),\n }),\n ..HostConfig::default()\n },\n detected,\n );\n assert!(matches!(updater.check(), Err(HostError::Unsupported { capability: Capability::Updates, .. })));\n // Even handed a staged build directly, apply refuses the folder and touches nothing.\n let staged = beside(&bin, \"eloxiv-update\");\n std::fs::create_dir_all(&staged).expect(\"a test directory\");\n script(&staged.join(\"eloxiv-desktop-rune\"), \"printf started > \\\"$ELOXIV_UPDATE_TRIAL\\\"\");\n let s = Staged {\n version: v(\"1.1.0\"),\n current: v(\"1.0.0\"),\n install: Install::Directory { dir: bin.clone(), exe: \"eloxiv-desktop-rune\".into() },\n path: staged.clone(),\n recheck: None,\n };\n let refused = apply(&s, &[], &root.0, Duration::from_secs(5)).expect_err(\"refused\");\n assert!(refused.contains(\"not a dedicated install directory\"), \"{refused}\");\n assert_eq!(std::fs::read_to_string(bin.join(\"someone-elses-notes.txt\")).expect(\"still there\"), \"keep me\");\n // A marked install takes only an update marked for the same app; another app's marker is not this app's.\n std::fs::write(bin.join(INSTALL_MARKER), \"app=dev.eloxiv.desktop-rune\\n\").expect(\"a test file\");\n assert!(check_markers(&bin, &staged).expect_err(\"unmarked update\").contains(\"names None\"));\n std::fs::write(staged.join(INSTALL_MARKER), \"app=com.other.app\\n\").expect(\"a test file\");\n assert!(check_markers(&bin, &staged).is_err());\n std::fs::write(staged.join(INSTALL_MARKER), \"app=dev.eloxiv.desktop-rune\\n\").expect(\"a test file\");\n assert_eq!(check_markers(&bin, &staged), Ok(()));\n std::fs::write(bin.join(INSTALL_MARKER), \"app=com.other.app\\n\").expect(\"a test file\");\n let other =\n Updater::new(&HostConfig::default(), Install::detect_for(&bin.join(\"eloxiv-desktop-rune\"), None, \"linux\"));\n assert!(other.supported().is_err(), \"another app's install directory\");\n }\n\n #[test]\n fn an_update_interrupted_mid_apply_is_restored_at_the_next_start() {\n let root = Dir::new(\"interrupted\");\n let (install, _staged) = directory_install(&root.0);\n let dir = root.0.join(\"app\");\n let backup = beside(&dir, \"eloxiv-previous\");\n let journal = beside(&dir, JOURNAL);\n // The applying process, already dead.\n let mut gone = Command::new(\"true\").spawn().expect(\"true\");\n let dead = gone.id();\n gone.wait().expect(\"true exits\");\n\n // Killed during the trial: the new build is in place, the old one aside.\n std::fs::rename(&dir, &backup).expect(\"as the test set it up\");\n std::fs::create_dir_all(&dir).expect(\"a test directory\");\n std::fs::write(dir.join(\"eloxiv-desktop-rune\"), \"new, hanging\").expect(\"a test file\");\n std::fs::write(&journal, format!(\"pid={dead}\\nfrom=1.0.0\\nto=1.1.0\\n\")).expect(\"a test file\");\n let why = recover(&install, &root.0).expect(\"restored\");\n assert!(why.contains(\"1.1.0\"), \"{why}\");\n assert!(std::fs::read_to_string(dir.join(\"eloxiv-desktop-rune\")).expect(\"the old build\").contains(\"old\"));\n assert!(!backup.exists() && !journal.exists());\n assert_eq!(failed_version(&root.0), Some(v(\"1.1.0\")), \"not offered again\");\n\n // Killed between the renames: nothing at the install's path, only the backup.\n std::fs::rename(&dir, &backup).expect(\"as the test set it up\");\n std::fs::write(&journal, format!(\"pid={dead}\\nfrom=1.0.0\\nto=1.1.0\\n\")).expect(\"a test file\");\n assert!(recover(&install, &root.0).is_some());\n assert!(dir.join(\"eloxiv-desktop-rune\").is_file(), \"the old build is back at its path\");\n\n // A journal whose process still runs (supervising a trial) is left alone.\n std::fs::create_dir_all(&backup).expect(\"a test directory\");\n std::fs::write(&journal, format!(\"pid={}\\nto=1.1.0\\n\", std::process::id())).expect(\"a test file\");\n assert_eq!(recover(&install, &root.0), None);\n assert!(backup.exists() && journal.exists());\n remove(&backup);\n let _ = std::fs::remove_file(&journal);\n\n // A completed apply leaves no journal behind; nothing to recover.\n let (install, staged) = directory_install(&root.0);\n script(&staged.join(\"eloxiv-desktop-rune\"), \"printf started > \\\"$ELOXIV_UPDATE_TRIAL\\\"\");\n let s =\n Staged { version: v(\"1.2.0\"), current: v(\"1.0.0\"), install: install.clone(), path: staged, recheck: None };\n assert_eq!(apply(&s, &[], &root.0, Duration::from_secs(10)), Ok(Applied::Updated));\n assert!(!journal.exists());\n assert_eq!(recover(&install, &root.0), None);\n }\n\n #[test]\n fn a_staged_build_must_be_the_version_that_was_signed() {\n let root = Dir::new(\"version\");\n let exe = root.0.join(\"app\");\n script(&exe, \"[ \\\"$1\\\" = --print-version ] && echo 1.1.0\");\n assert_eq!(staged_version(&exe, Duration::from_secs(5)), Ok(v(\"1.1.0\")));\n assert_eq!(check_staged_version(&exe, &v(\"1.1.0\")), Ok(()));\n // Its app.json says another version: started, it would be offered the same update again, forever.\n let refused = check_staged_version(&exe, &v(\"1.2.0\")).expect_err(\"refused\");\n assert!(refused.contains(\"signed as 1.2.0 but the build says it is 1.1.0\"), \"{refused}\");\n script(&exe, \"echo not-a-version\");\n assert!(check_staged_version(&exe, &v(\"1.1.0\")).is_err());\n script(&exe, \"exec sleep 30\");\n let started = Instant::now();\n assert!(staged_version(&exe, Duration::from_millis(300)).is_err());\n assert!(started.elapsed() < Duration::from_secs(10), \"one that does not answer is stopped\");\n }\n}\n\n#[cfg(test)]\nmod installer_tests {\n use super::*;\n\n #[test]\n fn an_installer_is_started_directly_each_argument_its_own() {\n let exe = Path::new(r\"C:\\Users\\A User\\AppData\\Local\\Temp\\eloxiv-update-1f\\com.acme.crm-1.2.0-setup.exe\");\n let (program, args) = installer_command(exe);\n assert_eq!(program, exe.as_os_str(), \"the installer itself, no cmd\");\n assert_eq!(args, vec![OsString::from(\"/S\"), OsString::from(\"/R\")]);\n let msi = Path::new(r\"C:\\Users\\A User\\Temp\\x\\setup.MSI\");\n let (program, args) = installer_command(msi);\n assert_eq!(program, OsString::from(\"msiexec\"));\n assert_eq!(args, vec![OsString::from(\"/i\"), msi.as_os_str().to_owned(), OsString::from(\"/passive\")]);\n }\n\n #[test]\n fn an_installer_is_kept_in_a_private_folder_and_verified_again_before_it_runs() {\n let dir = private_dir().expect(\"a private folder\");\n let other = private_dir().expect(\"another\");\n assert_ne!(dir, other, \"named at random\");\n #[cfg(unix)]\n {\n use std::os::unix::fs::PermissionsExt;\n assert_eq!(std::fs::metadata(&dir).expect(\"made\").permissions().mode() & 0o777, 0o700);\n }\n let file = dir.join(\"setup.exe\");\n std::fs::write(&file, b\"the signed installer\").expect(\"a test file\");\n let keys = up::sign::keygen(\"\").expect(\"keys\");\n let comment =\n up::trusted_comment(\"com.acme.crm\", \"stable\", &Version::new(1, 2, 0), \"windows-x86_64\", Kind::Installer);\n let signature = up::sign::sign_file(&keys.secret_file, \"\", &file, &comment).expect(\"signed\");\n let staged = Staged {\n version: Version::new(1, 2, 0),\n current: Version::new(1, 1, 0),\n install: Install::Installer { exe: PathBuf::from(\"app.exe\") },\n path: file.clone(),\n recheck: Some(Recheck { public_key: keys.public_base64.clone(), signature, trusted_comment: comment }),\n };\n assert_eq!(recheck(&staged), Ok(()));\n // Swapped after the download (another process of this user): refused before it runs.\n std::fs::write(&file, b\"something else\").expect(\"a test file\");\n let refused = recheck(&staged).expect_err(\"refused\");\n assert!(refused.contains(\"no longer matches its signature\"), \"{refused}\");\n let applied = apply(&staged, &[], &dir, Duration::from_secs(1));\n assert!(applied.expect_err(\"refused\").contains(\"no longer matches\"), \"never started\");\n let _ = std::fs::remove_dir_all(&dir);\n let _ = std::fs::remove_dir_all(&other);\n }\n}\n",
228
+ "type": "registry:file",
229
+ "target": "desktop-rune/app/src/updates.rs"
230
+ },
231
+ {
232
+ "path": "app/desktop-rune/app/src/view.rs",
233
+ "content": "//! The screens (decision 11: a minimal reference, not a product): sign-in, the organisation switcher, the live\n//! greetings with an optimistic write and a refused one, the agent's chat (a conversation, its transcript with the\n//! streamed text, a composer, consent and approval prompts, the engine not set up), a MAKE view, sign-out; light and\n//! dark; left to right or right to left (`El::dir`, so rows, alignment and padding mirror). Every control has a role\n//! and a name for AccessKit.\n\nuse eloxiv_local_client::{ConnectionState, RowsStatus, WritePhase};\nuse rune::tok::{Theme, type_};\nuse rune::{Color, Cx, Direction, El, LiveRegion, ScrollSpec, TextStyle, col, el, row, spacer, text, text_input};\n\nuse crate::chat::Decision;\nuse crate::make::render::Palette;\nuse crate::make::{self, Phase};\nuse crate::model::Session;\nuse crate::outstanding::SendState;\nuse crate::services::UpdateState;\nuse crate::ui::{Appearance, Screen, Startup, Ui};\n\n/// Everything a component needs to paint itself.\n#[derive(Clone, Copy)]\nstruct Paint {\n t: Theme,\n accent: Color,\n danger: Color,\n}\n\nfn paint(dark: bool) -> Paint {\n Paint { t: rune::tok::theme(dark), accent: rune::tok::accent(0, dark), danger: rune::oklch(0.62, 0.2, 25.0) }\n}\n\n/// A labelled button; `None` for the handler draws it disabled.\nfn button(p: Paint, key: &str, label: &str, primary: bool, on: Option<fn(&mut Ui)>) -> El {\n let ink = if primary { Color::WHITE } else { p.t.text };\n let mut b = row()\n .key(key.to_owned())\n .role(\"button\")\n .label(label.to_owned())\n .px(12.0)\n .h(30.0)\n .center_y()\n .radius(6.0)\n .fill(if primary { p.accent } else { p.t.control_off })\n .child(text(label.to_owned()).font(type_::LABEL).color(ink).a11y_hidden());\n match on {\n Some(f) => {\n b = b.focusable(true).hover(p.t.hover).press(p.t.press).on_press(f);\n }\n None => b = b.disabled(true).opacity(0.5),\n }\n b\n}\n\n/// A labelled toggle chip (theme, direction, organisation, tab): role `radio`, checked when chosen.\nfn choice(p: Paint, key: String, label: String, chosen: bool, on: impl Fn(&mut Ui) + 'static) -> El {\n row()\n .key(key)\n .role(\"radio\")\n .label(label.clone())\n .checked(chosen)\n .focusable(true)\n .px(10.0)\n .h(26.0)\n .center_y()\n .radius(6.0)\n .fill(if chosen { p.accent.alpha(0.22) } else { Color::TRANSPARENT })\n .hover(p.t.hover)\n .on_press(on)\n .child(text(label).font(type_::LABEL).color(p.t.text).a11y_hidden())\n}\n\n/// A labelled button whose handler captures what it acts on; `enabled: false` draws it disabled.\nfn act(p: Paint, key: String, label: &str, primary: bool, enabled: bool, on: impl Fn(&mut Ui) + 'static) -> El {\n let ink = if primary { Color::WHITE } else { p.t.text };\n let b = row()\n .key(key)\n .role(\"button\")\n .label(label.to_owned())\n .px(12.0)\n .h(30.0)\n .center_y()\n .radius(6.0)\n .fill(if primary { p.accent } else { p.t.control_off })\n .child(text(label.to_owned()).font(type_::LABEL).color(ink).a11y_hidden());\n if enabled {\n b.focusable(true).hover(p.t.hover).press(p.t.press).on_press(on)\n } else {\n b.disabled(true).opacity(0.5)\n }\n}\n\nfn heading(p: Paint, key: &str, label: &str, size: f32) -> El {\n text(label.to_owned())\n .key(key.to_owned())\n .role(\"heading\")\n .level(if size > 18.0 { 1 } else { 2 })\n .font(TextStyle::new(size, 650.0))\n .color(p.t.text)\n}\n\nfn note(p: Paint, key: &str, s: String) -> El {\n text(s).key(key.to_owned()).font(type_::BODY).color(p.t.text_secondary).wrap()\n}\n\npub fn view(s: &Ui, cx: &mut Cx<Ui>) -> El {\n let dark = s.dark(cx.system_dark());\n let p = paint(dark);\n let mut body = col().key(\"body\").grow(1.0).min_h(0.0).padding(20.0).gap(14.0);\n body = match &s.startup {\n Startup::Starting => body.child(note(p, \"status\", \"Starting the daemon…\".into()).role(\"status\")),\n Startup::Failed(why) => body\n .child(heading(p, \"title\", \"The daemon did not start\", 20.0))\n .child(note(p, \"status\", why.clone()).role(\"alert\")),\n Startup::Ready => match &s.model.session {\n Session::Unknown => body.child(note(p, \"status\", \"Connecting…\".into()).role(\"status\")),\n Session::SignedOut | Session::SigningIn => body.child(sign_in(s, p)),\n Session::SigningOut => body.child(note(p, \"status\", \"Signing out…\".into()).role(\"status\")),\n Session::SignedIn { .. } => body.child(signed_in(s, p, dark)),\n },\n };\n if let Some(n) = &s.notice {\n body = body.child(\n text(n.clone())\n .key(\"notice\")\n .role(\"alert\")\n .live_region(LiveRegion::Assertive)\n .font(type_::BODY)\n .color(p.danger)\n .wrap(),\n );\n }\n if s.startup == Startup::Ready {\n body = body.child(host_row(s, p));\n }\n col()\n .key(\"window\")\n .role(\"window\")\n .dir(s.direction)\n .w_full()\n .h_full()\n .fill(p.t.bg)\n .child(header(s, p))\n .child(body.scroll(ScrollSpec { stick_bottom: false }))\n}\n\nfn header(s: &Ui, p: Paint) -> El {\n let connection = match s.model.connection {\n // An offline start: the kernel was not reached, so what shows is this device's copy (whatever the replica says).\n _ if s.model.offline => \"Offline: showing this device's copy\",\n Some(ConnectionState::Connected) => \"Synced\",\n Some(ConnectionState::Connecting) => \"Connecting\",\n Some(ConnectionState::Disconnected) => \"Offline\",\n Some(ConnectionState::NeedsAuth) => \"Signed out by the server\",\n None if s.stream_open => \"Ready\",\n None => \"Not connected\",\n };\n let mut r = row()\n .key(\"header\")\n .role(\"toolbar\")\n .label(\"Eloxiv\")\n .h(48.0)\n .px(16.0)\n .gap(8.0)\n .center_y()\n .fill(p.t.card)\n .child(heading(p, \"app-title\", \"Eloxiv\", 15.0))\n .child(text(connection).key(\"connection\").role(\"status\").font(type_::LABEL).color(p.t.text_secondary))\n .child(spacer());\n for (a, key, label) in [\n (Appearance::System, \"theme-system\", \"System\"),\n (Appearance::Light, \"theme-light\", \"Light\"),\n (Appearance::Dark, \"theme-dark\", \"Dark\"),\n ] {\n r = r.child(choice(p, key.into(), label.into(), s.appearance == a, move |s: &mut Ui| s.appearance = a));\n }\n let rtl = s.direction == Direction::Rtl;\n r.child(\n row()\n .key(\"dir-rtl\")\n .role(\"switch\")\n .label(\"Right to left\")\n .checked(rtl)\n .focusable(true)\n .px(10.0)\n .h(26.0)\n .center_y()\n .radius(6.0)\n .fill(if rtl { p.accent.alpha(0.22) } else { Color::TRANSPARENT })\n .on_press(|s: &mut Ui| {\n s.direction = if s.direction == Direction::Rtl { Direction::Ltr } else { Direction::Rtl }\n })\n .child(text(\"RTL\").font(type_::LABEL).color(p.t.text).a11y_hidden()),\n )\n}\n\nfn sign_in(s: &Ui, p: Paint) -> El {\n let waiting = matches!(s.model.session, Session::SigningIn) || s.sign_in_url.is_some();\n let mut c = col()\n .key(\"sign-in-screen\")\n .gap(10.0)\n .child(heading(p, \"title\", \"Sign in\", 22.0))\n .child(note(p, \"sign-in-help\", \"Sign in opens your browser; this app never sees your password.\".into()))\n .child(button(\n p,\n \"sign-in\",\n if waiting { \"Open the browser again\" } else { \"Sign in with the browser\" },\n true,\n if s.busy == Some(\"sign-in\") { None } else { Some(Ui::sign_in) },\n ));\n if waiting {\n c = c.child(note(p, \"sign-in-waiting\", \"Waiting for the browser to finish signing in…\".into()).role(\"status\"));\n }\n // A deep link waits for a session: say so, without the link itself (it may name a record).\n if s.host.pending_link.is_some() {\n c = c.child(note(p, \"link-waiting\", \"A link is waiting: sign in to open it.\".into()).role(\"status\"));\n }\n c\n}\n\nfn signed_in(s: &Ui, p: Paint, dark: bool) -> El {\n let Session::SignedIn { user, organizations, org_id } = &s.model.session else { return el() };\n let mut orgs = row().key(\"orgs\").role(\"radiogroup\").label(\"Organisation\").gap(4.0).center_y();\n for o in organizations {\n let id = o.org_id.clone();\n let chosen = org_id.as_deref() == Some(id.as_str());\n orgs = orgs.child(choice(p, format!(\"org-{id}\"), o.name.clone(), chosen, move |s: &mut Ui| s.select_org(&id)));\n }\n let account = row()\n .key(\"account\")\n .gap(10.0)\n .center_y()\n .child(text(format!(\"{} ({})\", user.name, user.email)).key(\"user\").font(type_::BODY).color(p.t.text))\n .child(spacer())\n .child(button(\n p,\n \"sign-out\",\n \"Sign out\",\n false,\n if s.busy == Some(\"sign-out\") { None } else { Some(Ui::sign_out) },\n ));\n let mut tabs = row().key(\"tabs\").role(\"tablist\").label(\"Screens\").gap(4.0).child(choice(\n p,\n \"tab-greetings\".into(),\n \"Greetings\".into(),\n s.screen == Screen::Greetings,\n |s: &mut Ui| s.screen = Screen::Greetings,\n ));\n if s.model.chat_enabled {\n tabs = tabs.child(choice(p, \"tab-chat\".into(), \"Agent\".into(), s.screen == Screen::Chat, |s: &mut Ui| {\n s.screen = Screen::Chat\n }));\n }\n let tabs = tabs.child(choice(p, \"tab-make\".into(), \"MAKE view\".into(), s.screen == Screen::Make, |s: &mut Ui| {\n s.screen = Screen::Make\n }));\n let mut c = col().key(\"signed-in\").gap(12.0).child(account).child(orgs).child(tabs);\n if org_id.is_none() {\n return c.child(note(p, \"choose-org\", \"Choose an organisation.\".into()));\n }\n c = match s.screen {\n Screen::Greetings => c.child(greetings(s, p)),\n Screen::Chat if s.model.chat_enabled => c.child(chat_screen(s, p)),\n Screen::Chat => c.child(greetings(s, p)),\n Screen::Make => c.child(make_screen(s, p, dark)),\n };\n c\n}\n\nfn greetings(s: &Ui, p: Paint) -> El {\n let field = text_input(&s.greeting, type_::BODY)\n .key(\"greeting-input\")\n .label(\"Greeting\")\n .single_line()\n .placeholder(\"Say hello\", p.t.text_secondary)\n .color(p.t.text)\n .px(8.0)\n .py(6.0)\n .radius(6.0)\n .border(1.0, p.t.text_secondary.alpha(0.5))\n .grow(1.0)\n .on_edit(|s: &mut Ui| &mut s.greeting)\n .on_submit(|s: &mut Ui, _| post(s));\n let form = row()\n .key(\"greet-form\")\n .role(\"form\")\n .label(\"New greeting\")\n .gap(8.0)\n .center_y()\n .child(field)\n .child(button(p, \"greet\", \"Post\", true, Some(post)))\n .child(button(p, \"farewell\", \"Post a farewell\", false, Some(|s: &mut Ui| s.greet(\"goodbye, everyone\".into()))));\n let status = match s.model.list.status {\n Some(RowsStatus::Complete) => \"Up to date\",\n Some(RowsStatus::Cached) => \"From the last session\",\n Some(RowsStatus::Unknown) => \"Loading…\",\n Some(RowsStatus::Error) => \"The list failed\",\n None => \"Loading…\",\n };\n let mut list = col().key(\"greetings\").role(\"list\").label(\"Greetings\").gap(4.0);\n for (id, message) in s.model.greeting_texts() {\n // The greeting a link (a notification's click) opened.\n let selected = s.focused_record.as_deref() == Some(id.as_str());\n list = list.child(\n row()\n .key(format!(\"greeting-{id}\"))\n .role(\"listitem\")\n .label(message.clone())\n .focus_selected(selected)\n .px(10.0)\n .py(6.0)\n .radius(6.0)\n .fill(if selected { p.t.hover } else { p.t.card })\n .child(text(message).dir(Direction::Auto).font(type_::BODY).color(p.t.text).wrap().a11y_hidden()),\n );\n }\n let mut writes = col().key(\"writes\").role(\"list\").label(\"Your writes\").gap(2.0);\n for w in s.model.writes.iter().rev().take(6) {\n let (label, colour) = match (&w.phase, &w.error) {\n (Some(WritePhase::Rejected), Some((tag, _))) => (format!(\"Refused: {}\", refusal_words(tag)), p.danger),\n (Some(WritePhase::Rejected), None) => (\"Refused\".into(), p.danger),\n (Some(WritePhase::Confirmed), _) => (\"Confirmed\".into(), p.t.text_secondary),\n (Some(WritePhase::Predicted), _) => (\"Shown, waiting for the server\".into(), p.t.text_secondary),\n (Some(WritePhase::NotConfirmed), _) => (\"Not confirmed yet (offline)\".into(), p.t.text_secondary),\n (None, _) => (\"Sending…\".into(), p.t.text_secondary),\n };\n writes = writes.child(\n row()\n .key(format!(\"write-{}\", w.id))\n .role(\"listitem\")\n .label(format!(\"{}: {label}\", w.message))\n .gap(8.0)\n .child(text(w.message.clone()).font(type_::LABEL).color(p.t.text).a11y_hidden())\n .child(text(label).font(type_::LABEL).color(colour).a11y_hidden()),\n );\n }\n let mut c = col()\n .key(\"greetings-screen\")\n .gap(10.0)\n .child(heading(p, \"title\", \"Greetings\", 20.0))\n .child(form)\n .child(text(status).key(\"list-status\").role(\"status\").font(type_::LABEL).color(p.t.text_secondary))\n .child(list);\n if let Some(e) = &s.model.list.error {\n c = c.child(text(e.clone()).key(\"list-error\").role(\"alert\").font(type_::BODY).color(p.danger).wrap());\n }\n if !s.model.writes.is_empty() {\n c = c.child(heading(p, \"writes-title\", \"Your writes\", 15.0)).child(writes);\n }\n c\n}\n\n/// A prompt card (a consent or an approval): what waits, and the person's two answers.\nfn prompt_card(p: Paint, key: String, words: String, busy: bool, approve: El, reject: El) -> El {\n col()\n .key(key)\n .role(\"group\")\n .label(words.clone())\n .gap(8.0)\n .padding(12.0)\n .radius(8.0)\n .fill(p.accent.alpha(0.12))\n .border(1.0, p.accent.alpha(0.5))\n .child(text(words).font(type_::BODY).color(p.t.text).wrap().a11y_hidden())\n .child(row().gap(8.0).child(approve).child(reject).child(if busy {\n text(\"Sending your decision…\").font(type_::LABEL).color(p.t.text_secondary).role(\"status\")\n } else {\n el()\n }))\n}\n\nfn chat_screen(s: &Ui, p: Paint) -> El {\n let chat = &s.model.chat;\n let user_id = match &s.model.session {\n Session::SignedIn { user, .. } => user.id.clone(),\n _ => String::new(),\n };\n let mut c = col().key(\"chat-screen\").gap(10.0).child(heading(p, \"title\", \"Agent\", 20.0));\n if chat.engine_blocked() {\n let detail = chat.engine.as_ref().map(|e| e.detail.clone()).unwrap_or_default();\n c = c.child(\n col()\n .key(\"chat-engine\")\n .role(\"alert\")\n .label(format!(\"The agent is not set up: {detail}\"))\n .gap(4.0)\n .padding(12.0)\n .radius(8.0)\n .fill(p.t.card)\n .child(text(\"The agent is not set up\").font(TextStyle::new(15.0, 650.0)).color(p.t.text).a11y_hidden())\n .child(\n text(format!(\"{detail}. You can still write a message; it is sent once a model is set up.\"))\n .font(type_::BODY)\n .color(p.t.text_secondary)\n .wrap()\n .a11y_hidden(),\n ),\n );\n }\n let title = chat.title().unwrap_or_else(|| \"New conversation\".to_owned());\n c = c.child(\n row()\n .key(\"chat-conversation\")\n .gap(8.0)\n .center_y()\n .child(heading(p, \"chat-title\", &title, 15.0))\n .child(spacer())\n .child(act(\n p,\n \"chat-new\".into(),\n \"New conversation\",\n false,\n chat.conversation_id.is_some(),\n |s: &mut Ui| s.new_conversation(),\n )),\n );\n let entries = chat.transcript();\n let mut list = col().key(\"chat-transcript\").role(\"list\").label(\"Transcript\").gap(6.0);\n for e in &entries {\n let who = match e.role.as_str() {\n \"user\" => \"You\",\n \"assistant\" => \"Agent\",\n other => other,\n };\n let mine = e.role == \"user\";\n list = list.child(\n col()\n .key(if e.live { format!(\"chat-live-{}\", e.id) } else { format!(\"chat-msg-{}\", e.id) })\n .role(\"listitem\")\n .label(format!(\"{who}: {}\", e.text))\n .gap(2.0)\n .px(10.0)\n .py(6.0)\n .radius(8.0)\n .fill(if mine { p.accent.alpha(0.15) } else { p.t.card })\n .child(text(who.to_owned()).font(type_::LABEL).color(p.t.text_secondary).a11y_hidden())\n .child(\n text(e.text.clone()).dir(Direction::Auto).font(type_::BODY).color(p.t.text).wrap().a11y_hidden(),\n ),\n );\n }\n c = c.child(list);\n if entries.is_empty() {\n let words =\n if chat.conversations.is_none() { \"Loading the conversation…\" } else { \"Ask your agent something.\" };\n c = c.child(note(p, \"chat-empty\", words.into()).role(\"status\"));\n }\n for consent in &chat.consents {\n let id = consent.consent_id.clone();\n let busy = chat.deciding.contains(&id);\n let (a, r) = (id.clone(), id.clone());\n c = c.child(prompt_card(\n p,\n format!(\"consent-{id}\"),\n format!(\"Your agent wants to: {}\", consent.title),\n busy,\n act(p, format!(\"consent-approve-{id}\"), \"Approve\", true, !busy, move |s: &mut Ui| {\n s.decide_consent(&a, Decision::Approve)\n }),\n act(p, format!(\"consent-reject-{id}\"), \"Reject\", false, !busy, move |s: &mut Ui| {\n s.decide_consent(&r, Decision::Reject)\n }),\n ));\n }\n for approval in chat.approvals_to_decide(&user_id) {\n let id = approval.id.clone();\n let busy = chat.deciding.contains(&id);\n let (a, r) = (id.clone(), id.clone());\n c = c.child(prompt_card(\n p,\n format!(\"approval-{id}\"),\n format!(\"Approval needed: {}\", approval.title),\n busy,\n act(p, format!(\"approval-approve-{id}\"), \"Approve\", true, !busy, move |s: &mut Ui| {\n s.decide_approval(&a, Decision::Approve)\n }),\n act(p, format!(\"approval-reject-{id}\"), \"Reject\", false, !busy, move |s: &mut Ui| {\n s.decide_approval(&r, Decision::Reject)\n }),\n ));\n }\n if chat.active_run().is_some() || chat.sending.is_some() {\n let words = if !chat.consents.is_empty() {\n \"Waiting for your decision\"\n } else if chat.sending.is_some() {\n \"Sending…\"\n } else {\n \"The agent is working…\"\n };\n c = c.child(\n text(words)\n .key(\"chat-working\")\n .role(\"status\")\n .live_region(LiveRegion::Polite)\n .font(type_::LABEL)\n .color(p.t.text_secondary),\n );\n }\n if let Some(unresolved) = chat.unresolved_here() {\n let unconfirmed = chat.outstanding_send(&unresolved.key).is_some_and(|s| s.state == SendState::Unconfirmed);\n if unconfirmed {\n // It may have run: kept under its key until an answer settles it, or the person lets it go.\n let key = unresolved.key.clone();\n c = c.child(\n row()\n .key(\"chat-unconfirmed\")\n .gap(8.0)\n .center_y()\n .child(\n note(\n p,\n \"chat-unresolved\",\n format!(\n \"Couldn't confirm whether “{}” was sent. Select Send to retry without sending a duplicate.\",\n unresolved.text\n ),\n )\n .grow(1.0),\n )\n .child(act(p, \"chat-discard\".into(), \"Discard\", false, true, move |s: &mut Ui| {\n s.discard_send(&key)\n })),\n );\n } else {\n c = c.child(note(\n p,\n \"chat-unresolved\",\n format!(\n \"Your message “{}” may not have reached the agent: Send tries it again, once.\",\n unresolved.text\n ),\n ));\n }\n }\n if let Some((tag, message)) = &chat.error {\n let words = if message.is_empty() { tag.clone() } else { format!(\"{tag}: {message}\") };\n c = c.child(text(words).key(\"chat-error\").role(\"alert\").font(type_::BODY).color(p.danger).wrap());\n }\n let field = text_input(&s.chat_input, type_::BODY)\n .key(\"chat-input\")\n .label(\"Message\")\n .single_line()\n .placeholder(\"Ask the agent\", p.t.text_secondary)\n .color(p.t.text)\n .px(8.0)\n .py(6.0)\n .radius(6.0)\n .border(1.0, p.t.text_secondary.alpha(0.5))\n .grow(1.0)\n .on_edit(|s: &mut Ui| &mut s.chat_input)\n .on_submit(|s: &mut Ui, _| s.send_message());\n let can_send = chat.can_send(&s.chat_input.text);\n c.child(row().key(\"chat-composer\").role(\"form\").label(\"New message\").gap(8.0).center_y().child(field).child(act(\n p,\n \"chat-send\".into(),\n \"Send\",\n true,\n can_send,\n |s: &mut Ui| s.send_message(),\n )))\n}\n\nfn post(s: &mut Ui) {\n let message = std::mem::take(&mut s.greeting.text);\n s.greeting = rune::TextEdit::new(\"\");\n s.greet(message);\n}\n\nfn make_lens(s: &mut Ui) -> &mut make::Host {\n &mut s.make\n}\n\nfn make_screen(s: &Ui, p: Paint, dark: bool) -> El {\n let field = text_input(&s.make.module_input, type_::BODY)\n .key(\"make-module\")\n .label(\"Module\")\n .single_line()\n .placeholder(\"mk_<module>\", p.t.text_secondary)\n .color(p.t.text)\n .px(8.0)\n .py(6.0)\n .radius(6.0)\n .border(1.0, p.t.text_secondary.alpha(0.5))\n .grow(1.0)\n .on_edit(|s: &mut Ui| &mut s.make.module_input)\n .on_submit(|s: &mut Ui, _| open_make(s));\n let mut c = col().key(\"make-screen\").gap(10.0).child(heading(p, \"title\", \"MAKE view\", 20.0)).child(\n row().key(\"make-open-form\").role(\"form\").label(\"Open a view\").gap(8.0).center_y().child(field).child(button(\n p,\n \"make-open\",\n \"Open\",\n true,\n Some(open_make),\n )),\n );\n c = match &s.make.phase {\n Phase::Closed => c.child(note(p, \"make-status\", \"Name a MAKE module to open its view.\".into())),\n Phase::Loading { module } => c.child(note(p, \"make-status\", format!(\"Opening {module}…\")).role(\"status\")),\n Phase::Failed { module, message } => c.child(\n text(format!(\"{module}: {message}\"))\n .key(\"make-status\")\n .role(\"alert\")\n .font(type_::BODY)\n .color(p.danger)\n .wrap(),\n ),\n Phase::Shown => match &s.make.view {\n Some(v) => c\n .child(heading(p, \"make-title\", &v.title, 16.0))\n .child(make::render::view(v, make_lens, Palette::new(dark), s.direction).fill(p.t.card).radius(8.0)),\n None => c,\n },\n };\n c\n}\n\nfn open_make(s: &mut Ui) {\n let module = s.make.module_input.text.clone();\n s.make.open(&module);\n}\n\n/// A button's key, label and handler.\ntype Action = (&'static str, &'static str, fn(&mut Ui));\n\n/// The host's own row: this build's version and its updates, a restart's outcome, what the last deep link opened.\nfn host_row(s: &Ui, p: Paint) -> El {\n let version = s.host.config.version.to_string();\n let (status, action): (String, Option<Action>) = match &s.host.update {\n UpdateState::Unsupported(why) => (format!(\"Version {version}. Updates: not available here ({why})\"), None),\n UpdateState::Idle => (format!(\"Version {version}\"), Some((\"update-check\", \"Check for updates\", check_update))),\n UpdateState::Checking => (format!(\"Version {version}. Checking for updates…\"), None),\n UpdateState::UpToDate => {\n (format!(\"Version {version} is up to date\"), Some((\"update-check\", \"Check again\", check_update)))\n }\n UpdateState::Available(offer) => (\n format!(\"Version {} is available (you have {version})\", offer.version),\n Some((\"update-download\", \"Download the update\", download_update)),\n ),\n UpdateState::Downloading { version: v, got, total } => {\n (format!(\"Downloading {v}: {}%\", if *total == 0 { 0 } else { got * 100 / total }), None)\n }\n UpdateState::Ready(staged) => (\n format!(\"Version {} is downloaded and verified\", staged.version),\n Some((\"update-restart\", \"Restart to update\", restart_to_update)),\n ),\n UpdateState::Failed(why) => {\n (format!(\"The update failed: {why}\"), Some((\"update-check\", \"Check again\", check_update)))\n }\n };\n let mut r =\n row().key(\"host-row\").role(\"group\").label(\"Updates\").gap(10.0).center_y().child(\n text(status).key(\"update-status\").role(\"status\").font(type_::LABEL).color(p.t.text_secondary).wrap(),\n );\n if let Some((key, label, on)) = action {\n r = r.child(button(p, key, label, false, Some(on)));\n }\n let mut c = col().key(\"host\").gap(6.0).child(r);\n if let Some(n) = &s.host.update_notice {\n c = c.child(text(n.clone()).key(\"update-notice\").role(\"status\").font(type_::LABEL).color(p.t.text).wrap());\n }\n if let Some(l) = &s.host.link_status {\n c = c.child(text(l.clone()).key(\"link-status\").role(\"status\").font(type_::LABEL).color(p.t.text_secondary));\n }\n c\n}\n\nfn check_update(s: &mut Ui) {\n s.host.check_update();\n}\n\nfn download_update(s: &mut Ui) {\n s.host.download_update();\n}\n\nfn restart_to_update(s: &mut Ui) {\n s.host.restart_to_update();\n}\n\n/// Why a write was refused, in words for people: the kernel's error tag mapped, never its raw message.\npub fn refusal_words(tag: &str) -> &'static str {\n match tag {\n \"Forbidden\" => \"You don't have permission to post this.\",\n _ => \"Something went wrong. Try again.\",\n }\n}\n",
234
+ "type": "registry:file",
235
+ "target": "desktop-rune/app/src/view.rs"
236
+ },
237
+ {
238
+ "path": "app/desktop-rune/app/tests/chat.rs",
239
+ "content": "//! The chat screen against the fake `/client/v1` (tests/support, LocalClient 1.1.0): the conversation and its\n//! messages from named queries, a send as `agent.send` under its key, the run followed through a run subscription\n//! (streamed text by step, replaced by the stored answer; a consent prompt the person decides under the decision's\n//! key), approval prompts, the engine not set up, a lost send resent under its key, and nothing of the conversation\n//! after an organisation switch.\n\nmod support;\n\nuse eloxiv_desktop_rune::model::Session;\nuse eloxiv_desktop_rune::ui::Screen;\nuse serde_json::{Value, json};\nuse support::*;\n\ntype Rt = rune::Runtime<eloxiv_desktop_rune::Ui>;\n\n/// Signed in, on the chat screen, its queries loaded and the engine known.\nfn on_chat(fake: &Fake) -> Rt {\n let mut rt = signed_in(fake);\n assert!(rt.state.model.chat_enabled, \"hello names the chat's queries and run events\");\n press(&mut rt, \"tab-chat\");\n assert_eq!(rt.state.screen, Screen::Chat);\n until(&mut rt, \"the conversation loaded\", |s| {\n s.model.chat.conversations.is_some() && s.model.chat.engine.is_some()\n });\n rt\n}\n\nfn transcript(rt: &Rt) -> Vec<(String, bool)> {\n rt.state.model.chat.transcript().into_iter().map(|e| (e.text, e.live)).collect()\n}\n\nfn name(rt: &Rt, key: &str) -> String {\n a11y(rt, key).and_then(|n| n[\"name\"].as_str().map(str::to_owned)).unwrap_or_default()\n}\n\n#[test]\nfn an_agent_turn_streams_asks_consent_and_shows_the_stored_answer() {\n let fake = Fake::start();\n let mut rt = on_chat(&fake);\n assert!(rt.find(\"chat-empty\").is_some(), \"a new conversation: nothing yet\");\n assert!(has_state(&rt, \"chat-send\", \"disabled\"), \"nothing to send\");\n type_into(&mut rt, \"chat-input\", \"Please file my notes.\");\n assert!(!has_state(&rt, \"chat-send\", \"disabled\"));\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the run followed\", |s| s.model.chat.followed.is_some());\n assert_eq!(rt.state.chat_input.text, \"\", \"the draft went with the send\");\n let (key, text) = fake.with(|s| s.agent.sends[0].clone());\n assert_eq!(text, \"Please file my notes.\");\n assert_eq!(key.len(), 36, \"a send carries its own key (a UUID): {key}\");\n let run = fake.with(|s| s.agent.runs[0][\"id\"].as_str().map(str::to_owned)).expect(\"a run\");\n // The fake records a request on its own thread: wait for it rather than read it the frame the model changed.\n until(&mut rt, \"the run's follow request\", |_| fake.requests_to(\"/client/v1/runs\").len() == 1);\n let follow = fake.requests_to(\"/client/v1/runs\");\n assert_eq!(follow.len(), 1);\n assert_eq!((follow[0].body[\"runId\"].as_str(), follow[0].body[\"after\"].as_i64()), (Some(run.as_str()), Some(-1)));\n until(&mut rt, \"the person's message\", |s| s.model.chat.transcript().len() == 1);\n assert!(has_state(&rt, \"chat-send\", \"disabled\"), \"the run holds the composer\");\n assert!(rt.find(\"chat-working\").is_some());\n\n // The model asks for a consent-marked call: the prompt shows; the person allows it under the decision's key.\n fake.with(|s| {\n s.run_event(&run, 0, \"run-started\", json!({}));\n s.run_event(&run, 1, \"model-step\", json!({ \"step\": 0, \"text\": \"\" }));\n s.run_event(\n &run,\n 2,\n \"consent-required\",\n json!({ \"consentId\": \"k1\", \"action\": \"agent.moveResources\", \"title\": \"Move agent resources\", \"step\": 0 }),\n );\n });\n until(&mut rt, \"the consent prompt\", |s| s.model.chat.consents.len() == 1);\n // Named as people see the action (the title the kernel recorded when it held the call), never by its id.\n assert_eq!(name(&rt, \"consent-k1\"), \"Your agent wants to: Move agent resources\");\n assert_eq!(name(&rt, \"consent-approve-k1\"), \"Approve\");\n press(&mut rt, \"consent-approve-k1\");\n until(&mut rt, \"the decision\", |s| s.model.chat.deciding.is_empty());\n assert_eq!(\n fake.with(|s| s.agent.decisions.clone()),\n vec![(\"consent.approve\".to_owned(), \"k1\".to_owned(), \"consent:k1:approve:\".to_owned())]\n );\n fake.with(|s| s.run_event(&run, 3, \"consent-decided\", json!({ \"consentId\": \"k1\", \"status\": \"approved\" })));\n until(&mut rt, \"the prompt gone\", |s| s.model.chat.consents.is_empty());\n\n // Streamed text shows as it comes, then the stored answer replaces it (never twice).\n fake.with(|s| {\n s.run_event(&run, -1, \"text-delta\", json!({ \"delta\": \"Your notes \", \"step\": 1, \"attempt\": \"a1\" }));\n s.run_event(&run, -1, \"text-delta\", json!({ \"delta\": \"are \", \"step\": 1, \"attempt\": \"a1\" }));\n });\n until(&mut rt, \"the streamed text\", |s| s.model.chat.transcript().iter().any(|e| e.live));\n assert_eq!(transcript(&rt).last(), Some(&(\"Your notes are \".to_owned(), true)));\n assert!(rt.find(&format!(\"chat-live-live-{run}-1\")).is_some(), \"the streamed line is drawn\");\n fake.with(|s| s.finish_run(&run, 1, &[\"filed.\"], \"Your notes are filed.\", 4));\n until(&mut rt, \"the stored answer\", |s| {\n s.model.chat.transcript().iter().any(|e| e.text == \"Your notes are filed.\" && !e.live)\n });\n assert_eq!(\n transcript(&rt),\n vec![(\"Please file my notes.\".to_owned(), false), (\"Your notes are filed.\".to_owned(), false)]\n );\n assert_eq!(rt.state.model.chat.deltas, 3);\n assert!(rt.state.model.chat.followed.is_none() && rt.state.model.chat.active_run().is_none());\n assert_eq!(name(&rt, \"chat-title\"), \"Please file my notes.\", \"the conversation's title\");\n type_into(&mut rt, \"chat-input\", \"Thanks\");\n assert!(!has_state(&rt, \"chat-send\", \"disabled\"), \"the run ended: the composer sends again\");\n let urls = rt.take_url_requests();\n assert!(urls.is_empty(), \"no URL opened: {urls:?}\");\n}\n\n#[test]\nfn the_engine_not_set_up_shows_why_and_holds_the_send_but_not_the_draft() {\n let fake = Fake::start();\n fake.with(|s| {\n s.agent.engine = json!({ \"state\": \"missing\", \"provider\": null, \"model\": null,\n \"detail\": \"No model is chosen for this organisation\" })\n });\n let mut rt = on_chat(&fake);\n let engine = a11y(&rt, \"chat-engine\").expect(\"the engine's state is shown\");\n assert_eq!(engine[\"role\"].as_str(), Some(\"alert\"));\n assert_eq!(name(&rt, \"chat-engine\"), \"The agent is not set up: No model is chosen for this organisation\");\n type_into(&mut rt, \"chat-input\", \"hello?\");\n assert_eq!(rt.state.chat_input.text, \"hello?\", \"drafting never waits for the engine\");\n assert!(has_state(&rt, \"chat-send\", \"disabled\"));\n press_if_enabled(&mut rt, \"chat-send\");\n settle(&mut rt, 100);\n assert!(fake.with(|s| s.agent.sends.is_empty()), \"nothing was sent\");\n}\n\n#[test]\nfn the_composer_sends_once_a_model_is_set_up_meanwhile_keeping_the_draft() {\n let fake = Fake::start();\n fake.with(|s| {\n s.agent.engine = json!({ \"state\": \"missing\", \"provider\": null, \"model\": null,\n \"detail\": \"No model is chosen for this organisation\" })\n });\n let mut rt = on_chat(&fake);\n type_into(&mut rt, \"chat-input\", \"Once you can answer\");\n assert!(has_state(&rt, \"chat-send\", \"disabled\"));\n // The model is set up elsewhere (the web shell) while the host stays open.\n fake.with(|s| {\n s.agent.engine =\n json!({ \"state\": \"configured\", \"provider\": \"openai\", \"model\": \"gpt-5-mini\", \"detail\": \"set up\" })\n });\n until(&mut rt, \"the agent ready\", |s| !s.model.chat.engine_blocked());\n assert!(rt.find(\"chat-engine\").is_none());\n assert_eq!(rt.state.chat_input.text, \"Once you can answer\", \"the draft is kept\");\n assert!(!has_state(&rt, \"chat-send\", \"disabled\"), \"Send is enabled\");\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"sent\", |_| fake.with(|s| s.agent.sends.len() == 1));\n // Ready: nothing asks again.\n let asked = fake.requests_to(\"/client/v1/agent/readiness\").len();\n settle(&mut rt, 200);\n assert_eq!(fake.requests_to(\"/client/v1/agent/readiness\").len(), asked);\n}\n\n#[test]\nfn approval_prompts_are_decided_as_the_person_under_their_keys() {\n let fake = Fake::start();\n fake.with(|s| {\n s.agent.approvals = vec![\n json!({ \"id\": \"a1\", \"requesterId\": \"u-ben\", \"action\": \"people.offboard\", \"title\": \"Offboard a person\", \"status\": \"pending\", \"createdAt\": 1 }),\n json!({ \"id\": \"a2\", \"requesterId\": \"u-alice\", \"action\": \"people.hire\", \"status\": \"pending\", \"createdAt\": 2 }),\n ]\n });\n let mut rt = on_chat(&fake);\n until(&mut rt, \"the approval prompt\", |s| !s.model.chat.approvals.is_empty());\n assert_eq!(name(&rt, \"approval-a1\"), \"Approval needed: Offboard a person\");\n assert!(rt.find(\"approval-a2\").is_none(), \"the person's own request is not theirs to decide\");\n press(&mut rt, \"approval-reject-a1\");\n until(&mut rt, \"the prompt gone\", |s| s.model.chat.approvals_to_decide(\"u-alice\").is_empty());\n assert_eq!(\n fake.with(|s| s.agent.decisions.clone()),\n vec![(\"approvals.reject\".to_owned(), \"a1\".to_owned(), \"approval:a1:reject\".to_owned())]\n );\n}\n\n#[test]\nfn a_make_action_s_decision_is_named_from_its_id_never_a_stored_title() {\n let fake = Fake::start();\n fake.with(|s| {\n // A row held before (or the module's own words): the label still comes from the action's id.\n s.agent.approvals = vec![\n json!({ \"id\": \"a3\", \"requesterId\": \"u-ben\", \"action\": \"mk_pay.send\", \"title\": \"Tidy up your list\", \"status\": \"pending\", \"createdAt\": 1 }),\n ]\n });\n let mut rt = on_chat(&fake);\n until(&mut rt, \"the approval prompt\", |s| !s.model.chat.approvals.is_empty());\n assert_eq!(name(&rt, \"approval-a3\"), \"Approval needed: mk_pay: Send\");\n type_into(&mut rt, \"chat-input\", \"Pay them.\");\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the run followed\", |s| s.model.chat.followed.is_some());\n let run = fake.with(|s| s.agent.runs[0][\"id\"].as_str().map(str::to_owned)).expect(\"a run\");\n fake.with(|s| {\n s.run_event(&run, 0, \"run-started\", json!({}));\n s.run_event(\n &run,\n 1,\n \"consent-required\",\n json!({ \"consentId\": \"k7\", \"action\": \"mk_pay.send\", \"title\": \"Tidy up your list\", \"step\": 0 }),\n );\n });\n until(&mut rt, \"the consent prompt\", |s| s.model.chat.consents.len() == 1);\n assert_eq!(name(&rt, \"consent-k7\"), \"Your agent wants to: mk_pay: Send\");\n}\n\n#[test]\nfn a_send_whose_answer_was_lost_is_resent_under_its_key() {\n let fake = Fake::start();\n fake.with(|s| s.agent.lose_next_send = true);\n let mut rt = on_chat(&fake);\n type_into(&mut rt, \"chat-input\", \"Did this arrive?\");\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the lost answer\", |s| s.model.chat.unresolved_here().is_some());\n assert!(rt.find(\"chat-unresolved\").is_some(), \"the person is told it may not have arrived\");\n assert_eq!(rt.state.chat_input.text, \"Did this arrive?\", \"the draft is kept\");\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the resend answered\", |s| {\n s.model.chat.unresolved_here().is_none() && s.model.chat.sending.is_none()\n });\n let sends = fake.with(|s| s.agent.sends.clone());\n assert_eq!(sends.len(), 2);\n assert_eq!(sends[0], sends[1], \"the same send, under the same key: a replay, never a second run\");\n}\n\n/// Whether the chat shows a send to be resent, and its words.\nfn unresolved_shown(rt: &Rt) -> Option<String> {\n rt.find(\"chat-unresolved\").map(|_| name(rt, \"chat-unresolved\"))\n}\n\n#[test]\nfn a_send_whose_answer_was_lost_is_resent_under_its_key_after_an_organisation_switch_and_back() {\n let fake = Fake::start();\n fake.with(|s| s.agent.lose_next_send = true);\n let mut rt = on_chat(&fake);\n type_into(&mut rt, \"chat-input\", \"Did this arrive in acme?\");\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the lost answer\", |s| s.model.chat.unresolved_here().is_some());\n press(&mut rt, \"org-globex\");\n until(&mut rt, \"globex's chat\", |s| {\n s.model.session.org_id() == Some(\"globex\") && s.model.chat.conversations.is_some()\n });\n assert_eq!(unresolved_shown(&rt), None, \"acme's send is not globex's\");\n press(&mut rt, \"org-acme\");\n until(&mut rt, \"acme's chat again\", |s| {\n s.model.session.org_id() == Some(\"acme\") && s.model.chat.conversations.is_some()\n });\n assert!(unresolved_shown(&rt).is_some_and(|w| w.contains(\"Did this arrive in acme?\")), \"kept, to be resent\");\n assert_eq!(rt.state.chat_input.text, \"\", \"the draft did not cross the switch\");\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the resend answered\", |s| {\n s.model.chat.unresolved_here().is_none() && s.model.chat.sending.is_none()\n });\n let sends = fake.with(|s| s.agent.sends.clone());\n assert_eq!(sends.len(), 2);\n assert_eq!(sends[0], sends[1], \"the same send under the same key: a replay, never a second run\");\n}\n\n#[test]\nfn a_refused_retry_keeps_the_send_unconfirmed_under_its_key() {\n let fake = Fake::start();\n fake.with(|s| s.agent.lose_next_send = true);\n let mut rt = on_chat(&fake);\n type_into(&mut rt, \"chat-input\", \"Did this run?\");\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the lost answer\", |s| s.model.chat.unresolved_here().is_some());\n // The retry is refused before the kernel looks at the key (the person's access changed meanwhile).\n fake.with(|s| s.agent.refuse_sends = Some(json!({ \"_tag\": \"Forbidden\", \"action\": \"agent.send\", \"message\": \"no\" })));\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the refusal\", |s| s.model.chat.sending.is_none() && s.model.chat.error.is_some());\n assert!(\n unresolved_shown(&rt).is_some_and(|w| w.contains(\"Couldn't confirm whether\")),\n \"the first attempt may have run: kept, shown as possibly sent\"\n );\n assert_eq!(name(&rt, \"chat-discard\"), \"Discard\");\n // Access is back; the person sends again: under the send's own key, so it runs at most once.\n fake.with(|s| s.agent.refuse_sends = None);\n type_into(&mut rt, \"chat-input\", \"Did this run?\");\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the resend answered\", |s| {\n s.model.chat.unresolved_here().is_none() && s.model.chat.sending.is_none()\n });\n let sends = fake.with(|s| s.agent.sends.clone());\n assert_eq!(sends.len(), 2);\n assert_eq!(sends[0], sends[1], \"the same key: a replay of the first attempt, never a second run\");\n}\n\n#[test]\nfn a_send_whose_answer_was_lost_is_resent_under_its_key_after_the_host_restarts() {\n let dir = TempDir::new(\"restart\");\n let fake = Fake::start();\n fake.with(|s| s.agent.lose_next_send = true);\n {\n let mut rt = runtime_in(&fake, Some(&dir.0));\n until(&mut rt, \"the sign-in screen\", |s| matches!(s.model.session, Session::SignedOut));\n press(&mut rt, \"sign-in\");\n until(&mut rt, \"the browser opened\", |s| s.sign_in_url.is_some());\n fake.with(State::complete_sign_in);\n until(&mut rt, \"the chat\", |s| s.model.chat.conversations.is_some());\n press(&mut rt, \"tab-chat\");\n type_into(&mut rt, \"chat-input\", \"Before the restart\");\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the lost answer\", |s| s.model.chat.unresolved_here().is_some());\n }\n let kept = std::fs::read_to_string(dir.0.join(eloxiv_desktop_rune::outstanding::FILE)).expect(\"kept in a file\");\n assert!(kept.contains(\"Before the restart\") && !kept.contains(TOKEN), \"its text and key, never a credential\");\n // The host starts again; the daemon's session is still signed in.\n let mut rt = runtime_in(&fake, Some(&dir.0));\n until(&mut rt, \"the session\", |s| s.model.chat.conversations.is_some());\n press(&mut rt, \"tab-chat\");\n assert!(unresolved_shown(&rt).is_some_and(|w| w.contains(\"Before the restart\")));\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the resend answered\", |s| {\n s.model.chat.unresolved_here().is_none() && s.model.chat.sending.is_none()\n });\n let sends = fake.with(|s| s.agent.sends.clone());\n assert_eq!(sends.len(), 2);\n assert_eq!(sends[0], sends[1], \"the same send under the same key, after the restart\");\n assert!(!dir.0.join(eloxiv_desktop_rune::outstanding::FILE).exists(), \"settled: nothing kept\");\n}\n\n#[test]\nfn a_send_another_host_settled_is_not_resent() {\n use eloxiv_desktop_rune::outstanding::{Outcome, Store};\n let dir = TempDir::new(\"shared\");\n let fake = Fake::start();\n fake.with(|s| s.agent.lose_next_send = true);\n let mut rt = runtime_in(&fake, Some(&dir.0));\n until(&mut rt, \"the sign-in screen\", |s| matches!(s.model.session, Session::SignedOut));\n press(&mut rt, \"sign-in\");\n until(&mut rt, \"the browser opened\", |s| s.sign_in_url.is_some());\n fake.with(State::complete_sign_in);\n until(&mut rt, \"the chat\", |s| s.model.chat.conversations.is_some());\n press(&mut rt, \"tab-chat\");\n type_into(&mut rt, \"chat-input\", \"Shared data directory\");\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the lost answer\", |s| s.model.chat.unresolved_here().is_some());\n let (key, _) = fake.with(|s| s.agent.sends[0].clone());\n // A second host sharing the data directory discards it (the person gave up on it there).\n let scope = rt.state.scope().expect(\"signed in, in acme\");\n Store::open(Some(&dir.0)).settle(&scope, &key, &Outcome::Discarded);\n // The draft is still in the composer; sending it now is a new send, never the one settled elsewhere.\n assert_eq!(rt.state.chat_input.text, \"Shared data directory\");\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the send answered\", |s| s.model.chat.sending.is_none());\n until(&mut rt, \"both sends recorded\", |_| fake.requests_to(\"/client/v1/actions/agent.send\").len() == 2);\n let keys = fake.requests_to(\"/client/v1/actions/agent.send\");\n let keys: Vec<_> = keys.iter().map(|r| r.body[\"idempotencyKey\"].as_str().unwrap_or(\"\").to_owned()).collect();\n assert_eq!(keys.len(), 2);\n assert_eq!(keys.iter().filter(|k| **k == key).count(), 1, \"settled elsewhere: never resent under its key\");\n}\n\n#[test]\nfn an_answer_that_comes_after_its_organisation_was_left_settles_the_send() {\n let fake = Fake::start();\n let mut rt = on_chat(&fake);\n fake.with(|s| s.agent.hold_answers = true);\n type_into(&mut rt, \"chat-input\", \"Answered late\");\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the send made\", |_| fake.with(|s| s.agent.held == 1));\n let acme = rt.state.scope().expect(\"signed in, in acme\");\n assert_eq!(rt.state.outstanding.list(&acme).len(), 1, \"recorded before it left\");\n press(&mut rt, \"org-globex\");\n until(&mut rt, \"globex\", |s| s.model.session.org_id() == Some(\"globex\"));\n fake.with(|s| s.agent.hold_answers = false);\n until(&mut rt, \"the answer recorded\", |s| s.outstanding.list(&acme).is_empty());\n press(&mut rt, \"org-acme\");\n until(&mut rt, \"acme's chat again\", |s| {\n s.model.session.org_id() == Some(\"acme\") && s.model.chat.conversations.is_some()\n });\n assert_eq!(unresolved_shown(&rt), None, \"it ran: nothing to resend\");\n assert_eq!(fake.with(|s| s.agent.sends.len()), 1);\n}\n\n#[test]\nfn an_organisation_switch_drops_the_conversation_and_late_run_events() {\n let fake = Fake::start();\n let mut rt = on_chat(&fake);\n type_into(&mut rt, \"chat-input\", \"Start something long\");\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the run followed\", |s| s.model.chat.followed.is_some());\n let run = fake.with(|s| s.agent.runs[0][\"id\"].as_str().map(str::to_owned)).expect(\"a run\");\n fake.with(|s| {\n s.run_event(&run, 2, \"consent-required\", json!({ \"consentId\": \"k9\", \"action\": \"agent.moveResources\" }))\n });\n until(&mut rt, \"the consent prompt\", |s| !s.model.chat.consents.is_empty());\n let old = rt.state.model.generation;\n\n press(&mut rt, \"org-globex\");\n assert!(rt.state.model.chat.transcript().is_empty(), \"nothing of acme's conversation from the intent on\");\n until(&mut rt, \"globex's chat\", |s| {\n s.model.session.org_id() == Some(\"globex\") && s.model.chat.conversations.is_some()\n });\n // A late event of acme's run, of the old generation: dropped.\n fake.with(|s| {\n s.emit(json!({ \"type\": \"run\", \"subscription\": \"whatever\", \"generation\": old,\n \"event\": { \"runId\": run, \"seq\": 3, \"type\": \"consent-decided\", \"data\": {}, \"at\": \"\" } }))\n });\n settle(&mut rt, 100);\n let chat = &rt.state.model.chat;\n assert!(chat.transcript().is_empty() && chat.consents.is_empty() && chat.followed.is_none());\n assert!(rt.find(\"consent-k9\").is_none());\n assert_eq!(chat.generation, rt.state.model.generation);\n}\n\n#[test]\nfn a_send_made_in_one_organisation_never_runs_in_the_next() {\n let fake = Fake::start();\n let mut rt = on_chat(&fake);\n let acme = rt.state.model.generation;\n type_into(&mut rt, \"chat-input\", \"Only for acme\");\n // The send's request is slow; the organisation switch reaches the daemon first.\n fake.with(|s| s.agent.hold_sends = true);\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the send on its way\", |_| fake.with(|s| s.agent.held == 1));\n press(&mut rt, \"org-globex\");\n until(&mut rt, \"globex\", |s| s.model.session.org_id() == Some(\"globex\") && s.model.generation > acme);\n fake.with(|s| s.agent.hold_sends = false);\n until(&mut rt, \"the send answered\", |_| fake.with(|s| s.agent.held == 0));\n settle(&mut rt, 100);\n let asked = fake.requests_to(\"/client/v1/actions/agent.send\");\n assert_eq!(asked.len(), 1);\n assert_eq!(asked[0].body[\"generation\"].as_i64(), Some(acme), \"made in acme's generation\");\n assert!(fake.with(|s| s.agent.sends.is_empty()), \"refused by the daemon: it ran nowhere\");\n assert!(rt.state.model.chat.transcript().is_empty());\n}\n\n#[test]\nfn a_draft_never_crosses_a_reset_the_daemon_made() {\n let fake = Fake::start();\n let mut rt = on_chat(&fake);\n // Another local client switches the shared daemon to globex: acme's draft does not follow.\n type_into(&mut rt, \"chat-input\", \"Private to acme\");\n fake.with(|s| {\n s.org = Some(\"globex\".into());\n s.generation += 1;\n let g = s.generation;\n s.emit(json!({ \"type\": \"context\", \"generation\": g, \"reason\": \"org\" }));\n s.emit_session();\n });\n until(&mut rt, \"globex\", |s| s.model.session.org_id() == Some(\"globex\"));\n assert_eq!(rt.state.chat_input.text, \"\");\n // The daemon signs out (another client, or the session revoked): nothing typed stays for the next person.\n type_into(&mut rt, \"chat-input\", \"Private to Alice\");\n fake.with(|s| {\n s.signed_in = false;\n s.org = None;\n s.generation += 1;\n let g = s.generation;\n s.emit(json!({ \"type\": \"context\", \"generation\": g, \"reason\": \"signOut\" }));\n s.emit_session();\n });\n until(&mut rt, \"signed out\", |s| matches!(s.model.session, Session::SignedOut));\n fake.with(State::complete_sign_in);\n until(&mut rt, \"signed in again\", |s| s.model.chat.conversations.is_some());\n press(&mut rt, \"tab-chat\");\n assert_eq!(rt.state.chat_input.text, \"\", \"the draft did not survive the sign-out\");\n}\n\n#[test]\nfn a_restored_send_waits_for_the_session_of_a_new_context() {\n let fake = Fake::start();\n fake.with(|s| s.agent.lose_next_send = true);\n let mut rt = on_chat(&fake);\n type_into(&mut rt, \"chat-input\", \"Private to acme\");\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the lost answer\", |s| s.model.chat.unresolved_here().is_some());\n let old = rt.state.model.generation;\n // Another local client switches the shared daemon to globex; the `context` event arrives before its session.\n fake.with(|s| {\n s.org = Some(\"globex\".into());\n s.generation += 1;\n let g = s.generation;\n s.emit(json!({ \"type\": \"context\", \"generation\": g, \"reason\": \"org\" }));\n });\n until(&mut rt, \"the context\", |s| s.model.generation > old);\n let offered = !has_state(&rt, \"chat-send\", \"disabled\");\n press_if_enabled(&mut rt, \"chat-send\");\n rt.state.send_message();\n rt.state.greet(\"Private to acme too\".into());\n settle(&mut rt, 100);\n assert_eq!(fake.requests_to(\"/client/v1/actions/agent.send\").len(), 1, \"nothing sent before the session\");\n assert!(fake.requests_to(\"/client/v1/writes\").is_empty(), \"nothing written before the session\");\n assert!(!offered, \"Send is not offered before the session\");\n assert!(rt.state.scope().is_none(), \"the retained session does not describe the new context\");\n assert!(rt.state.model.chat.unresolved_here().is_none(), \"acme's send is not offered in a context not yet known\");\n // The session of the new context: globex's chat, without acme's send.\n fake.with(State::emit_session);\n until(&mut rt, \"globex's chat\", |s| {\n s.scope().is_some_and(|scope| scope.org_id == \"globex\") && s.model.chat.conversations.is_some()\n });\n assert!(rt.state.model.chat.unresolved_here().is_none());\n // Back in acme, it is offered again under its key.\n press(&mut rt, \"org-acme\");\n until(&mut rt, \"acme's chat\", |s| {\n s.scope().is_some_and(|scope| scope.org_id == \"acme\") && s.model.chat.conversations.is_some()\n });\n let retry = rt.state.model.chat.unresolved_here().expect(\"acme's send, restored\");\n assert_eq!(retry.generation, rt.state.model.generation);\n assert_eq!(fake.with(|s| s.agent.sends.len()), 1);\n}\n\n#[test]\nfn the_chat_tab_is_hidden_without_the_agent() {\n // A daemon whose app has no agent (a 1.0.0 daemon, or no agent module): no chat tab.\n let mut model = eloxiv_desktop_rune::model::Model::default();\n assert!(!model.chat_enabled);\n let session: eloxiv_local_client::SessionState = serde_json::from_value(json!({ \"state\": \"signedIn\",\n \"user\": { \"id\": \"u\", \"email\": \"a@x\", \"name\": \"A\" }, \"organizations\": [], \"orgId\": \"acme\", \"generation\": 1 }))\n .expect(\"a session\");\n let effects = model.set_session(&session);\n assert!(!effects.iter().any(|e| matches!(e, eloxiv_desktop_rune::model::Effect::SubscribeChat { .. })));\n let _ = Value::Null;\n}\n\n/// Presses `key` only if it can be pressed (a disabled control takes no action).\nfn press_if_enabled(rt: &mut Rt, key: &str) {\n let _ = rt.accessibility_action(key, rune::accesskit::Action::Click, None);\n rt.frame(1.0 / 60.0);\n}\n",
240
+ "type": "registry:file",
241
+ "target": "desktop-rune/app/tests/chat.rs"
242
+ },
243
+ {
244
+ "path": "app/desktop-rune/app/tests/journey.rs",
245
+ "content": "//! The live journey: the app's Runtime (headless, no GPU) driven against a **real** daemon with `clientApp`,\n//! kernel and zero-cache, which a runner started (the TypeScript runner plays the browser and checks the rest).\n//! Skipped, passing, when `ELOXIV_JOURNEY_DAEMON_URL` is not set.\n//!\n//! | Variable | |\n//! | --- | --- |\n//! | `ELOXIV_JOURNEY_DAEMON_URL` | the daemon (`http://127.0.0.1:<port>`); without it the test skips |\n//! | `ELOXIV_JOURNEY_HOST_SECRET` | the host secret the runner started the daemon with |\n//! | `ELOXIV_JOURNEY_BROWSER` | a command run with the sign-in URL as its last argument, which signs in, approves and follows the redirect to the daemon's callback, and exits 0; or |\n//! | `ELOXIV_JOURNEY_BROWSER_URL` | an HTTP endpoint given `POST { \"url\": <sign-in URL> }` that does the same and answers 2xx once the callback was reached; or |\n//! | `ELOXIV_JOURNEY_SIGNED_IN=1` | the daemon's session is already signed in (pre-approved) |\n//! | `ELOXIV_JOURNEY_ORG_A`, `ELOXIV_JOURNEY_ORG_B` | the organisations (default: the session's first two) |\n//! | `ELOXIV_JOURNEY_MAKE_MODULE` | an installed MAKE module whose view has an enabled button whose event asks for a listed action's call; without it the MAKE step is reported skipped |\n//! | `ELOXIV_JOURNEY_PUSH_BARRIER_URL` | the barrier in front of the kernel's push endpoint (`POST /hold`, `POST /release`, `GET /held` answering `{ held, total }`); without it both write checks fail |\n//! | `ELOXIV_JOURNEY_AGENT_PROMPT`, `ELOXIV_JOURNEY_AGENT_ANSWER`, `ELOXIV_JOURNEY_AGENT_ACTION` | a message whose turn (the app's agent on a scripted model, in the first organisation) asks for a consent-marked call of the action, and the answer it then gives; without them the agent step is reported skipped |\n//! | `ELOXIV_JOURNEY_MODEL_RELEASE_URL` | where to `POST` to let the scripted model's answer go on after its first word (it holds it until the journey has seen that partial text drawn); without it the model must not hold |\n//! | `ELOXIV_JOURNEY_KERNEL_URL` | the kernel, recorded in the report |\n//! | `ELOXIV_JOURNEY_REPORT` | where to write the report (JSON: every check with its verdict, the greeting written and its write id) |\n//! | `ELOXIV_JOURNEY_TIMEOUT_SECS` | the wait for each step (default 60) |\n//!\n//! Checks, in order: started (`/health`, `hello`); signed in through the system browser; live rows of the first\n//! organisation; an optimistic write predicted then confirmed and in the rows (the runner checks a second client\n//! sees it: the report names it); a refused write shown, then rolled back with `Forbidden`; an agent turn in the chat\n//! screen (a new conversation, the send, the consent prompt for the action, allowed, the answer streamed in more than\n//! one delta and shown live, then the stored answer, once, and the run ended); an organisation switch after whose\n//! `context` event no row of the first organisation is ever shown; a MAKE view step with a call; sign-out.\n//! Each prints `JOURNEY <check> ok|fail|skipped <detail>`.\n//!\n//! Both writes are made with the push barrier closed, so neither can be confirmed or refused until the journey has\n//! seen it: the write must reach `Predicted` and its row must be shown while its push waits at the barrier; only then\n//! is the barrier opened. The greeting must then go `Predicted` → `Confirmed` with its row kept; the farewell\n//! `Predicted` → `Rejected` with `Forbidden`, its row gone. A host or daemon that predicts nothing fails both.\n\nmod support;\n\nuse std::time::{Duration, Instant};\n\nuse eloxiv_desktop_rune::make::Phase;\nuse eloxiv_desktop_rune::model::Session;\nuse eloxiv_desktop_rune::ui::{Screen, Startup};\nuse eloxiv_local_client::{MakeViewElementTag, MakeViewNode, WritePhase};\nuse serde_json::{Value, json};\nuse support::{a11y_nodes, press, type_into};\n\ntype Rt = rune::Runtime<eloxiv_desktop_rune::Ui>;\n\nstruct Journey {\n rt: Rt,\n timeout: Duration,\n checks: Vec<Value>,\n failed: bool,\n}\n\nimpl Journey {\n fn wait(&mut self, what: &str, done: impl Fn(&eloxiv_desktop_rune::Ui) -> bool) -> bool {\n let deadline = Instant::now() + self.timeout;\n loop {\n self.rt.frame(1.0 / 60.0);\n if done(&self.rt.state) {\n self.rt.frame(1.0 / 60.0);\n return true;\n }\n if Instant::now() > deadline {\n eprintln!(\"JOURNEY timed out waiting for {what}\");\n return false;\n }\n std::thread::sleep(Duration::from_millis(10));\n }\n }\n\n fn check(&mut self, name: &str, ok: Option<bool>, detail: impl Into<String>) {\n let detail = detail.into();\n let verdict = match ok {\n Some(true) => \"ok\",\n Some(false) => \"fail\",\n None => \"skipped\",\n };\n println!(\"JOURNEY {name} {verdict} {detail}\");\n if ok == Some(false) {\n self.failed = true;\n }\n self.checks.push(json!({ \"name\": name, \"verdict\": verdict, \"detail\": detail }));\n }\n}\n\nfn play_browser(url: &str) -> Result<(), String> {\n if let Ok(command) = std::env::var(\"ELOXIV_JOURNEY_BROWSER\") {\n let mut parts = command.split_whitespace();\n let program = parts.next().ok_or(\"ELOXIV_JOURNEY_BROWSER is empty\")?;\n let status = std::process::Command::new(program).args(parts).arg(url).status().map_err(|e| e.to_string())?;\n return if status.success() { Ok(()) } else { Err(format!(\"the browser command exited {status}\")) };\n }\n if let Ok(endpoint) = std::env::var(\"ELOXIV_JOURNEY_BROWSER_URL\") {\n let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into();\n let answer = agent.post(&endpoint).send_json(json!({ \"url\": url })).map_err(|e| e.to_string())?;\n return if answer.status().is_success() {\n Ok(())\n } else {\n Err(format!(\"the browser helper answered {}\", answer.status()))\n };\n }\n Err(\"no ELOXIV_JOURNEY_BROWSER, ELOXIV_JOURNEY_BROWSER_URL or ELOXIV_JOURNEY_SIGNED_IN\".into())\n}\n\n/// One call to the push barrier: its `{ held, total }` answer.\nfn barrier(path: &str, post: bool) -> Result<Value, String> {\n let base = std::env::var(\"ELOXIV_JOURNEY_PUSH_BARRIER_URL\")\n .map_err(|_| \"ELOXIV_JOURNEY_PUSH_BARRIER_URL is not set: nothing holds the server's answer\".to_owned())?;\n let url = format!(\"{}{path}\", base.trim_end_matches('/'));\n let answer = if post { ureq::post(&url).send_empty() } else { ureq::get(&url).call() };\n answer.map_err(|e| e.to_string())?.body_mut().read_json::<Value>().map_err(|e| e.to_string())\n}\n\nfn held_now() -> u64 {\n barrier(\"/held\", false).ok().and_then(|v| v.get(\"held\").and_then(Value::as_u64)).unwrap_or(0)\n}\n\n/// What one held write did: every phase it went through, whether its row was shown while its push was held (it\n/// could only be the prediction), and whether the row is shown at the end.\n#[derive(Debug, Default)]\nstruct HeldWrite {\n id: String,\n phases: Vec<WritePhase>,\n shown_while_held: bool,\n held: u64,\n error: Option<(String, String)>,\n barrier: Option<String>,\n}\n\nimpl Journey {\n fn record(&mut self, w: &mut HeldWrite, matches: &impl Fn(&str) -> bool) {\n if let Some(view) = self.rt.state.model.writes.iter().find(|v| matches(&v.message)) {\n w.id = view.id.clone();\n w.error = view.error.clone();\n if let Some(p) = view.phase\n && w.phases.last() != Some(&p)\n {\n w.phases.push(p);\n }\n }\n }\n\n fn row_shown(&self, matches: &impl Fn(&str) -> bool) -> bool {\n self.rt.state.model.greeting_texts().iter().any(|(_, t)| matches(t))\n }\n\n /// Close the barrier, press `button`, and watch the write whose message `matches`: until it is predicted and its\n /// row shown while its push is held; then open the barrier and watch it until it is confirmed or rejected.\n fn held_write(&mut self, button: &str, matches: impl Fn(&str) -> bool) -> HeldWrite {\n let mut w = HeldWrite::default();\n if let Err(e) = barrier(\"/hold\", true) {\n w.barrier = Some(e);\n return w;\n }\n press(&mut self.rt, button);\n let deadline = Instant::now() + self.timeout;\n while Instant::now() < deadline {\n self.rt.frame(1.0 / 60.0);\n self.record(&mut w, &matches);\n let predicted = w.phases.last() == Some(&WritePhase::Predicted);\n if predicted && self.row_shown(&matches) {\n // Seen: its push must be the one waiting at the barrier (it cannot have been answered).\n w.held = held_now();\n w.shown_while_held = w.held >= 1 && w.phases == [WritePhase::Predicted];\n if w.held >= 1 {\n break;\n }\n }\n if matches!(w.phases.last(), Some(WritePhase::Confirmed | WritePhase::Rejected)) {\n break;\n }\n std::thread::sleep(Duration::from_millis(5));\n }\n if let Err(e) = barrier(\"/release\", true) {\n w.barrier = Some(e);\n }\n let deadline = Instant::now() + self.timeout;\n while Instant::now() < deadline\n && !matches!(w.phases.last(), Some(WritePhase::Confirmed | WritePhase::Rejected | WritePhase::NotConfirmed))\n {\n self.rt.frame(1.0 / 60.0);\n self.record(&mut w, &matches);\n std::thread::sleep(Duration::from_millis(5));\n }\n w\n }\n}\n\nimpl Journey {\n /// The chat screen: a new conversation, `prompt` sent, the consent for `action` allowed, the streamed answer shown\n /// live, then `answer` stored and shown once. Its verdict and what it saw.\n fn agent_turn(&mut self, prompt: &str, answer: &str, action: &str) -> (bool, String) {\n if !self.rt.state.model.chat_enabled {\n return (false, \"the daemon's hello names no agent (queries, runEvents)\".into());\n }\n press(&mut self.rt, \"tab-chat\");\n let loaded = self.wait(\"the chat\", |s| s.model.chat.conversations.is_some() && s.model.chat.engine.is_some());\n let engine = self.rt.state.model.chat.engine.as_ref().map(|e| format!(\"{:?}\", e.state)).unwrap_or_default();\n if !loaded || self.rt.state.model.chat.engine_blocked() {\n return (false, format!(\"chat loaded: {loaded}, engine {engine}\"));\n }\n if self.rt.state.model.chat.conversation_id.is_some() {\n press(&mut self.rt, \"chat-new\");\n }\n type_into(&mut self.rt, \"chat-input\", prompt);\n press(&mut self.rt, \"chat-send\");\n // Until the consent prompt, then allow it; until the run ended with its answer stored. Every frame, what the\n // transcript shows live is recorded.\n let mut live_seen: Vec<String> = Vec::new();\n // Streamed text drawn in the transcript (its rendered nodes) before the stored answer is shown.\n let mut drawn_before_stored: Vec<String> = Vec::new();\n let mut released = false;\n let mut consent: Option<(String, String)> = None;\n let mut stored_once = false;\n let deadline = Instant::now() + self.timeout * 2;\n while Instant::now() < deadline {\n self.rt.frame(1.0 / 60.0);\n let chat = &self.rt.state.model.chat;\n for e in chat.transcript().into_iter().filter(|e| e.live) {\n if live_seen.last() != Some(&e.text) {\n live_seen.push(e.text);\n }\n }\n let stored_shown = chat.transcript().iter().any(|e| !e.live && e.text == answer);\n if !stored_shown && !released {\n for text in drawn_live(&self.rt) {\n if drawn_before_stored.last() != Some(&text) {\n drawn_before_stored.push(text);\n }\n }\n if streamed_partially(&drawn_before_stored, answer) {\n // Seen drawn: the scripted model's answer may go on.\n released = true;\n if let Ok(url) = std::env::var(\"ELOXIV_JOURNEY_MODEL_RELEASE_URL\")\n && let Err(e) = ureq::post(&url).send_empty()\n {\n eprintln!(\"JOURNEY could not release the model at {url}: {e}\");\n }\n }\n }\n let chat = &self.rt.state.model.chat;\n if consent.is_none()\n && let Some(c) = chat.consents.first()\n {\n consent = Some((c.consent_id.clone(), c.action.clone()));\n let key = format!(\"consent-approve-{}\", c.consent_id);\n press(&mut self.rt, &key);\n }\n let chat = &self.rt.state.model.chat;\n let shown = chat.transcript();\n stored_once = shown.iter().filter(|e| !e.live && e.text == answer).count() == 1\n && !shown.iter().any(|e| e.live)\n && shown.iter().any(|e| !e.live && e.role == \"user\" && e.text == prompt);\n if consent.is_some() && stored_once && chat.active_run().is_none() {\n break;\n }\n std::thread::sleep(Duration::from_millis(2));\n }\n let chat = &self.rt.state.model.chat;\n let asked = consent.as_ref().is_some_and(|(_, a)| a == action);\n let streamed = chat.deltas >= 1 && streamed_partially(&drawn_before_stored, answer);\n let ended = chat.active_run().is_none() && chat.followed.is_none() && chat.consents.is_empty();\n let no_error = chat.error.is_none();\n let detail = format!(\n \"consent {consent:?}; {} deltas, live {live_seen:?}, drawn before the stored answer {drawn_before_stored:?}; \\\n stored answer shown once: {stored_once}; run ended: {ended}; error {:?}; conversation {:?}\",\n chat.deltas, chat.error, chat.conversation_id\n );\n press(&mut self.rt, \"tab-greetings\");\n (asked && streamed && stored_once && ended && no_error, detail)\n }\n}\n\n/// The streamed text the chat's transcript draws now: its live lines' accessible names (`Agent: <text>`).\nfn drawn_live(rt: &rune::Runtime<eloxiv_desktop_rune::Ui>) -> Vec<String> {\n a11y_nodes(rt)\n .into_iter()\n .filter(|n| n.get(\"key\").and_then(Value::as_str).is_some_and(|k| k.starts_with(\"chat-live-\")))\n .filter_map(|n| {\n n.get(\"name\").and_then(Value::as_str).and_then(|t| t.strip_prefix(\"Agent: \")).map(str::to_owned)\n })\n .collect()\n}\n\n/// Whether part of `answer`, not all of it, was drawn as streamed text before the stored answer: a stored step's\n/// whole text shown in its place, or deltas that never reached the transcript, are not streaming.\nfn streamed_partially(drawn: &[String], answer: &str) -> bool {\n drawn.iter().any(|t| !t.is_empty() && t.len() < answer.len() && answer.starts_with(t.as_str()))\n}\n\n#[test]\nfn the_streaming_check_needs_partial_text_drawn() {\n let answer = \"Your journey notes are filed.\";\n assert!(!streamed_partially(&[], answer), \"nothing drawn\");\n assert!(!streamed_partially(&[answer.to_owned()], answer), \"only the stored step's whole text\");\n assert!(!streamed_partially(&[\"Something else\".to_owned()], answer));\n assert!(streamed_partially(&[\"Your \".to_owned(), answer.to_owned()], answer));\n}\n\nfn first_control(node: &MakeViewNode, path: &mut Vec<usize>) -> Option<String> {\n let MakeViewNode::MakeViewElement(e) = node else { return None };\n let disabled = e.props.as_ref().and_then(|p| p.disabled.as_ref()).is_some_and(|d| d.to_string() == \"true\");\n if matches!(e.tag, MakeViewElementTag::Button | MakeViewElementTag::Link) && e.on.is_some() && !disabled {\n return Some(eloxiv_desktop_rune::make::fields::key_of(path));\n }\n for (i, c) in e.children.iter().enumerate() {\n path.push(i);\n let found = first_control(c, path);\n path.pop();\n if found.is_some() {\n return found;\n }\n }\n None\n}\n\nfn row_orgs(s: &eloxiv_desktop_rune::Ui) -> Vec<String> {\n s.model.list.rows.iter().filter_map(|r| r.get(\"orgId\").and_then(Value::as_str).map(str::to_owned)).collect()\n}\n\n#[test]\nfn journey_against_a_real_daemon() {\n let Ok(url) = std::env::var(\"ELOXIV_JOURNEY_DAEMON_URL\") else {\n eprintln!(\"skipped: ELOXIV_JOURNEY_DAEMON_URL is not set (the journey runner sets it)\");\n return;\n };\n let secret =\n std::env::var(\"ELOXIV_JOURNEY_HOST_SECRET\").expect(\"ELOXIV_JOURNEY_HOST_SECRET with ELOXIV_JOURNEY_DAEMON_URL\");\n let timeout = Duration::from_secs(\n std::env::var(\"ELOXIV_JOURNEY_TIMEOUT_SECS\").ok().and_then(|s| s.parse().ok()).unwrap_or(60),\n );\n let mut rt =\n // The outstanding sends in memory: the journey leaves no file behind.\n eloxiv_desktop_rune::app_in(url.clone(), secret, None)\n .headless_runtime((1000.0, 800.0), rune::Env::new(false, 1.0));\n rt.frame(0.0);\n let mut j = Journey { rt, timeout, checks: Vec::new(), failed: false };\n let tag = eloxiv_desktop_rune::random_id();\n let greeting = format!(\"hello from the rune journey {tag}\");\n let mut write_id = String::new();\n\n // Started.\n let started = j.wait(\"the daemon\", |s| s.startup != Startup::Starting)\n && j.wait(\"the session\", |s| !matches!(s.model.session, Session::Unknown));\n let detail = match &j.rt.state.startup {\n Startup::Failed(m) => m.clone(),\n _ => format!(\"{:?}\", j.rt.state.hello.as_ref().map(|h| h.version.clone())),\n };\n let ready = started && j.rt.state.startup == Startup::Ready;\n j.check(\"started\", Some(ready), detail);\n\n // Sign in through the system browser (the runner plays it).\n if ready && !matches!(j.rt.state.model.session, Session::SignedIn { .. }) {\n if std::env::var(\"ELOXIV_JOURNEY_SIGNED_IN\").as_deref() == Ok(\"1\") {\n let ok = j.wait(\"the pre-approved session\", |s| matches!(s.model.session, Session::SignedIn { .. }));\n j.check(\"sign-in\", Some(ok), \"pre-approved\");\n } else {\n press(&mut j.rt, \"sign-in\");\n let opened = j.wait(\"the browser\", |s| s.sign_in_url.is_some());\n let urls = j.rt.take_url_requests();\n let result = match (opened, urls.first()) {\n (true, Some(u)) => play_browser(u),\n _ => Err(format!(\"no sign-in URL was opened ({:?})\", j.rt.state.notice)),\n };\n let ok = result.is_ok()\n && j.wait(\"the signed-in session\", |s| matches!(s.model.session, Session::SignedIn { .. }));\n j.check(\"sign-in\", Some(ok), result.err().unwrap_or_else(|| format!(\"{} URL(s) opened\", urls.len())));\n }\n } else if ready {\n j.check(\"sign-in\", Some(true), \"already signed in\");\n }\n\n let orgs: Vec<String> = match &j.rt.state.model.session {\n Session::SignedIn { organizations, .. } => organizations.iter().map(|o| o.org_id.clone()).collect(),\n _ => Vec::new(),\n };\n let org_a = std::env::var(\"ELOXIV_JOURNEY_ORG_A\").ok().or_else(|| orgs.first().cloned());\n let org_b = std::env::var(\"ELOXIV_JOURNEY_ORG_B\").ok().or_else(|| orgs.get(1).cloned());\n\n // Live rows of the first organisation.\n if let Some(a) = org_a.clone().filter(|_| !orgs.is_empty()) {\n if j.rt.state.model.session.org_id() != Some(a.as_str()) {\n press(&mut j.rt, &format!(\"org-{a}\"));\n }\n let ok = j.wait(\"the live list\", |s| {\n s.model.session.org_id() == Some(a.as_str())\n && s.model.list.status == Some(eloxiv_local_client::RowsStatus::Complete)\n });\n let rows = j.rt.state.model.list.rows.len();\n j.check(\"live-rows\", Some(ok), format!(\"{rows} rows in {a}\"));\n\n // An optimistic write: predicted and shown while the server cannot have answered, then confirmed.\n type_into(&mut j.rt, \"greeting-input\", &greeting);\n let wrote = j.held_write(\"greet\", |m| m == greeting);\n write_id = wrote.id.clone();\n let shown =\n j.wait(\"the greeting in the rows\", |s| s.model.greeting_texts().iter().any(|(_, t)| *t == greeting));\n let ok = wrote.barrier.is_none()\n && wrote.shown_while_held\n && wrote.phases == [WritePhase::Predicted, WritePhase::Confirmed]\n && shown;\n j.check(\n \"optimistic-write\",\n Some(ok),\n format!(\n \"phases {:?}, predicted row shown while its push was held: {} ({} held){}, write {write_id}\",\n wrote.phases,\n wrote.shown_while_held,\n wrote.held,\n wrote.barrier.as_ref().map(|e| format!(\", barrier: {e}\")).unwrap_or_default(),\n ),\n );\n\n // A refused write: predicted and shown while held, then rolled back with its typed error.\n let refused = j.held_write(\"farewell\", |m| m.contains(\"goodbye\"));\n let gone = j.wait(\"the rollback\", |s| !s.model.greeting_texts().iter().any(|(_, t)| t.contains(\"goodbye\")));\n let forbidden = refused.error.as_ref().is_some_and(|(t, _)| t == \"Forbidden\");\n let ok = refused.barrier.is_none()\n && refused.shown_while_held\n && refused.phases == [WritePhase::Predicted, WritePhase::Rejected]\n && forbidden\n && gone;\n j.check(\n \"refused-write\",\n Some(ok),\n format!(\n \"phases {:?}, predicted row shown while its push was held: {} ({} held), gone after: {gone}, {:?}{}\",\n refused.phases,\n refused.shown_while_held,\n refused.held,\n refused.error,\n refused.barrier.as_ref().map(|e| format!(\", barrier: {e}\")).unwrap_or_default(),\n ),\n );\n\n // An agent turn in the chat screen, on the app's scripted model.\n let agent = (\n std::env::var(\"ELOXIV_JOURNEY_AGENT_PROMPT\"),\n std::env::var(\"ELOXIV_JOURNEY_AGENT_ANSWER\"),\n std::env::var(\"ELOXIV_JOURNEY_AGENT_ACTION\"),\n );\n match agent {\n (Ok(prompt), Ok(answer), Ok(action)) => {\n let (ok, detail) = j.agent_turn(&prompt, &answer, &action);\n j.check(\"agent-turn\", Some(ok), detail);\n }\n _ => j.check(\"agent-turn\", None, \"ELOXIV_JOURNEY_AGENT_PROMPT, _ANSWER and _ACTION are not set\"),\n }\n\n // An organisation switch: after the context event, nothing of the first organisation.\n match org_b.clone() {\n Some(b) => {\n let before = j.rt.state.model.generation;\n press(&mut j.rt, &format!(\"org-{b}\"));\n let mut leaked = Vec::new();\n let deadline = Instant::now() + j.timeout;\n let mut settled = false;\n while Instant::now() < deadline {\n j.rt.frame(1.0 / 60.0);\n let s = &j.rt.state;\n if s.model.generation > before {\n leaked.extend(row_orgs(s).into_iter().filter(|o| *o == a));\n if s.model.greeting_texts().iter().any(|(_, t)| *t == greeting) {\n leaked.push(greeting.clone());\n }\n if s.model.list.status == Some(eloxiv_local_client::RowsStatus::Complete) {\n settled = true;\n break;\n }\n }\n std::thread::sleep(Duration::from_millis(5));\n }\n // Keep watching for late events of the old generation.\n let watch = Instant::now() + Duration::from_secs(2);\n while Instant::now() < watch {\n j.rt.frame(1.0 / 60.0);\n leaked.extend(row_orgs(&j.rt.state).into_iter().filter(|o| *o == a));\n std::thread::sleep(Duration::from_millis(10));\n }\n j.check(\"org-switch\", Some(settled && leaked.is_empty()), format!(\"to {b}: leaked {leaked:?}\"));\n }\n None => j.check(\"org-switch\", Some(false), \"the person has one organisation; set ELOXIV_JOURNEY_ORG_B\"),\n }\n\n // A MAKE view step with a call.\n match std::env::var(\"ELOXIV_JOURNEY_MAKE_MODULE\") {\n Ok(module) => {\n press(&mut j.rt, \"tab-make\");\n assert_eq!(j.rt.state.screen, Screen::Make);\n type_into(&mut j.rt, \"make-module\", &module);\n press(&mut j.rt, \"make-open\");\n let shown = j.wait(\"the view\", |s| {\n s.make.view.as_ref().is_some_and(|v| v.steps >= 1) || matches!(s.make.phase, Phase::Failed { .. })\n });\n let control = j.rt.state.make.view.as_ref().and_then(|v| first_control(&v.tree, &mut Vec::new()));\n let ok = match (shown, control) {\n (true, Some(key)) => {\n press(&mut j.rt, &key);\n j.wait(\"a call's result in a step\", |s| {\n s.make.view.as_ref().is_some_and(|v| v.calls >= 1 && v.results >= 1 && v.steps >= 3)\n || matches!(s.make.phase, Phase::Failed { .. })\n }) && j.rt.state.make.view.is_some()\n }\n _ => false,\n };\n let no_url = j.rt.take_url_requests().is_empty();\n let detail = format!(\n \"{:?}; steps, calls, results {:?}; no URL opened: {no_url}\",\n j.rt.state.make.phase,\n j.rt.state.make.view.as_ref().map(|v| (v.steps, v.calls, v.results)),\n );\n j.check(\"make-view\", Some(ok && no_url), detail);\n press(&mut j.rt, \"tab-greetings\");\n }\n Err(_) => j.check(\"make-view\", None, \"ELOXIV_JOURNEY_MAKE_MODULE is not set\"),\n }\n\n // Sign-out.\n press(&mut j.rt, \"sign-out\");\n let out = j.wait(\"signed out\", |s| matches!(s.model.session, Session::SignedOut));\n let empty = j.rt.state.model.list.rows.is_empty() && j.rt.find(\"greetings\").is_none();\n j.check(\"sign-out\", Some(out && empty), format!(\"controls named: {}\", a11y_nodes(&j.rt).len()));\n }\n\n let report = json!({\n \"daemon\": url,\n \"kernel\": std::env::var(\"ELOXIV_JOURNEY_KERNEL_URL\").ok(),\n \"greeting\": greeting,\n \"writeId\": write_id,\n \"checks\": j.checks,\n });\n if let Ok(path) = std::env::var(\"ELOXIV_JOURNEY_REPORT\") {\n std::fs::write(&path, serde_json::to_vec_pretty(&report).unwrap_or_default()).expect(\"write the report\");\n }\n println!(\"JOURNEY report {report}\");\n assert!(!j.failed, \"the journey failed: {report}\");\n}\n",
246
+ "type": "registry:file",
247
+ "target": "desktop-rune/app/tests/journey.rs"
248
+ },
249
+ {
250
+ "path": "app/desktop-rune/app/tests/links.rs",
251
+ "content": "//! Deep links reaching the host's screens (headless, against the fake `/client/v1`): read with the View contract's\n//! `parseLink` over the app's views, kept until the views and a signed-in session are there, the organisation they\n//! name switched to (only one the person belongs to), routed to hello's greetings, the agent's conversation or a\n//! MAKE view; links that are not the app's are refused and change nothing.\n\nmod support;\n\nuse eloxiv_desktop_rune::links::{ViewEntry, ViewTable};\nuse eloxiv_desktop_rune::make::Phase;\nuse eloxiv_desktop_rune::routing::on_open_url;\nuse eloxiv_desktop_rune::ui::Screen;\nuse support::*;\n\nfn views() -> ViewTable {\n let v = |id: &str, route: &str, title: &str| ViewEntry {\n id: id.into(),\n route: route.into(),\n title: title.into(),\n ..ViewEntry::default()\n };\n ViewTable::new(vec![v(\"hello.greetings\", \"/hello\", \"Greetings\"), v(\"notes.list\", \"/notes\", \"Notes\")])\n .expect(\"as the test set it up\")\n}\n\nfn open(rt: &mut rune::Runtime<eloxiv_desktop_rune::Ui>, url: &str) {\n rt.update(|s, tx| on_open_url(s, url, tx));\n rt.frame(1.0 / 60.0);\n}\n\nfn org(s: &eloxiv_desktop_rune::Ui) -> Option<String> {\n s.model.session.org_id().map(str::to_owned)\n}\n\n#[test]\nfn a_link_opens_its_screen_in_its_organisation() {\n let fake = Fake::start();\n let mut rt = signed_in(&fake);\n rt.state.host.views = Some(views());\n assert_eq!(org(&rt.state).as_deref(), Some(\"acme\"));\n\n open(&mut rt, \"eloxiv://open/make/mk_board\");\n assert_eq!(rt.state.screen, Screen::Make);\n assert_eq!(rt.state.make.module_input.text, \"mk_board\", \"the module filled in\");\n assert!(!matches!(&rt.state.make.phase, Phase::Loading { .. }), \"not opened: {:?}\", rt.state.make.phase);\n assert_eq!(rt.state.host.link_status.as_deref(), Some(\"Opened from a link: MAKE view\"));\n settle(&mut rt, 50);\n assert!(\n !fake.seen().iter().any(|r| r.path.starts_with(\"/client/v1/actions/\")),\n \"a link runs no action, make.view and init included\"\n );\n // The person's press opens it.\n press(&mut rt, \"make-open\");\n until(&mut rt, \"make.view asked\", |_| !fake.requests_to(\"/client/v1/actions/make.view\").is_empty());\n\n open(&mut rt, \"eloxiv://open/hello?org=globex\");\n until(&mut rt, \"the switch to globex\", |s| org(s).as_deref() == Some(\"globex\") && s.host.pending_link.is_none());\n assert_eq!(rt.state.screen, Screen::Greetings);\n assert_eq!(fake.requests_to(\"/client/v1/org\").len(), 1, \"one switch\");\n until(&mut rt, \"globex's greetings\", |s| s.model.greeting_texts().iter().any(|(_, m)| m == \"hello from globex\"));\n\n // An organisation the person is not in is ignored; the link still opens its screen.\n rt.state.screen = Screen::Make;\n open(&mut rt, \"/hello?org=initech\");\n assert_eq!(rt.state.screen, Screen::Greetings);\n assert_eq!(org(&rt.state).as_deref(), Some(\"globex\"));\n assert_eq!(fake.requests_to(\"/client/v1/org\").len(), 1, \"no switch\");\n\n // A view of the app the host has no screen for says so.\n open(&mut rt, \"eloxiv://open/notes\");\n assert!(rt.state.notice.as_deref().is_some_and(|n| n.contains(\"Notes has no screen\")), \"{:?}\", rt.state.notice);\n assert_eq!(rt.state.screen, Screen::Greetings);\n}\n\n#[test]\nfn links_that_are_not_the_apps_are_refused_and_change_nothing() {\n let fake = Fake::start();\n let mut rt = signed_in(&fake);\n rt.state.host.views = Some(views());\n let before = fake.seen().len();\n for (url, reason) in [\n (\"https://evil.example.com/hello\", \"foreign-origin\"),\n (\"other://open/hello\", \"scheme\"),\n (\"eloxiv://evil/hello\", \"malformed\"),\n (\"eloxiv://open/nowhere?action=delete\", \"unknown-view\"),\n ] {\n open(&mut rt, url);\n let notice = rt.state.notice.clone().unwrap_or_default();\n assert!(notice.contains(&format!(\"InvalidLink ({reason})\")), \"{url}: {notice}\");\n assert_eq!(rt.state.screen, Screen::Greetings, \"{url}\");\n assert!(rt.state.host.pending_link.is_none(), \"{url} is not kept\");\n }\n settle(&mut rt, 100);\n assert_eq!(fake.seen().len(), before, \"no request for a refused link\");\n assert!(rt.take_url_requests().is_empty(), \"nothing opened\");\n}\n\n#[test]\nfn a_link_waits_for_the_views_and_for_sign_in() {\n let fake = Fake::start();\n let mut rt = runtime(&fake);\n until(&mut rt, \"the sign-in screen\", |s| matches!(s.model.session, eloxiv_desktop_rune::model::Session::SignedOut));\n rt.state.host.views = None;\n open(&mut rt, \"eloxiv://open/make/mk_later?org=globex\");\n assert_eq!(rt.state.host.pending_link.as_deref(), Some(\"eloxiv://open/make/mk_later?org=globex\"), \"kept\");\n rt.state.host.views = Some(views());\n settle(&mut rt, 50);\n assert!(rt.state.host.pending_link.is_some(), \"still signed out: still kept\");\n assert!(a11y(&rt, \"link-waiting\").is_some(), \"the sign-in screen says a link waits\");\n\n press(&mut rt, \"sign-in\");\n until(&mut rt, \"the browser opened\", |s| s.sign_in_url.is_some());\n fake.with(State::complete_sign_in);\n until(&mut rt, \"the link opened in globex\", |s| s.host.pending_link.is_none() && s.screen == Screen::Make);\n assert_eq!(org(&rt.state).as_deref(), Some(\"globex\"));\n assert!(a11y(&rt, \"link-waiting\").is_none(), \"no longer waiting\");\n assert_eq!(rt.state.make.module_input.text, \"mk_later\");\n settle(&mut rt, 50);\n assert!(\n !fake.seen().iter().any(|r| r.path.starts_with(\"/client/v1/actions/\")),\n \"nothing run until the person opens it\"\n );\n}\n\n#[test]\nfn the_window_shows_the_version_and_why_updates_are_not_available() {\n let fake = Fake::start();\n let mut rt = runtime(&fake);\n until(&mut rt, \"ready\", |s| s.startup == eloxiv_desktop_rune::ui::Startup::Ready);\n let status = a11y(&rt, \"update-status\").expect(\"the update status\");\n let name =\n status.get(\"name\").or_else(|| status.get(\"value\")).and_then(|v| v.as_str()).unwrap_or_default().to_owned();\n assert!(name.contains(\"Updates: not available here\"), \"{status}\");\n let caps = rt.state.host.capabilities().to_json();\n assert_eq!(caps[\"updates\"], \"unsupported\");\n assert_eq!(caps[\"push\"], \"unsupported\");\n assert_eq!(caps[\"deepLinks\"], \"supported\");\n}\n",
252
+ "type": "registry:file",
253
+ "target": "desktop-rune/app/tests/links.rs"
254
+ },
255
+ {
256
+ "path": "app/desktop-rune/app/tests/make_view.rs",
257
+ "content": "//! The native MAKE renderer and host against a fake `/client/v1` whose `make.renderView` the test plays: every\n//! tag drawn, fields collected by name, events and results, calls limited to the view's actions (any other\n//! refused here with no request), steps one at a time, malformed and oversized trees, and no URL ever opened.\n\nmod support;\n\nuse std::sync::{Arc, Mutex};\n\nuse eloxiv_desktop_rune::make::Phase;\nuse eloxiv_desktop_rune::ui::Screen;\nuse serde_json::{Value, json};\nuse support::*;\n\n/// Every message the view's `update` was given, in order.\ntype Messages = Arc<Mutex<Vec<Value>>>;\n\nfn open(\n fake: &Fake,\n code: impl Fn(&Value, &Value) -> Value + Send + 'static,\n actions: &[&str],\n) -> (rune::Runtime<eloxiv_desktop_rune::Ui>, Messages) {\n let messages: Messages = Arc::new(Mutex::new(Vec::new()));\n let seen = messages.clone();\n fake.with(|s| {\n s.view = Some(Box::new(move |state, message| {\n seen.lock().expect(\"messages\").push(message.clone());\n code(state, message)\n }));\n s.view_actions = actions.iter().map(|a| (*a).to_owned()).collect();\n });\n let mut rt = signed_in(fake);\n press(&mut rt, \"tab-make\");\n assert_eq!(rt.state.screen, Screen::Make);\n type_into(&mut rt, \"make-module\", \"mk_demo\");\n press(&mut rt, \"make-open\");\n until(&mut rt, \"the view's first step\", |s| s.make.view.as_ref().is_some_and(|v| v.steps >= 1));\n (rt, messages)\n}\n\nfn step(state: Value, tree: Value) -> Value {\n json!({ \"state\": state, \"calls\": [], \"tree\": tree })\n}\n\nfn last(messages: &Messages) -> Value {\n messages.lock().expect(\"messages\").last().cloned().unwrap_or(Value::Null)\n}\n\n/// Every tag and input type of the vocabulary.\nfn everything() -> Value {\n json!({ \"tag\": \"div\", \"props\": { \"class\": \"p-4 text-red-500\" }, \"children\": [\n { \"tag\": \"h1\", \"children\": [\"Title\"] },\n { \"tag\": \"h2\", \"children\": [\"Sub\"] },\n { \"tag\": \"h3\", \"children\": [\"Third\"] },\n { \"tag\": \"h4\", \"children\": [\"Fourth\"] },\n { \"tag\": \"p\", \"children\": [\"Some \", { \"tag\": \"strong\", \"children\": [\"bold\"] }, \", \",\n { \"tag\": \"em\", \"children\": [\"em\"] }, \", \", { \"tag\": \"small\", \"children\": [\"small\"] }, \", \",\n { \"tag\": \"code\", \"children\": [\"code\"] }, { \"tag\": \"br\" }, { \"tag\": \"span\", \"props\": { \"style\": \"color: #f00\" }, \"children\": [\"red\"] }, 42] },\n { \"tag\": \"pre\", \"children\": [\" keep spaces\"] },\n { \"tag\": \"hr\" },\n { \"tag\": \"ul\", \"children\": [{ \"tag\": \"li\", \"children\": [\"one\"] }, { \"tag\": \"li\", \"children\": [\"two\"] }] },\n { \"tag\": \"ol\", \"children\": [{ \"tag\": \"li\", \"children\": [\"first\"] }] },\n { \"tag\": \"table\", \"children\": [\n { \"tag\": \"thead\", \"children\": [{ \"tag\": \"tr\", \"children\": [{ \"tag\": \"th\", \"children\": [\"Name\"] }, { \"tag\": \"th\", \"props\": { \"colspan\": 2 }, \"children\": [\"Value\"] }] }] },\n { \"tag\": \"tbody\", \"children\": [{ \"tag\": \"tr\", \"children\": [{ \"tag\": \"td\", \"children\": [\"a\"] }, { \"tag\": \"td\", \"props\": { \"rowspan\": 3 }, \"children\": [\"1\"] }] }] }\n ] },\n { \"tag\": \"section\", \"children\": [{ \"tag\": \"header\", \"children\": [\"head\"] }, { \"tag\": \"footer\", \"children\": [\"foot\"] }] },\n { \"tag\": \"form\", \"children\": [\n { \"tag\": \"label\", \"children\": [\"Title \", { \"tag\": \"input\", \"props\": { \"name\": \"title\" } }] },\n { \"tag\": \"input\", \"props\": { \"name\": \"count\", \"type\": \"number\", \"ariaLabel\": \"Count\" } },\n { \"tag\": \"input\", \"props\": { \"name\": \"when\", \"type\": \"date\", \"placeholder\": \"Date\" } },\n { \"tag\": \"input\", \"props\": { \"name\": \"done\", \"type\": \"checkbox\", \"ariaLabel\": \"Done\" } },\n { \"tag\": \"input\", \"props\": { \"name\": \"size\", \"type\": \"radio\", \"value\": \"s\", \"ariaLabel\": \"Small\" } },\n { \"tag\": \"input\", \"props\": { \"name\": \"size\", \"type\": \"radio\", \"value\": \"m\", \"ariaLabel\": \"Medium\" } },\n { \"tag\": \"input\", \"props\": { \"name\": \"level\", \"type\": \"range\", \"min\": 0, \"max\": 10, \"step\": 2, \"ariaLabel\": \"Level\" } },\n { \"tag\": \"input\", \"props\": { \"name\": \"secret\", \"type\": \"hidden\", \"value\": \"h1\" } },\n { \"tag\": \"input\", \"props\": { \"name\": \"odd\", \"type\": \"file\", \"ariaLabel\": \"Odd\" } },\n { \"tag\": \"textarea\", \"props\": { \"name\": \"notes\", \"rows\": 3, \"ariaLabel\": \"Notes\" } },\n { \"tag\": \"select\", \"props\": { \"name\": \"colour\", \"ariaLabel\": \"Colour\" }, \"children\": [\n { \"tag\": \"option\", \"children\": [\"Red\"] }, { \"tag\": \"option\", \"props\": { \"selected\": true }, \"children\": [\"Blue\"] }] },\n { \"tag\": \"button\", \"on\": \"save\", \"data\": { \"row\": 7 }, \"children\": [\"Save\"] }\n ] },\n { \"tag\": \"input\", \"props\": { \"name\": \"outside\", \"value\": \"o\" } },\n { \"tag\": \"button\", \"on\": \"all\", \"children\": [\"Everything\"] },\n { \"tag\": \"button\", \"on\": \"never\", \"props\": { \"disabled\": true }, \"children\": [\"Disabled\"] },\n { \"tag\": \"link\", \"on\": \"go\", \"props\": { \"title\": \"Goes nowhere\" }, \"children\": [\"A link\"] }\n ] })\n}\n\nfn role_of(rt: &rune::Runtime<eloxiv_desktop_rune::Ui>, key: &str) -> String {\n a11y(rt, key).and_then(|n| n[\"role\"].as_str().map(str::to_owned)).unwrap_or_default()\n}\n\n#[test]\nfn every_tag_is_drawn_with_its_role() {\n let fake = Fake::start();\n let (rt, _) = open(&fake, |_, _| step(json!({}), everything()), &[]);\n let nodes = a11y_nodes(&rt);\n let roles: Vec<&str> = nodes.iter().filter_map(|n| n[\"role\"].as_str()).collect();\n for role in [\n \"heading\",\n \"list\",\n \"list-item\",\n \"table\",\n \"row\",\n \"column-header\",\n \"cell\",\n \"form\",\n \"button\",\n \"link\",\n \"check-box\",\n \"radio-button\",\n \"slider\",\n \"text-input\",\n \"multiline-text-input\",\n \"list-box\",\n \"list-box-option\",\n ] {\n assert!(roles.contains(&role), \"no {role} in {roles:?}\");\n }\n // `hr` is a rule between sections: drawn, and decoration to assistive technology (Rune's `separator`).\n assert!(rt.find(\"mk:6\").is_some());\n // Headings carry their levels.\n let levels: Vec<u64> =\n nodes.iter().filter(|n| n[\"role\"] == \"heading\").filter_map(|n| n[\"level\"].as_u64()).collect();\n for l in 1..=4 {\n assert!(levels.contains(&l), \"heading level {l} in {levels:?}\");\n }\n // A file input is a text field; a hidden one is not drawn.\n let odd = rt\n .state\n .make\n .view\n .as_ref()\n .and_then(|v| v.fields.list.iter().find(|f| f.name.as_deref() == Some(\"odd\")).cloned())\n .expect(\"odd\");\n assert!(matches!(odd.kind, eloxiv_desktop_rune::make::fields::Kind::Line { .. }));\n assert!(a11y_nodes(&rt).iter().all(|n| n[\"name\"] != \"secret\"));\n assert_eq!(role_of(&rt, \"mk:13\"), \"button\");\n assert_eq!(role_of(&rt, \"mk:15\"), \"link\");\n}\n\n#[test]\nfn a_button_sends_its_event_with_its_forms_fields() {\n let fake = Fake::start();\n let (mut rt, messages) = open(&fake, |_, _| step(json!({}), everything()), &[]);\n let field = |rt: &rune::Runtime<eloxiv_desktop_rune::Ui>, name: &str| {\n rt.state\n .make\n .view\n .as_ref()\n .and_then(|v| v.fields.list.iter().find(|f| f.name.as_deref() == Some(name)).map(|f| f.key.clone()))\n .expect(name)\n };\n let (title, count, done, medium, level, colour) = (\n field(&rt, \"title\"),\n field(&rt, \"count\"),\n field(&rt, \"done\"),\n field(&rt, \"size\"),\n field(&rt, \"level\"),\n field(&rt, \"colour\"),\n );\n type_into(&mut rt, &title, \"Groceries\");\n type_into(&mut rt, &count, \"12x\");\n press(&mut rt, &done);\n // The second radio of \"size\" (Medium).\n let medium_key = rt\n .state\n .make\n .view\n .as_ref()\n .and_then(|v| v.fields.list.iter().filter(|f| f.name.as_deref() == Some(\"size\")).nth(1).map(|f| f.key.clone()))\n .expect(\"medium\");\n assert_ne!(medium, medium_key);\n press(&mut rt, &medium_key);\n assert!(rt.accessibility_action(&level, rune::accesskit::Action::Increment, None));\n rt.frame(1.0 / 60.0);\n press(&mut rt, &format!(\"{colour}~o0\"));\n\n let save = rt.state.make.view.as_ref().map(|v| v.fields.list[0].form.clone().expect(\"in a form\")).expect(\"form\");\n let save_button = format!(\"{save}.11\");\n press(&mut rt, &save_button);\n until(&mut rt, \"the save event\", |_| last(&messages)[\"name\"] == \"save\");\n let m = last(&messages);\n assert_eq!(m[\"type\"], \"event\");\n assert_eq!(m[\"data\"], json!({ \"row\": 7 }));\n assert_eq!(\n m[\"fields\"],\n json!({ \"title\": \"Groceries\", \"count\": \"12\", \"when\": \"\", \"done\": true, \"size\": \"m\", \"level\": \"8\",\n \"secret\": \"h1\", \"odd\": \"\", \"notes\": \"\", \"colour\": \"Red\" }),\n \"the form's named fields only (not `outside`), a number's characters, the range stepped from its midpoint (6, the greater of the two nearest steps)\"\n );\n\n press(&mut rt, \"mk:13\");\n until(&mut rt, \"the view-wide event\", |_| last(&messages)[\"name\"] == \"all\");\n let all = last(&messages);\n assert_eq!(all[\"fields\"][\"outside\"], \"o\", \"outside a form: the whole view's fields\");\n assert_eq!(all[\"fields\"][\"title\"], \"Groceries\");\n assert!(all.get(\"data\").is_none(), \"no data when the tree gives none\");\n\n // A disabled button sends nothing and has no handler.\n assert!(\n has_state(&rt, \"mk:14\", \"disabled\") || !rt.accessibility_action(\"mk:14\", rune::accesskit::Action::Click, None)\n );\n settle(&mut rt, 50);\n assert_ne!(last(&messages)[\"name\"], \"never\");\n assert!(rt.take_url_requests().is_empty(), \"no URL is ever opened\");\n}\n\n#[test]\nfn a_watched_field_reports_its_value_and_typed_values_survive_a_redraw() {\n let fake = Fake::start();\n let code = |state: &Value, message: &Value| {\n let n = state.get(\"n\").and_then(Value::as_u64).unwrap_or(0) + u64::from(!message.is_null());\n step(\n json!({ \"n\": n }),\n json!({ \"tag\": \"div\", \"children\": [\n { \"tag\": \"input\", \"on\": \"typed\", \"props\": { \"name\": \"q\", \"ariaLabel\": \"Query\" } },\n { \"tag\": \"input\", \"on\": \"ticked\", \"props\": { \"name\": \"ok\", \"type\": \"checkbox\", \"ariaLabel\": \"OK\" } },\n { \"tag\": \"input\", \"props\": { \"name\": \"fixed\", \"value\": format!(\"v{n}\"), \"ariaLabel\": \"Fixed\" } },\n format!(\"steps {n}\")\n ] }),\n )\n };\n let (mut rt, messages) = open(&fake, code, &[]);\n type_into(&mut rt, \"mk:0\", \"abc\");\n until(&mut rt, \"the typed event\", |_| last(&messages)[\"name\"] == \"typed\");\n assert_eq!(last(&messages)[\"value\"], \"abc\");\n until(&mut rt, \"the redraw\", |s| s.make.view.as_ref().is_some_and(|v| v.steps >= 2));\n let view = rt.state.make.view.as_ref().expect(\"view\");\n assert_eq!(view.fields.edits.get(\"mk:0\").map(|e| e.text.clone()).as_deref(), Some(\"abc\"), \"what was typed is kept\");\n assert_eq!(view.fields.edits.get(\"mk:2\").map(|e| e.text.clone()).as_deref(), Some(\"v1\"), \"the tree's value wins\");\n press(&mut rt, \"mk:1\");\n until(&mut rt, \"the ticked event\", |_| last(&messages)[\"name\"] == \"ticked\");\n assert_eq!(last(&messages)[\"value\"], true);\n assert_eq!(last(&messages)[\"fields\"][\"q\"], \"abc\");\n}\n\n#[test]\nfn a_form_at_the_root_sends_every_field_it_holds() {\n let fake = Fake::start();\n let code = |_: &Value, _: &Value| {\n step(\n json!({}),\n json!({ \"tag\": \"form\", \"children\": [\n { \"tag\": \"input\", \"on\": \"typed\", \"props\": { \"name\": \"q\", \"ariaLabel\": \"Query\" } },\n { \"tag\": \"div\", \"children\": [{ \"tag\": \"input\", \"props\": { \"name\": \"deep\", \"value\": \"d\" } }] },\n { \"tag\": \"button\", \"on\": \"save\", \"children\": [\"Save\"] }\n ] }),\n )\n };\n let (mut rt, messages) = open(&fake, code, &[]);\n type_into(&mut rt, \"mk:0\", \"Hello\");\n until(&mut rt, \"the typed event\", |_| last(&messages)[\"name\"] == \"typed\");\n assert_eq!(last(&messages)[\"fields\"], json!({ \"q\": \"Hello\", \"deep\": \"d\" }), \"a watched field's form\");\n press(&mut rt, \"mk:2\");\n until(&mut rt, \"the save event\", |_| last(&messages)[\"name\"] == \"save\");\n assert_eq!(last(&messages)[\"fields\"], json!({ \"q\": \"Hello\", \"deep\": \"d\" }), \"a button's form\");\n}\n\n#[test]\nfn calls_are_made_only_for_listed_actions_and_their_results_come_back() {\n let fake = Fake::start();\n fake.with(|s| {\n s.call = Some(Box::new(|action, input| {\n if action == \"mk_demo.add\" {\n Ok(json!({ \"added\": input[\"n\"] }))\n } else {\n Err(json!({ \"_tag\": \"ActionFailed\", \"message\": \"no\" }))\n }\n }))\n });\n let code = |_: &Value, message: &Value| {\n let calls = if message[\"name\"] == \"go\" {\n json!([\n { \"id\": \"c1\", \"action\": \"mk_demo.add\", \"input\": { \"n\": 1 }, \"key\": \"k-1\" },\n { \"id\": \"c2\", \"action\": \"mk_demo.drop\", \"input\": {} },\n { \"id\": \"c3\", \"action\": \"mk_demo.add\", \"input\": null, \"key\": \"not a key!\" }\n ])\n } else {\n json!([])\n };\n json!({ \"state\": {}, \"calls\": calls, \"tree\": { \"tag\": \"button\", \"on\": \"go\", \"children\": [\"Go\"] } })\n };\n let (mut rt, messages) = open(&fake, code, &[\"mk_demo.add\"]);\n press(&mut rt, \"mk:r\");\n until(&mut rt, \"three results\", |_| {\n messages.lock().expect(\"m\").iter().filter(|m| m[\"type\"] == \"result\").count() == 3\n });\n let instance = rt.state.make.view.as_ref().map(|v| v.instance.clone()).expect(\"view\");\n let results: Vec<Value> = messages.lock().expect(\"m\").iter().filter(|m| m[\"type\"] == \"result\").cloned().collect();\n let by_id = |id: &str| results.iter().find(|m| m[\"id\"] == id).cloned().expect(id);\n assert_eq!(\n by_id(\"c1\"),\n json!({ \"type\": \"result\", \"id\": \"c1\", \"ok\": true, \"result\": { \"kind\": \"output\", \"output\": { \"added\": 1 } } })\n );\n assert_eq!(\n by_id(\"c2\"),\n json!({ \"type\": \"result\", \"id\": \"c2\", \"ok\": false, \"error\": { \"_tag\": \"Forbidden\", \"message\": \"The view may not call mk_demo.drop\" } })\n );\n assert_eq!(by_id(\"c3\")[\"ok\"], true);\n\n let calls = fake.seen().into_iter().filter(|r| r.path.starts_with(\"/client/v1/actions/mk_\")).collect::<Vec<_>>();\n assert_eq!(calls.len(), 2, \"the unlisted action made no request: {calls:?}\");\n assert!(calls.iter().all(|c| c.path == \"/client/v1/actions/mk_demo.add\"));\n // The two calls run concurrently, as on the web: find each by its input.\n let keyed = calls.iter().find(|c| c.body[\"input\"] == json!({ \"n\": 1 })).expect(\"c1\");\n assert_eq!(\n keyed.body[\"idempotencyKey\"],\n json!(format!(\"make-view:{instance}:k-1\")),\n \"the view's key, namespaced by the mount\"\n );\n let other = calls.iter().find(|c| c.body[\"input\"] == json!({})).expect(\"c3: a null input is sent as {}\");\n let fresh = other.body[\"idempotencyKey\"].as_str().expect(\"a key\");\n assert!(\n fresh.starts_with(&format!(\"make-view:{instance}:\"))\n && fresh.len() == format!(\"make-view:{instance}:\").len() + 36,\n \"{fresh}\"\n );\n}\n\n#[test]\nfn steps_run_one_at_a_time_each_from_the_last_state() {\n let fake = Fake::start();\n let code = |state: &Value, message: &Value| {\n let n = state.get(\"n\").and_then(Value::as_u64).unwrap_or(0);\n let n = if message.is_null() { 0 } else { n + 1 };\n step(json!({ \"n\": n }), json!({ \"tag\": \"button\", \"on\": \"inc\", \"children\": [format!(\"{n}\")] }))\n };\n let (mut rt, _) = open(&fake, code, &[]);\n for _ in 0..4 {\n assert!(rt.accessibility_action(\"mk:r\", rune::accesskit::Action::Click, None));\n }\n rt.frame(1.0 / 60.0);\n until(&mut rt, \"four more steps\", |s| s.make.view.as_ref().is_some_and(|v| v.steps == 5));\n let states: Vec<Value> = fake\n .requests_to(\"/client/v1/actions/make.renderView\")\n .iter()\n .map(|r| r.body[\"input\"][\"state\"].clone())\n .collect();\n assert_eq!(states, vec![Value::Null, json!({ \"n\": 0 }), json!({ \"n\": 1 }), json!({ \"n\": 2 }), json!({ \"n\": 3 })]);\n assert_eq!(rt.state.make.view.as_ref().map(|v| v.state.clone()), Some(json!({ \"n\": 4 })));\n}\n\n#[test]\nfn malformed_and_oversized_trees_stop_the_view() {\n let cases: Vec<(&str, Value)> = vec![\n (\"script\", json!({ \"tag\": \"script\", \"children\": [\"alert(1)\"] })),\n (\"img\", json!({ \"tag\": \"img\", \"props\": { \"src\": \"https://attacker.example/x\" } })),\n (\"not a tree\", json!({ \"nope\": true })),\n (\"too many nodes\", json!({ \"tag\": \"div\", \"children\": vec![json!(\"x\"); 5_000] })),\n (\"too deep\", (0..70).fold(json!(\"leaf\"), |inner, _| json!({ \"tag\": \"div\", \"children\": [inner] }))),\n ];\n for (name, tree) in cases {\n let fake = Fake::start();\n let messages: Messages = Arc::new(Mutex::new(Vec::new()));\n let seen = messages.clone();\n fake.with(|s| {\n s.view = Some(Box::new(move |_, m| {\n seen.lock().expect(\"m\").push(m.clone());\n json!({ \"state\": {}, \"calls\": [], \"tree\": tree })\n }))\n });\n let mut rt = signed_in(&fake);\n press(&mut rt, \"tab-make\");\n type_into(&mut rt, \"make-module\", \"mk_demo\");\n press(&mut rt, \"make-open\");\n until(&mut rt, name, |s| matches!(s.make.phase, Phase::Failed { .. }));\n assert!(rt.state.make.view.is_none(), \"{name}\");\n assert!(rt.find(\"make-status\").is_some(), \"{name}: the failure is shown\");\n assert!(rt.take_url_requests().is_empty(), \"{name}: nothing opened\");\n }\n}\n\n#[test]\nfn a_step_for_a_version_no_longer_installed_stops_the_view() {\n let fake = Fake::start();\n let (mut rt, _) =\n open(&fake, |_, _| step(json!({}), json!({ \"tag\": \"button\", \"on\": \"x\", \"children\": [\"X\"] })), &[]);\n fake.with(|s| s.view_version = \"2.0.0\".into());\n press(&mut rt, \"mk:r\");\n until(\n &mut rt,\n \"the refusal\",\n |s| matches!(&s.make.phase, Phase::Failed { message, .. } if message.contains(\"open the view again\")),\n );\n}\n\n#[test]\nfn an_organisation_switch_tears_the_view_down_and_drops_its_late_answers() {\n let fake = Fake::start();\n let (mut rt, messages) = open(&fake, |_, _| step(json!({}), json!({ \"tag\": \"p\", \"children\": [\"acme view\"] })), &[]);\n let mount = rt.state.make.current_mount();\n press(&mut rt, \"org-globex\");\n assert!(rt.state.make.view.is_none(), \"gone with the intent\");\n until(&mut rt, \"globex\", |s| s.model.greeting_texts().iter().any(|(_, t)| t == \"hello from globex\"));\n // A step's and a call's answer for the old mount change nothing and send nothing.\n let before = messages.lock().expect(\"m\").len();\n rt.state.make.stepped(mount, Ok(json!({ \"state\": {}, \"calls\": [], \"tree\": \"late\" })));\n rt.state.make.called(mount, \"c\".into(), Ok(json!({})));\n assert!(rt.state.make.view.is_none() && rt.state.make.outbox.is_empty());\n settle(&mut rt, 100);\n assert_eq!(messages.lock().expect(\"m\").len(), before);\n assert_eq!(rt.state.make.phase, Phase::Closed);\n}\n\n#[test]\nfn class_is_inert_and_style_is_held_to_its_subset() {\n let fake = Fake::start();\n let tree = json!({ \"tag\": \"div\", \"children\": [\n { \"tag\": \"p\", \"props\": { \"class\": \"bg-red-500 hidden\" }, \"children\": [\"classed\"] },\n { \"tag\": \"p\", \"children\": [\"plain\"] },\n { \"tag\": \"div\", \"props\": { \"style\": \"background-color: #ff0000; width: 120px; background-image: url(https://x.example/a)\" }, \"children\": [\"styled\"] },\n { \"tag\": \"div\", \"props\": { \"style\": \"display: none\" }, \"children\": [\"hidden\"] }\n ] });\n let (rt, _) = open(&fake, move |_, _| step(json!({}), tree.clone()), &[]);\n let els = rt.elements();\n let by_key = |k: &str| els.iter().find(|e| e.key.as_deref() == Some(k)).cloned();\n let (classed, plain) = (by_key(\"mk:0\").expect(\"classed\"), by_key(\"mk:1\").expect(\"plain\"));\n assert_eq!((classed.fill, classed.rect[3]), (plain.fill, plain.rect[3]), \"class changes nothing\");\n let styled = by_key(\"mk:2\").expect(\"styled\");\n assert!((styled.rect[2] - 120.0).abs() < 0.5, \"width: 120px → {}\", styled.rect[2]);\n assert!(styled.fill.r > 0.9 && styled.fill.g < 0.1, \"background-color drawn: {:?}\", styled.fill);\n assert!(by_key(\"mk:3\").is_none(), \"display: none draws nothing\");\n}\n",
258
+ "type": "registry:file",
259
+ "target": "desktop-rune/app/tests/make_view.rs"
260
+ },
261
+ {
262
+ "path": "app/desktop-rune/app/tests/notices.rs",
263
+ "content": "//! OS notifications for the person's notification records, while the app runs, over the fake `/client/v1`: the host\n//! follows `notifications.mine`, shows a new row once (the in-memory backend records it), nothing old or read; a\n//! click opens the record through the deep links; Approve and Reject decide through LocalClient with the person's\n//! generation and the chat SDK's keys; a context reset withdraws what was shown and its clicks do nothing.\n\nmod support;\n\nuse eloxiv_desktop_rune::chat::Decision;\nuse eloxiv_desktop_rune::links::{ViewEntry, ViewTable};\nuse eloxiv_desktop_rune::notices::{CONSENT_BODY, CONSENT_TITLE, Click, Notice};\nuse eloxiv_desktop_rune::ui::Screen;\nuse serde_json::{Value, json};\nuse support::*;\n\n/// When this test began (ms since the epoch, as the server's `createdAt`): rows are dated from it. Per test (each runs\n/// on a thread of its own), never per process: a test that starts minutes after the first one (a slow runner, few\n/// cores) would otherwise date its new rows before its own session's start, less the clock allowance, and see none shown.\nfn base() -> i64 {\n thread_local! {\n static BASE: i64 =\n std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).expect(\"after 1970\").as_millis() as i64;\n }\n BASE.with(|base| *base)\n}\n\n/// A notification row created `at` ms after the test began (negative: before).\nfn notification(id: &str, at: i64, category: &str, link: Option<(&str, &str, &str)>, org: &str) -> Value {\n let (module, entity, record) =\n link.map_or((Value::Null, Value::Null, Value::Null), |(m, e, r)| (json!(m), json!(e), json!(r)));\n json!({ \"id\": id, \"orgId\": org, \"recipientId\": \"u-alice\", \"category\": category, \"title\": format!(\"Title of {id}\"),\n \"body\": format!(\"Body of {id}\"), \"linkModule\": module, \"linkEntity\": entity, \"linkId\": record,\n \"createdAt\": base() + at, \"readAt\": null, \"dismissedAt\": null })\n}\n\nfn add(fake: &Fake, org: &str, row: Value) {\n fake.with(|s| {\n s.notifications.insert(0, (org.to_owned(), row));\n s.emit_rows();\n });\n}\n\nfn posted(rt: &rune::Runtime<eloxiv_desktop_rune::Ui>) -> Vec<Notice> {\n rt.state.host.notifier.memory_log().expect(\"the in-memory notifier\").posted()\n}\n\nfn withdrawn(rt: &rune::Runtime<eloxiv_desktop_rune::Ui>) -> Vec<String> {\n rt.state.host.notifier.memory_log().expect(\"the in-memory notifier\").withdrawn()\n}\n\nfn click(rt: &mut rune::Runtime<eloxiv_desktop_rune::Ui>, notice: &str, generation: i64, action: Option<Decision>) {\n rt.state.host.notifier.click_sink().send(Click { notice: notice.into(), generation, action, token: None });\n}\n\n/// A pending approval request someone else made, as `approvals.requests` has it (an older kernel's row: no title).\nfn pending_approval(id: &str, action: &str) -> Value {\n json!({ \"id\": id, \"requesterId\": \"u-ben\", \"action\": action, \"status\": \"pending\", \"createdAt\": 1 })\n}\n\n/// A waiting run of the person's agent in conversation `conversation` (before sign-in: the chat opens the latest\n/// conversation and follows its run), which will hold the call `consent` ([`hold_consent`]).\nfn waiting_run(fake: &Fake, conversation: &str, consent: &str) {\n let run = format!(\"r-{consent}\");\n fake.with(|s| {\n s.agent.conversations.insert(0, json!({ \"id\": conversation, \"title\": conversation }));\n s.agent\n .runs\n .insert(0, json!({ \"id\": run, \"conversationId\": conversation, \"status\": \"waiting\", \"createdAt\": 5 }));\n });\n}\n\n/// The followed run's `consent-required` event names `consent`: the person's agent holds a call for their consent.\nfn hold_consent(fake: &Fake, rt: &mut rune::Runtime<eloxiv_desktop_rune::Ui>, consent: &str) {\n let run = format!(\"r-{consent}\");\n until(rt, \"the run followed\", |s| s.model.chat.followed.as_ref().is_some_and(|f| f.run_id == run));\n until(rt, \"the follow request\", |_| {\n fake.requests_to(\"/client/v1/runs\").iter().any(|r| r.body[\"runId\"] == json!(run))\n });\n fake.with(|s| {\n s.run_event(\n &run,\n 1,\n \"consent-required\",\n json!({ \"consentId\": consent, \"action\": \"agent.moveResources\", \"title\": \"Move agent resources\" }),\n )\n });\n until(rt, \"the consent held\", |s| s.model.chat.consents.iter().any(|c| c.consent_id == consent));\n}\n\n/// Signed in, with the notifications' baseline in.\nfn watching(fake: &Fake) -> rune::Runtime<eloxiv_desktop_rune::Ui> {\n let mut rt = signed_in(fake);\n until(&mut rt, \"the notifications followed\", |s| s.model.notices.watching());\n rt\n}\n\n#[test]\nfn a_new_notification_is_shown_once_and_old_or_read_ones_never() {\n let fake = Fake::start();\n let mut read_before = notification(\"n-read-old\", 900, \"hello.greeted\", None, \"acme\");\n read_before[\"readAt\"] = json!(base() + 950);\n fake.with(|s| {\n s.notifications.push((\"acme\".into(), notification(\"n-old\", 1_000, \"hello.greeted\", None, \"acme\")));\n s.notifications.push((\"acme\".into(), read_before));\n });\n let mut rt = watching(&fake);\n assert!(\n fake.requests_to(\"/client/v1/subscriptions\").iter().any(|r| r.body[\"query\"] == json!(\"notifications.mine\")),\n \"the host follows the person's notifications\"\n );\n assert_eq!(\n rt.state.notifications(),\n json!({ \"shown\": \"while-running\", \"backend\": \"memory\", \"permission\": \"granted\" }),\n \"the app follows them and the backend shows them\"\n );\n settle(&mut rt, 50);\n assert!(posted(&rt).is_empty(), \"rows from before the watch began are not shown\");\n\n add(&fake, \"acme\", notification(\"n-new\", 2_000, \"hello.greeted\", None, \"acme\"));\n until(&mut rt, \"the new notification shown\", |s| !s.model.notices.shown().is_empty());\n let shown = posted(&rt);\n assert_eq!(shown.len(), 1);\n assert_eq!((shown[0].id.as_str(), shown[0].title.as_str()), (\"n-new\", \"Title of n-new\"));\n assert_eq!(shown[0].generation, rt.state.model.generation);\n\n // The same rows again (another change in the replica): shown once.\n fake.with(|s| s.emit_rows());\n settle(&mut rt, 50);\n // Read already, older than the baseline (synced late), dismissed: none shown.\n let mut read = notification(\"n-read\", 3_000, \"hello.greeted\", None, \"acme\");\n read[\"readAt\"] = json!(base() + 3_001);\n let mut dismissed = notification(\"n-dismissed\", 3_000, \"hello.greeted\", None, \"acme\");\n dismissed[\"dismissedAt\"] = json!(base() + 3_002);\n add(&fake, \"acme\", read);\n add(&fake, \"acme\", dismissed);\n add(&fake, \"acme\", notification(\"n-late\", 500, \"hello.greeted\", None, \"acme\"));\n // And one more new one, so the others had their chance to land.\n add(&fake, \"acme\", notification(\"n-next\", 4_000, \"hello.greeted\", None, \"acme\"));\n until(&mut rt, \"the next notification shown\", |s| s.model.notices.shown().len() == 2);\n assert_eq!(posted(&rt).iter().map(|n| n.id.as_str()).collect::<Vec<_>>(), [\"n-new\", \"n-next\"]);\n\n // Read elsewhere (the web shell): taken back out of the system's list.\n fake.with(|s| {\n for (_, r) in &mut s.notifications {\n if r[\"id\"] == json!(\"n-new\") {\n r[\"readAt\"] = json!(base() + 5_000);\n }\n }\n s.emit_rows();\n });\n until(&mut rt, \"the read notification withdrawn\", |s| s.model.notices.shown().len() == 1);\n assert_eq!(withdrawn(&rt), [\"n-new\"]);\n}\n\n#[test]\nfn a_click_opens_the_notifications_record_through_the_deep_links() {\n let fake = Fake::start();\n let mut rt = watching(&fake);\n rt.state.host.views = Some(\n ViewTable::new(vec![ViewEntry {\n id: \"hello.greetings\".into(),\n route: \"/hello\".into(),\n title: \"Greetings\".into(),\n module: Some(\"hello\".into()),\n entity: Some(\"greeting\".into()),\n }])\n .expect(\"as the test set it up\"),\n );\n rt.state.screen = Screen::Make;\n add(&fake, \"acme\", notification(\"n-g\", 2_000, \"hello.greeted\", Some((\"hello\", \"greeting\", \"g-acme-2\")), \"acme\"));\n until(&mut rt, \"the notification shown\", |s| !s.model.notices.shown().is_empty());\n let notice = rt.state.model.notices.shown()[0].clone();\n assert_eq!(\n rt.state.notice_link(&notice).as_deref(),\n Some(\"eloxiv://open/hello/g-acme-2?org=acme\"),\n \"the record in the view that shows its entity, in its organisation\"\n );\n\n let generation = rt.state.model.generation;\n click(&mut rt, \"n-g\", generation, None);\n until(&mut rt, \"the record opened\", |s| s.screen == Screen::Greetings);\n assert_eq!(rt.state.host.link_status.as_deref(), Some(\"Opened from a link: Greetings\"));\n assert_eq!(withdrawn(&rt), [\"n-g\"], \"a notification acted on leaves the list\");\n assert!(fake.with(|s| s.agent.decisions.is_empty()), \"a click only navigates\");\n assert!(rt.state.model.notices.shown().is_empty());\n\n // A click on a notification no longer shown does nothing.\n rt.state.screen = Screen::Make;\n click(&mut rt, \"n-g\", generation, None);\n settle(&mut rt, 50);\n assert_eq!(rt.state.screen, Screen::Make);\n}\n\n#[test]\nfn approve_and_reject_decide_with_the_chat_sdks_keys_and_the_current_generation() {\n let fake = Fake::start();\n fake.with(|s| {\n s.agent.approvals = vec![pending_approval(\"apr-1\", \"people.offboard\"), pending_approval(\"apr-2\", \"x.pay\")]\n });\n waiting_run(&fake, \"c-1\", \"cns-1\");\n let mut rt = watching(&fake);\n hold_consent(&fake, &mut rt, \"cns-1\");\n add(&fake, \"acme\", notification(\"n-plain\", 2_000, \"hello.greeted\", None, \"acme\"));\n add(\n &fake,\n \"acme\",\n notification(\"n-apr\", 2_001, \"approvals.requested\", Some((\"approvals\", \"request\", \"apr-1\")), \"acme\"),\n );\n add(\n &fake,\n \"acme\",\n notification(\"n-cns\", 2_002, \"consent.requested\", Some((\"consent\", \"request\", \"cns-1\")), \"acme\"),\n );\n add(\n &fake,\n \"acme\",\n notification(\"n-apr2\", 2_003, \"approvals.requested\", Some((\"approvals\", \"request\", \"apr-2\")), \"acme\"),\n );\n until(&mut rt, \"four notifications shown\", |s| s.model.notices.shown().len() == 4);\n let shown = posted(&rt);\n let by_id = |id: &str| shown.iter().find(|n| n.id == id).cloned().expect(\"shown\");\n // The action as people see it called: the title recorded with the request, never its id.\n assert_eq!(by_id(\"n-cns\").title, format!(\"{CONSENT_TITLE} Move agent resources\"), \"the request's words\");\n assert_eq!(by_id(\"n-cns\").body, CONSENT_BODY, \"a held call's input stays in the app\");\n assert!(by_id(\"n-apr\").decision.is_some() && by_id(\"n-plain\").decision.is_none());\n // A row with no title (an older kernel's): the action's readable name, still never its id.\n assert_eq!(by_id(\"n-apr\").body, \"Offboard (people)\", \"the request's words\");\n\n let generation = rt.state.model.generation;\n // A decision button on a notification that offers none decides nothing.\n click(&mut rt, \"n-plain\", generation, Some(Decision::Approve));\n click(&mut rt, \"n-apr\", generation, Some(Decision::Approve));\n click(&mut rt, \"n-cns\", generation, Some(Decision::Reject));\n until(&mut rt, \"both decisions made\", |_| fake.with(|s| s.agent.decisions.len() >= 2));\n settle(&mut rt, 50);\n // Each request runs on a thread of its own: in whichever order they arrived.\n let mut decisions = fake.with(|s| s.agent.decisions.clone());\n decisions.sort();\n assert_eq!(\n decisions,\n vec![\n (\"approvals.approve\".to_owned(), \"apr-1\".to_owned(), \"approval:apr-1:approve\".to_owned()),\n (\"consent.reject\".to_owned(), \"cns-1\".to_owned(), \"consent:cns-1:reject:\".to_owned()),\n ]\n );\n for path in [\"/client/v1/actions/approvals.approve\", \"/client/v1/actions/consent.reject\"] {\n let request = fake.requests_to(path).pop().expect(\"made\");\n assert!(request.authorized, \"through LocalClient with the host's secret\");\n assert_eq!(request.body[\"generation\"], json!(generation), \"made in the current generation\");\n }\n until(&mut rt, \"the answers landed\", |s| s.notice_decisions.is_empty());\n assert!(rt.state.notice.is_none(), \"{:?}\", rt.state.notice);\n\n // A click on an approval request's notification opens the agent's conversation, where its card is; it decides\n // nothing.\n rt.state.screen = Screen::Make;\n click(&mut rt, \"n-apr2\", generation, None);\n until(&mut rt, \"the conversation opened\", |s| s.screen == Screen::Chat);\n assert_eq!(fake.with(|s| s.agent.decisions.len()), 2);\n}\n\n#[test]\nfn buttons_show_only_for_requests_the_rows_say_the_person_can_decide() {\n let fake = Fake::start();\n fake.with(|s| s.agent.approvals = vec![pending_approval(\"apr-real\", \"people.offboard\")]);\n let mut rt = watching(&fake);\n // Through `notifications.notify`, anyone who can notify the person picks the category, title and link.\n let mut forged =\n notification(\"n-forged\", 2_000, \"approvals.requested\", Some((\"approvals\", \"request\", \"apr-none\")), \"acme\");\n forged[\"title\"] = json!(\"Your payroll is ready: approve it\");\n add(&fake, \"acme\", forged);\n let mut ordinary =\n notification(\"n-ordinary\", 2_001, \"hello.greeted\", Some((\"approvals\", \"request\", \"apr-real\")), \"acme\");\n ordinary[\"title\"] = json!(\"Approve this to get a gift card\");\n add(&fake, \"acme\", ordinary);\n let mut consent =\n notification(\"n-consent\", 2_002, \"consent.requested\", Some((\"consent\", \"request\", \"cns-none\")), \"acme\");\n consent[\"title\"] = json!(\"Allow everything\");\n add(&fake, \"acme\", consent);\n until(&mut rt, \"three notifications shown\", |s| s.model.notices.shown().len() == 3);\n settle(&mut rt, 50);\n let shown = posted(&rt);\n let last = |id: &str| shown.iter().rev().find(|n| n.id == id).cloned().expect(\"shown\");\n assert_eq!(last(\"n-forged\").decision, None, \"no such pending request: it only navigates\");\n assert_eq!(last(\"n-consent\").decision, None, \"no held call the person's run reports: it only navigates\");\n let ordinary = last(\"n-ordinary\");\n assert!(ordinary.decision.is_some(), \"the request is pending and the person may decide it\");\n assert!(!ordinary.title.contains(\"gift card\") && ordinary.body == \"Offboard (people)\", \"{ordinary:?}\");\n\n // A button on them anyway (another surface, an old notification) decides nothing.\n let generation = rt.state.model.generation;\n click(&mut rt, \"n-forged\", generation, Some(Decision::Approve));\n click(&mut rt, \"n-consent\", generation, Some(Decision::Approve));\n settle(&mut rt, 100);\n assert!(fake.with(|s| s.agent.decisions.is_empty()));\n\n // Decided elsewhere: the buttons go with the notification.\n fake.with(|s| {\n s.agent.approvals[0][\"status\"] = json!(\"approved\");\n s.emit_rows();\n });\n until(&mut rt, \"the decided request's notification withdrawn\", |s| s.model.notices.find(\"n-ordinary\").is_none());\n click(&mut rt, \"n-ordinary\", generation, Some(Decision::Approve));\n settle(&mut rt, 50);\n assert!(fake.with(|s| s.agent.decisions.is_empty()));\n}\n\n#[test]\nfn a_late_subscribe_answer_from_before_the_stream_reopened_does_not_replace_the_new_subscription() {\n let fake = Fake::start();\n fake.with(|s| s.hold_subscribe = Some(\"notifications.mine\".into()));\n let mut rt = signed_in(&fake);\n until(&mut rt, \"the first subscription asked\", |_| fake.with(|s| s.subscribe_held));\n let first = rt.state.model.notices.subscription.clone().expect(\"asked\");\n // The stream closes and opens again in the same generation: the host subscribes again, under a new id.\n fake.with(|s| {\n if let Some(sink) = s.sink.take() {\n let _ = sink.shutdown(std::net::Shutdown::Both);\n }\n });\n until(&mut rt, \"subscribed again\", |s| {\n s.model.notices.subscription.as_ref().is_some_and(|id| *id != first) && s.model.notices.watching()\n });\n let second = rt.state.model.notices.subscription.clone().expect(\"asked\");\n // Now the first answer lands: the subscription it names was ended with the stream.\n fake.with(|s| s.subscribe_held = false);\n until(&mut rt, \"the old subscription let go\", |_| {\n fake.requests_to(&format!(\"/client/v1/subscriptions/{first}\")).len() == 1\n });\n assert_eq!(rt.state.model.notices.subscription.as_deref(), Some(second.as_str()));\n add(&fake, \"acme\", notification(\"n-after\", 2_000, \"hello.greeted\", None, \"acme\"));\n until(&mut rt, \"the new subscription's row shown\", |s| s.model.notices.find(\"n-after\").is_some());\n}\n\nfn greeting_views() -> ViewTable {\n ViewTable::new(vec![ViewEntry {\n id: \"hello.greetings\".into(),\n route: \"/hello\".into(),\n title: \"Greetings\".into(),\n module: Some(\"hello\".into()),\n entity: Some(\"greeting\".into()),\n }])\n .expect(\"as the test set it up\")\n}\n\n#[test]\nfn clicks_do_nothing_from_the_moment_a_switch_or_sign_out_is_asked_for() {\n let fake = Fake::start();\n fake.with(|s| s.agent.approvals = vec![pending_approval(\"apr-1\", \"people.offboard\")]);\n let mut rt = watching(&fake);\n rt.state.host.views = Some(greeting_views());\n add(&fake, \"acme\", notification(\"n-g\", 2_000, \"hello.greeted\", Some((\"hello\", \"greeting\", \"g-acme-1\")), \"acme\"));\n add(\n &fake,\n \"acme\",\n notification(\"n-apr\", 2_001, \"approvals.requested\", Some((\"approvals\", \"request\", \"apr-1\")), \"acme\"),\n );\n until(&mut rt, \"two notifications shown, one with buttons\", |s| {\n s.model.notices.shown().len() == 2 && s.model.notices.find(\"n-apr\").is_some_and(|n| n.decision.is_some())\n });\n let acme = rt.state.model.generation;\n rt.state.screen = Screen::Make;\n\n // The daemon is slow to switch (a membership lookup): from the intent on, nothing of acme's is shown or clickable.\n fake.with(|s| s.hold_context = true);\n press(&mut rt, \"org-globex\");\n let mut gone = withdrawn(&rt);\n gone.sort();\n assert_eq!(gone, [\"n-apr\", \"n-g\"], \"withdrawn at the intent, before the daemon answers\");\n click(&mut rt, \"n-apr\", acme, Some(Decision::Approve));\n click(&mut rt, \"n-g\", acme, None);\n settle(&mut rt, 100);\n assert!(fake.with(|s| s.agent.decisions.is_empty()), \"no decision in the organisation being left\");\n assert_eq!(rt.state.host.pending_link, None, \"no link of the organisation being left waits\");\n fake.with(|s| s.hold_context = false);\n until(&mut rt, \"globex\", |s| s.model.generation > acme && s.model.usable());\n settle(&mut rt, 100);\n assert_eq!(rt.state.model.session.org_id(), Some(\"globex\"), \"an old click does not switch the person back\");\n assert_eq!(rt.state.screen, Screen::Make);\n assert!(fake.with(|s| s.agent.decisions.is_empty()));\n\n // Signing out: the same from the intent on, and no link survives to a later sign-in.\n until(&mut rt, \"globex's notifications followed\", |s| s.model.notices.watching());\n add(\n &fake,\n \"globex\",\n notification(\"n-x\", 3_000, \"hello.greeted\", Some((\"hello\", \"greeting\", \"g-globex-1\")), \"globex\"),\n );\n until(&mut rt, \"globex's notification shown\", |s| s.model.notices.find(\"n-x\").is_some());\n let globex = rt.state.model.generation;\n fake.with(|s| s.hold_context = true);\n press(&mut rt, \"sign-out\");\n assert!(withdrawn(&rt).contains(&\"n-x\".to_owned()));\n click(&mut rt, \"n-x\", globex, None);\n settle(&mut rt, 100);\n assert_eq!(rt.state.host.pending_link, None);\n fake.with(|s| s.hold_context = false);\n until(&mut rt, \"signed out\", |s| matches!(s.model.session, eloxiv_desktop_rune::model::Session::SignedOut));\n assert_eq!(rt.state.host.pending_link, None);\n}\n\n#[test]\nfn a_switch_that_fails_resumes_the_same_feed_without_showing_anything_again() {\n let fake = Fake::start();\n let mut rt = watching(&fake);\n add(&fake, \"acme\", notification(\"n-a\", 2_000, \"hello.greeted\", None, \"acme\"));\n until(&mut rt, \"shown\", |s| s.model.notices.find(\"n-a\").is_some());\n let generation = rt.state.model.generation;\n // An organisation the person does not belong to: refused, definitively.\n rt.state.select_org(\"initech\");\n assert!(rt.state.model.notices.shown().is_empty(), \"withdrawn at the intent\");\n until(&mut rt, \"the switch refused\", |s| s.busy.is_none());\n assert_eq!(rt.state.model.generation, generation);\n add(&fake, \"acme\", notification(\"n-b\", 3_000, \"hello.greeted\", None, \"acme\"));\n until(&mut rt, \"the next one shown\", |s| s.model.notices.find(\"n-b\").is_some());\n assert_eq!(posted(&rt).iter().map(|n| n.id.as_str()).collect::<Vec<_>>(), [\"n-a\", \"n-b\"], \"n-a is not shown again\");\n}\n\n#[test]\nfn a_request_is_decided_once_whether_from_the_chat_or_the_notification() {\n let fake = Fake::start();\n fake.with(|s| {\n s.agent.approvals = vec![pending_approval(\"apr-1\", \"people.offboard\"), pending_approval(\"apr-2\", \"x.pay\")]\n });\n let mut rt = watching(&fake);\n for (id, request) in [(\"n-1\", \"apr-1\"), (\"n-2\", \"apr-2\")] {\n add(\n &fake,\n \"acme\",\n notification(id, 2_000, \"approvals.requested\", Some((\"approvals\", \"request\", request)), \"acme\"),\n );\n }\n until(&mut rt, \"both offered\", |s| s.model.notices.shown().iter().filter(|n| n.decision.is_some()).count() == 2);\n let generation = rt.state.model.generation;\n fake.with(|s| s.hold_decisions = true);\n\n // The chat's card first: the notification's buttons go at once, and a click on one still delivered does nothing.\n rt.state.decide_approval(\"apr-1\", Decision::Approve);\n assert!(rt.state.model.notices.find(\"n-1\").is_none(), \"withdrawn when the chat started deciding\");\n click(&mut rt, \"n-1\", generation, Some(Decision::Reject));\n // The notification first: the chat's card cannot decide it again while it is on its way.\n click(&mut rt, \"n-2\", generation, Some(Decision::Approve));\n until(&mut rt, \"the notification's decision on its way\", |s| s.model.chat.deciding.iter().any(|d| d == \"apr-2\"));\n rt.state.decide_approval(\"apr-2\", Decision::Reject);\n rt.state.decide_approval(\"apr-1\", Decision::Reject);\n settle(&mut rt, 100);\n fake.with(|s| s.hold_decisions = false);\n until(&mut rt, \"the answers\", |s| s.model.chat.deciding.is_empty());\n settle(&mut rt, 100);\n let mut decisions = fake.with(|s| s.agent.decisions.clone());\n decisions.sort();\n assert_eq!(\n decisions,\n vec![\n (\"approvals.approve\".to_owned(), \"apr-1\".to_owned(), \"approval:apr-1:approve\".to_owned()),\n (\"approvals.approve\".to_owned(), \"apr-2\".to_owned(), \"approval:apr-2:approve\".to_owned()),\n ]\n );\n assert!(rt.state.model.notices.shown().is_empty(), \"decided: nothing offers them again\");\n}\n\n#[test]\nfn a_row_from_before_the_session_that_syncs_late_is_not_shown_even_after_an_empty_baseline() {\n let fake = Fake::start();\n let mut rt = watching(&fake);\n // Created ten minutes before the app started following, synced only now (the baseline was empty).\n add(&fake, \"acme\", notification(\"n-stale\", -600_000, \"hello.greeted\", None, \"acme\"));\n add(&fake, \"acme\", notification(\"n-new\", 2_000, \"hello.greeted\", None, \"acme\"));\n until(&mut rt, \"the new one shown\", |s| s.model.notices.find(\"n-new\").is_some());\n assert_eq!(posted(&rt).iter().map(|n| n.id.as_str()).collect::<Vec<_>>(), [\"n-new\"]);\n}\n\n#[test]\nfn a_notification_shown_once_is_not_shown_again_after_a_switch_away_and_back() {\n let fake = Fake::start();\n let mut rt = watching(&fake);\n add(&fake, \"acme\", notification(\"n-a\", 2_000, \"hello.greeted\", None, \"acme\"));\n until(&mut rt, \"shown\", |s| s.model.notices.find(\"n-a\").is_some());\n // Not in acme's rows for a while (a replica catching up), across a switch to globex and back.\n let row = fake.with(|s| s.notifications.remove(0));\n for org in [\"org-globex\", \"org-acme\"] {\n let before = rt.state.model.generation;\n press(&mut rt, org);\n until(&mut rt, \"switched\", |s| s.model.generation > before && s.model.usable() && s.model.notices.watching());\n }\n fake.with(|s| {\n s.notifications.insert(0, row);\n s.emit_rows();\n });\n add(&fake, \"acme\", notification(\"n-b\", 4_000, \"hello.greeted\", None, \"acme\"));\n until(&mut rt, \"the next one shown\", |s| s.model.notices.find(\"n-b\").is_some());\n assert_eq!(posted(&rt).iter().map(|n| n.id.as_str()).collect::<Vec<_>>(), [\"n-a\", \"n-b\"]);\n}\n\n#[test]\nfn a_click_opens_the_named_greeting_among_the_others() {\n let fake = Fake::start();\n let mut rt = watching(&fake);\n rt.state.host.views = Some(greeting_views());\n rt.state.screen = Screen::Make;\n add(&fake, \"acme\", notification(\"n-g\", 2_000, \"hello.greeted\", Some((\"hello\", \"greeting\", \"g-acme-2\")), \"acme\"));\n until(&mut rt, \"shown\", |s| s.model.notices.find(\"n-g\").is_some());\n let generation = rt.state.model.generation;\n click(&mut rt, \"n-g\", generation, None);\n until(&mut rt, \"the greetings\", |s| s.screen == Screen::Greetings);\n settle(&mut rt, 20);\n assert!(has_state(&rt, \"greeting-g-acme-2\", \"selected\"), \"the notification's greeting is the one selected\");\n assert!(!has_state(&rt, \"greeting-g-acme-1\", \"selected\"));\n}\n\n#[test]\nfn a_consent_click_opens_the_conversation_whose_run_holds_it() {\n let fake = Fake::start();\n // The latest conversation is shown; the call waits in another one's run.\n waiting_run(&fake, \"c-other\", \"cns-2\");\n fake.with(|s| {\n s.agent.conversations.insert(0, json!({ \"id\": \"c-shown\", \"title\": \"Shown\" }));\n s.run_event(\"r-cns-2\", 1, \"consent-required\", json!({ \"consentId\": \"cns-2\", \"action\": \"agent.moveResources\" }));\n });\n let mut rt = watching(&fake);\n until(&mut rt, \"the latest conversation shown\", |s| s.model.chat.conversation_id.as_deref() == Some(\"c-shown\"));\n rt.state.screen = Screen::Make;\n add(\n &fake,\n \"acme\",\n notification(\"n-cns\", 2_000, \"consent.requested\", Some((\"consent\", \"request\", \"cns-2\")), \"acme\"),\n );\n until(&mut rt, \"shown\", |s| s.model.notices.find(\"n-cns\").is_some());\n let generation = rt.state.model.generation;\n click(&mut rt, \"n-cns\", generation, None);\n until(&mut rt, \"the conversation\", |s| s.screen == Screen::Chat);\n assert_eq!(rt.state.model.chat.conversation_id.as_deref(), Some(\"c-other\"));\n until(&mut rt, \"its card\", |s| s.model.chat.consents.iter().any(|c| c.consent_id == \"cns-2\"));\n settle(&mut rt, 20);\n assert!(rt.find(\"consent-cns-2\").is_some(), \"the request's card is on screen\");\n}\n\n#[test]\nfn a_click_before_the_apps_views_are_known_opens_its_record_once_they_are() {\n let fake = Fake::start();\n let mut rt = watching(&fake);\n rt.state.host.views = None;\n rt.state.screen = Screen::Make;\n add(&fake, \"acme\", notification(\"n-g\", 2_000, \"hello.greeted\", Some((\"hello\", \"greeting\", \"g-acme-2\")), \"acme\"));\n until(&mut rt, \"shown\", |s| s.model.notices.find(\"n-g\").is_some());\n let generation = rt.state.model.generation;\n click(&mut rt, \"n-g\", generation, None);\n settle(&mut rt, 50);\n assert_eq!(rt.state.screen, Screen::Make, \"waiting for the views\");\n rt.state.host.views = Some(greeting_views());\n until(&mut rt, \"the greeting opened\", |s| s.screen == Screen::Greetings);\n}\n\n#[test]\nfn a_slow_notification_service_does_not_hold_the_window_and_the_watch_starts_once_it_answers() {\n let fake = Fake::start();\n let started = std::time::Instant::now();\n let mut rt = eloxiv_desktop_rune::app_with(fake.url.clone(), TOKEN.into(), None, || {\n let mut host = eloxiv_desktop_rune::services::HostServices::default();\n // The service takes 1.5 s to say who it is.\n host.notifier_ready_after(std::time::Duration::from_millis(1_500));\n host\n })\n .headless_runtime((900.0, 700.0), rune::Env::new(false, 1.0));\n rt.frame(0.0);\n assert!(started.elapsed() < std::time::Duration::from_millis(1_000), \"the first frame did not wait for it\");\n assert!(!rt.state.host.notifier.can_post());\n until(&mut rt, \"the sign-in screen\", |s| matches!(s.model.session, eloxiv_desktop_rune::model::Session::SignedOut));\n press(&mut rt, \"sign-in\");\n until(&mut rt, \"the browser opened\", |s| s.sign_in_url.is_some());\n fake.with(State::complete_sign_in);\n until(&mut rt, \"signed in\", |s| s.model.usable());\n let followed =\n || fake.requests_to(\"/client/v1/subscriptions\").iter().any(|r| r.body[\"query\"] == json!(\"notifications.mine\"));\n assert!(!followed(), \"nothing to show them with yet\");\n until(&mut rt, \"the notifications followed once the service answered\", |s| s.model.notices.watching());\n assert!(followed());\n add(&fake, \"acme\", notification(\"n-a\", 2_000, \"hello.greeted\", None, \"acme\"));\n until(&mut rt, \"shown\", |s| s.model.notices.find(\"n-a\").is_some());\n}\n\n#[test]\nfn a_context_reset_withdraws_what_was_shown_and_its_clicks_do_nothing() {\n let fake = Fake::start();\n fake.with(|s| {\n s.notifications.push((\"globex\".into(), notification(\"n-globex-old\", 1_000, \"hello.greeted\", None, \"globex\")))\n });\n let mut rt = watching(&fake);\n add(&fake, \"acme\", notification(\"n-a\", 2_000, \"hello.greeted\", None, \"acme\"));\n add(\n &fake,\n \"acme\",\n notification(\"n-apr\", 2_001, \"approvals.requested\", Some((\"approvals\", \"request\", \"apr-1\")), \"acme\"),\n );\n until(&mut rt, \"two notifications shown\", |s| s.model.notices.shown().len() == 2);\n let old = rt.state.model.generation;\n\n press(&mut rt, \"org-globex\");\n until(&mut rt, \"globex\", |s| s.model.generation > old && s.model.usable());\n let mut gone = withdrawn(&rt);\n gone.sort();\n assert_eq!(gone, [\"n-a\", \"n-apr\"], \"everything of the generation before is withdrawn\");\n assert!(rt.state.model.notices.shown().is_empty());\n\n // Clicks and buttons on them (the system may still deliver one) do nothing.\n rt.state.screen = Screen::Make;\n click(&mut rt, \"n-apr\", old, Some(Decision::Approve));\n click(&mut rt, \"n-a\", old, None);\n settle(&mut rt, 100);\n assert!(fake.with(|s| s.agent.decisions.is_empty()));\n assert_eq!(rt.state.screen, Screen::Make);\n\n // The new generation has its own baseline: globex's old row is not shown, a new one is.\n until(&mut rt, \"globex's notifications followed\", |s| s.model.notices.watching());\n add(&fake, \"globex\", notification(\"n-globex-new\", 3_000, \"hello.greeted\", None, \"globex\"));\n until(&mut rt, \"globex's new notification\", |s| !s.model.notices.shown().is_empty());\n let last = posted(&rt).pop().expect(\"shown\");\n assert_eq!((last.id.as_str(), last.org_id.as_str()), (\"n-globex-new\", \"globex\"));\n assert_eq!(last.generation, rt.state.model.generation);\n assert_eq!(posted(&rt).len(), 3);\n\n // Signing out withdraws it too.\n press(&mut rt, \"sign-out\");\n until(&mut rt, \"signed out\", |s| s.model.notices.shown().is_empty());\n assert!(withdrawn(&rt).contains(&\"n-globex-new\".to_owned()));\n}\n",
264
+ "type": "registry:file",
265
+ "target": "desktop-rune/app/tests/notices.rs"
266
+ },
267
+ {
268
+ "path": "app/desktop-rune/app/tests/rtl_a11y.rs",
269
+ "content": "//! Right to left (Rune's `El::dir`: rows, alignment and padding mirror), light and dark, and the accessibility\n//! tree: every control on every screen has a role and a name.\n\nmod support;\n\nuse eloxiv_desktop_rune::model::Session;\nuse serde_json::{Value, json};\nuse support::*;\n\nconst CONTROLS: &[&str] = &[\n \"button\",\n \"link\",\n \"check-box\",\n \"radio-button\",\n \"switch\",\n \"slider\",\n \"text-input\",\n \"multiline-text-input\",\n \"list-box\",\n \"list-box-option\",\n \"radio-group\",\n \"tab-list\",\n \"combo-box\",\n];\n\nfn unnamed_controls(rt: &rune::Runtime<eloxiv_desktop_rune::Ui>) -> Vec<Value> {\n a11y_nodes(rt)\n .into_iter()\n .filter(|n| CONTROLS.contains(&n[\"role\"].as_str().unwrap_or(\"\")))\n .filter(|n| n[\"name\"].as_str().is_none_or(|s| s.trim().is_empty()))\n .collect()\n}\n\nfn x_of(rt: &rune::Runtime<eloxiv_desktop_rune::Ui>, key: &str) -> f32 {\n rt.find(key).unwrap_or_else(|| panic!(\"{key} is drawn\")).0\n}\n\nfn rect(rt: &rune::Runtime<eloxiv_desktop_rune::Ui>, key: &str) -> [f32; 4] {\n rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!(\"{key}\")).rect\n}\n\n#[test]\nfn right_to_left_mirrors_the_window() {\n let fake = Fake::start();\n let mut rt = signed_in(&fake);\n rt.settle_all();\n assert!(x_of(&rt, \"app-title\") < x_of(&rt, \"theme-system\"), \"left to right: the title leads at the left\");\n assert!(x_of(&rt, \"org-acme\") < x_of(&rt, \"org-globex\"));\n assert!(!has_state(&rt, \"dir-rtl\", \"checked\"));\n\n press(&mut rt, \"dir-rtl\");\n rt.frame(1.0 / 60.0);\n rt.settle_all();\n rt.frame(0.0);\n assert!(has_state(&rt, \"dir-rtl\", \"checked\"));\n assert!(x_of(&rt, \"app-title\") > x_of(&rt, \"theme-system\"), \"right to left: the title leads at the right\");\n assert!(x_of(&rt, \"org-acme\") > x_of(&rt, \"org-globex\"), \"the organisations' order mirrors\");\n}\n\n#[test]\nfn a_make_views_physical_sides_stay_physical_in_right_to_left() {\n let fake = Fake::start();\n fake.with(|s| {\n s.view = Some(Box::new(|_, _| {\n json!({ \"state\": {}, \"calls\": [], \"tree\": { \"tag\": \"div\", \"props\": { \"style\": \"padding-left: 40px; width: 300px\" },\n \"children\": [{ \"tag\": \"div\", \"props\": { \"style\": \"width: 50px; height: 10px; background-color: #00f\" } }] } })\n }))\n });\n let mut rt = signed_in(&fake);\n press(&mut rt, \"tab-make\");\n type_into(&mut rt, \"make-module\", \"mk_demo\");\n press(&mut rt, \"make-open\");\n until(&mut rt, \"the view\", |s| s.make.view.as_ref().is_some_and(|v| v.steps >= 1));\n rt.settle_all();\n let (outer, inner) = (rect(&rt, \"mk:r\"), rect(&rt, \"mk:0\"));\n assert!((inner[0] - outer[0] - 40.0).abs() < 1.0, \"LTR: 40 pt from the left: {outer:?} {inner:?}\");\n\n press(&mut rt, \"dir-rtl\");\n rt.frame(1.0 / 60.0);\n rt.settle_all();\n rt.frame(0.0);\n let (outer, inner) = (rect(&rt, \"mk:r\"), rect(&rt, \"mk:0\"));\n // `padding-left` is CSS's physical left: in a right-to-left view it is still the left, so the child, at the\n // start (the right), keeps clear of nothing on the right and 40 pt on the left.\n let right_gap = (outer[0] + outer[2]) - (inner[0] + inner[2]);\n assert!(right_gap.abs() < 1.0, \"RTL: the child starts at the right: {outer:?} {inner:?}\");\n assert!(inner[0] - outer[0] >= 40.0 - 1.0);\n}\n\n#[test]\nfn light_and_dark_change_the_window() {\n let fake = Fake::start();\n let mut rt = runtime(&fake);\n until(&mut rt, \"signed out\", |s| matches!(s.model.session, Session::SignedOut));\n let fill = |rt: &rune::Runtime<eloxiv_desktop_rune::Ui>| {\n rt.elements().into_iter().find(|e| e.key.as_deref() == Some(\"window\")).map(|e| e.fill).expect(\"window\")\n };\n press(&mut rt, \"theme-light\");\n rt.settle_all();\n rt.frame(0.0);\n let light = fill(&rt);\n press(&mut rt, \"theme-dark\");\n rt.settle_all();\n rt.frame(0.0);\n let dark = fill(&rt);\n assert!(light.luminance() > dark.luminance() + 0.3, \"{light:?} {dark:?}\");\n assert!(has_state(&rt, \"theme-dark\", \"checked\") && !has_state(&rt, \"theme-light\", \"checked\"));\n}\n\n#[test]\nfn every_control_on_every_screen_is_named() {\n let fake = Fake::start();\n let mut rt = runtime(&fake);\n until(&mut rt, \"signed out\", |s| matches!(s.model.session, Session::SignedOut));\n assert_eq!(unnamed_controls(&rt), Vec::<Value>::new(), \"sign-in\");\n assert_eq!(\n a11y(&rt, \"sign-in\").and_then(|n| n[\"name\"].as_str().map(str::to_owned)).as_deref(),\n Some(\"Sign in with the browser\")\n );\n\n press(&mut rt, \"sign-in\");\n until(&mut rt, \"waiting\", |s| s.sign_in_url.is_some());\n fake.with(State::complete_sign_in);\n until(&mut rt, \"the greetings\", |s| s.model.list.rows.len() == 2);\n type_into(&mut rt, \"greeting-input\", \"named\");\n press(&mut rt, \"greet\");\n until(&mut rt, \"a write\", |s| !s.model.writes.is_empty());\n assert_eq!(unnamed_controls(&rt), Vec::<Value>::new(), \"greetings\");\n let field = a11y(&rt, \"greeting-input\").expect(\"the field\");\n assert_eq!((field[\"role\"].as_str(), field[\"name\"].as_str()), (Some(\"text-input\"), Some(\"Greeting\")));\n\n fake.with(|s| {\n s.view = Some(Box::new(|_, _| {\n json!({ \"state\": {}, \"calls\": [], \"tree\": { \"tag\": \"form\", \"children\": [\n { \"tag\": \"label\", \"children\": [\"Your name\", { \"tag\": \"input\", \"props\": { \"name\": \"who\" } }] },\n { \"tag\": \"input\", \"props\": { \"name\": \"plain\" } },\n { \"tag\": \"input\", \"props\": { \"type\": \"checkbox\", \"name\": \"ok\" } },\n { \"tag\": \"input\", \"props\": { \"type\": \"radio\", \"name\": \"pick\", \"value\": \"a\" } },\n { \"tag\": \"input\", \"props\": { \"type\": \"range\", \"name\": \"amount\" } },\n { \"tag\": \"textarea\", \"props\": { \"placeholder\": \"Notes\" } },\n { \"tag\": \"select\", \"props\": { \"name\": \"kind\" }, \"children\": [{ \"tag\": \"option\", \"children\": [\"One\"] }] },\n { \"tag\": \"button\", \"on\": \"x\" },\n { \"tag\": \"link\", \"on\": \"y\", \"children\": [\"More\"] }\n ] } })\n }))\n });\n press(&mut rt, \"tab-make\");\n type_into(&mut rt, \"make-module\", \"mk_demo\");\n press(&mut rt, \"make-open\");\n until(&mut rt, \"the view\", |s| s.make.view.as_ref().is_some_and(|v| v.steps >= 1));\n assert_eq!(unnamed_controls(&rt), Vec::<Value>::new(), \"a MAKE view whose fields have no labels of their own\");\n let name = |k: &str| a11y(&rt, k).and_then(|n| n[\"name\"].as_str().map(str::to_owned)).unwrap_or_default();\n assert_eq!(name(\"mk:0.1\"), \"Your name\", \"a field inside a label is named by it\");\n assert_eq!(name(\"mk:1\"), \"plain\", \"else by its name\");\n assert_eq!(name(\"mk:5\"), \"Notes\", \"or its placeholder\");\n assert_eq!(name(\"mk:7\"), \"Button\", \"a button with no text still has a name\");\n assert_eq!(name(\"make-view\"), \"Demo view\", \"the view is a group named by its title\");\n}\n\n#[test]\nfn the_chat_screen_names_every_control_and_mirrors_in_right_to_left() {\n let fake = Fake::start();\n fake.with(|s| {\n s.agent.approvals = vec![\n json!({ \"id\": \"a1\", \"requesterId\": \"u-ben\", \"action\": \"people.offboard\", \"status\": \"pending\", \"createdAt\": 1 }),\n ]\n });\n let mut rt = signed_in(&fake);\n press(&mut rt, \"tab-chat\");\n until(&mut rt, \"the chat\", |s| s.model.chat.conversations.is_some() && !s.model.chat.approvals.is_empty());\n type_into(&mut rt, \"chat-input\", \"مرحبا، رتّب ملاحظاتي\");\n press(&mut rt, \"chat-send\");\n until(&mut rt, \"the run followed\", |s| s.model.chat.followed.is_some());\n let run = fake.with(|s| s.agent.runs[0][\"id\"].as_str().map(str::to_owned)).expect(\"a run\");\n fake.with(|s| {\n s.run_event(&run, 1, \"consent-required\", json!({ \"consentId\": \"k1\", \"action\": \"agent.moveResources\" }));\n s.run_event(&run, -1, \"text-delta\", json!({ \"delta\": \"Working on it\", \"step\": 0, \"attempt\": \"a\" }));\n });\n until(&mut rt, \"the prompt and the streamed text\", |s| {\n !s.model.chat.consents.is_empty() && s.model.chat.transcript().iter().any(|e| e.live)\n });\n assert_eq!(unnamed_controls(&rt), Vec::<Value>::new(), \"the chat\");\n let role = |k: &str| a11y(&rt, k).and_then(|n| n[\"role\"].as_str().map(str::to_owned)).unwrap_or_default();\n assert_eq!(role(\"chat-input\"), \"text-input\");\n assert_eq!(role(\"chat-transcript\"), \"list\");\n assert_eq!(role(\"consent-approve-k1\"), \"button\");\n assert_eq!(role(\"approval-approve-a1\"), \"button\");\n assert_eq!(role(\"chat-working\"), \"status\");\n\n rt.settle_all();\n assert!(x_of(&rt, \"chat-input\") < x_of(&rt, \"chat-send\"), \"left to right: the field, then Send\");\n press(&mut rt, \"dir-rtl\");\n rt.frame(1.0 / 60.0);\n rt.settle_all();\n rt.frame(0.0);\n assert!(x_of(&rt, \"chat-input\") > x_of(&rt, \"chat-send\"), \"right to left: Send at the left\");\n let (field, send) = (rect(&rt, \"chat-input\"), rect(&rt, \"chat-send\"));\n assert!(field[0] >= send[0] + send[2], \"the field does not run under Send: {field:?} {send:?}\");\n assert!(x_of(&rt, \"consent-approve-k1\") > x_of(&rt, \"consent-reject-k1\"), \"the prompt's answers mirror\");\n}\n",
270
+ "type": "registry:file",
271
+ "target": "desktop-rune/app/tests/rtl_a11y.rs"
272
+ },
273
+ {
274
+ "path": "app/desktop-rune/app/tests/screens.rs",
275
+ "content": "//! The screens against a fake `/client/v1` (tests/support): Rune's headless Runtime, no window, no GPU. The app\n//! is the real one (`eloxiv_desktop_rune::app`): its worker threads make real HTTP requests and read a real SSE\n//! stream.\n\nmod support;\n\nuse eloxiv_desktop_rune::model::Session;\nuse eloxiv_local_client::WritePhase;\nuse serde_json::json;\nuse support::*;\n\n#[test]\nfn sign_in_opens_the_system_browser_and_shows_the_live_list() {\n let fake = Fake::start();\n let mut rt = runtime(&fake);\n until(&mut rt, \"the sign-in screen\", |s| matches!(s.model.session, Session::SignedOut));\n assert!(rt.find(\"sign-in\").is_some(), \"the sign-in button is shown\");\n assert!(rt.take_url_requests().is_empty());\n\n press(&mut rt, \"sign-in\");\n until(&mut rt, \"the browser opened\", |s| s.sign_in_url.is_some());\n assert_eq!(rt.take_url_requests(), vec![\"http://127.0.0.1:9/sign-in?state=st-1\".to_owned()]);\n assert!(rt.find(\"sign-in-waiting\").is_some(), \"waiting for the browser\");\n\n // The browser finishes: the daemon's callback redeems the code and the session event follows.\n fake.with(State::complete_sign_in);\n until(&mut rt, \"the greetings\", |s| s.model.list.rows.len() == 2);\n let texts: Vec<String> = rt.state.model.greeting_texts().into_iter().map(|(_, t)| t).collect();\n assert_eq!(texts, [\"hello from acme\", \"welcome to acme\"]);\n assert!(rt.find(\"greeting-g-acme-1\").is_some());\n assert_eq!(\n a11y(&rt, \"user\").and_then(|n| n[\"name\"].as_str().map(str::to_owned)).as_deref(),\n Some(\"Alice (alice@example.com)\")\n );\n\n // Every request but /health carried the host token; the stream was opened once.\n let seen = fake.seen();\n assert!(seen.iter().filter(|r| r.path != \"/health\").all(|r| r.authorized), \"{seen:?}\");\n assert_eq!(seen.iter().filter(|r| r.path == \"/client/v1/events\").count(), 1);\n assert_eq!(seen.first().map(|r| r.path.as_str()), Some(\"/health\"), \"health is waited for first\");\n}\n\n#[test]\nfn the_session_comes_only_from_the_stream() {\n // A separate `GET /session` answered late could overwrite a newer session (another organisation, or signed\n // in again after a sign-out); the stream's first event is the current session, so nothing else is read.\n let fake = Fake::start();\n let mut rt = signed_in(&fake);\n press(&mut rt, \"org-globex\");\n until(&mut rt, \"globex selected\", |s| s.model.session.org_id() == Some(\"globex\"));\n press(&mut rt, \"sign-out\");\n until(&mut rt, \"signed out\", |s| matches!(s.model.session, Session::SignedOut));\n assert!(fake.requests_to(\"/client/v1/session\").is_empty(), \"{:?}\", fake.seen());\n}\n\n#[test]\nfn an_optimistic_write_is_shown_and_confirmed() {\n let fake = Fake::start();\n let mut rt = signed_in(&fake);\n type_into(&mut rt, \"greeting-input\", \"hi from rune\");\n press(&mut rt, \"greet\");\n until(&mut rt, \"the write confirmed\", |s| {\n s.model.writes.first().is_some_and(|w| w.phase == Some(WritePhase::Confirmed))\n });\n assert!(rt.state.model.greeting_texts().iter().any(|(_, t)| t == \"hi from rune\"));\n assert_eq!(rt.state.greeting.text, \"\", \"the field is emptied once posted\");\n let write = &fake.requests_to(\"/client/v1/writes\")[0];\n assert_eq!(write.body[\"mutator\"], \"hello.greet\");\n assert_eq!(write.body[\"input\"], json!({ \"message\": \"hi from rune\" }));\n let id = rt.state.model.writes[0].id.clone();\n assert_eq!(write.body[\"id\"], json!(id), \"the host chose the write's id\");\n let label = a11y(&rt, &format!(\"write-{id}\")).and_then(|n| n[\"name\"].as_str().map(str::to_owned));\n assert_eq!(label.as_deref(), Some(\"hi from rune: Confirmed\"));\n}\n\n#[test]\nfn a_refused_write_is_shown_then_rolled_back_with_its_typed_error() {\n let fake = Fake::start();\n let mut rt = signed_in(&fake);\n fake.with(|s| s.hold_writes = true);\n press(&mut rt, \"farewell\");\n until(&mut rt, \"the prediction\", |s| s.model.greeting_texts().iter().any(|(_, t)| t == \"goodbye, everyone\"));\n assert_eq!(rt.state.model.writes[0].phase, Some(WritePhase::Predicted));\n let id = rt.state.model.writes[0].id.clone();\n\n settle_write(&fake.state, &id, \"goodbye, everyone\");\n until(&mut rt, \"the rejection\", |s| s.model.writes[0].phase == Some(WritePhase::Rejected));\n assert!(!rt.state.model.greeting_texts().iter().any(|(_, t)| t == \"goodbye, everyone\"), \"rolled back\");\n assert_eq!(rt.state.model.writes[0].error, Some((\"Forbidden\".into(), \"farewells are not allowed\".into())));\n let label = a11y(&rt, &format!(\"write-{id}\")).and_then(|n| n[\"name\"].as_str().map(str::to_owned));\n assert_eq!(label.as_deref(), Some(\"goodbye, everyone: Refused: You don't have permission to post this.\"));\n}\n\n#[test]\nfn switching_organisation_shows_nothing_of_the_old_one() {\n let fake = Fake::start();\n let mut rt = signed_in(&fake);\n let old_generation = rt.state.model.generation;\n let old_subscription = rt.state.model.list.subscription.clone().expect(\"subscribed\");\n assert!(has_state(&rt, \"org-acme\", \"checked\"));\n\n press(&mut rt, \"org-globex\");\n // From the intent on: no row of acme.\n assert!(rt.state.model.list.rows.is_empty(), \"the old rows go with the intent\");\n until(&mut rt, \"globex's rows\", |s| s.model.greeting_texts().iter().any(|(_, t)| t == \"hello from globex\"));\n assert!(rt.state.model.generation > old_generation);\n\n // A late snapshot and write event of the old generation change nothing.\n fake.with(|s| {\n s.emit(json!({ \"type\": \"rows\", \"subscription\": old_subscription, \"generation\": old_generation,\n \"status\": \"complete\", \"rows\": [{ \"id\": \"late\", \"message\": \"late acme row\" }] }));\n s.emit(json!({ \"type\": \"write\", \"id\": \"w-old\", \"generation\": old_generation, \"phase\": \"confirmed\" }));\n });\n settle(&mut rt, 150);\n let texts: Vec<String> = rt.state.model.greeting_texts().into_iter().map(|(_, t)| t).collect();\n assert_eq!(texts, [\"hello from globex\"]);\n assert!(rt.find(\"greeting-g-acme-1\").is_none());\n assert!(has_state(&rt, \"org-globex\", \"checked\") && !has_state(&rt, \"org-acme\", \"checked\"));\n}\n\n#[test]\nfn sign_out_clears_the_screen() {\n let fake = Fake::start();\n let mut rt = signed_in(&fake);\n press(&mut rt, \"sign-out\");\n assert!(rt.state.model.list.rows.is_empty(), \"nothing of the person stays from the intent on\");\n until(&mut rt, \"signed out\", |s| matches!(s.model.session, Session::SignedOut));\n assert!(rt.find(\"sign-in\").is_some());\n assert!(rt.find(\"greetings\").is_none());\n assert_eq!(fake.requests_to(\"/client/v1/sign-out\").len(), 1);\n}\n\n#[test]\nfn sign_out_stops_saying_synced() {\n // The replica's connection state belongs to the context it was opened for: after sign-out there is none.\n let fake = Fake::start();\n let mut rt = signed_in(&fake);\n let label = |rt: &rune::Runtime<eloxiv_desktop_rune::Ui>| {\n a11y(rt, \"connection\").and_then(|n| n[\"name\"].as_str().map(str::to_owned)).unwrap_or_default()\n };\n fake.with(|s| s.emit(json!({ \"type\": \"connection\", \"state\": \"connected\" })));\n until(&mut rt, \"synced\", |s| s.model.connection.is_some());\n assert_eq!(label(&rt), \"Synced\");\n press(&mut rt, \"sign-out\");\n until(&mut rt, \"signed out\", |s| matches!(s.model.session, Session::SignedOut));\n settle(&mut rt, 50);\n assert_eq!(rt.state.model.connection, None);\n assert_eq!(label(&rt), \"Ready\", \"connected to the daemon, no replica open\");\n}\n\n#[test]\nfn an_offline_start_shows_the_devices_copy_and_says_so_until_the_kernel_answers() {\n // The daemon started without reaching the kernel: it reports the remembered person and organisation `offline`,\n // and serves the replica it kept on disk.\n let fake = Fake::start();\n fake.with(|s| {\n s.signed_in = true;\n s.offline = true;\n s.org = Some(\"acme\".into());\n s.generation = 1;\n });\n let mut rt = runtime(&fake);\n let label = |rt: &rune::Runtime<eloxiv_desktop_rune::Ui>| {\n a11y(rt, \"connection\").and_then(|n| n[\"name\"].as_str().map(str::to_owned)).unwrap_or_default()\n };\n until(&mut rt, \"the cached greetings\", |s| s.model.list.rows.len() == 2);\n assert!(rt.state.model.offline);\n assert_eq!(label(&rt), \"Offline: showing this device's copy\");\n // Even while the replica reports itself connecting, the offline start is what is said.\n fake.with(|s| s.emit(json!({ \"type\": \"connection\", \"state\": \"connecting\" })));\n settle(&mut rt, 50);\n assert_eq!(label(&rt), \"Offline: showing this device's copy\");\n // The kernel answers: the same context, no longer offline, and the replica syncs.\n fake.with(|s| {\n s.offline = false;\n s.emit_session();\n s.emit(json!({ \"type\": \"connection\", \"state\": \"connected\" }));\n });\n until(&mut rt, \"synced\", |s| !s.model.offline && s.model.connection.is_some());\n settle(&mut rt, 50);\n assert_eq!(label(&rt), \"Synced\");\n assert_eq!(rt.state.model.list.rows.len(), 2, \"the same list, not opened again\");\n}\n\n#[test]\nfn a_dropped_stream_is_opened_again_and_the_list_subscribed_again() {\n let fake = Fake::start();\n let mut rt = signed_in(&fake);\n fake.with(|s| {\n if let Some(sink) = s.sink.take() {\n let _ = sink.shutdown(std::net::Shutdown::Both);\n }\n });\n until(&mut rt, \"a second stream\", |_| fake.requests_to(\"/client/v1/events\").len() == 2);\n until(&mut rt, \"the list again\", |s| s.model.list.rows.len() == 2 && s.stream_open);\n let asked = |query: &str| {\n fake.requests_to(\"/client/v1/subscriptions\").iter().filter(|r| r.body[\"query\"].as_str() == Some(query)).count()\n };\n assert_eq!(asked(\"hello.greetings\"), 2);\n // The chat's queries too (a stream's subscriptions end with it).\n until(&mut rt, \"the chat's queries again\", |_| asked(\"agent.messages\") == 2);\n assert_eq!(asked(\"agent.runs\"), 2);\n}\n\n#[test]\nfn a_wrong_token_is_refused_and_said_so() {\n let fake = Fake::start();\n let mut rt =\n eloxiv_desktop_rune::app_in(fake.url.clone(), \"not-the-host-secret-xxxxxxxxxxxxxxxxxxxxxxx\".into(), None)\n .headless_runtime((900.0, 700.0), rune::Env::new(false, 1.0));\n rt.frame(0.0);\n until(\n &mut rt,\n \"the refusal\",\n |s| matches!(&s.startup, eloxiv_desktop_rune::ui::Startup::Failed(m) if m.contains(\"Unauthenticated\")),\n );\n assert!(rt.find(\"status\").is_some());\n}\n",
276
+ "type": "registry:file",
277
+ "target": "desktop-rune/app/tests/screens.rs"
278
+ },
279
+ {
280
+ "path": "app/desktop-rune/app/tests/single_instance.rs",
281
+ "content": "//! One process per app, with the real binary and a real window (Linux; skipped without a display, as on a CI runner\n//! with no compositor, unless `ELOXIV_RUNE_WINDOW_TESTS=1` requires it): the first launch claims the app's single\n//! instance and opens its window over the fake daemon; a second launch with a link hands the link to it and exits at\n//! once without a window or a sidecar of its own; the first opens the link's screen.\n\n#![cfg(target_os = \"linux\")]\n\nmod support;\n\nuse std::io::{BufRead, BufReader};\nuse std::process::{Command, Stdio};\nuse std::sync::mpsc;\nuse std::time::{Duration, Instant};\n\nuse support::*;\n\nfn display() -> bool {\n std::env::var_os(\"WAYLAND_DISPLAY\").is_some() || std::env::var_os(\"DISPLAY\").is_some()\n}\n\n#[test]\nfn a_second_launch_hands_its_link_to_the_running_app_and_exits() {\n if !display() {\n assert!(std::env::var(\"ELOXIV_RUNE_WINDOW_TESTS\").as_deref() != Ok(\"1\"), \"no display to open a window on\");\n eprintln!(\"no display; skipped\");\n return;\n }\n let fake = Fake::start();\n fake.with(|s| {\n s.signed_in = true;\n s.org = Some(\"acme\".into());\n s.generation = 1;\n });\n let dir = TempDir::new(\"instance\");\n let views = dir.0.join(\"views.json\");\n std::fs::write(&views, r#\"[{\"id\":\"hello.greetings\",\"route\":\"/hello\",\"title\":\"Greetings\"}]\"#).expect(\"a test file\");\n // An app id of this run's own, so its instance socket is nobody else's.\n let app_id = format!(\"dev.eloxiv.instance-test-{}\", eloxiv_desktop_rune::random_id());\n let exe = env!(\"CARGO_BIN_EXE_eloxiv-desktop-rune\");\n let launch = |link: Option<&str>| {\n let mut c = Command::new(exe);\n c.args(link)\n .env(\"ELOXIV_DAEMON_URL\", &fake.url)\n .env(\"ELOXIV_DAEMON_HOST_SECRET\", TOKEN)\n .env(\"ELOXIV_APP_ID\", &app_id)\n .env(\"ELOXIV_REGISTER_SCHEME\", \"0\")\n .env(\"ELOXIV_RUNE_VIEWS\", &views)\n .env(\"ELOXIV_RUNE_DATA_DIR\", &dir.0)\n .stdin(Stdio::null())\n .stdout(Stdio::null())\n .stderr(Stdio::piped());\n c\n };\n struct Killed(std::process::Child);\n impl Drop for Killed {\n fn drop(&mut self) {\n let _ = self.0.kill();\n let _ = self.0.wait();\n }\n }\n let mut first = Killed(launch(Some(\"eloxiv://open/make\")).spawn().expect(\"the first launch\"));\n let (lines, log) = mpsc::channel::<String>();\n let stderr = first.0.stderr.take().expect(\"as the test set it up\");\n std::thread::spawn(move || {\n for line in BufReader::new(stderr).lines().map_while(Result::ok) {\n let _ = lines.send(line);\n }\n });\n let wait_for = |what: &str| {\n let deadline = Instant::now() + Duration::from_secs(30);\n while let Ok(line) = log.recv_timeout(deadline.saturating_duration_since(Instant::now())) {\n if line.contains(what) {\n return;\n }\n }\n panic!(\"the running app never logged {what:?}\");\n };\n // Its own launching link reaches it, and opens its screen once the session is there.\n wait_for(\"link received\");\n wait_for(\"link opened: view make\");\n\n let started = Instant::now();\n let second = launch(Some(\"eloxiv://open/hello\")).output().expect(\"the second launch\");\n assert!(second.status.success(), \"{:?}: {}\", second.status, String::from_utf8_lossy(&second.stderr));\n assert!(started.elapsed() < Duration::from_secs(5), \"it handed over and exited at once\");\n assert!(!String::from_utf8_lossy(&second.stderr).contains(\"link opened\"), \"the second launch opened nothing\");\n wait_for(\"link received\");\n wait_for(\"link opened: view hello.greetings\");\n drop(first);\n // The instance socket and its lock, which a killed process leaves behind.\n if let Some(run) = std::env::var_os(\"XDG_RUNTIME_DIR\") {\n let run = std::path::PathBuf::from(run);\n let _ = std::fs::remove_file(run.join(format!(\"rune-instance-{app_id}.sock\")));\n let _ = std::fs::remove_file(run.join(format!(\"rune-instance-{app_id}.lock\")));\n }\n}\n",
282
+ "type": "registry:file",
283
+ "target": "desktop-rune/app/tests/single_instance.rs"
284
+ },
285
+ {
286
+ "path": "app/desktop-rune/app/tests/support/mod.rs",
287
+ "content": "//! A fake `/client/v1` for the screens' tests: a small HTTP server on loopback with the LocalClient v1 routes\n//! and one SSE stream (chunked, as Bun and Node send it), playing a client runtime with two organisations, the\n//! greetings query, `hello.greet` (a farewell refused with `Forbidden` after its prediction), a scripted MAKE\n//! view, and the agent (LocalClient 1.1.0: the chat's named queries, `agent.send`, consent and approval decisions,\n//! run subscriptions whose events the test plays, readiness) and the person's notifications (`notifications.mine`,\n//! rows the test adds per organisation). Every request is recorded. Dropping it stops the server.\n\n#![allow(dead_code)]\n\nuse std::io::{BufRead, BufReader, Read, Write};\nuse std::net::{TcpListener, TcpStream};\nuse std::sync::atomic::{AtomicBool, Ordering};\nuse std::sync::{Arc, Mutex};\nuse std::time::{Duration, Instant};\n\nuse serde_json::{Value, json};\n\npub const TOKEN: &str = \"test-host-secret-0123456789abcdef0123456789\";\n\n/// One recorded request.\n#[derive(Clone, Debug)]\npub struct Seen {\n pub method: String,\n pub path: String,\n pub body: Value,\n pub authorized: bool,\n}\n\n/// A MAKE view's code, played by the test: `(state, message) -> { state, calls, tree }`.\npub type ViewCode = Box<dyn Fn(&Value, &Value) -> Value + Send>;\n/// A MAKE call's answer, by action and input: the envelope's output, or an error.\npub type CallCode = Box<dyn Fn(&str, &Value) -> Result<Value, Value> + Send>;\n\npub struct State {\n pub signed_in: bool,\n /// The session is an offline start (LocalClient 1.2.0's `offline`): the daemon did not reach the kernel.\n pub offline: bool,\n pub signing_in: bool,\n pub org: Option<String>,\n pub generation: i64,\n pub seq: u64,\n pub rows: Vec<(String, Value)>,\n pub subs: Vec<(String, i64)>,\n pub next: u64,\n pub sink: Option<TcpStream>,\n pub seen: Vec<Seen>,\n pub view: Option<ViewCode>,\n pub view_actions: Vec<String>,\n pub view_version: String,\n pub call: Option<CallCode>,\n /// Hold `rows` events back while true (to see a prediction before its rollback).\n pub hold_writes: bool,\n /// The query of each subscription (by id).\n pub sub_queries: Vec<(String, String)>,\n pub agent: AgentFake,\n /// The person's notification rows, by organisation (`notifications.mine`).\n pub notifications: Vec<(String, Value)>,\n /// Hold the answer to the next subscription of this query (made, its answer not sent) until `subscribe_held`\n /// is cleared.\n pub hold_subscribe: Option<String>,\n pub subscribe_held: bool,\n /// Hold `POST /client/v1/org` and `POST /client/v1/sign-out` before the daemon looks at them, while true (the\n /// daemon waiting on a membership lookup, a slow revocation).\n pub hold_context: bool,\n /// Hold every decision (`consent.*`, `approvals.*`) before the daemon looks at it, while true.\n pub hold_decisions: bool,\n}\n\n/// The agent as the fake plays it: its rows, the run subscriptions, what was sent and decided.\n#[derive(Default)]\npub struct AgentFake {\n /// `GET /client/v1/agent/readiness`'s answer.\n pub engine: Value,\n pub conversations: Vec<Value>,\n pub messages: Vec<Value>,\n pub runs: Vec<Value>,\n pub approvals: Vec<Value>,\n /// Run subscriptions: (id, run, generation).\n pub run_subs: Vec<(String, String, i64)>,\n /// Every run's stored events, to replay to a subscription after its `after`.\n pub stored: Vec<Value>,\n /// The sends' keys and texts, in order.\n pub sends: Vec<(String, String)>,\n /// Decisions: (action, id, key).\n pub decisions: Vec<(String, String, String)>,\n /// Drop the next send's answer (the connection closes with no answer: lost), after making it.\n pub lose_next_send: bool,\n /// Hold every `agent.send` request before the daemon looks at it, while true (`held` counts those waiting).\n pub hold_sends: bool,\n /// Hold every `agent.send` answer after the send was made, while true (counted in `held` too).\n pub hold_answers: bool,\n /// Refuse every `agent.send` with this error (403) before the kernel looks at its key, while set.\n pub refuse_sends: Option<Value>,\n pub held: usize,\n pub next: u64,\n}\n\npub struct Fake {\n pub url: String,\n pub state: Arc<Mutex<State>>,\n stop: Arc<AtomicBool>,\n}\n\nfn org_rows(org: &str) -> Vec<Value> {\n match org {\n \"acme\" => vec![\n json!({ \"id\": \"g-acme-1\", \"message\": \"hello from acme\", \"orgId\": \"acme\" }),\n json!({ \"id\": \"g-acme-2\", \"message\": \"welcome to acme\", \"orgId\": \"acme\" }),\n ],\n _ => vec![json!({ \"id\": \"g-globex-1\", \"message\": \"hello from globex\", \"orgId\": \"globex\" })],\n }\n}\n\nimpl State {\n pub fn session(&self) -> Value {\n if self.signing_in {\n return json!({ \"state\": \"signingIn\" });\n }\n if !self.signed_in {\n return json!({ \"state\": \"signedOut\" });\n }\n let mut session = json!({\n \"state\": \"signedIn\",\n \"user\": { \"id\": \"u-alice\", \"email\": \"alice@example.com\", \"name\": \"Alice\" },\n \"organizations\": [\n { \"orgId\": \"acme\", \"name\": \"Acme\", \"roles\": [\"member\"] },\n { \"orgId\": \"globex\", \"name\": \"Globex\", \"roles\": [\"member\"] }\n ],\n \"orgId\": self.org,\n \"generation\": self.generation,\n });\n if self.offline {\n session[\"offline\"] = json!(true);\n }\n session\n }\n\n /// Writes one event to the stream (a chunk), numbering it.\n pub fn emit(&mut self, mut event: Value) {\n self.seq += 1;\n event[\"seq\"] = json!(self.seq);\n let data = format!(\"data: {event}\\n\\n\");\n if let Some(sink) = self.sink.as_mut() {\n let chunk = format!(\"{:x}\\r\\n{data}\\r\\n\", data.len());\n if sink.write_all(chunk.as_bytes()).is_err() {\n self.sink = None;\n }\n }\n }\n\n pub fn emit_session(&mut self) {\n let s = self.session();\n self.emit(json!({ \"type\": \"session\", \"session\": s }));\n }\n\n pub fn current_rows(&self) -> Vec<Value> {\n let org = self.org.clone().unwrap_or_default();\n let mut rows: Vec<Value> = self.rows.iter().filter(|(o, _)| *o == org).map(|(_, r)| r.clone()).collect();\n rows.extend(org_rows(&org));\n rows\n }\n\n /// The rows of `query` now (the agent's queries in acme only: globex has none).\n pub fn rows_of(&self, query: &str) -> Vec<Value> {\n let acme = self.org.as_deref() == Some(\"acme\");\n match query {\n \"agent.conversations\" if acme => self.agent.conversations.clone(),\n \"agent.messages\" if acme => self.agent.messages.clone(),\n \"agent.runs\" if acme => self.agent.runs.clone(),\n \"approvals.requests\" if acme => self.agent.approvals.clone(),\n \"hello.greetings\" => self.current_rows(),\n \"notifications.mine\" => {\n let org = self.org.clone().unwrap_or_default();\n self.notifications.iter().filter(|(o, _)| *o == org).map(|(_, r)| r.clone()).collect()\n }\n _ => Vec::new(),\n }\n }\n\n pub fn emit_rows(&mut self) {\n for (id, g) in self.subs.clone() {\n if g == self.generation {\n let query =\n self.sub_queries.iter().find(|(i, _)| *i == id).map_or(\"hello.greetings\", |(_, q)| q.as_str());\n let rows = self.rows_of(query);\n self.emit(\n json!({ \"type\": \"rows\", \"subscription\": id, \"generation\": g, \"status\": \"complete\", \"rows\": rows }),\n );\n }\n }\n }\n\n /// One event of `run`, to every subscription following it (stored ones kept for a later subscription).\n pub fn run_event(&mut self, run: &str, seq: i64, kind: &str, data: Value) {\n let at = if seq >= 0 { \"2026-11-17T00:00:00Z\" } else { \"\" };\n let event = json!({ \"runId\": run, \"seq\": seq, \"type\": kind, \"data\": data, \"at\": at });\n if seq >= 0 {\n self.agent.stored.push(event.clone());\n }\n for (id, r, g) in self.agent.run_subs.clone() {\n if r == run && g == self.generation {\n self.emit(json!({ \"type\": \"run\", \"subscription\": id, \"generation\": g, \"event\": event }));\n }\n }\n if kind == \"run-finished\" {\n self.agent.run_subs.retain(|(_, r, _)| r != run);\n }\n }\n\n /// The run's answer `text`: its last `chunks` streamed for `step`, then stored (the message, the run succeeded),\n /// then `model-step` and `run-finished` (stored events `first_seq` and the next).\n pub fn finish_run(&mut self, run: &str, step: i64, chunks: &[&str], text: &str, first_seq: i64) {\n for chunk in chunks {\n self.run_event(run, -1, \"text-delta\", json!({ \"delta\": chunk, \"step\": step, \"attempt\": \"a1\" }));\n }\n let conversation = self\n .agent\n .runs\n .iter()\n .find(|r| r[\"id\"] == json!(run))\n .and_then(|r| r[\"conversationId\"].as_str().map(str::to_owned))\n .unwrap_or_default();\n self.agent.next += 1;\n let (id, seq) = (format!(\"m-{}\", self.agent.next), self.agent.messages.len() as i64 + 1);\n self.agent.messages.push(\n json!({ \"id\": id, \"conversationId\": conversation, \"runId\": run, \"seq\": seq, \"role\": \"assistant\", \"text\": text }),\n );\n for r in &mut self.agent.runs {\n if r[\"id\"] == json!(run) {\n r[\"status\"] = json!(\"succeeded\");\n }\n }\n self.run_event(run, first_seq, \"model-step\", json!({ \"step\": step, \"text\": text }));\n self.run_event(run, first_seq + 1, \"run-finished\", json!({ \"status\": \"succeeded\" }));\n self.emit_rows();\n }\n\n pub fn complete_sign_in(&mut self) {\n self.signing_in = false;\n self.signed_in = true;\n self.org = Some(\"acme\".into());\n self.generation += 1;\n self.emit_session();\n }\n}\n\nimpl Fake {\n pub fn start() -> Fake {\n let listener = TcpListener::bind(\"127.0.0.1:0\").expect(\"bind\");\n let url = format!(\"http://{}\", listener.local_addr().expect(\"addr\"));\n listener.set_nonblocking(true).expect(\"nonblocking\");\n let state = Arc::new(Mutex::new(State {\n signed_in: false,\n offline: false,\n signing_in: false,\n org: None,\n generation: 0,\n seq: 0,\n rows: Vec::new(),\n subs: Vec::new(),\n next: 0,\n sink: None,\n seen: Vec::new(),\n view: None,\n view_actions: Vec::new(),\n view_version: \"1.0.0\".into(),\n call: None,\n hold_writes: false,\n sub_queries: Vec::new(),\n agent: AgentFake {\n engine: json!({ \"state\": \"configured\", \"provider\": \"openai\", \"model\": \"gpt-5-mini\", \"detail\": \"openai:gpt-5-mini is set up\" }),\n ..AgentFake::default()\n },\n notifications: Vec::new(),\n hold_subscribe: None,\n subscribe_held: false,\n hold_context: false,\n hold_decisions: false,\n }));\n let stop = Arc::new(AtomicBool::new(false));\n let (st, flag) = (state.clone(), stop.clone());\n std::thread::spawn(move || {\n while !flag.load(Ordering::SeqCst) {\n match listener.accept() {\n Ok((stream, _)) => {\n let st = st.clone();\n std::thread::spawn(move || serve(stream, &st));\n }\n Err(_) => std::thread::sleep(Duration::from_millis(2)),\n }\n }\n });\n Fake { url, state, stop }\n }\n\n pub fn with<R>(&self, f: impl FnOnce(&mut State) -> R) -> R {\n let mut s = self.state.lock().expect(\"fake state\");\n f(&mut s)\n }\n\n pub fn seen(&self) -> Vec<Seen> {\n self.with(|s| s.seen.clone())\n }\n\n pub fn requests_to(&self, path: &str) -> Vec<Seen> {\n self.seen().into_iter().filter(|r| r.path == path).collect()\n }\n}\n\nimpl Drop for Fake {\n fn drop(&mut self) {\n self.stop.store(true, Ordering::SeqCst);\n self.with(|s| {\n if let Some(sink) = s.sink.take() {\n let _ = sink.shutdown(std::net::Shutdown::Both);\n }\n });\n }\n}\n\nfn respond(stream: &mut TcpStream, status: u16, body: &Value) {\n let text = body.to_string();\n let reason = if status < 300 { \"OK\" } else { \"Refused\" };\n let head = format!(\n \"HTTP/1.1 {status} {reason}\\r\\ncontent-type: application/json\\r\\ncontent-length: {}\\r\\nconnection: close\\r\\n\\r\\n\",\n text.len()\n );\n let _ = stream.write_all(head.as_bytes());\n let _ = stream.write_all(text.as_bytes());\n}\n\nfn serve(mut stream: TcpStream, state: &Arc<Mutex<State>>) {\n let _ = stream.set_nonblocking(false);\n let Ok(clone) = stream.try_clone() else { return };\n let mut reader = BufReader::new(clone);\n let mut line = String::new();\n if reader.read_line(&mut line).is_err() {\n return;\n }\n let mut parts = line.split_whitespace();\n let (method, target) = (parts.next().unwrap_or(\"\").to_owned(), parts.next().unwrap_or(\"\").to_owned());\n let mut length = 0usize;\n let mut auth = String::new();\n loop {\n let mut h = String::new();\n if reader.read_line(&mut h).unwrap_or(0) == 0 || h == \"\\r\\n\" {\n break;\n }\n let lower = h.to_ascii_lowercase();\n if let Some(v) = lower.strip_prefix(\"content-length:\") {\n length = v.trim().parse().unwrap_or(0);\n }\n if lower.starts_with(\"authorization:\") {\n auth = h[\"authorization:\".len()..].trim().to_owned();\n }\n }\n let mut raw = vec![0u8; length];\n let _ = reader.read_exact(&mut raw);\n let body: Value = serde_json::from_slice(&raw).unwrap_or(Value::Null);\n let path = target.split('?').next().unwrap_or(\"\").to_owned();\n let authorized = auth == format!(\"Bearer {TOKEN}\");\n state.lock().expect(\"state\").seen.push(Seen {\n method: method.clone(),\n path: path.clone(),\n body: body.clone(),\n authorized,\n });\n\n if path == \"/health\" {\n return respond(&mut stream, 200, &json!({ \"ok\": true }));\n }\n if !authorized {\n return respond(&mut stream, 401, &json!({ \"_tag\": \"Unauthenticated\", \"message\": \"no local token\" }));\n }\n let mut s = state.lock().expect(\"state\");\n if s.hold_context && method == \"POST\" && (path == \"/client/v1/org\" || path == \"/client/v1/sign-out\") {\n drop(s);\n while state.lock().expect(\"state\").hold_context {\n std::thread::sleep(Duration::from_millis(5));\n }\n s = state.lock().expect(\"state\");\n }\n let deciding = [\"consent.\", \"approvals.\"].iter().any(|p| path.starts_with(&format!(\"/client/v1/actions/{p}\")));\n if s.hold_decisions && deciding {\n drop(s);\n while state.lock().expect(\"state\").hold_decisions {\n std::thread::sleep(Duration::from_millis(5));\n }\n s = state.lock().expect(\"state\");\n }\n match (method.as_str(), path.as_str()) {\n (\"GET\", \"/client/v1/events\") => {\n let head = \"HTTP/1.1 200 OK\\r\\ncontent-type: text/event-stream\\r\\ntransfer-encoding: chunked\\r\\ncache-control: no-store\\r\\n\\r\\n\";\n if stream.write_all(head.as_bytes()).is_ok() {\n // A heartbeat comment first, as the daemon sends every 15 s.\n let _ = stream.write_all(b\"d\\r\\n: heartbeat\\n\\n\\r\\n\");\n if let Some(old) = s.sink.replace(stream) {\n let _ = old.shutdown(std::net::Shutdown::Both);\n }\n s.subs.clear();\n // The first event on a stream is the current session (LocalClient's contract).\n s.emit_session();\n }\n }\n (\"GET\", \"/client/v1/hello\") => respond(\n &mut stream,\n 200,\n &json!({ \"protocol\": \"eloxiv.local-client\", \"version\": \"1.1.0\", \"features\": [\"runEvents\", \"agentReadiness\"],\n \"app\": { \"queries\": [\"agent.conversations\", \"agent.messages\", \"agent.runs\", \"approvals.requests\", \"hello.greetings\", \"notifications.mine\"],\n \"mutators\": [\"hello.greet\"], \"actions\": [] } }),\n ),\n (\"GET\", \"/client/v1/session\") => {\n let v = s.session();\n respond(&mut stream, 200, &v)\n }\n (\"POST\", \"/client/v1/sign-in\") => {\n s.signing_in = true;\n s.emit_session();\n respond(&mut stream, 200, &json!({ \"url\": \"http://127.0.0.1:9/sign-in?state=st-1\", \"state\": \"st-1\" }))\n }\n (\"POST\", \"/client/v1/org\") => {\n let org = body.get(\"orgId\").and_then(Value::as_str).unwrap_or(\"\").to_owned();\n if org != \"acme\" && org != \"globex\" {\n return respond(\n &mut stream,\n 403,\n &json!({ \"_tag\": \"Forbidden\", \"message\": \"not a member\", \"action\": \"org\" }),\n );\n }\n s.org = Some(org);\n s.generation += 1;\n let g = s.generation;\n s.subs.clear();\n s.emit(json!({ \"type\": \"context\", \"generation\": g, \"reason\": \"org\" }));\n s.emit_session();\n respond(&mut stream, 200, &json!({ \"generation\": g }))\n }\n (\"POST\", \"/client/v1/sign-out\") => {\n s.signed_in = false;\n s.org = None;\n s.generation += 1;\n let g = s.generation;\n s.subs.clear();\n s.emit(json!({ \"type\": \"context\", \"generation\": g, \"reason\": \"signOut\" }));\n s.emit_session();\n respond(&mut stream, 200, &json!({ \"ok\": true }))\n }\n (\"POST\", \"/client/v1/subscriptions\") => {\n if !s.signed_in {\n return respond(&mut stream, 401, &json!({ \"_tag\": \"NotSignedIn\", \"message\": \"sign in first\" }));\n }\n const QUERIES: [&str; 6] = [\n \"hello.greetings\",\n \"agent.conversations\",\n \"agent.messages\",\n \"agent.runs\",\n \"approvals.requests\",\n \"notifications.mine\",\n ];\n if !body.get(\"query\").and_then(Value::as_str).is_some_and(|q| QUERIES.contains(&q)) {\n return respond(\n &mut stream,\n 404,\n &json!({ \"_tag\": \"UnknownQuery\", \"message\": \"no such query\", \"query\": body[\"query\"] }),\n );\n }\n s.next += 1;\n // The client's id when it names one (LocalClient 1.0: `id?`), else the daemon's.\n let id = body.get(\"id\").and_then(Value::as_str).map_or_else(|| format!(\"s{}\", s.next), str::to_owned);\n let g = s.generation;\n s.subs.push((id.clone(), g));\n let query = body[\"query\"].as_str().unwrap_or(\"\").to_owned();\n s.sub_queries.push((id.clone(), query.clone()));\n if s.hold_subscribe.as_deref() == Some(query.as_str()) {\n // Made; its answer is slow (the stream may close and open again before it comes).\n s.hold_subscribe = None;\n s.subscribe_held = true;\n s.emit_rows();\n drop(s);\n while state.lock().expect(\"state\").subscribe_held {\n std::thread::sleep(Duration::from_millis(5));\n }\n return respond(&mut stream, 200, &json!({ \"id\": id, \"generation\": g }));\n }\n respond(&mut stream, 200, &json!({ \"id\": id, \"generation\": g }));\n drop(stream);\n s.emit_rows();\n }\n (\"GET\", \"/client/v1/agent/readiness\") => {\n let engine = s.agent.engine.clone();\n respond(&mut stream, 200, &engine)\n }\n (\"POST\", \"/client/v1/runs\") => {\n let id = body[\"id\"].as_str().unwrap_or(\"run-sub\").to_owned();\n let run = body[\"runId\"].as_str().unwrap_or(\"\").to_owned();\n let after = body[\"after\"].as_i64().unwrap_or(-1);\n let g = s.generation;\n s.agent.run_subs.push((id.clone(), run.clone(), g));\n respond(&mut stream, 200, &json!({ \"id\": id, \"generation\": g }));\n drop(stream);\n // The run's stored events after `after`, as the core replays them to a new subscription.\n let replay: Vec<Value> = s\n .agent\n .stored\n .iter()\n .filter(|e| e[\"runId\"] == json!(run) && e[\"seq\"].as_i64() > Some(after))\n .cloned()\n .collect();\n for event in replay {\n s.emit(json!({ \"type\": \"run\", \"subscription\": id, \"generation\": g, \"event\": event }));\n }\n }\n (\"DELETE\", p) if p.starts_with(\"/client/v1/runs/\") => {\n let id = p.trim_start_matches(\"/client/v1/runs/\").to_owned();\n if !s.agent.run_subs.iter().any(|(i, ..)| *i == id) {\n return respond(\n &mut stream,\n 404,\n &json!({ \"_tag\": \"UnknownSubscription\", \"id\": id, \"message\": \"no run subscription\" }),\n );\n }\n s.agent.run_subs.retain(|(i, ..)| *i != id);\n respond(&mut stream, 200, &json!({ \"ok\": true }))\n }\n (\"DELETE\", p) if p.starts_with(\"/client/v1/subscriptions/\") => {\n let id = p.trim_start_matches(\"/client/v1/subscriptions/\").to_owned();\n s.subs.retain(|(i, _)| *i != id);\n respond(&mut stream, 200, &json!({ \"ok\": true }))\n }\n (\"POST\", \"/client/v1/writes\") => {\n if let Some(made) = body.get(\"generation\").and_then(Value::as_i64)\n && made != s.generation\n {\n let g = s.generation;\n return respond(\n &mut stream,\n 409,\n &json!({ \"_tag\": \"StaleGeneration\", \"generation\": g, \"message\": \"the context changed\" }),\n );\n }\n let id = body.get(\"id\").and_then(Value::as_str).unwrap_or(\"w\").to_owned();\n let message = body.pointer(\"/input/message\").and_then(Value::as_str).unwrap_or(\"\").to_owned();\n let g = s.generation;\n let org = s.org.clone().unwrap_or_default();\n respond(&mut stream, 200, &json!({ \"id\": id, \"generation\": g }));\n drop(stream);\n let row = json!({ \"id\": format!(\"g-{id}\"), \"message\": message, \"orgId\": org });\n s.rows.insert(0, (org.clone(), row));\n s.emit(json!({ \"type\": \"write\", \"id\": id, \"generation\": g, \"phase\": \"predicted\" }));\n s.emit_rows();\n if s.hold_writes {\n return;\n }\n drop(s);\n settle_write(state, &id, &message);\n }\n (\"POST\", p) if p.starts_with(\"/client/v1/actions/\") => {\n let name = p.trim_start_matches(\"/client/v1/actions/\").to_owned();\n if name == \"agent.send\" && s.agent.hold_sends {\n // Held on its way (a slow worker thread or connection): the daemon has not seen it yet.\n s.agent.held += 1;\n drop(s);\n while state.lock().expect(\"state\").agent.hold_sends {\n std::thread::sleep(Duration::from_millis(5));\n }\n s = state.lock().expect(\"state\");\n s.agent.held -= 1;\n }\n // LocalClient 1.1.0's precondition: made in another generation, refused and not run.\n if let Some(made) = body.get(\"generation\").and_then(Value::as_i64)\n && made != s.generation\n {\n let g = s.generation;\n return respond(\n &mut stream,\n 409,\n &json!({ \"_tag\": \"StaleGeneration\", \"generation\": g, \"message\": \"the context changed\" }),\n );\n }\n let input = body.get(\"input\").cloned().unwrap_or(Value::Null);\n let key = body.get(\"idempotencyKey\").and_then(Value::as_str).unwrap_or(\"\").to_owned();\n match name.as_str() {\n \"agent.send\" => {\n if let Some(error) = s.agent.refuse_sends.clone() {\n return respond(&mut stream, 403, &error);\n }\n let text = input[\"text\"].as_str().unwrap_or(\"\").to_owned();\n let replay = s.agent.sends.iter().any(|(k, _)| *k == key);\n s.agent.sends.push((key.clone(), text.clone()));\n if replay {\n let answer = json!({ \"kind\": \"replay\", \"receipt\": { \"action\": \"agent.send\" } });\n return respond(&mut stream, 200, &answer);\n }\n s.agent.next += 1;\n let n = s.agent.next;\n let conversation = input[\"conversationId\"].as_str().map_or_else(|| format!(\"c-{n}\"), str::to_owned);\n if !s.agent.conversations.iter().any(|c| c[\"id\"] == json!(conversation)) {\n s.agent.conversations.insert(0, json!({ \"id\": conversation, \"title\": text }));\n }\n let run = format!(\"r-{n}\");\n let seq = s.agent.messages.len() as i64 + 1;\n s.agent.messages.push(json!({ \"id\": format!(\"m-{n}\"), \"conversationId\": conversation,\n \"runId\": run, \"seq\": seq, \"role\": \"user\", \"text\": text }));\n s.agent.runs.insert(\n 0,\n json!({ \"id\": run, \"conversationId\": conversation, \"status\": \"running\", \"createdAt\": n }),\n );\n if s.agent.hold_answers {\n // Made; its answer is slow (the host may have left the organisation by the time it comes).\n s.agent.held += 1;\n drop(s);\n while state.lock().expect(\"state\").agent.hold_answers {\n std::thread::sleep(Duration::from_millis(5));\n }\n s = state.lock().expect(\"state\");\n s.agent.held -= 1;\n }\n if s.agent.lose_next_send {\n // Made, but its answer is lost: the connection closes with nothing said.\n s.agent.lose_next_send = false;\n let _ = stream.shutdown(std::net::Shutdown::Both);\n } else {\n let output =\n json!({ \"conversationId\": conversation, \"runId\": run, \"messageId\": format!(\"m-{n}\") });\n respond(&mut stream, 200, &json!({ \"kind\": \"output\", \"output\": output }));\n }\n drop(stream);\n s.emit_rows();\n }\n \"consent.approve\" | \"consent.reject\" | \"approvals.approve\" | \"approvals.reject\" => {\n let id = input[\"id\"].as_str().unwrap_or(\"\").to_owned();\n s.agent.decisions.push((name.clone(), id.clone(), key));\n if name.starts_with(\"approvals.\") {\n let status = if name.ends_with(\"approve\") { \"approved\" } else { \"rejected\" };\n for a in &mut s.agent.approvals {\n if a[\"id\"] == json!(id) {\n a[\"status\"] = json!(status);\n }\n }\n }\n respond(\n &mut stream,\n 200,\n &json!({ \"kind\": \"output\", \"output\": { \"id\": id, \"status\": \"decided\" } }),\n );\n drop(stream);\n s.emit_rows();\n }\n \"make.view\" => {\n let module = input.get(\"module\").and_then(Value::as_str).unwrap_or(\"\");\n if module != \"mk_demo\" || s.view.is_none() {\n return respond(\n &mut stream,\n 404,\n &json!({ \"_tag\": \"InvalidInput\", \"message\": format!(\"no module {module}\") }),\n );\n }\n let out = json!({ \"kind\": \"output\", \"output\": {\n \"module\": module, \"version\": s.view_version,\n \"view\": { \"title\": \"Demo view\" }, \"actions\": s.view_actions } });\n respond(&mut stream, 200, &out)\n }\n \"make.renderView\" => {\n if input.get(\"version\").and_then(Value::as_str) != Some(s.view_version.as_str()) {\n return respond(\n &mut stream,\n 400,\n &json!({ \"_tag\": \"InvalidInput\", \"message\": \"another version is installed: open the view again\" }),\n );\n }\n let state = input.get(\"state\").cloned().unwrap_or(Value::Null);\n let message = input.get(\"message\").cloned().unwrap_or(Value::Null);\n let step = s.view.as_ref().map(|code| code(&state, &message)).unwrap_or(Value::Null);\n respond(&mut stream, 200, &json!({ \"kind\": \"output\", \"output\": step }))\n }\n _ => {\n let answer = s.call.as_ref().map(|c| c(&name, &input));\n match answer {\n Some(Ok(output)) => respond(&mut stream, 200, &json!({ \"kind\": \"output\", \"output\": output })),\n Some(Err(error)) => respond(&mut stream, 403, &error),\n None => respond(\n &mut stream,\n 404,\n &json!({ \"_tag\": \"UnknownAction\", \"action\": name, \"message\": format!(\"No action {name}\") }),\n ),\n }\n }\n }\n }\n _ => respond(\n &mut stream,\n 404,\n &json!({ \"_tag\": \"InvalidInput\", \"message\": format!(\"no route {method} {path}\") }),\n ),\n }\n}\n\n/// Settles a held or fresh write: a farewell is refused (rolled back, then `rejected`), anything else confirmed.\npub fn settle_write(state: &Arc<Mutex<State>>, id: &str, message: &str) {\n let mut s = state.lock().expect(\"state\");\n let g = s.generation;\n if message.to_lowercase().contains(\"goodbye\") {\n let row_id = format!(\"g-{id}\");\n s.rows.retain(|(_, r)| r[\"id\"] != json!(row_id));\n s.emit_rows();\n s.emit(json!({ \"type\": \"write\", \"id\": id, \"generation\": g, \"phase\": \"rejected\",\n \"error\": { \"_tag\": \"Forbidden\", \"message\": \"farewells are not allowed\", \"action\": \"hello.greet\" } }));\n } else {\n s.emit(json!({ \"type\": \"write\", \"id\": id, \"generation\": g, \"phase\": \"confirmed\" }));\n }\n}\n\n/// The app over `fake`, in a headless Runtime (no window, no GPU), its outstanding sends in memory.\npub fn runtime(fake: &Fake) -> rune::Runtime<eloxiv_desktop_rune::Ui> {\n runtime_in(fake, None)\n}\n\n/// The app over `fake` with the data directory `dir`.\npub fn runtime_in(fake: &Fake, dir: Option<&std::path::Path>) -> rune::Runtime<eloxiv_desktop_rune::Ui> {\n let mut rt = eloxiv_desktop_rune::app_in(fake.url.clone(), TOKEN.into(), dir.map(std::path::Path::to_path_buf))\n .headless_runtime((900.0, 700.0), rune::Env::new(false, 1.0));\n // The agent's readiness is asked again sooner than a person's host does, while it is blocked.\n rt.state.readiness_recheck = Duration::from_millis(50);\n rt.frame(0.0);\n rt\n}\n\n/// A directory of its own under the system's temporary directory, removed (with everything in it) when dropped.\npub struct TempDir(pub std::path::PathBuf);\n\nimpl TempDir {\n pub fn new(name: &str) -> TempDir {\n let dir = std::env::temp_dir().join(format!(\"eloxiv-rune-{name}-{}\", eloxiv_desktop_rune::random_id()));\n std::fs::create_dir_all(&dir).expect(\"a temporary directory\");\n TempDir(dir)\n }\n}\n\nimpl Drop for TempDir {\n fn drop(&mut self) {\n let _ = std::fs::remove_dir_all(&self.0);\n }\n}\n\n/// Frames until `done` holds (the worker threads answer in real time), at most 5 s.\npub fn until(\n rt: &mut rune::Runtime<eloxiv_desktop_rune::Ui>,\n what: &str,\n done: impl Fn(&eloxiv_desktop_rune::Ui) -> bool,\n) {\n let deadline = Instant::now() + Duration::from_secs(5);\n loop {\n rt.frame(1.0 / 60.0);\n if done(&rt.state) {\n rt.frame(1.0 / 60.0);\n return;\n }\n assert!(Instant::now() < deadline, \"timed out waiting for {what}\");\n std::thread::sleep(Duration::from_millis(5));\n }\n}\n\n/// Frames for a while, letting the worker answer, without a condition.\npub fn settle(rt: &mut rune::Runtime<eloxiv_desktop_rune::Ui>, ms: u64) {\n let deadline = Instant::now() + Duration::from_millis(ms);\n while Instant::now() < deadline {\n rt.frame(1.0 / 60.0);\n std::thread::sleep(Duration::from_millis(5));\n }\n}\n\n/// Presses the element keyed `key` the way an assistive client does (its `on_press`).\npub fn press(rt: &mut rune::Runtime<eloxiv_desktop_rune::Ui>, key: &str) {\n assert!(rt.accessibility_action(key, rune::accesskit::Action::Click, None), \"{key} cannot be pressed\");\n rt.frame(1.0 / 60.0);\n}\n\n/// Sets a text field's value through its editor (`on_input_change` runs).\npub fn type_into(rt: &mut rune::Runtime<eloxiv_desktop_rune::Ui>, key: &str, value: &str) {\n assert!(\n rt.accessibility_action(\n key,\n rune::accesskit::Action::SetValue,\n Some(rune::accesskit::ActionData::Value(value.into()))\n ),\n \"{key} takes no value\"\n );\n rt.frame(1.0 / 60.0);\n}\n\n/// The accessibility tree's nodes, flattened (each with `role`, `key`, `name`, ...).\npub fn a11y_nodes(rt: &rune::Runtime<eloxiv_desktop_rune::Ui>) -> Vec<Value> {\n fn walk(v: &Value, out: &mut Vec<Value>) {\n if v.get(\"role\").is_some() {\n out.push(v.clone());\n }\n if let Some(children) = v.get(\"children\").and_then(Value::as_array) {\n for c in children {\n walk(c, out);\n }\n }\n }\n let mut out = Vec::new();\n walk(&rt.accessibility_json(), &mut out);\n out\n}\n\npub fn a11y(rt: &rune::Runtime<eloxiv_desktop_rune::Ui>, key: &str) -> Option<Value> {\n a11y_nodes(rt).into_iter().find(|n| n.get(\"key\").and_then(Value::as_str) == Some(key))\n}\n\n/// Signs in through the fake (the browser's part played by `complete_sign_in`) and waits for the live list.\npub fn signed_in(fake: &Fake) -> rune::Runtime<eloxiv_desktop_rune::Ui> {\n let mut rt = runtime(fake);\n until(&mut rt, \"the sign-in screen\", |s| matches!(s.model.session, eloxiv_desktop_rune::model::Session::SignedOut));\n press(&mut rt, \"sign-in\");\n until(&mut rt, \"the browser opened\", |s| s.sign_in_url.is_some());\n assert_eq!(rt.take_url_requests().len(), 1, \"the sign-in page, and nothing else\");\n fake.with(State::complete_sign_in);\n until(&mut rt, \"the greetings\", |s| s.model.list.rows.len() >= 2);\n rt\n}\n\n/// Whether the node keyed `key` has state `state` (`checked`, `disabled`, `selected`, ...).\npub fn has_state(rt: &rune::Runtime<eloxiv_desktop_rune::Ui>, key: &str, state: &str) -> bool {\n a11y(rt, key)\n .and_then(|n| n.get(\"states\").and_then(Value::as_array).cloned())\n .is_some_and(|s| s.iter().any(|v| v == state))\n}\n",
288
+ "type": "registry:file",
289
+ "target": "desktop-rune/app/tests/support/mod.rs"
290
+ },
291
+ {
292
+ "path": "app/desktop-rune/crates/eloxiv-local-client-codegen/Cargo.toml",
293
+ "content": "[package]\nname = \"eloxiv-local-client-codegen\"\nversion = \"0.1.0\"\ndescription = \"Generates eloxiv-local-client's types with typify from Eloxiv's JSON Schemas, and checks they are current\"\nedition.workspace = true\nrust-version.workspace = true\nlicense.workspace = true\npublish.workspace = true\n\n[dependencies]\ntypify = \"=0.10.1\"\nprettyplease = \"=0.2.37\"\nsyn = { version = \"2\", features = [\"full\"] }\nschemars = \"0.8\"\nserde_json.workspace = true\n\n[lints]\nworkspace = true\n",
294
+ "type": "registry:file",
295
+ "target": "desktop-rune/crates/eloxiv-local-client-codegen/Cargo.toml"
296
+ },
297
+ {
298
+ "path": "app/desktop-rune/crates/eloxiv-local-client-codegen/src/lib.rs",
299
+ "content": "//! Generates `eloxiv-local-client`'s `src/generated.rs` with typify from Eloxiv's JSON Schemas. The crate's\n//! freshness test (`tests/fresh.rs`) generates it again and fails while the checked-in file differs;\n//! `cargo run -p eloxiv-local-client-codegen` writes it.\n//!\n//! Inputs (emitted by `pnpm --filter @eloxiv/contracts emit`, never hand-written): the code generation bundles\n//! `schema/codegen/LocalClient.json` (the LocalClient contract) and `schema/codegen/Sandbox.json` (the MAKE view\n//! runtime's types: `MakeViewStep`, `MakeViewMessage`, `MakeViewNode`, `MakeViewElement`, `MakeViewProps`,\n//! `MakeViewPropValue`, `MakeViewCall`). Each has every type under `$defs` by its own name, tagged unions as `oneOf`\n//! and Effect's encodings a generator reads poorly already simplified (`codegenBundle` in `@eloxiv/contracts`), so\n//! nothing is renamed or rewritten here, except one name Rust cannot take: `Ok` is generated as `OkAnswer` (a type\n//! called `Ok` would shadow `Result::Ok` in the generated module).\n//!\n//! The schemas are found in this repository (`packages/contracts/schema`) or, in an app that installed the item,\n//! in `node_modules/@eloxiv/contracts/schema`; `ELOXIV_CONTRACTS_SCHEMA` names another directory. Without them the\n//! freshness test skips, unless `ELOXIV_REQUIRE_SCHEMAS=1` (CI and `mise run rust:check`), where it fails.\n\nuse std::collections::BTreeMap;\nuse std::path::{Path, PathBuf};\n\nuse serde_json::{Map, Value, json};\n\nconst HEADER: &str = \"//! Generated by `eloxiv-local-client-codegen` (typify) from `@eloxiv/contracts`' `schema/codegen/LocalClient.json` and\\n//! `schema/codegen/Sandbox.json`. Do not edit: `cargo run -p eloxiv-local-client-codegen` writes it\\n//! again, and its test fails while this file differs from what the schemas give.\\n\\n\";\n\n/// The bundles generated from, in order.\nconst BUNDLES: [&str; 2] = [\"codegen/LocalClient.json\", \"codegen/Sandbox.json\"];\n\n/// The directory holding the bundles, if one is found.\npub fn schema_dir() -> Option<PathBuf> {\n if let Ok(dir) = std::env::var(\"ELOXIV_CONTRACTS_SCHEMA\") {\n return Some(PathBuf::from(dir));\n }\n let crate_dir = Path::new(env!(\"CARGO_MANIFEST_DIR\"));\n // Both crates sit side by side under crates/.\n let candidates = [\n // registry/app/desktop-rune/crates/eloxiv-local-client -> the repository root\n crate_dir.join(\"../../../../../packages/contracts/schema\"),\n // <app>/desktop-rune/crates/eloxiv-local-client -> the app root\n crate_dir.join(\"../../../node_modules/@eloxiv/contracts/schema\"),\n ];\n candidates.into_iter().find(|p| BUNDLES.iter().all(|bundle| p.join(bundle).is_file()))\n}\n\nfn read(path: &Path) -> Value {\n let text = std::fs::read_to_string(path).unwrap_or_else(|e| panic!(\"{}: {e}\", path.display()));\n serde_json::from_str(&text).unwrap_or_else(|e| panic!(\"{}: {e}\", path.display()))\n}\n\n/// Rewrites every `$ref` `#/$defs/<from>` (or `#/definitions/<from>`) through `rename`, as `#/definitions/<to>`.\nfn rewrite_refs(value: &mut Value, rename: &dyn Fn(&str) -> String) {\n match value {\n Value::Object(map) => {\n for (key, field) in map.iter_mut() {\n if key == \"$ref\"\n && let Value::String(r) = field\n {\n let name = r.strip_prefix(\"#/$defs/\").or_else(|| r.strip_prefix(\"#/definitions/\"));\n if let Some(name) = name {\n *r = format!(\"#/definitions/{}\", rename(name));\n }\n } else {\n rewrite_refs(field, rename);\n }\n }\n }\n Value::Array(items) => items.iter_mut().for_each(|v| rewrite_refs(v, rename)),\n _ => {}\n }\n}\n\n/// The definitions typify generates from, by name: every bundle's `$defs`, with `$ref`s as `#/definitions/...`.\nfn definitions(dir: &Path) -> BTreeMap<String, Value> {\n let rename = |name: &str| if name == \"Ok\" { \"OkAnswer\".to_owned() } else { name.to_owned() };\n let mut defs = BTreeMap::new();\n for bundle in BUNDLES {\n let document = read(&dir.join(bundle));\n let bundle_defs = document.get(\"$defs\").and_then(Value::as_object).cloned().unwrap_or_default();\n assert!(!bundle_defs.is_empty(), \"{bundle} has no $defs\");\n for (name, mut schema) in bundle_defs {\n rewrite_refs(&mut schema, &rename);\n let name = rename(&name);\n if let Some(existing) = defs.get(&name) {\n assert!(existing == &schema, \"two different types are both named {name}\");\n }\n defs.insert(name, schema);\n }\n }\n defs\n}\n\n/// `src/generated.rs` as the schemas in `dir` give it.\npub fn generate(dir: &Path) -> String {\n let defs = definitions(dir);\n let root = json!({\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"definitions\": Value::Object(defs.into_iter().collect::<Map<_, _>>()),\n });\n let root: schemars::schema::RootSchema = serde_json::from_value(root).expect(\"a JSON Schema document\");\n // typify's defaults: Serialize, Deserialize, Clone and Debug always; PartialEq, Eq, Default and the rest where\n // a type supports them.\n let settings = typify::TypeSpaceSettings::default();\n let mut space = typify::TypeSpace::new(&settings);\n space.add_root_schema(root).expect(\"typify accepts the schemas\");\n let file: syn::File =\n syn::parse2(space.to_stream().expect(\"typify generates the types\")).expect(\"typify's output parses\");\n format!(\"{HEADER}{}\", prettyplease::unparse(&file))\n}\n\n/// Where the generated file lives.\npub fn target() -> PathBuf {\n Path::new(env!(\"CARGO_MANIFEST_DIR\")).join(\"../eloxiv-local-client/src/generated.rs\")\n}\n",
300
+ "type": "registry:file",
301
+ "target": "desktop-rune/crates/eloxiv-local-client-codegen/src/lib.rs"
302
+ },
303
+ {
304
+ "path": "app/desktop-rune/crates/eloxiv-local-client-codegen/src/main.rs",
305
+ "content": "//! `cargo run -p eloxiv-local-client-codegen`: writes `eloxiv-local-client/src/generated.rs` from the schemas.\n\nfn main() {\n let Some(dir) = eloxiv_local_client_codegen::schema_dir() else {\n eprintln!(\"no @eloxiv/contracts schema directory found; set ELOXIV_CONTRACTS_SCHEMA\");\n std::process::exit(1);\n };\n let target = eloxiv_local_client_codegen::target();\n if let Err(e) = std::fs::write(&target, eloxiv_local_client_codegen::generate(&dir)) {\n eprintln!(\"{}: {e}\", target.display());\n std::process::exit(1);\n }\n println!(\"wrote {} from {}\", target.display(), dir.display());\n}\n",
306
+ "type": "registry:file",
307
+ "target": "desktop-rune/crates/eloxiv-local-client-codegen/src/main.rs"
308
+ },
309
+ {
310
+ "path": "app/desktop-rune/crates/eloxiv-local-client-codegen/tests/fresh.rs",
311
+ "content": "//! The checked-in `eloxiv-local-client/src/generated.rs` is exactly what the schemas give.\n\n#[test]\nfn generated_types_match_the_schemas() {\n let Some(dir) = eloxiv_local_client_codegen::schema_dir() else {\n assert!(\n std::env::var(\"ELOXIV_REQUIRE_SCHEMAS\").as_deref() != Ok(\"1\"),\n \"ELOXIV_REQUIRE_SCHEMAS=1 but no @eloxiv/contracts schema directory was found\"\n );\n eprintln!(\"skipped: no @eloxiv/contracts schema directory (set ELOXIV_CONTRACTS_SCHEMA)\");\n return;\n };\n let generated = eloxiv_local_client_codegen::generate(&dir);\n // A Windows checkout may turn the file's line endings into CRLF (core.autocrlf); compare the text, not them.\n let current =\n std::fs::read_to_string(eloxiv_local_client_codegen::target()).unwrap_or_default().replace(\"\\r\\n\", \"\\n\");\n assert!(\n current == generated.replace(\"\\r\\n\", \"\\n\"),\n \"eloxiv-local-client/src/generated.rs is stale against {}: run cargo run -p eloxiv-local-client-codegen\",\n dir.display()\n );\n}\n",
312
+ "type": "registry:file",
313
+ "target": "desktop-rune/crates/eloxiv-local-client-codegen/tests/fresh.rs"
314
+ },
315
+ {
316
+ "path": "app/desktop-rune/crates/eloxiv-local-client/Cargo.toml",
317
+ "content": "[package]\nname = \"eloxiv-local-client\"\nversion = \"0.1.0\"\ndescription = \"LocalClient v1 for Rust: protocol and MAKE view types generated from Eloxiv's JSON Schemas, a blocking HTTP client and an SSE reader\"\nedition.workspace = true\nrust-version.workspace = true\nlicense.workspace = true\npublish.workspace = true\n\n[dependencies]\nserde.workspace = true\nserde_json.workspace = true\nureq.workspace = true\n\n[lints]\nworkspace = true\n",
318
+ "type": "registry:file",
319
+ "target": "desktop-rune/crates/eloxiv-local-client/Cargo.toml"
320
+ },
321
+ {
322
+ "path": "app/desktop-rune/crates/eloxiv-local-client/src/client.rs",
323
+ "content": "//! The requests of LocalClient v1: blocking, one call per route, typed answers and typed refusals.\n//!\n//! Every call blocks its thread; call them off the UI thread.\n\nuse std::time::Duration;\n\nuse serde::Serialize;\nuse serde::de::DeserializeOwned;\nuse serde_json::{Value, json};\n\nuse crate::error::ClientError;\nuse crate::generated::{\n EngineReadiness, GenerationAnswer, Hello, OkAnswer, SessionState, SignInStarted, Subscribed, WriteAccepted,\n};\nuse crate::sse::{EventStream, StreamItem};\n\n/// The protocol this crate speaks (`GET /client/v1/hello` answers it).\npub const PROTOCOL: &str = \"eloxiv.local-client\";\n/// The major version this crate speaks; a daemon answering another major is refused by [`LocalClient::hello`].\npub const MAJOR: u64 = 1;\n/// The version this crate names in `x-eloxiv-local-client` on every request: a daemon of another major refuses it\n/// with `ProtocolVersion`.\npub const VERSION: &str = \"1.2.0\";\npub const VERSION_HEADER: &str = \"x-eloxiv-local-client\";\n/// Longest answer body read (an action's result).\npub const MAX_BODY_BYTES: u64 = 16 * 1024 * 1024;\n\n/// A client of one daemon's `/client/v1`, authenticated with one local token (the host secret, or a paired\n/// `desktop-app` client's token). Cheap to clone; every clone shares the connection pool.\n#[derive(Clone)]\npub struct LocalClient {\n base: String,\n token: String,\n agent: ureq::Agent,\n}\n\nimpl std::fmt::Debug for LocalClient {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n // Never the token.\n f.debug_struct(\"LocalClient\").field(\"base\", &self.base).finish_non_exhaustive()\n }\n}\n\nimpl LocalClient {\n /// A client of the daemon at `base` (`http://127.0.0.1:<port>`; the daemon accepts only a loopback Host).\n pub fn new(base: impl Into<String>, token: impl Into<String>) -> LocalClient {\n let config = ureq::Agent::config_builder()\n .http_status_as_error(false)\n .timeout_global(Some(Duration::from_secs(60)))\n .timeout_connect(Some(Duration::from_secs(5)))\n .build();\n LocalClient { base: base.into().trim_end_matches('/').to_owned(), token: token.into(), agent: config.into() }\n }\n\n /// The daemon's address.\n pub fn base(&self) -> &str {\n &self.base\n }\n\n /// `GET /health` (unauthenticated): whether the daemon answers.\n pub fn health(&self) -> bool {\n self.agent\n .get(format!(\"{}/health\", self.base))\n .config()\n .timeout_global(Some(Duration::from_secs(2)))\n .build()\n .call()\n .is_ok_and(|r| r.status().is_success())\n }\n\n /// `GET /client/v1/hello`: the protocol, its version and the app. Refuses a protocol or major version this\n /// crate does not speak with `ProtocolVersion`.\n pub fn hello(&self) -> Result<Hello, ClientError> {\n let hello: Hello = self.get(\"/client/v1/hello\")?;\n let major = hello.version.split('.').next().and_then(|m| m.parse::<u64>().ok());\n if major != Some(MAJOR) {\n return Err(ClientError::RefusedOther {\n status: 200,\n tag: \"ProtocolVersion\".into(),\n message: format!(\"the daemon speaks LocalClient {}, this host {MAJOR}.x\", hello.version),\n body: Value::Null,\n });\n }\n Ok(hello)\n }\n\n /// `GET /client/v1/session`.\n pub fn session(&self) -> Result<SessionState, ClientError> {\n self.get(\"/client/v1/session\")\n }\n\n /// `POST /client/v1/sign-in`: the URL to open in the system browser.\n pub fn sign_in(&self) -> Result<SignInStarted, ClientError> {\n self.post(\"/client/v1/sign-in\", &json!({}))\n }\n\n /// `POST /client/v1/org`: select an organisation; answers the new generation (a `context` event precedes the\n /// `session` event on the stream).\n pub fn select_org(&self, org_id: &str) -> Result<GenerationAnswer, ClientError> {\n self.post(\"/client/v1/org\", &json!({ \"orgId\": org_id }))\n }\n\n /// `POST /client/v1/sign-out`: answers once revocation is confirmed.\n pub fn sign_out(&self) -> Result<OkAnswer, ClientError> {\n self.post(\"/client/v1/sign-out\", &json!({}))\n }\n\n /// `POST /client/v1/subscriptions`: run a named query live; its `rows` events follow on the stream. `id` is the\n /// client's choice (1 to 128 characters), so a `rows` event that arrives before the answer is already known.\n pub fn subscribe(&self, query: &str, args: Value, id: Option<&str>) -> Result<Subscribed, ClientError> {\n let mut body = json!({ \"query\": query, \"args\": args });\n if let Some(id) = id {\n body[\"id\"] = Value::String(id.to_owned());\n }\n self.post(\"/client/v1/subscriptions\", &body)\n }\n\n /// `DELETE /client/v1/subscriptions/:id`.\n pub fn unsubscribe(&self, id: &str) -> Result<OkAnswer, ClientError> {\n self.send(\"DELETE\", &format!(\"/client/v1/subscriptions/{}\", encode(id)), None)\n }\n\n /// `POST /client/v1/writes`: an optimistic write through the app's mutator; its `write` events follow. With\n /// `generation` (1.1.0), the generation it was made in: refused with `StaleGeneration`, unwritten, in another.\n pub fn write(\n &self,\n mutator: &str,\n input: Value,\n id: Option<&str>,\n generation: Option<i64>,\n ) -> Result<WriteAccepted, ClientError> {\n let mut body = json!({ \"mutator\": mutator, \"input\": input });\n if let Some(id) = id {\n body[\"id\"] = Value::String(id.to_owned());\n }\n if let Some(g) = generation {\n body[\"generation\"] = json!(g);\n }\n self.post(\"/client/v1/writes\", &body)\n }\n\n /// `POST /client/v1/actions/:name`: a non-optimistic call as the person in the selected organisation;\n /// answers the action's result envelope (`{ kind: \"output\", output }` or a replay). With `generation` (1.1.0),\n /// the generation it was made in: in another, the daemon refuses it with `StaleGeneration` naming the current one\n /// and runs nothing ([`ClientError::not_run_in`]).\n pub fn action(\n &self,\n name: &str,\n input: Value,\n idempotency_key: Option<&str>,\n generation: Option<i64>,\n ) -> Result<Value, ClientError> {\n let mut body = json!({ \"input\": input });\n if let Some(key) = idempotency_key {\n body[\"idempotencyKey\"] = Value::String(key.to_owned());\n }\n if let Some(g) = generation {\n body[\"generation\"] = json!(g);\n }\n self.post(&format!(\"/client/v1/actions/{}\", encode(name)), &body)\n }\n\n /// `POST /client/v1/runs` (1.1.0): follow an agent run's events after the stored event `after` (-1: from the\n /// start); its `run` events follow on the stream, for this client only, ending after `run-finished` (or with the\n /// kernel's refusal). `id` is the client's choice, so an event that arrives before the answer is already known.\n pub fn follow_run(&self, run_id: &str, after: i64, id: Option<&str>) -> Result<Subscribed, ClientError> {\n let mut body = json!({ \"runId\": run_id, \"after\": after });\n if let Some(id) = id {\n body[\"id\"] = Value::String(id.to_owned());\n }\n self.post(\"/client/v1/runs\", &body)\n }\n\n /// `DELETE /client/v1/runs/:id` (1.1.0): stop following a run.\n pub fn unfollow_run(&self, id: &str) -> Result<OkAnswer, ClientError> {\n self.send(\"DELETE\", &format!(\"/client/v1/runs/{}\", encode(id)), None)\n }\n\n /// `GET /client/v1/agent/readiness` (1.1.0): whether the person's agent can answer in the selected organisation.\n pub fn agent_readiness(&self) -> Result<EngineReadiness, ClientError> {\n self.get(\"/client/v1/agent/readiness\")\n }\n\n /// `GET /client/v1/events` on a thread of its own (see [`EventStream`]).\n pub fn events(&self, deliver: impl FnMut(StreamItem) + Send + 'static) -> EventStream {\n EventStream::open(&self.base, &self.token, deliver)\n }\n\n fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T, ClientError> {\n self.send(\"GET\", path, None)\n }\n\n fn post<T: DeserializeOwned>(&self, path: &str, body: &impl Serialize) -> Result<T, ClientError> {\n let body = serde_json::to_value(body).map_err(|e| ClientError::Decode(e.to_string()))?;\n self.send(\"POST\", path, Some(body))\n }\n\n fn send<T: DeserializeOwned>(&self, method: &str, path: &str, body: Option<Value>) -> Result<T, ClientError> {\n let url = format!(\"{}{}\", self.base, path);\n let bearer = format!(\"Bearer {}\", self.token);\n let answer = match (method, body) {\n (\"GET\", _) => self.agent.get(&url).header(\"authorization\", &bearer).header(VERSION_HEADER, VERSION).call(),\n (\"DELETE\", _) => {\n self.agent.delete(&url).header(\"authorization\", &bearer).header(VERSION_HEADER, VERSION).call()\n }\n (_, body) => self\n .agent\n .post(&url)\n .header(\"authorization\", &bearer)\n .header(VERSION_HEADER, VERSION)\n .send_json(body.unwrap_or(Value::Null)),\n };\n let mut response = answer.map_err(|e| ClientError::Transport(e.to_string()))?;\n let status = response.status().as_u16();\n let text = response\n .body_mut()\n .with_config()\n .limit(MAX_BODY_BYTES)\n .read_to_string()\n .map_err(|e| ClientError::Transport(e.to_string()))?;\n if !(200..300).contains(&status) {\n return Err(ClientError::from_status(status, &text));\n }\n serde_json::from_str(&text).map_err(|e| ClientError::Decode(format!(\"{method} {path}: {e}\")))\n }\n}\n\n/// Percent-encodes a path segment (an action name, a subscription id).\nfn encode(segment: &str) -> String {\n let mut out = String::with_capacity(segment.len());\n for b in segment.bytes() {\n if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {\n out.push(b as char);\n } else {\n out.push_str(&format!(\"%{b:02X}\"));\n }\n }\n out\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn path_segments_are_encoded() {\n assert_eq!(super::encode(\"mk_notes.add\"), \"mk_notes.add\");\n assert_eq!(super::encode(\"a/b c\"), \"a%2Fb%20c\");\n }\n}\n",
324
+ "type": "registry:file",
325
+ "target": "desktop-rune/crates/eloxiv-local-client/src/client.rs"
326
+ },
327
+ {
328
+ "path": "app/desktop-rune/crates/eloxiv-local-client/src/error.rs",
329
+ "content": "//! What a request can fail with: the daemon's typed refusal, or a failure to reach or read it.\n\nuse std::fmt;\n\nuse crate::generated::LocalClientError;\n\n/// A failed request.\n#[derive(Debug, Clone)]\npub enum ClientError {\n /// The daemon refused with a typed error (`{ _tag, message, ...fields }`, decoded) and this HTTP status.\n Refused { status: u16, error: LocalClientError },\n /// The daemon refused with an error this crate does not know (a newer daemon's `_tag`), kept as JSON.\n RefusedOther { status: u16, tag: String, message: String, body: serde_json::Value },\n /// The daemon could not be reached, or the connection failed.\n Transport(String),\n /// The answer was not what the protocol says.\n Decode(String),\n}\n\nimpl ClientError {\n /// From a non-2xx answer's status and body.\n pub fn from_status(status: u16, body: &str) -> ClientError {\n let value: serde_json::Value = serde_json::from_str(body).unwrap_or(serde_json::Value::Null);\n if let Ok(error) = serde_json::from_value::<LocalClientError>(value.clone()) {\n return ClientError::Refused { status, error };\n }\n let tag = value.get(\"_tag\").and_then(|v| v.as_str()).map_or_else(|| format!(\"HTTP {status}\"), str::to_owned);\n let message = value.get(\"message\").and_then(|v| v.as_str()).unwrap_or(body).to_owned();\n ClientError::RefusedOther { status, tag, message, body: value }\n }\n\n /// The refusal's `_tag` (`Forbidden`, `NotSignedIn`, ...), or the failure's kind.\n pub fn tag(&self) -> String {\n match self {\n ClientError::Refused { error, .. } => tag_of(error),\n ClientError::RefusedOther { tag, .. } => tag.clone(),\n ClientError::Transport(_) => \"Transport\".into(),\n ClientError::Decode(_) => \"Decode\".into(),\n }\n }\n\n /// A message for a person.\n pub fn message(&self) -> String {\n match self {\n ClientError::Refused { error, .. } => message_of(error),\n ClientError::RefusedOther { message, .. } => message.clone(),\n ClientError::Transport(m) | ClientError::Decode(m) => m.clone(),\n }\n }\n\n /// Whether this answers a request made in `generation` with \"nothing was run\": `StaleGeneration` naming another\n /// generation (the current one: the precondition refused it). `StaleGeneration` naming `generation` itself means\n /// the context changed while it ran, so it may have run.\n pub fn not_run_in(&self, generation: i64) -> bool {\n let named = match self {\n ClientError::Refused { error, .. } => serde_json::to_value(error).ok(),\n ClientError::RefusedOther { body, .. } => Some(body.clone()),\n ClientError::Transport(_) | ClientError::Decode(_) => None,\n };\n named.is_some_and(|v| {\n v.get(\"_tag\").and_then(|t| t.as_str()) == Some(\"StaleGeneration\")\n && v.get(\"generation\").and_then(serde_json::Value::as_i64).is_some_and(|g| g != generation)\n })\n }\n\n /// The error as the MAKE view's result message carries it: `{ _tag, message }`.\n pub fn to_view_error(&self) -> serde_json::Value {\n serde_json::json!({ \"_tag\": self.tag(), \"message\": self.message() })\n }\n}\n\n/// A typed refusal's `_tag`, read from its JSON form so it holds for every variant.\npub fn tag_of(error: &LocalClientError) -> String {\n serde_json::to_value(error)\n .ok()\n .and_then(|v| v.get(\"_tag\").and_then(|t| t.as_str()).map(str::to_owned))\n .unwrap_or_else(|| \"Unknown\".into())\n}\n\n/// A typed refusal's `message` (its tag, should one arrive without a message).\npub fn message_of(error: &LocalClientError) -> String {\n let value = serde_json::to_value(error).unwrap_or(serde_json::Value::Null);\n match value.get(\"message\").and_then(|m| m.as_str()) {\n Some(m) => m.to_owned(),\n None => tag_of(error),\n }\n}\n\nimpl fmt::Display for ClientError {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"{}: {}\", self.tag(), self.message())\n }\n}\n\nimpl std::error::Error for ClientError {}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn a_stale_generation_says_whether_the_request_ran() {\n let refused = ClientError::from_status(409, r#\"{\"_tag\":\"StaleGeneration\",\"generation\":5,\"message\":\"m\"}\"#);\n assert!(refused.not_run_in(4), \"refused before it ran: the current generation is named\");\n assert!(!refused.not_run_in(5), \"the context changed while it ran: it may have run\");\n assert!(!ClientError::Transport(\"x\".into()).not_run_in(4));\n }\n}\n",
330
+ "type": "registry:file",
331
+ "target": "desktop-rune/crates/eloxiv-local-client/src/error.rs"
332
+ },
333
+ {
334
+ "path": "app/desktop-rune/crates/eloxiv-local-client/src/generated.rs",
335
+ "content": "//! Generated by `eloxiv-local-client-codegen` (typify) from `@eloxiv/contracts`' `schema/codegen/LocalClient.json` and\n//! `schema/codegen/Sandbox.json`. Do not edit: `cargo run -p eloxiv-local-client-codegen` writes it\n//! again, and its test fails while this file differs from what the schemas give.\n\n///A non-optimistic action call's input, optional idempotency key and, since 1.1.0, the generation the client made it in (`generation`, see `ExpectedGeneration`).\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, Default)]\npub struct ActionCall {\n ///The generation the client made the request in (1.1.0): when another is current, the request is refused with StaleGeneration (naming the current one) and nothing is run. Absent, the current generation is used.\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub generation: ::std::option::Option<i64>,\n #[serde(\n rename = \"idempotencyKey\",\n skip_serializing_if = \"::std::option::Option::is_none\"\n )]\n pub idempotency_key: ::std::option::Option<ActionCallIdempotencyKey>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub input: ::std::option::Option<::serde_json::Value>,\n}\n///`ActionCallIdempotencyKey`\n#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\n#[serde(transparent)]\npub struct ActionCallIdempotencyKey(::std::string::String);\nimpl ::std::ops::Deref for ActionCallIdempotencyKey {\n type Target = ::std::string::String;\n fn deref(&self) -> &::std::string::String {\n &self.0\n }\n}\nimpl ::std::convert::From<ActionCallIdempotencyKey> for ::std::string::String {\n fn from(value: ActionCallIdempotencyKey) -> Self {\n value.0\n }\n}\nimpl ::std::str::FromStr for ActionCallIdempotencyKey {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n ::std::convert::TryFrom::try_from(value)\n }\n}\nimpl ::std::convert::TryFrom<&str> for ActionCallIdempotencyKey {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n if value.chars().count() > 255usize {\n return Err(\"longer than 255 characters\".into());\n }\n if value.chars().count() < 1usize {\n return Err(\"shorter than 1 characters\".into());\n }\n Ok(Self(value.to_string()))\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for ActionCallIdempotencyKey {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n ::std::convert::TryFrom::try_from(value.as_str())\n }\n}\nimpl<'de> ::serde::Deserialize<'de> for ActionCallIdempotencyKey {\n fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>\n where\n D: ::serde::Deserializer<'de>,\n {\n ::std::convert::TryFrom::try_from(\n ::std::string::String::deserialize(deserializer)?,\n )\n .map_err(|e: self::error::ConversionError| {\n <D::Error as ::serde::de::Error>::custom(e.to_string())\n })\n }\n}\n///`ActionFailed`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct ActionFailed {\n pub action: ::std::string::String,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub effect: ::std::option::Option<ActionFailedEffect>,\n pub message: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: ActionFailedTag,\n}\n///`ActionFailedEffect`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum ActionFailedEffect {\n #[serde(rename = \"none\")]\n None,\n #[serde(rename = \"unknown\")]\n Unknown,\n}\nimpl ::std::fmt::Display for ActionFailedEffect {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::None => f.write_str(\"none\"),\n Self::Unknown => f.write_str(\"unknown\"),\n }\n }\n}\nimpl ::std::str::FromStr for ActionFailedEffect {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"none\" => Ok(Self::None),\n \"unknown\" => Ok(Self::Unknown),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for ActionFailedEffect {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for ActionFailedEffect {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///`ActionFailedTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum ActionFailedTag {\n ActionFailed,\n}\nimpl ::std::fmt::Display for ActionFailedTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::ActionFailed => f.write_str(\"ActionFailed\"),\n }\n }\n}\nimpl ::std::str::FromStr for ActionFailedTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"ActionFailed\" => Ok(Self::ActionFailed),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for ActionFailedTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for ActionFailedTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///The action's result envelope as every surface returns it: `{ kind: \"output\", output }` or, for a replayed idempotent call, `{ kind: \"replay\", receipt }`.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\n#[serde(transparent)]\npub struct ActionResult(pub ::serde_json::Value);\nimpl ::std::ops::Deref for ActionResult {\n type Target = ::serde_json::Value;\n fn deref(&self) -> &::serde_json::Value {\n &self.0\n }\n}\nimpl ::std::convert::From<ActionResult> for ::serde_json::Value {\n fn from(value: ActionResult) -> Self {\n value.0\n }\n}\nimpl ::std::convert::From<::serde_json::Value> for ActionResult {\n fn from(value: ::serde_json::Value) -> Self {\n Self(value)\n }\n}\n///One event of an agent run, as the chat SDK's `chatClient.events` delivers it: its run, its stored sequence number (`-1` for streamed text, `text-delta`, whose `data` has `delta`, `step` and `attempt`), its type, its data (`consent-required`: `consentId`, `action`, `toolCallId`, `step`; `model-step`: `step`, `text`; `run-finished`: `status`, ...) and when it happened (empty for streamed text).\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct AgentRunEvent {\n pub at: ::std::string::String,\n pub data: ::serde_json::Value,\n #[serde(rename = \"runId\")]\n pub run_id: ::std::string::String,\n pub seq: i64,\n #[serde(rename = \"type\")]\n pub type_: RunEventKind,\n}\n///What the app composed into the daemon offers: its named queries, optimistic mutators and actions.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct AppInfo {\n pub actions: ::std::vec::Vec<::std::string::String>,\n pub mutators: ::std::vec::Vec<::std::string::String>,\n pub queries: ::std::vec::Vec<::std::string::String>,\n}\n///`ApprovalRequired`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct ApprovalRequired {\n pub action: ::std::string::String,\n #[serde(rename = \"approvalId\")]\n pub approval_id: ::std::string::String,\n pub message: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: ApprovalRequiredTag,\n}\n///`ApprovalRequiredTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum ApprovalRequiredTag {\n ApprovalRequired,\n}\nimpl ::std::fmt::Display for ApprovalRequiredTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::ApprovalRequired => f.write_str(\"ApprovalRequired\"),\n }\n }\n}\nimpl ::std::str::FromStr for ApprovalRequiredTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"ApprovalRequired\" => Ok(Self::ApprovalRequired),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for ApprovalRequiredTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for ApprovalRequiredTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///`ClientNotConfigured`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct ClientNotConfigured {\n pub message: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: ClientNotConfiguredTag,\n}\n///`ClientNotConfiguredTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum ClientNotConfiguredTag {\n ClientNotConfigured,\n}\nimpl ::std::fmt::Display for ClientNotConfiguredTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::ClientNotConfigured => f.write_str(\"ClientNotConfigured\"),\n }\n }\n}\nimpl ::std::str::FromStr for ClientNotConfiguredTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"ClientNotConfigured\" => Ok(Self::ClientNotConfigured),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for ClientNotConfiguredTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for ClientNotConfiguredTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///`ClientOutdated`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct ClientOutdated {\n pub action: ::std::string::String,\n #[serde(rename = \"clientVersion\")]\n pub client_version: ::std::string::String,\n pub message: ::std::string::String,\n #[serde(rename = \"minClientVersion\")]\n pub min_client_version: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: ClientOutdatedTag,\n}\n///`ClientOutdatedTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum ClientOutdatedTag {\n ClientOutdated,\n}\nimpl ::std::fmt::Display for ClientOutdatedTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::ClientOutdated => f.write_str(\"ClientOutdated\"),\n }\n }\n}\nimpl ::std::str::FromStr for ClientOutdatedTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"ClientOutdated\" => Ok(Self::ClientOutdated),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for ClientOutdatedTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for ClientOutdatedTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///The replica's connection changed.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct ConnectionEvent {\n ///Increases by one per event on its stream, starting at 1.\n pub seq: ::std::num::NonZeroU64,\n pub state: ConnectionState,\n #[serde(rename = \"type\")]\n pub type_: ConnectionEventType,\n}\n///`ConnectionEventType`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum ConnectionEventType {\n #[serde(rename = \"connection\")]\n Connection,\n}\nimpl ::std::fmt::Display for ConnectionEventType {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::Connection => f.write_str(\"connection\"),\n }\n }\n}\nimpl ::std::str::FromStr for ConnectionEventType {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"connection\" => Ok(Self::Connection),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for ConnectionEventType {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for ConnectionEventType {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///The replica's connection to the sync server.\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum ConnectionState {\n #[serde(rename = \"connecting\")]\n Connecting,\n #[serde(rename = \"connected\")]\n Connected,\n #[serde(rename = \"disconnected\")]\n Disconnected,\n #[serde(rename = \"needsAuth\")]\n NeedsAuth,\n}\nimpl ::std::fmt::Display for ConnectionState {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::Connecting => f.write_str(\"connecting\"),\n Self::Connected => f.write_str(\"connected\"),\n Self::Disconnected => f.write_str(\"disconnected\"),\n Self::NeedsAuth => f.write_str(\"needsAuth\"),\n }\n }\n}\nimpl ::std::str::FromStr for ConnectionState {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"connecting\" => Ok(Self::Connecting),\n \"connected\" => Ok(Self::Connected),\n \"disconnected\" => Ok(Self::Disconnected),\n \"needsAuth\" => Ok(Self::NeedsAuth),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for ConnectionState {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for ConnectionState {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///`ConsentRequired`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct ConsentRequired {\n pub action: ::std::string::String,\n #[serde(rename = \"consentId\")]\n pub consent_id: ::std::string::String,\n pub message: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: ConsentRequiredTag,\n}\n///`ConsentRequiredTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum ConsentRequiredTag {\n ConsentRequired,\n}\nimpl ::std::fmt::Display for ConsentRequiredTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::ConsentRequired => f.write_str(\"ConsentRequired\"),\n }\n }\n}\nimpl ::std::str::FromStr for ConsentRequiredTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"ConsentRequired\" => Ok(Self::ConsentRequired),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for ConsentRequiredTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for ConsentRequiredTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///A reset: drop every row, view and write of older generations. After it, no event of an older generation is ever sent; subscriptions of older generations are gone (subscribe again).\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct ContextEvent {\n pub generation: i64,\n pub reason: ContextReason,\n ///Increases by one per event on its stream, starting at 1.\n pub seq: ::std::num::NonZeroU64,\n #[serde(rename = \"type\")]\n pub type_: ContextEventType,\n}\n///`ContextEventType`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum ContextEventType {\n #[serde(rename = \"context\")]\n Context,\n}\nimpl ::std::fmt::Display for ContextEventType {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::Context => f.write_str(\"context\"),\n }\n }\n}\nimpl ::std::str::FromStr for ContextEventType {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"context\" => Ok(Self::Context),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for ContextEventType {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for ContextEventType {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///Why the context was reset: another organisation was selected, the person signed out, or the sync server refused the session.\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum ContextReason {\n #[serde(rename = \"org\")]\n Org,\n #[serde(rename = \"signOut\")]\n SignOut,\n #[serde(rename = \"needsAuth\")]\n NeedsAuth,\n}\nimpl ::std::fmt::Display for ContextReason {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::Org => f.write_str(\"org\"),\n Self::SignOut => f.write_str(\"signOut\"),\n Self::NeedsAuth => f.write_str(\"needsAuth\"),\n }\n }\n}\nimpl ::std::str::FromStr for ContextReason {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"org\" => Ok(Self::Org),\n \"signOut\" => Ok(Self::SignOut),\n \"needsAuth\" => Ok(Self::NeedsAuth),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for ContextReason {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for ContextReason {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///No fields.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\n#[serde(transparent)]\npub struct Empty(pub ::serde_json::Map<::std::string::String, ::serde_json::Value>);\nimpl ::std::ops::Deref for Empty {\n type Target = ::serde_json::Map<::std::string::String, ::serde_json::Value>;\n fn deref(&self) -> &::serde_json::Map<::std::string::String, ::serde_json::Value> {\n &self.0\n }\n}\nimpl ::std::convert::From<Empty>\nfor ::serde_json::Map<::std::string::String, ::serde_json::Value> {\n fn from(value: Empty) -> Self {\n value.0\n }\n}\nimpl ::std::convert::From<::serde_json::Map<::std::string::String, ::serde_json::Value>>\nfor Empty {\n fn from(\n value: ::serde_json::Map<::std::string::String, ::serde_json::Value>,\n ) -> Self {\n Self(value)\n }\n}\n///Whether the person's agent can answer in the selected organisation, as the kernel decides it: `configured`, `missing` (no model set up: a chat keeps its draft and does not send), `unavailable`, or `unknown` (the kernel could not be asked, which holds nothing back). `detail` is for people; never a credential.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct EngineReadiness {\n pub detail: ::std::string::String,\n #[serde(deserialize_with = \"::std::option::Option::deserialize\")]\n pub model: ::std::option::Option<::std::string::String>,\n #[serde(deserialize_with = \"::std::option::Option::deserialize\")]\n pub provider: ::std::option::Option<::std::string::String>,\n pub state: EngineReadinessState,\n}\n///`EngineReadinessState`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum EngineReadinessState {\n #[serde(rename = \"configured\")]\n Configured,\n #[serde(rename = \"missing\")]\n Missing,\n #[serde(rename = \"unavailable\")]\n Unavailable,\n #[serde(rename = \"unknown\")]\n Unknown,\n}\nimpl ::std::fmt::Display for EngineReadinessState {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::Configured => f.write_str(\"configured\"),\n Self::Missing => f.write_str(\"missing\"),\n Self::Unavailable => f.write_str(\"unavailable\"),\n Self::Unknown => f.write_str(\"unknown\"),\n }\n }\n}\nimpl ::std::str::FromStr for EngineReadinessState {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"configured\" => Ok(Self::Configured),\n \"missing\" => Ok(Self::Missing),\n \"unavailable\" => Ok(Self::Unavailable),\n \"unknown\" => Ok(Self::Unknown),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for EngineReadinessState {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for EngineReadinessState {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///One event on the stream (`GET /client/v1/events`), tagged by `type`; each is one SSE `data:` line.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\n#[serde(untagged)]\npub enum Event {\n SessionEvent(SessionEvent),\n ContextEvent(ContextEvent),\n RowsEvent(RowsEvent),\n WriteEvent(WriteEvent),\n ConnectionEvent(ConnectionEvent),\n RunEvent(RunEvent),\n}\nimpl ::std::convert::From<SessionEvent> for Event {\n fn from(value: SessionEvent) -> Self {\n Self::SessionEvent(value)\n }\n}\nimpl ::std::convert::From<ContextEvent> for Event {\n fn from(value: ContextEvent) -> Self {\n Self::ContextEvent(value)\n }\n}\nimpl ::std::convert::From<RowsEvent> for Event {\n fn from(value: RowsEvent) -> Self {\n Self::RowsEvent(value)\n }\n}\nimpl ::std::convert::From<WriteEvent> for Event {\n fn from(value: WriteEvent) -> Self {\n Self::WriteEvent(value)\n }\n}\nimpl ::std::convert::From<ConnectionEvent> for Event {\n fn from(value: ConnectionEvent) -> Self {\n Self::ConnectionEvent(value)\n }\n}\nimpl ::std::convert::From<RunEvent> for Event {\n fn from(value: RunEvent) -> Self {\n Self::RunEvent(value)\n }\n}\n///Follow an agent run's events (`runId`, from `agent.send`'s answer or `agent.runs`) after the stored event `after` (exclusive; default -1, from the start), under an optional client-chosen id. The run must be the person's, in the selected organisation.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct FollowRun {\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub after: ::std::option::Option<i64>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub id: ::std::option::Option<FollowRunId>,\n #[serde(rename = \"runId\")]\n pub run_id: FollowRunRunId,\n}\n///`FollowRunId`\n#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\n#[serde(transparent)]\npub struct FollowRunId(::std::string::String);\nimpl ::std::ops::Deref for FollowRunId {\n type Target = ::std::string::String;\n fn deref(&self) -> &::std::string::String {\n &self.0\n }\n}\nimpl ::std::convert::From<FollowRunId> for ::std::string::String {\n fn from(value: FollowRunId) -> Self {\n value.0\n }\n}\nimpl ::std::str::FromStr for FollowRunId {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n ::std::convert::TryFrom::try_from(value)\n }\n}\nimpl ::std::convert::TryFrom<&str> for FollowRunId {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n if value.chars().count() > 128usize {\n return Err(\"longer than 128 characters\".into());\n }\n if value.chars().count() < 1usize {\n return Err(\"shorter than 1 characters\".into());\n }\n Ok(Self(value.to_string()))\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for FollowRunId {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n ::std::convert::TryFrom::try_from(value.as_str())\n }\n}\nimpl<'de> ::serde::Deserialize<'de> for FollowRunId {\n fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>\n where\n D: ::serde::Deserializer<'de>,\n {\n ::std::convert::TryFrom::try_from(\n ::std::string::String::deserialize(deserializer)?,\n )\n .map_err(|e: self::error::ConversionError| {\n <D::Error as ::serde::de::Error>::custom(e.to_string())\n })\n }\n}\n///`FollowRunRunId`\n#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\n#[serde(transparent)]\npub struct FollowRunRunId(::std::string::String);\nimpl ::std::ops::Deref for FollowRunRunId {\n type Target = ::std::string::String;\n fn deref(&self) -> &::std::string::String {\n &self.0\n }\n}\nimpl ::std::convert::From<FollowRunRunId> for ::std::string::String {\n fn from(value: FollowRunRunId) -> Self {\n value.0\n }\n}\nimpl ::std::str::FromStr for FollowRunRunId {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n ::std::convert::TryFrom::try_from(value)\n }\n}\nimpl ::std::convert::TryFrom<&str> for FollowRunRunId {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n if value.chars().count() > 128usize {\n return Err(\"longer than 128 characters\".into());\n }\n if value.chars().count() < 1usize {\n return Err(\"shorter than 1 characters\".into());\n }\n Ok(Self(value.to_string()))\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for FollowRunRunId {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n ::std::convert::TryFrom::try_from(value.as_str())\n }\n}\nimpl<'de> ::serde::Deserialize<'de> for FollowRunRunId {\n fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>\n where\n D: ::serde::Deserializer<'de>,\n {\n ::std::convert::TryFrom::try_from(\n ::std::string::String::deserialize(deserializer)?,\n )\n .map_err(|e: self::error::ConversionError| {\n <D::Error as ::serde::de::Error>::custom(e.to_string())\n })\n }\n}\n///`Forbidden`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct Forbidden {\n pub action: ::std::string::String,\n pub message: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: ForbiddenTag,\n}\n///`ForbiddenTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum ForbiddenTag {\n Forbidden,\n}\nimpl ::std::fmt::Display for ForbiddenTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::Forbidden => f.write_str(\"Forbidden\"),\n }\n }\n}\nimpl ::std::str::FromStr for ForbiddenTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"Forbidden\" => Ok(Self::Forbidden),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for ForbiddenTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for ForbiddenTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///The generation now current.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct GenerationAnswer {\n pub generation: i64,\n}\n///The protocol, its version and features, and the app.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct Hello {\n pub app: AppInfo,\n pub features: ::std::vec::Vec<::std::string::String>,\n pub protocol: HelloProtocol,\n pub version: ::std::string::String,\n}\n///`HelloProtocol`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum HelloProtocol {\n #[serde(rename = \"eloxiv.local-client\")]\n EloxivLocalClient,\n}\nimpl ::std::fmt::Display for HelloProtocol {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::EloxivLocalClient => f.write_str(\"eloxiv.local-client\"),\n }\n }\n}\nimpl ::std::str::FromStr for HelloProtocol {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"eloxiv.local-client\" => Ok(Self::EloxivLocalClient),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for HelloProtocol {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for HelloProtocol {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///`IdempotencyConflict`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct IdempotencyConflict {\n pub key: ::std::string::String,\n pub message: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: IdempotencyConflictTag,\n}\n///`IdempotencyConflictTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum IdempotencyConflictTag {\n IdempotencyConflict,\n}\nimpl ::std::fmt::Display for IdempotencyConflictTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::IdempotencyConflict => f.write_str(\"IdempotencyConflict\"),\n }\n }\n}\nimpl ::std::str::FromStr for IdempotencyConflictTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"IdempotencyConflict\" => Ok(Self::IdempotencyConflict),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for IdempotencyConflictTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for IdempotencyConflictTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///`InvalidInput`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct InvalidInput {\n pub message: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: InvalidInputTag,\n}\n///`InvalidInputTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum InvalidInputTag {\n InvalidInput,\n}\nimpl ::std::fmt::Display for InvalidInputTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::InvalidInput => f.write_str(\"InvalidInput\"),\n }\n }\n}\nimpl ::std::str::FromStr for InvalidInputTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"InvalidInput\" => Ok(Self::InvalidInput),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for InvalidInputTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for InvalidInputTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///The kernel's standard error for a refused or failed action: `{ _tag, message, ...fields }`.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\n#[serde(untagged)]\npub enum InvocationError {\n Unauthenticated(Unauthenticated),\n Forbidden(Forbidden),\n ApprovalRequired(ApprovalRequired),\n ConsentRequired(ConsentRequired),\n IdempotencyConflict(IdempotencyConflict),\n InvalidInput(InvalidInput),\n UnknownAction(UnknownAction),\n ActionFailed(ActionFailed),\n ClientOutdated(ClientOutdated),\n}\nimpl ::std::convert::From<Unauthenticated> for InvocationError {\n fn from(value: Unauthenticated) -> Self {\n Self::Unauthenticated(value)\n }\n}\nimpl ::std::convert::From<Forbidden> for InvocationError {\n fn from(value: Forbidden) -> Self {\n Self::Forbidden(value)\n }\n}\nimpl ::std::convert::From<ApprovalRequired> for InvocationError {\n fn from(value: ApprovalRequired) -> Self {\n Self::ApprovalRequired(value)\n }\n}\nimpl ::std::convert::From<ConsentRequired> for InvocationError {\n fn from(value: ConsentRequired) -> Self {\n Self::ConsentRequired(value)\n }\n}\nimpl ::std::convert::From<IdempotencyConflict> for InvocationError {\n fn from(value: IdempotencyConflict) -> Self {\n Self::IdempotencyConflict(value)\n }\n}\nimpl ::std::convert::From<InvalidInput> for InvocationError {\n fn from(value: InvalidInput) -> Self {\n Self::InvalidInput(value)\n }\n}\nimpl ::std::convert::From<UnknownAction> for InvocationError {\n fn from(value: UnknownAction) -> Self {\n Self::UnknownAction(value)\n }\n}\nimpl ::std::convert::From<ActionFailed> for InvocationError {\n fn from(value: ActionFailed) -> Self {\n Self::ActionFailed(value)\n }\n}\nimpl ::std::convert::From<ClientOutdated> for InvocationError {\n fn from(value: ClientOutdated) -> Self {\n Self::ClientOutdated(value)\n }\n}\n///A refusal: `{ _tag, message, ...fields }`.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\n#[serde(untagged)]\npub enum LocalClientError {\n Unauthenticated(Unauthenticated),\n Forbidden(Forbidden),\n ApprovalRequired(ApprovalRequired),\n ConsentRequired(ConsentRequired),\n IdempotencyConflict(IdempotencyConflict),\n InvalidInput(InvalidInput),\n UnknownAction(UnknownAction),\n ActionFailed(ActionFailed),\n ClientOutdated(ClientOutdated),\n ClientNotConfigured(ClientNotConfigured),\n NotSignedIn(NotSignedIn),\n UnknownSubscription(UnknownSubscription),\n UnknownQuery(UnknownQuery),\n UnknownMutator(UnknownMutator),\n StaleGeneration(StaleGeneration),\n SignInFailed(SignInFailed),\n ProtocolVersion(ProtocolVersion),\n}\nimpl ::std::convert::From<Unauthenticated> for LocalClientError {\n fn from(value: Unauthenticated) -> Self {\n Self::Unauthenticated(value)\n }\n}\nimpl ::std::convert::From<Forbidden> for LocalClientError {\n fn from(value: Forbidden) -> Self {\n Self::Forbidden(value)\n }\n}\nimpl ::std::convert::From<ApprovalRequired> for LocalClientError {\n fn from(value: ApprovalRequired) -> Self {\n Self::ApprovalRequired(value)\n }\n}\nimpl ::std::convert::From<ConsentRequired> for LocalClientError {\n fn from(value: ConsentRequired) -> Self {\n Self::ConsentRequired(value)\n }\n}\nimpl ::std::convert::From<IdempotencyConflict> for LocalClientError {\n fn from(value: IdempotencyConflict) -> Self {\n Self::IdempotencyConflict(value)\n }\n}\nimpl ::std::convert::From<InvalidInput> for LocalClientError {\n fn from(value: InvalidInput) -> Self {\n Self::InvalidInput(value)\n }\n}\nimpl ::std::convert::From<UnknownAction> for LocalClientError {\n fn from(value: UnknownAction) -> Self {\n Self::UnknownAction(value)\n }\n}\nimpl ::std::convert::From<ActionFailed> for LocalClientError {\n fn from(value: ActionFailed) -> Self {\n Self::ActionFailed(value)\n }\n}\nimpl ::std::convert::From<ClientOutdated> for LocalClientError {\n fn from(value: ClientOutdated) -> Self {\n Self::ClientOutdated(value)\n }\n}\nimpl ::std::convert::From<ClientNotConfigured> for LocalClientError {\n fn from(value: ClientNotConfigured) -> Self {\n Self::ClientNotConfigured(value)\n }\n}\nimpl ::std::convert::From<NotSignedIn> for LocalClientError {\n fn from(value: NotSignedIn) -> Self {\n Self::NotSignedIn(value)\n }\n}\nimpl ::std::convert::From<UnknownSubscription> for LocalClientError {\n fn from(value: UnknownSubscription) -> Self {\n Self::UnknownSubscription(value)\n }\n}\nimpl ::std::convert::From<UnknownQuery> for LocalClientError {\n fn from(value: UnknownQuery) -> Self {\n Self::UnknownQuery(value)\n }\n}\nimpl ::std::convert::From<UnknownMutator> for LocalClientError {\n fn from(value: UnknownMutator) -> Self {\n Self::UnknownMutator(value)\n }\n}\nimpl ::std::convert::From<StaleGeneration> for LocalClientError {\n fn from(value: StaleGeneration) -> Self {\n Self::StaleGeneration(value)\n }\n}\nimpl ::std::convert::From<SignInFailed> for LocalClientError {\n fn from(value: SignInFailed) -> Self {\n Self::SignInFailed(value)\n }\n}\nimpl ::std::convert::From<ProtocolVersion> for LocalClientError {\n fn from(value: ProtocolVersion) -> Self {\n Self::ProtocolVersion(value)\n }\n}\n///`MakeViewCall`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct MakeViewCall {\n pub action: ::std::string::String,\n pub id: ::std::string::String,\n pub input: ::serde_json::Value,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub key: ::std::option::Option<::std::string::String>,\n}\n///`MakeViewElement`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct MakeViewElement {\n #[serde(default, skip_serializing_if = \"::std::vec::Vec::is_empty\")]\n pub children: ::std::vec::Vec<MakeViewNode>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub data: ::std::option::Option<::serde_json::Value>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub on: ::std::option::Option<::std::string::String>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub props: ::std::option::Option<MakeViewProps>,\n pub tag: MakeViewElementTag,\n}\n///`MakeViewElementTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum MakeViewElementTag {\n #[serde(rename = \"div\")]\n Div,\n #[serde(rename = \"span\")]\n Span,\n #[serde(rename = \"p\")]\n P,\n #[serde(rename = \"h1\")]\n H1,\n #[serde(rename = \"h2\")]\n H2,\n #[serde(rename = \"h3\")]\n H3,\n #[serde(rename = \"h4\")]\n H4,\n #[serde(rename = \"ul\")]\n Ul,\n #[serde(rename = \"ol\")]\n Ol,\n #[serde(rename = \"li\")]\n Li,\n #[serde(rename = \"strong\")]\n Strong,\n #[serde(rename = \"em\")]\n Em,\n #[serde(rename = \"small\")]\n Small,\n #[serde(rename = \"code\")]\n Code,\n #[serde(rename = \"pre\")]\n Pre,\n #[serde(rename = \"br\")]\n Br,\n #[serde(rename = \"hr\")]\n Hr,\n #[serde(rename = \"table\")]\n Table,\n #[serde(rename = \"thead\")]\n Thead,\n #[serde(rename = \"tbody\")]\n Tbody,\n #[serde(rename = \"tr\")]\n Tr,\n #[serde(rename = \"th\")]\n Th,\n #[serde(rename = \"td\")]\n Td,\n #[serde(rename = \"section\")]\n Section,\n #[serde(rename = \"header\")]\n Header,\n #[serde(rename = \"footer\")]\n Footer,\n #[serde(rename = \"label\")]\n Label,\n #[serde(rename = \"form\")]\n Form,\n #[serde(rename = \"button\")]\n Button,\n #[serde(rename = \"link\")]\n Link,\n #[serde(rename = \"input\")]\n Input,\n #[serde(rename = \"textarea\")]\n Textarea,\n #[serde(rename = \"select\")]\n Select,\n #[serde(rename = \"option\")]\n Option,\n}\nimpl ::std::fmt::Display for MakeViewElementTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::Div => f.write_str(\"div\"),\n Self::Span => f.write_str(\"span\"),\n Self::P => f.write_str(\"p\"),\n Self::H1 => f.write_str(\"h1\"),\n Self::H2 => f.write_str(\"h2\"),\n Self::H3 => f.write_str(\"h3\"),\n Self::H4 => f.write_str(\"h4\"),\n Self::Ul => f.write_str(\"ul\"),\n Self::Ol => f.write_str(\"ol\"),\n Self::Li => f.write_str(\"li\"),\n Self::Strong => f.write_str(\"strong\"),\n Self::Em => f.write_str(\"em\"),\n Self::Small => f.write_str(\"small\"),\n Self::Code => f.write_str(\"code\"),\n Self::Pre => f.write_str(\"pre\"),\n Self::Br => f.write_str(\"br\"),\n Self::Hr => f.write_str(\"hr\"),\n Self::Table => f.write_str(\"table\"),\n Self::Thead => f.write_str(\"thead\"),\n Self::Tbody => f.write_str(\"tbody\"),\n Self::Tr => f.write_str(\"tr\"),\n Self::Th => f.write_str(\"th\"),\n Self::Td => f.write_str(\"td\"),\n Self::Section => f.write_str(\"section\"),\n Self::Header => f.write_str(\"header\"),\n Self::Footer => f.write_str(\"footer\"),\n Self::Label => f.write_str(\"label\"),\n Self::Form => f.write_str(\"form\"),\n Self::Button => f.write_str(\"button\"),\n Self::Link => f.write_str(\"link\"),\n Self::Input => f.write_str(\"input\"),\n Self::Textarea => f.write_str(\"textarea\"),\n Self::Select => f.write_str(\"select\"),\n Self::Option => f.write_str(\"option\"),\n }\n }\n}\nimpl ::std::str::FromStr for MakeViewElementTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"div\" => Ok(Self::Div),\n \"span\" => Ok(Self::Span),\n \"p\" => Ok(Self::P),\n \"h1\" => Ok(Self::H1),\n \"h2\" => Ok(Self::H2),\n \"h3\" => Ok(Self::H3),\n \"h4\" => Ok(Self::H4),\n \"ul\" => Ok(Self::Ul),\n \"ol\" => Ok(Self::Ol),\n \"li\" => Ok(Self::Li),\n \"strong\" => Ok(Self::Strong),\n \"em\" => Ok(Self::Em),\n \"small\" => Ok(Self::Small),\n \"code\" => Ok(Self::Code),\n \"pre\" => Ok(Self::Pre),\n \"br\" => Ok(Self::Br),\n \"hr\" => Ok(Self::Hr),\n \"table\" => Ok(Self::Table),\n \"thead\" => Ok(Self::Thead),\n \"tbody\" => Ok(Self::Tbody),\n \"tr\" => Ok(Self::Tr),\n \"th\" => Ok(Self::Th),\n \"td\" => Ok(Self::Td),\n \"section\" => Ok(Self::Section),\n \"header\" => Ok(Self::Header),\n \"footer\" => Ok(Self::Footer),\n \"label\" => Ok(Self::Label),\n \"form\" => Ok(Self::Form),\n \"button\" => Ok(Self::Button),\n \"link\" => Ok(Self::Link),\n \"input\" => Ok(Self::Input),\n \"textarea\" => Ok(Self::Textarea),\n \"select\" => Ok(Self::Select),\n \"option\" => Ok(Self::Option),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for MakeViewElementTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for MakeViewElementTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///`MakeViewMessage`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\n#[serde(untagged)]\npub enum MakeViewMessage {\n Variant0 {\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n data: ::std::option::Option<::serde_json::Value>,\n fields: ::std::collections::HashMap<\n ::std::string::String,\n MakeViewMessageVariant0FieldsValue,\n >,\n name: ::std::string::String,\n #[serde(rename = \"type\")]\n type_: MakeViewMessageVariant0Type,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n value: ::std::option::Option<MakeViewMessageVariant0Value>,\n },\n Variant1 {\n id: ::std::string::String,\n ok: bool,\n result: ::serde_json::Value,\n #[serde(rename = \"type\")]\n type_: MakeViewMessageVariant1Type,\n },\n Variant2 {\n error: MakeViewMessageVariant2Error,\n id: ::std::string::String,\n ok: bool,\n #[serde(rename = \"type\")]\n type_: MakeViewMessageVariant2Type,\n },\n}\n///`MakeViewMessageVariant0FieldsValue`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\n#[serde(untagged)]\npub enum MakeViewMessageVariant0FieldsValue {\n String(::std::string::String),\n Boolean(bool),\n}\nimpl ::std::fmt::Display for MakeViewMessageVariant0FieldsValue {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match self {\n Self::String(x) => x.fmt(f),\n Self::Boolean(x) => x.fmt(f),\n }\n }\n}\nimpl ::std::convert::From<bool> for MakeViewMessageVariant0FieldsValue {\n fn from(value: bool) -> Self {\n Self::Boolean(value)\n }\n}\n///`MakeViewMessageVariant0Type`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum MakeViewMessageVariant0Type {\n #[serde(rename = \"event\")]\n Event,\n}\nimpl ::std::fmt::Display for MakeViewMessageVariant0Type {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::Event => f.write_str(\"event\"),\n }\n }\n}\nimpl ::std::str::FromStr for MakeViewMessageVariant0Type {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"event\" => Ok(Self::Event),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for MakeViewMessageVariant0Type {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for MakeViewMessageVariant0Type {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///`MakeViewMessageVariant0Value`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\n#[serde(untagged)]\npub enum MakeViewMessageVariant0Value {\n String(::std::string::String),\n Boolean(bool),\n}\nimpl ::std::fmt::Display for MakeViewMessageVariant0Value {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match self {\n Self::String(x) => x.fmt(f),\n Self::Boolean(x) => x.fmt(f),\n }\n }\n}\nimpl ::std::convert::From<bool> for MakeViewMessageVariant0Value {\n fn from(value: bool) -> Self {\n Self::Boolean(value)\n }\n}\n///`MakeViewMessageVariant1Type`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum MakeViewMessageVariant1Type {\n #[serde(rename = \"result\")]\n Result,\n}\nimpl ::std::fmt::Display for MakeViewMessageVariant1Type {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::Result => f.write_str(\"result\"),\n }\n }\n}\nimpl ::std::str::FromStr for MakeViewMessageVariant1Type {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"result\" => Ok(Self::Result),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for MakeViewMessageVariant1Type {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for MakeViewMessageVariant1Type {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///`MakeViewMessageVariant2Error`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct MakeViewMessageVariant2Error {\n pub message: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: ::std::string::String,\n}\n///`MakeViewMessageVariant2Type`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum MakeViewMessageVariant2Type {\n #[serde(rename = \"result\")]\n Result,\n}\nimpl ::std::fmt::Display for MakeViewMessageVariant2Type {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::Result => f.write_str(\"result\"),\n }\n }\n}\nimpl ::std::str::FromStr for MakeViewMessageVariant2Type {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"result\" => Ok(Self::Result),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for MakeViewMessageVariant2Type {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for MakeViewMessageVariant2Type {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///`MakeViewNode`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\n#[serde(untagged)]\npub enum MakeViewNode {\n String(::std::string::String),\n Number(f64),\n Boolean(bool),\n Null,\n MakeViewElement(MakeViewElement),\n}\nimpl ::std::convert::From<f64> for MakeViewNode {\n fn from(value: f64) -> Self {\n Self::Number(value)\n }\n}\nimpl ::std::convert::From<bool> for MakeViewNode {\n fn from(value: bool) -> Self {\n Self::Boolean(value)\n }\n}\nimpl ::std::convert::From<MakeViewElement> for MakeViewNode {\n fn from(value: MakeViewElement) -> Self {\n Self::MakeViewElement(value)\n }\n}\n///`MakeViewPropValue`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\n#[serde(untagged)]\npub enum MakeViewPropValue {\n String(::std::string::String),\n Number(f64),\n Boolean(bool),\n}\nimpl ::std::fmt::Display for MakeViewPropValue {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match self {\n Self::String(x) => x.fmt(f),\n Self::Number(x) => x.fmt(f),\n Self::Boolean(x) => x.fmt(f),\n }\n }\n}\nimpl ::std::convert::From<f64> for MakeViewPropValue {\n fn from(value: f64) -> Self {\n Self::Number(value)\n }\n}\nimpl ::std::convert::From<bool> for MakeViewPropValue {\n fn from(value: bool) -> Self {\n Self::Boolean(value)\n }\n}\n///`MakeViewProps`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, Default)]\npub struct MakeViewProps {\n #[serde(\n rename = \"ariaLabel\",\n skip_serializing_if = \"::std::option::Option::is_none\"\n )]\n pub aria_label: ::std::option::Option<MakeViewPropValue>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub checked: ::std::option::Option<MakeViewPropValue>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub class: ::std::option::Option<MakeViewPropValue>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub colspan: ::std::option::Option<MakeViewPropValue>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub disabled: ::std::option::Option<MakeViewPropValue>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub max: ::std::option::Option<MakeViewPropValue>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub min: ::std::option::Option<MakeViewPropValue>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub name: ::std::option::Option<MakeViewPropValue>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub placeholder: ::std::option::Option<MakeViewPropValue>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub rows: ::std::option::Option<MakeViewPropValue>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub rowspan: ::std::option::Option<MakeViewPropValue>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub selected: ::std::option::Option<MakeViewPropValue>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub step: ::std::option::Option<MakeViewPropValue>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub style: ::std::option::Option<MakeViewPropValue>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub title: ::std::option::Option<MakeViewPropValue>,\n #[serde(rename = \"type\", skip_serializing_if = \"::std::option::Option::is_none\")]\n pub type_: ::std::option::Option<MakeViewPropValue>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub value: ::std::option::Option<MakeViewPropValue>,\n}\n///`MakeViewStep`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct MakeViewStep {\n pub calls: ::std::vec::Vec<MakeViewCall>,\n pub state: ::serde_json::Value,\n pub tree: MakeViewNode,\n}\n///`NotSignedIn`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct NotSignedIn {\n pub message: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: NotSignedInTag,\n}\n///`NotSignedInTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum NotSignedInTag {\n NotSignedIn,\n}\nimpl ::std::fmt::Display for NotSignedInTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::NotSignedIn => f.write_str(\"NotSignedIn\"),\n }\n }\n}\nimpl ::std::str::FromStr for NotSignedInTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"NotSignedIn\" => Ok(Self::NotSignedIn),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for NotSignedInTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for NotSignedInTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///Done.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct OkAnswer {\n pub ok: bool,\n}\n///An organisation the person belongs to, with their roles in it.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct Organization {\n pub name: ::std::string::String,\n #[serde(rename = \"orgId\")]\n pub org_id: ::std::string::String,\n pub roles: ::std::vec::Vec<::std::string::String>,\n}\n///`ProtocolVersion`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct ProtocolVersion {\n pub message: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: ProtocolVersionTag,\n pub version: ::std::string::String,\n}\n///`ProtocolVersionTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum ProtocolVersionTag {\n ProtocolVersion,\n}\nimpl ::std::fmt::Display for ProtocolVersionTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::ProtocolVersion => f.write_str(\"ProtocolVersion\"),\n }\n }\n}\nimpl ::std::str::FromStr for ProtocolVersionTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"ProtocolVersion\" => Ok(Self::ProtocolVersion),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for ProtocolVersionTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for ProtocolVersionTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///A subscription's full snapshot (version 1 sends the whole result on every change). With status `error`, `error` is why, as the kernel's typed error (the server's refusal of the query, or `ActionFailed` naming the query), like a rejected write's.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct RowsEvent {\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub error: ::std::option::Option<InvocationError>,\n ///The context the event belongs to.\n pub generation: i64,\n pub rows: ::std::vec::Vec<::serde_json::Value>,\n ///Increases by one per event on its stream, starting at 1.\n pub seq: ::std::num::NonZeroU64,\n pub status: RowsStatus,\n pub subscription: ::std::string::String,\n #[serde(rename = \"type\")]\n pub type_: RowsEventType,\n}\n///`RowsEventType`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum RowsEventType {\n #[serde(rename = \"rows\")]\n Rows,\n}\nimpl ::std::fmt::Display for RowsEventType {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::Rows => f.write_str(\"rows\"),\n }\n }\n}\nimpl ::std::str::FromStr for RowsEventType {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"rows\" => Ok(Self::Rows),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for RowsEventType {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for RowsEventType {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///How settled a snapshot is: `unknown` (only what the replica held before asking), `cached` (a result an earlier session settled), `complete` (the server answered), `error`.\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum RowsStatus {\n #[serde(rename = \"unknown\")]\n Unknown,\n #[serde(rename = \"cached\")]\n Cached,\n #[serde(rename = \"complete\")]\n Complete,\n #[serde(rename = \"error\")]\n Error,\n}\nimpl ::std::fmt::Display for RowsStatus {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::Unknown => f.write_str(\"unknown\"),\n Self::Cached => f.write_str(\"cached\"),\n Self::Complete => f.write_str(\"complete\"),\n Self::Error => f.write_str(\"error\"),\n }\n }\n}\nimpl ::std::str::FromStr for RowsStatus {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"unknown\" => Ok(Self::Unknown),\n \"cached\" => Ok(Self::Cached),\n \"complete\" => Ok(Self::Complete),\n \"error\" => Ok(Self::Error),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for RowsStatus {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for RowsStatus {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///One event of a run subscription (`POST /client/v1/runs`, LocalClient 1.1.0), sent only to the client that made it: `event` is the run's next event (a stored event at most once, by its `seq`; streamed text as it comes). The subscription ends after the event of type `run-finished`, or with `error` (and no `event`) when the kernel refused the stream (the session ended, not the person's run); nothing of it follows either. A context reset ends it too, like every subscription.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct RunEvent {\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub error: ::std::option::Option<InvocationError>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub event: ::std::option::Option<AgentRunEvent>,\n ///The context the event belongs to.\n pub generation: i64,\n ///Increases by one per event on its stream, starting at 1.\n pub seq: ::std::num::NonZeroU64,\n pub subscription: ::std::string::String,\n #[serde(rename = \"type\")]\n pub type_: RunEventType,\n}\n///What a run's event is (the AgentRuntime contract's run event types): `text-delta` is streamed text, never stored; every other one is stored, numbered by `seq`.\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum RunEventKind {\n #[serde(rename = \"run-started\")]\n RunStarted,\n #[serde(rename = \"model-step\")]\n ModelStep,\n #[serde(rename = \"tool-call\")]\n ToolCall,\n #[serde(rename = \"tool-result\")]\n ToolResult,\n #[serde(rename = \"consent-required\")]\n ConsentRequired,\n #[serde(rename = \"consent-decided\")]\n ConsentDecided,\n #[serde(rename = \"compacted\")]\n Compacted,\n #[serde(rename = \"delegated\")]\n Delegated,\n #[serde(rename = \"seat-spawned\")]\n SeatSpawned,\n #[serde(rename = \"team-message\")]\n TeamMessage,\n #[serde(rename = \"reply-discarded\")]\n ReplyDiscarded,\n #[serde(rename = \"answer-checked\")]\n AnswerChecked,\n #[serde(rename = \"reconciled\")]\n Reconciled,\n #[serde(rename = \"processor-tripped\")]\n ProcessorTripped,\n #[serde(rename = \"run-finished\")]\n RunFinished,\n #[serde(rename = \"text-delta\")]\n TextDelta,\n}\nimpl ::std::fmt::Display for RunEventKind {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::RunStarted => f.write_str(\"run-started\"),\n Self::ModelStep => f.write_str(\"model-step\"),\n Self::ToolCall => f.write_str(\"tool-call\"),\n Self::ToolResult => f.write_str(\"tool-result\"),\n Self::ConsentRequired => f.write_str(\"consent-required\"),\n Self::ConsentDecided => f.write_str(\"consent-decided\"),\n Self::Compacted => f.write_str(\"compacted\"),\n Self::Delegated => f.write_str(\"delegated\"),\n Self::SeatSpawned => f.write_str(\"seat-spawned\"),\n Self::TeamMessage => f.write_str(\"team-message\"),\n Self::ReplyDiscarded => f.write_str(\"reply-discarded\"),\n Self::AnswerChecked => f.write_str(\"answer-checked\"),\n Self::Reconciled => f.write_str(\"reconciled\"),\n Self::ProcessorTripped => f.write_str(\"processor-tripped\"),\n Self::RunFinished => f.write_str(\"run-finished\"),\n Self::TextDelta => f.write_str(\"text-delta\"),\n }\n }\n}\nimpl ::std::str::FromStr for RunEventKind {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"run-started\" => Ok(Self::RunStarted),\n \"model-step\" => Ok(Self::ModelStep),\n \"tool-call\" => Ok(Self::ToolCall),\n \"tool-result\" => Ok(Self::ToolResult),\n \"consent-required\" => Ok(Self::ConsentRequired),\n \"consent-decided\" => Ok(Self::ConsentDecided),\n \"compacted\" => Ok(Self::Compacted),\n \"delegated\" => Ok(Self::Delegated),\n \"seat-spawned\" => Ok(Self::SeatSpawned),\n \"team-message\" => Ok(Self::TeamMessage),\n \"reply-discarded\" => Ok(Self::ReplyDiscarded),\n \"answer-checked\" => Ok(Self::AnswerChecked),\n \"reconciled\" => Ok(Self::Reconciled),\n \"processor-tripped\" => Ok(Self::ProcessorTripped),\n \"run-finished\" => Ok(Self::RunFinished),\n \"text-delta\" => Ok(Self::TextDelta),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for RunEventKind {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for RunEventKind {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///`RunEventType`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum RunEventType {\n #[serde(rename = \"run\")]\n Run,\n}\nimpl ::std::fmt::Display for RunEventType {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::Run => f.write_str(\"run\"),\n }\n }\n}\nimpl ::std::str::FromStr for RunEventType {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"run\" => Ok(Self::Run),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for RunEventType {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for RunEventType {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///Select an organisation the person belongs to.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct SelectOrg {\n #[serde(rename = \"orgId\")]\n pub org_id: SelectOrgOrgId,\n}\n///`SelectOrgOrgId`\n#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\n#[serde(transparent)]\npub struct SelectOrgOrgId(::std::string::String);\nimpl ::std::ops::Deref for SelectOrgOrgId {\n type Target = ::std::string::String;\n fn deref(&self) -> &::std::string::String {\n &self.0\n }\n}\nimpl ::std::convert::From<SelectOrgOrgId> for ::std::string::String {\n fn from(value: SelectOrgOrgId) -> Self {\n value.0\n }\n}\nimpl ::std::str::FromStr for SelectOrgOrgId {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n ::std::convert::TryFrom::try_from(value)\n }\n}\nimpl ::std::convert::TryFrom<&str> for SelectOrgOrgId {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n if value.chars().count() < 1usize {\n return Err(\"shorter than 1 characters\".into());\n }\n Ok(Self(value.to_string()))\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for SelectOrgOrgId {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n ::std::convert::TryFrom::try_from(value.as_str())\n }\n}\nimpl<'de> ::serde::Deserialize<'de> for SelectOrgOrgId {\n fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>\n where\n D: ::serde::Deserializer<'de>,\n {\n ::std::convert::TryFrom::try_from(\n ::std::string::String::deserialize(deserializer)?,\n )\n .map_err(|e: self::error::ConversionError| {\n <D::Error as ::serde::de::Error>::custom(e.to_string())\n })\n }\n}\n///The session changed.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct SessionEvent {\n ///Increases by one per event on its stream, starting at 1.\n pub seq: ::std::num::NonZeroU64,\n pub session: SessionState,\n #[serde(rename = \"type\")]\n pub type_: SessionEventType,\n}\n///`SessionEventType`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum SessionEventType {\n #[serde(rename = \"session\")]\n Session,\n}\nimpl ::std::fmt::Display for SessionEventType {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::Session => f.write_str(\"session\"),\n }\n }\n}\nimpl ::std::str::FromStr for SessionEventType {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"session\" => Ok(Self::Session),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for SessionEventType {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for SessionEventType {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///Where the person's session stands, tagged by `state`.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\n#[serde(untagged)]\npub enum SessionState {\n SignedOut(SignedOut),\n SigningIn(SigningIn),\n SignedIn(SignedIn),\n SigningOut(SigningOut),\n}\nimpl ::std::convert::From<SignedOut> for SessionState {\n fn from(value: SignedOut) -> Self {\n Self::SignedOut(value)\n }\n}\nimpl ::std::convert::From<SigningIn> for SessionState {\n fn from(value: SigningIn) -> Self {\n Self::SigningIn(value)\n }\n}\nimpl ::std::convert::From<SignedIn> for SessionState {\n fn from(value: SignedIn) -> Self {\n Self::SignedIn(value)\n }\n}\nimpl ::std::convert::From<SigningOut> for SessionState {\n fn from(value: SigningOut) -> Self {\n Self::SigningOut(value)\n }\n}\n///What the browser brings to the callback (query parameters).\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct SignInCallback {\n pub code: ::std::string::String,\n pub state: ::std::string::String,\n}\n///`SignInFailed`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct SignInFailed {\n pub message: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: SignInFailedTag,\n}\n///`SignInFailedTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum SignInFailedTag {\n SignInFailed,\n}\nimpl ::std::fmt::Display for SignInFailedTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::SignInFailed => f.write_str(\"SignInFailed\"),\n }\n }\n}\nimpl ::std::str::FromStr for SignInFailedTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"SignInFailed\" => Ok(Self::SignInFailed),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for SignInFailedTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for SignInFailedTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///Open `url` (the app's web sign-in page with the desktop sign-in parameters) in the system browser; `state` identifies this sign-in.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct SignInStarted {\n pub state: ::std::string::String,\n pub url: ::std::string::String,\n}\n///A person is signed in. `orgId` is the selected organisation (the first membership until another is selected; null when they belong to none); `generation` is the current context's (see the `context` event). `offline` (1.2.0) is true during an offline start: the kernel could not be reached to check the stored session, so the person and organisation remembered with it are shown from the replica on this device (writes kept in it until the connection is back); absent once the kernel answered.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct SignedIn {\n pub generation: i64,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub offline: ::std::option::Option<bool>,\n #[serde(rename = \"orgId\", deserialize_with = \"::std::option::Option::deserialize\")]\n pub org_id: ::std::option::Option<::std::string::String>,\n pub organizations: ::std::vec::Vec<Organization>,\n pub state: SignedInState,\n pub user: User,\n}\n///`SignedInState`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum SignedInState {\n #[serde(rename = \"signedIn\")]\n SignedIn,\n}\nimpl ::std::fmt::Display for SignedInState {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::SignedIn => f.write_str(\"signedIn\"),\n }\n }\n}\nimpl ::std::str::FromStr for SignedInState {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"signedIn\" => Ok(Self::SignedIn),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for SignedInState {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for SignedInState {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///No person is signed in.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct SignedOut {\n pub state: SignedOutState,\n}\n///`SignedOutState`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum SignedOutState {\n #[serde(rename = \"signedOut\")]\n SignedOut,\n}\nimpl ::std::fmt::Display for SignedOutState {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::SignedOut => f.write_str(\"signedOut\"),\n }\n }\n}\nimpl ::std::str::FromStr for SignedOutState {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"signedOut\" => Ok(Self::SignedOut),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for SignedOutState {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for SignedOutState {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///A desktop sign-in was started and its callback has not arrived yet.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct SigningIn {\n pub state: SigningInState,\n}\n///`SigningInState`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum SigningInState {\n #[serde(rename = \"signingIn\")]\n SigningIn,\n}\nimpl ::std::fmt::Display for SigningInState {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::SigningIn => f.write_str(\"signingIn\"),\n }\n }\n}\nimpl ::std::str::FromStr for SigningInState {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"signingIn\" => Ok(Self::SigningIn),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for SigningInState {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for SigningInState {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///Sign-out started: nothing more is read or written; the session is kept until the kernel confirms its revocation.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct SigningOut {\n pub state: SigningOutState,\n}\n///`SigningOutState`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum SigningOutState {\n #[serde(rename = \"signingOut\")]\n SigningOut,\n}\nimpl ::std::fmt::Display for SigningOutState {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::SigningOut => f.write_str(\"signingOut\"),\n }\n }\n}\nimpl ::std::str::FromStr for SigningOutState {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"signingOut\" => Ok(Self::SigningOut),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for SigningOutState {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for SigningOutState {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///`StaleGeneration`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct StaleGeneration {\n pub generation: i64,\n pub message: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: StaleGenerationTag,\n}\n///`StaleGenerationTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum StaleGenerationTag {\n StaleGeneration,\n}\nimpl ::std::fmt::Display for StaleGenerationTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::StaleGeneration => f.write_str(\"StaleGeneration\"),\n }\n }\n}\nimpl ::std::str::FromStr for StaleGenerationTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"StaleGeneration\" => Ok(Self::StaleGeneration),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for StaleGenerationTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for StaleGenerationTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///Run a named query (`hello.greetings`) live with its arguments, under an optional client-chosen id.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct Subscribe {\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub args: ::std::option::Option<::serde_json::Value>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub id: ::std::option::Option<SubscribeId>,\n pub query: ::std::string::String,\n}\n///`SubscribeId`\n#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\n#[serde(transparent)]\npub struct SubscribeId(::std::string::String);\nimpl ::std::ops::Deref for SubscribeId {\n type Target = ::std::string::String;\n fn deref(&self) -> &::std::string::String {\n &self.0\n }\n}\nimpl ::std::convert::From<SubscribeId> for ::std::string::String {\n fn from(value: SubscribeId) -> Self {\n value.0\n }\n}\nimpl ::std::str::FromStr for SubscribeId {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n ::std::convert::TryFrom::try_from(value)\n }\n}\nimpl ::std::convert::TryFrom<&str> for SubscribeId {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n if value.chars().count() > 128usize {\n return Err(\"longer than 128 characters\".into());\n }\n if value.chars().count() < 1usize {\n return Err(\"shorter than 1 characters\".into());\n }\n Ok(Self(value.to_string()))\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for SubscribeId {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n ::std::convert::TryFrom::try_from(value.as_str())\n }\n}\nimpl<'de> ::serde::Deserialize<'de> for SubscribeId {\n fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>\n where\n D: ::serde::Deserializer<'de>,\n {\n ::std::convert::TryFrom::try_from(\n ::std::string::String::deserialize(deserializer)?,\n )\n .map_err(|e: self::error::ConversionError| {\n <D::Error as ::serde::de::Error>::custom(e.to_string())\n })\n }\n}\n///The subscription's id and the generation it belongs to; its first `rows` event follows on the stream.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct Subscribed {\n pub generation: i64,\n pub id: ::std::string::String,\n}\n///`Unauthenticated`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct Unauthenticated {\n pub message: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: UnauthenticatedTag,\n}\n///`UnauthenticatedTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum UnauthenticatedTag {\n Unauthenticated,\n}\nimpl ::std::fmt::Display for UnauthenticatedTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::Unauthenticated => f.write_str(\"Unauthenticated\"),\n }\n }\n}\nimpl ::std::str::FromStr for UnauthenticatedTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"Unauthenticated\" => Ok(Self::Unauthenticated),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for UnauthenticatedTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for UnauthenticatedTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///`UnknownAction`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct UnknownAction {\n pub action: ::std::string::String,\n pub message: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: UnknownActionTag,\n}\n///`UnknownActionTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum UnknownActionTag {\n UnknownAction,\n}\nimpl ::std::fmt::Display for UnknownActionTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::UnknownAction => f.write_str(\"UnknownAction\"),\n }\n }\n}\nimpl ::std::str::FromStr for UnknownActionTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"UnknownAction\" => Ok(Self::UnknownAction),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for UnknownActionTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for UnknownActionTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///`UnknownMutator`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct UnknownMutator {\n pub message: ::std::string::String,\n pub mutator: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: UnknownMutatorTag,\n}\n///`UnknownMutatorTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum UnknownMutatorTag {\n UnknownMutator,\n}\nimpl ::std::fmt::Display for UnknownMutatorTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::UnknownMutator => f.write_str(\"UnknownMutator\"),\n }\n }\n}\nimpl ::std::str::FromStr for UnknownMutatorTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"UnknownMutator\" => Ok(Self::UnknownMutator),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for UnknownMutatorTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for UnknownMutatorTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///`UnknownQuery`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct UnknownQuery {\n pub message: ::std::string::String,\n pub query: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: UnknownQueryTag,\n}\n///`UnknownQueryTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum UnknownQueryTag {\n UnknownQuery,\n}\nimpl ::std::fmt::Display for UnknownQueryTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::UnknownQuery => f.write_str(\"UnknownQuery\"),\n }\n }\n}\nimpl ::std::str::FromStr for UnknownQueryTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"UnknownQuery\" => Ok(Self::UnknownQuery),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for UnknownQueryTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for UnknownQueryTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///`UnknownSubscription`\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct UnknownSubscription {\n pub id: ::std::string::String,\n pub message: ::std::string::String,\n #[serde(rename = \"_tag\")]\n pub tag: UnknownSubscriptionTag,\n}\n///`UnknownSubscriptionTag`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum UnknownSubscriptionTag {\n UnknownSubscription,\n}\nimpl ::std::fmt::Display for UnknownSubscriptionTag {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::UnknownSubscription => f.write_str(\"UnknownSubscription\"),\n }\n }\n}\nimpl ::std::str::FromStr for UnknownSubscriptionTag {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"UnknownSubscription\" => Ok(Self::UnknownSubscription),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for UnknownSubscriptionTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for UnknownSubscriptionTag {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///The signed-in person: never a credential.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct User {\n pub email: ::std::string::String,\n pub id: ::std::string::String,\n pub name: ::std::string::String,\n}\n///An optimistic write: the mutator (named by its action, `hello.greet`), its input, an optional client-chosen id and, since 1.1.0, the generation the client made it in (`generation`, see `ExpectedGeneration`).\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct Write {\n ///The generation the client made the request in (1.1.0): when another is current, the request is refused with StaleGeneration (naming the current one) and nothing is run. Absent, the current generation is used.\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub generation: ::std::option::Option<i64>,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub id: ::std::option::Option<WriteId>,\n pub input: ::serde_json::Value,\n pub mutator: ::std::string::String,\n}\n///The write's id and generation; its `write` events follow on the stream.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct WriteAccepted {\n pub generation: i64,\n pub id: ::std::string::String,\n}\n///An optimistic write's outcome. `rejected` carries the kernel's typed error and is sent only after the replica rolled the prediction back; `notConfirmed` carries why.\n#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]\npub struct WriteEvent {\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub error: ::std::option::Option<InvocationError>,\n ///The context the event belongs to.\n pub generation: i64,\n pub id: ::std::string::String,\n #[serde(skip_serializing_if = \"::std::option::Option::is_none\")]\n pub message: ::std::option::Option<::std::string::String>,\n pub phase: WritePhase,\n ///Increases by one per event on its stream, starting at 1.\n pub seq: ::std::num::NonZeroU64,\n #[serde(rename = \"type\")]\n pub type_: WriteEventType,\n}\n///`WriteEventType`\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum WriteEventType {\n #[serde(rename = \"write\")]\n Write,\n}\nimpl ::std::fmt::Display for WriteEventType {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::Write => f.write_str(\"write\"),\n }\n }\n}\nimpl ::std::str::FromStr for WriteEventType {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"write\" => Ok(Self::Write),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for WriteEventType {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for WriteEventType {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n///`WriteId`\n#[derive(::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]\n#[serde(transparent)]\npub struct WriteId(::std::string::String);\nimpl ::std::ops::Deref for WriteId {\n type Target = ::std::string::String;\n fn deref(&self) -> &::std::string::String {\n &self.0\n }\n}\nimpl ::std::convert::From<WriteId> for ::std::string::String {\n fn from(value: WriteId) -> Self {\n value.0\n }\n}\nimpl ::std::str::FromStr for WriteId {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n ::std::convert::TryFrom::try_from(value)\n }\n}\nimpl ::std::convert::TryFrom<&str> for WriteId {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n if value.chars().count() > 128usize {\n return Err(\"longer than 128 characters\".into());\n }\n if value.chars().count() < 1usize {\n return Err(\"shorter than 1 characters\".into());\n }\n Ok(Self(value.to_string()))\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for WriteId {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n ::std::convert::TryFrom::try_from(value.as_str())\n }\n}\nimpl<'de> ::serde::Deserialize<'de> for WriteId {\n fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>\n where\n D: ::serde::Deserializer<'de>,\n {\n ::std::convert::TryFrom::try_from(\n ::std::string::String::deserialize(deserializer)?,\n )\n .map_err(|e: self::error::ConversionError| {\n <D::Error as ::serde::de::Error>::custom(e.to_string())\n })\n }\n}\n///An optimistic write's progress: `predicted` (in the replica), `confirmed` (the server ran it and the replica holds its rows), `rejected` (refused, after the replica dropped the prediction), `notConfirmed` (the replica went offline or closed first: it may still run).\n#[derive(\n ::serde::Deserialize,\n ::serde::Serialize,\n Clone,\n Copy,\n Debug,\n Eq,\n Hash,\n Ord,\n PartialEq,\n PartialOrd\n)]\npub enum WritePhase {\n #[serde(rename = \"predicted\")]\n Predicted,\n #[serde(rename = \"confirmed\")]\n Confirmed,\n #[serde(rename = \"rejected\")]\n Rejected,\n #[serde(rename = \"notConfirmed\")]\n NotConfirmed,\n}\nimpl ::std::fmt::Display for WritePhase {\n fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {\n match *self {\n Self::Predicted => f.write_str(\"predicted\"),\n Self::Confirmed => f.write_str(\"confirmed\"),\n Self::Rejected => f.write_str(\"rejected\"),\n Self::NotConfirmed => f.write_str(\"notConfirmed\"),\n }\n }\n}\nimpl ::std::str::FromStr for WritePhase {\n type Err = self::error::ConversionError;\n fn from_str(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n match value {\n \"predicted\" => Ok(Self::Predicted),\n \"confirmed\" => Ok(Self::Confirmed),\n \"rejected\" => Ok(Self::Rejected),\n \"notConfirmed\" => Ok(Self::NotConfirmed),\n _ => Err(\"invalid value\".into()),\n }\n }\n}\nimpl ::std::convert::TryFrom<&str> for WritePhase {\n type Error = self::error::ConversionError;\n fn try_from(\n value: &str,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\nimpl ::std::convert::TryFrom<::std::string::String> for WritePhase {\n type Error = self::error::ConversionError;\n fn try_from(\n value: ::std::string::String,\n ) -> ::std::result::Result<Self, self::error::ConversionError> {\n value.parse()\n }\n}\n/// Error types.\npub mod error {\n /// Error from a `TryFrom` or `FromStr` implementation.\n pub struct ConversionError(::std::borrow::Cow<'static, str>);\n impl ::std::error::Error for ConversionError {}\n impl ::std::fmt::Display for ConversionError {\n fn fmt(\n &self,\n f: &mut ::std::fmt::Formatter<'_>,\n ) -> Result<(), ::std::fmt::Error> {\n ::std::fmt::Display::fmt(&self.0, f)\n }\n }\n impl ::std::fmt::Debug for ConversionError {\n fn fmt(\n &self,\n f: &mut ::std::fmt::Formatter<'_>,\n ) -> Result<(), ::std::fmt::Error> {\n ::std::fmt::Debug::fmt(&self.0, f)\n }\n }\n impl From<&'static str> for ConversionError {\n fn from(value: &'static str) -> Self {\n Self(value.into())\n }\n }\n impl From<String> for ConversionError {\n fn from(value: String) -> Self {\n Self(value.into())\n }\n }\n}\n",
336
+ "type": "registry:file",
337
+ "target": "desktop-rune/crates/eloxiv-local-client/src/generated.rs"
338
+ },
339
+ {
340
+ "path": "app/desktop-rune/crates/eloxiv-local-client/src/lib.rs",
341
+ "content": "//! LocalClient v1 (1.1.0) for Rust hosts (docs/contracts/local-client.md).\n//!\n//! - [`generated`]: the protocol's types and the MAKE view types, **generated** by typify from the JSON Schemas\n//! `@eloxiv/contracts` emits (`schema/codegen/LocalClient.json` and `schema/codegen/Sandbox.json`). Never edit\n//! it by hand: `cargo run -p eloxiv-local-client-codegen` writes it again, and that crate's test fails while the\n//! checked-in file differs from what the schemas give.\n//! - [`LocalClient`]: the routes, blocking (call them off the UI thread), with typed refusals ([`ClientError`]).\n//! - [`EventStream`]: the event stream on a thread of its own, cancellable at once.\n//!\n//! The crate holds no session, no replica and no prediction: the daemon's client runtime owns all of them, and\n//! this crate only carries its protocol.\n\npub mod client;\npub mod error;\n#[allow(clippy::all, clippy::pedantic, unused_imports, irrefutable_let_patterns, unreachable_patterns)]\n#[rustfmt::skip]\npub mod generated;\npub mod sse;\n\npub use client::{LocalClient, MAJOR, PROTOCOL, VERSION};\npub use error::ClientError;\npub use generated::*;\npub use sse::{EventStream, StreamEnd, StreamItem};\n\nimpl Event {\n /// The event's sequence number on its stream (from 1).\n pub fn seq(&self) -> u64 {\n match self {\n Event::SessionEvent(e) => e.seq.get(),\n Event::ContextEvent(e) => e.seq.get(),\n Event::RowsEvent(e) => e.seq.get(),\n Event::WriteEvent(e) => e.seq.get(),\n Event::ConnectionEvent(e) => e.seq.get(),\n Event::RunEvent(e) => e.seq.get(),\n }\n }\n}\n",
342
+ "type": "registry:file",
343
+ "target": "desktop-rune/crates/eloxiv-local-client/src/lib.rs"
344
+ },
345
+ {
346
+ "path": "app/desktop-rune/crates/eloxiv-local-client/src/sse.rs",
347
+ "content": "//! The event stream (`GET /client/v1/events`) on a thread of its own.\n//!\n//! The daemon is on loopback and speaks plain HTTP/1.1, so the stream is read from a `TcpStream` this module\n//! owns: cancelling shuts the socket down, which ends a blocked read at once (an HTTP library's blocking body\n//! read can only be abandoned, not stopped). Bodies are read chunked or until the connection closes.\n\nuse std::io::{self, BufRead, BufReader, Read, Write};\nuse std::net::{Shutdown, TcpStream, ToSocketAddrs};\nuse std::sync::Arc;\nuse std::sync::atomic::{AtomicBool, Ordering};\nuse std::thread::JoinHandle;\nuse std::time::Duration;\n\nuse crate::error::ClientError;\nuse crate::generated::Event;\n\n/// Longest event the reader accepts (one SSE `data:` payload, a whole snapshot in v1). A larger one ends the\n/// stream with [`StreamEnd::TooLarge`] rather than growing without bound.\npub const MAX_EVENT_BYTES: usize = 16 * 1024 * 1024;\n\n/// What the stream delivers, in order, on its own thread.\n#[derive(Debug)]\npub enum StreamItem {\n /// The response's headers arrived: the stream is live.\n Open,\n /// One event, parsed.\n Event(Event),\n /// A `data:` payload that is not an event this crate knows (a newer daemon's): skipped by the caller, kept\n /// here so it can be logged.\n Unknown(String),\n /// The stream ended; nothing follows.\n End(StreamEnd),\n}\n\n/// Why the stream ended.\n#[derive(Debug)]\npub enum StreamEnd {\n /// [`EventStream::cancel`] (or drop) asked for it.\n Cancelled,\n /// The daemon closed it (another stream replaced it, or the daemon stopped).\n Closed,\n /// The daemon answered with a refusal instead of a stream.\n Refused(ClientError),\n /// Reading failed.\n Failed(String),\n /// An event passed [`MAX_EVENT_BYTES`].\n TooLarge,\n}\n\n/// The stream's thread: [`cancel`](EventStream::cancel) ends it; dropping it cancels too.\npub struct EventStream {\n socket: Arc<std::sync::Mutex<Option<TcpStream>>>,\n cancelled: Arc<AtomicBool>,\n thread: Option<JoinHandle<()>>,\n}\n\nimpl EventStream {\n /// Opens the stream at `base` (`http://127.0.0.1:<port>`) with the local bearer `token`; `deliver` runs on the\n /// stream's thread for every item, the last being [`StreamItem::End`].\n pub fn open(base: &str, token: &str, deliver: impl FnMut(StreamItem) + Send + 'static) -> EventStream {\n let socket = Arc::new(std::sync::Mutex::new(None));\n let cancelled = Arc::new(AtomicBool::new(false));\n let (base, token) = (base.to_owned(), token.to_owned());\n let (sock, flag) = (socket.clone(), cancelled.clone());\n let thread = std::thread::Builder::new()\n .name(\"eloxiv-events\".into())\n .spawn(move || run(&base, &token, &sock, &flag, deliver))\n .ok();\n EventStream { socket, cancelled, thread }\n }\n\n /// Ends the stream: the socket is shut down, so a read waiting on it returns at once; the thread delivers\n /// [`StreamEnd::Cancelled`] and exits. Returns once it has.\n pub fn cancel(&mut self) {\n self.cancelled.store(true, Ordering::SeqCst);\n if let Ok(guard) = self.socket.lock()\n && let Some(socket) = guard.as_ref()\n {\n let _ = socket.shutdown(Shutdown::Both);\n }\n if let Some(thread) = self.thread.take() {\n let _ = thread.join();\n }\n }\n\n /// Whether the thread has finished (after its [`StreamItem::End`]).\n pub fn is_finished(&self) -> bool {\n self.thread.as_ref().is_none_or(JoinHandle::is_finished)\n }\n}\n\nimpl Drop for EventStream {\n fn drop(&mut self) {\n self.cancel();\n }\n}\n\nfn run(\n base: &str,\n token: &str,\n socket: &std::sync::Mutex<Option<TcpStream>>,\n cancelled: &AtomicBool,\n mut deliver: impl FnMut(StreamItem),\n) {\n let end = match read_stream(base, token, socket, cancelled, &mut deliver) {\n Ok(()) => StreamEnd::Closed,\n Err(_) if cancelled.load(Ordering::SeqCst) => StreamEnd::Cancelled,\n Err(end) => end,\n };\n deliver(StreamItem::End(end));\n}\n\nfn read_stream(\n base: &str,\n token: &str,\n socket: &std::sync::Mutex<Option<TcpStream>>,\n cancelled: &AtomicBool,\n deliver: &mut impl FnMut(StreamItem),\n) -> Result<(), StreamEnd> {\n let authority = base\n .strip_prefix(\"http://\")\n .ok_or_else(|| StreamEnd::Failed(format!(\"{base}: the daemon is reached over http:// on loopback\")))?\n .trim_end_matches('/');\n let address = authority\n .to_socket_addrs()\n .map_err(|e| StreamEnd::Failed(format!(\"{authority}: {e}\")))?\n .next()\n .ok_or_else(|| StreamEnd::Failed(format!(\"{authority}: no address\")))?;\n let mut stream =\n TcpStream::connect_timeout(&address, Duration::from_secs(5)).map_err(|e| StreamEnd::Failed(e.to_string()))?;\n // Heartbeats come every 15 s; a minute of silence means the daemon is gone.\n stream.set_read_timeout(Some(Duration::from_secs(60))).map_err(|e| StreamEnd::Failed(e.to_string()))?;\n {\n let mut guard = socket.lock().map_err(|_| StreamEnd::Failed(\"stream lock poisoned\".into()))?;\n *guard = Some(stream.try_clone().map_err(|e| StreamEnd::Failed(e.to_string()))?);\n }\n if cancelled.load(Ordering::SeqCst) {\n return Err(StreamEnd::Cancelled);\n }\n let request = format!(\n \"GET /client/v1/events HTTP/1.1\\r\\nHost: {authority}\\r\\nAuthorization: Bearer {token}\\r\\nx-eloxiv-local-client: {}\\r\\nAccept: text/event-stream\\r\\nCache-Control: no-store\\r\\nConnection: close\\r\\n\\r\\n\",\n crate::client::VERSION\n );\n stream.write_all(request.as_bytes()).map_err(|e| StreamEnd::Failed(e.to_string()))?;\n let mut reader = BufReader::new(stream);\n let (status, headers) = read_head(&mut reader)?;\n let chunked = headers.iter().any(|(k, v)| k == \"transfer-encoding\" && v.to_ascii_lowercase().contains(\"chunked\"));\n if status != 200 {\n let mut body = Vec::new();\n let mut limited = body_reader(reader, chunked).take(64 * 1024);\n let _ = limited.read_to_end(&mut body);\n return Err(StreamEnd::Refused(ClientError::from_status(status, &String::from_utf8_lossy(&body))));\n }\n deliver(StreamItem::Open);\n let mut lines = BufReader::new(body_reader(reader, chunked));\n let mut parser = Parser::default();\n loop {\n if cancelled.load(Ordering::SeqCst) {\n return Err(StreamEnd::Cancelled);\n }\n let mut line = Vec::new();\n let read = read_line_bounded(&mut lines, &mut line, MAX_EVENT_BYTES)?;\n if read == 0 {\n return Ok(());\n }\n match parser.line(&line) {\n Ok(Some(data)) => deliver(match serde_json::from_str::<Event>(&data) {\n Ok(event) => StreamItem::Event(event),\n Err(_) => StreamItem::Unknown(data),\n }),\n Ok(None) => {}\n Err(()) => return Err(StreamEnd::TooLarge),\n }\n }\n}\n\nfn read_line_bounded(reader: &mut impl BufRead, line: &mut Vec<u8>, max: usize) -> Result<usize, StreamEnd> {\n let mut total = 0;\n loop {\n let buf = match reader.fill_buf() {\n Ok(buf) => buf,\n Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,\n Err(e) => return Err(StreamEnd::Failed(e.to_string())),\n };\n if buf.is_empty() {\n return Ok(total);\n }\n let (taken, done) = match buf.iter().position(|&b| b == b'\\n') {\n Some(i) => (i + 1, true),\n None => (buf.len(), false),\n };\n line.extend_from_slice(&buf[..taken]);\n reader.consume(taken);\n total += taken;\n if line.len() > max + 2 {\n return Err(StreamEnd::TooLarge);\n }\n if done {\n return Ok(total);\n }\n }\n}\n\ntype Head = (u16, Vec<(String, String)>);\n\nfn read_head(reader: &mut impl BufRead) -> Result<Head, StreamEnd> {\n let mut status_line = String::new();\n reader.read_line(&mut status_line).map_err(|e| StreamEnd::Failed(e.to_string()))?;\n let status = status_line\n .split_whitespace()\n .nth(1)\n .and_then(|s| s.parse::<u16>().ok())\n .ok_or_else(|| StreamEnd::Failed(format!(\"not an HTTP answer: {}\", status_line.trim())))?;\n let mut headers = Vec::new();\n loop {\n let mut line = String::new();\n let n = reader.read_line(&mut line).map_err(|e| StreamEnd::Failed(e.to_string()))?;\n if n == 0 || line == \"\\r\\n\" || line == \"\\n\" {\n break;\n }\n if headers.len() > 100 {\n return Err(StreamEnd::Failed(\"too many headers\".into()));\n }\n if let Some((k, v)) = line.split_once(':') {\n headers.push((k.trim().to_ascii_lowercase(), v.trim().to_owned()));\n }\n }\n Ok((status, headers))\n}\n\nfn body_reader<R: BufRead + 'static>(reader: R, chunked: bool) -> Box<dyn Read> {\n if chunked { Box::new(Chunked { inner: reader, left: 0, done: false }) } else { Box::new(reader) }\n}\n\n/// `Transfer-Encoding: chunked`, decoded.\nstruct Chunked<R> {\n inner: R,\n left: usize,\n done: bool,\n}\n\nimpl<R: BufRead> Read for Chunked<R> {\n fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {\n if self.done || out.is_empty() {\n return Ok(0);\n }\n if self.left == 0 {\n let mut size = String::new();\n if self.inner.read_line(&mut size)? == 0 {\n self.done = true;\n return Ok(0);\n }\n let hex = size.trim().split(';').next().unwrap_or(\"\");\n self.left = usize::from_str_radix(hex, 16)\n .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, format!(\"bad chunk size {hex:?}\")))?;\n if self.left == 0 {\n self.done = true;\n return Ok(0);\n }\n }\n let want = out.len().min(self.left);\n let n = self.inner.read(&mut out[..want])?;\n if n == 0 {\n self.done = true;\n return Ok(0);\n }\n self.left -= n;\n if self.left == 0 {\n let mut crlf = String::new();\n self.inner.read_line(&mut crlf)?;\n }\n Ok(n)\n }\n}\n\n/// The SSE line protocol: `data:` lines joined by newlines until a blank line dispatches them; comments (`:`, the\n/// heartbeat) and other fields are ignored.\n#[derive(Default)]\npub(crate) struct Parser {\n data: Option<String>,\n}\n\nimpl Parser {\n /// One line (with or without its line ending); the event's data when the line ends one. `Err` when the event\n /// passed [`MAX_EVENT_BYTES`].\n pub(crate) fn line(&mut self, raw: &[u8]) -> Result<Option<String>, ()> {\n let text = String::from_utf8_lossy(raw);\n let line = text.trim_end_matches(['\\r', '\\n']);\n if line.is_empty() {\n return Ok(self.data.take());\n }\n if line.starts_with(':') {\n return Ok(None);\n }\n let (field, value) = match line.split_once(':') {\n Some((f, v)) => (f, v.strip_prefix(' ').unwrap_or(v)),\n None => (line, \"\"),\n };\n if field == \"data\" {\n let data = self.data.get_or_insert_with(String::new);\n if !data.is_empty() {\n data.push('\\n');\n }\n data.push_str(value);\n if data.len() > MAX_EVENT_BYTES {\n self.data = None;\n return Err(());\n }\n }\n Ok(None)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn parser_joins_data_lines_and_skips_comments() {\n let mut p = Parser::default();\n assert_eq!(p.line(b\": heartbeat\\n\"), Ok(None));\n assert_eq!(p.line(b\"event: x\\n\"), Ok(None));\n assert_eq!(p.line(b\"data: {\\\"a\\\":\\n\"), Ok(None));\n assert_eq!(p.line(b\"data: 1}\\r\\n\"), Ok(None));\n assert_eq!(p.line(b\"\\r\\n\"), Ok(Some(\"{\\\"a\\\":\\n1}\".into())));\n assert_eq!(p.line(b\"\\n\"), Ok(None));\n }\n\n #[test]\n fn chunked_bodies_decode() {\n let raw = b\"5\\r\\nhello\\r\\n6;ext=1\\r\\n world\\r\\n0\\r\\n\\r\\n\";\n let mut out = String::new();\n Chunked { inner: &raw[..], left: 0, done: false }.read_to_string(&mut out).ok();\n assert_eq!(out, \"hello world\");\n }\n}\n",
348
+ "type": "registry:file",
349
+ "target": "desktop-rune/crates/eloxiv-local-client/src/sse.rs"
350
+ },
351
+ {
352
+ "path": "app/desktop-rune/crates/eloxiv-mac-notifications/Cargo.toml",
353
+ "content": "[package]\nname = \"eloxiv-mac-notifications\"\nversion = \"0.1.0\"\ndescription = \"The Rune desktop host's calls into macOS's UserNotifications framework, behind a safe API (empty elsewhere)\"\nedition.workspace = true\nrust-version.workspace = true\nlicense.workspace = true\npublish.workspace = true\n\n# The objc2 the pinned Rune's rune-notify already brings (no second copy in the build).\n[target.'cfg(target_os = \"macos\")'.dependencies]\nobjc2 = \"0.5.2\"\nblock2 = \"0.5.1\"\n\n# The workspace's lints, but for `unsafe_code`: Objective-C messages are `unsafe`, and this crate is where the host's\n# only `unsafe` lives (the workspace forbids it everywhere else).\n[lints.rust]\nunsafe_code = \"allow\"\nunused_must_use = \"deny\"\n\n[lints.clippy]\ndbg_macro = \"deny\"\ntodo = \"deny\"\nunwrap_used = \"warn\"\n",
354
+ "type": "registry:file",
355
+ "target": "desktop-rune/crates/eloxiv-mac-notifications/Cargo.toml"
356
+ },
357
+ {
358
+ "path": "app/desktop-rune/crates/eloxiv-mac-notifications/src/lib.rs",
359
+ "content": "//! macOS's `UNUserNotificationCenter`, as the Rune host drives it (`app/src/notices_mac.rs`): reading and asking for\n//! the person's authorisation, scheduling a notification with its user info and, for a decision, its Approve and Reject\n//! actions, and withdrawing notifications. Every Objective-C message is here, behind a safe API; what to show and when\n//! stays in the app. On other systems the crate is empty.\n\n#[cfg(target_os = \"macos\")]\nmod mac {\n use block2::RcBlock;\n use objc2::rc::Retained;\n use objc2::runtime::{AnyObject, Bool};\n use objc2::{class, msg_send, msg_send_id};\n\n #[link(name = \"UserNotifications\", kind = \"framework\")]\n unsafe extern \"C\" {}\n\n // UNAuthorizationOptionAlert: banners only, never a sound or badge.\n const AUTH_ALERT: usize = 1 << 2;\n\n /// The category of a notification offering a decision, and its two actions' identifiers and titles.\n pub struct Decision<'a> {\n pub category: &'a str,\n pub approve: (&'a str, &'a str),\n pub reject: (&'a str, &'a str),\n }\n\n fn center() -> *mut AnyObject {\n // SAFETY: a class method of a framework this crate links, returning the shared center (not owned).\n unsafe { msg_send![class!(UNUserNotificationCenter), currentNotificationCenter] }\n }\n\n /// An autoreleased `NSString` (valid inside the caller's autorelease pool); a NUL in `s` is dropped.\n fn ns(s: &str) -> *mut AnyObject {\n let c = std::ffi::CString::new(s.replace('\\0', \"\")).unwrap_or_default();\n // SAFETY: `c` is a valid NUL-terminated UTF-8 string for the duration of the call.\n unsafe { msg_send![class!(NSString), stringWithUTF8String: c.as_ptr()] }\n }\n\n /// `getNotificationSettingsWithCompletionHandler:`: the `authorizationStatus` (-1 when no settings came back).\n pub fn read_settings(done: impl Fn(isize) + 'static) {\n let block = RcBlock::new(move |settings: *mut AnyObject| {\n // SAFETY: a non-null settings object the system handed to this completion handler.\n let status: isize =\n if settings.is_null() { -1 } else { unsafe { msg_send![settings, authorizationStatus] } };\n done(status);\n });\n // SAFETY: the block matches the handler's signature and is copied by the callee.\n unsafe {\n let _: () = msg_send![center(), getNotificationSettingsWithCompletionHandler: &*block];\n }\n }\n\n /// `requestAuthorizationWithOptions:completionHandler:` (banners): asks the person once; answers at once after that.\n pub fn request_authorization(done: impl Fn(bool) + 'static) {\n let block = RcBlock::new(move |granted: Bool, _error: *mut AnyObject| done(granted.as_bool()));\n // SAFETY: as above.\n unsafe {\n let _: () = msg_send![center(), requestAuthorizationWithOptions: AUTH_ALERT, completionHandler: &*block];\n }\n }\n\n /// Registers the decision category (its two actions; neither brings the app forward), once per process.\n fn register_category(decision: &Decision<'_>) {\n static ONCE: std::sync::Once = std::sync::Once::new();\n ONCE.call_once(|| {\n objc2::rc::autoreleasepool(|_| {\n // SAFETY: every argument is a live object of the class the selector takes; arrays and sets are built\n // from exactly `count` pointers.\n unsafe {\n let made: [*mut AnyObject; 2] = [\n msg_send![class!(UNNotificationAction), actionWithIdentifier: ns(decision.approve.0), title: ns(decision.approve.1), options: 0usize],\n msg_send![class!(UNNotificationAction), actionWithIdentifier: ns(decision.reject.0), title: ns(decision.reject.1), options: 0usize],\n ];\n let actions: *mut AnyObject = msg_send![class!(NSArray), arrayWithObjects: made.as_ptr(), count: made.len()];\n let empty: *mut AnyObject = msg_send![class!(NSArray), array];\n let category: Retained<AnyObject> = msg_send_id![class!(UNNotificationCategory), categoryWithIdentifier: ns(decision.category), actions: actions, intentIdentifiers: empty, options: 0usize];\n let all = [Retained::as_ptr(&category).cast_mut()];\n let set: *mut AnyObject = msg_send![class!(NSSet), setWithObjects: all.as_ptr(), count: all.len()];\n let _: () = msg_send![center(), setNotificationCategories: set];\n }\n });\n });\n }\n\n /// Schedules a notification now under the OS id `id`, with `info` as its user info (what a click hands back) and,\n /// for a decision, its category.\n pub fn schedule(id: &str, title: &str, body: &str, info: &[(&str, &str)], decision: Option<&Decision<'_>>) {\n if let Some(decision) = decision {\n register_category(decision);\n }\n objc2::rc::autoreleasepool(|_| {\n // SAFETY: as in `register_category`; the content object is retained for the whole block.\n unsafe {\n let content: Retained<AnyObject> = msg_send_id![class!(UNMutableNotificationContent), new];\n let content = Retained::as_ptr(&content).cast_mut();\n let _: () = msg_send![content, setTitle: ns(title)];\n let _: () = msg_send![content, setBody: ns(body)];\n let keys: Vec<*mut AnyObject> = info.iter().map(|(k, _)| ns(k)).collect();\n let values: Vec<*mut AnyObject> = info.iter().map(|(_, v)| ns(v)).collect();\n let dictionary: *mut AnyObject = msg_send![class!(NSDictionary), dictionaryWithObjects: values.as_ptr(), forKeys: keys.as_ptr(), count: info.len()];\n let _: () = msg_send![content, setUserInfo: dictionary];\n if let Some(decision) = decision {\n let _: () = msg_send![content, setCategoryIdentifier: ns(decision.category)];\n }\n let request: *mut AnyObject = msg_send![\n class!(UNNotificationRequest),\n requestWithIdentifier: ns(id),\n content: content,\n trigger: std::ptr::null::<AnyObject>()\n ];\n let _: () = msg_send![center(), addNotificationRequest: request, withCompletionHandler: std::ptr::null::<block2::Block<dyn Fn(*mut AnyObject)>>()];\n }\n });\n }\n\n /// Takes these OS ids out of Notification Center, delivered or still scheduled.\n pub fn remove(ids: &[String]) {\n if ids.is_empty() {\n return;\n }\n objc2::rc::autoreleasepool(|_| {\n // SAFETY: an array of exactly `count` live strings.\n unsafe {\n let items: Vec<*mut AnyObject> = ids.iter().map(|id| ns(id)).collect();\n let array: *mut AnyObject =\n msg_send![class!(NSArray), arrayWithObjects: items.as_ptr(), count: items.len()];\n let center = center();\n let _: () = msg_send![center, removeDeliveredNotificationsWithIdentifiers: array];\n let _: () = msg_send![center, removePendingNotificationRequestsWithIdentifiers: array];\n }\n });\n }\n}\n\n#[cfg(target_os = \"macos\")]\npub use mac::{Decision, read_settings, remove, request_authorization, schedule};\n",
360
+ "type": "registry:file",
361
+ "target": "desktop-rune/crates/eloxiv-mac-notifications/src/lib.rs"
362
+ },
363
+ {
364
+ "path": "app/desktop-rune/crates/eloxiv-update/Cargo.toml",
365
+ "content": "[package]\nname = \"eloxiv-update\"\nversion = \"0.1.0\"\ndescription = \"Signed updates for the Eloxiv desktop host: the update manifest, minisign (Ed25519) verification, download, archives, and the release signer\"\nedition.workspace = true\nrust-version.workspace = true\nlicense.workspace = true\npublish.workspace = true\n\n[features]\n# The signer (keys, signatures, the manifest): the `eloxiv-update` command. The host needs only verification.\ndefault = [\"sign\"]\nsign = []\n\n[[bin]]\nname = \"eloxiv-update\"\npath = \"src/main.rs\"\nrequired-features = [\"sign\"]\n\n[dependencies]\nserde.workspace = true\nserde_json.workspace = true\n# HTTPS for update hosts; plain HTTP is accepted on loopback only (tests, a local server).\nureq = { workspace = true, features = [\"rustls\"] }\nminisign = \"0.7.9\"\nsemver = \"1.0.28\"\nurl = \"2.5.8\"\ntar = \"0.4.44\"\nflate2 = \"1.1.11\"\n\n[lints]\nworkspace = true\n",
366
+ "type": "registry:file",
367
+ "target": "desktop-rune/crates/eloxiv-update/Cargo.toml"
368
+ },
369
+ {
370
+ "path": "app/desktop-rune/crates/eloxiv-update/src/archive.rs",
371
+ "content": "//! The `archive` kind: a gzipped tar of an install's contents (a macOS `.app` bundle's, or a Linux install\n//! directory's), modes and symbolic links kept. Unpacking refuses entries that would land outside the destination\n//! (absolute paths, `..`), as the `tar` crate's `unpack` does.\n\nuse std::fs::File;\nuse std::io;\nuse std::path::Path;\n\nuse flate2::Compression;\nuse flate2::read::GzDecoder;\nuse flate2::write::GzEncoder;\n\n/// Packs the contents of `dir` (not `dir` itself) into `out`.\npub fn pack(dir: &Path, out: &Path) -> io::Result<()> {\n let file = File::create(out)?;\n let mut builder = tar::Builder::new(GzEncoder::new(file, Compression::default()));\n builder.follow_symlinks(false);\n builder.mode(tar::HeaderMode::Complete);\n builder.append_dir_all(\".\", dir)?;\n builder.into_inner()?.finish()?.sync_all()\n}\n\n/// Unpacks `archive` into `dest`, which must not exist yet; on failure nothing is left there.\npub fn unpack(archive: &Path, dest: &Path) -> io::Result<()> {\n if dest.exists() {\n return Err(io::Error::new(io::ErrorKind::AlreadyExists, format!(\"{} exists\", dest.display())));\n }\n std::fs::create_dir_all(dest)?;\n let result = (|| {\n let mut tar = tar::Archive::new(GzDecoder::new(File::open(archive)?));\n tar.set_preserve_permissions(true);\n tar.set_overwrite(false);\n tar.unpack(dest)\n })();\n if result.is_err() {\n let _ = std::fs::remove_dir_all(dest);\n }\n result\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn an_install_round_trips_with_its_modes() {\n let root = std::env::temp_dir().join(format!(\"eloxiv-update-archive-{}\", std::process::id()));\n let _ = std::fs::remove_dir_all(&root);\n struct Gone<'a>(&'a Path);\n impl Drop for Gone<'_> {\n fn drop(&mut self) {\n let _ = std::fs::remove_dir_all(self.0);\n }\n }\n let _gone = Gone(&root);\n let install = root.join(\"install\");\n std::fs::create_dir_all(install.join(\"Contents/MacOS\")).expect(\"a test directory\");\n std::fs::write(install.join(\"Contents/MacOS/app\"), b\"#!/bin/sh\\n\").expect(\"a test file\");\n std::fs::write(install.join(\"notes.txt\"), b\"kept\\n\").expect(\"a test file\");\n #[cfg(unix)]\n {\n use std::os::unix::fs::PermissionsExt;\n std::fs::set_permissions(install.join(\"Contents/MacOS/app\"), std::fs::Permissions::from_mode(0o755))\n .expect(\"as the test set it up\");\n }\n let archive = root.join(\"install.tar.gz\");\n pack(&install, &archive).expect(\"as the test set it up\");\n let out = root.join(\"out\");\n unpack(&archive, &out).expect(\"as the test set it up\");\n assert_eq!(std::fs::read(out.join(\"Contents/MacOS/app\")).expect(\"as the test set it up\"), b\"#!/bin/sh\\n\");\n assert_eq!(std::fs::read(out.join(\"notes.txt\")).expect(\"as the test set it up\"), b\"kept\\n\");\n #[cfg(unix)]\n {\n use std::os::unix::fs::PermissionsExt;\n let mode =\n std::fs::metadata(out.join(\"Contents/MacOS/app\")).expect(\"as the test set it up\").permissions().mode();\n assert_eq!(mode & 0o777, 0o755);\n }\n assert!(unpack(&archive, &out).is_err(), \"never over an existing directory\");\n std::fs::write(root.join(\"broken.tar.gz\"), b\"not a gzip\").expect(\"a test file\");\n assert!(unpack(&root.join(\"broken.tar.gz\"), &root.join(\"broken\")).is_err());\n assert!(!root.join(\"broken\").exists(), \"nothing left of a failed unpack\");\n }\n}\n",
372
+ "type": "registry:file",
373
+ "target": "desktop-rune/crates/eloxiv-update/src/archive.rs"
374
+ },
375
+ {
376
+ "path": "app/desktop-rune/crates/eloxiv-update/src/lib.rs",
377
+ "content": "//! Signed updates for the Eloxiv desktop host (the Host contract's `updates`).\n//!\n//! - **The manifest** is JSON at a URL the app configures (a template: `{channel}`, `{platform}`, `{os}`, `{arch}`,\n//! `{kind}`, `{app}` and `{current}` are filled in), one per channel:\n//!\n//! ```json\n//! { \"app\": \"com.example.app\", \"channel\": \"stable\", \"version\": \"1.2.0\", \"notes\": \"…\", \"pub_date\": \"…\",\n//! \"platforms\": { \"linux-x86_64-appimage\": { \"url\": \"Example-1.2.0.AppImage\", \"kind\": \"appimage\",\n//! \"size\": 123456, \"signature\": \"untrusted comment: …\\n…\" } } }\n//! ```\n//!\n//! A platform is `<os>-<arch>` (`linux-x86_64`, `macos-aarch64`, `windows-x86_64`); an entry is found under\n//! `<platform>-<kind>`, else `<platform>` (whose kind must then be this install's). An artifact URL may be\n//! relative to the manifest's. Update hosts are HTTPS; plain HTTP is accepted on loopback only.\n//! - **Signatures** are minisign's (Ed25519 over the file's BLAKE2b-512 hash), checked against the app's public key.\n//! The signature's trusted comment, which the key also signs, names what was signed:\n//! `eloxiv-update app=<id> version=<v> platform=<p> kind=<k>`; it must equal the manifest's entry, so a validly\n//! signed artifact of an older version, another platform or another app is refused even under a forged manifest.\n//! Unsigned, legacy (not prehashed) and mismatched signatures are refused.\n//! - **Never a downgrade**: a manifest whose version is not newer than this build (semver) offers nothing.\n//! - **Downloads** are bounded by the manifest's `size`: more bytes, or fewer (an interrupted download), refuse it;\n//! a refused or interrupted download leaves no file behind.\n//!\n//! The signer (feature `sign`, the `eloxiv-update` command) makes the keys, signs a release's artifacts and writes\n//! the manifest.\n\npub mod archive;\n#[cfg(feature = \"sign\")]\npub mod sign;\n\nuse std::collections::BTreeMap;\nuse std::fs::File;\nuse std::io::{Read, Write};\nuse std::path::Path;\nuse std::time::Duration;\n\npub use minisign::PublicKey;\nuse minisign::SignatureBox;\npub use semver::Version;\nuse serde::{Deserialize, Serialize};\nuse url::Url;\n\n/// How an update is applied, per install: an AppImage swapped for the new one (Linux), an archive of the install\n/// (a macOS `.app` bundle's contents, or a Linux install directory) swapped for the old one, or an installer run\n/// (Windows: NSIS `.exe` or `.msi`).\n#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]\n#[serde(rename_all = \"lowercase\")]\npub enum Kind {\n Appimage,\n Archive,\n Installer,\n}\n\nimpl Kind {\n pub fn as_str(self) -> &'static str {\n match self {\n Kind::Appimage => \"appimage\",\n Kind::Archive => \"archive\",\n Kind::Installer => \"installer\",\n }\n }\n\n pub fn parse(s: &str) -> Option<Kind> {\n match s {\n \"appimage\" => Some(Kind::Appimage),\n \"archive\" => Some(Kind::Archive),\n \"installer\" => Some(Kind::Installer),\n _ => None,\n }\n }\n}\n\nimpl std::fmt::Display for Kind {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.write_str(self.as_str())\n }\n}\n\n/// This build's platform: `<os>-<arch>` (`linux-x86_64`, `macos-aarch64`, `windows-x86_64`).\npub fn platform() -> String {\n format!(\"{}-{}\", std::env::consts::OS, std::env::consts::ARCH)\n}\n\n/// The update manifest.\n#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]\npub struct Manifest {\n /// The app identifier it is for (required; refused when it names another).\n pub app: String,\n /// Its channel (required; refused when it names another than the host's; also signed into each artifact).\n pub channel: String,\n pub version: String,\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n pub notes: Option<String>,\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n pub pub_date: Option<String>,\n pub platforms: BTreeMap<String, Artifact>,\n}\n\n/// One platform's build.\n#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]\npub struct Artifact {\n /// Absolute, or relative to the manifest's URL.\n pub url: String,\n pub kind: Kind,\n /// Its exact size in bytes.\n pub size: u64,\n /// The minisign signature (the `.minisig` file's text).\n pub signature: String,\n}\n\n/// Where this host looks for updates, and what it is.\n#[derive(Clone, Debug)]\npub struct Source {\n /// The manifest URL template.\n pub manifest_url: String,\n /// The app's minisign public key (the base64 line, or the whole `.pub` file).\n pub public_key: String,\n pub channel: String,\n pub app: String,\n pub current: Version,\n pub kind: Kind,\n pub platform: String,\n}\n\nimpl Source {\n /// The manifest URL, its placeholders filled in.\n pub fn url(&self) -> String {\n self.manifest_url\n .replace(\"{channel}\", &self.channel)\n .replace(\"{platform}\", &self.platform)\n .replace(\"{os}\", std::env::consts::OS)\n .replace(\"{arch}\", std::env::consts::ARCH)\n .replace(\"{kind}\", self.kind.as_str())\n .replace(\"{app}\", &self.app)\n .replace(\"{current}\", &self.current.to_string())\n }\n}\n\n/// A newer build the manifest offers for this install.\n#[derive(Clone, Debug, PartialEq)]\npub struct Offer {\n pub version: Version,\n pub notes: Option<String>,\n /// Absolute.\n pub url: String,\n pub kind: Kind,\n pub size: u64,\n pub signature: String,\n pub platform: String,\n}\n\n#[derive(Clone, Debug, PartialEq, Eq)]\npub enum Error {\n /// The host's update configuration is unusable (a URL that is not HTTPS, a public key that does not decode).\n Config(String),\n /// The update host could not be reached or answered with an error.\n Network(String),\n /// The manifest is malformed, or for another app or channel.\n Manifest(String),\n /// The signature is missing, malformed, by another key, for something else, or does not match the file.\n Signature(String),\n /// What would be applied is not newer than this build.\n Downgrade {\n current: String,\n offered: String,\n },\n /// The download ended early or ran past its declared size.\n Interrupted(String),\n Io(String),\n}\n\nimpl std::fmt::Display for Error {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n match self {\n Error::Config(m) => write!(f, \"the update configuration is unusable: {m}\"),\n Error::Network(m) => write!(f, \"the update host could not be reached: {m}\"),\n Error::Manifest(m) => write!(f, \"the update manifest is refused: {m}\"),\n Error::Signature(m) => write!(f, \"the update's signature is refused: {m}\"),\n Error::Downgrade { current, offered } => {\n write!(f, \"{offered} is not newer than this build ({current}): never a downgrade\")\n }\n Error::Interrupted(m) => write!(f, \"the download did not complete: {m}\"),\n Error::Io(m) => write!(f, \"{m}\"),\n }\n }\n}\n\nimpl std::error::Error for Error {}\n\nimpl From<std::io::Error> for Error {\n fn from(e: std::io::Error) -> Error {\n Error::Io(e.to_string())\n }\n}\n\n/// Whether `a` is newer than `b` by SemVer precedence: build metadata (`+…`) never makes a version newer (semver's\n/// `Ord` orders it, so `1.2.0+x > 1.2.0` there; every comparison of versions here goes through this).\npub fn newer(a: &Version, b: &Version) -> bool {\n a.cmp_precedence(b) == std::cmp::Ordering::Greater\n}\n\n/// The trusted comment a release's artifact is signed with: its app, channel, version, platform and kind, so a\n/// signed build of another channel (a beta served to stable) is refused like one of another app.\npub fn trusted_comment(app: &str, channel: &str, version: &Version, platform: &str, kind: Kind) -> String {\n format!(\"eloxiv-update app={app} channel={channel} version={version} platform={platform} kind={kind}\")\n}\n\n/// The app's public key, from its base64 line or a whole minisign `.pub` file.\npub fn public_key(text: &str) -> Result<PublicKey, Error> {\n let line = text\n .lines()\n .map(str::trim)\n .rfind(|l| !l.is_empty() && !l.starts_with(\"untrusted comment:\"))\n .ok_or_else(|| Error::Config(\"no public key\".into()))?;\n PublicKey::from_base64(line).map_err(|e| Error::Config(format!(\"the public key does not decode: {e}\")))\n}\n\n/// Whether `url` may be fetched: HTTPS, or HTTP to a loopback host.\npub fn allowed(url: &Url) -> bool {\n match url.scheme() {\n \"https\" => true,\n \"http\" => matches!(url.host_str(), Some(\"127.0.0.1\" | \"localhost\" | \"[::1]\" | \"::1\")),\n _ => false,\n }\n}\n\nconst MANIFEST_MAX: u64 = 1 << 20;\n/// No artifact is larger, whatever a manifest says.\npub const ARTIFACT_MAX: u64 = 4 << 30;\n\nfn network(e: ureq::Error) -> Error {\n Error::Network(e.to_string())\n}\n\n/// The most redirects followed for one request.\nconst REDIRECTS: usize = 5;\n\n/// GETs `url`, following redirects by hand, each one held to [`allowed`] (HTTPS, or HTTP on loopback): an HTTPS host\n/// that redirects to plain HTTP elsewhere is refused, never followed.\nfn get(url: &Url, body: Duration) -> Result<ureq::http::Response<ureq::Body>, Error> {\n let agent: ureq::Agent = ureq::Agent::config_builder()\n .timeout_connect(Some(Duration::from_secs(15)))\n .timeout_recv_response(Some(Duration::from_secs(30)))\n .timeout_recv_body(Some(body))\n .max_redirects(0)\n .build()\n .into();\n let mut url = url.clone();\n for _ in 0..=REDIRECTS {\n let response = agent.get(url.as_str()).call().map_err(network)?;\n if !response.status().is_redirection() {\n return Ok(response);\n }\n let location = response\n .headers()\n .get(\"location\")\n .and_then(|v| v.to_str().ok())\n .ok_or_else(|| Error::Network(format!(\"{url} redirects without a location\")))?;\n let next = url.join(location).map_err(|e| Error::Network(format!(\"{url} redirects to {location:?}: {e}\")))?;\n if !allowed(&next) {\n return Err(Error::Network(format!(\"{url} redirects to {next}, which is not HTTPS: refused\")));\n }\n url = next;\n }\n Err(Error::Network(format!(\"more than {REDIRECTS} redirects\")))\n}\n\n/// Asks the update host for the manifest and returns the newer build it offers for this install, if any.\npub fn check(source: &Source) -> Result<Option<Offer>, Error> {\n let url = Url::parse(&source.url()).map_err(|e| Error::Config(format!(\"{}: {e}\", source.url())))?;\n if !allowed(&url) {\n return Err(Error::Config(format!(\"{url} is not HTTPS (plain HTTP only on loopback)\")));\n }\n let mut response = get(&url, Duration::from_secs(30))?;\n let text = response\n .body_mut()\n .with_config()\n .limit(MANIFEST_MAX)\n .read_to_string()\n .map_err(|e| Error::Manifest(format!(\"could not read it: {e}\")))?;\n let manifest: Manifest =\n serde_json::from_str(&text).map_err(|e| Error::Manifest(format!(\"it does not decode: {e}\")))?;\n offer_in(source, &url, manifest)\n}\n\n/// The newer build `manifest` (fetched from `manifest_url`) offers for this install, if any (pure).\npub fn offer_in(source: &Source, manifest_url: &Url, manifest: Manifest) -> Result<Option<Offer>, Error> {\n if manifest.app != source.app {\n return Err(Error::Manifest(format!(\"it is for {:?}, not {:?}\", manifest.app, source.app)));\n }\n if manifest.channel != source.channel {\n return Err(Error::Manifest(format!(\"it is for the {:?} channel, not {:?}\", manifest.channel, source.channel)));\n }\n let version = Version::parse(manifest.version.trim())\n .map_err(|e| Error::Manifest(format!(\"{:?} is not a version: {e}\", manifest.version)))?;\n if !newer(&version, &source.current) {\n return Ok(None);\n }\n let keyed = format!(\"{}-{}\", source.platform, source.kind);\n let Some(artifact) = manifest.platforms.get(&keyed).or_else(|| manifest.platforms.get(&source.platform)) else {\n return Ok(None);\n };\n if artifact.kind != source.kind {\n // A build for another install kind (an installer where this is an AppImage) is not this install's update.\n return Ok(None);\n }\n let url = manifest_url.join(&artifact.url).map_err(|e| Error::Manifest(format!(\"{:?}: {e}\", artifact.url)))?;\n if !allowed(&url) {\n return Err(Error::Manifest(format!(\"{url} is not HTTPS (plain HTTP only on loopback)\")));\n }\n if artifact.size == 0 || artifact.size > ARTIFACT_MAX {\n return Err(Error::Manifest(format!(\"{} bytes is not a size it may have\", artifact.size)));\n }\n Ok(Some(Offer {\n version,\n notes: manifest.notes,\n url: url.into(),\n kind: artifact.kind,\n size: artifact.size,\n signature: artifact.signature.clone(),\n platform: source.platform.clone(),\n }))\n}\n\n/// Downloads `offer` to `dest` and verifies it against the app's key; on any failure nothing is left at `dest`.\n/// `progress` is called with the bytes received so far.\npub fn download(source: &Source, offer: &Offer, dest: &Path, progress: &mut dyn FnMut(u64)) -> Result<(), Error> {\n let result = fetch_to(offer, dest, progress).and_then(|()| {\n if !newer(&offer.version, &source.current) {\n return Err(Error::Downgrade { current: source.current.to_string(), offered: offer.version.to_string() });\n }\n let key = public_key(&source.public_key)?;\n let expected = trusted_comment(&source.app, &source.channel, &offer.version, &offer.platform, offer.kind);\n verify_file(&key, dest, &offer.signature, &expected)\n });\n if result.is_err() {\n let _ = std::fs::remove_file(dest);\n }\n result\n}\n\nfn fetch_to(offer: &Offer, dest: &Path, progress: &mut dyn FnMut(u64)) -> Result<(), Error> {\n let url = Url::parse(&offer.url).map_err(|e| Error::Manifest(e.to_string()))?;\n if !allowed(&url) {\n return Err(Error::Manifest(format!(\"{url} is not HTTPS (plain HTTP only on loopback)\")));\n }\n let mut response = get(&url, Duration::from_secs(60 * 60))?;\n let declared = response.headers().get(\"content-length\").and_then(|v| v.to_str().ok()?.parse::<u64>().ok());\n if declared.is_some_and(|n| n != offer.size) {\n return Err(Error::Interrupted(format!(\n \"the host sends {} bytes, the manifest says {}\",\n declared.unwrap_or_default(),\n offer.size\n )));\n }\n // One byte past the declared size is enough to know it is too long.\n let mut reader = response.body_mut().with_config().limit(offer.size + 1).reader();\n let mut file = File::create(dest)?;\n let mut buf = vec![0u8; 64 * 1024];\n let mut got: u64 = 0;\n loop {\n let n = match reader.read(&mut buf) {\n Ok(0) => break,\n Ok(n) => n,\n Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,\n Err(e) => return Err(Error::Interrupted(format!(\"after {got} of {} bytes: {e}\", offer.size))),\n };\n got += n as u64;\n if got > offer.size {\n return Err(Error::Interrupted(format!(\"more than the {} bytes the manifest says\", offer.size)));\n }\n file.write_all(&buf[..n])?;\n progress(got);\n }\n if got != offer.size {\n return Err(Error::Interrupted(format!(\"{got} of {} bytes arrived\", offer.size)));\n }\n file.sync_all()?;\n Ok(())\n}\n\n/// Verifies `path` against `signature` (a minisign signature's text) by `key`, whose trusted comment must be\n/// `expected`. Legacy (not prehashed) signatures are refused.\npub fn verify_file(key: &PublicKey, path: &Path, signature: &str, expected: &str) -> Result<(), Error> {\n if signature.trim().is_empty() {\n return Err(Error::Signature(\"the artifact is unsigned\".into()));\n }\n let sig = SignatureBox::from_string(signature).map_err(|e| Error::Signature(format!(\"it does not decode: {e}\")))?;\n let comment = sig.trusted_comment().map_err(|e| Error::Signature(format!(\"no trusted comment: {e}\")))?;\n let file = File::open(path)?;\n minisign::verify(key, &sig, file, true, false, false).map_err(|e| Error::Signature(e.to_string()))?;\n // Checked once the key vouched for the comment.\n if comment.trim() != expected {\n return Err(Error::Signature(format!(\"it was signed for {:?}, not {expected:?}\", comment.trim())));\n }\n Ok(())\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n fn source() -> Source {\n Source {\n manifest_url: \"https://updates.example.com/{app}/{channel}/{platform}-{kind}.json?from={current}\".into(),\n public_key: String::new(),\n channel: \"stable\".into(),\n app: \"com.example.app\".into(),\n current: Version::new(1, 2, 0),\n kind: Kind::Appimage,\n platform: \"linux-x86_64\".into(),\n }\n }\n\n fn manifest(version: &str) -> Manifest {\n let artifact =\n |kind| Artifact { url: \"files/app.bin\".into(), kind, size: 10, signature: \"untrusted comment: x\".into() };\n Manifest {\n app: \"com.example.app\".into(),\n channel: \"stable\".into(),\n version: version.into(),\n notes: None,\n pub_date: None,\n platforms: BTreeMap::from([\n (\"linux-x86_64-appimage\".into(), artifact(Kind::Appimage)),\n (\"linux-x86_64-archive\".into(), artifact(Kind::Archive)),\n (\"windows-x86_64\".into(), artifact(Kind::Installer)),\n ]),\n }\n }\n\n fn base() -> Url {\n Url::parse(\"https://updates.example.com/com.example.app/stable/m.json\").expect(\"a URL\")\n }\n\n #[test]\n fn the_manifest_url_is_filled_in() {\n assert_eq!(\n source().url(),\n \"https://updates.example.com/com.example.app/stable/linux-x86_64-appimage.json?from=1.2.0\"\n );\n }\n\n #[test]\n fn only_a_newer_version_is_offered() {\n let s = source();\n let offer = offer_in(&s, &base(), manifest(\"1.3.0\")).expect(\"as the test set it up\").expect(\"1.3.0 is newer\");\n assert_eq!(offer.url, \"https://updates.example.com/com.example.app/stable/files/app.bin\");\n assert_eq!(offer.kind, Kind::Appimage);\n // Build metadata has no precedence (SemVer 10): 1.2.0+rebuild is 1.2.0, never newer.\n for older in [\"1.2.0\", \"1.1.9\", \"0.9.0\", \"1.2.0-rc.1\", \"1.2.0+rebuild\", \"1.1.9+zzz\"] {\n assert_eq!(offer_in(&s, &base(), manifest(older)).expect(\"as the test set it up\"), None, \"{older}\");\n }\n assert!(\n offer_in(&s, &base(), manifest(\"1.2.1-beta.1\")).expect(\"as the test set it up\").is_some(),\n \"a newer prerelease\"\n );\n }\n\n #[test]\n fn another_apps_or_channels_manifest_is_refused() {\n let mut m = manifest(\"2.0.0\");\n m.app = \"com.evil.app\".into();\n assert!(matches!(offer_in(&source(), &base(), m), Err(Error::Manifest(_))));\n let mut m = manifest(\"2.0.0\");\n m.channel = \"beta\".into();\n assert!(matches!(offer_in(&source(), &base(), m), Err(Error::Manifest(_))));\n assert!(matches!(offer_in(&source(), &base(), manifest(\"two\")), Err(Error::Manifest(_))));\n }\n\n #[test]\n fn the_entry_is_this_platforms_and_this_installs() {\n let mut s = source();\n s.platform = \"macos-aarch64\".into();\n assert_eq!(\n offer_in(&s, &base(), manifest(\"2.0.0\")).expect(\"as the test set it up\"),\n None,\n \"no build for the platform\"\n );\n let mut s = source();\n s.platform = \"windows-x86_64\".into();\n s.kind = Kind::Installer;\n assert_eq!(\n offer_in(&s, &base(), manifest(\"2.0.0\")).expect(\"as the test set it up\").map(|o| o.kind),\n Some(Kind::Installer)\n );\n s.kind = Kind::Archive;\n assert_eq!(\n offer_in(&s, &base(), manifest(\"2.0.0\")).expect(\"as the test set it up\"),\n None,\n \"an installer is not an archive\"\n );\n }\n\n #[test]\n fn update_hosts_are_https_or_loopback() {\n for ok in [\"https://u.example.com/m.json\", \"http://127.0.0.1:8080/m.json\", \"http://localhost/m\"] {\n assert!(allowed(&Url::parse(ok).expect(\"a URL\")), \"{ok}\");\n }\n for bad in [\"http://u.example.com/m.json\", \"file:///etc/passwd\", \"ftp://x/y\", \"http://127.0.0.2.evil.com/\"] {\n assert!(!allowed(&Url::parse(bad).expect(\"a URL\")), \"{bad}\");\n }\n let mut m = manifest(\"2.0.0\");\n m.platforms.get_mut(\"linux-x86_64-appimage\").expect(\"as the test set it up\").url =\n \"http://cdn.example.com/a\".into();\n assert!(matches!(offer_in(&source(), &base(), m), Err(Error::Manifest(_))));\n }\n}\n",
378
+ "type": "registry:file",
379
+ "target": "desktop-rune/crates/eloxiv-update/src/lib.rs"
380
+ },
381
+ {
382
+ "path": "app/desktop-rune/crates/eloxiv-update/src/main.rs",
383
+ "content": "//! `eloxiv-update`: signs a desktop host's release and writes its update manifest.\n//!\n//! ```sh\n//! eloxiv-update keygen --out keys/ # keys/update.key (secret), keys/update.pub; prints the public key\n//! eloxiv-update pack <install dir> <out.tar.gz> # the `archive` kind: a .app bundle's or install dir's contents\n//! eloxiv-update release --config desktop-rune/app.json [--notes TEXT] \\\n//! --artifact linux-x86_64:appimage:dist/Example.AppImage [--artifact <platform>:<kind>:<path>[=<url>]]... \\\n//! --out dist/stable.json # signs each artifact (<path>.minisig) and writes the manifest\n//! eloxiv-update release --app com.example.app --version 1.2.0 [--channel stable] ... # without the app's app.json\n//! eloxiv-update verify --public-key <base64|file> --manifest dist/stable.json --platform linux-x86_64 --kind appimage --file dist/Example.AppImage\n//! ```\n//!\n//! The secret key is read from `ELOXIV_UPDATE_SECRET_KEY` (its file's text) or `--key <file>`; its password from\n//! `ELOXIV_UPDATE_KEY_PASSWORD` (empty or unset: an unencrypted key). `keygen` encrypts with that password when set.\n//! An existing manifest at `--out` for the same app, channel and version is added to (each CI runner its platform).\n//! `--config` reads the app's `app.json` (the file the host compiles in and packaging reads): the app is its\n//! `identifier`, the version its `version`, the channel its `updates.channel`; `--app`, `--version` and `--channel`\n//! override them.\n\nuse std::path::{Path, PathBuf};\nuse std::process::ExitCode;\n\nuse eloxiv_update::sign::{self, Release, ReleaseInfo};\nuse eloxiv_update::{Kind, Manifest, Version, archive, public_key, trusted_comment, verify_file};\n\nfn main() -> ExitCode {\n let args: Vec<String> = std::env::args().skip(1).collect();\n match run(&args) {\n Ok(()) => ExitCode::SUCCESS,\n Err(e) => {\n eprintln!(\"eloxiv-update: {e}\");\n ExitCode::FAILURE\n }\n }\n}\n\n/// `--name value` options, repeated ones in order.\nstruct Options(Vec<(String, String)>);\n\nimpl Options {\n fn parse(args: &[String]) -> Result<(Options, Vec<String>), String> {\n let (mut opts, mut rest) = (Vec::new(), Vec::new());\n let mut it = args.iter();\n while let Some(a) = it.next() {\n if let Some(name) = a.strip_prefix(\"--\") {\n let value = it.next().ok_or_else(|| format!(\"--{name} needs a value\"))?;\n opts.push((name.to_owned(), value.clone()));\n } else {\n rest.push(a.clone());\n }\n }\n Ok((Options(opts), rest))\n }\n fn get(&self, name: &str) -> Option<&str> {\n self.0.iter().rev().find(|(n, _)| n == name).map(|(_, v)| v.as_str())\n }\n fn need(&self, name: &str) -> Result<&str, String> {\n self.get(name).ok_or_else(|| format!(\"--{name} is required\"))\n }\n fn all(&self, name: &str) -> impl Iterator<Item = &str> {\n self.0.iter().filter(move |(n, _)| n == name).map(|(_, v)| v.as_str())\n }\n}\n\nfn password() -> String {\n std::env::var(\"ELOXIV_UPDATE_KEY_PASSWORD\").unwrap_or_default()\n}\n\nfn run(args: &[String]) -> Result<(), String> {\n let Some((command, rest)) = args.split_first() else {\n return Err(\"a command: keygen, pack, release or verify (see the crate's README)\".into());\n };\n let (opts, positional) = Options::parse(rest)?;\n match command.as_str() {\n \"keygen\" => {\n let out = PathBuf::from(opts.need(\"out\")?);\n std::fs::create_dir_all(&out).map_err(|e| e.to_string())?;\n let (secret, public) = (out.join(\"update.key\"), out.join(\"update.pub\"));\n if secret.exists() {\n return Err(format!(\"{} exists: never overwritten\", secret.display()));\n }\n let pw = password();\n let keys = sign::keygen(&pw).map_err(|e| e.to_string())?;\n write_private(&secret, &keys.secret_file)?;\n std::fs::write(&public, &keys.public_file).map_err(|e| e.to_string())?;\n if pw.is_empty() {\n eprintln!(\"eloxiv-update: the secret key is unencrypted (ELOXIV_UPDATE_KEY_PASSWORD was not set)\");\n }\n eprintln!(\"eloxiv-update: wrote {} and {}\", secret.display(), public.display());\n eprintln!(\"eloxiv-update: the app's public key (app.json updates.publicKey):\");\n println!(\"{}\", keys.public_base64);\n Ok(())\n }\n \"pack\" => {\n let [dir, out] = positional.as_slice() else { return Err(\"pack <install dir> <out.tar.gz>\".into()) };\n archive::pack(Path::new(dir), Path::new(out)).map_err(|e| e.to_string())\n }\n \"release\" => {\n let config = match opts.get(\"config\") {\n Some(file) => AppConfig::read(Path::new(file))?,\n None => AppConfig::default(),\n };\n let pick = |name: &str, from_config: Option<String>| {\n opts.get(name)\n .map(str::to_owned)\n .or(from_config)\n .ok_or_else(|| format!(\"--{name} is required (or --config <app.json>)\"))\n };\n let version = Version::parse(&pick(\"version\", config.version)?).map_err(|e| e.to_string())?;\n let info = ReleaseInfo {\n app: pick(\"app\", config.identifier)?,\n channel: opts.get(\"channel\").map(str::to_owned).or(config.channel).unwrap_or_else(|| \"stable\".into()),\n version,\n notes: opts.get(\"notes\").map(str::to_owned),\n pub_date: opts.get(\"pub-date\").map(str::to_owned),\n };\n let artifacts = opts.all(\"artifact\").map(artifact).collect::<Result<Vec<_>, _>>()?;\n if artifacts.is_empty() {\n return Err(\"at least one --artifact <platform>:<kind>:<path>\".into());\n }\n let secret = match (std::env::var(\"ELOXIV_UPDATE_SECRET_KEY\"), opts.get(\"key\")) {\n (Ok(text), _) if !text.trim().is_empty() => text,\n (_, Some(file)) => std::fs::read_to_string(file).map_err(|e| format!(\"{file}: {e}\"))?,\n _ => return Err(\"the secret key: ELOXIV_UPDATE_SECRET_KEY or --key <file>\".into()),\n };\n let out = PathBuf::from(opts.need(\"out\")?);\n let existing = std::fs::read_to_string(&out).ok().and_then(|t| serde_json::from_str::<Manifest>(&t).ok());\n let manifest =\n sign::release(&info, &secret, &password(), &artifacts, existing).map_err(|e| e.to_string())?;\n for a in &artifacts {\n let entry = &manifest.platforms[&format!(\"{}-{}\", a.platform, a.kind)];\n let sig = a.path.with_file_name(format!(\n \"{}.minisig\",\n a.path.file_name().map(|n| n.to_string_lossy()).unwrap_or_default()\n ));\n std::fs::write(&sig, &entry.signature).map_err(|e| e.to_string())?;\n }\n let json = serde_json::to_string_pretty(&manifest).map_err(|e| e.to_string())?;\n std::fs::write(&out, json + \"\\n\").map_err(|e| e.to_string())?;\n eprintln!(\"eloxiv-update: {} {} signed; manifest {}\", info.app, info.version, out.display());\n Ok(())\n }\n \"verify\" => {\n let key_arg = opts.need(\"public-key\")?;\n let key_text = std::fs::read_to_string(key_arg).unwrap_or_else(|_| key_arg.to_owned());\n let key = public_key(&key_text).map_err(|e| e.to_string())?;\n let manifest: Manifest =\n serde_json::from_str(&std::fs::read_to_string(opts.need(\"manifest\")?).map_err(|e| e.to_string())?)\n .map_err(|e| e.to_string())?;\n let platform = opts.need(\"platform\")?;\n let kind = Kind::parse(opts.need(\"kind\")?).ok_or(\"--kind is appimage, archive or installer\")?;\n let entry = manifest\n .platforms\n .get(&format!(\"{platform}-{kind}\"))\n .ok_or_else(|| format!(\"no {platform}-{kind} entry\"))?;\n let version = Version::parse(&manifest.version).map_err(|e| e.to_string())?;\n let (app, channel) = (manifest.app.clone(), manifest.channel.clone());\n verify_file(\n &key,\n Path::new(opts.need(\"file\")?),\n &entry.signature,\n &trusted_comment(&app, &channel, &version, platform, kind),\n )\n .map_err(|e| e.to_string())?;\n eprintln!(\"eloxiv-update: verified\");\n Ok(())\n }\n other => Err(format!(\"unknown command {other:?}: keygen, pack, release or verify\")),\n }\n}\n\n/// What the signer takes from the app's `app.json`.\n#[derive(Default)]\nstruct AppConfig {\n identifier: Option<String>,\n version: Option<String>,\n channel: Option<String>,\n}\n\nimpl AppConfig {\n fn read(file: &Path) -> Result<AppConfig, String> {\n let text = std::fs::read_to_string(file).map_err(|e| format!(\"{}: {e}\", file.display()))?;\n let json: serde_json::Value = serde_json::from_str(&text).map_err(|e| format!(\"{}: {e}\", file.display()))?;\n let field = |v: &serde_json::Value| v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned);\n Ok(AppConfig {\n identifier: field(&json[\"identifier\"]),\n version: field(&json[\"version\"]),\n channel: field(&json[\"updates\"][\"channel\"]),\n })\n }\n}\n\n/// `<platform>:<kind>:<path>[=<url>]`.\nfn artifact(spec: &str) -> Result<Release, String> {\n let (spec, url) = match spec.split_once('=') {\n Some((s, u)) => (s, Some(u.to_owned())),\n None => (spec, None),\n };\n let mut parts = spec.splitn(3, ':');\n let (Some(platform), Some(kind), Some(path)) = (parts.next(), parts.next(), parts.next()) else {\n return Err(format!(\"{spec:?} is not <platform>:<kind>:<path>\"));\n };\n let kind = Kind::parse(kind).ok_or_else(|| format!(\"{kind:?}: the kind is appimage, archive or installer\"))?;\n Ok(Release { platform: platform.to_owned(), kind, path: PathBuf::from(path), url })\n}\n\nfn write_private(path: &Path, text: &str) -> Result<(), String> {\n let mut options = std::fs::OpenOptions::new();\n options.write(true).create_new(true);\n #[cfg(unix)]\n {\n use std::os::unix::fs::OpenOptionsExt;\n options.mode(0o600);\n }\n use std::io::Write;\n options.open(path).and_then(|mut f| f.write_all(text.as_bytes())).map_err(|e| format!(\"{}: {e}\", path.display()))\n}\n",
384
+ "type": "registry:file",
385
+ "target": "desktop-rune/crates/eloxiv-update/src/main.rs"
386
+ },
387
+ {
388
+ "path": "app/desktop-rune/crates/eloxiv-update/src/sign.rs",
389
+ "content": "//! The release signer: minisign keys, a release's signatures and its manifest. Nothing here asks for a password\n//! interactively: it is given (empty for a key kept unencrypted, as a CI secret usually is).\n\nuse std::path::{Path, PathBuf};\n\nuse minisign::{KeyPair, PublicKey, SecretKeyBox};\n\nuse crate::{Artifact, Error, Kind, Manifest, Version, trusted_comment};\n\n/// A new key pair: the public key's base64 line (what the app configures), its `.pub` file, and the secret key's\n/// file (encrypted with the password, unless it is empty).\n#[derive(Clone, Debug)]\npub struct Keys {\n pub public_base64: String,\n pub public_file: String,\n pub secret_file: String,\n}\n\nfn failed(e: minisign::PError) -> Error {\n Error::Signature(e.to_string())\n}\n\npub fn keygen(password: &str) -> Result<Keys, Error> {\n let KeyPair { pk, sk } = KeyPair::generate_encrypted_keypair(Some(password.to_owned())).map_err(failed)?;\n Ok(Keys {\n public_base64: pk.to_base64(),\n public_file: pk.to_box().map_err(failed)?.into_string(),\n secret_file: sk.to_box(Some(\"eloxiv-update secret key\")).map_err(failed)?.into_string(),\n })\n}\n\n/// Signs `path` with the secret key (its file's text) under `comment`; returns the signature's text.\npub fn sign_file(secret_key: &str, password: &str, path: &Path, comment: &str) -> Result<String, Error> {\n let sk = SecretKeyBox::from_string(secret_key)\n .and_then(|b| b.into_secret_key(Some(password.to_owned())))\n .map_err(|e| Error::Signature(format!(\"the secret key is unusable: {e}\")))?;\n let pk = PublicKey::from_secret_key(&sk).ok();\n let file = std::fs::File::open(path)?;\n let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();\n let signature =\n minisign::sign(pk.as_ref(), &sk, file, Some(comment), Some(&format!(\"signature of {name}\"))).map_err(failed)?;\n Ok(signature.into_string())\n}\n\n/// One artifact of a release.\n#[derive(Clone, Debug)]\npub struct Release {\n pub platform: String,\n pub kind: Kind,\n pub path: PathBuf,\n /// Its URL in the manifest (default: its file name, relative to the manifest).\n pub url: Option<String>,\n}\n\n/// What a release is.\n#[derive(Clone, Debug)]\npub struct ReleaseInfo {\n pub app: String,\n pub channel: String,\n pub version: Version,\n pub notes: Option<String>,\n pub pub_date: Option<String>,\n}\n\n/// Signs each artifact and writes its entry (`<platform>-<kind>`) into the manifest: into `existing` when it is the\n/// same release (app, channel, version: CI runners each adding their platform), else a new one.\npub fn release(\n info: &ReleaseInfo,\n secret_key: &str,\n password: &str,\n artifacts: &[Release],\n existing: Option<Manifest>,\n) -> Result<Manifest, Error> {\n let mut manifest = match existing {\n Some(m)\n if m.app == info.app\n && m.channel == info.channel\n && Version::parse(&m.version).ok().as_ref() == Some(&info.version) =>\n {\n m\n }\n _ => Manifest {\n app: info.app.clone(),\n channel: info.channel.clone(),\n version: info.version.to_string(),\n notes: None,\n pub_date: None,\n platforms: Default::default(),\n },\n };\n if info.notes.is_some() {\n manifest.notes = info.notes.clone();\n }\n if info.pub_date.is_some() {\n manifest.pub_date = info.pub_date.clone();\n }\n for a in artifacts {\n let comment = trusted_comment(&info.app, &info.channel, &info.version, &a.platform, a.kind);\n let signature = sign_file(secret_key, password, &a.path, &comment)?;\n let size = std::fs::metadata(&a.path)?.len();\n let url = match &a.url {\n Some(u) => u.clone(),\n None => a\n .path\n .file_name()\n .map(|n| n.to_string_lossy().into_owned())\n .ok_or_else(|| Error::Io(format!(\"{} names no file\", a.path.display())))?,\n };\n manifest\n .platforms\n .insert(format!(\"{}-{}\", a.platform, a.kind), Artifact { url, kind: a.kind, size, signature });\n }\n Ok(manifest)\n}\n",
390
+ "type": "registry:file",
391
+ "target": "desktop-rune/crates/eloxiv-update/src/sign.rs"
392
+ },
393
+ {
394
+ "path": "app/desktop-rune/crates/eloxiv-update/tests/server.rs",
395
+ "content": "//! The updater against a local update server (plain HTTP on loopback): a good update, bad signatures, a downgrade,\n//! interrupted and overlong downloads. Every file a test makes is removed when it ends, passing or not.\n\nuse std::collections::HashMap;\nuse std::io::{Read, Write};\nuse std::net::TcpListener;\nuse std::path::{Path, PathBuf};\nuse std::sync::{Arc, Mutex};\n\nuse eloxiv_update::sign::{self, Release, ReleaseInfo};\nuse eloxiv_update::{Error, Kind, Source, Version, check, download};\n\n/// How the server answers a path.\n#[derive(Clone)]\nenum Answer {\n Full(Vec<u8>),\n /// Declares the whole length, sends `n` bytes, then closes the connection.\n Cut(Vec<u8>, usize),\n /// A 302 to this location.\n Redirect(String),\n}\n\n/// A tiny HTTP/1.1 server: one request per connection.\nstruct Server {\n url: String,\n routes: Arc<Mutex<HashMap<String, Answer>>>,\n}\n\nimpl Server {\n fn start() -> Server {\n let listener = TcpListener::bind(\"127.0.0.1:0\").expect(\"a port\");\n let url = format!(\"http://{}\", listener.local_addr().expect(\"as the test set it up\"));\n let routes: Arc<Mutex<HashMap<String, Answer>>> = Arc::default();\n let served = routes.clone();\n std::thread::spawn(move || {\n for stream in listener.incoming() {\n let Ok(mut stream) = stream else { continue };\n let mut head = Vec::new();\n let mut byte = [0u8; 1];\n while !head.ends_with(b\"\\r\\n\\r\\n\") && stream.read(&mut byte).map(|n| n == 1).unwrap_or(false) {\n head.push(byte[0]);\n }\n let line = String::from_utf8_lossy(&head).lines().next().unwrap_or_default().to_owned();\n let path = line.split_whitespace().nth(1).unwrap_or(\"/\").to_owned();\n let answer = served.lock().expect(\"the lock\").get(&path).cloned();\n let _ = match answer {\n Some(Answer::Full(body)) => stream\n .write_all(\n format!(\"HTTP/1.1 200 OK\\r\\nContent-Length: {}\\r\\nConnection: close\\r\\n\\r\\n\", body.len())\n .as_bytes(),\n )\n .and_then(|()| stream.write_all(&body)),\n Some(Answer::Cut(body, n)) => stream\n .write_all(\n format!(\"HTTP/1.1 200 OK\\r\\nContent-Length: {}\\r\\nConnection: close\\r\\n\\r\\n\", body.len())\n .as_bytes(),\n )\n .and_then(|()| stream.write_all(&body[..n])),\n Some(Answer::Redirect(location)) => stream.write_all(\n format!(\"HTTP/1.1 302 Found\\r\\nLocation: {location}\\r\\nContent-Length: 0\\r\\nConnection: close\\r\\n\\r\\n\")\n .as_bytes(),\n ),\n None => {\n stream.write_all(b\"HTTP/1.1 404 Not Found\\r\\nContent-Length: 0\\r\\nConnection: close\\r\\n\\r\\n\")\n }\n };\n }\n });\n Server { url, routes }\n }\n\n fn serve(&self, path: &str, answer: Answer) {\n self.routes.lock().expect(\"the lock\").insert(path.to_owned(), answer);\n }\n}\n\nstruct Dir(PathBuf);\n\nimpl Dir {\n fn new(name: &str) -> Dir {\n let n = std::time::SystemTime::now()\n .duration_since(std::time::UNIX_EPOCH)\n .expect(\"as the test set it up\")\n .as_nanos();\n let dir = std::env::temp_dir().join(format!(\"eloxiv-update-{name}-{}-{n}\", std::process::id()));\n std::fs::create_dir_all(&dir).expect(\"a test directory\");\n Dir(dir)\n }\n}\n\nimpl Drop for Dir {\n fn drop(&mut self) {\n let _ = std::fs::remove_dir_all(&self.0);\n }\n}\n\nconst APP: &str = \"com.example.app\";\nconst PLATFORM: &str = \"linux-x86_64\";\n\nfn source(server: &Server, public_key: &str) -> Source {\n Source {\n manifest_url: format!(\"{}/{{channel}}/{{platform}}.json\", server.url),\n public_key: public_key.into(),\n channel: \"stable\".into(),\n app: APP.into(),\n current: Version::new(1, 0, 0),\n kind: Kind::Appimage,\n platform: PLATFORM.into(),\n }\n}\n\n/// Signs `bytes` as `version` with `keys` and serves the release: the manifest and the artifact.\nfn publish(server: &Server, dir: &Path, keys: &sign::Keys, version: &str, bytes: &[u8]) -> eloxiv_update::Manifest {\n let file = dir.join(format!(\"App-{version}.AppImage\"));\n std::fs::write(&file, bytes).expect(\"a test file\");\n let info = ReleaseInfo {\n app: APP.into(),\n channel: \"stable\".into(),\n version: Version::parse(version).expect(\"a version\"),\n notes: Some(\"Better.\".into()),\n pub_date: None,\n };\n let release = Release { platform: PLATFORM.into(), kind: Kind::Appimage, path: file.clone(), url: None };\n let manifest = sign::release(&info, &keys.secret_file, \"\", &[release], None).expect(\"as the test set it up\");\n server.serve(\n &format!(\"/stable/{PLATFORM}.json\"),\n Answer::Full(serde_json::to_vec(&manifest).expect(\"as the test set it up\")),\n );\n server.serve(&format!(\"/stable/App-{version}.AppImage\"), Answer::Full(bytes.to_vec()));\n manifest\n}\n\nfn none(_: u64) {}\n\n#[test]\nfn a_good_update_is_offered_downloaded_and_verified() {\n let (server, dir) = (Server::start(), Dir::new(\"good\"));\n let keys = sign::keygen(\"\").expect(\"a key pair\");\n let bytes: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect();\n publish(&server, &dir.0, &keys, \"1.1.0\", &bytes);\n let source = source(&server, &keys.public_base64);\n let offer = check(&source).expect(\"as the test set it up\").expect(\"1.1.0 is offered\");\n assert_eq!(offer.version, Version::new(1, 1, 0));\n assert_eq!(offer.notes.as_deref(), Some(\"Better.\"));\n assert_eq!(offer.url, format!(\"{}/stable/App-1.1.0.AppImage\", server.url));\n let dest = dir.0.join(\"staged\");\n let mut seen = 0;\n download(&source, &offer, &dest, &mut |n| seen = n).expect(\"as the test set it up\");\n assert_eq!(std::fs::read(&dest).expect(\"as the test set it up\"), bytes);\n assert_eq!(seen, bytes.len() as u64);\n // The whole `.pub` file is a key too.\n let mut by_file = source.clone();\n by_file.public_key = keys.public_file.clone();\n download(&by_file, &offer, &dest, &mut none).expect(\"as the test set it up\");\n}\n\n#[test]\nfn bad_signatures_are_refused_and_leave_nothing() {\n let (server, dir) = (Server::start(), Dir::new(\"bad\"));\n let (keys, other) = (sign::keygen(\"\").expect(\"a key pair\"), sign::keygen(\"\").expect(\"a key pair\"));\n let bytes = b\"the real build\".repeat(1000);\n publish(&server, &dir.0, &keys, \"1.1.0\", &bytes);\n let dest = dir.0.join(\"staged\");\n\n // Another key than the app's.\n let wrong = source(&server, &other.public_base64);\n let offer = check(&wrong).expect(\"as the test set it up\").expect(\"offered\");\n assert!(matches!(download(&wrong, &offer, &dest, &mut none), Err(Error::Signature(_))));\n assert!(!dest.exists(), \"nothing staged\");\n\n // The app's key, but the bytes were changed on the host (same size).\n let good = source(&server, &keys.public_base64);\n let mut tampered = bytes.clone();\n tampered[10] ^= 1;\n server.serve(\"/stable/App-1.1.0.AppImage\", Answer::Full(tampered));\n assert!(matches!(download(&good, &offer, &dest, &mut none), Err(Error::Signature(_))));\n assert!(!dest.exists());\n\n // Unsigned, and a signature that does not decode.\n for signature in [\"\", \"untrusted comment: nothing\\nnot base64\\n\"] {\n let mut unsigned = offer.clone();\n unsigned.signature = signature.into();\n server.serve(\"/stable/App-1.1.0.AppImage\", Answer::Full(bytes.clone()));\n assert!(matches!(download(&good, &unsigned, &dest, &mut none), Err(Error::Signature(_))), \"{signature:?}\");\n assert!(!dest.exists());\n }\n\n // A validly signed older build replayed under a newer version: its trusted comment names 1.0.5.\n let old = publish(&server, &dir.0, &keys, \"1.0.5\", &bytes);\n let mut replay = old.clone();\n replay.version = \"9.0.0\".into();\n replay.platforms.values_mut().for_each(|a| a.url = \"App-1.0.5.AppImage\".into());\n server.serve(\n &format!(\"/stable/{PLATFORM}.json\"),\n Answer::Full(serde_json::to_vec(&replay).expect(\"as the test set it up\")),\n );\n let offer = check(&good).expect(\"as the test set it up\").expect(\"the forged manifest offers 9.0.0\");\n match download(&good, &offer, &dest, &mut none) {\n Err(Error::Signature(m)) => assert!(m.contains(\"version=1.0.5\"), \"{m}\"),\n other => panic!(\"a replayed signature must be refused: {other:?}\"),\n }\n assert!(!dest.exists());\n\n // A key that does not decode is the configuration's fault.\n let broken = source(&server, \"not a key\");\n publish(&server, &dir.0, &keys, \"1.1.0\", &bytes);\n let offer = check(&broken).expect(\"as the test set it up\").expect(\"offered\");\n assert!(matches!(download(&broken, &offer, &dest, &mut none), Err(Error::Config(_))));\n}\n\n#[test]\nfn never_a_downgrade() {\n let (server, dir) = (Server::start(), Dir::new(\"downgrade\"));\n let keys = sign::keygen(\"\").expect(\"a key pair\");\n let mut source = source(&server, &keys.public_base64);\n source.current = Version::new(1, 2, 0);\n for version in [\"1.2.0\", \"1.1.9\", \"0.1.0\"] {\n publish(&server, &dir.0, &keys, version, b\"old build\");\n assert_eq!(check(&source).expect(\"as the test set it up\"), None, \"{version} is not newer than 1.2.0\");\n }\n // An offer for an older build is refused at download too (it was made before the host moved on).\n publish(&server, &dir.0, &keys, \"1.3.0\", b\"new build\");\n let offer = check(&source).expect(\"as the test set it up\").expect(\"1.3.0\");\n source.current = Version::new(1, 3, 0);\n let dest = dir.0.join(\"staged\");\n assert!(matches!(download(&source, &offer, &dest, &mut none), Err(Error::Downgrade { .. })));\n assert!(!dest.exists());\n}\n\n#[test]\nfn an_interrupted_or_overlong_download_is_refused_and_leaves_nothing() {\n let (server, dir) = (Server::start(), Dir::new(\"cut\"));\n let keys = sign::keygen(\"\").expect(\"a key pair\");\n let bytes = vec![7u8; 300_000];\n publish(&server, &dir.0, &keys, \"1.1.0\", &bytes);\n let source = source(&server, &keys.public_base64);\n let offer = check(&source).expect(\"as the test set it up\").expect(\"offered\");\n let dest = dir.0.join(\"staged\");\n\n server.serve(\"/stable/App-1.1.0.AppImage\", Answer::Cut(bytes.clone(), 100_000));\n assert!(matches!(download(&source, &offer, &dest, &mut none), Err(Error::Interrupted(_) | Error::Network(_))));\n assert!(!dest.exists(), \"no partial file\");\n\n let mut longer = bytes.clone();\n longer.extend_from_slice(b\"and more\");\n server.serve(\"/stable/App-1.1.0.AppImage\", Answer::Full(longer));\n assert!(matches!(download(&source, &offer, &dest, &mut none), Err(Error::Interrupted(_))));\n assert!(!dest.exists());\n\n // The host is gone.\n server.serve(\"/stable/App-1.1.0.AppImage\", Answer::Full(bytes.clone()));\n let mut gone = offer.clone();\n gone.url = format!(\"{}/missing.AppImage\", server.url);\n assert!(matches!(download(&source, &gone, &dest, &mut none), Err(Error::Network(_))));\n assert!(!dest.exists());\n // And it works once the host serves it whole.\n download(&source, &offer, &dest, &mut none).expect(\"as the test set it up\");\n}\n\n#[test]\nfn an_unreachable_or_broken_manifest_is_an_error_not_an_update() {\n let server = Server::start();\n let keys = sign::keygen(\"\").expect(\"a key pair\");\n let source = source(&server, &keys.public_base64);\n assert!(matches!(check(&source), Err(Error::Network(_))), \"404\");\n server.serve(&format!(\"/stable/{PLATFORM}.json\"), Answer::Full(b\"{ not json\".to_vec()));\n assert!(matches!(check(&source), Err(Error::Manifest(_))));\n let mut http = source.clone();\n http.manifest_url = \"http://updates.example.com/m.json\".into();\n assert!(matches!(check(&http), Err(Error::Config(_))), \"plain HTTP off loopback\");\n}\n\n#[test]\nfn an_encrypted_key_signs_with_its_password_only() {\n let dir = Dir::new(\"password\");\n let keys = sign::keygen(\"correct horse\").expect(\"a key pair\");\n let file = dir.0.join(\"a.bin\");\n std::fs::write(&file, b\"x\").expect(\"a test file\");\n assert!(sign::sign_file(&keys.secret_file, \"wrong\", &file, \"c\").is_err());\n let sig = sign::sign_file(&keys.secret_file, \"correct horse\", &file, \"c\").expect(\"as the test set it up\");\n let key = eloxiv_update::public_key(&keys.public_base64).expect(\"as the test set it up\");\n eloxiv_update::verify_file(&key, &file, &sig, \"c\").expect(\"as the test set it up\");\n}\n\n#[test]\nfn a_build_signed_for_another_channel_is_refused_and_the_manifest_must_name_its_app_and_channel() {\n let (server, dir) = (Server::start(), Dir::new(\"channel\"));\n let keys = sign::keygen(\"\").expect(\"a key pair\");\n let bytes = b\"a beta build\".repeat(100);\n let file = dir.0.join(\"App-1.1.0.AppImage\");\n std::fs::write(&file, &bytes).expect(\"a test file\");\n // Signed for beta, served in a manifest that says stable (a mirror's doing).\n let info = ReleaseInfo {\n app: APP.into(),\n channel: \"beta\".into(),\n version: Version::new(1, 1, 0),\n notes: None,\n pub_date: None,\n };\n let release = Release { platform: PLATFORM.into(), kind: Kind::Appimage, path: file, url: None };\n let mut manifest = sign::release(&info, &keys.secret_file, \"\", &[release], None).expect(\"as the test set it up\");\n manifest.channel = \"stable\".into();\n server.serve(&format!(\"/stable/{PLATFORM}.json\"), Answer::Full(serde_json::to_vec(&manifest).expect(\"json\")));\n server.serve(\"/stable/App-1.1.0.AppImage\", Answer::Full(bytes));\n let source = source(&server, &keys.public_base64);\n let offer = check(&source).expect(\"as the test set it up\").expect(\"the manifest offers it\");\n let dest = dir.0.join(\"staged\");\n assert!(matches!(download(&source, &offer, &dest, &mut none), Err(Error::Signature(_))), \"another channel's build\");\n assert!(!dest.exists());\n // A manifest that does not name its app and channel does not decode.\n let mut bare = serde_json::to_value(&manifest).expect(\"json\");\n bare.as_object_mut().expect(\"an object\").remove(\"channel\");\n server.serve(&format!(\"/stable/{PLATFORM}.json\"), Answer::Full(serde_json::to_vec(&bare).expect(\"json\")));\n assert!(matches!(check(&source), Err(Error::Manifest(_))));\n}\n\n#[test]\nfn a_redirect_is_followed_only_to_an_allowed_url() {\n let (server, dir) = (Server::start(), Dir::new(\"redirect\"));\n let keys = sign::keygen(\"\").expect(\"a key pair\");\n let bytes = b\"the build\".repeat(100);\n publish(&server, &dir.0, &keys, \"1.1.0\", &bytes);\n let manifest = format!(\"/stable/{PLATFORM}.json\");\n let moved = \"/moved/manifest.json\";\n let body = match server.routes.lock().expect(\"the lock\").get(&manifest).cloned() {\n Some(Answer::Full(body)) => body,\n _ => panic!(\"published\"),\n };\n server.serve(moved, Answer::Full(body));\n // To the same loopback host: followed.\n server.serve(&manifest, Answer::Redirect(format!(\"{}{moved}\", server.url)));\n let mut source = source(&server, &keys.public_base64);\n source.manifest_url = format!(\"{}/{{channel}}/{{platform}}.json\", server.url);\n assert!(check(&source).expect(\"followed\").is_some());\n // To plain HTTP elsewhere: refused, never fetched.\n server.serve(&manifest, Answer::Redirect(\"http://updates.example.com/stable.json\".into()));\n match check(&source) {\n Err(Error::Network(why)) => assert!(why.contains(\"not HTTPS\"), \"{why}\"),\n other => panic!(\"{other:?}\"),\n }\n}\n",
396
+ "type": "registry:file",
397
+ "target": "desktop-rune/crates/eloxiv-update/tests/server.rs"
398
+ }
399
+ ],
400
+ "meta": {
401
+ "eloxiv": {
402
+ "kind": "desktop",
403
+ "version": "0.6.10",
404
+ "next": [
405
+ "Build the app's daemon sidecar (desktop-rune/sidecar/daemon.ts, composed with the app's clientApp): node desktop-rune/scripts/build-sidecar.ts (in development the host also runs it from source with Bun)",
406
+ "Build and run from desktop-rune/: cargo run --release (Linux needs libxkbcommon-dev and libwayland-dev); cargo test runs its headless tests",
407
+ "The web shell approves its sign-in at /desktop/sign-in: set ELOXIV_SHELL_URL for the sidecar when the shell is not at http://localhost:5173",
408
+ "Set the app's identity and host settings in desktop-rune/app.json: name, identifier, binaryName, version, urlScheme, its icon (app-icon.svg), servers (kernelUrl, zeroUrl, shellUrl: what the packaged app reaches) and, for signed updates, updates.url and updates.publicKey (cargo run -p eloxiv-update -- keygen --out <dir>)",
409
+ "Make installers: node desktop-rune/scripts/package.ts (needs cargo install cargo-packager --version 0.11.8 --locked); signed only when APPLE_SIGNING_IDENTITY or WINDOWS_CERTIFICATE_THUMBPRINT / WINDOWS_SIGN_COMMAND are set",
410
+ "Sign a release and its update manifest: cargo run -p eloxiv-update -- release --config app.json --artifact <platform>:<kind>:<file> --out <manifest> (from desktop-rune/, with ELOXIV_UPDATE_SECRET_KEY)"
411
+ ]
412
+ }
413
+ },
414
+ "type": "registry:item"
415
+ }