From cbbec858fc3a54cc3c4852ebc8a2b48ae5c5b544 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Mon, 16 Nov 2026 18:01:09 +0000 Subject: [PATCH 01/10] feat: add the desktop interface and session tree (Phase E) Version 0.29.0 adds a prototype Tauri desktop shell with a session tree, full-text search, chat, and an isolated approvals window. The trusted CLI is unchanged in behaviour. See ADR-0044, ADR-0045, and ADR-0046. - core: inspect a journal without the writer lock, discover journals within bounds, and index them in a rebuildable SQLite FTS5 store - core: review an approval by reproducing its digest with the tool dispatcher's own request builder, and render display-safe fields - omgcode-app: move the chat turn out of the CLI binary into a shared library and add the desktop service layer; no CLI test file changed - omgcode-desktop: an 18-command Tauri 2 shell. Only the approvals window can decide an approval, enforced by capability files and by a Rust check that every handler runs first - frontend: strict TypeScript that renders text nodes only, with Vite, Vitest, and Biome - ci: build the frontend before Cargo and add a Frontend workflow - docs: a desktop interface guide, three ADRs, and corrected guides Verified on Windows 11 and on Linux under WSL 6.6: formatting, Clippy, all-target tests, and doc tests pass on both. The real shell was driven end to end on Windows only. No window has been opened on Linux, and the workflow changes have not run on GitHub. Co-Authored-By: Claude Fable 5.2 --- .gitattributes | 4 + .github/workflows/frontend.yml | 46 + .github/workflows/rust.yml | 21 +- .gitignore | 4 + AGENTS.md | 16 +- CHANGELOG.md | 80 + Cargo.lock | 4404 ++++++++++++++--- Cargo.toml | 6 +- IMPLEMENTATION_PLAN.md | 165 +- README.md | 52 +- crates/omgcode-app/Cargo.toml | 23 + crates/omgcode-app/src/chat.rs | 237 + crates/omgcode-app/src/chat/output.rs | 185 + crates/omgcode-app/src/chat/preflight.rs | 140 + crates/omgcode-app/src/chat/text.rs | 101 + crates/omgcode-app/src/chat/tools.rs | 267 + crates/omgcode-app/src/context.rs | 210 + crates/omgcode-app/src/desktop.rs | 196 + crates/omgcode-app/src/desktop/approvals.rs | 316 ++ crates/omgcode-app/src/desktop/chat.rs | 243 + crates/omgcode-app/src/desktop/error.rs | 237 + .../omgcode-app/src/desktop/review_tokens.rs | 276 ++ crates/omgcode-app/src/desktop/sessions.rs | 450 ++ crates/omgcode-app/src/desktop/state.rs | 361 ++ crates/omgcode-app/src/desktop/turns.rs | 428 ++ crates/omgcode-app/src/desktop/wire.rs | 663 +++ crates/omgcode-app/src/desktop/workspaces.rs | 95 + crates/omgcode-app/src/error.rs | 148 + crates/omgcode-app/src/lib.rs | 35 + crates/omgcode-app/src/paths.rs | 55 + crates/omgcode-app/src/secrets.rs | 69 + crates/omgcode-app/src/sessions.rs | 45 + crates/omgcode-app/src/tool_mode.rs | 142 + crates/omgcode-app/tests/chat_turn.rs | 579 +++ crates/omgcode-app/tests/common/mod.rs | 491 ++ crates/omgcode-app/tests/desktop_approvals.rs | 580 +++ crates/omgcode-app/tests/desktop_chat.rs | 540 ++ crates/omgcode-app/tests/desktop_sessions.rs | 715 +++ crates/omgcode-app/tests/desktop_wire.rs | 945 ++++ crates/omgcode-cli/Cargo.toml | 2 +- crates/omgcode-cli/src/context_cli.rs | 76 - crates/omgcode-cli/src/main.rs | 494 +- crates/omgcode-cli/src/model_tools.rs | 339 -- crates/omgcode-core/Cargo.toml | 1 + crates/omgcode-core/src/control.rs | 37 +- crates/omgcode-core/src/lib.rs | 1 + crates/omgcode-core/src/session.rs | 163 +- crates/omgcode-core/src/session/discovery.rs | 313 ++ crates/omgcode-core/src/session/filename.rs | 122 + crates/omgcode-core/src/session/inspection.rs | 244 + crates/omgcode-core/src/session_index.rs | 220 + .../omgcode-core/src/session_index/query.rs | 486 ++ .../omgcode-core/src/session_index/refresh.rs | 691 +++ .../omgcode-core/src/session_index/schema.rs | 285 ++ .../omgcode-core/src/session_index/snippet.rs | 152 + crates/omgcode-core/src/storage.rs | 22 + crates/omgcode-core/src/turn.rs | 184 +- crates/omgcode-core/src/turn/review.rs | 724 +++ crates/omgcode-core/tests/approval_review.rs | 805 +++ crates/omgcode-core/tests/session_index.rs | 1388 ++++++ .../omgcode-core/tests/session_inspection.rs | 678 +++ .../omgcode-core/tests/workspace_listing.rs | 93 + crates/omgcode-desktop/.gitignore | 3 + crates/omgcode-desktop/Cargo.toml | 43 + crates/omgcode-desktop/build.rs | 17 + .../capabilities/approvals.json | 14 + crates/omgcode-desktop/capabilities/main.json | 26 + crates/omgcode-desktop/icons/128x128.png | Bin 0 -> 7136 bytes crates/omgcode-desktop/icons/128x128@2x.png | Bin 0 -> 15630 bytes crates/omgcode-desktop/icons/32x32.png | Bin 0 -> 1481 bytes crates/omgcode-desktop/icons/icon.ico | Bin 0 -> 29130 bytes crates/omgcode-desktop/icons/icon.png | Bin 0 -> 32080 bytes crates/omgcode-desktop/src/command_names.rs | 25 + crates/omgcode-desktop/src/commands.rs | 157 + .../omgcode-desktop/src/commands/approvals.rs | 83 + crates/omgcode-desktop/src/commands/chat.rs | 79 + .../omgcode-desktop/src/commands/sessions.rs | 158 + crates/omgcode-desktop/src/error.rs | 102 + crates/omgcode-desktop/src/launch.rs | 187 + crates/omgcode-desktop/src/lib.rs | 125 + crates/omgcode-desktop/src/main.rs | 8 + crates/omgcode-desktop/src/policy.rs | 225 + crates/omgcode-desktop/src/shutdown.rs | 116 + crates/omgcode-desktop/src/windows.rs | 207 + crates/omgcode-desktop/tauri.conf.json | 30 + crates/omgcode-desktop/tests/layers.rs | 669 +++ crates/omgcode-desktop/ui/.npmrc | 2 + crates/omgcode-desktop/ui/README.md | 72 + crates/omgcode-desktop/ui/approvals.html | 14 + crates/omgcode-desktop/ui/biome.json | 14 + crates/omgcode-desktop/ui/index.html | 14 + crates/omgcode-desktop/ui/package-lock.json | 2399 +++++++++ crates/omgcode-desktop/ui/package.json | 29 + crates/omgcode-desktop/ui/src/approvals.ts | 12 + .../omgcode-desktop/ui/src/approvals/app.ts | 263 + .../omgcode-desktop/ui/src/approvals/model.ts | 107 + .../ui/src/approvals/review.ts | 177 + crates/omgcode-desktop/ui/src/dom.ts | 84 + crates/omgcode-desktop/ui/src/format.ts | 53 + .../ui/src/ipc/approvals_client.ts | 20 + crates/omgcode-desktop/ui/src/ipc/client.ts | 91 + crates/omgcode-desktop/ui/src/ipc/errors.ts | 34 + crates/omgcode-desktop/ui/src/ipc/types.ts | 194 + crates/omgcode-desktop/ui/src/main.ts | 12 + crates/omgcode-desktop/ui/src/main/app.ts | 88 + .../ui/src/main/chat_runner.ts | 86 + .../omgcode-desktop/ui/src/main/composer.ts | 205 + .../ui/src/main/conversation.ts | 419 ++ crates/omgcode-desktop/ui/src/main/model.ts | 125 + .../ui/src/main/new_session.ts | 152 + crates/omgcode-desktop/ui/src/main/sidebar.ts | 236 + .../omgcode-desktop/ui/src/main/transcript.ts | 98 + crates/omgcode-desktop/ui/src/main/tree.ts | 215 + crates/omgcode-desktop/ui/src/mock/backend.ts | 484 ++ .../omgcode-desktop/ui/src/mock/fixtures.ts | 260 + crates/omgcode-desktop/ui/src/poll.ts | 63 + .../ui/src/styles/approvals.css | 141 + crates/omgcode-desktop/ui/src/styles/main.css | 499 ++ .../omgcode-desktop/ui/src/styles/tokens.css | 192 + .../ui/tests/approvals.test.ts | 412 ++ crates/omgcode-desktop/ui/tests/dist.test.ts | 76 + crates/omgcode-desktop/ui/tests/helpers.ts | 156 + .../ui/tests/main_window.test.ts | 674 +++ crates/omgcode-desktop/ui/tests/mock.test.ts | 95 + crates/omgcode-desktop/ui/tests/model.test.ts | 124 + crates/omgcode-desktop/ui/tests/poll.test.ts | 80 + .../omgcode-desktop/ui/tests/security.test.ts | 108 + .../ui/tests/transcript.test.ts | 110 + crates/omgcode-desktop/ui/tsconfig.json | 22 + crates/omgcode-desktop/ui/vite.config.ts | 22 + docs/README.md | 19 +- ...he-writer-lock-and-index-them-in-sqlite.md | 132 + ...-on-tauri-with-a-narrow-command-surface.md | 144 + ...approvals-in-an-isolated-desktop-window.md | 133 + docs/adr/index.md | 3 + docs/agent-instructions.md | 15 +- docs/coding-rules.md | 21 +- docs/context-management.md | 6 +- docs/desktop-interface.md | 561 +++ docs/development.md | 76 +- docs/execution.md | 10 +- docs/file-access.md | 7 +- docs/platform-support.md | 19 +- docs/provider-authentication.md | 6 +- docs/repository-checks.md | 37 +- docs/security-coding-rules.md | 38 +- docs/session-storage.md | 138 +- docs/testing-standards.md | 95 +- docs/workspace-permissions.md | 7 +- 149 files changed, 31945 insertions(+), 1619 deletions(-) create mode 100644 .github/workflows/frontend.yml create mode 100644 crates/omgcode-app/Cargo.toml create mode 100644 crates/omgcode-app/src/chat.rs create mode 100644 crates/omgcode-app/src/chat/output.rs create mode 100644 crates/omgcode-app/src/chat/preflight.rs create mode 100644 crates/omgcode-app/src/chat/text.rs create mode 100644 crates/omgcode-app/src/chat/tools.rs create mode 100644 crates/omgcode-app/src/context.rs create mode 100644 crates/omgcode-app/src/desktop.rs create mode 100644 crates/omgcode-app/src/desktop/approvals.rs create mode 100644 crates/omgcode-app/src/desktop/chat.rs create mode 100644 crates/omgcode-app/src/desktop/error.rs create mode 100644 crates/omgcode-app/src/desktop/review_tokens.rs create mode 100644 crates/omgcode-app/src/desktop/sessions.rs create mode 100644 crates/omgcode-app/src/desktop/state.rs create mode 100644 crates/omgcode-app/src/desktop/turns.rs create mode 100644 crates/omgcode-app/src/desktop/wire.rs create mode 100644 crates/omgcode-app/src/desktop/workspaces.rs create mode 100644 crates/omgcode-app/src/error.rs create mode 100644 crates/omgcode-app/src/lib.rs create mode 100644 crates/omgcode-app/src/paths.rs create mode 100644 crates/omgcode-app/src/secrets.rs create mode 100644 crates/omgcode-app/src/sessions.rs create mode 100644 crates/omgcode-app/src/tool_mode.rs create mode 100644 crates/omgcode-app/tests/chat_turn.rs create mode 100644 crates/omgcode-app/tests/common/mod.rs create mode 100644 crates/omgcode-app/tests/desktop_approvals.rs create mode 100644 crates/omgcode-app/tests/desktop_chat.rs create mode 100644 crates/omgcode-app/tests/desktop_sessions.rs create mode 100644 crates/omgcode-app/tests/desktop_wire.rs delete mode 100644 crates/omgcode-cli/src/context_cli.rs delete mode 100644 crates/omgcode-cli/src/model_tools.rs create mode 100644 crates/omgcode-core/src/session/discovery.rs create mode 100644 crates/omgcode-core/src/session/filename.rs create mode 100644 crates/omgcode-core/src/session/inspection.rs create mode 100644 crates/omgcode-core/src/session_index.rs create mode 100644 crates/omgcode-core/src/session_index/query.rs create mode 100644 crates/omgcode-core/src/session_index/refresh.rs create mode 100644 crates/omgcode-core/src/session_index/schema.rs create mode 100644 crates/omgcode-core/src/session_index/snippet.rs create mode 100644 crates/omgcode-core/src/turn/review.rs create mode 100644 crates/omgcode-core/tests/approval_review.rs create mode 100644 crates/omgcode-core/tests/session_index.rs create mode 100644 crates/omgcode-core/tests/session_inspection.rs create mode 100644 crates/omgcode-core/tests/workspace_listing.rs create mode 100644 crates/omgcode-desktop/.gitignore create mode 100644 crates/omgcode-desktop/Cargo.toml create mode 100644 crates/omgcode-desktop/build.rs create mode 100644 crates/omgcode-desktop/capabilities/approvals.json create mode 100644 crates/omgcode-desktop/capabilities/main.json create mode 100644 crates/omgcode-desktop/icons/128x128.png create mode 100644 crates/omgcode-desktop/icons/128x128@2x.png create mode 100644 crates/omgcode-desktop/icons/32x32.png create mode 100644 crates/omgcode-desktop/icons/icon.ico create mode 100644 crates/omgcode-desktop/icons/icon.png create mode 100644 crates/omgcode-desktop/src/command_names.rs create mode 100644 crates/omgcode-desktop/src/commands.rs create mode 100644 crates/omgcode-desktop/src/commands/approvals.rs create mode 100644 crates/omgcode-desktop/src/commands/chat.rs create mode 100644 crates/omgcode-desktop/src/commands/sessions.rs create mode 100644 crates/omgcode-desktop/src/error.rs create mode 100644 crates/omgcode-desktop/src/launch.rs create mode 100644 crates/omgcode-desktop/src/lib.rs create mode 100644 crates/omgcode-desktop/src/main.rs create mode 100644 crates/omgcode-desktop/src/policy.rs create mode 100644 crates/omgcode-desktop/src/shutdown.rs create mode 100644 crates/omgcode-desktop/src/windows.rs create mode 100644 crates/omgcode-desktop/tauri.conf.json create mode 100644 crates/omgcode-desktop/tests/layers.rs create mode 100644 crates/omgcode-desktop/ui/.npmrc create mode 100644 crates/omgcode-desktop/ui/README.md create mode 100644 crates/omgcode-desktop/ui/approvals.html create mode 100644 crates/omgcode-desktop/ui/biome.json create mode 100644 crates/omgcode-desktop/ui/index.html create mode 100644 crates/omgcode-desktop/ui/package-lock.json create mode 100644 crates/omgcode-desktop/ui/package.json create mode 100644 crates/omgcode-desktop/ui/src/approvals.ts create mode 100644 crates/omgcode-desktop/ui/src/approvals/app.ts create mode 100644 crates/omgcode-desktop/ui/src/approvals/model.ts create mode 100644 crates/omgcode-desktop/ui/src/approvals/review.ts create mode 100644 crates/omgcode-desktop/ui/src/dom.ts create mode 100644 crates/omgcode-desktop/ui/src/format.ts create mode 100644 crates/omgcode-desktop/ui/src/ipc/approvals_client.ts create mode 100644 crates/omgcode-desktop/ui/src/ipc/client.ts create mode 100644 crates/omgcode-desktop/ui/src/ipc/errors.ts create mode 100644 crates/omgcode-desktop/ui/src/ipc/types.ts create mode 100644 crates/omgcode-desktop/ui/src/main.ts create mode 100644 crates/omgcode-desktop/ui/src/main/app.ts create mode 100644 crates/omgcode-desktop/ui/src/main/chat_runner.ts create mode 100644 crates/omgcode-desktop/ui/src/main/composer.ts create mode 100644 crates/omgcode-desktop/ui/src/main/conversation.ts create mode 100644 crates/omgcode-desktop/ui/src/main/model.ts create mode 100644 crates/omgcode-desktop/ui/src/main/new_session.ts create mode 100644 crates/omgcode-desktop/ui/src/main/sidebar.ts create mode 100644 crates/omgcode-desktop/ui/src/main/transcript.ts create mode 100644 crates/omgcode-desktop/ui/src/main/tree.ts create mode 100644 crates/omgcode-desktop/ui/src/mock/backend.ts create mode 100644 crates/omgcode-desktop/ui/src/mock/fixtures.ts create mode 100644 crates/omgcode-desktop/ui/src/poll.ts create mode 100644 crates/omgcode-desktop/ui/src/styles/approvals.css create mode 100644 crates/omgcode-desktop/ui/src/styles/main.css create mode 100644 crates/omgcode-desktop/ui/src/styles/tokens.css create mode 100644 crates/omgcode-desktop/ui/tests/approvals.test.ts create mode 100644 crates/omgcode-desktop/ui/tests/dist.test.ts create mode 100644 crates/omgcode-desktop/ui/tests/helpers.ts create mode 100644 crates/omgcode-desktop/ui/tests/main_window.test.ts create mode 100644 crates/omgcode-desktop/ui/tests/mock.test.ts create mode 100644 crates/omgcode-desktop/ui/tests/model.test.ts create mode 100644 crates/omgcode-desktop/ui/tests/poll.test.ts create mode 100644 crates/omgcode-desktop/ui/tests/security.test.ts create mode 100644 crates/omgcode-desktop/ui/tests/transcript.test.ts create mode 100644 crates/omgcode-desktop/ui/tsconfig.json create mode 100644 crates/omgcode-desktop/ui/vite.config.ts create mode 100644 docs/adr/0044-observe-journals-without-the-writer-lock-and-index-them-in-sqlite.md create mode 100644 docs/adr/0045-build-the-desktop-shell-on-tauri-with-a-narrow-command-surface.md create mode 100644 docs/adr/0046-decide-model-tool-approvals-in-an-isolated-desktop-window.md create mode 100644 docs/desktop-interface.md diff --git a/.gitattributes b/.gitattributes index 6df6a37..cc78a1f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,3 +2,7 @@ prompts/system.md text eol=lf # Keep bundled skill source digests stable across Windows and Linux checkouts. skills/**/SKILL.md text eol=lf + +# Check the desktop frontend out with LF on every platform. Biome's formatter +# check expects LF, and a CRLF checkout on Windows would fail it. +crates/omgcode-desktop/ui/** text=auto eol=lf diff --git a/.github/workflows/frontend.yml b/.github/workflows/frontend.yml new file mode 100644 index 0000000..d3f26cf --- /dev/null +++ b/.github/workflows/frontend.yml @@ -0,0 +1,46 @@ +name: Frontend + +on: + pull_request: + branches: [main] + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: frontend-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + check: + name: Desktop frontend (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + os: [ubuntu-24.04, windows-2025] + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + defaults: + run: + working-directory: crates/omgcode-desktop/ui + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + - name: Install the locked dependencies + # .npmrc sets ignore-scripts, so no package install script runs. + run: npm ci + - name: Check types + run: npm run check + - name: Check formatting and lints + run: npm run lint + - name: Run tests + run: npm test + - name: Build and check the bundles + run: npm run test:dist diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 3b8c694..5ca5d93 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -22,7 +22,7 @@ jobs: matrix: os: [ubuntu-24.04, windows-2025] runs-on: ${{ matrix.os }} - timeout-minutes: 20 + timeout-minutes: 40 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -31,6 +31,25 @@ jobs: run: rustup toolchain install 1.99.1 --profile minimal --component rustfmt --component clippy - name: Check formatting run: cargo fmt --all -- --check + - name: Install the desktop shell's Linux build packages + if: runner.os == 'Linux' + run: | + # The Tauri prerequisites for Debian and Ubuntu. They are needed to + # compile the desktop crate; no test here starts a webview. + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + libwebkit2gtk-4.1-dev build-essential curl wget file libxdo-dev \ + libssl-dev libayatana-appindicator3-dev librsvg2-dev + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + - name: Build the desktop frontend + # The desktop crate embeds ui/dist at compile time, so the frontend + # must be built before any workspace-wide Cargo step. + working-directory: crates/omgcode-desktop/ui + run: | + npm ci + npm run build - name: Check lints and compilation run: cargo clippy --workspace --all-targets --locked -- -D warnings - name: Start a user service manager for delegated cgroups diff --git a/.gitignore b/.gitignore index 56de40e..36123c2 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,7 @@ rustc-ice-*.txt # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. #.idea/ + +# Desktop UI (Node) +node_modules/ +dist/ diff --git a/AGENTS.md b/AGENTS.md index 917a6cd..e676a7e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,7 +7,11 @@ repository contains a pinned Rust workspace with configuration-only workspace preferences, a bounded native file broker exposed through trusted CLI commands, and native identity checks. Follow [workspace settings](docs/workspace-permissions.md) and [workspace file access](docs/file-access.md) for their contracts. Enabled -preferences never authorize execution. The prototype is not a desktop app. +preferences never authorize execution. A prototype Tauri desktop shell adds a +session tree, full-text search, chat, and an isolated approvals window. It is +unpackaged, has run only on Windows, and gives the webview no authority: the +Rust side authorizes every command and the trusted CLI remains. Follow the +[desktop interface](docs/desktop-interface.md) contract. Chat offers the local LM Studio model read and list tools; when the workspace also enables `read` and `write`, one exact-edit tool; and, when it also enables `execute`, `read`, and `write`, one command tool. The edit and command tools @@ -35,14 +39,20 @@ commands can store API keys in protected OS storage (DPAPI on Windows, the Secret Service on Linux) and bind them to `api_key` profiles; no adapter reads them yet. Trusted single-use approval records authorize one exact model-tool call: only a later -identical call may consume an approved record. `workspace_run_command` then +identical call may consume an approved record. The trusted CLI or the desktop +approvals window can decide a record; the window shows a request only when core +reproduces its digest, and approval needs a single-use review token. +`workspace_run_command` then invokes the trusted runner, and `workspace_edit_file` then calls the checkpointed apply with the size and digest of a live trusted read ([ADR-0043](docs/adr/0043-gate-the-model-file-edit-tool-with-approvals-and-checkpointed-apply.md)). Neither route detects a concurrent writer. Trusted CLI commands record, apply, and revoke Windows container ACL grants. Follow the [execution contract](docs/execution.md). -The bundled web interface and most planned features are not implemented. +Sessions are indexed in a derived SQLite index that the journals can rebuild. +The desktop shell has no settings interface, streaming, development panels, +packaging, or recovery interface. Most other planned features are not +implemented. The core validates replacement records and can prepare protected checkpoints on Linux and Windows through a live authorized binding. The CLI provides existing-only checkpoint inspection and acknowledgement. Trusted CLI apply can diff --git a/CHANGELOG.md b/CHANGELOG.md index 1acaf9d..4eb7e55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,86 @@ Changes are recorded here before a release version is assigned. ### Added +- Version 0.29.0 adds the desktop interface and session tree (Phase E). See + ADR-0044, ADR-0045, and ADR-0046, and the + [desktop interface guide](docs/desktop-interface.md). It is a prototype on + branch `codex/desktop-interface`; it has no installer and has run only on + Windows. No CLI command changed behaviour: every existing CLI test suite + passes unmodified, and `model_tools.rs` and `context_cli.rs` moved from + `omgcode-cli` into the new `omgcode-app` crate. + - **Journal inspection:** `SessionInspection::inspect` reads one journal + without any lock call, without following links, and with the writer's + validator, so a viewer never makes a writer report `Busy`. On Windows a + lock or sharing violation becomes `Busy` with no retry. Bytes after the last + line feed are ignored and reported as `incomplete_tail`; the file is never + changed, and `SessionJournal::open` still rejects such a file. The result + adds `created_at`, `updated_at`, and an ordered list of transcript entries; + a request manifest entry carries the model, prompt version, and tool names + only. `MessageSource` is now public. + - **Discovery:** `session::discover` and `session::locate` walk only the dated + `sessions` layout with a strict file-name parser, never open a journal or + follow a link or reparse point, and stop with `LimitReached` after 50,000 + journals or 500,000 directory entries. + - **Session index:** `session_index::SessionIndex` keeps a derived SQLite + index with FTS5 in `/session-index-v1/index.sqlite3`. It is a + cache that is deleted and rebuilt when it is foreign or corrupt at open. + Refresh is incremental and bounded to 1,000 journals per call; a busy + journal keeps its last metadata, and an invalid journal is listed with a + code. Search quotes every term and binds the expression as a parameter; it + refuses more than 16 terms or 256 characters. Titles and the user, + assistant, tool, and summary text are indexed; tool arguments, manifests, + and instructions are not. New dependency: `rusqlite` 0.43.0 with the + bundled SQLite 3.54.1 (MIT), which compiles C source at build time, so a C + compiler is required. The lockfile gains `rusqlite`, `libsqlite3-sys`, + `fallible-iterator`, and `fallible-streaming-iterator`. + - **Application library:** `omgcode-app` holds the chat turn, compaction, + session creation, the data-root resolver, token redaction, and + `DesktopService`. The CLI and the desktop shell both call it. It grants no + authority. Chat gains a cooperative cancellation hook; the CLI does not use + it, and it cannot interrupt a provider request in flight. + - **Approval review:** core adds `review_approval` and display-safe text. It + recomputes an approval's digest from the recorded tool request with the + tool handler's own function and returns `exact`, `stale`, or `not_found`. + It decides, consumes, and applies nothing. `ControlStore` gains + `workspaces()`, `directory_path()`, and `directory_display()`. + - **Desktop shell:** the new `omgcode-desktop` crate is a Tauri 2 shell with + two windows, 18 commands, a capability file per window and no `core:` + permission, a Rust window check as the first statement of every handler, a + content security policy, a navigation guard, and a five second bounded + shutdown. It takes `--data-dir` and `--endpoint` and reads no other + configuration. The webview receives no host path, journal path, or token. + Chat tools follow the workspace settings as in the CLI. New dependencies: + `tauri` 2.12.6 (`wry` and `x11` features only) and `tauri-build` 2.7.5, + Apache-2.0 OR MIT, with no plugin, tray, updater, asset protocol, or + devtools feature. The lockfile grows by about 283 entries. A Linux build + needs the WebKitGTK development packages. + - **Approvals window:** a separate `approvals` window holds the only decision + controls. Approving needs an `exact` review binding and a single-use review + token that lives 120 seconds; a file edit also needs the writers-stopped + checkbox. The CLI `approvals` commands are unchanged. The window is still + web content and is not a trusted computing base. + - **Frontend:** `crates/omgcode-desktop/ui` is strict TypeScript with Vite, + Vitest (jsdom), and Biome, with one runtime dependency, `@tauri-apps/api` + 2.12.5. Versions are exact, the lockfile is committed, and `.npmrc` sets + `ignore-scripts=true`. The interface builds its document from text nodes + only; tests scan for markup injection, inline script, remote resources, and + browser storage. It polls for chat status and approvals; there is no push + channel. + - **Continuous integration:** the Rust workflow installs the Tauri Linux + packages, sets up Node 24, builds the frontend before Clippy, and has a 40 + minute timeout (was 20). A new Frontend workflow runs the type check, Biome, + Vitest, and the bundle checks on Ubuntu 24.04 and Windows Server 2025. + `.gitattributes` checks the frontend out with LF. The root `.gitignore` + gains `node_modules/` and `dist/`. + - **Limits:** on Linux the shell builds and the workspace tests pass (WSL + 6.6, Ubuntu 24.04), but no window has been opened there, so its webview, + IPC, and capability enforcement are unverified on Linux. The workflow + changes have not run on GitHub, and CodeQL's JavaScript/TypeScript + selection is unverified. Two link tests are skipped on a host without + symlink privilege; they ran on Linux. The shell has no packaging, streaming, settings + interface, development panels, or recovery interface. Corruption inside an + index table behind a valid header is not rebuilt automatically, and two + versions sharing a data root rebuild each other's index. - Version 0.28.0 adds the approval-gated model edit tool (Phase C17). See ADR-0043. - **Tool:** `workspace_edit_file { path, old_text, new_text }` replaces diff --git a/Cargo.lock b/Cargo.lock index 1008554..e3f5e35 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aes" version = "0.9.4" @@ -10,7 +16,25 @@ checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" dependencies = [ "cipher", "cpubits", - "cpufeatures", + "cpufeatures 0.3.1", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", ] [[package]] @@ -49,7 +73,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -60,9 +84,15 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys", + "windows-sys 0.61.2", ] +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + [[package]] name = "async-broadcast" version = "0.7.2" @@ -97,6 +127,29 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "atk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b" +dependencies = [ + "atk-sys", + "glib", + "libc", +] + +[[package]] +name = "atk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + [[package]] name = "atomic-waker" version = "1.1.2" @@ -109,17 +162,71 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + [[package]] name = "base64" version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec 0.8.0", +] + +[[package]] +name = "bit-set" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec 0.10.2", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bit-vec" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] [[package]] name = "block-buffer" @@ -139,17 +246,118 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2", +] + +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + [[package]] name = "bumpalo" version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "bytes" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +dependencies = [ + "serde", +] + +[[package]] +name = "cairo-rs" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2" +dependencies = [ + "bitflags 2.13.2", + "cairo-sys-rs", + "glib", + "libc", + "once_cell", + "thiserror 1.0.69", +] + +[[package]] +name = "cairo-sys-rs" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "camino" +version = "1.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591" +dependencies = [ + "serde_core", +] + +[[package]] +name = "cargo-platform" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea" +dependencies = [ + "serde", +] + +[[package]] +name = "cargo_metadata" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba" +dependencies = [ + "camino", + "cargo-platform", + "semver", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "cargo_toml" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9" +dependencies = [ + "semver", + "serde", + "toml 1.2.1+spec-1.1.0", +] [[package]] name = "cbc" @@ -170,19 +378,58 @@ dependencies = [ "shlex", ] +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cfb" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a347dcabdae9c31b0825fd6a8bed285ec9c2acb89c47827126d52fa4f59cece3" +dependencies = [ + "fnv", + "uuid", + "web-time", +] + +[[package]] +name = "cfg-expr" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" +dependencies = [ + "smallvec", + "target-lexicon", +] + [[package]] name = "cfg-if" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "serde", + "windows-link", +] + [[package]] name = "cipher" version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ - "crypto-common", + "crypto-common 0.2.2", "inout", ] @@ -214,7 +461,7 @@ version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" dependencies = [ - "heck", + "heck 0.5.0", "proc-macro2", "quote", "syn 3.0.9", @@ -238,12 +485,32 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + [[package]] name = "const-oid" version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +[[package]] +name = "cookie" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +dependencies = [ + "time", + "version_check", +] + [[package]] name = "core-foundation" version = "0.10.1" @@ -260,12 +527,45 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "core-graphics" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" +dependencies = [ + "bitflags 2.13.2", + "core-foundation", + "core-graphics-types", + "foreign-types 0.5.0", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" +dependencies = [ + "bitflags 2.13.2", + "core-foundation", + "libc", +] + [[package]] name = "cpubits" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + [[package]] name = "cpufeatures" version = "0.3.1" @@ -276,109 +576,394 @@ dependencies = [ ] [[package]] -name = "crypto-common" -version = "0.2.2" +name = "crc32fast" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" dependencies = [ - "hybrid-array", + "cfg-if", ] [[package]] -name = "ctutils" -version = "0.4.8" +name = "crossbeam-channel" +version = "0.5.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" dependencies = [ - "cmov", + "crossbeam-utils", ] [[package]] -name = "deranged" -version = "0.5.9" +name = "crossbeam-utils" +version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ - "serde_core", + "generic-array", + "typenum", ] [[package]] -name = "digest" -version = "0.11.3" +name = "crypto-common" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ - "block-buffer", - "const-oid", - "crypto-common", - "ctutils", + "hybrid-array", ] [[package]] -name = "directories" -version = "6.0.0" +name = "cssparser" +version = "0.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16f5094c54661b38d03bd7e50df373292118db60b585c08a411c6d840017fe7d" +checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98" dependencies = [ - "dirs-sys", + "cssparser-macros", + "dtoa-short", + "itoa", + "phf 0.13.1", + "smallvec", ] [[package]] -name = "dirs-sys" -version = "0.5.0" +name = "cssparser" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +checksum = "11119743ad110e8c1bdccd930d7f5c30c99e5fc76a7b63ec9807e84eef0c5f59" dependencies = [ - "libc", - "option-ext", - "redox_users", - "windows-sys", + "cssparser-macros", + "dtoa-short", + "itoa", + "phf 0.14.0", + "smallvec", ] [[package]] -name = "displaydoc" -version = "0.2.7" +name = "cssparser-macros" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a" dependencies = [ - "proc-macro2", "quote", "syn 3.0.9", ] [[package]] -name = "endi" -version = "1.1.1" +name = "ctor" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" +checksum = "ea691ed9f36489d087419b8b2ba3ef27d89621380b4178c73e2445a379e4e0f4" +dependencies = [ + "link-section", +] [[package]] -name = "enumflags2" -version = "0.7.12" +name = "ctutils" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" dependencies = [ - "enumflags2_derive", - "serde", + "cmov", ] [[package]] -name = "enumflags2_derive" -version = "0.7.12" +name = "darling" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", + "darling_core", + "darling_macro", ] [[package]] -name = "equivalent" -version = "1.0.3" +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.9", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "serde_core", +] + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", + "ctutils", +] + +[[package]] +name = "directories" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16f5094c54661b38d03bd7e50df373292118db60b585c08a411c6d840017fe7d" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "block2", + "libc", + "objc2", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "dlopen2" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e2c5bd4158e66d1e215c49b837e11d62f3267b30c92f1d171c4d3105e3dc4d4" +dependencies = [ + "dlopen2_derive", + "libc", + "once_cell", + "winapi", +] + +[[package]] +name = "dlopen2_derive" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbbb781877580993a8707ec48672673ec7b81eeba04cfd2310bd28c08e47c8f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "dom_query" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc" +dependencies = [ + "bit-set 0.8.0", + "cssparser 0.37.0", + "foldhash", + "html5ever 0.39.0", + "precomputed-hash", + "selectors 0.38.0", + "tendril", +] + +[[package]] +name = "dom_query" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498c698ac51127148a3984450e51fca7f01805a91d7a1f7a24af0a5f761e3385" +dependencies = [ + "bit-set 0.11.1", + "cssparser 0.38.0", + "foldhash", + "html5ever 0.40.1", + "precomputed-hash", + "selectors 0.41.0", + "tendril", +] + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +dependencies = [ + "serde", +] + +[[package]] +name = "dtoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" + +[[package]] +name = "dtoa-short" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" +dependencies = [ + "dtoa", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "embed-resource" +version = "3.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f" +dependencies = [ + "cc", + "memchr", + "rustc_version", + "toml 1.2.1+spec-1.1.0", + "vswhom", + "winreg", +] + +[[package]] +name = "embed_plist" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" + +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +[[package]] +name = "erased-serde" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + [[package]] name = "errno" version = "0.3.14" @@ -386,7 +971,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -409,25 +994,100 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + [[package]] name = "fastrand" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "field-offset" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" +dependencies = [ + "memoffset", + "rustc_version", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "foreign-types" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" dependencies = [ - "foreign-types-shared", + "foreign-types-shared 0.1.1", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared 0.3.1", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", ] [[package]] @@ -436,6 +1096,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -461,6 +1127,17 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + [[package]] name = "futures-io" version = "0.3.34" @@ -520,22 +1197,303 @@ dependencies = [ ] [[package]] -name = "getrandom" -version = "0.4.3" +name = "gdk" +version = "0.18.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691" dependencies = [ - "cfg-if", + "cairo-rs", + "gdk-pixbuf", + "gdk-sys", + "gio", + "glib", "libc", - "r-efi", + "pango", ] +[[package]] +name = "gdk-pixbuf" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec" +dependencies = [ + "gdk-pixbuf-sys", + "gio", + "glib", + "libc", + "once_cell", +] + +[[package]] +name = "gdk-pixbuf-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gdk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7" +dependencies = [ + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "pkg-config", + "system-deps", +] + +[[package]] +name = "gdkwayland-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69" +dependencies = [ + "gdk-sys", + "glib-sys", + "gobject-sys", + "libc", + "pkg-config", + "system-deps", +] + +[[package]] +name = "gdkx11" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3caa00e14351bebbc8183b3c36690327eb77c49abc2268dd4bd36b856db3fbfe" +dependencies = [ + "gdk", + "gdkx11-sys", + "gio", + "glib", + "libc", + "x11", +] + +[[package]] +name = "gdkx11-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d" +dependencies = [ + "gdk-sys", + "glib-sys", + "libc", + "system-deps", + "x11", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "gio" +version = "0.18.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "gio-sys", + "glib", + "libc", + "once_cell", + "pin-project-lite", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "gio-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", + "winapi", +] + +[[package]] +name = "glib" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5" +dependencies = [ + "bitflags 2.13.2", + "futures-channel", + "futures-core", + "futures-executor", + "futures-task", + "futures-util", + "gio-sys", + "glib-macros", + "glib-sys", + "gobject-sys", + "libc", + "memchr", + "once_cell", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "glib-macros" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc" +dependencies = [ + "heck 0.4.1", + "proc-macro-crate 2.0.2", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "glib-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898" +dependencies = [ + "libc", + "system-deps", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "gobject-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gtk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a" +dependencies = [ + "atk", + "cairo-rs", + "field-offset", + "futures-channel", + "gdk", + "gdk-pixbuf", + "gio", + "glib", + "gtk-sys", + "gtk3-macros", + "libc", + "pango", + "pkg-config", +] + +[[package]] +name = "gtk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414" +dependencies = [ + "atk-sys", + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "system-deps", +] + +[[package]] +name = "gtk3-macros" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d" +dependencies = [ + "proc-macro-crate 1.3.1", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + [[package]] name = "heck" version = "0.5.0" @@ -563,7 +1521,28 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" dependencies = [ - "digest", + "digest 0.11.3", +] + +[[package]] +name = "html5ever" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8" +dependencies = [ + "log", + "markup5ever 0.39.0", +] + +[[package]] +name = "html5ever" +version = "0.40.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456a1a377e608e555d22ddab27ac0114bc7a7b4199078108e34c2aeae6c9b130" +dependencies = [ + "log", + "markup5ever 0.40.0", + "memchr", ] [[package]] @@ -655,7 +1634,7 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ - "base64", + "base64 0.23.1", "bytes", "futures-channel", "futures-util", @@ -673,6 +1652,40 @@ dependencies = [ "tracing", ] +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "ico" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d75e94d66081e4d8dcd098bd8dc5254800fea14a26389b298410158d834de167" +dependencies = [ + "byteorder", + "png", +] + [[package]] name = "icu_collections" version = "2.4.0" @@ -756,6 +1769,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "idna" version = "1.1.0" @@ -777,6 +1796,17 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -784,7 +1814,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", - "hashbrown", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "infer" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4" +dependencies = [ + "cfb", ] [[package]] @@ -816,73 +1857,319 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] -name = "js-sys" -version = "0.3.107" +name = "javascriptcore-rs" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc" dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", + "bitflags 1.3.2", + "glib", + "javascriptcore-rs-sys", ] [[package]] -name = "libc" -version = "0.2.191" +name = "javascriptcore-rs-sys" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] [[package]] -name = "libredox" -version = "0.1.25" +name = "jiff" +version = "0.2.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f" dependencies = [ - "libc", + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", ] [[package]] -name = "linux-raw-sys" -version = "0.12.1" +name = "jiff-core" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b" +dependencies = [ + "log", +] [[package]] -name = "litemap" -version = "0.8.3" +name = "jiff-static" +version = "0.2.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] [[package]] -name = "log" -version = "0.4.35" +name = "jiff-tzdb" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" +checksum = "0980fca2cc272465bd60e82397607ba9f33add9e48defd77923301bbd03808f2" [[package]] -name = "memchr" -version = "2.8.3" +name = "jiff-tzdb-platform" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] [[package]] -name = "memoffset" -version = "0.9.1" +name = "jni" +version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" dependencies = [ - "autocfg", + "cesu8", + "cfg-if", + "combine", + "jni-sys 0.3.1", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", ] [[package]] -name = "mio" -version = "1.2.4" +name = "jni-sys" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" dependencies = [ - "libc", - "wasi", - "windows-sys", + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "json-patch" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72" +dependencies = [ + "jsonptr", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "jsonptr" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "keyboard-types" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d" +dependencies = [ + "bitflags 2.13.2", + "serde", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b06e69070b7e12262b0cd90832f0a7396f142a2b330181255562decf9f0c6215" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "link-section" +version = "0.19.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d9aae57673c1a235149777a74d152f3210ebd3e3b13346d2cdb6809e566bd3c" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "markup5ever" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de" +dependencies = [ + "log", + "tendril", + "web_atoms 0.2.6", +] + +[[package]] +name = "markup5ever" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ab3dc68ac4a0f5719e560136778c1ee716e296030d75dbd4484e37e39e3a842" +dependencies = [ + "log", + "tendril", + "web_atoms 0.3.0", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "muda" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cca139e57da4383727f189e43e66e84fa372347027fc996f9f1a007ec0a37996" +dependencies = [ + "crossbeam-channel", + "dpi", + "gtk", + "keyboard-types", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "once_cell", + "png", + "serde", + "thiserror 2.0.21", + "windows-sys 0.61.2", ] [[package]] @@ -902,6 +2189,42 @@ dependencies = [ "tempfile", ] +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + [[package]] name = "num" version = "0.4.3" @@ -981,666 +2304,2504 @@ dependencies = [ ] [[package]] -name = "omgcode-cli" -version = "0.28.0" +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" dependencies = [ - "clap", - "directories", - "omgcode-core", - "serde", - "serde_json", - "tempfile", - "uuid", + "num_enum_derive", + "rustversion", ] [[package]] -name = "omgcode-core" -version = "0.28.0" +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" dependencies = [ - "libc", - "omgcode-platform", - "reqwest", - "serde", - "serde_json", - "sha2", - "tempfile", - "thiserror", - "time", - "tokio", - "uuid", + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] -name = "omgcode-platform" -version = "0.28.0" +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" dependencies = [ - "libc", - "rustix", - "secret-service", - "tempfile", - "tokio", - "uuid", - "windows-sys", - "zbus", - "zeroize", + "objc2-encode", + "objc2-exception-helper", ] [[package]] -name = "once_cell" -version = "1.21.4" +name = "objc2-app-kit" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2", + "objc2-core-foundation", + "objc2-foundation", + "objc2-quartz-core", +] [[package]] -name = "once_cell_polyfill" -version = "1.70.2" +name = "objc2-cloud-kit" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-foundation", +] [[package]] -name = "openssl" -version = "0.10.81" +name = "objc2-core-data" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" dependencies = [ - "bitflags", - "cfg-if", - "foreign-types", - "libc", - "openssl-macros", - "openssl-sys", + "objc2", + "objc2-foundation", ] [[package]] -name = "openssl-macros" -version = "0.1.1" +name = "objc2-core-foundation" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", + "bitflags 2.13.2", + "dispatch2", + "objc2", ] [[package]] -name = "openssl-probe" -version = "0.2.2" +name = "objc2-core-graphics" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2", + "objc2-core-foundation", + "objc2-io-surface", +] [[package]] -name = "openssl-sys" -version = "0.9.117" +name = "objc2-core-image" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" dependencies = [ - "cc", - "libc", - "pkg-config", - "vcpkg", + "objc2", + "objc2-foundation", ] [[package]] -name = "option-ext" -version = "0.2.0" +name = "objc2-core-location" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009" +dependencies = [ + "objc2", + "objc2-foundation", +] [[package]] -name = "ordered-stream" +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-exception-helper" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7a1c5fbb72d7735b076bb47b578523aedc40f3c439bea6dfd595c089d79d98a" +dependencies = [ + "cc", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", + "objc2-foundation", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image", + "objc2-core-location", + "objc2-core-text", + "objc2-foundation", + "objc2-quartz-core", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-web-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", +] + +[[package]] +name = "omgcode-app" +version = "0.29.0" +dependencies = [ + "directories", + "omgcode-core", + "serde", + "serde_json", + "sha2 0.11.1", + "tempfile", + "time", + "uuid", +] + +[[package]] +name = "omgcode-cli" +version = "0.29.0" +dependencies = [ + "clap", + "omgcode-app", + "omgcode-core", + "serde", + "serde_json", + "tempfile", + "uuid", +] + +[[package]] +name = "omgcode-core" +version = "0.29.0" +dependencies = [ + "libc", + "omgcode-platform", + "reqwest", + "rusqlite", + "serde", + "serde_json", + "sha2 0.11.1", + "tempfile", + "thiserror 2.0.21", + "time", + "tokio", + "uuid", +] + +[[package]] +name = "omgcode-desktop" +version = "0.29.0" +dependencies = [ + "omgcode-app", + "serde", + "serde_json", + "tauri", + "tauri-build", + "uuid", +] + +[[package]] +name = "omgcode-platform" +version = "0.29.0" +dependencies = [ + "libc", + "rustix", + "secret-service", + "tempfile", + "tokio", + "uuid", + "windows-sys 0.61.2", + "zbus", + "zeroize", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "openssl" +version = "0.10.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "foreign-types 0.3.2", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "ordered-stream" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "pango" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4" +dependencies = [ + "gio", + "glib", + "libc", + "once_cell", + "pango-sys", +] + +[[package]] +name = "pango-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros 0.13.1", + "phf_shared 0.13.1", + "serde", +] + +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" +dependencies = [ + "phf_macros 0.14.0", + "phf_shared 0.14.0", + "serde", +] + +[[package]] +name = "phf_codegen" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", +] + +[[package]] +name = "phf_codegen" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b585a510fb76fdebead6897982ef2a03a21d8e6cbcca904999742a4afc6ffe" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared 0.13.1", +] + +[[package]] +name = "phf_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" +dependencies = [ + "fastrand", + "phf_shared 0.14.0", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_macros" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "phf_shared" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plist" +version = "1.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285" +dependencies = [ + "base64 0.23.1", + "indexmap 2.14.2", + "quick-xml", + "serde", + "time", +] + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit 0.19.15", +] + +[[package]] +name = "proc-macro-crate" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24" +dependencies = [ + "toml_datetime 0.6.3", + "toml_edit 0.20.2", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit 0.25.19+spec-1.1.0", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", +] + +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-tls", + "hyper-util", + "js-sys", + "log", + "native-tls", + "percent-encoding", + "pin-project-lite", + "rustls-pki-types", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tokio-native-tls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[package]] +name = "rusqlite" +version = "0.43.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f172c4812a19b26d1c23cdb0070e69db335503dfa378b910eb857386e5b8beba" +dependencies = [ + "bitflags 2.13.2", + "fallible-iterator", + "fallible-streaming-iterator", + "libsqlite3-sys", + "smallvec", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "schemars" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" +dependencies = [ + "dyn-clone", + "indexmap 1.9.3", + "schemars_derive", + "serde", + "serde_json", + "url", + "uuid", +] + +[[package]] +name = "schemars" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 2.0.119", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "secret-service" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8" +dependencies = [ + "aes", + "cbc", + "futures-util", + "getrandom 0.4.3", + "hkdf", + "hybrid-array", + "num", + "once_cell", + "serde", + "sha2 0.11.1", + "zbus", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "selectors" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d" +dependencies = [ + "bitflags 2.13.2", + "cssparser 0.37.0", + "derive_more", + "log", + "new_debug_unreachable", + "phf 0.13.1", + "phf_codegen 0.13.1", + "precomputed-hash", + "rustc-hash", + "servo_arc 0.4.3", + "smallvec", +] + +[[package]] +name = "selectors" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8322aebea94a6cc288ff884e8a49bdbceef60206c400c6c46d22e62fc4fd91a6" +dependencies = [ + "bitflags 2.13.2", + "cssparser 0.38.0", + "derive_more", + "log", + "new_debug_unreachable", + "precomputed-hash", + "rustc-hash", + "servo_arc 0.5.0", + "smallvec", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde-untagged" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058" +dependencies = [ + "erased-serde", + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_with" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f" +dependencies = [ + "base64 0.23.1", + "bs58", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.14.2", + "jiff", + "schemars 0.9.0", + "schemars 1.2.3", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serialize-to-javascript" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04f3666a07a197cdb77cdf306c32be9b7f598d7060d50cfd4d5aa04bfd92f6c5" +dependencies = [ + "serde", + "serde_json", + "serialize-to-javascript-impl", +] + +[[package]] +name = "serialize-to-javascript-impl" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "servo_arc" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "servo_arc" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4eceb519ec34d8290aaf6e46f435102f2bfa63f22b05a144fb16ab266d3b198" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "softbuffer" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3" +dependencies = [ + "bytemuck", + "js-sys", + "ndk", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "objc2-quartz-core", + "raw-window-handle", + "redox_syscall", + "tracing", + "wasm-bindgen", + "web-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "soup3" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f" +dependencies = [ + "futures-channel", + "gio", + "glib", + "libc", + "soup3-sys", +] + +[[package]] +name = "soup3-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_vcruntime" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff7589a1859b09232522bb9edf076ca7fcf14ded96685d3fa629db73023ffbb7" + +[[package]] +name = "string_cache" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared 0.13.1", + "precomputed-hash", +] + +[[package]] +name = "string_cache" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffa8a5dbe8b3f0bbe29d4c3225daafaeead63afdc1b65fc4c01a1384166038e6" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared 0.14.0", + "precomputed-hash", +] + +[[package]] +name = "string_cache_codegen" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2", + "quote", +] + +[[package]] +name = "string_cache_codegen" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928dcdf75e47626b3617a976ec205d9f057584c371c1f23b782129268d0e6edc" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", + "proc-macro2", + "quote", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "swift-rs" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cefd87076fd385308ee4aff597256c902f1fbb4d031de1558efc12f8ffefadd9" +dependencies = [ + "base64 0.21.7", + "serde", + "serde_json", +] + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "system-deps" +version = "6.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" +dependencies = [ + "cfg-expr", + "heck 0.5.0", + "pkg-config", + "toml 0.8.2", + "version-compare", +] + +[[package]] +name = "tao" +version = "0.37.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5777b06fe6435126ae8d816eba269e050e1e10d302cf5461e9c49eccabc3548" +dependencies = [ + "bitflags 2.13.2", + "block2", + "core-foundation", + "core-graphics", + "crossbeam-channel", + "dispatch2", + "dlopen2", + "dpi", + "gdkwayland-sys", + "gdkx11-sys", + "gtk", + "jni", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "objc2-ui-kit", + "parking_lot", + "percent-encoding", + "raw-window-handle", + "tao-macros", + "unicode-segmentation", + "url", + "windows", + "windows-core", + "windows-version", + "x11-dl", +] + +[[package]] +name = "tao-macros" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f7eeb6d99155545da6150a1795945f16ac9c178deb2a5f2e74d776107bd5849" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "target-lexicon" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" + +[[package]] +name = "tauri" +version = "2.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c2a5cad3827d1fa46c206a6bcaee8ca14203e9b0aaabe447dd4acef33ecd065" +dependencies = [ + "anyhow", + "bytes", + "cookie", + "dirs", + "dunce", + "embed_plist", + "getrandom 0.3.4", + "glob", + "gtk", + "heck 0.5.0", + "http", + "jni", + "libc", + "log", + "mime", + "muda", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "objc2-ui-kit", + "objc2-web-kit", + "percent-encoding", + "plist", + "raw-window-handle", + "reqwest", + "serde", + "serde_json", + "serde_repr", + "serialize-to-javascript", + "swift-rs", + "tauri-build", + "tauri-macros", + "tauri-runtime", + "tauri-runtime-wry", + "tauri-utils", + "thiserror 2.0.21", + "tokio", + "url", + "webkit2gtk", + "webview2-com", + "window-vibrancy", + "windows", +] + +[[package]] +name = "tauri-build" +version = "2.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e03658bfc9cb60f96a05b7d07a7f7cdfbf4c30b1bbfcb5cf6b5342cc2c9e0bc" +dependencies = [ + "anyhow", + "cargo_toml", + "dirs", + "glob", + "heck 0.5.0", + "json-patch", + "schemars 0.8.22", + "semver", + "serde", + "serde_json", + "static_vcruntime", + "strsim", + "tauri-utils", + "tauri-winres", + "walkdir", +] + +[[package]] +name = "tauri-codegen" +version = "2.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c454a15120b885bf57d0cb9ab218c01e12bc672f793452cb6527b460db883aa" +dependencies = [ + "base64 0.23.1", + "ico", + "json-patch", + "plist", + "png", + "proc-macro2", + "quote", + "semver", + "serde", + "serde_json", + "sha2 0.11.1", + "syn 2.0.119", + "tauri-utils", + "thiserror 2.0.21", + "time", + "url", + "uuid", + "walkdir", +] + +[[package]] +name = "tauri-macros" +version = "2.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8f7513896f637528ec27ff76effd90638b1cdfa77499fae3db078043aed7ecb" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", + "tauri-codegen", + "tauri-utils", +] + +[[package]] +name = "tauri-runtime" +version = "2.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c4b2a71c4bf51cde5cdcf1b45d7943282c7c669d3d26f7a324cce25f1b53e75" +dependencies = [ + "cookie", + "dpi", + "gtk", + "http", + "jni", + "objc2", + "objc2-ui-kit", + "objc2-web-kit", + "raw-window-handle", + "serde", + "serde_json", + "tauri-utils", + "thiserror 2.0.21", + "url", + "webkit2gtk", + "webview2-com", + "windows", +] + +[[package]] +name = "tauri-runtime-wry" +version = "2.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d9be5e7af9560a4a60cdd441389a066cdd3e7c5d464a006ae34cb276cc78abd" +dependencies = [ + "gtk", + "http", + "jni", + "log", + "objc2", + "objc2-app-kit", + "percent-encoding", + "raw-window-handle", + "softbuffer", + "tao", + "tauri-runtime", + "tauri-utils", + "url", + "webkit2gtk", + "webview2-com", + "windows", + "wry", +] + +[[package]] +name = "tauri-utils" +version = "2.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bf649f12d6fb11e1867214973cd37d89786ae2c0904f79b787b1db4fdcd14c" +dependencies = [ + "anyhow", + "cargo_metadata", + "ctor", + "dom_query 0.28.0", + "dunce", + "glob", + "http", + "infer", + "json-patch", + "log", + "memchr", + "phf 0.13.1", + "plist", + "proc-macro2", + "quote", + "regex", + "schemars 0.8.22", + "semver", + "serde", + "serde-untagged", + "serde_json", + "serde_with", + "swift-rs", + "thiserror 2.0.21", + "toml 1.2.1+spec-1.1.0", + "url", + "urlpattern", + "uuid", + "walkdir", +] + +[[package]] +name = "tauri-winres" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c52bb6904475a6ca662f15ef787f18ade61d5740a1ee12c45d3b748efdb6f796" +dependencies = [ + "dunce", + "embed-resource", + "toml 1.2.1+spec-1.1.0", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "tendril" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08" +dependencies = [ + "new_debug_unreachable", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ - "futures-core", - "pin-project-lite", + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] -name = "parking" -version = "2.2.1" +name = "thiserror-impl" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] [[package]] -name = "percent-encoding" -version = "2.3.2" +name = "time" +version = "0.3.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] [[package]] -name = "pin-project-lite" -version = "0.2.17" +name = "time-core" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" [[package]] -name = "pkg-config" -version = "0.3.34" +name = "time-macros" +version = "0.2.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] [[package]] -name = "potential_utf" -version = "0.1.6" +name = "tinystr" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ + "displaydoc", "zerovec", ] [[package]] -name = "powerfmt" -version = "0.2.1" +name = "tinyvec" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] -name = "proc-macro-crate" -version = "3.5.0" +name = "tokio" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ - "toml_edit", + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tracing", + "windows-sys 0.61.2", ] [[package]] -name = "proc-macro2" -version = "1.0.107" +name = "tokio-native-tls" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" dependencies = [ - "unicode-ident", + "native-tls", + "tokio", ] [[package]] -name = "quote" -version = "1.0.47" +name = "tokio-util" +version = "0.7.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" dependencies = [ - "proc-macro2", + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", ] [[package]] -name = "r-efi" -version = "6.0.0" +name = "toml" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d" +dependencies = [ + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.3", + "toml_edit 0.20.2", +] [[package]] -name = "redox_users" +name = "toml" +version = "1.2.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +dependencies = [ + "indexmap 2.14.2", + "serde_core", + "serde_spanned 1.1.3", + "toml_datetime 1.1.3+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 1.0.5", +] + +[[package]] +name = "toml_datetime" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.19.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" +dependencies = [ + "indexmap 2.14.2", + "toml_datetime 0.6.3", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338" +dependencies = [ + "indexmap 2.14.2", + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.3", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.25.19+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" +dependencies = [ + "indexmap 2.14.2", + "toml_datetime 1.1.3+spec-1.1.0", + "toml_parser", + "winnow 1.0.5", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow 1.0.5", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "tower" version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" dependencies = [ - "libredox", - "thiserror", + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", ] [[package]] -name = "reqwest" -version = "0.13.5" +name = "tower-http" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ - "base64", + "bitflags 2.13.2", "bytes", - "futures-channel", - "futures-core", "futures-util", "http", "http-body", - "http-body-util", - "hyper", - "hyper-tls", - "hyper-util", - "js-sys", - "log", - "native-tls", - "percent-encoding", "pin-project-lite", - "rustls-pki-types", - "serde", - "serde_json", - "sync_wrapper", - "tokio", - "tokio-native-tls", "tower", - "tower-http", + "tower-layer", "tower-service", "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", ] [[package]] -name = "rustix" -version = "1.1.6" +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uds_windows" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ - "bitflags", - "errno", - "libc", - "linux-raw-sys", - "windows-sys", + "memoffset", + "tempfile", + "windows-sys 0.61.2", ] [[package]] -name = "rustls-pki-types" -version = "1.16.0" +name = "unicode-ident" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" -dependencies = [ - "zeroize", -] +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] -name = "rustversion" -version = "1.0.23" +name = "unicode-segmentation" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" [[package]] -name = "schannel" -version = "0.1.30" +name = "url" +version = "2.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" dependencies = [ - "windows-sys", + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", ] [[package]] -name = "secret-service" -version = "5.2.0" +name = "urlpattern" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8" +checksum = "df16f50ef4cc145211879a3867ba757076b25dfee812040dcb0658bd9ae7904b" dependencies = [ - "aes", - "cbc", - "futures-util", - "getrandom", - "hkdf", - "hybrid-array", - "num", - "once_cell", + "icu_properties", + "regex", "serde", - "sha2", - "zbus", + "url", ] [[package]] -name = "security-framework" -version = "3.7.0" +name = "utf8_iter" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" dependencies = [ - "bitflags", - "core-foundation", - "core-foundation-sys", - "libc", - "security-framework-sys", + "utf_types", ] [[package]] -name = "security-framework-sys" -version = "2.17.0" +name = "utf8parse" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" -dependencies = [ - "core-foundation-sys", - "libc", -] +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] -name = "serde" -version = "1.0.229" +name = "utf_types" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" -dependencies = [ - "serde_core", - "serde_derive", -] +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" [[package]] -name = "serde_core" -version = "1.0.229" +name = "uuid" +version = "1.29.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +checksum = "4a06f08a856b009bc7bbaf7d3e79808595d032dd19074c0c2ef26e49e03e6bdc" dependencies = [ - "serde_derive", + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", ] [[package]] -name = "serde_derive" -version = "1.0.229" +name = "vcpkg" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" [[package]] -name = "serde_json" -version = "1.0.154" +name = "version-compare" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" [[package]] -name = "serde_repr" -version = "0.1.21" +name = "version_check" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] -name = "sha2" -version = "0.11.1" +name = "vswhom" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b" dependencies = [ - "cfg-if", - "cpufeatures", - "digest", + "libc", + "vswhom-sys", ] [[package]] -name = "shlex" -version = "2.0.1" +name = "vswhom-sys" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150" +dependencies = [ + "cc", + "libc", +] [[package]] -name = "signal-hook-registry" -version = "1.4.8" +name = "walkdir" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" dependencies = [ - "errno", - "libc", + "same-file", + "winapi-util", ] [[package]] -name = "slab" -version = "0.4.12" +name = "want" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] [[package]] -name = "smallvec" -version = "1.16.5" +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] -name = "socket2" -version = "0.6.5" +name = "wasip2" +version = "1.0.4+wasi-0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" dependencies = [ - "libc", - "windows-sys", + "wit-bindgen", ] [[package]] -name = "stable_deref_trait" -version = "1.2.1" +name = "wasm-bindgen" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] [[package]] -name = "strsim" -version = "0.11.1" +name = "wasm-bindgen-futures" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] [[package]] -name = "syn" -version = "2.0.119" +name = "wasm-bindgen-macro" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ - "proc-macro2", "quote", - "unicode-ident", + "wasm-bindgen-macro-support", ] [[package]] -name = "syn" -version = "3.0.9" +name = "wasm-bindgen-macro-support" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ + "bumpalo", "proc-macro2", "quote", - "unicode-ident", + "syn 3.0.9", + "wasm-bindgen-shared", ] [[package]] -name = "sync_wrapper" -version = "1.0.2" +name = "wasm-bindgen-shared" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ - "futures-core", + "unicode-ident", ] [[package]] -name = "synstructure" -version = "0.14.0" +name = "wasm-streams" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", ] [[package]] -name = "tempfile" -version = "3.27.0" +name = "web-sys" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ - "fastrand", - "getrandom", - "once_cell", - "rustix", - "windows-sys", + "js-sys", + "wasm-bindgen", ] [[package]] -name = "thiserror" -version = "2.0.21" +name = "web-time" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" dependencies = [ - "thiserror-impl", + "js-sys", + "wasm-bindgen", ] [[package]] -name = "thiserror-impl" -version = "2.0.21" +name = "web_atoms" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3" dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", + "phf 0.13.1", + "phf_codegen 0.13.1", + "string_cache 0.9.0", + "string_cache_codegen 0.6.1", ] [[package]] -name = "time" -version = "0.3.55" +name = "web_atoms" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +checksum = "7572660c8890448ba236b7376f27e389c6a7e1c70195622faced601f855c0ada" dependencies = [ - "deranged", - "num-conv", - "powerfmt", - "serde_core", - "time-core", - "time-macros", + "phf 0.14.0", + "phf_codegen 0.14.0", + "string_cache 0.11.0", + "string_cache_codegen 0.11.2", ] [[package]] -name = "time-core" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" - -[[package]] -name = "time-macros" -version = "0.2.32" +name = "webkit2gtk" +version = "2.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793" dependencies = [ - "num-conv", - "time-core", + "bitflags 1.3.2", + "cairo-rs", + "gdk", + "gdk-sys", + "gio", + "gio-sys", + "glib", + "glib-sys", + "gobject-sys", + "gtk", + "gtk-sys", + "javascriptcore-rs", + "libc", + "once_cell", + "soup3", + "webkit2gtk-sys", ] [[package]] -name = "tinystr" -version = "0.8.5" +name = "webkit2gtk-sys" +version = "2.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5" dependencies = [ - "displaydoc", - "zerovec", + "bitflags 1.3.2", + "cairo-sys-rs", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "gtk-sys", + "javascriptcore-rs-sys", + "libc", + "pkg-config", + "soup3-sys", + "system-deps", ] [[package]] -name = "tokio" -version = "1.54.1" +name = "webview2-com" +version = "0.39.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +checksum = "3f89fca7a704cee10dcb3654c1dbb8941d1783132f1917358af75bec37a7d7e6" dependencies = [ - "bytes", - "libc", - "mio", - "pin-project-lite", - "signal-hook-registry", - "socket2", - "tracing", - "windows-sys", + "webview2-com-macros", + "webview2-com-sys", + "windows", + "windows-core", ] [[package]] -name = "tokio-native-tls" -version = "0.3.1" +name = "webview2-com-macros" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54" dependencies = [ - "native-tls", - "tokio", + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] -name = "toml_datetime" -version = "1.1.3+spec-1.1.0" +name = "webview2-com-sys" +version = "0.39.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb" dependencies = [ - "serde_core", + "thiserror 2.0.21", + "windows", + "windows-core", ] [[package]] -name = "toml_edit" -version = "0.25.19+spec-1.1.0" +name = "winapi" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ - "indexmap", - "toml_datetime", - "toml_parser", - "winnow", + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", ] [[package]] -name = "toml_parser" -version = "1.1.5+spec-1.1.0" +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "winnow", + "windows-sys 0.61.2", ] [[package]] -name = "tower" -version = "0.5.3" +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "window-vibrancy" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "111e51caca442cafd9bab396628ac4d814880eaea4e63dfd76a12e9f342b5580" dependencies = [ - "futures-core", - "futures-util", - "pin-project-lite", - "sync_wrapper", - "tokio", - "tower-layer", - "tower-service", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "objc2-quartz-core", + "raw-window-handle", + "windows-sys 0.61.2", + "windows-version", ] [[package]] -name = "tower-http" -version = "0.6.11" +name = "windows" +version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" dependencies = [ - "bitflags", - "bytes", - "futures-util", - "http", - "http-body", - "pin-project-lite", - "tower", - "tower-layer", - "tower-service", - "url", + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", ] [[package]] -name = "tower-layer" -version = "0.3.3" +name = "windows-collections" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] [[package]] -name = "tower-service" -version = "0.3.3" +name = "windows-core" +version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] [[package]] -name = "tracing" -version = "0.1.44" +name = "windows-future" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" dependencies = [ - "pin-project-lite", - "tracing-attributes", - "tracing-core", + "windows-core", + "windows-link", + "windows-threading", ] [[package]] -name = "tracing-attributes" -version = "0.1.31" +name = "windows-implement" +version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2", "quote", @@ -1648,203 +4809,246 @@ dependencies = [ ] [[package]] -name = "tracing-core" -version = "0.1.36" +name = "windows-interface" +version = "0.59.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ - "once_cell", + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] -name = "try-lock" -version = "0.2.5" +name = "windows-link" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" [[package]] -name = "typenum" -version = "1.20.1" +name = "windows-numerics" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] [[package]] -name = "uds_windows" -version = "1.2.1" +name = "windows-result" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" dependencies = [ - "memoffset", - "tempfile", - "windows-sys", + "windows-link", ] [[package]] -name = "unicode-ident" -version = "1.0.27" +name = "windows-strings" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] [[package]] -name = "url" -version = "2.5.8" +name = "windows-sys" +version = "0.45.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", + "windows-targets", ] [[package]] -name = "utf8_iter" -version = "1.1.0" +name = "windows-sys" +version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "utf_types", + "windows-link", ] [[package]] -name = "utf8parse" -version = "0.2.2" +name = "windows-targets" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] [[package]] -name = "utf_types" -version = "1.0.0" +name = "windows-threading" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] [[package]] -name = "uuid" -version = "1.29.1" +name = "windows-version" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a06f08a856b009bc7bbaf7d3e79808595d032dd19074c0c2ef26e49e03e6bdc" +checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631" dependencies = [ - "getrandom", - "js-sys", - "serde_core", - "wasm-bindgen", + "windows-link", ] [[package]] -name = "vcpkg" -version = "0.2.15" +name = "windows_aarch64_gnullvm" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" [[package]] -name = "want" -version = "0.3.2" +name = "windows_aarch64_msvc" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" -dependencies = [ - "try-lock", -] +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" [[package]] -name = "wasi" -version = "0.11.1+wasi-snapshot-preview1" +name = "windows_i686_gnu" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" [[package]] -name = "wasm-bindgen" -version = "0.2.130" +name = "windows_i686_msvc" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" -dependencies = [ - "cfg-if", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" [[package]] -name = "wasm-bindgen-futures" -version = "0.4.80" +name = "windows_x86_64_gnu" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" -dependencies = [ - "js-sys", - "tokio", - "wasm-bindgen", -] +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" [[package]] -name = "wasm-bindgen-macro" -version = "0.2.130" +name = "windows_x86_64_gnullvm" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" [[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.130" +name = "windows_x86_64_msvc" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + +[[package]] +name = "winnow" +version = "0.5.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 3.0.9", - "wasm-bindgen-shared", + "memchr", ] [[package]] -name = "wasm-bindgen-shared" -version = "0.2.130" +name = "winnow" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" dependencies = [ - "unicode-ident", + "memchr", ] [[package]] -name = "web-sys" -version = "0.3.107" +name = "winreg" +version = "0.56.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" dependencies = [ - "js-sys", - "wasm-bindgen", + "cfg-if", + "windows-sys 0.61.2", ] [[package]] -name = "windows-link" -version = "0.2.1" +name = "wit-bindgen" +version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" [[package]] -name = "windows-sys" -version = "0.61.2" +name = "writeable" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "wry" +version = "0.57.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a490119196d02a51d0871df7b9119a1f3e46d75b7e90053a801454d5c6b3491c" dependencies = [ - "windows-link", + "base64 0.23.1", + "block2", + "cookie", + "crossbeam-channel", + "dirs", + "dom_query 0.29.0", + "dpi", + "dunce", + "gdkx11", + "gtk", + "http", + "javascriptcore-rs", + "jni", + "libc", + "ndk", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "objc2-ui-kit", + "objc2-web-kit", + "percent-encoding", + "raw-window-handle", + "sha2 0.10.9", + "soup3", + "tao-macros", + "thiserror 2.0.21", + "url", + "webkit2gtk", + "webkit2gtk-sys", + "webview2-com", + "windows", + "windows-core", + "windows-version", + "x11-dl", ] [[package]] -name = "winnow" -version = "1.0.5" +name = "x11" +version = "2.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e" dependencies = [ - "memchr", + "libc", + "pkg-config", ] [[package]] -name = "writeable" -version = "0.6.4" +name = "x11-dl" +version = "2.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] [[package]] name = "yoke" @@ -1892,8 +5096,8 @@ dependencies = [ "tracing", "uds_windows", "uuid", - "windows-sys", - "winnow", + "windows-sys 0.61.2", + "winnow 1.0.5", "zbus_macros", "zbus_names", "zvariant", @@ -1905,7 +5109,7 @@ version = "5.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" dependencies = [ - "proc-macro-crate", + "proc-macro-crate 3.5.0", "proc-macro2", "quote", "syn 3.0.9", @@ -1921,7 +5125,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" dependencies = [ "serde", - "winnow", + "winnow 1.0.5", "zvariant", ] @@ -1994,6 +5198,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" @@ -2009,7 +5219,7 @@ dependencies = [ "endi", "enumflags2", "serde", - "winnow", + "winnow 1.0.5", "zcheapstr", "zvariant_derive", "zvariant_utils", @@ -2021,7 +5231,7 @@ version = "5.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" dependencies = [ - "proc-macro-crate", + "proc-macro-crate 3.5.0", "proc-macro2", "quote", "syn 3.0.9", @@ -2038,5 +5248,5 @@ dependencies = [ "quote", "serde", "syn 3.0.9", - "winnow", + "winnow 1.0.5", ] diff --git a/Cargo.toml b/Cargo.toml index 23c91cf..688645d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,9 +1,9 @@ [workspace] resolver = "3" -members = ["crates/omgcode-core", "crates/omgcode-cli", "crates/omgcode-platform"] +members = ["crates/omgcode-core", "crates/omgcode-cli", "crates/omgcode-platform", "crates/omgcode-app", "crates/omgcode-desktop"] [workspace.package] -version = "0.28.0" +version = "0.29.0" edition = "2024" rust-version = "1.99.1" license = "Apache-2.0" @@ -25,6 +25,8 @@ tempfile = "3" libc = "0.2.191" rustix = { version = "1.1.6", features = ["fs", "process"] } zeroize = { version = "1.8", default-features = false, features = ["alloc"] } +# Derived session index cache (ADR pending). Bundled SQLite; no extension loading. +rusqlite = { version = "0.43.0", default-features = false, features = ["bundled"] } secret-service = { version = "5.2", default-features = false, features = ["rt-tokio-crypto-rust"] } # Pinned to the version secret-service already uses, with the same features, # for raw Secret Service calls that refuse prompts (ADR-0042). diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index 8412a0c..633513d 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -1,6 +1,6 @@ # OMGCode implementation plan -Last verified: 2026-11-15. +Last verified: 2026-11-16. This guide is part of `main` after PR #9. Read it before selecting the next increment. Checkpoint preparation does not mean native replacement exists. @@ -66,21 +66,28 @@ This is a resume guide, not a replacement for the owning contracts in its native end-to-end acceptance test (C15). - **PR #31** merged at `28da2cf` on 2026-11-15: PR #30 review fixes, including asynchronous package-fetch file I/O. -- This branch, `codex/context-compaction`: **Phase C16**, version **0.26.0**, - with manual and pre-turn automatic context compaction (ADR-0041). It starts - from `97c733e`, the PR #31 head. No run accepts a profile or has - destination-scoped networking; no provider adapter is enabled, and the - command tool is the only model tool that can request a process. -- Commit `e88df5b` on this branch: **Phase D1**, version **0.27.0**, the - provider credential service (ADR-0042). No adapter reads a stored credential. -- This change: **Phase C17**, version **0.28.0**, the approval-gated model - edit tool (ADR-0043). It writes only through the checkpointed apply after an - approved, writers-stopped decision. +- **PR #32** merged at `60430ee` on 2026-11-16, from + `codex/context-compaction`. The merge was verified through GitHub. It + carried three phases: + - **Phase C16**, version **0.26.0**, with manual and pre-turn automatic + context compaction (ADR-0041). No run accepts a profile or has + destination-scoped networking, and no provider adapter is enabled. + - **Phase D1**, version **0.27.0**, the provider credential service + (ADR-0042). No adapter reads a stored credential. + - **Phase C17**, version **0.28.0**, the approval-gated model edit tool + (ADR-0043). It writes only through the checkpointed apply after an + approved, writers-stopped decision. +- Branch `codex/desktop-interface`: **Phase E**, version **0.29.0**, the + desktop interface and session tree (ADR-0044, ADR-0045, ADR-0046). Unlike + the entries above, it is **not merged and has no pull request yet**. It is a + prototype whose windows have run only on Windows; on Linux it builds and its + tests pass. See [the desktop interface guide](docs/desktop-interface.md). Implemented today: -- Pinned Rust 1.99.1 workspace with `omgcode-core`, `omgcode-cli`, and - `omgcode-platform`. +- Pinned Rust 1.99.1 workspace with `omgcode-core`, `omgcode-cli`, + `omgcode-platform`, `omgcode-app`, and `omgcode-desktop`. The last two exist + only on the unmerged Phase E branch. - Compiled, versioned base prompt `0.1.4` with a visible digest. - Workspace settings, native directory identity, process-local bindings, and a separate settings/audit journal. @@ -204,8 +211,13 @@ Not implemented: - Model create, delete, rename, multi-edit, network, Git, and MCP tools; concurrent-writer detection for any apply route; live provider tool-call qualification; and streaming, discovery, and cancellation in a live provider. -- A run network destination allowlist, runtime skills, memories, desktop/UI - panels, mid-turn and provider-native compaction, and caches. Nothing calls the unconfined process runner. +- A run network destination allowlist, runtime skills, memories, mid-turn and + provider-native compaction, and caches. Nothing calls the unconfined process + runner. +- Desktop development panels (terminal tabs, task logs, and diffs), a settings + interface, streaming, a recovery interface, packaging and installers, and any + Linux run of the desktop shell. The prototype shell, session tree, search, + chat, and approvals window exist on the Phase E branch only. - Provider adapters and subscription/API-key login; the recorded provider profiles are configuration only, and no adapter reads a stored credential. - Subscription token storage and a memory-only session credential. @@ -237,6 +249,20 @@ Not implemented: ## Verification baseline +Build the desktop frontend before any Cargo step that includes +`omgcode-desktop`. The crate embeds `crates/omgcode-desktop/ui/dist` at compile +time, and `cargo check`, `clippy`, `build`, and `test` fail without it: + +```text +cd crates/omgcode-desktop/ui +npm ci +npm run build +``` + +The frontend checks, run from the same directory, are `npm run check`, +`npm run lint`, `npm test`, and `npm run test:dist`. They need Node 24. The +Frontend workflow runs them on Linux and Windows. + Run from the repository root with the pinned toolchain: ```text @@ -261,6 +287,46 @@ suite on both hosts with default parallelism, as CI does. Use provider fixtures; record failures before any isolated rerun or full retry. A serial run alone cannot detect races between test threads. +On a Windows host whose repository is on ReFS, point `TEMP` and `TMP` at a +directory on NTFS. The private-store, credential, container, and replacement +tests need NTFS. Earlier notes here put `TEMP` and `TMP` on the same volume as +the fixtures; that works only when the repository volume is NTFS. Phase E +development ran with the repository on a ReFS volume. See +[testing standards](docs/testing-standards.md#desktop-shell-and-frontend). + +Phase E final verification on 2026-11-16 used Rust 1.99.1 and default test +parallelism, with the Windows and Linux runs one after the other. + +- **Windows** (Windows 11 build 26300, repository on ReFS, `TEMP` and `TMP` + on NTFS): formatting, Clippy with `--locked`, all-target tests, and doc + tests each exited zero. 782 tests in 36 test binaries and one doc test + passed. None failed. Eight were ignored, the same eight as before this + phase: one in `run_workflow`, six in `toolchain_acceptance`, and one in + `omgcode-platform`. The two file-symlink tests printed `SKIPPED link + assertions`. The frontend passed `npm run check`, `npm run lint`, and 113 + Vitest tests, including the four bundle checks. +- **Linux** (WSL 6.6, Ubuntu 24.04, ext4, a clean LF clone of `60430ee` with + the changed files overlaid and the frontend bundle built on Windows): + formatting, Clippy with `--locked`, all-target tests with `--no-fail-fast`, + and doc tests each exited zero. 776 tests in 36 test binaries and one doc + test passed. None failed. Eight were ignored. The platform suite re-runs + four tests inside `systemd-run` scopes and prints a nested result line for + each; those four are not counted twice here. The frontend commands did not + run on Linux, because that host has Node 18. +- **Failures before the final runs.** The first complete Linux run failed 19 + tests. Eighteen credential tests failed because the login keyring was + locked; they passed after it was unlocked, with no code change. One desktop + approval test failed because its fixture created the data root with the + default mode; the fixture now creates it with mode 0700. An earlier Linux + run stopped at one `omgcode-app` test that assumed the Windows spelling of + the data directory; that assertion is now case-insensitive. +- No test timed out and no provider fixture was retried on either host. + +These local results do not establish remote CI status: neither workflow change +has run. The real shell was driven end to end on Windows only +([testing standards](docs/testing-standards.md#desktop-shell-and-frontend)). +No window has been opened on Linux. + A2b local verification on 2026-11-10 passed formatting, Clippy, serial all-target tests, and doc tests with Rust 1.99.1. Ubuntu 24.04 under WSL, uid 1000, passed 266 tests and one doc test. Native Windows passed 235 tests and one doc test. @@ -689,7 +755,51 @@ login or entitlement route. The Rust core remains the authority. The UI must not receive raw journal paths, credentials, or unrestricted host capabilities. Follow the session, permission, -context, and security contracts. +context, and security contracts. Follow the +[desktop interface guide](docs/desktop-interface.md). + +Version 0.29.0 builds a prototype on branch `codex/desktop-interface`. It is +not merged, and no pull request exists yet. + +- **E1 (ADR-0044):** lock-free journal inspection. `SessionInspection::inspect` + reads one journal with no lock call, no link following, and the writer's + validator. Windows lock and sharing violations become `Busy`. Bytes after the + last line feed are reported as `incomplete_tail`. It adds times and a bounded + transcript entry list. `session::discover` walks only the dated layout and + never opens a journal or follows a link. Limits: 50,000 journals and 500,000 + directory entries. +- **E2 (ADR-0044):** a derived SQLite index in + `/session-index-v1/index.sqlite3` through `rusqlite` 0.43.0 with + the bundled SQLite and FTS5. Incremental, bounded refresh; a busy journal + keeps its last metadata; an invalid journal is listed with a code. A + missing, corrupt, or foreign index is deleted and rebuilt. +- **E3 (ADR-0045):** the `omgcode-app` library. The chat turn, compaction, + session creation, the data-root resolver, and token redaction moved out of + the CLI, which is now a thin adapter. `DesktopService` is the + front-end-neutral command service, including review tokens. Core adds + `review_approval` and display-safe text. No CLI behaviour changed. +- **E4 (ADR-0045, ADR-0046):** the Tauri shell `omgcode-desktop`: two windows, + 18 commands, a capability file per window, the Rust window policy, the content + policy, the navigation guard, and a bounded shutdown. +- **E5 (ADR-0045, ADR-0046):** the strict TypeScript frontend with Vite, + Vitest, and Biome: the session tree, search, transcript, composer, and the + separate approvals bundle. + +Still open for the desktop: + +- a Linux build and run of the shell, and Linux evidence for the Unix-only + inspection and index branches; +- development panels (terminal tabs, task logs, and diffs), a settings + interface, and persisted chat settings; +- streaming and a push channel instead of polling; +- a recovery interface for an incomplete tail or a damaged journal, plus + `session.archive_requested` stop-and-archive and storage-use display; +- Git, MCP, skills, and memory interfaces; +- a native confirmation dialog for approvals, which would remove the webview + from the final decision; +- packaging, signing, and installers (Phase G); +- automatic repair of a corrupt index behind a valid header, and a protection + against two versions sharing one data root and rebuilding each other's index. ### Phase F: runtime skills, MCP, memories, compaction, and caches @@ -713,6 +823,29 @@ release readiness remain separate gates. ## Known cautions +- Build `crates/omgcode-desktop/ui/dist` before any Cargo command that includes + `omgcode-desktop`. Without it the build fails with `The frontendDist + configuration is set to "ui/dist" but this path doesn't exist`. +- Never run `tauri dev` or the shell without `--data-dir `. Without it + the shell uses the real per-user data directory. +- Two tests print `SKIPPED link assertions` and return on a host that cannot + create file symbolic links (error 1314): `a_symlinked_journal_is_rejected` + and `a_database_file_that_is_a_link_is_refused`. They did not run on the + Phase E Windows host; they ran in the Linux run. A privileged Windows run + has not executed them. +- A Linux login keyring can exist and still be locked, which fails every + credential suite with "an unlocked Secret Service default collection is + required". Check the collection's `Locked` property before a Linux run. +- A test fixture that creates its own data root must make it mode 0700 on + Unix. The checkpoint store refuses the default mode. +- A data root under the user's Temp directory inherits an ACL that the private + store refuses. Reset it before a manual run: + `icacls /inheritance:r /grant:r *:(OI)(CI)F`. +- The session index file carries a version. A binary with a different index + version deletes and rebuilds the index, so two versions sharing a data root + rebuild each other's index. Rebuild also fails on Windows while another + process has the database open. +- `.claude/` is untracked local tooling state. Do not commit it. - Linux CLI integration tests raced on inherited `flock` descriptors, producing `Busy` and mock-provider timeouts. The spawn gate in [testing standards](docs/testing-standards.md#isolation-and-concurrency) covers diff --git a/README.md b/README.md index 89a3aa5..628b878 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,11 @@ native workspace file broker is available through trusted CLI commands. A core turn/tool runtime and schema-v2 session format let chat offer the local LM Studio model read, list, approval-gated exact-edit, and approval-gated command tools, only for a workspace that enables `model_tools` and each tool's own -preferences. Model file creation, deletion, and renaming, a desktop interface, -and Git workflows remain planned. The trusted CLI `run` command starts one program for a workspace whose +preferences. Model file creation, deletion, and renaming, and Git workflows +remain planned. A prototype desktop shell (Tauri, with a strict TypeScript +frontend) browses and searches sessions, runs chat, and decides model-tool +approvals in a separate window; it is unpackaged and has run only on Windows. +The trusted CLI `run` command starts one program for a workspace whose `execute` preference is enabled. It uses an operator-declared toolchain profile, records each run in a run journal, and confines the process tree with Landlock and a seccomp socket filter on Linux or a per-workspace AppContainer @@ -50,9 +53,10 @@ directory grants. > declared origins into a private per-workspace cache. A selected cache root > is exposed read-only on Linux and Windows; Windows needs a read-execute > container grant, and Linux falls back to application storage when no root is -> selected. Provider profiles record connection shapes, and trusted -> single-use approval records prepare per-call model-tool consent; neither -> enables an adapter, login, or model tool. API keys can be stored in protected +> selected. Provider profiles record connection shapes and enable no adapter +> or login. Trusted single-use approval records authorize one exact model-tool +> call; the trusted CLI or the desktop approvals window can decide them. API +> keys can be stored in protected > OS storage (DPAPI on Windows, the Secret Service on Linux) and bound to a > profile, but no adapter reads them yet. Runs have memory, process-count, > CPU-time, and sampled disk-growth limits; the disk limit is not a filesystem @@ -71,8 +75,10 @@ Security takes priority when an optimization would weaken these boundaries. ## Current prototype -The workspace contains three Rust crates: `omgcode-core`, `omgcode-cli`, -and `omgcode-platform`. The CLI command is `omgcode`. It provides: +The workspace contains five Rust crates: `omgcode-core`, `omgcode-cli`, +`omgcode-platform`, `omgcode-app`, and `omgcode-desktop`. The CLI command is +`omgcode`. The desktop shell is the `omgcode-desktop` binary, with its +frontend in `crates/omgcode-desktop/ui`. The CLI provides: - `prompt`: print the compiled, read-only base prompt, version, and SHA-256 digest. - `capabilities`: report what this prototype implements and rejects. @@ -123,6 +129,16 @@ It has no create, delete, rename, Git, MCP, or network tool. New sessions use schema version 3; version 1 and 2 journals remain readable and writable with their original subsets. +The desktop shell is a prototype. It has a session tree grouped by workspace +folder, full-text search over a derived SQLite index, a paged transcript view, +chat that runs the same turn as `omgcode chat`, and an approvals window that +shows an exact reviewed request before it lets the operator decide. The webview +gets no authority: the Rust side authorizes every command, and no command +accepts a host path. The webview is still not a trusted computing base. It has +no packaging, streaming, settings interface, development panels, or recovery +interface, and it has not been run on Linux. See the +[desktop interface guide](docs/desktop-interface.md). + The platform crate checks opened journal handles, captures native directory identity for workspace registration, and implements handle-relative file operations. The broker applies the current registered workspace checks, but it @@ -209,9 +225,12 @@ check the server's configuration before sending sensitive text. pull, and push, with controlled remote access and credential handling. - **Development panels:** Terminal tabs, background task status and logs, and file and hunk diffs. -- **Session interface:** A searchable desktop session tree grouped by working - folder, with sorting and status. The current CLI stores versioned JSONL - journals and supports inspect, archive, and restore. +- **Session interface:** The prototype desktop shell has a searchable session + tree grouped by working folder, with sorting, archived and active views, and + status; it supports archive, restore, and interrupt. Recovery workflows, + storage-use display, and packaging remain planned. The CLI stores the + versioned JSONL journals and supports inspect, archive, and restore. See the + [desktop interface guide](docs/desktop-interface.md). - **MCP support:** Connect local stdio and remote Streamable HTTP servers for tools, resources, and prompt templates through core-owned permissions. See [MCP support](docs/mcp.md). @@ -262,15 +281,18 @@ explicit rather than being assumed to work identically across providers. authentication, permissions, file access, toolchain profiles, Git operations, task supervision, prompt assembly, context management, caching, skills, MCP, and scoped memories. -- **Desktop interface:** Tauri with a bundled TypeScript web interface. +- **Desktop interface:** Tauri with a bundled TypeScript web interface. A + prototype exists (`omgcode-desktop`); see the + [desktop interface guide](docs/desktop-interface.md). - **Execution backends:** Separate Windows and Linux sandbox implementations. - **Local storage:** Versioned JSONL session journals, archive/restore events, - a rebuildable folder/search index, settings, scoped memories, and referenced + a rebuildable SQLite folder and search index (implemented), settings, scoped memories, and referenced task artifacts. - **Credential handling:** Operating-system credential storage, accessed through narrow services in the Rust core. -The interface will use a limited command interface to the Rust core. Provider +The desktop prototype uses a limited command interface to the Rust core: 18 +commands, no host paths, and per-window permissions checked in Rust. Provider keys will stay out of frontend state, repository files, and task environments. ## Development tools @@ -332,7 +354,9 @@ cannot grant permissions. See [context management](docs/context-management.md) a 2. Resolve subscription integration eligibility and validate both login/usage paths. 3. Prove Windows/Linux isolation, representative toolchains, and process cleanup. 4. Extend the Rust core and build the desktop interface, session tree, and - remaining persistence and recovery workflows. + remaining persistence and recovery workflows. The first desktop prototype + (session tree, search, chat, and approvals) is implemented; recovery, + settings, streaming, development panels, and packaging remain. 5. Expand provider adapters and add streaming and core-authorized tool workflows. 6. Add visible instructions, token accounting, compaction, safe caching, skills, and project/global memories with boundary tests and efficiency measurements. diff --git a/crates/omgcode-app/Cargo.toml b/crates/omgcode-app/Cargo.toml new file mode 100644 index 0000000..16b7a2a --- /dev/null +++ b/crates/omgcode-app/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "omgcode-app" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +description = "Front-end-neutral application services shared by the OMGCode CLI and desktop shell" + +[dependencies] +omgcode-core = { path = "../omgcode-core" } +directories.workspace = true +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +time.workspace = true +uuid.workspace = true + +[dev-dependencies] +tempfile.workspace = true + +[lints] +workspace = true diff --git a/crates/omgcode-app/src/chat.rs b/crates/omgcode-app/src/chat.rs new file mode 100644 index 0000000..bf96f88 --- /dev/null +++ b/crates/omgcode-app/src/chat.rs @@ -0,0 +1,237 @@ +//! One chat turn against the selected local model, without any front end. +//! +//! This module performs no printing, no environment reads, no argument +//! parsing, and never exits the process. Whether the turn offers workspace +//! tools is decided from live settings by the core; this module grants no +//! authority. The settings store is opened and dropped inside its own steps and +//! is never held while a model request is in flight. + +mod output; +mod preflight; +mod text; +mod tools; + +use std::path::Path; + +use omgcode_core::context::DEFAULT_COMPACT_THRESHOLD; +use omgcode_core::prompt::{self, BASE_PROMPT, BASE_PROMPT_VERSION}; +use omgcode_core::provider::{LocalModelClient, LocalModelConfig}; +use omgcode_core::session::{RequestManifest, SessionJournal}; +use omgcode_core::turn::CancelToken; + +pub use self::output::ChatTurnOutput; +use crate::context::summary_output_tokens; +use crate::error::{AppError, ErrorKind}; +use crate::secrets::redact_known_secret; +use crate::tool_mode::{TOOL_SCHEMA_ESTIMATE_BYTES, ToolMode, select}; + +/// Selected model, budgets, and user-level preferences for chat turns. +/// +/// The settings carry no credential. They are user preferences and cannot +/// replace the compiled base prompt or grant any workspace authority. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ChatSettings { + /// A literal loopback HTTP URL with an explicit port and `/v1` path. + pub endpoint: String, + /// The model identifier already available to the selected server. + pub model: String, + /// Validated context capacity for the selected loaded model. + pub context_tokens: u64, + /// Output reserve for each model request. + pub max_output_tokens: u32, + /// User-level preferences, sent as untrusted-origin custom instructions. + pub instructions: String, + /// Compact before a turn when the conservative estimate reaches this value. + pub compact_threshold: u64, + /// Whether to compact at the effective trigger before a turn. + pub auto_compact: bool, +} + +impl ChatSettings { + /// Settings with the CLI's defaults for everything but the model and its context. + pub fn new(endpoint: impl Into, model: impl Into, context_tokens: u64) -> Self { + Self { + endpoint: endpoint.into(), + model: model.into(), + context_tokens, + max_output_tokens: 1024, + instructions: String::new(), + compact_threshold: DEFAULT_COMPACT_THRESHOLD, + auto_compact: false, + } + } +} + +/// The inputs of one chat turn. +/// +/// It has no `Debug` implementation because `token` is a credential. +pub struct ChatTurnInput<'a> { + /// The current user request. Known-token text is removed before use. + pub message: &'a str, + /// The model and budgets for this turn. + pub settings: &'a ChatSettings, + /// The optional local server token, used for the request header and for + /// removing the same text from everything recorded or sent. It is borrowed + /// for the call and never stored, logged, or serialized. + pub token: Option<&'a str>, +} + +/// Optional callbacks a front end can supply to a turn. +/// +/// Today the only hook delivers the cancellation token. Cancellation is +/// cooperative: the core checks it between rounds and tool calls, so it cannot +/// interrupt a provider request already in flight. The text-only path has no +/// cancellation point at all, so the hook is never called there. +#[derive(Default)] +pub struct ChatHooks<'a> { + /// Called once on the tool-enabled path, immediately after the turn + /// runtime is built and before the first model request. The callback runs + /// on the turn's thread and must not block; hand the token to another + /// thread and return. + pub on_cancel_token: Option<&'a mut dyn FnMut(CancelToken)>, +} + +/// The two validated model clients a turn uses. +/// +/// Building them validates the endpoint and token before any storage is +/// opened. The clients keep their own copy of the token header; they do not +/// implement `Debug` output of it. +pub struct ChatClients { + chat: LocalModelClient, + summary: LocalModelClient, +} + +impl ChatClients { + /// Validate `settings` and build the chat client and the summary client. + /// + /// Fails with `provider` when the endpoint, model budgets, or token are + /// unusable. No network request is made. + pub fn new(settings: &ChatSettings, token: Option<&str>) -> Result { + let chat = LocalModelClient::new( + LocalModelConfig { + base_url: settings.endpoint.clone(), + model: settings.model.clone(), + context_tokens: settings.context_tokens, + max_output_tokens: settings.max_output_tokens, + }, + // The client owns its header; the caller keeps one copy for redaction. + token.map(str::to_owned), + ) + .map_err(AppError::provider)?; + let summary = LocalModelClient::new( + LocalModelConfig { + base_url: settings.endpoint.clone(), + model: settings.model.clone(), + context_tokens: settings.context_tokens, + max_output_tokens: summary_output_tokens(settings.context_tokens), + }, + token.map(str::to_owned), + ) + .map_err(AppError::provider)?; + Ok(Self { chat, summary }) + } +} + +/// The pieces of one turn after secret redaction, shared by its steps. +struct Turn<'a> { + message: &'a str, + instructions: &'a str, + settings: &'a ChatSettings, + token: Option<&'a str>, + data_root: &'a Path, +} + +/// Run one chat turn, building the clients from the settings first. +/// +/// This is the whole turn for a caller that supplies only settings, a message, +/// and the optional token. See [`run_chat_turn_with_clients`] for the order of +/// checks and the errors. +pub fn run_chat_turn( + journal: &mut SessionJournal, + data_root: &Path, + input: &ChatTurnInput<'_>, + hooks: &mut ChatHooks<'_>, +) -> Result { + let clients = ChatClients::new(input.settings, input.token)?; + run_chat_turn_with_clients(journal, data_root, input, &clients, hooks) +} + +/// Run one chat turn with clients built earlier by [`ChatClients::new`]. +/// +/// Deterministic failures return before the turn starts: an archived session or +/// an incomplete previous turn (`session`), unreadable settings (`control`), +/// an unreachable context trigger without auto-compaction (`context`), and a +/// prompt that cannot be assembled (`prompt`). After the turn starts, a failed +/// provider request or runtime is recorded in the journal where the core can +/// do so, and an uncertain storage failure is reported, never papered over. +/// +/// The message and instructions are cleaned of the known token before use. The +/// token is used only for redaction and is never part of any returned error. +pub fn run_chat_turn_with_clients( + journal: &mut SessionJournal, + data_root: &Path, + input: &ChatTurnInput<'_>, + clients: &ChatClients, + hooks: &mut ChatHooks<'_>, +) -> Result { + let settings = input.settings; + let message = redact_known_secret(input.message, input.token); + let instructions = redact_known_secret(&settings.instructions, input.token); + let turn = Turn { + message: &message, + instructions: &instructions, + settings, + token: input.token, + data_root, + }; + if journal.snapshot().archived { + return Err(AppError::new( + ErrorKind::Session, + "Restore the archived session before chatting", + )); + } + if journal.snapshot().active_turn.is_some() { + return Err(AppError::new( + ErrorKind::Session, + tools::ACTIVE_TURN_MESSAGE, + )); + } + let mode = select(data_root, journal)?; + let tools_enabled = matches!(mode, ToolMode::Enabled { .. }); + let tool_extra = if tools_enabled { + TOOL_SCHEMA_ESTIMATE_BYTES + } else { + 0 + }; + let meter = + preflight::preflight_context(journal, &turn, &clients.summary, tool_extra, tools_enabled)?; + let manifest = RequestManifest { + base_prompt: BASE_PROMPT.to_owned(), + prompt_version: BASE_PROMPT_VERSION.to_owned(), + prompt_sha256: prompt::base_prompt_sha256(), + custom_instructions: instructions.clone(), + model: settings.model.clone(), + base_url: settings.endpoint.clone(), + context_tokens: settings.context_tokens, + max_output_tokens: settings.max_output_tokens, + tool_schema_version: None, + tools: None, + }; + // Live settings decide whether this turn offers the workspace tools. + match mode { + ToolMode::Enabled { workspace_id } => tools::run( + journal, + workspace_id, + &clients.chat, + &turn, + manifest, + meter, + hooks, + ) + .map(ChatTurnOutput::tools), + ToolMode::Disabled { reason } => { + text::run(journal, &clients.chat, &turn, reason, manifest, meter) + .map(ChatTurnOutput::text) + } + } +} diff --git a/crates/omgcode-app/src/chat/output.rs b/crates/omgcode-app/src/chat/output.rs new file mode 100644 index 0000000..b067aaa --- /dev/null +++ b/crates/omgcode-app/src/chat/output.rs @@ -0,0 +1,185 @@ +//! The result of one completed chat turn. + +use omgcode_core::provider::ModelReply; +use serde::ser::Error as _; +use serde::{Serialize, Serializer}; +use serde_json::{Map, Value, to_value}; + +use crate::context::ContextMeter; + +/// Assistant text from a tool-enabled turn. It remains untrusted model output. +#[derive(Clone, Debug, Serialize)] +pub(crate) struct ToolTurnReply { + pub(crate) content: String, + /// `stop`, or `length` when the token limit cut the reply short. + pub(crate) finish_reason: String, +} + +/// Bounded counters for a tool-enabled turn. +#[derive(Clone, Debug, Serialize)] +pub(crate) struct ToolTurnSummary { + pub(crate) mode: &'static str, + pub(crate) workspace_id: String, + pub(crate) rounds: usize, + pub(crate) tool_calls: usize, + pub(crate) tool_bytes: u64, + pub(crate) withheld_tool_results: usize, +} + +/// Summary of one completed tool-enabled turn. +#[derive(Clone, Debug, Serialize)] +pub(crate) struct ToolTurnOutput { + pub(crate) reply: ToolTurnReply, + pub(crate) model_tools: ToolTurnSummary, + pub(crate) context: ContextMeter, +} + +/// Summary of one completed text-only turn. +#[derive(Clone, Debug)] +pub(crate) struct TextTurnOutput { + pub(crate) reply: ModelReply, + pub(crate) reason: &'static str, + pub(crate) withheld_tool_results: usize, + pub(crate) context: ContextMeter, +} + +impl Serialize for TextTurnOutput { + /// Build the same key-ordered object the CLI printed before the extraction. + fn serialize(&self, serializer: S) -> Result { + let mut model_tools = Map::new(); + model_tools.insert("mode".to_owned(), Value::from("disabled")); + model_tools.insert("reason".to_owned(), Value::from(self.reason)); + model_tools.insert( + "withheld_tool_results".to_owned(), + Value::from(self.withheld_tool_results), + ); + let mut object = Map::new(); + object.insert( + "reply".to_owned(), + to_value(&self.reply).map_err(S::Error::custom)?, + ); + object.insert("model_tools".to_owned(), Value::Object(model_tools)); + object.insert( + "context".to_owned(), + to_value(&self.context).map_err(S::Error::custom)?, + ); + Value::Object(object).serialize(serializer) + } +} + +/// The two turn shapes behind [`ChatTurnOutput`]. +#[derive(Clone, Debug)] +enum Shape { + Tools(ToolTurnOutput), + Text(TextTurnOutput), +} + +/// One completed chat turn: the reply, the tool outcome, and the context meter. +/// +/// It serializes to the object the trusted CLI prints after the session +/// locator. Typed accessors let another front end avoid parsing that JSON. The +/// reply is untrusted model output. +#[derive(Clone, Debug)] +pub struct ChatTurnOutput { + shape: Shape, +} + +impl ChatTurnOutput { + pub(crate) fn tools(output: ToolTurnOutput) -> Self { + Self { + shape: Shape::Tools(output), + } + } + + pub(crate) fn text(output: TextTurnOutput) -> Self { + Self { + shape: Shape::Text(output), + } + } + + /// The assistant reply text. It is untrusted model output. + pub fn reply(&self) -> &str { + match &self.shape { + Shape::Tools(output) => &output.reply.content, + Shape::Text(output) => &output.reply.content, + } + } + + /// The provider finish reason: `stop`, or `length` when the limit cut the reply. + pub fn finish_reason(&self) -> &str { + match &self.shape { + Shape::Tools(output) => &output.reply.finish_reason, + Shape::Text(output) => &output.reply.finish_reason, + } + } + + /// Whether this turn offered the workspace tools. + pub fn tools_enabled(&self) -> bool { + matches!(self.shape, Shape::Tools(_)) + } + + /// Why a text-only turn did not offer tools; `None` when tools were offered. + pub fn disabled_reason(&self) -> Option<&'static str> { + match &self.shape { + Shape::Tools(_) => None, + Shape::Text(output) => Some(output.reason), + } + } + + /// The registered workspace whose tools were offered, as text. + pub fn workspace_id(&self) -> Option<&str> { + match &self.shape { + Shape::Tools(output) => Some(&output.model_tools.workspace_id), + Shape::Text(_) => None, + } + } + + /// Model requests made; `None` for a text-only turn, which does not count them. + pub fn rounds(&self) -> Option { + match &self.shape { + Shape::Tools(output) => Some(output.model_tools.rounds), + Shape::Text(_) => None, + } + } + + /// Tool calls dispatched; `None` for a text-only turn. + pub fn tool_calls(&self) -> Option { + match &self.shape { + Shape::Tools(output) => Some(output.model_tools.tool_calls), + Shape::Text(_) => None, + } + } + + /// Aggregate tool-message bytes; `None` for a text-only turn. + pub fn tool_bytes(&self) -> Option { + match &self.shape { + Shape::Tools(output) => Some(output.model_tools.tool_bytes), + Shape::Text(_) => None, + } + } + + /// Saved tool results replaced by a withheld notice when the turn started. + pub fn withheld_tool_results(&self) -> usize { + match &self.shape { + Shape::Tools(output) => output.model_tools.withheld_tool_results, + Shape::Text(output) => output.withheld_tool_results, + } + } + + /// The conservative pre-turn context accounting. + pub fn context(&self) -> &ContextMeter { + match &self.shape { + Shape::Tools(output) => &output.context, + Shape::Text(output) => &output.context, + } + } +} + +impl Serialize for ChatTurnOutput { + fn serialize(&self, serializer: S) -> Result { + match &self.shape { + Shape::Tools(output) => output.serialize(serializer), + Shape::Text(output) => output.serialize(serializer), + } + } +} diff --git a/crates/omgcode-app/src/chat/preflight.rs b/crates/omgcode-app/src/chat/preflight.rs new file mode 100644 index 0000000..5db2145 --- /dev/null +++ b/crates/omgcode-app/src/chat/preflight.rs @@ -0,0 +1,140 @@ +//! The pre-turn context trigger and visible meter. + +use std::path::Path; + +use omgcode_core::context::{ContextBudget, estimate_history_input_tokens}; +use omgcode_core::prompt::{self, BASE_PROMPT, ConversationMessage, ConversationRole, PromptError}; +use omgcode_core::provider::LocalModelClient; +use omgcode_core::session::SessionJournal; +use omgcode_core::turn::replay_active; + +use super::Turn; +use crate::context::{ContextMeter, compact_journal, summary_output_tokens}; +use crate::error::{AppError, ErrorKind}; +use crate::tool_mode::tool_replay_allowed; + +/// Apply the context trigger before a turn and return the visible meter. +/// +/// A zero threshold is a `configuration` error. Reaching the trigger without +/// auto-compaction is a `context` error that names the operator's options. +/// With auto-compaction, the summary client compacts the journal and the +/// estimate is recomputed from live settings. No control store is held across +/// the summarizer requests. +pub(super) fn preflight_context( + journal: &mut SessionJournal, + turn: &Turn<'_>, + summary_client: &LocalModelClient, + fixed_extra_bytes: usize, + tools_enabled: bool, +) -> Result { + let settings = turn.settings; + let (data_root, token) = (turn.data_root, turn.token); + if settings.compact_threshold == 0 { + return Err(AppError::new( + ErrorKind::Configuration, + "The compaction threshold must be a positive token count", + )); + } + let budget = ContextBudget { + threshold: settings.compact_threshold, + context_tokens: settings.context_tokens, + max_output_tokens: settings.max_output_tokens, + }; + // Summary chunks are sized from the summary request's own output reserve. + let summary_budget = ContextBudget { + threshold: u64::MAX, + context_tokens: settings.context_tokens, + max_output_tokens: summary_output_tokens(settings.context_tokens), + }; + let (mut estimate, mut assembly_blocked) = estimate_with_user( + journal, + turn, + fixed_extra_bytes, + replay_allowed_now(journal, data_root, tools_enabled), + )?; + let mut summarizer_calls = None; + if budget.should_compact(estimate) || assembly_blocked { + if !settings.auto_compact { + let reason = if assembly_blocked { + "Active history exceeds the prompt assembly limits".to_owned() + } else { + format!( + "The conservative input estimate ({estimate} tokens) reaches the compaction trigger ({})", + budget.trigger() + ) + }; + return Err(AppError::new( + ErrorKind::Context, + format!("{reason}. Use session compact or rerun chat with --auto-compact."), + )); + } + let outcome = compact_journal(journal, data_root, summary_client, token, summary_budget)?; + summarizer_calls = Some(outcome.calls); + // Settings can change during the summarizer requests, so read the + // replay authority again for the compacted history. + (estimate, assembly_blocked) = estimate_with_user( + journal, + turn, + fixed_extra_bytes, + replay_allowed_now(journal, data_root, tools_enabled), + )?; + if budget.should_compact(estimate) || assembly_blocked { + return Err(AppError::new( + ErrorKind::Context, + "Compaction did not reduce the context below the trigger and assembly limits", + )); + } + } + Ok(ContextMeter::new( + journal, + budget, + settings.max_output_tokens, + settings.auto_compact, + estimate, + summarizer_calls, + )) +} + +/// Whether the next request may replay saved tool results, read from live +/// settings at each call. Text-only chat never replays them; a tool turn +/// replays them only under live `model_tools` and `read`, as the runtime +/// does. Unreadable settings fail closed to the withheld form. +fn replay_allowed_now(journal: &SessionJournal, data_root: &Path, tools_enabled: bool) -> bool { + tools_enabled + && tool_replay_allowed( + data_root, + journal.snapshot().workspace_id, + journal.schema_version(), + ) + .unwrap_or(false) +} + +/// The input-only estimate for the next request, and whether its active +/// history plus the pending user message exceeds a prompt-assembly limit that +/// compaction can relieve (message count or total assembled bytes). +fn estimate_with_user( + journal: &SessionJournal, + turn: &Turn<'_>, + fixed_extra_bytes: usize, + tool_results_allowed: bool, +) -> Result<(u64, bool), AppError> { + // Estimate the history this mode will send: saved tool results, and a + // summary built from them, are withheld without live tool authority. + let (mut history, _) = replay_active(journal, tool_results_allowed); + history.push(ConversationMessage { + role: ConversationRole::User, + content: turn.message.to_owned(), + }); + let estimate = estimate_history_input_tokens( + BASE_PROMPT.len(), + turn.instructions, + &history, + fixed_extra_bytes, + ) + .map_err(|error| AppError::new(ErrorKind::Context, error.to_string()))?; + let assembly_blocked = matches!( + prompt::assemble(turn.instructions, &history), + Err(PromptError::TooManyHistoryMessages | PromptError::AssembledPromptTooLarge) + ); + Ok((estimate, assembly_blocked)) +} diff --git a/crates/omgcode-app/src/chat/text.rs b/crates/omgcode-app/src/chat/text.rs new file mode 100644 index 0000000..cc0bc94 --- /dev/null +++ b/crates/omgcode-app/src/chat/text.rs @@ -0,0 +1,101 @@ +//! The text-only chat turn. +//! +//! Text-only chat has no model file-read authority and no cancellation point: +//! the turn is one provider request that cannot be interrupted once started. + +use omgcode_core::prompt::{self, ConversationMessage, ConversationRole}; +use omgcode_core::provider::LocalModelClient; +use omgcode_core::session::{MessageRole, RequestManifest, SessionError, SessionJournal}; +use omgcode_core::turn::replay_active; + +use super::Turn; +use super::output::TextTurnOutput; +use crate::context::ContextMeter; +use crate::error::{AppError, ErrorKind}; +use crate::secrets::redact_known_secret; + +/// Largest assistant text kept resumable within the journal and prompt limits. +const MAX_REPLY_BYTES: usize = 16 * 1024; + +/// Run one text-only turn. Deterministic failures return before the turn starts; +/// uncertain storage state after a failed write is preserved, not overwritten. +pub(super) fn run( + journal: &mut SessionJournal, + client: &LocalModelClient, + turn: &Turn<'_>, + reason: &'static str, + manifest: RequestManifest, + context: ContextMeter, +) -> Result { + let token = turn.token; + // Text-only chat has no model file-read authority, so saved tool results, + // and a summary built from them, are withheld rather than sent again. + let (mut history, withheld_tool_results) = replay_active(journal, false); + for message in &mut history { + message.content = redact_known_secret(&message.content, token); + } + history.push(ConversationMessage { + role: ConversationRole::User, + content: turn.message.to_owned(), + }); + let messages = prompt::assemble(turn.instructions, &history) + .map_err(|error| AppError::new(ErrorKind::Prompt, error.to_string()))?; + journal + .preflight_request(turn.message, &manifest) + .map_err(AppError::session)?; + let request_id = journal.start_turn().map_err(AppError::session)?; + journal + .record_message(MessageRole::User, turn.message) + .map_err(AppError::session)?; + journal + .record_manifest(request_id, manifest) + .map_err(AppError::session)?; + let mut reply = match client.complete(&messages) { + Ok(reply) => reply, + Err(error) => { + journal + .fail_turn(request_id, "provider_error") + .map_err(|_| { + AppError::new( + ErrorKind::Persistence, + "Provider failed and failure could not be recorded", + ) + })?; + return Err(AppError::provider(error)); + } + }; + reply.content = redact_known_secret(&reply.content, token); + // Keep every accepted reply resumable within the journal and prompt limits. + // The wire response limit also covers protocol metadata, so it is larger. + if reply.content.len() > MAX_REPLY_BYTES { + journal + .fail_turn(request_id, "response_too_large") + .map_err(AppError::session)?; + return Err(AppError::new( + ErrorKind::Provider, + "Assistant text exceeds the 16 KiB session message limit", + )); + } + if let Err(error) = journal.record_message(MessageRole::Assistant, &reply.content) { + if matches!( + error, + SessionError::LimitReached | SessionError::InvalidValue(_) + ) { + journal + .fail_turn(request_id, "response_too_large") + .map_err(AppError::session)?; + } + // Failed writes/syncs can have changed storage. Do not overwrite that + // uncertain state with a fabricated terminal event or an automatic retry. + return Err(AppError::session(error)); + } + journal + .complete_turn(request_id) + .map_err(AppError::session)?; + Ok(TextTurnOutput { + reply, + reason, + withheld_tool_results, + context, + }) +} diff --git a/crates/omgcode-app/src/chat/tools.rs b/crates/omgcode-app/src/chat/tools.rs new file mode 100644 index 0000000..f47cda6 --- /dev/null +++ b/crates/omgcode-app/src/chat/tools.rs @@ -0,0 +1,267 @@ +//! The tool-enabled chat turn. +//! +//! Authority comes from the live settings preference, rechecked by the core +//! runtime before every tool call, and each call stays inside the selected +//! workspace. The edit and command tools also need a trusted single-use +//! approval, which the core checks; nothing here grants or widens it. + +use std::time::Duration; + +use omgcode_core::policy::WorkspaceId; +use omgcode_core::prompt::ModelMessage; +use omgcode_core::provider::{LocalModelClient, LocalToolModel, ProviderError}; +use omgcode_core::session::{RequestManifest, SessionJournal}; +use omgcode_core::turn::{ + ModelError, ToolModel, ToolModelReply, ToolModelRequest, TurnError, TurnLimits, TurnReport, + TurnRuntime, +}; +use serde_json::Value; + +use super::output::{ToolTurnOutput, ToolTurnReply, ToolTurnSummary}; +use super::{ChatHooks, Turn}; +use crate::context::ContextMeter; +use crate::error::{AppError, ErrorKind}; +use crate::secrets::redact_known_secret; + +/// Cooperative deadline for one tool-enabled chat turn. +/// +/// Each local model request may take up to 30 seconds, and a turn makes at most +/// four requests, so the 30-second library default would stop ordinary turns. +const CHAT_TURN_DEADLINE: Duration = Duration::from_secs(120); + +/// Runtime limits for tool-enabled chat: library maxima with a chat deadline. +fn chat_limits() -> TurnLimits { + TurnLimits { + deadline: CHAT_TURN_DEADLINE, + ..TurnLimits::default() + } +} + +/// Run one tool-enabled turn through the core runtime. +/// +/// `hooks.on_cancel_token` is called once, right after the runtime is built +/// and before the first model request. +pub(super) fn run( + journal: &mut SessionJournal, + workspace_id: WorkspaceId, + client: &LocalModelClient, + turn: &Turn<'_>, + manifest: RequestManifest, + context: ContextMeter, + hooks: &mut ChatHooks<'_>, +) -> Result { + let token = turn.token; + let mut model = RedactingModel { + inner: LocalToolModel::new(client), + token, + secret_in_tool_call: false, + }; + // Tool results are recorded before the next model request, so they need + // their own redaction; the model wrapper sees them only afterwards. + let redact_tool_text = |text: &str| redact_known_secret(text, token); + let report: TurnReport = TurnRuntime::new(journal, turn.data_root, workspace_id, chat_limits()) + .and_then(|runtime| { + if let Some(hook) = hooks.on_cancel_token.as_deref_mut() { + hook(runtime.cancel_token()); + } + runtime.with_tool_text_filter(&redact_tool_text).run( + &mut model, + turn.message, + turn.instructions, + manifest, + ) + }) + .map_err(|error| { + if model.secret_in_tool_call { + return AppError::new( + ErrorKind::Provider, + "The model returned a tool call containing the configured server token; it was not recorded or run", + ); + } + turn_error(error, model.inner.last_error()) + })?; + Ok(ToolTurnOutput { + reply: ToolTurnReply { + content: report.reply, + finish_reason: report.finish_reason, + }, + model_tools: ToolTurnSummary { + mode: "enabled", + workspace_id: workspace_id.to_string(), + rounds: report.rounds, + tool_calls: report.tool_calls, + tool_bytes: report.tool_bytes, + withheld_tool_results: report.withheld_tool_results, + }, + context, + }) +} + +/// Remove a known local server token from text sent to and received from the model. +/// +/// A tool call that contains the token is refused rather than redacted, because +/// editing its arguments could change the requested path. The runtime records +/// calls before any result filter runs, so the refusal happens here. +struct RedactingModel<'a> { + inner: LocalToolModel<'a>, + token: Option<&'a str>, + secret_in_tool_call: bool, +} + +impl ToolModel for RedactingModel<'_> { + fn complete(&mut self, request: ToolModelRequest<'_>) -> Result { + let messages: Vec = request + .messages + .iter() + .map(|message| ModelMessage { + role: message.role, + content: redact_known_secret(&message.content, self.token), + }) + .collect(); + let mut reply = self.inner.complete(ToolModelRequest { + messages: &messages, + tools: request.tools, + })?; + if let Some(token) = self.token.filter(|token| !token.is_empty()) + && reply + .tool_calls + .iter() + .any(|call| contains_secret(call, token, true)) + { + self.secret_in_tool_call = true; + return Err(ModelError::InvalidResponse); + } + reply.content = redact_known_secret(&reply.content, self.token); + Ok(reply) + } +} + +/// Report whether any key or string in a raw tool-call value contains `token`. +/// +/// Tool-call arguments arrive as a JSON-encoded string, so a string that parses +/// as JSON is searched once more after decoding. Decoding is not repeated +/// inside that nested value. +fn contains_secret(value: &Value, token: &str, decode_nested: bool) -> bool { + match value { + Value::String(text) => { + text.contains(token) + || (decode_nested + && serde_json::from_str::(text) + .is_ok_and(|nested| contains_secret(&nested, token, false))) + } + Value::Array(items) => items + .iter() + .any(|item| contains_secret(item, token, decode_nested)), + Value::Object(fields) => fields + .iter() + .any(|(key, item)| key.contains(token) || contains_secret(item, token, decode_nested)), + Value::Null | Value::Bool(_) | Value::Number(_) => false, + } +} + +/// Map a runtime failure to a stable application error without echoing model text. +fn turn_error(error: TurnError, provider: Option) -> AppError { + match error { + TurnError::Model(_) => provider.map_or_else( + || AppError::new(ErrorKind::Provider, "Local model request failed"), + AppError::provider, + ), + TurnError::ToolDenied(_) => AppError::new( + ErrorKind::Permission, + "A model tool call was denied by the current workspace preferences", + ), + TurnError::InvalidToolCall(error) => AppError::new( + ErrorKind::ToolCall, + format!("The model returned an invalid tool call: {error}"), + ), + TurnError::Limit(limit) => AppError::new( + ErrorKind::ToolLimit, + format!("Turn limit exceeded: {limit}"), + ), + TurnError::Session(error) => AppError::session(error), + TurnError::Prompt(error) => AppError::new(ErrorKind::Prompt, error.to_string()), + TurnError::Archived => AppError::new( + ErrorKind::Session, + "Restore the archived session before chatting", + ), + TurnError::ActiveTurn => AppError::new(ErrorKind::Session, ACTIVE_TURN_MESSAGE), + other => AppError::new(ErrorKind::Turn, other.to_string()), + } +} + +/// The message for a session whose previous turn never reached a terminal event. +pub(super) const ACTIVE_TURN_MESSAGE: &str = "The previous turn is incomplete; inspect it, then use session interrupt to mark it failed without retrying"; + +#[cfg(test)] +mod tests { + use omgcode_core::session::SessionError; + use omgcode_core::turn::TurnLimit; + + use super::*; + + fn pair(error: AppError) -> (&'static str, String) { + (error.code(), error.into_message()) + } + + #[test] + fn model_failures_keep_the_provider_message_or_the_generic_one() { + assert_eq!( + pair(turn_error( + TurnError::Model(ModelError::InvalidResponse), + Some(ProviderError::Transport) + )), + ("provider", "local model transport failed".to_owned()) + ); + assert_eq!( + pair(turn_error( + TurnError::Model(ModelError::InvalidResponse), + None + )), + ("provider", "Local model request failed".to_owned()) + ); + } + + #[test] + fn runtime_failures_map_to_the_published_codes_and_messages() { + assert_eq!( + pair(turn_error(TurnError::Archived, None)), + ( + "session", + "Restore the archived session before chatting".to_owned() + ) + ); + assert_eq!( + pair(turn_error(TurnError::ActiveTurn, None)), + ("session", ACTIVE_TURN_MESSAGE.to_owned()) + ); + assert_eq!( + pair(turn_error(TurnError::Limit(TurnLimit::Rounds), None)), + ( + "tool_limit", + "Turn limit exceeded: model round limit".to_owned() + ) + ); + assert_eq!( + pair(turn_error(TurnError::Cancelled, None)), + ("turn", "turn was cancelled".to_owned()) + ); + assert_eq!( + pair(turn_error( + TurnError::Session(SessionError::LimitReached), + None + )), + ("session", SessionError::LimitReached.to_string()) + ); + } + + #[test] + fn secrets_are_found_in_keys_values_and_nested_arguments() { + let call = serde_json::json!({ + "id": "c1", + "function": {"name": "read", "arguments": "{\"path\":\"has-\\u0073ecret-9\"}"} + }); + assert!(contains_secret(&call, "secret-9", true)); + assert!(!contains_secret(&call, "secret-9", false)); + assert!(!contains_secret(&call, "other", true)); + } +} diff --git a/crates/omgcode-app/src/context.rs b/crates/omgcode-app/src/context.rs new file mode 100644 index 0000000..75c7da1 --- /dev/null +++ b/crates/omgcode-app/src/context.rs @@ -0,0 +1,210 @@ +//! Bounded conversation compaction and the visible context meter. +//! +//! The core owns the cutoff, journal event, and summary validation. This module +//! supplies the local-model summarizer and applies the configured secret +//! redaction before the summary is recorded or shown. Summaries are untrusted +//! evidence and grant no authority. + +use std::path::Path; + +use omgcode_core::context::{ + COMPACTION_INSTRUCTIONS, CompactionLimits, CompactionOutcome, ContextBudget, ContextError, + MAX_SUMMARY_BYTES, SummaryReply, compact, +}; +use omgcode_core::prompt::{self, ConversationMessage}; +use omgcode_core::provider::LocalModelClient; +use omgcode_core::session::SessionJournal; +use serde::Serialize; + +use crate::error::{AppError, ErrorKind}; +use crate::secrets::redact_known_secret; +use crate::tool_mode::tool_replay_allowed; + +/// Most output tokens reserved for one summary request. +const MAX_SUMMARY_OUTPUT_TOKENS: u64 = 2048; + +/// Output reserve for an automatic summary request: a quarter of the context, +/// at most 2048 tokens and at least one. +pub fn summary_output_tokens(context_tokens: u64) -> u32 { + u32::try_from((context_tokens / 4).clamp(1, MAX_SUMMARY_OUTPUT_TOKENS)).unwrap_or(1) +} + +/// Compact the active context with the selected local model. +/// +/// `summary_budget` sizes the summarizer chunks; its `max_output_tokens` must +/// be the summary client's output reserve. Live `model_tools` and `read` +/// settings for the session's workspace are read before the summarizer input +/// is built and again before each request that carries tool-derived content; +/// a withdrawal stops compaction with a `permission` error and records nothing. +/// Unreadable settings fail closed: no tool data reaches the summarizer. Other +/// failures are `context`. `token` is removed from summarizer input and output. +pub fn compact_journal( + journal: &mut SessionJournal, + data_root: &Path, + client: &LocalModelClient, + token: Option<&str>, + summary_budget: ContextBudget, +) -> Result { + let model = client.model().to_owned(); + let workspace = journal.snapshot().workspace_id; + let schema_version = journal.schema_version(); + compact( + journal, + CompactionLimits { + max_chunk_bytes: summary_budget.summarizer_chunk_bytes(), + max_summary_bytes: MAX_SUMMARY_BYTES, + }, + model, + // Unreadable settings fail closed: no tool data reaches the summarizer. + || tool_replay_allowed(data_root, workspace, schema_version).unwrap_or(false), + |history: &[ConversationMessage]| { + let redacted: Vec = history + .iter() + .map(|message| ConversationMessage { + role: message.role, + content: redact_known_secret(&message.content, token), + }) + .collect(); + let messages = prompt::assemble(COMPACTION_INSTRUCTIONS, &redacted) + .map_err(|_| ContextError::TooLarge)?; + let reply = client.complete(&messages).map_err(ContextError::Provider)?; + let usage = reply.usage.as_ref(); + Ok(SummaryReply { + text: redact_known_secret(&reply.content, token), + prompt_tokens: usage.and_then(|usage| usage.prompt_tokens), + completion_tokens: usage.and_then(|usage| usage.completion_tokens), + }) + }, + ) + .map_err(|error| match error { + ContextError::AuthorityWithdrawn => AppError::new(ErrorKind::Permission, error.to_string()), + error => AppError::new(ErrorKind::Context, error.to_string()), + }) +} + +/// Visible, conservative context accounting for one chat turn. +#[derive(Clone, Debug, Serialize)] +pub struct ContextMeter { + estimated_input_tokens: u64, + context_tokens: u64, + max_output_tokens: u32, + effective_trigger: u64, + auto_compaction: bool, + estimate_scope: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + compaction: Option, +} + +impl ContextMeter { + /// Build the meter from a finished pre-turn estimate and the active journal. + pub(crate) fn new( + journal: &SessionJournal, + budget: ContextBudget, + max_output_tokens: u32, + auto_compaction: bool, + estimate: u64, + summarizer_calls: Option, + ) -> Self { + let compaction = journal + .snapshot() + .compaction + .as_ref() + .map(|record| CompactionMeter { + compacted_messages: record.compacted_messages, + retained_messages: u64::try_from(journal.snapshot().messages.len()) + .unwrap_or(u64::MAX) + .saturating_sub(record.compacted_messages), + summarizer_calls, + summary_sha256: record.summary_sha256.clone(), + }); + Self { + estimated_input_tokens: estimate, + context_tokens: budget.context_tokens, + max_output_tokens, + effective_trigger: budget.trigger(), + auto_compaction, + estimate_scope: "pre_turn_conservative", + compaction, + } + } + + /// The conservative input estimate for the turn, in tokens. + pub fn estimated_input_tokens(&self) -> u64 { + self.estimated_input_tokens + } + + /// The validated context capacity of the selected model. + pub fn context_tokens(&self) -> u64 { + self.context_tokens + } + + /// The output reserve for the turn. + pub fn max_output_tokens(&self) -> u32 { + self.max_output_tokens + } + + /// The estimate at which compaction triggers. + pub fn effective_trigger(&self) -> u64 { + self.effective_trigger + } + + /// Whether compaction before a turn was enabled. + pub fn auto_compaction(&self) -> bool { + self.auto_compaction + } + + /// The fixed label of what the estimate covers. + pub fn estimate_scope(&self) -> &'static str { + self.estimate_scope + } + + /// The active compaction boundary, when the session has one. + pub fn compaction(&self) -> Option<&CompactionMeter> { + self.compaction.as_ref() + } +} + +/// The active compaction boundary and summary identity. +#[derive(Clone, Debug, Serialize)] +pub struct CompactionMeter { + compacted_messages: u64, + retained_messages: u64, + #[serde(skip_serializing_if = "Option::is_none")] + summarizer_calls: Option, + summary_sha256: String, +} + +impl CompactionMeter { + /// Journal messages now represented by the summary. + pub fn compacted_messages(&self) -> u64 { + self.compacted_messages + } + + /// Journal messages retained verbatim after the boundary. + pub fn retained_messages(&self) -> u64 { + self.retained_messages + } + + /// Summarizer calls made during this turn's preflight, if it compacted. + pub fn summarizer_calls(&self) -> Option { + self.summarizer_calls + } + + /// Digest of the active summary text. + pub fn summary_sha256(&self) -> &str { + &self.summary_sha256 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_summary_reserve_is_a_quarter_of_the_context_within_bounds() { + assert_eq!(summary_output_tokens(0), 1); + assert_eq!(summary_output_tokens(3), 1); + assert_eq!(summary_output_tokens(400), 100); + assert_eq!(summary_output_tokens(1_000_000), 2048); + } +} diff --git a/crates/omgcode-app/src/desktop.rs b/crates/omgcode-app/src/desktop.rs new file mode 100644 index 0000000..a798e9e --- /dev/null +++ b/crates/omgcode-app/src/desktop.rs @@ -0,0 +1,196 @@ +//! The front-end-neutral desktop service (ADR-0044, ADR-0045, ADR-0046). +//! +//! [`DesktopService`] is what a thin shell adapter calls, one method per +//! command, from blocking tasks. It grants no authority. Every decision that +//! matters (workspace preferences, tool approvals, checkpointed edits, +//! confinement, journal validation) is made by `omgcode-core`; this module +//! orders calls to core, bounds them, and shapes their results for the +//! interface. +//! +//! # What the service never does +//! +//! - It accepts no filesystem path from a caller. Sessions are addressed by +//! UUID, workspaces by their registered identifier, approvals by identifier. +//! A journal path is resolved only through `SessionIndex::journal_path`. +//! - It returns no journal path and no absolute path except workspace folder +//! display text, which is escaped by core's `display_safe_line`. +//! - It never returns, stores in a response, or logs the local server token. +//! The token is read for one turn, held in a private type with a redacted +//! `Debug`, removed from every recorded and returned message, and dropped +//! when the turn thread ends. +//! +//! # State and locks +//! +//! The service state is shared by the service and by each running chat turn's +//! thread through one `Arc`. It holds: +//! +//! | field | guards | +//! | --- | --- | +//! | `index` | the one `SessionIndex` connection and its refresh bookkeeping | +//! | `turns` | the table of chat turns, their cancel tokens and thread handles | +//! | `reviews` | outstanding single-use approval review tokens | +//! | `pending_cache` | an atomic copy of the last pending-approval count read | +//! +//! **Lock order** when two are ever needed: `turns`, then `index`, then +//! `reviews`. The code takes one at a time. No service lock and no open +//! control store is held across provider I/O, a chat turn, a journal +//! inspection, a thread join, or a sleep. The one deliberate exception is the +//! `index` lock during a refresh: a refresh needs `&mut SessionIndex`, so it +//! holds the lock for at most two seconds plus one chunk of 200 journal +//! inspections. A poisoned lock never panics and is never ignored: the call +//! returns `DesktopError` code `internal`. +//! +//! # Chat turns +//! +//! `chat_send` validates everything that can be checked without running the +//! turn, reserves a slot in the table under the `turns` lock, and starts one +//! named thread (`omgcode-turn`). The thread owns the journal handle, the +//! clients, and the token for the whole turn. It opens the journal, runs the +//! turn, drops the journal (which releases the writer lock), refreshes that +//! one session in the index, and only then records the outcome in its slot. It +//! does not hold the `turns` lock while the turn runs. At most two turns run at +//! once. +//! +//! The slot keeps the thread's `JoinHandle`. `chat_status`, `chat_send`, and +//! the session commands reap finished threads: they take the handle out of the +//! slot under the lock, join it after releasing the lock, and record a thread +//! that panicked as `failed` with `internal`. Finished results stay until the +//! next `chat_send` for that session; at most 64 finished entries are kept and +//! the oldest is evicted first. +//! +//! Cancellation is cooperative. The tool-enabled path hands its `CancelToken` +//! to the slot; the text-only path has no cancellation point, so a cancel +//! request on it changes nothing and the status stays `running`. +//! +//! # Shutdown +//! +//! [`DesktopService::shutdown`] requests cancellation of every running turn +//! and polls `JoinHandle::is_finished` until the grace period ends. A provider +//! request in flight cannot be interrupted, so a turn can outlast the grace +//! period. Shutdown then returns without waiting; the abandoned thread leaves +//! its journal with an open turn, which the operator can close later with the +//! interrupt command or the trusted CLI. After shutdown no new turn starts. + +mod approvals; +mod chat; +mod error; +mod review_tokens; +mod sessions; +mod state; +mod turns; +mod wire; +mod workspaces; + +use std::path::PathBuf; +use std::sync::atomic::AtomicU64; +use std::sync::{Arc, Mutex}; + +use omgcode_core::session_index::SessionIndex; + +pub use self::error::DesktopError; +use self::review_tokens::ReviewTokens; +use self::state::IndexState; +pub use self::turns::ShutdownReport; +use self::turns::TurnTable; +pub use self::wire::{ + ApprovalDecideRequest, ApprovalDetail, ApprovalField, ApprovalList, ApprovalOperationDto, + ApprovalRequest, ApprovalStateDto, ApprovalView, ApprovalsSummary, Binding, ChatOutcome, + ChatSendRequest, ChatSettingsDto, ChatState, ChatStatus, ContextMeterDto, Decision, EntryKind, + MessageRoleDto, SearchHit, SearchRequest, SearchResult, SearchRoleDto, SessionCreateRequest, + SessionRequest, SessionStatus, SessionSummary, SessionTree, SnippetPart, ToolOutcomeDto, + ToolsMode, TranscriptEntry, TranscriptPage, TranscriptRequest, TreeRequest, TreeSort, TreeView, + WorkspaceChoice, WorkspaceGroup, WorkspaceList, +}; +use crate::AppError; + +/// Fixed settings of one desktop process. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct DesktopConfig { + /// Trusted application storage. It comes from the operator, never from the + /// interface. + pub data_root: PathBuf, + /// The chat endpoint, fixed for the process lifetime. A chat request whose + /// endpoint differs byte-for-byte is refused. + pub endpoint: String, +} + +/// Supplies the optional local server token for one chat turn. +/// +/// [`DesktopService::open`] uses [`crate::read_lm_token`]. A different source +/// exists so an embedder or a test can avoid the process environment. +pub type TokenSource = fn() -> Result, AppError>; + +/// The state shared by the service and its turn threads. +/// +/// Owners: the [`DesktopService`] and one clone per running turn thread. The +/// last owner frees it. There is no reference cycle: the thread handles that +/// the table keeps do not own this `Arc`. +struct Inner { + data_root: PathBuf, + endpoint: String, + token_source: TokenSource, + index: Mutex, + turns: Mutex, + reviews: Mutex, + /// The last pending-approval count read, served when the settings store is + /// busy. Advisory only; it authorizes nothing. + pending_cache: AtomicU64, +} + +/// The desktop command service. See the [module documentation](self). +/// +/// It is `Send + Sync`; a shell may keep one in application state and call it +/// from blocking tasks. +pub struct DesktopService { + inner: Arc, +} + +impl DesktopService { + /// Open the service for `config`, creating the session index directory. + /// + /// The index is not refreshed here. The local server token is read from the + /// environment per chat turn. + /// + /// # Errors + /// + /// `busy` when another process holds the index database, `internal` when + /// the index location is unusable. + pub fn open(config: DesktopConfig) -> Result { + Self::open_with_token_source(config, crate::read_lm_token) + } + + /// Open the service with an explicit [`TokenSource`]. + /// + /// # Errors + /// + /// The same as [`open`](Self::open). + pub fn open_with_token_source( + config: DesktopConfig, + token_source: TokenSource, + ) -> Result { + let index = SessionIndex::open(&config.data_root) + .map_err(|error| DesktopError::from_index(&error))?; + Ok(Self { + inner: Arc::new(Inner { + data_root: config.data_root, + endpoint: config.endpoint, + token_source, + index: Mutex::new(IndexState::new(index)), + turns: Mutex::new(TurnTable::default()), + reviews: Mutex::new(ReviewTokens::default()), + pending_cache: AtomicU64::new(0), + }), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_service_can_be_shared_between_threads() { + fn assert_send_sync() {} + assert_send_sync::(); + } +} diff --git a/crates/omgcode-app/src/desktop/approvals.rs b/crates/omgcode-app/src/desktop/approvals.rs new file mode 100644 index 0000000..be34327 --- /dev/null +++ b/crates/omgcode-app/src/desktop/approvals.rs @@ -0,0 +1,316 @@ +//! Approval commands (ADR-0046). +//! +//! The service decides nothing about authority. Core owns the approval +//! records, the exact-binding review, and the refusals. This module lists +//! records, asks core to review the recorded request an approval is bound to, +//! issues a single-use review token for an exact review, and refuses an +//! approve whose token is missing, expired, or for another approval. + +use std::collections::{HashMap, HashSet}; +use std::sync::atomic::Ordering; +use std::time::Instant; + +use omgcode_core::control::{ApprovalOperation, ApprovalState, ApprovalStatus, now_unix}; +use omgcode_core::session::{SessionInspection, TranscriptEntryKind}; +use omgcode_core::turn::{ApprovalReview, ReviewCandidate, display_safe_line, review_approval}; +use uuid::Uuid; + +use super::error::DesktopError; +use super::review_tokens::RedeemError; +use super::wire::{ + ApprovalDecideRequest, ApprovalDetail, ApprovalField, ApprovalList, ApprovalRequest, + ApprovalView, ApprovalsSummary, Binding, Decision, +}; +use super::{DesktopService, Inner}; + +/// Most non-pending approvals `approvals_list` returns, the most recent ones. +const MAX_LISTED_RESOLVED: usize = 50; + +impl DesktopService { + /// How many approvals are pending. + /// + /// Without a settings store the count is 0. When the store stays busy past + /// the bounded wait, the last count read is returned: this is an advisory + /// badge and grants nothing. + /// + /// # Errors + /// + /// `control` when the settings store is invalid. + pub fn approvals_summary(&self) -> Result { + let inner = &self.inner; + let pending = match inner.open_control() { + Ok(Some(store)) => { + let statuses = store.approval_statuses(now_unix()); + drop(store); + inner.note_pending(&statuses) + } + Ok(None) => { + inner.pending_cache.store(0, Ordering::Relaxed); + 0 + } + Err(error) if error.code() == "busy" => inner.pending_cache.load(Ordering::Relaxed), + Err(error) => return Err(error), + }; + Ok(ApprovalsSummary { pending }) + } + + /// Every pending approval, then the 50 most recent others, each joined with + /// its session's title and folder when the index knows the session. + /// + /// # Errors + /// + /// `busy` or `control` for the settings store, `internal` for service state. + pub fn approvals_list(&self) -> Result { + let inner = &self.inner; + let now = now_unix(); + // Statuses first; the store is released before the index is locked. + let statuses = match inner.open_control()? { + Some(store) => { + let statuses = store.approval_statuses(now); + drop(store); + statuses + } + None => Vec::new(), + }; + inner.note_pending(&statuses); + let (pending, resolved): (Vec, Vec) = statuses + .into_iter() + .partition(|status| status.state == ApprovalState::Pending); + let skip = resolved.len().saturating_sub(MAX_LISTED_RESOLVED); + let chosen: Vec = pending + .into_iter() + .chain(resolved.into_iter().skip(skip)) + .collect(); + let approvals = inner.views_of(&chosen)?; + Ok(ApprovalList { + now_unix: now, + approvals, + }) + } + + /// Review the recorded request that one approval is bound to. + /// + /// A non-pending approval is `stale` and nothing is read. For a pending + /// one, the session's journal is inspected without the writer lock and core + /// finds the recorded request whose digest the approval holds. Only an + /// `exact` result carries the tool, the fields, and a fresh single-use + /// review token, which replaces any earlier token for this approval. + /// + /// # Errors + /// + /// `not_found` for an unknown approval, `busy` when a turn runs here for the + /// session or a store or journal is held, `invalid_journal`, `control`. + pub fn approval_detail( + &self, + request: ApprovalRequest, + ) -> Result { + let inner = &self.inner; + let status = inner.status_of_approval(request.id)?; + let not_reviewed = |binding: Binding| -> Result { + Ok(ApprovalDetail { + approval: inner.view_of(&status)?, + binding, + tool: None, + fields: Vec::new(), + review_token: None, + }) + }; + if status.state != ApprovalState::Pending { + return not_reviewed(Binding::Stale); + } + if inner.is_running(status.session_id)? { + return Err(DesktopError::busy()); + } + let path = match inner.resolve_path(status.session_id) { + Ok(path) => path, + Err(error) if error.code() == "not_found" => return not_reviewed(Binding::NotFound), + Err(error) => return Err(error), + }; + let inspection = SessionInspection::inspect(&path) + .map_err(|error| DesktopError::from_session(&error))?; + let candidates: Vec> = inspection + .entries + .iter() + .filter_map(|entry| match &entry.kind { + TranscriptEntryKind::ToolRequested { + tool, arguments, .. + } => Some(ReviewCandidate { tool, arguments }), + _ => None, + }) + .collect(); + // No service lock and no control store is held; core opens its own. + let review = review_approval(&inner.data_root, &status, &candidates) + .map_err(|error| DesktopError::from_review(&error))?; + match review { + ApprovalReview::Exact(reviewed) => { + let token = + inner + .lock_reviews()? + .issue(status.id, &status.request_sha256, Instant::now()); + Ok(ApprovalDetail { + approval: inner.view_of(&status)?, + binding: Binding::Exact, + tool: Some(reviewed.tool), + fields: reviewed + .fields + .into_iter() + .map(|field| ApprovalField { + label: field.label.to_owned(), + value: field.value, + multiline: field.multiline, + }) + .collect(), + review_token: Some(token), + }) + } + ApprovalReview::Stale(_) => not_reviewed(Binding::Stale), + ApprovalReview::NotFound => not_reviewed(Binding::NotFound), + } + } + + /// Approve or deny one pending approval. + /// + /// Deny needs no token. Approve first redeems the review token against the + /// approval's current digest, read from the store in the same hold as the + /// decision. The token is consumed by every attempt, so a refused approve + /// needs a fresh `approval_detail`. A `file_write` approve also needs + /// `writers_stopped` and calls core's acknowledgement path; other + /// operations ignore the field. Core still refuses the wrong combination. + /// + /// # Errors + /// + /// `not_found`, `not_pending`, `review_expired`, `review_mismatch`, + /// `writers_stopped_required`, `busy`, or `control` with core's refusal. + pub fn approval_decide( + &self, + request: ApprovalDecideRequest, + ) -> Result { + let inner = &self.inner; + let mut store = inner + .open_control()? + .ok_or_else(|| DesktopError::not_found("approval"))?; + let now = now_unix(); + let status = store + .approval_status(request.id, now) + .ok_or_else(|| DesktopError::not_found("approval"))?; + if status.state != ApprovalState::Pending { + return Err(DesktopError::not_pending()); + } + let decided = match request.decision { + Decision::Deny => store.decide_approval(request.id, false, now), + Decision::Approve => { + // Only the redeem takes the reviews lock; the store stays open + // so the record cannot change between the check and the decision. + inner.redeem( + request.id, + request.review_token.as_deref(), + &status.request_sha256, + )?; + if status.operation == ApprovalOperation::FileWrite { + if !request.writers_stopped { + return Err(DesktopError::writers_stopped_required()); + } + store.approve_with_writers_stopped(request.id, now) + } else { + store.decide_approval(request.id, true, now) + } + } + }; + decided.map_err(|error| DesktopError::from_control(&error))?; + let updated = store + .approval_status(request.id, now) + .ok_or_else(|| DesktopError::not_found("approval"))?; + let statuses = store.approval_statuses(now); + drop(store); + inner.note_pending(&statuses); + inner.view_of(&updated) + } +} + +impl Inner { + /// Cache and return how many of `statuses` are pending. + fn note_pending(&self, statuses: &[ApprovalStatus]) -> u64 { + let pending = statuses + .iter() + .filter(|status| status.state == ApprovalState::Pending) + .count(); + let pending = u64::try_from(pending).unwrap_or(u64::MAX); + self.pending_cache.store(pending, Ordering::Relaxed); + pending + } + + /// The status of one approval; the store is released before returning. + fn status_of_approval(&self, id: Uuid) -> Result { + let store = self + .open_control()? + .ok_or_else(|| DesktopError::not_found("approval"))?; + let status = store.approval_status(id, now_unix()); + drop(store); + status.ok_or_else(|| DesktopError::not_found("approval")) + } + + /// Use the review token for an approval. + fn redeem( + &self, + approval: Uuid, + presented: Option<&str>, + digest: &str, + ) -> Result<(), DesktopError> { + let outcome = self + .lock_reviews()? + .redeem(approval, presented, digest, Instant::now()); + outcome.map_err(|error| match error { + RedeemError::Expired => DesktopError::review_expired(), + RedeemError::Mismatch => DesktopError::review_mismatch(), + }) + } + + fn view_of(&self, status: &ApprovalStatus) -> Result { + let mut views = self.views_of(std::slice::from_ref(status))?; + views + .pop() + .ok_or_else(|| DesktopError::internal("The approval could not be shown.")) + } + + /// Join statuses with session labels from the index, which is locked once. + /// + /// A label the index cannot supply is `null`: it is cosmetic, and the + /// record itself comes from the settings store. + fn views_of(&self, statuses: &[ApprovalStatus]) -> Result, DesktopError> { + let labels: HashMap = self.with_index(|state| { + let mut labels = HashMap::new(); + for status in statuses { + if labels.contains_key(&status.session_id) { + continue; + } + if let Ok(Some(session)) = state.index.session(status.session_id) { + let title = super::state::summary_of(&session, &HashSet::new()).title; + labels.insert( + status.session_id, + (title, super::state::folder_of(&session)), + ); + } + } + Ok(labels) + })?; + Ok(statuses + .iter() + .map(|status| { + let label = labels.get(&status.session_id); + ApprovalView { + id: status.id, + session_id: status.session_id, + session_title: label.map(|(title, _)| title.clone()), + folder_display: label.map(|(_, folder)| folder.clone()), + operation: status.operation.into(), + summary: display_safe_line(&status.summary), + state: status.state.into(), + created_unix: status.created_unix, + expires_unix: status.expires_unix, + request_sha256: status.request_sha256.clone(), + writers_stopped: status.writers_stopped, + } + }) + .collect()) + } +} diff --git a/crates/omgcode-app/src/desktop/chat.rs b/crates/omgcode-app/src/desktop/chat.rs new file mode 100644 index 0000000..608995d --- /dev/null +++ b/crates/omgcode-app/src/desktop/chat.rs @@ -0,0 +1,243 @@ +//! Chat commands: defaults, send, status, cancel, and shutdown. + +use std::time::Duration; + +use omgcode_core::context::DEFAULT_COMPACT_THRESHOLD; +use omgcode_core::session_index::IndexedState; +use uuid::Uuid; + +use super::error::DesktopError; +use super::turns::{LmToken, MAX_RUNNING_TURNS, ShutdownReport, SlotState, TurnJob, spawn_turn}; +use super::wire::{ChatSendRequest, ChatSettingsDto, ChatState, ChatStatus, SessionRequest}; +use super::{DesktopService, Inner}; +use crate::{ChatClients, ChatSettings}; + +/// Largest message accepted before core applies its own, smaller bound. It only +/// keeps an oversized request from being copied into a turn thread. +const MAX_MESSAGE_INPUT_BYTES: usize = 64 * 1024; +/// Largest custom-instruction text accepted before core applies its bound. +const MAX_INSTRUCTIONS_INPUT_BYTES: usize = 64 * 1024; +/// Output reserve of the default settings. +const DEFAULT_MAX_OUTPUT_TOKENS: u32 = 1024; + +impl DesktopService { + /// The settings the interface starts from: the fixed endpoint, an empty + /// model, and the CLI's budgets. + pub fn chat_defaults(&self) -> ChatSettingsDto { + ChatSettingsDto { + endpoint: self.inner.endpoint.clone(), + model: String::new(), + context_tokens: 0, + max_output_tokens: DEFAULT_MAX_OUTPUT_TOKENS, + instructions: String::new(), + compact_threshold: DEFAULT_COMPACT_THRESHOLD, + auto_compact: false, + } + } + + /// Start one chat turn and return at once with state `running`. + /// + /// Everything that can be checked without running the turn is checked + /// first, so a bad endpoint, model, or session is refused synchronously. + /// The turn then runs on its own thread; poll [`chat_status`](Self::chat_status). + /// + /// # Errors + /// + /// `invalid_request` (endpoint differs, empty or oversized message), + /// `not_found`, `invalid_journal`, `busy`, `archived`, `turn_open`, + /// `turn_running`, `too_many_turns`, `shutting_down`, `internal` (thread + /// start failure), and the application layer's `provider` and + /// `configuration` codes for unusable settings or token. + pub fn chat_send(&self, request: ChatSendRequest) -> Result { + let inner = &self.inner; + let session_id = request.session_id; + if request.settings.endpoint != inner.endpoint { + return Err(DesktopError::invalid_request( + "The endpoint is fixed by the application.", + )); + } + if request.message.trim().is_empty() { + return Err(DesktopError::invalid_request("The message is empty.")); + } + if request.message.len() > MAX_MESSAGE_INPUT_BYTES + || request.settings.instructions.len() > MAX_INSTRUCTIONS_INPUT_BYTES + { + return Err(DesktopError::invalid_request("The request is too large.")); + } + inner.reap()?; + check_slot(inner, session_id)?; + + // A fresh read of this one journal, so archive and open-turn state is + // current. The path comes only from the index. + let (session, path) = inner.with_index(|state| { + let session = state + .index + .refresh_session(session_id) + .map_err(|error| DesktopError::from_index(&error))? + .ok_or_else(|| DesktopError::not_found("session"))?; + let path = state + .index + .journal_path(session_id) + .map_err(|error| DesktopError::from_index(&error))? + .ok_or_else(|| DesktopError::not_found("session"))?; + Ok((session, path)) + })?; + match session.state { + IndexedState::Invalid => return Err(DesktopError::invalid_journal()), + IndexedState::Busy => return Err(DesktopError::busy()), + IndexedState::Ok => {} + } + if session.archived { + return Err(DesktopError::archived()); + } + if session.active_turn.is_some() { + return Err(DesktopError::turn_open()); + } + + // Build the clients now so a bad model, context, endpoint, or token is + // a synchronous provider error, not a later failed turn. + let token = (inner.token_source)() + .map_err(|error| DesktopError::from_app(&error))? + .map(LmToken::new); + let settings = chat_settings(request.settings); + let clients = ChatClients::new(&settings, token.as_ref().map(LmToken::as_str)) + .map_err(|error| DesktopError::from_app(&error))?; + let job = TurnJob { + session_id, + path, + message: request.message, + settings, + token, + clients, + }; + + // Reserve the slot and start the thread under one lock hold, so two + // racing calls cannot both pass the limits. Starting a thread does not + // block; the thread waits for this lock only to store its cancel token. + let mut turns = inner.lock_turns()?; + if turns.is_closed() { + return Err(DesktopError::shutting_down()); + } + if turns.is_running(session_id) { + return Err(DesktopError::turn_running()); + } + if turns.running_count() >= MAX_RUNNING_TURNS { + return Err(DesktopError::too_many_turns()); + } + let handle = spawn_turn(inner, job)?; + turns.insert_running(session_id, handle); + drop(turns); + Ok(status_of( + session_id, + Some(&SlotState::Running { + cancel_requested: false, + cancel: None, + }), + )) + } + + /// The state of a session's chat turn. + /// + /// Reaps finished turn threads first. A session this service has no record + /// of is `idle`. A finished result stays until the next `chat_send` for the + /// session. + /// + /// # Errors + /// + /// `internal` when the service state is unavailable. + pub fn chat_status(&self, request: SessionRequest) -> Result { + self.inner.reap()?; + self.read_status(request.session_id) + } + + /// Request cooperative cancellation of a running turn. + /// + /// Only the tool-enabled path has a cancellation point, between model + /// rounds and tool calls. A text-only turn ignores the request and its + /// status stays `running`; `cancelling` is reported only when a cancel + /// token exists. A provider request in flight is not interrupted. + /// + /// # Errors + /// + /// `internal` when the service state is unavailable. + pub fn chat_cancel(&self, request: SessionRequest) -> Result { + self.inner.lock_turns()?.request_cancel(request.session_id); + self.inner.reap()?; + self.read_status(request.session_id) + } + + /// Request cancellation of every running turn and wait up to `grace` for + /// the turn threads to finish, polling for completion. + /// + /// Returns without waiting past `grace`. A provider request in flight + /// cannot be interrupted, so such a turn is reported in `still_running`; it + /// leaves its journal with an open turn, which the operator can close later + /// with the interrupt command. After shutdown, `chat_send` is refused. + pub fn shutdown(&self, grace: Duration) -> ShutdownReport { + self.inner.shutdown_turns(grace) + } + + fn read_status(&self, session_id: Uuid) -> Result { + let turns = self.inner.lock_turns()?; + Ok(status_of( + session_id, + turns.slot(session_id).map(|slot| &slot.state), + )) + } +} + +/// Refuse early when a turn for the session runs or the running limit is hit. +fn check_slot(inner: &Inner, session_id: Uuid) -> Result<(), DesktopError> { + let turns = inner.lock_turns()?; + if turns.is_closed() { + return Err(DesktopError::shutting_down()); + } + if turns.is_running(session_id) { + return Err(DesktopError::turn_running()); + } + if turns.running_count() >= MAX_RUNNING_TURNS { + return Err(DesktopError::too_many_turns()); + } + Ok(()) +} + +fn chat_settings(settings: ChatSettingsDto) -> ChatSettings { + ChatSettings { + endpoint: settings.endpoint, + model: settings.model, + context_tokens: settings.context_tokens, + max_output_tokens: settings.max_output_tokens, + instructions: settings.instructions, + compact_threshold: settings.compact_threshold, + auto_compact: settings.auto_compact, + } +} + +/// The wire status of a slot, or `idle` when there is none. +fn status_of(session_id: Uuid, state: Option<&SlotState>) -> ChatStatus { + let (state, outcome, error) = match state { + None => (ChatState::Idle, None, None), + Some(SlotState::Running { + cancel_requested, + cancel, + }) => ( + if *cancel_requested && cancel.is_some() { + ChatState::Cancelling + } else { + ChatState::Running + }, + None, + None, + ), + Some(SlotState::Finished(result)) => match result.as_ref() { + Ok(outcome) => (ChatState::Completed, Some(outcome.clone()), None), + Err(error) => (ChatState::Failed, None, Some(error.clone())), + }, + }; + ChatStatus { + session_id, + state, + outcome, + error, + } +} diff --git a/crates/omgcode-app/src/desktop/error.rs b/crates/omgcode-app/src/desktop/error.rs new file mode 100644 index 0000000..c7bfb38 --- /dev/null +++ b/crates/omgcode-app/src/desktop/error.rs @@ -0,0 +1,237 @@ +//! The one failure shape the desktop commands return. +//! +//! A [`DesktopError`] serializes as exactly `{ "code": string, "message": +//! string }`. The code is a stable `snake_case` identifier that the interface +//! may branch on. The message is short English text. It never carries an +//! absolute path, recorded file content, or the local server token: every +//! message is fixed text, a static reason from core, or the message of an +//! [`AppError`], which the application layer already keeps free of secrets. + +use std::fmt; + +use omgcode_core::control::ControlError; +use omgcode_core::session::SessionError; +use omgcode_core::session_index::IndexError; +use omgcode_core::turn::ReviewError; +use serde::Serialize; + +use crate::error::{AppError, ErrorKind}; + +/// A controlled failure of one desktop command. +/// +/// Codes defined by this service: `busy`, `invalid_journal`, `review_expired`, +/// `review_mismatch`, `not_found`, `invalid_request`, `archived`, +/// `turn_running`, `turn_open`, `too_many_turns`, `not_pending`, +/// `writers_stopped_required`, `unknown_workspace`, `shutting_down`, and +/// `internal`. Failures that come from the application layer keep their +/// [`ErrorKind`] code (`provider`, `session`, `control`, `context`, +/// `permission`, `turn`, and the others). +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct DesktopError { + code: &'static str, + message: String, +} + +impl DesktopError { + fn new(code: &'static str, message: impl Into) -> Self { + Self { + code, + message: message.into(), + } + } + + /// The stable machine-readable code. + pub const fn code(&self) -> &'static str { + self.code + } + + /// The short human-readable message. + pub fn message(&self) -> &str { + &self.message + } + + /// A journal, the settings store, or the index is held elsewhere. Retry later. + pub(crate) fn busy() -> Self { + Self::new( + "busy", + "The data is in use by another operation. Try again shortly.", + ) + } + + /// The session's journal failed validation. + pub(crate) fn invalid_journal() -> Self { + Self::new("invalid_journal", "The session journal failed validation.") + } + + /// The review token is missing, used, or older than its lifetime. + pub(crate) fn review_expired() -> Self { + Self::new( + "review_expired", + "The review has expired. Open the approval again.", + ) + } + + /// The review token does not belong to this approval. + pub(crate) fn review_mismatch() -> Self { + Self::new( + "review_mismatch", + "The review does not match this approval. Open the approval again.", + ) + } + + /// No such session or approval. + pub(crate) fn not_found(what: &'static str) -> Self { + Self::new("not_found", format!("The {what} was not found.")) + } + + /// The request is not acceptable as sent. + pub(crate) fn invalid_request(message: impl Into) -> Self { + Self::new("invalid_request", message) + } + + /// The session is archived. + pub(crate) fn archived() -> Self { + Self::new("archived", "Restore the archived session before chatting.") + } + + /// A turn for the session is running in this application. + pub(crate) fn turn_running() -> Self { + Self::new( + "turn_running", + "A chat turn is already running for this session.", + ) + } + + /// The journal records a turn that never finished. + pub(crate) fn turn_open() -> Self { + Self::new( + "turn_open", + "The session has an unfinished turn. Interrupt it first.", + ) + } + + /// The running-turn limit is reached. + pub(crate) fn too_many_turns() -> Self { + Self::new( + "too_many_turns", + "Too many chat turns are running. Wait for one to finish.", + ) + } + + /// The approval already has a decision, or it expired. + pub(crate) fn not_pending() -> Self { + Self::new("not_pending", "The approval is no longer pending.") + } + + /// A file write needs the writers-stopped acknowledgement. + pub(crate) fn writers_stopped_required() -> Self { + Self::new( + "writers_stopped_required", + "Confirm that other writers to the file are stopped to approve a file write.", + ) + } + + /// The workspace is not registered. + pub(crate) fn unknown_workspace() -> Self { + Self::new("unknown_workspace", "The workspace is not registered.") + } + + /// The application is shutting down. + pub(crate) fn shutting_down() -> Self { + Self::new("shutting_down", "The application is shutting down.") + } + + /// Service state or a lower layer is unavailable. + pub(crate) fn internal(message: &'static str) -> Self { + Self::new("internal", message) + } + + /// A poisoned service lock. State whose invariants are uncertain is not used. + pub(crate) fn poisoned() -> Self { + Self::internal("The desktop service state is unavailable.") + } + + /// Keep the application layer's code and message. + pub(crate) fn from_app(error: &AppError) -> Self { + Self::new(error.code(), error.message()) + } + + /// Remove a known secret from the message. + pub(crate) fn redacted(mut self, secret: Option<&str>) -> Self { + self.message = crate::redact_known_secret(&self.message, secret); + self + } + + /// Map a title-validation failure from session creation to `invalid_request`. + pub(crate) fn from_create(error: &AppError) -> Self { + if error.kind() == ErrorKind::Session + && error.message().starts_with("invalid session value") + { + Self::invalid_request(error.message()) + } else { + Self::from_app(error) + } + } + + /// Map a journal failure. + pub(crate) fn from_session(error: &SessionError) -> Self { + match error { + SessionError::Busy => Self::busy(), + SessionError::InvalidJournal(_) | SessionError::LimitReached => Self::invalid_journal(), + SessionError::ActiveTurn => Self::turn_open(), + SessionError::Io(io) if io.kind() == std::io::ErrorKind::NotFound => { + Self::not_found("session") + } + SessionError::Io(_) => Self::new("session", "The session journal could not be read."), + SessionError::InvalidValue(reason) => Self::invalid_request(*reason), + SessionError::WrongTurn | SessionError::Poisoned => { + Self::new("session", error.to_string()) + } + } + } + + /// Map an index failure. Index text and stored values never reach the caller. + pub(crate) fn from_index(error: &IndexError) -> Self { + match error { + IndexError::Busy => Self::busy(), + IndexError::InvalidQuery(reason) => Self::invalid_request(*reason), + IndexError::InvalidIndexEntry(_) => Self::invalid_journal(), + IndexError::UnsafeLocation(_) + | IndexError::Session(_) + | IndexError::Io(_) + | IndexError::Sqlite(_) => Self::internal("The session index is unavailable."), + } + } + + /// Map a settings-store failure. + pub(crate) fn from_control(error: &ControlError) -> Self { + match error { + ControlError::Busy => Self::busy(), + ControlError::UnknownWorkspace => Self::unknown_workspace(), + ControlError::UnknownApproval => Self::not_found("approval"), + ControlError::Io(_) + | ControlError::Container(_) + | ControlError::ProfileRemoval(_) + | ControlError::WorkspacePath(_) => { + Self::new("control", "The settings store could not be used.") + } + other => Self::new("control", other.to_string()), + } + } + + /// Map an approval-review failure. + pub(crate) fn from_review(error: &ReviewError) -> Self { + match error { + ReviewError::Busy => Self::busy(), + other => Self::new("control", other.to_string()), + } + } +} + +impl fmt::Display for DesktopError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "{}: {}", self.code, self.message) + } +} + +impl std::error::Error for DesktopError {} diff --git a/crates/omgcode-app/src/desktop/review_tokens.rs b/crates/omgcode-app/src/desktop/review_tokens.rs new file mode 100644 index 0000000..5d3acfb --- /dev/null +++ b/crates/omgcode-app/src/desktop/review_tokens.rs @@ -0,0 +1,276 @@ +//! Single-use review tokens (ADR-0046, decision 4). +//! +//! A token proves that `approval_detail` showed the operator the exact request +//! an approval is bound to. It is random, bound to one approval and its digest, +//! lives for [`TOKEN_LIFETIME`], and is removed by the first attempt to redeem +//! it, successful or not. Tokens live in memory only. This module is pure: the +//! caller supplies every `Instant`, so expiry is testable without sleeping. + +use std::time::{Duration, Instant}; + +use uuid::Uuid; + +/// How long a token stays valid. A token is expired at exactly this age. +pub(super) const TOKEN_LIFETIME: Duration = Duration::from_secs(120); + +/// Most tokens kept at once. A new token evicts the oldest beyond this. +pub(super) const MAX_OUTSTANDING_TOKENS: usize = 64; + +/// Why a redeem attempt failed. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) enum RedeemError { + /// No token exists for the approval, none was presented, or it is too old. + Expired, + /// The presented token or the approval's digest differs from the issued one. + Mismatch, +} + +/// One outstanding token. +struct Entry { + approval: Uuid, + token: String, + digest: String, + issued: Instant, +} + +/// The outstanding tokens, oldest first. A token is a credential for one +/// approve, so this type has no `Debug` output. +#[derive(Default)] +pub(super) struct ReviewTokens { + entries: Vec, +} + +impl ReviewTokens { + /// Issue a fresh token for `approval`, replacing any earlier one. + /// + /// Expired tokens are dropped first, then the oldest is evicted while the + /// table would exceed [`MAX_OUTSTANDING_TOKENS`]. + pub(super) fn issue(&mut self, approval: Uuid, digest: &str, now: Instant) -> String { + self.entries.retain(|entry| entry.approval != approval); + self.entries.retain(|entry| !is_expired(entry, now)); + while self.entries.len() >= MAX_OUTSTANDING_TOKENS { + self.entries.remove(0); + } + let token = Uuid::new_v4().to_string(); + self.entries.push(Entry { + approval, + token: token.clone(), + digest: digest.to_owned(), + issued: now, + }); + token + } + + /// Use the token for `approval`. The entry is removed on every attempt. + /// + /// `presented` is `None` when the caller sent no token, which is `Expired`. + pub(super) fn redeem( + &mut self, + approval: Uuid, + presented: Option<&str>, + digest: &str, + now: Instant, + ) -> Result<(), RedeemError> { + let position = self + .entries + .iter() + .position(|entry| entry.approval == approval); + let entry = match position { + Some(index) => self.entries.remove(index), + None => return Err(RedeemError::Expired), + }; + if is_expired(&entry, now) { + return Err(RedeemError::Expired); + } + let Some(presented) = presented else { + return Err(RedeemError::Expired); + }; + let token_matches = constant_time_equal(presented.as_bytes(), entry.token.as_bytes()); + let digest_matches = constant_time_equal(digest.as_bytes(), entry.digest.as_bytes()); + if token_matches && digest_matches { + Ok(()) + } else { + Err(RedeemError::Mismatch) + } + } + + /// How many tokens are outstanding. + #[cfg(test)] + pub(super) fn len(&self) -> usize { + self.entries.len() + } +} + +/// Whether `entry` has reached [`TOKEN_LIFETIME`] at `now`. +fn is_expired(entry: &Entry, now: Instant) -> bool { + now.saturating_duration_since(entry.issued) >= TOKEN_LIFETIME +} + +/// Compare two byte strings without stopping at the first difference. +/// +/// Lengths are not secret: tokens and digests have fixed lengths. +fn constant_time_equal(left: &[u8], right: &[u8]) -> bool { + if left.len() != right.len() { + return false; + } + let difference = left + .iter() + .zip(right) + .fold(0_u8, |accumulated, (a, b)| accumulated | (a ^ b)); + difference == 0 +} + +#[cfg(test)] +mod tests { + use super::*; + + const DIGEST: &str = "aa"; + + fn id() -> Uuid { + Uuid::new_v4() + } + + #[test] + fn a_token_redeems_once() { + let mut tokens = ReviewTokens::default(); + let start = Instant::now(); + let approval = id(); + let token = tokens.issue(approval, DIGEST, start); + assert_eq!(tokens.redeem(approval, Some(&token), DIGEST, start), Ok(())); + assert_eq!( + tokens.redeem(approval, Some(&token), DIGEST, start), + Err(RedeemError::Expired) + ); + } + + #[test] + fn a_token_is_valid_just_before_the_lifetime_and_expired_at_it() { + let start = Instant::now(); + let approval = id(); + let mut tokens = ReviewTokens::default(); + let token = tokens.issue(approval, DIGEST, start); + let almost = start + TOKEN_LIFETIME - Duration::from_millis(1); + assert_eq!( + tokens.redeem(approval, Some(&token), DIGEST, almost), + Ok(()) + ); + + let token = tokens.issue(approval, DIGEST, start); + assert_eq!( + tokens.redeem(approval, Some(&token), DIGEST, start + TOKEN_LIFETIME), + Err(RedeemError::Expired) + ); + } + + #[test] + fn issuing_again_replaces_the_earlier_token() { + let start = Instant::now(); + let approval = id(); + let mut tokens = ReviewTokens::default(); + let first = tokens.issue(approval, DIGEST, start); + let second = tokens.issue(approval, DIGEST, start); + assert_ne!(first, second); + assert_eq!(tokens.len(), 1); + assert_eq!( + tokens.redeem(approval, Some(&first), DIGEST, start), + Err(RedeemError::Mismatch) + ); + // The failed attempt removed the entry, so the second token is gone too. + assert_eq!( + tokens.redeem(approval, Some(&second), DIGEST, start), + Err(RedeemError::Expired) + ); + } + + #[test] + fn a_wrong_token_or_digest_is_a_mismatch_and_removes_the_entry() { + let start = Instant::now(); + let approval = id(); + let mut tokens = ReviewTokens::default(); + let token = tokens.issue(approval, DIGEST, start); + assert_eq!( + tokens.redeem(approval, Some("not-the-token"), DIGEST, start), + Err(RedeemError::Mismatch) + ); + assert_eq!( + tokens.redeem(approval, Some(&token), DIGEST, start), + Err(RedeemError::Expired) + ); + + let token = tokens.issue(approval, DIGEST, start); + assert_eq!( + tokens.redeem(approval, Some(&token), "bb", start), + Err(RedeemError::Mismatch) + ); + assert_eq!(tokens.len(), 0); + } + + #[test] + fn a_missing_token_is_expired_and_removes_the_entry() { + let start = Instant::now(); + let approval = id(); + let mut tokens = ReviewTokens::default(); + let token = tokens.issue(approval, DIGEST, start); + assert_eq!( + tokens.redeem(approval, None, DIGEST, start), + Err(RedeemError::Expired) + ); + assert_eq!( + tokens.redeem(approval, Some(&token), DIGEST, start), + Err(RedeemError::Expired) + ); + } + + #[test] + fn a_token_for_one_approval_does_not_redeem_another() { + let start = Instant::now(); + let (a, b) = (id(), id()); + let mut tokens = ReviewTokens::default(); + let token_a = tokens.issue(a, DIGEST, start); + assert_eq!( + tokens.redeem(b, Some(&token_a), DIGEST, start), + Err(RedeemError::Expired) + ); + assert_eq!(tokens.redeem(a, Some(&token_a), DIGEST, start), Ok(())); + } + + #[test] + fn the_sixty_fifth_token_evicts_the_oldest() { + let start = Instant::now(); + let mut tokens = ReviewTokens::default(); + let approvals: Vec = (0..=MAX_OUTSTANDING_TOKENS).map(|_| id()).collect(); + let issued: Vec = approvals + .iter() + .map(|approval| tokens.issue(*approval, DIGEST, start)) + .collect(); + assert_eq!(tokens.len(), MAX_OUTSTANDING_TOKENS); + assert_eq!( + tokens.redeem(approvals[0], Some(&issued[0]), DIGEST, start), + Err(RedeemError::Expired) + ); + assert_eq!( + tokens.redeem(approvals[1], Some(&issued[1]), DIGEST, start), + Ok(()) + ); + } + + #[test] + fn expired_tokens_are_dropped_when_a_new_one_is_issued() { + let start = Instant::now(); + let mut tokens = ReviewTokens::default(); + for _ in 0..10 { + tokens.issue(id(), DIGEST, start); + } + tokens.issue(id(), DIGEST, start + TOKEN_LIFETIME); + assert_eq!(tokens.len(), 1); + } + + #[test] + fn tokens_are_random_version_four_identifiers() { + let start = Instant::now(); + let mut tokens = ReviewTokens::default(); + let token = tokens.issue(id(), DIGEST, start); + let parsed = Uuid::try_parse(&token).expect("a uuid token"); + assert_eq!(parsed.get_version_num(), 4); + } +} diff --git a/crates/omgcode-app/src/desktop/sessions.rs b/crates/omgcode-app/src/desktop/sessions.rs new file mode 100644 index 0000000..65f194f --- /dev/null +++ b/crates/omgcode-app/src/desktop/sessions.rs @@ -0,0 +1,450 @@ +//! Session tree, search, transcript, and lifecycle commands. + +use std::fmt::Write as _; + +use omgcode_core::session::{NativePath, SessionInspection, SessionJournal, TranscriptEntryKind}; +use omgcode_core::session_index::SnippetPart as IndexSnippetPart; +use omgcode_core::session_index::{ + ArchiveView, IndexedSession, SearchRole, SessionQuery, SessionSort, +}; +use sha2::{Digest, Sha256}; +use uuid::Uuid; + +use super::error::DesktopError; +use super::state::{folder_of, folder_of_path, format_time, summary_of, summary_of_inspection}; +use super::wire::{ + EntryKind, SearchHit, SearchRequest, SearchResult, SearchRoleDto, SessionRequest, + SessionSummary, SessionTree, SnippetPart, TranscriptEntry, TranscriptPage, TranscriptRequest, + TreeRequest, TreeSort, TreeView, WorkspaceGroup, source_label, +}; +use super::{DesktopService, Inner}; + +/// Most sessions one tree listing returns. +const LISTING_LIMIT: usize = 5000; +/// Most search hits one request returns. +const MAX_SEARCH_HITS: usize = 200; +/// Most transcript entries one page returns. +const MAX_PAGE_ENTRIES: usize = 200; +/// Most bytes of text one transcript page carries. A page always holds at +/// least one entry. +const MAX_PAGE_TEXT_BYTES: usize = 1024 * 1024; +/// Failure code recorded when the operator closes an open turn. +const INTERRUPT_CODE: &str = "operator_interrupted"; +/// Characters of a group key that make the opaque group identifier. +const GROUP_ID_CHARS: usize = 16; + +impl DesktopService { + /// List sessions grouped by their recorded workspace folder. + /// + /// The index is refreshed first, within a time bound. Groups appear in the + /// order their first session appears in the sorted listing, and sessions + /// keep the listing order. At most 5000 sessions are listed; + /// `indexed_sessions` counts the whole view. + /// + /// # Errors + /// + /// `busy` when the index is held elsewhere, `internal` otherwise. + pub fn session_tree(&self, request: TreeRequest) -> Result { + let inner = &self.inner; + let running = inner.running_sessions()?; + let query = SessionQuery { + view: archive_view(request.view), + sort: match request.sort { + TreeSort::Updated => SessionSort::Updated, + TreeSort::Created => SessionSort::Created, + TreeSort::Title => SessionSort::Title, + }, + descending: request.descending, + limit: LISTING_LIMIT, + }; + let (listing, skipped_entries) = inner.with_index(|state| { + state.refresh_bounded(false)?; + let listing = state + .index + .sessions(&query) + .map_err(|error| DesktopError::from_index(&error))?; + Ok((listing, state.skipped_entries)) + })?; + + let mut groups: Vec = Vec::new(); + let mut positions: std::collections::HashMap = + std::collections::HashMap::new(); + for session in &listing.sessions { + let key = group_key(session.workspace.as_ref()); + let summary = summary_of(session, &running); + if let Some(index) = positions.get(&key).copied() + && let Some(group) = groups.get_mut(index) + { + group.sessions.push(summary); + continue; + } + positions.insert(key.clone(), groups.len()); + groups.push(WorkspaceGroup { + group_id: key.chars().take(GROUP_ID_CHARS).collect(), + folder_display: folder_of(session), + sessions: vec![summary], + }); + } + Ok(SessionTree { + groups, + indexed_sessions: listing.total, + skipped_entries, + }) + } + + /// Search transcript text. + /// + /// The index is refreshed first. The query is never search-engine syntax; + /// an unusable query is `invalid_request`. The limit is clamped to 1 + /// through 200. + /// + /// # Errors + /// + /// `invalid_request`, `busy`, or `internal`. + pub fn session_search(&self, request: SearchRequest) -> Result { + let inner = &self.inner; + let running = inner.running_sessions()?; + let limit = usize::try_from(request.limit) + .unwrap_or(MAX_SEARCH_HITS) + .clamp(1, MAX_SEARCH_HITS); + let listing = inner.with_index(|state| { + state.refresh_bounded(false)?; + state + .index + .search(&request.query, archive_view(request.view), limit) + .map_err(|error| DesktopError::from_index(&error)) + })?; + let hits = listing + .hits + .iter() + .map(|hit| SearchHit { + session: summary_of(&hit.session, &running), + folder_display: folder_of(&hit.session), + seq: hit.seq, + role: match hit.role { + SearchRole::User => SearchRoleDto::User, + SearchRole::Assistant => SearchRoleDto::Assistant, + SearchRole::Tool => SearchRoleDto::Tool, + SearchRole::Summary => SearchRoleDto::Summary, + SearchRole::Title => SearchRoleDto::Title, + }, + snippet: hit.snippet.iter().map(snippet_part).collect(), + }) + .collect(); + Ok(SearchResult { + hits, + truncated: listing.truncated, + }) + } + + /// Read one page of a session's transcript without the writer lock. + /// + /// Returns entries with a sequence number above `after_seq` (all when it is + /// `null`), at most `limit` (clamped to 1 through 200) and at most 1 MiB of + /// text, always at least one. `next_after_seq` is the last returned + /// sequence number when more entries remain. + /// + /// # Errors + /// + /// `not_found`; `busy` when a turn runs here for the session or another + /// process holds the journal; `invalid_journal` when it fails validation. + pub fn session_transcript( + &self, + request: TranscriptRequest, + ) -> Result { + let inner = &self.inner; + if inner.is_running(request.session_id)? { + return Err(DesktopError::busy()); + } + let path = inner.resolve_path(request.session_id)?; + let inspection = SessionInspection::inspect(&path) + .map_err(|error| DesktopError::from_session(&error))?; + let limit = usize::try_from(request.limit) + .unwrap_or(MAX_PAGE_ENTRIES) + .clamp(1, MAX_PAGE_ENTRIES); + let mut entries = Vec::new(); + let mut text_bytes = 0_usize; + let mut more = false; + for entry in inspection + .entries + .iter() + .filter(|entry| request.after_seq.is_none_or(|after| entry.seq > after)) + { + let kind = entry_kind(&entry.kind); + let size = entry_text_bytes(&kind); + let next_total = text_bytes.saturating_add(size); + if !entries.is_empty() && (entries.len() >= limit || next_total > MAX_PAGE_TEXT_BYTES) { + more = true; + break; + } + let timestamp = format_time(entry.timestamp) + .ok_or_else(|| DesktopError::internal("A recorded time could not be formatted."))?; + text_bytes = next_total; + entries.push(TranscriptEntry { + seq: entry.seq, + timestamp, + kind, + }); + } + let next_after_seq = if more { + entries.last().map(|entry| entry.seq) + } else { + None + }; + Ok(TranscriptPage { + session: summary_of_inspection(&inspection), + folder_display: folder_of_path(&inspection.workspace), + entries, + next_after_seq, + incomplete_tail: inspection.incomplete_tail, + }) + } + + /// Archive an idle session. Archiving an archived session changes nothing. + /// + /// # Errors + /// + /// `turn_running`, `turn_open`, `busy`, `not_found`, or `invalid_journal`. + pub fn session_archive(&self, request: SessionRequest) -> Result { + self.lifecycle(request.session_id, |journal| { + journal + .archive() + .map_err(|error| DesktopError::from_session(&error)) + }) + } + + /// Restore an archived session. Restoring an active session changes nothing. + /// + /// # Errors + /// + /// `turn_running`, `busy`, `not_found`, or `invalid_journal`. + pub fn session_restore(&self, request: SessionRequest) -> Result { + self.lifecycle(request.session_id, |journal| { + journal + .restore() + .map_err(|error| DesktopError::from_session(&error)) + }) + } + + /// Close a session's unfinished turn with the failure code + /// `operator_interrupted`. It starts no work and replays nothing. + /// + /// # Errors + /// + /// `invalid_request` when no turn is open, `turn_running`, `busy`, + /// `not_found`, or `invalid_journal`. + pub fn session_interrupt( + &self, + request: SessionRequest, + ) -> Result { + self.lifecycle(request.session_id, |journal| { + let Some(turn) = journal.snapshot().active_turn else { + return Err(DesktopError::invalid_request("No turn is open.")); + }; + journal + .fail_turn(turn, INTERRUPT_CODE) + .map_err(|error| DesktopError::from_session(&error)) + }) + } + + /// Open the journal, apply one change, release it, refresh the index for + /// this session, and summarize it. + fn lifecycle( + &self, + session_id: Uuid, + change: impl FnOnce(&mut SessionJournal) -> Result<(), DesktopError>, + ) -> Result { + let inner = &self.inner; + if inner.is_running(session_id)? { + return Err(DesktopError::turn_running()); + } + let path = inner.resolve_path(session_id)?; + let mut journal = + SessionJournal::open(&path).map_err(|error| DesktopError::from_session(&error))?; + let changed = change(&mut journal); + drop(journal); + changed?; + refreshed_summary(inner, session_id) + } +} + +/// Refresh one session in the index and summarize it. +pub(super) fn refreshed_summary( + inner: &Inner, + session_id: Uuid, +) -> Result { + let running = inner.running_sessions()?; + let session: IndexedSession = inner + .with_index(|state| { + state + .index + .refresh_session(session_id) + .map_err(|error| DesktopError::from_index(&error)) + })? + .ok_or_else(|| DesktopError::not_found("session"))?; + Ok(summary_of(&session, &running)) +} + +const fn archive_view(view: TreeView) -> ArchiveView { + match view { + TreeView::Active => ArchiveView::Active, + TreeView::Archived => ArchiveView::Archived, + } +} + +fn snippet_part(part: &IndexSnippetPart) -> SnippetPart { + SnippetPart { + text: part.text.clone(), + matched: part.matched, + } +} + +/// The grouping key of a recorded workspace path: the hex SHA-256 over the +/// path's encoding tag and units (exact equality of paths, up to a hash +/// collision), or the literal `unknown` when the journal recorded none. The +/// group identifier is the first 16 characters of the key. +fn group_key(path: Option<&NativePath>) -> String { + let Some(path) = path else { + return String::from("unknown"); + }; + let mut hasher = Sha256::new(); + match path { + NativePath::UnixBytes(bytes) => { + hasher.update(b"unix_bytes\0"); + hasher.update(bytes); + } + NativePath::WindowsUtf16(units) => { + hasher.update(b"windows_utf16\0"); + for unit in units { + hasher.update(unit.to_le_bytes()); + } + } + } + let digest = hasher.finalize(); + let mut text = String::with_capacity(64); + for byte in digest.iter() { + // Writing to a String cannot fail. + if write!(text, "{byte:02x}").is_err() { + break; + } + } + text +} + +/// Map one recorded event to the wire union. +fn entry_kind(kind: &TranscriptEntryKind) -> EntryKind { + match kind { + TranscriptEntryKind::Message { + role, + source, + text, + call_id, + } => EntryKind::Message { + role: (*role).into(), + source: source_label(*source).to_owned(), + text: text.clone(), + call_id: call_id.clone(), + }, + TranscriptEntryKind::TurnStarted { request_id } => EntryKind::TurnStarted { + request_id: *request_id, + }, + TranscriptEntryKind::TurnCompleted { request_id } => EntryKind::TurnCompleted { + request_id: *request_id, + }, + TranscriptEntryKind::TurnFailed { request_id, code } => EntryKind::TurnFailed { + request_id: *request_id, + code: Some(code.clone()), + }, + TranscriptEntryKind::ToolRequested { + request_id, + call_id, + tool, + arguments, + } => EntryKind::ToolRequested { + request_id: *request_id, + call_id: call_id.clone(), + tool: tool.clone(), + arguments: arguments.clone(), + }, + TranscriptEntryKind::ToolCompleted { + request_id, + call_id, + outcome, + code, + output_bytes, + output_sha256: _, + } => EntryKind::ToolCompleted { + request_id: *request_id, + call_id: call_id.clone(), + outcome: (*outcome).into(), + code: code.clone(), + output_bytes: *output_bytes, + }, + TranscriptEntryKind::RequestManifest { + request_id, + model, + prompt_version, + tools, + } => EntryKind::RequestManifest { + request_id: *request_id, + model: model.clone(), + prompt_version: prompt_version.clone(), + tools: tools.clone(), + }, + TranscriptEntryKind::ContextCompacted { record } => EntryKind::ContextCompacted { + summary: record.summary.clone(), + compacted_messages: record.compacted_messages, + model: record.model.clone(), + }, + TranscriptEntryKind::SessionArchived => EntryKind::SessionArchived, + TranscriptEntryKind::SessionRestored => EntryKind::SessionRestored, + } +} + +/// Bytes of recorded text an entry adds to a page. +fn entry_text_bytes(kind: &EntryKind) -> usize { + match kind { + EntryKind::Message { text, .. } => text.len(), + EntryKind::ToolRequested { + arguments, tool, .. + } => arguments.len().saturating_add(tool.len()), + EntryKind::ContextCompacted { summary, .. } => summary.len(), + EntryKind::RequestManifest { tools, .. } => tools + .iter() + .fold(0_usize, |total, tool| total.saturating_add(tool.len())), + EntryKind::TurnStarted { .. } + | EntryKind::TurnCompleted { .. } + | EntryKind::TurnFailed { .. } + | EntryKind::ToolCompleted { .. } + | EntryKind::SessionArchived + | EntryKind::SessionRestored => 0, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn group_ids_are_sixteen_hex_characters_and_depend_on_the_encoding() { + let unix = group_key(Some(&NativePath::UnixBytes(vec![b'a']))); + assert_eq!(unix.len(), 64); + let windows = group_key(Some(&NativePath::WindowsUtf16(vec![u16::from(b'a')]))); + assert_eq!(unix.chars().take(GROUP_ID_CHARS).count(), 16); + assert!(unix.bytes().all(|byte| byte.is_ascii_hexdigit())); + assert_ne!(unix, windows); + assert_eq!(group_key(None), "unknown"); + } + + #[test] + fn paths_that_differ_only_by_the_verbatim_prefix_are_separate_groups() { + let units = |text: &str| NativePath::WindowsUtf16(text.encode_utf16().collect()); + let verbatim = group_key(Some(&units(r"\\?\C:\proj"))); + let plain = group_key(Some(&units(r"C:\proj"))); + assert_ne!(verbatim, plain); + assert_ne!( + verbatim.chars().take(GROUP_ID_CHARS).collect::(), + plain.chars().take(GROUP_ID_CHARS).collect::() + ); + } +} diff --git a/crates/omgcode-app/src/desktop/state.rs b/crates/omgcode-app/src/desktop/state.rs new file mode 100644 index 0000000..38d2c50 --- /dev/null +++ b/crates/omgcode-app/src/desktop/state.rs @@ -0,0 +1,361 @@ +//! Shared helpers over the service state: locks, bounded refresh, journal +//! resolution, the settings-store opener, and session summaries. + +use std::collections::HashSet; +use std::path::PathBuf; +use std::sync::MutexGuard; +use std::thread; +use std::time::{Duration, Instant}; + +use omgcode_core::control::{ControlError, ControlStore}; +use omgcode_core::session::{NativePath, SessionInspection}; +use omgcode_core::session_index::{IndexedSession, IndexedState, SessionIndex}; +use omgcode_core::turn::display_safe_line; +use time::OffsetDateTime; +use time::format_description::well_known::Rfc3339; +use uuid::Uuid; + +use super::Inner; +use super::error::DesktopError; +use super::review_tokens::ReviewTokens; +use super::turns::TurnTable; +use super::wire::{SessionStatus, SessionSummary}; + +/// Journals inspected per `refresh` call. +const REFRESH_CHUNK: usize = 200; +/// Longest a bounded refresh keeps starting new chunks. +const REFRESH_DEADLINE: Duration = Duration::from_secs(2); +/// A completed refresh newer than this makes the next listing skip refreshing. +const REFRESH_REUSE: Duration = Duration::from_secs(1); +/// Longest a settings-store open waits for another holder. +const CONTROL_RETRY_DEADLINE: Duration = Duration::from_secs(2); +/// Pause between settings-store open attempts. +const CONTROL_RETRY_INTERVAL: Duration = Duration::from_millis(20); + +/// Folder text for a session whose journal recorded no workspace. +pub(super) const UNKNOWN_FOLDER: &str = "(unknown folder)"; +/// Title of a busy session the index never read. +const TITLE_IN_USE: &str = "(session in use)"; +/// Title of a session whose journal failed validation. +const TITLE_UNREADABLE: &str = "(unreadable session)"; +/// Title of a readable session that somehow has none. +const TITLE_UNTITLED: &str = "(untitled session)"; +/// Folder text for a path that another operating system recorded. +const FOLDER_NOT_REPRESENTABLE: &str = "(path not representable on this system)"; + +/// The index connection with its refresh bookkeeping. +pub(super) struct IndexState { + pub(super) index: SessionIndex, + /// When the last refresh that reached `remaining == 0` finished. + last_refresh: Option, + /// `skipped_links + unrecognized` of the last refresh report. + pub(super) skipped_entries: u64, +} + +impl IndexState { + pub(super) const fn new(index: SessionIndex) -> Self { + Self { + index, + last_refresh: None, + skipped_entries: 0, + } + } + + /// Bring the index up to date within a time bound. + /// + /// Calls `refresh(200)` until nothing remains or the deadline passes. A + /// refresh that stops at the deadline is partial; the next call continues. + /// Unless `force` is set, a completed refresh less than a second old is + /// reused. + pub(super) fn refresh_bounded(&mut self, force: bool) -> Result<(), DesktopError> { + if !force + && self + .last_refresh + .is_some_and(|finished| finished.elapsed() < REFRESH_REUSE) + { + return Ok(()); + } + let started = Instant::now(); + loop { + let report = self + .index + .refresh(REFRESH_CHUNK) + .map_err(|error| DesktopError::from_index(&error))?; + self.skipped_entries = report.skipped_links.saturating_add(report.unrecognized); + if report.remaining == 0 { + self.last_refresh = Some(Instant::now()); + return Ok(()); + } + if started.elapsed() >= REFRESH_DEADLINE { + return Ok(()); + } + } + } +} + +impl Inner { + pub(super) fn lock_index(&self) -> Result, DesktopError> { + self.index.lock().map_err(|_| DesktopError::poisoned()) + } + + pub(super) fn lock_turns(&self) -> Result, DesktopError> { + self.turns.lock().map_err(|_| DesktopError::poisoned()) + } + + pub(super) fn lock_reviews(&self) -> Result, DesktopError> { + self.reviews.lock().map_err(|_| DesktopError::poisoned()) + } + + /// Run `action` with the index locked. Keep `action` short. + pub(super) fn with_index( + &self, + action: impl FnOnce(&mut IndexState) -> Result, + ) -> Result { + let mut state = self.lock_index()?; + action(&mut state) + } + + /// The sessions with a chat turn running in this service. + pub(super) fn running_sessions(&self) -> Result, DesktopError> { + self.reap()?; + Ok(self.lock_turns()?.running_ids()) + } + + /// Whether a chat turn for `session_id` is running in this service. + pub(super) fn is_running(&self, session_id: Uuid) -> Result { + self.reap()?; + Ok(self.lock_turns()?.is_running(session_id)) + } + + /// Resolve a session's journal path, only through the index. + /// + /// An unknown session triggers one bounded refresh and a retry. + pub(super) fn resolve_path(&self, session_id: Uuid) -> Result { + self.with_index(|state| { + let lookup = |state: &IndexState| { + state + .index + .journal_path(session_id) + .map_err(|error| DesktopError::from_index(&error)) + }; + if let Some(path) = lookup(state)? { + return Ok(path); + } + state.refresh_bounded(true)?; + lookup(state)?.ok_or_else(|| DesktopError::not_found("session")) + }) + } + + /// Open the existing settings store, waiting briefly for another holder. + /// + /// `Ok(None)` means no store exists. No service lock is held while waiting. + pub(super) fn open_control(&self) -> Result, DesktopError> { + let deadline = Instant::now() + CONTROL_RETRY_DEADLINE; + loop { + match ControlStore::open_existing(&self.data_root) { + Ok(store) => return Ok(store), + Err(ControlError::Busy) if Instant::now() < deadline => { + thread::sleep(CONTROL_RETRY_INTERVAL); + } + Err(error) => return Err(DesktopError::from_control(&error)), + } + } + } +} + +/// The status of an indexed session. A turn running here wins over everything, +/// because on Windows the journal is locked while the turn runs. +pub(super) fn status_of(session: &IndexedSession, running: &HashSet) -> SessionStatus { + if running.contains(&session.session_id) { + return SessionStatus::Running; + } + match session.state { + IndexedState::Invalid => SessionStatus::Invalid, + IndexedState::Busy => SessionStatus::Busy, + IndexedState::Ok if session.active_turn.is_some() => SessionStatus::TurnOpen, + IndexedState::Ok => SessionStatus::Idle, + } +} + +/// Summarize an indexed session for the interface. +pub(super) fn summary_of(session: &IndexedSession, running: &HashSet) -> SessionSummary { + let status = status_of(session, running); + let placeholder = match status { + SessionStatus::Invalid => TITLE_UNREADABLE, + SessionStatus::Idle | SessionStatus::TurnOpen => TITLE_UNTITLED, + SessionStatus::Running | SessionStatus::Busy => TITLE_IN_USE, + }; + SessionSummary { + session_id: session.session_id, + title: session + .title + .as_deref() + .map_or_else(|| placeholder.to_owned(), display_safe_line), + created_at: session.created_at.and_then(format_time), + updated_at: session.updated_at.and_then(format_time), + status, + archived: session.archived, + event_count: session.event_count, + invalid_code: if status == SessionStatus::Invalid { + session.invalid_code.clone() + } else { + None + }, + } +} + +/// Rewrite a Windows verbatim path as the text people expect to read. +/// +/// `\\?\UNC\server\share\x` becomes `\\server\share\x` and `\\?\C:\x` becomes +/// `C:\x`. Every other text is returned unchanged: other verbatim forms such as +/// `\\?\Volume{...}\`, `\\.\` device paths, a `\\?\` that is not at the start, +/// and every non-Windows path. +/// +/// This is display text only. Never use the result to open, compare, group, or +/// authorize a path; those keep the recorded value. Escape the result with +/// [`display_safe_line`] afterwards. +pub(super) fn windows_display_path(text: &str) -> String { + const VERBATIM: &str = r"\\?\"; + let Some(rest) = text.strip_prefix(VERBATIM) else { + return text.to_owned(); + }; + // `get(..4)` is a character-boundary-checked slice, so no panic on text. + if let Some(head) = rest.get(..4) + && head.eq_ignore_ascii_case(r"UNC\") + && let Some(share) = rest.get(4..) + && !share.is_empty() + { + return format!(r"\\{share}"); + } + let mut characters = rest.chars(); + if let (Some(letter), Some(':')) = (characters.next(), characters.next()) + && letter.is_ascii_alphabetic() + && matches!(characters.next(), None | Some('\\')) + { + return rest.to_owned(); + } + text.to_owned() +} + +/// Escape folder text for display after the verbatim prefix is removed. +fn folder_text(raw: &str) -> String { + display_safe_line(&windows_display_path(raw)) +} + +/// The display-safe folder text of an indexed session. +pub(super) fn folder_of(session: &IndexedSession) -> String { + session + .folder_display + .as_deref() + .filter(|text| !text.is_empty()) + .map_or_else(|| UNKNOWN_FOLDER.to_owned(), folder_text) +} + +/// The display-safe folder text of a registered workspace directory, or the +/// not-representable text when this system cannot form the path. +pub(super) fn folder_of_directory(directory: Option) -> String { + directory.map_or_else( + || FOLDER_NOT_REPRESENTABLE.to_owned(), + |path| folder_text(&path.to_string_lossy()), + ) +} + +/// Summarize a fresh inspection. No turn of this session runs here. +pub(super) fn summary_of_inspection(inspection: &SessionInspection) -> SessionSummary { + SessionSummary { + session_id: inspection.session_id, + title: display_safe_line(&inspection.title), + created_at: format_time(inspection.created_at), + updated_at: format_time(inspection.updated_at), + status: if inspection.active_turn.is_some() { + SessionStatus::TurnOpen + } else { + SessionStatus::Idle + }, + archived: inspection.archived, + event_count: inspection.event_count, + invalid_code: None, + } +} + +/// The display-safe folder text of a recorded native path. +pub(super) fn folder_of_path(path: &NativePath) -> String { + folder_of_directory(path.to_path_buf().ok()) +} + +/// Format a time as RFC 3339, or `None` when it is outside the format's range. +pub(super) fn format_time(time: OffsetDateTime) -> Option { + time.format(&Rfc3339).ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn verbatim_drive_and_unc_paths_are_rewritten() { + assert_eq!( + windows_display_path(r"\\?\C:\Users\me\proj"), + r"C:\Users\me\proj" + ); + assert_eq!(windows_display_path(r"\\?\c:\x"), r"c:\x"); + assert_eq!(windows_display_path(r"\\?\Z:"), "Z:"); + assert_eq!( + windows_display_path(r"\\?\UNC\server\share\x"), + r"\\server\share\x" + ); + assert_eq!( + windows_display_path(r"\\?\unc\server\share"), + r"\\server\share" + ); + } + + #[test] + fn other_text_is_returned_unchanged() { + for text in [ + "", + "/home/me/proj", + r"C:\Users\me", + r"\\server\share", + r"\\?\Volume{01234567-89ab-cdef-0123-456789abcdef}\x", + r"\\.\COM1", + r"\\.\C:\x", + r"\\?\UNC\", + r"\\?\UNC", + r"\\?\C", + r"\\?\1:\x", + r"\\?\C:x", + r"D:\a\\?\C:\x", + r"\\?\", + "\\\\?\\\u{e9}\u{e9}\u{e9}", + ] { + assert_eq!(windows_display_path(text), text, "{text:?}"); + } + } + + #[test] + fn hostile_text_after_the_prefix_is_still_escaped() { + assert_eq!( + folder_text("\\\\?\\C:\\evil\u{202e}dir\nnext"), + "C:\\evil\\u{202e}dir\\u{000a}next" + ); + assert_eq!( + folder_text("\\\\?\\UNC\\srv\u{200b}\\share"), + "\\\\srv\\u{200b}\\share" + ); + // A forged escape after the rewrite is still neutralised. + assert_eq!(folder_text("\\\\?\\C:\\u{202e}"), "C:\\u{5c}u{202e}"); + } + + #[test] + fn a_directory_that_cannot_be_formed_keeps_its_text() { + assert_eq!( + folder_of_directory(None), + "(path not representable on this system)" + ); + assert_eq!( + folder_of_directory(Some(PathBuf::from("/work/a\u{202e}b"))), + "/work/a\\u{202e}b" + ); + } +} diff --git a/crates/omgcode-app/src/desktop/turns.rs b/crates/omgcode-app/src/desktop/turns.rs new file mode 100644 index 0000000..d54493a --- /dev/null +++ b/crates/omgcode-app/src/desktop/turns.rs @@ -0,0 +1,428 @@ +//! The table of chat turns and the thread that runs each one. +//! +//! A turn owns, for its whole life, the journal handle, the validated clients, +//! and the server token, all on its own thread. The table holds only what other +//! threads need: the state, the cancel token, and the `JoinHandle`. The table +//! lock is held for short bookkeeping and never while the turn runs, while a +//! thread is joined, or while the index is refreshed. + +use std::collections::{HashMap, HashSet}; +use std::fmt; +use std::path::PathBuf; +use std::sync::Arc; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; + +use omgcode_core::session::SessionJournal; +use omgcode_core::turn::CancelToken; +use uuid::Uuid; + +use super::Inner; +use super::error::DesktopError; +use super::wire::{ChatOutcome, ContextMeterDto, ToolsMode}; +use crate::{ + ChatClients, ChatHooks, ChatSettings, ChatTurnInput, ChatTurnOutput, run_chat_turn_with_clients, +}; + +/// Most chat turns that run at once. +pub(super) const MAX_RUNNING_TURNS: usize = 2; +/// Most finished results kept; the oldest is evicted first. +pub(super) const MAX_FINISHED_TURNS: usize = 64; +/// Name of every turn thread. +pub(super) const TURN_THREAD_NAME: &str = "omgcode-turn"; +/// How often shutdown checks whether turn threads have finished. +const SHUTDOWN_POLL: Duration = Duration::from_millis(10); +/// Message of a turn thread that ended without recording a result. +const STOPPED_UNEXPECTEDLY: &str = "The chat turn stopped unexpectedly."; + +/// What happened to the threads that were in flight when shutdown began. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ShutdownReport { + /// Turn threads that were in flight at the start and have finished. + pub finished: usize, + /// Turn threads still running when the grace period ended. A provider + /// request cannot be interrupted, so such a thread may still be waiting on + /// the model; its journal is left with an open turn. + pub still_running: usize, +} + +/// The local server token, held only for the life of one turn. +/// +/// It has no `Serialize` and a redacted `Debug`, so it cannot reach a +/// response, an error, or a log line by accident. +pub(super) struct LmToken(String); + +impl LmToken { + pub(super) const fn new(value: String) -> Self { + Self(value) + } + + pub(super) fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Debug for LmToken { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("LmToken()") + } +} + +/// Where one session's turn stands. +pub(super) enum SlotState { + /// The turn is running. + Running { + /// A cancel was requested (it may have no token to act on yet). + cancel_requested: bool, + /// The tool-enabled path's cancel token, once it exists. + cancel: Option, + }, + /// The turn ended. + Finished(Box>), +} + +/// One session's slot. +pub(super) struct Slot { + pub(super) state: SlotState, + /// The turn thread, until it is joined. + handle: Option>, + /// Order in which finished slots were finished; smaller is older. + finished_order: u64, +} + +/// All slots, keyed by session. +#[derive(Default)] +pub(super) struct TurnTable { + slots: HashMap, + next_order: u64, + /// Set by shutdown; no new turn starts afterwards. + closed: bool, +} + +impl TurnTable { + pub(super) const fn is_closed(&self) -> bool { + self.closed + } + + pub(super) fn slot(&self, session_id: Uuid) -> Option<&Slot> { + self.slots.get(&session_id) + } + + pub(super) fn is_running(&self, session_id: Uuid) -> bool { + self.slots + .get(&session_id) + .is_some_and(|slot| matches!(slot.state, SlotState::Running { .. })) + } + + pub(super) fn running_ids(&self) -> HashSet { + self.slots + .iter() + .filter(|(_, slot)| matches!(slot.state, SlotState::Running { .. })) + .map(|(id, _)| *id) + .collect() + } + + pub(super) fn running_count(&self) -> usize { + self.slots + .values() + .filter(|slot| matches!(slot.state, SlotState::Running { .. })) + .count() + } + + /// Slots whose thread has not been joined yet. + fn unjoined_count(&self) -> usize { + self.slots + .values() + .filter(|slot| slot.handle.is_some()) + .count() + } + + /// Insert a running slot, replacing a finished one for the same session and + /// evicting the oldest joined finished slots beyond the bound. + pub(super) fn insert_running(&mut self, session_id: Uuid, handle: JoinHandle<()>) { + self.slots.insert( + session_id, + Slot { + state: SlotState::Running { + cancel_requested: false, + cancel: None, + }, + handle: Some(handle), + finished_order: 0, + }, + ); + loop { + let mut finished: Vec<(Uuid, u64)> = self + .slots + .iter() + .filter(|(_, slot)| { + matches!(slot.state, SlotState::Finished(_)) && slot.handle.is_none() + }) + .map(|(id, slot)| (*id, slot.finished_order)) + .collect(); + if finished.len() <= MAX_FINISHED_TURNS { + return; + } + finished.sort_by_key(|(_, order)| *order); + match finished.first() { + Some((oldest, _)) => { + self.slots.remove(oldest); + } + None => return, + } + } + } + + /// Record a cancel request. Returns without effect for a slot that is not running. + pub(super) fn request_cancel(&mut self, session_id: Uuid) { + if let Some(Slot { + state: + SlotState::Running { + cancel_requested, + cancel, + }, + .. + }) = self.slots.get_mut(&session_id) + { + *cancel_requested = true; + if let Some(token) = cancel { + token.cancel(); + } + } + } + + /// Request cancellation of every running turn. + fn request_cancel_all(&mut self) { + for slot in self.slots.values_mut() { + if let SlotState::Running { + cancel_requested, + cancel, + } = &mut slot.state + { + *cancel_requested = true; + if let Some(token) = cancel { + token.cancel(); + } + } + } + } + + /// Store the tool path's cancel token, acting on an earlier request. + fn store_cancel_token(&mut self, session_id: Uuid, token: CancelToken) { + if let Some(Slot { + state: + SlotState::Running { + cancel_requested, + cancel, + }, + .. + }) = self.slots.get_mut(&session_id) + { + if *cancel_requested { + token.cancel(); + } + *cancel = Some(token); + } + } + + /// End a running slot with `result`. + fn finish(&mut self, session_id: Uuid, result: Result) { + let order = self.next_order; + if let Some(slot) = self.slots.get_mut(&session_id) + && matches!(slot.state, SlotState::Running { .. }) + { + slot.state = SlotState::Finished(Box::new(result)); + slot.finished_order = order; + self.next_order = order.saturating_add(1); + } + } +} + +impl Inner { + /// Join turn threads that have finished. + /// + /// Handles are taken out under the lock and joined after it is released. A + /// thread that panicked leaves its slot `running`, so it is recorded as + /// `failed` with `internal`. + pub(super) fn reap(&self) -> Result<(), DesktopError> { + let finished: Vec<(Uuid, JoinHandle<()>)> = { + let mut turns = self.lock_turns()?; + let ids: Vec = turns + .slots + .iter() + .filter(|(_, slot)| slot.handle.as_ref().is_some_and(JoinHandle::is_finished)) + .map(|(id, _)| *id) + .collect(); + ids.into_iter() + .filter_map(|id| { + turns + .slots + .get_mut(&id) + .and_then(|slot| slot.handle.take()) + .map(|handle| (id, handle)) + }) + .collect() + }; + for (session_id, handle) in finished { + // The thread already finished, so this join returns at once. + if handle.join().is_err() { + self.lock_turns()?.finish( + session_id, + Err(DesktopError::internal(STOPPED_UNEXPECTEDLY)), + ); + } + } + Ok(()) + } + + /// Request cancellation of every turn, wait up to `grace`, and report. + pub(super) fn shutdown_turns(&self, grace: Duration) -> ShutdownReport { + let deadline = Instant::now().checked_add(grace); + let in_flight = match self.lock_turns() { + Ok(mut turns) => { + turns.closed = true; + turns.request_cancel_all(); + turns.unjoined_count() + } + // A poisoned table cannot be inspected or cancelled; nothing is + // known to be finished. + Err(_) => { + return ShutdownReport { + finished: 0, + still_running: 0, + }; + } + }; + let mut remaining = in_flight; + loop { + if self.reap().is_err() { + break; + } + remaining = self + .lock_turns() + .map_or(remaining, |turns| turns.unjoined_count()); + let expired = deadline.is_none_or(|limit| Instant::now() >= limit); + if remaining == 0 || expired { + break; + } + thread::sleep(SHUTDOWN_POLL); + } + ShutdownReport { + finished: in_flight.saturating_sub(remaining), + still_running: remaining, + } + } + + /// Hand the tool path's cancel token to the slot. + fn hand_over_cancel_token(&self, session_id: Uuid, token: CancelToken) { + // A poisoned table is reported to every caller of the service; the + // turn simply cannot be cancelled and runs to its deadline. + if let Ok(mut turns) = self.lock_turns() { + turns.store_cancel_token(session_id, token); + } + } + + /// Record the end of a turn. + fn record_finish(&self, session_id: Uuid, result: Result) { + // A poisoned table is reported to every caller of the service; the + // thread has nothing left to do either way. + if let Ok(mut turns) = self.lock_turns() { + turns.finish(session_id, result); + } + } +} + +/// Everything a turn thread owns. +pub(super) struct TurnJob { + pub(super) session_id: Uuid, + pub(super) path: PathBuf, + pub(super) message: String, + pub(super) settings: ChatSettings, + pub(super) token: Option, + pub(super) clients: ChatClients, +} + +/// Start the turn thread. +/// +/// The caller holds the `turns` lock; the thread does not need it until it +/// stores its cancel token, so it waits there briefly if it is fast. +pub(super) fn spawn_turn(inner: &Arc, job: TurnJob) -> Result, DesktopError> { + let worker = Arc::clone(inner); + thread::Builder::new() + .name(TURN_THREAD_NAME.to_owned()) + .spawn(move || run_turn(&worker, job)) + .map_err(|_| DesktopError::internal("The chat turn could not be started.")) +} + +/// The body of a turn thread. +fn run_turn(inner: &Inner, job: TurnJob) { + let session_id = job.session_id; + let result = execute(inner, &job); + // The journal handle is gone, so the index can read the finished journal. + // A failed refresh leaves the cache stale until the next listing refresh; + // the journal remains the source of truth, so it is not a turn failure. + drop(inner.with_index(|state| { + state + .index + .refresh_session(session_id) + .map_err(|error| DesktopError::from_index(&error)) + })); + inner.record_finish(session_id, result); +} + +/// Open the journal, run the turn, and drop the journal before returning. +fn execute(inner: &Inner, job: &TurnJob) -> Result { + let token = job.token.as_ref().map(LmToken::as_str); + let mut journal = + SessionJournal::open(&job.path).map_err(|error| DesktopError::from_session(&error))?; + let session_id = job.session_id; + let mut hand_over = |cancel: CancelToken| inner.hand_over_cancel_token(session_id, cancel); + let mut hooks = ChatHooks { + on_cancel_token: Some(&mut hand_over), + }; + let result = run_chat_turn_with_clients( + &mut journal, + &inner.data_root, + &ChatTurnInput { + message: &job.message, + settings: &job.settings, + token, + }, + &job.clients, + &mut hooks, + ); + drop(journal); + match result { + Ok(output) => Ok(outcome_of(&output)), + Err(error) => { + // Defence in depth: the application layer keeps the token out of + // messages, and this removes it again if that ever failed. + Err(DesktopError::from_app(&error).redacted(token)) + } + } +} + +/// Map a completed turn to the wire outcome. +fn outcome_of(output: &ChatTurnOutput) -> ChatOutcome { + let context = output.context(); + let count = + |value: Option| value.map_or(0, |count| u64::try_from(count).unwrap_or(u64::MAX)); + ChatOutcome { + finish_reason: output.finish_reason().to_owned(), + tools_mode: if output.tools_enabled() { + ToolsMode::Enabled + } else { + ToolsMode::Disabled + }, + tools_disabled_reason: output.disabled_reason().map(str::to_owned), + rounds: count(output.rounds()), + tool_calls: count(output.tool_calls()), + withheld_tool_results: u64::try_from(output.withheld_tool_results()).unwrap_or(u64::MAX), + context: Some(ContextMeterDto { + estimated_tokens: context.estimated_input_tokens(), + trigger_tokens: context.effective_trigger(), + context_tokens: context.context_tokens(), + compacted: context.compaction().is_some(), + }), + } +} diff --git a/crates/omgcode-app/src/desktop/wire.rs b/crates/omgcode-app/src/desktop/wire.rs new file mode 100644 index 0000000..c1d67ea --- /dev/null +++ b/crates/omgcode-app/src/desktop/wire.rs @@ -0,0 +1,663 @@ +//! Request and response shapes of the desktop command surface. +//! +//! These types are the Rust side of the wire contract that the interface +//! declares in `crates/omgcode-desktop/ui/src/ipc/types.ts`. Field names are +//! `snake_case`; an optional value that the interface types as `T | null` is +//! always present and serializes as `null` when absent. +//! +//! Requests derive `Deserialize` with `deny_unknown_fields`, so a caller cannot +//! smuggle an extra field, and no request type carries a filesystem path. +//! Responses derive `Serialize` only. Every response label that comes from +//! recorded data has already passed through core's display-safe escaping where +//! the service contract says so; transcript text, tool arguments, and search +//! snippets are returned as recorded and must be rendered as text. + +use omgcode_core::control::{ApprovalOperation, ApprovalState}; +use omgcode_core::session::{MessageRole, MessageSource, ToolOutcome}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use super::error::DesktopError; + +/// Whether a listing or search covers active or archived sessions. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum TreeView { + /// Sessions that are not archived. + Active, + /// Archived sessions. + Archived, +} + +/// The key a session listing sorts by. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum TreeSort { + /// Time of the last complete event. + Updated, + /// Time of the session start. + Created, + /// Title, case-insensitive. + Title, +} + +/// Arguments of `session_tree`. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct TreeRequest { + /// Active or archived sessions. + pub view: TreeView, + /// The sort key. + pub sort: TreeSort, + /// Sort largest or latest first (last to first for titles). + pub descending: bool, +} + +/// Arguments of `session_search`. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct SearchRequest { + /// The text to search for. It is never search-engine syntax. + pub query: String, + /// Active or archived sessions. + pub view: TreeView, + /// Most hits to return, clamped to 1 through 200. + pub limit: u32, +} + +/// Arguments of `session_transcript`. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct TranscriptRequest { + /// The session to read. + pub session_id: Uuid, + /// Return entries with a larger sequence number; `null` starts at the top. + pub after_seq: Option, + /// Most entries to return, clamped to 1 through 200. + pub limit: u32, +} + +/// Arguments of every command that names only a session. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct SessionRequest { + /// The session to act on. + pub session_id: Uuid, +} + +/// Arguments of `session_create`. A caller names a registered workspace by +/// identifier and never supplies a path. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct SessionCreateRequest { + /// A workspace the operator registered with the trusted CLI. + pub workspace_id: Uuid, + /// The new session's title; core validates it. + pub title: String, +} + +/// Chat settings as the interface sends and receives them. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct ChatSettingsDto { + /// Must equal the endpoint the service was opened with. + pub endpoint: String, + /// The model identifier available on the selected server. + pub model: String, + /// Validated context capacity of the loaded model. + pub context_tokens: u64, + /// Output reserve for each model request. + pub max_output_tokens: u32, + /// User-level preferences, sent as untrusted-origin custom instructions. + pub instructions: String, + /// Compact before a turn when the estimate reaches this value. + pub compact_threshold: u64, + /// Whether to compact at the effective trigger before a turn. + pub auto_compact: bool, +} + +/// Arguments of `chat_send`. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct ChatSendRequest { + /// The session to chat in. + pub session_id: Uuid, + /// The user's message. + pub message: String, + /// Model and budgets for this turn. + pub settings: ChatSettingsDto, +} + +/// Arguments of `approval_detail`. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct ApprovalRequest { + /// The approval record to review. + pub id: Uuid, +} + +/// The operator's decision. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum Decision { + /// Grant the approval. + Approve, + /// Refuse the approval. + Deny, +} + +/// Arguments of `approval_decide`. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct ApprovalDecideRequest { + /// The approval record to decide. + pub id: Uuid, + /// Approve or deny. + pub decision: Decision, + /// The operator's writers-stopped acknowledgement; used for `file_write`. + pub writers_stopped: bool, + /// The token `approval_detail` returned; required to approve. + pub review_token: Option, +} + +/// How a session is doing, for display. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum SessionStatus { + /// Nothing is running and no turn is open. + Idle, + /// A chat turn is running in this service. + Running, + /// The journal records a turn that never finished. + TurnOpen, + /// Another process holds the journal. + Busy, + /// The journal failed validation. + Invalid, +} + +/// One session as the tree, search, and lifecycle commands show it. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct SessionSummary { + /// The session identifier. + pub session_id: Uuid, + /// Display-safe title, or a fixed placeholder when none is known. + pub title: String, + /// RFC 3339 start time, when known. + pub created_at: Option, + /// RFC 3339 time of the last event, when known. + pub updated_at: Option, + /// The session's status. + pub status: SessionStatus, + /// Whether the session is archived. + pub archived: bool, + /// Number of complete journal events. + pub event_count: u64, + /// Stable failure code for an `invalid` journal. + pub invalid_code: Option, +} + +/// Sessions that share a recorded workspace folder. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct WorkspaceGroup { + /// An opaque stable identifier of the folder. + pub group_id: String, + /// Display-safe folder text. Never used to open anything. + pub folder_display: String, + /// The group's sessions in listing order. + pub sessions: Vec, +} + +/// The `session_tree` response. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct SessionTree { + /// Groups in order of first appearance. + pub groups: Vec, + /// How many sessions the view holds before the listing limit applied. + pub indexed_sessions: u64, + /// Directory entries the last refresh skipped as links or unrecognized. + pub skipped_entries: u64, +} + +/// A run of snippet text. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct SnippetPart { + /// Recorded text. + pub text: String, + /// Whether the search matched this run. + pub matched: bool, +} + +/// What kind of text a search hit matched. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum SearchRoleDto { + /// A user message. + User, + /// An assistant message. + Assistant, + /// A tool result message. + Tool, + /// A compaction summary. + Summary, + /// The session title. + Title, +} + +/// One matching text. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct SearchHit { + /// The session the text belongs to. + pub session: SessionSummary, + /// Display-safe folder text. + pub folder_display: String, + /// The journal sequence number, or `null` for a title. + pub seq: Option, + /// What matched. + pub role: SearchRoleDto, + /// Text around the match. + pub snippet: Vec, +} + +/// The `session_search` response. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct SearchResult { + /// Hits in relevance order. + pub hits: Vec, + /// Whether more hits exist than the limit allowed. + pub truncated: bool, +} + +/// The role of a recorded message. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum MessageRoleDto { + /// A user message. + User, + /// An assistant message. + Assistant, + /// A tool result message. + Tool, +} + +impl From for MessageRoleDto { + fn from(role: MessageRole) -> Self { + match role { + MessageRole::User => Self::User, + MessageRole::Assistant => Self::Assistant, + MessageRole::Tool => Self::Tool, + } + } +} + +/// The core-observed outcome of a tool call. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ToolOutcomeDto { + /// The operation completed. + Succeeded, + /// The request failed. + Failed, + /// Policy denied the operation. + Denied, +} + +impl From for ToolOutcomeDto { + fn from(outcome: ToolOutcome) -> Self { + match outcome { + ToolOutcome::Succeeded => Self::Succeeded, + ToolOutcome::Failed => Self::Failed, + ToolOutcome::Denied => Self::Denied, + } + } +} + +/// The recorded origin label of a message, as text. +pub(super) const fn source_label(source: MessageSource) -> &'static str { + match source { + MessageSource::UserCli => "user_cli", + MessageSource::Provider => "provider", + MessageSource::CoreTool => "core_tool", + } +} + +/// The recorded data of one transcript event. All text is untrusted. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum EntryKind { + /// A user, assistant, or tool message. + Message { + /// Display role. + role: MessageRoleDto, + /// Recorded origin label. + source: String, + /// Message text as recorded. + text: String, + /// Tool call identifier, only on tool messages. + call_id: Option, + }, + /// A turn began. + TurnStarted { + /// The turn identifier. + request_id: Uuid, + }, + /// A turn completed. + TurnCompleted { + /// The turn identifier. + request_id: Uuid, + }, + /// A turn failed. + TurnFailed { + /// The turn identifier. + request_id: Uuid, + /// The recorded failure code. + code: Option, + }, + /// The model asked for a tool call. + ToolRequested { + /// The turn identifier. + request_id: Uuid, + /// Provider call identifier. + call_id: String, + /// Requested tool name. + tool: String, + /// Exact arguments text as recorded. + arguments: String, + }, + /// Core recorded a tool call's outcome. + ToolCompleted { + /// The turn identifier. + request_id: Uuid, + /// Provider call identifier. + call_id: String, + /// The observed outcome. + outcome: ToolOutcomeDto, + /// Stable error code for a failed or denied call. + code: Option, + /// Size of the rendered output. + output_bytes: u64, + }, + /// The descriptive part of a request manifest. + RequestManifest { + /// The turn identifier. + request_id: Uuid, + /// The model used. + model: String, + /// The compiled base prompt's version label. + prompt_version: String, + /// Tool names advertised to the model. + tools: Vec, + }, + /// A summary replaced earlier messages. + ContextCompacted { + /// The summary text, which is untrusted model output. + summary: String, + /// How many messages it represents. + compacted_messages: u64, + /// The summarizer model. + model: String, + }, + /// The session was archived. + SessionArchived, + /// The session was restored. + SessionRestored, +} + +/// One transcript event. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct TranscriptEntry { + /// Zero-based journal sequence number. + pub seq: u64, + /// RFC 3339 event time. + pub timestamp: String, + /// The event and its data. + #[serde(flatten)] + pub kind: EntryKind, +} + +/// The `session_transcript` response. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct TranscriptPage { + /// The session, summarized from the inspection this page came from. + pub session: SessionSummary, + /// Display-safe folder text. + pub folder_display: String, + /// Entries in journal order. + pub entries: Vec, + /// The last returned sequence number when more entries remain. + pub next_after_seq: Option, + /// Whether bytes followed the last complete record when inspected. + pub incomplete_tail: bool, +} + +/// How full the model context is. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +pub struct ContextMeterDto { + /// Conservative estimate of the input tokens. + pub estimated_tokens: u64, + /// The effective compaction trigger. + pub trigger_tokens: u64, + /// The model's context capacity. + pub context_tokens: u64, + /// Whether a compaction summary is active. + pub compacted: bool, +} + +/// Whether the turn offered workspace tools. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ToolsMode { + /// Tools were offered. + Enabled, + /// A text-only turn. + Disabled, +} + +/// What a completed turn reports. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct ChatOutcome { + /// The provider finish reason. + pub finish_reason: String, + /// Whether tools were offered. + pub tools_mode: ToolsMode, + /// Why a text-only turn offered no tools. + pub tools_disabled_reason: Option, + /// Model requests made; 0 for a text-only turn. + pub rounds: u64, + /// Tool calls dispatched; 0 for a text-only turn. + pub tool_calls: u64, + /// Saved tool results replaced by a withheld notice. + pub withheld_tool_results: u64, + /// The context accounting. + pub context: Option, +} + +/// The state of a session's chat turn. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ChatState { + /// The service has no record for the session. + Idle, + /// A turn is running. + Running, + /// A turn is running and cancellation was requested. + Cancelling, + /// The last turn completed. + Completed, + /// The last turn failed. + Failed, +} + +/// The `chat_*` response. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct ChatStatus { + /// The session. + pub session_id: Uuid, + /// The turn state. + pub state: ChatState, + /// The outcome of a completed turn. + pub outcome: Option, + /// The failure of a failed turn. + pub error: Option, +} + +/// A workspace the operator registered, with its saved preferences. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct WorkspaceChoice { + /// The workspace identifier. + pub workspace_id: Uuid, + /// Display-safe folder text. + pub folder_display: String, + /// The model-tools preference. + pub model_tools: bool, + /// The read preference. + pub read: bool, + /// The write preference. + pub write: bool, + /// The execute preference. + pub execute: bool, +} + +/// The `workspace_list` response. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct WorkspaceList { + /// Whether the operator selected a development root. + pub development_root_set: bool, + /// Registered workspaces. + pub workspaces: Vec, +} + +/// The `approvals_summary` response. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +pub struct ApprovalsSummary { + /// How many approvals are pending. + pub pending: u64, +} + +/// What an approval covers. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ApprovalOperationDto { + /// Start a confined command. + Command, + /// Replace a workspace file. + FileWrite, + /// A Git operation with remote access. + GitPush, + /// A destination-scoped network operation. + Network, +} + +impl From for ApprovalOperationDto { + fn from(operation: ApprovalOperation) -> Self { + match operation { + ApprovalOperation::Command => Self::Command, + ApprovalOperation::FileWrite => Self::FileWrite, + ApprovalOperation::GitPush => Self::GitPush, + ApprovalOperation::Network => Self::Network, + } + } +} + +/// Where an approval stands. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ApprovalStateDto { + /// Waiting for a decision. + Pending, + /// Granted, not yet used. + Approved, + /// Refused. + Denied, + /// Used by exactly one call. + Consumed, + /// Past its lifetime. + Expired, +} + +impl From for ApprovalStateDto { + fn from(state: ApprovalState) -> Self { + match state { + ApprovalState::Pending => Self::Pending, + ApprovalState::Approved => Self::Approved, + ApprovalState::Denied => Self::Denied, + ApprovalState::Consumed => Self::Consumed, + ApprovalState::Expired => Self::Expired, + } + } +} + +/// One approval record, joined with its session's label. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct ApprovalView { + /// The approval identifier. + pub id: Uuid, + /// The session that asked. + pub session_id: Uuid, + /// Display-safe session title, when the index knows the session. + pub session_title: Option, + /// Display-safe folder text, when the index knows the session. + pub folder_display: Option, + /// What the approval covers. + pub operation: ApprovalOperationDto, + /// Display-safe one-line summary. + pub summary: String, + /// Where the approval stands. + pub state: ApprovalStateDto, + /// Unix time the request was recorded. + pub created_unix: u64, + /// Unix time the approval expires. + pub expires_unix: u64, + /// SHA-256 of the exact request the approval is bound to. + pub request_sha256: String, + /// Whether the operator acknowledged that other writers are stopped. + pub writers_stopped: bool, +} + +/// The `approvals_list` response. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct ApprovalList { + /// The service's current Unix time. + pub now_unix: u64, + /// Pending approvals first, then the most recent others. + pub approvals: Vec, +} + +/// One labelled, display-safe value of a reviewed request. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct ApprovalField { + /// The field label. + pub label: String, + /// The display-safe value. + pub value: String, + /// Whether the value may span lines. + pub multiline: bool, +} + +/// Whether the recorded request that an approval is bound to was found. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Binding { + /// A recorded request reproduces the approval's digest. + Exact, + /// Something of the right kind exists but nothing matches the digest. + Stale, + /// No recorded request exists to review. + NotFound, +} + +/// The `approval_detail` response. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct ApprovalDetail { + /// The approval record. + pub approval: ApprovalView, + /// The review result. + pub binding: Binding, + /// The reviewed tool, only for an `exact` binding. + pub tool: Option, + /// The reviewed fields, only for an `exact` binding. + pub fields: Vec, + /// A single-use token that allows one approve, only for an `exact`, + /// pending approval. + pub review_token: Option, +} diff --git a/crates/omgcode-app/src/desktop/workspaces.rs b/crates/omgcode-app/src/desktop/workspaces.rs new file mode 100644 index 0000000..9f8d252 --- /dev/null +++ b/crates/omgcode-app/src/desktop/workspaces.rs @@ -0,0 +1,95 @@ +//! Registered workspaces and session creation. +//! +//! A new session can be created only in a workspace the operator registered +//! with the trusted CLI. The caller names it by identifier; the path comes from +//! the settings store, never from the caller. + +use super::DesktopService; +use super::error::DesktopError; +use super::sessions::refreshed_summary; +use super::state::folder_of_directory; +use super::wire::{SessionCreateRequest, SessionSummary, WorkspaceChoice, WorkspaceList}; +use crate::create_session; + +impl DesktopService { + /// List the workspaces the operator registered, with their preferences. + /// + /// Without a settings store the list is empty and `development_root_set` is + /// false. The store is opened and released inside this call. + /// + /// # Errors + /// + /// `busy` when the settings store stays held past a two-second wait, + /// `control` when it is invalid. + pub fn workspace_list(&self) -> Result { + let Some(store) = self.inner.open_control()? else { + return Ok(WorkspaceList { + development_root_set: false, + workspaces: Vec::new(), + }); + }; + let development_root_set = store.has_development_root(); + let workspaces = store + .workspaces() + .map(|workspace| { + let permissions = workspace.permissions(); + WorkspaceChoice { + workspace_id: *workspace.id().as_uuid(), + folder_display: folder_of_directory(workspace.directory_path()), + model_tools: permissions.model_tools, + read: permissions.read, + write: permissions.write, + execute: permissions.execute, + } + }) + .collect(); + drop(store); + Ok(WorkspaceList { + development_root_set, + workspaces, + }) + } + + /// Create a session in a registered workspace. + /// + /// Core validates the title. The session is created exactly as the trusted + /// CLI creates one, its journal is released, the index learns about it, and + /// its summary is returned. + /// + /// # Errors + /// + /// `unknown_workspace` when the identifier is not registered, + /// `invalid_request` for an unusable title or a workspace path this system + /// cannot represent, `busy`, `control`, or `session`. + pub fn session_create( + &self, + request: SessionCreateRequest, + ) -> Result { + let inner = &self.inner; + let directory = { + let store = inner + .open_control()? + .ok_or_else(DesktopError::unknown_workspace)?; + let found = store + .workspaces() + .find(|workspace| *workspace.id().as_uuid() == request.workspace_id) + .map(|workspace| workspace.directory_path()); + drop(store); + found + }; + let path = match directory { + None => return Err(DesktopError::unknown_workspace()), + Some(None) => { + return Err(DesktopError::invalid_request( + "The workspace path is not usable on this system.", + )); + } + Some(Some(path)) => path, + }; + let journal = create_session(&inner.data_root, &path, &request.title) + .map_err(|error| DesktopError::from_create(&error))?; + let session_id = journal.snapshot().session_id; + drop(journal); + refreshed_summary(inner, session_id) + } +} diff --git a/crates/omgcode-app/src/error.rs b/crates/omgcode-app/src/error.rs new file mode 100644 index 0000000..b78d248 --- /dev/null +++ b/crates/omgcode-app/src/error.rs @@ -0,0 +1,148 @@ +//! The typed failure shared by every application service. + +use std::fmt; + +use omgcode_core::provider::ProviderError; +use omgcode_core::session::SessionError; + +/// The stable failure category behind an [`AppError`] code. +/// +/// Policy and front ends may branch on the kind. The code strings are part of +/// the trusted CLI's JSON error contract and must not change. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ErrorKind { + /// Invalid operator input or an unusable local configuration. + Configuration, + /// A session journal could not be read, written, or used in its state. + Session, + /// The local model provider failed or returned an unusable reply. + Provider, + /// The workspace settings (control store) failed. + Control, + /// Context accounting or compaction refused or failed. + Context, + /// Current workspace preferences denied a requested action. + Permission, + /// Prompt assembly rejected the bounded request. + Prompt, + /// A terminal journal event could not be made durable. + Persistence, + /// The model returned an invalid tool call. + ToolCall, + /// A bounded turn limit stopped the request. + ToolLimit, + /// Any other controlled turn failure, such as cancellation or timeout. + Turn, +} + +impl ErrorKind { + /// The stable machine-readable code for this category. + pub const fn code(self) -> &'static str { + match self { + Self::Configuration => "configuration", + Self::Session => "session", + Self::Provider => "provider", + Self::Control => "control", + Self::Context => "context", + Self::Permission => "permission", + Self::Prompt => "prompt", + Self::Persistence => "persistence", + Self::ToolCall => "tool_call", + Self::ToolLimit => "tool_limit", + Self::Turn => "turn", + } + } +} + +/// A controlled application failure: a stable category and a safe message. +/// +/// Messages come from fixed text or from core error `Display` output. They +/// never include the configured server token, model output, or tool text. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct AppError { + kind: ErrorKind, + message: String, +} + +impl AppError { + /// Build an error. `message` must not contain secrets or untrusted text. + pub fn new(kind: ErrorKind, message: impl Into) -> Self { + Self { + kind, + message: message.into(), + } + } + + /// Map a session journal failure to the `session` category. + pub fn session(error: SessionError) -> Self { + Self::new(ErrorKind::Session, error.to_string()) + } + + /// Map a provider failure to the `provider` category. + pub fn provider(error: ProviderError) -> Self { + Self::new(ErrorKind::Provider, error.to_string()) + } + + /// The failure category. + pub const fn kind(&self) -> ErrorKind { + self.kind + } + + /// The stable machine-readable code for the category. + pub const fn code(&self) -> &'static str { + self.kind.code() + } + + /// The human-readable message. + pub fn message(&self) -> &str { + &self.message + } + + /// Consume the error and return its message. + pub fn into_message(self) -> String { + self.message + } +} + +impl fmt::Display for AppError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "{}: {}", self.code(), self.message) + } +} + +impl std::error::Error for AppError {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_kind_keeps_its_published_code() { + let codes = [ + (ErrorKind::Configuration, "configuration"), + (ErrorKind::Session, "session"), + (ErrorKind::Provider, "provider"), + (ErrorKind::Control, "control"), + (ErrorKind::Context, "context"), + (ErrorKind::Permission, "permission"), + (ErrorKind::Prompt, "prompt"), + (ErrorKind::Persistence, "persistence"), + (ErrorKind::ToolCall, "tool_call"), + (ErrorKind::ToolLimit, "tool_limit"), + (ErrorKind::Turn, "turn"), + ]; + for (kind, code) in codes { + assert_eq!(AppError::new(kind, "m").code(), code); + } + } + + #[test] + fn provider_and_session_mappers_use_the_core_display_text() { + let provider = AppError::provider(ProviderError::Transport); + assert_eq!(provider.code(), "provider"); + assert_eq!(provider.message(), "local model transport failed"); + let session = AppError::session(SessionError::LimitReached); + assert_eq!(session.code(), "session"); + assert_eq!(session.message(), SessionError::LimitReached.to_string()); + } +} diff --git a/crates/omgcode-app/src/lib.rs b/crates/omgcode-app/src/lib.rs new file mode 100644 index 0000000..9b77142 --- /dev/null +++ b/crates/omgcode-app/src/lib.rs @@ -0,0 +1,35 @@ +//! Front-end-neutral application services for OMGCode. +//! +//! The trusted CLI and the desktop shell both call this crate so that they run +//! exactly the same chat turn, session creation, and compaction. The crate +//! grants no authority of its own: every authorization decision (workspace +//! preferences, tool approvals, checkpointed edits, confinement) stays in +//! `omgcode-core`. It does no argument parsing, printing, or process exit, and +//! it reads the process environment only in [`read_lm_token`], which the caller +//! invokes. +//! +//! The optional local server token is a credential. It is borrowed per call, +//! used to build a request header and to remove the same text from everything +//! recorded or sent, and never appears in an [`AppError`], a `Debug` string, or +//! serialized output. +#![forbid(unsafe_code)] + +mod chat; +mod context; +pub mod desktop; +mod error; +mod paths; +mod secrets; +mod sessions; +mod tool_mode; + +pub use chat::{ + ChatClients, ChatHooks, ChatSettings, ChatTurnInput, ChatTurnOutput, run_chat_turn, + run_chat_turn_with_clients, +}; +pub use context::{CompactionMeter, ContextMeter, compact_journal, summary_output_tokens}; +pub use error::{AppError, ErrorKind}; +pub use paths::data_root; +pub use secrets::{read_lm_token, redact_known_secret}; +pub use sessions::create_session; +pub use tool_mode::{MODEL_TOOLS_SUPPORTED, ToolMode, select, tool_replay_allowed}; diff --git a/crates/omgcode-app/src/paths.rs b/crates/omgcode-app/src/paths.rs new file mode 100644 index 0000000..f37c2e6 --- /dev/null +++ b/crates/omgcode-app/src/paths.rs @@ -0,0 +1,55 @@ +//! Trusted application storage location. + +use std::path::PathBuf; + +use directories::ProjectDirs; + +use crate::error::{AppError, ErrorKind}; + +/// Choose trusted application storage. +/// +/// A supplied override is returned as given; it must come from the trusted +/// operator, never from repository content. Without one, the per-user local +/// data directory for OMGCode is used. No directory is created or checked here. +/// Fails with `configuration` when the platform has no per-user data directory. +pub fn data_root(override_path: Option) -> Result { + if let Some(path) = override_path { + return Ok(path); + } + ProjectDirs::from("org", "OMG-Software", "OMGCode") + .map(|directories| directories.data_local_dir().to_owned()) + .ok_or_else(|| { + AppError::new( + ErrorKind::Configuration, + "No per-user application data directory", + ) + }) +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use super::*; + + #[test] + fn an_override_is_returned_unchanged() { + let path = PathBuf::from("trusted-override"); + assert_eq!(data_root(Some(path.clone())).expect("override"), path); + } + + #[test] + fn the_default_is_the_per_user_omgcode_directory() { + // Hosts without a home directory legitimately fail closed. + if let Ok(path) = data_root(None) { + assert!(path.is_absolute()); + // The platform convention decides the spelling: Windows keeps + // `OMG-Software\OMGCode`, while Linux XDG paths use `omgcode`. + assert!( + path.to_string_lossy() + .to_ascii_lowercase() + .contains("omgcode") + ); + } + } +} diff --git a/crates/omgcode-app/src/secrets.rs b/crates/omgcode-app/src/secrets.rs new file mode 100644 index 0000000..fded0bd --- /dev/null +++ b/crates/omgcode-app/src/secrets.rs @@ -0,0 +1,69 @@ +//! Handling of the optional local server token. +//! +//! The token is a credential. It is never logged, serialized, or placed in an +//! error message; the only treatment here is removing it from untrusted text. + +use std::env; + +use crate::error::{AppError, ErrorKind}; + +/// The environment variable that carries the optional local server token. +const TOKEN_VARIABLE: &str = "OMGCODE_LM_TOKEN"; + +/// Read the trusted operator's credential input from the environment. +/// +/// This performs the process-environment read; the caller decides when. An +/// unset or empty variable gives `None`. A non-Unicode value is a +/// `configuration` error that does not include the value. +pub fn read_lm_token() -> Result, AppError> { + match env::var(TOKEN_VARIABLE) { + Ok(value) if !value.is_empty() => Ok(Some(value)), + Ok(_) | Err(env::VarError::NotPresent) => Ok(None), + Err(env::VarError::NotUnicode(_)) => Err(AppError::new( + ErrorKind::Configuration, + "Server token must be Unicode", + )), + } +} + +/// Remove the configured credential from untrusted text before retention or egress. +/// +/// If replacement would itself contain the credential, the text is discarded +/// and an empty string is returned. +pub fn redact_known_secret(text: &str, token: Option<&str>) -> String { + match token.filter(|token| !token.is_empty()) { + Some(token) => { + let result = text.replace(token, "[REDACTED]"); + if result.contains(token) { + String::new() + } else { + result + } + } + None => text.to_owned(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_known_token_is_replaced_everywhere() { + assert_eq!( + redact_known_secret("a secret-1 b secret-1", Some("secret-1")), + "a [REDACTED] b [REDACTED]" + ); + } + + #[test] + fn text_is_unchanged_without_a_token() { + assert_eq!(redact_known_secret("plain", None), "plain"); + assert_eq!(redact_known_secret("plain", Some("")), "plain"); + } + + #[test] + fn text_is_discarded_when_replacement_recreates_the_token() { + assert_eq!(redact_known_secret("xx[REDACTED]", Some("x[RED")), ""); + } +} diff --git a/crates/omgcode-app/src/sessions.rs b/crates/omgcode-app/src/sessions.rs new file mode 100644 index 0000000..6929cbb --- /dev/null +++ b/crates/omgcode-app/src/sessions.rs @@ -0,0 +1,45 @@ +//! Session creation with current workspace registry metadata. + +use std::path::Path; + +use omgcode_core::control::ControlStore; +use omgcode_core::session::SessionJournal; + +use crate::error::{AppError, ErrorKind}; + +/// Create a session with current registry metadata when a trusted root is configured. +/// +/// An absent or valid unconfigured store preserves legacy session creation. Corrupt +/// control state or an invalid workspace under a configured root fails closed with +/// `control`; journal failures are `session`. The control store is opened and +/// closed inside this call and is never held while the journal is created. +pub fn create_session( + data_root: &Path, + workspace: &Path, + title: &str, +) -> Result { + let control_error = |error: omgcode_core::control::ControlError| { + AppError::new(ErrorKind::Control, error.to_string()) + }; + let registration_id = match ControlStore::open_existing(data_root).map_err(control_error)? { + Some(mut store) if store.has_development_root() => { + let registration = store + .register_workspace(workspace, store.revision()) + .map_err(control_error)?; + let id = registration.id(); + drop(store); + Some(id) + } + Some(store) => { + drop(store); + None + } + None => None, + }; + + match registration_id { + Some(id) => SessionJournal::create_with_workspace_id(data_root, workspace, title, id), + None => SessionJournal::create(data_root, workspace, title), + } + .map_err(AppError::session) +} diff --git a/crates/omgcode-app/src/tool_mode.rs b/crates/omgcode-app/src/tool_mode.rs new file mode 100644 index 0000000..90a5d77 --- /dev/null +++ b/crates/omgcode-app/src/tool_mode.rs @@ -0,0 +1,142 @@ +//! Whether a chat turn offers the model the workspace tools. +//! +//! The session journal only selects which registered workspace to consult. +//! Authority comes from the live settings preference, rechecked by the core +//! runtime before every tool call. Nothing here grants authority. + +use std::path::Path; + +use omgcode_core::control::ControlStore; +use omgcode_core::policy::WorkspaceId; +use omgcode_core::session::SessionJournal; +use uuid::Uuid; + +use crate::error::{AppError, ErrorKind}; + +/// Whether this build can serve the model read/list tools. +/// +/// The capability report and tool selection share this value, so chat never +/// offers tools the platform cannot run. +pub const MODEL_TOOLS_SUPPORTED: bool = cfg!(any(target_os = "linux", target_os = "windows")); + +/// Conservative byte allowance for the advertised tool definitions. +/// +/// The largest set (read, list, edit, and command) serializes to 2,763 bytes +/// in the adapter's wire shape; a unit test keeps this allowance above it. +pub(crate) const TOOL_SCHEMA_ESTIMATE_BYTES: usize = 4 * 1024; + +/// Whether this chat turn offers the model the workspace tools. +#[derive(Debug)] +pub enum ToolMode { + /// The selected workspace's live preference enables model tools. + Enabled { + /// The registered workspace taken from current settings. + workspace_id: WorkspaceId, + }, + /// Text-only chat, with the reason tools were not offered. + Disabled { + /// A stable reason code, such as `preference_disabled`. + reason: &'static str, + }, +} + +/// Decide the tool mode from current settings without holding the settings lock. +/// +/// An unsupported platform, an absent store, an unregistered workspace, or a +/// disabled preference gives text-only chat. Invalid settings fail closed with +/// a `control` error. A version 1 journal cannot record tool events, so it +/// stays text-only. The settings lock is released before this returns. +pub fn select(data_root: &Path, journal: &SessionJournal) -> Result { + if !MODEL_TOOLS_SUPPORTED { + return Ok(ToolMode::Disabled { + reason: "platform_unsupported", + }); + } + let Some(control) = ControlStore::open_existing(data_root) + .map_err(|error| AppError::new(ErrorKind::Control, error.to_string()))? + else { + return Ok(ToolMode::Disabled { + reason: "settings_absent", + }); + }; + // The journal's UUID only selects a registration; the ID used afterwards + // and its preference come from current settings. + let (workspace_id, enabled) = + match control.registered_workspace(journal.snapshot().workspace_id) { + None => { + return Ok(ToolMode::Disabled { + reason: "workspace_unregistered", + }); + } + Some(workspace) => (workspace.id(), workspace.permissions().model_tools), + }; + // Release the settings lock before any model request. + drop(control); + if !enabled { + return Ok(ToolMode::Disabled { + reason: "preference_disabled", + }); + } + if journal.schema_version() < 2 { + return Ok(ToolMode::Disabled { + reason: "session_schema_v1", + }); + } + Ok(ToolMode::Enabled { workspace_id }) +} + +/// Whether live settings authorize replaying saved tool results for a session: +/// the same `model_tools` and `read` rule the turn runtime applies. +/// +/// The session is named by its recorded workspace UUID and schema version, so +/// compaction can recheck while it holds the journal. Each call reads current +/// settings. Every condition that gives text-only chat gives `false`; invalid +/// settings return a `control` error. +pub fn tool_replay_allowed( + data_root: &Path, + workspace: Uuid, + schema_version: u32, +) -> Result { + if !MODEL_TOOLS_SUPPORTED || schema_version < 2 { + return Ok(false); + } + let Some(control) = ControlStore::open_existing(data_root) + .map_err(|error| AppError::new(ErrorKind::Control, error.to_string()))? + else { + return Ok(false); + }; + Ok(control + .registered_workspace(workspace) + .is_some_and(|workspace| { + let permissions = workspace.permissions(); + permissions.model_tools && permissions.read + })) +} + +#[cfg(test)] +mod tests { + use omgcode_core::turn::{command_tool_definition, edit_tool_definition, tool_definitions}; + use serde_json::{Value, json}; + + use super::TOOL_SCHEMA_ESTIMATE_BYTES; + + /// The estimate must cover the largest advertised tool set in the exact + /// OpenAI-compatible wire shape the adapter sends. + #[test] + fn the_schema_estimate_covers_every_advertised_tool_definition() { + let mut definitions = tool_definitions(); + definitions.push(edit_tool_definition()); + definitions.push(command_tool_definition()); + let wire: Vec = definitions + .iter() + .map(|definition| json!({"type": "function", "function": definition})) + .collect(); + let bytes = serde_json::to_vec(&wire).expect("serialize tool definitions"); + println!("advertised tool definitions: {} bytes", bytes.len()); + assert!( + bytes.len() <= TOOL_SCHEMA_ESTIMATE_BYTES, + "{} bytes exceed the {TOOL_SCHEMA_ESTIMATE_BYTES}-byte estimate", + bytes.len() + ); + } +} diff --git a/crates/omgcode-app/tests/chat_turn.rs b/crates/omgcode-app/tests/chat_turn.rs new file mode 100644 index 0000000..a22f4ac --- /dev/null +++ b/crates/omgcode-app/tests/chat_turn.rs @@ -0,0 +1,579 @@ +//! Behaviour of the front-end-neutral chat turn against a local mock provider. +//! +//! Every test uses a private temporary data root and a loopback server bound to +//! an ephemeral port. No process is spawned on Unix; on Windows the private +//! data root is prepared with `icacls`, which holds no store handle. + +use std::fs; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::{Path, PathBuf}; +use std::sync::mpsc::{self, Receiver}; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; + +use omgcode_app::{ + ChatHooks, ChatSettings, ChatTurnInput, ChatTurnOutput, create_session, run_chat_turn, +}; +use omgcode_core::control::ControlStore; +use omgcode_core::policy::PermissionSet; +use omgcode_core::session::SessionJournal; +use omgcode_core::turn::CancelToken; +use serde_json::{Value, json}; +use tempfile::TempDir; + +const MOCK_TIMEOUT: Duration = Duration::from_secs(8); +const MAX_HTTP_BYTES: usize = 1024 * 1024; +const SECRET: &str = "fixture-token-7f3a91"; + +/// Serve one scripted response per connection and optionally cancel a turn first. +struct SequenceServer { + endpoint: String, + worker: JoinHandle>, +} + +impl SequenceServer { + /// `cancel_source` delivers the token the hook captured; the server cancels + /// it after the first request arrives and before it replies. + fn start(responses: Vec, cancel_source: Option>) -> Self { + let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bind mock server"); + listener.set_nonblocking(true).expect("bounded accept"); + let address = listener.local_addr().expect("mock address"); + let worker = thread::spawn(move || { + let mut served = 0; + for response in responses { + let Ok(mut stream) = accept(&listener) else { + break; + }; + read_body(&mut stream)?; + if served == 0 + && let Some(source) = &cancel_source + { + let token = source + .recv_timeout(MOCK_TIMEOUT) + .map_err(|error| error.to_string())?; + token.cancel(); + } + let bytes = serde_json::to_vec(&response).map_err(|error| error.to_string())?; + let head = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + bytes.len() + ); + stream + .write_all(head.as_bytes()) + .and_then(|()| stream.write_all(&bytes)) + .map_err(|error| error.to_string())?; + served += 1; + } + Ok(served) + }); + Self { + endpoint: format!("http://{address}/v1"), + worker, + } + } + + /// Wait for the server thread and return how many requests it answered. + fn finish(self) -> usize { + self.worker + .join() + .expect("mock server thread") + .expect("mock server exchange") + } +} + +fn accept(listener: &TcpListener) -> Result { + let deadline = Instant::now() + MOCK_TIMEOUT; + loop { + match listener.accept() { + Ok((stream, _)) => { + stream + .set_nonblocking(false) + .map_err(|error| error.to_string())?; + stream + .set_read_timeout(Some(MOCK_TIMEOUT)) + .map_err(|error| error.to_string())?; + return Ok(stream); + } + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + if Instant::now() >= deadline { + return Err("no further request".to_owned()); + } + thread::sleep(Duration::from_millis(5)); + } + Err(error) => return Err(error.to_string()), + } + } +} + +fn read_body(stream: &mut TcpStream) -> Result, String> { + let mut bytes = Vec::new(); + let mut buffer = [0_u8; 4096]; + loop { + if let Some(end) = bytes.windows(4).position(|window| window == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&bytes[..end]).to_ascii_lowercase(); + let length: usize = head + .lines() + .find_map(|line| line.strip_prefix("content-length:")) + .ok_or("missing content length")? + .trim() + .parse() + .map_err(|_| "invalid content length")?; + if length > MAX_HTTP_BYTES { + return Err("request too large".to_owned()); + } + while bytes.len() < end + 4 + length { + let read = stream + .read(&mut buffer) + .map_err(|error| error.to_string())?; + if read == 0 { + return Err("truncated body".to_owned()); + } + bytes.extend_from_slice(&buffer[..read]); + } + return Ok(bytes[end + 4..end + 4 + length].to_vec()); + } + if bytes.len() > MAX_HTTP_BYTES { + return Err("headers too large".to_owned()); + } + let read = stream + .read(&mut buffer) + .map_err(|error| error.to_string())?; + if read == 0 { + return Err("connection closed before headers".to_owned()); + } + bytes.extend_from_slice(&buffer[..read]); + } +} + +fn text(content: &str) -> Value { + json!({ + "choices": [{ + "index": 0, + "message": {"role": "assistant", "content": content}, + "finish_reason": "stop" + }] + }) +} + +fn tool_call(id: &str, name: &str, arguments: &Value) -> Value { + json!({ + "choices": [{ + "index": 0, + "message": { + "role": "assistant", + "content": null, + "tool_calls": [{ + "id": id, + "type": "function", + "function": {"name": name, "arguments": arguments.to_string()} + }] + }, + "finish_reason": "tool_calls" + }] + }) +} + +/// Private application data and one workspace; optionally a registered +/// workspace whose `model_tools` and `read` preferences are enabled. +struct Fixture { + _temporary: TempDir, + data: PathBuf, + workspace: PathBuf, +} + +impl Fixture { + fn new(tools_enabled: bool) -> Self { + let temporary = tempfile::tempdir().expect("private fixture root"); + let data = temporary.path().join("application-data"); + let development = temporary.path().join("development"); + let workspace = development.join("project"); + fs::create_dir_all(&workspace).expect("workspace directories"); + fs::create_dir_all(&data).expect("application data"); + if tools_enabled { + #[cfg(windows)] + restrict_to_current_user(&data); + let mut control = ControlStore::open(&data).expect("private control store"); + control + .set_development_root(&development, control.revision()) + .expect("development root"); + let id = control + .register_workspace(&workspace, control.revision()) + .expect("registered workspace") + .id(); + control + .set_permissions( + id, + PermissionSet { + read: true, + write: false, + execute: false, + task_network: false, + model_tools: true, + host_services: false, + }, + control.revision(), + ) + .expect("model tool preferences"); + } + Self { + _temporary: temporary, + data, + workspace, + } + } + + fn journal(&self) -> SessionJournal { + create_session(&self.data, &self.workspace, "Fixture session").expect("session") + } +} + +/// Give `data` the private ACL the Windows control store requires of its root. +#[cfg(windows)] +fn restrict_to_current_user(data: &Path) { + let whoami = std::process::Command::new("whoami") + .args(["/user", "/fo", "csv", "/nh"]) + .output() + .expect("whoami"); + assert!(whoami.status.success(), "whoami fixture failed"); + let identity = String::from_utf8_lossy(&whoami.stdout).into_owned(); + let sid = identity + .trim() + .rsplit(',') + .next() + .expect("SID column") + .trim_matches('"') + .to_owned(); + let granted = std::process::Command::new("icacls") + .arg(data) + .args(["/inheritance:r", "/grant:r", &format!("*{sid}:(OI)(CI)F")]) + .output() + .expect("icacls"); + assert!(granted.status.success(), "icacls fixture failed"); +} + +fn settings(endpoint: &str) -> ChatSettings { + let mut settings = ChatSettings::new(endpoint, "fixture", 131_072); + settings.max_output_tokens = 64; + settings +} + +fn turn( + journal: &mut SessionJournal, + data: &Path, + settings: &ChatSettings, + token: Option<&str>, + message: &str, + hooks: &mut ChatHooks<'_>, +) -> Result { + run_chat_turn( + journal, + data, + &ChatTurnInput { + message, + settings, + token, + }, + hooks, + ) +} + +/// Close the journal, which holds an exclusive lock, and read its events. +fn close_and_read(journal: SessionJournal) -> Vec { + let path = journal.path().to_owned(); + drop(journal); + fs::read_to_string(path) + .expect("journal file") + .lines() + .map(|line| serde_json::from_str(line).expect("journal event")) + .collect() +} + +fn last_failure_code(events: &[Value]) -> Option { + events + .iter() + .rev() + .find(|event| event["type"] == "turn.failed") + .and_then(|event| event["payload"]["code"].as_str().map(str::to_owned)) +} + +fn unused_endpoint() -> String { + let listener = TcpListener::bind(("127.0.0.1", 0)).expect("reserve port"); + let port = listener.local_addr().expect("address").port(); + drop(listener); + format!("http://127.0.0.1:{port}/v1") +} + +#[test] +fn an_archived_session_is_refused_with_the_published_message() { + let fixture = Fixture::new(false); + let mut journal = fixture.journal(); + journal.archive().expect("archive"); + let error = turn( + &mut journal, + &fixture.data, + &settings(&unused_endpoint()), + None, + "hello", + &mut ChatHooks::default(), + ) + .expect_err("archived sessions cannot chat"); + assert_eq!(error.code(), "session"); + assert_eq!( + error.message(), + "Restore the archived session before chatting" + ); +} + +#[test] +fn an_incomplete_previous_turn_is_refused_with_the_published_message() { + let fixture = Fixture::new(false); + let mut journal = fixture.journal(); + journal.start_turn().expect("start turn"); + let error = turn( + &mut journal, + &fixture.data, + &settings(&unused_endpoint()), + None, + "hello", + &mut ChatHooks::default(), + ) + .expect_err("an active turn blocks chat"); + assert_eq!(error.code(), "session"); + assert_eq!( + error.message(), + "The previous turn is incomplete; inspect it, then use session interrupt to mark it failed without retrying" + ); +} + +#[test] +fn reaching_the_trigger_without_auto_compact_is_a_context_error() { + let fixture = Fixture::new(false); + let mut journal = fixture.journal(); + let mut chat = settings(&unused_endpoint()); + chat.compact_threshold = 1; + let error = turn( + &mut journal, + &fixture.data, + &chat, + None, + "hello", + &mut ChatHooks::default(), + ) + .expect_err("the trigger is reached"); + assert_eq!(error.code(), "context"); + let message = error.message(); + assert!( + message.starts_with("The conservative input estimate ("), + "{message}" + ); + assert!( + message.ends_with(". Use session compact or rerun chat with --auto-compact."), + "{message}" + ); + assert!( + close_and_read(journal) + .iter() + .all(|event| event["type"] != "turn.started"), + "a refused preflight must not start a turn" + ); +} + +#[test] +fn a_zero_threshold_is_a_configuration_error() { + let fixture = Fixture::new(false); + let mut journal = fixture.journal(); + let mut chat = settings(&unused_endpoint()); + chat.compact_threshold = 0; + let error = turn( + &mut journal, + &fixture.data, + &chat, + None, + "hello", + &mut ChatHooks::default(), + ) + .expect_err("a zero threshold is invalid"); + assert_eq!(error.code(), "configuration"); + assert_eq!( + error.message(), + "The compaction threshold must be a positive token count" + ); +} + +#[test] +fn an_invalid_endpoint_is_a_provider_error_before_any_storage_use() { + let fixture = Fixture::new(false); + let mut journal = fixture.journal(); + let error = turn( + &mut journal, + &fixture.data, + &settings("http://example.com/v1"), + None, + "hello", + &mut ChatHooks::default(), + ) + .expect_err("only loopback endpoints are accepted"); + assert_eq!(error.code(), "provider"); + assert_eq!(error.message(), "invalid local model configuration"); +} + +#[test] +fn a_transport_failure_is_recorded_and_never_mentions_the_token() { + let fixture = Fixture::new(false); + let mut journal = fixture.journal(); + let error = turn( + &mut journal, + &fixture.data, + &settings(&unused_endpoint()), + Some(SECRET), + "hello", + &mut ChatHooks::default(), + ) + .expect_err("nothing is listening"); + assert_eq!(error.code(), "provider"); + assert_eq!(error.message(), "local model transport failed"); + assert!(!format!("{error:?}{error}").contains(SECRET)); + assert_eq!(journal.snapshot().active_turn, None); + let events = close_and_read(journal); + assert_eq!( + last_failure_code(&events).as_deref(), + Some("provider_error") + ); +} + +#[test] +fn a_text_only_turn_serializes_the_published_object_and_skips_the_cancel_hook() { + let fixture = Fixture::new(false); + let mut journal = fixture.journal(); + let server = SequenceServer::start(vec![text(&format!("pong {SECRET}"))], None); + let mut calls = 0_usize; + let mut on_cancel_token = |_token: CancelToken| calls += 1; + let output = turn( + &mut journal, + &fixture.data, + &settings(&server.endpoint), + Some(SECRET), + &format!("ping {SECRET}"), + &mut ChatHooks { + on_cancel_token: Some(&mut on_cancel_token), + }, + ) + .expect("text-only turn"); + assert_eq!(server.finish(), 1); + assert_eq!(calls, 0, "the text-only path has no cancellation point"); + + assert!(!output.tools_enabled()); + assert_eq!(output.disabled_reason(), Some("settings_absent")); + assert_eq!(output.reply(), "pong [REDACTED]"); + assert_eq!(output.finish_reason(), "stop"); + assert_eq!(output.rounds(), None); + assert_eq!(output.withheld_tool_results(), 0); + assert_eq!(output.context().estimate_scope(), "pre_turn_conservative"); + + let serialized = serde_json::to_string(&output).expect("serialize"); + assert!(!serialized.contains(SECRET)); + let value: Value = serde_json::from_str(&serialized).expect("JSON"); + assert_eq!(value["reply"]["content"], "pong [REDACTED]"); + assert_eq!(value["reply"]["finish_reason"], "stop"); + assert_eq!( + value["model_tools"], + json!({"mode": "disabled", "reason": "settings_absent", "withheld_tool_results": 0}) + ); + let mut keys: Vec<&str> = value + .as_object() + .expect("object") + .keys() + .map(String::as_str) + .collect(); + keys.sort_unstable(); + assert_eq!(keys, ["context", "model_tools", "reply"]); + // The recorded user message is the redacted one. + let events = close_and_read(journal); + assert!(!format!("{events:?}").contains(SECRET)); +} + +#[test] +fn a_tool_turn_calls_the_cancel_hook_once_and_serializes_the_published_object() { + let fixture = Fixture::new(true); + let mut journal = fixture.journal(); + let server = SequenceServer::start(vec![text("done")], None); + let mut calls = 0_usize; + let mut on_cancel_token = |token: CancelToken| { + assert!(!token.is_cancelled()); + calls += 1; + }; + let output = turn( + &mut journal, + &fixture.data, + &settings(&server.endpoint), + None, + "hello", + &mut ChatHooks { + on_cancel_token: Some(&mut on_cancel_token), + }, + ) + .expect("tool turn"); + assert_eq!(server.finish(), 1); + assert_eq!(calls, 1); + + assert!(output.tools_enabled()); + assert_eq!(output.disabled_reason(), None); + assert_eq!(output.reply(), "done"); + assert_eq!(output.rounds(), Some(1)); + assert_eq!(output.tool_calls(), Some(0)); + assert_eq!(output.tool_bytes(), Some(0)); + assert_eq!(output.withheld_tool_results(), 0); + assert!(output.workspace_id().is_some()); + + let serialized = serde_json::to_string(&output).expect("serialize"); + let reply_at = serialized.find("\"reply\"").expect("reply key"); + let tools_at = serialized.find("\"model_tools\"").expect("tools key"); + let context_at = serialized.find("\"context\"").expect("context key"); + assert!(reply_at < tools_at && tools_at < context_at, "{serialized}"); + let value: Value = serde_json::from_str(&serialized).expect("JSON"); + assert_eq!(value["model_tools"]["mode"], "enabled"); + assert_eq!(value["model_tools"]["rounds"], 1); + assert_eq!(value["model_tools"]["tool_calls"], 0); + assert_eq!(value["model_tools"]["tool_bytes"], 0); + assert_eq!(value["model_tools"]["withheld_tool_results"], 0); + assert_eq!(value["reply"]["content"], "done"); +} + +#[test] +fn a_cancelled_token_ends_the_tool_turn_with_the_core_cancelled_failure() { + let fixture = Fixture::new(true); + let mut journal = fixture.journal(); + let (sender, receiver) = mpsc::channel::(); + let server = SequenceServer::start( + vec![tool_call( + "call-1", + "workspace_list_directory", + &json!({"path": "."}), + )], + Some(receiver), + ); + let mut calls = 0_usize; + let mut on_cancel_token = |token: CancelToken| { + calls += 1; + sender.send(token).expect("hand the token to the server"); + }; + let error = turn( + &mut journal, + &fixture.data, + &settings(&server.endpoint), + None, + "list the files", + &mut ChatHooks { + on_cancel_token: Some(&mut on_cancel_token), + }, + ) + .expect_err("cancellation stops the turn"); + assert_eq!(server.finish(), 1); + assert_eq!(calls, 1); + assert_eq!(error.code(), "turn"); + assert_eq!(error.message(), "turn was cancelled"); + assert_eq!(journal.snapshot().active_turn, None); + let events = close_and_read(journal); + assert_eq!(last_failure_code(&events).as_deref(), Some("cancelled")); +} diff --git a/crates/omgcode-app/tests/common/mod.rs b/crates/omgcode-app/tests/common/mod.rs new file mode 100644 index 0000000..ef63adf --- /dev/null +++ b/crates/omgcode-app/tests/common/mod.rs @@ -0,0 +1,491 @@ +//! Fixtures shared by the desktop service tests: a private data root, a +//! registered development root and workspaces, a scripted loopback model +//! server, and bounded polling helpers. +//! +//! Each test crate uses a subset of these helpers, so unused-item warnings are +//! allowed for this one shared module. +#![allow(dead_code)] + +use std::fs; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::PathBuf; +use std::sync::mpsc::{self, Receiver, Sender}; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; + +use omgcode_app::AppError; +use omgcode_app::desktop::{ChatState, ChatStatus, DesktopConfig, DesktopService, SessionRequest}; +use omgcode_core::control::{ControlStore, ProfileDeclaration}; +use omgcode_core::policy::PermissionSet; +use serde::Serialize; +use serde::de::DeserializeOwned; +use serde_json::{Value, json}; +use tempfile::TempDir; +use uuid::Uuid; + +/// A made-up token, used only to prove it never leaks. +pub const SECRET: &str = "fixture-token-7f3a91"; +/// How long the scripted server waits for a request or a release. +const SERVER_TIMEOUT: Duration = Duration::from_secs(30); +const MAX_HTTP_BYTES: usize = 1024 * 1024; +/// How long a test polls for a state before it fails. +pub const POLL_DEADLINE: Duration = Duration::from_secs(30); + +/// No token. +pub fn no_token() -> Result, AppError> { + Ok(None) +} + +/// The fixture token. +pub fn fixed_token() -> Result, AppError> { + Ok(Some(SECRET.to_owned())) +} + +/// Build a request or any wire type from JSON, as the shell would. +pub fn wire(value: Value) -> T { + serde_json::from_value(value).expect("wire value deserializes") +} + +/// Serialize a response to text, as the shell would. +pub fn text_of(value: &T) -> String { + serde_json::to_string(value).expect("response serializes") +} + +/// Serialize a response to a JSON value. +pub fn json_of(value: &T) -> Value { + serde_json::to_value(value).expect("response serializes") +} + +/// The request object that names only a session. +pub fn session_request(id: Uuid) -> Value { + json!({"session_id": id}) +} + +/// One scripted reply of the loopback model server. +pub struct Step { + reply: Value, + gate: Option>, + arrived: Option>, +} + +impl Step { + /// Reply as soon as the request has been read. + pub fn reply(reply: Value) -> Self { + Self { + reply, + gate: None, + arrived: None, + } + } + + /// Wait for the gate to be released (or its sender dropped) before replying. + pub fn gated(reply: Value, gate: Receiver<()>) -> Self { + Self { + reply, + gate: Some(gate), + arrived: None, + } + } + + /// Announce on `arrived` once the request has been read. + pub fn announcing(mut self, arrived: Sender<()>) -> Self { + self.arrived = Some(arrived); + self + } +} + +/// A loopback model server that answers one scripted reply per connection. +pub struct MockServer { + pub endpoint: String, + worker: JoinHandle>, +} + +impl MockServer { + pub fn start(steps: Vec) -> Self { + let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bind mock server"); + listener.set_nonblocking(true).expect("bounded accept"); + let address = listener.local_addr().expect("mock address"); + let worker = thread::spawn(move || { + let mut served = 0; + for step in steps { + let Ok(mut stream) = accept(&listener) else { + break; + }; + read_body(&mut stream)?; + if let Some(arrived) = &step.arrived { + // The test may have stopped listening; that is not an error. + arrived.send(()).ok(); + } + if let Some(gate) = &step.gate { + // A release and a dropped sender both let the reply go. + gate.recv_timeout(SERVER_TIMEOUT).ok(); + } + let bytes = serde_json::to_vec(&step.reply).map_err(|error| error.to_string())?; + let head = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + bytes.len() + ); + // The client may have given up (a cancelled turn); that is not an error. + stream + .write_all(head.as_bytes()) + .and_then(|()| stream.write_all(&bytes)) + .ok(); + served += 1; + } + Ok(served) + }); + Self { + endpoint: format!("http://{address}/v1"), + worker, + } + } + + /// Wait for the server thread and return how many requests it answered. + pub fn finish(self) -> usize { + self.worker + .join() + .expect("mock server thread") + .expect("mock server exchange") + } +} + +fn accept(listener: &TcpListener) -> Result { + let deadline = Instant::now() + SERVER_TIMEOUT; + loop { + match listener.accept() { + Ok((stream, _)) => { + stream + .set_nonblocking(false) + .map_err(|error| error.to_string())?; + stream + .set_read_timeout(Some(SERVER_TIMEOUT)) + .map_err(|error| error.to_string())?; + return Ok(stream); + } + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + if Instant::now() >= deadline { + return Err("no further request".to_owned()); + } + thread::sleep(Duration::from_millis(5)); + } + Err(error) => return Err(error.to_string()), + } + } +} + +fn read_body(stream: &mut TcpStream) -> Result, String> { + let mut bytes = Vec::new(); + let mut buffer = [0_u8; 4096]; + loop { + if let Some(end) = bytes.windows(4).position(|window| window == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&bytes[..end]).to_ascii_lowercase(); + let length: usize = head + .lines() + .find_map(|line| line.strip_prefix("content-length:")) + .ok_or("missing content length")? + .trim() + .parse() + .map_err(|_| "invalid content length")?; + if length > MAX_HTTP_BYTES { + return Err("request too large".to_owned()); + } + while bytes.len() < end + 4 + length { + let read = stream + .read(&mut buffer) + .map_err(|error| error.to_string())?; + if read == 0 { + return Err("truncated body".to_owned()); + } + bytes.extend_from_slice(&buffer[..read]); + } + return Ok(bytes[end + 4..end + 4 + length].to_vec()); + } + if bytes.len() > MAX_HTTP_BYTES { + return Err("headers too large".to_owned()); + } + let read = stream + .read(&mut buffer) + .map_err(|error| error.to_string())?; + if read == 0 { + return Err("connection closed before headers".to_owned()); + } + bytes.extend_from_slice(&buffer[..read]); + } +} + +/// A plain assistant reply. +pub fn text(content: &str) -> Value { + json!({ + "choices": [{ + "index": 0, + "message": {"role": "assistant", "content": content}, + "finish_reason": "stop" + }] + }) +} + +/// An assistant reply that requests one tool call. +pub fn tool_call(id: &str, name: &str, arguments: &Value) -> Value { + json!({ + "choices": [{ + "index": 0, + "message": { + "role": "assistant", + "content": null, + "tool_calls": [{ + "id": id, + "type": "function", + "function": {"name": name, "arguments": arguments.to_string()} + }] + }, + "finish_reason": "tool_calls" + }] + }) +} + +/// An endpoint nothing listens on. +pub fn unused_endpoint() -> String { + let listener = TcpListener::bind(("127.0.0.1", 0)).expect("reserve port"); + let port = listener.local_addr().expect("address").port(); + drop(listener); + format!("http://127.0.0.1:{port}/v1") +} + +/// A registered workspace. +#[derive(Clone, Debug)] +pub struct Workspace { + pub id: Uuid, + pub path: PathBuf, +} + +/// Private application data, a development root, and registered workspaces. +pub struct Fixture { + _temporary: TempDir, + pub data: PathBuf, + pub development: PathBuf, +} + +impl Fixture { + /// Application data only; no settings store exists. + pub fn bare() -> Self { + let temporary = tempfile::tempdir().expect("private fixture root"); + let data = temporary.path().join("application-data"); + let development = temporary.path().join("development"); + // The checkpoint store refuses a data root that is not private. On + // Unix that means mode 0700, which the default create mode is not. + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + fs::DirBuilder::new() + .mode(0o700) + .create(&data) + .expect("application data"); + } + #[cfg(not(unix))] + fs::create_dir_all(&data).expect("application data"); + fs::create_dir_all(&development).expect("development root"); + #[cfg(windows)] + restrict_to_current_user(&data); + Self { + _temporary: temporary, + data, + development, + } + } + + /// Application data with a settings store that has a development root. + pub fn new() -> Self { + let fixture = Self::bare(); + let mut control = ControlStore::open(&fixture.data).expect("private control store"); + control + .set_development_root(&fixture.development, control.revision()) + .expect("development root"); + fixture + } + + /// Register `name` below the development root with `permissions`. + pub fn workspace(&self, name: &str, permissions: PermissionSet) -> Workspace { + let path = self.development.join(name); + fs::create_dir_all(&path).expect("workspace directory"); + let mut control = ControlStore::open(&self.data).expect("control store"); + let id = control + .register_workspace(&path, control.revision()) + .expect("registered workspace") + .id(); + control + .set_permissions(id, permissions, control.revision()) + .expect("workspace permissions"); + Workspace { + id: *id.as_uuid(), + path, + } + } + + /// Declare a toolchain profile so the command tool can be offered. + pub fn declare_profile(&self) { + let tools = self.data.parent().expect("temporary root").join("tools"); + fs::create_dir_all(&tools).expect("toolchain root"); + let mut control = ControlStore::open(&self.data).expect("control store"); + control + .add_profile( + &ProfileDeclaration { + name: "system".into(), + read_only_roots: vec![tools], + path_entries: Vec::new(), + environment: Vec::new(), + }, + control.revision(), + ) + .expect("toolchain profile"); + } + + pub fn service(&self, endpoint: &str) -> DesktopService { + self.service_with(endpoint, no_token) + } + + pub fn service_with( + &self, + endpoint: &str, + source: fn() -> Result, AppError>, + ) -> DesktopService { + DesktopService::open_with_token_source( + DesktopConfig { + data_root: self.data.clone(), + endpoint: endpoint.to_owned(), + }, + source, + ) + .expect("open desktop service") + } +} + +/// Permissions that offer the read and list tools. +pub fn read_tools() -> PermissionSet { + PermissionSet { + read: true, + write: false, + model_tools: true, + ..PermissionSet::default() + } +} + +/// Permissions that offer every model tool. +pub fn all_tools() -> PermissionSet { + PermissionSet { + read: true, + write: true, + execute: true, + model_tools: true, + ..PermissionSet::default() + } +} + +/// Registered but with no model tools: chats are text-only. +pub fn text_only() -> PermissionSet { + PermissionSet { + read: false, + write: false, + ..PermissionSet::default() + } +} + +/// Settings the fixture model accepts. +pub fn settings_json(endpoint: &str) -> Value { + json!({ + "endpoint": endpoint, + "model": "fixture", + "context_tokens": 131_072, + "max_output_tokens": 64, + "instructions": "", + "compact_threshold": 200_000, + "auto_compact": false + }) +} + +/// Poll `chat_status` until `done` holds, or fail at the deadline. +pub fn wait_for( + service: &DesktopService, + session_id: Uuid, + done: impl Fn(&ChatStatus) -> bool, +) -> ChatStatus { + let deadline = Instant::now() + POLL_DEADLINE; + loop { + let status = service + .chat_status(wire::(session_request(session_id))) + .expect("chat status"); + if done(&status) { + return status; + } + assert!( + Instant::now() < deadline, + "timed out waiting; last state {:?}", + status.state + ); + thread::sleep(Duration::from_millis(10)); + } +} + +/// Wait until the turn is no longer running. +pub fn wait_finished(service: &DesktopService, session_id: Uuid) -> ChatStatus { + wait_for(service, session_id, |status| { + matches!(status.state, ChatState::Completed | ChatState::Failed) + }) +} + +/// Wait for a signal from the mock server. +pub fn wait_arrived(arrived: &Receiver<()>) { + arrived + .recv_timeout(POLL_DEADLINE) + .expect("the model request arrived"); +} + +/// A fresh gate: release by sending or dropping the sender. +pub fn gate() -> (Sender<()>, Receiver<()>) { + mpsc::channel() +} + +/// Give `data` the private ACL the Windows control store requires of its root. +#[cfg(windows)] +fn restrict_to_current_user(data: &std::path::Path) { + let whoami = std::process::Command::new("whoami") + .args(["/user", "/fo", "csv", "/nh"]) + .output() + .expect("whoami"); + assert!(whoami.status.success(), "whoami fixture failed"); + let identity = String::from_utf8_lossy(&whoami.stdout).into_owned(); + let sid = identity + .trim() + .rsplit(',') + .next() + .expect("SID column") + .trim_matches('"') + .to_owned(); + let granted = std::process::Command::new("icacls") + .arg(data) + .args(["/inheritance:r", "/grant:r", &format!("*{sid}:(OI)(CI)F")]) + .output() + .expect("icacls"); + assert!(granted.status.success(), "icacls fixture failed"); +} + +/// Assert that no serialized response names the data root, a journal file, or +/// the server token. +pub fn assert_no_leaks(fixture: &Fixture, responses: &[String]) { + let data = fixture.data.to_string_lossy().into_owned(); + // The JSON form of the same path, with its backslashes escaped. + let escaped = serde_json::to_string(&data).expect("escape path"); + let escaped = escaped.trim_matches('"').to_owned(); + for response in responses { + assert!(!response.contains(&data), "data root in {response}"); + assert!( + !response.contains(&escaped), + "escaped data root in {response}" + ); + assert!( + !response.contains(".jsonl"), + "journal file name in {response}" + ); + assert!(!response.contains(SECRET), "token in {response}"); + } +} diff --git a/crates/omgcode-app/tests/desktop_approvals.rs b/crates/omgcode-app/tests/desktop_approvals.rs new file mode 100644 index 0000000..2f25165 --- /dev/null +++ b/crates/omgcode-app/tests/desktop_approvals.rs @@ -0,0 +1,580 @@ +//! Approval commands of the desktop service (ADR-0046) end to end: a scripted +//! model requests a gated tool call, the operator reviews and decides through +//! the service, and the identical call in a later turn consumes the approval. + +use std::fs; +use std::time::Duration; + +use omgcode_app::desktop::{ + ApprovalOperationDto, ApprovalStateDto, ApprovalView, Binding, ChatState, DesktopService, +}; +use omgcode_core::control::{ApprovalDeclaration, ApprovalOperation, ControlStore, now_unix}; +use omgcode_core::policy::WorkspaceId; +use serde_json::{Value, json}; +use uuid::Uuid; + +mod common; +use common::{ + Fixture, MockServer, Step, Workspace, all_tools, assert_no_leaks, json_of, settings_json, text, + text_of, tool_call, wait_finished, wire, +}; + +const EDIT_TOOL: &str = "workspace_edit_file"; +const COMMAND_TOOL: &str = "workspace_run_command"; +const FILE_AUDIT_NAME: &str = "file-operations-v1.jsonl"; + +struct Setup { + fixture: Fixture, + workspace: Workspace, + service: DesktopService, + server: MockServer, +} + +fn setup(steps: Vec) -> Setup { + let fixture = Fixture::new(); + fixture.declare_profile(); + let workspace = fixture.workspace("project", all_tools()); + let server = MockServer::start(steps); + let service = fixture.service(&server.endpoint); + Setup { + fixture, + workspace, + service, + server, + } +} + +fn edit_args(path: &str) -> Value { + json!({"path": path, "old_text": "bc", "new_text": "b"}) +} + +fn command_args() -> Value { + json!({"profile": "system", "program": "echo", "arguments": ["hello"]}) +} + +impl Setup { + fn session(&self, title: &str) -> Uuid { + self.service + .session_create(wire( + json!({"workspace_id": self.workspace.id, "title": title}), + )) + .expect("create session") + .session_id + } + + /// Send one message and wait for the turn to complete. + fn turn(&self, session: Uuid, message: &str) { + self.service + .chat_send(wire(json!({ + "session_id": session, + "message": message, + "settings": settings_json(&self.server.endpoint), + }))) + .expect("send"); + let done = wait_finished(&self.service, session); + assert_eq!(done.state, ChatState::Completed, "{:?}", done.error); + } + + fn list(&self) -> Vec { + self.service.approvals_list().expect("approvals").approvals + } + + fn pending(&self) -> Vec { + self.list() + .into_iter() + .filter(|view| view.state == ApprovalStateDto::Pending) + .collect() + } + + fn detail(&self, id: Uuid) -> omgcode_app::desktop::ApprovalDetail { + self.service + .approval_detail(wire(json!({"id": id}))) + .expect("detail") + } + + fn decide( + &self, + id: Uuid, + decision: &str, + writers_stopped: bool, + token: Option<&str>, + ) -> Result { + self.service.approval_decide(wire(json!({ + "id": id, + "decision": decision, + "writers_stopped": writers_stopped, + "review_token": token, + }))) + } + + fn state_of(&self, id: Uuid) -> ApprovalStateDto { + self.list() + .into_iter() + .find(|view| view.id == id) + .expect("listed approval") + .state + } + + fn audit_lines(&self) -> usize { + fs::read_to_string(self.fixture.data.join(FILE_AUDIT_NAME)) + .map(|text| text.lines().count()) + .unwrap_or(0) + } +} + +#[test] +fn an_edit_approval_is_reviewed_approved_and_consumed_by_the_identical_call() { + let setup = setup(vec![ + Step::reply(tool_call("edit-1", EDIT_TOOL, &edit_args("notes.txt"))), + Step::reply(text("waiting for approval")), + Step::reply(tool_call("edit-2", EDIT_TOOL, &edit_args("notes.txt"))), + Step::reply(text("applied")), + ]); + let notes = setup.workspace.path.join("notes.txt"); + fs::write(¬es, "alpha bcc\n").expect("workspace file"); + let session = setup.session("Edits"); + let service = &setup.service; + let mut responses = Vec::new(); + + assert_eq!(service.approvals_summary().expect("summary").pending, 0); + setup.turn(session, "fix the typo"); + let summary = service.approvals_summary().expect("summary"); + assert_eq!(summary.pending, 1); + responses.push(text_of(&summary)); + + // The list shows it with the session's title and folder. + let listed = service.approvals_list().expect("list"); + responses.push(text_of(&listed)); + assert_eq!(listed.approvals.len(), 1); + let approval = &listed.approvals[0]; + assert_eq!(approval.session_id, session); + assert_eq!(approval.session_title.as_deref(), Some("Edits")); + assert!( + approval + .folder_display + .as_deref() + .is_some_and(|folder| folder.ends_with("project")) + ); + assert_eq!(approval.operation, ApprovalOperationDto::FileWrite); + assert_eq!(approval.state, ApprovalStateDto::Pending); + assert!(!approval.writers_stopped); + assert_eq!(approval.request_sha256.len(), 64); + assert!(listed.now_unix <= approval.expires_unix); + let id = approval.id; + + // Review: exact, with the edit's fields and a token. Nothing is changed. + let detail = setup.detail(id); + responses.push(text_of(&detail)); + assert_eq!(detail.binding, Binding::Exact); + assert_eq!(detail.tool.as_deref(), Some(EDIT_TOOL)); + let field = |label: &str| { + detail + .fields + .iter() + .find(|field| field.label == label) + .unwrap_or_else(|| panic!("field {label}")) + }; + assert_eq!(field("File").value, "notes.txt"); + assert_eq!(field("Old text").value, "bc"); + assert!(field("Old text").multiline); + assert_eq!(field("New text").value, "b"); + assert_eq!(field("Size").value, "10 -> 9 bytes"); + assert_eq!(fs::read_to_string(¬es).expect("read"), "alpha bcc\n"); + let first_token = detail.review_token.clone().expect("a review token"); + + // Approve without the writers-stopped acknowledgement is refused, and the + // refused attempt consumed the token. + let refused = setup + .decide(id, "approve", false, Some(&first_token)) + .expect_err("a file write needs the acknowledgement"); + assert_eq!(refused.code(), "writers_stopped_required"); + assert_eq!(setup.state_of(id), ApprovalStateDto::Pending); + let reused = setup + .decide(id, "approve", true, Some(&first_token)) + .expect_err("the token is single use"); + assert_eq!(reused.code(), "review_expired"); + + // A fresh review gives a fresh token, and with the acknowledgement it works. + let again = setup.detail(id); + let second_token = again.review_token.expect("a fresh token"); + assert_ne!(second_token, first_token); + let approved = setup + .decide(id, "approve", true, Some(&second_token)) + .expect("approve"); + responses.push(text_of(&approved)); + assert_eq!(approved.state, ApprovalStateDto::Approved); + assert!(approved.writers_stopped); + assert_eq!(service.approvals_summary().expect("summary").pending, 0); + assert_eq!(fs::read_to_string(¬es).expect("read"), "alpha bcc\n"); + + // The model repeats the identical call; core consumes the approval and applies. + setup.turn(session, "try again"); + assert_eq!(fs::read_to_string(¬es).expect("read"), "alpha bc\n"); + assert_eq!(setup.state_of(id), ApprovalStateDto::Consumed); + responses.push(text_of(&setup.list())); + + assert_no_leaks(&setup.fixture, &responses); + assert_eq!(setup.server.finish(), 4); +} + +#[test] +fn a_command_approval_is_consumed_by_the_identical_call() { + let setup = setup(vec![ + Step::reply(tool_call("cmd-1", COMMAND_TOOL, &command_args())), + Step::reply(text("waiting")), + Step::reply(tool_call("cmd-2", COMMAND_TOOL, &command_args())), + Step::reply(text("ran")), + ]); + let session = setup.session("Commands"); + setup.turn(session, "say hello"); + let pending = setup.pending(); + assert_eq!(pending.len(), 1); + assert_eq!(pending[0].operation, ApprovalOperationDto::Command); + let id = pending[0].id; + + let detail = setup.detail(id); + assert_eq!(detail.binding, Binding::Exact); + assert_eq!(detail.tool.as_deref(), Some(COMMAND_TOOL)); + let value_of = |label: &str| { + detail + .fields + .iter() + .find(|field| field.label == label) + .map(|field| field.value.as_str()) + }; + assert_eq!(value_of("Profile"), Some("system")); + assert_eq!(value_of("Program"), Some("echo")); + assert_eq!(value_of("Arguments"), Some("1: hello")); + + // `writers_stopped` is ignored for a command. + let token = detail.review_token.expect("a token"); + let approved = setup + .decide(id, "approve", false, Some(&token)) + .expect("approve a command"); + assert_eq!(approved.state, ApprovalStateDto::Approved); + assert!(!approved.writers_stopped); + + setup.turn(session, "again"); + assert_eq!(setup.state_of(id), ApprovalStateDto::Consumed); + assert_eq!(setup.server.finish(), 4); +} + +/// Two sessions, each with one pending edit approval on its own file. +fn two_pending() -> (Setup, Uuid, Uuid) { + let setup = setup(vec![ + Step::reply(tool_call("edit-a", EDIT_TOOL, &edit_args("a.txt"))), + Step::reply(text("a asked")), + Step::reply(tool_call("edit-b", EDIT_TOOL, &edit_args("b.txt"))), + Step::reply(text("b asked")), + ]); + fs::write(setup.workspace.path.join("a.txt"), "abcc\n").expect("a"); + fs::write(setup.workspace.path.join("b.txt"), "bbcc\n").expect("b"); + let first = setup.session("First"); + setup.turn(first, "edit a"); + let second = setup.session("Second"); + setup.turn(second, "edit b"); + let pending = setup.pending(); + assert_eq!(pending.len(), 2); + let id_for = |session: Uuid| { + pending + .iter() + .find(|view| view.session_id == session) + .expect("approval for session") + .id + }; + let (a, b) = (id_for(first), id_for(second)); + (setup, a, b) +} + +#[test] +fn approve_needs_a_matching_unused_unexpired_review_token() { + let (setup, a, b) = two_pending(); + + // No token at all. + let none = setup + .decide(a, "approve", true, None) + .expect_err("no token"); + assert_eq!(none.code(), "review_expired"); + + // A wrong token is a mismatch, and it burns the right one. + let token = setup.detail(a).review_token.expect("token"); + let wrong = setup + .decide(a, "approve", true, Some("not-the-token")) + .expect_err("wrong token"); + assert_eq!(wrong.code(), "review_mismatch"); + let burnt = setup + .decide(a, "approve", true, Some(&token)) + .expect_err("the right token no longer works"); + assert_eq!(burnt.code(), "review_expired"); + + // A token for approval A cannot approve B, and does not disturb A's own. + let token_a = setup.detail(a).review_token.expect("token for a"); + let foreign = setup + .decide(b, "approve", true, Some(&token_a)) + .expect_err("a's token on b"); + assert_eq!(foreign.code(), "review_expired"); + let token_b = setup.detail(b).review_token.expect("token for b"); + let crossed = setup + .decide(b, "approve", true, Some(&token_a)) + .expect_err("a's token on b with b reviewed"); + assert_eq!(crossed.code(), "review_mismatch"); + assert_eq!(setup.state_of(b), ApprovalStateDto::Pending); + let still = setup + .decide(a, "approve", true, Some(&token_a)) + .expect("a's own token still works"); + assert_eq!(still.state, ApprovalStateDto::Approved); + // B's token was burnt by the crossed attempt. + let burnt_b = setup + .decide(b, "approve", true, Some(&token_b)) + .expect_err("b's token was removed by the failed attempt"); + assert_eq!(burnt_b.code(), "review_expired"); +} + +#[test] +fn deny_needs_no_token_and_a_second_decision_is_not_pending() { + let (setup, a, b) = two_pending(); + let denied = setup.decide(a, "deny", false, None).expect("deny"); + assert_eq!(denied.state, ApprovalStateDto::Denied); + + for decision in ["deny", "approve"] { + let twice = setup + .decide(a, decision, true, Some("whatever")) + .expect_err("already decided"); + assert_eq!(twice.code(), "not_pending"); + } + let unknown = setup + .decide(Uuid::new_v4(), "deny", false, None) + .expect_err("unknown approval"); + assert_eq!(unknown.code(), "not_found"); + + // The list shows pending first, then the resolved one. + let listed = setup.list(); + assert_eq!(listed[0].id, b); + assert_eq!(listed[1].id, a); + assert_eq!( + setup.service.approvals_summary().expect("summary").pending, + 1 + ); +} + +#[test] +fn reviewing_a_non_pending_approval_reads_nothing_and_returns_stale_without_a_token() { + let (setup, a, b) = two_pending(); + setup.decide(a, "deny", false, None).expect("deny"); + + let before = setup.audit_lines(); + let detail = setup.detail(a); + assert_eq!(detail.binding, Binding::Stale); + assert_eq!(detail.tool, None); + assert!(detail.fields.is_empty()); + assert_eq!(detail.review_token, None); + assert_eq!(detail.approval.state, ApprovalStateDto::Denied); + assert_eq!(setup.audit_lines(), before, "no file was read"); + + // A pending review reads exactly the target file once, through the audit. + let exact = setup.detail(b); + assert_eq!(exact.binding, Binding::Exact); + assert!( + setup.audit_lines() > before, + "the exact review read the file" + ); + + let unknown = setup + .service + .approval_detail(wire(json!({"id": Uuid::new_v4()}))) + .expect_err("unknown approval"); + assert_eq!(unknown.code(), "not_found"); +} + +#[test] +fn a_changed_target_makes_the_review_stale_and_blocks_approval() { + let (setup, a, _) = two_pending(); + fs::write(setup.workspace.path.join("a.txt"), "completely different\n").expect("change a"); + let detail = setup.detail(a); + assert_eq!(detail.binding, Binding::Stale); + assert_eq!(detail.review_token, None); + assert!(detail.fields.is_empty()); + let refused = setup + .decide(a, "approve", true, None) + .expect_err("a stale review has no token"); + assert_eq!(refused.code(), "review_expired"); +} + +#[test] +fn a_turn_running_for_the_session_makes_the_review_busy() { + let (release, hold) = common::gate(); + let (announce, arrived) = std::sync::mpsc::channel(); + let setup = setup(vec![ + Step::reply(tool_call("edit-a", EDIT_TOOL, &edit_args("a.txt"))), + Step::reply(text("asked")), + Step::gated(text("later"), hold).announcing(announce), + ]); + fs::write(setup.workspace.path.join("a.txt"), "abcc\n").expect("a"); + let session = setup.session("Busy review"); + setup.turn(session, "edit"); + let id = setup.pending()[0].id; + + setup + .service + .chat_send(wire(json!({ + "session_id": session, + "message": "again", + "settings": settings_json(&setup.server.endpoint), + }))) + .expect("send"); + common::wait_arrived(&arrived); + let busy = setup + .service + .approval_detail(wire(json!({"id": id}))) + .expect_err("the journal belongs to the running turn"); + assert_eq!(busy.code(), "busy"); + release.send(()).expect("release"); + wait_finished(&setup.service, session); +} + +#[test] +fn the_list_orders_pending_first_caps_resolved_ones_and_escapes_summaries() { + let fixture = Fixture::new(); + let workspace = fixture.workspace("project", all_tools()); + let service = fixture.service("http://127.0.0.1:1/v1"); + let workspace_id: WorkspaceId = { + let control = ControlStore::open(&fixture.data).expect("control"); + control + .workspaces() + .find(|registered| *registered.id().as_uuid() == workspace.id) + .expect("registered") + .id() + }; + let session = Uuid::new_v4(); + let mut ids = Vec::new(); + { + let mut control = ControlStore::open(&fixture.data).expect("control"); + let now = now_unix(); + for number in 0..62_u32 { + let summary = if number == 61 { + "hostile \u{202e}summary".to_owned() + } else { + format!("network request {number}") + }; + let status = control + .request_approval( + &ApprovalDeclaration { + session_id: session, + workspace_id, + operation: ApprovalOperation::Network, + request_sha256: format!("{number:064x}"), + summary, + ttl_secs: 600, + }, + now, + ) + .expect("request an approval"); + ids.push(status.id); + } + // Deny all but the first and the last: 60 resolved, 2 pending. + for id in &ids[1..61] { + control.decide_approval(*id, false, now).expect("deny"); + } + } + + let listed = service.approvals_list().expect("list").approvals; + assert_eq!(listed.len(), 2 + 50); + assert_eq!(listed[0].id, ids[0]); + assert_eq!(listed[1].id, ids[61]); + assert_eq!( + listed[1].summary, + omgcode_core::turn::display_safe_line("hostile \u{202e}summary") + ); + assert!(listed[1].summary.contains("\\u{202e}")); + // The 50 most recent resolved ones, in store order: numbers 11 through 60. + let resolved: Vec = listed[2..].iter().map(|view| view.id).collect(); + assert_eq!(resolved, ids[11..61].to_vec()); + assert!( + listed[2..] + .iter() + .all(|view| view.state == ApprovalStateDto::Denied) + ); + // An unknown session has no labels. + assert!(listed[0].session_title.is_none() && listed[0].folder_display.is_none()); + assert_eq!(listed[0].operation, ApprovalOperationDto::Network); + assert_eq!(service.approvals_summary().expect("summary").pending, 2); + + // A network record has no reviewable tool: its review is `not_found`, not an error. + let detail = service + .approval_detail(wire(json!({"id": ids[0]}))) + .expect("detail"); + assert_eq!(detail.binding, Binding::NotFound); + assert!(detail.review_token.is_none()); +} + +#[test] +fn the_summary_serves_its_last_count_while_the_store_is_held_and_the_list_reports_busy() { + let fixture = Fixture::new(); + let service = fixture.service("http://127.0.0.1:1/v1"); + // No approvals yet; remember the count of zero, then add one and read it. + assert_eq!(service.approvals_summary().expect("summary").pending, 0); + let workspace = fixture.workspace("project", all_tools()); + { + let mut control = ControlStore::open(&fixture.data).expect("control"); + let id = control + .workspaces() + .find(|registered| *registered.id().as_uuid() == workspace.id) + .expect("registered") + .id(); + control + .request_approval( + &ApprovalDeclaration { + session_id: Uuid::new_v4(), + workspace_id: id, + operation: ApprovalOperation::Network, + request_sha256: "a".repeat(64), + summary: "one".to_owned(), + ttl_secs: 600, + }, + now_unix(), + ) + .expect("request"); + } + assert_eq!(service.approvals_summary().expect("summary").pending, 1); + + let held = ControlStore::open(&fixture.data).expect("hold the settings store"); + let begun = std::time::Instant::now(); + let cached = service + .approvals_summary() + .expect("a busy store is not an error"); + assert_eq!(cached.pending, 1, "the last count read is served"); + assert!( + begun.elapsed() >= Duration::from_millis(1500), + "bounded retry" + ); + let busy = service + .approvals_list() + .expect_err("the list needs the store"); + assert_eq!(busy.code(), "busy"); + let busy = service + .workspace_list() + .expect_err("the workspace list needs the store"); + assert_eq!(busy.code(), "busy"); + drop(held); + assert_eq!(service.approvals_summary().expect("summary").pending, 1); +} + +#[test] +fn without_a_settings_store_there_are_no_approvals() { + let fixture = Fixture::bare(); + let service = fixture.service("http://127.0.0.1:1/v1"); + assert_eq!(service.approvals_summary().expect("summary").pending, 0); + let listed = service.approvals_list().expect("list"); + assert!(listed.approvals.is_empty()); + let missing = service + .approval_detail(wire(json!({"id": Uuid::new_v4()}))) + .expect_err("no such approval"); + assert_eq!(missing.code(), "not_found"); + let missing = service + .approval_decide(wire(json!({ + "id": Uuid::new_v4(), "decision": "deny", "writers_stopped": false, "review_token": null + }))) + .expect_err("no such approval"); + assert_eq!(missing.code(), "not_found"); + assert!(json_of(&listed).get("now_unix").is_some()); +} diff --git a/crates/omgcode-app/tests/desktop_chat.rs b/crates/omgcode-app/tests/desktop_chat.rs new file mode 100644 index 0000000..38e34f5 --- /dev/null +++ b/crates/omgcode-app/tests/desktop_chat.rs @@ -0,0 +1,540 @@ +//! Chat commands of the desktop service end to end: a real journal, a real +//! index, and a scripted loopback model server. Every wait is bounded. + +use std::time::{Duration, Instant}; + +use omgcode_app::desktop::{ + ChatState, ChatStatus, DesktopError, DesktopService, SessionStatus, ToolsMode, +}; +use serde_json::json; +use uuid::Uuid; + +mod common; +use common::{ + Fixture, MockServer, SECRET, Step, Workspace, fixed_token, gate, json_of, read_tools, + session_request, settings_json, text, text_of, text_only, tool_call, unused_endpoint, + wait_arrived, wait_finished, wire, +}; + +fn new_session(service: &DesktopService, workspace: &Workspace, title: &str) -> Uuid { + service + .session_create(wire(json!({"workspace_id": workspace.id, "title": title}))) + .expect("create session") + .session_id +} + +fn send( + service: &DesktopService, + session: Uuid, + message: &str, + endpoint: &str, +) -> Result { + service.chat_send(wire(json!({ + "session_id": session, + "message": message, + "settings": settings_json(endpoint), + }))) +} + +fn status(service: &DesktopService, session: Uuid) -> ChatStatus { + service + .chat_status(wire(session_request(session))) + .expect("status") +} + +fn texts(service: &DesktopService, session: Uuid) -> Vec<(String, String)> { + let page = service + .session_transcript(wire( + json!({"session_id": session, "after_seq": null, "limit": 200}), + )) + .expect("transcript"); + page.entries + .iter() + .filter_map(|entry| { + let value = json_of(entry); + (value["kind"] == "message").then(|| { + ( + value["role"].as_str().unwrap_or_default().to_owned(), + value["text"].as_str().unwrap_or_default().to_owned(), + ) + }) + }) + .collect() +} + +/// A service on a fresh fixture with one workspace and its model server. +fn started(permissions: omgcode_core::policy::PermissionSet, steps: Vec) -> Started { + let fixture = Fixture::new(); + let workspace = fixture.workspace("project", permissions); + let server = MockServer::start(steps); + let service = fixture.service(&server.endpoint); + Started { + _fixture: fixture, + workspace, + server, + service, + } +} + +struct Started { + /// Keeps the private data root alive for the test. + _fixture: Fixture, + workspace: Workspace, + server: MockServer, + service: DesktopService, +} + +#[test] +fn a_text_only_turn_runs_in_the_background_and_completes_with_its_outcome() { + let started = started(text_only(), vec![Step::reply(text("pong"))]); + let service = &started.service; + let session = new_session(service, &started.workspace, "Chat"); + + let running = send(service, session, "ping", &started.server.endpoint).expect("send"); + assert_eq!(running.state, ChatState::Running); + assert_eq!(running.session_id, session); + assert!(running.outcome.is_none() && running.error.is_none()); + + let done = wait_finished(service, session); + assert_eq!(done.state, ChatState::Completed); + let outcome = done.outcome.expect("an outcome"); + assert_eq!(outcome.finish_reason, "stop"); + assert_eq!(outcome.tools_mode, ToolsMode::Disabled); + assert!(outcome.tools_disabled_reason.is_some()); + assert_eq!((outcome.rounds, outcome.tool_calls), (0, 0)); + assert_eq!(outcome.withheld_tool_results, 0); + let context = outcome.context.expect("a context meter"); + assert_eq!(context.context_tokens, 131_072); + assert!(context.estimated_tokens > 0 && context.trigger_tokens > 0); + assert!(!context.compacted); + assert!(done.error.is_none()); + // Reading the result again returns the same one until the next send. + assert_eq!(status(service, session).state, ChatState::Completed); + + assert_eq!( + texts(service, session), + [ + ("user".to_owned(), "ping".to_owned()), + ("assistant".to_owned(), "pong".to_owned()) + ] + ); + let tree = service + .session_tree(wire( + json!({"view": "active", "sort": "updated", "descending": true}), + )) + .expect("tree"); + let summary = &tree.groups[0].sessions[0]; + assert_eq!(summary.status, SessionStatus::Idle); + assert!(summary.event_count > 1, "the index saw the finished turn"); + assert_eq!(started.server.finish(), 1); +} + +#[test] +fn a_tool_turn_reports_rounds_and_tool_calls() { + let started = started( + read_tools(), + vec![ + Step::reply(tool_call( + "call-1", + "workspace_list_directory", + &json!({"path": ""}), + )), + Step::reply(text("listed")), + ], + ); + let service = &started.service; + std::fs::write( + started.workspace.path.join("notes.txt"), + "alpha +", + ) + .expect("workspace file"); + let session = new_session(service, &started.workspace, "Tools"); + send(service, session, "list", &started.server.endpoint).expect("send"); + let done = wait_finished(service, session); + let outcome = done + .outcome + .clone() + .unwrap_or_else(|| panic!("failed: {:?}", done.error)); + assert_eq!(outcome.tools_mode, ToolsMode::Enabled); + assert_eq!(outcome.tools_disabled_reason, None); + assert_eq!((outcome.rounds, outcome.tool_calls), (2, 1)); + assert_eq!(started.server.finish(), 2); +} + +#[test] +fn concurrent_turns_are_limited_per_session_and_in_total_and_a_finished_session_can_chat_again() { + let (release_one, gate_one) = gate(); + let (release_two, gate_two) = gate(); + let (announce, arrived) = std::sync::mpsc::channel(); + let started = started( + text_only(), + vec![ + Step::gated(text("one"), gate_one).announcing(announce), + Step::gated(text("two"), gate_two), + Step::reply(text("three")), + ], + ); + let service = &started.service; + let endpoint = started.server.endpoint.clone(); + let first = new_session(service, &started.workspace, "First"); + let second = new_session(service, &started.workspace, "Second"); + let third = new_session(service, &started.workspace, "Third"); + + send(service, first, "a", &endpoint).expect("first turn"); + wait_arrived(&arrived); + send(service, second, "b", &endpoint).expect("second turn"); + + // The same session again, and a third session beyond the limit of two. + let again = send(service, first, "again", &endpoint).expect_err("one turn per session"); + assert_eq!(again.code(), "turn_running"); + let over = send(service, third, "c", &endpoint).expect_err("two turns at most"); + assert_eq!(over.code(), "too_many_turns"); + assert_eq!(status(service, third).state, ChatState::Idle); + + // While running: the tree says so, and journal access is refused. + let tree = service + .session_tree(wire( + json!({"view": "active", "sort": "title", "descending": false}), + )) + .expect("tree"); + let state_of = |id: Uuid| { + tree.groups + .iter() + .flat_map(|group| &group.sessions) + .find(|session| session.session_id == id) + .map(|session| session.status) + .expect("listed") + }; + assert_eq!(state_of(first), SessionStatus::Running); + assert_eq!(state_of(second), SessionStatus::Running); + assert_eq!(state_of(third), SessionStatus::Idle); + let busy = service + .session_transcript(wire( + json!({"session_id": first, "after_seq": null, "limit": 5}), + )) + .expect_err("no inspection while a turn runs here"); + assert_eq!(busy.code(), "busy"); + for refused in [ + service.session_archive(wire(session_request(first))), + service.session_restore(wire(session_request(first))), + service.session_interrupt(wire(session_request(first))), + ] { + assert_eq!(refused.expect_err("running").code(), "turn_running"); + } + + release_one.send(()).expect("release the first model reply"); + release_two + .send(()) + .expect("release the second model reply"); + assert_eq!(wait_finished(service, first).state, ChatState::Completed); + assert_eq!(wait_finished(service, second).state, ChatState::Completed); + + // With the slots free, a third session can chat; a finished session can + // chat again and its old result is replaced. + send(service, third, "c", &endpoint).expect("third turn after the others finished"); + assert_eq!(wait_finished(service, third).state, ChatState::Completed); + assert_eq!(started.server.finish(), 3); +} + +#[test] +fn a_refused_send_starts_no_thread_and_records_nothing() { + let fixture = Fixture::new(); + let workspace = fixture.workspace("project", text_only()); + let endpoint = unused_endpoint(); + let service = fixture.service(&endpoint); + let session = new_session(&service, &workspace, "Refusals"); + + // A different endpoint than the one fixed at launch. + let other = send(&service, session, "hi", "http://127.0.0.1:9/v1").expect_err("endpoint"); + assert_eq!(other.code(), "invalid_request"); + assert_eq!(other.message(), "The endpoint is fixed by the application."); + + // Nothing to send, or too much. + let blank = send(&service, session, " \n\t", &endpoint).expect_err("blank"); + assert_eq!(blank.code(), "invalid_request"); + let huge = "x".repeat(65 * 1024); + let large = send(&service, session, &huge, &endpoint).expect_err("oversized"); + assert_eq!(large.code(), "invalid_request"); + + // Bad model settings are a synchronous provider error. + let mut settings = settings_json(&endpoint); + settings["model"] = json!(""); + let bad_model = service + .chat_send(wire( + json!({"session_id": session, "message": "hi", "settings": settings}), + )) + .expect_err("an empty model"); + assert_eq!(bad_model.code(), "provider"); + let mut settings = settings_json(&endpoint); + settings["context_tokens"] = json!(0); + let bad_context = service + .chat_send(wire( + json!({"session_id": session, "message": "hi", "settings": settings}), + )) + .expect_err("a zero context"); + assert_eq!(bad_context.code(), "provider"); + + // An unknown session. + let unknown = send(&service, Uuid::new_v4(), "hi", &endpoint).expect_err("unknown"); + assert_eq!(unknown.code(), "not_found"); + + // None of those started a turn or touched the journal. + assert_eq!(status(&service, session).state, ChatState::Idle); + let report = service.shutdown(Duration::from_secs(5)); + assert_eq!((report.finished, report.still_running), (0, 0)); + assert!(texts(&service, session).is_empty()); +} + +#[test] +fn an_archived_session_and_an_open_turn_refuse_a_send() { + let fixture = Fixture::new(); + let workspace = fixture.workspace("project", text_only()); + let endpoint = unused_endpoint(); + let service = fixture.service(&endpoint); + + let archived = new_session(&service, &workspace, "Archived"); + service + .session_archive(wire(session_request(archived))) + .expect("archive"); + let error = send(&service, archived, "hi", &endpoint).expect_err("archived"); + assert_eq!(error.code(), "archived"); + + let open = new_session(&service, &workspace, "Open turn"); + // Leave a turn open in the journal, as a crashed process would. + let path = omgcode_core::session::locate(&fixture.data, open) + .expect("locate") + .expect("journal"); + { + let mut journal = omgcode_core::session::SessionJournal::open(&path).expect("open"); + journal + .record_message(omgcode_core::session::MessageRole::User, "q") + .expect("message"); + journal.start_turn().expect("start turn"); + } + let error = send(&service, open, "hi", &endpoint).expect_err("open turn"); + assert_eq!(error.code(), "turn_open"); +} + +#[test] +fn a_provider_transport_failure_ends_failed_with_code_provider_and_no_token() { + let fixture = Fixture::new(); + let workspace = fixture.workspace("project", text_only()); + let endpoint = unused_endpoint(); + let service = fixture.service_with(&endpoint, fixed_token); + let session = new_session(&service, &workspace, "Unreachable"); + + send(&service, session, &format!("hello {SECRET}"), &endpoint).expect("send"); + let done = wait_finished(&service, session); + assert_eq!(done.state, ChatState::Failed); + assert!(done.outcome.is_none()); + let error = done.error.as_ref().expect("an error"); + assert_eq!(error.code(), "provider"); + let serialized = text_of(&done); + assert!(!serialized.contains(SECRET), "{serialized}"); + assert!(!format!("{done:?}").contains(SECRET)); + + // The journal recorded the failed turn and the redacted message only. + let page = service + .session_transcript(wire( + json!({"session_id": session, "after_seq": null, "limit": 50}), + )) + .expect("transcript"); + let all = text_of(&page); + assert!(!all.contains(SECRET), "the token was recorded: {all}"); + assert!(all.contains("[REDACTED]")); + assert!(all.contains("turn_failed")); +} + +#[test] +fn the_server_token_never_reaches_a_response_even_when_the_model_echoes_it() { + let fixture = Fixture::new(); + let workspace = fixture.workspace("project", text_only()); + let server = MockServer::start(vec![Step::reply(text(&format!("echo {SECRET}")))]); + let service = fixture.service_with(&server.endpoint, fixed_token); + let session = new_session(&service, &workspace, "Echo"); + send( + &service, + session, + &format!("say {SECRET}"), + &server.endpoint, + ) + .expect("send"); + let done = wait_finished(&service, session); + assert_eq!(done.state, ChatState::Completed); + + let mut responses = vec![text_of(&done)]; + responses.push(text_of( + &service + .session_transcript(wire( + json!({"session_id": session, "after_seq": null, "limit": 50}), + )) + .expect("transcript"), + )); + responses.push(text_of( + &service + .session_tree(wire( + json!({"view": "active", "sort": "updated", "descending": true}), + )) + .expect("tree"), + )); + responses.push(text_of( + &service + .session_search(wire( + json!({"query": "echo", "view": "active", "limit": 10}), + )) + .expect("search"), + )); + responses.push(text_of(&service.workspace_list().expect("workspaces"))); + responses.push(text_of(&service.approvals_list().expect("approvals"))); + responses.push(text_of(&service.chat_defaults())); + common::assert_no_leaks(&fixture, &responses); + assert!(responses[1].contains("[REDACTED]")); + assert_eq!(server.finish(), 1); +} + +#[test] +fn cancelling_a_tool_turn_reports_cancelling_then_fails_with_the_core_error() { + let (release, hold) = gate(); + let (announce, arrived) = std::sync::mpsc::channel(); + let started = started( + read_tools(), + vec![ + Step::gated( + tool_call("call-1", "workspace_list_directory", &json!({"path": "."})), + hold, + ) + .announcing(announce), + ], + ); + let service = &started.service; + let session = new_session(service, &started.workspace, "Cancel me"); + send(service, session, "list", &started.server.endpoint).expect("send"); + wait_arrived(&arrived); + + let cancelling = service + .chat_cancel(wire(session_request(session))) + .expect("cancel"); + assert_eq!(cancelling.state, ChatState::Cancelling); + assert_eq!(status(service, session).state, ChatState::Cancelling); + release.send(()).expect("release the model reply"); + + let done = wait_finished(service, session); + assert_eq!(done.state, ChatState::Failed); + let error = done.error.expect("an error"); + assert_eq!(error.code(), "turn"); + assert_eq!(error.message(), "turn was cancelled"); + let page = service + .session_transcript(wire( + json!({"session_id": session, "after_seq": null, "limit": 50}), + )) + .expect("transcript"); + let failure = page + .entries + .iter() + .map(json_of) + .find(|entry| entry["kind"] == "turn_failed") + .expect("a failed turn is recorded"); + assert_eq!(failure["code"], "cancelled"); + assert_eq!(started.server.finish(), 1); +} + +#[test] +fn a_cancel_request_does_not_pretend_to_stop_a_text_only_turn() { + let (release, hold) = gate(); + let (announce, arrived) = std::sync::mpsc::channel(); + let started = started( + text_only(), + vec![Step::gated(text("late answer"), hold).announcing(announce)], + ); + let service = &started.service; + let session = new_session(service, &started.workspace, "Uncancellable"); + send(service, session, "hi", &started.server.endpoint).expect("send"); + wait_arrived(&arrived); + + let after = service + .chat_cancel(wire(session_request(session))) + .expect("cancel"); + assert_eq!( + after.state, + ChatState::Running, + "no cancellation point exists" + ); + assert_eq!(status(service, session).state, ChatState::Running); + release.send(()).expect("release the model reply"); + assert_eq!(wait_finished(service, session).state, ChatState::Completed); + + // Cancelling something that is not running or unknown is idle or unchanged. + let unknown = service + .chat_cancel(wire(session_request(Uuid::new_v4()))) + .expect("cancel unknown"); + assert_eq!(unknown.state, ChatState::Idle); + assert_eq!( + service + .chat_cancel(wire(session_request(session))) + .expect("cancel finished") + .state, + ChatState::Completed + ); + assert_eq!(started.server.finish(), 1); +} + +#[test] +fn shutdown_does_not_wait_past_its_grace_and_later_reports_the_turn_finished() { + let (release, hold) = gate(); + let (announce, arrived) = std::sync::mpsc::channel(); + let started = started( + text_only(), + vec![Step::gated(text("slow"), hold).announcing(announce)], + ); + let service = &started.service; + let session = new_session(service, &started.workspace, "Slow"); + send(service, session, "hi", &started.server.endpoint).expect("send"); + wait_arrived(&arrived); + + let grace = Duration::from_millis(150); + let begun = Instant::now(); + let report = service.shutdown(grace); + let elapsed = begun.elapsed(); + assert_eq!((report.finished, report.still_running), (0, 1)); + assert!(elapsed >= grace, "waited the grace period: {elapsed:?}"); + assert!( + elapsed < grace + Duration::from_secs(2), + "did not block past the grace period: {elapsed:?}" + ); + assert_eq!(status(service, session).state, ChatState::Running); + let after = send(service, session, "more", &started.server.endpoint) + .expect_err("no new turn after shutdown"); + assert_eq!(after.code(), "shutting_down"); + + // Once the model answers, the thread ends and shutdown reports it finished. + release.send(()).expect("release the model reply"); + let report = service.shutdown(Duration::from_secs(20)); + assert_eq!((report.finished, report.still_running), (1, 0)); + assert_eq!(status(service, session).state, ChatState::Completed); + assert_eq!(started.server.finish(), 1); +} + +#[test] +fn shutdown_with_no_turns_returns_at_once() { + let fixture = Fixture::bare(); + let service = fixture.service(&unused_endpoint()); + let begun = Instant::now(); + let report = service.shutdown(Duration::from_secs(30)); + assert_eq!((report.finished, report.still_running), (0, 0)); + assert!(begun.elapsed() < Duration::from_secs(2)); +} + +#[test] +fn chat_defaults_are_the_cli_defaults_with_the_fixed_endpoint() { + let fixture = Fixture::bare(); + let endpoint = "http://127.0.0.1:1234/v1"; + let defaults = fixture.service(endpoint).chat_defaults(); + assert_eq!(defaults.endpoint, endpoint); + assert_eq!(defaults.model, ""); + assert_eq!(defaults.context_tokens, 0); + assert_eq!(defaults.max_output_tokens, 1024); + assert_eq!(defaults.instructions, ""); + assert_eq!(defaults.compact_threshold, 200_000); + assert!(!defaults.auto_compact); +} diff --git a/crates/omgcode-app/tests/desktop_sessions.rs b/crates/omgcode-app/tests/desktop_sessions.rs new file mode 100644 index 0000000..a28dfa3 --- /dev/null +++ b/crates/omgcode-app/tests/desktop_sessions.rs @@ -0,0 +1,715 @@ +//! Session tree, search, transcript, lifecycle, workspace, and creation +//! commands of the desktop service, against real journals and a real index. + +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::PathBuf; +use std::thread; +use std::time::Duration; + +use omgcode_app::desktop::{ + DesktopService, SearchRoleDto, SessionStatus, SessionSummary, SessionTree, TranscriptPage, +}; +use omgcode_core::session::{ + CompactionRecord, MessageRole, RequestManifest, SessionJournal, ToolOutcome, +}; +use omgcode_core::turn::display_safe_line; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use uuid::Uuid; + +mod common; +use common::{Fixture, Workspace, json_of, no_token, read_tools, session_request, text_only, wire}; + +/// A short pause so consecutive journal events carry distinct times. +const TICK: Duration = Duration::from_millis(8); +const NO_ENDPOINT: &str = "http://127.0.0.1:1/v1"; + +fn service(fixture: &Fixture) -> DesktopService { + fixture.service(NO_ENDPOINT) +} + +fn tree(service: &DesktopService, view: &str, sort: &str, descending: bool) -> SessionTree { + service + .session_tree(wire( + json!({"view": view, "sort": sort, "descending": descending}), + )) + .expect("session tree") +} + +fn create(service: &DesktopService, workspace: &Workspace, title: &str) -> SessionSummary { + thread::sleep(TICK); + service + .session_create(wire(json!({"workspace_id": workspace.id, "title": title}))) + .expect("create session") +} + +fn titles(tree: &SessionTree) -> Vec> { + tree.groups + .iter() + .map(|group| group.sessions.iter().map(|s| s.title.clone()).collect()) + .collect() +} + +fn manifest() -> RequestManifest { + RequestManifest { + base_prompt: "BASE".into(), + prompt_version: "7".into(), + prompt_sha256: "a".repeat(64), + custom_instructions: String::new(), + model: "local-model".into(), + base_url: "http://127.0.0.1:1234/v1".into(), + context_tokens: 32_000, + max_output_tokens: 2_000, + tool_schema_version: Some("1".into()), + tools: Some(vec!["workspace_read_file".into()]), + } +} + +fn sha256_hex(text: &str) -> String { + Sha256::digest(text.as_bytes()) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +/// Create a journal directly with the core, release it, and return id and path. +fn core_session(fixture: &Fixture, workspace: &Workspace, title: &str) -> (Uuid, PathBuf) { + let journal = SessionJournal::create(&fixture.data, &workspace.path, title).expect("create"); + (journal.snapshot().session_id, journal.path().to_path_buf()) +} + +fn fixture_with_workspaces() -> (Fixture, Workspace, Workspace) { + let fixture = Fixture::new(); + let first = fixture.workspace("alpha-project", text_only()); + let second = fixture.workspace("beta-project", text_only()); + (fixture, first, second) +} + +#[test] +fn the_tree_groups_by_folder_orders_each_sort_and_filters_the_view() { + let (fixture, alpha, beta) = fixture_with_workspaces(); + let service = service(&fixture); + let charlie = create(&service, &alpha, "Charlie"); + create(&service, &beta, "alpha"); + create(&service, &alpha, "Bravo"); + let archived = create(&service, &beta, "Zulu archived"); + service + .session_archive(wire(session_request(archived.session_id))) + .expect("archive"); + + // Updated, newest first: Bravo, alpha, Charlie -> groups alpha-project, beta-project. + let by_updated = tree(&service, "active", "updated", true); + assert_eq!(by_updated.indexed_sessions, 3); + assert_eq!(by_updated.skipped_entries, 0); + assert_eq!( + titles(&by_updated), + [vec!["Bravo", "Charlie"], vec!["alpha"]] + ); + // Oldest first: Charlie, alpha, Bravo. + assert_eq!( + titles(&tree(&service, "active", "updated", false)), + [vec!["Charlie", "Bravo"], vec!["alpha"]] + ); + // Created, ascending and descending. + assert_eq!( + titles(&tree(&service, "active", "created", false)), + [vec!["Charlie", "Bravo"], vec!["alpha"]] + ); + assert_eq!( + titles(&tree(&service, "active", "created", true)), + [vec!["Bravo", "Charlie"], vec!["alpha"]] + ); + // Title, case-insensitive: alpha, Bravo, Charlie. + assert_eq!( + titles(&tree(&service, "active", "title", false)), + [vec!["alpha"], vec!["Bravo", "Charlie"]] + ); + assert_eq!( + titles(&tree(&service, "active", "title", true)), + [vec!["Charlie", "Bravo"], vec!["alpha"]] + ); + + // The group folders and their opaque, stable, distinct identifiers. + let groups = &by_updated.groups; + assert!(groups[0].folder_display.ends_with("alpha-project")); + assert!(groups[1].folder_display.ends_with("beta-project")); + assert_eq!(groups[0].group_id.len(), 16); + assert_ne!(groups[0].group_id, groups[1].group_id); + let again = tree(&service, "active", "title", false); + let alpha_group = again + .groups + .iter() + .find(|group| group.folder_display.ends_with("alpha-project")) + .expect("alpha group"); + assert_eq!(alpha_group.group_id, groups[0].group_id); + + // The archived view holds only the archived session. + let archived_view = tree(&service, "archived", "updated", true); + assert_eq!(archived_view.indexed_sessions, 1); + assert_eq!(titles(&archived_view), [vec!["Zulu archived"]]); + assert!(archived_view.groups[0].sessions[0].archived); + assert_eq!(charlie.status, SessionStatus::Idle); +} + +#[test] +fn a_session_without_a_registered_workspace_still_groups_by_its_recorded_folder() { + let fixture = Fixture::new(); + let loose = fixture.workspace("loose", text_only()); + let (id, _) = core_session(&fixture, &loose, "Direct"); + let service = service(&fixture); + let tree = tree(&service, "active", "updated", true); + assert_eq!(tree.groups.len(), 1); + assert_eq!(tree.groups[0].sessions[0].session_id, id); + assert!(tree.groups[0].folder_display.ends_with("loose")); +} + +#[test] +fn an_open_turn_is_reported_and_interrupting_closes_it_with_the_operator_code() { + let (fixture, alpha, _) = fixture_with_workspaces(); + let (id, path) = core_session(&fixture, &alpha, "Unfinished"); + { + let mut journal = SessionJournal::open(&path).expect("open"); + journal + .record_message(MessageRole::User, "question") + .expect("message"); + journal.start_turn().expect("start turn"); + } + let service = service(&fixture); + let listed = tree(&service, "active", "updated", true); + assert_eq!(listed.groups[0].sessions[0].status, SessionStatus::TurnOpen); + + // Archiving is refused while a turn is open. + let refused = service + .session_archive(wire(session_request(id))) + .expect_err("an open turn blocks archiving"); + assert_eq!(refused.code(), "turn_open"); + + let closed = service + .session_interrupt(wire(session_request(id))) + .expect("interrupt"); + assert_eq!(closed.status, SessionStatus::Idle); + let page = transcript(&service, id, None, 50); + let failure = json_of(page.entries.last().expect("entries")); + assert_eq!(failure["kind"], "turn_failed"); + assert_eq!(failure["code"], "operator_interrupted"); + + let again = service + .session_interrupt(wire(session_request(id))) + .expect_err("no turn is open"); + assert_eq!(again.code(), "invalid_request"); + assert_eq!(again.message(), "No turn is open."); +} + +#[test] +fn archive_and_restore_change_the_listing_and_are_idempotent() { + let (fixture, alpha, _) = fixture_with_workspaces(); + let service = service(&fixture); + let session = create(&service, &alpha, "Keep or file"); + let request = || wire(session_request(session.session_id)); + + let archived = service.session_archive(request()).expect("archive"); + assert!(archived.archived); + assert_eq!(archived.event_count, session.event_count + 1); + let twice = service.session_archive(request()).expect("archive again"); + assert!(twice.archived); + assert_eq!(twice.event_count, archived.event_count, "no second event"); + assert_eq!( + tree(&service, "active", "updated", true).indexed_sessions, + 0 + ); + assert_eq!( + tree(&service, "archived", "updated", true).indexed_sessions, + 1 + ); + + let restored = service.session_restore(request()).expect("restore"); + assert!(!restored.archived); + let twice = service.session_restore(request()).expect("restore again"); + assert_eq!(twice.event_count, restored.event_count); + assert_eq!( + tree(&service, "active", "updated", true).indexed_sessions, + 1 + ); + + let missing = service + .session_archive(wire(session_request(Uuid::new_v4()))) + .expect_err("unknown session"); + assert_eq!(missing.code(), "not_found"); +} + +#[test] +fn a_corrupted_journal_is_invalid_with_a_code_and_a_placeholder_title() { + let (fixture, alpha, _) = fixture_with_workspaces(); + let (id, path) = core_session(&fixture, &alpha, "Soon broken"); + fs::write(&path, b"this is not a journal\n").expect("corrupt the journal"); + let service = service(&fixture); + let listed = tree(&service, "active", "updated", true); + let broken = listed + .groups + .iter() + .flat_map(|group| &group.sessions) + .find(|session| session.session_id == id) + .expect("the corrupt session is listed"); + assert_eq!(broken.status, SessionStatus::Invalid); + assert_eq!(broken.title, "(unreadable session)"); + let code = broken.invalid_code.as_deref().expect("an invalid code"); + assert!(code.starts_with("invalid_journal"), "{code}"); + + let error = service + .session_transcript(wire( + json!({"session_id": id, "after_seq": null, "limit": 10}), + )) + .expect_err("a corrupt journal has no transcript"); + assert_eq!(error.code(), "invalid_journal"); + let error = service + .session_archive(wire(session_request(id))) + .expect_err("a corrupt journal cannot be archived"); + assert_eq!(error.code(), "invalid_journal"); +} + +#[cfg(windows)] +#[test] +fn a_journal_held_by_another_writer_is_busy() { + let (fixture, alpha, _) = fixture_with_workspaces(); + let writer = SessionJournal::create(&fixture.data, &alpha.path, "Held elsewhere") + .expect("create and hold"); + let id = writer.snapshot().session_id; + let service = service(&fixture); + let listed = tree(&service, "active", "updated", true); + let held = &listed.groups[0].sessions[0]; + assert_eq!(held.session_id, id); + assert_eq!(held.status, SessionStatus::Busy); + assert_eq!(held.title, "(session in use)"); + + let error = service + .session_transcript(wire( + json!({"session_id": id, "after_seq": null, "limit": 10}), + )) + .expect_err("a held journal cannot be inspected on Windows"); + assert_eq!(error.code(), "busy"); + let error = service + .session_archive(wire(session_request(id))) + .expect_err("a held journal cannot be opened"); + assert_eq!(error.code(), "busy"); + drop(writer); +} + +#[test] +fn hostile_titles_and_folders_come_back_escaped() { + let fixture = Fixture::new(); + let hostile_folder = "evil\u{202e}dir"; + let workspace = fixture.workspace(hostile_folder, text_only()); + let hostile_title = "Pay \u{202e}txt.exe\u{200b} now\u{1b}[2J"; + let (id, _) = core_session(&fixture, &workspace, hostile_title); + let service = service(&fixture); + let listed = tree(&service, "active", "updated", true); + let group = &listed.groups[0]; + let session = &group.sessions[0]; + assert_eq!(session.session_id, id); + assert_eq!(session.title, display_safe_line(hostile_title)); + assert!(session.title.contains("\\u{202e}")); + for text in [&session.title, &group.folder_display] { + assert!( + text.chars() + .all(|c| !c.is_control() && !matches!(c, '\u{202e}' | '\u{200b}')), + "hidden characters must be escaped in {text:?}" + ); + } + assert!(group.folder_display.contains("\\u{202e}")); + + // The transcript page and search results are escaped the same way. + let page = transcript(&service, id, None, 10); + assert_eq!(page.session.title, session.title); + assert_eq!(page.folder_display, group.folder_display); +} + +fn transcript( + service: &DesktopService, + id: Uuid, + after: Option, + limit: u32, +) -> TranscriptPage { + service + .session_transcript(wire( + json!({"session_id": id, "after_seq": after, "limit": limit}), + )) + .expect("transcript") +} + +#[test] +fn search_maps_roles_sequence_numbers_snippets_and_the_view() { + let (fixture, alpha, beta) = fixture_with_workspaces(); + let (first, path) = core_session(&fixture, &alpha, "Orchard notes"); + { + let mut journal = SessionJournal::open(&path).expect("open"); + journal + .record_message(MessageRole::User, "tell me about the quince tree") + .expect("user"); + journal + .record_message(MessageRole::Assistant, "a quince is a fruit") + .expect("assistant"); + } + let (second, _) = core_session(&fixture, &beta, "Quince recipes"); + let service = service(&fixture); + + let search = |query: &str, view: &str, limit: u32| { + service + .session_search(wire(json!({"query": query, "view": view, "limit": limit}))) + .expect("search") + }; + let result = search("quince", "active", 50); + assert!(!result.truncated); + let mut found: Vec<(Uuid, Option, SearchRoleDto)> = result + .hits + .iter() + .map(|hit| (hit.session.session_id, hit.seq, hit.role)) + .collect(); + found.sort_by_key(|(id, seq, _)| (*id, *seq)); + let mut expected = vec![ + (first, Some(1), SearchRoleDto::User), + (first, Some(2), SearchRoleDto::Assistant), + (second, None, SearchRoleDto::Title), + ]; + expected.sort_by_key(|(id, seq, _)| (*id, *seq)); + assert_eq!(found, expected); + for hit in &result.hits { + assert!(hit.snippet.iter().any(|part| part.matched), "{hit:?}"); + let joined: String = hit.snippet.iter().map(|part| part.text.as_str()).collect(); + assert!(joined.to_lowercase().contains("quince")); + assert!(!hit.folder_display.is_empty()); + } + + // The limit clamps to at least one hit, and truncation is reported. + let clamped = search("quince", "active", 0); + assert_eq!(clamped.hits.len(), 1); + assert!(clamped.truncated); + + // The view filter: archive the first session. + service + .session_archive(wire(session_request(first))) + .expect("archive"); + assert_eq!(search("quince", "active", 50).hits.len(), 1); + assert_eq!(search("quince", "archived", 50).hits.len(), 2); + + let error = service + .session_search(wire(json!({"query": " ", "view": "active", "limit": 10}))) + .expect_err("an empty query is invalid"); + assert_eq!(error.code(), "invalid_request"); +} + +/// A journal that records every kind of event, as the core inspection test does. +fn rich_journal(fixture: &Fixture, workspace: &Workspace) -> (Uuid, PathBuf, Uuid, Uuid) { + let mut journal = + SessionJournal::create(&fixture.data, &workspace.path, "Everything").expect("create"); + let id = journal.snapshot().session_id; + let path = journal.path().to_path_buf(); + journal + .record_message(MessageRole::User, "hello") + .expect("user"); + let first = journal.start_turn().expect("turn one"); + journal + .record_manifest(first, manifest()) + .expect("manifest"); + journal + .record_tool_request( + first, + "call-1", + "workspace_read_file", + "{\"path\":\"a.txt\"}", + ) + .expect("tool request"); + let rendered = "file contents"; + journal + .record_tool_result( + first, + "call-1", + ToolOutcome::Succeeded, + None, + u64::try_from(rendered.len()).expect("size"), + &sha256_hex(rendered), + ) + .expect("tool result"); + journal + .record_tool_message("call-1", rendered) + .expect("tool message"); + journal + .record_message(MessageRole::Assistant, "done") + .expect("assistant"); + journal.complete_turn(first).expect("complete"); + journal + .record_message(MessageRole::User, "second") + .expect("second user"); + let second = journal.start_turn().expect("turn two"); + journal + .fail_turn(second, "provider_unreachable") + .expect("fail"); + let summary = "Earlier work read a file."; + journal + .record_compaction(CompactionRecord { + summary: summary.into(), + compacted_messages: 3, + includes_tool_results: true, + summary_sha256: sha256_hex(summary), + model: "fixture".into(), + prompt_tokens: Some(10), + completion_tokens: Some(4), + }) + .expect("compact"); + journal.archive().expect("archive"); + journal.restore().expect("restore"); + (id, path, first, second) +} + +#[test] +fn every_transcript_entry_kind_maps_to_its_wire_shape() { + let (fixture, alpha, _) = fixture_with_workspaces(); + let (id, _, first, second) = rich_journal(&fixture, &alpha); + let service = service(&fixture); + let page = transcript(&service, id, None, 200); + assert_eq!(page.next_after_seq, None); + assert!(!page.incomplete_tail); + assert_eq!(page.session.session_id, id); + assert_eq!(page.session.status, SessionStatus::Idle); + assert!(page.folder_display.ends_with("alpha-project")); + + let entries: Vec = page.entries.iter().map(json_of).collect(); + let kinds: Vec<&str> = entries + .iter() + .map(|entry| entry["kind"].as_str().expect("kind")) + .collect(); + assert_eq!( + kinds, + [ + "message", + "turn_started", + "request_manifest", + "tool_requested", + "tool_completed", + "message", + "message", + "turn_completed", + "message", + "turn_started", + "turn_failed", + "context_compacted", + "session_archived", + "session_restored", + ] + ); + let seqs: Vec = entries + .iter() + .map(|entry| entry["seq"].as_u64().expect("seq")) + .collect(); + assert_eq!(seqs, (1..=14).collect::>()); + + assert_eq!(entries[0]["role"], "user"); + assert_eq!(entries[0]["source"], "user_cli"); + assert_eq!(entries[0]["text"], "hello"); + assert!(entries[0]["call_id"].is_null()); + assert_eq!(entries[1]["request_id"], first.to_string()); + assert_eq!(entries[2]["model"], "local-model"); + assert_eq!(entries[2]["prompt_version"], "7"); + assert_eq!(entries[2]["tools"], json!(["workspace_read_file"])); + assert_eq!(entries[3]["tool"], "workspace_read_file"); + assert_eq!(entries[3]["arguments"], "{\"path\":\"a.txt\"}"); + assert_eq!(entries[4]["outcome"], "succeeded"); + assert!(entries[4]["code"].is_null()); + assert_eq!(entries[4]["output_bytes"], 13); + assert!(entries[4].get("output_sha256").is_none(), "digest omitted"); + assert_eq!(entries[5]["role"], "tool"); + assert_eq!(entries[5]["source"], "core_tool"); + assert_eq!(entries[5]["call_id"], "call-1"); + assert_eq!(entries[6]["role"], "assistant"); + assert_eq!(entries[6]["source"], "provider"); + assert_eq!(entries[10]["request_id"], second.to_string()); + assert_eq!(entries[10]["code"], "provider_unreachable"); + assert_eq!(entries[11]["summary"], "Earlier work read a file."); + assert_eq!(entries[11]["compacted_messages"], 3); + assert_eq!(entries[11]["model"], "fixture"); + for entry in &entries { + let stamp = entry["timestamp"].as_str().expect("timestamp"); + assert!(stamp.ends_with('Z') && stamp.contains('T'), "{stamp}"); + } +} + +#[test] +fn transcript_pages_follow_after_seq_and_limit_until_no_entries_remain() { + let (fixture, alpha, _) = fixture_with_workspaces(); + let (id, _, _, _) = rich_journal(&fixture, &alpha); + let service = service(&fixture); + + let mut seen = Vec::new(); + let mut after = None; + let mut pages = 0; + loop { + let page = transcript(&service, id, after, 5); + assert!(page.entries.len() <= 5); + seen.extend(page.entries.iter().map(|entry| entry.seq)); + pages += 1; + match page.next_after_seq { + Some(next) => { + assert_eq!(Some(next), page.entries.last().map(|entry| entry.seq)); + after = Some(next); + } + None => break, + } + assert!(pages < 10, "paging must terminate"); + } + assert_eq!(seen, (1..=14).collect::>()); + assert_eq!(pages, 3); + + // An exact fit has no next page; a limit of zero clamps to one entry. + assert_eq!(transcript(&service, id, Some(9), 5).next_after_seq, None); + let one = transcript(&service, id, None, 0); + assert_eq!(one.entries.len(), 1); + assert_eq!(one.next_after_seq, Some(1)); + // Past the end there is nothing. + let none = transcript(&service, id, Some(14), 5); + assert!(none.entries.is_empty() && none.next_after_seq.is_none()); +} + +#[test] +fn a_transcript_page_holds_at_most_one_mebibyte_of_text() { + let (fixture, alpha, _) = fixture_with_workspaces(); + let (id, path) = core_session(&fixture, &alpha, "Heavy"); + let chunk = "x".repeat(16_000); + { + let mut journal = SessionJournal::open(&path).expect("open"); + for _ in 0..80 { + journal + .record_message(MessageRole::User, &chunk) + .expect("message"); + } + } + let service = service(&fixture); + let page = transcript(&service, id, None, 200); + // 65 entries of 16,000 bytes fit in 1 MiB; a 66th would exceed it. + assert_eq!(page.entries.len(), 65); + assert_eq!(page.next_after_seq, Some(65)); + let rest = transcript(&service, id, page.next_after_seq, 200); + assert_eq!(rest.entries.len(), 15); + assert_eq!(rest.next_after_seq, None); +} + +#[test] +fn an_incomplete_tail_is_reported_and_an_unknown_session_is_not_found() { + let (fixture, alpha, _) = fixture_with_workspaces(); + let (id, path) = core_session(&fixture, &alpha, "Mid-append"); + OpenOptions::new() + .append(true) + .open(&path) + .expect("open for append") + .write_all(b"{\"partial") + .expect("partial record"); + let service = service(&fixture); + let page = transcript(&service, id, None, 10); + assert!(page.incomplete_tail); + + let missing = service + .session_transcript(wire( + json!({"session_id": Uuid::new_v4(), "after_seq": null, "limit": 10}), + )) + .expect_err("unknown session"); + assert_eq!(missing.code(), "not_found"); +} + +#[test] +fn a_session_the_index_has_not_seen_is_found_after_one_refresh() { + let (fixture, alpha, _) = fixture_with_workspaces(); + let service = service(&fixture); + // Warm the index, then add a journal behind its back. + tree(&service, "active", "updated", true); + let (id, _) = core_session(&fixture, &alpha, "Late arrival"); + let page = transcript(&service, id, None, 10); + assert_eq!(page.session.title, "Late arrival"); +} + +#[test] +fn workspace_listing_reports_the_store_state_and_permissions() { + let bare = Fixture::bare(); + let service = service(&bare); + let empty = service.workspace_list().expect("workspace list"); + assert!(!empty.development_root_set); + assert!(empty.workspaces.is_empty()); + let error = service + .session_create(wire(json!({"workspace_id": Uuid::new_v4(), "title": "t"}))) + .expect_err("no store, no workspace"); + assert_eq!(error.code(), "unknown_workspace"); + + let fixture = Fixture::new(); + let service = fixture.service(NO_ENDPOINT); + let rooted = service.workspace_list().expect("workspace list"); + assert!(rooted.development_root_set); + assert!(rooted.workspaces.is_empty()); + + let tools = fixture.workspace("tools-on", read_tools()); + let plain = fixture.workspace("plain", text_only()); + let listed = service.workspace_list().expect("workspace list"); + assert_eq!(listed.workspaces.len(), 2); + let find = |id: Uuid| { + listed + .workspaces + .iter() + .find(|choice| choice.workspace_id == id) + .expect("registered workspace") + }; + let tools_on = find(tools.id); + assert!(tools_on.folder_display.ends_with("tools-on")); + assert!(tools_on.model_tools && tools_on.read && !tools_on.write && !tools_on.execute); + let plain_off = find(plain.id); + assert!(!plain_off.model_tools && !plain_off.read && !plain_off.write && !plain_off.execute); +} + +#[test] +fn creating_a_session_uses_a_registered_workspace_and_core_validates_the_title() { + let fixture = Fixture::new(); + let workspace = fixture.workspace("created-here", text_only()); + let service = service(&fixture); + + let summary = service + .session_create(wire( + json!({"workspace_id": workspace.id, "title": "Fresh \u{202e}title"}), + )) + .expect("create"); + assert_eq!(summary.status, SessionStatus::Idle); + assert!(!summary.archived); + assert_eq!(summary.event_count, 1); + assert_eq!(summary.title, display_safe_line("Fresh \u{202e}title")); + assert!(summary.created_at.is_some() && summary.updated_at.is_some()); + + let listed = tree(&service, "active", "updated", true); + assert_eq!(listed.groups.len(), 1); + assert_eq!(listed.groups[0].sessions[0].session_id, summary.session_id); + assert!(listed.groups[0].folder_display.ends_with("created-here")); + + let unknown = service + .session_create(wire(json!({"workspace_id": Uuid::new_v4(), "title": "t"}))) + .expect_err("unregistered workspace"); + assert_eq!(unknown.code(), "unknown_workspace"); + let empty = service + .session_create(wire(json!({"workspace_id": workspace.id, "title": " "}))) + .expect_err("a blank title"); + assert_eq!(empty.code(), "invalid_request"); + assert_eq!( + tree(&service, "active", "updated", true).indexed_sessions, + 1, + "a refused create leaves no session" + ); +} + +#[test] +fn a_service_opens_on_a_new_data_root_and_lists_nothing() { + let fixture = Fixture::bare(); + let service = DesktopService::open_with_token_source( + omgcode_app::desktop::DesktopConfig { + data_root: fixture.data.join("not-yet-created"), + endpoint: NO_ENDPOINT.to_owned(), + }, + no_token, + ) + .expect("open on a missing directory"); + let empty = tree(&service, "active", "updated", true); + assert!(empty.groups.is_empty()); + assert_eq!(empty.indexed_sessions, 0); +} diff --git a/crates/omgcode-app/tests/desktop_wire.rs b/crates/omgcode-app/tests/desktop_wire.rs new file mode 100644 index 0000000..f9d6bc1 --- /dev/null +++ b/crates/omgcode-app/tests/desktop_wire.rs @@ -0,0 +1,945 @@ +//! The wire contract of the desktop service: exact JSON keys and types of every +//! response, the closed request shapes, and agreement with the TypeScript +//! declarations in `crates/omgcode-desktop/ui/src/ipc/types.ts`. + +use std::collections::BTreeSet; +use std::fs; + +use omgcode_app::desktop::{ + ApprovalDecideRequest, ApprovalDetail, ApprovalField, ApprovalList, ApprovalOperationDto, + ApprovalRequest, ApprovalStateDto, ApprovalView, ApprovalsSummary, Binding, ChatOutcome, + ChatSendRequest, ChatSettingsDto, ChatState, ChatStatus, ContextMeterDto, Decision, + DesktopError, EntryKind, MessageRoleDto, SearchHit, SearchRequest, SearchResult, SearchRoleDto, + SessionCreateRequest, SessionRequest, SessionStatus, SessionSummary, SessionTree, SnippetPart, + ToolOutcomeDto, ToolsMode, TranscriptEntry, TranscriptPage, TranscriptRequest, TreeRequest, + TreeSort, TreeView, WorkspaceChoice, WorkspaceGroup, WorkspaceList, +}; +use serde_json::{Value, json}; +use uuid::Uuid; + +mod common; +use common::{json_of, text_of, wire}; + +const TYPES_TS: &str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../omgcode-desktop/ui/src/ipc/types.ts" +); +const CLIENT_TS: &str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../omgcode-desktop/ui/src/ipc/client.ts" +); +const APPROVALS_CLIENT_TS: &str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../omgcode-desktop/ui/src/ipc/approvals_client.ts" +); + +/// Assert that `value` is an object with exactly these keys and JSON kinds. +/// A kind is `string`, `number`, `bool`, `array`, `object`, or one of those +/// followed by `|null`. +fn assert_shape(value: &Value, expected: &[(&str, &str)]) { + let object = value.as_object().expect("a JSON object"); + let actual: BTreeSet<&str> = object.keys().map(String::as_str).collect(); + let wanted: BTreeSet<&str> = expected.iter().map(|(key, _)| *key).collect(); + assert_eq!(actual, wanted, "exact key set of {value}"); + for (key, kind) in expected { + let field = &object[*key]; + let (base, nullable) = kind + .strip_suffix("|null") + .map_or((*kind, false), |base| (base, true)); + let matches = match base { + "string" => field.is_string(), + "number" => field.is_u64() || field.is_i64(), + "bool" => field.is_boolean(), + "array" => field.is_array(), + "object" => field.is_object(), + other => panic!("unknown kind {other}"), + }; + assert!( + matches || (nullable && field.is_null()), + "{key} must be {kind}, got {field}" + ); + } +} + +fn id() -> Uuid { + Uuid::new_v4() +} + +fn summary(created: Option<&str>, invalid: Option<&str>) -> SessionSummary { + SessionSummary { + session_id: id(), + title: "Title".to_owned(), + created_at: created.map(str::to_owned), + updated_at: created.map(str::to_owned), + status: SessionStatus::Idle, + archived: false, + event_count: 3, + invalid_code: invalid.map(str::to_owned), + } +} + +const SUMMARY_SHAPE: &[(&str, &str)] = &[ + ("session_id", "string"), + ("title", "string"), + ("created_at", "string|null"), + ("updated_at", "string|null"), + ("status", "string"), + ("archived", "bool"), + ("event_count", "number"), + ("invalid_code", "string|null"), +]; + +fn approval_view(with_labels: bool) -> ApprovalView { + ApprovalView { + id: id(), + session_id: id(), + session_title: with_labels.then(|| "Session".to_owned()), + folder_display: with_labels.then(|| "/work".to_owned()), + operation: ApprovalOperationDto::FileWrite, + summary: "edit".to_owned(), + state: ApprovalStateDto::Pending, + created_unix: 1, + expires_unix: 2, + request_sha256: "ab".repeat(32), + writers_stopped: false, + } +} + +const APPROVAL_VIEW_SHAPE: &[(&str, &str)] = &[ + ("id", "string"), + ("session_id", "string"), + ("session_title", "string|null"), + ("folder_display", "string|null"), + ("operation", "string"), + ("summary", "string"), + ("state", "string"), + ("created_unix", "number"), + ("expires_unix", "number"), + ("request_sha256", "string"), + ("writers_stopped", "bool"), +]; + +fn outcome() -> ChatOutcome { + ChatOutcome { + finish_reason: "stop".to_owned(), + tools_mode: ToolsMode::Disabled, + tools_disabled_reason: Some("reason".to_owned()), + rounds: 0, + tool_calls: 0, + withheld_tool_results: 0, + context: Some(ContextMeterDto { + estimated_tokens: 1, + trigger_tokens: 2, + context_tokens: 3, + compacted: false, + }), + } +} + +#[test] +fn session_summaries_have_exactly_the_declared_keys_and_nullability() { + assert_shape( + &json_of(&summary(Some("2026-01-01T00:00:00Z"), None)), + SUMMARY_SHAPE, + ); + let bare = json_of(&summary(None, Some("invalid_header"))); + assert_shape(&bare, SUMMARY_SHAPE); + assert!(bare["created_at"].is_null() && bare["invalid_code"].is_string()); +} + +#[test] +fn the_tree_search_and_transcript_responses_have_exactly_the_declared_keys() { + let group = WorkspaceGroup { + group_id: "0123456789abcdef".to_owned(), + folder_display: "/work".to_owned(), + sessions: vec![summary(None, None)], + }; + let tree = SessionTree { + groups: vec![group], + indexed_sessions: 1, + skipped_entries: 0, + }; + let tree = json_of(&tree); + assert_shape( + &tree, + &[ + ("groups", "array"), + ("indexed_sessions", "number"), + ("skipped_entries", "number"), + ], + ); + assert_shape( + &tree["groups"][0], + &[ + ("group_id", "string"), + ("folder_display", "string"), + ("sessions", "array"), + ], + ); + + let hit = |seq: Option| SearchHit { + session: summary(None, None), + folder_display: "/work".to_owned(), + seq, + role: SearchRoleDto::Summary, + snippet: vec![SnippetPart { + text: "x".to_owned(), + matched: true, + }], + }; + let result = json_of(&SearchResult { + hits: vec![hit(Some(4)), hit(None)], + truncated: false, + }); + assert_shape(&result, &[("hits", "array"), ("truncated", "bool")]); + for (index, kind) in [(0, "number"), (1, "number|null")] { + assert_shape( + &result["hits"][index], + &[ + ("session", "object"), + ("folder_display", "string"), + ("seq", kind), + ("role", "string"), + ("snippet", "array"), + ], + ); + } + assert_shape( + &result["hits"][0]["snippet"][0], + &[("text", "string"), ("matched", "bool")], + ); + + let page = json_of(&TranscriptPage { + session: summary(None, None), + folder_display: "/work".to_owned(), + entries: Vec::new(), + next_after_seq: None, + incomplete_tail: false, + }); + assert_shape( + &page, + &[ + ("session", "object"), + ("folder_display", "string"), + ("entries", "array"), + ("next_after_seq", "number|null"), + ("incomplete_tail", "bool"), + ], + ); +} + +#[test] +fn chat_responses_have_exactly_the_declared_keys() { + let completed = json_of(&ChatStatus { + session_id: id(), + state: ChatState::Completed, + outcome: Some(outcome()), + error: None, + }); + assert_shape( + &completed, + &[ + ("session_id", "string"), + ("state", "string"), + ("outcome", "object|null"), + ("error", "object|null"), + ], + ); + assert_shape( + &completed["outcome"], + &[ + ("finish_reason", "string"), + ("tools_mode", "string"), + ("tools_disabled_reason", "string|null"), + ("rounds", "number"), + ("tool_calls", "number"), + ("withheld_tool_results", "number"), + ("context", "object|null"), + ], + ); + assert_shape( + &completed["outcome"]["context"], + &[ + ("estimated_tokens", "number"), + ("trigger_tokens", "number"), + ("context_tokens", "number"), + ("compacted", "bool"), + ], + ); + assert!(completed["error"].is_null()); + + // A failed status carries the error shape and no outcome. + let failed = ChatStatus { + session_id: id(), + state: ChatState::Failed, + outcome: None, + error: Some(error_value()), + }; + let failed = json_of(&failed); + assert!(failed["outcome"].is_null()); + assert_shape( + &failed["error"], + &[("code", "string"), ("message", "string")], + ); +} + +/// A `DesktopError` as the service produces it, without a public constructor: +/// a request the service refuses without touching storage. +fn error_value() -> DesktopError { + let directory = tempfile::tempdir().expect("data root"); + let service = omgcode_app::desktop::DesktopService::open_with_token_source( + omgcode_app::desktop::DesktopConfig { + data_root: directory.path().to_owned(), + endpoint: "http://127.0.0.1:1/v1".to_owned(), + }, + common::no_token, + ) + .expect("service"); + service + .chat_send(wire::(json!({ + "session_id": id(), + "message": " ", + "settings": common::settings_json("http://127.0.0.1:1/v1"), + }))) + .expect_err("an empty message is refused") +} + +#[test] +fn a_desktop_error_serializes_as_exactly_code_and_message() { + let error = error_value(); + let value = json_of(&error); + assert_shape(&value, &[("code", "string"), ("message", "string")]); + assert_eq!(value["code"], "invalid_request"); + assert_eq!(error.code(), "invalid_request"); +} + +#[test] +fn workspace_and_approval_responses_have_exactly_the_declared_keys() { + let list = json_of(&WorkspaceList { + development_root_set: true, + workspaces: vec![WorkspaceChoice { + workspace_id: id(), + folder_display: "/work".to_owned(), + model_tools: true, + read: true, + write: false, + execute: false, + }], + }); + assert_shape( + &list, + &[("development_root_set", "bool"), ("workspaces", "array")], + ); + assert_shape( + &list["workspaces"][0], + &[ + ("workspace_id", "string"), + ("folder_display", "string"), + ("model_tools", "bool"), + ("read", "bool"), + ("write", "bool"), + ("execute", "bool"), + ], + ); + assert_shape( + &json_of(&ApprovalsSummary { pending: 2 }), + &[("pending", "number")], + ); + + assert_shape(&json_of(&approval_view(true)), APPROVAL_VIEW_SHAPE); + let unlabelled = json_of(&approval_view(false)); + assert_shape(&unlabelled, APPROVAL_VIEW_SHAPE); + assert!(unlabelled["session_title"].is_null() && unlabelled["folder_display"].is_null()); + + let approvals = json_of(&ApprovalList { + now_unix: 9, + approvals: vec![approval_view(true)], + }); + assert_shape( + &approvals, + &[("now_unix", "number"), ("approvals", "array")], + ); + + let detail = |binding, token: Option<&str>| ApprovalDetail { + approval: approval_view(true), + binding, + tool: token.map(|_| "workspace_edit_file".to_owned()), + fields: vec![ApprovalField { + label: "File".to_owned(), + value: "a".to_owned(), + multiline: false, + }], + review_token: token.map(str::to_owned), + }; + for (value, tool_kind) in [ + (detail(Binding::Exact, Some("token")), "string"), + (detail(Binding::Stale, None), "string|null"), + ] { + let value = json_of(&value); + assert_shape( + &value, + &[ + ("approval", "object"), + ("binding", "string"), + ("tool", tool_kind), + ("fields", "array"), + ("review_token", "string|null"), + ], + ); + assert_shape( + &value["fields"][0], + &[ + ("label", "string"), + ("value", "string"), + ("multiline", "bool"), + ], + ); + } +} + +#[test] +fn every_transcript_entry_kind_has_exactly_its_declared_keys() { + let request = id(); + let entries = [ + ( + EntryKind::Message { + role: MessageRoleDto::Tool, + source: "core_tool".to_owned(), + text: "t".to_owned(), + call_id: None, + }, + "message", + vec![ + ("role", "string"), + ("source", "string"), + ("text", "string"), + ("call_id", "string|null"), + ], + ), + ( + EntryKind::TurnStarted { + request_id: request, + }, + "turn_started", + vec![("request_id", "string")], + ), + ( + EntryKind::TurnCompleted { + request_id: request, + }, + "turn_completed", + vec![("request_id", "string")], + ), + ( + EntryKind::TurnFailed { + request_id: request, + code: Some("c".to_owned()), + }, + "turn_failed", + vec![("request_id", "string"), ("code", "string|null")], + ), + ( + EntryKind::ToolRequested { + request_id: request, + call_id: "c".to_owned(), + tool: "t".to_owned(), + arguments: "{}".to_owned(), + }, + "tool_requested", + vec![ + ("request_id", "string"), + ("call_id", "string"), + ("tool", "string"), + ("arguments", "string"), + ], + ), + ( + EntryKind::ToolCompleted { + request_id: request, + call_id: "c".to_owned(), + outcome: ToolOutcomeDto::Denied, + code: None, + output_bytes: 4, + }, + "tool_completed", + vec![ + ("request_id", "string"), + ("call_id", "string"), + ("outcome", "string"), + ("code", "string|null"), + ("output_bytes", "number"), + ], + ), + ( + EntryKind::RequestManifest { + request_id: request, + model: "m".to_owned(), + prompt_version: "v".to_owned(), + tools: vec!["a".to_owned()], + }, + "request_manifest", + vec![ + ("request_id", "string"), + ("model", "string"), + ("prompt_version", "string"), + ("tools", "array"), + ], + ), + ( + EntryKind::ContextCompacted { + summary: "s".to_owned(), + compacted_messages: 2, + model: "m".to_owned(), + }, + "context_compacted", + vec![ + ("summary", "string"), + ("compacted_messages", "number"), + ("model", "string"), + ], + ), + (EntryKind::SessionArchived, "session_archived", Vec::new()), + (EntryKind::SessionRestored, "session_restored", Vec::new()), + ]; + let ts = fs::read_to_string(TYPES_TS).expect("types.ts"); + for (kind, name, fields) in entries { + let value = json_of(&TranscriptEntry { + seq: 3, + timestamp: "2026-01-01T00:00:00Z".to_owned(), + kind, + }); + let mut expected = vec![ + ("seq", "number"), + ("timestamp", "string"), + ("kind", "string"), + ]; + expected.extend(fields); + assert_shape(&value, &expected); + assert_eq!(value["kind"], name); + // The TypeScript variant declares the same fields. + let declared = variant_fields(&ts, name); + let serialized: BTreeSet = + value.as_object().expect("object").keys().cloned().collect(); + assert_eq!(declared, serialized, "TypeScript variant {name}"); + } +} + +/// The field names that `types.ts` declares for the transcript variant `kind`, +/// including the shared `seq` and `timestamp`. +fn variant_fields(ts: &str, kind: &str) -> BTreeSet { + let marker = format!("kind: \"{kind}\""); + let at = ts.find(&marker).unwrap_or_else(|| panic!("variant {kind}")); + let start = ts[..at].rfind('{').expect("opening brace"); + let end = at + ts[at..].find('}').expect("closing brace"); + let mut names: BTreeSet = declared_names(&ts[start + 1..end]); + names.insert("seq".to_owned()); + names.insert("timestamp".to_owned()); + names +} + +/// Names before a colon in a `;`, `,`, or newline separated field list. +fn declared_names(body: &str) -> BTreeSet { + body.split([';', ',', '\n']) + .filter_map(|piece| { + let (name, _) = piece.trim().split_once(':')?; + let name = name.trim().trim_end_matches('?'); + (!name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')) + .then(|| name.to_owned()) + }) + .collect() +} + +/// The field names of `export interface `. +fn interface_fields(ts: &str, name: &str) -> BTreeSet { + let header = format!("export interface {name} {{"); + let start = ts + .find(&header) + .unwrap_or_else(|| panic!("interface {name}")); + let body = &ts[start + header.len()..]; + let end = body.find("\n}").expect("end of interface"); + declared_names(&body[..end]) +} + +fn keys_of(value: &Value) -> BTreeSet { + value.as_object().expect("object").keys().cloned().collect() +} + +#[test] +fn every_serialized_interface_has_exactly_the_fields_types_ts_declares() { + let ts = fs::read_to_string(TYPES_TS).expect("types.ts"); + let error = json_of(&error_value()); + let tree = json_of(&SessionTree { + groups: vec![WorkspaceGroup { + group_id: "g".to_owned(), + folder_display: "f".to_owned(), + sessions: vec![summary(None, None)], + }], + indexed_sessions: 0, + skipped_entries: 0, + }); + let hit = json_of(&SearchHit { + session: summary(None, None), + folder_display: "f".to_owned(), + seq: None, + role: SearchRoleDto::Title, + snippet: vec![SnippetPart { + text: "t".to_owned(), + matched: false, + }], + }); + let page = json_of(&TranscriptPage { + session: summary(None, None), + folder_display: "f".to_owned(), + entries: Vec::new(), + next_after_seq: None, + incomplete_tail: false, + }); + let status = json_of(&ChatStatus { + session_id: id(), + state: ChatState::Idle, + outcome: Some(outcome()), + error: None, + }); + let settings = json_of(&ChatSettingsDto { + endpoint: "e".to_owned(), + model: "m".to_owned(), + context_tokens: 1, + max_output_tokens: 1, + instructions: String::new(), + compact_threshold: 1, + auto_compact: false, + }); + let workspaces = json_of(&WorkspaceList { + development_root_set: false, + workspaces: vec![WorkspaceChoice { + workspace_id: id(), + folder_display: "f".to_owned(), + model_tools: false, + read: false, + write: false, + execute: false, + }], + }); + let detail = json_of(&ApprovalDetail { + approval: approval_view(false), + binding: Binding::NotFound, + tool: None, + fields: vec![ApprovalField { + label: "l".to_owned(), + value: "v".to_owned(), + multiline: true, + }], + review_token: None, + }); + let list = json_of(&ApprovalList { + now_unix: 1, + approvals: vec![approval_view(false)], + }); + let checks: Vec<(&str, BTreeSet)> = vec![ + ("IpcError", keys_of(&error)), + ("SessionSummary", keys_of(&tree["groups"][0]["sessions"][0])), + ("WorkspaceGroup", keys_of(&tree["groups"][0])), + ("SessionTree", keys_of(&tree)), + ("SnippetPart", keys_of(&hit["snippet"][0])), + ("SearchHit", keys_of(&hit)), + ( + "SearchResult", + keys_of(&json_of(&SearchResult { + hits: Vec::new(), + truncated: false, + })), + ), + ("TranscriptPage", keys_of(&page)), + ("ChatSettings", keys_of(&settings)), + ("ContextMeter", keys_of(&status["outcome"]["context"])), + ("ChatOutcome", keys_of(&status["outcome"])), + ("ChatStatus", keys_of(&status)), + ("WorkspaceChoice", keys_of(&workspaces["workspaces"][0])), + ("WorkspaceList", keys_of(&workspaces)), + ("ApprovalView", keys_of(&list["approvals"][0])), + ("ApprovalList", keys_of(&list)), + ("ApprovalField", keys_of(&detail["fields"][0])), + ("ApprovalDetail", keys_of(&detail)), + ]; + for (name, serialized) in checks { + assert_eq!(interface_fields(&ts, name), serialized, "interface {name}"); + } +} + +#[test] +fn closed_unions_serialize_to_the_values_types_ts_declares() { + let ts = fs::read_to_string(TYPES_TS).expect("types.ts"); + let union = |name: &str| -> BTreeSet { + let header = format!("export type {name} = "); + let start = ts.find(&header).expect("type alias") + header.len(); + let end = start + ts[start..].find(';').expect("semicolon"); + ts[start..end] + .split('|') + .map(|part| part.trim().trim_matches('"').to_owned()) + .collect() + }; + let strings = |values: Vec| -> BTreeSet { + values + .iter() + .map(|value| value.as_str().expect("string").to_owned()) + .collect() + }; + assert_eq!( + union("SessionStatus"), + strings( + [ + SessionStatus::Idle, + SessionStatus::Running, + SessionStatus::TurnOpen, + SessionStatus::Busy, + SessionStatus::Invalid + ] + .iter() + .map(json_of) + .collect() + ) + ); + assert_eq!( + union("ApprovalState"), + strings( + [ + ApprovalStateDto::Pending, + ApprovalStateDto::Approved, + ApprovalStateDto::Denied, + ApprovalStateDto::Consumed, + ApprovalStateDto::Expired + ] + .iter() + .map(json_of) + .collect() + ) + ); + assert_eq!( + union("ApprovalOperation"), + strings( + [ + ApprovalOperationDto::Command, + ApprovalOperationDto::FileWrite, + ApprovalOperationDto::GitPush, + ApprovalOperationDto::Network + ] + .iter() + .map(json_of) + .collect() + ) + ); + assert_eq!( + union("TreeView"), + strings( + [TreeView::Active, TreeView::Archived] + .iter() + .map(json_of) + .collect() + ) + ); + assert_eq!( + union("TreeSort"), + strings( + [TreeSort::Updated, TreeSort::Created, TreeSort::Title] + .iter() + .map(json_of) + .collect() + ) + ); + let chat_states: BTreeSet = strings( + [ + ChatState::Idle, + ChatState::Running, + ChatState::Cancelling, + ChatState::Completed, + ChatState::Failed, + ] + .iter() + .map(json_of) + .collect(), + ); + assert!( + ts.contains("state: \"idle\" | \"running\" | \"cancelling\" | \"completed\" | \"failed\";") + ); + assert_eq!(chat_states.len(), 5); + assert!(ts.contains("binding: \"exact\" | \"stale\" | \"not_found\";")); + assert_eq!(json_of(&Binding::NotFound), "not_found"); + assert!(ts.contains("role: \"user\" | \"assistant\" | \"tool\" | \"summary\" | \"title\";")); + assert_eq!(json_of(&SearchRoleDto::Summary), "summary"); +} + +#[test] +fn the_summary_command_returns_the_object_the_client_declares() { + let client = fs::read_to_string(CLIENT_TS).expect("client.ts"); + assert!(client.contains("invokeCommand<{ pending: number }>(\"approvals_summary\"")); + assert_shape( + &json_of(&ApprovalsSummary { pending: 0 }), + &[("pending", "number")], + ); +} + +#[test] +fn requests_match_the_argument_objects_the_client_sends() { + let client = fs::read_to_string(CLIENT_TS).expect("client.ts"); + let approvals = fs::read_to_string(APPROVALS_CLIENT_TS).expect("approvals_client.ts"); + let session = id(); + + assert!(client.contains("\"session_tree\", { view, sort, descending }")); + let tree: TreeRequest = wire(json!({"view": "active", "sort": "updated", "descending": true})); + assert_eq!(tree.sort, TreeSort::Updated); + + assert!(client.contains("\"session_search\", { query, view, limit }")); + let search: SearchRequest = wire(json!({"query": "q", "view": "archived", "limit": 20})); + assert_eq!(search.view, TreeView::Archived); + + assert!(client.contains("session_id: sessionId,\n after_seq: afterSeq,\n limit,")); + let transcript: TranscriptRequest = + wire(json!({"session_id": session, "after_seq": null, "limit": 50})); + assert_eq!(transcript.after_seq, None); + let transcript: TranscriptRequest = + wire(json!({"session_id": session, "after_seq": 7, "limit": 50})); + assert_eq!(transcript.after_seq, Some(7)); + + assert!(client.contains("\"session_archive\", { session_id: sessionId }")); + let by_session: SessionRequest = wire(json!({"session_id": session})); + assert_eq!(by_session.session_id, session); + + assert!(client.contains("{ workspace_id: workspaceId, title }")); + let create: SessionCreateRequest = wire(json!({"workspace_id": session, "title": "t"})); + assert_eq!(create.title, "t"); + + assert!(client.contains("{ session_id: sessionId, message, settings }")); + let send: ChatSendRequest = wire(json!({ + "session_id": session, + "message": "m", + "settings": common::settings_json("http://127.0.0.1:1/v1"), + })); + assert_eq!(send.message, "m"); + + assert!(approvals.contains("\"approval_detail\", { id }")); + let detail: ApprovalRequest = wire(json!({"id": session})); + assert_eq!(detail.id, session); + + assert!( + approvals.contains("writers_stopped: writersStopped,\n review_token: reviewToken,") + ); + let decide: ApprovalDecideRequest = wire(json!({ + "id": session, + "decision": "approve", + "writers_stopped": true, + "review_token": null, + })); + assert_eq!(decide.decision, Decision::Approve); + assert_eq!(decide.review_token, None); +} + +#[test] +fn requests_reject_unknown_fields_and_wrong_values() { + let session = id(); + let reject = |result: Result, what: &str| { + assert!(result.is_err(), "{what} must be rejected"); + }; + macro_rules! parse { + ($type:ty, $value:expr) => { + serde_json::from_value::<$type>($value).map(|_| Value::Null) + }; + } + reject( + parse!( + TreeRequest, + json!({"view": "active", "sort": "updated", "descending": false, "path": "/x"}) + ), + "an extra tree field", + ); + reject( + parse!( + TreeRequest, + json!({"view": "all", "sort": "updated", "descending": false}) + ), + "a wrong view", + ); + reject( + parse!( + TreeRequest, + json!({"view": "active", "sort": "size", "descending": false}) + ), + "a wrong sort", + ); + reject( + parse!( + SearchRequest, + json!({"query": "q", "view": "active", "limit": -1}) + ), + "a negative limit", + ); + reject( + parse!(SessionRequest, json!({"session_id": "not-a-uuid"})), + "a malformed id", + ); + reject( + parse!( + SessionRequest, + json!({"session_id": session, "path": "C:\\x"}) + ), + "a path field", + ); + reject( + parse!( + SessionCreateRequest, + json!({"workspace_id": session, "title": "t", "path": "/x"}) + ), + "a path on session_create", + ); + reject( + parse!( + ApprovalDecideRequest, + json!({ + "id": session, "decision": "maybe", "writers_stopped": false, "review_token": null + }) + ), + "a wrong decision", + ); + reject( + parse!( + ApprovalDecideRequest, + json!({ + "id": session, "decision": "deny", "writers_stopped": false, "review_token": null, "extra": 1 + }) + ), + "an extra decide field", + ); + reject( + parse!( + ChatSendRequest, + json!({ + "session_id": session, "message": "m", "settings": {"endpoint": "e"} + }) + ), + "incomplete settings", + ); + let mut settings = common::settings_json("e"); + settings["secret"] = json!("x"); + reject( + parse!( + ChatSendRequest, + json!({"session_id": session, "message": "m", "settings": settings}) + ), + "an extra settings field", + ); +} + +#[test] +fn a_session_create_request_has_no_way_to_carry_a_path() { + // Compile-time: this destructuring lists every field of the request type. + let SessionCreateRequest { + workspace_id: _, + title: _, + } = wire(json!({"workspace_id": Uuid::new_v4(), "title": "t"})); +} + +#[test] +fn an_error_serializes_code_before_message() { + // The serialized form of an error is stable text with no path markers. + let text = text_of(&error_value()); + assert!(text.starts_with("{\"code\":\"invalid_request\",\"message\":")); +} diff --git a/crates/omgcode-cli/Cargo.toml b/crates/omgcode-cli/Cargo.toml index df79cd7..38fd3ba 100644 --- a/crates/omgcode-cli/Cargo.toml +++ b/crates/omgcode-cli/Cargo.toml @@ -12,9 +12,9 @@ name = "omgcode" path = "src/main.rs" [dependencies] +omgcode-app = { path = "../omgcode-app" } omgcode-core = { path = "../omgcode-core" } clap.workspace = true -directories.workspace = true serde.workspace = true serde_json.workspace = true uuid.workspace = true diff --git a/crates/omgcode-cli/src/context_cli.rs b/crates/omgcode-cli/src/context_cli.rs deleted file mode 100644 index 52c080d..0000000 --- a/crates/omgcode-cli/src/context_cli.rs +++ /dev/null @@ -1,76 +0,0 @@ -//! CLI glue for bounded conversation compaction. -//! -//! The core owns the cutoff, journal event, and summary validation. This module -//! supplies the local-model summarizer and applies the configured secret -//! redaction before the summary is recorded or shown. - -use omgcode_core::context::{ - COMPACTION_INSTRUCTIONS, CompactionLimits, CompactionOutcome, ContextBudget, ContextError, - MAX_SUMMARY_BYTES, SummaryReply, compact, -}; -use omgcode_core::prompt::{self, ConversationMessage}; -use omgcode_core::provider::LocalModelClient; -use omgcode_core::session::SessionJournal; -use std::path::Path; - -use crate::{CliError, model_tools, redact_known_secret}; - -/// Most output tokens reserved for one summary request. -const MAX_SUMMARY_OUTPUT_TOKENS: u64 = 2048; - -/// Output reserve for an automatic summary request: a quarter of the context, -/// at most 2048 tokens and at least one. -pub(crate) fn summary_output_tokens(context_tokens: u64) -> u32 { - u32::try_from((context_tokens / 4).clamp(1, MAX_SUMMARY_OUTPUT_TOKENS)).unwrap_or(1) -} - -/// Compact the active context with the selected local model. -/// -/// `summary_budget` sizes the summarizer chunks; its `max_output_tokens` must -/// be the summary client's output reserve. Live `model_tools` and `read` -/// settings for the session's workspace are read before the summarizer input -/// is built and again before each request that carries tool-derived content; -/// a withdrawal stops compaction with a `permission` error and records nothing. -pub(crate) fn compact_journal( - journal: &mut SessionJournal, - data_root: &Path, - client: &LocalModelClient, - token: Option<&str>, - summary_budget: ContextBudget, -) -> Result { - let model = client.model().to_owned(); - let workspace = journal.snapshot().workspace_id; - let schema_version = journal.schema_version(); - compact( - journal, - CompactionLimits { - max_chunk_bytes: summary_budget.summarizer_chunk_bytes(), - max_summary_bytes: MAX_SUMMARY_BYTES, - }, - model, - // Unreadable settings fail closed: no tool data reaches the summarizer. - || model_tools::tool_replay_allowed(data_root, workspace, schema_version).unwrap_or(false), - |history: &[ConversationMessage]| { - let redacted: Vec = history - .iter() - .map(|message| ConversationMessage { - role: message.role, - content: redact_known_secret(&message.content, token), - }) - .collect(); - let messages = prompt::assemble(COMPACTION_INSTRUCTIONS, &redacted) - .map_err(|_| ContextError::TooLarge)?; - let reply = client.complete(&messages).map_err(ContextError::Provider)?; - let usage = reply.usage.as_ref(); - Ok(SummaryReply { - text: redact_known_secret(&reply.content, token), - prompt_tokens: usage.and_then(|usage| usage.prompt_tokens), - completion_tokens: usage.and_then(|usage| usage.completion_tokens), - }) - }, - ) - .map_err(|error| match error { - ContextError::AuthorityWithdrawn => CliError::new("permission", error.to_string()), - error => CliError::new("context", error.to_string()), - }) -} diff --git a/crates/omgcode-cli/src/main.rs b/crates/omgcode-cli/src/main.rs index 6c2e643..e81fc15 100644 --- a/crates/omgcode-cli/src/main.rs +++ b/crates/omgcode-cli/src/main.rs @@ -2,31 +2,24 @@ #![forbid(unsafe_code)] mod approvals_cli; -mod context_cli; mod control_cli; mod credential_cli; mod file_cli; -mod model_tools; mod packages_cli; mod run_cli; use clap::{Args, Parser, Subcommand}; -use directories::ProjectDirs; -use omgcode_core::context::{ - ContextBudget, DEFAULT_COMPACT_THRESHOLD, estimate_history_input_tokens, -}; -use omgcode_core::control::ControlStore; -use omgcode_core::prompt::{ - self, BASE_PROMPT, BASE_PROMPT_VERSION, ConversationMessage, ConversationRole, PromptError, +use omgcode_app::{ + AppError, ChatClients, ChatHooks, ChatSettings, ChatTurnInput, MODEL_TOOLS_SUPPORTED, + compact_journal, create_session, data_root, read_lm_token, redact_known_secret, + run_chat_turn_with_clients, }; +use omgcode_core::context::{ContextBudget, DEFAULT_COMPACT_THRESHOLD}; +use omgcode_core::prompt::{self, BASE_PROMPT, BASE_PROMPT_VERSION}; use omgcode_core::provider::{LocalModelClient, LocalModelConfig}; -use omgcode_core::session::{ - MessageRole, NativePath, RequestManifest, SessionError, SessionJournal, -}; -use omgcode_core::turn::replay_active; +use omgcode_core::session::{NativePath, SessionJournal}; use serde::Serialize; use serde_json::json; -use std::env; use std::io::{self, Write}; use std::path::PathBuf; use std::process::ExitCode; @@ -195,27 +188,10 @@ struct JournalOutput { detail: T, } -/// Visible, conservative context accounting for one chat turn. -#[derive(Clone, Serialize)] -pub(crate) struct ContextMeter { - estimated_input_tokens: u64, - context_tokens: u64, - max_output_tokens: u32, - effective_trigger: u64, - auto_compaction: bool, - estimate_scope: &'static str, - #[serde(skip_serializing_if = "Option::is_none")] - compaction: Option, -} - -/// The active compaction boundary and summary identity. -#[derive(Clone, Serialize)] -struct CompactionMeter { - compacted_messages: u64, - retained_messages: u64, - #[serde(skip_serializing_if = "Option::is_none")] - summarizer_calls: Option, - summary_sha256: String, +impl From for CliError { + fn from(error: AppError) -> Self { + Self::new(error.code(), error.into_message()) + } } impl CliError { @@ -283,7 +259,7 @@ fn run(cli: Cli) -> Result<(), CliError> { "checkpoint_restore": cfg!(any(target_os = "linux", target_os = "windows")), "checkpoint_deletion": cfg!(any(target_os = "linux", target_os = "windows")), "edit_previews": cfg!(any(target_os = "linux", target_os = "windows")), - "model_read_list_tools": model_tools::MODEL_TOOLS_SUPPORTED, + "model_read_list_tools": MODEL_TOOLS_SUPPORTED, "model_command_tool": "approval_required", "model_write_tools": "approval_required", "workspace_container_grants": omgcode_core::control::CONTAINER_GRANTS_SUPPORTED, @@ -382,31 +358,17 @@ fn run(cli: Cli) -> Result<(), CliError> { /// Validate the provider before opening storage, then attach recovery information. fn chat(data_dir: Option, mut args: ChatArgs) -> Result<(), CliError> { let token = read_lm_token()?; - let client = LocalModelClient::new( - LocalModelConfig { - base_url: args.endpoint.clone(), - model: args.model.clone(), - context_tokens: args.context_tokens, - max_output_tokens: args.max_output_tokens, - }, - // CLI retains one copy for text redaction; the client owns its header. - token.clone(), - ) - .map_err(provider_error)?; - let summary_tokens = context_cli::summary_output_tokens(args.context_tokens); - let summary_client = LocalModelClient::new( - LocalModelConfig { - base_url: args.endpoint.clone(), - model: args.model.clone(), - context_tokens: args.context_tokens, - max_output_tokens: summary_tokens, - }, - token.clone(), - ) - .map_err(provider_error)?; - args.title = redact_known_secret(&args.title, token.as_deref()); - args.message = redact_known_secret(&args.message, token.as_deref()); - args.instructions = redact_known_secret(&args.instructions, token.as_deref()); + let settings = ChatSettings { + endpoint: args.endpoint, + model: args.model, + context_tokens: args.context_tokens, + max_output_tokens: args.max_output_tokens, + instructions: args.instructions, + compact_threshold: args.compact_threshold, + auto_compact: args.auto_compact, + }; + let clients = ChatClients::new(&settings, token.as_deref())?; + let title = redact_known_secret(&args.title, token.as_deref()); let path = if args.journal.is_some() || args.journal_native.is_some() { Some(resolve_journal( args.journal.take(), @@ -422,178 +384,31 @@ fn chat(data_dir: Option, mut args: ChatArgs) -> Result<(), CliError> { let workspace = args.workspace.as_deref().ok_or_else(|| { CliError::new("configuration", "A workspace or journal is required") })?; - create_session(&data_root, workspace, &args.title)? + create_session(&data_root, workspace, &title)? } }; let locator = journal_locator(&journal)?; - chat_turn( + let input = ChatTurnInput { + message: &args.message, + settings: &settings, + token: token.as_deref(), + }; + // Every post-open failure, including output failures, carries the locator. + let result = run_chat_turn_with_clients( &mut journal, &data_root, - &client, - &summary_client, - args, - token.as_deref(), + &input, + &clients, + &mut ChatHooks::default(), ) - .map_err(|error| error.with_session(locator)) -} - -/// Apply the context trigger before a turn and return the visible meter. -fn preflight_context( - journal: &mut SessionJournal, - data_root: &std::path::Path, - args: &ChatArgs, - summary_client: &LocalModelClient, - token: Option<&str>, - fixed_extra_bytes: usize, - tools_enabled: bool, -) -> Result { - if args.compact_threshold == 0 { - return Err(CliError::new( - "configuration", - "The compaction threshold must be a positive token count", - )); - } - let budget = ContextBudget { - threshold: args.compact_threshold, - context_tokens: args.context_tokens, - max_output_tokens: args.max_output_tokens, - }; - // Summary chunks are sized from the summary request's own output reserve. - let summary_budget = ContextBudget { - threshold: u64::MAX, - context_tokens: args.context_tokens, - max_output_tokens: context_cli::summary_output_tokens(args.context_tokens), - }; - let (mut estimate, mut assembly_blocked) = estimate_with_user( - journal, - args, - fixed_extra_bytes, - replay_allowed_now(journal, data_root, tools_enabled), - )?; - let mut summarizer_calls = None; - if budget.should_compact(estimate) || assembly_blocked { - if !args.auto_compact { - let reason = if assembly_blocked { - "Active history exceeds the prompt assembly limits".to_owned() - } else { - format!( - "The conservative input estimate ({estimate} tokens) reaches the compaction trigger ({})", - budget.trigger() - ) - }; - return Err(CliError::new( - "context", - format!("{reason}. Use session compact or rerun chat with --auto-compact."), - )); - } - let outcome = context_cli::compact_journal( - journal, - data_root, - summary_client, - token, - summary_budget, - )?; - summarizer_calls = Some(outcome.calls); - // Settings can change during the summarizer requests, so read the - // replay authority again for the compacted history. - (estimate, assembly_blocked) = estimate_with_user( - journal, - args, - fixed_extra_bytes, - replay_allowed_now(journal, data_root, tools_enabled), - )?; - if budget.should_compact(estimate) || assembly_blocked { - return Err(CliError::new( - "context", - "Compaction did not reduce the context below the trigger and assembly limits", - )); - } - } - Ok(context_meter( - journal, - args, - budget, - estimate, - summarizer_calls, - )) -} - -/// Whether the next request may replay saved tool results, read from live -/// settings at each call. Text-only chat never replays them; a tool turn -/// replays them only under live `model_tools` and `read`, as the runtime -/// does. Unreadable settings fail closed to the withheld form. -fn replay_allowed_now( - journal: &SessionJournal, - data_root: &std::path::Path, - tools_enabled: bool, -) -> bool { - tools_enabled - && model_tools::tool_replay_allowed( - data_root, - journal.snapshot().workspace_id, - journal.schema_version(), - ) - .unwrap_or(false) -} - -/// The input-only estimate for the next request, and whether its active -/// history plus the pending user message exceeds a prompt-assembly limit that -/// compaction can relieve (message count or total assembled bytes). -fn estimate_with_user( - journal: &SessionJournal, - args: &ChatArgs, - fixed_extra_bytes: usize, - tool_results_allowed: bool, -) -> Result<(u64, bool), CliError> { - // Estimate the history this mode will send: saved tool results, and a - // summary built from them, are withheld without live tool authority. - let (mut history, _) = replay_active(journal, tool_results_allowed); - history.push(ConversationMessage { - role: ConversationRole::User, - content: args.message.clone(), + .map_err(CliError::from) + .and_then(|output| { + print_json(&JournalOutput { + locator: journal_locator(&journal)?, + detail: output, + }) }); - let estimate = estimate_history_input_tokens( - BASE_PROMPT.len(), - &args.instructions, - &history, - fixed_extra_bytes, - ) - .map_err(|error| CliError::new("context", error.to_string()))?; - let assembly_blocked = matches!( - prompt::assemble(&args.instructions, &history), - Err(PromptError::TooManyHistoryMessages | PromptError::AssembledPromptTooLarge) - ); - Ok((estimate, assembly_blocked)) -} - -fn context_meter( - journal: &SessionJournal, - args: &ChatArgs, - budget: ContextBudget, - estimate: u64, - summarizer_calls: Option, -) -> ContextMeter { - let compaction = journal - .snapshot() - .compaction - .as_ref() - .map(|record| CompactionMeter { - compacted_messages: record.compacted_messages, - retained_messages: u64::try_from(journal.snapshot().messages.len()) - .unwrap_or(u64::MAX) - .saturating_sub(record.compacted_messages), - summarizer_calls, - summary_sha256: record.summary_sha256.clone(), - }); - ContextMeter { - estimated_input_tokens: estimate, - context_tokens: budget.context_tokens, - max_output_tokens: args.max_output_tokens, - effective_trigger: budget.trigger(), - auto_compaction: args.auto_compact, - estimate_scope: "pre_turn_conservative", - compaction, - } + result.map_err(|error| error.with_session(locator)) } fn compact_session( @@ -625,7 +440,7 @@ fn compact_session( let path = resolve_journal(locator.journal, locator.journal_native)?; let mut journal = SessionJournal::open(&path).map_err(session_error)?; // Live settings decide whether saved tool results may reach the summarizer. - let outcome = context_cli::compact_journal( + let outcome = compact_journal( &mut journal, &data_root, &client, @@ -647,198 +462,6 @@ fn compact_session( }) } -/// Preflight deterministic failures before starting; preserve uncertain I/O state. -fn chat_turn( - journal: &mut SessionJournal, - data_root: &std::path::Path, - client: &LocalModelClient, - summary_client: &LocalModelClient, - args: ChatArgs, - token: Option<&str>, -) -> Result<(), CliError> { - if journal.snapshot().archived { - return Err(CliError::new( - "session", - "Restore the archived session before chatting", - )); - } - if journal.snapshot().active_turn.is_some() { - return Err(CliError::new( - "session", - "The previous turn is incomplete; inspect it, then use session interrupt to mark it failed without retrying", - )); - } - let mode = model_tools::select(data_root, journal)?; - let tool_extra = match &mode { - model_tools::ToolMode::Enabled { .. } => model_tools::TOOL_SCHEMA_ESTIMATE_BYTES, - model_tools::ToolMode::Disabled { .. } => 0, - }; - let tools_enabled = matches!(mode, model_tools::ToolMode::Enabled { .. }); - let meter = preflight_context( - journal, - data_root, - &args, - summary_client, - token, - tool_extra, - tools_enabled, - )?; - let manifest = RequestManifest { - base_prompt: BASE_PROMPT.to_owned(), - prompt_version: BASE_PROMPT_VERSION.to_owned(), - prompt_sha256: prompt::base_prompt_sha256(), - custom_instructions: args.instructions.clone(), - model: args.model.clone(), - base_url: args.endpoint.clone(), - context_tokens: args.context_tokens, - max_output_tokens: args.max_output_tokens, - tool_schema_version: None, - tools: None, - }; - // Live settings decide whether this turn offers the workspace tools. - let reason = match mode { - model_tools::ToolMode::Enabled { workspace_id } => { - let mut output = model_tools::run( - journal, - data_root, - workspace_id, - client, - token, - model_tools::UserTurn { - message: &args.message, - instructions: &args.instructions, - manifest, - }, - )?; - output.context = Some(meter.clone()); - return print_json(&JournalOutput { - locator: journal_locator(journal)?, - detail: output, - }); - } - model_tools::ToolMode::Disabled { reason } => reason, - }; - // Text-only chat has no model file-read authority, so saved tool results, - // and a summary built from them, are withheld rather than sent again. - let (mut history, withheld_tool_results) = replay_active(journal, false); - for message in &mut history { - message.content = redact_known_secret(&message.content, token); - } - history.push(ConversationMessage { - role: ConversationRole::User, - content: args.message.clone(), - }); - let messages = prompt::assemble(&args.instructions, &history) - .map_err(|error| CliError::new("prompt", error.to_string()))?; - journal - .preflight_request(&args.message, &manifest) - .map_err(session_error)?; - let request_id = journal.start_turn().map_err(session_error)?; - journal - .record_message(MessageRole::User, &args.message) - .map_err(session_error)?; - journal - .record_manifest(request_id, manifest) - .map_err(session_error)?; - let mut reply = match client.complete(&messages) { - Ok(reply) => reply, - Err(error) => { - journal - .fail_turn(request_id, "provider_error") - .map_err(|_| { - CliError::new( - "persistence", - "Provider failed and failure could not be recorded", - ) - })?; - return Err(provider_error(error)); - } - }; - reply.content = redact_known_secret(&reply.content, token); - // Keep every accepted reply resumable within the journal and prompt limits. - // The wire response limit also covers protocol metadata, so it is larger. - if reply.content.len() > 16 * 1024 { - journal - .fail_turn(request_id, "response_too_large") - .map_err(session_error)?; - return Err(CliError::new( - "provider", - "Assistant text exceeds the 16 KiB session message limit", - )); - } - if let Err(error) = journal.record_message(MessageRole::Assistant, &reply.content) { - if matches!( - error, - SessionError::LimitReached | SessionError::InvalidValue(_) - ) { - journal - .fail_turn(request_id, "response_too_large") - .map_err(session_error)?; - } - // Failed writes/syncs can have changed storage. Do not overwrite that - // uncertain state with a fabricated terminal event or an automatic retry. - return Err(session_error(error)); - } - journal.complete_turn(request_id).map_err(session_error)?; - print_json(&JournalOutput { - locator: journal_locator(journal)?, - detail: json!({ - "reply": reply, - "model_tools": { - "mode": "disabled", - "reason": reason, - "withheld_tool_results": withheld_tool_results, - }, - "context": meter, - }), - }) -} - -/// Create a session with current registry metadata when a trusted root is configured. -/// -/// An absent or valid unconfigured store preserves legacy session creation. Corrupt -/// control state or an invalid workspace under a configured root fails closed. -fn create_session( - data_root: &std::path::Path, - workspace: &std::path::Path, - title: &str, -) -> Result { - let registration_id = match ControlStore::open_existing(data_root) - .map_err(|error| CliError::new("control", error.to_string()))? - { - Some(mut store) if store.has_development_root() => { - let registration = store - .register_workspace(workspace, store.revision()) - .map_err(|error| CliError::new("control", error.to_string()))?; - let id = registration.id(); - drop(store); - Some(id) - } - Some(store) => { - drop(store); - None - } - None => None, - }; - - let journal = match registration_id { - Some(id) => SessionJournal::create_with_workspace_id(data_root, workspace, title, id), - None => SessionJournal::create(data_root, workspace, title), - } - .map_err(session_error)?; - Ok(journal) -} - -/// Choose trusted application storage; repository content cannot set this value. -fn data_root(override_path: Option) -> Result { - if let Some(path) = override_path { - return Ok(path); - } - ProjectDirs::from("org", "OMG-Software", "OMGCode") - .map(|directories| directories.data_local_dir().to_owned()) - .ok_or_else(|| CliError::new("configuration", "No per-user application data directory")) -} - fn print_session(journal: &SessionJournal) -> Result<(), CliError> { print_json(&JournalOutput { locator: journal_locator(journal)?, @@ -885,35 +508,6 @@ fn resolve_journal(path: Option, native: Option) -> Result Result, CliError> { - match env::var("OMGCODE_LM_TOKEN") { - Ok(value) if !value.is_empty() => Ok(Some(value)), - Ok(_) | Err(env::VarError::NotPresent) => Ok(None), - Err(env::VarError::NotUnicode(_)) => Err(CliError::new( - "configuration", - "Server token must be Unicode", - )), - } -} - -/// Remove the configured credential from untrusted text before retention or egress. -/// If replacement would itself contain the credential, discard that text instead. -fn redact_known_secret(text: &str, token: Option<&str>) -> String { - match token.filter(|token| !token.is_empty()) { - Some(token) => { - let result = text.replace(token, "[REDACTED]"); - if result.contains(token) { - String::new() - } else { - result - } - } - None => text.to_owned(), - } -} - /// Serialize untrusted strings as escaped JSON and propagate broken output errors. fn print_json(value: &impl Serialize) -> Result<(), CliError> { let mut output = io::stdout().lock(); @@ -925,9 +519,9 @@ fn print_json(value: &impl Serialize) -> Result<(), CliError> { } fn session_error(error: omgcode_core::session::SessionError) -> CliError { - CliError::new("session", error.to_string()) + AppError::session(error).into() } fn provider_error(error: omgcode_core::provider::ProviderError) -> CliError { - CliError::new("provider", error.to_string()) + AppError::provider(error).into() } diff --git a/crates/omgcode-cli/src/model_tools.rs b/crates/omgcode-cli/src/model_tools.rs deleted file mode 100644 index a695c41..0000000 --- a/crates/omgcode-cli/src/model_tools.rs +++ /dev/null @@ -1,339 +0,0 @@ -//! Chat with the persisted model-tool preference. -//! -//! The session journal only selects which registered workspace to consult. -//! Authority comes from the live settings preference, rechecked by the core -//! runtime before every tool call, and each call stays inside that workspace. -//! The edit and command tools also need a trusted single-use approval. - -use std::path::Path; -use std::time::Duration; - -use omgcode_core::control::ControlStore; -use omgcode_core::policy::WorkspaceId; -use omgcode_core::prompt::ModelMessage; -use omgcode_core::provider::{LocalModelClient, LocalToolModel, ProviderError}; -use omgcode_core::session::{RequestManifest, SessionJournal}; -use omgcode_core::turn::{ - ModelError, ToolModel, ToolModelReply, ToolModelRequest, TurnError, TurnLimits, TurnReport, - TurnRuntime, -}; -use serde::Serialize; -use serde_json::Value; -use uuid::Uuid; - -use crate::{CliError, provider_error, redact_known_secret}; - -/// Whether this build can serve the model read/list tools. -/// -/// The capability report and tool selection share this value, so chat never -/// offers tools the platform cannot run. -pub(crate) const MODEL_TOOLS_SUPPORTED: bool = - cfg!(any(target_os = "linux", target_os = "windows")); - -/// Conservative byte allowance for the advertised tool definitions. -/// -/// The largest set (read, list, edit, and command) serializes to 2,763 bytes -/// in the adapter's wire shape; a unit test keeps this allowance above it. -pub(crate) const TOOL_SCHEMA_ESTIMATE_BYTES: usize = 4 * 1024; - -/// Whether this chat turn offers the model the workspace read/list tools. -#[derive(Debug)] -pub(crate) enum ToolMode { - /// The selected workspace's live preference enables model tools. - Enabled { workspace_id: WorkspaceId }, - /// Text-only chat, with the reason tools were not offered. - Disabled { reason: &'static str }, -} - -/// Decide the tool mode from current settings without holding the settings lock. -/// -/// An unsupported platform, an absent store, an unregistered workspace, or a -/// disabled preference gives text-only chat. Invalid settings fail closed. A -/// version 1 journal cannot record tool events, so it stays text-only. -pub(crate) fn select(data_root: &Path, journal: &SessionJournal) -> Result { - if !MODEL_TOOLS_SUPPORTED { - return Ok(ToolMode::Disabled { - reason: "platform_unsupported", - }); - } - let Some(control) = ControlStore::open_existing(data_root) - .map_err(|error| CliError::new("control", error.to_string()))? - else { - return Ok(ToolMode::Disabled { - reason: "settings_absent", - }); - }; - // The journal's UUID only selects a registration; the ID used afterwards - // and its preference come from current settings. - let (workspace_id, enabled) = - match control.registered_workspace(journal.snapshot().workspace_id) { - None => { - return Ok(ToolMode::Disabled { - reason: "workspace_unregistered", - }); - } - Some(workspace) => (workspace.id(), workspace.permissions().model_tools), - }; - // Release the settings lock before any model request. - drop(control); - if !enabled { - return Ok(ToolMode::Disabled { - reason: "preference_disabled", - }); - } - if journal.schema_version() < 2 { - return Ok(ToolMode::Disabled { - reason: "session_schema_v1", - }); - } - Ok(ToolMode::Enabled { workspace_id }) -} - -/// Whether live settings authorize replaying saved tool results for a session: -/// the same `model_tools` and `read` rule the turn runtime applies. -/// -/// The session is named by its recorded workspace UUID and schema version, so -/// compaction can recheck while it holds the journal. Each call reads current -/// settings. Every condition that gives text-only chat gives `false`; invalid -/// settings return an error. -pub(crate) fn tool_replay_allowed( - data_root: &Path, - workspace: Uuid, - schema_version: u32, -) -> Result { - if !MODEL_TOOLS_SUPPORTED || schema_version < 2 { - return Ok(false); - } - let Some(control) = ControlStore::open_existing(data_root) - .map_err(|error| CliError::new("control", error.to_string()))? - else { - return Ok(false); - }; - Ok(control - .registered_workspace(workspace) - .is_some_and(|workspace| { - let permissions = workspace.permissions(); - permissions.model_tools && permissions.read - })) -} - -/// Summary of one completed tool-enabled turn. -#[derive(Serialize)] -pub(crate) struct ToolTurnOutput { - pub(crate) reply: ToolTurnReply, - pub(crate) model_tools: ToolTurnSummary, - pub(crate) context: Option, -} - -/// Assistant text from a tool-enabled turn. It remains untrusted model output. -#[derive(Serialize)] -pub(crate) struct ToolTurnReply { - pub(crate) content: String, - /// `stop`, or `length` when the token limit cut the reply short. - pub(crate) finish_reason: String, -} - -/// Bounded counters for a tool-enabled turn. -#[derive(Serialize)] -pub(crate) struct ToolTurnSummary { - mode: &'static str, - workspace_id: String, - rounds: usize, - tool_calls: usize, - tool_bytes: u64, - withheld_tool_results: usize, -} - -/// The user's request for one tool-enabled turn. -pub(crate) struct UserTurn<'a> { - pub(crate) message: &'a str, - pub(crate) instructions: &'a str, - pub(crate) manifest: RequestManifest, -} - -/// Run one tool-enabled turn through the core runtime. -pub(crate) fn run( - journal: &mut SessionJournal, - data_root: &Path, - workspace_id: WorkspaceId, - client: &LocalModelClient, - token: Option<&str>, - turn: UserTurn<'_>, -) -> Result { - let mut model = RedactingModel { - inner: LocalToolModel::new(client), - token, - secret_in_tool_call: false, - }; - // Tool results are recorded before the next model request, so they need - // their own redaction; the model wrapper sees them only afterwards. - let redact_tool_text = |text: &str| redact_known_secret(text, token); - let report: TurnReport = TurnRuntime::new(journal, data_root, workspace_id, chat_limits()) - .and_then(|runtime| { - runtime.with_tool_text_filter(&redact_tool_text).run( - &mut model, - turn.message, - turn.instructions, - turn.manifest, - ) - }) - .map_err(|error| { - if model.secret_in_tool_call { - return CliError::new( - "provider", - "The model returned a tool call containing the configured server token; it was not recorded or run", - ); - } - turn_error(error, model.inner.last_error()) - })?; - Ok(ToolTurnOutput { - reply: ToolTurnReply { - content: report.reply, - finish_reason: report.finish_reason, - }, - model_tools: ToolTurnSummary { - mode: "enabled", - workspace_id: workspace_id.to_string(), - rounds: report.rounds, - tool_calls: report.tool_calls, - tool_bytes: report.tool_bytes, - withheld_tool_results: report.withheld_tool_results, - }, - context: None, - }) -} - -/// Cooperative deadline for one tool-enabled chat turn. -/// -/// Each local model request may take up to 30 seconds, and a turn makes at most -/// four requests, so the 30-second library default would stop ordinary turns. -const CHAT_TURN_DEADLINE: Duration = Duration::from_secs(120); - -/// Runtime limits for tool-enabled chat: library maxima with a chat deadline. -fn chat_limits() -> TurnLimits { - TurnLimits { - deadline: CHAT_TURN_DEADLINE, - ..TurnLimits::default() - } -} - -/// Remove a known local server token from text sent to and received from the model. -/// -/// A tool call that contains the token is refused rather than redacted, because -/// editing its arguments could change the requested path. The runtime records -/// calls before any result filter runs, so the refusal happens here. -struct RedactingModel<'a> { - inner: LocalToolModel<'a>, - token: Option<&'a str>, - secret_in_tool_call: bool, -} - -impl ToolModel for RedactingModel<'_> { - fn complete(&mut self, request: ToolModelRequest<'_>) -> Result { - let messages: Vec = request - .messages - .iter() - .map(|message| ModelMessage { - role: message.role, - content: redact_known_secret(&message.content, self.token), - }) - .collect(); - let mut reply = self.inner.complete(ToolModelRequest { - messages: &messages, - tools: request.tools, - })?; - if let Some(token) = self.token.filter(|token| !token.is_empty()) - && reply - .tool_calls - .iter() - .any(|call| contains_secret(call, token, true)) - { - self.secret_in_tool_call = true; - return Err(ModelError::InvalidResponse); - } - reply.content = redact_known_secret(&reply.content, self.token); - Ok(reply) - } -} - -/// Report whether any key or string in a raw tool-call value contains `token`. -/// -/// Tool-call arguments arrive as a JSON-encoded string, so a string that parses -/// as JSON is searched once more after decoding. Decoding is not repeated -/// inside that nested value. -fn contains_secret(value: &Value, token: &str, decode_nested: bool) -> bool { - match value { - Value::String(text) => { - text.contains(token) - || (decode_nested - && serde_json::from_str::(text) - .is_ok_and(|nested| contains_secret(&nested, token, false))) - } - Value::Array(items) => items - .iter() - .any(|item| contains_secret(item, token, decode_nested)), - Value::Object(fields) => fields - .iter() - .any(|(key, item)| key.contains(token) || contains_secret(item, token, decode_nested)), - Value::Null | Value::Bool(_) | Value::Number(_) => false, - } -} - -/// Map a runtime failure to a stable CLI error without echoing model text. -fn turn_error(error: TurnError, provider: Option) -> CliError { - match error { - TurnError::Model(_) => provider.map_or_else( - || CliError::new("provider", "Local model request failed"), - provider_error, - ), - TurnError::ToolDenied(_) => CliError::new( - "permission", - "A model tool call was denied by the current workspace preferences", - ), - TurnError::InvalidToolCall(error) => CliError::new( - "tool_call", - format!("The model returned an invalid tool call: {error}"), - ), - TurnError::Limit(limit) => { - CliError::new("tool_limit", format!("Turn limit exceeded: {limit}")) - } - TurnError::Session(error) => crate::session_error(error), - TurnError::Prompt(error) => CliError::new("prompt", error.to_string()), - TurnError::Archived => { - CliError::new("session", "Restore the archived session before chatting") - } - TurnError::ActiveTurn => CliError::new( - "session", - "The previous turn is incomplete; inspect it, then use session interrupt to mark it failed without retrying", - ), - other => CliError::new("turn", other.to_string()), - } -} - -#[cfg(test)] -mod tests { - use omgcode_core::turn::{command_tool_definition, edit_tool_definition, tool_definitions}; - use serde_json::{Value, json}; - - use super::TOOL_SCHEMA_ESTIMATE_BYTES; - - /// The estimate must cover the largest advertised tool set in the exact - /// OpenAI-compatible wire shape the adapter sends. - #[test] - fn the_schema_estimate_covers_every_advertised_tool_definition() { - let mut definitions = tool_definitions(); - definitions.push(edit_tool_definition()); - definitions.push(command_tool_definition()); - let wire: Vec = definitions - .iter() - .map(|definition| json!({"type": "function", "function": definition})) - .collect(); - let bytes = serde_json::to_vec(&wire).expect("serialize tool definitions"); - println!("advertised tool definitions: {} bytes", bytes.len()); - assert!( - bytes.len() <= TOOL_SCHEMA_ESTIMATE_BYTES, - "{} bytes exceed the {TOOL_SCHEMA_ESTIMATE_BYTES}-byte estimate", - bytes.len() - ); - } -} diff --git a/crates/omgcode-core/Cargo.toml b/crates/omgcode-core/Cargo.toml index eb29888..62baecc 100644 --- a/crates/omgcode-core/Cargo.toml +++ b/crates/omgcode-core/Cargo.toml @@ -16,6 +16,7 @@ thiserror.workspace = true reqwest.workspace = true tokio.workspace = true sha2.workspace = true +rusqlite.workspace = true [dev-dependencies] tempfile.workspace = true diff --git a/crates/omgcode-core/src/control.rs b/crates/omgcode-core/src/control.rs index 0893992..efe58f9 100644 --- a/crates/omgcode-core/src/control.rs +++ b/crates/omgcode-core/src/control.rs @@ -7,7 +7,7 @@ use std::collections::{BTreeMap, HashSet}; use std::fs::File; use std::io::{self, Read, Seek, SeekFrom, Write}; -use std::path::Path; +use std::path::{Path, PathBuf}; use serde::{Deserialize, Deserializer, Serialize}; use thiserror::Error; @@ -183,6 +183,32 @@ impl WorkspaceRegistration { pub const fn permissions(&self) -> PermissionSet { self.permissions } + + /// The directory recorded at registration, as a native path. + /// + /// This is a recorded value, not proof that the directory still exists or + /// is the one that was registered. A caller must open it through the + /// session or file layers, which re-validate the live identity, the + /// development root, and the permissions. The path alone grants nothing. + /// Returns `None` when the record was written with another operating + /// system's path encoding. + pub fn directory_path(&self) -> Option { + self.directory.path.to_path_buf().ok() + } + + /// The recorded directory as display text. + /// + /// The text is lossy and has control, invisible, and bidirectional + /// formatting characters replaced by visible escapes (see + /// [`crate::turn::display_safe_line`]). It is for people to read. Never use + /// it as an authorization key or to reopen the directory; use + /// [`Self::id`] and [`Self::directory_path`]. + pub fn directory_display(&self) -> String { + self.directory_path().map_or_else( + || String::from("(path not representable on this system)"), + |path| crate::turn::display_safe_line(&path.to_string_lossy()), + ) + } } /// Reject malformed persisted IDs before constructing typed workspace metadata. @@ -749,6 +775,15 @@ impl ControlStore { .find(|status| status.workspace_id == workspace_id) .map(|status| &status.directory) } + /// Iterate every registered workspace in registration order. + /// + /// The order is the settings journal's replay order, so it is + /// deterministic for one store state. The registrations are descriptive + /// settings, not capabilities; listing one grants no access. + pub fn workspaces(&self) -> impl Iterator { + self.snapshot.workspaces.iter() + } + /// Look up descriptive workspace metadata by its stable identifier. pub fn workspace(&self, id: WorkspaceId) -> Option<&WorkspaceRegistration> { self.snapshot diff --git a/crates/omgcode-core/src/lib.rs b/crates/omgcode-core/src/lib.rs index bda43eb..8f01da1 100644 --- a/crates/omgcode-core/src/lib.rs +++ b/crates/omgcode-core/src/lib.rs @@ -14,6 +14,7 @@ pub mod replacement; pub mod run; pub mod run_journal; pub mod session; +pub mod session_index; mod storage; pub mod turn; mod workspace; diff --git a/crates/omgcode-core/src/session.rs b/crates/omgcode-core/src/session.rs index c1249c6..0800412 100644 --- a/crates/omgcode-core/src/session.rs +++ b/crates/omgcode-core/src/session.rs @@ -18,6 +18,20 @@ use uuid::Uuid; use crate::storage::{self, StorageError}; +mod discovery; +mod filename; +mod inspection; + +pub use discovery::{DiscoveredJournal, Discovery, discover, locate}; +pub use inspection::{SessionInspection, TranscriptEntry, TranscriptEntryKind}; + +/// Return the session UUID of a file name that matches the writer's exact +/// journal name format, or `None`. The session index uses this to revalidate a +/// stored path before handing it to a writer open. +pub(crate) fn strict_journal_session_id(name: &str) -> Option { + filename::parse_strict(name) +} + const SCHEMA_VERSION_V1: u32 = 1; const SCHEMA_VERSION_V2: u32 = 2; const SCHEMA_VERSION: u32 = 3; @@ -308,14 +322,7 @@ impl SessionJournal { .join(format!("{:02}", u8::from(now.month()))) .join(format!("{:02}", now.day())); storage::create_private_directories(&dir).map_err(map_storage_error)?; - let filename = format!( - "omgcode-{:02}-{:02}-{:02}-{:03}Z-{session_id}.jsonl", - now.hour(), - now.minute(), - now.second(), - now.millisecond() - ); - let path = dir.join(filename); + let path = dir.join(filename::journal_file_name(now, session_id)); let mut file = storage::open_locked_file(&path, true).map_err(map_storage_error)?; let started = SessionStarted { @@ -375,16 +382,7 @@ impl SessionJournal { .file_name() .and_then(|name| name.to_str()) .ok_or(SessionError::InvalidJournal("filename is not valid UTF-8"))?; - let id_text = filename - .strip_prefix("omgcode-") - .and_then(|name| name.strip_suffix(".jsonl")) - .and_then(|name| name.rsplit_once("Z-")) - .map(|(_, id)| id) - .ok_or(SessionError::InvalidJournal( - "filename does not contain a session UUID", - ))?; - let filename_id = Uuid::parse_str(id_text) - .map_err(|_| SessionError::InvalidJournal("filename has an invalid session UUID"))?; + let filename_id = filename::lenient_session_id(filename)?; let metadata = fs::symlink_metadata(path)?; if metadata.file_type().is_symlink() || !metadata.is_file() { return Err(SessionError::InvalidJournal( @@ -393,7 +391,12 @@ impl SessionJournal { } let mut file = storage::open_locked_file(path, false).map_err(map_storage_error)?; let contents = read_bounded(&mut file)?; - let (snapshot, tool_state, tool_requests) = replay(&contents, filename_id)?; + let Replayed { + snapshot, + tool_state, + tool_requests, + .. + } = replay(&contents, filename_id, None)?; let bytes = u64::try_from(contents.len()).map_err(|_| SessionError::LimitReached)?; let next_seq = snapshot.event_count; let schema_version = snapshot.schema_version; @@ -987,11 +990,15 @@ struct MessagePayload { call_id: Option, } +/// The recorded origin label of a message. A label never grants authority. #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] -enum MessageSource { +pub enum MessageSource { + /// Text entered through the trusted CLI. UserCli, + /// Text returned by the model provider. Provider, + /// Text rendered by core from a tool result. Schema version 2 and later. CoreTool, } @@ -1354,11 +1361,43 @@ fn read_bounded(file: &mut File) -> Result, SessionError> { Ok(contents) } +/// The validated result of replaying a complete journal. +struct Replayed { + snapshot: SessionSnapshot, + tool_state: ToolState, + tool_requests: Vec, + /// Timestamp of the `session.started` event. + created_at: OffsetDateTime, + /// Timestamp of the last replayed event. + updated_at: OffsetDateTime, +} + +/// Queue one transcript entry when a caller asked for entries. The kind is +/// built lazily so a writer-side replay clones nothing. +fn note_entry( + entries: &mut Option<&mut Vec>, + seq: u64, + timestamp: OffsetDateTime, + kind: impl FnOnce() -> TranscriptEntryKind, +) { + if let Some(sink) = entries.as_mut() { + sink.push(TranscriptEntry { + seq, + timestamp, + kind: kind(), + }); + } +} + /// Validate every event and transition without interpreting content as work. +/// +/// `entries` receives one record per event after `session.started` when the +/// caller is an observer. Both the writer and the observer share these rules. fn replay( contents: &[u8], filename_id: Uuid, -) -> Result<(SessionSnapshot, ToolState, Vec), SessionError> { + mut entries: Option<&mut Vec>, +) -> Result { if contents.is_empty() || contents[0..contents.len().min(3)] == [0xef, 0xbb, 0xbf] { return Err(SessionError::InvalidJournal( "journal is empty or has a byte-order mark", @@ -1378,6 +1417,8 @@ fn replay( let mut expected_seq = 0_u64; let mut total_events = 0_usize; let mut consumed_bytes = 0_usize; + let mut created_at = None; + let mut updated_at = None; for raw_line in contents.split_inclusive(|byte| *byte == b'\n') { if raw_line.len() > MAX_EVENT_BYTES { return Err(SessionError::InvalidJournal("event exceeds 64 KiB")); @@ -1442,7 +1483,8 @@ fn replay( if !event_ids.insert(envelope.event_id) { return Err(SessionError::InvalidJournal("duplicate event UUID")); } - validate_timestamp(&envelope.timestamp)?; + let at = validate_timestamp(&envelope.timestamp)?; + let seq = envelope.seq; match envelope.event_type.as_str() { "session.started" => { if snapshot.is_some() || expected_seq != 0 { @@ -1453,6 +1495,7 @@ fn replay( let started: SessionStarted = decode_payload(envelope.payload)?; validate_title(&started.title) .map_err(|_| SessionError::InvalidJournal("initial title is invalid"))?; + created_at = Some(at); snapshot = Some(SessionSnapshot { schema_version: envelope.schema_version, session_id: envelope.session_id, @@ -1537,6 +1580,12 @@ fn replay( )); } } + note_entry(&mut entries, seq, at, || TranscriptEntryKind::Message { + role: message.role, + source: message.source, + text: message.text.clone(), + call_id: message.call_id.clone(), + }); target.messages.push(RecordedMessage { role: message.role, text: message.text, @@ -1552,6 +1601,9 @@ fn replay( } let payload: TurnPayload = decode_payload(envelope.payload)?; tool_state.clear(); + note_entry(&mut entries, seq, at, || TranscriptEntryKind::TurnStarted { + request_id: payload.request_id, + }); target.active_turn = Some(payload.request_id); } "tool.requested" => { @@ -1590,6 +1642,14 @@ fn replay( )); } tool_state.pending.insert(payload.call_id.clone()); + note_entry(&mut entries, seq, at, || { + TranscriptEntryKind::ToolRequested { + request_id: payload.request_id, + call_id: payload.call_id.clone(), + tool: payload.tool.clone(), + arguments: payload.arguments.clone(), + } + }); tool_requests.push(RecordedToolRequest { request_id: payload.request_id, call_id: payload.call_id, @@ -1632,6 +1692,16 @@ fn replay( )?; tool_state.pending.remove(&payload.call_id); tool_state.completed.insert(payload.call_id.clone()); + note_entry(&mut entries, seq, at, || { + TranscriptEntryKind::ToolCompleted { + request_id: payload.request_id, + call_id: payload.call_id.clone(), + outcome: payload.outcome, + code: payload.code.clone(), + output_bytes: payload.output_bytes, + output_sha256: payload.output_sha256.clone(), + } + }); tool_state.outputs.insert( payload.call_id, (payload.output_bytes, payload.output_sha256), @@ -1653,6 +1723,14 @@ fn replay( validate_manifest(&payload.manifest, envelope.schema_version).map_err(|_| { SessionError::InvalidJournal("request manifest exceeds event size limit") })?; + note_entry(&mut entries, seq, at, || { + TranscriptEntryKind::RequestManifest { + request_id: payload.request_id, + model: payload.manifest.model.clone(), + prompt_version: payload.manifest.prompt_version.clone(), + tools: payload.manifest.tools.clone().unwrap_or_default(), + } + }); } "turn.completed" | "turn.failed" => { let target = snapshot @@ -1687,6 +1765,18 @@ fn replay( "completed turn has unresolved or unrecorded tool calls", )); } + note_entry(&mut entries, seq, at, || { + if envelope.event_type == "turn.failed" { + TranscriptEntryKind::TurnFailed { + request_id: payload.request_id, + code: payload.code.clone().unwrap_or_default(), + } + } else { + TranscriptEntryKind::TurnCompleted { + request_id: payload.request_id, + } + } + }); target.active_turn = None; tool_state.clear(); } @@ -1698,6 +1788,9 @@ fn replay( if target.active_turn.is_some() { return Err(SessionError::InvalidJournal("active session was archived")); } + note_entry(&mut entries, seq, at, || { + TranscriptEntryKind::SessionArchived + }); target.archived = true; tool_state.clear(); } @@ -1706,6 +1799,9 @@ fn replay( .as_mut() .ok_or(SessionError::InvalidJournal("event before start"))?; let _: EmptyPayload = decode_payload(envelope.payload)?; + note_entry(&mut entries, seq, at, || { + TranscriptEntryKind::SessionRestored + }); target.archived = false; } "context.compacted" => { @@ -1730,6 +1826,11 @@ fn replay( .map(|record| record.compacted_messages); validate_compaction(&record, &target.messages, prior) .map_err(|_| SessionError::InvalidJournal("invalid compaction record"))?; + note_entry(&mut entries, seq, at, || { + TranscriptEntryKind::ContextCompacted { + record: record.clone(), + } + }); target.compaction = Some(record); } _ => return Err(SessionError::InvalidJournal("unknown event type")), @@ -1745,6 +1846,7 @@ fn replay( expected_seq = expected_seq .checked_add(1) .ok_or(SessionError::LimitReached)?; + updated_at = Some(at); if let Some(target) = snapshot.as_mut() { target.event_count = u64::try_from(total_events).map_err(|_| SessionError::LimitReached)?; @@ -1753,7 +1855,18 @@ fn replay( let snapshot = snapshot.ok_or(SessionError::InvalidJournal( "missing session.started event", ))?; - Ok((snapshot, tool_state, tool_requests)) + let (Some(created_at), Some(updated_at)) = (created_at, updated_at) else { + return Err(SessionError::InvalidJournal( + "missing session.started event", + )); + }; + Ok(Replayed { + snapshot, + tool_state, + tool_requests, + created_at, + updated_at, + }) } /// Reject transcript changes while replay says the session is archived. @@ -1768,13 +1881,13 @@ fn ensure_not_archived(snapshot: &SessionSnapshot) -> Result<(), SessionError> { } /// Require parseable UTC metadata without using clocks to reorder events. -fn validate_timestamp(value: &str) -> Result<(), SessionError> { +fn validate_timestamp(value: &str) -> Result { let timestamp = OffsetDateTime::parse(value, &Rfc3339) .map_err(|_| SessionError::InvalidJournal("timestamp is not RFC 3339"))?; if timestamp.offset().whole_seconds() != 0 { return Err(SessionError::InvalidJournal("timestamp is not UTC")); } - Ok(()) + Ok(timestamp) } /// Apply the selected event's typed schema and reject unsupported fields. diff --git a/crates/omgcode-core/src/session/discovery.rs b/crates/omgcode-core/src/session/discovery.rs new file mode 100644 index 0000000..0a5ed6f --- /dev/null +++ b/crates/omgcode-core/src/session/discovery.rs @@ -0,0 +1,313 @@ +//! Bounded discovery of session journals below a trusted data root. +//! +//! Discovery walks only `/sessions///
/` and lists +//! files whose names match the writer's exact pattern. It never follows a +//! symbolic link or Windows reparse point, never opens a journal, and never +//! reads journal content. A listing is a locator, not validation: inspect or +//! open a journal to learn whether it is valid. + +use std::fs::{self, DirEntry, FileType}; +use std::io; +use std::path::{Path, PathBuf}; +use std::time::SystemTime; + +use uuid::Uuid; + +use super::{SessionError, filename}; + +/// The most journals one discovery may list. +const MAX_DISCOVERED_JOURNALS: usize = 50_000; +/// The most directory entries one discovery may examine, at every level. +const MAX_DIRECTORY_ENTRIES: usize = 500_000; +/// Directory levels below `sessions`: year, month, day. +const DATE_LEVELS: usize = 3; +/// Required ASCII digit counts for the year, month, and day directory names. +const DATE_WIDTHS: [usize; DATE_LEVELS] = [4, 2, 2]; +const SESSIONS_DIRECTORY: &str = "sessions"; + +/// One journal file found by discovery. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct DiscoveredJournal { + /// The session UUID taken from the file name. Replay must still confirm it. + pub session_id: Uuid, + /// The journal path: the absolute form of the data root joined with + /// `relative_path`. Symbolic links are not resolved. + pub path: PathBuf, + /// The path below the data root, such as + /// `sessions/2026/11/16/omgcode-...jsonl`. It is a stable key. + pub relative_path: PathBuf, + /// The file size in bytes when discovery listed it. + pub size: u64, + /// The file's last-modified time as reported by the operating system. + pub modified: SystemTime, +} + +/// The result of one discovery walk. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct Discovery { + /// Journals sorted by `relative_path`. + pub journals: Vec, + /// Symbolic links and reparse points that were skipped at any level. + pub skipped_links: u64, + /// Entries that do not match the layout, including non-UTF-8 names, + /// wrongly named files and directories, and entries that vanished mid-walk. + pub unrecognized: u64, +} + +/// List journals below `data_root` in a deterministic order. +/// +/// `data_root` must come from trusted application settings. A missing +/// `sessions` directory yields an empty result. A `sessions` directory that is +/// itself a link is skipped and counted. Concurrent changes can make a listing +/// stale; it is not a snapshot. +/// +/// # Errors +/// +/// Returns `SessionError::LimitReached` after more than 50,000 journals or +/// 500,000 directory entries, and `SessionError::Io` when a directory cannot be +/// read. +pub fn discover(data_root: &Path) -> Result { + discover_with_limits(data_root, MAX_DISCOVERED_JOURNALS, MAX_DIRECTORY_ENTRIES) +} + +/// Run `discover` with explicit caps so tests can reach them cheaply. +fn discover_with_limits( + data_root: &Path, + max_journals: usize, + max_entries: usize, +) -> Result { + let absolute_root = std::path::absolute(data_root)?; + let mut walk = Walk { + absolute_root, + max_journals, + max_entries, + examined: 0, + discovery: Discovery::default(), + }; + let sessions = data_root.join(SESSIONS_DIRECTORY); + let metadata = match fs::symlink_metadata(&sessions) { + Ok(metadata) => metadata, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(walk.discovery), + Err(error) => return Err(error.into()), + }; + if metadata.file_type().is_symlink() || is_reparse_point(&metadata) { + walk.discovery.skipped_links += 1; + return Ok(walk.discovery); + } + if !metadata.is_dir() { + walk.discovery.unrecognized += 1; + return Ok(walk.discovery); + } + walk.directory(&sessions, Path::new(SESSIONS_DIRECTORY), 0)?; + let mut discovery = walk.discovery; + discovery + .journals + .sort_by(|left, right| left.relative_path.cmp(&right.relative_path)); + Ok(discovery) +} + +/// Find the one journal path for `session_id` below `data_root`. +/// +/// A UI addresses sessions by UUID and never supplies a path. This runs a full +/// `discover` walk and compares file-name UUIDs. It returns `None` when no +/// journal carries the UUID. +/// +/// # Errors +/// +/// Returns `SessionError::InvalidJournal` when two files carry the same UUID, +/// because choosing one would be a guess. It also returns every error of +/// `discover`. +pub fn locate(data_root: &Path, session_id: Uuid) -> Result, SessionError> { + let mut matches = discover(data_root)? + .journals + .into_iter() + .filter(|journal| journal.session_id == session_id); + let first = matches.next(); + if matches.next().is_some() { + return Err(SessionError::InvalidJournal( + "more than one journal has this session UUID", + )); + } + Ok(first.map(|journal| journal.path)) +} + +/// Mutable walk state with the shared entry budget. +struct Walk { + absolute_root: PathBuf, + max_journals: usize, + max_entries: usize, + examined: usize, + discovery: Discovery, +} + +impl Walk { + /// Visit one directory. `level` 0 holds years, 1 months, 2 days, 3 files. + fn directory( + &mut self, + directory: &Path, + relative: &Path, + level: usize, + ) -> Result<(), SessionError> { + let entries = match fs::read_dir(directory) { + Ok(entries) => entries, + Err(error) if level > 0 && error.kind() == io::ErrorKind::NotFound => { + self.discovery.unrecognized += 1; + return Ok(()); + } + Err(error) => return Err(error.into()), + }; + for entry in entries { + let entry = entry?; + self.examined += 1; + if self.examined > self.max_entries { + return Err(SessionError::LimitReached); + } + self.entry(&entry, relative, level)?; + } + Ok(()) + } + + /// Classify one entry without following it. + fn entry( + &mut self, + entry: &DirEntry, + relative: &Path, + level: usize, + ) -> Result<(), SessionError> { + let file_type = match entry.file_type() { + Ok(file_type) => file_type, + Err(error) if error.kind() == io::ErrorKind::NotFound => { + self.discovery.unrecognized += 1; + return Ok(()); + } + Err(error) => return Err(error.into()), + }; + if file_type.is_symlink() || entry_is_reparse_point(entry, &file_type)? { + self.discovery.skipped_links += 1; + return Ok(()); + } + let file_name = entry.file_name(); + let Some(name) = file_name.to_str() else { + self.discovery.unrecognized += 1; + return Ok(()); + }; + if let Some(width) = DATE_WIDTHS.get(level) { + if file_type.is_dir() && has_ascii_digits(name, *width) { + return self.directory(&entry.path(), &relative.join(name), level + 1); + } + } else if file_type.is_file() + && let Some(session_id) = filename::parse_strict(name) + { + return self.journal(entry, relative, name, session_id); + } + self.discovery.unrecognized += 1; + Ok(()) + } + + /// Record one matching file, or count it when it vanished. + fn journal( + &mut self, + entry: &DirEntry, + relative: &Path, + name: &str, + session_id: Uuid, + ) -> Result<(), SessionError> { + let metadata = match entry.metadata() { + Ok(metadata) => metadata, + Err(error) if error.kind() == io::ErrorKind::NotFound => { + self.discovery.unrecognized += 1; + return Ok(()); + } + Err(error) => return Err(error.into()), + }; + if self.discovery.journals.len() >= self.max_journals { + return Err(SessionError::LimitReached); + } + let relative_path = relative.join(name); + self.discovery.journals.push(DiscoveredJournal { + session_id, + path: self.absolute_root.join(&relative_path), + relative_path, + size: metadata.len(), + modified: metadata.modified()?, + }); + Ok(()) + } +} + +/// Return whether `name` is exactly `width` ASCII digits. +fn has_ascii_digits(name: &str, width: usize) -> bool { + name.len() == width && name.bytes().all(|byte| byte.is_ascii_digit()) +} + +/// Detect a Windows reparse point that `FileType` did not report as a link. +#[cfg(windows)] +fn entry_is_reparse_point(entry: &DirEntry, _file_type: &FileType) -> io::Result { + match entry.metadata() { + Ok(metadata) => Ok(is_reparse_point(&metadata)), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } +} + +/// Other platforms report links through `FileType` alone. +#[cfg(not(windows))] +fn entry_is_reparse_point(_entry: &DirEntry, _file_type: &FileType) -> io::Result { + Ok(false) +} + +/// Return whether metadata carries the Windows reparse-point attribute. +#[cfg(windows)] +fn is_reparse_point(metadata: &fs::Metadata) -> bool { + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0400; + metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 +} + +/// Other platforms have no reparse points. +#[cfg(not(windows))] +fn is_reparse_point(_metadata: &fs::Metadata) -> bool { + false +} + +#[cfg(test)] +mod tests { + use super::discover_with_limits; + use crate::session::{SessionError, filename}; + use std::fs; + use time::OffsetDateTime; + use uuid::Uuid; + + fn day_with_journals(count: usize) -> tempfile::TempDir { + let temporary = tempfile::tempdir().expect("temporary directory"); + let day = temporary.path().join("sessions/2026/01/02"); + fs::create_dir_all(&day).expect("day directory"); + for _ in 0..count { + let name = filename::journal_file_name(OffsetDateTime::now_utc(), Uuid::new_v4()); + fs::write(day.join(name), b"").expect("journal placeholder"); + } + temporary + } + + #[test] + fn journal_cap_returns_limit_reached_only_when_exceeded() { + let temporary = day_with_journals(3); + let at_cap = discover_with_limits(temporary.path(), 3, 1_000).expect("at the cap"); + assert_eq!(at_cap.journals.len(), 3); + assert!(matches!( + discover_with_limits(temporary.path(), 2, 1_000), + Err(SessionError::LimitReached) + )); + } + + #[test] + fn entry_cap_counts_directories_and_files_together() { + // Entries examined: year, month, day, then three files. + let temporary = day_with_journals(3); + discover_with_limits(temporary.path(), 100, 6).expect("exactly at the cap"); + assert!(matches!( + discover_with_limits(temporary.path(), 100, 5), + Err(SessionError::LimitReached) + )); + } +} diff --git a/crates/omgcode-core/src/session/filename.rs b/crates/omgcode-core/src/session/filename.rs new file mode 100644 index 0000000..3945788 --- /dev/null +++ b/crates/omgcode-core/src/session/filename.rs @@ -0,0 +1,122 @@ +//! Journal file naming shared by the writer, `SessionJournal::open`, the +//! read-only inspector, and discovery. +//! +//! A name is `omgcode----Z-.jsonl`. The name is only a +//! locator. Replay still requires every event to carry the same session UUID. + +use time::OffsetDateTime; +use uuid::Uuid; + +use super::SessionError; + +const NAME_PREFIX: &str = "omgcode-"; +const NAME_SUFFIX: &str = ".jsonl"; +const UUID_TEXT_BYTES: usize = 36; + +/// Format the file name the writer creates for a new session at `at`. +pub(super) fn journal_file_name(at: OffsetDateTime, session_id: Uuid) -> String { + format!( + "{NAME_PREFIX}{:02}-{:02}-{:02}-{:03}Z-{session_id}{NAME_SUFFIX}", + at.hour(), + at.minute(), + at.second(), + at.millisecond() + ) +} + +/// Extract the session UUID the way `SessionJournal::open` always has. +/// +/// This accepts any UUID spelling that `Uuid::parse_str` accepts and does not +/// check the time fields. Replay then rejects any event whose UUID differs. +pub(super) fn lenient_session_id(filename: &str) -> Result { + let id_text = filename + .strip_prefix(NAME_PREFIX) + .and_then(|name| name.strip_suffix(NAME_SUFFIX)) + .and_then(|name| name.rsplit_once("Z-")) + .map(|(_, id)| id) + .ok_or(SessionError::InvalidJournal( + "filename does not contain a session UUID", + ))?; + Uuid::parse_str(id_text) + .map_err(|_| SessionError::InvalidJournal("filename has an invalid session UUID")) +} + +/// Parse exactly the name the writer produces, or return `None`. +/// +/// The time fields must be fixed-width ASCII digits within range, and the UUID +/// must be a lowercase hyphenated version 4 value. +pub(super) fn parse_strict(name: &str) -> Option { + let body = name.strip_prefix(NAME_PREFIX)?.strip_suffix(NAME_SUFFIX)?; + let (stamp, id_text) = body.split_once("Z-")?; + let mut parts = stamp.split('-'); + let hour = fixed_digits(parts.next()?, 2)?; + let minute = fixed_digits(parts.next()?, 2)?; + let second = fixed_digits(parts.next()?, 2)?; + let millisecond = fixed_digits(parts.next()?, 3)?; + if parts.next().is_some() || hour > 23 || minute > 59 || second > 59 || millisecond > 999 { + return None; + } + if id_text.len() != UUID_TEXT_BYTES { + return None; + } + let id = Uuid::try_parse(id_text).ok()?; + if id.get_version_num() != 4 || id.as_hyphenated().to_string() != id_text { + return None; + } + Some(id) +} + +/// Parse a field of exactly `width` ASCII digits. +fn fixed_digits(text: &str, width: usize) -> Option { + if text.len() != width || !text.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + text.parse().ok() +} + +#[cfg(test)] +mod tests { + use super::{journal_file_name, lenient_session_id, parse_strict}; + use time::OffsetDateTime; + use uuid::Uuid; + + #[test] + fn writer_names_round_trip_through_the_strict_parser() { + let id = Uuid::new_v4(); + let name = journal_file_name(OffsetDateTime::now_utc(), id); + assert_eq!(parse_strict(&name), Some(id)); + assert_eq!(lenient_session_id(&name).expect("lenient"), id); + } + + #[test] + fn strict_parser_rejects_every_deviation_from_the_writer_format() { + let id = Uuid::new_v4(); + let good = format!("omgcode-01-02-03-004Z-{id}.jsonl"); + assert_eq!(parse_strict(&good), Some(id)); + let upper = format!( + "omgcode-01-02-03-004Z-{}.jsonl", + id.to_string().to_uppercase() + ); + let simple = format!("omgcode-01-02-03-004Z-{}.jsonl", id.simple()); + let nil = "omgcode-01-02-03-004Z-00000000-0000-0000-0000-000000000000.jsonl"; + let bad = [ + upper, + simple, + nil.to_owned(), + format!("omgcode-24-02-03-004Z-{id}.jsonl"), + format!("omgcode-01-60-03-004Z-{id}.jsonl"), + format!("omgcode-01-02-60-004Z-{id}.jsonl"), + format!("omgcode-1-02-03-004Z-{id}.jsonl"), + format!("omgcode-01-02-03-4Z-{id}.jsonl"), + format!("omgcode-01-02-03-004-{id}.jsonl"), + format!("omgcode-01-02-03-004-05Z-{id}.jsonl"), + format!("omgcode-+1-02-03-004Z-{id}.jsonl"), + format!("omgcode-01-02-03-004Z-{id}.json"), + format!("omgcode-01-02-03-004Z-{id}.jsonl.bak"), + format!("other-01-02-03-004Z-{id}.jsonl"), + ]; + for name in bad { + assert_eq!(parse_strict(&name), None, "{name}"); + } + } +} diff --git a/crates/omgcode-core/src/session/inspection.rs b/crates/omgcode-core/src/session/inspection.rs new file mode 100644 index 0000000..f716a44 --- /dev/null +++ b/crates/omgcode-core/src/session/inspection.rs @@ -0,0 +1,244 @@ +//! Read-only inspection of one session journal without the writer lock. +//! +//! An inspector never calls `try_lock`, `lock`, or `lock_shared`, so scanning +//! cannot make a writer in another process report `Busy`. It validates the +//! journal with the same replay rules as `SessionJournal::open`, never +//! modifies the file, and never executes or resumes recorded work. Everything +//! it returns is untrusted historical data. + +use std::fs; +use std::path::Path; + +use serde::Serialize; +use time::OffsetDateTime; +use uuid::Uuid; + +use super::{ + CompactionRecord, MessageRole, MessageSource, NativePath, Replayed, SessionError, ToolOutcome, + filename, map_storage_error, read_bounded, replay, +}; +use crate::storage; + +/// A validated, read-only view of one journal. +/// +/// Fields mirror the header facts of `SessionSnapshot` and add event times and +/// the ordered transcript. Nothing here grants authority or starts work. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct SessionInspection { + /// The UUID shared by all events in this journal. + pub session_id: Uuid, + /// Workspace association recorded at creation. Descriptive only. + pub workspace_id: Uuid, + /// Canonical workspace path recorded at creation. Descriptive only. + pub workspace: NativePath, + /// Session title recorded at creation. + pub title: String, + /// Whether the session is archived after the last complete event. + pub archived: bool, + /// The turn left active by the last complete event, if any. Inspecting + /// never resumes it, and a live writer may already have finished it. + pub active_turn: Option, + /// The journal schema version that every event shares. + pub schema_version: u32, + /// Number of complete events, including `session.started`. + pub event_count: u64, + /// Timestamp of the `session.started` event. + #[serde(with = "time::serde::rfc3339")] + pub created_at: OffsetDateTime, + /// Timestamp of the last complete event. + #[serde(with = "time::serde::rfc3339")] + pub updated_at: OffsetDateTime, + /// True when bytes followed the last LF. A writer may be mid-append, so the + /// partial record was ignored. The file was not changed. + pub incomplete_tail: bool, + /// Every event after `session.started`, in journal order. + pub entries: Vec, +} + +/// One validated event after `session.started`. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct TranscriptEntry { + /// Zero-based journal sequence number. Sequence, not time, orders events. + pub seq: u64, + /// The recorded UTC event time. + #[serde(with = "time::serde::rfc3339")] + pub timestamp: OffsetDateTime, + /// The event type and its recorded data. + #[serde(flatten)] + pub kind: TranscriptEntryKind, +} + +/// The recorded data of one event. All text is untrusted. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum TranscriptEntryKind { + /// A user, assistant, or tool message. + Message { + /// The recorded display role. + role: MessageRole, + /// The recorded origin label. + source: MessageSource, + /// The message text, at most 16 KiB. + text: String, + /// Tool call identifier. Present only on tool messages. + #[serde(skip_serializing_if = "Option::is_none")] + call_id: Option, + }, + /// A turn began. + TurnStarted { + /// The turn identifier. + request_id: Uuid, + }, + /// A turn completed. + TurnCompleted { + /// The turn identifier. + request_id: Uuid, + }, + /// A turn failed. Replay requires a code on every failed turn. + TurnFailed { + /// The turn identifier. + request_id: Uuid, + /// The bounded, non-secret failure code. + code: String, + }, + /// The model asked for a tool call. Schema version 2 and later. + ToolRequested { + /// The turn identifier. + request_id: Uuid, + /// Provider call identifier, unique within its turn. + call_id: String, + /// Requested tool name. + tool: String, + /// Exact strict-JSON arguments string, at most 4 KiB. + arguments: String, + }, + /// Core recorded the outcome of a tool call. Schema version 2 and later. + ToolCompleted { + /// The turn identifier. + request_id: Uuid, + /// Provider call identifier. + call_id: String, + /// The core-observed outcome. + outcome: ToolOutcome, + /// Stable error code. Present only when the call failed or was denied. + #[serde(skip_serializing_if = "Option::is_none")] + code: Option, + /// Size in bytes of the rendered output. + output_bytes: u64, + /// Lowercase SHA-256 of the rendered output. + output_sha256: String, + }, + /// The request manifest, reduced to its small descriptive fields. The base + /// prompt and custom instructions are deliberately not included. + RequestManifest { + /// The turn identifier. + request_id: Uuid, + /// The model name used for the request. + model: String, + /// The version label of the compiled base prompt. + prompt_version: String, + /// Tool names advertised to the model. Empty before schema version 2. + tools: Vec, + }, + /// A compaction summary replaced earlier messages. Schema version 3 only. + ContextCompacted { + /// The recorded compaction. Its summary is untrusted model output. + record: CompactionRecord, + }, + /// The session was archived. + SessionArchived, + /// The session was restored from the archive. + SessionRestored, +} + +impl SessionInspection { + /// Inspect the journal at `path` without taking the writer lock. + /// + /// The file is opened read-only without following links, checked with the + /// same platform handle validation as the writer, and read within the + /// journal size bound. Bytes after the last LF are ignored and reported + /// through `incomplete_tail`, because a writer may be mid-append. A journal + /// with no complete record is invalid. The file is never changed. + /// + /// # Errors + /// + /// Returns `SessionError::Busy` when Windows reports that a writer's + /// byte-range lock or a sharing rule blocks the read. The call does not + /// retry. Returns `SessionError::InvalidJournal` or + /// `SessionError::LimitReached` for a journal that fails validation, and + /// `SessionError::Io` for any other operating-system failure. + pub fn inspect(path: &Path) -> Result { + let filename = path + .file_name() + .and_then(|name| name.to_str()) + .ok_or(SessionError::InvalidJournal("filename is not valid UTF-8"))?; + let filename_id = filename::lenient_session_id(filename)?; + let metadata = fs::symlink_metadata(path).map_err(classify_lock_conflict)?; + if metadata.file_type().is_symlink() || !metadata.is_file() { + return Err(SessionError::InvalidJournal( + "journal is not a regular file", + )); + } + let mut file = storage::open_read_only_file(path) + .map_err(|error| classify_lock_conflict(map_storage_error(error)))?; + let contents = read_bounded(&mut file).map_err(classify_lock_conflict)?; + let complete_len = contents + .iter() + .rposition(|byte| *byte == b'\n') + .map(|index| index + 1) + .ok_or(SessionError::InvalidJournal( + "journal has no complete record", + ))?; + let complete = contents + .get(..complete_len) + .ok_or(SessionError::InvalidJournal( + "journal has no complete record", + ))?; + let mut entries = Vec::new(); + let Replayed { + snapshot, + created_at, + updated_at, + .. + } = replay(complete, filename_id, Some(&mut entries))?; + Ok(Self { + session_id: snapshot.session_id, + workspace_id: snapshot.workspace_id, + workspace: snapshot.workspace, + title: snapshot.title, + archived: snapshot.archived, + active_turn: snapshot.active_turn, + schema_version: snapshot.schema_version, + event_count: snapshot.event_count, + created_at, + updated_at, + incomplete_tail: complete_len != contents.len(), + entries, + }) + } +} + +/// Turn a Windows lock or sharing violation into the distinct `Busy` outcome. +/// +/// Raw error 33 is `ERROR_LOCK_VIOLATION` and 32 is `ERROR_SHARING_VIOLATION`. +/// Other platforms and error kinds pass through unchanged. +fn classify_lock_conflict(error: impl Into) -> SessionError { + let error = error.into(); + #[cfg(windows)] + if let SessionError::Io(io_error) = &error + && is_windows_lock_conflict(io_error) + { + return SessionError::Busy; + } + error +} + +#[cfg(windows)] +fn is_windows_lock_conflict(error: &std::io::Error) -> bool { + const ERROR_SHARING_VIOLATION: i32 = 32; + const ERROR_LOCK_VIOLATION: i32 = 33; + matches!( + error.raw_os_error(), + Some(ERROR_SHARING_VIOLATION | ERROR_LOCK_VIOLATION) + ) +} diff --git a/crates/omgcode-core/src/session_index.rs b/crates/omgcode-core/src/session_index.rs new file mode 100644 index 0000000..4b02534 --- /dev/null +++ b/crates/omgcode-core/src/session_index.rs @@ -0,0 +1,220 @@ +//! A derived, rebuildable index over session journals. +//! +//! The JSONL journals stay the only source of truth. This index is a cache that +//! lets a session tree list titles, folders, times, and status without +//! re-reading every journal, and lets the user search transcripts. Losing, +//! deleting, or corrupting the index never loses data: [`SessionIndex::open`] +//! discards an unusable database and the next [`SessionIndex::refresh`] +//! rebuilds it from the journals. The index grants no authority. Every value it +//! returns is untrusted historical data, and a stored path is revalidated +//! before [`SessionIndex::journal_path`] returns it. +//! +//! # Storage +//! +//! The index is one SQLite database, `/session-index-v1/index.sqlite3`, +//! built with the bundled SQLite and its FTS5 extension. It uses the default +//! rollback journal (not WAL) and these settings on every connection: +//! `application_id` [`APPLICATION_ID`], `user_version` 1, `foreign_keys=ON`, +//! `trusted_schema=OFF`, `secure_delete=ON` (the file holds transcript text), +//! a two-second busy timeout, `SQLITE_OPEN_NOFOLLOW`, no URI filenames, no +//! shared cache, and extension loading disabled. All statements are +//! parameterized. A sort order comes from a closed enum that maps to static SQL. +//! The directory and the database file are refused when either is a symbolic +//! link or Windows reparse point ([`IndexError::UnsafeLocation`]). +//! +//! A database that is not SQLite, is corrupt at open, or carries another +//! `application_id` or `user_version` is deleted together with its `-journal` +//! file, and an empty index is created. Nothing outside `session-index-v1/` is +//! touched. The schema is numbered as migration 1; a later migration can be +//! appended to the migration list. +//! +//! # What is indexed +//! +//! Per journal: the title, every message (user, assistant, tool), and a +//! compaction summary, each as one searchable text. Tool-call arguments, request +//! manifests, outcomes, and failure codes are not indexed. Journals are read only +//! through [`SessionInspection::inspect`], which never takes the writer lock. +//! The code points U+E000 and U+E001 are reserved as snippet markers, so they +//! are replaced with U+FFFD before text enters the index. +//! +//! # Concurrency +//! +//! A [`SessionIndex`] owns one connection and is used from one thread at a time +//! (`&mut self` for refresh). Two processes may open the same index; SQLite's +//! own locking arbitrates and contention that outlasts the busy timeout surfaces +//! as [`IndexError::Busy`]. Each transaction covers exactly one journal, and a +//! journal is inspected before its transaction opens, never inside it. +//! +//! # Busy and invalid journals +//! +//! A journal that a writer holds (Windows) keeps its previous metadata and text +//! with state `busy` and is retried on every refresh. A journal that fails +//! validation becomes `invalid` with a stable code, loses its text, and is not +//! inspected again until its size or modification time changes. An operating +//! system failure marks the journal `invalid` with `io_error` and is retried. +//! One bad journal never fails a refresh. + +mod query; +mod refresh; +mod schema; +mod snippet; + +use std::io; +use std::path::{Path, PathBuf}; + +use rusqlite::Connection; +use serde::Serialize; +use thiserror::Error; +use time::OffsetDateTime; +use uuid::Uuid; + +use crate::session::{NativePath, SessionError}; + +pub use query::{ + ArchiveView, SearchHit, SearchListing, SearchRole, SessionListing, SessionQuery, SessionSort, + SnippetPart, +}; +pub use refresh::RefreshReport; + +/// SQLite `application_id` stamped into the database header: the ASCII bytes +/// `OMGI` read as a big-endian integer. A database with another value is not +/// this index and is rebuilt. +pub const APPLICATION_ID: i32 = 0x4f4d_4749; + +/// Directory below the data root that holds the index. The `v1` names the +/// on-disk layout; a different layout would use a new directory. +pub const INDEX_DIRECTORY: &str = "session-index-v1"; + +/// Database file name inside [`INDEX_DIRECTORY`]. +pub const INDEX_FILE: &str = "index.sqlite3"; + +/// A failure while opening, refreshing, or querying the session index. +/// +/// No variant embeds transcript text or an absolute path. +#[derive(Debug, Error)] +pub enum IndexError { + /// Another connection held a conflicting lock past the busy timeout. + #[error("session index is busy")] + Busy, + /// The caller's search text cannot be used. + #[error("invalid search query: {0}")] + InvalidQuery(&'static str), + /// A stored value failed validation. The database is a cache that can be + /// tampered with, so nothing stored is trusted. + #[error("invalid session index entry: {0}")] + InvalidIndexEntry(&'static str), + /// The index directory or database file is a link, a reparse point, or not + /// the expected kind of file. + #[error("unsafe session index location: {0}")] + UnsafeLocation(&'static str), + /// Journal discovery failed. + #[error(transparent)] + Session(#[from] SessionError), + /// A filesystem operation on the index location failed. + #[error("session index I/O failed: {0}")] + Io(#[from] io::Error), + /// SQLite reported any other failure. + #[error("session index database operation failed")] + Sqlite(#[source] rusqlite::Error), +} + +impl From for IndexError { + fn from(error: rusqlite::Error) -> Self { + use rusqlite::ErrorCode; + if let rusqlite::Error::SqliteFailure(failure, _) = &error + && matches!( + failure.code, + ErrorCode::DatabaseBusy | ErrorCode::DatabaseLocked + ) + { + return Self::Busy; + } + Self::Sqlite(error) + } +} + +/// How a journal was last classified by the index. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum IndexedState { + /// Inspected successfully. Metadata and text are current as of the stored + /// size and modification time. + Ok, + /// A writer held the journal at the last attempt. Metadata and text, if any, + /// are from an earlier inspection. + Busy, + /// The journal failed validation or could not be read. It has no text. + Invalid, +} + +/// One session as the index last saw it. Everything here is untrusted +/// historical data and grants no authority. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct IndexedSession { + /// The session UUID taken from the journal file name. + pub session_id: Uuid, + /// How the journal was last classified. + pub state: IndexedState, + /// Stable code and static detail for an `Invalid` journal. + pub invalid_code: Option, + /// Session title, when the journal has been inspected. + pub title: Option, + /// Workspace association recorded at creation. + pub workspace_id: Option, + /// Lossless workspace path recorded at creation. Descriptive only. + pub workspace: Option, + /// Lossy workspace path text for display. Never reopen a path from it. + pub folder_display: Option, + /// Time of the `session.started` event. + #[serde(with = "time::serde::rfc3339::option")] + pub created_at: Option, + /// Time of the last complete event. + #[serde(with = "time::serde::rfc3339::option")] + pub updated_at: Option, + /// Whether the session was archived after its last complete event. `false` + /// when unknown. + pub archived: bool, + /// The turn left active by the last complete event, if any. + pub active_turn: Option, + /// Number of complete events, including `session.started`. + pub event_count: u64, + /// Whether bytes followed the last complete record when inspected. + pub incomplete_tail: bool, +} + +/// A handle to the derived session index. See the module documentation. +#[derive(Debug)] +pub struct SessionIndex { + data_root: PathBuf, + connection: Connection, +} + +impl SessionIndex { + /// Open the index below `data_root`, creating it when absent. + /// + /// `data_root` must come from trusted application settings. The index lives + /// in `/session-index-v1/`. A database that is not SQLite, is + /// corrupt, or has another `application_id` or `user_version` is deleted + /// (only the index's own files) and recreated empty; call + /// [`refresh`](Self::refresh) to repopulate it. + /// + /// # Errors + /// + /// Returns [`IndexError::UnsafeLocation`] when the index directory or file is + /// a link or reparse point or is not the expected kind of object, + /// [`IndexError::Busy`] when another connection holds the database past the + /// busy timeout, [`IndexError::Io`] for filesystem failures, and + /// [`IndexError::Sqlite`] for other database failures. + pub fn open(data_root: &Path) -> Result { + let connection = schema::open_connection(data_root)?; + Ok(Self { + data_root: data_root.to_path_buf(), + connection, + }) + } + + /// The data root this index describes journals for. + pub fn data_root(&self) -> &Path { + &self.data_root + } +} diff --git a/crates/omgcode-core/src/session_index/query.rs b/crates/omgcode-core/src/session_index/query.rs new file mode 100644 index 0000000..41c22fc --- /dev/null +++ b/crates/omgcode-core/src/session_index/query.rs @@ -0,0 +1,486 @@ +//! Listing, lookup, and full-text search over the index. + +use std::path::PathBuf; + +use rusqlite::Row; +use serde::Serialize; +use time::OffsetDateTime; +use uuid::Uuid; + +use super::snippet::{MARK_END, MARK_START, match_expression, parse_snippet}; +use super::{IndexError, IndexedSession, IndexedState, SessionIndex}; +use crate::session::{NativePath, strict_journal_session_id}; + +/// The most sessions one listing returns. +const MAX_LISTING: usize = 5000; +/// The most hits one search returns. +const MAX_HITS: usize = 200; +/// Tokens of context around a match in a snippet. +const SNIPPET_TOKENS: i64 = 24; +/// The code recorded for a session UUID carried by two journal files. +const CODE_DUPLICATE: &str = "duplicate_session_id"; + +/// The columns `IndexedSession` needs, in the order `RawSession::read` expects. +/// Statements alias `journal` as `j`. +macro_rules! session_columns { + () => { + "j.session_id, j.state, j.invalid_code, j.title, j.workspace_id, \ + j.workspace_encoding, j.workspace_units, j.folder_display, j.created_ns, \ + j.updated_ns, j.archived, j.active_turn, j.event_count, j.incomplete_tail" + }; +} + +/// A listing statement with a fixed `ORDER BY`. The order text is a literal at +/// the call site, never caller input. +macro_rules! list_sql { + ($order:literal) => { + concat!( + "SELECT ", + session_columns!(), + " FROM journal j WHERE j.archived = ?1 ORDER BY ", + $order, + " LIMIT ?2" + ) + }; +} + +/// Which sessions a listing or search covers. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ArchiveView { + /// Sessions that are not archived, including those with unknown status + /// because their journal is busy or invalid and was never read. + Active, + /// Archived sessions. + Archived, +} + +impl ArchiveView { + fn archived_flag(self) -> i64 { + match self { + Self::Active => 0, + Self::Archived => 1, + } + } +} + +/// The key a listing sorts by. Rows without a value for the key sort last in +/// either direction, and ties break by session UUID ascending. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum SessionSort { + /// Time of the last complete event. + Updated, + /// Time of the `session.started` event. + Created, + /// Title, compared case-insensitively by Unicode lowercase. + Title, +} + +/// A listing request. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct SessionQuery { + /// Archived or active sessions. + pub view: ArchiveView, + /// The sort key. + pub sort: SessionSort, + /// Sort largest or latest first, or last to first for titles. + pub descending: bool, + /// The most sessions to return, clamped to 1 through 5000. + pub limit: usize, +} + +/// One page of a listing. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct SessionListing { + /// Sessions in the requested order, at most `limit`. + pub sessions: Vec, + /// How many sessions the view holds before `limit` applied. + pub total: u64, +} + +/// What kind of text a search hit matched. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum SearchRole { + /// A user message. + User, + /// An assistant message. + Assistant, + /// A tool result message. + Tool, + /// A context compaction summary. + Summary, + /// The session title. + Title, +} + +/// A run of snippet text, plain or matched. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct SnippetPart { + /// Transcript text. It never contains the reserved marker code points. + pub text: String, + /// Whether the search matched this run. + pub matched: bool, +} + +/// One matching text. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct SearchHit { + /// The session the text belongs to. + pub session: IndexedSession, + /// The journal sequence number, or `None` for a title. + pub seq: Option, + /// What kind of text matched. + pub role: SearchRole, + /// About 24 tokens around the match. + pub snippet: Vec, +} + +/// Search results. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct SearchListing { + /// Hits ordered by relevance, then newest session, then position. + pub hits: Vec, + /// Whether more hits exist than `limit` allowed. + pub truncated: bool, +} + +/// The stored values of one `journal` row before validation. +struct RawSession { + session_id: String, + state: String, + invalid_code: Option, + title: Option, + workspace_id: Option, + workspace_encoding: Option, + workspace_units: Option>, + folder_display: Option, + created_ns: Option, + updated_ns: Option, + archived: i64, + active_turn: Option, + event_count: i64, + incomplete_tail: i64, +} + +impl RawSession { + fn read(row: &Row<'_>) -> rusqlite::Result { + Ok(Self { + session_id: row.get(0)?, + state: row.get(1)?, + invalid_code: row.get(2)?, + title: row.get(3)?, + workspace_id: row.get(4)?, + workspace_encoding: row.get(5)?, + workspace_units: row.get(6)?, + folder_display: row.get(7)?, + created_ns: row.get(8)?, + updated_ns: row.get(9)?, + archived: row.get(10)?, + active_turn: row.get(11)?, + event_count: row.get(12)?, + incomplete_tail: row.get(13)?, + }) + } + + /// Validate every stored value. The database is a cache that may have been + /// altered, so nothing is trusted. + fn into_session(self) -> Result { + let state = match self.state.as_str() { + "ok" => IndexedState::Ok, + "busy" => IndexedState::Busy, + "invalid" => IndexedState::Invalid, + _ => return Err(IndexError::InvalidIndexEntry("unknown journal state")), + }; + Ok(IndexedSession { + session_id: parse_uuid(&self.session_id)?, + state, + invalid_code: self.invalid_code, + title: self.title, + workspace_id: self.workspace_id.as_deref().map(parse_uuid).transpose()?, + workspace: decode_workspace(self.workspace_encoding, self.workspace_units)?, + folder_display: self.folder_display, + created_at: self.created_ns.map(timestamp).transpose()?, + updated_at: self.updated_ns.map(timestamp).transpose()?, + archived: self.archived != 0, + active_turn: self.active_turn.as_deref().map(parse_uuid).transpose()?, + event_count: u64::try_from(self.event_count) + .map_err(|_| IndexError::InvalidIndexEntry("negative event count"))?, + incomplete_tail: self.incomplete_tail != 0, + }) + } +} + +fn parse_uuid(text: &str) -> Result { + Uuid::try_parse(text).map_err(|_| IndexError::InvalidIndexEntry("malformed UUID")) +} + +fn timestamp(nanos: i64) -> Result { + OffsetDateTime::from_unix_timestamp_nanos(i128::from(nanos)) + .map_err(|_| IndexError::InvalidIndexEntry("timestamp out of range")) +} + +fn decode_workspace( + encoding: Option, + units: Option>, +) -> Result, IndexError> { + match (encoding.as_deref(), units) { + (None, None) => Ok(None), + (Some("unix_bytes"), Some(bytes)) => Ok(Some(NativePath::UnixBytes(bytes))), + (Some("windows_utf16"), Some(bytes)) => { + if bytes.len() % 2 != 0 { + return Err(IndexError::InvalidIndexEntry("odd UTF-16 byte count")); + } + let (pairs, _) = bytes.as_chunks::<2>(); + let units = pairs.iter().map(|pair| u16::from_le_bytes(*pair)).collect(); + Ok(Some(NativePath::WindowsUtf16(units))) + } + _ => Err(IndexError::InvalidIndexEntry("malformed workspace path")), + } +} + +impl SessionIndex { + /// List sessions in one view with a fixed, deterministic order. + /// + /// `total` counts the whole view before `limit` (clamped to 1 through 5000) + /// applies. Busy and invalid sessions are listed with their state. + /// + /// # Errors + /// + /// Returns database failures and [`IndexError::InvalidIndexEntry`] when a + /// stored row fails validation. + pub fn sessions(&self, query: &SessionQuery) -> Result { + let sql = match (query.sort, query.descending) { + (SessionSort::Updated, false) => { + list_sql!("j.updated_ns IS NULL, j.updated_ns ASC, j.session_id ASC") + } + (SessionSort::Updated, true) => { + list_sql!("j.updated_ns IS NULL, j.updated_ns DESC, j.session_id ASC") + } + (SessionSort::Created, false) => { + list_sql!("j.created_ns IS NULL, j.created_ns ASC, j.session_id ASC") + } + (SessionSort::Created, true) => { + list_sql!("j.created_ns IS NULL, j.created_ns DESC, j.session_id ASC") + } + (SessionSort::Title, false) => { + list_sql!("j.title_key IS NULL, j.title_key ASC, j.session_id ASC") + } + (SessionSort::Title, true) => { + list_sql!("j.title_key IS NULL, j.title_key DESC, j.session_id ASC") + } + }; + let limit = i64::try_from(query.limit.clamp(1, MAX_LISTING)).unwrap_or(i64::MAX); + let archived = query.view.archived_flag(); + let total: i64 = self.connection.query_row( + "SELECT count(*) FROM journal WHERE archived = ?1", + [archived], + |row| row.get(0), + )?; + let mut statement = self.connection.prepare(sql)?; + let raws = statement + .query_map(rusqlite::params![archived, limit], RawSession::read)? + .collect::, _>>()?; + let sessions = raws + .into_iter() + .map(RawSession::into_session) + .collect::, _>>()?; + Ok(SessionListing { + sessions, + total: u64::try_from(total).unwrap_or(0), + }) + } + + /// Look up one session by UUID. + /// + /// # Errors + /// + /// Returns database failures and [`IndexError::InvalidIndexEntry`]. + pub fn session(&self, session_id: Uuid) -> Result, IndexError> { + let key = session_id.as_hyphenated().to_string(); + let mut statement = self.connection.prepare(concat!( + "SELECT ", + session_columns!(), + " FROM journal j WHERE j.session_id = ?1" + ))?; + let mut rows = statement.query_map([key], RawSession::read)?; + rows.next() + .transpose()? + .map(RawSession::into_session) + .transpose() + } + + /// Resolve a session UUID to its journal path for a later writer open. + /// + /// The database is a cache and could have been altered, so the stored + /// relative path is revalidated before it is joined to the data root: it + /// must be exactly `sessions///
/` where `` is the + /// writer's exact journal name carrying `session_id`. Nothing on the + /// filesystem is touched, and the journal may no longer exist. + /// + /// Returns `None` when the index has no row for the session. + /// + /// # Errors + /// + /// Returns [`IndexError::InvalidIndexEntry`] for a stored path that fails + /// validation, and for a session whose UUID two journal files carry. + pub fn journal_path(&self, session_id: Uuid) -> Result, IndexError> { + let key = session_id.as_hyphenated().to_string(); + let mut statement = self + .connection + .prepare("SELECT relative_path, invalid_code FROM journal WHERE session_id = ?1")?; + let mut rows = statement.query_map([key], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, Option>(1)?)) + })?; + let Some(row) = rows.next().transpose()? else { + return Ok(None); + }; + let (relative_path, invalid_code) = row; + if invalid_code.as_deref() == Some(CODE_DUPLICATE) { + return Err(IndexError::InvalidIndexEntry( + "more than one journal has this session UUID", + )); + } + let mut path = self.data_root.clone(); + for part in validated_components(&relative_path, session_id)? { + path.push(part); + } + Ok(Some(path)) + } + + /// Search transcripts for `text`. + /// + /// The text is never FTS5 syntax. Whitespace-separated terms (at most 16, + /// at most 256 characters in all) must all match, case- and + /// diacritic-insensitively, and the last term also matches as a prefix. + /// Only `ok` and `busy` sessions in `view` can match. `limit` is clamped to + /// 1 through 200. Results order by relevance, then most recently updated + /// session, then session and position. + /// + /// # Errors + /// + /// Returns [`IndexError::InvalidQuery`] for unusable text, database + /// failures, and [`IndexError::InvalidIndexEntry`]. + pub fn search( + &self, + text: &str, + view: ArchiveView, + limit: usize, + ) -> Result { + let expression = match_expression(text)?; + let limit = limit.clamp(1, MAX_HITS); + let fetch = i64::try_from(limit + 1).unwrap_or(i64::MAX); + let mut statement = self.connection.prepare(concat!( + "SELECT ", + session_columns!(), + ", entry_text.seq, entry_text.role, snippet(entry_text, 0, ?4, ?5, '', ?6) \ + FROM entry_text JOIN journal j ON j.session_id = entry_text.session_id \ + WHERE entry_text MATCH ?1 AND j.state IN ('ok', 'busy') AND j.archived = ?2 \ + ORDER BY rank, j.updated_ns DESC, j.session_id ASC, entry_text.seq ASC \ + LIMIT ?3" + ))?; + let start = MARK_START.to_string(); + let end = MARK_END.to_string(); + let raws = statement + .query_map( + rusqlite::params![ + expression, + view.archived_flag(), + fetch, + start, + end, + SNIPPET_TOKENS + ], + |row| { + Ok(( + RawSession::read(row)?, + row.get::<_, Option>(14)?, + row.get::<_, String>(15)?, + row.get::<_, String>(16)?, + )) + }, + )? + .collect::, _>>()?; + let mut hits = Vec::new(); + for (raw, seq, role, marked) in raws { + hits.push(SearchHit { + session: raw.into_session()?, + seq: seq + .map(u64::try_from) + .transpose() + .map_err(|_| IndexError::InvalidIndexEntry("negative sequence number"))?, + role: parse_role(&role)?, + snippet: parse_snippet(&marked), + }); + } + let truncated = hits.len() > limit; + hits.truncate(limit); + Ok(SearchListing { hits, truncated }) + } +} + +fn parse_role(role: &str) -> Result { + match role { + "user" => Ok(SearchRole::User), + "assistant" => Ok(SearchRole::Assistant), + "tool" => Ok(SearchRole::Tool), + "summary" => Ok(SearchRole::Summary), + "title" => Ok(SearchRole::Title), + _ => Err(IndexError::InvalidIndexEntry("unknown text role")), + } +} + +/// Check a stored relative path against the exact layout the writer produces +/// and return its components. +fn validated_components(relative: &str, session_id: Uuid) -> Result, IndexError> { + const INVALID: IndexError = IndexError::InvalidIndexEntry("stored journal path is not valid"); + if relative.contains(['\\', '\0']) { + return Err(INVALID); + } + let parts: Vec<&str> = relative.split('/').collect(); + let [sessions, year, month, day, file] = parts.as_slice() else { + return Err(INVALID); + }; + let layout_ok = *sessions == "sessions" + && has_ascii_digits(year, 4) + && has_ascii_digits(month, 2) + && has_ascii_digits(day, 2); + if !layout_ok || strict_journal_session_id(file) != Some(session_id) { + return Err(INVALID); + } + Ok(parts) +} + +fn has_ascii_digits(text: &str, width: usize) -> bool { + text.len() == width && text.bytes().all(|byte| byte.is_ascii_digit()) +} + +#[cfg(test)] +mod tests { + use super::validated_components; + use uuid::Uuid; + + #[test] + fn only_the_exact_writer_layout_for_the_same_session_validates() { + let id = Uuid::new_v4(); + let other = Uuid::new_v4(); + let good = format!("sessions/2026/11/16/omgcode-01-02-03-004Z-{id}.jsonl"); + assert_eq!(validated_components(&good, id).expect("valid").len(), 5); + let bad = [ + "../../evil.jsonl".to_owned(), + format!("/sessions/2026/11/16/omgcode-01-02-03-004Z-{id}.jsonl"), + format!("sessions\\2026\\11\\16\\omgcode-01-02-03-004Z-{id}.jsonl"), + format!("sessions/2026/11/16/omgcode-01-02-03-004Z-{other}.jsonl"), + format!("sessions/2026/11/16/extra/omgcode-01-02-03-004Z-{id}.jsonl"), + format!("sessions/2026/11/../16/omgcode-01-02-03-004Z-{id}.jsonl"), + format!("sessions/26/11/16/omgcode-01-02-03-004Z-{id}.jsonl"), + format!("sessions/2026/11/16/omgcode-01-02-03-004Z-{id}.jsonl\0"), + format!("other/2026/11/16/omgcode-01-02-03-004Z-{id}.jsonl"), + String::new(), + ]; + for path in bad { + assert!(validated_components(&path, id).is_err(), "{path:?}"); + } + } +} diff --git a/crates/omgcode-core/src/session_index/refresh.rs b/crates/omgcode-core/src/session_index/refresh.rs new file mode 100644 index 0000000..39e9100 --- /dev/null +++ b/crates/omgcode-core/src/session_index/refresh.rs @@ -0,0 +1,691 @@ +//! Incremental, bounded refresh of the index from the journals. +//! +//! A refresh inspects at most a caller-chosen number of journals, one at a time, +//! with no database transaction open. It then writes each result in its own +//! short transaction. Journals are opened only through +//! `SessionInspection::inspect`, which never takes the writer lock. + +use std::collections::{HashMap, HashSet}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use rusqlite::{Connection, OptionalExtension, TransactionBehavior, named_params}; +use serde::Serialize; +use time::OffsetDateTime; +use uuid::Uuid; + +use super::snippet::sanitize_text; +use super::{IndexError, IndexedSession, SessionIndex}; +use crate::session::{ + self, DiscoveredJournal, MessageRole, NativePath, SessionError, SessionInspection, + TranscriptEntryKind, +}; + +/// The most journals one refresh call inspects, however large the request. +const MAX_JOURNALS_PER_REFRESH: usize = 1000; + +/// Stable code for a session UUID that two journal files carry. +const CODE_DUPLICATE: &str = "duplicate_session_id"; +/// Stable code for an operating-system failure. The journal is retried. +const CODE_IO: &str = "io_error"; + +/// What one `refresh` call did. Counts of `busy` and `invalid` cover only the +/// journals this call inspected or reclassified. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)] +pub struct RefreshReport { + /// Journals found by discovery. + pub discovered: u64, + /// Journals this call opened for inspection. + pub inspected: u64, + /// Journals skipped because size, modification time, and path match a + /// settled row. + pub unchanged: u64, + /// Journals this call found held by a writer. + pub busy: u64, + /// Journals this call classified as invalid, including duplicates. + pub invalid: u64, + /// Rows removed because their journal is no longer discovered. + pub removed: u64, + /// Journals that need inspection but exceeded this call's budget. Call + /// again to continue. + pub remaining: u64, + /// Links and reparse points that discovery skipped. + pub skipped_links: u64, + /// Entries that did not match the journal layout. + pub unrecognized: u64, +} + +/// The facts a stored row contributes to the unchanged check. +struct Existing { + relative_path: String, + size: i64, + modified_ns: i64, + state: String, + invalid_code: Option, +} + +impl Existing { + /// A row is settled when nothing about the file changed and the last result + /// will not change without the file changing. + fn is_settled_for(&self, journal: &DiscoveredJournal, relative_path: &str) -> bool { + let same_file = self.relative_path == relative_path + && self.size == size_value(journal.size) + && self.modified_ns == modified_value(journal.modified); + if !same_file { + return false; + } + match self.state.as_str() { + "ok" => true, + "invalid" => !matches!( + self.invalid_code.as_deref(), + Some(CODE_IO | CODE_DUPLICATE) | None + ), + _ => false, + } + } + + fn is_settled_duplicate(&self, journal: &DiscoveredJournal, relative_path: &str) -> bool { + self.state == "invalid" + && self.invalid_code.as_deref() == Some(CODE_DUPLICATE) + && self.relative_path == relative_path + && self.size == size_value(journal.size) + && self.modified_ns == modified_value(journal.modified) + } +} + +/// The result of inspecting one journal, ready to store. +enum Outcome { + Indexed(Box), + Busy, + Invalid { + code: String, + /// Whether to record size and modification time so the journal is not + /// inspected again until it changes. + record_stat: bool, + }, +} + +/// Metadata and searchable texts of an inspected journal. +struct Indexed { + metadata: Metadata, + rows: Vec, +} + +struct Metadata { + title: String, + title_key: String, + workspace_id: String, + workspace_encoding: &'static str, + workspace_units: Vec, + folder_display: String, + created_ns: i64, + updated_ns: i64, + archived: bool, + active_turn: Option, + event_count: i64, + schema_version: i64, + incomplete_tail: bool, +} + +struct TextRow { + text: String, + seq: Option, + role: &'static str, +} + +/// The values for one `journal` row. `metadata` is `None` for busy or invalid. +struct JournalRow<'a> { + session_id: &'a str, + relative_path: &'a str, + size: i64, + modified_ns: i64, + state: &'static str, + invalid_code: Option<&'a str>, + metadata: Option<&'a Metadata>, + fts: Option<(i64, i64)>, +} + +impl SessionIndex { + /// Bring the index up to date with the journals on disk. + /// + /// Discovers journals, removes rows for vanished ones, then inspects at most + /// `max_journals` (clamped to 1 through 1000) whose size, modification time, + /// or path changed, or whose last result was `busy` or an operating-system + /// failure. Journals left over are counted in `remaining`; call again until + /// it is zero. A journal held by a writer keeps its earlier data with state + /// `busy`. An invalid journal is recorded and not re-inspected until it + /// changes. Two files carrying one session UUID make that session invalid + /// with `duplicate_session_id` and neither file's text is indexed. + /// + /// # Errors + /// + /// Returns discovery failures as [`IndexError::Session`], and database + /// failures, including [`IndexError::Busy`]. A failure in one journal is + /// recorded for that journal and never fails the refresh. Work committed + /// before an error stays committed. + pub fn refresh(&mut self, max_journals: usize) -> Result { + let budget = max_journals.clamp(1, MAX_JOURNALS_PER_REFRESH); + let discovery = session::discover(&self.data_root)?; + let mut report = RefreshReport { + discovered: count(discovery.journals.len()), + skipped_links: discovery.skipped_links, + unrecognized: discovery.unrecognized, + ..RefreshReport::default() + }; + let existing = load_existing(&self.connection)?; + + let present: HashSet = discovery + .journals + .iter() + .map(|journal| journal.session_id) + .collect(); + for key in existing.keys() { + let still_present = Uuid::try_parse(key).is_ok_and(|id| present.contains(&id)); + if !still_present { + remove_session(&mut self.connection, key)?; + report.removed += 1; + } + } + + let mut copies: HashMap = HashMap::new(); + for journal in &discovery.journals { + *copies.entry(journal.session_id).or_default() += 1; + } + let mut handled_duplicates: HashSet = HashSet::new(); + for journal in &discovery.journals { + let relative = relative_text(journal)?; + let key = journal.session_id.as_hyphenated().to_string(); + let row = existing.get(&key); + if copies.get(&journal.session_id).copied().unwrap_or(0) > 1 { + if !handled_duplicates.insert(journal.session_id) { + continue; + } + if row.is_some_and(|row| row.is_settled_duplicate(journal, &relative)) { + report.unchanged += 1; + } else { + self.record_duplicate(journal, &relative)?; + report.invalid += 1; + } + continue; + } + if row.is_some_and(|row| row.is_settled_for(journal, &relative)) { + report.unchanged += 1; + } else if report.inspected >= count(budget) { + report.remaining += 1; + } else { + report.inspected += 1; + match self.index_journal(journal, &relative, row)? { + IndexedAs::Ok => {} + IndexedAs::Busy => report.busy += 1, + IndexedAs::Invalid => report.invalid += 1, + } + } + } + Ok(report) + } + + /// Re-inspect exactly one session now, whatever its size and modification + /// time. Use it right after the application's own writer closes a journal. + /// + /// Returns `None` when no journal has `session_id`, and removes a stale row. + /// A journal held by a writer yields its row with state `busy`. + /// + /// # Errors + /// + /// Returns the same errors as [`refresh`](Self::refresh). + pub fn refresh_session( + &mut self, + session_id: Uuid, + ) -> Result, IndexError> { + let discovery = session::discover(&self.data_root)?; + let matches: Vec<&DiscoveredJournal> = discovery + .journals + .iter() + .filter(|journal| journal.session_id == session_id) + .collect(); + let key = session_id.as_hyphenated().to_string(); + let existing = load_existing_one(&self.connection, &key)?; + match matches.as_slice() { + [] => { + remove_session(&mut self.connection, &key)?; + return Ok(None); + } + [journal] => { + let relative = relative_text(journal)?; + self.index_journal(journal, &relative, existing.as_ref())?; + } + [first, ..] => { + let relative = relative_text(first)?; + self.record_duplicate(first, &relative)?; + } + } + self.session(session_id) + } + + /// Inspect `journal` with no transaction open, then store the result. + fn index_journal( + &mut self, + journal: &DiscoveredJournal, + relative: &str, + existing: Option<&Existing>, + ) -> Result { + let outcome = inspect(journal); + let key = journal.session_id.as_hyphenated().to_string(); + let transaction = self + .connection + .transaction_with_behavior(TransactionBehavior::Immediate)?; + clear_path_conflicts(&transaction, &key, relative)?; + let size = size_value(journal.size); + let modified_ns = modified_value(journal.modified); + let stored = match outcome { + Outcome::Indexed(indexed) => { + delete_text(&transaction, &key)?; + let fts = insert_text(&transaction, &key, &indexed.rows)?; + write_row( + &transaction, + &JournalRow { + session_id: &key, + relative_path: relative, + size, + modified_ns, + state: "ok", + invalid_code: None, + metadata: Some(&indexed.metadata), + fts, + }, + )?; + IndexedAs::Ok + } + Outcome::Busy => { + // Keep earlier metadata and text, and keep the old size and + // time so the next refresh retries. + let changed = transaction.execute( + "UPDATE journal SET state = 'busy', invalid_code = NULL, relative_path = ?2 \ + WHERE session_id = ?1", + rusqlite::params![key, relative], + )?; + if changed == 0 { + write_row( + &transaction, + &JournalRow { + session_id: &key, + relative_path: relative, + size: 0, + modified_ns: 0, + state: "busy", + invalid_code: None, + metadata: None, + fts: None, + }, + )?; + } + IndexedAs::Busy + } + Outcome::Invalid { code, record_stat } => { + delete_text(&transaction, &key)?; + let (size, modified_ns) = if record_stat { + (size, modified_ns) + } else { + existing.map_or((0, 0), |row| (row.size, row.modified_ns)) + }; + write_row( + &transaction, + &JournalRow { + session_id: &key, + relative_path: relative, + size, + modified_ns, + state: "invalid", + invalid_code: Some(&code), + metadata: None, + fts: None, + }, + )?; + IndexedAs::Invalid + } + }; + transaction.commit()?; + Ok(stored) + } + + /// Mark a session invalid because two files carry its UUID. Neither file is + /// inspected and no text stays indexed. + fn record_duplicate( + &mut self, + first: &DiscoveredJournal, + relative: &str, + ) -> Result<(), IndexError> { + let key = first.session_id.as_hyphenated().to_string(); + let transaction = self + .connection + .transaction_with_behavior(TransactionBehavior::Immediate)?; + clear_path_conflicts(&transaction, &key, relative)?; + delete_text(&transaction, &key)?; + write_row( + &transaction, + &JournalRow { + session_id: &key, + relative_path: relative, + size: size_value(first.size), + modified_ns: modified_value(first.modified), + state: "invalid", + invalid_code: Some(CODE_DUPLICATE), + metadata: None, + fts: None, + }, + )?; + transaction.commit()?; + Ok(()) + } +} + +/// How a stored journal ended up, for the report. +enum IndexedAs { + Ok, + Busy, + Invalid, +} + +/// Inspect one journal and turn the result into a storable outcome. No error +/// from one journal escapes: it becomes an outcome for that journal. +fn inspect(journal: &DiscoveredJournal) -> Outcome { + match SessionInspection::inspect(&journal.path) { + Ok(inspection) => { + if inspection.session_id != journal.session_id { + return Outcome::Invalid { + code: "session_id_mismatch".to_owned(), + record_stat: true, + }; + } + match build_indexed(&inspection) { + Some(indexed) => Outcome::Indexed(Box::new(indexed)), + None => Outcome::Invalid { + code: "timestamp_out_of_range".to_owned(), + record_stat: true, + }, + } + } + Err(SessionError::Busy) => Outcome::Busy, + Err(SessionError::InvalidJournal(detail)) => Outcome::Invalid { + code: format!("invalid_journal: {detail}"), + record_stat: true, + }, + Err(SessionError::LimitReached) => Outcome::Invalid { + code: "limit_reached".to_owned(), + record_stat: true, + }, + Err(_) => Outcome::Invalid { + code: CODE_IO.to_owned(), + record_stat: false, + }, + } +} + +/// Reduce an inspection to the stored metadata and searchable texts. Returns +/// `None` when a timestamp does not fit the stored integer. +fn build_indexed(inspection: &SessionInspection) -> Option { + let (workspace_encoding, workspace_units) = encode_workspace(&inspection.workspace); + let folder_display = inspection + .workspace + .to_path_buf() + .map(|path| path.to_string_lossy().into_owned()) + .unwrap_or_default(); + let title = sanitize_text(&inspection.title); + let metadata = Metadata { + title_key: title.to_lowercase(), + title, + workspace_id: inspection.workspace_id.as_hyphenated().to_string(), + workspace_encoding, + workspace_units, + folder_display, + created_ns: nanos(inspection.created_at)?, + updated_ns: nanos(inspection.updated_at)?, + archived: inspection.archived, + active_turn: inspection + .active_turn + .map(|turn| turn.as_hyphenated().to_string()), + event_count: i64::try_from(inspection.event_count).ok()?, + schema_version: i64::from(inspection.schema_version), + incomplete_tail: inspection.incomplete_tail, + }; + let mut rows = Vec::new(); + if !inspection.title.is_empty() { + rows.push(TextRow { + text: sanitize_text(&inspection.title), + seq: None, + role: "title", + }); + } + for entry in &inspection.entries { + let seq = i64::try_from(entry.seq).ok(); + match &entry.kind { + TranscriptEntryKind::Message { role, text, .. } => rows.push(TextRow { + text: sanitize_text(text), + seq, + role: match role { + MessageRole::User => "user", + MessageRole::Assistant => "assistant", + MessageRole::Tool => "tool", + }, + }), + TranscriptEntryKind::ContextCompacted { record } => rows.push(TextRow { + text: sanitize_text(&record.summary), + seq, + role: "summary", + }), + _ => {} + } + } + Some(Indexed { metadata, rows }) +} + +/// Store a workspace path as an encoding tag and unit bytes that round-trip. +fn encode_workspace(workspace: &NativePath) -> (&'static str, Vec) { + match workspace { + NativePath::UnixBytes(bytes) => ("unix_bytes", bytes.clone()), + NativePath::WindowsUtf16(units) => ( + "windows_utf16", + units.iter().flat_map(|unit| unit.to_le_bytes()).collect(), + ), + } +} + +fn nanos(time: OffsetDateTime) -> Option { + i64::try_from(time.unix_timestamp_nanos()).ok() +} + +fn count(value: usize) -> u64 { + u64::try_from(value).unwrap_or(u64::MAX) +} + +fn size_value(size: u64) -> i64 { + i64::try_from(size).unwrap_or(i64::MAX) +} + +fn modified_value(modified: SystemTime) -> i64 { + match modified.duration_since(UNIX_EPOCH) { + Ok(after) => i64::try_from(after.as_nanos()).unwrap_or(i64::MAX), + Err(before) => i64::try_from(before.duration().as_nanos()) + .map(|nanos| -nanos) + .unwrap_or(i64::MIN), + } +} + +/// The forward-slash form of the journal's path below the data root. +fn relative_text(journal: &DiscoveredJournal) -> Result { + let mut text = String::new(); + for component in journal.relative_path.components() { + let part = component + .as_os_str() + .to_str() + .ok_or(IndexError::InvalidIndexEntry("journal path is not UTF-8"))?; + if !text.is_empty() { + text.push('/'); + } + text.push_str(part); + } + Ok(text) +} + +fn load_existing(connection: &Connection) -> Result, IndexError> { + let mut statement = connection.prepare( + "SELECT session_id, relative_path, size, modified_ns, state, invalid_code FROM journal", + )?; + let rows = statement.query_map([], |row| { + Ok(( + row.get::<_, String>(0)?, + Existing { + relative_path: row.get(1)?, + size: row.get(2)?, + modified_ns: row.get(3)?, + state: row.get(4)?, + invalid_code: row.get(5)?, + }, + )) + })?; + let mut map = HashMap::new(); + for row in rows { + let (key, existing) = row?; + map.insert(key, existing); + } + Ok(map) +} + +fn load_existing_one(connection: &Connection, key: &str) -> Result, IndexError> { + Ok(connection + .query_row( + "SELECT relative_path, size, modified_ns, state, invalid_code FROM journal \ + WHERE session_id = ?1", + [key], + |row| { + Ok(Existing { + relative_path: row.get(0)?, + size: row.get(1)?, + modified_ns: row.get(2)?, + state: row.get(3)?, + invalid_code: row.get(4)?, + }) + }, + ) + .optional()?) +} + +/// Remove a session's row and text in one transaction. +fn remove_session(connection: &mut Connection, key: &str) -> Result<(), IndexError> { + let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?; + delete_text(&transaction, key)?; + transaction.execute("DELETE FROM journal WHERE session_id = ?1", [key])?; + transaction.commit()?; + Ok(()) +} + +/// Delete another session's row that claims `relative_path`. A name carries its +/// own UUID, so this only happens when the stored rows were altered. +fn clear_path_conflicts( + connection: &Connection, + key: &str, + relative_path: &str, +) -> Result<(), IndexError> { + let mut statement = connection + .prepare("SELECT session_id FROM journal WHERE relative_path = ?1 AND session_id <> ?2")?; + let others = statement + .query_map([relative_path, key], |row| row.get::<_, String>(0))? + .collect::, _>>()?; + for other in others { + delete_text(connection, &other)?; + connection.execute("DELETE FROM journal WHERE session_id = ?1", [other])?; + } + Ok(()) +} + +/// Delete the session's `entry_text` rows by the rowid range its row records. +/// The session filter keeps an altered range from deleting another session's +/// text. +fn delete_text(connection: &Connection, key: &str) -> Result<(), IndexError> { + let range: Option<(Option, Option)> = connection + .query_row( + "SELECT fts_first, fts_last FROM journal WHERE session_id = ?1", + [key], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional()?; + if let Some((Some(first), Some(last))) = range { + connection.execute( + "DELETE FROM entry_text WHERE rowid BETWEEN ?1 AND ?2 AND session_id = ?3", + rusqlite::params![first, last, key], + )?; + } + Ok(()) +} + +/// Insert searchable texts. Inside the write transaction the rowids are +/// assigned in increasing order, so the first and last bound all of them. +fn insert_text( + connection: &Connection, + key: &str, + rows: &[TextRow], +) -> Result, IndexError> { + let mut statement = connection + .prepare("INSERT INTO entry_text (text, session_id, seq, role) VALUES (?1, ?2, ?3, ?4)")?; + let mut bounds: Option<(i64, i64)> = None; + for row in rows { + statement.execute(rusqlite::params![row.text, key, row.seq, row.role])?; + let rowid = connection.last_insert_rowid(); + bounds = Some(bounds.map_or((rowid, rowid), |(first, _)| (first, rowid))); + } + Ok(bounds) +} + +/// Insert or replace the `journal` row for one session. +fn write_row(connection: &Connection, row: &JournalRow<'_>) -> Result<(), IndexError> { + let metadata = row.metadata; + let (first, last) = row.fts.unzip(); + connection.execute( + "INSERT INTO journal ( + session_id, relative_path, size, modified_ns, state, invalid_code, + title, title_key, workspace_id, workspace_encoding, workspace_units, + folder_display, created_ns, updated_ns, archived, active_turn, + event_count, schema_version, incomplete_tail, fts_first, fts_last + ) VALUES ( + :session_id, :relative_path, :size, :modified_ns, :state, :invalid_code, + :title, :title_key, :workspace_id, :workspace_encoding, :workspace_units, + :folder_display, :created_ns, :updated_ns, :archived, :active_turn, + :event_count, :schema_version, :incomplete_tail, :fts_first, :fts_last + ) ON CONFLICT (session_id) DO UPDATE SET + relative_path = excluded.relative_path, size = excluded.size, + modified_ns = excluded.modified_ns, state = excluded.state, + invalid_code = excluded.invalid_code, title = excluded.title, + title_key = excluded.title_key, workspace_id = excluded.workspace_id, + workspace_encoding = excluded.workspace_encoding, + workspace_units = excluded.workspace_units, + folder_display = excluded.folder_display, created_ns = excluded.created_ns, + updated_ns = excluded.updated_ns, archived = excluded.archived, + active_turn = excluded.active_turn, event_count = excluded.event_count, + schema_version = excluded.schema_version, + incomplete_tail = excluded.incomplete_tail, + fts_first = excluded.fts_first, fts_last = excluded.fts_last", + named_params! { + ":session_id": row.session_id, + ":relative_path": row.relative_path, + ":size": row.size, + ":modified_ns": row.modified_ns, + ":state": row.state, + ":invalid_code": row.invalid_code, + ":title": metadata.map(|m| m.title.as_str()), + ":title_key": metadata.map(|m| m.title_key.as_str()), + ":workspace_id": metadata.map(|m| m.workspace_id.as_str()), + ":workspace_encoding": metadata.map(|m| m.workspace_encoding), + ":workspace_units": metadata.map(|m| m.workspace_units.as_slice()), + ":folder_display": metadata.map(|m| m.folder_display.as_str()), + ":created_ns": metadata.map(|m| m.created_ns), + ":updated_ns": metadata.map(|m| m.updated_ns), + ":archived": metadata.is_some_and(|m| m.archived), + ":active_turn": metadata.and_then(|m| m.active_turn.as_deref()), + ":event_count": metadata.map_or(0, |m| m.event_count), + ":schema_version": metadata.map(|m| m.schema_version), + ":incomplete_tail": metadata.is_some_and(|m| m.incomplete_tail), + ":fts_first": first, + ":fts_last": last, + }, + )?; + Ok(()) +} diff --git a/crates/omgcode-core/src/session_index/schema.rs b/crates/omgcode-core/src/session_index/schema.rs new file mode 100644 index 0000000..c16ae55 --- /dev/null +++ b/crates/omgcode-core/src/session_index/schema.rs @@ -0,0 +1,285 @@ +//! Opening the database, its pragmas, and its numbered migrations. + +use std::fs; +use std::io; +use std::path::Path; +use std::time::Duration; + +use rusqlite::config::DbConfig; +use rusqlite::{Connection, ErrorCode, OpenFlags, TransactionBehavior}; + +use super::{APPLICATION_ID, INDEX_DIRECTORY, INDEX_FILE, IndexError}; +use crate::storage::{self, StorageError}; + +/// How long a statement waits for another connection's lock. +const BUSY_TIMEOUT: Duration = Duration::from_secs(2); + +/// Migration 1: the first schema. Append later migrations to `MIGRATIONS`; +/// never edit an applied one. The index is a cache, so a version that is not +/// in `1..=MIGRATIONS.len()` is rebuilt rather than migrated. +/// +/// Times are UTC nanoseconds since the Unix epoch so they sort numerically. +/// `workspace_units` holds `NativePath` units: raw bytes for `unix_bytes`, or +/// little-endian UTF-16 code units for `windows_utf16`. `fts_first` and +/// `fts_last` bound the `entry_text` rowids written for the journal so they can +/// be deleted by range instead of by scanning the full-text table. +pub(super) const MIGRATION_1: &str = " +CREATE TABLE journal ( + session_id TEXT NOT NULL PRIMARY KEY, + relative_path TEXT NOT NULL UNIQUE, + size INTEGER NOT NULL, + modified_ns INTEGER NOT NULL, + state TEXT NOT NULL CHECK (state IN ('ok', 'busy', 'invalid')), + invalid_code TEXT, + title TEXT, + title_key TEXT, + workspace_id TEXT, + workspace_encoding TEXT CHECK (workspace_encoding IN ('unix_bytes', 'windows_utf16')), + workspace_units BLOB, + folder_display TEXT, + created_ns INTEGER, + updated_ns INTEGER, + archived INTEGER NOT NULL DEFAULT 0 CHECK (archived IN (0, 1)), + active_turn TEXT, + event_count INTEGER NOT NULL DEFAULT 0, + schema_version INTEGER, + incomplete_tail INTEGER NOT NULL DEFAULT 0 CHECK (incomplete_tail IN (0, 1)), + fts_first INTEGER, + fts_last INTEGER +) STRICT; +CREATE INDEX journal_archived_updated ON journal (archived, updated_ns); +CREATE VIRTUAL TABLE entry_text USING fts5( + text, + session_id UNINDEXED, + seq UNINDEXED, + role UNINDEXED, + tokenize = 'unicode61 remove_diacritics 2' +); +"; + +/// Ordered migrations. Migration `n` is `MIGRATIONS[n - 1]`. +const MIGRATIONS: [&str; 1] = [MIGRATION_1]; + +/// The `user_version` after every migration has run. +const SCHEMA_VERSION: i64 = 1; +const _: () = assert!( + MIGRATIONS.len() == 1, + "update SCHEMA_VERSION with MIGRATIONS" +); + +/// What opening one database file found. +enum Opened { + Ready(Connection), + /// The file is not a usable index of this version. It is a cache, so the + /// caller deletes it and starts again. + Rebuild, +} + +/// Open or create the index database below `data_root`. +pub(super) fn open_connection(data_root: &Path) -> Result { + let directory = data_root.join(INDEX_DIRECTORY); + check_location(&directory, LocationKind::Directory)?; + storage::create_private_directories(&directory).map_err(storage_error)?; + check_location(&directory, LocationKind::Directory)?; + let database = std::path::absolute(directory.join(INDEX_FILE))?; + if database + .to_str() + .is_some_and(|text| text.starts_with("file:")) + { + // The bundled SQLite is built with URI filenames on by default. An + // absolute native path never starts this way, but refuse it anyway. + return Err(IndexError::UnsafeLocation( + "index path looks like a URI filename", + )); + } + check_location(&database, LocationKind::File)?; + match try_open(&database)? { + Opened::Ready(connection) => Ok(connection), + Opened::Rebuild => { + remove_index_files(&directory)?; + check_location(&database, LocationKind::File)?; + match try_open(&database)? { + Opened::Ready(connection) => Ok(connection), + Opened::Rebuild => Err(IndexError::InvalidIndexEntry( + "a newly created index failed validation", + )), + } + } + } +} + +#[derive(Clone, Copy)] +enum LocationKind { + Directory, + File, +} + +/// Refuse a link, a reparse point, or an object of the wrong kind. A missing +/// object is fine. A race between this check and the open is not excluded: the +/// data root must be trusted, and `SQLITE_OPEN_NOFOLLOW` covers the final +/// component on platforms that honor it. +fn check_location(path: &Path, kind: LocationKind) -> Result<(), IndexError> { + let metadata = match fs::symlink_metadata(path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error.into()), + }; + if metadata.file_type().is_symlink() || is_reparse_point(&metadata) { + return Err(IndexError::UnsafeLocation( + "index location is a link or reparse point", + )); + } + let expected = match kind { + LocationKind::Directory => metadata.is_dir(), + LocationKind::File => metadata.is_file(), + }; + if expected { + Ok(()) + } else { + Err(IndexError::UnsafeLocation( + "index location is not the expected kind of file", + )) + } +} + +#[cfg(windows)] +fn is_reparse_point(metadata: &fs::Metadata) -> bool { + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0400; + metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 +} + +#[cfg(not(windows))] +fn is_reparse_point(_metadata: &fs::Metadata) -> bool { + false +} + +fn storage_error(error: StorageError) -> IndexError { + match error { + StorageError::Io(error) => IndexError::Io(error), + StorageError::Invalid(detail) => IndexError::UnsafeLocation(detail), + StorageError::Busy => IndexError::Busy, + } +} + +/// Delete only the index's own database and rollback-journal files. +fn remove_index_files(directory: &Path) -> Result<(), IndexError> { + for name in [INDEX_FILE, "index.sqlite3-journal"] { + match fs::remove_file(directory.join(name)) { + Ok(()) => {} + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error.into()), + } + } + Ok(()) +} + +fn is_unusable_database(error: &rusqlite::Error) -> bool { + matches!( + error, + rusqlite::Error::SqliteFailure(failure, _) + if matches!(failure.code, ErrorCode::NotADatabase | ErrorCode::DatabaseCorrupt) + ) +} + +/// Open `database` with the fixed flags and settings and validate its header. +fn try_open(database: &Path) -> Result { + // No URI flag and no shared cache. NO_MUTEX because a connection is used by + // one thread at a time. + let flags = OpenFlags::SQLITE_OPEN_READ_WRITE + | OpenFlags::SQLITE_OPEN_CREATE + | OpenFlags::SQLITE_OPEN_NOFOLLOW + | OpenFlags::SQLITE_OPEN_NO_MUTEX; + let mut connection = match Connection::open_with_flags(database, flags) { + Ok(connection) => connection, + Err(error) if is_unusable_database(&error) => return Ok(Opened::Rebuild), + Err(error) => return Err(error.into()), + }; + match prepare(&mut connection) { + Ok(true) => Ok(Opened::Ready(connection)), + Ok(false) => Ok(Opened::Rebuild), + Err(error) if is_unusable_database(&error) => Ok(Opened::Rebuild), + Err(error) => Err(error.into()), + } +} + +/// Apply connection settings, then validate or initialize the schema. Returns +/// `false` when the file is not a usable index. +fn prepare(connection: &mut Connection) -> rusqlite::Result { + connection.busy_timeout(BUSY_TIMEOUT)?; + connection.set_db_config(DbConfig::SQLITE_DBCONFIG_TRUSTED_SCHEMA, false)?; + connection.set_db_config(DbConfig::SQLITE_DBCONFIG_DEFENSIVE, true)?; + connection.set_db_config(DbConfig::SQLITE_DBCONFIG_ENABLE_FKEY, true)?; + connection.pragma_update(None, "secure_delete", "ON")?; + // The first statement that reads the file: a non-database fails here. + let (application_id, user_version) = read_header(connection)?; + if application_id == 0 && user_version == 0 { + if !is_empty_database(connection)? { + return Ok(false); + } + return initialize(connection); + } + if application_id != APPLICATION_ID || !(1..=SCHEMA_VERSION).contains(&user_version) { + return Ok(false); + } + if user_version < SCHEMA_VERSION { + migrate(connection, user_version)?; + } + has_expected_tables(connection) +} + +fn read_header(connection: &Connection) -> rusqlite::Result<(i32, i64)> { + let application_id = connection.pragma_query_value(None, "application_id", |row| row.get(0))?; + let user_version = connection.pragma_query_value(None, "user_version", |row| row.get(0))?; + Ok((application_id, user_version)) +} + +fn is_empty_database(connection: &Connection) -> rusqlite::Result { + let objects: i64 = + connection.query_row("SELECT count(*) FROM sqlite_schema", [], |row| row.get(0))?; + Ok(objects == 0) +} + +fn has_expected_tables(connection: &Connection) -> rusqlite::Result { + let tables: i64 = connection.query_row( + "SELECT count(*) FROM sqlite_schema WHERE type = 'table' AND name IN ('journal', 'entry_text')", + [], + |row| row.get(0), + )?; + Ok(tables == 2) +} + +/// Create the schema in one immediate transaction. Another process may have +/// initialized the file while this one waited for the lock, so re-check first. +fn initialize(connection: &mut Connection) -> rusqlite::Result { + let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?; + let (application_id, user_version) = read_header(&transaction)?; + if application_id == 0 && user_version == 0 && is_empty_database(&transaction)? { + transaction.pragma_update(None, "application_id", APPLICATION_ID)?; + migrate_in(&transaction, 0)?; + transaction.commit()?; + return has_expected_tables(connection); + } + drop(transaction); + let (application_id, user_version) = read_header(connection)?; + if application_id != APPLICATION_ID || user_version != SCHEMA_VERSION { + return Ok(false); + } + has_expected_tables(connection) +} + +/// Bring an older supported version up to date in one transaction. +fn migrate(connection: &mut Connection, from: i64) -> rusqlite::Result<()> { + let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?; + migrate_in(&transaction, from)?; + transaction.commit() +} + +/// Run every migration after version `from` and record the new version. +fn migrate_in(connection: &Connection, from: i64) -> rusqlite::Result<()> { + let skip = usize::try_from(from).unwrap_or(MIGRATIONS.len()); + for migration in MIGRATIONS.iter().skip(skip) { + connection.execute_batch(migration)?; + } + connection.pragma_update(None, "user_version", SCHEMA_VERSION) +} diff --git a/crates/omgcode-core/src/session_index/snippet.rs b/crates/omgcode-core/src/session_index/snippet.rs new file mode 100644 index 0000000..787a4a9 --- /dev/null +++ b/crates/omgcode-core/src/session_index/snippet.rs @@ -0,0 +1,152 @@ +//! Safe construction of FTS5 queries and parsing of marked snippets. +//! +//! Caller text is never passed to FTS5 as query syntax. This module quotes each +//! term itself, and it reserves two private-use code points as snippet markers +//! so transcript text cannot forge a match highlight. + +use super::IndexError; +use super::query::SnippetPart; + +/// Marks the start of a matched run in an FTS5 snippet. +pub(super) const MARK_START: char = '\u{e000}'; +/// Marks the end of a matched run in an FTS5 snippet. +pub(super) const MARK_END: char = '\u{e001}'; + +/// The most characters a search text may have. +pub(super) const MAX_QUERY_CHARS: usize = 256; +/// The most whitespace-separated terms a search text may have. +pub(super) const MAX_QUERY_TERMS: usize = 16; + +/// Replace the marker code points so indexed text can never contain them. +pub(super) fn sanitize_text(text: &str) -> String { + text.replace([MARK_START, MARK_END], "\u{fffd}") +} + +/// Build the FTS5 `MATCH` expression for the caller's text. +/// +/// Each whitespace-separated term becomes a double-quoted FTS5 string with +/// embedded quotes doubled, so operators, column filters, and `NEAR` are plain +/// text. Terms join with spaces (implicit AND). The last term gets a trailing +/// `*` for prefix matching while typing. +/// +/// # Errors +/// +/// `InvalidQuery` for text over 256 characters, with no terms, with more than +/// 16 terms, or containing NUL. +pub(super) fn match_expression(text: &str) -> Result { + if text.chars().count() > MAX_QUERY_CHARS { + return Err(IndexError::InvalidQuery("search text is too long")); + } + if text.contains('\0') { + return Err(IndexError::InvalidQuery("search text contains NUL")); + } + let terms: Vec<&str> = text.split_whitespace().collect(); + if terms.is_empty() { + return Err(IndexError::InvalidQuery("search text has no terms")); + } + if terms.len() > MAX_QUERY_TERMS { + return Err(IndexError::InvalidQuery("search text has too many terms")); + } + let mut expression = String::new(); + for (index, term) in terms.iter().enumerate() { + if index > 0 { + expression.push(' '); + } + expression.push('"'); + expression.push_str(&term.replace('"', "\"\"")); + expression.push('"'); + if index + 1 == terms.len() { + expression.push('*'); + } + } + Ok(expression) +} + +/// Split an FTS5 snippet into plain and matched parts. Marker code points never +/// appear in the output, and empty parts are omitted. +pub(super) fn parse_snippet(marked: &str) -> Vec { + let mut parts = Vec::new(); + let mut current = String::new(); + let mut matched = false; + for character in marked.chars() { + let next = match character { + MARK_START => Some(true), + MARK_END => Some(false), + _ => None, + }; + match next { + Some(state) => { + flush(&mut parts, &mut current, matched); + matched = state; + } + None => current.push(character), + } + } + flush(&mut parts, &mut current, matched); + parts +} + +fn flush(parts: &mut Vec, current: &mut String, matched: bool) { + if !current.is_empty() { + parts.push(SnippetPart { + text: std::mem::take(current), + matched, + }); + } +} + +#[cfg(test)] +mod tests { + use super::{match_expression, parse_snippet, sanitize_text}; + use crate::session_index::IndexError; + + #[test] + fn terms_are_quoted_and_only_the_last_gets_a_prefix_star() { + assert_eq!( + match_expression(" alpha be\"ta gam ").expect("expression"), + "\"alpha\" \"be\"\"ta\" \"gam\"*" + ); + assert_eq!( + match_expression("a OR b").expect("expression"), + "\"a\" \"OR\" \"b\"*" + ); + assert_eq!(match_expression("\"").expect("expression"), "\"\"\"\"*"); + } + + #[test] + fn unusable_text_is_rejected_with_a_typed_error() { + for text in ["", " \t\n", &"x".repeat(257), "a\0b", &"a ".repeat(17)] { + assert!( + matches!(match_expression(text), Err(IndexError::InvalidQuery(_))), + "{text:?}" + ); + } + assert!(match_expression(&"x".repeat(256)).is_ok()); + assert!(match_expression(&"a ".repeat(16)).is_ok()); + } + + #[test] + fn snippet_parts_alternate_and_never_contain_markers() { + let parts = parse_snippet("one \u{e000}two\u{e001} three \u{e000}four\u{e001}"); + let shown: Vec<(&str, bool)> = parts + .iter() + .map(|part| (part.text.as_str(), part.matched)) + .collect(); + assert_eq!( + shown, + [ + ("one ", false), + ("two", true), + (" three ", false), + ("four", true) + ] + ); + assert!(parse_snippet("").is_empty()); + assert!(parse_snippet("\u{e000}\u{e001}").is_empty()); + } + + #[test] + fn sanitizing_removes_both_markers() { + assert_eq!(sanitize_text("a\u{e000}b\u{e001}c"), "a\u{fffd}b\u{fffd}c"); + } +} diff --git a/crates/omgcode-core/src/storage.rs b/crates/omgcode-core/src/storage.rs index 014b73d..f1a3ef2 100644 --- a/crates/omgcode-core/src/storage.rs +++ b/crates/omgcode-core/src/storage.rs @@ -69,6 +69,28 @@ pub(crate) fn open_locked_file(path: &Path, create_new: bool) -> Result Result { + let mut options = OpenOptions::new(); + options.read(true); + configure_open_options(&mut options); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW); + } + let file = options.open(path)?; + validate_open_file(path, &file)?; + Ok(file) +} + /// Sync the containing directory entry on Unix. Rust does not provide a /// qualified safe directory-handle sync contract on Windows, so this is a /// documented no-op there. The caller chooses the parent directory to sync. diff --git a/crates/omgcode-core/src/turn.rs b/crates/omgcode-core/src/turn.rs index 6eb23c7..f5a5435 100644 --- a/crates/omgcode-core/src/turn.rs +++ b/crates/omgcode-core/src/turn.rs @@ -26,7 +26,7 @@ use crate::control::{ ControlStore, now_unix, valid_profile_name, }; use crate::files::{FileBroker, FileError, FileListing, FileTarget}; -use crate::policy::{DecisionReason, PermissionSet, WorkspaceId}; +use crate::policy::{DecisionReason, PermissionSet, SessionBinding, WorkspaceId}; use crate::prompt::{ self, BASE_PROMPT, BASE_PROMPT_VERSION, ConversationMessage, ConversationRole, ModelMessage, PromptError, @@ -37,6 +37,13 @@ use crate::session::{ SessionJournal, ToolOutcome, sha256_hex, }; +mod review; + +pub use review::{ + ApprovalReview, ReviewCandidate, ReviewError, ReviewField, ReviewedRequest, StaleReason, + display_safe, display_safe_line, review_approval, +}; + /// Revision of the tool schemas advertised by this runtime. /// /// Version `0.3.0` adds `workspace_edit_file`. Journals record the version @@ -1496,36 +1503,21 @@ impl WorkspaceToolDispatcher<'_> { ); } }; - let target = FileTarget { - session_id: self.session_id, - workspace_id: self.workspace_id, - path: PathBuf::from(path), - }; - let current = - match FileBroker::new(&mut control).read(&binding, &target, MAX_EDIT_FILE_BYTES) { - Ok(read) => read.bytes, - Err(error) => return classify_edit_error(call, error), - }; - let Ok(text) = std::str::from_utf8(¤t) else { - return ToolExecution::recoverable("non_utf8", call); + let target = edit_target(self.session_id, self.workspace_id, path); + let current = match read_edit_source(&mut control, &binding, &target) { + Ok(bytes) => bytes, + Err(error) => return classify_edit_error(call, error), }; - let start = match unique_match(text, old_text) { - TextMatch::None => return ToolExecution::recoverable("edit_no_match", call), - TextMatch::Many => return ToolExecution::recoverable("edit_ambiguous", call), - TextMatch::Once(start) => start, - }; - if old_text == new_text { - return ToolExecution::recoverable("edit_unchanged", call); - } - let Some(proposed) = replace_once(text, start, old_text.len(), new_text) else { - return ToolExecution::recoverable("edit_too_large", call); + let prepared = match prepare_edit(path, old_text, new_text, ¤t) { + Ok(prepared) => prepared, + Err(code) => return ToolExecution::recoverable(code, call), }; - let (Some(current_artifact), Some(proposed_artifact)) = - (artifact(¤t), artifact(proposed.as_bytes())) - else { - return ToolExecution::recoverable("edit_too_large", call); - }; - let normalized = normalized_path(path); + let PreparedEdit { + normalized, + current_artifact, + proposed, + proposed_artifact, + } = prepared; let digest = edit_digest( self.session_id, self.workspace_id, @@ -1657,17 +1649,8 @@ impl WorkspaceToolDispatcher<'_> { else { return ToolExecution::recoverable("invalid_command", call); }; - let request = crate::run::RunRequest { - workspace_id: self.workspace_id, - profile: profile.clone(), - program: PathBuf::from(program), - arguments: arguments.iter().map(OsString::from).collect(), - working_directory: cwd.as_ref().map(PathBuf::from), - host_services: false, - network: false, - model_tools: true, - limits: command_limits(), - }; + let request = + command_run_request(self.workspace_id, profile, program, arguments, cwd.as_ref()); let digest = command_digest(self.session_id, &request); let now = now_unix(); let revision = control.revision(); @@ -1813,6 +1796,32 @@ impl WorkspaceToolDispatcher<'_> { } } +/// Build the run request for one model command call. +/// +/// This is the only place that turns parsed command arguments into a +/// [`crate::run::RunRequest`]. Dispatch runs and digests the result, and +/// approval review recomputes the same digest from it, so the two cannot +/// diverge. Network and host services are always off and the limits are fixed. +fn command_run_request( + workspace_id: WorkspaceId, + profile: &str, + program: &str, + arguments: &[String], + cwd: Option<&String>, +) -> crate::run::RunRequest { + crate::run::RunRequest { + workspace_id, + profile: profile.to_owned(), + program: PathBuf::from(program), + arguments: arguments.iter().map(OsString::from).collect(), + working_directory: cwd.map(PathBuf::from), + host_services: false, + network: false, + model_tools: true, + limits: command_limits(), + } +} + /// Fixed limits for one model command run. fn command_limits() -> crate::run::ProcessLimits { crate::run::ProcessLimits { @@ -1943,6 +1952,75 @@ fn replace_once(text: &str, start: usize, length: usize, replacement: &str) -> O Some(proposed) } +/// One exact edit prepared against the live bytes of its target file. +struct PreparedEdit { + /// The `/`-joined path used in the digest and the summary. + normalized: String, + /// Size and SHA-256 of the live current bytes. + current_artifact: RecordedArtifact, + /// The complete proposed file text. + proposed: String, + /// Size and SHA-256 of the proposed bytes. + proposed_artifact: RecordedArtifact, +} + +/// The broker target for one model edit path. +fn edit_target(session_id: Uuid, workspace_id: WorkspaceId, path: &str) -> FileTarget { + FileTarget { + session_id, + workspace_id, + path: PathBuf::from(path), + } +} + +/// Read the live current bytes of an edit target through the audited broker. +/// +/// This is the only edit read. The broker checks the live `read` permission +/// and appends its own audit record. Dispatch and approval review both call it. +fn read_edit_source( + control: &mut ControlStore, + binding: &SessionBinding, + target: &FileTarget, +) -> Result, FileError> { + FileBroker::new(control) + .read(binding, target, MAX_EDIT_FILE_BYTES) + .map(|read| read.bytes) +} + +/// Turn parsed edit arguments and the live current bytes into the exact edit. +/// +/// This is the only place that applies the unique-match rule, the no-op check, +/// and the size bounds. An error is the recoverable tool code that dispatch +/// reports; approval review treats any of them as "not this request". +fn prepare_edit( + path: &str, + old_text: &str, + new_text: &str, + current: &[u8], +) -> Result { + let text = std::str::from_utf8(current).map_err(|_| "non_utf8")?; + let start = match unique_match(text, old_text) { + TextMatch::None => return Err("edit_no_match"), + TextMatch::Many => return Err("edit_ambiguous"), + TextMatch::Once(start) => start, + }; + if old_text == new_text { + return Err("edit_unchanged"); + } + let proposed = replace_once(text, start, old_text.len(), new_text).ok_or("edit_too_large")?; + let (Some(current_artifact), Some(proposed_artifact)) = + (artifact(current), artifact(proposed.as_bytes())) + else { + return Err("edit_too_large"); + }; + Ok(PreparedEdit { + normalized: normalized_path(path), + current_artifact, + proposed, + proposed_artifact, + }) +} + /// The labelled report of an applied edit. It never contains file text. fn edit_success_message( call: &ToolCall, @@ -2047,14 +2125,38 @@ fn edit_summary(path: &str, current: &RecordedArtifact, proposed: &RecordedArtif /// Invisible, line-breaking, or bidirectional formatting characters that can /// hide or reorder displayed text. +/// +/// Categories: bidirectional and zero-width marks (U+061C, U+200B to U+200F, +/// U+2028 to U+202E, U+2060 to U+2069, U+FEFF); characters that render as +/// nothing or merge into a neighbour (soft hyphen U+00AD, combining grapheme +/// joiner U+034F, Hangul fillers U+115F, U+1160, U+3164, U+FFA0, Khmer +/// invisible vowels U+17B4 to U+17B5, Mongolian selectors and separator +/// U+180B to U+180F); variation selectors (U+FE00 to U+FE0F); interlinear +/// annotation anchors and the object replacement character (U+FFF9 to +/// U+FFFC); musical formatting controls (U+1D173 to U+1D17A); and the tag +/// characters with the variation selectors supplement (U+E0000 to U+E0FFF). +/// +/// This list does not cover look-alike letters, mixed scripts, or ordinary +/// spaces. const fn is_hidden_format(character: char) -> bool { matches!( character, - '\u{061c}' + '\u{00ad}' + | '\u{034f}' + | '\u{061c}' + | '\u{115f}'..='\u{1160}' + | '\u{17b4}'..='\u{17b5}' + | '\u{180b}'..='\u{180f}' | '\u{200b}'..='\u{200f}' | '\u{2028}'..='\u{202e}' | '\u{2060}'..='\u{2069}' + | '\u{3164}' + | '\u{fe00}'..='\u{fe0f}' | '\u{feff}' + | '\u{ffa0}' + | '\u{fff9}'..='\u{fffc}' + | '\u{1d173}'..='\u{1d17a}' + | '\u{e0000}'..='\u{e0fff}' ) } diff --git a/crates/omgcode-core/src/turn/review.rs b/crates/omgcode-core/src/turn/review.rs new file mode 100644 index 0000000..81ee752 --- /dev/null +++ b/crates/omgcode-core/src/turn/review.rs @@ -0,0 +1,724 @@ +//! Read-only review of the recorded request an approval is bound to (ADR-0046). +//! +//! An approval record stores a digest and a short summary, never the tool +//! arguments. A reviewer that shows arguments next to an Approve control must +//! show only arguments that reproduce that digest. This module is the one +//! place that does the matching, using the same argument parser, request +//! construction, edit preparation, and digest functions as the tool dispatcher. +//! It grants nothing: it never requests, decides, or consumes an approval. + +use std::collections::HashSet; +use std::path::Path; + +use serde::Serialize; +use serde_json::json; +use thiserror::Error; + +use super::{ + PreparedEdit, ToolArguments, ToolCall, ToolName, command_digest, command_run_request, + edit_digest, edit_target, is_hidden_format, prepare_edit, read_edit_source, +}; +use crate::control::{ApprovalOperation, ApprovalStatus, ControlError, ControlStore}; +use crate::file_audit::FileAuditError; +use crate::files::FileError; +use crate::replacement::CheckpointError; + +/// Most distinct edit requests evaluated for one review. +/// +/// Each evaluation reads a workspace file through the audited broker and +/// writes one audit record, so the work and the audit growth are bounded. +const MAX_REVIEW_EDIT_CANDIDATES: usize = 8; + +/// One recorded model tool request offered as a candidate for review. +/// +/// Both fields are untrusted model data, usually copied from the session +/// journal's recorded tool requests. Offering a candidate grants nothing. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ReviewCandidate<'a> { + /// The requested tool name. + pub tool: &'a str, + /// The exact arguments JSON string that was recorded. + pub arguments: &'a str, +} + +/// What core found for one approval record. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ApprovalReview { + /// A recorded request reproduces the approval's digest under the current + /// settings, so a retry of it would consume the approval. + Exact(ReviewedRequest), + /// Candidates of the right tool exist, or the settings revision changed, + /// but nothing reproduces the digest. The approval cannot be consumed by + /// any request core can show. + Stale(StaleReason), + /// No recorded request of the right tool exists, the operation has no + /// reviewable tool, or the settings store or workspace is absent. + NotFound, +} + +/// Why a review is stale. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum StaleReason { + /// The settings revision changed after the approval was requested. The + /// record can never be consumed. + SettingsChanged, + /// No candidate reproduces the digest, for example because the target + /// file changed after the request. + NoMatchingRequest, +} + +/// The request an approval is bound to, rendered for a person to read. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct ReviewedRequest { + /// The wire name of the tool that makes the request. + pub tool: String, + /// Labelled values, each already passed through [`display_safe`]. + pub fields: Vec, +} + +/// One labelled, display-safe value of a reviewed request. +#[derive(Clone, Debug, Eq, PartialEq, Serialize)] +pub struct ReviewField { + /// A fixed English label. + pub label: &'static str, + /// Display-safe text. It may contain `\n` only when `multiline` is true. + pub value: String, + /// Whether the value is meant to be shown as several lines. + pub multiline: bool, +} + +/// A review that could not be completed. Messages hold no file contents, +/// request text, or absolute paths; the codes are fixed strings. +#[derive(Debug, Error)] +pub enum ReviewError { + /// Another process holds the settings store or the file-operation store. + /// Retry later; nothing was changed. + #[error("the settings or file-operation store is in use by another process")] + Busy, + /// The settings store could not be read. + #[error("the settings store could not be read ({0})")] + Control(&'static str), + /// A review file read failed in a way that is not a plain non-match. + #[error("the review file read could not complete ({0})")] + Files(&'static str), +} + +/// Find the recorded request that an approval record is bound to. +/// +/// `candidates` are the recorded tool requests of the approval's session in +/// journal order, oldest first. They are untrusted; the result depends only on +/// whether a candidate reproduces `approval.request_sha256`, so a candidate +/// from another session or workspace can match only by reproducing the digest +/// of the approval's own session and workspace. +/// +/// 1. Only [`ApprovalOperation::Command`] and [`ApprovalOperation::FileWrite`] +/// are reviewable. Others give [`ApprovalReview::NotFound`]. +/// 2. The existing settings store is opened once, without retries. A missing +/// store or unregistered workspace gives `NotFound`, a busy store gives +/// [`ReviewError::Busy`], and a settings revision that differs from the +/// approval's gives `Stale(SettingsChanged)`. +/// 3. Only candidates whose tool is the operation's tool are considered; with +/// none, the result is `NotFound`. +/// 4. They are tried newest first, each parsed by [`ToolCall::parse`]. A +/// candidate that fails to parse is skipped. A command candidate is built +/// into a run request by the dispatcher's own constructor. An edit candidate +/// is read live through the audited broker under the live `read` +/// requirement and prepared by the dispatcher's own edit preparation. At +/// most eight distinct edit candidates (distinct by exact arguments) are +/// evaluated, newest first. A candidate whose preparation fails for a +/// recoverable reason (missing file, no match, ambiguous match, too large, +/// read denied) is not a match. +/// 5. If none reproduces the digest, the result is `Stale(NoMatchingRequest)`. +/// +/// The fields of an `Exact` result come from the request that reproduced the +/// digest, not from the newest candidate and not from re-reading the JSON. +/// +/// # Side effects +/// +/// None on approvals. The function never requests, decides, or consumes a +/// record, never applies an edit, never creates a checkpoint, and never starts +/// a process. For an edit candidate it reads one workspace file through the +/// broker, which appends one audit record per read; nothing else is written. +/// +/// # Locking +/// +/// The settings store is opened once, the same way the dispatcher opens it. A +/// command review releases it before comparing candidates. An edit review +/// holds it while it reads, as dispatch does, because the broker needs the +/// writer; the broker takes its own subordinate stores one at a time under the +/// documented order (settings, then file audit). The settings store is never +/// held across anything but those bounded reads and is dropped before return. +/// A store held elsewhere gives [`ReviewError::Busy`]; the function does not +/// retry. +/// +/// # Not validated +/// +/// Whether `approval` is still pending, approved, or unexpired. The caller +/// shows state separately. A consumed or expired record can still be `Exact`. +/// An `Exact` result is a snapshot: a file can change before an approval is +/// decided, and core still checks the binding when the call is consumed. +pub fn review_approval( + data_directory: &Path, + approval: &ApprovalStatus, + candidates: &[ReviewCandidate<'_>], +) -> Result { + let tool = match approval.operation { + ApprovalOperation::Command => ToolName::Command, + ApprovalOperation::FileWrite => ToolName::EditFile, + ApprovalOperation::GitPush | ApprovalOperation::Network => { + return Ok(ApprovalReview::NotFound); + } + }; + let control = match ControlStore::open_existing(data_directory) { + Ok(Some(control)) => control, + Ok(None) => return Ok(ApprovalReview::NotFound), + Err(ControlError::Busy) => return Err(ReviewError::Busy), + Err(error) => return Err(ReviewError::Control(control_code(&error))), + }; + if approval.settings_revision != control.revision() { + return Ok(ApprovalReview::Stale(StaleReason::SettingsChanged)); + } + if control.workspace(approval.workspace_id).is_none() { + return Ok(ApprovalReview::NotFound); + } + let mut relevant = candidates + .iter() + .rev() + .filter(|candidate| candidate.tool == tool.as_str()) + .peekable(); + if relevant.peek().is_none() { + return Ok(ApprovalReview::NotFound); + } + let found = match tool { + ToolName::Command => { + drop(control); + review_command(approval, relevant) + } + _ => review_edit(control, approval, relevant)?, + }; + Ok(found.map_or( + ApprovalReview::Stale(StaleReason::NoMatchingRequest), + ApprovalReview::Exact, + )) +} + +/// Parse a candidate with the dispatcher's strict parser. +/// +/// The parser takes a whole provider call, so the candidate is wrapped in one +/// with a fixed identifier. Everything else it checks applies unchanged. +fn parse_candidate(candidate: &ReviewCandidate<'_>, tool: ToolName) -> Option { + let value = json!({ + "id": "review", + "type": "function", + "function": {"name": candidate.tool, "arguments": candidate.arguments}, + }); + ToolCall::parse(&value) + .ok() + .filter(|call| call.name == tool) +} + +/// Find the newest command candidate that reproduces the approval's digest. +fn review_command<'a>( + approval: &ApprovalStatus, + candidates: impl Iterator>, +) -> Option { + for candidate in candidates { + let Some(call) = parse_candidate(candidate, ToolName::Command) else { + continue; + }; + let ToolArguments::Command { + profile, + program, + arguments, + cwd, + } = &call.arguments + else { + continue; + }; + let request = command_run_request( + approval.workspace_id, + profile, + program, + arguments, + cwd.as_ref(), + ); + if command_digest(approval.session_id, &request) == approval.request_sha256 { + return Some(ReviewedRequest { + tool: ToolName::Command.as_str().to_owned(), + fields: command_fields(&request), + }); + } + } + None +} + +/// Find the newest edit candidate that reproduces the approval's digest. +/// +/// Evaluates at most [`MAX_REVIEW_EDIT_CANDIDATES`] distinct candidates. +fn review_edit<'a>( + mut control: ControlStore, + approval: &ApprovalStatus, + candidates: impl Iterator>, +) -> Result, ReviewError> { + let binding = control + .bind_session(approval.session_id, approval.workspace_id) + .map_err(|error| match error { + ControlError::Busy => ReviewError::Busy, + other => ReviewError::Control(control_code(&other)), + })?; + let mut seen = HashSet::new(); + let mut evaluated = 0usize; + for candidate in candidates { + let Some(call) = parse_candidate(candidate, ToolName::EditFile) else { + continue; + }; + let ToolArguments::EditFile { + path, + old_text, + new_text, + } = &call.arguments + else { + continue; + }; + if !seen.insert(candidate.arguments) { + continue; + } + if evaluated == MAX_REVIEW_EDIT_CANDIDATES { + break; + } + evaluated += 1; + let target = edit_target(approval.session_id, approval.workspace_id, path); + let current = match read_edit_source(&mut control, &binding, &target) { + Ok(bytes) => bytes, + Err(error) => { + classify_review_read(error)?; + continue; + } + }; + let Ok(prepared) = prepare_edit(path, old_text, new_text, ¤t) else { + continue; + }; + let digest = edit_digest( + approval.session_id, + approval.workspace_id, + &prepared.normalized, + &prepared.current_artifact, + &prepared.proposed_artifact, + ); + if digest == approval.request_sha256 { + return Ok(Some(ReviewedRequest { + tool: ToolName::EditFile.as_str().to_owned(), + fields: edit_fields(&prepared, old_text, new_text), + })); + } + } + Ok(None) +} + +/// Decide whether a failed review read is a plain non-match (`Ok`) or leaves +/// the review unable to continue (`Err`). +/// +/// Permission denial, a missing or unsuitable file, and a file over the edit +/// bound mean this candidate cannot be what the approval is bound to. A busy +/// store, an unresolved file operation, or an audit failure mean core could +/// not look, so claiming the approval is stale would be wrong. +fn classify_review_read(error: FileError) -> Result<(), ReviewError> { + match error { + FileError::Denied(_) + | FileError::Native(_) + | FileError::InvalidPath(_) + | FileError::Invalid(_) => Ok(()), + FileError::Control(ControlError::Busy) | FileError::Checkpoint(CheckpointError::Busy) => { + Err(ReviewError::Busy) + } + FileError::Control(other) => Err(ReviewError::Control(control_code(&other))), + FileError::Audit(source) => { + if matches!( + source.downcast_ref::(), + Some(FileAuditError::Busy) + ) { + Err(ReviewError::Busy) + } else { + Err(ReviewError::Files("audit_failed")) + } + } + FileError::Pending { .. } => Err(ReviewError::Files("operation_pending")), + _ => Err(ReviewError::Files("read_failed")), + } +} + +/// A fixed, content-free code for a settings-store failure. +const fn control_code(error: &ControlError) -> &'static str { + match error { + ControlError::Io(_) => "io", + ControlError::Invalid(_) => "invalid", + ControlError::Busy => "busy", + ControlError::UnknownWorkspace => "unknown_workspace", + ControlError::DirectoryChanged => "directory_changed", + _ => "unavailable", + } +} + +/// Command fields, taken from the constructed run request so the display +/// cannot diverge from what would run. +fn command_fields(request: &crate::run::RunRequest) -> Vec { + let arguments = if request.arguments.is_empty() { + String::from("(none)") + } else { + request + .arguments + .iter() + .enumerate() + .map(|(index, argument)| { + format!( + "{}: {}", + index + 1, + display_safe_line(&argument.to_string_lossy()) + ) + }) + .collect::>() + .join("\n") + }; + let directory = request.working_directory.as_ref().map_or_else( + || String::from("(workspace root)"), + |directory| display_safe_line(&directory.to_string_lossy()), + ); + let limits = &request.limits; + let output = if limits.max_stdout_bytes == limits.max_stderr_bytes { + format!("{} bytes per stream", limits.max_stdout_bytes) + } else { + format!( + "stdout {} bytes, stderr {} bytes", + limits.max_stdout_bytes, limits.max_stderr_bytes + ) + }; + vec![ + single("Profile", display_safe_line(&request.profile)), + single( + "Program", + display_safe_line(&request.program.to_string_lossy()), + ), + ReviewField { + label: "Arguments", + value: arguments, + multiline: true, + }, + single("Working directory", directory), + single("Network", on_off(request.network)), + single("Host services", on_off(request.host_services)), + single( + "Time limit", + format!("{} seconds", limits.deadline.as_secs()), + ), + single("Output limit", output), + ] +} + +/// Edit fields. The path, sizes, and digests come from the prepared edit and +/// the old and new text from the parsed arguments that produced it. +fn edit_fields(prepared: &PreparedEdit, old_text: &str, new_text: &str) -> Vec { + vec![ + single("File", display_safe_line(&prepared.normalized)), + ReviewField { + label: "Old text", + value: display_safe(old_text), + multiline: true, + }, + ReviewField { + label: "New text", + value: display_safe(new_text), + multiline: true, + }, + single( + "Size", + format!( + "{} -> {} bytes", + prepared.current_artifact.bytes, prepared.proposed_artifact.bytes + ), + ), + single("Current SHA-256", prepared.current_artifact.sha256.clone()), + single( + "Proposed SHA-256", + prepared.proposed_artifact.sha256.clone(), + ), + ] +} + +fn single(label: &'static str, value: String) -> ReviewField { + ReviewField { + label, + value, + multiline: false, + } +} + +fn on_off(enabled: bool) -> String { + String::from(if enabled { "on" } else { "off" }) +} + +/// Replace characters that can hide or reorder displayed text with visible +/// escapes, keeping line feeds so multi-line text stays readable. +/// +/// Every `char::is_control` character except `\n` (so `\r`, `\t`, NUL, and +/// C1 controls) and every invisible or bidirectional formatting character that +/// the approval summaries already replace becomes `\u{XXXX}`: lowercase hex, at +/// least four digits. The ranges are listed on `is_hidden_format`; they include +/// bidirectional and zero-width marks, soft hyphen, fillers, variation +/// selectors, interlinear anchors, and tag characters. Variation selectors are +/// shown on purpose, so an emoji followed by U+FE0F displays the escape. +/// +/// Limits: this does not detect look-alike letters (homoglyphs) or mixed +/// scripts, and it leaves ordinary trailing spaces as typed. +/// +/// A backslash that begins the two characters `u{` would let text forge an +/// escape, so it becomes `\u{5c}`. A backslash directly before a character that +/// is itself escaped is escaped the same way, so a forged and a real escape +/// stay distinguishable. The output holds no control or hidden character other +/// than `\n`. The result is for display only; it is not reversible text and +/// not an authorization key. +pub fn display_safe(text: &str) -> String { + escape_text(text, true) +} + +/// Like [`display_safe`], but `\n` is escaped too, so the result is one line. +/// +/// Use it for values that must not be able to start a new displayed line, such +/// as a command argument that could imitate the next numbered argument. +pub fn display_safe_line(text: &str) -> String { + escape_text(text, false) +} + +fn escape_text(text: &str, keep_newline: bool) -> String { + let characters: Vec = text.chars().collect(); + let mut escaped = vec![false; characters.len()]; + // Right to left, so a backslash can see whether its successor is escaped. + for index in (0..characters.len()).rev() { + let character = characters[index]; + escaped[index] = if character == '\\' { + let forges = + characters.get(index + 1) == Some(&'u') && characters.get(index + 2) == Some(&'{'); + forges || escaped.get(index + 1).copied().unwrap_or(false) + } else { + character.is_control() && !(keep_newline && character == '\n') + || is_hidden_format(character) + }; + } + let mut output = String::with_capacity(text.len()); + for (character, escape) in characters.into_iter().zip(escaped) { + if !escape { + output.push(character); + } else if character == '\\' { + output.push_str("\\u{5c}"); + } else { + output.push_str(&format!("\\u{{{:04x}}}", u32::from(character))); + } + } + output +} + +#[cfg(test)] +mod tests { + use super::{display_safe, display_safe_line}; + + /// Output must hold no control or hidden character except `\n`. + fn assert_clean(output: &str) { + assert!( + output + .chars() + .all(|c| c == '\n' || (!c.is_control() && !super::is_hidden_format(c))), + "unsafe character in {output:?}" + ); + } + + #[test] + fn plain_text_and_line_feeds_pass_through_unchanged() { + assert_eq!( + display_safe("fn main() {\n é 日本 😀\n}"), + "fn main() {\n é 日本 😀\n}" + ); + assert_eq!(display_safe(""), ""); + } + + #[test] + fn controls_other_than_line_feed_become_visible_escapes() { + assert_eq!( + display_safe("a\rb\tc\0d"), + "a\\u{000d}b\\u{0009}c\\u{0000}d" + ); + assert_eq!( + display_safe("\u{7f}\u{85}\u{9f}"), + "\\u{007f}\\u{0085}\\u{009f}" + ); + assert_eq!(display_safe("\u{1b}[31m"), "\\u{001b}[31m"); + } + + #[test] + fn every_hidden_format_range_boundary_is_escaped_and_neighbours_are_not() { + let hidden = [ + '\u{061c}', '\u{200b}', '\u{200f}', '\u{2028}', '\u{202e}', '\u{2060}', '\u{2069}', + '\u{feff}', + ]; + for character in hidden { + let text = format!("a{character}b"); + let escaped = display_safe(&text); + assert_eq!( + escaped, + format!("a\\u{{{:04x}}}b", u32::from(character)), + "{character:?}" + ); + assert_clean(&escaped); + } + for character in [ + '\u{061b}', '\u{061d}', '\u{200a}', '\u{2010}', '\u{2027}', '\u{202f}', '\u{205f}', + '\u{206a}', '\u{fefe}', '\u{ff00}', + ] { + let text = format!("a{character}b"); + assert_eq!(display_safe(&text), text, "{character:?} must pass"); + } + // Every member of each range, not only its ends. + for code in (0x200b..=0x200f) + .chain(0x2028..=0x202e) + .chain(0x2060..=0x2069) + { + let character = char::from_u32(code).expect("scalar"); + assert_eq!( + display_safe(&character.to_string()), + format!("\\u{{{code:04x}}}") + ); + } + } + + /// The documented inclusive ranges, written out independently of the + /// function under test. + const HIDDEN_RANGES: [(u32, u32); 16] = [ + (0x00ad, 0x00ad), + (0x034f, 0x034f), + (0x061c, 0x061c), + (0x115f, 0x1160), + (0x17b4, 0x17b5), + (0x180b, 0x180f), + (0x200b, 0x200f), + (0x2028, 0x202e), + (0x2060, 0x2069), + (0x3164, 0x3164), + (0xfe00, 0xfe0f), + (0xfeff, 0xfeff), + (0xffa0, 0xffa0), + (0xfff9, 0xfffc), + (0x1d173, 0x1d17a), + (0xe0000, 0xe0fff), + ]; + + fn listed(code: u32) -> bool { + HIDDEN_RANGES + .iter() + .any(|&(first, last)| (first..=last).contains(&code)) + } + + #[test] + fn every_range_boundary_is_hidden_and_the_code_points_outside_are_not() { + for (first, last) in HIDDEN_RANGES { + for code in [first, last] { + let character = char::from_u32(code).expect("scalar"); + assert!(super::is_hidden_format(character), "U+{code:04X}"); + assert_eq!( + display_safe(&format!("a{character}b")), + format!("a\\u{{{code:04x}}}b"), + "U+{code:04X}" + ); + } + for code in [first - 1, last + 1] { + let character = char::from_u32(code).expect("scalar"); + assert_eq!( + super::is_hidden_format(character), + listed(code), + "U+{code:04X}" + ); + if !listed(code) && !character.is_control() { + let text = format!("a{character}b"); + assert_eq!(display_safe(&text), text, "U+{code:04X} must pass"); + } + } + } + } + + #[test] + fn the_hidden_set_matches_the_documented_ranges_for_every_scalar() { + for code in 0..=0x0010_ffff_u32 { + if let Some(character) = char::from_u32(code) { + assert_eq!( + super::is_hidden_format(character), + listed(code), + "U+{code:04X}" + ); + } + } + } + + #[test] + fn ordinary_text_and_emoji_without_a_selector_are_unchanged() { + for text in [ + "plain ASCII 123 ~!", + "caf\u{e9} na\u{ef}ve \u{c5}ngstr\u{f6}m", + "\u{65e5}\u{672c}\u{8a9e} \u{d55c}\u{ae00}", + "\u{1f600} \u{1f44d} \u{2764}", + "\u{1f44d}\u{1f3fd}", + ] { + assert_eq!(display_safe(text), text); + assert_eq!(display_safe_line(text), text); + } + } + + #[test] + fn a_variation_selector_after_an_emoji_is_shown_on_purpose() { + assert_eq!(display_safe("\u{2764}\u{fe0f}"), "\u{2764}\\u{fe0f}"); + assert_eq!( + display_safe("\u{1f600}\u{e0001}\u{e007f}"), + "\u{1f600}\\u{e0001}\\u{e007f}" + ); + } + + #[test] + fn look_alikes_and_trailing_spaces_are_not_addressed() { + // Cyrillic a, mixed script, and trailing spaces pass through. This + // documents the limit; it is not a promise to detect them. + assert_eq!(display_safe("p\u{430}ypal "), "p\u{430}ypal "); + } + + #[test] + fn a_literal_escape_cannot_forge_a_real_one() { + let real = display_safe("\u{202e}"); + assert_eq!(real, "\\u{202e}"); + let forged = display_safe("\\u{202e}"); + assert_eq!(forged, "\\u{5c}u{202e}"); + assert_ne!(real, forged); + // A backslash before a real escape is not left to merge with it. + assert_eq!(display_safe("\\\u{202e}"), "\\u{5c}\\u{202e}"); + // Backslashes that do not start `u{` stay as typed. + assert_eq!(display_safe(r"C:\dir\u1234 \n"), r"C:\dir\u1234 \n"); + // A run of backslashes ahead of `u{` is escaped as a unit. + assert_eq!(display_safe("\\\\u{41}"), "\\u{5c}\\u{5c}u{41}"); + assert_clean(&display_safe("x\\\\u{202e}\u{202e}\\")); + } + + #[test] + fn mixed_hostile_text_has_no_unsafe_character_left() { + let hostile = "ok\u{202e}evil\u{200b}\r\n\ttab\0nul\u{2028}\u{feff}\\u{1b}end\n"; + let output = display_safe(hostile); + assert_clean(&output); + assert_eq!( + output.matches('\n').count(), + 2, + "only real line feeds remain" + ); + assert!(output.starts_with("ok\\u{202e}evil\\u{200b}\\u{000d}\n")); + } + + #[test] + fn the_line_variant_escapes_line_feeds_too() { + assert_eq!(display_safe_line("a\n2: rm"), "a\\u{000a}2: rm"); + assert!(!display_safe_line("a\nb\r\n").contains('\n')); + assert_eq!(display_safe_line("plain"), "plain"); + } +} diff --git a/crates/omgcode-core/tests/approval_review.rs b/crates/omgcode-core/tests/approval_review.rs new file mode 100644 index 0000000..26a3f0e --- /dev/null +++ b/crates/omgcode-core/tests/approval_review.rs @@ -0,0 +1,805 @@ +//! Approval review: core finds the recorded request an approval is bound to, +//! using the dispatcher's own parser, request construction, and digests. +//! +//! These tests drive real turns with a scripted model, real files, and the +//! real control store. Edit applies need a private data root; on Windows the +//! temporary directory must be on NTFS (set `TEMP` and `TMP` accordingly). + +use std::collections::VecDeque; +use std::fs; +use std::path::{Path, PathBuf}; + +use omgcode_core::control::{ + ApprovalOperation, ApprovalState, ApprovalStatus, ControlStore, ProfileDeclaration, now_unix, +}; +use omgcode_core::policy::{PermissionSet, WorkspaceId}; +use omgcode_core::prompt::{self, BASE_PROMPT, BASE_PROMPT_VERSION}; +use omgcode_core::session::{RecordedToolRequest, RequestManifest, SessionJournal}; +use omgcode_core::turn::{ + ApprovalReview, ModelError, ReviewCandidate, ReviewError, ReviewField, ReviewedRequest, + StaleReason, ToolModel, ToolModelReply, ToolModelRequest, TurnLimits, TurnRuntime, + review_approval, +}; +use serde_json::{Value, json}; +use tempfile::TempDir; +use uuid::Uuid; + +const FILE_AUDIT_NAME: &str = "file-operations-v1.jsonl"; +const COMMAND_TOOL: &str = "workspace_run_command"; +const EDIT_TOOL: &str = "workspace_edit_file"; + +struct Fixture { + _temporary: TempDir, + data: PathBuf, + workspace: PathBuf, + workspace_id: WorkspaceId, + journal: SessionJournal, +} + +impl Fixture { + fn new() -> Self { + let temporary = TempDir::new().expect("private temporary directory"); + let data = temporary.path().join("application-data"); + let root = temporary.path().join("development-root"); + let workspace = root.join("workspace"); + let tools = temporary.path().join("tools"); + fs::create_dir(&root).expect("create development root"); + fs::create_dir(&workspace).expect("create workspace"); + fs::create_dir(&tools).expect("create toolchain root"); + // Checkpointed edits need a private data root on Windows. + #[cfg(windows)] + make_private_root(&data); + + let mut control = ControlStore::open(&data).expect("open control store"); + control + .set_development_root(&root, control.revision()) + .expect("select development root"); + let workspace_id = control + .register_workspace(&workspace, control.revision()) + .expect("register workspace") + .id(); + control + .set_permissions( + workspace_id, + PermissionSet { + model_tools: true, + execute: true, + read: true, + write: true, + ..PermissionSet::default() + }, + control.revision(), + ) + .expect("enable the command and edit tools"); + control + .add_profile( + &ProfileDeclaration { + name: "system".into(), + read_only_roots: vec![tools], + path_entries: Vec::new(), + environment: Vec::new(), + }, + control.revision(), + ) + .expect("declare a toolchain profile"); + drop(control); + let journal = + SessionJournal::create_with_workspace_id(&data, &workspace, "Review", workspace_id) + .expect("create session"); + Self { + _temporary: temporary, + data, + workspace, + workspace_id, + journal, + } + } + + /// Run one turn in which the model makes `calls` and then replies. + fn turn(&mut self, calls: Vec) { + let mut model = ScriptedModel { + replies: VecDeque::from([ + Ok(ToolModelReply { + content: String::new(), + tool_calls: calls, + finish_reason: "tool_calls".to_owned(), + }), + Ok(ToolModelReply { + content: "reported".to_owned(), + tool_calls: Vec::new(), + finish_reason: "stop".to_owned(), + }), + ]), + }; + let mut runtime = TurnRuntime::new( + &mut self.journal, + &self.data, + self.workspace_id, + TurnLimits::default(), + ) + .expect("build runtime"); + runtime + .run(&mut model, "go", "", manifest()) + .expect("turn completes"); + } + + fn recorded(&self) -> Vec { + self.journal.tool_requests().to_vec() + } + + fn approvals(&self) -> Vec { + ControlStore::open_existing(&self.data) + .expect("open control") + .expect("control store") + .approval_statuses(now_unix()) + } + + fn pending(&self, operation: ApprovalOperation) -> ApprovalStatus { + let found: Vec<_> = self + .approvals() + .into_iter() + .filter(|status| { + status.operation == operation && status.state == ApprovalState::Pending + }) + .collect(); + assert_eq!(found.len(), 1, "one pending approval: {found:?}"); + found.into_iter().next().expect("one pending approval") + } + + fn state(&self, id: Uuid) -> ApprovalState { + ControlStore::open_existing(&self.data) + .expect("open control") + .expect("control store") + .approval_status(id, now_unix()) + .expect("approval status") + .state + } + + fn review( + &self, + approval: &ApprovalStatus, + recorded: &[RecordedToolRequest], + ) -> Result { + let candidates = candidates(recorded); + review_approval(&self.data, approval, &candidates) + } + + fn audit_reads(&self) -> usize { + read_events(&self.data.join(FILE_AUDIT_NAME)) + .iter() + .filter(|event| { + event["action"]["type"] == "operation_started" + && event["action"]["payload"]["operation"] == "read" + }) + .count() + } + + fn checkpoint_operations(&self) -> usize { + let mut control = ControlStore::open_existing(&self.data) + .expect("open control") + .expect("control store"); + omgcode_core::files::FileBroker::new(&mut control) + .checkpoint_inspect() + .expect("inspect checkpoints") + .operations + .len() + } + + fn write_file(&self, name: &str, contents: &str) -> PathBuf { + let path = self.workspace.join(name); + fs::write(&path, contents).expect("write workspace file"); + path + } +} + +/// Gives the data root a protected DACL for the current user only, as the +/// Windows checkpoint store requires of its private root. +#[cfg(windows)] +fn make_private_root(data: &Path) { + let whoami = std::process::Command::new("whoami") + .args(["/user", "/fo", "csv", "/nh"]) + .output() + .expect("whoami"); + assert!(whoami.status.success(), "whoami fixture failed"); + let identity = String::from_utf8_lossy(&whoami.stdout).into_owned(); + let sid = identity + .trim() + .rsplit(',') + .next() + .expect("SID column") + .trim_matches('"') + .to_owned(); + fs::create_dir(data).expect("application data"); + let granted = std::process::Command::new("icacls") + .arg(data) + .args(["/inheritance:r", "/grant:r", &format!("*{sid}:(OI)(CI)F")]) + .output() + .expect("icacls"); + assert!(granted.status.success(), "icacls fixture failed"); +} + +struct ScriptedModel { + replies: VecDeque>, +} + +impl ToolModel for ScriptedModel { + fn complete(&mut self, _request: ToolModelRequest<'_>) -> Result { + self.replies + .pop_front() + .unwrap_or(Err(ModelError::InvalidResponse)) + } +} + +fn manifest() -> RequestManifest { + RequestManifest { + base_prompt: BASE_PROMPT.to_owned(), + prompt_version: BASE_PROMPT_VERSION.to_owned(), + prompt_sha256: prompt::base_prompt_sha256(), + custom_instructions: String::new(), + model: "mock-model".into(), + base_url: "http://127.0.0.1:1234/v1".into(), + context_tokens: 32_000, + max_output_tokens: 1_000, + tool_schema_version: None, + tools: None, + } +} + +fn call(id: &str, name: &str, arguments: Value) -> Value { + json!({ + "id": id, + "type": "function", + "function": {"name": name, "arguments": arguments.to_string()} + }) +} + +fn command_call(id: &str, arguments: Value) -> Value { + call(id, COMMAND_TOOL, arguments) +} + +fn edit_call(id: &str, path: &str, old_text: &str, new_text: &str) -> Value { + call( + id, + EDIT_TOOL, + json!({"path": path, "old_text": old_text, "new_text": new_text}), + ) +} + +fn candidates(recorded: &[RecordedToolRequest]) -> Vec> { + recorded + .iter() + .map(|request| ReviewCandidate { + tool: &request.tool, + arguments: &request.arguments, + }) + .collect() +} + +fn read_events(path: &Path) -> Vec { + let Ok(bytes) = fs::read(path) else { + return Vec::new(); + }; + bytes + .split(|byte| *byte == b'\n') + .filter(|line| !line.is_empty()) + .map(|line| serde_json::from_slice(line).expect("bounded JSONL event")) + .collect() +} + +fn sha256(bytes: &[u8]) -> String { + use sha2::{Digest, Sha256}; + Sha256::digest(bytes) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +fn exact(review: Result) -> ReviewedRequest { + match review.expect("review completes") { + ApprovalReview::Exact(request) => request, + other => panic!("expected an exact match, found {other:?}"), + } +} + +fn field<'a>(request: &'a ReviewedRequest, label: &str) -> &'a ReviewField { + request + .fields + .iter() + .find(|field| field.label == label) + .unwrap_or_else(|| panic!("no {label:?} field in {request:?}")) +} + +/// A value the review may show: no control or hidden character but `\n`. +fn assert_display_clean(text: &str) { + for character in text.chars() { + let hidden = matches!( + character, + '\u{061c}' + | '\u{200b}'..='\u{200f}' + | '\u{2028}'..='\u{202e}' + | '\u{2060}'..='\u{2069}' + | '\u{feff}' + ); + assert!( + character == '\n' || (!character.is_control() && !hidden), + "unsafe character {character:?} in {text:?}" + ); + } +} + +/// A workspace identifier that is registered in no store this test opens. +fn foreign_workspace_id() -> WorkspaceId { + let temporary = TempDir::new().expect("private temporary directory"); + let root = temporary.path().join("root"); + let workspace = root.join("other"); + fs::create_dir_all(&workspace).expect("create workspace"); + let mut control = ControlStore::open(&temporary.path().join("data")).expect("open store"); + control + .set_development_root(&root, control.revision()) + .expect("select development root"); + control + .register_workspace(&workspace, control.revision()) + .expect("register workspace") + .id() +} + +fn statuses_json(statuses: &[ApprovalStatus]) -> String { + serde_json::to_string(statuses).expect("serialize statuses") +} + +// ---------------------------------------------------------------- commands + +#[test] +fn a_command_approval_reviews_exact_fields_and_changes_nothing() { + let mut fixture = Fixture::new(); + fixture.turn(vec![command_call( + "cmd-1", + json!({ + "profile": "system", + "program": "echo", + "arguments": ["hello", "two words", ""], + "cwd": "sub/dir", + }), + )]); + let approval = fixture.pending(ApprovalOperation::Command); + let recorded = fixture.recorded(); + let before = statuses_json(&fixture.approvals()); + + let request = exact(fixture.review(&approval, &recorded)); + + assert_eq!(request.tool, COMMAND_TOOL); + let values: Vec<(&str, &str, bool)> = request + .fields + .iter() + .map(|field| (field.label, field.value.as_str(), field.multiline)) + .collect(); + assert_eq!( + values, + [ + ("Profile", "system", false), + ("Program", "echo", false), + ("Arguments", "1: hello\n2: two words\n3: ", true), + ("Working directory", "sub/dir", false), + ("Network", "off", false), + ("Host services", "off", false), + ("Time limit", "20 seconds", false), + ("Output limit", "4096 bytes per stream", false), + ] + ); + // Reviewing is read-only: the record is still pending and unchanged, and + // nothing ran. + assert_eq!(statuses_json(&fixture.approvals()), before); + assert_eq!(fixture.state(approval.id), ApprovalState::Pending); + assert!(!fixture.data.join("runs-v1.jsonl").exists()); +} + +/// The review digest and the dispatch digest are the same value: after an +/// exact review, approving the record lets the identical call consume it and +/// reach the runner. As in the existing approved-command test the fixture +/// profile has no PATH entry, so the run is refused after consumption +/// (`command_failed`); that proves the gate and the hand-off, and this +/// suite does not qualify native confinement. +#[test] +fn an_exactly_reviewed_command_is_the_call_that_consumes_the_approval() { + let mut fixture = Fixture::new(); + let arguments = json!({"profile": "system", "program": "echo", "arguments": ["hello"]}); + fixture.turn(vec![command_call("cmd-1", arguments.clone())]); + let approval = fixture.pending(ApprovalOperation::Command); + let recorded = fixture.recorded(); + exact(fixture.review(&approval, &recorded)); + + ControlStore::open_existing(&fixture.data) + .expect("open control") + .expect("control store") + .decide_approval(approval.id, true, now_unix()) + .expect("approve"); + fixture.turn(vec![command_call("cmd-2", arguments)]); + + assert_eq!(fixture.state(approval.id), ApprovalState::Consumed); + // The journal file is locked while the session is open, so read the + // recorded tool result from its snapshot. + assert!( + fixture + .journal + .snapshot() + .messages + .iter() + .any(|message| message.text.contains("\"status\":\"command_failed\"")), + "the approved call did not reach the runner" + ); +} + +#[test] +fn an_earlier_matching_command_is_reviewed_not_the_newest_candidate() { + let mut fixture = Fixture::new(); + fixture.turn(vec![command_call( + "cmd-1", + json!({"profile": "system", "program": "echo"}), + )]); + let approval = fixture.pending(ApprovalOperation::Command); + let mut recorded = fixture.recorded(); + // Newer requests that were never approved, one valid and one malformed. + for (index, arguments) in [ + r#"{"profile":"system","program":"rm","arguments":["-rf","x"]}"#, + r#"{"profile":"system","program":"echo","unexpected":true}"#, + "not json at all", + ] + .into_iter() + .enumerate() + { + recorded.push(RecordedToolRequest { + request_id: Uuid::new_v4(), + call_id: format!("later-{index}"), + tool: COMMAND_TOOL.to_owned(), + arguments: arguments.to_owned(), + }); + } + + let request = exact(fixture.review(&approval, &recorded)); + + assert_eq!(field(&request, "Program").value, "echo"); + assert_eq!(field(&request, "Arguments").value, "(none)"); + assert_eq!( + field(&request, "Working directory").value, + "(workspace root)" + ); +} + +#[test] +fn a_command_review_is_stale_or_not_found_when_nothing_matches() { + let mut fixture = Fixture::new(); + fixture.turn(vec![command_call( + "cmd-1", + json!({"profile": "system", "program": "echo", "arguments": ["a"]}), + )]); + let approval = fixture.pending(ApprovalOperation::Command); + let recorded = fixture.recorded(); + + // Another session's approval for identical arguments is a different digest. + let other_session = ApprovalStatus { + session_id: Uuid::new_v4(), + ..approval.clone() + }; + assert_eq!( + fixture.review(&other_session, &recorded).expect("review"), + ApprovalReview::Stale(StaleReason::NoMatchingRequest) + ); + // Candidates of another tool do not count. + let edits_only = [RecordedToolRequest { + request_id: Uuid::new_v4(), + call_id: "e".into(), + tool: EDIT_TOOL.into(), + arguments: r#"{"path":"a","old_text":"b","new_text":"c"}"#.into(), + }]; + assert_eq!( + fixture.review(&approval, &edits_only).expect("review"), + ApprovalReview::NotFound + ); + assert_eq!( + fixture.review(&approval, &[]).expect("review"), + ApprovalReview::NotFound + ); + // Operations without a reviewable tool. + for operation in [ApprovalOperation::GitPush, ApprovalOperation::Network] { + let unreviewable = ApprovalStatus { + operation, + ..approval.clone() + }; + assert_eq!( + fixture.review(&unreviewable, &recorded).expect("review"), + ApprovalReview::NotFound + ); + } + // An unregistered workspace. + let unknown = ApprovalStatus { + workspace_id: foreign_workspace_id(), + ..approval.clone() + }; + assert_eq!( + fixture.review(&unknown, &recorded).expect("review"), + ApprovalReview::NotFound + ); + + // A settings change bumps the revision: the record can never be consumed. + let mut control = ControlStore::open_existing(&fixture.data) + .expect("open control") + .expect("control store"); + control + .set_permissions( + fixture.workspace_id, + PermissionSet { + model_tools: true, + execute: true, + read: true, + write: true, + host_services: true, + ..PermissionSet::default() + }, + control.revision(), + ) + .expect("change settings"); + drop(control); + assert_eq!( + fixture.review(&approval, &recorded).expect("review"), + ApprovalReview::Stale(StaleReason::SettingsChanged) + ); +} + +#[test] +fn a_missing_settings_store_is_not_found() { + let empty = TempDir::new().expect("empty data directory"); + let approval = ApprovalStatus { + id: Uuid::new_v4(), + session_id: Uuid::new_v4(), + workspace_id: foreign_workspace_id(), + operation: ApprovalOperation::Command, + request_sha256: "0".repeat(64), + summary: "run".into(), + settings_revision: 1, + created_unix: 0, + expires_unix: 0, + state: ApprovalState::Pending, + writers_stopped: false, + }; + let candidate = ReviewCandidate { + tool: COMMAND_TOOL, + arguments: r#"{"profile":"system","program":"echo"}"#, + }; + assert_eq!( + review_approval(empty.path(), &approval, &[candidate]).expect("review"), + ApprovalReview::NotFound + ); + assert!( + !empty.path().join("control-v1.jsonl").exists(), + "nothing created" + ); +} + +#[test] +fn a_held_settings_store_makes_the_review_busy() { + let mut fixture = Fixture::new(); + fixture.turn(vec![command_call( + "cmd-1", + json!({"profile": "system", "program": "echo"}), + )]); + let approval = fixture.pending(ApprovalOperation::Command); + let recorded = fixture.recorded(); + let held = ControlStore::open_existing(&fixture.data) + .expect("open control") + .expect("control store"); + + let result = fixture.review(&approval, &recorded); + assert!(matches!(result, Err(ReviewError::Busy)), "{result:?}"); + let message = result.expect_err("busy").to_string(); + assert!(!message.contains(fixture.data.to_string_lossy().as_ref())); + + drop(held); + exact(fixture.review(&approval, &recorded)); +} + +#[test] +fn hostile_command_text_is_escaped_and_cannot_add_lines() { + let mut fixture = Fixture::new(); + let arguments = [ + "plain", + "a\u{202e}b", + "zero\u{200b}width", + "cr\rtab\tend", + "line\n9: forged argument", + r"literal \u{202e} text", + ]; + fixture.turn(vec![command_call( + "cmd-1", + json!({"profile": "system", "program": "echo", "arguments": arguments}), + )]); + let approval = fixture.pending(ApprovalOperation::Command); + let recorded = fixture.recorded(); + + let request = exact(fixture.review(&approval, &recorded)); + + for field in &request.fields { + assert_display_clean(&field.value); + } + let shown = field(&request, "Arguments"); + let lines: Vec<&str> = shown.value.lines().collect(); + assert_eq!( + lines.len(), + arguments.len(), + "one line per argument: {lines:?}" + ); + assert_eq!(lines[1], "2: a\\u{202e}b"); + assert_eq!(lines[2], "3: zero\\u{200b}width"); + assert_eq!(lines[3], "4: cr\\u{000d}tab\\u{0009}end"); + assert_eq!(lines[4], "5: line\\u{000a}9: forged argument"); + assert_eq!(lines[5], "6: literal \\u{5c}u{202e} text"); +} + +// ------------------------------------------------------------------- edits + +#[test] +fn an_edit_approval_reviews_exact_fields_without_touching_the_file() { + let mut fixture = Fixture::new(); + let target = fixture.write_file("notes.txt", "alpha bcc\n"); + fixture.turn(vec![edit_call("edit-1", "notes.txt", "bc", "b")]); + let approval = fixture.pending(ApprovalOperation::FileWrite); + let recorded = fixture.recorded(); + let before = statuses_json(&fixture.approvals()); + let reads = fixture.audit_reads(); + + let request = exact(fixture.review(&approval, &recorded)); + + assert_eq!(request.tool, EDIT_TOOL); + let values: Vec<(&str, String, bool)> = request + .fields + .iter() + .map(|field| (field.label, field.value.clone(), field.multiline)) + .collect(); + assert_eq!( + values, + [ + ("File", "notes.txt".to_owned(), false), + ("Old text", "bc".to_owned(), true), + ("New text", "b".to_owned(), true), + ("Size", "10 -> 9 bytes".to_owned(), false), + ("Current SHA-256", sha256(b"alpha bcc\n"), false), + ("Proposed SHA-256", sha256(b"alpha bc\n"), false), + ] + ); + assert_eq!(fs::read(&target).expect("read"), b"alpha bcc\n"); + assert_eq!(fixture.checkpoint_operations(), 0); + assert_eq!(statuses_json(&fixture.approvals()), before); + assert_eq!(fixture.audit_reads(), reads + 1, "one audited read"); +} + +/// After an exact review and an approval with the writers-stopped +/// acknowledgement, the identical call applies the edit: the review digest is +/// the dispatch digest. +#[test] +fn an_exactly_reviewed_edit_is_the_call_that_applies() { + let mut fixture = Fixture::new(); + let target = fixture.write_file("notes.txt", "alpha bcc\n"); + let arguments = edit_call("edit-1", "notes.txt", "bc", "b"); + fixture.turn(vec![arguments.clone()]); + let approval = fixture.pending(ApprovalOperation::FileWrite); + let recorded = fixture.recorded(); + exact(fixture.review(&approval, &recorded)); + + ControlStore::open_existing(&fixture.data) + .expect("open control") + .expect("control store") + .approve_with_writers_stopped(approval.id, now_unix()) + .expect("approve the edit"); + fixture.turn(vec![edit_call("edit-2", "notes.txt", "bc", "b")]); + + assert_eq!(fs::read_to_string(&target).expect("read"), "alpha bc\n"); + assert_eq!(fixture.state(approval.id), ApprovalState::Consumed); + assert_eq!(fixture.checkpoint_operations(), 1); +} + +#[test] +fn an_edit_review_is_stale_after_the_file_changes() { + let mut fixture = Fixture::new(); + let target = fixture.write_file("notes.txt", "xa"); + fixture.turn(vec![edit_call("edit-1", "notes.txt", "x", "")]); + let approval = fixture.pending(ApprovalOperation::FileWrite); + let recorded = fixture.recorded(); + exact(fixture.review(&approval, &recorded)); + + fs::write(&target, "ax").expect("change the file after the request"); + + assert_eq!( + fixture.review(&approval, &recorded).expect("review"), + ApprovalReview::Stale(StaleReason::NoMatchingRequest) + ); + // A removed file is also simply not a match. + fs::remove_file(&target).expect("remove the file"); + assert_eq!( + fixture.review(&approval, &recorded).expect("review"), + ApprovalReview::Stale(StaleReason::NoMatchingRequest) + ); + assert_eq!(fixture.checkpoint_operations(), 0); +} + +fn recorded_edit(index: usize, arguments: String) -> RecordedToolRequest { + RecordedToolRequest { + request_id: Uuid::new_v4(), + call_id: format!("edit-{index}"), + tool: EDIT_TOOL.to_owned(), + arguments, + } +} + +fn distinct_edit_arguments(index: usize) -> String { + json!({"path": "notes.txt", "old_text": "alpha", "new_text": format!("other{index}")}) + .to_string() +} + +#[test] +fn at_most_eight_distinct_edit_candidates_are_read_newest_first() { + let mut fixture = Fixture::new(); + fixture.write_file("notes.txt", "alpha bcc\n"); + fixture.turn(vec![edit_call("edit-1", "notes.txt", "bc", "b")]); + let approval = fixture.pending(ApprovalOperation::FileWrite); + let matching = fixture.recorded(); + + // Seven newer non-matching candidates: the matching one is the eighth. + let mut within = matching.clone(); + for index in 0..7 { + within.push(recorded_edit(index, distinct_edit_arguments(index))); + } + let reads = fixture.audit_reads(); + exact(fixture.review(&approval, &within)); + assert_eq!(fixture.audit_reads() - reads, 8); + + // Eight newer non-matching candidates push it past the bound. Repeats of + // one arguments string count once, so the bound is on distinct requests. + let mut beyond = matching; + for index in 0..8 { + beyond.push(recorded_edit(index, distinct_edit_arguments(index))); + beyond.push(recorded_edit(index + 100, distinct_edit_arguments(index))); + } + let reads = fixture.audit_reads(); + let result = fixture.review(&approval, &beyond).expect("review"); + assert_eq!( + result, + ApprovalReview::Stale(StaleReason::NoMatchingRequest) + ); + assert!( + fixture.audit_reads() - reads <= 8, + "{} audited reads", + fixture.audit_reads() - reads + ); + assert_eq!(fixture.audit_reads() - reads, 8); +} + +#[test] +fn hostile_edit_text_is_escaped_and_a_literal_escape_stays_distinguishable() { + let mut fixture = Fixture::new(); + // The file holds every kind of hostile character, including a NUL. + let contents = "x\u{202e}rtl\u{200b}zw\r\ttab\0nul \\u{202e} literal\nsecond\n"; + fixture.write_file("odd.txt", contents); + let replacement = "ok\u{2028}\u{feff}\r\\u{200b}"; + fixture.turn(vec![edit_call("edit-1", "odd.txt", contents, replacement)]); + let approval = fixture.pending(ApprovalOperation::FileWrite); + let recorded = fixture.recorded(); + + let request = exact(fixture.review(&approval, &recorded)); + + for field in &request.fields { + assert_display_clean(&field.value); + } + let old = &field(&request, "Old text").value; + assert_eq!( + old, + "x\\u{202e}rtl\\u{200b}zw\\u{000d}\\u{0009}tab\\u{0000}nul \\u{5c}u{202e} literal\nsecond\n" + ); + assert!(old.contains("\\u{202e}rtl"), "the real override is shown"); + assert!( + old.contains("\\u{5c}u{202e}"), + "the forged literal is marked" + ); + assert_eq!( + field(&request, "New text").value, + "ok\\u{2028}\\u{feff}\\u{000d}\\u{5c}u{200b}" + ); +} diff --git a/crates/omgcode-core/tests/session_index.rs b/crates/omgcode-core/tests/session_index.rs new file mode 100644 index 0000000..955554f --- /dev/null +++ b/crates/omgcode-core/tests/session_index.rs @@ -0,0 +1,1388 @@ +//! Native tests for the derived session index. Journals are real files made by +//! the real `SessionJournal`, and the index is a real SQLite database. + +use std::fs; +use std::path::{Path, PathBuf}; + +use omgcode_core::session::{ + CompactionRecord, MessageRole, NativePath, RequestManifest, SessionInspection, SessionJournal, + ToolOutcome, +}; +use omgcode_core::session_index::{ + APPLICATION_ID, ArchiveView, INDEX_DIRECTORY, INDEX_FILE, IndexError, IndexedSession, + IndexedState, SearchListing, SearchRole, SessionIndex, SessionListing, SessionQuery, + SessionSort, +}; +use rusqlite::Connection; +use sha2::{Digest, Sha256}; +use tempfile::TempDir; +use time::OffsetDateTime; +use uuid::Uuid; + +fn setup() -> (TempDir, PathBuf, PathBuf) { + let temp = TempDir::new().expect("temporary directory"); + let root = temp.path().join("app-data"); + let workspace = temp.path().join("workspace"); + fs::create_dir_all(&workspace).expect("workspace directory"); + (temp, root, workspace) +} + +fn sha256_hex(text: &str) -> String { + Sha256::digest(text.as_bytes()) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +fn manifest() -> RequestManifest { + RequestManifest { + base_prompt: "BASE-PROMPT-TEXT".into(), + prompt_version: "7".into(), + prompt_sha256: "a".repeat(64), + custom_instructions: "CUSTOM-INSTRUCTIONS-TEXT".into(), + model: "local-model".into(), + base_url: "http://127.0.0.1:1234/v1".into(), + context_tokens: 32_000, + max_output_tokens: 2_000, + tool_schema_version: Some("1".into()), + tools: Some(vec!["workspace_read_file".into()]), + } +} + +/// Create a journal with user messages, release it, and return id and path. +fn session(root: &Path, workspace: &Path, title: &str, messages: &[&str]) -> (Uuid, PathBuf) { + let mut journal = SessionJournal::create(root, workspace, title).expect("create"); + let id = journal.snapshot().session_id; + for message in messages { + journal + .record_message(MessageRole::User, message) + .expect("message"); + } + (id, journal.path().to_path_buf()) +} + +/// Move a journal file under another day directory and return its new path. +fn move_to_day(root: &Path, path: &Path, day: &str) -> PathBuf { + let directory = root.join("sessions").join(day); + fs::create_dir_all(&directory).expect("day directory"); + let target = directory.join(path.file_name().expect("file name")); + fs::rename(path, &target).expect("move journal"); + target +} + +fn append(path: &Path, text: &str) { + let mut journal = SessionJournal::open(path).expect("open writer"); + journal + .record_message(MessageRole::User, text) + .expect("append"); +} + +fn database_path(root: &Path) -> PathBuf { + root.join(INDEX_DIRECTORY).join(INDEX_FILE) +} + +fn refreshed(root: &Path) -> SessionIndex { + let mut index = SessionIndex::open(root).expect("open index"); + index.refresh(1000).expect("refresh"); + index +} + +fn query(view: ArchiveView, sort: SessionSort, descending: bool, limit: usize) -> SessionQuery { + SessionQuery { + view, + sort, + descending, + limit, + } +} + +fn list(index: &SessionIndex, view: ArchiveView) -> SessionListing { + index + .sessions(&query(view, SessionSort::Title, false, 5000)) + .expect("listing") +} + +fn ids(listing: &SessionListing) -> Vec { + listing.sessions.iter().map(|s| s.session_id).collect() +} + +fn find(index: &SessionIndex, text: &str, view: ArchiveView) -> SearchListing { + index.search(text, view, 50).expect("search") +} + +fn nanos(time: OffsetDateTime) -> i128 { + time.unix_timestamp_nanos() +} + +fn raw(root: &Path) -> Connection { + Connection::open(database_path(root)).expect("raw connection") +} + +fn read_all(paths: &[PathBuf]) -> Vec> { + paths + .iter() + .map(|path| fs::read(path).expect("journal bytes")) + .collect() +} + +#[test] +fn first_build_lists_every_session_with_the_inspected_metadata() { + // Given sessions in two workspaces on different days, one archived. + let (temp, root, workspace_a) = setup(); + let workspace_b = temp.path().join("workspace-b"); + fs::create_dir_all(&workspace_b).expect("second workspace"); + let (a1, p1) = session(&root, &workspace_a, "Alpha", &["one"]); + let (b1, p2) = session(&root, &workspace_b, "Bravo", &["two", "three"]); + let (a2, p3) = session(&root, &workspace_a, "Charlie", &[]); + let p1 = move_to_day(&root, &p1, "2025/03/04"); + let p2 = move_to_day(&root, &p2, "2025/03/05"); + let _ = move_to_day(&root, &p3, "2024/12/31"); + { + let mut journal = SessionJournal::open(&p2).expect("open"); + journal.archive().expect("archive"); + } + + // When the index is built. + let mut index = SessionIndex::open(&root).expect("open"); + let report = index.refresh(1000).expect("refresh"); + + // Then every journal was inspected and metadata matches the inspection. + assert_eq!(report.discovered, 3); + assert_eq!(report.inspected, 3); + assert_eq!( + report.unchanged + report.busy + report.invalid + report.removed, + 0 + ); + assert_eq!(report.remaining, 0); + let active = list(&index, ArchiveView::Active); + let archived = list(&index, ArchiveView::Archived); + assert_eq!((active.total, archived.total), (2, 1)); + assert_eq!(ids(&archived), vec![b1]); + let by_id = |listing: &SessionListing, id: Uuid| -> IndexedSession { + listing + .sessions + .iter() + .find(|s| s.session_id == id) + .expect("session listed") + .clone() + }; + for (id, path, listing) in [(a1, &p1, &active), (b1, &p2, &archived)] { + let inspection = SessionInspection::inspect(path).expect("inspect"); + let indexed = by_id(listing, id); + assert_eq!(indexed.state, IndexedState::Ok); + assert_eq!(indexed.invalid_code, None); + assert_eq!(indexed.title.as_deref(), Some(inspection.title.as_str())); + assert_eq!(indexed.workspace_id, Some(inspection.workspace_id)); + assert_eq!(indexed.workspace, Some(inspection.workspace.clone())); + assert_eq!( + indexed.folder_display, + Some( + inspection + .workspace + .to_path_buf() + .expect("native path") + .to_string_lossy() + .into_owned() + ) + ); + assert_eq!( + indexed.created_at.map(nanos), + Some(nanos(inspection.created_at)) + ); + assert_eq!( + indexed.updated_at.map(nanos), + Some(nanos(inspection.updated_at)) + ); + assert_eq!(indexed.archived, inspection.archived); + assert_eq!(indexed.active_turn, None); + assert_eq!(indexed.event_count, inspection.event_count); + assert!(!indexed.incomplete_tail); + assert_eq!(index.session(id).expect("lookup"), Some(indexed)); + } + assert_eq!(by_id(&active, a2).title.as_deref(), Some("Charlie")); + assert_eq!(by_id(&active, a1).workspace, by_id(&active, a2).workspace); + assert_ne!( + by_id(&active, a1).workspace_id, + by_id(&archived, b1).workspace_id + ); + assert_eq!(index.session(Uuid::new_v4()).expect("unknown"), None); +} + +#[test] +fn every_sort_key_orders_in_both_directions_with_deterministic_ties() { + // Given sessions where three titles differ only by case. + let (_temp, root, workspace) = setup(); + let mut known = Vec::new(); + for title in ["delta", "Same", "same", "SAME", "Éclair", "apple"] { + let (id, path) = session(&root, &workspace, title, &["x"]); + known.push(( + id, + title.to_owned(), + SessionInspection::inspect(&path).expect("inspect"), + )); + } + let index = refreshed(&root); + + for sort in [ + SessionSort::Updated, + SessionSort::Created, + SessionSort::Title, + ] { + for descending in [false, true] { + let mut expected: Vec<_> = known.iter().collect(); + expected.sort_by(|a, b| { + let primary = match sort { + SessionSort::Updated => nanos(a.2.updated_at).cmp(&nanos(b.2.updated_at)), + SessionSort::Created => nanos(a.2.created_at).cmp(&nanos(b.2.created_at)), + SessionSort::Title => a.1.to_lowercase().cmp(&b.1.to_lowercase()), + }; + let primary = if descending { + primary.reverse() + } else { + primary + }; + primary.then(a.0.cmp(&b.0)) + }); + let listing = index + .sessions(&query(ArchiveView::Active, sort, descending, 5000)) + .expect("listing"); + let expected_ids: Vec = expected.iter().map(|k| k.0).collect(); + assert_eq!( + ids(&listing), + expected_ids, + "{sort:?} descending={descending}" + ); + } + } + // The tied titles come out in ascending session id whichever way titles sort. + for descending in [false, true] { + let listing = index + .sessions(&query( + ArchiveView::Active, + SessionSort::Title, + descending, + 5000, + )) + .expect("listing"); + let tied: Vec = listing + .sessions + .iter() + .filter(|s| { + s.title + .as_deref() + .is_some_and(|t| t.eq_ignore_ascii_case("same")) + }) + .map(|s| s.session_id) + .collect(); + let mut sorted = tied.clone(); + sorted.sort(); + assert_eq!(tied, sorted); + assert_eq!(tied.len(), 3); + } +} + +#[test] +fn listing_reports_the_view_total_before_the_limit_and_clamps_the_limit() { + let (_temp, root, workspace) = setup(); + for index in 0..5 { + session(&root, &workspace, &format!("Session {index}"), &[]); + } + let index = refreshed(&root); + + let two = index + .sessions(&query(ArchiveView::Active, SessionSort::Title, false, 2)) + .expect("two"); + assert_eq!((two.sessions.len(), two.total), (2, 5)); + let zero = index + .sessions(&query(ArchiveView::Active, SessionSort::Title, false, 0)) + .expect("zero clamps to one"); + assert_eq!((zero.sessions.len(), zero.total), (1, 5)); + let huge = index + .sessions(&query( + ArchiveView::Active, + SessionSort::Title, + false, + usize::MAX, + )) + .expect("huge clamps"); + assert_eq!((huge.sessions.len(), huge.total), (5, 5)); + let archived = list(&index, ArchiveView::Archived); + assert_eq!((archived.sessions.len(), archived.total), (0, 0)); +} + +#[test] +fn a_second_refresh_inspects_nothing_and_an_append_reindexes_only_that_journal() { + let (_temp, root, workspace) = setup(); + let mut paths = Vec::new(); + for index in 0..4 { + paths.push(session(&root, &workspace, &format!("S{index}"), &["first"]).1); + } + let mut index = SessionIndex::open(&root).expect("open"); + assert_eq!(index.refresh(1000).expect("first").inspected, 4); + + let second = index.refresh(1000).expect("second"); + assert_eq!( + (second.discovered, second.unchanged, second.inspected), + (4, 4, 0) + ); + assert_eq!(second.remaining, 0); + + append(&paths[2], "uniqueappended"); + let third = index.refresh(1000).expect("third"); + assert_eq!((third.inspected, third.unchanged), (1, 3)); + assert_eq!( + find(&index, "uniqueappended", ArchiveView::Active) + .hits + .len(), + 1 + ); +} + +#[test] +fn a_deleted_journal_leaves_the_listing_and_the_search() { + let (_temp, root, workspace) = setup(); + let (keep, _) = session(&root, &workspace, "Keep", &["keepword"]); + let (gone, gone_path) = session(&root, &workspace, "Gone", &["goneword"]); + let mut index = SessionIndex::open(&root).expect("open"); + index.refresh(1000).expect("first"); + assert_eq!(find(&index, "goneword", ArchiveView::Active).hits.len(), 1); + + fs::remove_file(&gone_path).expect("delete journal"); + let report = index.refresh(1000).expect("second"); + + assert_eq!( + (report.removed, report.discovered, report.unchanged), + (1, 1, 1) + ); + assert_eq!(ids(&list(&index, ArchiveView::Active)), vec![keep]); + assert!( + find(&index, "goneword", ArchiveView::Active) + .hits + .is_empty() + ); + assert_eq!(find(&index, "keepword", ArchiveView::Active).hits.len(), 1); + assert_eq!(index.session(gone).expect("lookup"), None); + assert_eq!(index.journal_path(gone).expect("path lookup"), None); +} + +#[test] +fn a_small_budget_leaves_remaining_work_and_repeated_calls_converge() { + let (_temp, root, workspace) = setup(); + for index in 0..5 { + session(&root, &workspace, &format!("S{index}"), &[]); + } + let mut index = SessionIndex::open(&root).expect("open"); + + let first = index.refresh(2).expect("first"); + assert_eq!((first.inspected, first.remaining), (2, 3)); + assert_eq!(list(&index, ArchiveView::Active).total, 2); + let second = index.refresh(2).expect("second"); + assert_eq!( + (second.inspected, second.unchanged, second.remaining), + (2, 2, 1) + ); + let third = index.refresh(2).expect("third"); + assert_eq!( + (third.inspected, third.unchanged, third.remaining), + (1, 4, 0) + ); + assert_eq!(list(&index, ArchiveView::Active).total, 5); + // A zero budget is clamped to one journal rather than doing nothing. + session(&root, &workspace, "Late", &[]); + assert_eq!(index.refresh(0).expect("clamped").inspected, 1); +} + +#[test] +fn archive_and_restore_are_reflected_after_a_refresh() { + let (_temp, root, workspace) = setup(); + let (id, path) = session(&root, &workspace, "Cycle", &["body"]); + let mut index = SessionIndex::open(&root).expect("open"); + index.refresh(1000).expect("first"); + assert_eq!(ids(&list(&index, ArchiveView::Active)), vec![id]); + + SessionJournal::open(&path) + .expect("open") + .archive() + .expect("archive"); + index.refresh(1000).expect("after archive"); + assert!(list(&index, ArchiveView::Active).sessions.is_empty()); + assert_eq!(ids(&list(&index, ArchiveView::Archived)), vec![id]); + assert!(index.session(id).expect("lookup").expect("row").archived); + assert_eq!(find(&index, "body", ArchiveView::Archived).hits.len(), 1); + assert!(find(&index, "body", ArchiveView::Active).hits.is_empty()); + + SessionJournal::open(&path) + .expect("open") + .restore() + .expect("restore"); + index.refresh(1000).expect("after restore"); + assert_eq!(ids(&list(&index, ArchiveView::Active)), vec![id]); + assert!(list(&index, ArchiveView::Archived).sessions.is_empty()); +} + +#[test] +fn an_unfinished_turn_is_reported_as_the_active_turn() { + let (_temp, root, workspace) = setup(); + let mut journal = SessionJournal::create(&root, &workspace, "Busy turn").expect("create"); + let id = journal.snapshot().session_id; + let turn = journal.start_turn().expect("turn"); + drop(journal); + + let index = refreshed(&root); + + let indexed = index.session(id).expect("lookup").expect("row"); + assert_eq!(indexed.state, IndexedState::Ok); + assert_eq!(indexed.active_turn, Some(turn)); +} + +#[cfg(windows)] +#[test] +fn a_journal_held_by_a_writer_keeps_its_previous_data_and_is_retried() { + let (_temp, root, workspace) = setup(); + let (id, path) = session(&root, &workspace, "Orchard", &["original apple"]); + let mut index = SessionIndex::open(&root).expect("open"); + index.refresh(1000).expect("first"); + let before = index.session(id).expect("lookup").expect("row"); + + let mut writer = SessionJournal::open(&path).expect("hold the writer lock"); + writer + .record_message(MessageRole::User, "added banana") + .expect("append"); + let held = index.refresh(1000).expect("refresh beside writer"); + assert_eq!((held.inspected, held.busy), (1, 1)); + let busy = index.session(id).expect("lookup").expect("row"); + assert_eq!(busy.state, IndexedState::Busy); + assert_eq!(busy.title, before.title); + assert_eq!(busy.updated_at, before.updated_at); + assert_eq!(busy.event_count, before.event_count); + assert_eq!(find(&index, "apple", ArchiveView::Active).hits.len(), 1); + assert!(find(&index, "banana", ArchiveView::Active).hits.is_empty()); + // A busy row is retried on every refresh, never treated as unchanged. + assert_eq!(index.refresh(1000).expect("again").inspected, 1); + + drop(writer); + let released = index.refresh(1000).expect("refresh after release"); + assert_eq!((released.inspected, released.busy), (1, 0)); + let ok = index.session(id).expect("lookup").expect("row"); + assert_eq!(ok.state, IndexedState::Ok); + assert_eq!(ok.event_count, before.event_count + 1); + assert_eq!(find(&index, "banana", ArchiveView::Active).hits.len(), 1); +} + +#[cfg(windows)] +#[test] +fn a_never_indexed_journal_held_by_a_writer_gets_a_minimal_busy_row() { + let (_temp, root, workspace) = setup(); + let writer = SessionJournal::create(&root, &workspace, "Held").expect("create"); + let id = writer.snapshot().session_id; + let mut index = SessionIndex::open(&root).expect("open"); + + let report = index.refresh(1000).expect("refresh"); + + assert_eq!((report.inspected, report.busy), (1, 1)); + let row = index.session(id).expect("lookup").expect("row"); + assert_eq!(row.state, IndexedState::Busy); + assert_eq!( + (row.title, row.workspace, row.created_at, row.updated_at), + (None, None, None, None) + ); + assert_eq!((row.archived, row.event_count), (false, 0)); + // A busy row with no data counts as active and sorts after known rows. + assert_eq!(ids(&list(&index, ArchiveView::Active)), vec![id]); + let refreshed_row = index + .refresh_session(id) + .expect("refresh one") + .expect("row"); + assert_eq!(refreshed_row.state, IndexedState::Busy); + drop(writer); + index.refresh(1000).expect("after release"); + assert_eq!( + index + .session(id) + .expect("lookup") + .expect("row") + .title + .as_deref(), + Some("Held") + ); +} + +#[cfg(unix)] +#[test] +fn inspection_beside_a_live_writer_indexes_the_journal() { + let (_temp, root, workspace) = setup(); + let mut writer = SessionJournal::create(&root, &workspace, "Live").expect("create"); + let id = writer.snapshot().session_id; + writer + .record_message(MessageRole::User, "written while held") + .expect("message"); + let mut index = SessionIndex::open(&root).expect("open"); + + let report = index.refresh(1000).expect("refresh"); + + assert_eq!((report.inspected, report.busy), (1, 0)); + assert_eq!( + index.session(id).expect("lookup").expect("row").state, + IndexedState::Ok + ); + assert_eq!(find(&index, "written", ArchiveView::Active).hits.len(), 1); +} + +#[test] +fn a_corrupt_journal_is_invalid_without_text_and_not_reinspected_until_it_changes() { + let (_temp, root, workspace) = setup(); + let (id, path) = session(&root, &workspace, "Fragile", &["valuableword"]); + let valid = fs::read(&path).expect("valid bytes"); + let mut index = SessionIndex::open(&root).expect("open"); + index.refresh(1000).expect("first"); + assert_eq!( + find(&index, "valuableword", ArchiveView::Active).hits.len(), + 1 + ); + + fs::write(&path, b"this is not a journal\n").expect("corrupt"); + let corrupt = index.refresh(1000).expect("second"); + assert_eq!((corrupt.inspected, corrupt.invalid), (1, 1)); + let row = index.session(id).expect("lookup").expect("row"); + assert_eq!(row.state, IndexedState::Invalid); + let code = row.invalid_code.expect("code"); + assert!(code.starts_with("invalid_journal"), "{code}"); + assert_eq!( + (row.title, row.created_at, row.workspace), + (None, None, None) + ); + assert!( + find(&index, "valuableword", ArchiveView::Active) + .hits + .is_empty() + ); + assert!(find(&index, "Fragile", ArchiveView::Active).hits.is_empty()); + + let settled = index.refresh(1000).expect("third"); + assert_eq!( + (settled.inspected, settled.unchanged, settled.invalid), + (0, 1, 0) + ); + + fs::write(&path, &valid).expect("replace with a valid file"); + let fixed = index.refresh(1000).expect("fourth"); + assert_eq!((fixed.inspected, fixed.invalid), (1, 0)); + let row = index.session(id).expect("lookup").expect("row"); + assert_eq!(row.state, IndexedState::Ok); + assert_eq!(row.invalid_code, None); + assert_eq!( + find(&index, "valuableword", ArchiveView::Active).hits.len(), + 1 + ); +} + +#[test] +fn a_journal_whose_events_name_another_session_is_invalid() { + let (_temp, root, workspace) = setup(); + let (id, path) = session(&root, &workspace, "Mismatch", &["text"]); + let other = Uuid::new_v4(); + let text = fs::read_to_string(&path) + .expect("journal text") + .replace(&id.to_string(), &other.to_string()); + // The file name still carries `id`; every event now carries `other`. + fs::write(&path, text).expect("rewrite"); + + let index = refreshed(&root); + + let row = index.session(id).expect("lookup").expect("row"); + assert_eq!(row.state, IndexedState::Invalid); + assert!(row.invalid_code.is_some()); + assert!(find(&index, "text", ArchiveView::Active).hits.is_empty()); +} + +#[test] +fn two_files_with_one_session_id_are_invalid_and_neither_is_indexed() { + let (_temp, root, workspace) = setup(); + let (id, path) = session(&root, &workspace, "Twin", &["twinword"]); + let copy_directory = root.join("sessions/2020/01/01"); + fs::create_dir_all(©_directory).expect("directory"); + let copy = copy_directory.join(path.file_name().expect("name")); + fs::copy(&path, ©).expect("duplicate file"); + let mut index = SessionIndex::open(&root).expect("open"); + + let report = index.refresh(1000).expect("refresh"); + + assert_eq!( + (report.discovered, report.invalid, report.inspected), + (2, 1, 0) + ); + let row = index.session(id).expect("lookup").expect("row"); + assert_eq!(row.state, IndexedState::Invalid); + assert_eq!(row.invalid_code.as_deref(), Some("duplicate_session_id")); + assert!( + find(&index, "twinword", ArchiveView::Active) + .hits + .is_empty() + ); + assert!(matches!( + index.journal_path(id), + Err(IndexError::InvalidIndexEntry(_)) + )); + let settled = index.refresh(1000).expect("again"); + assert_eq!( + (settled.unchanged, settled.invalid, settled.inspected), + (1, 0, 0) + ); + + fs::remove_file(©).expect("remove the duplicate"); + let resolved = index.refresh(1000).expect("resolved"); + assert_eq!((resolved.inspected, resolved.invalid), (1, 0)); + assert_eq!( + index.session(id).expect("lookup").expect("row").state, + IndexedState::Ok + ); + assert_eq!(find(&index, "twinword", ArchiveView::Active).hits.len(), 1); +} + +#[test] +fn refresh_session_reinspects_one_session_regardless_of_size_and_time() { + let (_temp, root, workspace) = setup(); + let (id, _) = session(&root, &workspace, "Genuine title", &["body"]); + let mut index = SessionIndex::open(&root).expect("open"); + index.refresh(1000).expect("first"); + raw(&root) + .execute("UPDATE journal SET title = 'Tampered title'", []) + .expect("tamper"); + index.refresh(1000).expect("cache hit"); + assert_eq!( + index + .session(id) + .expect("lookup") + .expect("row") + .title + .as_deref(), + Some("Tampered title") + ); + + let row = index + .refresh_session(id) + .expect("refresh one") + .expect("row"); + + assert_eq!(row.title.as_deref(), Some("Genuine title")); + assert_eq!( + index.refresh_session(Uuid::new_v4()).expect("unknown"), + None + ); +} + +#[test] +fn refresh_session_forgets_a_vanished_journal() { + let (_temp, root, workspace) = setup(); + let (id, path) = session(&root, &workspace, "Vanishing", &["vanishword"]); + let mut index = refreshed(&root); + fs::remove_file(path).expect("delete"); + + assert_eq!(index.refresh_session(id).expect("refresh one"), None); + + assert_eq!(index.session(id).expect("lookup"), None); + assert!( + find(&index, "vanishword", ArchiveView::Active) + .hits + .is_empty() + ); +} + +fn sample_index() -> (TempDir, PathBuf, SessionIndex) { + let (temp, root, workspace) = setup(); + session( + &root, + &workspace, + "Zebra planning", + &[ + "The quick brown fox jumps over the lazy dog", + "Caf\u{e9} r\u{e9}sum\u{e9} and na\u{ef}ve fa\u{e7}ade", + ], + ); + session(&root, &workspace, "Other", &["a only b", "text only"]); + let index = refreshed(&root); + (temp, root, index) +} + +#[test] +fn search_requires_every_term_and_matches_a_prefix_on_the_last_term_only() { + let (_temp, _root, index) = sample_index(); + let hits = |text: &str| find(&index, text, ArchiveView::Active).hits.len(); + + assert_eq!(hits("quick"), 1); + assert_eq!(hits("quick dog"), 1); + assert_eq!(hits("quick cat"), 0); + assert_eq!(hits("dog quick"), 1); + // The last term is a prefix; an earlier term must match a whole token. + assert_eq!(hits("qui"), 1); + assert_eq!(hits("brown fo"), 1); + assert_eq!(hits("qui brown"), 0); + // Case and diacritics do not matter. + assert_eq!(hits("FOX"), 1); + assert_eq!(hits("cafe"), 1); + assert_eq!(hits("RESUME"), 1); + assert_eq!(hits("naive facade"), 1); + assert_eq!(hits("caf\u{e9}"), 1); +} + +#[test] +fn title_hits_have_no_sequence_and_message_hits_carry_their_role_and_sequence() { + let (_temp, root, workspace) = setup(); + let mut journal = SessionJournal::create(&root, &workspace, "Zebra planning").expect("create"); + journal + .record_message(MessageRole::User, "usermarker line") + .expect("user"); + let turn = journal.start_turn().expect("turn"); + journal.record_manifest(turn, manifest()).expect("manifest"); + journal + .record_tool_request( + turn, + "call-1", + "workspace_read_file", + "{\"path\":\"a.txt\"}", + ) + .expect("request"); + let rendered = "toolmarker output"; + journal + .record_tool_result( + turn, + "call-1", + ToolOutcome::Succeeded, + None, + u64::try_from(rendered.len()).expect("size"), + &sha256_hex(rendered), + ) + .expect("result"); + journal + .record_tool_message("call-1", rendered) + .expect("tool message"); + journal + .record_message(MessageRole::Assistant, "assistantmarker reply") + .expect("assistant"); + journal.complete_turn(turn).expect("complete"); + journal + .record_message(MessageRole::User, "after the turn") + .expect("later user"); + let summary = "summarymarker of earlier work"; + journal + .record_compaction(CompactionRecord { + summary: summary.into(), + compacted_messages: 3, + includes_tool_results: true, + summary_sha256: sha256_hex(summary), + model: "fixture".into(), + prompt_tokens: None, + completion_tokens: None, + }) + .expect("compaction"); + let path = journal.path().to_path_buf(); + drop(journal); + let inspection = SessionInspection::inspect(&path).expect("inspect"); + let index = refreshed(&root); + + let title = &find(&index, "zebra", ArchiveView::Active).hits; + assert_eq!( + (title.len(), title[0].seq, title[0].role), + (1, None, SearchRole::Title) + ); + for (term, role) in [ + ("usermarker", SearchRole::User), + ("toolmarker", SearchRole::Tool), + ("assistantmarker", SearchRole::Assistant), + ("summarymarker", SearchRole::Summary), + ] { + let hits = find(&index, term, ArchiveView::Active).hits; + assert_eq!(hits.len(), 1, "{term}"); + assert_eq!(hits[0].role, role, "{term}"); + let seq = hits[0].seq.expect("message hits have a sequence"); + assert!( + inspection.entries.iter().any(|entry| entry.seq == seq), + "{term}" + ); + } + // Tool-call arguments and manifests are not indexed. + for unindexed in [ + "workspace_read_file", + "a.txt", + "CUSTOM-INSTRUCTIONS-TEXT", + "local-model", + ] { + assert!( + find(&index, unindexed, ArchiveView::Active).hits.is_empty(), + "{unindexed}" + ); + } +} + +#[test] +fn search_reports_truncation_honors_the_view_and_clamps_the_limit() { + let (_temp, root, workspace) = setup(); + for number in 0..5 { + session( + &root, + &workspace, + &format!("S{number}"), + &["commonword here"], + ); + } + let (_, archived_path) = session(&root, &workspace, "Old", &["commonword archived"]); + SessionJournal::open(&archived_path) + .expect("open") + .archive() + .expect("archive"); + let many: Vec = (0..205).map(|n| format!("needleword {n}")).collect(); + let many_refs: Vec<&str> = many.iter().map(String::as_str).collect(); + session(&root, &workspace, "Many", &many_refs); + let index = refreshed(&root); + + let three = index + .search("commonword", ArchiveView::Active, 3) + .expect("three"); + assert_eq!((three.hits.len(), three.truncated), (3, true)); + let all = index + .search("commonword", ArchiveView::Active, 5) + .expect("five"); + assert_eq!((all.hits.len(), all.truncated), (5, false)); + let zero = index + .search("commonword", ArchiveView::Active, 0) + .expect("zero"); + assert_eq!((zero.hits.len(), zero.truncated), (1, true)); + let archived = index + .search("commonword", ArchiveView::Archived, 10) + .expect("archived"); + assert_eq!(archived.hits.len(), 1); + assert!(archived.hits[0].session.archived); + let clamped = index + .search("needleword", ArchiveView::Active, usize::MAX) + .expect("clamp"); + assert_eq!((clamped.hits.len(), clamped.truncated), (200, true)); +} + +#[test] +fn unusable_search_text_is_rejected_with_a_typed_error() { + let (_temp, _root, index) = sample_index(); + for text in ["", " ", "\t\n", &"x".repeat(257), &"a ".repeat(17)] { + assert!( + matches!( + index.search(text, ArchiveView::Active, 10), + Err(IndexError::InvalidQuery(_)) + ), + "{text:?}" + ); + } + assert!( + index + .search(&"x".repeat(256), ArchiveView::Active, 10) + .is_ok() + ); +} + +#[test] +fn hostile_search_text_never_errors_and_is_matched_literally() { + // Given one session that contains the operator text and a control that does not. + let (_temp, root, workspace) = setup(); + session( + &root, + &workspace, + "Literal", + &[ + "x a OR b y", + "x a AND b y", + "x NEAR(a b) y", + "x text:a y", + "x (a) OR (b y", + ], + ); + session(&root, &workspace, "Control", &["a only b", "text only"]); + let index = refreshed(&root); + let control_title = |hits: &SearchListing| { + hits.hits + .iter() + .any(|hit| hit.session.title.as_deref() == Some("Control")) + }; + + // Every hostile string is accepted and never reaches FTS5 as syntax. + let hostile = [ + "\"", + "\"\"", + "a\"b", + "NEAR(a b)", + "a OR b", + "a AND b", + "-a", + "^a", + "a*", + "text:a", + "(", + ")", + "a) OR (b", + "a NOT b", + "{text}: a", + "a + b", + "*", + "NEAR/2", + &"z".repeat(256), + ]; + for text in hostile { + let result = index.search(text, ArchiveView::Active, 50); + assert!(result.is_ok(), "{text:?}: {result:?}"); + } + // Operator words are plain terms: all must be present, so the control + // session (which has no `or`, `and`, `near`, or `text:` run) cannot match. + for text in ["a OR b", "a AND b", "NEAR(a b)", "text:a", "a) OR (b"] { + let hits = find(&index, text, ArchiveView::Active); + assert!(!control_title(&hits), "{text}"); + assert!( + !hits.hits.is_empty(), + "{text} should match its literal text" + ); + } + assert!(find(&index, "zzzz", ArchiveView::Active).hits.is_empty()); +} + +#[test] +fn snippets_mark_the_matched_terms_and_reconstruct_a_substring_of_the_source() { + let (_temp, root, workspace) = setup(); + let source = "The quick brown fox jumps over the lazy dog"; + let long: String = + (0..300).map(|n| format!("filler{n} ")).collect::() + "needle " + "tail"; + session(&root, &workspace, "Snippets", &[source, &long]); + let index = refreshed(&root); + + let hits = find(&index, "brown fox", ArchiveView::Active).hits; + assert_eq!(hits.len(), 1); + let parts = &hits[0].snippet; + let joined: String = parts.iter().map(|p| p.text.as_str()).collect(); + assert!(source.contains(&joined), "{joined:?}"); + let matched: Vec<&str> = parts + .iter() + .filter(|p| p.matched) + .map(|p| p.text.as_str()) + .collect(); + assert_eq!(matched, ["brown", "fox"]); + assert!( + parts + .iter() + .all(|p| !p.text.contains(['\u{e000}', '\u{e001}'])) + ); + + let hits = find(&index, "needle", ArchiveView::Active).hits; + let parts = &hits[0].snippet; + let joined: String = parts.iter().map(|p| p.text.as_str()).collect(); + assert!(long.contains(&joined)); + assert!( + joined.len() < long.len() / 4, + "the snippet is a window, not the whole text" + ); + assert_eq!( + parts + .iter() + .filter(|p| p.matched) + .map(|p| p.text.as_str()) + .collect::>(), + ["needle"] + ); +} + +#[test] +fn transcript_text_cannot_forge_a_snippet_match() { + let (_temp, root, workspace) = setup(); + let hostile = "before \u{e000}zebra\u{e001} after marker \u{e001}\u{e000} end"; + session(&root, &workspace, "Spoof", &[hostile]); + let index = refreshed(&root); + + let hits = find(&index, "marker", ArchiveView::Active).hits; + + assert_eq!(hits.len(), 1); + let parts = &hits[0].snippet; + assert!( + parts + .iter() + .all(|p| !p.text.contains(['\u{e000}', '\u{e001}'])) + ); + let matched: Vec<&str> = parts + .iter() + .filter(|p| p.matched) + .map(|p| p.text.as_str()) + .collect(); + assert_eq!(matched, ["marker"]); + // The spoofed word is plain text, not a highlight. + assert!(parts.iter().any(|p| !p.matched && p.text.contains("zebra"))); + // The markers were replaced, so they cannot be searched for either. + assert!( + find(&index, "\u{e000}zebra", ArchiveView::Active) + .hits + .len() + <= 1 + ); +} + +#[test] +fn sql_metacharacters_in_titles_and_messages_are_stored_and_found_literally() { + let (_temp, root, workspace) = setup(); + let hostile = "'; DROP TABLE journal;--"; + let (id, _) = session( + &root, + &workspace, + hostile, + &[hostile, "x'); DELETE FROM entry_text;--"], + ); + session(&root, &workspace, "Another", &["still here"]); + let index = refreshed(&root); + + let row = index.session(id).expect("lookup").expect("row"); + assert_eq!(row.title.as_deref(), Some(hostile)); + assert_eq!(list(&index, ArchiveView::Active).total, 2); + let hits = find(&index, "DROP TABLE journal", ArchiveView::Active).hits; + assert_eq!(hits.len(), 2); + assert_eq!( + find(&index, "still here", ArchiveView::Active).hits.len(), + 1 + ); + assert_eq!( + find(&index, "DELETE FROM entry_text", ArchiveView::Active) + .hits + .len(), + 1 + ); +} + +#[test] +fn deleting_the_index_directory_rebuilds_identical_listings_and_leaves_journals_alone() { + let (_temp, root, workspace) = setup(); + let mut paths = Vec::new(); + for (title, body) in [ + ("One", "firstbody"), + ("Two", "secondbody"), + ("Three", "thirdbody"), + ] { + paths.push(session(&root, &workspace, title, &[body]).1); + } + let bytes_before = read_all(&paths); + let index = refreshed(&root); + let listing_before = list(&index, ArchiveView::Active); + let hits_before = find(&index, "secondbody", ArchiveView::Active); + drop(index); + + fs::remove_dir_all(root.join(INDEX_DIRECTORY)).expect("delete the whole index"); + let mut rebuilt = SessionIndex::open(&root).expect("reopen"); + assert_eq!(list(&rebuilt, ArchiveView::Active).total, 0); + let report = rebuilt.refresh(1000).expect("refresh"); + + assert_eq!(report.inspected, 3); + assert_eq!(list(&rebuilt, ArchiveView::Active), listing_before); + assert_eq!( + find(&rebuilt, "secondbody", ArchiveView::Active), + hits_before + ); + assert_eq!(read_all(&paths), bytes_before); +} + +#[test] +fn a_garbage_database_is_replaced_without_touching_anything_else() { + let (_temp, root, workspace) = setup(); + let (_, path) = session(&root, &workspace, "Survivor", &["survivorword"]); + let bytes_before = fs::read(&path).expect("bytes"); + drop(refreshed(&root)); + let sibling = root.join(INDEX_DIRECTORY).join("keep.txt"); + fs::write(&sibling, "not an index file").expect("sibling"); + fs::write(database_path(&root), vec![b'x'; 4096]).expect("overwrite with garbage"); + + let mut index = SessionIndex::open(&root).expect("open recovers"); + assert_eq!(list(&index, ArchiveView::Active).total, 0); + assert_eq!(index.refresh(1000).expect("refresh").inspected, 1); + + assert_eq!( + find(&index, "survivorword", ArchiveView::Active).hits.len(), + 1 + ); + assert_eq!( + fs::read(&sibling).expect("sibling kept"), + b"not an index file" + ); + assert_eq!(fs::read(&path).expect("journal"), bytes_before); +} + +#[test] +fn a_different_user_version_or_application_id_rebuilds_the_index() { + let (_temp, root, workspace) = setup(); + session(&root, &workspace, "Versioned", &["versionword"]); + for (pragma, value) in [ + ("user_version", 2_i64), + ("user_version", 0), + ("user_version", 99), + ("application_id", 12_345), + ("application_id", 0), + ] { + drop(refreshed(&root)); + raw(&root) + .pragma_update(None, pragma, value) + .expect("change the header"); + + let mut index = SessionIndex::open(&root).expect("open recovers"); + assert_eq!( + list(&index, ArchiveView::Active).total, + 0, + "{pragma}={value}" + ); + assert_eq!( + index.refresh(1000).expect("refresh").inspected, + 1, + "{pragma}={value}" + ); + assert_eq!( + find(&index, "versionword", ArchiveView::Active).hits.len(), + 1 + ); + drop(index); + let connection = raw(&root); + let id: i32 = connection + .pragma_query_value(None, "application_id", |row| row.get(0)) + .expect("application_id"); + let version: i64 = connection + .pragma_query_value(None, "user_version", |row| row.get(0)) + .expect("user_version"); + assert_eq!((id, version), (APPLICATION_ID, 1)); + } +} + +#[test] +fn a_database_with_the_right_header_but_no_tables_is_rebuilt() { + let (_temp, root, workspace) = setup(); + session(&root, &workspace, "Hollow", &["hollowword"]); + drop(refreshed(&root)); + { + let connection = raw(&root); + connection + .execute_batch("DROP TABLE entry_text; DROP TABLE journal;") + .expect("drop tables"); + } + + let mut index = SessionIndex::open(&root).expect("open recovers"); + index.refresh(1000).expect("refresh"); + + assert_eq!( + find(&index, "hollowword", ArchiveView::Active).hits.len(), + 1 + ); +} + +#[test] +fn journal_path_resolves_a_real_session_to_a_path_a_writer_can_open() { + let (_temp, root, workspace) = setup(); + let (id, path) = session(&root, &workspace, "Resolve", &["body"]); + let path = move_to_day(&root, &path, "2025/03/04"); + let index = refreshed(&root); + + let resolved = index.journal_path(id).expect("resolve").expect("known"); + + assert_eq!( + resolved, + root.join("sessions/2025/03/04") + .join(path.file_name().expect("name")) + ); + let writer = SessionJournal::open(&resolved).expect("writer opens the resolved path"); + assert_eq!(writer.snapshot().session_id, id); + assert_eq!(index.journal_path(Uuid::new_v4()).expect("unknown"), None); +} + +#[test] +fn a_tampered_stored_path_is_rejected_with_a_typed_error() { + let (_temp, root, workspace) = setup(); + let (id, path) = session(&root, &workspace, "Tamper", &["body"]); + let file = path + .file_name() + .expect("name") + .to_string_lossy() + .into_owned(); + let other = Uuid::new_v4(); + let index = refreshed(&root); + let connection = raw(&root); + let tampered = [ + "../../evil.jsonl".to_owned(), + format!("{}/evil.jsonl", root.display()), + "/etc/passwd".to_owned(), + "C:/Windows/evil.jsonl".to_owned(), + format!("sessions\\2026\\01\\02\\{file}"), + format!("sessions/2026/01/02/omgcode-01-02-03-004Z-{other}.jsonl"), + format!("sessions/2026/01/02/extra/{file}"), + format!("sessions/2026/01/../02/{file}"), + format!("sessions/2026/01/{file}"), + format!("sessions/2026/01/02/{file}/"), + String::new(), + ]; + for value in tampered { + connection + .execute( + "UPDATE journal SET relative_path = ?1 WHERE session_id = ?2", + rusqlite::params![value, id.to_string()], + ) + .expect("tamper"); + assert!( + matches!( + index.journal_path(id), + Err(IndexError::InvalidIndexEntry(_)) + ), + "{value:?}" + ); + } +} + +#[test] +fn a_refresh_repairs_a_tampered_stored_path() { + let (_temp, root, workspace) = setup(); + let (id, path) = session(&root, &workspace, "Repair", &["body"]); + let mut index = refreshed(&root); + raw(&root) + .execute("UPDATE journal SET relative_path = '../../evil.jsonl'", []) + .expect("tamper"); + assert!(index.journal_path(id).is_err()); + + let report = index.refresh(1000).expect("refresh"); + + assert_eq!(report.inspected, 1); + assert_eq!(index.journal_path(id).expect("resolve"), Some(path)); +} + +#[test] +fn an_index_directory_that_is_a_link_is_refused() { + let (temp, root, _workspace) = setup(); + fs::create_dir_all(&root).expect("root"); + let elsewhere = temp.path().join("elsewhere"); + fs::create_dir_all(&elsewhere).expect("target"); + if !try_symlink_dir(&elsewhere, &root.join(INDEX_DIRECTORY)) { + return; + } + + let result = SessionIndex::open(&root); + + assert!( + matches!(result, Err(IndexError::UnsafeLocation(_))), + "{result:?}" + ); + assert_eq!(fs::read_dir(&elsewhere).expect("target").count(), 0); +} + +#[test] +fn a_database_file_that_is_a_link_is_refused() { + let (temp, root, _workspace) = setup(); + let directory = root.join(INDEX_DIRECTORY); + fs::create_dir_all(&directory).expect("index directory"); + let target = temp.path().join("target.sqlite3"); + fs::write(&target, b"untouched").expect("target"); + if !try_symlink_file(&target, &directory.join(INDEX_FILE)) { + return; + } + + let result = SessionIndex::open(&root); + + assert!( + matches!(result, Err(IndexError::UnsafeLocation(_))), + "{result:?}" + ); + assert_eq!(fs::read(&target).expect("target"), b"untouched"); +} + +#[test] +fn contention_past_the_busy_timeout_is_a_distinct_busy_error() { + let (_temp, root, workspace) = setup(); + session(&root, &workspace, "Locked", &[]); + let index = refreshed(&root); + let connection = raw(&root); + connection + .execute_batch("BEGIN EXCLUSIVE") + .expect("exclusive lock"); + + let result = index.sessions(&query(ArchiveView::Active, SessionSort::Title, false, 10)); + + assert!(matches!(result, Err(IndexError::Busy)), "{result:?}"); + connection.execute_batch("ROLLBACK").expect("release"); + assert_eq!(list(&index, ArchiveView::Active).total, 1); +} + +#[test] +fn the_workspace_path_round_trips_losslessly_through_the_stored_units() { + let (_temp, root, workspace) = setup(); + let (id, path) = session(&root, &workspace, "Units", &[]); + let inspection = SessionInspection::inspect(&path).expect("inspect"); + let index = refreshed(&root); + + let row = index.session(id).expect("lookup").expect("row"); + + assert_eq!(row.workspace, Some(inspection.workspace.clone())); + match row.workspace.expect("workspace") { + NativePath::WindowsUtf16(units) => assert!(!units.is_empty()), + NativePath::UnixBytes(bytes) => assert!(!bytes.is_empty()), + } +} + +#[test] +fn the_bundled_sqlite_has_fts5_and_refuses_sql_extension_loading() { + let connection = Connection::open_in_memory().expect("in-memory database"); + connection + .execute_batch( + "CREATE VIRTUAL TABLE probe USING fts5(text, tokenize = 'unicode61 remove_diacritics 2'); + INSERT INTO probe (text) VALUES ('Caf\u{e9} au lait');", + ) + .expect("FTS5 is compiled in"); + let hits: i64 = connection + .query_row( + "SELECT count(*) FROM probe WHERE probe MATCH 'cafe'", + [], + |row| row.get(0), + ) + .expect("match"); + assert_eq!(hits, 1); + let version: String = connection + .query_row("SELECT sqlite_version()", [], |row| row.get(0)) + .expect("version"); + eprintln!("bundled SQLite version: {version}"); + assert!( + connection + .query_row("SELECT load_extension('no-such-extension')", [], |_| Ok(())) + .is_err() + ); +} + +// Link helpers, as in `tests/session_inspection.rs`. + +fn try_symlink_file(target: &Path, link: &Path) -> bool { + #[cfg(unix)] + let result = std::os::unix::fs::symlink(target, link); + #[cfg(windows)] + let result = std::os::windows::fs::symlink_file(target, link); + report_symlink(result) +} + +fn try_symlink_dir(target: &Path, link: &Path) -> bool { + #[cfg(unix)] + let result = std::os::unix::fs::symlink(target, link); + #[cfg(windows)] + let result = std::os::windows::fs::symlink_dir(target, link).or_else(|_| { + // A junction needs no privilege and is also a reparse point. + let status = std::process::Command::new("cmd") + .arg("/C") + .arg("mklink") + .arg("/J") + .arg(link) + .arg(target) + .stdout(std::process::Stdio::null()) + .status()?; + if status.success() { + Ok(()) + } else { + Err(std::io::Error::other("mklink /J failed")) + } + }); + report_symlink(result) +} + +fn report_symlink(result: std::io::Result<()>) -> bool { + match result { + Ok(()) => true, + Err(error) => { + eprintln!("SKIPPED link assertions: this host cannot create a symlink: {error}"); + false + } + } +} diff --git a/crates/omgcode-core/tests/session_inspection.rs b/crates/omgcode-core/tests/session_inspection.rs new file mode 100644 index 0000000..00dc421 --- /dev/null +++ b/crates/omgcode-core/tests/session_inspection.rs @@ -0,0 +1,678 @@ +//! Native tests for read-only journal inspection, discovery, and resolution. + +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; + +use omgcode_core::session::{ + CompactionRecord, MessageRole, MessageSource, RequestManifest, SessionError, SessionInspection, + SessionJournal, ToolOutcome, TranscriptEntryKind, discover, locate, +}; +use sha2::{Digest, Sha256}; +use tempfile::TempDir; +use uuid::Uuid; + +fn setup() -> (TempDir, PathBuf, PathBuf) { + let temp = TempDir::new().expect("temporary directory"); + let root = temp.path().join("app-data"); + let workspace = temp.path().join("workspace"); + fs::create_dir_all(&workspace).expect("workspace directory"); + (temp, root, workspace) +} + +fn sha256_hex(text: &str) -> String { + Sha256::digest(text.as_bytes()) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +fn manifest() -> RequestManifest { + RequestManifest { + base_prompt: "BASE-PROMPT-TEXT".into(), + prompt_version: "7".into(), + prompt_sha256: "a".repeat(64), + custom_instructions: "SECRET-CUSTOM-INSTRUCTIONS".into(), + model: "local-model".into(), + base_url: "http://127.0.0.1:1234/v1".into(), + context_tokens: 32_000, + max_output_tokens: 2_000, + tool_schema_version: Some("1".into()), + tools: Some(vec!["workspace_read_file".into(), "workspace_list".into()]), + } +} + +/// Create a small idle journal with `messages` user messages and release it. +fn small_journal(root: &Path, workspace: &Path, messages: usize) -> PathBuf { + let mut journal = SessionJournal::create(root, workspace, "Small").expect("create"); + for index in 0..messages { + journal + .record_message(MessageRole::User, &format!("message {index}")) + .expect("message"); + } + journal.path().to_path_buf() +} + +/// Replace the journal's text with `edit(text)`. +fn rewrite(path: &Path, edit: impl FnOnce(String) -> String) { + let text = fs::read_to_string(path).expect("journal text"); + fs::write(path, edit(text)).expect("rewrite journal"); +} + +/// Create a file symlink. Returns false, after saying so, when this host does +/// not allow the calling account to create one. +fn try_symlink_file(target: &Path, link: &Path) -> bool { + #[cfg(unix)] + let result = std::os::unix::fs::symlink(target, link); + #[cfg(windows)] + let result = std::os::windows::fs::symlink_file(target, link); + report_symlink(result) +} + +fn try_symlink_dir(target: &Path, link: &Path) -> bool { + #[cfg(unix)] + let result = std::os::unix::fs::symlink(target, link); + #[cfg(windows)] + let result = std::os::windows::fs::symlink_dir(target, link).or_else(|_| { + // A junction needs no privilege and is also a reparse point. + let status = std::process::Command::new("cmd") + .arg("/C") + .arg("mklink") + .arg("/J") + .arg(link) + .arg(target) + .stdout(std::process::Stdio::null()) + .status()?; + if status.success() { + Ok(()) + } else { + Err(std::io::Error::other("mklink /J failed")) + } + }); + report_symlink(result) +} + +fn report_symlink(result: std::io::Result<()>) -> bool { + match result { + Ok(()) => true, + Err(error) => { + eprintln!("SKIPPED link assertions: this host cannot create a symlink: {error}"); + false + } + } +} + +#[test] +fn inspection_reports_header_and_every_recorded_event() { + let (_temp, root, workspace) = setup(); + let mut journal = + SessionJournal::create(&root, &workspace, "Inspect everything").expect("create"); + let path = journal.path().to_path_buf(); + let workspace_id = journal.snapshot().workspace_id; + let session_id = journal.snapshot().session_id; + let native_workspace = journal.snapshot().workspace.clone(); + + journal + .record_message(MessageRole::User, "hello") + .expect("user"); + let first = journal.start_turn().expect("turn one"); + journal + .record_manifest(first, manifest()) + .expect("manifest"); + journal + .record_tool_request( + first, + "call-1", + "workspace_read_file", + "{\"path\":\"a.txt\"}", + ) + .expect("tool request"); + let rendered = "file contents"; + journal + .record_tool_result( + first, + "call-1", + ToolOutcome::Succeeded, + None, + u64::try_from(rendered.len()).expect("size"), + &sha256_hex(rendered), + ) + .expect("tool result"); + journal + .record_tool_message("call-1", rendered) + .expect("tool message"); + journal + .record_message(MessageRole::Assistant, "done") + .expect("assistant"); + journal.complete_turn(first).expect("complete"); + journal + .record_message(MessageRole::User, "second") + .expect("second user"); + let second = journal.start_turn().expect("turn two"); + journal + .fail_turn(second, "provider_unreachable") + .expect("fail"); + let summary = "Earlier work read a file."; + let record = CompactionRecord { + summary: summary.into(), + compacted_messages: 3, + includes_tool_results: true, + summary_sha256: sha256_hex(summary), + model: "fixture".into(), + prompt_tokens: Some(10), + completion_tokens: Some(4), + }; + journal.record_compaction(record.clone()).expect("compact"); + journal.archive().expect("archive"); + journal.restore().expect("restore"); + drop(journal); + + let inspection = SessionInspection::inspect(&path).expect("inspect"); + + assert_eq!(inspection.session_id, session_id); + assert_eq!(inspection.workspace_id, workspace_id); + assert_eq!(inspection.workspace, native_workspace); + assert_eq!(inspection.title, "Inspect everything"); + assert!(!inspection.archived); + assert_eq!(inspection.active_turn, None); + assert_eq!(inspection.schema_version, 3); + assert_eq!(inspection.event_count, 15); + assert!(!inspection.incomplete_tail); + assert!(inspection.created_at <= inspection.updated_at); + let last = inspection.entries.last().expect("entries"); + assert_eq!(inspection.updated_at, last.timestamp); + + let seqs: Vec = inspection.entries.iter().map(|entry| entry.seq).collect(); + assert_eq!(seqs, (1..=14).collect::>()); + let kinds: Vec<&TranscriptEntryKind> = + inspection.entries.iter().map(|entry| &entry.kind).collect(); + let expected = vec![ + TranscriptEntryKind::Message { + role: MessageRole::User, + source: MessageSource::UserCli, + text: "hello".into(), + call_id: None, + }, + TranscriptEntryKind::TurnStarted { request_id: first }, + TranscriptEntryKind::RequestManifest { + request_id: first, + model: "local-model".into(), + prompt_version: "7".into(), + tools: vec!["workspace_read_file".into(), "workspace_list".into()], + }, + TranscriptEntryKind::ToolRequested { + request_id: first, + call_id: "call-1".into(), + tool: "workspace_read_file".into(), + arguments: "{\"path\":\"a.txt\"}".into(), + }, + TranscriptEntryKind::ToolCompleted { + request_id: first, + call_id: "call-1".into(), + outcome: ToolOutcome::Succeeded, + code: None, + output_bytes: 13, + output_sha256: sha256_hex(rendered), + }, + TranscriptEntryKind::Message { + role: MessageRole::Tool, + source: MessageSource::CoreTool, + text: rendered.into(), + call_id: Some("call-1".into()), + }, + TranscriptEntryKind::Message { + role: MessageRole::Assistant, + source: MessageSource::Provider, + text: "done".into(), + call_id: None, + }, + TranscriptEntryKind::TurnCompleted { request_id: first }, + TranscriptEntryKind::Message { + role: MessageRole::User, + source: MessageSource::UserCli, + text: "second".into(), + call_id: None, + }, + TranscriptEntryKind::TurnStarted { request_id: second }, + TranscriptEntryKind::TurnFailed { + request_id: second, + code: "provider_unreachable".into(), + }, + TranscriptEntryKind::ContextCompacted { record }, + TranscriptEntryKind::SessionArchived, + TranscriptEntryKind::SessionRestored, + ]; + assert_eq!(kinds, expected.iter().collect::>()); + + // The serialized form tags each entry, uses RFC 3339 times, and leaves the + // base prompt and custom instructions out of the manifest entry. + let json = serde_json::to_value(&inspection).expect("serialize"); + assert_eq!(json["entries"][0]["kind"], "message"); + assert_eq!(json["entries"][2]["kind"], "request_manifest"); + assert_eq!(json["entries"][10]["kind"], "turn_failed"); + assert!( + json["created_at"] + .as_str() + .is_some_and(|text| text.ends_with('Z')) + ); + let text = json.to_string(); + assert!(!text.contains("BASE-PROMPT-TEXT")); + assert!(!text.contains("SECRET-CUSTOM-INSTRUCTIONS")); +} + +#[test] +fn inspection_reports_an_active_turn_and_an_archived_session() { + let (_temp, root, workspace) = setup(); + let mut journal = SessionJournal::create(&root, &workspace, "States").expect("create"); + let path = journal.path().to_path_buf(); + let request = journal.start_turn().expect("turn"); + drop(journal); + let active = SessionInspection::inspect(&path).expect("inspect active"); + assert_eq!(active.active_turn, Some(request)); + assert!(!active.archived); + + let mut journal = SessionJournal::open(&path).expect("reopen"); + journal.complete_turn(request).expect("complete"); + journal.archive().expect("archive"); + drop(journal); + let archived = SessionInspection::inspect(&path).expect("inspect archived"); + assert!(archived.archived); + assert_eq!(archived.active_turn, None); +} + +#[cfg(windows)] +#[test] +fn inspection_of_a_live_writer_is_busy_and_disturbs_nothing() { + let (_temp, root, workspace) = setup(); + let mut journal = SessionJournal::create(&root, &workspace, "Live").expect("create"); + let path = journal.path().to_path_buf(); + for _ in 0..5 { + assert!(matches!( + SessionInspection::inspect(&path), + Err(SessionError::Busy) + )); + } + // The writer is unaffected, and the observer did not take the lock. + journal + .record_message(MessageRole::User, "still appending") + .expect("append after refused inspections"); + drop(journal); + let inspection = SessionInspection::inspect(&path).expect("inspect after release"); + assert_eq!(inspection.event_count, 2); +} + +#[cfg(unix)] +#[test] +fn inspection_of_a_live_writer_succeeds_and_disturbs_nothing() { + let (_temp, root, workspace) = setup(); + let mut journal = SessionJournal::create(&root, &workspace, "Live").expect("create"); + let path = journal.path().to_path_buf(); + let inspection = SessionInspection::inspect(&path).expect("inspect beside a writer"); + assert_eq!(inspection.event_count, 1); + journal + .record_message(MessageRole::User, "still appending") + .expect("append after inspection"); + assert_eq!( + SessionInspection::inspect(&path) + .expect("again") + .event_count, + 2 + ); +} + +#[test] +fn a_writer_opens_immediately_after_many_inspections() { + let (_temp, root, workspace) = setup(); + let path = small_journal(&root, &workspace, 2); + for _ in 0..200 { + SessionInspection::inspect(&path).expect("inspect idle journal"); + // An inspection that returned must leave no lock behind. + drop(SessionJournal::open(&path).expect("writer opens right after an inspection")); + } + for _ in 0..200 { + SessionInspection::inspect(&path).expect("inspect idle journal"); + } + let mut writer = SessionJournal::open(&path).expect("writer opens after the loop"); + writer + .record_message(MessageRole::Assistant, "ok") + .expect("append"); +} + +#[test] +fn an_incomplete_tail_is_ignored_without_changing_the_file() { + let (_temp, root, workspace) = setup(); + let path = small_journal(&root, &workspace, 2); + let mut file = OpenOptions::new().append(true).open(&path).expect("append"); + file.write_all(b"{\"schema_version\":3,\"session_id\":\"partial") + .expect("partial record"); + drop(file); + let before = fs::read(&path).expect("bytes"); + + let inspection = SessionInspection::inspect(&path).expect("inspect with tail"); + assert!(inspection.incomplete_tail); + assert_eq!(inspection.event_count, 3); + assert_eq!(inspection.entries.len(), 2); + assert_eq!(fs::read(&path).expect("bytes after"), before); + + // The writer path is unchanged: it still refuses the incomplete tail. + assert!(matches!( + SessionJournal::open(&path), + Err(SessionError::InvalidJournal(_)) + )); + assert_eq!(fs::read(&path).expect("bytes after open"), before); + // And that refused open released its lock. + assert!(SessionInspection::inspect(&path).is_ok()); +} + +#[test] +fn a_journal_with_no_complete_record_is_invalid() { + let (_temp, root, workspace) = setup(); + let path = small_journal(&root, &workspace, 0); + let file = OpenOptions::new().write(true).open(&path).expect("open"); + file.set_len(20) + .expect("truncate to a partial first record"); + drop(file); + assert!(matches!( + SessionInspection::inspect(&path), + Err(SessionError::InvalidJournal(_)) + )); + fs::write(&path, b"").expect("empty file"); + assert!(matches!( + SessionInspection::inspect(&path), + Err(SessionError::InvalidJournal(_)) + )); +} + +#[test] +fn interior_corruption_is_rejected() { + let (_temp, root, workspace) = setup(); + let path = small_journal(&root, &workspace, 3); + rewrite(&path, |text| { + let mut lines: Vec<&str> = text.lines().collect(); + lines[1] = "{not json}"; + lines.join("\n") + "\n" + }); + assert!(matches!( + SessionInspection::inspect(&path), + Err(SessionError::InvalidJournal(_)) + )); +} + +#[test] +fn duplicate_keys_are_rejected() { + let (_temp, root, workspace) = setup(); + let path = small_journal(&root, &workspace, 2); + rewrite(&path, |text| { + text.replacen("\"seq\":1,", "\"seq\":1,\"seq\":1,", 1) + }); + assert!(matches!( + SessionInspection::inspect(&path), + Err(SessionError::InvalidJournal(_)) + )); +} + +#[test] +fn a_session_id_that_differs_from_the_filename_is_rejected() { + let (_temp, root, workspace) = setup(); + let path = small_journal(&root, &workspace, 1); + let name = path + .file_name() + .and_then(|name| name.to_str()) + .expect("name"); + let (stamp, _) = name.rsplit_once("Z-").expect("stamp"); + let renamed = path.with_file_name(format!("{stamp}Z-{}.jsonl", Uuid::new_v4())); + fs::rename(&path, &renamed).expect("rename"); + assert!(matches!( + SessionInspection::inspect(&renamed), + Err(SessionError::InvalidJournal(_)) + )); +} + +#[test] +fn a_non_contiguous_sequence_is_rejected() { + let (_temp, root, workspace) = setup(); + let path = small_journal(&root, &workspace, 3); + rewrite(&path, |text| text.replacen("\"seq\":2,", "\"seq\":5,", 1)); + assert!(matches!( + SessionInspection::inspect(&path), + Err(SessionError::InvalidJournal(_)) + )); +} + +#[test] +fn an_oversized_journal_is_rejected_without_reading_it_all() { + let (_temp, root, workspace) = setup(); + let path = small_journal(&root, &workspace, 1); + let mut file = OpenOptions::new().append(true).open(&path).expect("append"); + file.write_all(&vec![b'a'; 9 * 1024 * 1024]) + .expect("padding"); + drop(file); + assert!(matches!( + SessionInspection::inspect(&path), + Err(SessionError::InvalidJournal(_)) + )); +} + +#[test] +fn a_symlinked_journal_is_rejected() { + let (temp, root, workspace) = setup(); + let path = small_journal(&root, &workspace, 1); + let name = path.file_name().expect("name"); + let alias_directory = temp.path().join("alias"); + fs::create_dir(&alias_directory).expect("alias directory"); + let alias = alias_directory.join(name); + if !try_symlink_file(&path, &alias) { + return; + } + assert!(matches!( + SessionInspection::inspect(&alias), + Err(SessionError::InvalidJournal(_)) + )); +} + +#[test] +fn an_unnamed_or_missing_journal_is_a_controlled_failure() { + let (temp, _root, _workspace) = setup(); + let bad_name = temp.path().join("not-a-journal.jsonl"); + fs::write(&bad_name, b"").expect("file"); + assert!(matches!( + SessionInspection::inspect(&bad_name), + Err(SessionError::InvalidJournal(_)) + )); + let missing = temp + .path() + .join(format!("omgcode-00-00-00-000Z-{}.jsonl", Uuid::new_v4())); + assert!(matches!( + SessionInspection::inspect(&missing), + Err(SessionError::Io(_)) + )); +} + +fn journal_name(id: Uuid) -> String { + format!("omgcode-01-02-03-004Z-{id}.jsonl") +} + +fn place(root: &Path, day: &str, name: &str, bytes: &[u8]) -> PathBuf { + let directory = root.join("sessions").join(day); + fs::create_dir_all(&directory).expect("directory"); + let path = directory.join(name); + fs::write(&path, bytes).expect("file"); + path +} + +#[test] +fn discovery_lists_a_nested_layout_in_relative_path_order() { + let (temp, _root, _workspace) = setup(); + let root = temp.path().join("data"); + let ids: Vec = (0..4).map(|_| Uuid::new_v4()).collect(); + place(&root, "2026/01/06", &journal_name(ids[0]), b"abc"); + place(&root, "2025/12/31", &journal_name(ids[1]), b""); + place(&root, "2026/01/05", &journal_name(ids[2]), b"hello"); + place(&root, "2026/01/05", &journal_name(ids[3]), b"x"); + + let found = discover(&root).expect("discover"); + assert_eq!(found.skipped_links, 0); + assert_eq!(found.unrecognized, 0); + let relative: Vec = found + .journals + .iter() + .map(|item| item.relative_path.clone()) + .collect(); + let mut sorted = relative.clone(); + sorted.sort(); + assert_eq!(relative, sorted, "sorted by relative path"); + assert_eq!(found.journals.len(), 4); + assert_eq!(found.journals[0].session_id, ids[1]); + assert_eq!(found.journals[0].size, 0); + assert_eq!( + found.journals[0].relative_path, + Path::new("sessions") + .join("2025") + .join("12") + .join("31") + .join(journal_name(ids[1])) + ); + for item in &found.journals { + assert!(item.path.is_absolute()); + assert_eq!(item.path, root.join(&item.relative_path)); + assert!(item.path.is_file()); + assert_eq!(item.size, fs::metadata(&item.path).expect("metadata").len()); + } + let again = discover(&root).expect("discover again"); + assert_eq!(again, found, "deterministic"); +} + +#[test] +fn discovery_counts_and_ignores_names_outside_the_layout() { + let (temp, _root, _workspace) = setup(); + let root = temp.path().join("data"); + let id = Uuid::new_v4(); + let good = place(&root, "2026/01/05", &journal_name(id), b""); + // Each of these is one unrecognized entry. + place(&root, "2026/01/05", "notes.txt", b""); + place( + &root, + "2026/01/05", + &format!("{}.bak", journal_name(Uuid::new_v4())), + b"", + ); + place( + &root, + "2026/01/05", + &journal_name(Uuid::new_v4()).to_uppercase(), + b"", + ); + place( + &root, + "2026/01/05", + "omgcode-25-00-00-000Z-00000000-0000-4000-8000-000000000000.jsonl", + b"", + ); + // A journal-named file one level too high. + place(&root, "2026/01", &journal_name(Uuid::new_v4()), b""); + // Wrong-length directories, with a valid journal inside each. + place(&root, "26/01/05", &journal_name(Uuid::new_v4()), b""); + place(&root, "2026/1/05", &journal_name(Uuid::new_v4()), b""); + place(&root, "2026/01/5", &journal_name(Uuid::new_v4()), b""); + place(&root, "abcd/01/05", &journal_name(Uuid::new_v4()), b""); + // A plain file where a year directory belongs. + fs::write(root.join("sessions").join("2027"), b"").expect("file"); + + let found = discover(&root).expect("discover"); + assert_eq!(found.journals.len(), 1); + assert_eq!(found.journals[0].session_id, id); + assert_eq!(found.journals[0].path, good); + // 4 bad files, 1 high file, 4 bad directories, 1 plain file. + assert_eq!(found.unrecognized, 10); + assert_eq!(found.skipped_links, 0); +} + +#[test] +fn discovery_skips_a_directory_link_that_points_outside() { + let (temp, _root, _workspace) = setup(); + let root = temp.path().join("data"); + let outside = temp.path().join("outside"); + let outside_id = Uuid::new_v4(); + place(&outside, "x/01/05", &journal_name(outside_id), b""); + let inner = outside.join("sessions").join("x"); + fs::create_dir_all(root.join("sessions")).expect("sessions"); + // The link takes a valid year name and points at a tree holding a journal. + if !try_symlink_dir(&inner, &root.join("sessions").join("2030")) { + return; + } + let real = Uuid::new_v4(); + place(&root, "2026/01/05", &journal_name(real), b""); + + let found = discover(&root).expect("discover"); + assert_eq!(found.skipped_links, 1); + assert_eq!(found.journals.len(), 1); + assert_eq!(found.journals[0].session_id, real); + assert_eq!(locate(&root, outside_id).expect("locate"), None); +} + +#[test] +fn discovery_skips_a_sessions_directory_that_is_a_link() { + let (temp, _root, _workspace) = setup(); + let root = temp.path().join("data"); + let outside = temp.path().join("outside"); + place(&outside, "2026/01/05", &journal_name(Uuid::new_v4()), b""); + fs::create_dir_all(&root).expect("root"); + if !try_symlink_dir(&outside.join("sessions"), &root.join("sessions")) { + return; + } + let found = discover(&root).expect("discover"); + assert!(found.journals.is_empty()); + assert_eq!(found.skipped_links, 1); +} + +#[test] +fn a_missing_sessions_directory_is_an_empty_result() { + let (temp, _root, _workspace) = setup(); + let found = discover(&temp.path().join("never-created")).expect("empty"); + assert!(found.journals.is_empty()); + assert_eq!(found.skipped_links, 0); + assert_eq!(found.unrecognized, 0); + fs::create_dir_all(temp.path().join("data")).expect("root without sessions"); + assert!( + discover(&temp.path().join("data")) + .expect("empty") + .journals + .is_empty() + ); +} + +#[test] +fn locate_resolves_real_journals_by_uuid_only() { + let (_temp, root, workspace) = setup(); + let first = SessionJournal::create(&root, &workspace, "One").expect("one"); + let second = SessionJournal::create(&root, &workspace, "Two").expect("two"); + let (first_id, first_path) = (first.snapshot().session_id, first.path().to_path_buf()); + let second_id = second.snapshot().session_id; + drop((first, second)); + + assert_eq!(locate(&root, first_id).expect("locate"), Some(first_path)); + assert_ne!( + locate(&root, first_id).expect("locate"), + locate(&root, second_id).expect("locate") + ); + assert_eq!(locate(&root, Uuid::new_v4()).expect("unknown"), None); + let inspected = + SessionInspection::inspect(&locate(&root, second_id).expect("locate").expect("found")) + .expect("inspect located journal"); + assert_eq!(inspected.title, "Two"); +} + +#[test] +fn locate_refuses_a_duplicate_uuid_instead_of_picking_one() { + let (temp, _root, _workspace) = setup(); + let root = temp.path().join("data"); + let id = Uuid::new_v4(); + place(&root, "2026/01/05", &journal_name(id), b""); + place(&root, "2026/01/06", &journal_name(id), b""); + assert_eq!(discover(&root).expect("discover").journals.len(), 2); + assert!(matches!( + locate(&root, id), + Err(SessionError::InvalidJournal(_)) + )); + assert_eq!(locate(&root, Uuid::new_v4()).expect("other id"), None); +} diff --git a/crates/omgcode-core/tests/workspace_listing.rs b/crates/omgcode-core/tests/workspace_listing.rs new file mode 100644 index 0000000..2339553 --- /dev/null +++ b/crates/omgcode-core/tests/workspace_listing.rs @@ -0,0 +1,93 @@ +//! Read-only workspace listing for an open control store. + +use std::fs; + +use omgcode_core::control::ControlStore; +use tempfile::TempDir; + +fn store_with(names: &[&str]) -> (TempDir, ControlStore, Vec) { + let temporary = TempDir::new().expect("private temporary directory"); + let data = temporary.path().join("application-data"); + let root = temporary.path().join("development-root"); + fs::create_dir(&root).expect("create development root"); + let mut control = ControlStore::open(&data).expect("open control store"); + control + .set_development_root(&root, control.revision()) + .expect("select development root"); + let mut directories = Vec::new(); + for name in names { + let directory = root.join(name); + fs::create_dir(&directory).expect("create workspace"); + control + .register_workspace(&directory, control.revision()) + .expect("register workspace"); + directories.push(directory); + } + (temporary, control, directories) +} + +#[test] +fn an_empty_store_lists_no_workspaces() { + let (_temporary, control, _) = store_with(&[]); + assert_eq!(control.workspaces().count(), 0); +} + +#[test] +fn workspaces_are_listed_in_registration_order_with_their_recorded_directory() { + let (_temporary, control, directories) = store_with(&["zeta", "alpha", "mid"]); + + let listed: Vec<_> = control.workspaces().collect(); + + assert_eq!(listed.len(), 3); + for (registration, directory) in listed.iter().zip(&directories) { + let recorded = registration.directory_path().expect("native path"); + assert_eq!( + fs::canonicalize(&recorded).expect("recorded path exists"), + fs::canonicalize(directory).expect("directory exists") + ); + assert!( + registration.directory_display().ends_with( + directory + .file_name() + .and_then(|name| name.to_str()) + .expect("name") + ), + "{}", + registration.directory_display() + ); + assert_eq!( + control.workspace(registration.id()).map(|found| found.id()), + Some(registration.id()) + ); + } + // The order is stable across calls. + let first: Vec<_> = control + .workspaces() + .map(|workspace| workspace.id()) + .collect(); + let second: Vec<_> = control + .workspaces() + .map(|workspace| workspace.id()) + .collect(); + assert_eq!(first, second); +} + +#[test] +fn directory_display_text_escapes_hidden_formatting_characters() { + // NTFS and most Unix filesystems admit U+202E in a name. + let (_temporary, control, _) = store_with(&["name\u{202e}gpj"]); + + let registration = control.workspaces().next().expect("one workspace"); + let display = registration.directory_display(); + + assert!(display.contains("name\\u{202e}gpj"), "{display}"); + assert!(!display.contains('\u{202e}')); + // The path used to reopen the directory is untouched. + assert!( + registration + .directory_path() + .expect("native path") + .to_string_lossy() + .contains('\u{202e}') + ); +} diff --git a/crates/omgcode-desktop/.gitignore b/crates/omgcode-desktop/.gitignore new file mode 100644 index 0000000..b50b9bb --- /dev/null +++ b/crates/omgcode-desktop/.gitignore @@ -0,0 +1,3 @@ +# Generated by tauri-build: ACL manifests and capability schemas. +/gen/ +/permissions/autogenerated/ diff --git a/crates/omgcode-desktop/Cargo.toml b/crates/omgcode-desktop/Cargo.toml new file mode 100644 index 0000000..91d158b --- /dev/null +++ b/crates/omgcode-desktop/Cargo.toml @@ -0,0 +1,43 @@ +[package] +name = "omgcode-desktop" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +description = "Tauri 2 desktop shell for OMGCode with a capability-gated command surface and two isolated webview windows" +build = "build.rs" + +[lib] +# A distinct library name keeps the binary and library outputs from colliding on Windows. +name = "omgcode_desktop_lib" +path = "src/lib.rs" + +[[bin]] +name = "omgcode-desktop" +path = "src/main.rs" + +[features] +# Tauri embeds the built frontend (`ui/dist`) only with `tauri/custom-protocol`; without +# it the shell loads `build.devUrl`, which a release build's navigation guard refuses. +# Embedding is the default so a plain `cargo build -p omgcode-desktop` yields a working +# shell. The Tauri CLI's `tauri dev` drops any default feature that enables +# `tauri/custom-protocol` and passes `--no-default-features`, so it still reaches the +# dev server. Do not rename this feature or change what it enables. +default = ["custom-protocol"] +custom-protocol = ["tauri/custom-protocol"] + +[dependencies] +omgcode-app = { path = "../omgcode-app" } +serde.workspace = true +serde_json.workspace = true +uuid.workspace = true +# Stable 2.x only (3.0 is alpha). `wry` is the webview runtime. `x11` lets WebKitGTK +# run under X11 sessions on Linux. No devtools, tray, updater, asset protocol, or plugin. +tauri = { version = "2.12.6", default-features = false, features = ["wry", "x11"] } + +[build-dependencies] +tauri-build = { version = "2.7.5", default-features = false, features = ["config-json"] } + +[lints] +workspace = true diff --git a/crates/omgcode-desktop/build.rs b/crates/omgcode-desktop/build.rs new file mode 100644 index 0000000..13e5456 --- /dev/null +++ b/crates/omgcode-desktop/build.rs @@ -0,0 +1,17 @@ +//! Declares every application command to Tauri's permission layer. +//! +//! With `AppManifest::commands`, each command gets generated `allow-` and +//! `deny-` permissions and is refused unless a capability grants it to the +//! calling window. Without a manifest, every registered command is open to +//! every window. The list is shared with `src/policy.rs` so the two cannot drift. + +include!("src/command_names.rs"); + +fn main() { + let manifest = tauri_build::AppManifest::new().commands(COMMAND_NAMES); + let attributes = tauri_build::Attributes::new().app_manifest(manifest); + if let Err(error) = tauri_build::try_build(attributes) { + eprintln!("tauri build script failed: {error:#}"); + std::process::exit(1); + } +} diff --git a/crates/omgcode-desktop/capabilities/approvals.json b/crates/omgcode-desktop/capabilities/approvals.json new file mode 100644 index 0000000..7d4b4e7 --- /dev/null +++ b/crates/omgcode-desktop/capabilities/approvals.json @@ -0,0 +1,14 @@ +{ + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "approvals-window", + "description": "The three approval commands for the approvals window only. No core permissions.", + "local": true, + "windows": [ + "approvals" + ], + "permissions": [ + "allow-approvals-list", + "allow-approval-detail", + "allow-approval-decide" + ] +} diff --git a/crates/omgcode-desktop/capabilities/main.json b/crates/omgcode-desktop/capabilities/main.json new file mode 100644 index 0000000..04331b7 --- /dev/null +++ b/crates/omgcode-desktop/capabilities/main.json @@ -0,0 +1,26 @@ +{ + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "main-window", + "description": "Application commands for the main window only. No core permissions and no approval-decision commands.", + "local": true, + "windows": [ + "main" + ], + "permissions": [ + "allow-app-info", + "allow-session-tree", + "allow-session-search", + "allow-session-transcript", + "allow-session-archive", + "allow-session-restore", + "allow-session-interrupt", + "allow-workspace-list", + "allow-session-create", + "allow-chat-defaults", + "allow-chat-send", + "allow-chat-status", + "allow-chat-cancel", + "allow-approvals-summary", + "allow-approvals-show-window" + ] +} diff --git a/crates/omgcode-desktop/icons/128x128.png b/crates/omgcode-desktop/icons/128x128.png new file mode 100644 index 0000000000000000000000000000000000000000..c113ef5e6bc161bf77d02dddff8e4ed6b49dd27a GIT binary patch literal 7136 zcmX|mWn2_o^Y#(~ONYS1f*>i~-3`)>lys+bcPS~7(nu~WEh#LW0@A&7Nq6(-zVGLK zKg>B_X0G{gu9<6oXJXV;*Z2kD;NwoZX_P!vFxdL_u0Y%X{H4 z+b>aTIs-QLYniJX(-{TXB3(U9m=nM}{bi=&Ib2ONz^?m4{_tQ?c zGzA8bqs-;cP8y-I%QxbcpHBxh>oJqmK;hNMkuiwf?3nDBBTDdA`008AZrZZ*4T68>d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v?nuM37@hZCYbeNW(CmoR>@ zwG|Bw>kx@VrgF!u0{ovXrvN6EUI`qUka14)*|rZ8k*oOQ%whP0atV0~l-Te8;UGLt z6hEE)8SCmBG#fG$izN}g*Vcy4&JzmkY%tCcfd1jd!radEO2$kwjC03{!|M;A=g3>= zKDZa-p+A+_KX>F!6co=vNJ8+()29^&Y;@tVV_!{$V)l)hHxY5+!NXr*>C&YNoEM&d zPUD-8&X-##uEaja=r#(x`?Wo4J?`D#-mcnbgYO>`5t9e~$cu%!o$2-C zjstjn!v@K65y|m`65A0a_BqBmuHjnl;a;A>v+~pkxRWlU+jt$bI4G|ix*%#V6r4Dj zuE{J&m|SkIAYn;nEGaiH4G+w(Nf#tq6_r&k{LHegO;QrZQYKCw1}Brx2lEmT)BLlIP|?` z*>=K-r{4z3b6S#q_+*wbvJK}Mg{X93x jH^VJ^p1U^`yV3pzPWp_w&cgt300000NkvXXu0mjf@e$aL literal 0 HcmV?d00001 diff --git a/crates/omgcode-desktop/icons/icon.ico b/crates/omgcode-desktop/icons/icon.ico new file mode 100644 index 0000000000000000000000000000000000000000..3ead97c7965d0144ac3925b4481360b60e0ef085 GIT binary patch literal 29130 zcmcG$2UJsC*d}@sI)ZdTK)M2=f`Sw&iHJ&3P*71oil9gbQ2~J@fHbL6q!UCb>W6?z zFQG|Mnxb?PIwCdnkiy;J`)A#M=FXj&`>%DgSdiqLv-io~Z+V{QeFFr+AZCc08v+jr z$btca9)M>;LjS&g$pk?S;5`Y6e_zM4LeOOs{%oh*NiW7vJ10=H#rUT^-RHE`i$JH%;2~9`koyGF-RKdoxkA=TWVm) zk-77#mAL1#9Mj%e@W{yiquWUNfBZN_XTLHm&OW0owM=?i;ruK=T+`)u@uN_PVP@SNF*RVkNTQ%2F(F&{!8&qEA!fP1`e0P*LIn-1JxQ_3p0ca-tkjnPjp({zVZ zcB;L75K|vuY~vf7T)TfFc5e;|=P`cxo!;Ec;9LY<>1&ytJ+w}W?oW^l?VPvo9-~GV zAG&6I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$3M11;tK_}4 z!>b{=J(tQRK1wAK@-bgIT7pks7BKg)U}U+|zdXm(SJA!~$9{1Y?+3W5Dq zgkifZuEaU5l9{xF8Z&y<%+{8wh?P@Qe3TP_q%uD_hRA;zl{Za0LJ>6`tu=WVdvM7DA zUR1B?lgQJCgRO)ltco(*H&csiJb6xgTbMLdLjRB#qa-rX|U|!9XQVbO-YZr>;VEk|Me!g{{vuZu-O0r literal 0 HcmV?d00001 diff --git a/crates/omgcode-desktop/icons/icon.png b/crates/omgcode-desktop/icons/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..cdc5b749fce981a6ff54c1a29f80c60c2cfd2764 GIT binary patch literal 32080 zcmcG#goN_Cpe$q)Q(p->g7ad8f zJJvys-$nXJv?d}_Nih!@nKG>N6!f(XY=oS*yzal*@U~vCRP1f5xoq0^cH7u1-|6j_ z+>qW7mxf`=K{4enh(L^>`w#H|`Um<84FB&P7r6fg$_D)R$Nzu-`TrHKDxpL#Ohp2s zI3&z37!rqs96|id=Q3Y*a6oV8x;OLK;GuA6(>Sj0KQPB2NwxyKEY4+XgQk9t?4)n* zDSk{nJ4WE#+#QXSTF?O{H}}NYX0ppp-14WbBwRJ3^_i@=VFMTlM*61`C++OmT~1^> zHF0!GawX(_MuaZ43%HSWS*2-JB~C?g^hEYqNECxBoAg-*408CqACX6vV7N(eJeMHR zcs-ke)TN9K5mnCU(c>VU<0Sl@{_)|?L>B(N;bOb~S$Qw@P(o9K~WTpEm z?!(;t_FBt}%U#2g6ckxbpN0zY+eUw+VFY0!l@R=SSsxZFZE8*0|D3F37M$;Oz*|(~ zblmAmiM#pi{G~zWd-}_Xs z(faWJxvIFrA4YroXgT6l5yCt6XfG$0ECOq%?GPK`y#E;n$z@fQW7DF-S~>kt$HBB| z+C=KIhQ*E%b>`-g(I|lrAq7k+k41#mN<;mlf)j>Oo2Hq?{XQ9FkPhEVO;?M+EIK)8 zqza@&NBhS}po$m)!(-Ft+n@1dH_e$wlg?8-+$}3|q`;wW%3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sgj5x4PJqA@icKJ*mvpnkV&u}oVkF&ai^Db&LiNm2-xPCxPt$+gZ}^k?cu`n za0vt#XaK-@xR^a$0C24X0P=@R`@`k`+pRc2#KXP+zdkFRb|;|}w>Z@^;hgjE5Jg!v KnQ|$!;Qt58sC)SU literal 0 HcmV?d00001 diff --git a/crates/omgcode-desktop/src/command_names.rs b/crates/omgcode-desktop/src/command_names.rs new file mode 100644 index 0000000..2722ea3 --- /dev/null +++ b/crates/omgcode-desktop/src/command_names.rs @@ -0,0 +1,25 @@ +// Single source of truth for the command names. It is `include!`d by `build.rs` +// (to declare the permissions) and by `policy.rs` (to check the `Command` enum +// against it in tests). Keep it a plain constant: no `use`, no items besides it. + +/// Every application command, in `snake_case`, exactly as the frontend invokes it. +pub const COMMAND_NAMES: &[&str] = &[ + "app_info", + "session_tree", + "session_search", + "session_transcript", + "session_archive", + "session_restore", + "session_interrupt", + "workspace_list", + "session_create", + "chat_defaults", + "chat_send", + "chat_status", + "chat_cancel", + "approvals_summary", + "approvals_show_window", + "approvals_list", + "approval_detail", + "approval_decide", +]; diff --git a/crates/omgcode-desktop/src/commands.rs b/crates/omgcode-desktop/src/commands.rs new file mode 100644 index 0000000..cd6238c --- /dev/null +++ b/crates/omgcode-desktop/src/commands.rs @@ -0,0 +1,157 @@ +//! Command handlers exposed to the webviews. +//! +//! Every handler: +//! 1. takes the calling [`tauri::Webview`] and calls [`authorize`] first, with +//! the runtime-supplied label of that webview, before it reads any state or +//! argument-dependent data; +//! 2. returns only fixed-shape data or a [`CommandError`]. +//! +//! Scheduling (Tauri 2, "Calling Rust from the Frontend"): a command without +//! `async` runs on the main (UI) thread unless declared +//! `#[tauri::command(async)]`; an `async` command runs on the async runtime's +//! worker threads. The service blocks on files, `SQLite`, and the settings +//! store (and `approvals_summary` for up to two seconds), so every service +//! handler is `async` and moves the call into +//! [`tauri::async_runtime::spawn_blocking`] through [`blocking`]. The service +//! is managed state of type `Arc`; `State<'_, T>` is borrowed +//! for the handler, so a handler clones the `Arc` into the blocking closure. +//! The two handlers below that touch no service only read constants or send a +//! window message, so they stay synchronous. +//! +//! Arguments are matched by name: Tauri deserializes each parameter from the +//! key of the invoke argument object with the same name (`rename_all = +//! "snake_case"` keeps the Rust names; the default would expect camelCase +//! keys). Each parameter list therefore equals the keys the frontend passes, +//! which `tests/layers.rs` checks mechanically. + +use std::sync::Arc; + +use omgcode_app::desktop::{DesktopError, DesktopService}; +use serde::Serialize; +use tauri::{Manager, State, Webview}; + +use crate::error::CommandError; +use crate::policy::{Command, WindowLabel, authorize}; + +// Handlers are referenced by their full module path in `generate_handler!`: +// the macro each `#[tauri::command]` generates is not re-exported by `pub use`. +pub mod approvals; +pub mod chat; +pub mod sessions; + +/// The service as Tauri state. +pub type Service<'a> = State<'a, Arc>; + +/// Runs one service call on the blocking pool and maps its failures. +/// +/// The caller has already passed [`authorize`]. A [`DesktopError`] becomes the +/// same `code` and `message`; a task that panicked or was cancelled becomes +/// `internal` with a fixed message. +pub(crate) async fn blocking(state: &Service<'_>, work: F) -> Result +where + T: Send + 'static, + F: FnOnce(&DesktopService) -> Result + Send + 'static, +{ + let service = Arc::clone(state.inner()); + match tauri::async_runtime::spawn_blocking(move || work(&service)).await { + Ok(result) => result.map_err(CommandError::from), + Err(_) => Err(CommandError::internal()), + } +} + +/// The reply to `app_info`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct AppInfo { + /// This crate's package version. + pub version: String, + /// `"windows"`, `"linux"`, or `"other"`. + pub platform: &'static str, + /// Whether the build supports model tools at all (not whether any is enabled). + pub model_tools_supported: bool, +} + +/// The platform name reported to the frontend. +const fn platform_name() -> &'static str { + if cfg!(target_os = "windows") { + "windows" + } else if cfg!(target_os = "linux") { + "linux" + } else { + "other" + } +} + +/// Builds the `app_info` reply. Separate from the handler so tests need no webview. +#[must_use] +pub fn app_info_value() -> AppInfo { + AppInfo { + version: env!("CARGO_PKG_VERSION").to_owned(), + platform: platform_name(), + model_tools_supported: omgcode_app::MODEL_TOOLS_SUPPORTED, + } +} + +/// `main` only. Returns the version, platform, and model-tool support. +/// +/// # Errors +/// +/// `forbidden_window` when the caller is not `main`. +#[tauri::command(rename_all = "snake_case")] +pub fn app_info(webview: Webview) -> Result { + authorize(Command::AppInfo, webview.label())?; + Ok(app_info_value()) +} + +/// `main` only. Shows, unminimizes, and focuses the existing `approvals` window. +/// It creates no window and navigates nothing. +/// +/// # Errors +/// +/// `forbidden_window` when the caller is not `main`; `window_unavailable` when +/// the approvals window is missing or the platform refuses a step. +#[tauri::command(rename_all = "snake_case")] +pub fn approvals_show_window(webview: Webview) -> Result<(), CommandError> { + authorize(Command::ApprovalsShowWindow, webview.label())?; + let window = webview + .app_handle() + .get_webview_window(WindowLabel::Approvals.as_str()) + .ok_or_else(CommandError::window_unavailable)?; + window + .unminimize() + .map_err(|_| CommandError::window_unavailable())?; + window + .show() + .map_err(|_| CommandError::window_unavailable())?; + window + .set_focus() + .map_err(|_| CommandError::window_unavailable())?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn app_info_reports_package_version_platform_and_tool_support() { + // When the reply is built. + let info = app_info_value(); + + // Then it carries this crate's version and the app crate's constant. + assert_eq!(info.version, env!("CARGO_PKG_VERSION")); + assert_eq!( + info.model_tools_supported, + omgcode_app::MODEL_TOOLS_SUPPORTED + ); + assert!(["windows", "linux", "other"].contains(&info.platform)); + } + + #[test] + fn app_info_serializes_with_snake_case_fields() { + let value = serde_json::to_value(app_info_value()).expect("serialize"); + let object = value.as_object().expect("object"); + let mut keys: Vec<&str> = object.keys().map(String::as_str).collect(); + keys.sort_unstable(); + assert_eq!(keys, ["model_tools_supported", "platform", "version"]); + } +} diff --git a/crates/omgcode-desktop/src/commands/approvals.rs b/crates/omgcode-desktop/src/commands/approvals.rs new file mode 100644 index 0000000..448e8c7 --- /dev/null +++ b/crates/omgcode-desktop/src/commands/approvals.rs @@ -0,0 +1,83 @@ +//! Approval handlers. `approvals_summary` belongs to `main`; the other three +//! belong to the `approvals` window only (ADR-0046 decisions 1 and 2). + +use omgcode_app::desktop::{ + ApprovalDecideRequest, ApprovalDetail, ApprovalList, ApprovalRequest, ApprovalView, + ApprovalsSummary, Decision, +}; +use tauri::Webview; +use uuid::Uuid; + +use super::{Service, blocking}; +use crate::error::CommandError; +use crate::policy::{Command, authorize}; + +/// `main` only. Counts pending approvals for the badge. It waits up to two +/// seconds for the settings store, which is why it runs on the blocking pool. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error. +#[tauri::command(rename_all = "snake_case")] +pub async fn approvals_summary( + webview: Webview, + state: Service<'_>, +) -> Result { + authorize(Command::ApprovalsSummary, webview.label())?; + blocking(&state, |service| service.approvals_summary()).await +} + +/// `approvals` only. Lists approval records. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error. +#[tauri::command(rename_all = "snake_case")] +pub async fn approvals_list( + webview: Webview, + state: Service<'_>, +) -> Result { + authorize(Command::ApprovalsList, webview.label())?; + blocking(&state, |service| service.approvals_list()).await +} + +/// `approvals` only. Returns the full review of one approval and a single-use +/// review token. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error. +#[tauri::command(rename_all = "snake_case")] +pub async fn approval_detail( + webview: Webview, + state: Service<'_>, + id: Uuid, +) -> Result { + authorize(Command::ApprovalDetail, webview.label())?; + let request = ApprovalRequest { id }; + blocking(&state, move |service| service.approval_detail(request)).await +} + +/// `approvals` only. Approves or denies one approval. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error. +#[tauri::command(rename_all = "snake_case")] +pub async fn approval_decide( + webview: Webview, + state: Service<'_>, + id: Uuid, + decision: Decision, + writers_stopped: bool, + review_token: Option, +) -> Result { + authorize(Command::ApprovalDecide, webview.label())?; + let request = ApprovalDecideRequest { + id, + decision, + writers_stopped, + review_token, + }; + blocking(&state, move |service| service.approval_decide(request)).await +} diff --git a/crates/omgcode-desktop/src/commands/chat.rs b/crates/omgcode-desktop/src/commands/chat.rs new file mode 100644 index 0000000..1de5470 --- /dev/null +++ b/crates/omgcode-desktop/src/commands/chat.rs @@ -0,0 +1,79 @@ +//! `main`-window handlers for chat settings, turns, status, and cancellation. + +use omgcode_app::desktop::{ChatSendRequest, ChatSettingsDto, ChatStatus, SessionRequest}; +use tauri::Webview; +use uuid::Uuid; + +use super::{Service, blocking}; +use crate::error::CommandError; +use crate::policy::{Command, authorize}; + +/// `main` only. Returns the process-wide chat defaults, including the fixed +/// endpoint the process was started with. +/// +/// # Errors +/// +/// `forbidden_window`, or `internal` when the blocking task fails. +#[tauri::command(rename_all = "snake_case")] +pub async fn chat_defaults( + webview: Webview, + state: Service<'_>, +) -> Result { + authorize(Command::ChatDefaults, webview.label())?; + blocking(&state, |service| Ok(service.chat_defaults())).await +} + +/// `main` only. Starts one chat turn on a service thread and returns at once. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error (`invalid_request` when the +/// endpoint differs from the process endpoint). +#[tauri::command(rename_all = "snake_case")] +pub async fn chat_send( + webview: Webview, + state: Service<'_>, + session_id: Uuid, + message: String, + settings: ChatSettingsDto, +) -> Result { + authorize(Command::ChatSend, webview.label())?; + let request = ChatSendRequest { + session_id, + message, + settings, + }; + blocking(&state, move |service| service.chat_send(request)).await +} + +/// `main` only. Reports a session's chat turn state. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error. +#[tauri::command(rename_all = "snake_case")] +pub async fn chat_status( + webview: Webview, + state: Service<'_>, + session_id: Uuid, +) -> Result { + authorize(Command::ChatStatus, webview.label())?; + let request = SessionRequest { session_id }; + blocking(&state, move |service| service.chat_status(request)).await +} + +/// `main` only. Requests cooperative cancellation of a running turn. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error. +#[tauri::command(rename_all = "snake_case")] +pub async fn chat_cancel( + webview: Webview, + state: Service<'_>, + session_id: Uuid, +) -> Result { + authorize(Command::ChatCancel, webview.label())?; + let request = SessionRequest { session_id }; + blocking(&state, move |service| service.chat_cancel(request)).await +} diff --git a/crates/omgcode-desktop/src/commands/sessions.rs b/crates/omgcode-desktop/src/commands/sessions.rs new file mode 100644 index 0000000..5f918de --- /dev/null +++ b/crates/omgcode-desktop/src/commands/sessions.rs @@ -0,0 +1,158 @@ +//! `main`-window handlers for the session tree, search, transcripts, the +//! session lifecycle, workspaces, and session creation. + +use omgcode_app::desktop::{ + SearchRequest, SearchResult, SessionCreateRequest, SessionRequest, SessionSummary, SessionTree, + TranscriptPage, TranscriptRequest, TreeRequest, TreeSort, TreeView, WorkspaceList, +}; +use tauri::Webview; +use uuid::Uuid; + +use super::{Service, blocking}; +use crate::error::CommandError; +use crate::policy::{Command, authorize}; + +/// `main` only. Lists sessions grouped by workspace folder. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error. +#[tauri::command(rename_all = "snake_case")] +pub async fn session_tree( + webview: Webview, + state: Service<'_>, + view: TreeView, + sort: TreeSort, + descending: bool, +) -> Result { + authorize(Command::SessionTree, webview.label())?; + let request = TreeRequest { + view, + sort, + descending, + }; + blocking(&state, move |service| service.session_tree(request)).await +} + +/// `main` only. Searches session text. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error. +#[tauri::command(rename_all = "snake_case")] +pub async fn session_search( + webview: Webview, + state: Service<'_>, + query: String, + view: TreeView, + limit: u32, +) -> Result { + authorize(Command::SessionSearch, webview.label())?; + let request = SearchRequest { query, view, limit }; + blocking(&state, move |service| service.session_search(request)).await +} + +/// `main` only. Reads one page of a session transcript. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error. +#[tauri::command(rename_all = "snake_case")] +pub async fn session_transcript( + webview: Webview, + state: Service<'_>, + session_id: Uuid, + after_seq: Option, + limit: u32, +) -> Result { + authorize(Command::SessionTranscript, webview.label())?; + let request = TranscriptRequest { + session_id, + after_seq, + limit, + }; + blocking(&state, move |service| service.session_transcript(request)).await +} + +/// `main` only. Archives a session. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error. +#[tauri::command(rename_all = "snake_case")] +pub async fn session_archive( + webview: Webview, + state: Service<'_>, + session_id: Uuid, +) -> Result { + authorize(Command::SessionArchive, webview.label())?; + let request = SessionRequest { session_id }; + blocking(&state, move |service| service.session_archive(request)).await +} + +/// `main` only. Restores an archived session. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error. +#[tauri::command(rename_all = "snake_case")] +pub async fn session_restore( + webview: Webview, + state: Service<'_>, + session_id: Uuid, +) -> Result { + authorize(Command::SessionRestore, webview.label())?; + let request = SessionRequest { session_id }; + blocking(&state, move |service| service.session_restore(request)).await +} + +/// `main` only. Closes a session's unfinished turn as operator-interrupted. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error. +#[tauri::command(rename_all = "snake_case")] +pub async fn session_interrupt( + webview: Webview, + state: Service<'_>, + session_id: Uuid, +) -> Result { + authorize(Command::SessionInterrupt, webview.label())?; + let request = SessionRequest { session_id }; + blocking(&state, move |service| service.session_interrupt(request)).await +} + +/// `main` only. Lists the workspaces the operator registered. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error. +#[tauri::command(rename_all = "snake_case")] +pub async fn workspace_list( + webview: Webview, + state: Service<'_>, +) -> Result { + authorize(Command::WorkspaceList, webview.label())?; + blocking(&state, |service| service.workspace_list()).await +} + +/// `main` only. Creates a session in a registered workspace. +/// +/// # Errors +/// +/// `forbidden_window`, or the service's error (`unknown_workspace` for an +/// identifier the operator did not register). +#[tauri::command(rename_all = "snake_case")] +pub async fn session_create( + webview: Webview, + state: Service<'_>, + workspace_id: Uuid, + title: String, +) -> Result { + authorize(Command::SessionCreate, webview.label())?; + let request = SessionCreateRequest { + workspace_id, + title, + }; + blocking(&state, move |service| service.session_create(request)).await +} diff --git a/crates/omgcode-desktop/src/error.rs b/crates/omgcode-desktop/src/error.rs new file mode 100644 index 0000000..4c23b07 --- /dev/null +++ b/crates/omgcode-desktop/src/error.rs @@ -0,0 +1,102 @@ +//! The error type returned to the webview. + +use std::borrow::Cow; + +use omgcode_app::desktop::DesktopError; +use serde::Serialize; + +/// An error that crosses the IPC boundary. +/// +/// The webview is untrusted, so a message is never built from a lower-level error +/// here. It is either a fixed string chosen in this crate or the message of a +/// [`DesktopError`], which the service keeps free of absolute paths, recorded +/// content, and the local server token. The `code` is a stable machine-readable +/// token the frontend may branch on. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct CommandError { + code: &'static str, + message: Cow<'static, str>, +} + +impl CommandError { + /// The calling webview is not the window this command belongs to. + pub(crate) const fn forbidden_window() -> Self { + Self { + code: "forbidden_window", + message: Cow::Borrowed("This window may not use this command."), + } + } + + /// A window the command needs is missing or could not be controlled. + pub(crate) const fn window_unavailable() -> Self { + Self { + code: "window_unavailable", + message: Cow::Borrowed("The requested window is not available."), + } + } + + /// A blocking task failed or panicked before it produced a result. + #[must_use] + pub const fn internal() -> Self { + Self { + code: "internal", + message: Cow::Borrowed("The command could not be completed."), + } + } + + /// The stable error code. + #[must_use] + pub const fn code(&self) -> &'static str { + self.code + } + + /// The message shown to the user. + #[must_use] + pub fn message(&self) -> &str { + &self.message + } +} + +impl From for CommandError { + /// Keeps the service's `code` and `message` exactly. + fn from(error: DesktopError) -> Self { + Self { + code: error.code(), + message: Cow::Owned(error.message().to_owned()), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn serializes_as_code_and_message_only() { + // Given a forbidden-window error. + let error = CommandError::forbidden_window(); + + // When it is serialized for the webview. + let value = serde_json::to_value(&error).expect("serialize"); + + // Then it has exactly the code and message fields. + assert_eq!( + value, + serde_json::json!({ + "code": "forbidden_window", + "message": "This window may not use this command." + }) + ); + } + + #[test] + fn messages_hold_no_path_separators() { + for error in [ + CommandError::forbidden_window(), + CommandError::window_unavailable(), + ] { + assert!(!error.message.contains(['/', '\\', ':'])); + assert!(!error.code().is_empty()); + } + } +} diff --git a/crates/omgcode-desktop/src/launch.rs b/crates/omgcode-desktop/src/launch.rs new file mode 100644 index 0000000..bc0e932 --- /dev/null +++ b/crates/omgcode-desktop/src/launch.rs @@ -0,0 +1,187 @@ +//! Launch configuration, read from the process command line only. +//! +//! ```text +//! omgcode-desktop [--data-dir ] [--endpoint ] +//! ``` +//! +//! The command line belongs to the operator who starts the process. The +//! webviews cannot influence it, and neither can workspace content. This module +//! reads no environment variable and no configuration file. The local server +//! token is a separate matter: the service reads `OMGCODE_LM_TOKEN` for each +//! chat turn and this module never touches it. +//! +//! Any unknown argument, a flag without a value, a value that looks like +//! another flag, an empty value, a non-UTF-8 endpoint, or a repeated flag is a +//! [`UsageError`]. The caller prints [`USAGE`] and exits before a window opens. + +use std::ffi::OsString; +use std::path::PathBuf; + +/// The endpoint used when `--endpoint` is absent. It is the CLI's default. +pub const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:1234/v1"; + +/// The fixed message printed to stderr for a usage error. +pub const USAGE: &str = "usage: omgcode-desktop [--data-dir ] [--endpoint ]\n \ +--data-dir application data root (default: the per-user OMGCode data directory)\n \ +--endpoint local model endpoint, a loopback http URL (default: http://127.0.0.1:1234/v1)"; + +/// What the command line asked for. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct LaunchArgs { + /// The data root override, or `None` for the per-user default. + pub data_dir: Option, + /// The chat endpoint for the whole process. + pub endpoint: String, +} + +/// The command line was not understood. It carries no detail on purpose: the +/// usage text is the only message. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct UsageError; + +/// Parses the arguments after the program name. +/// +/// A path is kept as an `OsString` so a non-UTF-8 path survives. A value must +/// not begin with `--`, so a forgotten value is not read as the next flag's +/// name. A flag given twice is refused, not merged. +/// +/// # Errors +/// +/// [`UsageError`] for anything outside the contract above. +pub fn parse_args(args: I) -> Result +where + I: IntoIterator, +{ + let mut data_dir: Option = None; + let mut endpoint: Option = None; + let mut args = args.into_iter(); + while let Some(flag) = args.next() { + let value = args.next().ok_or(UsageError)?; + if value.is_empty() || value.as_encoded_bytes().starts_with(b"--") { + return Err(UsageError); + } + match flag.to_str() { + Some("--data-dir") if data_dir.is_none() => data_dir = Some(PathBuf::from(value)), + Some("--endpoint") if endpoint.is_none() => { + endpoint = Some(value.into_string().map_err(|_| UsageError)?); + } + _ => return Err(UsageError), + } + } + Ok(LaunchArgs { + data_dir, + endpoint: endpoint.unwrap_or_else(|| DEFAULT_ENDPOINT.to_owned()), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(args: &[&str]) -> Result { + parse_args(args.iter().map(OsString::from)) + } + + #[test] + fn no_arguments_gives_the_defaults() { + assert_eq!( + parse(&[]), + Ok(LaunchArgs { + data_dir: None, + endpoint: DEFAULT_ENDPOINT.to_owned() + }) + ); + } + + #[test] + fn each_flag_sets_its_value_in_either_order() { + let both = LaunchArgs { + data_dir: Some(PathBuf::from("data")), + endpoint: "http://127.0.0.1:9/v1".to_owned(), + }; + assert_eq!( + parse(&["--data-dir", "data", "--endpoint", "http://127.0.0.1:9/v1"]), + Ok(both.clone()) + ); + assert_eq!( + parse(&["--endpoint", "http://127.0.0.1:9/v1", "--data-dir", "data"]), + Ok(both) + ); + assert_eq!( + parse(&["--data-dir", "C:\\a b\\c"]) + .expect("data dir") + .data_dir, + Some(PathBuf::from("C:\\a b\\c")) + ); + assert_eq!( + parse(&["--endpoint", "http://127.0.0.1:9/v1"]) + .expect("endpoint") + .data_dir, + None + ); + } + + #[test] + fn unknown_missing_repeated_and_malformed_arguments_are_refused() { + for args in [ + &["--bogus"][..], + &["--bogus", "x"], + &["positional"], + &["--data-dir"], + &["--endpoint"], + &["--data-dir", "a", "--endpoint"], + &["--data-dir", "a", "--data-dir", "b"], + &["--endpoint", "u", "--endpoint", "v"], + &["--data-dir", "--endpoint", "u"], + &["--data-dir", ""], + &["--endpoint", ""], + &["--data-dir=a"], + &["--endpoint=http://127.0.0.1:1/v1"], + &["-h"], + &["--help"], + &["--data-dir", "a", "extra"], + ] { + assert_eq!(parse(args), Err(UsageError), "{args:?}"); + } + } + + #[test] + fn usage_text_names_both_flags_and_the_default() { + assert!(USAGE.contains("--data-dir") && USAGE.contains("--endpoint")); + assert!(USAGE.contains(DEFAULT_ENDPOINT)); + } + + #[cfg(windows)] + #[test] + fn a_non_utf8_data_dir_is_kept_and_a_non_utf8_endpoint_is_refused() { + use std::os::windows::ffi::{OsStrExt, OsStringExt}; + + // Given a path with an unpaired surrogate, which is valid on Windows only. + let mut wide: Vec = OsString::from("C:\\data-").encode_wide().collect(); + wide.push(0xD800); + let odd = OsString::from_wide(&wide); + assert!(odd.to_str().is_none()); + + // Then the data root keeps it unchanged and the endpoint refuses it. + let kept = parse_args([OsString::from("--data-dir"), odd.clone()]).expect("path"); + assert_eq!(kept.data_dir, Some(PathBuf::from(&odd))); + assert_eq!( + parse_args([OsString::from("--endpoint"), odd]), + Err(UsageError) + ); + } + + #[cfg(unix)] + #[test] + fn a_non_utf8_data_dir_is_kept_and_a_non_utf8_endpoint_is_refused() { + use std::os::unix::ffi::OsStringExt; + + let odd = OsString::from_vec(b"/data-\xff".to_vec()); + let kept = parse_args([OsString::from("--data-dir"), odd.clone()]).expect("path"); + assert_eq!(kept.data_dir, Some(PathBuf::from(&odd))); + assert_eq!( + parse_args([OsString::from("--endpoint"), odd]), + Err(UsageError) + ); + } +} diff --git a/crates/omgcode-desktop/src/lib.rs b/crates/omgcode-desktop/src/lib.rs new file mode 100644 index 0000000..2622154 --- /dev/null +++ b/crates/omgcode-desktop/src/lib.rs @@ -0,0 +1,125 @@ +//! OMGCode desktop shell (Tauri 2). +//! +//! The Rust side is the only authority. Both webviews render untrusted text and +//! reach Rust only through commands that are (1) gated by a per-window Tauri +//! capability and (2) checked again against the window policy in +//! [`policy`]. See ADR-0045 and ADR-0046. +//! +//! The data root and the model endpoint come from the process command line +//! ([`launch`]) and nowhere else. + +pub mod commands; +pub mod error; +pub mod launch; +pub mod policy; +pub mod shutdown; +pub mod windows; + +use std::process::ExitCode; +use std::sync::Arc; + +use omgcode_app::desktop::{DesktopConfig, DesktopService}; +use omgcode_app::{ChatClients, ChatSettings}; +use tauri::{Manager, RunEvent}; + +use crate::launch::{LaunchArgs, USAGE}; +use crate::shutdown::ShutdownGate; + +/// Exit code for a command line that was not understood. +const EXIT_USAGE: u8 = 2; + +/// A context size that is valid for any model, used only to validate the endpoint. +const PROBE_CONTEXT_TOKENS: u64 = 8192; + +/// Builds and runs the application. +/// +/// Exit codes: `0` after a normal close, `2` for a command-line usage error, +/// `1` for any other startup failure (endpoint rejected, data root or index +/// unusable, runtime could not start). Every failure happens before a window +/// opens and prints a fixed or provider message to stderr. In a release build +/// on Windows the process has no console, so stderr is visible only when it is +/// redirected. +#[must_use] +pub fn run() -> ExitCode { + let Ok(args) = launch::parse_args(std::env::args_os().skip(1)) else { + eprintln!("{USAGE}"); + return ExitCode::from(EXIT_USAGE); + }; + let service = match open_service(args) { + Ok(service) => Arc::new(service), + Err(message) => { + eprintln!("omgcode-desktop: {message}"); + return ExitCode::FAILURE; + } + }; + run_app(service) +} + +/// Validates the endpoint and opens the one service for this process. +fn open_service(args: LaunchArgs) -> Result { + // Validate the endpoint the way a chat turn would, so a malformed or + // non-loopback endpoint fails now, with the provider's message. The clients + // are discarded; no request is made and no token is read. + let probe = ChatSettings::new( + args.endpoint.clone(), + "endpoint-check", + PROBE_CONTEXT_TOKENS, + ); + ChatClients::new(&probe, None).map_err(|error| error.to_string())?; + let data_root = omgcode_app::data_root(args.data_dir).map_err(|error| error.to_string())?; + DesktopService::open(DesktopConfig { + data_root, + endpoint: args.endpoint, + }) + .map_err(|error| format!("{}: {}", error.code(), error.message())) +} + +fn run_app(service: Arc) -> ExitCode { + let built = tauri::Builder::default() + .manage(service) + .manage(ShutdownGate::default()) + .setup(|app| { + windows::create_windows(app)?; + Ok(()) + }) + .invoke_handler(tauri::generate_handler![ + commands::app_info, + commands::sessions::session_tree, + commands::sessions::session_search, + commands::sessions::session_transcript, + commands::sessions::session_archive, + commands::sessions::session_restore, + commands::sessions::session_interrupt, + commands::sessions::workspace_list, + commands::sessions::session_create, + commands::chat::chat_defaults, + commands::chat::chat_send, + commands::chat::chat_status, + commands::chat::chat_cancel, + commands::approvals::approvals_summary, + commands::approvals_show_window, + commands::approvals::approvals_list, + commands::approvals::approval_detail, + commands::approvals::approval_decide + ]) + .build(tauri::generate_context!()); + match built { + Ok(app) => { + app.run(|handle, event| { + // Any exit path that did not come from the bounded shutdown is + // stopped, run through that shutdown once, and then allowed. + if let RunEvent::ExitRequested { code, api, .. } = event + && !handle.state::().is_done() + { + api.prevent_exit(); + shutdown::begin(handle, code.unwrap_or(0)); + } + }); + ExitCode::SUCCESS + } + Err(_) => { + eprintln!("omgcode-desktop: the application could not start"); + ExitCode::FAILURE + } + } +} diff --git a/crates/omgcode-desktop/src/main.rs b/crates/omgcode-desktop/src/main.rs new file mode 100644 index 0000000..7c358b0 --- /dev/null +++ b/crates/omgcode-desktop/src/main.rs @@ -0,0 +1,8 @@ +// Hide the console window in release builds on Windows. +#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] + +use std::process::ExitCode; + +fn main() -> ExitCode { + omgcode_desktop_lib::run() +} diff --git a/crates/omgcode-desktop/src/policy.rs b/crates/omgcode-desktop/src/policy.rs new file mode 100644 index 0000000..0275771 --- /dev/null +++ b/crates/omgcode-desktop/src/policy.rs @@ -0,0 +1,225 @@ +//! The window policy: which webview may call which command. +//! +//! This is the second of two layers (ADR-0046 decision 2). Tauri's capability +//! files are the first. Every command handler calls [`authorize`] before doing +//! anything else, so a capability file edited by mistake cannot expose a decision +//! command to the wrong window. The calling label comes from the runtime, which +//! binds the IPC channel to the webview that owns it; page script cannot choose it. + +use crate::error::CommandError; + +/// The two webview windows. Labels are fixed at creation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WindowLabel { + /// Session tree, transcripts, and chat. + Main, + /// The only window that may list, review, and decide approvals. + Approvals, +} + +impl WindowLabel { + /// The label string passed to the window builder and matched in capabilities. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Main => "main", + Self::Approvals => "approvals", + } + } +} + +/// Every application command. The set is closed: adding a command means adding +/// a variant here, a name in `command_names.rs`, and a capability grant. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Command { + AppInfo, + SessionTree, + SessionSearch, + SessionTranscript, + SessionArchive, + SessionRestore, + SessionInterrupt, + WorkspaceList, + SessionCreate, + ChatDefaults, + ChatSend, + ChatStatus, + ChatCancel, + ApprovalsSummary, + ApprovalsShowWindow, + ApprovalsList, + ApprovalDetail, + ApprovalDecide, +} + +impl Command { + /// All commands, in the order of `command_names.rs`. + pub const ALL: [Self; 18] = [ + Self::AppInfo, + Self::SessionTree, + Self::SessionSearch, + Self::SessionTranscript, + Self::SessionArchive, + Self::SessionRestore, + Self::SessionInterrupt, + Self::WorkspaceList, + Self::SessionCreate, + Self::ChatDefaults, + Self::ChatSend, + Self::ChatStatus, + Self::ChatCancel, + Self::ApprovalsSummary, + Self::ApprovalsShowWindow, + Self::ApprovalsList, + Self::ApprovalDetail, + Self::ApprovalDecide, + ]; + + /// The command name exactly as the frontend invokes it. + #[must_use] + pub const fn name(self) -> &'static str { + match self { + Self::AppInfo => "app_info", + Self::SessionTree => "session_tree", + Self::SessionSearch => "session_search", + Self::SessionTranscript => "session_transcript", + Self::SessionArchive => "session_archive", + Self::SessionRestore => "session_restore", + Self::SessionInterrupt => "session_interrupt", + Self::WorkspaceList => "workspace_list", + Self::SessionCreate => "session_create", + Self::ChatDefaults => "chat_defaults", + Self::ChatSend => "chat_send", + Self::ChatStatus => "chat_status", + Self::ChatCancel => "chat_cancel", + Self::ApprovalsSummary => "approvals_summary", + Self::ApprovalsShowWindow => "approvals_show_window", + Self::ApprovalsList => "approvals_list", + Self::ApprovalDetail => "approval_detail", + Self::ApprovalDecide => "approval_decide", + } + } + + /// The one window allowed to call this command. + #[must_use] + pub const fn window(self) -> WindowLabel { + match self { + Self::ApprovalsList | Self::ApprovalDetail | Self::ApprovalDecide => { + WindowLabel::Approvals + } + Self::AppInfo + | Self::SessionTree + | Self::SessionSearch + | Self::SessionTranscript + | Self::SessionArchive + | Self::SessionRestore + | Self::SessionInterrupt + | Self::WorkspaceList + | Self::SessionCreate + | Self::ChatDefaults + | Self::ChatSend + | Self::ChatStatus + | Self::ChatCancel + | Self::ApprovalsSummary + | Self::ApprovalsShowWindow => WindowLabel::Main, + } + } +} + +/// Allows `command` only when `caller_label` is exactly its window's label. +/// +/// Call this first in every handler, with the label of the webview that sent +/// the request (never a label taken from the request body). An unknown or empty +/// label is refused. +/// +/// # Errors +/// +/// Returns `forbidden_window` when the caller is not the command's window. +pub fn authorize(command: Command, caller_label: &str) -> Result<(), CommandError> { + if caller_label == command.window().as_str() { + Ok(()) + } else { + Err(CommandError::forbidden_window()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeSet; + + include!("command_names.rs"); + + fn with_window(window: WindowLabel) -> Vec { + Command::ALL + .into_iter() + .filter(|command| command.window() == window) + .collect() + } + + #[test] + fn every_command_has_exactly_one_window_and_the_counts_match() { + assert_eq!(Command::ALL.len(), 18); + assert_eq!(with_window(WindowLabel::Main).len(), 15); + assert_eq!(with_window(WindowLabel::Approvals).len(), 3); + } + + #[test] + fn approval_commands_are_approvals_only() { + for command in [ + Command::ApprovalsList, + Command::ApprovalDetail, + Command::ApprovalDecide, + ] { + assert_eq!(command.window(), WindowLabel::Approvals); + assert_eq!(authorize(command, "approvals"), Ok(())); + for label in ["main", "unknown", "", "Approvals", "approvals ", "main\0"] { + assert_eq!( + authorize(command, label), + Err(CommandError::forbidden_window()), + "{} must be refused for {label:?}", + command.name() + ); + } + } + } + + #[test] + fn main_commands_are_refused_for_every_other_label() { + for command in with_window(WindowLabel::Main) { + assert_eq!(authorize(command, "main"), Ok(())); + for label in ["approvals", "unknown", ""] { + assert_eq!( + authorize(command, label), + Err(CommandError::forbidden_window()), + "{} must be refused for {label:?}", + command.name() + ); + } + } + } + + #[test] + fn names_are_unique_snake_case() { + let names: BTreeSet<&str> = Command::ALL.iter().map(|c| c.name()).collect(); + assert_eq!(names.len(), Command::ALL.len()); + for name in names { + assert!(!name.is_empty()); + assert!( + name.bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'), + "{name} is not snake_case" + ); + assert!(!name.starts_with('_') && !name.ends_with('_') && !name.contains("__")); + } + } + + #[test] + fn shared_name_list_has_eighteen_unique_names_matching_the_enum() { + let shared: BTreeSet<&str> = COMMAND_NAMES.iter().copied().collect(); + assert_eq!(COMMAND_NAMES.len(), 18); + assert_eq!(shared.len(), 18); + let from_enum: Vec<&str> = Command::ALL.iter().map(|c| c.name()).collect(); + assert_eq!(from_enum, COMMAND_NAMES); + } +} diff --git a/crates/omgcode-desktop/src/shutdown.rs b/crates/omgcode-desktop/src/shutdown.rs new file mode 100644 index 0000000..02b8516 --- /dev/null +++ b/crates/omgcode-desktop/src/shutdown.rs @@ -0,0 +1,116 @@ +//! Bounded, idempotent shutdown. +//! +//! Closing `main` (or any other exit path) must not freeze the UI thread for +//! the service's grace period. The first request hides both windows at once, +//! then runs [`DesktopService::shutdown`] on a separate thread and exits the +//! application. A request that arrives while shutdown runs does nothing. +//! +//! A chat turn still waiting on the model provider when the grace period ends +//! is abandoned: a provider request in flight cannot be interrupted. Its +//! journal keeps an open turn, which the operator can close later with the +//! interrupt command or the trusted CLI. + +use std::sync::Arc; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::time::Duration; + +use omgcode_app::desktop::DesktopService; +use tauri::{AppHandle, Manager}; + +use crate::policy::WindowLabel; + +/// How long running turns get to stop before the process exits anyway. +pub const GRACE: Duration = Duration::from_secs(5); + +const IDLE: u8 = 0; +const RUNNING: u8 = 1; +const DONE: u8 = 2; + +/// The shutdown progress, shared as Tauri state. +#[derive(Debug, Default)] +pub struct ShutdownGate { + phase: AtomicU8, +} + +impl ShutdownGate { + /// Moves from idle to running. Returns `true` for exactly one caller. + #[must_use] + pub fn begin(&self) -> bool { + self.phase + .compare_exchange(IDLE, RUNNING, Ordering::AcqRel, Ordering::Acquire) + .is_ok() + } + + /// Records that the bounded shutdown has finished. + pub fn finish(&self) { + self.phase.store(DONE, Ordering::Release); + } + + /// Whether the bounded shutdown has finished, so an exit may proceed. + #[must_use] + pub fn is_done(&self) -> bool { + self.phase.load(Ordering::Acquire) == DONE + } +} + +/// Starts the shutdown once. Later calls, from any thread, do nothing. +/// +/// Both windows are hidden first so the user sees the application close at +/// once. The service shutdown and the final `exit(code)` run on one new thread. +pub fn begin(app: &AppHandle, code: i32) { + let gate = app.state::(); + if !gate.begin() { + return; + } + for label in [WindowLabel::Main, WindowLabel::Approvals] { + if let Some(window) = app.get_webview_window(label.as_str()) + && window.hide().is_err() + { + eprintln!("omgcode-desktop: could not hide a window during shutdown"); + } + } + let service = Arc::clone(&*app.state::>()); + let handle = app.clone(); + let spawned = std::thread::Builder::new() + .name("omgcode-shutdown".to_owned()) + .spawn(move || { + let report = service.shutdown(GRACE); + if report.still_running > 0 { + eprintln!( + "omgcode-desktop: {} chat turn(s) were still waiting on the provider and \ + were abandoned; interrupt each session to close its open turn", + report.still_running + ); + } + handle.state::().finish(); + handle.exit(code); + }); + if spawned.is_err() { + // No thread: exit now rather than hang with hidden windows. Open turns stay open. + eprintln!("omgcode-desktop: could not start the shutdown thread"); + gate.finish(); + app.exit(code); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_the_first_begin_wins_and_finish_is_observed() { + // Given a fresh gate. + let gate = ShutdownGate::default(); + assert!(!gate.is_done()); + + // When shutdown is requested twice. + assert!(gate.begin()); + assert!(!gate.begin()); + + // Then it is not done until finished, and stays begun afterwards. + assert!(!gate.is_done()); + gate.finish(); + assert!(gate.is_done()); + assert!(!gate.begin()); + } +} diff --git a/crates/omgcode-desktop/src/windows.rs b/crates/omgcode-desktop/src/windows.rs new file mode 100644 index 0000000..66aa1ba --- /dev/null +++ b/crates/omgcode-desktop/src/windows.rs @@ -0,0 +1,207 @@ +//! Window creation, the navigation guard, and close behaviour. +//! +//! Both windows are created in Rust so that the navigation and new-window +//! hooks are attached before the first page loads. Neither window may leave +//! the application's own origin: the webviews hold the IPC capability, so an +//! external page inside one would be a privilege problem. + +use tauri::webview::NewWindowResponse; +use tauri::{App, Url, WebviewUrl, WebviewWindowBuilder, WindowEvent}; + +use crate::policy::WindowLabel; +use crate::shutdown; + +/// The development server origin. Honoured in debug builds only. +const DEV_HOST: &str = "localhost"; +const DEV_PORT: u16 = 1420; + +/// Tauri's bundled-asset origin: `http://tauri.localhost` on Windows (the +/// default scheme; `useHttpsScheme` stays off because the CSP names +/// `http://ipc.localhost`) and `tauri://localhost` elsewhere. +const APP_HOST: &str = "localhost"; +const WINDOWS_APP_HOST: &str = "tauri.localhost"; + +/// Decides whether a webview may navigate to `url`. +/// +/// Allowed: the platform's bundled-asset origin, and `http://localhost:1420` in +/// debug builds. Everything else is denied, including `about:blank`, `file:`, +/// `data:`, `javascript:`, `blob:`, other loopback addresses and ports, and any +/// URL with credentials. The origin is compared on parsed scheme, host, and +/// port, never on a string prefix, so `tauri.localhost.evil.test` and +/// `http://tauri.localhost@evil.test/` are refused. `about:blank` is denied +/// because no page in this application needs it. +#[must_use] +pub fn navigation_allowed(url: &Url, debug: bool) -> bool { + allowed_for(url, cfg!(windows), debug) +} + +/// [`navigation_allowed`] with the platform made explicit so both can be tested. +fn allowed_for(url: &Url, windows: bool, debug: bool) -> bool { + if !url.username().is_empty() || url.password().is_some() { + return false; + } + let Some(host) = url.host_str() else { + return false; + }; + let port = url.port(); + match url.scheme() { + "http" => { + (windows && host == WINDOWS_APP_HOST && port.is_none()) + || (debug && host == DEV_HOST && port == Some(DEV_PORT)) + } + "tauri" => !windows && host == APP_HOST && port.is_none(), + _ => false, + } +} + +/// Creates the `main` and `approvals` windows. +/// +/// `approvals` starts hidden. Devtools exist only in debug builds. File +/// drag-and-drop is disabled so a dropped file cannot navigate a webview. +/// +/// # Errors +/// +/// Returns the runtime's error when a window cannot be built. +pub fn create_windows(app: &App) -> tauri::Result<()> { + let debug = cfg!(debug_assertions); + + let main = WebviewWindowBuilder::new( + app, + WindowLabel::Main.as_str(), + WebviewUrl::App("index.html".into()), + ) + .title("OMGCode") + .inner_size(1200.0, 800.0) + .min_inner_size(800.0, 560.0) + .disable_drag_drop_handler() + .devtools(debug) + .on_navigation(move |url| navigation_allowed(url, debug)) + .on_new_window(|_, _| NewWindowResponse::Deny) + .build()?; + let handle = app.handle().clone(); + main.on_window_event(move |event| { + // Closing `main` ends the application; the hidden approvals window must + // not keep the process alive. The close is held back so both windows can + // be hidden at once and the bounded shutdown can run off this thread. + if let WindowEvent::CloseRequested { api, .. } = event { + api.prevent_close(); + shutdown::begin(&handle, 0); + } + }); + + let approvals = WebviewWindowBuilder::new( + app, + WindowLabel::Approvals.as_str(), + WebviewUrl::App("approvals.html".into()), + ) + .title("OMGCode \u{2014} Tool approvals") + .inner_size(760.0, 720.0) + .min_inner_size(560.0, 480.0) + .visible(false) + .disable_drag_drop_handler() + .devtools(debug) + .on_navigation(move |url| navigation_allowed(url, debug)) + .on_new_window(|_, _| NewWindowResponse::Deny) + .build()?; + let hidden = approvals.clone(); + approvals.on_window_event(move |event| { + // Closing hides the window so its state and the process survive. + if let WindowEvent::CloseRequested { api, .. } = event { + api.prevent_close(); + if hidden.hide().is_err() { + eprintln!("omgcode-desktop: could not hide the approvals window"); + } + } + }); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn url(text: &str) -> Url { + Url::parse(text).expect("test URL parses") + } + + #[test] + fn app_origin_is_allowed_per_platform() { + assert!(allowed_for( + &url("http://tauri.localhost/index.html"), + true, + false + )); + assert!(allowed_for(&url("http://tauri.localhost/"), true, true)); + assert!(allowed_for( + &url("tauri://localhost/approvals.html"), + false, + false + )); + // The other platform's origin is not accepted. + assert!(!allowed_for(&url("tauri://localhost/"), true, false)); + assert!(!allowed_for(&url("http://tauri.localhost/"), false, false)); + assert!(!allowed_for(&url("https://tauri.localhost/"), true, false)); + } + + #[test] + fn dev_server_is_allowed_only_in_debug() { + for windows in [true, false] { + assert!(allowed_for(&url("http://localhost:1420/"), windows, true)); + assert!(!allowed_for(&url("http://localhost:1420/"), windows, false)); + assert!(!allowed_for(&url("http://localhost:1421/"), windows, true)); + assert!(!allowed_for(&url("http://localhost/"), windows, true)); + assert!(!allowed_for(&url("https://localhost:1420/"), windows, true)); + } + } + + #[test] + fn foreign_and_unusual_urls_are_denied() { + for windows in [true, false] { + for debug in [true, false] { + for text in [ + "https://example.com/", + "http://127.0.0.1:1420/", + "http://[::1]:1420/", + "file:///", + "file:///C:/Windows/win.ini", + "data:text/html,

x

", + "javascript:alert(1)", + "about:blank", + "blob:http://tauri.localhost/1", + "http://tauri.localhost.evil.test/", + "http://tauri.localhost@evil.test/", + "http://tauri.localhost:80@evil.test/", + "http://evil.test@tauri.localhost/", + "http://user:pw@tauri.localhost/", + "http://tauri.localhost:8080/", + "http://evil.test/tauri.localhost", + "tauri://localhost.evil.test/", + "tauri://evil@localhost/", + "ipc://localhost/app_info", + ] { + assert!( + !allowed_for(&url(text), windows, debug), + "{text} must be denied (windows={windows}, debug={debug})" + ); + } + } + } + } + + #[test] + fn host_case_and_default_port_normalize() { + assert!(allowed_for(&url("http://TAURI.LOCALHOST:80/"), true, false)); + assert!(allowed_for(&url("HTTP://Tauri.Localhost/"), true, false)); + } + + #[test] + fn public_function_uses_the_build_platform() { + let own = if cfg!(windows) { + "http://tauri.localhost/" + } else { + "tauri://localhost/" + }; + assert!(navigation_allowed(&url(own), false)); + assert!(!navigation_allowed(&url("https://example.com/"), true)); + } +} diff --git a/crates/omgcode-desktop/tauri.conf.json b/crates/omgcode-desktop/tauri.conf.json new file mode 100644 index 0000000..67566b5 --- /dev/null +++ b/crates/omgcode-desktop/tauri.conf.json @@ -0,0 +1,30 @@ +{ + "$schema": "https://schema.tauri.app/config/2", + "productName": "OMGCode", + "identifier": "org.omg-software.omgcode", + "build": { + "frontendDist": "ui/dist", + "devUrl": "http://localhost:1420", + "beforeDevCommand": { "script": "npm run dev", "cwd": "ui" }, + "beforeBuildCommand": { "script": "npm run build", "cwd": "ui" } + }, + "app": { + "withGlobalTauri": false, + "windows": [], + "security": { + "csp": "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; font-src 'self'; connect-src ipc: http://ipc.localhost; base-uri 'none'; form-action 'none'; frame-ancestors 'none'", + "freezePrototype": true, + "assetProtocol": { "enable": false, "scope": [] }, + "capabilities": ["main-window", "approvals-window"] + } + }, + "bundle": { + "active": false, + "icon": [ + "icons/32x32.png", + "icons/128x128.png", + "icons/128x128@2x.png", + "icons/icon.ico" + ] + } +} diff --git a/crates/omgcode-desktop/tests/layers.rs b/crates/omgcode-desktop/tests/layers.rs new file mode 100644 index 0000000..31d6106 --- /dev/null +++ b/crates/omgcode-desktop/tests/layers.rs @@ -0,0 +1,669 @@ +//! Agreement between the layers that gate a command: the Rust policy, the +//! capability files, the build manifest, the frontend's calls, and the Tauri +//! configuration. None of these tests starts a webview. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::{Path, PathBuf}; + +use omgcode_app::desktop::{DesktopConfig, DesktopService, SessionRequest}; +use omgcode_desktop_lib::error::CommandError; +use omgcode_desktop_lib::policy::{Command, WindowLabel}; +use serde_json::Value; + +const COMMAND_NAMES_SOURCE: &str = include_str!("../src/command_names.rs"); + +fn crate_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) +} + +fn read(path: &Path) -> String { + fs::read_to_string(path).unwrap_or_else(|error| panic!("read {}: {error}", path.display())) +} + +fn json(path: &Path) -> Value { + serde_json::from_str(&read(path)) + .unwrap_or_else(|error| panic!("parse {}: {error}", path.display())) +} + +/// The permission identifier Tauri generates for an application command. +fn permission_for(command: Command) -> String { + format!("allow-{}", command.name().replace('_', "-")) +} + +fn commands_for(window: WindowLabel) -> BTreeSet<&'static str> { + Command::ALL + .into_iter() + .filter(|command| command.window() == window) + .map(Command::name) + .collect() +} + +fn capability_files() -> Vec { + let mut files: Vec = fs::read_dir(crate_dir().join("capabilities")) + .expect("capabilities directory") + .map(|entry| entry.expect("entry").path()) + .collect(); + files.sort(); + files +} + +fn capability_for(window: WindowLabel) -> Value { + let matching: Vec = capability_files() + .iter() + .map(|path| json(path)) + .filter(|capability| capability["windows"] == serde_json::json!([window.as_str()])) + .collect(); + assert_eq!(matching.len(), 1, "one capability per window"); + matching.into_iter().next().expect("one capability") +} + +fn string_array(value: &Value) -> Vec { + value + .as_array() + .expect("array") + .iter() + .map(|item| item.as_str().expect("plain string entry").to_owned()) + .collect() +} + +#[test] +fn capability_grants_equal_the_policy_for_each_window() { + for window in [WindowLabel::Main, WindowLabel::Approvals] { + // Given the capability that names this window. + let capability = capability_for(window); + + // When its permissions are read. + let granted = string_array(&capability["permissions"]); + let granted_set: BTreeSet<&str> = granted.iter().map(String::as_str).collect(); + + // Then they are exactly the policy's commands for the window, once each. + let expected: Vec = Command::ALL + .into_iter() + .filter(|command| command.window() == window) + .map(permission_for) + .collect(); + let expected_set: BTreeSet<&str> = expected.iter().map(String::as_str).collect(); + assert_eq!(granted_set, expected_set, "{window:?} grants"); + assert_eq!(granted.len(), expected.len(), "no duplicate grants"); + assert!( + granted.iter().all(|p| !p.contains(':')), + "no core or plugin permission" + ); + } +} + +#[test] +fn each_capability_names_one_local_window_and_no_remote_url() { + let files = capability_files(); + assert_eq!(files.len(), 2, "exactly two capability files"); + for path in files { + let capability = json(&path); + let windows = string_array(&capability["windows"]); + assert_eq!(windows.len(), 1, "{}", path.display()); + assert!( + !windows[0].contains(['*', '?', '[']), + "no glob in {}", + path.display() + ); + assert_eq!(capability["local"], Value::Bool(true)); + assert!(capability.get("remote").is_none(), "no remote access"); + assert!(capability.get("webviews").is_none(), "windows only"); + assert!(capability.get("platforms").is_none(), "all platforms"); + } + let labels: BTreeSet = capability_files() + .iter() + .flat_map(|path| string_array(&json(path)["windows"])) + .collect(); + assert_eq!( + labels, + BTreeSet::from(["main".to_owned(), "approvals".to_owned()]) + ); +} + +#[test] +fn decision_commands_are_granted_to_no_other_window() { + let main = string_array(&capability_for(WindowLabel::Main)["permissions"]); + for command in [ + Command::ApprovalsList, + Command::ApprovalDetail, + Command::ApprovalDecide, + ] { + assert!(!main.contains(&permission_for(command))); + } + let approvals = string_array(&capability_for(WindowLabel::Approvals)["permissions"]); + assert_eq!(approvals.len(), 3); +} + +#[test] +fn build_script_declares_the_shared_command_list() { + // Given the shared list and the build script. + let build = read(&crate_dir().join("build.rs")); + + // Then the script includes that file, so the manifest is the policy's list. + assert!(build.contains("include!(\"src/command_names.rs\")")); + assert!(build.contains(".commands(COMMAND_NAMES)")); + + // And the shared list holds the 18 unique policy names. + let listed: Vec<&str> = COMMAND_NAMES_SOURCE + .lines() + .filter_map(|line| line.trim().strip_prefix('"')) + .filter_map(|rest| rest.strip_suffix("\",")) + .collect(); + let unique: BTreeSet<&str> = listed.iter().copied().collect(); + assert_eq!(listed.len(), 18); + assert_eq!(unique.len(), 18); + let policy: Vec<&str> = Command::ALL.into_iter().map(Command::name).collect(); + assert_eq!(listed, policy); +} + +/// Command names passed to `invokeCommand("name", ...)` in a TypeScript file. +fn invoked_commands(source: &str) -> BTreeSet { + let mut found = BTreeSet::new(); + let mut rest = source; + while let Some(at) = rest.find("invokeCommand<") { + rest = &rest[at + "invokeCommand<".len()..]; + let Some(open) = rest.find(">(\"") else { break }; + // The generic argument and `(` must belong to one expression. + if rest[..open].contains([';', '\n']) { + continue; + } + let name_start = open + 3; + if let Some(len) = rest[name_start..].find('"') { + found.insert(rest[name_start..name_start + len].to_owned()); + } + } + found +} + +#[test] +fn frontend_clients_call_only_commands_the_policy_gives_their_window() { + // Given the two IPC client modules. + let ui = crate_dir().join("ui/src/ipc"); + let main_calls = invoked_commands(&read(&ui.join("client.ts"))); + let approval_calls = invoked_commands(&read(&ui.join("approvals_client.ts"))); + + // Then the main client uses a subset of the main commands (all 15 today)... + let main_commands: BTreeSet = commands_for(WindowLabel::Main) + .into_iter() + .map(str::to_owned) + .collect(); + assert!(main_calls.is_subset(&main_commands), "{main_calls:?}"); + assert_eq!(main_calls.len(), 15); + + // ...the approvals client uses exactly the three approval commands... + let approval_commands: BTreeSet = commands_for(WindowLabel::Approvals) + .into_iter() + .map(str::to_owned) + .collect(); + assert_eq!(approval_calls, approval_commands); + + // ...and together they cover all 18 policy commands. + let union: BTreeSet = main_calls.union(&approval_calls).cloned().collect(); + let all: BTreeSet = Command::ALL + .into_iter() + .map(|c| c.name().to_owned()) + .collect(); + assert_eq!(union, all); +} + +fn csp_directives(csp: &str) -> Vec<(String, Vec)> { + csp.split(';') + .map(str::trim) + .filter(|directive| !directive.is_empty()) + .map(|directive| { + let mut parts = directive.split_whitespace().map(str::to_owned); + let name = parts.next().expect("directive name"); + (name, parts.collect()) + }) + .collect() +} + +#[test] +fn tauri_config_is_locked_down() { + let config = json(&crate_dir().join("tauri.conf.json")); + + // Globals, bundling, windows, and assets. + assert_eq!(config["app"]["withGlobalTauri"], Value::Bool(false)); + assert_eq!(config["bundle"]["active"], Value::Bool(false)); + assert_eq!(config["app"]["windows"], serde_json::json!([])); + assert_eq!( + config["app"]["security"]["freezePrototype"], + Value::Bool(true) + ); + assert_eq!( + config["app"]["security"]["assetProtocol"]["enable"], + Value::Bool(false) + ); + assert!( + config["app"]["security"] + .as_object() + .expect("security") + .keys() + .all(|key| !key.starts_with("dangerous")), + "no dangerous flag" + ); + + // The capability list is exactly the two files' identifiers. + let listed = string_array(&config["app"]["security"]["capabilities"]); + let from_files: Vec = capability_files() + .iter() + .map(|path| { + json(path)["identifier"] + .as_str() + .expect("identifier") + .to_owned() + }) + .collect(); + let listed_set: BTreeSet<&String> = listed.iter().collect(); + let files_set: BTreeSet<&String> = from_files.iter().collect(); + assert_eq!(listed.len(), 2); + assert_eq!(listed_set, files_set); + + // The CSP carries each required directive and no loose source. + let csp = config["app"]["security"]["csp"] + .as_str() + .expect("csp string"); + let directives = csp_directives(csp); + let get = |name: &str| -> Vec { + let matching: Vec<_> = directives.iter().filter(|(n, _)| n == name).collect(); + assert_eq!(matching.len(), 1, "directive {name} appears once"); + matching[0].1.clone() + }; + assert_eq!(get("default-src"), ["'none'"]); + assert_eq!(get("script-src"), ["'self'"]); + assert_eq!(get("style-src"), ["'self'"]); + assert_eq!(get("img-src"), ["'self'"]); + assert_eq!(get("font-src"), ["'self'"]); + assert_eq!(get("connect-src"), ["ipc:", "http://ipc.localhost"]); + assert_eq!(get("base-uri"), ["'none'"]); + assert_eq!(get("form-action"), ["'none'"]); + assert_eq!(get("frame-ancestors"), ["'none'"]); + for (_, sources) in &directives { + for source in sources { + assert!( + !matches!(source.as_str(), "'unsafe-inline'" | "'unsafe-eval'" | "*"), + "loose source {source}" + ); + assert!(!source.starts_with("data:") && !source.starts_with("blob:")); + if source.starts_with("http://") || source.starts_with("https://") { + assert_eq!(source, "http://ipc.localhost"); + } + } + } +} + +// --------------------------------------------------------------------------- +// Handlers: registration, window policy call, and argument names. +// --------------------------------------------------------------------------- + +/// Every source file that may hold a `#[tauri::command]`. +fn handler_sources() -> Vec<(PathBuf, String)> { + let mut paths = vec![crate_dir().join("src/commands.rs")]; + let mut nested: Vec = fs::read_dir(crate_dir().join("src/commands")) + .expect("commands directory") + .map(|entry| entry.expect("entry").path()) + .filter(|path| path.extension().is_some_and(|ext| ext == "rs")) + .collect(); + nested.sort(); + paths.extend(nested); + paths + .into_iter() + .map(|path| { + let text = read(&path); + (path, text) + }) + .collect() +} + +/// One `#[tauri::command]` function as found in source text. +struct Handler { + name: String, + is_async: bool, + /// The parameter list as `(name, type)` pairs. + params: Vec<(String, String)>, + /// The text from the opening brace of the body to the end of the handler. + body: String, +} + +/// Splits `text` at commas that are not nested in `<>`, `()`, `[]`, or `{}`. +fn split_top_level(text: &str) -> Vec { + let mut parts = Vec::new(); + let mut depth = 0_i32; + let mut current = String::new(); + let mut previous = ' '; + for ch in text.chars() { + match ch { + '<' | '(' | '[' | '{' => depth += 1, + // `->` is not a closing angle bracket. + '>' if previous == '-' => {} + '>' | ')' | ']' | '}' => depth -= 1, + ',' if depth == 0 => { + parts.push(std::mem::take(&mut current)); + previous = ch; + continue; + } + _ => {} + } + current.push(ch); + previous = ch; + } + parts.push(current); + parts + .into_iter() + .map(|part| part.trim().to_owned()) + .filter(|part| !part.is_empty()) + .collect() +} + +/// Index of the delimiter closing the one opened at `open` in `text`. +fn matching(text: &str, open: usize) -> usize { + let bytes = text.as_bytes(); + let (opening, closing) = match bytes[open] { + b'(' => (b'(', b')'), + b'{' => (b'{', b'}'), + other => panic!("not a delimiter: {}", other as char), + }; + let mut depth = 0_i32; + for (offset, byte) in bytes[open..].iter().enumerate() { + if *byte == opening { + depth += 1; + } else if *byte == closing { + depth -= 1; + if depth == 0 { + return open + offset; + } + } + } + panic!("unbalanced delimiter"); +} + +fn parse_handlers(source: &str) -> Vec { + let test_module = source.find("#[cfg(test)]").unwrap_or(source.len()); + let source = &source[..test_module]; + let mut handlers = Vec::new(); + let mut rest = source; + while let Some(at) = rest.find( + " +#[tauri::command", + ) { + rest = &rest[at + + " +#[tauri::command" + .len()..]; + let end_of_handler = rest + .find( + " +#[tauri::command", + ) + .unwrap_or(rest.len()); + let chunk = &rest[..end_of_handler]; + let fn_at = chunk.find("fn ").expect("a function follows the attribute"); + let is_async = chunk[..fn_at].trim_end().ends_with("async"); + let after_fn = &chunk[fn_at + 3..]; + let paren = after_fn.find('(').expect("parameter list"); + let name = after_fn[..paren].trim().to_owned(); + let close = matching(after_fn, paren); + let params = split_top_level(&after_fn[paren + 1..close]) + .into_iter() + .map(|param| { + let (n, t) = param.split_once(':').expect("typed parameter"); + (n.trim().to_owned(), t.trim().to_owned()) + }) + .collect(); + let brace = close + after_fn[close..].find('{').expect("body"); + handlers.push(Handler { + name, + is_async, + params, + body: after_fn[brace..].to_owned(), + }); + } + handlers +} + +fn all_handlers() -> Vec { + handler_sources() + .iter() + .flat_map(|(_, text)| parse_handlers(text)) + .collect() +} + +fn injected(param: &(String, String)) -> bool { + let ty = param.1.as_str(); + ty.starts_with("Webview") || ty.starts_with("Service<") || ty.starts_with("State<") +} + +#[test] +fn generate_handler_registers_exactly_the_eighteen_policy_commands() { + // Given the invoke handler in lib.rs. + let lib = read(&crate_dir().join("src/lib.rs")); + let start = + lib.find("generate_handler![").expect("generate_handler") + "generate_handler![".len(); + let end = start + lib[start..].find(']').expect("closing bracket"); + + // When the registered function names (last path segment) are collected. + let registered: Vec<&str> = lib[start..end] + .split(',') + .map(str::trim) + .filter(|entry| !entry.is_empty()) + .map(|entry| entry.rsplit("::").next().expect("segment")) + .collect(); + + // Then they are the 18 shared names, once each. + let unique: BTreeSet<&str> = registered.iter().copied().collect(); + assert_eq!(registered.len(), 18); + assert_eq!(unique.len(), 18); + let shared: BTreeSet<&str> = COMMAND_NAMES_SOURCE + .lines() + .filter_map(|line| line.trim().strip_prefix('"')) + .filter_map(|rest| rest.strip_suffix("\",")) + .collect(); + assert_eq!(unique, shared); + + // And every registered name is a handler in the commands sources. + let defined: BTreeSet = all_handlers().into_iter().map(|h| h.name).collect(); + let defined: BTreeSet<&str> = defined.iter().map(String::as_str).collect(); + assert_eq!(defined, shared); +} + +#[test] +fn every_handler_authorizes_its_own_command_before_touching_the_service() { + let handlers = all_handlers(); + assert_eq!(handlers.len(), 18); + for handler in handlers { + // Given the command the function name denotes. + let command = Command::ALL + .into_iter() + .find(|command| command.name() == handler.name) + .unwrap_or_else(|| panic!("{} is not a policy command", handler.name)); + assert!( + handler + .params + .first() + .is_some_and(|p| p.1.starts_with("Webview")), + "{} must take the calling Webview first", + handler.name + ); + + // When the body is searched for its policy call. + let call = format!("authorize(Command::{command:?}, webview.label())?;"); + let authorize_at = handler + .body + .find(&call) + .unwrap_or_else(|| panic!("{} lacks `{call}`", handler.name)); + assert_eq!( + handler.body.matches("authorize(").count(), + 1, + "{} calls authorize exactly once", + handler.name + ); + + // Then nothing but the opening brace precedes it, and any service use follows it. + assert!( + handler.body[1..authorize_at].trim().is_empty(), + "{}: authorize must be the first statement", + handler.name + ); + if handler + .params + .iter() + .any(|p| p.1.starts_with("Service<") || p.1.starts_with("State<")) + { + assert!( + handler.is_async, + "{} uses the service, so it is async", + handler.name + ); + let state_at = handler.body.find("&state").expect("state is used"); + assert!( + authorize_at < state_at, + "{}: state used before authorize", + handler.name + ); + assert!( + handler.body.contains("blocking(&state"), + "{} must run the service through the blocking helper", + handler.name + ); + assert!( + !handler.body.contains("state.inner()"), + "{} must not reach the service except through the helper", + handler.name + ); + } + } +} + +#[test] +fn the_blocking_helper_uses_the_blocking_pool_and_maps_failures() { + let commands = read(&crate_dir().join("src/commands.rs")); + assert!(commands.contains("tauri::async_runtime::spawn_blocking")); + assert!(commands.contains("CommandError::from")); + assert!(commands.contains("CommandError::internal()")); +} + +/// The keys of every argument object the frontend passes to each command. +fn frontend_arguments(source: &str) -> BTreeMap> { + let mut found = BTreeMap::new(); + let mut rest = source; + while let Some(at) = rest.find("invokeCommand<") { + rest = &rest[at + "invokeCommand<".len()..]; + let Some(open) = rest.find(">(\"") else { break }; + if rest[..open].contains([';', '\n']) { + continue; + } + let name_start = open + 3; + let Some(len) = rest[name_start..].find('"') else { + break; + }; + let name = rest[name_start..name_start + len].to_owned(); + let after_name = &rest[name_start + len + 1..]; + let brace = after_name.find('{').expect("argument object"); + assert!( + after_name[..brace].trim() == ",", + "{name}: argument object must follow the name directly" + ); + let close = matching(after_name, brace); + let keys = split_top_level(&after_name[brace + 1..close]) + .into_iter() + .map(|entry| { + entry + .split_once(':') + .map_or(entry.as_str(), |(key, _)| key) + .trim() + .to_owned() + }) + .collect(); + found.insert(name, keys); + } + found +} + +#[test] +fn handler_parameters_match_the_keys_the_frontend_passes() { + // Given the argument keys each frontend call passes. + let ui = crate_dir().join("ui/src/ipc"); + let mut expected = frontend_arguments(&read(&ui.join("client.ts"))); + expected.extend(frontend_arguments(&read(&ui.join("approvals_client.ts")))); + assert_eq!( + expected.len(), + 18, + "all commands are called by the frontend" + ); + + // Then each handler's non-injected parameters are exactly those keys. + for handler in all_handlers() { + let actual: BTreeSet = handler + .params + .iter() + .filter(|param| !injected(param)) + .map(|param| param.0.clone()) + .collect(); + let wanted = expected + .get(&handler.name) + .unwrap_or_else(|| panic!("{} is never called by the frontend", handler.name)); + assert_eq!(&actual, wanted, "{} parameters", handler.name); + } +} + +#[test] +fn every_handler_uses_snake_case_argument_matching() { + for (path, text) in handler_sources() { + let attributes = text + .matches( + " +#[tauri::command", + ) + .count(); + let renamed = text + .matches( + " +#[tauri::command(rename_all = \"snake_case\")]", + ) + .count(); + assert_eq!(attributes, renamed, "{}", path.display()); + } +} + +#[test] +fn command_error_keeps_the_service_code_and_message() { + // Given a real service failure: archiving a session that does not exist. + let root = std::env::temp_dir().join(format!( + "omgcode-desktop-layers-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()) + )); + let service = DesktopService::open(DesktopConfig { + data_root: root.clone(), + endpoint: "http://127.0.0.1:1234/v1".to_owned(), + }) + .expect("open service"); + let failure = service + .session_archive(SessionRequest { + session_id: uuid::Uuid::from_u128(7), + }) + .expect_err("no such session"); + + // When it is converted for the webview. + let converted = CommandError::from(failure.clone()); + + // Then the serialized forms are identical and the accessors agree. + assert_eq!(converted.code(), failure.code()); + assert_eq!(converted.message(), failure.message()); + assert_eq!( + serde_json::to_value(&converted).expect("command error"), + serde_json::to_value(&failure).expect("desktop error") + ); + drop(service); + let _ = fs::remove_dir_all(root); +} + +#[test] +fn internal_error_is_fixed_and_carries_no_detail() { + let value = serde_json::to_value(CommandError::internal()).expect("serialize"); + assert_eq!(value["code"], "internal"); + assert_eq!(value["message"], "The command could not be completed."); +} diff --git a/crates/omgcode-desktop/ui/.npmrc b/crates/omgcode-desktop/ui/.npmrc new file mode 100644 index 0000000..7c6e338 --- /dev/null +++ b/crates/omgcode-desktop/ui/.npmrc @@ -0,0 +1,2 @@ +ignore-scripts=true +save-exact=true diff --git a/crates/omgcode-desktop/ui/README.md b/crates/omgcode-desktop/ui/README.md new file mode 100644 index 0000000..91198a2 --- /dev/null +++ b/crates/omgcode-desktop/ui/README.md @@ -0,0 +1,72 @@ +# OMGCode desktop UI + +Webview frontend for the Tauri 2 desktop app. The Rust core is the only authority. +This code renders model- and repository-controlled text and must treat it as hostile. + +Vanilla strict TypeScript, Vite (multi-page), Vitest with jsdom, and Biome for both +formatting and linting. The only runtime dependency is `@tauri-apps/api`. Dependencies are +pinned exactly, `package-lock.json` is committed, and `.npmrc` sets `ignore-scripts=true`. + +## Scripts + +| Script | Purpose | +| ------------------- | ------------------------------------------------------------------------------------- | +| `npm run dev` | Vite dev server on port 1420 (strict port) | +| `npm run build` | `tsc --noEmit`, then `vite build` into `dist/` | +| `npm run check` | Strict type check | +| `npm run lint` | `biome check .` (lint, format check, import order) | +| `npm run format` | `biome format --write .` | +| `npm test` | Vitest. The `dist/` checks run only if `dist/` exists; otherwise they show as skipped | +| `npm run test:dist` | Build, then run `tests/dist.test.ts` | +| `npm run tauri` | Tauri CLI, run from `crates/omgcode-desktop` (`cd .. && tauri`) | + +## Running the desktop app + +Run this from `crates/omgcode-desktop/ui` (the script changes to the parent directory, +where `tauri.conf.json` lives, so it works in PowerShell, Git Bash, and Linux shells): + +``` +npm run tauri -- dev -- -- --data-dir +``` + +- **Always pass `--data-dir`.** Without it the app uses the real per-user data directory, + including your real sessions and approvals. Use a fresh directory for development. +- The first `--` ends `npm` options, the second ends the Tauri CLI options, and the rest go to + the app. `tauri dev` starts Vite on port 1420 through `beforeDevCommand` (`cwd: ui`) and + builds the Rust shell without the `custom-protocol` feature. +- `npm run tauri -- --version` and `npm run tauri -- info` also work from here. +- `ui/dist` must exist before any `cargo check`, `clippy`, `build`, or `test` that includes + the desktop crate, because the Tauri build embeds it. Run `npm run build` first. + +## Windows + +- `index.html` is the main window: session tree, search, transcript, composer. +- `approvals.html` is the approvals window. Only this entry imports + `src/ipc/approvals_client.ts`, so the main bundle never contains `approval_decide` or + `approval_detail`. It renders no transcript text. + +## Rules + +- Untrusted text is rendered only as text nodes through `src/dom.ts`. Bidirectional override + characters are replaced by visible `[U+XXXX]` markers. No `innerHTML`, `eval`, string timers, + computed dynamic imports, `window.open`, links, or web storage. A test scans `src/`. +- No inline script or style, and no remote resources. The build must run under + `default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; font-src 'self'; + connect-src ipc: http://ipc.localhost; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`. +- All IPC goes through `src/ipc/client.ts`, the only file that imports `@tauri-apps/api`. + Core error messages are shown as text. Client-side limits are usability only; the core + validates everything. +- The model endpoint is fixed when the desktop process starts. The composer shows the value + from `chat_defaults` as read-only text and sends back exactly that value. +- There is no push channel. Pollers (`src/poll.ts`) never overlap calls and pause while the + page is hidden. + +## Mock backend + +When `import.meta.env.DEV` is true and Tauri is absent, `client.ts` loads `src/mock/` with a +literal dynamic `import()`. Production builds drop that branch. The mock holds 12 sessions in +all five statuses, a 255-entry transcript, hostile strings (markup, ``, a right-to-left +override, a 5,000-character token, a `javascript:` URL), a chat turn that completes after 2 s +(model `fail` fails), and three approvals (two exact, one stale). `OMGCODE_MOCK_FIXTURE_MARKER` +must never appear in `dist/`; `tests/dist.test.ts` checks that. A production build with no +Tauri shows "This page must run inside OMGCode." diff --git a/crates/omgcode-desktop/ui/approvals.html b/crates/omgcode-desktop/ui/approvals.html new file mode 100644 index 0000000..8d967f8 --- /dev/null +++ b/crates/omgcode-desktop/ui/approvals.html @@ -0,0 +1,14 @@ + + + + + + + OMGCode approvals + + + +
+ + + diff --git a/crates/omgcode-desktop/ui/biome.json b/crates/omgcode-desktop/ui/biome.json new file mode 100644 index 0000000..f3d88e2 --- /dev/null +++ b/crates/omgcode-desktop/ui/biome.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://biomejs.dev/schemas/2.6.8/schema.json", + "files": { "includes": ["**", "!dist", "!node_modules"] }, + "formatter": { "enabled": true, "indentStyle": "space", "indentWidth": 2, "lineWidth": 100 }, + "linter": { + "enabled": true, + "rules": { + "preset": "recommended", + "suspicious": { "noExplicitAny": "error", "noDebugger": "error", "noConsole": "error" }, + "style": { "noNonNullAssertion": "error", "useImportType": "error" } + } + }, + "assist": { "actions": { "source": { "organizeImports": "on" } } } +} diff --git a/crates/omgcode-desktop/ui/index.html b/crates/omgcode-desktop/ui/index.html new file mode 100644 index 0000000..4e77511 --- /dev/null +++ b/crates/omgcode-desktop/ui/index.html @@ -0,0 +1,14 @@ + + + + + + + OMGCode + + + +
+ + + diff --git a/crates/omgcode-desktop/ui/package-lock.json b/crates/omgcode-desktop/ui/package-lock.json new file mode 100644 index 0000000..668ecee --- /dev/null +++ b/crates/omgcode-desktop/ui/package-lock.json @@ -0,0 +1,2399 @@ +{ + "name": "omgcode-desktop-ui", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "omgcode-desktop-ui", + "version": "0.0.0", + "license": "Apache-2.0", + "dependencies": { + "@tauri-apps/api": "2.12.5" + }, + "devDependencies": { + "@biomejs/biome": "2.6.8", + "@tauri-apps/cli": "2.12.5", + "jsdom": "31.0.1", + "typescript": "7.0.2", + "vite": "8.3.8", + "vitest": "5.1.0" + } + }, + "node_modules/@biomejs/biome": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.6.8.tgz", + "integrity": "sha512-kqZUFvX6/aYQOmzfRN5ANcfNS9wLH4aHLWWP/dQKyhRZVoA6rdWszA7DGugFcxPbMiznUyVYyukVl+ExZN4PQA==", + "dev": true, + "license": "MIT OR Apache-2.0", + "bin": { + "biome": "bin/biome" + }, + "engines": { + "node": ">=14.21.3" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/biome" + }, + "optionalDependencies": { + "@biomejs/cli-android-arm64": "2.6.8", + "@biomejs/cli-android-x64": "2.6.8", + "@biomejs/cli-darwin-arm64": "2.6.8", + "@biomejs/cli-darwin-x64": "2.6.8", + "@biomejs/cli-linux-arm64": "2.6.8", + "@biomejs/cli-linux-arm64-musl": "2.6.8", + "@biomejs/cli-linux-x64": "2.6.8", + "@biomejs/cli-linux-x64-musl": "2.6.8", + "@biomejs/cli-win32-arm64": "2.6.8", + "@biomejs/cli-win32-x64": "2.6.8" + } + }, + "node_modules/@biomejs/cli-android-arm64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-android-arm64/-/cli-android-arm64-2.6.8.tgz", + "integrity": "sha512-X4JKPLK85kfUTwuuaORFplnBfGjKkp62PsFhhcL7F/Tpltc7pyUofjlkkMnlZZLWsifFl7LNB8ngVrwJg1uo1Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-android-x64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-android-x64/-/cli-android-x64-2.6.8.tgz", + "integrity": "sha512-C3Hk485vl+deEj53K08+SYYelPIPkdSZL3qHuD31Xi+qydVa4q2ze+aCYo1k3iJGWtvWtjHaGkDh7S2sX6wk8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-darwin-arm64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.6.8.tgz", + "integrity": "sha512-DHyj+JnRHcn4YdvpiqgTFZMYKSPELMCfFpNNlEuu1L8DKTGXhzW7raIwdsbo2Ie9nCljQLAQkVWQk/mwM0ueiA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-darwin-x64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.6.8.tgz", + "integrity": "sha512-QWWUPjlA0RnkkgYnFLUHZu+RrDc0FdK0A+wEPA+dENQJwsuSHMH89lspnAw2QUWWc9VHyfluGx1Xmp6Y2GZi8Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.6.8.tgz", + "integrity": "sha512-0Bjim8lKwnrvXUHoI4k3Tb51BjoiLEwDnovCI8nSzkk6wj3dShiuAjrx6+X0Hjf4ejR1sRZgTQiSDHlpy9vB7w==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64-musl": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.6.8.tgz", + "integrity": "sha512-WB9PhOitX+bRc0G3+GNJGlvbKoWn3JoB9z4E04JQizIC9aPCQyIvwvWG7QZHxw6k20Fi+dHLmZ2fSEmBa9HqiA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.6.8.tgz", + "integrity": "sha512-XIk3pLQT56I6Tti+u0DF8FtSNXjCMTPbxVTzfJ9cS2t1ImVKvrqV5b52GuEaJg6/wuiXvz0sjfb5saB4TPRjzA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64-musl": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.6.8.tgz", + "integrity": "sha512-64Yzo+J4fEk7Kf9SMnVdVxC+Y2A2e/L86QTP9JjGQ57lsddyELLpbBcNMxSJggre2T1AvISwwSrOApkBAHDqNA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-arm64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.6.8.tgz", + "integrity": "sha512-ezjCEZzHIWE2pdh83a7zLVcAAcDaERcTcvfA7uWlxqz/1CuDxgtfO19pDg9B6YY4wKYIDvYBw2QCMnqIshSwmw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-x64": { + "version": "2.6.8", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.6.8.tgz", + "integrity": "sha512-cD6HvGczZUiAYsY8s2TxxXj2AHFzEdMomvVJfEjzOjBM45nGqIDfBpbtvwGQzDCN8X2yKKk9u1jnDZisT2nxIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@exodus/bytes": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz", + "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tauri-apps/api": { + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.12.5.tgz", + "integrity": "sha512-G9QIMt5fzED+aS4QhVK3w1HWLKpLIwH/MnpCr9z1ugGEHnS2ORmqrLkc0uALOjRK4qXJy+4Yiw8LDl/KicC1Hg==", + "license": "Apache-2.0 OR MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/tauri" + } + }, + "node_modules/@tauri-apps/cli": { + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.12.5.tgz", + "integrity": "sha512-Dm8s/4aiE52HsBh+Gz3uSrh+fEykRICA1VoAnQA80IqHoTRncPg+q4rGvuhmyNsHUPg3QrPjUrTUSfWmXLVVEw==", + "dev": true, + "license": "Apache-2.0 OR MIT", + "bin": { + "tauri": "tauri.js" + }, + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/tauri" + }, + "optionalDependencies": { + "@tauri-apps/cli-darwin-arm64": "2.12.5", + "@tauri-apps/cli-darwin-x64": "2.12.5", + "@tauri-apps/cli-linux-arm-gnueabihf": "2.12.5", + "@tauri-apps/cli-linux-arm64-gnu": "2.12.5", + "@tauri-apps/cli-linux-arm64-musl": "2.12.5", + "@tauri-apps/cli-linux-riscv64-gnu": "2.12.5", + "@tauri-apps/cli-linux-x64-gnu": "2.12.5", + "@tauri-apps/cli-linux-x64-musl": "2.12.5", + "@tauri-apps/cli-win32-arm64-msvc": "2.12.5", + "@tauri-apps/cli-win32-ia32-msvc": "2.12.5", + "@tauri-apps/cli-win32-x64-msvc": "2.12.5" + } + }, + "node_modules/@tauri-apps/cli-darwin-arm64": { + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.5.tgz", + "integrity": "sha512-VVvBRBdTFF7BP7RqGeItp9yDiyXj0DI1laRCEN2q6GLrNkw4wrHeWAxHp23PwtQtn/XET+yTN1jOKrq+Yor5PQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-darwin-x64": { + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.5.tgz", + "integrity": "sha512-A84QYNj93kaG06N2mIFBRZM/X3lf9TyAVQeQwOmP2AJZ2wCt1WLDJgHRCvjeJmwJjJ5Ud0jUbIKbXg8NEGvsVQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-arm-gnueabihf": { + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.5.tgz", + "integrity": "sha512-tb/5xG5HV6CJR9AZBmTyI2GCi05vcH8XUjUIjBquAx7x+AE4f1vMWngvq7JW2AqYK8nNl79LJH1GR9Hf5QQc5g==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-arm64-gnu": { + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.5.tgz", + "integrity": "sha512-Vb7SlbIWlmIqekfsGYT64wH1cQNg5MET8XFyT6pUlVJ7Y/z6LsOIh4MUal0Z5FCPL83GMuEUNxpYUHpt36teHQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-arm64-musl": { + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.5.tgz", + "integrity": "sha512-b/YfVGueoTOtENQHY1STBF9XlU4uZDtOiMUErp2Nao/YrDWCKggjxxBZU3ycbeDWUYxl8U8M9seE4HYag1xjiQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-riscv64-gnu": { + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.5.tgz", + "integrity": "sha512-/EXbTfE9FM9GKSSRL9YTRHcMglTVNzbcwegXM0MBR3ozVgoE+pFq46Ej/InJBs1l+sjSpu6jyi38MZ+xyU/3NQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-x64-gnu": { + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.5.tgz", + "integrity": "sha512-OIun574QsULxaZ5SmPDX4D8bO95RBmYJshu8yGFy0RSyCMKEs/y+o3BThot4fbCv4ttC1Tq6Hzt0QRHXCIgp7w==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-x64-musl": { + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.5.tgz", + "integrity": "sha512-GDzWcb/6OzJrHnVGQ/n3XndLan67bZ7cu4zJN9+zFmV10nBgKz5jDDm8sRQO4sGb7bu6Ztiy+Al2XY2ptRY0RQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-win32-arm64-msvc": { + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.5.tgz", + "integrity": "sha512-61KCX5vo0vex7P/P7sbXdfFhHqs+rFaG+UXK/UBwz/VlLveDx6vgpHkF+rfUIfCqj0VvLArpxR3+rQIzRwxKgw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-win32-ia32-msvc": { + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.5.tgz", + "integrity": "sha512-mGujjR/MlXwJiQcue4wlXrBYlIEdDCoap0g+GNPlLCb75ilSbWMC8qTsXVuGcLIMumIJvc2v+veDnCHnels/Zg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-win32-x64-msvc": { + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.5.tgz", + "integrity": "sha512-o1+EOjvi/nFwKx5XamCXSr+GUr2ko8TH7+0wnWuZjE+lZwE+/VWCbE49HPHa3/V59M3bJ0dlK1yhogGQ15OVPg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.5", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", + "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@vitest/mocker": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.0.tgz", + "integrity": "sha512-5umB9/jlWcqVS6fsrFmv5Gdnpu6wAUio/lEOwAmvB7v+lFo/IW2B9FhAD0p19GCULTgMzLCdUmuCDCnAzWgppQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.1.0", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.0.tgz", + "integrity": "sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/bcp-47": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/bcp-47/-/bcp-47-2.1.2.tgz", + "integrity": "sha512-wsv86UuNFuPnVieKLyECTT+CP1WSAHeoIg5P3xu2kA9Z+7fVPoKt7dxzSeEhtJel0AI+NW3fIW3KtTKQKUCngg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-alphabetical": "^2.0.0", + "is-alphanumerical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/bcp-47-match": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-2.0.3.tgz", + "integrity": "sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/data-urls": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz", + "integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.1.2" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/entities": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", + "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz", + "integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.15.1" + }, + "engines": { + "node": "^22.13.0 || >=24.0.0" + } + }, + "node_modules/is-alphabetical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz", + "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-alphanumerical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz", + "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-alphabetical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-decimal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz", + "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "31.0.1", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-31.0.1.tgz", + "integrity": "sha512-CbhJL8ZQg3eKswxSZth4QO9tW0jPIhmR0vtSXQSbKSfWbwIT6hoRc17wdHIVTQ43KI0mdV5iTJr3281IDgVZ5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "bcp-47": "^2.1.2", + "bcp-47-match": "^2.0.3", + "data-urls": "^8.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^7.0.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3", + "parse5": "^8.1.0", + "parse5-parser-stream": "^8.1.0", + "saxes": "^6.0.0", + "tough-cookie": "^6.0.2", + "undici": "^8.12.3", + "w3c-xmlserializer": "^6.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.3.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "@napi-rs/canvas": "^1.0.13" + }, + "peerDependenciesMeta": { + "@napi-rs/canvas": { + "optional": true + } + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/parse5": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz", + "integrity": "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^9.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-parser-stream": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-8.1.1.tgz", + "integrity": "sha512-hMcVbbUJcQmP8rURWUdYrT1flRiBiBVjq/RYGguJpDUgIXSqdYKlE0CxthmdMWoSlBAuL5bUBa73g0pttSy7Hw==", + "dev": true, + "license": "MIT", + "dependencies": { + "parse5": "^8.1.1" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/rolldown": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" + } + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", + "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tldts": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.5.4.tgz", + "integrity": "sha512-Rn2ABgjHZrA+jzqom5zhxA0hLohzYrIgfCPyhpTUxqsUrcsBYuab49LseR9waB9Jr8/MxdodvMHA91oRiGLO3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.5.4" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.5.4.tgz", + "integrity": "sha512-9+4zWtKEDZ3V3FoZ1B97rv+5z5oqp7yeXGVze3CxgQ+CJro9do9DCPD00wxstYZDXDMXsurkBerFfiB6GYtPbA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.1.0.tgz", + "integrity": "sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz", + "integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici": { + "version": "8.12.4", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.12.4.tgz", + "integrity": "sha512-8Mx+uNKKER2bA4AdtedkqRbwUCIJFr2nJckXRe5yrDqzePqwLP7VNcctN8/XdmDSbF7mS+jJKIszlL+vbam1VA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/vite": { + "version": "8.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.0.tgz", + "integrity": "sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.1.0", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.1.0", + "@vitest/browser-preview": "5.1.0", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.1.0", + "@vitest/coverage-v8": "5.1.0", + "@vitest/ui": "5.1.0", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/w3c-xmlserializer": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz", + "integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-mimetype": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-url": { + "version": "17.3.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.3.0.tgz", + "integrity": "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "tr46": "^7.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/crates/omgcode-desktop/ui/package.json b/crates/omgcode-desktop/ui/package.json new file mode 100644 index 0000000..8f95141 --- /dev/null +++ b/crates/omgcode-desktop/ui/package.json @@ -0,0 +1,29 @@ +{ + "name": "omgcode-desktop-ui", + "version": "0.0.0", + "private": true, + "type": "module", + "license": "Apache-2.0", + "description": "Webview frontend for the OMGCode desktop app. It renders untrusted content as text only.", + "scripts": { + "dev": "vite", + "build": "tsc --noEmit && vite build", + "check": "tsc --noEmit", + "lint": "biome check .", + "format": "biome format --write .", + "test": "vitest run", + "test:dist": "npm run build && vitest run tests/dist.test.ts", + "tauri": "cd .. && tauri" + }, + "dependencies": { + "@tauri-apps/api": "2.12.5" + }, + "devDependencies": { + "@biomejs/biome": "2.6.8", + "@tauri-apps/cli": "2.12.5", + "jsdom": "31.0.1", + "typescript": "7.0.2", + "vite": "8.3.8", + "vitest": "5.1.0" + } +} diff --git a/crates/omgcode-desktop/ui/src/approvals.ts b/crates/omgcode-desktop/ui/src/approvals.ts new file mode 100644 index 0000000..d190749 --- /dev/null +++ b/crates/omgcode-desktop/ui/src/approvals.ts @@ -0,0 +1,12 @@ +import { startApprovals } from "./approvals/app"; +import { el, replaceChildren } from "./dom"; +import { hostAvailable, NO_HOST_MESSAGE } from "./ipc/client"; + +const root = document.getElementById("app"); +if (root !== null) { + if (hostAvailable()) { + startApprovals(root); + } else { + replaceChildren(root, el("p", { class: "no-host", text: NO_HOST_MESSAGE })); + } +} diff --git a/crates/omgcode-desktop/ui/src/approvals/app.ts b/crates/omgcode-desktop/ui/src/approvals/app.ts new file mode 100644 index 0000000..eb2d8a9 --- /dev/null +++ b/crates/omgcode-desktop/ui/src/approvals/app.ts @@ -0,0 +1,263 @@ +import { el, replaceChildren } from "../dom"; +import { formatCountdown, formatUnix } from "../format"; +import { approvalsApi } from "../ipc/approvals_client"; +import { toIpcError } from "../ipc/errors"; +import type { ApprovalList, ApprovalView } from "../ipc/types"; +import { createPoller } from "../poll"; +import { operationLabel, orderApprovals, remainingSeconds } from "./model"; +import { createReviewPanel } from "./review"; + +export const LIST_POLL_MS = 3000; +const COUNTDOWN_MS = 1000; + +export interface ApprovalsApp { + dispose(): void; +} + +interface RowRef { + li: HTMLElement; + /** Everything the row displays; a row is rebuilt only when this changes. */ + signature: string; + /** Pending rows only. */ + expires: number | null; + countdown: HTMLElement | null; + button: HTMLButtonElement | null; +} + +function signatureOf(approval: ApprovalView): string { + return JSON.stringify([ + approval.state, + approval.summary, + approval.expires_unix, + approval.created_unix, + approval.session_title, + approval.folder_display, + approval.operation, + approval.writers_stopped, + ]); +} + +/** Makes `parent` hold exactly `wanted`, in order, moving only nodes that are out of place. */ +function reconcile(parent: HTMLElement, wanted: readonly HTMLElement[]): void { + let cursor = parent.firstChild; + for (const node of wanted) { + if (node === cursor) { + cursor = cursor.nextSibling; + } else { + parent.insertBefore(node, cursor); + } + } + while (cursor !== null) { + const next = cursor.nextSibling; + parent.removeChild(cursor); + cursor = next; + } +} + +/** + * Builds the approvals window. It never renders transcript text: it shows only the + * fields the core returns for each approval. + */ +export function startApprovals(root: HTMLElement): ApprovalsApp { + let received: ApprovalList = { now_unix: 0, approvals: [] }; + let receivedAtMs = performance.now(); + let selectedId: string | null = null; + let rows = new Map(); + let focusedOnce = false; + let decidedId: string | null = null; + + const emptyNote = el("p", { class: "empty", text: "No approvals are pending." }); + const pendingList = el("ul", { class: "approvals-ul" }); + const decidedHeading = el("h2", { text: "Recently decided" }); + const decidedList = el("ul", { class: "approvals-ul" }); + const listBox = el( + "div", + { class: "approval-list", attrs: { tabindex: "-1" } }, + emptyNote, + pendingList, + decidedHeading, + decidedList, + ); + const errorLine = el("p", { class: "error", attrs: { role: "status" } }); + errorLine.hidden = true; + const review = createReviewPanel({ + reload: (id, notice) => loadDetail(id, notice), + onDecided: (view) => { + decidedId = view.id; + void poller.tick(); + }, + }); + + replaceChildren( + root, + el( + "main", + { class: "approvals" }, + el("h1", { text: "Tool approvals" }), + el("p", { + class: "intro", + text: "Approving lets the model's next identical request run once. Nothing runs when you approve.", + }), + errorLine, + listBox, + review.element, + ), + ); + + function elapsedMs(): number { + return performance.now() - receivedAtMs; + } + + function updateCountdowns(): void { + for (const row of rows.values()) { + if (row.expires === null || row.countdown === null) { + continue; + } + const left = remainingSeconds(row.expires, received.now_unix, elapsedMs()); + const label = left === 0 ? "expired" : `expires in ${formatCountdown(left)}`; + if (row.countdown.textContent !== label) { + replaceChildren(row.countdown, label); + } + row.li.classList.toggle("expired", left === 0); + } + } + + function syncSelection(): void { + for (const [id, row] of rows) { + row.button?.setAttribute("aria-pressed", String(id === selectedId)); + } + } + + function approvalRow(approval: ApprovalView, pending: boolean): RowRef { + const signature = signatureOf(approval); + const who = [approval.session_title, approval.folder_display] + .filter((part): part is string => part !== null) + .join(" · "); + const body = [ + el("span", { class: "op", text: operationLabel(approval.operation) }), + el("span", { class: "who clamp-1", text: who === "" ? "Unknown session" : who }), + el("span", { class: "summary clamp-3", text: approval.summary }), + el("span", { class: "when", text: `Created ${formatUnix(approval.created_unix)}` }), + ]; + if (!pending) { + const li = el( + "li", + { class: "approval decided" }, + ...body, + el("span", { class: "state", text: approval.state }), + ); + return { li, signature, expires: null, countdown: null, button: null }; + } + const countdown = el("span", { class: "countdown" }); + const select = el("button", { class: "approval-button" }, ...body, countdown); + select.type = "button"; + select.setAttribute("aria-pressed", String(approval.id === selectedId)); + select.dataset.approvalId = approval.id; + select.addEventListener("click", () => { + selectedId = approval.id; + void loadDetail(approval.id); + syncSelection(); + }); + return { + li: el("li", { class: "approval pending" }, select), + signature, + expires: approval.expires_unix, + countdown, + button: select, + }; + } + + function draw(): void { + const activeId = + document.activeElement instanceof HTMLElement + ? document.activeElement.dataset.approvalId + : undefined; + const { pending, decided } = orderApprovals(received.approvals); + const next = new Map(); + const rowsFor = (list: ApprovalView[], isPending: boolean): HTMLElement[] => + list.map((approval) => { + const old = rows.get(approval.id); + const row = + old !== undefined && old.signature === signatureOf(approval) + ? old + : approvalRow(approval, isPending); + next.set(approval.id, row); + return row.li; + }); + const pendingNodes = rowsFor(pending, true); + const decidedNodes = rowsFor(decided, false); + rows = next; + reconcile(pendingList, pendingNodes); + reconcile(decidedList, decidedNodes); + emptyNote.hidden = pending.length > 0; + pendingList.hidden = pending.length === 0; + decidedHeading.hidden = decided.length === 0; + decidedList.hidden = decided.length === 0; + updateCountdowns(); + if (activeId !== undefined) { + const focused = rows.get(activeId)?.button; + if (focused !== null && focused !== undefined && document.activeElement !== focused) { + focused.focus(); + } + } + if (!focusedOnce) { + focusedOnce = true; + (listBox.querySelector(".approval-button") ?? listBox).focus(); + } + } + + async function loadDetail(id: string, notice?: string): Promise { + try { + const detail = await approvalsApi.detail(id); + if (selectedId === id) { + review.show(detail, notice); + } + } catch (reason) { + if (selectedId === id) { + const error = toIpcError(reason); + review.clear(); + showError(`${error.message} (${error.code})`); + } + } + } + + function showError(message: string | null): void { + replaceChildren(errorLine, message ?? ""); + errorLine.hidden = message === null; + } + + async function refresh(): Promise { + try { + received = await approvalsApi.list(); + receivedAtMs = performance.now(); + showError(null); + } catch (reason) { + const error = toIpcError(reason); + showError(`${error.message} (${error.code})`); + return; + } + draw(); + const selected = received.approvals.find((a) => a.id === selectedId); + if ( + selectedId !== null && + (selected === undefined || selected.state !== "pending") && + selectedId !== decidedId + ) { + selectedId = null; + review.clear(); + } + } + + const poller = createPoller(refresh, LIST_POLL_MS); + const countdownTimer = setInterval(updateCountdowns, COUNTDOWN_MS); + void poller.tick(); + poller.start(); + + return { + dispose() { + poller.stop(); + clearInterval(countdownTimer); + review.dispose(); + }, + }; +} diff --git a/crates/omgcode-desktop/ui/src/approvals/model.ts b/crates/omgcode-desktop/ui/src/approvals/model.ts new file mode 100644 index 0000000..f0b6e64 --- /dev/null +++ b/crates/omgcode-desktop/ui/src/approvals/model.ts @@ -0,0 +1,107 @@ +import type { ApprovalDetail, ApprovalOperation, ApprovalView } from "../ipc/types"; + +export const REVIEW_DELAY_MS = 1000; +export const WRITERS_STOPPED_TEXT = + "I have stopped every other program that could write to this file. OMGCode cannot detect a concurrent writer."; + +const OPERATION_LABELS: Record = { + command: "Command", + file_write: "File edit", + git_push: "Git push", + network: "Network", +}; + +export function operationLabel(operation: ApprovalOperation): string { + return OPERATION_LABELS[operation]; +} + +/** Pending approvals first (soonest expiry first), then decided ones (newest first). */ +export function orderApprovals(approvals: readonly ApprovalView[]): { + pending: ApprovalView[]; + decided: ApprovalView[]; +} { + const pending = approvals + .filter((a) => a.state === "pending") + .sort((a, b) => a.expires_unix - b.expires_unix); + const decided = approvals + .filter((a) => a.state !== "pending") + .sort((a, b) => b.created_unix - a.created_unix); + return { pending, decided }; +} + +/** + * Seconds left before `expiresUnix`. The base is the core's clock (`listNowUnix`), advanced + * by `elapsedMs` of monotonic time since the list arrived. The local wall clock is not used. + */ +export function remainingSeconds( + expiresUnix: number, + listNowUnix: number, + elapsedMs: number, +): number { + return Math.max(0, expiresUnix - (listNowUnix + Math.floor(elapsedMs / 1000))); +} + +export interface ReviewInput { + /** The "writers stopped" checkbox. */ + writersStopped: boolean; + /** True once the review delay has passed. */ + armed: boolean; + /** True while a decision is being sent. */ + busy: boolean; +} + +export interface Gate { + enabled: boolean; + /** Why Approve is disabled, shown as text. */ + reason: string | null; +} + +/** Decides whether Approve may be used for the shown detail. */ +export function approveGate(detail: ApprovalDetail, input: ReviewInput): Gate { + if (detail.approval.state !== "pending") { + return { enabled: false, reason: "This approval is no longer pending." }; + } + if (detail.binding !== "exact") { + return { enabled: false, reason: "The recorded request cannot be approved." }; + } + if (detail.review_token === null) { + return { enabled: false, reason: "No review token was issued. Reload the review." }; + } + if (detail.approval.operation === "file_write" && !input.writersStopped) { + return { enabled: false, reason: "Confirm that other writers are stopped." }; + } + if (!input.armed) { + return { enabled: false, reason: "Approve unlocks after a short review delay." }; + } + if (input.busy) { + return { enabled: false, reason: null }; + } + return { enabled: true, reason: null }; +} + +export interface DecisionArgs { + decision: "approve" | "deny"; + writersStopped: boolean; + reviewToken: string | null; +} + +/** Arguments for `approval_decide`. Deny never carries a token or an acknowledgement. */ +export function decisionArgs( + decision: "approve" | "deny", + detail: ApprovalDetail, + input: ReviewInput, +): DecisionArgs { + if (decision === "deny") { + return { decision, writersStopped: false, reviewToken: null }; + } + return { + decision, + writersStopped: detail.approval.operation === "file_write" && input.writersStopped, + reviewToken: detail.review_token, + }; +} + +export const REVIEW_AGAIN_CODES: ReadonlySet = new Set([ + "review_expired", + "review_mismatch", +]); diff --git a/crates/omgcode-desktop/ui/src/approvals/review.ts b/crates/omgcode-desktop/ui/src/approvals/review.ts new file mode 100644 index 0000000..f4fa188 --- /dev/null +++ b/crates/omgcode-desktop/ui/src/approvals/review.ts @@ -0,0 +1,177 @@ +import { append, el, replaceChildren } from "../dom"; +import { approvalsApi } from "../ipc/approvals_client"; +import { toIpcError } from "../ipc/errors"; +import type { ApprovalDetail, ApprovalView } from "../ipc/types"; +import { + approveGate, + decisionArgs, + REVIEW_AGAIN_CODES, + REVIEW_DELAY_MS, + type ReviewInput, + WRITERS_STOPPED_TEXT, +} from "./model"; + +export interface ReviewPanel { + element: HTMLElement; + /** Shows the detail and restarts the approve delay. `notice` is shown as an error line. */ + show(detail: ApprovalDetail, notice?: string): void; + clear(): void; + dispose(): void; +} + +export interface ReviewHandlers { + /** Reloads the detail for an id and shows `notice` with it. */ + reload(id: string, notice: string): Promise; + /** Called after a decision so the list can refresh. */ + onDecided(view: ApprovalView): void; +} + +function explanation(detail: ApprovalDetail): string | null { + if (detail.binding === "stale") { + return detail.approval.operation === "file_write" + ? "The request no longer matches what was recorded: the file changed since the request. Approving would have no effect." + : "The request no longer matches what was recorded. Approving would have no effect."; + } + if (detail.binding === "not_found") { + return "The recorded request could not be found. Approving would have no effect."; + } + return null; +} + +/** Builds the review panel. It renders approval fields as text and gates Approve. */ +export function createReviewPanel(handlers: ReviewHandlers): ReviewPanel { + const element = el("section", { class: "review", attrs: { "aria-label": "Review" } }); + element.hidden = true; + let timer: ReturnType | null = null; + + function cancelTimer(): void { + if (timer !== null) { + clearTimeout(timer); + timer = null; + } + } + + function show(detail: ApprovalDetail, notice?: string): void { + cancelTimer(); + const input: ReviewInput = { writersStopped: false, armed: false, busy: false }; + const isFile = detail.approval.operation === "file_write"; + const pending = detail.approval.state === "pending"; + const exact = detail.binding === "exact"; + + const result = el("p", { class: "result", attrs: { role: "status" } }); + if (notice !== undefined) { + replaceChildren(result, notice); + result.classList.add("error"); + } + const hint = el("p", { class: "muted" }); + const approve = el("button", { class: "primary", text: "Approve" }); + approve.type = "button"; + const deny = el("button", { class: "danger", text: "Deny" }); + deny.type = "button"; + const checkbox = el("input", { attrs: { type: "checkbox", id: "writers-stopped" } }); + const checkLabel = el( + "label", + { class: "field-check", attrs: { for: "writers-stopped" } }, + checkbox, + el("span", { text: WRITERS_STOPPED_TEXT }), + ); + + function sync(): void { + const gate = approveGate(detail, input); + approve.disabled = !gate.enabled; + deny.disabled = input.busy; + replaceChildren(hint, gate.reason ?? ""); + hint.hidden = gate.reason === null || !exact; + } + + async function decide(decision: "approve" | "deny"): Promise { + const args = decisionArgs(decision, detail, input); + input.busy = true; + sync(); + try { + const view = await approvalsApi.decide( + detail.approval.id, + args.decision, + args.writersStopped, + args.reviewToken, + ); + cancelTimer(); + replaceChildren(result, `Decision recorded: ${view.state}.`); + result.classList.remove("error"); + approve.disabled = true; + deny.disabled = true; + checkbox.disabled = true; + handlers.onDecided(view); + } catch (reason) { + const error = toIpcError(reason); + input.busy = false; + if (REVIEW_AGAIN_CODES.has(error.code)) { + await handlers.reload( + detail.approval.id, + "The review expired or the request changed. Review it again.", + ); + return; + } + replaceChildren(result, `${error.message} (${error.code})`); + result.classList.add("error"); + sync(); + } + } + + approve.addEventListener("click", () => void decide("approve")); + deny.addEventListener("click", () => void decide("deny")); + checkbox.addEventListener("change", () => { + input.writersStopped = checkbox.checked; + sync(); + }); + + const fields = el("dl", { class: "fields" }); + for (const field of detail.fields) { + append( + fields, + el("dt", { text: field.label }), + el("dd", {}, field.multiline ? el("pre", { text: field.value }) : field.value), + ); + } + const explain = explanation(detail); + replaceChildren( + element, + el("h2", { text: "Review" }), + explain === null ? null : el("p", { class: "banner", text: explain }), + exact && detail.tool !== null + ? el("p", { class: "tool", text: `Tool: ${detail.tool}` }) + : null, + exact ? fields : null, + exact + ? el( + "p", + { class: "hash" }, + "Request SHA-256: ", + el("code", { text: detail.approval.request_sha256 }), + ) + : null, + pending && isFile && exact ? checkLabel : null, + el("div", { class: "decision" }, ...(pending ? [deny, exact ? approve : null] : [])), + hint, + result, + ); + element.hidden = false; + sync(); + timer = setTimeout(() => { + timer = null; + input.armed = true; + sync(); + }, REVIEW_DELAY_MS); + } + + return { + element, + show, + clear() { + cancelTimer(); + element.hidden = true; + element.replaceChildren(); + }, + dispose: cancelTimer, + }; +} diff --git a/crates/omgcode-desktop/ui/src/dom.ts b/crates/omgcode-desktop/ui/src/dom.ts new file mode 100644 index 0000000..bb7475f --- /dev/null +++ b/crates/omgcode-desktop/ui/src/dom.ts @@ -0,0 +1,84 @@ +/** + * Minimal typed DOM builder. Text always goes through text nodes, so untrusted strings + * can never become markup. Attributes that can execute or navigate are refused. + */ + +export type Child = Node | string | null | undefined | false; + +export interface ElOptions { + class?: string; + text?: string; + attrs?: Readonly>; +} + +const BIDI_CONTROLS = /[‪-‮⁦-⁩]/g; + +/** Makes bidirectional override characters visible so they cannot reorder displayed text. */ +export function neutralise(value: string): string { + return value.replace(BIDI_CONTROLS, (c) => { + const hex = c.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0"); + return `[U+${hex}]`; + }); +} + +function attributeAllowed(name: string): boolean { + const lower = name.toLowerCase(); + const refused = lower === "style" || lower === "href" || lower === "src" || lower === "srcdoc"; + return !(refused || lower.startsWith("on")); +} + +/** Creates a text node for untrusted text. */ +export function text(value: string): Text { + return document.createTextNode(neutralise(value)); +} + +/** Appends children; strings become text nodes. */ +export function append(parent: Node, ...children: Child[]): void { + for (const child of children) { + if (child === null || child === undefined || child === false) { + continue; + } + parent.appendChild(typeof child === "string" ? text(child) : child); + } +} + +/** Replaces all children of `parent`. */ +export function replaceChildren(parent: Element, ...children: Child[]): void { + parent.replaceChildren(); + append(parent, ...children); +} + +/** Creates an element. Strings in `children` become text nodes. */ +export function el( + tag: K, + options: ElOptions = {}, + ...children: Child[] +): HTMLElementTagNameMap[K] { + const node = document.createElement(tag); + if (options.class !== undefined) { + node.className = options.class; + } + if (options.text !== undefined) { + node.textContent = neutralise(options.text); + } + for (const [name, value] of Object.entries(options.attrs ?? {})) { + if (!attributeAllowed(name)) { + throw new Error(`Attribute ${name} is not allowed.`); + } + node.setAttribute(name, value); + } + append(node, ...children); + return node; +} + +/** Creates a `