diff --git a/.github/workflows/build-windows-installer.yml b/.github/workflows/build-windows-installer.yml new file mode 100644 index 00000000..8373e4a2 --- /dev/null +++ b/.github/workflows/build-windows-installer.yml @@ -0,0 +1,88 @@ +name: Build Windows installer + +on: + workflow_dispatch: + inputs: + release_tag: + description: Existing desktop-v* release to verify after manual asset upload + required: false + type: string + pull_request: + paths: + - .github/workflows/build-windows-installer.yml + - app/** + - src/** + - scripts/** + - package.json + - package-lock.json + push: + tags: + - 'desktop-v*' + release: + types: [published] + +permissions: + contents: read + +jobs: + nsis: + if: ${{ github.event_name != 'release' && !(github.event_name == 'workflow_dispatch' && inputs.release_tag != '') }} + runs-on: windows-latest + steps: + - uses: actions/checkout@v6 + + - uses: actions/setup-node@v6 + with: + node-version: 22.13.0 + cache: npm + cache-dependency-path: | + package-lock.json + app/package-lock.json + + - name: Install CLI dependencies + run: npm ci + + - name: Install desktop dependencies + run: npm ci --prefix app + + - name: Test installer verifier + run: npm --prefix app test -- scripts/verify-windows-installer.test.ts + + - name: Build NSIS installer + run: npm --prefix app run package:win + + - name: Verify installer manifest + shell: pwsh + run: | + if ($env:GITHUB_REF_TYPE -eq 'tag') { + node app/scripts/verify-windows-installer.mjs --tag $env:GITHUB_REF_NAME + } else { + node app/scripts/verify-windows-installer.mjs + } + + - name: Upload installer artifact + uses: actions/upload-artifact@v6 + with: + name: CodeBurn-Windows-Installer + path: | + app/release/CodeBurn-Setup-*.exe + app/release/CodeBurn-Setup-*.exe.blockmap + if-no-files-found: error + retention-days: 30 + + verify-release-assets: + if: ${{ (github.event_name == 'release' && startsWith(github.event.release.tag_name, 'desktop-v')) || (github.event_name == 'workflow_dispatch' && inputs.release_tag != '') }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - name: Verify live desktop release assets + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ github.event.release.tag_name || inputs.release_tag }} + run: | + gh api "repos/${{ github.repository }}/releases/tags/$RELEASE_TAG" \ + --jq '[.assets[].name]' > "$RUNNER_TEMP/release-assets.json" + node app/scripts/verify-windows-installer.mjs \ + --tag "$RELEASE_TAG" \ + --release-assets "$RUNNER_TEMP/release-assets.json" diff --git a/.github/workflows/mac-menubar-ci.yml b/.github/workflows/mac-menubar-ci.yml new file mode 100644 index 00000000..f7d9cc1c --- /dev/null +++ b/.github/workflows/mac-menubar-ci.yml @@ -0,0 +1,34 @@ +name: macOS Menubar CI + +# The macOS menubar (mac/) ships from release-menubar.yml, which only packages the app. +# Its Swift test suite (170+ tests covering the credential stores, Keychain cache, +# serve connection, quota parsing) gated nothing until this workflow. Runs on every +# PR touching mac/** so a red test fails the PR, the same way tests.yml does for the CLI. +on: + push: + branches: [main] + paths: + - .github/workflows/mac-menubar-ci.yml + - mac/** + pull_request: + paths: + - .github/workflows/mac-menubar-ci.yml + - mac/** + +permissions: + contents: read + +jobs: + test: + runs-on: macos-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v6 + - name: Swift toolchain + run: swift --version + - name: Build + run: swift build --package-path mac + - name: Test + run: swift test --package-path mac + - name: Package (same script the release uses) + run: mac/Scripts/package-app.sh ci-smoke diff --git a/.github/workflows/release-menubar-windows.yml b/.github/workflows/release-menubar-windows.yml new file mode 100644 index 00000000..e69c5e66 --- /dev/null +++ b/.github/workflows/release-menubar-windows.yml @@ -0,0 +1,99 @@ +name: Release Windows Menubar + +# Triggers on a `windows-v*` tag push (e.g. `git tag windows-v0.9.20 && git push origin +# windows-v0.9.20`), or manually via the Actions tab. Mirrors release-menubar.yml, which +# does the same job for the macOS menubar under the `mac-v*` tags. The produced `.msi` is +# unsigned; users see a SmartScreen prompt on first run until we add signing. +on: + push: + tags: + - 'windows-v*' + workflow_dispatch: + inputs: + version: + description: 'Version label for the bundle (e.g. v0.9.20 or dev-preview)' + required: true + default: 'dev-preview' + +permissions: + contents: write # Needed to create the release + upload assets. + +jobs: + build: + runs-on: windows-latest + timeout-minutes: 45 + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Resolve version label + id: version + shell: bash + run: | + if [[ "${GITHUB_REF}" == refs/tags/windows-v* ]]; then + echo "value=${GITHUB_REF#refs/tags/windows-}" >> "$GITHUB_OUTPUT" + else + echo "value=${{ github.event.inputs.version }}" >> "$GITHUB_OUTPUT" + fi + + - uses: actions/setup-node@v6 + with: + node-version: 22.13.0 + cache: npm + cache-dependency-path: windows/package-lock.json + + - uses: dtolnay/rust-toolchain@stable + with: + targets: x86_64-pc-windows-msvc + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: windows/src-tauri + + - name: Install dependencies + working-directory: windows + run: npm ci + + - name: Build MSI bundle + working-directory: windows + run: npm run tauri build + + - name: Collect artifacts + shell: bash + run: | + set -euo pipefail + mkdir -p release-artifacts + find windows/src-tauri/target/release/bundle -type f -name '*.msi' \ + -exec cp -v {} release-artifacts/ \; + (cd release-artifacts && for f in *.msi; do sha256sum "$f" > "$f.sha256"; done) + ls -la release-artifacts + + - name: Upload artifact (for manual runs) + if: github.event_name == 'workflow_dispatch' + uses: actions/upload-artifact@v6 + with: + name: CodeBurnMenubar-Windows-${{ steps.version.outputs.value }} + path: release-artifacts/* + if-no-files-found: error + + - name: Create / update GitHub Release + if: startsWith(github.ref, 'refs/tags/windows-v') + uses: softprops/action-gh-release@v3 + with: + tag_name: ${{ github.ref_name }} + name: Windows Menubar ${{ steps.version.outputs.value }} + body: | + Download the `.msi` below and run it. The tray app reads everything through the + CodeBurn CLI, so install that first: + + ``` + npm install -g codeburn + ``` + + Requires codeburn 0.9.9 or newer and the WebView2 Runtime (preinstalled on + Windows 11 and recent Windows 10 updates; installed on demand otherwise). + + The bundle is unsigned, so Windows SmartScreen warns on first run: click + "More info", then "Run anyway". Signing is planned. + files: release-artifacts/* + fail_on_unmatched_files: true diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index d81667d5..58fad55e 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -9,12 +9,18 @@ jobs: test: runs-on: ubuntu-latest timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + # Package floor, and the newest 22.x so paths gated on later node:zlib + # features (zstd, 22.15+) get exercised. + node-version: [22.13.0, 22] steps: - uses: actions/checkout@v6 - uses: actions/setup-node@v4 with: - node-version: 22.13.0 + node-version: ${{ matrix.node-version }} cache: npm - run: npm ci - name: Typecheck diff --git a/.github/workflows/upgrade-path.yml b/.github/workflows/upgrade-path.yml new file mode 100644 index 00000000..4791d6a8 --- /dev/null +++ b/.github/workflows/upgrade-path.yml @@ -0,0 +1,53 @@ +name: Upgrade path + +# Every existing user upgrading from the last published CLI (0.9.20) crosses the +# session-cache v7 -> v9 re-layout and the daily-cache v17 -> v19 re-derivation on +# their first run. Unit tests cover the migration in isolation on one platform; this +# job proves it against a cache that the REAL 0.9.20 binary wrote, on all three +# platforms, at both the package floor and the newest 22.x. +on: + pull_request: + paths: + - 'src/**' + - 'scripts/upgrade-path/**' + - '.github/workflows/upgrade-path.yml' + workflow_dispatch: + +jobs: + upgrade-path: + runs-on: ${{ matrix.os }} + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + # Package floor, and the newest 22.x. The floor matters here: node:zlib + # gained zstd in 22.15, so dsh degrades below it (the corpus writes the + # uncompressed dsh variant so both legs still count the same numbers). + node-version: [22.13.0, 22] + + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + cache: npm + - run: npm ci + # dist/cli.js + dist/parse-worker.js. The dash bundle is not exercised by + # any command this job runs, so the full `npm run build` is not paid for. + - run: npm run build:cli + + - name: Upgrade path from codeburn@0.9.20 + run: npm run verify:upgrade + env: + # Under runner.temp so the artifact step below can find it. The space + # is deliberate: a real Windows HOME almost always has one. + UPGRADE_PATH_WORK: ${{ runner.temp }}/codeburn upgrade path + + - name: Upload payloads on failure + if: failure() + uses: actions/upload-artifact@v4 + with: + name: upgrade-path-${{ matrix.os }}-node${{ matrix.node-version }} + path: ${{ runner.temp }}/codeburn upgrade path/payloads + if-no-files-found: ignore diff --git a/.github/workflows/windows-menubar-ci.yml b/.github/workflows/windows-menubar-ci.yml new file mode 100644 index 00000000..9a2e0298 --- /dev/null +++ b/.github/workflows/windows-menubar-ci.yml @@ -0,0 +1,83 @@ +name: Windows Menubar CI + +# The Windows menubar (windows/) is a Tauri app: a React frontend plus a Rust binary whose +# interesting code is `#[cfg(windows)]` and therefore only ever compiled on a Windows runner. +# ubuntu-latest is in the matrix because the same crate has to stay clean on the ksni/Linux +# paths and because contributors develop it on non-Windows machines. +on: + push: + branches: [main] + paths: + - .github/workflows/windows-menubar-ci.yml + - windows/** + pull_request: + paths: + - .github/workflows/windows-menubar-ci.yml + - windows/** + +permissions: + contents: read + +jobs: + check: + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + os: [windows-latest, ubuntu-latest] + + steps: + - uses: actions/checkout@v6 + + # webkit2gtk + libayatana are what the Tauri and ksni crates link against; without + # them the Linux leg cannot even typecheck the Rust side. + - name: Install Linux system dependencies + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y \ + libwebkit2gtk-4.1-dev \ + libayatana-appindicator3-dev \ + librsvg2-dev \ + libssl-dev \ + libxdo-dev \ + libgtk-3-dev \ + build-essential + + - uses: actions/setup-node@v6 + with: + node-version: 22.13.0 + cache: npm + cache-dependency-path: windows/package-lock.json + + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: windows/src-tauri + + - name: Install dependencies + working-directory: windows + run: npm ci + + - name: Typecheck frontend + working-directory: windows + run: npx tsc --noEmit + + - name: Clippy + working-directory: windows/src-tauri + run: cargo clippy --all-targets -- -D warnings + + - name: Rust tests + working-directory: windows/src-tauri + run: cargo test + + # Release-profile compile of the real Windows binary. `--no-bundle` skips the WiX + # download and MSI packaging, which belong to the release workflow, not to every PR. + - name: Release build smoke + if: runner.os == 'Windows' + working-directory: windows + run: npm run tauri build -- --no-bundle diff --git a/CHANGELOG.md b/CHANGELOG.md index dcc7d196..a709a16f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,10 +2,25 @@ ## Unreleased +### Added +- **`codeburn models --unpriced`.** The dashboard warns about models that price at $0 and points at `codeburn model-alias`, but the list itself was hard to get out of the TUI. This filters the plain-stdout `models` report to exactly those rows, reusing `findUnpricedModels` so local, free, aliased and price-overridden models are treated the same way the warning treats them, and defaulting that mode's min-cost to 0 so $0 rows are not pre-filtered away. Thanks @kocaemre. (#969) +- **`optimize` spots the same long block pasted at the start of many sessions.** The new `recurring-context` detector groups sessions by their opening block — normalized for whitespace and ANSI, hashed over the first 2 KB — and reports a block of at least 1.5 KB that opens 5 or more sessions, with the top three by tokens, their session counts and the project each is confined to. It is a habit, not an apply-able fix: CodeBurn will not move your own text into `CLAUDE.md` for you, so the finding asks Claude to give the block a permanent home (a `CLAUDE.md` rule, or a file read on demand) and hand back a one-line pointer to open sessions with instead. Savings count the repeats only, never the first paste, and are marked `estimated`: provider usage is counted per API call, where the pasted block is mixed in with the system prompt, tool schemas and `CLAUDE.md`, so the block is sized from its own bytes. Injected system reminders and slash-command wrappers are not pastes and are skipped, and neither is a prompt a program wrote — an SDK session or a subagent task — read from the entry's flags, which survive the parser's large-line path. The opening block comes from the session scan that already runs, so nothing extra is read from disk. +- **Applied fixes get re-measured on every `optimize` run, and told plainly whether they worked.** After `codeburn optimize --apply`, every still-applied fix comes back in an `Applied fixes` section on subsequent `codeburn optimize` runs, carrying the verdict `act report` already computes from the same reconciliation: `worked` (at least 70% of its window-scaled estimate realized), `partial` (something, but under that), `no-effect` (no measured reduction, printed with the exact `codeburn act undo ` that puts it back), or `measuring` for anything younger than the 3-day measurement window. The numbers are measured — provider-counted usage over the post-apply window — not re-estimated. `--apply` now says when the re-measure will happen, `--format json` gains `appliedFixes[]` (add-only), and the same section appears in the dashboard TUI and the desktop app. New `codeburn optimize --auto-revert` undoes the fixes that measured no reduction at all through the same code path as `codeburn act undo`; it never touches `partial` or still-measuring fixes, and never auto-reverts a `CLAUDE.md` rule (it prints the undo command instead), matching the `--yes` guardrail. +- **Optimize findings say what to do with them and where their number came from.** Every finding now carries a class and a basis, and every surface groups by it: `Fix now (apply-able)` for findings `codeburn optimize --apply` can write itself, `Habits` for the behavioural ones, `FYI` for informational ones whose cost may be justified. A finding only counts as apply-able when a plan can actually be built for that instance, so an `mcp-deferral-off` caused by Vertex policy or a shell-profile override is grouped as a habit rather than promising a fix that does not exist. Alongside it, each finding is marked `measured` (summed from provider-counted usage) or `estimated` (a schema-size or recovery-fraction model), with the split reported in the header as `N measured · M estimated` in place of the blanket "Estimates only." footer. Sessions whose cost the provider never reported are kept out of the `cost-outliers` peer comparison, and a provider that only ever estimates gets the finding marked `estimated` rather than dropped. `--format json` gains `class` and `basis` per finding plus `summary.measuredSavingsUSD` (existing fields unchanged), and the new `docs/optimize.md` covers what is scanned, exactly what `--apply` may write, and how to read the health grade. + +- **`CODEBURN_CACHE_SCOPE=all` forces a full session-cache read.** A ranged query reads only the month shards that can contribute a turn to it, which is a real behaviour change on a warm cache; this is the escape hatch for the case where a number looks wrong and you want to know whether the scoped read is why. Set it and every load ignores its scope and reads every shard, one-shot runs and the resident `codeburn serve` alike. It is a read policy, not an input to any cache fingerprint: setting or unsetting it re-parses nothing and invalidates nothing. + +### Added (Windows) +- **`codeburn menubar` installs and launches the tray app on Windows.** The same command that installs the macOS menubar now does the Windows one, through the same pinned-release path: it resolves `windows-v`, falls back to a scan of the newest `windows-v*` release carrying both assets when that tag has none, downloads the `.msi` with the same retry and backoff, and verifies its sha256 before anything executes it — a mismatch aborts without ever handing the file to the installer. It then runs `msiexec` out of `%SystemRoot%\System32` (never a bare name, so nothing dropped next to the CLI can impersonate it) with `/i /passive /norestart`, treats exit 3010 as installed-pending-restart and 1602 as a cancelled install rather than failures, and launches the exe named by the product's Uninstall registry key. An already-installed matching version skips the download and just launches; `--force` reinstalls. +- **A menubar app for Windows.** `windows/` is a Tauri 2 tray app — Rust binary, React popover — that puts today's spend in the notification area and mirrors the macOS menubar screen for screen: agent tabs, period switcher, Trend, Forecast, Pulse, Stats and Plan insights, activity and model breakdowns, optimize findings, CSV/JSON export, launch at login, currency, and theme. Windows has no menubar title, so the number lives in a second tray icon rendered from the system font at the panel's native icon size (Settings can turn it off; the tooltip always carries it). It reads everything through the CLI like the macOS and GNOME clients do, and gates on **codeburn 0.9.9 or newer** — the first release accepting `status --format menubar-json --no-optimize` — showing a setup screen with the install command until it finds one. Refresh follows popover visibility the way the macOS app does: 60 s with optimize findings while open, 2 minutes for today's total while closed, and immediately on open when what you are looking at has gone stale. The Claude quota view never spends Claude's single-use refresh token; on a 401 it re-reads Claude Code's own credential file for a token it has already rotated, matching the macOS client. Ships as an unsigned `.msi` from the `windows-v*` tag, which `codeburn menubar` now installs for you. The same crate still builds and runs a tray on Linux, but that stays experimental and unreleased — `gnome/` is the supported Linux surface. + ### Added (CLI) -- **Copilot input/cache tokens are read per request from `~/.copilot/session-store.db`.** Previously, codeburn relied on `session.shutdown` rollups from the Copilot CLI and GitHub Copilot desktop app. Those rollups are written only after a clean shutdown, stamp all usage on the shutdown day, and reset their counters at in-session compaction — so a crash could lose an entire session's input/cache usage, and even cleanly-closed long sessions were silently truncated. On one machine with long history, reading the per-request rows recovered about 35% of actual Copilot spend. Covered sessions now use per-request tokens with their real timestamps, counted exactly once against existing rollups and never added as extra calls or turns. Pre-store CLI sessions continue using the unchanged rollup path, and a locked or unreadable store defers only its own re-read instead of prematurely sealing daily history. Copilot reasoning tokens are also no longer double-billed: they are a subset of output already priced through the per-turn calls. This triggers a one-time re-parse, with the daily cache bumped from v17 to v19 to re-derive finalized days. (#946) +- **Copilot input/cache tokens are read per request from `~/.copilot/session-store.db`.** Previously, codeburn relied on `session.shutdown` rollups from the Copilot CLI and GitHub Copilot desktop app. Those rollups are written only after a clean shutdown, stamp all usage on the shutdown day, and reset their counters at in-session compaction — so a crash could lose an entire session's input/cache usage, and even cleanly-closed long sessions were silently truncated. On one machine with long history, reading the per-request rows recovered about 35% of actual Copilot spend. Covered sessions now use per-request tokens with their real timestamps, counted exactly once against existing rollups and never added as extra calls or turns. Pre-store CLI sessions continue using the unchanged rollup path, and a locked or unreadable store defers only its own re-read instead of prematurely sealing daily history. Copilot reasoning tokens are also no longer double-billed: they are a subset of output already priced through the per-turn calls. This triggers a one-time re-parse, with the daily cache bumped to v21 to re-derive finalized days. (#946) +- **DeepSeek Harness (`dsh`) is now a supported provider.** Reads DeepSeek's open-source agent harness from `~/.dsh/sessions` (`DSH_HOME` relocates the root), both the default zstd logs and the uncompressed `session.jsonl` variant. A `.zstd` log is a concatenation of independent zstd frames, one per write batch, so it is decoded frame by frame behind a structural frame scan and a torn trailing frame from a crashed writer is ignored rather than failing the file (needs Node 22.15+ for `zlib` zstd; below that dsh is skipped with a notice instead of counted as $0). One call per `(turn, step)`, with the step's final `assistant/message` usage superseding the streamed `assistant/chunk` sample of the same call rather than adding to it, the model taken from the message that served the step, and reasoning tokens billed at the output rate. DSH records tokens but no cost, so calls are priced from the shared tables. The events a forked session replays from its parent are skipped, since codeburn already counts the parent's own log. The session format is pinned at version 0 upstream with no compatibility implied, so a log stamped with any other version is skipped with a notice instead of read under today's assumptions. ### Changed +- **SQLite providers now survive read-only database parents.** A read-only SQLite open is not read-only on disk: on a WAL database SQLite must create `-shm` and `-wal` in the database's own directory, so a source on read-only media, under restrictive permissions, or inside a Flatpak/snap confinement failed with `attempt to write a readonly database` (or `unable to open database file` when a `-wal` was present without its `-shm`), and both discovery sites swallowed it — the provider read as "not installed" rather than as an error. That covers cursor, cursor-agent, opencode, goose, warp, kilo-code, zerostack and the copilot agent-traces database. The direct open stays the fast path and is byte-identical when it succeeds. When it fails for want of sidecars: a database with no WAL frames to lose is opened in place with `immutable=1`, which costs nothing and cannot go stale; a database with a non-empty `-wal` is copied with its `-wal` into the CodeBurn cache and read there, so its un-checkpointed rows are never silently dropped. The copy costs one database's worth of disk and is taken once per change — it is keyed by the main-plus-WAL fingerprint, published under a fingerprint-stamped name so a refresh never overwrites a copy another process is reading, and superseded copies are evicted once a day has passed without a read, keeping at most one predecessor. If the cache itself cannot be written, the database is skipped with a notice naming it and the reason rather than in silence. The original provider database is never opened writable or modified. +- **Grok Build now reads the CLI's own completed-turn usage instead of estimating it.** Usage comes from the `turn_completed.usage` records Grok CLI already writes into `updates.jsonl` (`inputTokens`, `outputTokens`, `cachedReadTokens`, `cacheCreationTokens`, `reasoningTokens`), deduplicated by `prompt_id` and emitted as one session-level call from the top-level totals. The previous parser reconstructed an estimate from the running `_meta.totalTokens` context counter, so **existing Grok totals will change materially on upgrade** - on one real 568-session corpus cache-read went from 150K to 96.3M tokens, total tokens from 20.0M to 113.9M, and cost from $36.98 to $56.79. Cache read and cache creation are subsets of input and reasoning is a subset of output, so reasoning is clamped to the record's reported output and split back out to match this repo's exclusive-reasoning contract. `modelUsage` only selects a priced attribution id; multi-model rate attribution stays out of scope, so one session is priced at one model's rate. `costUsdTicks` is ignored because its scale is undocumented. Sessions with no usable record - older CLI versions - keep the old context-curve heuristic and stay flagged estimated. **In a session that has at least one `turn_completed` record, turns without one are not counted at all** (their tokens are dropped rather than estimated), and the session is marked estimated instead of claiming full provider coverage. Cached Grok sessions re-parse once. The daily cache re-derives once on first run after upgrade: this is a global re-derivation of every day and every provider, since the daily cache has no per-provider invalidation, but it reads the warm session cache rather than re-parsing transcripts, so it costs seconds (~3s on the corpus above), and the superseded cache file is retained on disk as the baseline for days no source can still re-derive. (#998) - **Codex rollouts parse across worker threads too, and the workload gate now takes bytes or files.** Codex is the bigger half of a real cold parse — a 4 GB rollout corpus against 1.8 GB of Claude sessions — and it was still decoding one file at a time. A whole-file rollout decode now runs on the same pool, against an empty dedup set, and comes back with the calls, the dedup keys it claimed, and the codex-cache entry it would have written; the parent installs all three in the serial loop's order, so `codex-results.json` and every payload come out byte-identical to a serial run. Cross-file state stays where it was: a forked rollout replaying its parent's token_count history collides on the parent's keys and is re-parsed in-process, and no worker ever touches the cache module's per-directory state. Files the Codex cache can serve exactly or resume into from a byte offset never reach a worker — they read a few KB and the resume state belongs to the parent. The workload gate is now pending BYTES alone (200 MB), not file count: 250 pending files holding under a megabyte between them spawned threads that made the run ~5% slower, while a few hundred huge rollouts were being turned away. The count takes `max(pendingFiles / 50, pendingBytes / 200 MB)`, and the per-thread memory budget is derived per parse as `clamp(256 MB, 2 × average pending file + 128 MB, 1 GB)` rather than a flat 256 MB — a 260 MB rollout peaks near 430 MB in its worker and scales linearly with the pool, so the flat figure over-subscribed exactly the workload this adds. The decision is per provider, and at most one pool is alive at a time. - **A large cold Claude parse now runs across worker threads.** Reading, decoding and line-parsing a session JSONL is per-file work that never touches anything shared, so it moves onto `worker_threads`; each worker ships its parsed turns back as a JSON string and the parent installs them in the exact order the serial loop would. Everything with cross-file state — the streaming-message dedup, canonical project paths, spawn links, PR correlation, progress saves — stays on the main thread, and a file whose message ids were already claimed by an earlier file (or whose worker failed) is simply re-parsed in-process, so the session cache and every payload are identical either way. On a 6 GB corpus a cold `status` drops from 27.5s to 14.8s with peak RSS up 2.27 GB → 2.52 GB. Threads only engage for a genuinely large cold parse: never with under 200 MB behind the pending whole-file re-parses, 2 or fewer cores, or under 4 GB of available memory — so warm and incremental runs are untouched and spawn nothing. Otherwise the count is `min(cores - 1, min(0.25 × available, 2 GB) / 256 MB, pendingFiles / 50)`, where available is `process.availableMemory()` (cgroup-aware in containers) rather than free memory, which on macOS reports free pages and would switch the feature on and off between runs. `CODEBURN_PARSE_WORKERS=0` forces the serial parse and `CODEBURN_PARSE_WORKERS=N` forces N (capped at the core count), both bypassing every gate; `CODEBURN_VERBOSE=1` prints the resolved count and why. - **A warm launch rewrites only the month that changed, and a ranged query reads only the months it can report on.** Per-provider shards still meant one appended session republished that provider's entire history — 95 MB for Claude on a 6 GB corpus. Each provider's shard is now split again by the UTC month of the cached session's FIRST turn, a bucket that never moves as a session grows, so an append rewrites one month. Every shard records the newest month it holds, which lets `--period today/week` skip the shards that cannot contribute a turn to the range; the skipped months stay on disk untouched across the save, and providers whose cache is the only surviving record (durable) or whose parse fingerprint moved are always read in full. Remaining shards are read concurrently. Existing v8 and v7 caches are re-laid-out losslessly on first load and the old layout removed once the new one is published: nothing re-parses. @@ -15,9 +30,22 @@ - **One rule for every cache file.** `CODEBURN_CACHE_DIR` when set, otherwise `~/.cache/codeburn`. `XDG_CACHE_HOME` is no longer consulted; the sync ledger, the only file that ever honored it, is merged into the canonical location on first read and the legacy copy is retired, so nothing is re-uploaded after the move. (#972) ### Fixed (Desktop & Menubar) +- **The menubar's copies of your Claude and Codex credentials move out of Application Support and into the login Keychain.** Connecting a provider used to leave the copied OAuth material in `~/Library/Application Support/CodeBurn/*-credentials.v1.json`, written world-readable (0644) because macOS ignores `.completeFileProtection` outside iOS. The copy now lives in a CodeBurn-owned login-Keychain item, and the first read after upgrading migrates the old file: it is reopened with `O_NOFOLLOW`, refused if it is a symlink or not owned by you, repaired to 0600 before a single secret byte is read, written to the Keychain, read back and compared, and only then unlinked — a failed or unverified write leaves the (now 0600) file in place so a retry can still find it, and the next read retries the cleanup. Where both a Keychain item and an old file exist, the one that expires later wins before anything is removed, so an item left behind by a much older build cannot displace a fresher token. Claude's entry no longer stores a refresh token at all — the CLI owns that grant and the menubar never spends it — and any refresh token in a historical blob is dropped on read. Disconnect only reports success once the material is actually gone; if the delete fails it says so and leaves the provider connected so you can retry. Keychain reads are non-interactive and are skipped outright while the login Keychain is locked, so a background quota refresh can never raise an unlock panel. (#1037) +- **First launch no longer asks to control System Events.** The macOS menubar registered its login item by driving System Events over AppleScript, which made macOS put up an Automation consent dialog the first time the app ran. It now registers itself through `SMAppService.mainApp`, an in-process call that needs no Automation grant; there is no AppleScript fallback, so a failure logs and leaves the login item unset rather than bringing the prompt back. The same `codeburn.loginItemRegistered` guard still limits this to the first launch, so a login item you removed by hand stays removed. (#1026) - **The resident `codeburn serve` child.** The first real panel request is also the cache warm-up, so startup never runs an artificial warm-up query beside a duplicate one-shot child; each served command carries its own read-only option allowlist, and anything outside it falls back to a normal spawn; the child exits when its stdin closes, so it can never outlive the app. Requests whose response exceeds the 16 MiB frame limit still replace the child, but that deliberate kill no longer spends the resident's unexpected-death budget. (#972) ### Fixed +- **MiMo sessions price from the LiteLLM Xiaomi rows, and MiMo v2 Flash no longer crashes the display path.** Hermes / Xiaomi token-plan sessions store the bare id (`mimo-v2.5-pro`, `mimo-v2.5`) while LiteLLM namespaces its row (`xiaomi/…`), so those models reported $0. They now alias to the existing snapshot rows — no invented rate, and `kimi-k3` still has none — which means a session Hermes left costless is priced from the shared tables and carries the estimated marker, exactly as `mimo-v2-flash` already did. The same change fixes a **pre-existing** crash that this alias did not introduce: the shipped `mimo-v2-flash -> xiaomi/mimo-v2-flash` alias already cycled through display-name resolution — strip the namespace, alias it back, take the leaf, repeat — so `getShortModelName` blew the stack on any real MiMo v2 Flash session and took every surface that names a model down with it, the `models` table included. Display-name resolution is now cycle-safe, and the `mimo-v2-flash` and `mimo-v2.5` rows are named rather than shown as raw slugs. +- **A date-ranged run no longer republishes the month shards it never read.** A scoped load leaves an out-of-range month on disk, so the files it holds have no visible cache entry and the reconcile re-parses them — re-deriving the entry the shard already stores. That re-parse marked the unloaded month dirty, and the save merged and republished it under a fresh nonce name on every single run, byte-identical content and all, so a repeated `codeburn status --format json` churned old months (on a real corpus: claude/2026-03, cursor/2026-02 and warp/2026-03 renamed every run) and left the retired shards for the sweeper. A merge into an unloaded month that neither adds, changes nor removes an entry now keeps the published shard, so unchanged months keep their names and their bytes. (#1032) +- **`models` and `audit` no longer show two identical `Grok 4.5` rows.** `grok-4.5-build` — the Grok Build harness's variant id — fell into the `grok-4.5` display entry by prefix, and since rows bucket by model id, not display name, the two came out as visually identical rows with different numbers. The variant now shows as `Grok 4.5 (build)`. Display only: no id is rewritten and no cost moves. (#1029) +- **An upgrade no longer loses history for days whose transcripts have only PARTLY aged out.** The never-lose contract carried a cached (day, provider) slice forward only when the re-derivation found NOTHING for it, but transcripts expire per FILE rather than per day: on a day whose sources are mostly gone, a handful of turns from surviving later files still bucket onto it, so the fresh slice came back non-empty but truncated and REPLACED the full cached one. On a real cache upgrading from the last shipped daily-cache version, 2026-07-16 fell from $1,685.17 / 12,530 calls to $385.44 / 560 calls, and 13 days lost $2,765.75, 19,209 calls and 520 sessions in total. A fresh slice now replaces a settled baseline slice only when it carries at least as many CALLS - the same or more evidence; fewer calls means the source set demonstrably lost data, and the baseline is kept whole. The comparison is on calls alone: cost and tokens are re-priced accounting on the same evidence, which is exactly what a legitimate re-derivation changes (the Grok accounting fix keeps its per-day calls and is unaffected), and session counts drift down by a few on days whose sources are entirely intact. Days inside a 7-day settle window stay authoritative - their session files are still on disk, so a shrink there is a real change rather than expiry. The trade-off is deliberate and matches the direction this cache has always chosen: a future fix that legitimately REDUCES calls on a settled day keeps the older, higher value until that day is re-derived at an equal or greater call count. The timezone-change re-derive gets the exact form of the same rule - what the fresh parse can no longer explain under the old bucketing is added on top of the fresh slice instead of being dropped - and the cross-file adoption union is unchanged, where the newer schema still wins per (day, provider). +- **The session chart legend now leads with a visible session disambiguator and title instead of the project path.** Every series in a monorepo shared the same project prefix, so the only thing separating them was a truncated hex fragment — and per-application cost attribution is the main reason to open that chart. `SessionSummary.title` is already parsed and already rendered in the Context tab; the legend now puts the short session id first, prefers the title, and falls back to the previous project-based label when a session never produced one. Titles come from transcripts, so they are stripped of ANSI and control characters and capped before they reach either the legend or the tooltip. (#997) +- **Context-bloat detection now counts reasoning tokens as generated output.** `detectContextBloat` divided context by `totalOutputTokens` alone, but reasoning is stored beside output rather than inside it, so for every reasoning-bearing provider the detector saw a fraction of the tokens actually generated and invented findings - a session whose real ratio was 20:1, under the 25:1 threshold, was reported as 133:1 and "high impact". It now uses the same `output + reasoning` sum the reports use, which corrects grok, codex, kiro, hermes, qwen and cursor-agent alike. +- **The unpriced-models warning in the dashboard is now readable at every terminal width.** It lived in a fixed-width panel with an inline model list and a fix command, so it clipped mid-name at 80 columns and clipped *earlier* at 200, where the three-column layout narrows each panel - neither the affected models nor a runnable command survived. The panel line is now a pointer, `! N unpriced: codeburn models --unpriced` (shortened to `! N: codeburn models --unpriced` below 45 columns of panel), and the model list moves to that command's plain output, which is full width, copyable, and lists every model rather than the first two. The command's hint no longer reads as an unconditional instruction to alias: a subscription or flat-rate model is correctly $0, and mapping it onto another model's per-token rate would invent spend that was never billed. Provider-supplied model IDs are now stripped of terminal control characters in every human-readable report rather than only on the unpriced path, and `--unpriced` shows raw IDs instead of friendly names because `model-alias` keys on the raw ID. (#969) +- **`codeburn models --unpriced --top N` returned nothing for a `--top N` smaller than the number of priced models.** `--top` is applied inside `aggregateModels`, before the unpriced filter, on rows sorted cost-first — and unpriced rows are $0 on both, so they sorted last and the slice removed exactly the rows the flag exists to show. A user with unpriced models was told they had none. The slice now runs after the filter — and after ranking, because unpriced rows tie at $0 on both keys, so slicing them in aggregate order kept whichever models happened to appear earliest in the transcript rather than the largest. The order now matches the one the unpriced-models warning shows. (#969) +- **Old durable sources remain visible while they still exist.** The 90-day session-cache age-out now applies only after a durable source disappears from discovery, so an unchanged older Copilot source keeps reporting usage and reuses its persisted fingerprint instead of being reparsed and immediately discarded. (#987) On long-lived machines this makes previously dropped history reappear, so lifetime totals can jump once after upgrading. +- **`optimize` no longer treats subagent transcripts as your sessions.** Claude Code writes each subagent's transcript to its own `subagents/agent-*.jsonl` file with `isSidechain: true` on every entry, and optimize counted each one as a user-started session. That inflated the session count in the header and fed the session-level detectors a population that fails their tests by construction: a sidechain is handed a large context and returns a short answer (context-heavy), and it never commits or opens a PR because its parent does (low-worth). Excluded from sidechains now: the header session count, the `low-worth-sessions`, `context-bloat`, `cost-outliers` and `capability-reliability` detectors, the coaching notes, the file-churn table, the median time-to-first-edit, the worst one-shot category, and the model-default recommendation - plus `duplicate-reads`, because a subagent starts on a fresh context and re-reading what its parent read is a necessary read, not a repeat. Everything else keeps the full population: `build-folder-reads` and `read-edit-ratio` still count calls made inside a sidechain, since reading `node_modules` or editing without reading is the same waste whoever does it and the `CLAUDE.md` rule they suggest binds subagents too, and so do the MCP, cache-bloat, ghost-command and configuration-overhead findings. Classification is sticky across the whole file, so calls that appear before the first marked entry are reclassified too, and `isSidechain` now survives the compact parser's 32 KB large-line path and warm-cache range rebuilds. Nothing is deleted from spend: sidechain tokens, calls and cost stay in every total and in `status`, and the optimize result cache keys on sidechain identity so a run cannot be served a pre-fix result. Absent markers still read as user-started, so no cache re-parse is needed. (#974) +- **`optimize` no longer offers `claude mcp remove` for claude.ai connectors, and its MCP schema-cost estimate is per session.** A `claude_ai_*` namespace that no readable local MCP config claims is a claude.ai connector, managed through `/mcp` or claude.ai Settings rather than as a local MCP server (a local server that carries the prefix keeps its removal command and gains a same-name connector note); low-coverage findings now render them as a manual follow-up and build `--apply` plans only for exact local server names found in readable MCP config, so mixed findings remove only the local subset and the "apply-able" subtotal counts only that subset. The same change replaces the old global schema-cost cap with per-session, per-server proportional attribution — a more accurate model that lowers `mcp-low-coverage` estimates for everyone, connectors or not (on a large corpus roughly by half). (#975, #991) - **Bash command splitting was quadratic on long whitespace-heavy commands.** The separator regex retried its leading `\s*` from every offset; matching the separator alone and widening over whitespace by hand makes cold parse ~24% and warm ~40% faster on large corpora, output unchanged. - **Cold parse no longer retains full message bodies through cached previews.** `flatSlice` skipped its Buffer round-trip for strings already within the bound, but provider adapters pre-truncate user-message previews with `.slice(0, 500)` before the cache-site call — those pre-sliced views are still V8 SlicedStrings pinning their large parent, so the retention that OOM'd cold parses of large histories survived. The round-trip now always runs. - **Kiro sessions carry the real `projectPath`** (CLI meta.cwd, v2 `workspacePaths[0]`, workspace sessions' `workspaceDirectory`), so git-repo attribution can resolve them; previously they were attribution-blind. Bumps the kiro parse version, so the first run after upgrade re-parses kiro history once, and kiro sessions in linked git worktrees now group under the main repo. diff --git a/README.md b/README.md index 2159e1da..b04e01db 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ Sponsor

-

If CodeBurn shows you something your bill never did, star the repo so other developers find it, and consider sponsoring to keep 40 integrations honest.

+

If CodeBurn shows you something your bill never did, star the repo so other developers find it, and consider sponsoring to keep 41 integrations honest.

@@ -52,20 +52,21 @@ npx codeburn
- macOS Menubar
+ Menubar
CodeBurn macOS menubar
- codeburn menubar + codeburn menubar
+ Download the CodeBurn Windows menubar

Four surfaces, one source of truth: everything reads the session files already on your disk.

-**CodeBurn is a free, open-source, local-first tool that tracks AI coding token usage and cost across 40 tools and agents (Claude Code, Cursor, Codex, Gemini, Grok and more), broken down by model, project, and task.** +**CodeBurn is a free, open-source, local-first tool that tracks AI coding token usage and cost across 41 tools and agents (Claude Code, Cursor, Codex, Gemini, Grok and more), broken down by model, project, and task.** You pay for Claude, Codex, Cursor, and a stack of other AI tools. The bill tells you the total. It never tells you that half of it went to conversation instead of code, or that an expensive model burned your budget on work a cheaper one would have one-shot. -CodeBurn does. It reads the session files your tools already write to disk and breaks down every token and dollar by **task, model, tool, and project**, across **40 AI tools**. +CodeBurn does. It reads the session files your tools already write to disk and breaks down every token and dollar by **task, model, tool, and project**, across **41 AI tools**. Everything runs locally. No wrapper, no proxy, no API keys, nothing leaves your machine. Pricing comes from [LiteLLM](https://github.com/BerriAI/litellm), refreshed daily. @@ -107,7 +108,7 @@ Also runs via `bunx codeburn` or `pnpm dlx codeburn`, or `brew install codeburn` codeburn menubar ``` -On Linux, a GNOME Shell extension gives the same panel view; see [Linux (GNOME)](#linux-gnome). +The same command installs the tray app on Windows; see [Windows](#windows). On Linux, a GNOME Shell extension gives it in the top panel; see [Linux (GNOME)](#linux-gnome). Requires **Node.js 22.13+** and at least one supported tool with session data on disk. For Cursor and OpenCode, `better-sqlite3` installs automatically. @@ -156,6 +157,14 @@ codeburn optimize --format json # setup health + findings as JSON `codeburn optimize` scans your sessions and your `~/.claude/` setup for waste patterns: +For Claude Code, the optimize session count, the per-session findings, coaching, +and model-default recommendations use user-started (main) sessions. Subagent +sidechain transcripts are excluded from that population because their delegated +context and delivery behavior are structurally different, and so is the re-read +finding, since a subagent starts on a fresh context. Findings about how Claude +uses tools (junk reads, read:edit ratio) and every spend, MCP, and +configuration-overhead finding keep counting them. + - Files Claude re-reads across sessions (same content, same context, over and over) - Low Read:Edit ratio (editing without reading leads to retries and wasted tokens) - Wasted bash output (uncapped `BASH_MAX_OUTPUT_LENGTH`, trailing noise) @@ -167,6 +176,12 @@ codeburn optimize --format json # setup health + findings as JSON - Possibly low-worth expensive sessions with no edit turns or repeated retries when no `git`/`gh` delivery command is observed +Findings are grouped into three classes: **Fix now** (CodeBurn can apply it for you), **Habits** +(you change how you drive the next session), and **FYI** (informational, the cost may be justified). +Each one says whether its savings number is `measured` from provider-counted usage or `estimated` +from a model. See [docs/optimize.md](docs/optimize.md) for what is scanned, what `--apply` may write, +and how to read the health grade. + Each finding shows the estimated token and dollar savings plus a ready-to-paste fix: a `CLAUDE.md` line, an environment variable, or a `mv` command to archive unused items. Findings are ranked by urgency (impact weighted against observed waste) and rolled up into an A to F setup health grade. Repeat runs classify each finding as new, improving, or resolved against a 48-hour recent window. You can also open it inline from the dashboard: press `o` when a finding count appears in the status bar, `b` to return. @@ -180,11 +195,12 @@ codeburn optimize --apply --yes # apply every appliable fix without prompt codeburn act list # every change CodeBurn has made codeburn act undo --last # roll the most recent change back codeburn act report # realized vs estimated savings +codeburn optimize --auto-revert # undo the applied fixes that measured no reduction ``` `codeburn optimize` finds the waste; `--apply` fixes the config-class findings for you: settings values, environment variables, archiving unused agents and skills. Every change is backed up and journaled before it lands. `codeburn act list` shows the history and `codeburn act undo ` restores the original files (it refuses if the files changed since being applied, unless you pass `--force`). -The loop closes on honesty: once an applied fix is at least 3 days old, `codeburn act report` compares its estimated savings against what your sessions actually did, and later `codeburn optimize` runs show that realized figure in the header. Estimates get checked against reality, not just claimed. +The loop closes on honesty: once an applied fix is at least 3 days old, `codeburn act report` compares its estimated savings against what your sessions actually did, and every later `codeburn optimize` run lists it under `Applied fixes` with a plain verdict — worked, under its estimate, or did not help, with the undo command for that last case. `--auto-revert` undoes the ones that did nothing (never `CLAUDE.md` rules). Estimates get checked against reality, not just claimed. ## Guard your budget @@ -281,6 +297,8 @@ Pairing is PIN-authorized and stays on your local network. You can also discover ## Menu bar +### macOS + ```bash codeburn menubar ``` @@ -321,6 +339,20 @@ defaults write org.agentseal.codeburn-menubar CodeBurnPreferredTerminal -string Allowed values are `terminal` (macOS Terminal.app, the default) and `iterm2`. Anything else falls back to `terminal`. Only terminals that can script a command into a live window are offered; if the chosen app is missing or fails to accept the command, CodeBurn tries Terminal.app and then runs the command in the background, logging each step to Console.app. Takes effect on the next launch of a command, no relaunch needed. +### Windows + +Windows gets the same ambient view from the system tray, from the same one command: + +```powershell +codeburn menubar +``` + +It downloads the `.msi` for your CLI version, verifies its sha256, runs it through `msiexec /passive`, and launches the tray app. Re-run with `--force` to reinstall; an already-installed matching version is just launched. You can also download the `.msi` yourself from the [latest Windows Menubar release](https://github.com/getagentseal/codeburn/releases/tag/windows-v0.9.20). + +Today's spend sits in the tray as a number beside the flame icon (turn it off in Settings, and the tooltip always carries it). Click for the same popover the macOS app shows: agent tabs, period switcher, Trend, Forecast, Pulse, Stats and Plan insights, activity and model breakdowns, optimize findings, and CSV/JSON export. Settings covers launch at login, the tray number, theme, and currency. It refreshes every 60 seconds while the popover is open and every 2 minutes while it is closed. + +The tray app reads everything through the CLI, so install that first (`npm install -g codeburn`) — it needs **codeburn 0.9.9 or newer**, and shows a setup screen with the install command until it finds one. Source and build instructions are in [`windows/`](windows/) ([windows/DEVELOPMENT.md](windows/DEVELOPMENT.md)). The `.msi` is unsigned for now, so SmartScreen prompts on first run. + ### Linux (GNOME) Linux gets the same ambient view through a GNOME Shell extension (GNOME 45+): spend in the top panel, period switcher, compact mode, and daily budget alerts. It lives in [`gnome/`](gnome/): @@ -331,7 +363,7 @@ git clone https://github.com/getagentseal/codeburn && cd codeburn/gnome gnome-extensions enable codeburn@codeburn.dev ``` -See [gnome/README.md](gnome/README.md) for settings and development notes. On Windows, `codeburn web` is the always-on view for now. +See [gnome/README.md](gnome/README.md) for settings and development notes. The Tauri tray app in `windows/` also builds and runs on Linux, but it is experimental and unreleased there — the GNOME extension is the supported Linux surface. ## CodeBurn in your agent (MCP) @@ -484,6 +516,7 @@ Sync sends token counts, costs, models, and projects, never prompts or code. Thi | `codeburn models --by-task` | Break each model into per-task-type rows | | `codeburn models --by-agent` | Break each model into per-agent rows: which agent drove which model's spend (`(main)` covers non-agent sessions; `--min-cost 0` shows sub-cent agents) | | `codeburn models --top 10` | Only the 10 most expensive models | +| `codeburn models --unpriced` | Only models with usage that currently price at $0 — the copyable form of the unpriced-models warning. Shows raw model IDs (not friendly names) so they can be pasted into `model-alias`; JSON keeps them exact | | `codeburn models --format markdown` | Emit a paste-friendly markdown table | | `codeburn models --task feature` | Filter to feature-development work | | `codeburn models --provider claude` | Filter to a single provider | @@ -683,6 +716,7 @@ These are starting points, not verdicts. A 60% cache hit on a single experimenta | **Cline / Roo Code / KiloCode** | VS Code `globalStorage` across VS Code, VS Code Insiders, and VSCodium (Cline at `saoudrizwan.claude-dev`, plus `~/.cline/data`) | Cline-family agents. CodeBurn reads `ui_messages.json` from each task directory, extracting token counts from `type: "say"` entries with `say: "api_req_started"`. | | **Cline CLI** | `~/.cline/data/sessions//` (honors `CLINE_SESSION_DATA_DIR`, `CLINE_DATA_DIR`, `CLINE_DIR`) | The Cline command-line agent, whose layout is unrelated to the VS Code extension's. Reads `.json` for session metadata and the rolled-up `usage`, and `.messages.json` for the per-message `metrics` block (input, output, cacheRead, cacheWrite, cost) that becomes one call each. | | **CodeWhale** | `~/.codewhale/sessions/*.json` plus unmigrated legacy `~/.deepseek/sessions/*.json`; `$CODEWHALE_HOME/sessions` is an exact override | Emits one cumulative record per saved session. CodeWhale exposes only `total_tokens`, so CodeBurn preserves that aggregate in the input column rather than inventing an input/output split. Cost is the exact stored parent-session plus subagent USD total; model pricing is used only when the cost snapshot is absent. Tool blocks, shell commands, skills, and subagent types are retained. | +| **DeepSeek Harness** (`dsh`) | `~/.dsh/sessions/----//session.jsonl.zstd` (or `session.jsonl` when compression is off); `DSH_HOME` relocates the root | DeepSeek's open-source agent harness, unrelated to the CodeWhale desktop app. The `.zstd` log is a concatenation of independent zstd frames (one per write batch), decoded frame by frame; needs Node 22.15+. One call per `(turn, step)`, with usage from the step's `assistant/message` (the streamed `assistant/chunk` sample is a draft of the same call, never a second one). DSH records tokens but no cost, so calls are priced from the shared tables with reasoning billed at the output rate. | | **IBM Bob** | `User/globalStorage/ibm.bob-code/tasks//` (GA `IBM Bob` and preview `Bob-IDE` app folders) | Reads `ui_messages.json` for API request token/cost records and `api_conversation_history.json` for the selected model. | | **Kimi Code CLI** | `$KIMI_SHARE_DIR/sessions///` or `~/.kimi/sessions///` | Reads `wire.jsonl` `StatusUpdate.token_usage` records, mapping `input_other`, `input_cache_read`, `input_cache_creation`, and `output` into the standard token columns; includes subagents under each session's `subagents/` folder. | | **LingTai TUI** | `~/.lingtai//logs/token_ledger.jsonl` plus project homes from `~/.lingtai-tui/registry.jsonl` (`/.lingtai//logs/token_ledger.jsonl`); honors `LINGTAI_HOME` / `LINGTAI_TUI_HOME` | Reads LingTai's append-only token ledger, mapping `input - cached` to fresh input, `cached` to cache reads, `output` to output, and `thinking` to reasoning. Nested daemon ledgers are skipped because parent ledgers already mirror daemon usage with `source`/`run_id` tags. | @@ -722,12 +756,12 @@ CodeBurn deduplicates messages (by API message ID for Claude, by cumulative toke CodeBurn is free, runs entirely on your machine, and exists to cut your AI bill. If it has already saved you more than a sponsorship costs, consider sending a little of that back. -Keeping 40 integrations accurate is constant work. The tools underneath change every week: Cursor reshapes its database, Claude moves a config path, new models ship at new prices. Sponsorship keeps CodeBurn current with all of it, so the numbers you see are always the real ones. +Keeping 41 integrations accurate is constant work. The tools underneath change every week: Cursor reshapes its database, Claude moves a config path, new models ship at new prices. Sponsorship keeps CodeBurn current with all of it, so the numbers you see are always the real ones. Where your sponsorship goes: - **Honest numbers.** New models and price changes are mapped quickly, so your cost is the real cost, not a guess. -- **More tools.** Every one of the 40 providers started as a single file. Sponsorship funds the next one. +- **More tools.** Every one of the 41 providers started as a single file. Sponsorship funds the next one. - **Fast fixes.** When a vendor breaks something, paid time is what gets it patched now instead of someday. Sponsoring as a team or company? Your logo lands right here, in front of every developer who opens the repo. The first sponsor gets it to themselves until the next one shows up. diff --git a/RELEASING.md b/RELEASING.md index df1c6754..be443b3d 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -1,8 +1,10 @@ # Releasing CodeBurn -This document describes the actual steps a maintainer takes to cut a CLI or macOS menubar release. CLI releases are run by hand with `npm publish`; macOS menubar releases are automated by `.github/workflows/release-menubar.yml` when a `mac-v*` tag is pushed. +This document describes the actual steps a maintainer takes to cut CLI, macOS menubar, and Electron desktop releases. CLI releases are run by hand with `npm publish`; macOS menubar releases are automated by `.github/workflows/release-menubar.yml` when a `mac-v*` tag is pushed. -The Electron desktop app (`app/`) has no CI automation yet, but it is released manually under `desktop-v` tags: build the artifacts on a macOS host (see `app/DISTRIBUTION.md`) and `gh release upload desktop-v … --clobber` them onto the release. See `app/DISTRIBUTION.md` for how to build and distribute it as an ad-hoc-signed, non-notarized macOS build (plus unsigned Windows and Linux builds). +The Electron desktop app (`app/`) is released manually under `desktop-v` tags. Build macOS and Linux artifacts as described in `app/DISTRIBUTION.md`; the tag also runs the read-only `Build Windows installer` workflow on `windows-latest`. Download its `CodeBurn-Windows-Installer` artifact and upload both the `.exe` and `.exe.blockmap` with the other platform assets. The workflow never publishes release assets. + +Before announcing a desktop release, the release owner must confirm the live GitHub Release contains all four macOS `.dmg`/`.zip` files, the Linux `.AppImage`, `.deb`, and `.rpm`, and both Windows installer files. Publishing the Release runs the workflow's read-only live-asset verification job. If assets are uploaded after publication, rerun `Build Windows installer` with the `release_tag` input and require that verification job to pass. A failed or missing verification is a release blocker. ## Versioning @@ -197,4 +199,4 @@ For the menubar, tag a new mac-v0.9.9 and let the workflow build and upload it. ## Summary -The CLI release is manual: bump the version, update `CHANGELOG.md`, commit, run `npm publish`, then tag and create a GitHub Release. The macOS menubar release is automated: pushing a `mac-v*` tag fires `.github/workflows/release-menubar.yml`, which builds, signs, zips, and publishes the bundle. The homebrew-core formula is updated automatically or via `brew bump-formula-pr`. +The CLI release is manual: bump the version, update `CHANGELOG.md`, commit, run `npm publish`, then tag and create a GitHub Release. The macOS menubar release is automated: pushing a `mac-v*` tag fires `.github/workflows/release-menubar.yml`, which builds, signs, zips, and publishes the bundle. The Electron desktop release is assembled manually under a `desktop-v*` tag, with the release-authoritative Windows NSIS installer built by the read-only `windows-latest` workflow. The homebrew-core formula is updated automatically or via `brew bump-formula-pr`. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 00000000..c1ffcb8e --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,51 @@ +# Third-party notices + +CodeBurn is MIT licensed (see `LICENSE`). It also contains code derived from the +projects below, which carry their own terms. Each notice is reproduced here as +those terms require. + +--- + +## @deepseek-ai/dsh-session-persistence-jsonl + +`scanZstdFrames` in `src/providers/dsh.ts` is a transcription of the function of +the same name in this package (`src/zstd.ts`), which is what lets CodeBurn read +a DeepSeek Harness session log without depending on the harness itself. No other +part of the package is used. + +Upstream declares two different licenses for this package: the published npm +package (0.0.1-rc.1) ships a BSD 3-Clause `LICENSE` and declares +`"license": "BSD-3-Clause"`, while the monorepo source it is built from +(`deepseek-ai/deepseek-harness`, `packages/session/session-persistence-jsonl`) +declares MIT. The stricter of the two is reproduced below. + +``` +BSD 3-Clause License + +Copyright (c) 2026, DeepSeek + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +``` diff --git a/app/DISTRIBUTION.md b/app/DISTRIBUTION.md index 69165022..56609fae 100644 --- a/app/DISTRIBUTION.md +++ b/app/DISTRIBUTION.md @@ -3,10 +3,10 @@ This document describes how to produce distributable macOS, Windows, and Linux builds of the Electron desktop app. The macOS build is ad-hoc-signed and **not notarized** (no paid Apple Developer account); the Windows and Linux -builds are **unsigned**. There is no CI automation for any of this yet (unlike -the CLI and menubar release processes in `../RELEASING.md`) — packaging is run -by hand on a maintainer's machine. All three targets are produced by -`electron-builder` and can be cross-built from a single macOS host. +builds are **unsigned**. Windows NSIS packages are built and checked by the +`Build Windows installer` GitHub Actions workflow; the other desktop packages +are still produced by hand. All three targets are produced by +`electron-builder`. ## The bundled CLI (no install prerequisite) @@ -93,8 +93,9 @@ self-contained bundle into `app/build/cli`; see "The bundled CLI" above), then `vite`), then `electron-builder --mac` (whose `afterPack` hook copies the staged CLI into the app). `package:win` and `package:linux` mirror it exactly, swapping the final flag for `electron-builder --win` and `electron-builder ---linux`. All three can run on the same macOS host — electron-builder downloads -the NSIS and AppImage tooling on first use. +--linux`. Developers can run all three locally on the same macOS host — +electron-builder downloads the NSIS and AppImage tooling on first use. Release +Windows installers are built by the `windows-latest` workflow described below. ### Artifacts @@ -154,19 +155,20 @@ separate `electron-builder.yml`): ## Windows and Linux builds -Both are cross-built from the same macOS host used for the mac build — no -Windows or Linux machine, and no `wine`, is required. electron-builder 26 -embeds the Windows executable's icon/version resources natively and downloads -the NSIS and AppImage tooling on first run. +Developers can cross-build both locally from the same macOS host used for the +mac build — no Windows or Linux machine, and no `wine`, is required. +Release-authoritative Windows NSIS installers are instead built by the `Build +Windows installer` workflow on `windows-latest`. electron-builder 26 embeds the +Windows executable's icon/version resources natively and downloads the NSIS and +AppImage tooling on first run. ### Windows (`package:win`) -`electron-builder --win` produces a single artifact in `app/release/`: +`electron-builder --win` produces a single installer in `app/release/`: -- **`CodeBurn Setup 0.9.15.exe`** — the NSIS installer (the version number - tracks `package.json`; note the spaces in the filename). A `.exe.blockmap` - is written alongside it (differential-update metadata, unused — no - auto-updater yet). +- **`CodeBurn-Setup-0.9.15.exe`** — the NSIS installer (the version number + tracks `package.json`). A `.exe.blockmap` is written alongside it + (differential-update metadata, unused — no auto-updater yet). Config (`build.win` + `build.nsis`): @@ -236,8 +238,7 @@ taskbar/dock; it does not affect packaging or launch. ## Releases -There is no release CI for the desktop app yet (see the note at the top). When -a maintainer cuts a desktop release by hand, the GitHub tag convention is: +When a maintainer cuts a desktop release, the GitHub tag convention is: ``` desktop-v # e.g. desktop-v0.9.15 @@ -245,14 +246,31 @@ desktop-v # e.g. desktop-v0.9.15 This mirrors the menubar's `mac-v` convention (see `../RELEASING.md`) and keeps the desktop app's tags in their own namespace, separate from the CLI -(`v`) and the menubar (`mac-v`). Upload all of the artifacts -above — the four macOS `.dmg`/`.zip` files, `CodeBurn-Setup-.exe`, -and `CodeBurn-.AppImage` — to the GitHub Release created at that -tag. The website's download links **pin that tag** in their URLs, so the -release name and the artifact filenames must match exactly. (The Windows -installer uses an explicit `nsis.artifactName` of -`CodeBurn-Setup-${version}.${ext}` — electron-builder's default contains -spaces, which make ugly percent-encoded URLs.) +(`v`) and the menubar (`mac-v`). + +Pushing a `desktop-v` tag runs the `Build Windows installer` workflow +on `windows-latest`. The workflow requires the tag version, root package +version, and app package version to agree, and it fails unless the build emits +exactly one `CodeBurn-Setup-.exe` and one matching +`.exe.blockmap` at the top level of `app/release/`. It uploads those exact +top-level filenames as the `CodeBurn-Windows-Installer` +Actions artifact. The workflow has read-only repository permissions and does +**not** publish release assets automatically. Artifacts are retained for 30 days. + +Before publishing the GitHub Release, the release owner must download that +workflow artifact and manually upload both Windows files along with the four +macOS `.dmg`/`.zip` files, `CodeBurn-.AppImage`, +`codeburn-desktop__amd64.deb`, and +`codeburn-desktop-.x86_64.rpm`. Confirm the live release contains +every required platform asset before announcing it. The +website's download links **pin that tag** in their URLs, so a release with a +missing installer is broken even when another Windows distribution channel is +available. The Windows installer uses an explicit `nsis.artifactName` of +`CodeBurn-Setup-${version}.${ext}`. + +Publishing the Release triggers a read-only live-asset check. If the files are +uploaded afterward, rerun the workflow manually with `release_tag` set to the +existing `desktop-v` tag and require the verification job to pass. ## Verifying a build diff --git a/app/package.json b/app/package.json index efe4fde8..ab5a29b4 100644 --- a/app/package.json +++ b/app/package.json @@ -169,6 +169,7 @@ "$HOME/.copilot", "$HOME/.cursor", "$HOME/.deepseek", + "$HOME/.dsh/sessions", "$HOME/.factory", "$HOME/.forge", "$HOME/.gemini", diff --git a/app/renderer/App.test.tsx b/app/renderer/App.test.tsx index dbf5e8ff..d29b4c43 100644 --- a/app/renderer/App.test.tsx +++ b/app/renderer/App.test.tsx @@ -138,7 +138,12 @@ function installDefaultMocks() { summary: { healthScore: 100, healthGrade: 'A', findingCount: 0, periodCostUSD: 0, sessions: 0, calls: 0, potentialSavingsTokens: 0, potentialSavingsCostUSD: 0, - potentialSavingsPercent: 0, costRateUSD: 0, + potentialSavingsPercent: 0, costRateUSD: 0, measuredSavingsUSD: 0, + byClass: { + fix: { tokensSaved: 0, savingsUSD: 0, count: 0 }, + nudge: { tokensSaved: 0, savingsUSD: 0, count: 0 }, + keep: { tokensSaved: 0, savingsUSD: 0, count: 0 }, + }, }, findings: [], }) diff --git a/app/renderer/lib/types.ts b/app/renderer/lib/types.ts index 25394087..fa05bc6d 100644 --- a/app/renderer/lib/types.ts +++ b/app/renderer/lib/types.ts @@ -403,10 +403,12 @@ export type SpendFlow = { // ————— src/optimize.ts ————— export type WasteAction = - | { type: 'paste'; label: string; text: string; destination?: 'claude-md' | 'session-opener' | 'prompt' | 'shell-config' } + | { type: 'paste'; label: string; text: string; destination?: 'claude-md' | 'session-opener' | 'prompt' | 'shell-config' | 'manual' } | { type: 'command'; label: string; text: string } | { type: 'file-content'; label: string; path: string; content: string } +export type FindingClass = 'fix' | 'nudge' | 'keep' + export type OptimizeJsonReport = { period: { label: string; start: string | null; end: string | null } summary: { @@ -420,6 +422,8 @@ export type OptimizeJsonReport = { potentialSavingsCostUSD: number potentialSavingsPercent: number | null costRateUSD: number + measuredSavingsUSD: number + byClass: Record } findings: Array<{ id: string @@ -429,8 +433,21 @@ export type OptimizeJsonReport = { trend: 'active' | 'improving' | null tokensSaved: number estimatedSavingsUSD: number + class: FindingClass + basis: 'measured' | 'estimated' fix: WasteAction }> + /** Still-applied fixes, re-measured on every run. Absent on older CLIs. */ + appliedFixes?: Array<{ + id: string + kind: string + findingId: string | null + appliedAt: string + verdict: 'worked' | 'partial' | 'no-effect' | 'pending' + estimatedTokens: number + realizedTokens: number + undoCommand: string + }> } // ————— T1b: src/sharing/* (defined by the shared contract) ————— diff --git a/app/renderer/sections/Optimize.test.tsx b/app/renderer/sections/Optimize.test.tsx index 5219afaf..70013522 100644 --- a/app/renderer/sections/Optimize.test.tsx +++ b/app/renderer/sections/Optimize.test.tsx @@ -48,23 +48,31 @@ function makeOptimizeReport(): OptimizeJsonReport { healthScore: 72, healthGrade: 'C', findingCount: 3, periodCostUSD: 612.48, sessions: 88, calls: 1220, potentialSavingsTokens: 184_000, potentialSavingsCostUSD: 94.4, potentialSavingsPercent: 15.4, costRateUSD: 0.0005, + measuredSavingsUSD: 27.8, + byClass: { + fix: { tokensSaved: 18_200, savingsUSD: 9.1, count: 1 }, + nudge: { tokensSaved: 17_400, savingsUSD: 8.7, count: 1 }, + keep: { tokensSaved: 4_800, savingsUSD: 2.4, count: 1 }, + }, }, findings: [ { - id: 'cost-outliers', title: 'Opus is doing your small talk', + id: 'unused-mcp', title: 'Opus is doing your small talk', explanation: 'Small conversational requests are running on an expensive model.', severity: 'high', trend: 'active', tokensSaved: 18_200, estimatedSavingsUSD: 9.1, + class: 'fix', basis: 'estimated', fix: { type: 'paste', label: 'Paste into CLAUDE.md', text: 'Use Sonnet for routine questions.', destination: 'claude-md' }, }, { - id: 'context-heavy-sessions', title: 'Cache hit is low in agentseal-dash', + id: 'cost-outliers', title: 'Cache hit is low in agentseal-dash', explanation: 'Repeated context is not being served from cache.', severity: 'medium', - trend: null, tokensSaved: 17_400, estimatedSavingsUSD: 8.7, + trend: null, tokensSaved: 17_400, estimatedSavingsUSD: 8.7, class: 'nudge', basis: 'measured', fix: { type: 'command', label: 'Run this command', text: 'codeburn cache inspect' }, }, { - id: 'warmup-heavy', title: 'Batch tiny requests', explanation: 'Many short sessions repeat setup work.', + id: 'context-heavy-sessions', title: 'Batch tiny requests', explanation: 'Many short sessions repeat setup work.', severity: 'low', trend: 'improving', tokensSaved: 4_800, estimatedSavingsUSD: 2.4, + class: 'keep', basis: 'measured', fix: { type: 'file-content', label: 'Create configuration', path: '~/.codeburn/config.json', content: '{"batch":true}' }, }, ], @@ -121,6 +129,46 @@ describe('Optimize', () => { Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) }) + it('lists applied fixes with a glyph per verdict and the undo hint', async () => { + const report = makeOptimizeReport() + report.appliedFixes = [ + { id: 'a1', kind: 'archive-skill', findingId: 'unused-skills', appliedAt: '2026-07-06T00:00:00.000Z', verdict: 'worked', estimatedTokens: 300_000, realizedTokens: 280_000, undoCommand: 'codeburn act undo a1' }, + { id: 'b2', kind: 'defer-threshold', findingId: 'mcp-defer-threshold', appliedAt: '2026-07-07T00:00:00.000Z', verdict: 'partial', estimatedTokens: 600_000, realizedTokens: 420_000, undoCommand: 'codeburn act undo b2' }, + { id: 'c3', kind: 'shell-config', findingId: 'bash-output-cap', appliedAt: '2026-07-05T00:00:00.000Z', verdict: 'no-effect', estimatedTokens: 41_000, realizedTokens: 0, undoCommand: 'codeburn act undo c3' }, + { id: 'd4', kind: 'mcp-remove', findingId: null, appliedAt: '2026-07-09T00:00:00.000Z', verdict: 'pending', estimatedTokens: 0, realizedTokens: 0, undoCommand: 'codeburn act undo d4' }, + ] + getOptimizeReport.mockResolvedValue(report) + render() + + await screen.findByText('Applied fixes') + const rows = [...document.querySelectorAll('.opt-applied-row')] + expect(rows.map(r => r.className.split(' ')[1])).toEqual([ + 'opt-applied-worked', 'opt-applied-partial', 'opt-applied-no-effect', 'opt-applied-pending', + ]) + expect(rows[0]!.textContent).toContain('unused-skills') + expect(rows[0]!.textContent).toContain('est. 300K \u2192 280K') + expect(rows[3]!.textContent).toContain('mcp-remove') + expect(screen.getByText('codeburn act undo c3')).toBeTruthy() + }) + + it('omits the applied-fixes list when nothing is applied', async () => { + render() + await screen.findByText('Opus is doing your small talk') + expect(document.querySelector('.opt-applied')).toBeNull() + }) + + it('groups Waste findings under the fix / habits / FYI headers in order', async () => { + render() + + await screen.findByText('Opus is doing your small talk') + const groups = document.querySelectorAll('.opt-group') + expect([...groups].map(g => g.textContent)).toEqual([ + 'Fix now (apply-able) · 18.2K tokens · $9.10 · 1 finding', + 'Habits · 17.4K tokens · $8.70 · 1 finding', + 'FYI · 4.8K tokens · $2.40 · 1 finding', + ]) + }) + it('renders tabs and actionable Waste findings with impact, savings, explanation, and copy-paste fix', async () => { render() @@ -130,7 +178,7 @@ describe('Optimize', () => { expect(screen.getByText('Medium')).toHaveClass('opt-impact-medium') expect(screen.getByText('Low')).toHaveClass('opt-impact-low') expect(screen.getByText('$9.10')).toHaveClass('opt-finding-savings') - expect(screen.getByText('18.2K tokens')).toBeInTheDocument() + expect(screen.getByText('18.2K tokens · estimated')).toBeInTheDocument() expect(screen.getByRole('tab', { name: 'Waste $94.40' })).toBeInTheDocument() expect(screen.getByRole('tab', { name: 'Reverts $107.00' })).toBeInTheDocument() expect(screen.getByRole('tab', { name: 'Abandoned $65.40' })).toBeInTheDocument() @@ -160,6 +208,32 @@ describe('Optimize', () => { expect(screen.getByText('{"batch":true}')).toBeInTheDocument() }) + it('renders and copies connector guidance as a manual action', async () => { + const report = makeOptimizeReport() + report.findings.push({ + id: 'mcp-low-coverage', title: 'Underused claude.ai connector', + explanation: 'The connector loads unused tools.', severity: 'medium', + trend: null, tokensSaved: 2_000, estimatedSavingsUSD: 1, + // Connector-only: no appliable plan, so the finding is a nudge. + class: 'nudge', basis: 'estimated', + fix: { + type: 'paste', destination: 'manual', label: 'Manage the connector where it loads:', + text: 'Open /mcp and disable claude.ai Google Calendar.', + }, + }) + report.summary.byClass.nudge = { tokensSaved: 19_400, savingsUSD: 9.7, count: 2 } + getOptimizeReport.mockResolvedValue(report) + render() + const row = await screen.findByRole('button', { name: /Underused claude.ai connector/ }) + fireEvent.click(row) + + expect(screen.getByText('Manage the connector where it loads:')).toBeInTheDocument() + expect(screen.getByText('Open /mcp and disable claude.ai Google Calendar.')).toBeInTheDocument() + expect(row.parentElement?.querySelector('.opt-fix')).toHaveClass('opt-fix-paste') + fireEvent.click(screen.getByRole('button', { name: 'Copy' })) + await waitFor(() => expect(writeText).toHaveBeenCalledWith('Open /mcp and disable claude.ai Google Calendar.')) + }) + it('switches to Reverts and Abandoned and shows only the matching yield details', async () => { render() await screen.findByText('Opus is doing your small talk') diff --git a/app/renderer/sections/Optimize.tsx b/app/renderer/sections/Optimize.tsx index 03d8674b..ac9350c2 100644 --- a/app/renderer/sections/Optimize.tsx +++ b/app/renderer/sections/Optimize.tsx @@ -9,7 +9,7 @@ import { StaleBanner } from '../components/StaleBanner' import { type Polled, usePolled } from '../hooks/usePolled' import { formatCompact, formatUsd } from '../lib/format' import { codeburn } from '../lib/ipc' -import type { DateRange, MenubarPayload, OptimizeJsonReport, Period, SessionYieldJson, WasteAction, YieldJsonReport } from '../lib/types' +import type { DateRange, FindingClass, MenubarPayload, OptimizeJsonReport, Period, SessionYieldJson, WasteAction, YieldJsonReport } from '../lib/types' type OptimizeTab = 'waste' | 'reverts' | 'abandoned' | 'fixes' @@ -101,7 +101,51 @@ function WasteRows({ report }: { report: Polled }) {
{report.data.summary.findingCount.toLocaleString('en-US')} findings · {formatUsd(report.data.summary.potentialSavingsCostUSD)} potential · health {report.data.summary.healthScore}/100
- + + + + ) +} + +type AppliedFix = NonNullable[number] + +const VERDICT_GLYPH: Record = { + worked: '\u2713', + partial: '~', + 'no-effect': '\u2717', + pending: '\u2026', +} + +const VERDICT_LABEL: Record = { + worked: 'worked', + partial: 'under estimate', + 'no-effect': 'did not help', + pending: 'measuring', +} + +// Closes the loop after `optimize --apply`: what each applied fix actually +// measured, and for the ones that did nothing, how to put them back. +function AppliedFixRows({ fixes }: { fixes: AppliedFix[] }) { + if (!fixes.length) return null + + return ( +
+
Applied fixes
+ {fixes.map(fix => ( +
+ + {fix.findingId ?? fix.kind} + {VERDICT_LABEL[fix.verdict]} + + {fix.verdict === 'pending' + ? '\u2014' + : `est. ${formatCompact(fix.estimatedTokens)} \u2192 ${formatCompact(fix.realizedTokens)}`} + +
+ ))} + {fixes.some(fix => fix.verdict === 'no-effect') && ( +
Revert one that did not help: {fixes.find(fix => fix.verdict === 'no-effect')!.undoCommand}
+ )}
) } @@ -114,11 +158,17 @@ const IMPACT_ICON: Record<'high' | 'medium' | 'low', string> = { low: '↓', } +const CLASS_HEADERS: Record = { + fix: 'Fix now (apply-able)', + nudge: 'Habits', + keep: 'FYI', +} + function actionText(fix: WasteAction): string { return fix.type === 'file-content' ? fix.content : fix.text } -function ActionableFindingRows({ findings }: { findings: OptimizeFinding[] }) { +function ActionableFindingRows({ findings, byClass }: { findings: OptimizeFinding[]; byClass: OptimizeJsonReport['summary']['byClass'] }) { const [expandedId, setExpandedId] = useState(null) const [copiedId, setCopiedId] = useState(null) @@ -132,10 +182,18 @@ function ActionableFindingRows({ findings }: { findings: OptimizeFinding[] }) { return (
- {findings.map(finding => { + {findings.map((finding, i) => { const expanded = expandedId === finding.id + // Findings arrive class-sorted from the CLI, so a header goes in + // wherever the class changes. + const showHeader = finding.class !== findings[i - 1]?.class return ( + {showHeader && ( +
+ {CLASS_HEADERS[finding.class]} · {formatCompact(byClass[finding.class].tokensSaved)} tokens · {formatUsd(byClass[finding.class].savingsUSD)} · {byClass[finding.class].count} {byClass[finding.class].count === 1 ? 'finding' : 'findings'} +
+ )} {expanded && ( diff --git a/app/renderer/styles/plain.css b/app/renderer/styles/plain.css index f82172b9..6d7a86c4 100644 --- a/app/renderer/styles/plain.css +++ b/app/renderer/styles/plain.css @@ -640,6 +640,9 @@ td:first-child { font-size: var(--fs-body); font-weight: var(--fw-body); } .opt-waste { min-width: 0; } .opt-summary { padding: 0 0 10px; color: var(--mut); font-size: 11.5px; font-variant-numeric: tabular-nums; } .opt-findings { display: grid; min-width: 0; } +.opt-group { padding: 11px 0 5px; color: var(--mut2); font-size: 10px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; } +.opt-group:first-child { padding-top: 0; } +.opt-group + .opt-finding { border-top: 0; } .opt-finding { display: grid; align-items: center; column-gap: 12px; min-height: 43px; border-top: 1px solid var(--line2); } .opt-finding:first-child { border-top: 0; } .opt-finding-legacy { grid-template-columns: 28px minmax(0, 1fr) 104px 86px; } @@ -668,6 +671,15 @@ td:first-child { font-size: var(--fs-body); font-weight: var(--fw-body); } .opt-fix-code { max-width: 100%; overflow-x: auto; margin: 0; padding: 10px 11px; border: 1px solid var(--line); border-radius: 6px; background: var(--phead); color: var(--ink); font-family: var(--mono); font-size: 11px; line-height: 1.5; white-space: pre; } .opt-fix-command .opt-fix-code code::before { content: '$ '; color: var(--mut2); user-select: none; } .opt-copy { flex: 0 0 auto; padding: 4px 9px; border: 1px solid var(--line); border-radius: 6px; background: var(--panel); color: var(--mut); font: inherit; font-size: 10.5px; cursor: pointer; } +.opt-applied { padding-top: 12px; } +.opt-applied-row { display: grid; grid-template-columns: 16px minmax(0, 1fr) 110px 140px; align-items: center; column-gap: 12px; min-height: 34px; border-top: 1px solid var(--line2); } +.opt-applied-glyph { color: var(--mut2); font-family: var(--mono); font-size: 12px; } +.opt-applied-verdict { color: var(--mut); font-size: 10.5px; } +.opt-applied-worked .opt-applied-glyph, .opt-applied-worked .opt-applied-verdict { color: var(--ok); } +.opt-applied-partial .opt-applied-glyph, .opt-applied-partial .opt-applied-verdict { color: var(--warn); } +.opt-applied-no-effect .opt-applied-glyph, .opt-applied-no-effect .opt-applied-verdict { color: var(--bad); } +.opt-applied-hint { padding: 9px 0 0; } +.opt-applied-hint code { font-family: var(--mono); } .opt-copy:hover, .opt-copy:focus-visible { border-color: var(--accent); color: var(--ink); outline: none; } .ov-analytics-row { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; align-items: stretch; } .ov-analytics-row > :only-child { grid-column: 1 / -1; } diff --git a/app/scripts/verify-windows-installer.mjs b/app/scripts/verify-windows-installer.mjs new file mode 100644 index 00000000..84d499e6 --- /dev/null +++ b/app/scripts/verify-windows-installer.mjs @@ -0,0 +1,101 @@ +#!/usr/bin/env node + +import { readFileSync, readdirSync } from 'node:fs' +import { basename, join, resolve } from 'node:path' +import { rootFromModuleUrl } from './windows-installer-paths.mjs' + +function fail(message) { + console.error(`Windows installer manifest invalid: ${message}`) + process.exitCode = 1 +} + +function option(name, fallback) { + const index = process.argv.indexOf(name) + if (index === -1) return fallback + if (!process.argv[index + 1]) throw new Error(`${name} requires a value`) + return process.argv[index + 1] +} + +function packageVersion(path) { + return JSON.parse(readFileSync(path, 'utf8')).version +} + +function filesBelow(directory) { + return readdirSync(directory, { withFileTypes: true }) + .filter(entry => entry.isFile()) + .map(entry => basename(entry.name)) +} + +function releaseVersion(tag) { + const match = /^desktop-v(.+)$/.exec(tag) + if (!match) throw new Error(`${tag || '(missing tag)'} is not a desktop release tag`) + return match[1] +} + +function verifyLiveRelease(tag, assetPath) { + const version = releaseVersion(tag) + const assets = JSON.parse(readFileSync(assetPath, 'utf8')) + if (!Array.isArray(assets) || assets.some(asset => typeof asset !== 'string')) { + throw new Error('release asset manifest must be a JSON array of names') + } + const required = [ + `CodeBurn-${version}-arm64.dmg`, + `CodeBurn-${version}.dmg`, + `CodeBurn-${version}-arm64-mac.zip`, + `CodeBurn-${version}-mac.zip`, + `CodeBurn-${version}.AppImage`, + `codeburn-desktop_${version}_amd64.deb`, + `codeburn-desktop-${version}.x86_64.rpm`, + `CodeBurn-Setup-${version}.exe`, + `CodeBurn-Setup-${version}.exe.blockmap`, + ] + for (const expected of required) { + const count = assets.filter(asset => asset === expected).length + if (count === 0) fail(`live release is missing ${expected}`) + if (count > 1) fail(`live release contains ${count} copies of ${expected}`) + } + if (!process.exitCode) console.log(`Live desktop release assets verified for ${version}`) +} + +try { + const tag = option('--tag', '') + const releaseAssets = option('--release-assets', '') + if (releaseAssets) { + verifyLiveRelease(tag, resolve(releaseAssets)) + } else { + const root = resolve(option('--root', rootFromModuleUrl(import.meta.url))) + const artifacts = resolve(option('--artifacts', join(root, 'app', 'release'))) + const rootVersion = packageVersion(join(root, 'package.json')) + const appVersion = packageVersion(join(root, 'app', 'package.json')) + + if (rootVersion !== appVersion) { + fail(`root version ${rootVersion} does not match app version ${appVersion}`) + } + + if (tag && tag !== `desktop-v${appVersion}`) { + fail(`${tag} does not match app version ${appVersion}`) + } + + const files = filesBelow(artifacts) + const expectedArtifacts = [ + `CodeBurn-Setup-${appVersion}.exe`, + `CodeBurn-Setup-${appVersion}.exe.blockmap`, + ] + for (const expected of expectedArtifacts) { + const count = files.filter(file => file === expected).length + if (count !== 1) fail(`expected exactly one ${expected}, found ${count}`) + } + + const installerArtifacts = files.filter(file => /^CodeBurn-Setup-.*\.exe(?:\.blockmap)?$/.test(file)) + const unexpected = installerArtifacts.filter(file => !expectedArtifacts.includes(file)) + if (unexpected.length > 0) { + fail(`unexpected Windows installer artifacts: ${unexpected.join(', ')}`) + } + + if (!process.exitCode) { + console.log(`Windows installer manifest verified for ${appVersion}`) + } + } +} catch (error) { + fail(error instanceof Error ? error.message : String(error)) +} diff --git a/app/scripts/verify-windows-installer.test.ts b/app/scripts/verify-windows-installer.test.ts new file mode 100644 index 00000000..2dd252f8 --- /dev/null +++ b/app/scripts/verify-windows-installer.test.ts @@ -0,0 +1,168 @@ +import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { spawnSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' +import { rootFromModuleUrl } from './windows-installer-paths.mjs' + +const verifier = new URL('./verify-windows-installer.mjs', import.meta.url) +const verifierPath = fileURLToPath(verifier) + +function fixture(options: { + appVersion?: string + rootVersion?: string + files?: string[] + tag?: string +} = {}) { + const root = mkdtempSync(join(tmpdir(), 'codeburn-windows-manifest-')) + const appDir = join(root, 'app') + const releaseDir = join(appDir, 'release') + mkdirSync(releaseDir, { recursive: true }) + + const appVersion = options.appVersion ?? '1.2.3' + writeFileSync(join(root, 'package.json'), JSON.stringify({ version: options.rootVersion ?? appVersion })) + writeFileSync(join(appDir, 'package.json'), JSON.stringify({ version: appVersion })) + for (const file of options.files ?? [ + `CodeBurn-Setup-${appVersion}.exe`, + `CodeBurn-Setup-${appVersion}.exe.blockmap`, + ]) { + const path = join(releaseDir, file) + mkdirSync(join(path, '..'), { recursive: true }) + writeFileSync(path, 'fixture') + } + + const args = [verifierPath, '--root', root, '--artifacts', releaseDir] + if (options.tag) args.push('--tag', options.tag) + return spawnSync(process.execPath, args, { encoding: 'utf8' }) +} + +function releaseFixture(files: string[]) { + const root = mkdtempSync(join(tmpdir(), 'codeburn-windows-release-')) + const assets = join(root, 'assets.json') + writeFileSync(assets, JSON.stringify(files)) + return spawnSync(process.execPath, [ + verifierPath, + '--tag', + 'desktop-v1.2.3', + '--release-assets', + assets, + ], { encoding: 'utf8' }) +} + +describe('Windows installer release manifest verifier', () => { + it('converts a Windows module URL into a valid drive-letter repository root', () => { + expect(rootFromModuleUrl( + 'file:///D:/a/codeburn/codeburn/app/scripts/verify-windows-installer.mjs', + true, + )).toBe('D:\\a\\codeburn\\codeburn') + }) + + it('accepts one exact installer and blockmap for matching package versions and tag', () => { + const result = fixture({ tag: 'desktop-v1.2.3' }) + + expect(result.status).toBe(0) + expect(result.stdout).toContain('Windows installer manifest verified for 1.2.3') + }) + + it('rejects a desktop tag that does not match the app version', () => { + const result = fixture({ tag: 'desktop-v1.2.4' }) + + expect(result.status).toBe(1) + expect(result.stderr).toContain('desktop-v1.2.4 does not match app version 1.2.3') + }) + + it('rejects divergent root and app versions', () => { + const result = fixture({ rootVersion: '1.2.2' }) + + expect(result.status).toBe(1) + expect(result.stderr).toContain('root version 1.2.2 does not match app version 1.2.3') + }) + + it('rejects a missing installer blockmap', () => { + const result = fixture({ files: ['CodeBurn-Setup-1.2.3.exe'] }) + + expect(result.status).toBe(1) + expect(result.stderr).toContain('expected exactly one CodeBurn-Setup-1.2.3.exe.blockmap, found 0') + }) + + it('requires installer artifacts at the documented top-level output', () => { + const result = fixture({ + files: [ + 'CodeBurn-Setup-1.2.3.exe.blockmap', + 'duplicate/CodeBurn-Setup-1.2.3.exe', + ], + }) + + expect(result.status).toBe(1) + expect(result.stderr).toContain('expected exactly one CodeBurn-Setup-1.2.3.exe, found 0') + }) + + it('rejects stale installer artifacts from another version', () => { + const result = fixture({ + files: [ + 'CodeBurn-Setup-1.2.3.exe', + 'CodeBurn-Setup-1.2.3.exe.blockmap', + 'CodeBurn-Setup-1.2.2.exe', + 'CodeBurn-Setup-1.2.2.exe.blockmap', + ], + }) + + expect(result.status).toBe(1) + expect(result.stderr).toContain('unexpected Windows installer artifacts') + }) + + it('accepts a complete live desktop release asset manifest', () => { + const result = releaseFixture([ + 'CodeBurn-1.2.3-arm64.dmg', + 'CodeBurn-1.2.3.dmg', + 'CodeBurn-1.2.3-arm64-mac.zip', + 'CodeBurn-1.2.3-mac.zip', + 'CodeBurn-1.2.3.AppImage', + 'codeburn-desktop_1.2.3_amd64.deb', + 'codeburn-desktop-1.2.3.x86_64.rpm', + 'CodeBurn-Setup-1.2.3.exe', + 'CodeBurn-Setup-1.2.3.exe.blockmap', + ]) + + expect(result.status).toBe(0) + expect(result.stdout).toContain('Live desktop release assets verified for 1.2.3') + }) + + it('rejects a live desktop release missing the Windows installer', () => { + const result = releaseFixture([ + 'CodeBurn-1.2.3-arm64.dmg', + 'CodeBurn-1.2.3.dmg', + 'CodeBurn-1.2.3-arm64-mac.zip', + 'CodeBurn-1.2.3-mac.zip', + 'CodeBurn-1.2.3.AppImage', + 'codeburn-desktop_1.2.3_amd64.deb', + 'codeburn-desktop-1.2.3.x86_64.rpm', + 'CodeBurn-Setup-1.2.3.exe.blockmap', + ]) + + expect(result.status).toBe(1) + expect(result.stderr).toContain('live release is missing CodeBurn-Setup-1.2.3.exe') + }) + + it.each([ + 'codeburn-desktop_1.2.3_amd64.deb', + 'codeburn-desktop-1.2.3.x86_64.rpm', + ])('rejects a live desktop release missing %s', missing => { + const required = [ + 'CodeBurn-1.2.3-arm64.dmg', + 'CodeBurn-1.2.3.dmg', + 'CodeBurn-1.2.3-arm64-mac.zip', + 'CodeBurn-1.2.3-mac.zip', + 'CodeBurn-1.2.3.AppImage', + 'codeburn-desktop_1.2.3_amd64.deb', + 'codeburn-desktop-1.2.3.x86_64.rpm', + 'CodeBurn-Setup-1.2.3.exe', + 'CodeBurn-Setup-1.2.3.exe.blockmap', + ] + const result = releaseFixture(required.filter(asset => asset !== missing)) + + expect(result.status).toBe(1) + expect(result.stderr).toContain(`live release is missing ${missing}`) + }) +}) diff --git a/app/scripts/windows-installer-paths.d.mts b/app/scripts/windows-installer-paths.d.mts new file mode 100644 index 00000000..7074fa43 --- /dev/null +++ b/app/scripts/windows-installer-paths.d.mts @@ -0,0 +1 @@ +export function rootFromModuleUrl(moduleUrl: string | URL, windows?: boolean): string diff --git a/app/scripts/windows-installer-paths.mjs b/app/scripts/windows-installer-paths.mjs new file mode 100644 index 00000000..b2b0eb45 --- /dev/null +++ b/app/scripts/windows-installer-paths.mjs @@ -0,0 +1,8 @@ +import { posix, win32 } from 'node:path' +import { fileURLToPath } from 'node:url' + +export function rootFromModuleUrl(moduleUrl, windows = process.platform === 'win32') { + const path = windows ? win32 : posix + const scriptPath = fileURLToPath(moduleUrl, { windows }) + return path.resolve(path.dirname(scriptPath), '..', '..') +} diff --git a/dash/src/components/UsageChart.tsx b/dash/src/components/UsageChart.tsx index 926409e8..d3c6b17d 100644 --- a/dash/src/components/UsageChart.tsx +++ b/dash/src/components/UsageChart.tsx @@ -33,7 +33,12 @@ function makeTooltip(labels: Record, fmt: (n: number) => string, {items.slice(0, 6).map((p: any) => (
- {labels[String(p.dataKey)] ?? String(p.dataKey)} + + {labels[String(p.dataKey)] ?? String(p.dataKey)} + {fmt(p.value)}
))} @@ -172,7 +177,7 @@ function GranularLines({ {series.map(item => ( - {item.label} + {item.label} ))}
diff --git a/docs/architecture.md b/docs/architecture.md index 2f7277b1..5ec39e28 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -4,27 +4,27 @@ A map of the codebase. Read this once before opening a non-trivial PR. ## Three Surfaces -CodeBurn is one Node.js CLI plus two GUI clients that shell out to it. +CodeBurn is one Node.js CLI plus three ambient GUI clients that shell out to it. ``` -+----------------------+ +-----------------+ -| mac/ (Swift) | ---> | | -+----------------------+ | src/cli.ts | -| gnome/ (JavaScript) | ---> | (the CLI) | -+----------------------+ | | - | status | - | --format | - | menubar-json | - +-----------------+ - | - v - +----------------------------+ - | session files on disk | - | (JSONL, SQLite, protobuf) | - +----------------------------+ ++---------------------------+ +-----------------+ +| mac/ (Swift) | ---> | | ++---------------------------+ | src/cli.ts | +| windows/ (Rust + React) | ---> | (the CLI) | ++---------------------------+ | | +| gnome/ (JavaScript) | ---> | status | ++---------------------------+ | --format | + | menubar-json | + +-----------------+ + | + v + +----------------------------+ + | session files on disk | + | (JSONL, SQLite, protobuf) | + +----------------------------+ ``` -The macOS menubar (`mac/`) and the GNOME extension (`gnome/`) both invoke `codeburn status --format menubar-json --period

` and parse the JSON. They do not share code with the CLI; they only depend on its output contract. +The macOS menubar (`mac/`), the Windows tray app (`windows/`), and the GNOME extension (`gnome/`) all invoke `codeburn status --format menubar-json --period

` and parse the JSON. They do not share code with the CLI; they only depend on its output contract. ## CLI (`src/`) @@ -142,9 +142,11 @@ Three caches under `~/.cache/codeburn/` (override with `CODEBURN_CACHE_DIR`): All three use atomic write (temp file + `rename`) and write with mode `0o600`. All three carry a numeric `version` field; bumping it forces a recompute next run. +The session cache (`src/session-cache.ts`) sits beside them as a directory of per-provider-month shards. A date-ranged query reads only the shards whose months can contribute a turn to that range; `CODEBURN_CACHE_SCOPE=all` turns that off and reads every shard, whatever the range. It is a read policy only — it is not part of any provider's env fingerprint, so setting or unsetting it never invalidates the cache. + ### Optimize Detectors -`src/optimize.ts` exports 14 detectors. Each returns a `WasteFinding | null`. They are composed by `runOptimize()` which collects findings, ranks them by impact, and returns them with `WasteAction` objects (paste-to-CLAUDE.md, paste-to-session-opener, prompt-now, edit shell config). +`src/optimize.ts` exports 20 detectors. Each returns a `WasteFinding | null`. They are composed by `runOptimize()` which collects findings, ranks them by impact, and returns them with `WasteAction` objects (paste-to-CLAUDE.md, paste-to-session-opener, prompt-now, edit shell config). | Detector | Line | What it catches | |---|---|---| @@ -191,7 +193,7 @@ type Provider = { `src/providers/index.ts` registers providers across two tiers: -- **Eager**: `claude`, `cline`, `codewhale`, `codebuff`, `codex`, `copilot`, `devin`, `droid`, `gemini`, `hermes`, `ibm-bob`, `kilo-code`, `kiro`, `kimi`, `lingtai-tui`, `mistral-vibe`, `mux`, `openclaw`, `open-design`, `pi`, `omp`, `qwen`, `roo-code`, `zerostack`, `grok`. Imported at module load. +- **Eager**: `claude`, `cline`, `codewhale`, `codebuff`, `codex`, `copilot`, `devin`, `droid`, `dsh`, `gemini`, `hermes`, `ibm-bob`, `kilo-code`, `kiro`, `kimi`, `lingtai-tui`, `mistral-vibe`, `mux`, `openclaw`, `open-design`, `pi`, `omp`, `qwen`, `roo-code`, `zerostack`, `grok`. Imported at module load. - **Lazy**: `antigravity`, `forge`, `goose`, `cursor`, `opencode`, `cursor-agent`, `crush`, `warp`, `vercel-gateway`, `zcode`, `zed`. Imported via dynamic `import()` so the heavy dependencies (SQLite, protobuf, network clients) do not touch users who do not have those tools installed. Both lists hit the same `getAllProviders()` aggregator. A failed lazy import is silent and excludes that provider from the run. @@ -217,6 +219,20 @@ Tests live in `mac/Tests/CodeBurnMenubarTests/` (currently `CapacityEstimatorTes The build artifact is a zipped `.app` bundle produced by `mac/Scripts/package-app.sh`. See `RELEASING.md` for how the GitHub Actions workflow uses it. +## Windows Menubar (`windows/`) + +Tauri 2 app: a Rust binary (`windows/src-tauri/`) owning the tray and the process spawning, plus a React + TypeScript popover (`windows/src/`) rendered in a WebView2 window. Design tokens come from `windows/tokens.json`, the same file `mac/` reads at build time, so both products render as one. + +- `src-tauri/src/lib.rs` builds the tray, positions the popover against the taskbar edge, and registers the `#[tauri::command]` surface the frontend calls. +- `src-tauri/src/cli.rs` resolves and spawns the CLI. Only absolute `PATH` directories are searched (an empty entry from `;;` would otherwise resolve against the current directory), `CODEBURN_BIN` is allowlisted, and Windows system tools are spawned by absolute `%SystemRoot%\System32` path because `CreateProcess` searches the current directory first. `MIN_CLI_VERSION` gates the whole app; below it the popover shows a setup screen. +- `src-tauri/src/plan.rs` ports the Claude quota view. Like the macOS `ClaudeCredentialStore`, it never spends Claude's single-use refresh token; on a 401 it re-reads Claude's own credential file for a token Claude Code has already rotated. +- `src-tauri/src/tray_badge.rs` renders today's spend into a second tray icon, since Windows has no menubar title. +- `src/App.tsx` owns the payload cache, the CLI gate, and the refresh cadence, which follows popover visibility the way `mac/`'s `RefreshCadence.swift` does. + +`cargo test` covers the PATH filter and the version gate. `windows/DEVELOPMENT.md` has the build, security, and release details; CI is `.github/workflows/windows-menubar-ci.yml` and releases go out on `windows-v*` tags. + +The Linux (ksni) paths in the same crate are kept compiling but are experimental and unreleased; `gnome/` is the shipping Linux surface. + ## GNOME Extension (`gnome/`) Plain JavaScript, no bundler. Targets GNOME Shell 45-50 (`metadata.json`). diff --git a/docs/optimize.md b/docs/optimize.md new file mode 100644 index 00000000..6cd23bbd --- /dev/null +++ b/docs/optimize.md @@ -0,0 +1,139 @@ +# optimize + +`codeburn optimize` scans your Claude Code sessions and your `~/.claude/` setup, reports what is +costing tokens without earning them, and grades the setup A to F. + +## What it scans + +- **Session transcripts** for the selected period: tool calls, per-call token usage, turn retries, + per-session cost, and the block each session opens with. This is where re-reads, junk directory + reads, low read:edit ratios, warmup overhead, retries, context pasted into session after session, + and expensive or context-heavy sessions come from. +- **Your configuration**: `~/.claude.json`, user and project `settings.json` / `settings.local.json`, + `.mcp.json`, `CLAUDE.md` (including `@`-imports), and the `skills/`, `agents/`, `commands/` + directories. This is where unused MCP servers, MCP deferral gaps, ghost skills/agents/commands, + the bash output cap, and oversized `CLAUDE.md` files come from. + +Nothing is written during a scan. Only `--apply` writes. + +## The three classes + +Every finding carries a `class`, and both the CLI and the apps group by it: + +| Class | Header | Meaning | +|---|---|---| +| `fix` | Fix now (apply-able) | CodeBurn can make this change for you: `codeburn optimize --apply` | +| `nudge` | Habits | Behavioural. Nothing to edit; the fix is how you drive the next session | +| `keep` | FYI | Informational. The cost may well be justified; decide for yourself | + +A finding is `fix` only when a plan can actually be built for that instance. The same detector can +report a `fix` in one run and a `nudge` in another: `mcp-deferral-off` is appliable when the cause is +an `ENABLE_TOOL_SEARCH` override in a settings file, but manual when the cause is Vertex AI policy, +an outdated Claude Code, or an override that lives in your shell profile. + +## What `--apply` may write + +`--apply` builds a plan per finding, shows you the exact files it will touch, and asks before +writing. `--dry-run` prints the plan and stops. + +| Finding | File it edits | +|---|---| +| `unused-mcp`, `mcp-low-coverage` | `~/.claude.json`, project `.mcp.json` / `settings.json` (removes the server entry) | +| `mcp-project-scope` | moves a global server entry into the keeper project's `.mcp.json` | +| `mcp-deferral-off` | the settings file carrying the `ENABLE_TOOL_SEARCH` override | +| `mcp-alwaysload-hygiene` | the config files carrying `"alwaysLoad": true` | +| `mcp-defer-threshold` | the settings file carrying the `auto:N` threshold | +| `unused-agents`, `unused-skills`, `unused-commands` | moves the files into `~/.claude//.archived/` | +| `bash-output-cap` | appends a marker block to `~/.zshrc` / `~/.bashrc` | +| `read-edit-ratio`, `build-folder-reads` | appends a marker block to the current project's `CLAUDE.md` | + +Every write is backed up and journaled first: + +```bash +codeburn act list # every change CodeBurn has made +codeburn act undo # restore the original files +codeburn act undo --last +``` + +Undo refuses if a file changed after the apply, unless you pass `--force`. + +### The `--yes` CLAUDE.md guardrail + +`--apply --yes` skips the prompt for every plan except `CLAUDE.md` rule blocks. Those land in the +`CLAUDE.md` of whatever directory you happen to be in, so a blanket `--yes` from an unrelated +directory would write advice into the wrong project. To apply one anyway, use the interactive picker +or name it explicitly: + +```bash +codeburn optimize --apply --only read-edit-ratio +``` + +## After you apply + +Applying a fix is a claim, so CodeBurn checks it. Every `codeburn optimize` run re-measures the +fixes still in place and prints them under `Applied fixes`, one line each: + +| Line | Verdict | Meaning | +|---|---|---| +| `✓ unused-skills (7d ago): est. 300.0K -> measured 280.0K` | worked | at least 70% of the estimate showed up in your sessions | +| `~ mcp-defer-threshold (5d ago): est. 600.0K -> measured 420.0K (-30% vs estimate)` | partial | it helped, but under its estimate | +| `✗ bash-output-cap (6d ago): est. 41.0K -> measured 0 - did not help. Revert: codeburn act undo 3f2a1c04` | no-effect | no measured reduction at all | +| `… mcp-remove (1d ago): measuring, check back after 3 days` | measuring | too young, or the change has not taken effect in a session yet | + +The estimate shown is the at-apply estimate scaled to the measured window, so the two numbers are +comparable. Both come from the same reconciliation `codeburn act report` prints — there is one set of +numbers, not two — and they are **measured**: provider-counted usage over the post-apply window. +Anything that cannot be measured (no baseline captured, a fix you reverted by hand, a +correlation-only kind like `guard-install`) stays on the `measuring` line with the reason, never a +claimed saving. + +`--format json` carries the same list as `appliedFixes[]`, and the section appears in the dashboard +TUI and the desktop app. + +### `--auto-revert` + +```bash +codeburn optimize --auto-revert +``` + +Off by default. It undoes exactly the fixes whose verdict is `no-effect`, through the same code path +as `codeburn act undo` (backups restored, drift check applied, the revert journaled). It never +touches a `partial` or still-measuring fix, and it never auto-reverts a `claude-md-rule` — those land +in whatever project directory you were in, the same reason `--yes` skips them, so it prints the undo +command and leaves the file alone. + +## measured vs estimated + +Each finding also carries a `basis`, printed next to its savings and summarised in the header as +`N measured · M estimated`: + +- **measured** — the token number is summed from provider-counted usage on your own calls. Today + that is `context-heavy-sessions` and `cost-outliers`. +- **estimated** — the token number comes from a model: a per-tool schema size, a per-line `CLAUDE.md` + cost, an average read size, a recovery fraction applied to real turn tokens. A detector that mixes + counted tokens with a model counts as estimated. + +Sessions whose cost the provider never reported (Kiro, Cursor, some Cline sessions price from +modelled token counts) are kept out of the `cost-outliers` peer comparison, so a modelled cost is +never called an outlier against provider-reported ones. When a provider only ever estimates, the +comparison falls back to those sessions and the finding reports itself as `estimated`. + +In `--format json`, `summary.measuredSavingsUSD` is the share of `summary.potentialSavingsCostUSD` +that comes from measured findings. + +## Reading the health grade + +Health starts at 100 and loses points per finding: 15 for a high-impact one, 7 for medium, 3 for low. +The total penalty is capped at 80, so a long tail of small findings cannot sink the score to zero on +its own. The grade is a band over that score: + +| Grade | Score | +|---|---| +| A | 90-100 | +| B | 75-89 | +| C | 55-74 | +| D | 30-54 | +| F | below 30 | + +The grade rates your setup, not your spending: an expensive month with a clean configuration still +scores an A. diff --git a/docs/providers/README.md b/docs/providers/README.md index 971ae2b4..938d5425 100644 --- a/docs/providers/README.md +++ b/docs/providers/README.md @@ -18,6 +18,7 @@ For the architectural picture, see `../architecture.md`. | [Copilot](copilot.md) | JSONL + SQLite (OTel) + Nitrite .db (JetBrains) | `src/providers/copilot.ts` | `tests/providers/copilot.test.ts` | | [Devin](devin.md) | JSON + SQLite enrichment | `src/providers/devin.ts` | `tests/providers/devin.test.ts` | | [Droid](droid.md) | JSONL | `src/providers/droid.ts` | `tests/providers/droid.test.ts` | +| [DeepSeek Harness](dsh.md) | JSONL (zstd frames) | `src/providers/dsh.ts` | `tests/providers/dsh.test.ts` | | [Gemini](gemini.md) | JSON / JSONL | `src/providers/gemini.ts` | none | | [Hermes Agent](hermes.md) | SQLite | `src/providers/hermes.ts` | `tests/providers/hermes.test.ts` | | [IBM Bob](ibm-bob.md) | JSON | `src/providers/ibm-bob.ts` | `tests/providers/ibm-bob.test.ts` | diff --git a/docs/providers/copilot.md b/docs/providers/copilot.md index c3b05338..1496281a 100644 --- a/docs/providers/copilot.md +++ b/docs/providers/copilot.md @@ -41,7 +41,8 @@ instead of trying to dedupe across stores. wrong-schema, OTel is skipped and the JSONL/transcript sources are used as a fallback. - **Durable cache (monotonic totals).** Copilot is marked `durableSources`: OTel-derived cache entries are never evicted when VS Code prunes old spans from the DB, so - month-to-date totals do not drop as the DB rotates. Entries age out after 90 days. + month-to-date totals do not drop as the DB rotates. Orphaned entries age out after + 90 days; sources still present in discovery remain cached regardless of call age. - **Upgrade note.** The first run after upgrading to the OTel version bumps the copilot parse version, which discards the prior copilot cache. Spans already pruned from the DB before the upgrade cannot be recovered, so monotonicity starts from the upgrade point, diff --git a/docs/providers/dsh.md b/docs/providers/dsh.md new file mode 100644 index 00000000..d3bb81ac --- /dev/null +++ b/docs/providers/dsh.md @@ -0,0 +1,71 @@ +# DeepSeek Harness (dsh) + +DeepSeek's open-source agent harness (`dsh`, npm `@deepseek-ai/dsh`). Unrelated to the [CodeWhale](codewhale.md) provider, which reads the DeepSeek desktop app. + +- **Source:** `src/providers/dsh.ts` +- **Loading:** eager (`src/providers/index.ts`) +- **Test:** `tests/providers/dsh.test.ts` + +## Where it reads from + +| Level | Env var | Default | +|---|---|---| +| sessions | — | `/sessions` | +| root | `DSH_HOME` | `~/.dsh` | + +An empty `DSH_HOME` is treated as unset. `probeRoots()` reports the resolved sessions dir, so `codeburn doctor` distinguishes "dsh not installed" from "`DSH_HOME` pointing somewhere empty". + +## Storage format + +``` +sessions/----// + session.jsonl.zstd default (compression: zstd) + session.jsonl when compression: none +``` + +Both variants are read; a session directory never holds both. The log is append-only JSONL whose first line is the session header: + +```jsonc +{ "type": "session", "version": 0, "id": "...", "createdAt": 1783352050748, + "cwd": "/home/u/proj", "parentSession": "...", "seedLength": 3, "delegationDepth": 0 } +``` + +`cwd` becomes `projectPath` / `workingDirectory` (git-repo attribution) and its last segment the project name. + +Every later line is one event `{ type, seq, time, data }`. The parser reads: + +| Event | Used for | +|---|---| +| `turn/start` | current turn number | +| `user/message` | the turn's preview, when `data.source.kind === 'user'` | +| `request/header` | `data.header.config.model` — the model for steps that follow | +| `assistant/chunk` with `chunk.type === 'usage'` | streamed usage sample for `(turn, step)` | +| `assistant/message` | final usage for `(turn, step)`, plus `data.message.source.model` | +| `tool/call` | tool names, bash commands, skill names | + +One parsed call per `(turn, step)` — one model call and the tools it requested. Dedup key: `dsh:::`. + +`.zstd` logs are a concatenation of **independent** zstd frames, one per write batch, so they are decoded frame by frame behind a structural frame scan ported from `@deepseek-ai/dsh-session-persistence-jsonl`. Needs Node 22.15+ for `zlib.zstdDecompressSync`; below that dsh is skipped with a notice instead of counted as $0. + +## Caching + +None at the provider level; the log file is the cached source path and the normal parser/cache layers apply. Cache invalidates on `DSH_HOME` (`PROVIDER_ENV_VARS`) and on parser changes (`PROVIDER_PARSE_VERSIONS`). + +## Quirks + +- **DSH is a developer preview.** `SESSION_FORMAT_VERSION` is pinned at `0` with "no compatibility implied" upstream, and breaking changes are expected. The parser reads version `0` only and skips a log stamped with anything else, with a notice — reading a bumped format under today's assumptions would report confident wrong numbers. **A version bump upstream means this parser needs updating, not just relaxing the check.** +- **The JSONL backend only.** DSH also ships an opt-in SQLite persistence backend (`@deepseek-ai/dsh-session-persistence-sqlite`); it is not the default and is not read. +- **DSH records tokens, never dollars.** `usage` is `{ inputTokens, outputTokens, cacheReadTokens?, cacheWriteTokens?, reasoningTokens? }` with no cost field, so every call is priced from the shared tables. Reasoning bills at the output rate (same as Gemini and Hermes): `outputTokens + reasoningTokens` goes into `calculateCost`, while the two stay separate on the emitted call. Tokens are the provider's own exact counts, so `costIsEstimated` stays false. +- **`assistant/message` usage wins over the `assistant/chunk` sample** for the same `(turn, step)` — the two are adjacent reports of one API call, not two calls. A late chunk never overwrites a final report, so the two are never summed. +- **The model comes from the message, not the request.** `data.message.source.model` is what actually served the step; `request/header` only describes the request DSH was about to make, and is the fallback when a message names no model. The `provider` field there (`deepseek-official`) is the upstream LLM route, not the tool — the codeburn provider name is always `dsh`. +- **A forked session's log replays its parent's events.** The header's `parentSession` + `seedLength` mark that prefix; codeburn parses the parent's own log as its own session, so events with `seq < seedLength` are skipped to avoid billing the same calls twice. +- **`user/message` also carries agent-injected context** (runtime snapshots, skill bodies, file-change notices) under `source.kind: 'plugin'`. Only `kind: 'user'` messages become the preview. +- **Delta chunks are packed.** Runs of streamed deltas are stored as `text-chunks` / `reasoning-chunks` / `tool-call-chunks` storage rows rather than one event per line. They carry no usage and no tool identity the `tool/call` event lacks, so they are ignored — as is any event type the parser does not know. +- **A torn final zstd frame is ignored.** A crashed writer leaves an incomplete trailing frame; the complete frames before it parse normally. A structurally corrupt file is skipped whole with a notice rather than throwing. + +## When fixing a bug here + +1. Reproduce with a minimal session dir: `sessions/--proj--//session.jsonl` (uncompressed is easiest to hand-write). +2. `tests/fixtures/dsh/bash-tool-turn.jsonl` is the upstream `examples/acp-agent/tests/snapshots/bash-tool-turn/session.jsonl` snapshot with its template placeholders filled in — refresh it from the DSH repo when the format moves. +3. Run `tests/providers/dsh.test.ts`. +4. `.zstd` fixtures must compress **each batch separately**; one `zstdCompressSync` over the whole file is a single-frame layout DSH never writes. diff --git a/docs/providers/grok.md b/docs/providers/grok.md index 4bed0ee8..56adec69 100644 --- a/docs/providers/grok.md +++ b/docs/providers/grok.md @@ -4,7 +4,7 @@ Grok Build, xAI's coding CLI. Sessions use the `grok-build` model by default. - **Source:** `src/providers/grok.ts` - **Loading:** eager (`src/providers/index.ts`) -- **Test:** `tests/providers/grok.test.ts` +- **Test:** `tests/grok-parser-pipeline.test.ts`, `tests/providers/grok.test.ts` ## Where it reads from @@ -13,19 +13,23 @@ Grok Build, xAI's coding CLI. Sessions use the `grok-build` model by default. ## Storage format -JSON + JSONL. `summary.json` holds the session id, cwd, timestamps, and `current_model_id`. `signals.json` holds `modelsUsed`, `toolsUsed`, and `contextTokensUsed`. `updates.jsonl` is the ACP log: each streamed chunk carries `params._meta.totalTokens` (running context size) and `params._meta.promptId` (one per turn). +JSON + JSONL. `summary.json` holds the session id, cwd, timestamps, and `current_model_id`. `signals.json` holds `modelsUsed`, `toolsUsed`, and `contextTokensUsed`. `updates.jsonl` is the ACP log: streamed chunks carry `params._meta.totalTokens` (running context size) and `params._meta.promptId` (one per turn); newer CLI versions also append `params.update.sessionUpdate: "turn_completed"` with snake_case `prompt_id` and a provider-recorded `usage` object. ## Token model -**Estimated.** Grok does not log billable input/output tokens. It only records the running context fill (`totalTokens` per chunk, and `contextTokensUsed` in signals). The parser reconstructs a rough estimate from the per-turn `totalTokens` curve: input is the context entering each turn, output is the context growth during it. The result is flagged `costIsEstimated` and re-priced with `calculateCost`. +**Authoritative when available.** A `turn_completed` record reports the whole input side in `inputTokens` and the whole output side in `outputTokens`. `cachedReadTokens` is treated as a subset of input; `cacheCreationTokens` is treated as another input subset by analogy because the record exposes no separate fresh-input field, with any per-record violation clamped locally. The top-level totals are the accounting basis. `modelUsage` is retained only as a model-attribution signal; multi-model attribution is deliberately out of scope, so one session uses one selected model's rate. `reasoningTokens` is clamped to that record's reported output before the parser emits exclusive output plus reasoning, preserving the reported total through the cache pipeline. These counts are provider-recorded, so `costIsEstimated` is false for fully covered sessions while CodeBurn applies its own pricing table. `costUsdTicks` is ignored because its scale is undocumented. + +**Estimated fallback.** Older sessions without any valid `turn_completed.usage` record use the running context fill (`totalTokens` per chunk) and the existing compaction-aware per-turn curve. That path remains flagged `costIsEstimated`; a completed record is never blended with the heuristic. + +**Mixed sessions undercount.** The choice between the two paths is per session, not per turn. If a session has at least one usable `turn_completed` record, the whole session is billed from the summed records and any turn WITHOUT a record contributes nothing at all - its tokens are dropped, not estimated, so such a session reads low. The row is marked `costIsEstimated: true` rather than claiming full provider coverage. This is deliberate: blending the heuristic into real records would reintroduce the roughly 5x output over-count this parser exists to remove. It happens when a session straddles a CLI upgrade or a run dies before writing its last record; an open turn is filled by a later parse once it writes one, pre-upgrade turns never are. Measured on a 568-session corpus, 1 turn out of 566 was uncovered. ## Pricing -`grok-build` is aliased to `grok-build-0.1` in `src/models.ts`, so it prices off the bundled LiteLLM fallback. Note that xAI's published API rate and the LiteLLM fallback figure differ, so treat the cost as an estimate and verify against your xAI usage console. +`grok-build` is aliased to `grok-build-0.1` in `src/models.ts`, so it prices off the bundled LiteLLM fallback. If `usage.modelUsage` contains a model id that CodeBurn can price, that id is preferred; when the real id is not priced yet, the existing summary/signals model is retained so a known alias does not become a $0 row. This is a single attribution choice for the session, not a per-model accounting split; multi-model rate attribution is a follow-up. CodeBurn still does not use Grok's undocumented `costUsdTicks`. ## Caching -None. +Authoritative records expose cache-read and cache-creation token counts. The legacy estimate has no cache-creation signal and keeps its inferred cache-read count. ## Deduplication @@ -33,7 +37,8 @@ Per `grok:::`. ## Quirks -- **No cache or output/tool-token split.** Only context fill is available, so cache fields are `0` and the cost is an estimate (likely an upper bound, since re-sent context is cached server-side and not exposed in the session files). +- **Two token paths.** Completed turns carry provider usage; sessions from older CLI versions have only the context curve and therefore remain estimates (likely an upper bound, since re-sent context is cached server-side and not exposed in those files). +- **A turn with no `turn_completed` record is dropped inside an otherwise-covered session** (see Token model). The session still reports, marked estimated, but reads low by those turns. - **No bash-command capture.** Tool names come from `signals.toolsUsed`; per-command bash text is not extracted, so `bashCommands` is empty. - **Whole-session timestamp.** Spend is attributed to `updated_at`, since the context curve is cumulative. - **Subscription vs API.** Grok Build runs via either a metered xAI API account (tiered) or a SuperGrok subscription; the session files do not record which. @@ -41,5 +46,5 @@ Per `grok:::`. ## When fixing a bug here 1. Discovery: check the `sessions///` walk and the `GROK_HOME` resolution. -2. Token estimate: see `estimateTokens` (groups `updates.jsonl` by `promptId`). +2. Token accounting: see `parseUpdates` (deduplicates `turn_completed` by snake_case `prompt_id`, then falls back to grouping streamed chunks by camelCase `_meta.promptId`). 3. Add a fixture-format session under `tests/providers/grok.test.ts`; do not mock the filesystem. diff --git a/mac/Sources/CodeBurnMenubar/AppStore.swift b/mac/Sources/CodeBurnMenubar/AppStore.swift index 005a7531..f8ff5bab 100644 --- a/mac/Sources/CodeBurnMenubar/AppStore.swift +++ b/mac/Sources/CodeBurnMenubar/AppStore.swift @@ -1053,7 +1053,7 @@ final class AppStore { return false } catch { guard gen == claudeRefreshGen else { return false } - subscriptionError = sanitizeForUI(String(describing: error)) + subscriptionError = sanitizeForUI(error.localizedDescription) subscriptionLoadState = .failed return false } @@ -1064,11 +1064,18 @@ final class AppStore { /// account or tier) starts clean. capacityEstimates and the snapshot store /// would otherwise contaminate "Based on last cycle" projections. func disconnectSubscription() { - ClaudeSubscriptionService.disconnect() + let result = ClaudeSubscriptionService.disconnect() // Bump the generation token so any in-flight refreshSubscription that // resumes after this point detects the disconnect and discards its // result instead of re-populating the cleared state. claudeRefreshGen &+= 1 + guard result.isSuccess else { + // Nothing was removed, so nothing is disconnected. Leave the + // connected state exactly as it was — the bootstrap flag is still + // set, Disconnect stays available, and the banner says to retry. + subscriptionError = "Could not fully remove the local Claude credential cache. Disconnect again to retry." + return + } subscription = nil subscriptionError = nil subscriptionLoadState = .notBootstrapped @@ -1091,7 +1098,7 @@ final class AppStore { } catch let err as CodexSubscriptionService.FetchError { applyCodexFetchError(err) } catch { - codexError = sanitizeForUI(String(describing: error)) + codexError = sanitizeForUI(error.localizedDescription) codexLoadState = .failed } } @@ -1124,15 +1131,21 @@ final class AppStore { return false } catch { guard gen == codexRefreshGen else { return false } - codexError = sanitizeForUI(String(describing: error)) + codexError = sanitizeForUI(error.localizedDescription) codexLoadState = .failed return false } } func disconnectCodex() { - CodexSubscriptionService.disconnect() + let result = CodexSubscriptionService.disconnect() codexRefreshGen &+= 1 + guard result.isSuccess else { + // Nothing removed means nothing disconnected; keep state intact so + // Disconnect stays available for a retry. + codexError = "Could not fully remove the local Codex credential cache. Disconnect again to retry." + return + } codexUsage = nil codexError = nil codexLoadState = .notBootstrapped @@ -1176,7 +1189,7 @@ final class AppStore { applyKimiFetchError(err) } catch { guard gen == kimiRefreshGen else { return } - kimiError = sanitizeForUI(String(describing: error)) + kimiError = sanitizeForUI(error.localizedDescription) kimiLoadState = .failed } } @@ -1210,7 +1223,7 @@ final class AppStore { return false } catch { guard gen == kimiRefreshGen else { return false } - kimiError = sanitizeForUI(String(describing: error)) + kimiError = sanitizeForUI(error.localizedDescription) kimiLoadState = .failed return false } diff --git a/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift b/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift index 63144f76..b0400d6e 100644 --- a/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift +++ b/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift @@ -2,6 +2,7 @@ import Foundation import SwiftUI import AppKit import Observation +import ServiceManagement private let refreshIntervalSeconds: UInt64 = 30 private let forceRefreshWatchdogSeconds: TimeInterval = 90 @@ -281,34 +282,19 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSM let key = "codeburn.loginItemRegistered" guard !UserDefaults.standard.bool(forKey: key) else { return } - let appPath = Bundle.main.bundlePath - let script = "tell application \"System Events\" to make login item at end with properties {path:\(appleScriptStringLiteral(appPath)), hidden:false}" - - let process = Process() - process.launchPath = "/usr/bin/osascript" - process.arguments = ["-e", script] - process.standardOutput = FileHandle.nullDevice - process.standardError = FileHandle.nullDevice - + // Registers in-process. The old path told System Events to make the login + // item, which made macOS ask for Automation access on first launch (#1026). + // No AppleScript fallback: a failure here must not bring that prompt back. do { - try process.run() - process.waitUntilExit() - if process.terminationStatus == 0 { - UserDefaults.standard.set(true, forKey: key) + if SMAppService.mainApp.status != .enabled { + try SMAppService.mainApp.register() } + UserDefaults.standard.set(true, forKey: key) } catch { - NSLog("CodeBurn: Login item registration failed: \(error)") + NSLog("CodeBurn: login item registration failed: \(error.localizedDescription)") } } - private func appleScriptStringLiteral(_ value: String) -> String { - var escaped = value.replacingOccurrences(of: "\\", with: "\\\\") - escaped = escaped.replacingOccurrences(of: "\"", with: "\\\"") - escaped = escaped.replacingOccurrences(of: "\r", with: "") - escaped = escaped.replacingOccurrences(of: "\n", with: "") - return "\"\(escaped)\"" - } - private var lastRefreshTime: Date = .distantPast /// Anchors the shallow provider-root snapshot only after a complete usage /// refresh succeeds. It sits beside the cadence anchor so a failed fetch diff --git a/mac/Sources/CodeBurnMenubar/Data/ClaudeCredentialStore.swift b/mac/Sources/CodeBurnMenubar/Data/ClaudeCredentialStore.swift index 002e861e..a5a7e8f7 100644 --- a/mac/Sources/CodeBurnMenubar/Data/ClaudeCredentialStore.swift +++ b/mac/Sources/CodeBurnMenubar/Data/ClaudeCredentialStore.swift @@ -16,9 +16,9 @@ import Security /// the refresh endpoint. If the CLI hasn't rotated yet we report a /// transient staleness (`sourceTokenStale`) and recover on its next use. /// -/// 3. **In-memory + file cache** so back-to-back reads in the same refresh +/// 3. **In-memory + Keychain cache** so back-to-back reads in the same refresh /// cycle don't re-hit the source, and we keep serving the last good token -/// across launches. +/// across launches without a plaintext Application Support file. enum ClaudeCredentialStore { private static let bootstrapCompletedKey = "codeburn.claude.bootstrapCompleted" private static let inMemoryTTL: TimeInterval = 5 * 60 @@ -28,12 +28,46 @@ enum ClaudeCredentialStore { private static let credentialsRelativePath = ".claude/.credentials.json" private static let maxCredentialBytes = 64 * 1024 - /// Legacy local cache file. New writes use the macOS Keychain; this path is + /// Legacy local cache file under Application Support. Migration to the + /// CodeBurn-namespaced Keychain item is staged behind an injectable seam. private static let cacheFilename = "claude-credentials.v1.json" + static let ourKeychainService = CodeBurnKeychainIdentity.claudeService + static let ourKeychainAccount = CodeBurnKeychainIdentity.account + private static let lock = NSLock() private nonisolated(unsafe) static var memoryCache: CachedRecord? + // MARK: - Injectable seams (tests + staged Keychain migration) + + /// Override Application Support root. Nil uses the real user domain. + nonisolated(unsafe) static var applicationSupportDirectoryOverride: URL? + /// Override home for Claude CLI credential discovery. Nil uses the real home. + nonisolated(unsafe) static var homeDirectoryOverride: URL? + /// Override defaults used for bootstrap flags. + nonisolated(unsafe) static var userDefaultsOverride: UserDefaults? + /// Keychain backend. Production uses Live; tests inject InMemory. + nonisolated(unsafe) static var keychainCache: any KeychainCredentialCaching = LiveKeychainCredentialCache() + + static func resetTestSeams() { + applicationSupportDirectoryOverride = nil + homeDirectoryOverride = nil + userDefaultsOverride = nil + keychainCache = LiveKeychainCredentialCache() + lastCacheDeleteResult = nil + unlinkLegacyOverride = nil + tightenLegacyOverride = nil + lock.withLock { memoryCache = nil } + } + + private static var defaults: UserDefaults { + userDefaultsOverride ?? .standard + } + + private static var homeDirectory: URL { + homeDirectoryOverride ?? FileManager.default.homeDirectoryForCurrentUser + } + struct CachedRecord { let record: CredentialRecord let cachedAt: Date @@ -88,18 +122,42 @@ enum ClaudeCredentialStore { /// True once the user has explicitly connected (clicked Connect in the Plan /// tab AND we successfully read their credentials). Persists across launches. static var isBootstrapCompleted: Bool { - get { UserDefaults.standard.bool(forKey: bootstrapCompletedKey) } - set { UserDefaults.standard.set(newValue, forKey: bootstrapCompletedKey) } + get { defaults.bool(forKey: bootstrapCompletedKey) } + set { defaults.set(newValue, forKey: bootstrapCompletedKey) } } /// Reset bootstrap state. Used when the user explicitly wants to disconnect - /// or when the refresh token has been revoked terminally. - static func resetBootstrap() { + /// or when the refresh token has been revoked terminally. Deletion failures + /// are recorded on `lastCacheDeleteResult` — callers must not claim the + /// local copy is gone when `isSuccess` is false. + @discardableResult + static func resetBootstrap() -> CacheDeleteResult { lock.withLock { memoryCache = nil } - deleteOurCache() - isBootstrapCompleted = false + let result = deleteOurCache() + lastCacheDeleteResult = result + // A failed Keychain delete must not pretend the provider is disconnected. + // Clearing the flag hides Disconnect and orphans the remaining item. + if result.isSuccess { + isBootstrapCompleted = false + } + return result } + /// Outcome of deleting CodeBurn-owned Claude cache material. + struct CacheDeleteResult: Equatable { + var keychainDeletedOrAbsent: Bool + var legacyDeletedOrAbsent: Bool + var isSuccess: Bool { keychainDeletedOrAbsent && legacyDeletedOrAbsent } + } + + /// Last disconnect/cleanup result. Nil until the first delete attempt. + nonisolated(unsafe) static var lastCacheDeleteResult: CacheDeleteResult? + + /// Test seam: force legacy unlink to throw so we can assert the 0600 repair. + nonisolated(unsafe) static var unlinkLegacyOverride: ((URL) throws -> Void)? + nonisolated(unsafe) static var tightenLegacyOverride: ((URL) throws -> Void)? + + // MARK: - Public API /// User-initiated entry point. Reads from Claude's source (PROMPTS for the @@ -124,7 +182,19 @@ enum ClaudeCredentialStore { if let cached = lock.withLock({ memoryCache }), cached.isFresh { return cached.record } - if let stored = try readOurCache() { + let fetched: CredentialRecord? + do { + fetched = try readOurCache() + } catch let err as KeychainCredentialCacheError { + // A locked/denied keychain means "can't look right now", not "the + // item is gone". Serve the last known token and leave the bootstrap + // flag alone so we don't silently disconnect the user. + if case .unavailable = err { + return lock.withLock { memoryCache }?.record + } + throw err + } + if let stored = fetched { cacheInMemory(stored) return stored } @@ -190,7 +260,7 @@ enum ClaudeCredentialStore { } private static func readClaudeFile() throws -> CredentialRecord? { - let url = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(credentialsRelativePath) + let url = homeDirectory.appendingPathComponent(credentialsRelativePath) guard FileManager.default.fileExists(atPath: url.path) else { return nil } let data = try SafeFile.read(from: url.path, maxBytes: maxCredentialBytes) return try parseClaudeBlob(data: sanitizeClaudeBlob(data)) @@ -305,37 +375,207 @@ enum ClaudeCredentialStore { } } - // MARK: - Local cache file (no keychain involvement) + // MARK: - Local cache (injectable Application Support + Keychain seam) - private static func cacheFileURL() -> URL { - let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first - ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support") + static func cacheFileURL() -> URL { + let support = applicationSupportDirectoryOverride + ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first + ?? homeDirectory.appendingPathComponent("Library/Application Support") return support .appendingPathComponent("CodeBurn", isDirectory: true) .appendingPathComponent(cacheFilename) } + /// Production-used write path. Persists to the CodeBurn-namespaced Keychain + /// item. Claude never stores a refresh token in this cache. After a verified + /// Keychain read-back, any legacy JSON is unlinked (not "securely erased"). + static func writeOurCache(record: CredentialRecord) throws { + let persisted = encodePersisted(record) + let data = try JSONEncoder().encode(persisted) + try keychainCache.upsert( + service: ourKeychainService, + account: ourKeychainAccount, + data: data + ) + try verifyKeychainMatches(persisted) + tryUnlinkLegacyAfterVerifiedKeychain() + } + + /// Cache shape stored in Keychain — intentionally omits refreshToken. + struct PersistedCacheRecord: Codable, Equatable { + let accessToken: String + let expiresAt: Date? + let rateLimitTier: String? + } + + private static func encodePersisted(_ record: CredentialRecord) -> PersistedCacheRecord { + PersistedCacheRecord( + accessToken: record.accessToken, + expiresAt: record.expiresAt, + rateLimitTier: record.rateLimitTier + ) + } + + private static func decodePersisted(_ data: Data) -> CredentialRecord? { + if let persisted = try? JSONDecoder().decode(PersistedCacheRecord.self, from: data) { + return CredentialRecord( + accessToken: persisted.accessToken, + refreshToken: nil, + expiresAt: persisted.expiresAt, + rateLimitTier: persisted.rateLimitTier + ) + } + // Historical blobs may still include refreshToken; drop it on read. + if let legacy = try? JSONDecoder().decode(CredentialRecord.self, from: data) { + return CredentialRecord( + accessToken: legacy.accessToken, + refreshToken: nil, + expiresAt: legacy.expiresAt, + rateLimitTier: legacy.rateLimitTier + ) + } + return nil + } + + private static func verifyKeychainMatches(_ expected: PersistedCacheRecord) throws { + guard let data = try keychainCache.read(service: ourKeychainService, account: ourKeychainAccount), + let roundTrip = decodePersisted(data), + encodePersisted(roundTrip) == expected + else { + throw StoreError.keychainWriteFailed(-1) + } + } + + /// Serializes migrate + unlink across processes so two menubar instances (or the + /// CLI) cannot race on the same legacy file. Only `SafeFile.Error` from acquiring + /// the lock is tolerated — `readOurCacheLocked` never lets one escape, because + /// `readLegacyFile` swallows its own read failures. private static func readOurCache() throws -> CredentialRecord? { + do { + return try SafeFile.withExclusiveLock(at: cacheFileURL().path + ".lock") { + try readOurCacheLocked() + } + } catch is SafeFile.Error { + return try readOurCacheLocked() + } + } + + private static func readOurCacheLocked() throws -> CredentialRecord? { + if let data = try keychainCache.read(service: ourKeychainService, account: ourKeychainAccount), + let record = decodePersisted(data) { + // The Keychain item can predate the legacy file by a long way — this + // service name has been in use since May 2026, so an upgrading install + // can hold a months-old item beside a file the old build wrote today. + // Adopt whichever expires later before unlinking anything. + if let fresher = legacyRecordIfNewer(than: record) { + try? writeOurCache(record: fresher) + return fresher + } + // Rewrite historical Claude blobs once without refreshToken. + if let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + object.keys.contains("refreshToken") { + try? writeOurCache(record: record) + } else { + tryUnlinkLegacyAfterVerifiedKeychain() + } + return record + } + + return try migrateLegacyFileIfPresent() + } + + /// Reads the legacy file only to compare recency. Returns it when it expires + /// strictly later than `record`; nil when absent, unreadable, or not newer. + private static func legacyRecordIfNewer(than record: CredentialRecord) -> CredentialRecord? { + guard let legacy = readLegacyFile() else { return nil } + guard let legacyExpiry = legacy.expiresAt else { return nil } + guard let currentExpiry = record.expiresAt else { return legacy } + return legacyExpiry > currentExpiry ? legacy : nil + } + + /// Secure-read + decode the legacy JSON, dropping any refreshToken it holds. + /// Returns nil on symlink / ownership / chmod / decode failure, leaving the + /// file in place. + private static func readLegacyFile() -> CredentialRecord? { let url = cacheFileURL() guard FileManager.default.fileExists(atPath: url.path) else { return nil } - let data = try SafeFile.read(from: url.path, maxBytes: maxCredentialBytes) - guard let record = try? JSONDecoder().decode(CredentialRecord.self, from: data) else { return nil } - return record + guard let data = try? SafeFile.readAfterSecuringPermissions( + from: url.path, + maxBytes: maxCredentialBytes + ) else { return nil } + guard let decoded = try? JSONDecoder().decode(CredentialRecord.self, from: data) else { + // Invalid data stays in place at 0600; do not delete. + return nil + } + return CredentialRecord( + accessToken: decoded.accessToken, + refreshToken: nil, + expiresAt: decoded.expiresAt, + rateLimitTier: decoded.rateLimitTier + ) } - private static func writeOurCache(record: CredentialRecord) throws { - try writeOurFileCache(record: record) + /// Secure-read legacy JSON, upsert Keychain, verify read-back, then unlink. + private static func migrateLegacyFileIfPresent() throws -> CredentialRecord? { + guard let migrated = readLegacyFile() else { return nil } + // Keychain write/read-back failure leaves the repaired 0600 legacy file + // in place; the next read retries the migration. + try? writeOurCache(record: migrated) + return migrated } - private static func writeOurFileCache(record: CredentialRecord) throws { + /// Unlink the redundant legacy JSON. Called on every successful cache read, + /// so a failure here is retried on the next read without a sticky flag. + private static func tryUnlinkLegacyAfterVerifiedKeychain() { let url = cacheFileURL() - try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) - let data = try JSONEncoder().encode(record) - try data.write(to: url, options: [.atomic, .completeFileProtection]) + guard FileManager.default.fileExists(atPath: url.path) else { return } + do { + if let unlinkLegacyOverride { + try unlinkLegacyOverride(url) + } else { + try FileManager.default.removeItem(at: url) + } + } catch { + // Could not remove it — at least make sure it is not world-readable. + if let tightenLegacyOverride { + try? tightenLegacyOverride(url) + } else { + try? SafeFile.tightenToOwnerReadWrite(at: url.path) + } + } } - private static func deleteOurCache() { - try? FileManager.default.removeItem(at: cacheFileURL()) + @discardableResult + private static func deleteOurCache() -> CacheDeleteResult { + var keychainOK = true + do { + try keychainCache.delete(service: ourKeychainService, account: ourKeychainAccount) + } catch { + keychainOK = false + } + + var legacyOK = true + let url = cacheFileURL() + if FileManager.default.fileExists(atPath: url.path) { + do { + if let unlinkLegacyOverride { + try unlinkLegacyOverride(url) + } else { + try FileManager.default.removeItem(at: url) + } + } catch { + legacyOK = false + } + } + return CacheDeleteResult( + keychainDeletedOrAbsent: keychainOK, + legacyDeletedOrAbsent: legacyOK + ) + } + + /// Clears only the in-memory TTL cache (simulates process restart in tests). + static func clearMemoryCacheForTesting() { + lock.withLock { memoryCache = nil } } private static func cacheInMemory(_ record: CredentialRecord) { diff --git a/mac/Sources/CodeBurnMenubar/Data/ClaudeSubscriptionService.swift b/mac/Sources/CodeBurnMenubar/Data/ClaudeSubscriptionService.swift index d2876d1b..8a12b411 100644 --- a/mac/Sources/CodeBurnMenubar/Data/ClaudeSubscriptionService.swift +++ b/mac/Sources/CodeBurnMenubar/Data/ClaudeSubscriptionService.swift @@ -99,9 +99,14 @@ enum ClaudeSubscriptionService { } /// Reset everything — used on user-initiated disconnect. - static func disconnect() { - ClaudeCredentialStore.resetBootstrap() - clearUsageBlock() + /// Returns the delete outcome so callers only tear down UI state once the + /// credential material is actually gone. A failed delete leaves the usage + /// block intact too, so a retry starts from the same state. + @discardableResult + static func disconnect() -> ClaudeCredentialStore.CacheDeleteResult { + let result = ClaudeCredentialStore.resetBootstrap() + if result.isSuccess { clearUsageBlock() } + return result } // MARK: - Internal diff --git a/mac/Sources/CodeBurnMenubar/Data/CodexCredentialStore.swift b/mac/Sources/CodeBurnMenubar/Data/CodexCredentialStore.swift index 9f7ae18f..2d500cfa 100644 --- a/mac/Sources/CodeBurnMenubar/Data/CodexCredentialStore.swift +++ b/mac/Sources/CodeBurnMenubar/Data/CodexCredentialStore.swift @@ -5,7 +5,7 @@ import Security /// ClaudeCredentialStore but reads from ~/.codex/auth.json — Codex CLI /// already stores its tokens as plaintext JSON in the home directory, so /// no keychain prompt is involved on bootstrap. After the user clicks -/// Connect we cache a copy under ~/Library/Application Support/CodeBurn so +/// Connect we cache a CodeBurn-owned copy in the macOS Keychain so /// we keep using rotated tokens after refresh. enum CodexCredentialStore { private static let bootstrapCompletedKey = "codeburn.codex.bootstrapCompleted" @@ -23,9 +23,38 @@ enum CodexCredentialStore { private static let cacheFilename = "codex-credentials.v1.json" + static let ourKeychainService = CodeBurnKeychainIdentity.codexService + static let ourKeychainAccount = CodeBurnKeychainIdentity.account + private static let lock = NSLock() private nonisolated(unsafe) static var memoryCache: CachedRecord? + // MARK: - Injectable seams (tests + staged Keychain migration) + + nonisolated(unsafe) static var applicationSupportDirectoryOverride: URL? + nonisolated(unsafe) static var homeDirectoryOverride: URL? + nonisolated(unsafe) static var userDefaultsOverride: UserDefaults? + nonisolated(unsafe) static var keychainCache: any KeychainCredentialCaching = LiveKeychainCredentialCache() + + static func resetTestSeams() { + applicationSupportDirectoryOverride = nil + homeDirectoryOverride = nil + userDefaultsOverride = nil + keychainCache = LiveKeychainCredentialCache() + lastCacheDeleteResult = nil + unlinkLegacyOverride = nil + tightenLegacyOverride = nil + lock.withLock { memoryCache = nil } + } + + private static var defaults: UserDefaults { + userDefaultsOverride ?? .standard + } + + private static var homeDirectory: URL { + homeDirectoryOverride ?? FileManager.default.homeDirectoryForCurrentUser + } + struct CachedRecord { let record: CredentialRecord let cachedAt: Date @@ -97,16 +126,31 @@ enum CodexCredentialStore { // MARK: - Bootstrap state static var isBootstrapCompleted: Bool { - get { UserDefaults.standard.bool(forKey: bootstrapCompletedKey) } - set { UserDefaults.standard.set(newValue, forKey: bootstrapCompletedKey) } + get { defaults.bool(forKey: bootstrapCompletedKey) } + set { defaults.set(newValue, forKey: bootstrapCompletedKey) } } - static func resetBootstrap() { + static func resetBootstrap() -> CacheDeleteResult { lock.withLock { memoryCache = nil } - deleteOurCache() - isBootstrapCompleted = false + let result = deleteOurCache() + lastCacheDeleteResult = result + if result.isSuccess { + isBootstrapCompleted = false + } + return result } + struct CacheDeleteResult: Equatable { + var keychainDeletedOrAbsent: Bool + var legacyDeletedOrAbsent: Bool + var isSuccess: Bool { keychainDeletedOrAbsent && legacyDeletedOrAbsent } + } + + nonisolated(unsafe) static var lastCacheDeleteResult: CacheDeleteResult? + nonisolated(unsafe) static var unlinkLegacyOverride: ((URL) throws -> Void)? + nonisolated(unsafe) static var tightenLegacyOverride: ((URL) throws -> Void)? + + // MARK: - Public API @discardableResult @@ -132,7 +176,18 @@ enum CodexCredentialStore { if let cached = lock.withLock({ memoryCache }), cached.isFresh { return cached.record } - if let stored = try readOurCache() { + let fetched: CredentialRecord? + do { + fetched = try readOurCache() + } catch let err as KeychainCredentialCacheError { + // Locked/denied keychain: serve the last known token rather than + // reporting the grant as missing. + if case .unavailable = err { + return lock.withLock { memoryCache }?.record + } + throw err + } + if let stored = fetched { cacheInMemory(stored) return stored } @@ -170,7 +225,7 @@ enum CodexCredentialStore { // MARK: - Bootstrap source: ~/.codex/auth.json private static func readCodexAuth() throws -> CredentialRecord { - let url = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(codexAuthPath) + let url = homeDirectory.appendingPathComponent(codexAuthPath) guard FileManager.default.fileExists(atPath: url.path) else { throw StoreError.bootstrapNoSource } @@ -231,7 +286,7 @@ enum CodexCredentialStore { /// key (OPENAI_API_KEY, auth_mode, ...) and only rewrites the tokens dict and /// last_refresh. Keeps the CLI and the menubar on the same rotated grant. private static func writeBackToCodexAuth(record: CredentialRecord) { - let url = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(codexAuthPath) + let url = homeDirectory.appendingPathComponent(codexAuthPath) var json: [String: Any] = [:] if let data = try? SafeFile.read(from: url.path, maxBytes: maxCredentialBytes), let existing = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { @@ -250,40 +305,152 @@ enum CodexCredentialStore { guard let out = try? JSONSerialization.data(withJSONObject: json, options: [.prettyPrinted, .sortedKeys]) else { return } - try? out.write(to: url, options: .atomic) + try? SafeFile.write(out, to: url.path, mode: 0o600) } - // MARK: - Local cache file + // MARK: - Local cache (injectable Application Support + Keychain seam) - private static func cacheFileURL() -> URL { - let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first - ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support") + static func cacheFileURL() -> URL { + let support = applicationSupportDirectoryOverride + ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first + ?? homeDirectory.appendingPathComponent("Library/Application Support") return support .appendingPathComponent("CodeBurn", isDirectory: true) .appendingPathComponent(cacheFilename) } + /// Production-used write path. Persists rotation fields to the CodeBurn + /// Keychain item. After verified read-back, unlinks any legacy JSON. + static func writeOurCache(record: CredentialRecord) throws { + let data = try JSONEncoder().encode(record) + try keychainCache.upsert( + service: ourKeychainService, + account: ourKeychainAccount, + data: data + ) + guard let readBack = try keychainCache.read(service: ourKeychainService, account: ourKeychainAccount), + let roundTrip = try? JSONDecoder().decode(CredentialRecord.self, from: readBack), + roundTrip.accessToken == record.accessToken, + roundTrip.refreshToken == record.refreshToken, + roundTrip.idToken == record.idToken, + roundTrip.accountId == record.accountId + else { + throw StoreError.fileWriteFailed("keychain read-back mismatch") + } + tryUnlinkLegacyAfterVerifiedKeychain() + } + + /// Serializes migrate + unlink across processes so two menubar instances (or the + /// CLI) cannot race on the same legacy file. Only `SafeFile.Error` from acquiring + /// the lock is tolerated — `readOurCacheLocked` never lets one escape, because + /// `readLegacyFile` swallows its own read failures. private static func readOurCache() throws -> CredentialRecord? { + do { + return try SafeFile.withExclusiveLock(at: cacheFileURL().path + ".lock") { + try readOurCacheLocked() + } + } catch is SafeFile.Error { + return try readOurCacheLocked() + } + } + + private static func readOurCacheLocked() throws -> CredentialRecord? { + if let data = try keychainCache.read(service: ourKeychainService, account: ourKeychainAccount), + let record = try? JSONDecoder().decode(CredentialRecord.self, from: data) { + // Only reached when auth.json is unreadable, but the Keychain item can + // still be older than the legacy file — and serving a spent rotating + // refresh token here ends in a terminal invalid_grant. Prefer the + // later `lastRefresh` before unlinking anything. + if let fresher = legacyRecordIfNewer(than: record) { + try? writeOurCache(record: fresher) + return fresher + } + tryUnlinkLegacyAfterVerifiedKeychain() + return record + } + return try migrateLegacyFileIfPresent() + } + + /// Returns the legacy file's record when it refreshed strictly later than + /// `record`; nil when absent, unreadable, or not newer. + private static func legacyRecordIfNewer(than record: CredentialRecord) -> CredentialRecord? { + guard let legacy = readLegacyFile() else { return nil } + guard let legacyRefresh = legacy.lastRefresh else { return nil } + guard let currentRefresh = record.lastRefresh else { return legacy } + return legacyRefresh > currentRefresh ? legacy : nil + } + + /// Secure-read + decode the legacy JSON. Returns nil on symlink / ownership / + /// chmod / decode failure, leaving the file in place. + private static func readLegacyFile() -> CredentialRecord? { let url = cacheFileURL() guard FileManager.default.fileExists(atPath: url.path) else { return nil } - let data = try SafeFile.read(from: url.path, maxBytes: maxCredentialBytes) - guard let record = try? JSONDecoder().decode(CredentialRecord.self, from: data) else { return nil } - return record + guard let data = try? SafeFile.readAfterSecuringPermissions( + from: url.path, + maxBytes: maxCredentialBytes + ) else { return nil } + return try? JSONDecoder().decode(CredentialRecord.self, from: data) } - private static func writeOurCache(record: CredentialRecord) throws { - try writeOurFileCache(record: record) + private static func migrateLegacyFileIfPresent() throws -> CredentialRecord? { + guard let decoded = readLegacyFile() else { return nil } + // Keychain write/read-back failure leaves the repaired 0600 legacy file + // in place; the next read retries the migration. + try? writeOurCache(record: decoded) + return decoded } - private static func writeOurFileCache(record: CredentialRecord) throws { + /// Unlink the redundant legacy JSON. Called on every successful cache read, + /// so a failure here is retried on the next read without a sticky flag. + private static func tryUnlinkLegacyAfterVerifiedKeychain() { let url = cacheFileURL() - try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) - let data = try JSONEncoder().encode(record) - try data.write(to: url, options: [.atomic, .completeFileProtection]) + guard FileManager.default.fileExists(atPath: url.path) else { return } + do { + if let unlinkLegacyOverride { + try unlinkLegacyOverride(url) + } else { + try FileManager.default.removeItem(at: url) + } + } catch { + // Could not remove it — at least make sure it is not world-readable. + if let tightenLegacyOverride { + try? tightenLegacyOverride(url) + } else { + try? SafeFile.tightenToOwnerReadWrite(at: url.path) + } + } } - private static func deleteOurCache() { - try? FileManager.default.removeItem(at: cacheFileURL()) + @discardableResult + private static func deleteOurCache() -> CacheDeleteResult { + var keychainOK = true + do { + try keychainCache.delete(service: ourKeychainService, account: ourKeychainAccount) + } catch { + keychainOK = false + } + + var legacyOK = true + let url = cacheFileURL() + if FileManager.default.fileExists(atPath: url.path) { + do { + if let unlinkLegacyOverride { + try unlinkLegacyOverride(url) + } else { + try FileManager.default.removeItem(at: url) + } + } catch { + legacyOK = false + } + } + return CacheDeleteResult( + keychainDeletedOrAbsent: keychainOK, + legacyDeletedOrAbsent: legacyOK + ) + } + + static func clearMemoryCacheForTesting() { + lock.withLock { memoryCache = nil } } private static func cacheInMemory(_ record: CredentialRecord) { diff --git a/mac/Sources/CodeBurnMenubar/Data/CodexSubscriptionService.swift b/mac/Sources/CodeBurnMenubar/Data/CodexSubscriptionService.swift index d25637c1..275f7848 100644 --- a/mac/Sources/CodeBurnMenubar/Data/CodexSubscriptionService.swift +++ b/mac/Sources/CodeBurnMenubar/Data/CodexSubscriptionService.swift @@ -78,9 +78,14 @@ enum CodexSubscriptionService { } } - static func disconnect() { - CodexCredentialStore.resetBootstrap() - clearUsageBlock() + /// Returns the delete outcome so callers only tear down UI state once the + /// credential material is actually gone. A failed delete leaves the usage + /// block intact too, so a retry starts from the same state. + @discardableResult + static func disconnect() -> CodexCredentialStore.CacheDeleteResult { + let result = CodexCredentialStore.resetBootstrap() + if result.isSuccess { clearUsageBlock() } + return result } private static func fetchWithToken(_ token: String, allowOne401Recovery: Bool) async throws -> CodexUsage { diff --git a/mac/Sources/CodeBurnMenubar/Data/UsageDataChangeGuard.swift b/mac/Sources/CodeBurnMenubar/Data/UsageDataChangeGuard.swift index d2a48c36..e28eed9c 100644 --- a/mac/Sources/CodeBurnMenubar/Data/UsageDataChangeGuard.swift +++ b/mac/Sources/CodeBurnMenubar/Data/UsageDataChangeGuard.swift @@ -72,6 +72,8 @@ enum UsageDataChangeGuard { add(expand(environment["CODEWHALE_HOME"] ?? path(homeDirectory, ".codewhale"), homeDirectory: homeDirectory), scanFirstLevelDirectories: false) add(path(homeDirectory, ".deepseek", "sessions"), scanFirstLevelDirectories: false) add(path(homeDirectory, ".cline", "data"), scanFirstLevelDirectories: false) + let dshHome = expand(environment["DSH_HOME"] ?? path(homeDirectory, ".dsh"), homeDirectory: homeDirectory) + add(path(dshHome, "sessions")) add(expand(environment["CODEBUFF_DATA_DIR"] ?? path(xdgConfig, "manicode"), homeDirectory: homeDirectory), scanFirstLevelDirectories: false) let factoryHome = expand(environment["FACTORY_DIR"] ?? path(homeDirectory, ".factory"), homeDirectory: homeDirectory) add(path(factoryHome, "sessions"), scanFirstLevelDirectories: false) diff --git a/mac/Sources/CodeBurnMenubar/Security/KeychainCredentialCache.swift b/mac/Sources/CodeBurnMenubar/Security/KeychainCredentialCache.swift new file mode 100644 index 00000000..2b8f5d3c --- /dev/null +++ b/mac/Sources/CodeBurnMenubar/Security/KeychainCredentialCache.swift @@ -0,0 +1,248 @@ +import Foundation +import LocalAuthentication +import Security + +/// Serializes credential-store test harnesses that mutate process-wide seams. +enum CredentialStoreTestIsolation { + static let lock = NSLock() +} + +/// Narrow CodeBurn-owned Keychain cache over exact service/account pairs. +/// +/// Production uses `LiveKeychainCredentialCache`. Tests inject +/// `InMemoryKeychainCredentialCache` so the suite never touches the login +/// Keychain. Errors carry only operation, service, and OSStatus — never blob data. +protocol KeychainCredentialCaching: Sendable { + func read(service: String, account: String) throws -> Data? + func upsert(service: String, account: String, data: Data) throws + func delete(service: String, account: String) throws +} + +enum KeychainCredentialCacheError: Error, LocalizedError, Equatable { + case readFailed(service: String, status: OSStatus) + case writeFailed(service: String, status: OSStatus) + case deleteFailed(service: String, status: OSStatus) + /// Keychain is locked or consent was refused. Transient — callers keep the + /// last known token and must not treat it as "the item is gone". + case unavailable(service: String, status: OSStatus) + + var errorDescription: String? { + switch self { + case let .readFailed(service, status): + return "Keychain read failed for \(service) (status \(status))." + case let .writeFailed(service, status): + return "Keychain write failed for \(service) (status \(status))." + case let .deleteFailed(service, status): + return "Keychain delete failed for \(service) (status \(status))." + case .unavailable: + return "Keychain unavailable — unlock your login keychain to refresh quota." + } + } + + /// Statuses that mean "we were not allowed to look right now", as opposed to + /// "the item does not exist". `errSecInteractionNotAllowed` (-25308) is what + /// a locked keychain returns once UI is suppressed. + static func isUnavailable(_ status: OSStatus) -> Bool { + status == errSecInteractionNotAllowed + || status == errSecAuthFailed + || status == errSecUserCanceled + || status == errSecInteractionRequired + } +} + +/// Published CodeBurn Keychain identities. Keep these exact — Electron contracts +/// on the Codex pair (`app/electron/quota/codex.ts`), and installs going back to +/// May 2026 already hold items under these names. +/// +/// Deliberately NOT derived from `CFBundleIdentifier`: the Electron app hardcodes +/// the same strings, so a per-bundle suffix would break that contract. The +/// tradeoff is that a dev/beta build sharing this source shares the item — patch +/// these constants when running a second build alongside the release. +enum CodeBurnKeychainIdentity { + static let claudeService = "org.agentseal.codeburn.menubar.claude.oauth.v1" + static let codexService = "org.agentseal.codeburn.menubar.codex.oauth.v1" + static let account = "default" +} + +struct LiveKeychainCredentialCache: KeychainCredentialCaching { + /// True when the default (login) keychain exists and is currently locked. + /// Returns false when the state cannot be determined, so an unexpected + /// failure degrades to "just try the read" rather than a hard outage. + /// + /// `SecKeychain*` is soft-deprecated with no replacement that reports + /// file-keychain lock state — `kSecUseDataProtectionKeychain` would move our + /// item to a different store and orphan every existing install. The + /// This is the one intentional deprecation warning in the file; annotating it + /// away only moves the warning to the call site, so it is left visible. + private func isDefaultKeychainLocked() -> Bool { + var status: SecKeychainStatus = 0 + guard SecKeychainGetStatus(nil, &status) == errSecSuccess else { return false } + return (status & SecKeychainStatus(kSecUnlockStateStatus)) == 0 + } + + func read(service: String, account: String) throws -> Data? { + // Reads happen on the background refresh timer, so they must never be + // able to raise UI. Measured on macOS 15 against a locked test keychain: + // NEITHER `kSecUseAuthenticationUI: …Fail` NOR + // `LAContext.interactionNotAllowed` suppresses the unlock panel for a + // file-based keychain — both govern the data-protection keychain, while + // unlocking is a keychain-level operation securityd drives itself. The + // only thing that reliably avoids the panel is not issuing the read at + // all, so check lock state first. Same class of bug as the + // partition-list re-prompt in #490. + if isDefaultKeychainLocked() { + throw KeychainCredentialCacheError.unavailable( + service: service, status: errSecInteractionNotAllowed) + } + // Still pass a non-interactive context: it is the supported way to keep + // a data-protection-backed item from raising biometric/passcode UI. + let context = LAContext() + context.interactionNotAllowed = true + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + kSecMatchLimit as String: kSecMatchLimitOne, + kSecReturnData as String: true, + kSecUseAuthenticationContext as String: context, + ] + var result: CFTypeRef? + let status = SecItemCopyMatching(query as CFDictionary, &result) + if status == errSecItemNotFound { return nil } + if KeychainCredentialCacheError.isUnavailable(status) { + throw KeychainCredentialCacheError.unavailable(service: service, status: status) + } + guard status == errSecSuccess, let data = result as? Data else { + throw KeychainCredentialCacheError.readFailed(service: service, status: status) + } + return data + } + + func upsert(service: String, account: String, data: Data) throws { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + ] + let attributes: [String: Any] = [ + kSecValueData as String: data, + ] + let updateStatus = SecItemUpdate(query as CFDictionary, attributes as CFDictionary) + if updateStatus == errSecSuccess { return } + if updateStatus == errSecItemNotFound { + var add = query + add[kSecValueData as String] = data + let addStatus = SecItemAdd(add as CFDictionary, nil) + if addStatus == errSecSuccess { return } + if addStatus == errSecDuplicateItem { + let retry = SecItemUpdate(query as CFDictionary, attributes as CFDictionary) + guard retry == errSecSuccess else { + throw KeychainCredentialCacheError.writeFailed(service: service, status: retry) + } + return + } + throw KeychainCredentialCacheError.writeFailed(service: service, status: addStatus) + } + throw KeychainCredentialCacheError.writeFailed(service: service, status: updateStatus) + } + + func delete(service: String, account: String) throws { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + ] + let status = SecItemDelete(query as CFDictionary) + if status == errSecSuccess || status == errSecItemNotFound { return } + throw KeychainCredentialCacheError.deleteFailed(service: service, status: status) + } +} + +/// Process-local fake for tests. Never writes to the system Keychain. +final class InMemoryKeychainCredentialCache: KeychainCredentialCaching, @unchecked Sendable { + private let lock = NSLock() + private var items: [String: Data] = [:] + private(set) var upsertCount = 0 + private(set) var readCount = 0 + private(set) var deleteCount = 0 + + private func key(_ service: String, _ account: String) -> String { + "\(service)\u{1f}\(account)" + } + + func read(service: String, account: String) throws -> Data? { + lock.lock(); defer { lock.unlock() } + readCount += 1 + return items[key(service, account)] + } + + func upsert(service: String, account: String, data: Data) throws { + lock.lock(); defer { lock.unlock() } + upsertCount += 1 + items[key(service, account)] = data + } + + func delete(service: String, account: String) throws { + lock.lock(); defer { lock.unlock() } + deleteCount += 1 + items.removeValue(forKey: key(service, account)) + } + + func storedJSONObject(service: String, account: String) -> [String: Any]? { + lock.lock(); defer { lock.unlock() } + guard let data = items[key(service, account)] else { return nil } + return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] + } + + func storedKeys(service: String, account: String) -> [String]? { + storedJSONObject(service: service, account: account).map { Array($0.keys).sorted() } + } + + /// Snapshot for simulated process restart: keep Keychain bytes, drop nothing else. + func cloneStorage() -> InMemoryKeychainCredentialCache { + lock.lock(); defer { lock.unlock() } + let copy = InMemoryKeychainCredentialCache() + copy.items = items + return copy + } +} + +/// Test double that wraps another backend and can force upsert/read/delete failures. +final class ControllableKeychainCredentialCache: KeychainCredentialCaching, @unchecked Sendable { + private let inner: any KeychainCredentialCaching + var failUpsert = false + var failRead = false + var failDelete = false + var upsertStatus: OSStatus = -1 + var readStatus: OSStatus = -1 + var deleteStatus: OSStatus = -1 + + init(inner: any KeychainCredentialCaching) { + self.inner = inner + } + + func read(service: String, account: String) throws -> Data? { + if failRead { + // Mirror the live adapter's mapping so tests exercise the same branch. + if KeychainCredentialCacheError.isUnavailable(readStatus) { + throw KeychainCredentialCacheError.unavailable(service: service, status: readStatus) + } + throw KeychainCredentialCacheError.readFailed(service: service, status: readStatus) + } + return try inner.read(service: service, account: account) + } + + func upsert(service: String, account: String, data: Data) throws { + if failUpsert { + throw KeychainCredentialCacheError.writeFailed(service: service, status: upsertStatus) + } + try inner.upsert(service: service, account: account, data: data) + } + + func delete(service: String, account: String) throws { + if failDelete { + throw KeychainCredentialCacheError.deleteFailed(service: service, status: deleteStatus) + } + try inner.delete(service: service, account: account) + } +} diff --git a/mac/Sources/CodeBurnMenubar/Security/SafeFile.swift b/mac/Sources/CodeBurnMenubar/Security/SafeFile.swift index 3b3dea29..3746f539 100644 --- a/mac/Sources/CodeBurnMenubar/Security/SafeFile.swift +++ b/mac/Sources/CodeBurnMenubar/Security/SafeFile.swift @@ -21,6 +21,42 @@ enum SafeFile { /// from exhausting memory in the Swift process. static let defaultReadLimit = 8 * 1024 * 1024 + /// Open the existing regular file with O_NOFOLLOW, fchmod 0600, and + /// fstat-verify the mode. Used when leftover credential JSON cannot be + /// unlinked after a verified Keychain write. + static func tightenToOwnerReadWrite(at path: String) throws { + var linkInfo = stat() + guard lstat(path, &linkInfo) == 0 else { + throw Error.readFailed(path, errno) + } + if (linkInfo.st_mode & S_IFMT) == S_IFLNK { + throw Error.symlinkDetected(path) + } + let fd = Darwin.open(path, O_RDONLY | O_NOFOLLOW) + guard fd >= 0 else { + throw Error.readFailed(path, errno) + } + defer { Darwin.close(fd) } + var opened = stat() + guard fstat(fd, &opened) == 0 else { + throw Error.readFailed(path, errno) + } + guard (opened.st_mode & S_IFMT) == S_IFREG else { + throw SecureReadError.notRegularFile(path) + } + if fchmod(fd, 0o600) != 0 { + throw SecureReadError.chmodFailed(path, errno) + } + var verified = stat() + guard fstat(fd, &verified) == 0 else { + throw Error.readFailed(path, errno) + } + let mode = verified.st_mode & 0o777 + guard mode == 0o600 else { + throw SecureReadError.modeVerifyFailed(path, mode) + } + } + /// Refuses to follow symlinks and writes atomically via a tmp file + rename. `mode` is the /// final file permission (0o600 by default so cache files stay user-private). static func write(_ data: Data, to path: String, mode: mode_t = 0o600) throws { @@ -101,6 +137,96 @@ enum SafeFile { return data } + enum SecureReadError: Swift.Error, Equatable { + case notRegularFile(String) + case wrongOwner(String) + case chmodFailed(String, Int32) + case modeVerifyFailed(String, mode_t) + } + + /// Legacy credential migration path: open with `O_NOFOLLOW`, refuse non-regular / + /// non-owned files, `fchmod(0600)` and verify mode, then read bounded bytes from + /// the same descriptor. Permissions are repaired before any secret byte is read. + /// + /// The chmod deliberately precedes any content check: validating JSON first would + /// mean reading the secret while it is still world-readable, which is the exact + /// window this function exists to close. The cost is that a non-credential file + /// sitting at the caller's exact cache path also gets tightened to 0600 — bounded + /// to our own Application Support directory, and already symlink- and owner-checked. + static func readAfterSecuringPermissions( + from path: String, + maxBytes: Int = defaultReadLimit, + expectedOwner: uid_t = geteuid() + ) throws -> Data { + var linkInfo = stat() + guard lstat(path, &linkInfo) == 0 else { + throw Error.readFailed(path, errno) + } + if (linkInfo.st_mode & S_IFMT) == S_IFLNK { + throw Error.symlinkDetected(path) + } + guard (linkInfo.st_mode & S_IFMT) == S_IFREG else { + throw SecureReadError.notRegularFile(path) + } + guard linkInfo.st_uid == expectedOwner else { + throw SecureReadError.wrongOwner(path) + } + + let fd = Darwin.open(path, O_RDONLY | O_NOFOLLOW) + guard fd >= 0 else { + throw Error.readFailed(path, errno) + } + defer { Darwin.close(fd) } + + var opened = stat() + guard fstat(fd, &opened) == 0 else { + throw Error.readFailed(path, errno) + } + guard (opened.st_mode & S_IFMT) == S_IFREG else { + throw SecureReadError.notRegularFile(path) + } + guard opened.st_uid == expectedOwner else { + throw SecureReadError.wrongOwner(path) + } + + if fchmod(fd, 0o600) != 0 { + throw SecureReadError.chmodFailed(path, errno) + } + var verified = stat() + guard fstat(fd, &verified) == 0 else { + throw Error.readFailed(path, errno) + } + let mode = verified.st_mode & 0o777 + guard mode == 0o600 else { + throw SecureReadError.modeVerifyFailed(path, mode) + } + + let size = Int(verified.st_size) + if size > maxBytes { + throw Error.sizeLimitExceeded(path, size) + } + + var data = Data() + data.reserveCapacity(max(size, 0)) + var chunk = [UInt8](repeating: 0, count: 4096) + let limit = maxBytes + 1 + while data.count < limit { + let n = chunk.withUnsafeMutableBytes { buffer -> Int in + guard let base = buffer.baseAddress else { return 0 } + return Darwin.read(fd, base, min(buffer.count, limit - data.count)) + } + guard n >= 0 else { + throw Error.readFailed(path, errno) + } + if n == 0 { break } + data.append(contentsOf: chunk.prefix(n)) + } + if data.count > maxBytes { + throw Error.sizeLimitExceeded(path, data.count) + } + return data + } + /// Runs `body` while holding an exclusive POSIX advisory lock on `path`. The lock file is /// created if missing (with 0o600 permissions) and released on scope exit, so other /// codeburn processes (the CLI running in a terminal, say) block on the same file instead diff --git a/mac/Sources/CodeBurnMenubar/Views/SettingsView.swift b/mac/Sources/CodeBurnMenubar/Views/SettingsView.swift index e8c1f218..d63bcffa 100644 --- a/mac/Sources/CodeBurnMenubar/Views/SettingsView.swift +++ b/mac/Sources/CodeBurnMenubar/Views/SettingsView.swift @@ -508,7 +508,7 @@ private struct CodexSettingsTab: View { CodexConnectionRow() } Section { - Text("Codex live-quota tracking reads `~/.codex/auth.json` once on Connect, then keeps a local copy under Application Support so subsequent quota fetches don't re-read the original. Only ChatGPT-mode auth (Plus / Pro / Team / Business / Edu / Enterprise) is supported. API-key users are billed per request and have a different reporting surface. Credit-metered workspaces report no rate-limit windows, so their monthly credit allowance is shown instead.") + Text("Codex live-quota tracking reads `~/.codex/auth.json` once on Connect, then keeps a CodeBurn-owned copy in your login Keychain instead of a world-readable file, so subsequent quota fetches don't re-read the original. The item is reachable by programs running as you, the same as any login-Keychain entry. Only ChatGPT-mode auth (Plus / Pro / Team / Business / Edu / Enterprise) is supported. API-key users are billed per request and have a different reporting surface. Credit-metered workspaces report no rate-limit windows, so their monthly credit allowance is shown instead.") .font(.system(size: 11)) .foregroundStyle(.secondary) } header: { diff --git a/mac/Tests/CodeBurnMenubarTests/CredentialKeychainCacheRedTests.swift b/mac/Tests/CodeBurnMenubarTests/CredentialKeychainCacheRedTests.swift new file mode 100644 index 00000000..51646d9b --- /dev/null +++ b/mac/Tests/CodeBurnMenubarTests/CredentialKeychainCacheRedTests.swift @@ -0,0 +1,149 @@ +import Foundation +import Testing +@testable import CodeBurnMenubar + +/// Red receipt for 0B: current plaintext writers must fail these assertions. +/// Disposable sentinels only — never log or expect raw secret values in receipts. +@Suite("Credential Keychain cache red", .serialized) +struct CredentialKeychainCacheRedTests { + private let accessSentinel = "cb-red-access-sentinel" + private let refreshSentinel = "cb-red-refresh-sentinel" + private let idSentinel = "cb-red-id-sentinel" + private let accountSentinel = "cb-red-account-sentinel" + + private func withIsolatedSeams( + _ body: (URL, InMemoryKeychainCredentialCache) throws -> Void + ) throws { + CredentialStoreTestIsolation.lock.lock() + defer { CredentialStoreTestIsolation.lock.unlock() } + + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("codeburn-0b-red-\(UUID().uuidString)", isDirectory: true) + let support = root.appendingPathComponent("Application Support", isDirectory: true) + try FileManager.default.createDirectory(at: support, withIntermediateDirectories: true) + let suiteName = "codeburn.0b.red.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suiteName)! + defaults.removePersistentDomain(forName: suiteName) + + let fakeKeychain = InMemoryKeychainCredentialCache() + ClaudeCredentialStore.resetTestSeams() + CodexCredentialStore.resetTestSeams() + ClaudeCredentialStore.applicationSupportDirectoryOverride = support + CodexCredentialStore.applicationSupportDirectoryOverride = support + ClaudeCredentialStore.userDefaultsOverride = defaults + CodexCredentialStore.userDefaultsOverride = defaults + ClaudeCredentialStore.keychainCache = fakeKeychain + CodexCredentialStore.keychainCache = fakeKeychain + + defer { + ClaudeCredentialStore.resetTestSeams() + CodexCredentialStore.resetTestSeams() + defaults.removePersistentDomain(forName: suiteName) + try? FileManager.default.removeItem(at: root) + } + + try body(support, fakeKeychain) + } + + private func posixMode(at url: URL) -> mode_t? { + var info = stat() + guard lstat(url.path, &info) == 0 else { return nil } + return info.st_mode & 0o777 + } + + private func jsonKeys(at url: URL) throws -> [String] { + let data = try Data(contentsOf: url) + let object = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any]) + return object.keys.sorted() + } + + @Test("Claude writeOurCache leaves no JSON and stores Keychain payload without refreshToken") + func claudeWriteUsesKeychainWithoutRefreshToken() throws { + try withIsolatedSeams { support, fakeKeychain in + let record = ClaudeCredentialStore.CredentialRecord( + accessToken: accessSentinel, + refreshToken: refreshSentinel, + expiresAt: Date(timeIntervalSince1970: 1_900_000_000), + rateLimitTier: "default" + ) + + try ClaudeCredentialStore.writeOurCache(record: record) + + let legacyURL = ClaudeCredentialStore.cacheFileURL() + let legacyExists = FileManager.default.fileExists(atPath: legacyURL.path) + let mode = legacyExists ? posixMode(at: legacyURL) : nil + let fileKeys = legacyExists ? try jsonKeys(at: legacyURL) : [] + let keychainKeys = fakeKeychain.storedKeys( + service: ClaudeCredentialStore.ourKeychainService, + account: ClaudeCredentialStore.ourKeychainAccount + ) + let keychainObject = fakeKeychain.storedJSONObject( + service: ClaudeCredentialStore.ourKeychainService, + account: ClaudeCredentialStore.ourKeychainAccount + ) + let hasRefreshKey = keychainObject?.keys.contains("refreshToken") == true + let refreshValueMatches = (keychainObject?["refreshToken"] as? String) == refreshSentinel + + // Intended green behavior (must fail against current plaintext writer): + #expect(!legacyExists, "legacy Claude JSON must not be created under Application Support") + #expect(fakeKeychain.upsertCount >= 1, "fake Keychain must receive a Claude upsert") + #expect(keychainKeys != nil, "Claude Keychain payload must exist") + #expect(!(keychainKeys?.contains("refreshToken") ?? false), "Claude Keychain keys must omit refreshToken") + #expect(!hasRefreshKey && !refreshValueMatches, "Claude Keychain must not persist refreshToken") + + // Red diagnostic (keys + mode only; never fixture values): + if legacyExists { + Issue.record( + Comment(rawValue: "RED Claude legacy present mode=\(String(mode.map { String($0, radix: 8) } ?? "nil")) keys=\(fileKeys.joined(separator: ","))") + ) + } + if fakeKeychain.upsertCount == 0 { + Issue.record(Comment(rawValue: "RED Claude Keychain upsertCount=0")) + } + _ = support + } + } + + @Test("Codex writeOurCache leaves no JSON and stores Keychain rotation fields") + func codexWriteUsesKeychainWithRotationFields() throws { + try withIsolatedSeams { support, fakeKeychain in + let record = CodexCredentialStore.CredentialRecord( + accessToken: accessSentinel, + refreshToken: refreshSentinel, + idToken: idSentinel, + accountId: accountSentinel, + expiresAt: Date(timeIntervalSince1970: 1_900_000_100), + lastRefresh: Date(timeIntervalSince1970: 1_700_000_000) + ) + + try CodexCredentialStore.writeOurCache(record: record) + + let legacyURL = CodexCredentialStore.cacheFileURL() + let legacyExists = FileManager.default.fileExists(atPath: legacyURL.path) + let mode = legacyExists ? posixMode(at: legacyURL) : nil + let fileKeys = legacyExists ? try jsonKeys(at: legacyURL) : [] + let keychainKeys = fakeKeychain.storedKeys( + service: CodexCredentialStore.ourKeychainService, + account: CodexCredentialStore.ourKeychainAccount + ) + + let required = ["accessToken", "refreshToken", "idToken", "accountId", "lastRefresh"] + let missingRequired = required.filter { !(keychainKeys?.contains($0) ?? false) } + + #expect(!legacyExists, "legacy Codex JSON must not be created under Application Support") + #expect(fakeKeychain.upsertCount >= 1, "fake Keychain must receive a Codex upsert") + #expect(keychainKeys != nil, "Codex Keychain payload must exist") + #expect(missingRequired.isEmpty, "Codex Keychain must retain rotation fields") + + if legacyExists { + Issue.record( + Comment(rawValue: "RED Codex legacy present mode=\(String(mode.map { String($0, radix: 8) } ?? "nil")) keys=\(fileKeys.joined(separator: ","))") + ) + } + if fakeKeychain.upsertCount == 0 { + Issue.record(Comment(rawValue: "RED Codex Keychain upsertCount=0")) + } + _ = support + } + } +} diff --git a/mac/Tests/CodeBurnMenubarTests/CredentialKeychainContinuityTests.swift b/mac/Tests/CodeBurnMenubarTests/CredentialKeychainContinuityTests.swift new file mode 100644 index 00000000..13385a94 --- /dev/null +++ b/mac/Tests/CodeBurnMenubarTests/CredentialKeychainContinuityTests.swift @@ -0,0 +1,557 @@ +import Foundation +import Testing +@testable import CodeBurnMenubar + +/// Implementation-continuity tests for option-3 evidence bar. +/// Uses only InMemory/Controllable Keychain backends and temp Application Support — +/// never the operator login Keychain or live credential files. +@Suite("Credential Keychain implementation continuity", .serialized) +struct CredentialKeychainContinuityTests { + private let accessSentinel = "cb-cont-access-sentinel" + private let refreshSentinel = "cb-cont-refresh-sentinel" + private let idSentinel = "cb-cont-id-sentinel" + private let accountSentinel = "cb-cont-account-sentinel" + + private struct Harness { + let root: URL + let support: URL + let defaults: UserDefaults + let suiteName: String + let fakeKeychain: InMemoryKeychainCredentialCache + } + + private func withHarness( + _ body: (Harness) throws -> Void + ) throws { + CredentialStoreTestIsolation.lock.lock() + defer { CredentialStoreTestIsolation.lock.unlock() } + + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("codeburn-0b-cont-\(UUID().uuidString)", isDirectory: true) + let support = root.appendingPathComponent("Application Support", isDirectory: true) + try FileManager.default.createDirectory(at: support, withIntermediateDirectories: true) + let suiteName = "codeburn.0b.cont.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suiteName)! + defaults.removePersistentDomain(forName: suiteName) + let fake = InMemoryKeychainCredentialCache() + + ClaudeCredentialStore.resetTestSeams() + CodexCredentialStore.resetTestSeams() + ClaudeCredentialStore.applicationSupportDirectoryOverride = support + CodexCredentialStore.applicationSupportDirectoryOverride = support + ClaudeCredentialStore.homeDirectoryOverride = root + CodexCredentialStore.homeDirectoryOverride = root + ClaudeCredentialStore.userDefaultsOverride = defaults + CodexCredentialStore.userDefaultsOverride = defaults + ClaudeCredentialStore.keychainCache = fake + CodexCredentialStore.keychainCache = fake + + defer { + ClaudeCredentialStore.resetTestSeams() + CodexCredentialStore.resetTestSeams() + defaults.removePersistentDomain(forName: suiteName) + try? FileManager.default.removeItem(at: root) + } + + try body(Harness(root: root, support: support, defaults: defaults, suiteName: suiteName, fakeKeychain: fake)) + } + + private func posixMode(at url: URL) -> mode_t? { + var info = stat() + guard lstat(url.path, &info) == 0 else { return nil } + return info.st_mode & 0o777 + } + + private func writeLegacyClaude0644(record: ClaudeCredentialStore.CredentialRecord) throws { + let url = ClaudeCredentialStore.cacheFileURL() + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + let data = try JSONEncoder().encode(record) + try data.write(to: url) + try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: url.path) + } + + private func writeLegacyCodex0644(record: CodexCredentialStore.CredentialRecord) throws { + let url = CodexCredentialStore.cacheFileURL() + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + let data = try JSONEncoder().encode(record) + try data.write(to: url) + try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: url.path) + } + + // MARK: - Continuity lifecycle + + @Test("Claude write → simulated restart → read → update → delete") + func claudeWriteRestartReadUpdateDelete() throws { + try withHarness { harness in + let initial = ClaudeCredentialStore.CredentialRecord( + accessToken: accessSentinel, + refreshToken: refreshSentinel, + expiresAt: Date(timeIntervalSince1970: 1_900_000_000), + rateLimitTier: "default" + ) + try ClaudeCredentialStore.writeOurCache(record: initial) + ClaudeCredentialStore.isBootstrapCompleted = true + + #expect(!FileManager.default.fileExists(atPath: ClaudeCredentialStore.cacheFileURL().path)) + let keys = harness.fakeKeychain.storedKeys( + service: ClaudeCredentialStore.ourKeychainService, + account: ClaudeCredentialStore.ourKeychainAccount + ) + #expect(keys?.contains("refreshToken") != true) + #expect(keys?.contains("accessToken") == true) + + // Simulated process restart: drop memory, keep Keychain bytes. + ClaudeCredentialStore.clearMemoryCacheForTesting() + let afterRestart = try #require(try ClaudeCredentialStore.currentRecord()) + #expect(afterRestart.accessToken == accessSentinel) + #expect(afterRestart.refreshToken == nil) + + let updated = ClaudeCredentialStore.CredentialRecord( + accessToken: accessSentinel + "-rotated", + refreshToken: refreshSentinel, + expiresAt: Date(timeIntervalSince1970: 1_900_000_100), + rateLimitTier: "default" + ) + try ClaudeCredentialStore.writeOurCache(record: updated) + ClaudeCredentialStore.clearMemoryCacheForTesting() + let afterUpdate = try #require(try ClaudeCredentialStore.currentRecord()) + #expect(afterUpdate.accessToken == accessSentinel + "-rotated") + + let deleteResult = ClaudeCredentialStore.resetBootstrap() + #expect(deleteResult.isSuccess) + let afterDelete = try harness.fakeKeychain.read( + service: ClaudeCredentialStore.ourKeychainService, + account: ClaudeCredentialStore.ourKeychainAccount + ) + #expect(afterDelete == nil) + let afterDisconnect = try ClaudeCredentialStore.currentRecord() + #expect(afterDisconnect == nil) + } + } + + @Test("Codex write → simulated restart → read → update → delete") + func codexWriteRestartReadUpdateDelete() throws { + try withHarness { harness in + let initial = CodexCredentialStore.CredentialRecord( + accessToken: accessSentinel, + refreshToken: refreshSentinel, + idToken: idSentinel, + accountId: accountSentinel, + expiresAt: nil, + lastRefresh: Date(timeIntervalSince1970: 1_700_000_000) + ) + try CodexCredentialStore.writeOurCache(record: initial) + CodexCredentialStore.isBootstrapCompleted = true + + #expect(!FileManager.default.fileExists(atPath: CodexCredentialStore.cacheFileURL().path)) + let keys = harness.fakeKeychain.storedKeys( + service: CodexCredentialStore.ourKeychainService, + account: CodexCredentialStore.ourKeychainAccount + ) + for required in ["accessToken", "refreshToken", "idToken", "accountId", "lastRefresh"] { + #expect(keys?.contains(required) == true) + } + + CodexCredentialStore.clearMemoryCacheForTesting() + // Without ~/.codex/auth.json, currentRecord falls through to Keychain cache. + let afterRestart = try #require(try CodexCredentialStore.currentRecord()) + #expect(afterRestart.accessToken == accessSentinel) + #expect(afterRestart.refreshToken == refreshSentinel) + + let updated = CodexCredentialStore.CredentialRecord( + accessToken: accessSentinel + "-rotated", + refreshToken: refreshSentinel + "-rotated", + idToken: idSentinel, + accountId: accountSentinel, + expiresAt: nil, + lastRefresh: Date(timeIntervalSince1970: 1_700_000_800) + ) + try CodexCredentialStore.writeOurCache(record: updated) + CodexCredentialStore.clearMemoryCacheForTesting() + let afterUpdate = try #require(try CodexCredentialStore.currentRecord()) + #expect(afterUpdate.accessToken == accessSentinel + "-rotated") + #expect(afterUpdate.refreshToken == refreshSentinel + "-rotated") + + let deleteResult = CodexCredentialStore.resetBootstrap() + #expect(deleteResult.isSuccess) + let afterDisconnect = try CodexCredentialStore.currentRecord() + #expect(afterDisconnect == nil) + } + } + + // MARK: - Migration + + @Test("successful Claude legacy 0644 migration unlinks JSON and omits refreshToken") + func claudeSuccessfulLegacyMigration() throws { + try withHarness { harness in + let legacy = ClaudeCredentialStore.CredentialRecord( + accessToken: accessSentinel, + refreshToken: refreshSentinel, + expiresAt: Date(timeIntervalSince1970: 1_900_000_000), + rateLimitTier: "default" + ) + try writeLegacyClaude0644(record: legacy) + #expect(posixMode(at: ClaudeCredentialStore.cacheFileURL()) == 0o644) + + ClaudeCredentialStore.isBootstrapCompleted = true + let migrated = try #require(try ClaudeCredentialStore.currentRecord()) + #expect(migrated.accessToken == accessSentinel) + #expect(migrated.refreshToken == nil) + #expect(!FileManager.default.fileExists(atPath: ClaudeCredentialStore.cacheFileURL().path)) + #expect(harness.fakeKeychain.upsertCount >= 1) + let keys = harness.fakeKeychain.storedKeys( + service: ClaudeCredentialStore.ourKeychainService, + account: ClaudeCredentialStore.ourKeychainAccount + ) + #expect(keys?.contains("refreshToken") != true) + } + } + + @Test("failed Claude Keychain upsert leaves secured legacy file") + func claudeFailedMigrationKeepsLegacy() throws { + try withHarness { harness in + let controllable = ControllableKeychainCredentialCache(inner: harness.fakeKeychain) + controllable.failUpsert = true + ClaudeCredentialStore.keychainCache = controllable + + let legacy = ClaudeCredentialStore.CredentialRecord( + accessToken: accessSentinel, + refreshToken: refreshSentinel, + expiresAt: Date(timeIntervalSince1970: 1_900_000_000), + rateLimitTier: "default" + ) + try writeLegacyClaude0644(record: legacy) + ClaudeCredentialStore.isBootstrapCompleted = true + + let record = try #require(try ClaudeCredentialStore.currentRecord()) + #expect(record.accessToken == accessSentinel) + #expect(FileManager.default.fileExists(atPath: ClaudeCredentialStore.cacheFileURL().path)) + #expect(posixMode(at: ClaudeCredentialStore.cacheFileURL()) == 0o600) + #expect(harness.fakeKeychain.upsertCount == 0) + } + } + + @Test("successful Codex legacy migration unlinks JSON and keeps rotation fields") + func codexSuccessfulLegacyMigration() throws { + try withHarness { harness in + let legacy = CodexCredentialStore.CredentialRecord( + accessToken: accessSentinel, + refreshToken: refreshSentinel, + idToken: idSentinel, + accountId: accountSentinel, + expiresAt: nil, + lastRefresh: Date(timeIntervalSince1970: 1_700_000_000) + ) + try writeLegacyCodex0644(record: legacy) + CodexCredentialStore.isBootstrapCompleted = true + + let migrated = try #require(try CodexCredentialStore.currentRecord()) + #expect(migrated.refreshToken == refreshSentinel) + #expect(!FileManager.default.fileExists(atPath: CodexCredentialStore.cacheFileURL().path)) + let keys = harness.fakeKeychain.storedKeys( + service: CodexCredentialStore.ourKeychainService, + account: CodexCredentialStore.ourKeychainAccount + ) + #expect(keys?.contains("refreshToken") == true) + #expect(keys?.contains("lastRefresh") == true) + } + } + + @Test("symlink legacy Claude file is refused and left in place") + func claudeSymlinkLegacyRefused() throws { + try withHarness { _ in + let codeburnDir = ClaudeCredentialStore.cacheFileURL().deletingLastPathComponent() + try FileManager.default.createDirectory(at: codeburnDir, withIntermediateDirectories: true) + let target = codeburnDir.appendingPathComponent("not-a-cred.txt") + try Data("x".utf8).write(to: target) + let link = ClaudeCredentialStore.cacheFileURL() + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: target) + + ClaudeCredentialStore.isBootstrapCompleted = true + let afterSymlink = try ClaudeCredentialStore.currentRecord() + #expect(afterSymlink == nil) + #expect(FileManager.default.fileExists(atPath: link.path)) + } + } + + // MARK: - Disconnect / reinstall + + @Test("disconnect not-found is success; delete failure is observable") + func disconnectIdempotentAndPartialFailure() throws { + try withHarness { harness in + let empty = ClaudeCredentialStore.resetBootstrap() + #expect(empty.isSuccess) + + try ClaudeCredentialStore.writeOurCache(record: .init( + accessToken: accessSentinel, + refreshToken: refreshSentinel, + expiresAt: nil, + rateLimitTier: nil + )) + ClaudeCredentialStore.isBootstrapCompleted = true + let controllable = ControllableKeychainCredentialCache(inner: harness.fakeKeychain) + controllable.failDelete = true + ClaudeCredentialStore.keychainCache = controllable + + let failed = ClaudeCredentialStore.resetBootstrap() + #expect(!failed.isSuccess) + #expect(failed.keychainDeletedOrAbsent == false) + #expect(ClaudeCredentialStore.lastCacheDeleteResult?.isSuccess == false) + #expect(ClaudeCredentialStore.isBootstrapCompleted == true) + } + } + + @Test("failed unlink after verified Keychain repairs leftover JSON to 0600") + func failedUnlinkRepairsLegacyMode() throws { + try withHarness { _ in + let record = ClaudeCredentialStore.CredentialRecord( + accessToken: accessSentinel, + refreshToken: refreshSentinel, + expiresAt: Date(timeIntervalSince1970: 1_900_000_000), + rateLimitTier: "default" + ) + try ClaudeCredentialStore.writeOurCache(record: record) + try writeLegacyClaude0644(record: record) + ClaudeCredentialStore.isBootstrapCompleted = true + ClaudeCredentialStore.unlinkLegacyOverride = { _ in + throw POSIXError(.EPERM) + } + ClaudeCredentialStore.clearMemoryCacheForTesting() + _ = try ClaudeCredentialStore.currentRecord() + #expect(FileManager.default.fileExists(atPath: ClaudeCredentialStore.cacheFileURL().path)) + #expect(posixMode(at: ClaudeCredentialStore.cacheFileURL()) == 0o600) + + // No sticky flag: the next read retries the unlink on its own. + ClaudeCredentialStore.unlinkLegacyOverride = nil + ClaudeCredentialStore.clearMemoryCacheForTesting() + _ = try ClaudeCredentialStore.currentRecord() + #expect(!FileManager.default.fileExists(atPath: ClaudeCredentialStore.cacheFileURL().path)) + } + } + + @Test("failed tighten after failed unlink keeps leftover in place") + func failedTightenLeavesRetrySignal() throws { + try withHarness { _ in + let record = ClaudeCredentialStore.CredentialRecord( + accessToken: accessSentinel, + refreshToken: refreshSentinel, + expiresAt: Date(timeIntervalSince1970: 1_900_000_000), + rateLimitTier: "default" + ) + try ClaudeCredentialStore.writeOurCache(record: record) + try writeLegacyClaude0644(record: record) + ClaudeCredentialStore.isBootstrapCompleted = true + ClaudeCredentialStore.unlinkLegacyOverride = { _ in throw POSIXError(.EPERM) } + ClaudeCredentialStore.tightenLegacyOverride = { _ in throw POSIXError(.EPERM) } + ClaudeCredentialStore.clearMemoryCacheForTesting() + _ = try ClaudeCredentialStore.currentRecord() + #expect(FileManager.default.fileExists(atPath: ClaudeCredentialStore.cacheFileURL().path)) + } + } + + @Test("legacy-only disconnect failure keeps bootstrap so retry stays") + func legacyOnlyDisconnectKeepsBootstrap() throws { + try withHarness { _ in + try ClaudeCredentialStore.writeOurCache(record: .init( + accessToken: accessSentinel, + refreshToken: refreshSentinel, + expiresAt: nil, + rateLimitTier: nil + )) + try writeLegacyClaude0644(record: .init( + accessToken: accessSentinel, + refreshToken: refreshSentinel, + expiresAt: nil, + rateLimitTier: nil + )) + ClaudeCredentialStore.isBootstrapCompleted = true + ClaudeCredentialStore.unlinkLegacyOverride = { _ in throw POSIXError(.EPERM) } + let failed = ClaudeCredentialStore.resetBootstrap() + #expect(failed.keychainDeletedOrAbsent == true) + #expect(failed.legacyDeletedOrAbsent == false) + #expect(failed.isSuccess == false) + #expect(ClaudeCredentialStore.isBootstrapCompleted == true) + } + } + + @Test("reinstall with empty Keychain and no legacy clears bootstrap on read") + func reinstallMissingCacheClearsBootstrap() throws { + try withHarness { _ in + ClaudeCredentialStore.isBootstrapCompleted = true + let missing = try ClaudeCredentialStore.currentRecord() + #expect(missing == nil) + #expect(ClaudeCredentialStore.isBootstrapCompleted == false) + } + } + + // MARK: - Locked / denied Keychain + + @Test("unavailable Keychain read is a miss, not a disconnect") + func unavailableKeychainKeepsBootstrap() throws { + try withHarness { harness in + try ClaudeCredentialStore.writeOurCache(record: .init( + accessToken: accessSentinel, + refreshToken: refreshSentinel, + expiresAt: Date(timeIntervalSince1970: 1_900_000_000), + rateLimitTier: "default" + )) + ClaudeCredentialStore.isBootstrapCompleted = true + + let controllable = ControllableKeychainCredentialCache(inner: harness.fakeKeychain) + controllable.failRead = true + controllable.readStatus = errSecInteractionNotAllowed // -25308 + ClaudeCredentialStore.keychainCache = controllable + ClaudeCredentialStore.clearMemoryCacheForTesting() + + // Must not throw and must not clear bootstrap: a locked keychain is + // "can't look right now", not "the user disconnected". + #expect(try ClaudeCredentialStore.currentRecord() == nil) + #expect(ClaudeCredentialStore.isBootstrapCompleted == true) + } + } + + @Test("a genuine read failure still surfaces as an error") + func nonUnavailableReadStillThrows() throws { + try withHarness { harness in + ClaudeCredentialStore.isBootstrapCompleted = true + let controllable = ControllableKeychainCredentialCache(inner: harness.fakeKeychain) + controllable.failRead = true + controllable.readStatus = errSecDecode + ClaudeCredentialStore.keychainCache = controllable + ClaudeCredentialStore.clearMemoryCacheForTesting() + + #expect(throws: KeychainCredentialCacheError.self) { + _ = try ClaudeCredentialStore.currentRecord() + } + } + } + + @Test("Keychain errors render a readable message, not a struct dump") + func keychainErrorMessageIsReadable() { + let unavailable = KeychainCredentialCacheError.unavailable( + service: ClaudeCredentialStore.ourKeychainService, + status: errSecInteractionNotAllowed + ) + let text = unavailable.localizedDescription + #expect(text.contains("Keychain unavailable")) + // AppStore renders errors via localizedDescription; a struct dump would + // read "unavailable(service:" and leak the raw item name. + #expect(!text.contains("unavailable(service:")) + #expect(!text.contains(ClaudeCredentialStore.ourKeychainService)) + } + + // MARK: - Recency between Keychain item and legacy file + + @Test("newer legacy file beats an older Keychain item and is then unlinked") + func newerLegacyFileWins() throws { + try withHarness { harness in + // Keychain item from an old build: already expired. + try ClaudeCredentialStore.writeOurCache(record: .init( + accessToken: "cb-stale-keychain-token", + refreshToken: nil, + expiresAt: Date(timeIntervalSince1970: 1_700_000_000), + rateLimitTier: "default" + )) + // Legacy file written far later by the pre-migration build. + try writeLegacyClaude0644(record: .init( + accessToken: accessSentinel, + refreshToken: refreshSentinel, + expiresAt: Date(timeIntervalSince1970: 1_900_000_000), + rateLimitTier: "default" + )) + ClaudeCredentialStore.isBootstrapCompleted = true + ClaudeCredentialStore.clearMemoryCacheForTesting() + + let record = try #require(try ClaudeCredentialStore.currentRecord()) + #expect(record.accessToken == accessSentinel) + #expect(record.refreshToken == nil) + #expect(!FileManager.default.fileExists(atPath: ClaudeCredentialStore.cacheFileURL().path)) + let keys = harness.fakeKeychain.storedKeys( + service: ClaudeCredentialStore.ourKeychainService, + account: ClaudeCredentialStore.ourKeychainAccount + ) + #expect(keys?.contains("refreshToken") != true) + } + } + + @Test("older legacy file loses to a newer Keychain item and is unlinked") + func olderLegacyFileLoses() throws { + try withHarness { _ in + try ClaudeCredentialStore.writeOurCache(record: .init( + accessToken: accessSentinel, + refreshToken: nil, + expiresAt: Date(timeIntervalSince1970: 1_900_000_000), + rateLimitTier: "default" + )) + try writeLegacyClaude0644(record: .init( + accessToken: "cb-stale-file-token", + refreshToken: refreshSentinel, + expiresAt: Date(timeIntervalSince1970: 1_700_000_000), + rateLimitTier: "default" + )) + ClaudeCredentialStore.isBootstrapCompleted = true + ClaudeCredentialStore.clearMemoryCacheForTesting() + + let record = try #require(try ClaudeCredentialStore.currentRecord()) + #expect(record.accessToken == accessSentinel) + #expect(!FileManager.default.fileExists(atPath: ClaudeCredentialStore.cacheFileURL().path)) + } + } + + @Test("Codex prefers the legacy file with the later lastRefresh") + func codexNewerLegacyFileWins() throws { + try withHarness { _ in + try CodexCredentialStore.writeOurCache(record: .init( + accessToken: "cb-stale-codex-access", + refreshToken: "cb-stale-codex-refresh", + idToken: nil, + accountId: accountSentinel, + expiresAt: nil, + lastRefresh: Date(timeIntervalSince1970: 1_700_000_000) + )) + try writeLegacyCodex0644(record: .init( + accessToken: accessSentinel, + refreshToken: refreshSentinel, + idToken: idSentinel, + accountId: accountSentinel, + expiresAt: nil, + lastRefresh: Date(timeIntervalSince1970: 1_800_000_000) + )) + CodexCredentialStore.isBootstrapCompleted = true + CodexCredentialStore.clearMemoryCacheForTesting() + + let record = try #require(try CodexCredentialStore.currentRecord()) + #expect(record.refreshToken == refreshSentinel) + #expect(!FileManager.default.fileExists(atPath: CodexCredentialStore.cacheFileURL().path)) + } + } + + @Test("corrupt Keychain plus valid legacy repairs the CodeBurn item") + func corruptKeychainRepairedFromLegacy() throws { + try withHarness { harness in + try harness.fakeKeychain.upsert( + service: ClaudeCredentialStore.ourKeychainService, + account: ClaudeCredentialStore.ourKeychainAccount, + data: Data("%not-json%".utf8) + ) + let legacy = ClaudeCredentialStore.CredentialRecord( + accessToken: accessSentinel, + refreshToken: refreshSentinel, + expiresAt: Date(timeIntervalSince1970: 1_900_000_000), + rateLimitTier: "default" + ) + try writeLegacyClaude0644(record: legacy) + ClaudeCredentialStore.isBootstrapCompleted = true + + let repaired = try #require(try ClaudeCredentialStore.currentRecord()) + #expect(repaired.accessToken == accessSentinel) + #expect(repaired.refreshToken == nil) + #expect(!FileManager.default.fileExists(atPath: ClaudeCredentialStore.cacheFileURL().path)) + let object = harness.fakeKeychain.storedJSONObject( + service: ClaudeCredentialStore.ourKeychainService, + account: ClaudeCredentialStore.ourKeychainAccount + ) + #expect(object?.keys.contains("refreshToken") != true) + } + } +} diff --git a/mac/Tests/CodeBurnMenubarTests/DataClientProcessTests.swift b/mac/Tests/CodeBurnMenubarTests/DataClientProcessTests.swift index 93d4ed6e..24939dea 100644 --- a/mac/Tests/CodeBurnMenubarTests/DataClientProcessTests.swift +++ b/mac/Tests/CodeBurnMenubarTests/DataClientProcessTests.swift @@ -89,38 +89,46 @@ struct DataClientProcessTests { /// Concurrency + timeout smoke test: launch more hung subprocesses than /// there are cooperative threads, all at once, with a short timeout, and - /// assert every call returns once the timeout kills its sleep. + /// assert every call returns because the timeout killed its sleep. /// /// NOTE: this does NOT reproduce the production permanent deadlock (16/16 - /// cooperative threads parked in waitUntilExit). In a short-lived unit-test - /// process libdispatch spins up replacement threads for blocked workers, so - /// even the old blocking-on-the-pool code completes here. The real deadlock - /// built up over ~2 days under the @MainActor refresh loop and is confirmed - /// by the live `sample`, not by this test. Kept as a guard that the - /// off-pool wait + timeout path stays correct under concurrency. - @Test("concurrent timed-out processes all complete") - func concurrentTimedOutProcessesAllComplete() { + /// cooperative threads parked in waitUntilExit). The real deadlock built up + /// over ~2 days under the @MainActor refresh loop and is confirmed by the + /// live `sample`, not by this test. Kept as a guard that the off-pool wait + /// + timeout path stays correct under concurrency. + /// + /// The body must stay `async` and await the group directly. It used to + /// block on a `DispatchSemaphore` with a 15s deadline, on the claim that a + /// test body runs on a real thread. It does not: Swift Testing invokes even + /// synchronous test bodies from a task on the cooperative pool, so the wait + /// parked one of the pool's `activeProcessorCount` workers on the very work + /// it was waiting for. A 16-core dev box has slack, a 3-core CI runner does + /// not, and the wait expired with the group making no progress at all. + /// Keeping it `async` also lets the compiler reject the blocking wait, + /// which is unavailable from asynchronous contexts. + @Test("concurrent timed-out processes all complete", .timeLimit(.minutes(1))) + func concurrentTimedOutProcessesAllComplete() async { let count = ProcessInfo.processInfo.activeProcessorCount * 2 + 4 - let done = DispatchSemaphore(value: 0) - - Task { - await withTaskGroup(of: Void.self) { group in - for _ in 0.. [Int32?] in + for _ in 0.. +// +// Each dir holds the payloads run.mjs captured: `export.json` (per-call records, +// the token/call source) and `menubar.json` (the unrounded per-provider cost). +// Prints one row per provider and exits non-zero on a diff that is not expected. +// +// Expectations, and why: +// claude, codex, gemini, kiro, cursor parse identically either side of the +// upgrade. Calls and every token field must match EXACTLY; cost is allowed +// COST_TOLERANCE of drift because the two binaries carry different bundled +// LiteLLM price snapshots and only agree when the shared pricing cache in +// CODEBURN_CACHE_DIR is warm (which it is, unless the runner is offline). +// grok changed by design in #1015: usage now comes from the CLI's own +// turn_completed records instead of a context-curve estimate. The change +// is REPORTED, never asserted — not even directionally. On real corpora +// the changelog documents totals rising, but that is a property of real +// Grok sessions, and the direction here would only reflect how the +// generator happened to size its synthetic context curve against its +// synthetic usage records. Both sides must still count the same SESSIONS, +// which is the part the corpus can honestly establish. +// dsh did not exist in the published CLI. Reported; required to be absent +// in the baseline and present after the upgrade. +const EXACT = ['claude', 'codex', 'gemini', 'kiro', 'cursor'] +const CHANGED_BY_DESIGN = ['grok'] +const NEW_IN_THIS_RELEASE = ['dsh'] + +const COST_TOLERANCE = 0.005 // 0.5% relative + +import { readFileSync } from 'node:fs' +import { join } from 'node:path' + +const [baseDir, upDir] = process.argv.slice(2) +if (!baseDir || !upDir) { + console.error('usage: compare.mjs ') + process.exit(2) +} + +const TOKEN_FIELDS = ['inputTokens', 'outputTokens', 'reasoningTokens', 'cacheWriteTokens', 'cacheReadTokens'] + +function load(dir) { + const exported = JSON.parse(readFileSync(join(dir, 'export.json'), 'utf8')) + const menubar = JSON.parse(readFileSync(join(dir, 'menubar.json'), 'utf8')) + const byProvider = {} + for (const r of exported.records ?? []) { + const p = r.provider || 'unknown' + const acc = (byProvider[p] ??= { calls: 0, cost: 0, ...Object.fromEntries(TOKEN_FIELDS.map(f => [f, 0])) }) + acc.calls++ + acc.cost += r.cost ?? 0 + for (const f of TOKEN_FIELDS) acc[f] += r[f] ?? 0 + } + // Prefer the unrounded cost, keyed by the provider's internal id. + // `providerDetails` is the only place that pairing exists — the sibling + // `providers` map is keyed by lowercased display name. The per-record sum + // above stands in when a binary predates providerDetails; it is rounded per + // record, so it is the coarser of the two. + for (const d of menubar.current?.providerDetails ?? []) { + if (byProvider[d.id]) byProvider[d.id].cost = d.cost + } + return byProvider +} + +const base = load(baseDir) +const up = load(upDir) +const providers = [...new Set([...Object.keys(base), ...Object.keys(up)])].sort() + +const failures = [] +const notes = [] +const rows = [] + +const relDiff = (a, b) => (a === 0 && b === 0 ? 0 : Math.abs(b - a) / Math.max(Math.abs(a), Math.abs(b))) +const fmt = n => (Number.isInteger(n) ? String(n) : n.toFixed(6)) + +for (const name of providers) { + const b = base[name] + const u = up[name] + let verdict + + if (NEW_IN_THIS_RELEASE.includes(name)) { + if (b) failures.push(`${name}: expected to be absent from the 0.9.20 baseline, but it reported ${b.calls} calls`) + else if (!u || u.calls === 0) failures.push(`${name}: new in this release but the upgraded run reported nothing`) + verdict = 'new (expected)' + } else if (!b || !u) { + failures.push(`${name}: present in ${b ? 'baseline' : 'upgraded'} only`) + verdict = 'MISSING' + } else if (CHANGED_BY_DESIGN.includes(name)) { + const bt = TOKEN_FIELDS.reduce((s, f) => s + b[f], 0) + const ut = TOKEN_FIELDS.reduce((s, f) => s + u[f], 0) + if (b.calls !== u.calls) failures.push(`${name}: usage accounting changed in #1015, but the session/call COUNT should not have: ${b.calls} != ${u.calls}`) + verdict = 'changed by design' + notes.push(`${name}: tokens ${bt} -> ${ut}, cost ${fmt(b.cost)} -> ${fmt(u.cost)} (#1015, expected; magnitude here is a property of the fixture, not evidence)`) + } else { + const diffs = [] + if (b.calls !== u.calls) diffs.push(`calls ${b.calls} != ${u.calls}`) + for (const f of TOKEN_FIELDS) if (b[f] !== u[f]) diffs.push(`${f} ${b[f]} != ${u[f]}`) + const costDrift = relDiff(b.cost, u.cost) + if (costDrift > COST_TOLERANCE) diffs.push(`cost ${fmt(b.cost)} != ${fmt(u.cost)} (${(costDrift * 100).toFixed(3)}% > ${(COST_TOLERANCE * 100).toFixed(1)}%)`) + if (!EXACT.includes(name)) { + notes.push(`${name}: no expectation declared in compare.mjs; ${diffs.length ? diffs.join(', ') : 'identical'}`) + verdict = diffs.length ? 'differs (unclassified)' : 'identical' + } else if (diffs.length) { + failures.push(`${name}: ${diffs.join(', ')}`) + verdict = 'DIFFERS' + } else { + verdict = costDrift === 0 ? 'identical' : `identical (cost ${(costDrift * 100).toFixed(3)}% drift)` + } + } + + rows.push({ + provider: name, + calls: `${b?.calls ?? '-'} -> ${u?.calls ?? '-'}`, + tokens: `${b ? TOKEN_FIELDS.reduce((s, f) => s + b[f], 0) : '-'} -> ${u ? TOKEN_FIELDS.reduce((s, f) => s + u[f], 0) : '-'}`, + cost: `${b ? fmt(b.cost) : '-'} -> ${u ? fmt(u.cost) : '-'}`, + verdict, + }) +} + +const cols = ['provider', 'calls', 'tokens', 'cost', 'verdict'] +const width = Object.fromEntries(cols.map(c => [c, Math.max(c.length, ...rows.map(r => r[c].length))])) +const line = r => cols.map(c => String(r[c]).padEnd(width[c])).join(' ') +console.log('') +console.log(line(Object.fromEntries(cols.map(c => [c, c.toUpperCase()])))) +console.log(cols.map(c => '-'.repeat(width[c])).join(' ')) +for (const r of rows) console.log(line(r)) +console.log('') +for (const n of notes) console.log(`note: ${n}`) +for (const f of failures) console.log(`FAIL: ${f}`) +console.log(failures.length ? `\nparity: ${failures.length} unexpected difference(s)` : '\nparity: ok') +process.exit(failures.length ? 1 : 0) diff --git a/scripts/upgrade-path/gen-corpus.mjs b/scripts/upgrade-path/gen-corpus.mjs new file mode 100644 index 00000000..a4ccbdb6 --- /dev/null +++ b/scripts/upgrade-path/gen-corpus.mjs @@ -0,0 +1,377 @@ +// Deterministic multi-provider fixture corpus for the upgrade-path check. +// +// node scripts/upgrade-path/gen-corpus.mjs +// +// Lays sessions out at each provider's DEFAULT path under , so the run +// only has to set HOME/USERPROFILE and no per-provider override var. Everything +// is seeded off a fixed constant: two invocations against the same day produce +// byte-identical files, which is what makes the worker-determinism and +// 0.9.20-vs-main payload comparisons meaningful. +// +// Day anchoring is the one thing that moves: sessions are dated relative to +// today so they land inside the daily cache's backfill window. That is fine — +// every comparison this corpus feeds happens inside a single run. + +import { mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs' +import { join } from 'node:path' +import { createRequire } from 'node:module' + +const require_ = createRequire(import.meta.url) + +const HOME = process.argv[2] +if (!HOME) { + console.error('usage: gen-corpus.mjs ') + process.exit(2) +} + +// mulberry32 — same seed, same corpus. +let seedState = 0x9e3779b9 +function rnd() { + seedState = (seedState + 0x6d2b79f5) | 0 + let t = seedState + t = Math.imul(t ^ (t >>> 15), t | 1) + t ^= t + Math.imul(t ^ (t >>> 7), t | 61) + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 +} +const pick = arr => arr[Math.floor(rnd() * arr.length)] +const between = (lo, hi) => lo + Math.floor(rnd() * (hi - lo)) + +// Day 0 = 92 days ago (UTC midnight); the corpus spans day 0..91. +const DAY_MS = 86_400_000 +const SPAN_DAYS = 92 +const day0 = Math.floor(Date.now() / DAY_MS) * DAY_MS - (SPAN_DAYS - 1) * DAY_MS +const at = (day, hour, min = 0, sec = 0) => + new Date(day0 + day * DAY_MS + hour * 3_600_000 + min * 60_000 + sec * 1000) +const iso = d => d.toISOString() + +const write = (path, body) => { + mkdirSync(join(path, '..'), { recursive: true }) + writeFileSync(path, body) +} +const writeLines = (path, lines) => write(path, lines.join('\n') + '\n') + +const PROJECTS = ['/work/api-gateway', '/work/billing', '/work/web app', '/work/infra'] + +// ── claude ─────────────────────────────────────────────────────────────────── +// 204 transcripts across the span: 200 plain, 2 parent/sidechain pairs. One +// plain transcript carries a single line over 32 KB (the large-line scanner +// path); the parent/sidechain pairs exercise the v7 spawn-link capture that the +// migration has to carry forward. + +const CLAUDE_MODELS = ['claude-sonnet-4-5', 'claude-opus-4-8', 'claude-haiku-4-5'] + +function claudeUser(sessionId, ts, cwd, text) { + return JSON.stringify({ type: 'user', sessionId, timestamp: iso(ts), cwd, gitBranch: 'main', message: { role: 'user', content: text } }) +} + +function claudeAssistant(sessionId, ts, cwd, msgId, model, usage, content) { + return JSON.stringify({ + type: 'assistant', sessionId, timestamp: iso(ts), cwd, gitBranch: 'main', + message: { id: msgId, type: 'message', role: 'assistant', model, content, usage }, + }) +} + +function claudeSession(sessionId, day, cwd, turns, opts = {}) { + const lines = [] + for (let t = 0; t < turns; t++) { + const ts = at(day, 9 + (t % 8), (t * 7) % 60) + lines.push(claudeUser(sessionId, ts, cwd, `task ${t} for ${sessionId}`)) + const content = [ + { type: 'text', text: `step ${t}` }, + { type: 'tool_use', id: `tu-${sessionId}-${t}`, name: t % 3 === 0 ? 'Edit' : 'Read', input: { file_path: `${cwd}/src/f${t}.ts` } }, + ] + // One line north of 32 KB, on the file the caller asked for it on. + if (opts.hugeLineAtTurn === t) content.push({ type: 'text', text: 'y'.repeat(40 * 1024) }) + lines.push(claudeAssistant(sessionId, at(day, 9 + (t % 8), (t * 7) % 60, 30), cwd, `msg-${sessionId}-${t}`, pick(CLAUDE_MODELS), { + input_tokens: between(400, 4000), + output_tokens: between(40, 900), + cache_read_input_tokens: between(0, 20000), + cache_creation_input_tokens: between(0, 3000), + }, content)) + } + return lines +} + +function genClaude() { + const projectsDir = join(HOME, '.claude', 'projects') + let files = 0 + for (let i = 0; i < 200; i++) { + const cwd = PROJECTS[i % PROJECTS.length] + const day = (i * 7) % SPAN_DAYS + const sid = `c-${String(i).padStart(4, '0')}` + const dirName = cwd.replace(/[/ ]/g, '-') + writeLines(join(projectsDir, dirName, `${sid}.jsonl`), claudeSession(sid, day, cwd, between(4, 14), i === 137 ? { hugeLineAtTurn: 2 } : {})) + files++ + } + + // Two parent transcripts, each spawning one subagent whose transcript lives + // under /subagents/agent-.jsonl and is marked isSidechain. + for (let p = 0; p < 2; p++) { + const cwd = PROJECTS[p] + const dirName = cwd.replace(/[/ ]/g, '-') + const parent = `p-000${p}` + const agent = `a-000${p}` + const day = 40 + p * 10 + const parentLines = claudeSession(parent, day, cwd, 5) + parentLines.push(JSON.stringify({ + type: 'assistant', sessionId: parent, timestamp: iso(at(day, 12)), cwd, + message: { id: `m-spawn-${p}`, type: 'message', role: 'assistant', model: 'claude-sonnet-4-5', content: [{ type: 'tool_use', id: `toolu_spawn_${p}`, name: 'Agent', input: {} }], usage: { input_tokens: 120, output_tokens: 30 } }, + })) + parentLines.push(JSON.stringify({ + type: 'user', sessionId: parent, timestamp: iso(at(day, 12, 1)), cwd, + message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: `toolu_spawn_${p}`, content: 'subagent done' }] }, + toolUseResult: { status: 'completed', agentId: agent, content: 'subagent done' }, + })) + parentLines.push(JSON.stringify({ type: 'pr-link', sessionId: parent, timestamp: iso(at(day, 12, 2)), cwd, prUrl: `https://github.com/acme/repo/pull/${100 + p}` })) + writeLines(join(projectsDir, dirName, `${parent}.jsonl`), parentLines) + files++ + + const side = [] + for (let t = 0; t < 4; t++) { + side.push(JSON.stringify({ type: 'user', isSidechain: true, sessionId: parent, agentId: agent, timestamp: iso(at(day, 12, 3 + t)), cwd, message: { role: 'user', content: `sub task ${t}` } })) + side.push(JSON.stringify({ + type: 'assistant', isSidechain: true, sessionId: parent, agentId: agent, timestamp: iso(at(day, 12, 3 + t, 20)), cwd, + message: { id: `sub-${p}-${t}`, type: 'message', role: 'assistant', model: 'claude-opus-4-8', content: [{ type: 'text', text: 'ok' }], usage: { input_tokens: between(800, 2000), output_tokens: between(100, 400), cache_read_input_tokens: between(0, 5000) } }, + })) + } + writeLines(join(projectsDir, dirName, parent, 'subagents', `agent-${agent}.jsonl`), side) + write(join(projectsDir, dirName, parent, 'subagents', `agent-${agent}.meta.json`), JSON.stringify({ agentType: 'reviewer' })) + files++ + } + return files +} + +// ── codex ──────────────────────────────────────────────────────────────────── +// token_count carries a CUMULATIVE total_token_usage; the parser diffs +// consecutive events, so the running totals below must only ever grow. + +function genCodex() { + const root = join(HOME, '.codex', 'sessions') + let files = 0 + for (let i = 0; i < 24; i++) { + const day = (i * 4) % SPAN_DAYS + const d = new Date(day0 + day * DAY_MS) + const cwd = PROJECTS[i % PROJECTS.length] + const sid = `codex-${String(i).padStart(3, '0')}` + const lines = [JSON.stringify({ type: 'session_meta', timestamp: iso(at(day, 10)), payload: { cwd, originator: 'codex-cli', session_id: sid, model: 'gpt-5.3-codex' } })] + const total = { input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, reasoning_output_tokens: 0, total_tokens: 0 } + for (let t = 0; t < between(3, 9); t++) { + const ts = iso(at(day, 10, t * 5)) + const last = { input_tokens: between(500, 6000), cached_input_tokens: between(0, 2000), output_tokens: between(50, 800), reasoning_output_tokens: between(0, 300), total_tokens: 0 } + last.total_tokens = last.input_tokens + last.output_tokens + for (const k of Object.keys(total)) total[k] += last[k] + lines.push(JSON.stringify({ type: 'event_msg', timestamp: ts, payload: { type: 'task_started' } })) + lines.push(JSON.stringify({ type: 'response_item', timestamp: ts, payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text: `task ${t}` }] } })) + lines.push(JSON.stringify({ type: 'response_item', timestamp: ts, payload: { type: 'function_call', name: 'shell', call_id: `c${t}`, arguments: JSON.stringify({ command: 'ls' }) } })) + lines.push(JSON.stringify({ type: 'response_item', timestamp: ts, payload: { type: 'function_call_output', call_id: `c${t}` } })) + lines.push(JSON.stringify({ type: 'response_item', timestamp: ts, payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'done' }] } })) + lines.push(JSON.stringify({ type: 'event_msg', timestamp: ts, payload: { type: 'token_count', info: { last_token_usage: last, total_token_usage: { ...total } } } })) + lines.push(JSON.stringify({ type: 'event_msg', timestamp: ts, payload: { type: 'task_complete', duration_ms: 4000 } })) + } + const dir = join(root, String(d.getUTCFullYear()), String(d.getUTCMonth() + 1).padStart(2, '0'), String(d.getUTCDate()).padStart(2, '0')) + writeLines(join(dir, `rollout-${sid}.jsonl`), lines) + files++ + } + return files +} + +// ── gemini ─────────────────────────────────────────────────────────────────── + +function genGemini() { + const messages = [] + for (let t = 0; t < 12; t++) { + messages.push({ id: `u${t}`, timestamp: iso(at(60, 9, t * 3)), type: 'user', content: `inspect ${t}` }) + messages.push({ + id: `g${t}`, timestamp: iso(at(60, 9, t * 3, 20)), type: 'gemini', content: 'reading files', + model: 'gemini-3.1-pro-preview', + tokens: { input: between(200, 3000), cached: between(0, 1000), output: between(30, 400), thoughts: between(0, 200) }, + toolCalls: [{ id: `t${t}`, name: 'read_file', args: { path: 'src/index.ts' } }], + }) + } + write(join(HOME, '.gemini', 'tmp', 'api-gateway', 'chats', 'session-upgrade-1.json'), + JSON.stringify({ sessionId: 'gemini-session-1', startTime: iso(at(60, 9)), messages })) + return 1 +} + +// ── kiro ───────────────────────────────────────────────────────────────────── + +function genKiro() { + const dir = join(HOME, '.kiro', 'sessions', 'cli') + const id = 'kiro-upgrade-1' + const lines = [] + for (let t = 0; t < 6; t++) { + lines.push(JSON.stringify({ kind: 'Prompt', data: { content: [{ kind: 'text', data: `add feature ${t}` }] } })) + lines.push(JSON.stringify({ kind: 'AssistantMessage', data: { content: [{ kind: 'text', data: `Done — added feature ${t} and its tests.` }] } })) + } + writeLines(join(dir, `${id}.jsonl`), lines) + write(join(dir, `${id}.json`), JSON.stringify({ + session_id: id, cwd: '/work/billing', + created_at: iso(at(70, 10)), updated_at: iso(at(70, 11)), + session_state: { + rts_model_state: { model_info: { model_id: 'auto' } }, + conversation_metadata: { user_turn_metadatas: [{ end_timestamp: iso(at(70, 11)), metering_usage: [] }] }, + }, + })) + return 2 +} + +// ── dsh ────────────────────────────────────────────────────────────────────── +// Written UNCOMPRESSED on purpose: node:zlib gained zstd in 22.15 and the +// package floor is 22.13, so the .zstd variant would silently drop out of the +// floor matrix leg and the two legs would not be comparable. + +function genDsh() { + const cwd = '/work/api-gateway' + const encoded = `--${cwd.replace(/[/\\]/g, '-')}--` + const dir = join(HOME, '.dsh', 'sessions', encoded, 'session-upgrade-0001') + const lines = [ + JSON.stringify({ type: 'session', version: 0, id: 'session-upgrade-0001', createdAt: at(75, 10).getTime(), cwd, delegationDepth: 0, agentPreset: 'cordis' }), + JSON.stringify({ type: 'request/header', seq: 1, time: at(75, 10).getTime(), data: { header: { config: { provider: 'deepseek-official', model: 'deepseek-v3.2', reasoningEffort: 'max', maxTokens: 256000 } } } }), + ] + let seq = 2 + for (let turn = 1; turn <= 8; turn++) { + const base = at(75, 10, turn * 5).getTime() + lines.push(JSON.stringify({ type: 'turn/start', seq: seq++, time: base, data: { turn } })) + lines.push(JSON.stringify({ type: 'user/message', seq: seq++, time: base + 100, data: { content: [{ type: 'text', text: `build ${turn}` }], source: { kind: 'user' }, role: 'user', id: `msg-${turn}` } })) + lines.push(JSON.stringify({ type: 'tool/call', seq: seq++, time: base + 200, data: { turn, step: 1, callId: `call_${turn}`, name: 'bash', arguments: JSON.stringify({ command: 'git status' }) } })) + lines.push(JSON.stringify({ + type: 'assistant/message', seq: seq++, time: base + 900, + data: { turn, step: 1, message: { role: 'assistant', content: [{ type: 'text', text: 'done' }] }, usage: { inputTokens: between(2000, 20000), outputTokens: between(100, 900), cacheReadTokens: between(0, 5000), reasoningTokens: between(0, 600) } }, + })) + } + writeLines(join(dir, 'session.jsonl'), lines) + return 1 +} + +// ── grok ───────────────────────────────────────────────────────────────────── +// Uses the authoritative `turn_completed.usage` records that #1015 switched to. + +function genGrok() { + const cwd = '/work/infra' + const root = join(HOME, '.grok', 'sessions', encodeURIComponent(cwd)) + let files = 0 + for (let i = 0; i < 3; i++) { + const id = `019edf9c-0000-7000-8000-00000000000${i + 1}` + const day = 80 + i + const dir = join(root, id) + write(join(dir, 'summary.json'), JSON.stringify({ + info: { id, cwd }, created_at: iso(at(day, 11)), updated_at: iso(at(day, 12)), last_active_at: iso(at(day, 12)), + num_messages: 12, current_model_id: 'grok-build', session_summary: 'repo work', generated_title: 'repo work', + })) + write(join(dir, 'signals.json'), JSON.stringify({ + primaryModelId: 'grok-build', modelsUsed: ['grok-build'], toolsUsed: ['read_file', 'grep'], + contextTokensUsed: 40000, contextWindowTokens: 512000, + })) + const updates = [] + let running = 0 + for (let t = 0; t < 5; t++) { + // Streamed chunk carrying the running context counter. This is all the + // published CLI can see, and what it estimates from; main ignores it in + // favour of the turn_completed record below. Both are present in a real + // session, so the corpus carries both and the two versions have something + // to disagree about. + running += between(3000, 12000) + updates.push(JSON.stringify({ + timestamp: iso(at(day, 11, t * 5)), method: 'session/update', + params: { sessionId: id, update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: `chunk ${t}` } }, _meta: { totalTokens: running, promptId: `p${t}`, updateType: 'AgentMessageChunk', modelId: 'grok-build' } }, + })) + const usage = { + inputTokens: between(1000, 9000), outputTokens: between(80, 700), totalTokens: 0, + cachedReadTokens: between(0, 40000), cacheCreationTokens: between(0, 2000), reasoningTokens: between(0, 300), + modelCalls: 1, apiDurationMs: 1000, costUsdTicks: 125117780000, numTurns: 1, + } + usage.totalTokens = usage.inputTokens + usage.outputTokens + usage.modelUsage = { 'grok-4.6-build': { ...usage } } + updates.push(JSON.stringify({ + timestamp: Math.floor(at(day, 11, t * 5).getTime() / 1000), method: '_x.ai/session/update', + params: { sessionId: id, update: { sessionUpdate: 'turn_completed', prompt_id: `p${t}`, usage }, _meta: { eventId: `event-${t}`, agentTimestampMs: at(day, 11, t * 5).getTime() } }, + })) + } + writeLines(join(dir, 'updates.jsonl'), updates) + files += 3 + } + return files +} + +// ── cursor (WAL-mode SQLite) ───────────────────────────────────────────────── +// Left with an un-checkpointed -wal sidecar and NO -shm: that is what a live +// Cursor database looks like on disk, and it is the shape that made +// read-only opens fail before #1017. + +function genCursor() { + let DatabaseSync + try { ({ DatabaseSync } = require_('node:sqlite')) } catch { return 0 } + + const userDir = process.platform === 'darwin' + ? join(HOME, 'Library', 'Application Support', 'Cursor', 'User') + : process.platform === 'win32' + ? join(HOME, 'AppData', 'Roaming', 'Cursor', 'User') + : join(HOME, '.config', 'Cursor', 'User') + + const globalDir = join(userDir, 'globalStorage') + mkdirSync(globalDir, { recursive: true }) + const dbPath = join(globalDir, 'state.vscdb') + for (const suffix of ['', '-wal', '-shm']) rmSync(dbPath + suffix, { force: true }) + const db = new DatabaseSync(dbPath) + db.exec('PRAGMA journal_mode=WAL') + db.exec('CREATE TABLE cursorDiskKV (key TEXT PRIMARY KEY, value BLOB)') + db.exec('CREATE TABLE ItemTable (key TEXT UNIQUE, value BLOB)') + const ins = db.prepare('INSERT INTO cursorDiskKV (key, value) VALUES (?, ?)') + + const composers = [] + for (let c = 0; c < 6; c++) { + const composerId = `composer-${c}` + composers.push({ composerId, name: `session-${c}`, unifiedMode: 'agent' }) + ins.run(`composerData:${composerId}`, JSON.stringify({ + promptTokenBreakdown: { totalUsedTokens: between(10000, 90000) }, + createdAt: at(85, 9 + c).getTime(), + })) + for (let b = 0; b < 8; b++) { + const createdAt = iso(at(85, 9 + c, b * 4)) + ins.run(`bubbleId:${composerId}:u${b}`, JSON.stringify({ type: 1, conversationId: composerId, createdAt, text: `ask ${b}`, codeBlocks: '[]' })) + ins.run(`bubbleId:${composerId}:a${b}`, JSON.stringify({ + type: 2, conversationId: composerId, createdAt, text: `reply ${b}`, codeBlocks: '[]', + tokenCount: { inputTokens: between(300, 4000), outputTokens: between(40, 500) }, + modelInfo: { modelName: 'claude-4.6-sonnet' }, + requestId: `req-${c}-${b}`, + })) + } + } + // Checkpoint what is written so far, then stop auto-checkpointing and append + // more: the tail rows live only in the -wal the copy below carries. + db.exec('PRAGMA wal_checkpoint(TRUNCATE)') + db.exec('PRAGMA wal_autocheckpoint=0') + ins.run('composerData:composer-tail', JSON.stringify({ promptTokenBreakdown: { totalUsedTokens: 12345 }, createdAt: at(86, 9).getTime() })) + ins.run('bubbleId:composer-tail:a0', JSON.stringify({ + type: 2, conversationId: 'composer-tail', createdAt: iso(at(86, 9)), text: 'tail reply', codeBlocks: '[]', + tokenCount: { inputTokens: 2222, outputTokens: 333 }, modelInfo: { modelName: 'claude-4.6-sonnet' }, + })) + composers.push({ composerId: 'composer-tail', name: 'session-tail', unifiedMode: 'agent' }) + db.close() + + // Per-workspace DB naming the composers, plus the workspace.json that gives + // the project its name. + const wsDir = join(userDir, 'workspaceStorage', 'ws0000000000000000000000000000000') + mkdirSync(wsDir, { recursive: true }) + for (const suffix of ['', '-wal', '-shm']) rmSync(join(wsDir, 'state.vscdb' + suffix), { force: true }) + const wsDb = new DatabaseSync(join(wsDir, 'state.vscdb')) + wsDb.exec('CREATE TABLE ItemTable (key TEXT UNIQUE, value BLOB)') + wsDb.prepare('INSERT INTO ItemTable (key, value) VALUES (?, ?)').run('composer.composerData', JSON.stringify({ allComposers: composers })) + wsDb.close() + write(join(wsDir, 'workspace.json'), JSON.stringify({ folder: 'file:///work/billing' })) + + return existsSync(dbPath + '-wal') ? 3 : 2 +} + +// ── run ────────────────────────────────────────────────────────────────────── + +const counts = { + claude: genClaude(), + codex: genCodex(), + gemini: genGemini(), + kiro: genKiro(), + dsh: genDsh(), + grok: genGrok(), + cursor: genCursor(), +} +console.log(JSON.stringify(counts)) diff --git a/scripts/upgrade-path/run.mjs b/scripts/upgrade-path/run.mjs new file mode 100644 index 00000000..f4bb0e53 --- /dev/null +++ b/scripts/upgrade-path/run.mjs @@ -0,0 +1,422 @@ +// Upgrade-path verification: prove that a cache written by the last PUBLISHED +// CLI survives this build's first run, on this platform, with this Node. +// +// npm run verify:upgrade +// +// What it does, in order: +// 1. generates a deterministic multi-provider corpus into an isolated HOME +// (whose path contains a space, because a real Windows HOME usually does) +// 2. installs codeburn@0.9.20 into an isolated global prefix and runs it, +// producing a genuine session-cache.v7 + daily-cache.v17 +// 3. installs THIS build the same way and runs it against the SAME cache dir, +// through the npm bin shim rather than `node dist/cli.js`, so +// dist/parse-worker.js has to resolve from a symlinked entry point +// 4. asserts the migration landed and compares payloads per provider +// 5. serve --stdio smoke, worker determinism, warm-run stability +// +// Env: UPGRADE_PATH_WORK (work dir), UPGRADE_PATH_OLD (published version to +// upgrade from), UPGRADE_PATH_KEEP=1 to leave the work dir behind. + +import { spawnSync, spawn } from 'node:child_process' +import { mkdirSync, rmSync, existsSync, readdirSync, statSync, readFileSync, writeFileSync, copyFileSync } from 'node:fs' +import { join, dirname } from 'node:path' +import { fileURLToPath } from 'node:url' +import { tmpdir } from 'node:os' + +const HERE = dirname(fileURLToPath(import.meta.url)) +const REPO = join(HERE, '..', '..') +const OLD_VERSION = process.env['UPGRADE_PATH_OLD'] || '0.9.20' +const WORK = process.env['UPGRADE_PATH_WORK'] || join(tmpdir(), 'codeburn upgrade path') + +// The published binary's cache versions. If a future baseline writes something +// else these two are the knobs to move, and the assertions below will say so. +const OLD_SESSION_CACHE = 'session-cache.v7.json' +const OLD_DAILY_CACHE = 'daily-cache.v17.json' +const NEW_SESSION_CACHE_DIR = 'session-cache.v9' +const NEW_DAILY_CACHE = 'daily-cache.v21.json' + +const HOME = join(WORK, 'user home') +const PAYLOADS = join(WORK, 'payloads') +const CACHES = join(WORK, 'caches') +const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm' + +let failures = 0 +let skipped = 0 +const step = msg => console.log(`\n=== ${msg}`) +const ok = msg => console.log(` ok ${msg}`) +const fail = msg => { failures++; console.log(` FAIL ${msg}`) } +const skip = msg => { skipped++; console.log(` skip ${msg}`) } +const check = (cond, msg) => (cond ? ok(msg) : fail(msg)) + +function run(cmd, args, opts = {}) { + const r = spawnSync(cmd, args, { encoding: 'utf8', maxBuffer: 1 << 29, shell: false, ...opts }) + if (r.error) throw new Error(`${cmd} ${args.join(' ')}: ${r.error.message}`) + return r +} + +// Node refuses to spawn a .cmd/.bat without a shell, and a shell spawn quotes +// nothing for you — so on Windows anything holding a space (every path here +// does, by design) has to be quoted by hand. +const quoteForShell = s => (process.platform === 'win32' && /[\s&|^]/.test(s) ? `"${s}"` : s) +function runShell(cmd, args, opts = {}) { + if (process.platform !== 'win32') return run(cmd, args, opts) + return run(quoteForShell(cmd), args.map(quoteForShell), { ...opts, shell: true }) +} + +function cliEnv(cacheDir, extra = {}) { + // Deliberately minimal: no provider override vars, so every provider resolves + // its own default path under the isolated HOME. APPDATA/LOCALAPPDATA are + // pinned under it too — several providers read them on Windows, and inheriting + // the runner's would let real (or leftover) data into the comparison. + const passthrough = {} + for (const k of ['PATH', 'PATHEXT', 'SystemRoot', 'ComSpec', 'windir', 'TEMP', 'TMP', 'NUMBER_OF_PROCESSORS']) { + if (process.env[k] !== undefined) passthrough[k] = process.env[k] + } + return { + ...passthrough, + HOME, USERPROFILE: HOME, TZ: 'UTC', CODEBURN_CACHE_DIR: cacheDir, + APPDATA: join(HOME, 'AppData', 'Roaming'), LOCALAPPDATA: join(HOME, 'AppData', 'Local'), + ...extra, + } +} + +function cli(bin, args, cacheDir, extra = {}) { + const r = run(bin.cmd, [...bin.args, ...args], { env: cliEnv(cacheDir, extra), cwd: WORK }) + if (r.status !== 0) throw new Error(`${args.join(' ')} exited ${r.status}\n${r.stderr?.slice(0, 4000)}`) + return r.stdout +} + +// Install into an isolated global prefix, so the CLI runs from a location that +// has nothing to do with this checkout — which is what makes dist/parse-worker.js +// resolution worth testing. On POSIX npm's bin is a symlink INTO the package and +// we drive that directly. On Windows it is a .cmd shim, which Node will not +// spawn without a shell; the payload captures go through the installed +// dist/cli.js there and the shim itself is smoke-tested once, separately. +function installGlobal(prefix, spec) { + const r = runShell(npmCmd, ['install', '-g', '--prefix', prefix, spec, '--no-audit', '--no-fund', '--loglevel', 'error'], { cwd: WORK }) + if (r.status !== 0) throw new Error(`npm install -g ${spec} exited ${r.status}\n${r.stdout}\n${r.stderr}`) + const symlink = join(prefix, 'bin', 'codeburn') + if (existsSync(symlink)) return { cmd: process.execPath, args: [symlink], shim: null } + const winCmd = join(prefix, 'codeburn.cmd') + const entry = join(prefix, 'node_modules', 'codeburn', 'dist', 'cli.js') + if (existsSync(entry)) return { cmd: process.execPath, args: [entry], shim: existsSync(winCmd) ? winCmd : null } + throw new Error(`no codeburn bin under ${prefix}`) +} + +// The npm shim, exercised once. Needs a shell on Windows, so nothing with a +// space in it is passed through here. +function checkShim(bin, cacheDir) { + if (!bin.shim) { ok("CLI invoked through npm's bin symlink"); return } + const r = runShell(bin.shim, ['--version'], { env: cliEnv(cacheDir), cwd: WORK }) + check(r.status === 0 && r.stdout.trim().length > 0, `npm .cmd shim runs: ${r.stdout.trim() || r.stderr?.slice(0, 200)}`) +} + +// Captured payloads. `export` is the token/call source, `menubar-json` the +// unrounded per-provider cost; both are stable given a fixed corpus. --period all +// so the whole three-month corpus is in scope on both sides. +function capture(bin, cacheDir, outDir, extra = {}) { + mkdirSync(outDir, { recursive: true }) + cli(bin, ['export', '--format', 'json', '--from', '2000-01-01', '--to', '2999-12-31', '-o', join(outDir, 'export.json')], cacheDir, extra) + const menubar = cli(bin, ['status', '--format', 'menubar-json', '--period', 'all', '--no-optimize', '--no-timeline'], cacheDir, extra) + writeFileSync(join(outDir, 'menubar.json'), menubar) + const status = cli(bin, ['status', '--format', 'json', '--period', 'all'], cacheDir, extra) + writeFileSync(join(outDir, 'status.json'), status) + return { menubar: JSON.parse(menubar), status: JSON.parse(status) } +} + +// The one field that moves between two runs of the same payload. +const stripGenerated = obj => JSON.parse(JSON.stringify(obj, (k, v) => (k.startsWith('generated') ? undefined : v))) + +// Shards carry real stat data and are published under a random filename, so +// "identical" means identical after normalizing both away. +function shardSnapshot(cacheDir) { + const dir = join(cacheDir, NEW_SESSION_CACHE_DIR) + if (!existsSync(dir)) return null + const out = {} + for (const name of readdirSync(dir).sort()) { + if (name === 'envelope.json') continue + const body = JSON.parse(readFileSync(join(dir, name), 'utf8')) + for (const entry of Object.values(body)) { + if (entry && typeof entry === 'object' && entry.fingerprint) { + delete entry.fingerprint.dev + delete entry.fingerprint.ino + delete entry.fingerprint.mtimeMs + } + } + // Key the bucket off the shard's provider.month prefix, dropping the nonce. + out[name.replace(/\.[0-9a-f]{16}\.json$/, '')] = sortDeep(body) + } + return out +} + +function sortDeep(v) { + if (Array.isArray(v)) return v.map(sortDeep) + if (v && typeof v === 'object') return Object.fromEntries(Object.keys(v).sort().map(k => [k, sortDeep(v[k])])) + return v +} + +function shardMtimes(cacheDir) { + const dir = join(cacheDir, NEW_SESSION_CACHE_DIR) + return Object.fromEntries(readdirSync(dir).sort().map(n => [n, statSync(join(dir, n)).mtimeMs])) +} + +// ── 1. corpus ──────────────────────────────────────────────────────────────── + +step(`work dir: ${WORK}`) +try { rmSync(WORK, { recursive: true, force: true }) } catch (err) { console.log(` note could not clear the work dir (${err.code}); reusing it`) } +mkdirSync(HOME, { recursive: true }) +mkdirSync(PAYLOADS, { recursive: true }) + +const gen = run(process.execPath, [join(HERE, 'gen-corpus.mjs'), HOME]) +if (gen.status !== 0) { console.log(gen.stderr); process.exit(1) } +ok(`corpus generated: ${gen.stdout.trim()}`) + +const upgradeCache = join(CACHES, 'upgrade') +mkdirSync(upgradeCache, { recursive: true }) + +// ── 2. baseline: the last published CLI ────────────────────────────────────── + +step(`baseline: codeburn@${OLD_VERSION}`) +const oldBin = installGlobal(join(WORK, 'old'), `codeburn@${OLD_VERSION}`) +const oldVersion = cli(oldBin, ['--version'], upgradeCache).trim() +check(oldVersion === OLD_VERSION, `installed baseline reports ${oldVersion}`) + +const baseline = capture(oldBin, upgradeCache, join(PAYLOADS, 'baseline')) +check(baseline.menubar.current.calls > 0, `baseline counted ${baseline.menubar.current.calls} calls across ${baseline.menubar.current.sessions} sessions`) +check(existsSync(join(upgradeCache, OLD_SESSION_CACHE)), `${OLD_VERSION} wrote ${OLD_SESSION_CACHE}`) +check(existsSync(join(upgradeCache, OLD_DAILY_CACHE)), `${OLD_VERSION} wrote ${OLD_DAILY_CACHE}`) + +// ── 3. upgrade: this build, same cache dir, through the npm bin shim ───────── + +step('upgrade: this build against the same cache dir') +const pack = runShell(npmCmd, ['pack', '--ignore-scripts', '--pack-destination', WORK, '--loglevel', 'error'], { cwd: REPO }) +if (pack.status !== 0) { console.log(pack.stdout, pack.stderr); process.exit(1) } +const tarball = join(WORK, pack.stdout.trim().split('\n').pop().trim()) +const newBin = installGlobal(join(WORK, 'new'), tarball) +ok(`this build installed as ${newBin.args[0] ?? newBin.cmd}`) +checkShim(newBin, upgradeCache) + +const upgraded = capture(newBin, upgradeCache, join(PAYLOADS, 'upgraded')) + +check(!existsSync(join(upgradeCache, OLD_SESSION_CACHE)), `${OLD_SESSION_CACHE} removed after the re-layout`) +check(existsSync(join(upgradeCache, NEW_SESSION_CACHE_DIR)), `${NEW_SESSION_CACHE_DIR}/ present`) +check(existsSync(join(upgradeCache, NEW_SESSION_CACHE_DIR, 'envelope.json')), `${NEW_SESSION_CACHE_DIR}/envelope.json present`) +const envelope = JSON.parse(readFileSync(join(upgradeCache, NEW_SESSION_CACHE_DIR, 'envelope.json'), 'utf8')) +check(envelope.version === 9 && Object.keys(envelope.providers ?? {}).length > 0, + `envelope at version ${envelope.version} with ${Object.keys(envelope.providers ?? {}).length} providers`) +check(readdirSync(join(upgradeCache, NEW_SESSION_CACHE_DIR)).some(n => n !== 'envelope.json'), 'shards published alongside the envelope') +check(existsSync(join(upgradeCache, NEW_DAILY_CACHE)), `${NEW_DAILY_CACHE} re-derived`) +check(existsSync(join(upgradeCache, OLD_DAILY_CACHE)), `${OLD_DAILY_CACHE} kept as the carry-forward baseline`) +const oldDays = JSON.parse(readFileSync(join(upgradeCache, OLD_DAILY_CACHE), 'utf8')).days.length +const newDays = JSON.parse(readFileSync(join(upgradeCache, NEW_DAILY_CACHE), 'utf8')).days.length +check(newDays >= oldDays, `daily history did not shrink: ${oldDays} -> ${newDays} days`) + +// ── 4. payload parity ──────────────────────────────────────────────────────── + +step('payload parity vs the baseline') +const cmp = run(process.execPath, [join(HERE, 'compare.mjs'), join(PAYLOADS, 'baseline'), join(PAYLOADS, 'upgraded')], { stdio: 'inherit' }) +if (cmp.status !== 0) failures++ + +// ── 5. serve smoke ─────────────────────────────────────────────────────────── + +step('serve --stdio') +const serveFrames = await serveSmoke() +if (serveFrames) { + for (const [name, args] of [['menubar-json', ['status', '--format', 'menubar-json', '--period', 'all', '--no-optimize', '--no-timeline']], ['models', ['models', '--format', 'json']]]) { + const frame = serveFrames.get(name) + if (!frame?.ok) { fail(`serve returned no ok frame for ${name}: ${JSON.stringify(frame)}`); continue } + ok(`serve ok frame for ${name}`) + const oneShot = cli(newBin, args, upgradeCache) + const a = JSON.stringify(stripGenerated(JSON.parse(frame.output))) + const b = JSON.stringify(stripGenerated(JSON.parse(oneShot))) + check(a === b, `serve ${name} matches the one-shot payload (ignoring generated*)`) + } +} + +async function serveSmoke() { + const child = spawn(newBin.cmd, [...newBin.args, 'serve', '--stdio'], { env: cliEnv(upgradeCache), cwd: WORK, stdio: ['pipe', 'pipe', 'pipe'] }) + const frames = new Map() + let buf = '' + let ready = false + const done = new Promise(resolve => { + child.stdout.on('data', d => { + buf += d + let nl + while ((nl = buf.indexOf('\n')) >= 0) { + const line = buf.slice(0, nl); buf = buf.slice(nl + 1) + if (!line.trim()) continue + let msg + try { msg = JSON.parse(line) } catch { continue } + if (msg.ready) { ready = true; continue } + if (msg.progress !== undefined) continue + if (msg.id === 1) frames.set('menubar-json', msg) + if (msg.id === 2) frames.set('models', msg) + if (frames.size === 2) resolve() + } + }) + }) + child.stdin.write(JSON.stringify({ id: 1, args: ['status', '--format', 'menubar-json', '--period', 'all', '--no-optimize', '--no-timeline'] }) + '\n') + child.stdin.write(JSON.stringify({ id: 2, args: ['models', '--format', 'json'] }) + '\n') + const timeout = new Promise(r => setTimeout(() => r('timeout'), 240_000)) + if ((await Promise.race([done, timeout])) === 'timeout') { child.kill(); fail('serve did not answer both requests within 240s'); return null } + check(ready, 'serve announced itself with a ready frame') + + // Closing stdin is the documented shutdown: the child must exit on its own. + const exited = new Promise(r => child.once('exit', code => r(code))) + child.stdin.end() + const exitCode = await Promise.race([exited, new Promise(r => setTimeout(() => r('hung'), 30_000))]) + if (exitCode === 'hung') { child.kill(); fail('serve did not exit when stdin closed') } + else ok(`serve exited on stdin close (code ${exitCode})`) + return frames +} + +// ── 6. worker determinism ──────────────────────────────────────────────────── + +step('parse-worker determinism (CODEBURN_PARSE_WORKERS 0 vs 3)') +const serialCache = join(CACHES, 'workers-0') +const parallelCache = join(CACHES, 'workers-3') +for (const dir of [serialCache, parallelCache]) { + mkdirSync(dir, { recursive: true }) + // Seed the shared price table so the two runs cannot be priced differently by + // a cache expiring between them. Parsing is unaffected either way. + const priced = join(upgradeCache, 'litellm-pricing.json') + if (existsSync(priced)) copyFileSync(priced, join(dir, 'litellm-pricing.json')) +} +const serialOut = capture(newBin, serialCache, join(PAYLOADS, 'workers-0'), { CODEBURN_PARSE_WORKERS: '0', CODEBURN_VERBOSE: '1' }) +const parallelOut = capture(newBin, parallelCache, join(PAYLOADS, 'workers-3'), { CODEBURN_PARSE_WORKERS: '3', CODEBURN_VERBOSE: '1' }) +check(JSON.stringify(stripGenerated(serialOut.menubar)) === JSON.stringify(stripGenerated(parallelOut.menubar)), + 'menubar-json payload identical with and without workers') +const readExport = dir => stripGenerated(JSON.parse(readFileSync(join(PAYLOADS, dir, 'export.json'), 'utf8'))) +check(JSON.stringify(readExport('workers-0')) === JSON.stringify(readExport('workers-3')), + 'export payload identical with and without workers') +check(JSON.stringify(shardSnapshot(serialCache)) === JSON.stringify(shardSnapshot(parallelCache)), + 'shard bodies identical with and without workers (fingerprint stat data and shard nonces normalized)') + +// A forced pool that never actually spawned would make the check above vacuous. +const verbose = run(newBin.cmd, [...newBin.args, 'status', '--format', 'json', '--period', 'all'], { + env: cliEnv(join(CACHES, 'workers-probe'), { CODEBURN_PARSE_WORKERS: '3', CODEBURN_VERBOSE: '1' }), cwd: WORK, +}) +const decision = (verbose.stderr || '').split('\n').filter(l => l.includes('parse workers=')) +if (decision.length === 0) skip('no "parse workers=" line on stderr; cannot confirm the pool was forced') +else check(decision.some(l => /parse workers=[1-9]/.test(l)), `worker pool engaged: ${decision.map(l => l.trim()).join(' | ')}`) + +// ── 7. second run is warm ──────────────────────────────────────────────────── + +step('second run is warm') +const beforeBodies = shardSnapshot(upgradeCache) +const beforeMtimes = shardMtimes(upgradeCache) +const warm = capture(newBin, upgradeCache, join(PAYLOADS, 'warm')) + +// The direct no-re-parse signal: the worker gate prints how many whole-file +// re-parses are pending. On an unchanged corpus that must be zero for the two +// providers big enough to be gated. +const warmVerbose = run(newBin.cmd, [...newBin.args, 'status', '--format', 'menubar-json', '--period', 'all', '--no-optimize', '--no-timeline'], { + env: cliEnv(upgradeCache, { CODEBURN_VERBOSE: '1' }), cwd: WORK, +}) +const pending = (warmVerbose.stderr || '').split('\n').filter(l => l.includes('parse workers=')) +if (pending.length === 0) skip('no "parse workers=" line on a warm run; cannot confirm nothing re-parsed') +else check(pending.every(l => /0 pending files|no full parses pending/.test(l)), + `nothing re-parsed on the warm run: ${pending.map(l => l.replace(/^codeburn: /, '').trim()).join(' | ')}`) + +check(JSON.stringify(shardSnapshot(upgradeCache)) === JSON.stringify(beforeBodies), 'warm run left every shard body unchanged') +check(JSON.stringify(stripGenerated(warm.menubar)) === JSON.stringify(stripGenerated(upgraded.menubar)), + 'warm run reports the same payload as the run that migrated the cache') + +// Republication without a content change is wasted I/O, not a correctness +// problem, so it is reported rather than failed. It is real, and it has a +// follow-up issue: a date-RANGED query (`status --format json`, the +// statusline/menubar fast path) republishes the month shards its range skipped, +// on every run, even when nothing changed — partially defeating #1007's +// "a warm launch rewrites only the month that changed". The identical-bodies +// check above is what proves the content survives it. +const afterMtimes = shardMtimes(upgradeCache) +const republished = Object.keys(afterMtimes).filter(n => n !== 'envelope.json' && beforeMtimes[n] !== afterMtimes[n]) +const retired = Object.keys(beforeMtimes).filter(n => n !== 'envelope.json' && !(n in afterMtimes)) +const churnNote = 'known defect, see #1032: a date-ranged run republishes the month shards it skipped' +if (retired.length) console.log(` note ${retired.length} shard(s) republished under a new name with identical content (${churnNote}): ${retired.join(', ')}`) +else if (republished.length) console.log(` note ${republished.length} shard(s) rewritten in place (${churnNote}): ${republished.join(', ')}`) +else ok('no shard republished on an unchanged corpus') + +// ── 8. partial source aging (release blocker, track C) ─────────────────────── +// Claude Code deletes its transcripts after ~30 days, so between one run and the +// next a day can go from fully sourced to PARTIALLY sourced. The daily cache's +// never-lose contract says a schema bump re-derives what it can and carries +// forward what it cannot — but on a partially-sourced day the re-derivation +// produces a smaller slice from the surviving files and that slice REPLACES the +// baseline one instead of being unioned with it, so the aged-out portion is lost. +// A day that aged out completely is carried forward correctly, which is what +// makes the partial case a hole rather than a missing feature. +// +// Runs last, and on its own cache dir, so mutating the corpus cannot disturb the +// parity comparison above. + +step('never-lose across partial source aging') +const agingCache = join(CACHES, 'aging') +mkdirSync(agingCache, { recursive: true }) + +// A fresh 0.9.20 cache, taken while every transcript still exists. +capture(oldBin, agingCache, join(PAYLOADS, 'aging-baseline')) +const baseDaily = JSON.parse(readFileSync(join(agingCache, OLD_DAILY_CACHE), 'utf8')) +const sliceOf = (cache, date) => cache.days.find(d => d.date === date)?.providers?.claude + +// Group transcripts by the day their turns land on. Sidechain files are left out: +// deleting a parent's subagent transcript entangles this with spawn-link +// carry-forward, which is a different contract. +const projectsDir = join(HOME, '.claude', 'projects') +const byDay = new Map() +for (const rel of readdirSync(projectsDir, { recursive: true })) { + const relPath = String(rel) + if (!relPath.endsWith('.jsonl') || relPath.includes('subagents')) continue + const full = join(projectsDir, relPath) + const first = readFileSync(full, 'utf8').split('\n', 1)[0] + const date = JSON.parse(first).timestamp?.slice(0, 10) + if (!date || !sliceOf(baseDaily, date)) continue + if (!byDay.has(date)) byDay.set(date, []) + byDay.get(date).push(full) +} + +// Densest days first, oldest among equals — the ones a retention window reaches +// first, and the ones where losing the aged-out portion shows up largest. +const candidates = [...byDay.entries()].filter(([, files]) => files.length >= 2) + .sort((a, b) => (b[1].length - a[1].length) || a[0].localeCompare(b[0])) + +let aged = [] +if (candidates.length < 3) fail(`need 3 multi-transcript claude days to age out, found ${candidates.length}`) +else { + for (const [date, files] of candidates.slice(0, 2)) { + // Keep exactly one file, so the day is still sourced — just not fully. + for (const f of files.slice(1)) rmSync(f) + aged.push({ date, kind: 'partially sourceless', kept: 1, removed: files.length - 1 }) + } + const [goneDate, goneFiles] = candidates[2] + for (const f of goneFiles) rmSync(f) + aged.push({ date: goneDate, kind: 'fully sourceless', kept: 0, removed: goneFiles.length }) + for (const a of aged) ok(`${a.date}: ${a.kind} (removed ${a.removed} of ${a.removed + a.kept} transcripts)`) + + capture(newBin, agingCache, join(PAYLOADS, 'aging-upgraded')) + const upDaily = JSON.parse(readFileSync(join(agingCache, NEW_DAILY_CACHE), 'utf8')) + const usd = n => `$${n.toFixed(6)}` + + for (const a of aged) { + const b = sliceOf(baseDaily, a.date) + const u = sliceOf(upDaily, a.date) + if (!u) { fail(`${a.date} (${a.kind}): the claude slice is gone entirely; baseline had ${usd(b.cost)} over ${b.calls} calls`); continue } + // A fully sourceless day has nothing to re-derive, so it must come back + // EXACTLY. A partially sourceless one may legitimately grow (a re-parse + // under new accounting), but must never shrink. + const exact = a.kind === 'fully sourceless' + const costOk = exact ? Math.abs(u.cost - b.cost) < 1e-9 : u.cost >= b.cost - 1e-9 + const callsOk = exact ? u.calls === b.calls : u.calls >= b.calls + const loss = costOk && callsOk ? '' : + ` — LOST ${usd(b.cost - u.cost)} (${(100 * (b.cost - u.cost) / b.cost).toFixed(1)}%) and ${b.calls - u.calls} calls` + check(costOk && callsOk, + `${a.date} (${a.kind}): cost ${usd(b.cost)} -> ${usd(u.cost)}, calls ${b.calls} -> ${u.calls}${loss}`) + } +} + +// ── done ───────────────────────────────────────────────────────────────────── + +console.log(`\n${failures ? `FAILED: ${failures} check(s)` : 'PASSED'}${skipped ? ` (${skipped} skipped)` : ''}`) +if (failures && process.env['UPGRADE_PATH_KEEP'] !== '0') console.log(`payloads left in: ${PAYLOADS}`) +else if (process.env['UPGRADE_PATH_KEEP'] !== '1') { try { rmSync(WORK, { recursive: true, force: true }) } catch { /* windows file locks */ } } +process.exit(failures ? 1 : 0) diff --git a/src/act/model-defaults.ts b/src/act/model-defaults.ts index 537f6a0e..6e2e7615 100644 --- a/src/act/model-defaults.ts +++ b/src/act/model-defaults.ts @@ -2,6 +2,7 @@ import { readFile } from 'node:fs/promises' import { join } from 'node:path' import { aggregateModelStats, type ModelStats } from '../compare-stats.js' +import { withUserStartedSessions } from '../session-population.js' import type { ProjectSummary } from '../types.js' import { sha256File } from './backup.js' import type { ActionPlan } from './types.js' @@ -73,15 +74,16 @@ function isDebuggingHeavy(project: ProjectSummary): boolean { } export function recommendModelDefault(project: ProjectSummary, opts: { now?: Date } = {}): ModelDefaultRecommendation | null { + const behavioralProject = withUserStartedSessions(project) const now = opts.now ?? new Date() - const stats = aggregateModelStats([project]) + const stats = aggregateModelStats([behavioralProject]) .filter(s => s.model !== '' && s.editTurns >= MIN_EDIT_TURNS) .sort((a, b) => b.editTurns - a.editTurns || b.editCost - a.editCost) const current = stats[0] if (!current) return null - const providers = providerByModel(project) + const providers = providerByModel(behavioralProject) const provider = providers.get(current.model) if (!provider || !isRecent(current.lastSeen, now)) return null @@ -89,7 +91,7 @@ export function recommendModelDefault(project: ProjectSummary, opts: { now?: Dat const currentCost = costPerEdit(current) if (!Number.isFinite(currentCost) || currentCost <= 0) return null - const debuggingHeavy = isDebuggingHeavy(project) + const debuggingHeavy = isDebuggingHeavy(behavioralProject) const tolerance = debuggingHeavy ? 0 : ONE_SHOT_TOLERANCE const candidates = stats diff --git a/src/act/optimize-apply.ts b/src/act/optimize-apply.ts index 5b90685a..235645a2 100644 --- a/src/act/optimize-apply.ts +++ b/src/act/optimize-apply.ts @@ -7,12 +7,17 @@ import { formatCost } from '../currency.js' import { formatTokens } from '../format.js' import { runAction } from './apply.js' import { shortId } from './journal.js' +import { REPORT_MIN_AGE_DAYS } from './types.js' import { planFindings, type FindingPlan, type PlanContext } from './plans.js' export type ApplyOptions = { yes?: boolean dryRun?: boolean only?: string + // Mirrors `optimize --provider`. The scan below only reads Claude + // transcripts, and this path does not just report findings, it plans and + // applies them - a Codex-scoped run must never offer to edit ~/.claude. + provider?: string actionsDir?: string ctx?: PlanContext // Test seams: crafted findings skip the session scan; streams default to @@ -37,16 +42,47 @@ function changeLines(fp: FindingPlan): string[] { }) } +function planTokensSaved(fp: FindingPlan): number { + if (fp.plan?.mcpSavingsUncertain) return Number.NaN + const byServer = fp.finding.applyTokensSavedByServer + const affected = fp.plan?.affectedMcpServers + if (byServer && affected) return affected.reduce((sum, server) => sum + (byServer[server] ?? 0), 0) + return fp.finding.applyTokensSaved ?? fp.finding.tokensSaved +} + +function manualActionLines(fp: FindingPlan): string[] { + if (fp.finding.manualFollowUp) { + return [fp.finding.manualFollowUp.label, fp.finding.manualFollowUp.text] + } + const action = fp.finding.fix + if (action.type === 'paste' && action.destination === 'manual') { + return [action.label, action.text] + } + return [] +} + export function renderApplyList(appliable: FindingPlan[], manual: FindingPlan[], costRate: number): string { const lines: string[] = [''] lines.push(chalk.bold(' Appliable config-class fixes:')) appliable.forEach((fp, i) => { const f = fp.finding - const savings = `~${formatTokens(f.tokensSaved)} tokens${costRate > 0 ? `, ~${formatCost(f.tokensSaved * costRate)}` : ''}` + const actionTokensSaved = planTokensSaved(fp) + const savings = Number.isFinite(actionTokensSaved) + ? `~${formatTokens(actionTokensSaved)} tokens${costRate > 0 ? `, ~${formatCost(actionTokensSaved * costRate)}` : ''}` + : 'Savings not estimated' lines.push('') lines.push(` ${i + 1}. ${f.title} ${chalk.hex('#FFD700')(`(${savings})`)}`) + if (fp.plan?.affectedMcpServers?.length) { + const servers = fp.plan.affectedMcpServers.join(', ') + lines.push(chalk.yellow(` Removes local MCP server${fp.plan.affectedMcpServers.length === 1 ? '' : 's'}: ${servers}`)) + } for (const line of changeLines(fp)) lines.push(chalk.dim(` ${line}`)) for (const note of fp.notes) lines.push(chalk.yellow(` ! ${note}`)) + const manualLines = manualActionLines(fp) + if (manualLines.length > 0) { + lines.push(chalk.cyan(' Manual follow-up (not applied):')) + for (const line of manualLines) lines.push(chalk.cyan(` ${line}`)) + } }) if (manual.length > 0) { lines.push('') @@ -54,6 +90,7 @@ export function renderApplyList(appliable: FindingPlan[], manual: FindingPlan[], for (const fp of manual) { lines.push(chalk.dim(` - ${fp.finding.title} [${fp.finding.id}] manual`)) for (const note of fp.notes) lines.push(chalk.yellow(` ! ${note}`)) + for (const line of manualActionLines(fp)) lines.push(chalk.cyan(` ${line}`)) } } lines.push('') @@ -103,7 +140,7 @@ export async function runOptimizeApply( let costRate = opts.costRate ?? 0 if (!findings) { errout.write(chalk.dim(' Analyzing your sessions...\n')) - const scanned = await scanAndDetect(projects, dateRange) + const scanned = await scanAndDetect(projects, dateRange, opts.provider) findings = scanned.findings costRate = scanned.costRate } @@ -129,6 +166,7 @@ export async function runOptimizeApply( print(chalk.dim('\n No appliable config-class fixes for this period.')) for (const fp of manual) { for (const note of fp.notes) print(chalk.yellow(` ! ${fp.finding.id}: ${note}`)) + for (const line of manualActionLines(fp)) print(chalk.cyan(` ${line}`)) } print() return @@ -172,15 +210,25 @@ export async function runOptimizeApply( } catch { /* baseline is optional; apply proceeds without it */ } print() + let applied = 0 for (const fp of selected) { try { const record = await runAction(fp.plan!, opts.actionsDir) + applied++ print(` Applied ${chalk.bold(shortId(record.id))} ${record.description}`) print(chalk.dim(` Undo anytime: codeburn act undo ${shortId(record.id)}`)) + const manualLines = manualActionLines(fp) + if (manualLines.length > 0) { + print(chalk.cyan(' Still requires manual action:')) + for (const line of manualLines) print(chalk.cyan(` ${line}`)) + } } catch (e) { errout.write(chalk.red(` Failed to apply ${fp.finding.id}: ${e instanceof Error ? e.message : String(e)}`) + '\n') process.exitCode = 1 } } + if (applied > 0) { + print(chalk.dim(` CodeBurn will re-measure these on your next optimize run after ${REPORT_MIN_AGE_DAYS} days.`)) + } print() } diff --git a/src/act/plans.ts b/src/act/plans.ts index b3ee4e39..9c02a1dd 100644 --- a/src/act/plans.ts +++ b/src/act/plans.ts @@ -9,6 +9,7 @@ import { ALWAYSLOAD_STARTUP_CAP_SECONDS, ENABLE_TOOL_SEARCH_VAR, parseVersion, + SHELL_PROFILE_SCOPE, versionPredates, } from '../optimize.js' import type { WasteFinding } from '../optimize.js' @@ -275,12 +276,15 @@ function pathNoteAdder(pathNotes: Record): (path: string, note: } function buildMcpRemove(finding: WasteFinding, r: ResolvedPaths): BuiltPlan { - const servers = finding.apply?.kind === 'mcp-remove' ? finding.apply.servers : [] + const servers = finding.apply?.kind === 'mcp-remove' + ? [...new Set(finding.apply.servers)] + : [] const searchPaths = [r.projectMcpJson, r.projectSettings, r.projectSettingsLocal, r.userClaudeJson] const docs = new ConfigDocs(r.homeDir) const skips: string[] = [] const pathNotes: Record = {} const addPathNote = pathNoteAdder(pathNotes) + const affectedServers: string[] = [] for (const server of servers) { let removed = false @@ -291,14 +295,24 @@ function buildMcpRemove(finding: WasteFinding, r: ResolvedPaths): BuiltPlan { if (res.removed) removed = true if (res.projectEntries.length > 0) addPathNote(path, projectRemovalNote(server, res.projectEntries, r.homeDir)) } - if (!removed) skips.push(`skipped ${server}: not found in editable config (plugin or managed config?)`) + if (removed) affectedServers.push(server) + else skips.push(`skipped ${server}: not found in editable config (plugin or managed config?)`) } const changes = docs.changes() const notes = [...docs.errorNotes(), ...skips] + const attribution = finding.applyTokensSavedByServer + const partialWithoutAttribution = affectedServers.length < servers.length && !attribution + const affectedMissingAttribution = attribution !== undefined + && affectedServers.some(server => !Object.hasOwn(attribution, server)) + const savingsUncertain = docs.errorNotes().length > 0 + || partialWithoutAttribution + || affectedMissingAttribution if (changes.length === 0) return { plan: null, notes } + const plan = mcpPlan('mcp-remove', finding.id, `Remove ${affectedServers.length === 1 ? 'an MCP server' : 'MCP servers'} from config`, changes, affectedServers) + if (savingsUncertain) plan.mcpSavingsUncertain = true return { - plan: mcpPlan('mcp-remove', finding.id, `Remove ${changes.length === 1 ? 'an MCP server' : 'MCP servers'} from config`, changes), + plan, notes, ...(Object.keys(pathNotes).length > 0 ? { pathNotes } : {}), } @@ -371,8 +385,8 @@ function buildMcpProjectScope(finding: WasteFinding, r: ResolvedPaths): BuiltPla } } -function mcpPlan(kind: ActionKind, findingId: string, description: string, changes: PlannedChange[]): ActionPlan { - return { kind, findingId, description, changes } +function mcpPlan(kind: ActionKind, findingId: string, description: string, changes: PlannedChange[], affectedMcpServers?: string[]): ActionPlan { + return { kind, findingId, description, changes, ...(affectedMcpServers ? { affectedMcpServers } : {}) } } // --------------------------------------------------------------------------- @@ -386,7 +400,6 @@ const NEXT_SESSION_NOTE = 'takes effect on the next session (this config is read // findDeferralEnvSetting (src/optimize.ts) reports shell-profile hits with // exactly this scope string; the plan layer keys its refusal on it. -const SHELL_PROFILE_SCOPE = 'shell profile' const SHELL_TOOL_SEARCH_LINE = new RegExp(`^\\s*(?:export\\s+)?${ENABLE_TOOL_SEARCH_VAR}\\s*=.*$`, 'm') diff --git a/src/act/report.ts b/src/act/report.ts index 30c88120..ed921f83 100644 --- a/src/act/report.ts +++ b/src/act/report.ts @@ -1,7 +1,8 @@ import { existsSync } from 'fs' import { dirname } from 'node:path' import type { DateRange, ProjectSummary, SessionSummary } from '../types.js' -import type { ActionBaseline, ActionKind, ActionRecord } from './types.js' +import type { ActionBaseline, ActionKind, ActionRecord, AppliedFix, AppliedVerdict } from './types.js' +import { REPORT_MIN_AGE_DAYS, VERDICT_WORKED_RATIO } from './types.js' import type { FindingPlan } from './plans.js' import { AVG_TOKENS_PER_READ, @@ -20,7 +21,8 @@ import { } from '../optimize.js' import { parseAllSessions } from '../parser.js' import { computeYield, type YieldSummary } from '../yield.js' -import { defaultActionsDir, readRecords } from './journal.js' +import { defaultActionsDir, readRecords, shortId } from './journal.js' +import { undoAction } from './undo.js' import { renderTable } from '../text-table.js' import { formatTokens } from '../format.js' import { formatCost } from '../currency.js' @@ -28,7 +30,6 @@ import { formatCost } from '../currency.js' const DAY_MS = 24 * 60 * 60 * 1000 const WINDOW_CAP_DAYS = 30 const BASELINE_WINDOW_DAYS = 14 -const REPORT_MIN_AGE_DAYS = 3 const MIN_POST_WINDOW_SESSIONS = 20 const VOLUME_SHIFT_FACTOR = 2 @@ -59,6 +60,8 @@ const ARCHIVE_DEF_TOKENS: Partial> = { // 'pending' means the applied change has not taken effect in any post-apply // session yet (e.g. deferral before a client restart) - distinct from // 'reverted', which asserts the user undid it. +export { REPORT_MIN_AGE_DAYS } + export type RealizedStatus = 'measured' | 'reverted' | 'not-measurable' | 'pending' export type ActReportRow = { @@ -102,6 +105,8 @@ export type ActReport = { // findingId -> earliest apply date of an active applied action; drives the // optimize "(previously applied ..., re-flagged)" title suffix. appliedByFinding: Record + // One entry per active applied action, including ones too young to measure. + appliedFixes: AppliedFix[] } export type ActReportOptions = { @@ -470,6 +475,63 @@ function isSaneRecord(r: ActionRecord): boolean { return typeof r.at === 'string' && typeof r.status === 'string' && !Number.isNaN(new Date(r.at).getTime()) } +// Turn the measured rows plus the still-young entries into one verdict per +// active applied action. No second reconciliation: everything measurable comes +// straight off the row `act report` already computed. +function buildAppliedFixes(active: ActionRecord[], rows: ActReportRow[], now: Date): AppliedFix[] { + const byId = new Map(rows.map(r => [r.id, r])) + return active.map(rec => { + const row = byId.get(rec.id) + const base = { + id: rec.id, + kind: rec.kind, + findingId: rec.findingId ?? null, + appliedAt: rec.at, + ageDays: ageDays(rec.at, now), + undoCommand: `codeburn act undo ${shortId(rec.id)}`, + } + // No row means too young to measure; a row that is not a measured token + // row (not-measurable, not yet in effect, reverted by the user, or a + // correlation-only kind) has no reduction to judge either. + if (!row) return { ...base, verdict: 'pending' as const, estimatedTokens: rec.baseline?.estimatedTokens ?? 0, realizedTokens: 0, note: '' } + if (row.status !== 'measured' || !isTokenKind(row.kind)) { + return { ...base, verdict: 'pending' as const, estimatedTokens: row.estimatedForWindow, realizedTokens: 0, note: row.note } + } + const estimatedTokens = row.estimatedForWindow + const realizedTokens = row.realizedTokens + const verdict: AppliedVerdict = realizedTokens <= 0 + ? 'no-effect' + : estimatedTokens <= 0 || realizedTokens >= estimatedTokens * VERDICT_WORKED_RATIO ? 'worked' : 'partial' + return { ...base, verdict, estimatedTokens, realizedTokens, note: row.note } + }) +} + +// --auto-revert: undo the fixes that measured no reduction at all. CLAUDE.md +// rules are never undone unattended, matching the --yes guardrail - the file +// belongs to whatever project the user happened to be in. +export async function autoRevertNoEffect( + fixes: AppliedFix[], opts: { actionsDir?: string } = {}, +): Promise<{ lines: string[]; revertedIds: Set }> { + const lines: string[] = [] + const revertedIds = new Set() + for (const fix of fixes) { + if (fix.verdict !== 'no-effect') continue + const label = fix.findingId ?? fix.kind + if (fix.kind === 'claude-md-rule') { + lines.push(`Not auto-reverted: ${label} edits a CLAUDE.md. Revert: ${fix.undoCommand}`) + continue + } + try { + const record = await undoAction({ id: fix.id }, { actionsDir: opts.actionsDir }) + revertedIds.add(fix.id) + lines.push(`Reverted ${shortId(record.id)}: ${record.description}`) + } catch (err) { + lines.push(`Could not revert ${label}: ${err instanceof Error ? err.message : String(err)}`) + } + } + return { lines, revertedIds } +} + export async function computeActReport(opts: ActReportOptions = {}): Promise { const now = opts.now ?? new Date() const rawRecords = await readRecords(opts.actionsDir ?? defaultActionsDir()) @@ -497,6 +559,7 @@ export async function computeActReport(opts: ActReportOptions = {}): Promise ageDays(r.at, now) > REPORT_MIN_AGE_DAYS) @@ -550,6 +613,7 @@ export async function computeActReport(opts: ActReportOptions = {}): Promise s.server) return [] @@ -684,24 +750,37 @@ function deferServers(finding: WasteFinding, ctx: CaptureCtx): string[] { return observedMcpServers(ctx.projects) } -export function captureBaseline(finding: WasteFinding, kind: ActionKind, ctx: CaptureCtx): ActionBaseline | undefined { +export function captureBaseline( + finding: WasteFinding, + kind: ActionKind, + ctx: CaptureCtx, + affectedMcpServers?: string[], +): ActionBaseline | undefined { const common = { windowDays: ctx.windowDays, capturedAt: ctx.now.toISOString(), - estimatedTokens: Math.max(0, Math.round(finding.tokensSaved)), + estimatedTokens: Math.max(0, Math.round(finding.applyTokensSaved ?? finding.tokensSaved)), } if (MCP_KINDS.has(kind)) { - const servers = mcpServersFromApply(finding) + const servers = mcpServersFromApply(finding, affectedMcpServers) if (servers.length === 0) return undefined const covByServer = new Map(ctx.coverage.map(c => [c.server, c])) const metrics: Record = {} for (const server of servers) { const cov = covByServer.get(server) - const tools = cov && cov.toolsAvailable > 0 ? cov.toolsAvailable : TOOLS_PER_MCP_SERVER + // Removal realizes only the unused schema that the low-coverage + // detector estimated. If coverage is unavailable, omit the numeric + // claim instead of inventing a five-tool baseline. + const tools = finding.id === 'mcp-low-coverage' + ? cov?.unusedTools.length ?? 0 + : cov && cov.toolsAvailable > 0 ? cov.toolsAvailable : TOOLS_PER_MCP_SERVER metrics[server] = tools * TOKENS_PER_MCP_TOOL } - return { ...common, sessions: countSessionsLoading(ctx.projects, servers), metrics } + const estimatedTokens = finding.applyTokensSavedByServer + ? Math.round(servers.reduce((sum, server) => sum + (finding.applyTokensSavedByServer?.[server] ?? 0), 0)) + : common.estimatedTokens + return { ...common, estimatedTokens, sessions: countSessionsLoading(ctx.projects, servers), metrics } } if (DEFER_KINDS.has(kind)) { @@ -750,7 +829,8 @@ export async function captureBaselinesForPlans( const projects = await loadProjects({ start, end: now }) const ctx: CaptureCtx = { projects, coverage: aggregateMcpCoverage(projects), windowDays: BASELINE_WINDOW_DAYS, now } for (const fp of applicable) { - const baseline = captureBaseline(fp.finding, fp.plan!.kind, ctx) + if (fp.plan!.mcpSavingsUncertain) continue + const baseline = captureBaseline(fp.finding, fp.plan!.kind, ctx, fp.plan!.affectedMcpServers) if (baseline) fp.plan!.baseline = baseline } } diff --git a/src/act/types.ts b/src/act/types.ts index 4142abe4..6ca0c1c4 100644 --- a/src/act/types.ts +++ b/src/act/types.ts @@ -1,3 +1,5 @@ +import { formatTokens } from '../format.js' + export type ActionKind = | 'mcp-remove' | 'mcp-project-scope' | 'defer-enable' | 'defer-alwaysload' | 'defer-threshold' @@ -66,4 +68,68 @@ export type ActionPlan = { findingId?: string | null changes: PlannedChange[] baseline?: ActionBaseline + // MCP plans only: exact server identities the generated file mutations own. + // Preview and baseline capture must not claim skipped/managed targets. + affectedMcpServers?: string[] + // Relevant config scopes could not all be read, so removal may proceed + // with warnings but savings/baseline claims must be suppressed. + mcpSavingsUncertain?: boolean +} + +// Applied actions are re-measured on every `codeburn optimize` run: only fixes +// at least this old have a post-apply window to measure against. +export const REPORT_MIN_AGE_DAYS = 3 +// A fix counts as having worked once it realizes this share of its +// window-scaled estimate; anything above zero but below it is partial. +export const VERDICT_WORKED_RATIO = 0.7 + +// Per-applied-entry judgement shown by `codeburn optimize` after an --apply. +// Computed in act/report.ts from the same rows `act report` prints - there is +// one reconciliation, not two. Lives here so the optimize renderer can format +// it without importing report.ts back into optimize.ts. +export type AppliedVerdict = 'worked' | 'partial' | 'no-effect' | 'pending' + +export type AppliedFix = { + id: string + kind: ActionKind + findingId: string | null + appliedAt: string + ageDays: number + verdict: AppliedVerdict + // Window-scaled estimate, the same column `act report` compares against. + estimatedTokens: number + realizedTokens: number + note: string + undoCommand: string +} + +const VERDICT_GLYPH: Record = { + worked: '\u2713', + partial: '~', + 'no-effect': '\u2717', + pending: '\u2026', +} + +export function appliedFixGlyph(fix: AppliedFix): string { + return VERDICT_GLYPH[fix.verdict] +} + +// One plain line per applied fix: what it estimated, what it measured, and for +// a fix that did nothing, how to put it back. +export function formatAppliedFix(fix: AppliedFix): string { + const age = Math.max(0, Math.floor(fix.ageDays)) + const head = `${fix.findingId ?? fix.kind} (${age}d ago)` + if (fix.verdict === 'pending') { + const why = fix.note || (age <= REPORT_MIN_AGE_DAYS + ? `measuring, check back after ${REPORT_MIN_AGE_DAYS} days` + : 'measuring') + return `${head}: ${why}` + } + const pair = `est. ${formatTokens(fix.estimatedTokens)} -> measured ${formatTokens(fix.realizedTokens)}` + if (fix.verdict === 'worked') return `${head}: ${pair}` + if (fix.verdict === 'partial') { + const under = Math.round((1 - fix.realizedTokens / fix.estimatedTokens) * 100) + return `${head}: ${pair} (-${under}% vs estimate)` + } + return `${head}: ${pair} - did not help. Revert: ${fix.undoCommand}` } diff --git a/src/audit-report.ts b/src/audit-report.ts index 4d3a1bbf..0d6ed123 100644 --- a/src/audit-report.ts +++ b/src/audit-report.ts @@ -1,5 +1,5 @@ import { isBehavioralCall } from './behavioral-weight.js' -import { getModelCosts, type ModelCosts } from './models.js' +import { getModelCosts, sanitizeModelForDisplay, type ModelCosts } from './models.js' import { getProvider } from './providers/index.js' import { formatCost, formatTokens } from './format.js' import { renderTable, type TableColumn } from './text-table.js' @@ -114,7 +114,9 @@ export async function aggregateAudit(projects: ProjectSummary[]): Promise p.modelDisplayName(m) : (m: string) => m, + formatModel: p + ? (m: string) => sanitizeModelForDisplay(p.modelDisplayName(m)) + : sanitizeModelForDisplay, } providerCache.set(name, entry) return entry diff --git a/src/daily-cache.ts b/src/daily-cache.ts index bcf7a896..17a84f25 100644 --- a/src/daily-cache.ts +++ b/src/daily-cache.ts @@ -6,24 +6,41 @@ import { join } from 'path' import { getCodeburnCacheDir } from './cache-dir.js' import type { DateRange, ProjectSummary } from './types.js' -// Bumped to 19, deliberately skipping 18: an earlier head of this same change -// (#946) was pushed publicly claiming v18 under DIFFERENT accounting — no -// supplementary-call weighting, whole-session rollup suppression — and -// adoptOlderDailyCaches/isMigratableCache would take those days forward as -// finalized without re-deriving them. A distinct version is the only thing -// that stops one version number meaning two accountings. +// Bumped to 21: copilot input/cache tokens for sessions covered by the CLI's +// session-store.db move from one shutdown-rollup lump (stamped at session end) +// to per-request DB rows with real timestamps, supplementary accounting calls +// (rollups, residuals, paired rows) stop counting as api/model calls, and +// reasoning tokens leave the copilot cost recompute (they are inside the +// output the per-turn calls already bill). Per-day attribution, call counts and +// costs all move, so days finalized under an earlier version would disagree +// with the live parse. // -// v18 (never released): copilot input/cache tokens for sessions covered by the CLI's -// session-store.db moved from one shutdown-rollup lump (stamped at session -// end) to per-request DB rows with real timestamps, supplementary accounting -// calls (rollups, covered rows) stopped counting as api/model calls, and -// reasoning tokens left the copilot cost recompute (they are inside the -// output the per-turn calls already bill). Per-day attribution, call counts -// and costs all move, so days finalized at v17 would disagree with the live -// parse. Re-derivation rides the v14 carry-forward semantics; sourceless -// days carry forward as-is. +// 20 is NOT free: an unmerged head of #1040 (codex model attribution) claims +// it, and 18 was burned by an earlier public head of THIS change under +// different accounting (whole-session rollup suppression, no supplementary +// weight). isMigratableCache/adoptOlderDailyCaches carry a same-or-newer +// version forward as FINALIZED without re-deriving it, so a number can never +// mean two accountings. 21 is the first number no other head claims. // -// v17: copilot CLI sessions were misclassified as VS Code transcripts +// Bumped to 19: Grok authoritative usage now keeps one session-level rollup +// from top-level totals, clamps reasoning to reported output, and labels mixed +// authoritative/heuristic coverage. Every day finalized under the previous +// accounting carries the old Grok totals, and the daily cache has no +// per-provider invalidation, so raising MIN_SUPPORTED_VERSION is the only +// lever: it forces a one-time re-derivation of ALL days, for every provider, +// not just Grok. That pass reads the warm session cache (CACHE_VERSION is +// unchanged and only PROVIDER_PARSE_VERSIONS.grok moved), so it costs seconds +// rather than a full re-parse, and adoptOlderDailyCaches keeps the superseded +// file as the baseline for days no source can still re-derive. Days whose +// sources only PARTLY survive are held by the partial-survival guard in +// mergeDayEntries, which is what makes a global re-derive safe to force: on a +// real 108-day cache the 17 -> 19 pass moves Grok cost and tokens and nothing +// else - the day-by-day call counts come back identical. +// +// The shipped predecessor is v17; v18 was an unreleased draft of this change +// and only exists in pre-release checkouts. 19 clears both. +// +// Bumped to 17: copilot CLI sessions were misclassified as VS Code transcripts // (#944), so days finalized at v16 or earlier carry output-only copilot costs — // the session.shutdown rollup's input/cache tokens were dropped. Raising // MIN_SUPPORTED_VERSION forces the one-time re-derivation under the @@ -91,8 +108,8 @@ import type { DateRange, ProjectSummary } from './types.js' // that older binaries skipped. v8 added local-model savings to the daily // rollup; the `savingsConfigHash` field is invalidated separately when the // user changes their `localModelSavings` mapping. -export const DAILY_CACHE_VERSION = 19 -const MIN_SUPPORTED_VERSION = 19 +export const DAILY_CACHE_VERSION = 21 +const MIN_SUPPORTED_VERSION = 21 // Version-suffixed so different binaries each own a distinct file and never // clobber an incompatible schema. Bumping the version mints a fresh filename; // adoptOlderDailyCaches then unions days out of every previous file (including @@ -859,6 +876,52 @@ function hasPositiveDayContent(day: DailyEntry): boolean { return false } +/// PARTIAL SURVIVAL (the v14 never-lose contract, extended past all-or-nothing). +/// v14 protected a (date, provider) slice only when the fresh derivation found +/// NOTHING there. But transcripts age out per FILE, not per day: Claude Code +/// deletes them after ~30 days, and turn-anchored bucketing means a handful of +/// turns from surviving later files still land on a mostly-aged-out day. The +/// fresh slice is then non-empty but truncated, and replacing the baseline with +/// it silently deletes the rest (measured on a real cache upgrading 17 -> 19: +/// 2026-07-16 fell from $1,685.17 / 12,530 calls to $385.44 / 560 calls). +/// +/// So a fresh slice replaces a settled baseline slice only when it carries at +/// least as many CALLS — the same or more evidence. Fewer calls means the +/// source set demonstrably lost data, and the baseline is kept whole. +/// +/// Why calls and not sessions: session counts shrink routinely on days whose +/// sources are entirely intact (a session's turns re-attribute to a neighbouring +/// day), measured at 1-5 sessions on recent days whose call counts were +/// identical across the re-derivation. A sessions test would freeze stale slices +/// on healthy days. Why not cost/tokens: those are re-priced accounting on the +/// same evidence — exactly what a legitimate re-derivation changes (#1015 Grok +/// keeps its per-day calls and raises cost, and is unaffected by this guard). +/// +/// Why no source-set test instead: a day entry records no source files, counts +/// or fingerprints, and the session cache is keyed by file rather than by day, +/// so "were this day's sources all present?" cannot be answered from the cache. +/// The calls comparison is the available proxy. +/// +/// TRADE-OFF: a future fix that legitimately REDUCES calls on a settled day +/// (deduplication) is blocked, and that day keeps the older, higher value until +/// its slice is re-derived under an equal-or-greater call count. That is the +/// "estimate high, never lose" direction v14 already chose over silent loss. +/// +/// Recent days stay authoritative: within the settle window their session files +/// are still on disk, so a shrink there is a real change (the user deleted a +/// transcript), not aged-out sources. Seven days is far inside the ~30-day +/// retention floor of the shortest-lived source we know of, so any shrink older +/// than that is source loss with overwhelming likelihood. +const SETTLE_DAYS = 7 + +function settleCutoffDate(now: Date): string { + return toDateString(new Date(now.getFullYear(), now.getMonth(), now.getDate() - SETTLE_DAYS)) +} + +function isPartialSurvival(date: string, baseline: ProviderDaySlice, fresh: ProviderDaySlice, settleCutoff: string): boolean { + return date < settleCutoff && fresh.calls < baseline.calls +} + /// Index `freshUnderOldTz` (the same parse re-aggregated under the cache's OLD /// tzKey) by date then provider, so the merge can subtract exactly what the /// fresh parse still explains under the old bucketing. @@ -889,21 +952,34 @@ function buildTzSubtraction(days: DailyEntry[]): ReadonlyMap>, + /// Set ONLY by the complete-parse re-derive, where `primary` is a fresh + /// derivation from live sources and `secondary` is the cache baseline: a + /// primary slice with fewer calls there means sources aged out, so the + /// baseline wins on settled days (`isPartialSurvival`). The adoption union + /// leaves it off - both sides are cache generations there and the newer + /// schema deliberately wins per (date, provider). + guardPartialSurvival = false, ): DailyEntry[] { const byDate = new Map() + const settleCutoff = settleCutoffDate(new Date()) for (const day of primary) byDate.set(day.date, structuredClone(day)) for (const day of secondary) { const existing = byDate.get(day.date) @@ -930,7 +1006,6 @@ export function mergeDayEntries( // day) still carry a real session count — worth preserving. if (!hasSliceData(slice) && !(slice.sessions ?? 0)) continue const existingSlice = Object.hasOwn(existing.providers, provider) ? existing.providers[provider] : undefined - if (existingSlice && hasSliceData(existingSlice)) continue let toAdd = slice let residual = false if (subtract) { @@ -946,6 +1021,13 @@ export function mergeDayEntries( residual = true } } + if (existingSlice && hasSliceData(existingSlice) && !residual) { + if (!guardPartialSurvival || !isPartialSurvival(day.date, slice, existingSlice, settleCutoff)) continue + // The baseline holds more evidence than the sources can still produce: + // swap the fresh slice back out for it (inverse of addSliceIntoDay, so + // the day's totals and nested maps stay reconciled with its slices). + subtractSliceFromDay(existing, provider, existingSlice) + } addSliceIntoDay(existing, provider, toAdd, residual) if (markSecondaryCarried) existing.carried = true } @@ -1108,7 +1190,7 @@ export async function ensureCacheHydrated( tzSubtraction = buildTzSubtraction(aggregateDaysInTz(wideProjects, c.tzKey)) } const merged = parseWasComplete - ? mergeDayEntries(freshDays, baseline, true, tzSubtraction) + ? mergeDayEntries(freshDays, baseline, true, tzSubtraction, true) : mergeDayEntries(baseline, freshDays, false) c = { version: DAILY_CACHE_VERSION, diff --git a/src/dashboard.tsx b/src/dashboard.tsx index b1f25302..da7ec15d 100644 --- a/src/dashboard.tsx +++ b/src/dashboard.tsx @@ -1,7 +1,8 @@ import { homedir } from 'os' +import { EventEmitter } from 'node:events' -import React, { useState, useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react' -import { render, Box, Text, measureElement, useInput, useApp, useWindowSize, type DOMElement } from 'ink' +import React, { Fragment, useState, useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react' +import { render, Box, Text, measureElement, useInput, useApp, useWindowSize, type DOMElement, type Instance, type RenderOptions } from 'ink' import { CATEGORY_LABELS, type DateRange, type ProjectSummary, type TaskCategory } from './types.js' import { formatCost, formatTokens, markEstimated, carriedCostNote } from './format.js' import { aggregateModelEfficiency } from './model-efficiency.js' @@ -10,7 +11,8 @@ import { findUnpricedModels, isExpectedFreeModel, loadPricing } from './models.j import { aggregateModelTotals } from './model-breakdown.js' import { buildDurablePeriod } from './usage-aggregator.js' import { getAllProviders } from './providers/index.js' -import { scanAndDetect, type WasteFinding, type WasteAction, type OptimizeResult } from './optimize.js' +import { classHeaderLine, classTotals, findingBasis, findingClass, scanAndDetect, type FindingClass, type WasteFinding, type WasteAction, type OptimizeResult } from './optimize.js' +import { appliedFixGlyph, formatAppliedFix, type AppliedFix } from './act/types.js' import { aggregateFileChurn, buildCoachingNotes, computePricingCoverage, medianTimeToFirstEditMs, scanUserCorrections, worstOneShotCategory, type ReworkedFile } from './workflow-insights.js' import { estimateContextBudget, type ContextBudget } from './context-budget.js' import { dateKey } from './day-aggregator.js' @@ -31,6 +33,138 @@ export type DailyActivityRow = { export const DAILY_ACTIVITY_PAGE_SIZE = 10 export const INTERACTIVE_RENDER_OPTIONS = { alternateScreen: true } as const +export const RESIZE_DEBOUNCE_MS = 150 + +export type TerminalSize = { columns: number; rows: number } +export type DebouncedResizeStream = NodeJS.WriteStream & { + dispose(): void + onSettledResize(listener: (size: TerminalSize) => void): () => void +} + +function normalizeTerminalDimension(value: number | undefined, fallback: number): number { + return Number.isFinite(value) && value! > 0 ? Math.floor(value!) : fallback +} + +function terminalSizeOf(source: NodeJS.WriteStream): TerminalSize { + return { + columns: normalizeTerminalDimension(source.columns, 80), + rows: normalizeTerminalDimension(source.rows, 24), + } +} + +const RESIZE_LISTENER_METHODS = new Set([ + 'addListener', 'on', 'once', 'prependListener', 'prependOnceListener', 'off', 'removeListener', +]) + +export function createDebouncedResizeStream(source: NodeJS.WriteStream, delayMs: number): DebouncedResizeStream { + let resizeTimer: ReturnType | undefined + let disposed = false + let { columns, rows } = terminalSizeOf(source) + const resizeEvents = new EventEmitter() + const settledResizeListeners = new Set<(size: TerminalSize) => void>() + + const resize = () => { + if (disposed) return + if (resizeTimer) clearTimeout(resizeTimer) + resizeTimer = setTimeout(() => { + resizeTimer = undefined + if (disposed) return + const next = terminalSizeOf(source) + const changed = next.columns !== columns || next.rows !== rows + columns = next.columns + rows = next.rows + if (!changed) return + // Rerender first so the settled view owns the first paint at the new + // size; then notify Ink/useWindowSize. Writes are never intercepted, so + // a mid-burst state update still reaches the terminal even when net + // size is unchanged. + for (const listener of [...settledResizeListeners]) listener(next) + resizeEvents.emit('resize') + }, delayMs) + } + source.on('resize', resize) + + const dispose = () => { + if (disposed) return + disposed = true + source.off('resize', resize) + if (resizeTimer) clearTimeout(resizeTimer) + resizeTimer = undefined + resizeEvents.removeAllListeners() + settledResizeListeners.clear() + } + + const stream = new Proxy(source as DebouncedResizeStream, { + get(target, property) { + if (property === 'dispose') return dispose + if (property === 'onSettledResize') { + return (listener: (size: TerminalSize) => void) => { + if (disposed) return () => {} + settledResizeListeners.add(listener) + return () => settledResizeListeners.delete(listener) + } + } + if (property === 'columns') return columns + if (property === 'rows') return rows + if (RESIZE_LISTENER_METHODS.has(property)) { + return (event: string | symbol, ...args: unknown[]) => { + if (event === 'resize') { + if (!disposed) { + Reflect.apply(Reflect.get(resizeEvents, property) as (...args: unknown[]) => unknown, resizeEvents, [event, ...args]) + } + return stream + } + Reflect.apply(Reflect.get(target, property, target) as (...args: unknown[]) => unknown, target, [event, ...args]) + return stream + } + } + const value = Reflect.get(target, property, target) + return typeof value === 'function' ? value.bind(target) : value + }, + }) + return stream +} + +function DisposeOnUnmount({ dispose, children }: { dispose: () => void; children: React.ReactNode }) { + useLayoutEffect(() => dispose, [dispose]) + return children +} + +export type DebouncedInteractiveInstance = Instance & { + dispose(): void + stdout: DebouncedResizeStream +} + +export function renderDebouncedInteractive( + source: NodeJS.WriteStream, + view: (size: TerminalSize) => React.ReactElement, + options: Omit = INTERACTIVE_RENDER_OPTIONS, +): DebouncedInteractiveInstance { + const stdout = createDebouncedResizeStream(source, RESIZE_DEBOUNCE_MS) + let size = { columns: stdout.columns, rows: stdout.rows } + let unsubscribe = () => {} + let disposed = false + const dispose = () => { + if (disposed) return + disposed = true + unsubscribe() + stdout.dispose() + } + const dashboard = () => {view(size)} + let app: Instance + try { + app = render(dashboard(), { ...options, stdout }) + } catch (error) { + dispose() + throw error + } + unsubscribe = stdout.onSettledResize(nextSize => { + if (disposed) return + size = nextSize + app.rerender(dashboard()) + }) + return Object.assign(app, { dispose, stdout }) +} export function getDailyActivityPageSize(columnCount: 1 | 2 | 3, projectRows: number, activityRows: number, dayMode = false): number { if (dayMode) return 1 @@ -653,8 +787,10 @@ function ModelBreakdown({ projects, pw, bw }: { projects: ProjectSummary[]; pw: ) })} {unpriced.length > 0 && ( - - {`! ${unpriced.length} model${unpriced.length === 1 ? '' : 's'} unpriced at $0, fix: codeburn model-alias (${unpriced.slice(0, 2).map(u => u.model).join(', ')}${unpriced.length > 2 ? ', ...' : ''})`} + + {pw <= 44 + ? `! ${unpriced.length}: codeburn models --unpriced` + : `! ${unpriced.length} unpriced: codeburn models --unpriced`} )} {anyEstimated && ( @@ -1047,6 +1183,8 @@ function actionDestinationHeader(action: WasteAction): string { return '── Ask Claude in the current session '.padEnd(64, '─') case 'shell-config': return '── Add to your shell config '.padEnd(64, '─') + case 'manual': + return '── Manual action '.padEnd(64, '─') default: return '── Suggested action '.padEnd(64, '─') } @@ -1080,7 +1218,7 @@ function FindingPanel({ index, finding, costRate, width }: { index: number; find {trendBadge && {trendBadge}} {finding.explanation} - Savings: ~{formatTokens(finding.tokensSaved)} tokens (~{formatCost(costSaved)}) + Savings: ~{formatTokens(finding.tokensSaved)} tokens (~{formatCost(costSaved)}) {findingBasis(finding)} @@ -1095,7 +1233,14 @@ const GRADE_COLORS: Record = { A: '#5BF5A0', B: '#5BF5A0', C: GO // off the alt-buffer top and the user couldn't see the StatusBar at all. const FINDINGS_WINDOW_SIZE = 3 -function OptimizeView({ findings, costRate, projects, label, width, healthScore, healthGrade, cursor }: { findings: WasteFinding[]; costRate: number; projects: ProjectSummary[]; label: string; width: number; healthScore: number; healthGrade: string; cursor: number }) { +const APPLIED_FIX_COLORS: Record = { + worked: '#5BF5A0', + partial: GOLD, + 'no-effect': '#F55B5B', + pending: DIM, +} + +function OptimizeView({ findings, costRate, projects, label, width, healthScore, healthGrade, cursor, appliedFixes = [] }: { findings: WasteFinding[]; costRate: number; projects: ProjectSummary[]; label: string; width: number; healthScore: number; healthGrade: string; cursor: number; appliedFixes?: AppliedFix[] }) { const periodCost = projects.reduce((s, p) => s + p.totalCostUSD, 0) const totalTokens = findings.reduce((s, f) => s + f.tokensSaved, 0) const totalCost = totalTokens * costRate @@ -1106,6 +1251,7 @@ function OptimizeView({ findings, costRate, projects, label, width, healthScore, const start = total === 0 ? 0 : Math.min(cursor, Math.max(0, total - FINDINGS_WINDOW_SIZE)) const end = Math.min(start + FINDINGS_WINDOW_SIZE, total) const visible = findings.slice(start, end) + const totals = classTotals(findings, costRate) return ( @@ -1120,8 +1266,28 @@ function OptimizeView({ findings, costRate, projects, label, width, healthScore, Showing {start + 1}–{end} of {total} · j/k to scroll )} - {visible.map((f, i) => )} - Token estimates are approximate. + {visible.map((f, i) => { + // Findings arrive class-sorted, so a header goes in wherever the class + // changes (including the top of the window after paging). + const cls = findingClass(f) + const previous: FindingClass | null = i > 0 ? findingClass(visible[i - 1]!) : null + return ( + + {cls !== previous && {classHeaderLine(cls, totals[cls], costRate)}} + + + ) + })} + {appliedFixes.length > 0 && ( + + Applied fixes + {appliedFixes.map(fix => ( + + {appliedFixGlyph(fix)} {formatAppliedFix(fix)} + + ))} + + )} ) } @@ -1303,6 +1469,7 @@ export function InteractiveDashboard({ initialProjects, initialDailyHistoryProje const [detectedProviders, setDetectedProviders] = useState([]) const [view, setView] = useState('dashboard') const [optimizeResult, setOptimizeResult] = useState(null) + const [appliedFixes, setAppliedFixes] = useState([]) const [optimizeLoading, setOptimizeLoading] = useState(false) const [projectBudgets, setProjectBudgets] = useState>(new Map()) const [planUsages, setPlanUsages] = useState(initialPlanUsages ?? []) @@ -1461,14 +1628,20 @@ export function InteractiveDashboard({ initialProjects, initialDailyHistoryProje const generation = reloadGenerationRef.current setOptimizeLoading(true) try { - const result = await scanAndDetect(projects, currentRange()) + const result = await scanAndDetect(projects, currentRange(), activeProvider) if (reloadGenerationRef.current === generation) setOptimizeResult(result) + // Best effort: a bad journal never keeps the findings off screen. + try { + const { computeActReport } = await import('./act/report.js') + const applied = await computeActReport() + if (reloadGenerationRef.current === generation) setAppliedFixes(applied.appliedFixes) + } catch { /* the applied section is optional */ } } catch (error) { console.error(error) } finally { if (reloadGenerationRef.current === generation) setOptimizeLoading(false) } - }, [optimizeAvailable, projects, currentRange, optimizeLoading, optimizeResult]) + }, [optimizeAvailable, projects, currentRange, optimizeLoading, optimizeResult, activeProvider]) useEffect(() => { const refreshIntervalMs = getRefreshIntervalMs(refreshSeconds ?? 0) @@ -1627,7 +1800,7 @@ export function InteractiveDashboard({ initialProjects, initialDailyHistoryProje {view === 'compare' ? setView('dashboard')} /> : view === 'optimize' && optimizeResult - ? + ? : } {coachingNote && ( @@ -1699,23 +1872,13 @@ export async function renderDashboard(period: Period = 'week', provider: string const label = initialDay ? formatDayRangeLabel(initialDay) : customRangeLabel patchStdoutForWindows() if (isTTY) { - let windowColumns = process.stdout.columns - const dashboard = () => ( - - ) - const app = render( - dashboard(), - INTERACTIVE_RENDER_OPTIONS, - ) - const resize = () => { - windowColumns = process.stdout.columns - app.rerender(dashboard()) - } - process.stdout.prependListener('resize', resize) + const app = renderDebouncedInteractive(process.stdout, ({ columns }) => ( + + )) try { await app.waitUntilExit() } finally { - process.stdout.off('resize', resize) + app.dispose() } } else { const { unmount } = render(, { patchConsole: false }) diff --git a/src/granular-history.ts b/src/granular-history.ts index aeecd565..75b6e328 100644 --- a/src/granular-history.ts +++ b/src/granular-history.ts @@ -1,3 +1,5 @@ +import stripAnsi from 'strip-ansi' + import type { DateRange, ProjectSummary } from './types.js' const FIFTEEN_MINUTES = 15 @@ -5,6 +7,10 @@ const ONE_HOUR = 60 const ONE_DAY = 24 * 60 const MINUTE_MS = 60 * 1000 const MAX_SERIES_PER_METRIC = 6 +// Keep metadata bounded for the legend and tooltip: 80 characters preserves a +// useful title without letting the parser's 200-char transcript cap dominate +// either UI surface. +const MAX_SESSION_TITLE_LENGTH = 80 export type GranularSeries = { id: string @@ -41,6 +47,25 @@ type RawBucket = { sessions: Map } +type SessionTitleCandidate = { + title: string + lastTimestamp: string +} + +type SessionLabelInfo = { + provider: string + projectPath: string + projectNames: Set + sessionId: string + titleCandidates: Map +} + +type SessionLabelEntry = { + key: string + info: SessionLabelInfo + baseLabel: string +} + function nonNegative(value: number): number { return Number.isFinite(value) && value > 0 ? value : 0 } @@ -99,6 +124,114 @@ function shortSessionId(sessionId: string): string { return trimmed.length > 12 ? `${trimmed.slice(0, 6)}…${trimmed.slice(-4)}` : trimmed || 'unknown' } +function cleanSessionTitle(title: string | undefined): string | undefined { + if (title === undefined) return undefined + + // Match the control-character range used by the model-name sanitizer. ANSI + // sequences are removed first; remaining controls become spaces so transcript + // line breaks cannot join words before internal whitespace is collapsed. + const cleaned = stripAnsi(title) + .replace(/[\x00-\x1F\x7F-\x9F]/g, ' ') + .replace(/\s+/g, ' ') + .trim() + if (!cleaned) return undefined + + return Array.from(cleaned).slice(0, MAX_SESSION_TITLE_LENGTH).join('').trimEnd() || undefined +} + +// SessionSummary.lastTimestamp is normally an ISO timestamp, but fixtures and +// older cache entries can be incomplete. Valid timestamps win over invalid +// ones; two invalid values are an exact tie and are resolved alphabetically by +// the caller. +function compareTimestamps(a: string, b: string): number { + const aMs = Date.parse(a) + const bMs = Date.parse(b) + const aValid = Number.isFinite(aMs) + const bValid = Number.isFinite(bMs) + if (aValid && bValid) return aMs - bMs + if (aValid) return 1 + if (bValid) return -1 + return 0 +} + +function preferredProjectName(projectNames: Set): string { + return [...projectNames].sort()[0] ?? 'Unknown project' +} + +function preferredSessionTitle(titleCandidates: Map): string | undefined { + const cleaned = [...titleCandidates.values()] + .map(candidate => { + const title = cleanSessionTitle(candidate.title) + return title === undefined ? undefined : { title, lastTimestamp: candidate.lastTimestamp } + }) + .filter((candidate): candidate is SessionTitleCandidate => candidate !== undefined) + + cleaned.sort((a, b) => { + const timestampOrder = compareTimestamps(b.lastTimestamp, a.lastTimestamp) + if (timestampOrder !== 0) return timestampOrder + return a.title < b.title ? -1 : a.title > b.title ? 1 : 0 + }) + return cleaned[0]?.title +} + +function buildSessionLabels(inputs: Map): Map { + // Stable raw-key order makes the residual used-label guard independent of + // project/session discovery order when a title happens to match another + // label shape. + const entries: SessionLabelEntry[] = [...inputs.entries()].map(([key, info]) => { + const sessionLabel = preferredSessionTitle(info.titleCandidates) + ?? shortProjectLabel(info.projectPath, preferredProjectName(info.projectNames)) + return { + key, + info, + baseLabel: `${shortSessionId(info.sessionId)} (${info.provider}) · ${sessionLabel}`, + } + }).sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0) + const byBaseLabel = new Map() + for (const entry of entries) { + const group = byBaseLabel.get(entry.baseLabel) ?? [] + group.push(entry) + byBaseLabel.set(entry.baseLabel, group) + } + + const labels = new Map() + const usedLabels = new Set() + const setUniqueLabel = (entry: SessionLabelEntry, candidate: string): void => { + let label = candidate + if (usedLabels.has(label)) { + const identity = `${candidate} · ${entry.info.projectPath} · ${entry.info.sessionId}` + label = identity + let suffix = 2 + while (usedLabels.has(label)) label = `${identity} · ${suffix++}` + } + labels.set(entry.key, label) + usedLabels.add(label) + } + for (const group of byBaseLabel.values()) { + if (group.length === 1) { + setUniqueLabel(group[0]!, group[0]!.baseLabel) + continue + } + + const projectLabels = group.map(entry => shortProjectLabel(entry.info.projectPath, preferredProjectName(entry.info.projectNames))) + if (new Set(projectLabels).size === group.length) { + for (let i = 0; i < group.length; i++) { + const entry = group[i]! + setUniqueLabel(entry, `${entry.baseLabel} · ${projectLabels[i]}`) + } + continue + } + + // A short project label can still collide (for example two worktrees with + // the same final path segments). The full path + id is only used for this + // residual collision, and is unique because provider/path/id form the key. + for (const entry of group) { + setUniqueLabel(entry, `${entry.baseLabel} · ${entry.info.projectPath} · ${entry.info.sessionId}`) + } + } + return labels +} + // Legend labels: the sanitized project dir ("-Users-name-Projects-app") is // unreadable, so prefer the real projectPath's last two segments ("app/web"). // Fall back to the sanitized name when no usable path exists. @@ -184,7 +317,7 @@ export function buildGranularHistory( const modelTotals = new Map() const sessionTotals = new Map() const modelLabels = new Map() - const sessionLabels = new Map() + const sessionLabelInputs = new Map() let callCount = 0 for (const project of projects) { @@ -214,7 +347,27 @@ export function buildGranularHistory( add(modelTotals, modelKey, cost, tokens) add(sessionTotals, sessionKey, cost, tokens) modelLabels.set(modelKey, modelKey === '' ? 'Other model' : modelKey) - sessionLabels.set(sessionKey, `${shortProjectLabel(project.projectPath, projectName)} · ${shortSessionId(session.sessionId)} (${call.provider})`) + // Collect raw metadata first. Titles are cleaned once per distinct + // session-key candidate after all calls are aggregated, so a late + // cache title can win without putting sanitisation on the call path. + const labelInfo = sessionLabelInputs.get(sessionKey) ?? { + provider: call.provider, + projectPath: project.projectPath, + projectNames: new Set(), + sessionId: session.sessionId, + titleCandidates: new Map(), + } + labelInfo.projectNames.add(projectName) + if (session.title !== undefined) { + const existingTitle = labelInfo.titleCandidates.get(session.title) + if (!existingTitle || compareTimestamps(session.lastTimestamp, existingTitle.lastTimestamp) > 0) { + labelInfo.titleCandidates.set(session.title, { + title: session.title, + lastTimestamp: session.lastTimestamp, + }) + } + } + sessionLabelInputs.set(sessionKey, labelInfo) callCount++ } } @@ -225,6 +378,7 @@ export function buildGranularHistory( return { bucketMinutes, modelSeries: [], sessionSeries: [], points: [] } } + const sessionLabels = buildSessionLabels(sessionLabelInputs) const modelProjection = projectSeries(rawBuckets, 'models', modelTotals, modelLabels) const sessionProjection = projectSeries(rawBuckets, 'sessions', sessionTotals, sessionLabels) return { diff --git a/src/main.ts b/src/main.ts index 8dacf5d3..6c4ab584 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2,7 +2,7 @@ import { isAbsolute } from 'path' import { Command, Option } from 'commander' import { installMenubarApp } from './menubar-installer.js' import { exportCsv, exportJson, type PeriodExport } from './export.js' -import { findUnpricedModels, loadPricing, setModelAliases, setPriceOverrides, setLocalModelSavings, setProxyPaths, normalizeProxyPath } from './models.js' +import { findUnpricedModels, loadPricing, sanitizeModelForDisplay, setModelAliases, setPriceOverrides, setLocalModelSavings, setProxyPaths, normalizeProxyPath } from './models.js' import { parseAllSessions, filterProjectsByName, filterProjectsByDateRange, clearSessionCache, setInteractiveScanUI } from './parser.js' import { allProviderNames, getAllProviders } from './providers/index.js' import { getProvider } from './providers/index.js' @@ -12,6 +12,7 @@ import { toDateString } from './daily-cache.js' import { dateKey } from './day-aggregator.js' import { isBehavioralCall, isBehavioralTurn } from './behavioral-weight.js' import { CATEGORY_LABELS, type DateRange, type ProjectSummary, type TaskCategory } from './types.js' +import type { AppliedFix } from './act/types.js' import { aggregateModelEfficiency } from './model-efficiency.js' import { buildPeriodData, buildMenubarPayloadForRange, buildDurablePeriod, type DurablePeriod } from './usage-aggregator.js' import { renderDashboard } from './dashboard.js' @@ -1320,12 +1321,13 @@ program program .command('menubar') - .description('Install and launch the macOS menubar app (one command, no clone)') - .option('--force', 'Reinstall even if an older copy is already in ~/Applications') + .description('Install and launch the menubar app on macOS and Windows (one command, no clone)') + .option('--force', 'Reinstall even if a copy is already installed') .action(async (opts: { force?: boolean }) => { try { const result = await installMenubarApp({ force: opts.force, cliVersion: version }) - console.log(`\n Ready. ${result.installedPath}\n`) + // A cancelled Windows installer leaves nothing to point at. + if (result.installedPath) console.log(`\n Ready. ${result.installedPath}\n`) } catch (err) { const message = err instanceof Error ? err.message : String(err) console.error(`\n Menubar install failed: ${message}\n`) @@ -1816,6 +1818,7 @@ program .option('--yes', 'With --apply: apply every appliable fix without prompting') .option('--dry-run', 'With --apply: print the plan and exit without changing anything') .option('--only ', 'With --apply: restrict to a comma-separated list of finding ids') + .option('--auto-revert', 'Undo applied fixes that measured no reduction (never CLAUDE.md rules)') .action(async (opts) => { assertProvider(opts.provider, 'optimize') const format = opts.json ? 'json' : opts.format @@ -1841,28 +1844,35 @@ program const projects = await parseAllSessions(range, opts.provider) if (opts.apply) { const { runOptimizeApply } = await import('./act/optimize-apply.js') - await runOptimizeApply(projects, range, { yes: opts.yes, dryRun: opts.dryRun, only: opts.only }) + await runOptimizeApply(projects, range, { yes: opts.yes, dryRun: opts.dryRun, only: opts.only, provider: opts.provider }) return } assertFormat(format, ['text', 'json'], 'optimize') - if (format === 'text') { - // Surface realized savings from applied actions. Best effort: optimize - // must never fail because of journal contents, so any error just drops - // the header. computeActReport returns fast without scanning when the - // journal has no eligible applied actions, so users who never opted in - // see identical output. - let appliedHeader: string | undefined - let previouslyApplied: Record | undefined - try { - const { computeActReport, buildOptimizeAppliedHeader } = await import('./act/report.js') - const applied = await computeActReport() - appliedHeader = buildOptimizeAppliedHeader(applied) ?? undefined - previouslyApplied = applied.appliedByFinding - } catch { /* the header is optional; never block the findings */ } - await runOptimize(projects, label, range, { format, appliedHeader, previouslyApplied }) - } else { - await runOptimize(projects, label, range, { format }) - } + // Surface realized savings from applied actions, and re-measure every one + // of them. Best effort: optimize must never fail because of journal + // contents, so any error just drops the extras. computeActReport returns + // fast without scanning when the journal has no applied actions, so users + // who never opted in see identical output. + let appliedHeader: string | undefined + let previouslyApplied: Record | undefined + let appliedFixes: AppliedFix[] | undefined + try { + const { computeActReport, buildOptimizeAppliedHeader, autoRevertNoEffect } = await import('./act/report.js') + const applied = await computeActReport() + appliedHeader = buildOptimizeAppliedHeader(applied) ?? undefined + previouslyApplied = applied.appliedByFinding + appliedFixes = applied.appliedFixes + if (opts.autoRevert) { + const { lines, revertedIds } = await autoRevertNoEffect(appliedFixes) + appliedFixes = appliedFixes.filter(f => !revertedIds.has(f.id)) + // JSON output must stay parseable, so the revert log goes to stderr there. + for (const line of lines) { + if (format === 'json') process.stderr.write(` ${line}\n`) + else console.log(` ${line}`) + } + } + } catch { /* the applied section is optional; never block the findings */ } + await runOptimize(projects, label, range, { format, appliedHeader, previouslyApplied, appliedFixes, provider: opts.provider }) }) program @@ -2085,6 +2095,7 @@ program .option('--by-agent', 'One row per (provider, model, agent) instead of one row per (provider, model). Claude subagent transcripts only; other providers and main sessions bucket under "main"') .option('--top ', 'Show only the top N rows', (v: string) => parseInt(v, 10)) .option('--min-cost ', 'Hide rows below this cost threshold', (v: string) => parseFloat(v)) + .option('--unpriced', 'Show only models with usage that currently price at $0') .option('--no-totals', 'Suppress the footer totals row') .option('--format ', 'Output format: table, markdown, json, csv', 'table') .action(async (opts) => { @@ -2109,27 +2120,60 @@ program } const projects = await parseAllSessions(range, opts.provider) - const rows = await aggregateModels(projects, { + const topN = typeof opts.top === 'number' && Number.isFinite(opts.top) ? opts.top : undefined + let rows = await aggregateModels(projects, { byTask: !!opts.byTask, byAgent: !!opts.byAgent, taskFilter: opts.task, - topN: typeof opts.top === 'number' && Number.isFinite(opts.top) ? opts.top : undefined, - minCost: typeof opts.minCost === 'number' && Number.isFinite(opts.minCost) ? opts.minCost : 0.01, + // `aggregateModels` filters and slices before the unpriced filter. Its + // rows are sorted cost-first, so a small --top would remove exactly the + // rows `--unpriced` exists to show. Take the whole set here and slice + // after filtering and ranking instead. + topN: opts.unpriced ? undefined : topN, + minCost: typeof opts.minCost === 'number' && Number.isFinite(opts.minCost) ? opts.minCost : (opts.unpriced ? 0 : 0.01), }) + if (opts.unpriced) { + const unpriced = findUnpricedModels(rows.map(row => ({ + model: row.model, + calls: row.calls, + cost: row.costUSD, + tokens: row.totalTokens, + }))) + const unpricedRank = new Map() + for (const [rank, usage] of unpriced.entries()) { + // Breakdown modes can emit several rows for one model. Keep the first + // rank so all rows for that model stay together and N still counts rows. + if (!unpricedRank.has(usage.model)) unpricedRank.set(usage.model, rank) + } + rows = rows + .filter(row => unpricedRank.has(row.model)) + .sort((a, b) => (unpricedRank.get(a.model)! - unpricedRank.get(b.model)!)) + if (topN !== undefined) rows = rows.slice(0, topN) + } const fmt = (opts.format ?? 'table').toLowerCase() if (rows.length === 0 && (fmt === 'table' || fmt === 'markdown')) { - process.stdout.write('No model usage found for the selected period.\n') + process.stdout.write(opts.unpriced + ? 'No unpriced models found for the selected period.\n' + : 'No model usage found for the selected period.\n') return } + // The friendly name is useless for `model-alias`, which keys on the raw ID. + // Sanitized because this bypasses the shared display path in models-report. + const renderRows = opts.unpriced && fmt !== 'json' + ? rows.map(row => ({ ...row, modelDisplayName: sanitizeModelForDisplay(row.model) })) + : rows if (fmt === 'json') { process.stdout.write(renderJson(rows) + '\n') } else if (fmt === 'csv') { - process.stdout.write(renderCsv(rows, { byTask: !!opts.byTask, byAgent: !!opts.byAgent }) + '\n') + process.stdout.write(renderCsv(renderRows, { byTask: !!opts.byTask, byAgent: !!opts.byAgent }) + '\n') } else if (fmt === 'markdown' || fmt === 'md') { - process.stdout.write(renderMarkdown(rows, { byTask: !!opts.byTask, byAgent: !!opts.byAgent, showTotals: opts.totals !== false }) + '\n') + process.stdout.write(renderMarkdown(renderRows, { byTask: !!opts.byTask, byAgent: !!opts.byAgent, showTotals: opts.totals !== false }) + '\n') } else if (fmt === 'table') { - process.stdout.write(renderTable(rows, { byTask: !!opts.byTask, byAgent: !!opts.byAgent, showTotals: opts.totals !== false }) + '\n') + process.stdout.write(renderTable(renderRows, { byTask: !!opts.byTask, byAgent: !!opts.byAgent, showTotals: opts.totals !== false }) + '\n') + // Never advise aliasing unconditionally: a subscription or flat-rate model + // is correctly $0, and mapping it onto another model's rate invents spend. + if (opts.unpriced) process.stdout.write('If a model is billed per token, map it with: codeburn model-alias "" . Subscription or flat-rate models are correctly $0.\n') } else { process.stderr.write(`codeburn: unknown --format "${opts.format}". Choose table, markdown, json, or csv.\n`) process.exit(1) diff --git a/src/menubar-installer.ts b/src/menubar-installer.ts index b43b136f..62494349 100644 --- a/src/menubar-installer.ts +++ b/src/menubar-installer.ts @@ -8,6 +8,7 @@ import { pipeline } from 'node:stream/promises' import { Readable } from 'node:stream' import { ProxyAgent, fetch as undiciFetch } from 'undici' +import { getCodeburnCacheDir } from './cache-dir.js' import { buildPersistentCodeburnLookupPath, resolvePersistentCodeburnPathFromWhichOutput, @@ -22,6 +23,11 @@ const EXPECTED_BUNDLE_ID = 'org.agentseal.codeburn-menubar' const VERSIONED_ASSET_PATTERN = /^CodeBurnMenubar-v.+\.zip$/ const APP_PROCESS_NAME = 'CodeBurnMenubar' const SUPPORTED_OS = 'darwin' +/// The Windows tray app (windows/) ships as an .msi under its own `windows-v*` tag. GitHub +/// rewrites the spaces in the bundle name to dots when it stores the asset, so both the asset +/// name and its download URL carry `CodeBurn.Menubar_...`. +const WINDOWS_PRODUCT_NAME = 'CodeBurn Menubar' +const WINDOWS_ASSET_PATTERN = /^CodeBurn\.Menubar_.+_x64_en-US\.msi$/ const MIN_MACOS_MAJOR = 14 const PERSISTED_CLI_PATH = join(homedir(), 'Library', 'Application Support', 'CodeBurn', 'codeburn-cli-path.v1') const PERSISTENT_CLI_REQUIRED_MESSAGE = @@ -31,8 +37,45 @@ export type InstallResult = { installedPath: string; launched: boolean } export type ReleaseAsset = { name: string; browser_download_url: string } export type ReleaseResponse = { tag_name: string; assets: ReleaseAsset[] } +/// `zip` is the platform's primary asset: the mac bundle zip, or the Windows .msi. export type ResolvedAssets = { release: ReleaseResponse; zip: ReleaseAsset; checksum: ReleaseAsset } -export type InstallOptions = { force?: boolean; cliVersion?: string } +export type InstallOptions = { + force?: boolean + cliVersion?: string + platform?: string + windows?: WindowsInstallHooks +} + +/// What differs per platform between the mac and Windows installs: which release tag holds the +/// build, and which asset in it is the installable. Everything downstream - versioned URL first, +/// release-API scan as fallback, retrying download, checksum verify - is shared. +export type ReleaseSpec = { + tagPrefix: string + assetPattern: RegExp + assetName: (version: string) => string + missingAsset: (tag: string) => string + noRelease: string +} + +const MAC_RELEASE: ReleaseSpec = { + tagPrefix: 'mac-v', + assetPattern: VERSIONED_ASSET_PATTERN, + assetName: version => `CodeBurnMenubar-v${version}.zip`, + missingAsset: tag => + `No ${APP_BUNDLE_NAME} versioned zip found in release ${tag}. ` + + `Check https://github.com/getagentseal/codeburn/releases.`, + noRelease: 'No mac-v* release with a CodeBurnMenubar-v*.zip and checksum was found.', +} + +export const WINDOWS_RELEASE: ReleaseSpec = { + tagPrefix: 'windows-v', + assetPattern: WINDOWS_ASSET_PATTERN, + assetName: version => `CodeBurn.Menubar_${version}_x64_en-US.msi`, + missingAsset: tag => + `No ${WINDOWS_PRODUCT_NAME} .msi found in release ${tag}. ` + + `Check https://github.com/getagentseal/codeburn/releases.`, + noRelease: 'No windows-v* release with a CodeBurn.Menubar_*.msi and checksum was found.', +} type ProxyEnv = Partial> type FetchOptions = Parameters[1] type HeaderGetter = { get(name: string): string | null } @@ -47,6 +90,10 @@ type FetchLikeResponse = { text(): Promise } type FetchImpl = (url: string, options?: FetchOptions) => Promise +/// The release-API lookup reads JSON instead of streaming a body, so it takes its own narrow +/// response shape rather than widening FetchLikeResponse for every asset download fake. +export type ReleaseApiFetch = (url: string, options?: FetchOptions) => + Promise<{ ok: boolean; status: number; headers: HeaderGetter; json(): Promise }> /// Release-asset delivery (github.com -> Azure blob) occasionally returns a transient 5xx or /// drops the socket. Three attempts with a short exponential backoff (0.5s, then 1s) rides out @@ -96,14 +143,9 @@ function fetchWithProxy(url: string, options: FetchOptions = {}) { return undiciFetch(url, dispatcher ? { ...options, dispatcher } : options) } -export function resolveMenubarReleaseAssets(release: ReleaseResponse): ResolvedAssets { - const zip = release.assets.find(a => VERSIONED_ASSET_PATTERN.test(a.name)) - if (!zip) { - throw new Error( - `No ${APP_BUNDLE_NAME} versioned zip found in release ${release.tag_name}. ` + - `Check https://github.com/getagentseal/codeburn/releases.` - ) - } +export function resolveMenubarReleaseAssets(release: ReleaseResponse, spec: ReleaseSpec = MAC_RELEASE): ResolvedAssets { + const zip = release.assets.find(a => spec.assetPattern.test(a.name)) + if (!zip) throw new Error(spec.missingAsset(release.tag_name)) const checksum = release.assets.find(a => a.name === `${zip.name}.sha256`) if (!checksum) { throw new Error(`Missing checksum asset ${zip.name}.sha256 in release ${release.tag_name}.`) @@ -111,28 +153,28 @@ export function resolveMenubarReleaseAssets(release: ReleaseResponse): ResolvedA return { release, zip, checksum } } -export function resolveLatestMenubarReleaseAssets(releases: ReleaseResponse[]): ResolvedAssets { +export function resolveLatestMenubarReleaseAssets(releases: ReleaseResponse[], spec: ReleaseSpec = MAC_RELEASE): ResolvedAssets { for (const release of releases) { - if (!release.tag_name.startsWith('mac-v')) continue + if (!release.tag_name.startsWith(spec.tagPrefix)) continue try { - return resolveMenubarReleaseAssets(release) + return resolveMenubarReleaseAssets(release, spec) } catch { continue } } - throw new Error('No mac-v* release with a CodeBurnMenubar-v*.zip and checksum was found.') + throw new Error(spec.noRelease) } function normalizeCliVersion(cliVersion: string): string { return cliVersion.trim().replace(/^v/, '') } -export function resolveVersionedMenubarReleaseAssets(cliVersion: string): ResolvedAssets { +export function resolveVersionedMenubarReleaseAssets(cliVersion: string, spec: ReleaseSpec = MAC_RELEASE): ResolvedAssets { const version = normalizeCliVersion(cliVersion) if (!version) throw new Error('Cannot resolve CodeBurn Menubar release without a CLI version.') - const tagName = `mac-v${version}` - const zipName = `CodeBurnMenubar-v${version}.zip` + const tagName = `${spec.tagPrefix}${version}` + const zipName = spec.assetName(version) const checksumName = `${zipName}.sha256` const releaseBase = `${RELEASE_DOWNLOAD_BASE}/${tagName}` const zip = { name: zipName, browser_download_url: `${releaseBase}/${zipName}` } @@ -207,8 +249,8 @@ async function sysProductVersion(): Promise { }) } -async function fetchLatestReleaseAssets(): Promise { - const response = await fetchWithProxy(RELEASE_API, { +async function fetchLatestReleaseAssets(spec: ReleaseSpec = MAC_RELEASE, fetchImpl?: ReleaseApiFetch): Promise { + const response = await (fetchImpl ?? fetchWithProxy)(RELEASE_API, { headers: { 'User-Agent': 'codeburn-menubar-installer', Accept: 'application/vnd.github+json', @@ -218,7 +260,7 @@ async function fetchLatestReleaseAssets(): Promise { throw new HttpStatusError(formatGitHubReleaseLookupError(response.status, response.headers), response.status) } const body = await response.json() as ReleaseResponse[] - return resolveLatestMenubarReleaseAssets(body) + return resolveLatestMenubarReleaseAssets(body, spec) } /// 5xx means "GitHub/the CDN is unhappy right now" and is worth another attempt. 4xx is not: @@ -473,7 +515,165 @@ async function killRunningApp(): Promise { } } +/// Windows mirror of the mac install below: pin the release to the CLI's own version, fall back +/// to the newest windows-v* release, verify the sha256 before anything executes the file, hand +/// the .msi to msiexec, then launch what it installed. +const WINDOWS_UNINSTALL_KEYS = [ + 'HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall', + 'HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall', + 'HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall', +] +/// 3010 is "installed, reboot to finish"; 1602 is the user closing the UAC/installer prompt. +const MSI_EXIT_REBOOT_REQUIRED = 3010 +const MSI_EXIT_USER_CANCEL = 1602 + +export type WindowsInstallHooks = { + fetchOptions?: AssetFetchOptions + apiFetch?: ReleaseApiFetch + runInstaller?: (exe: string, args: string[]) => Promise + queryRegistry?: () => Promise + launch?: (exePath: string) => void + log?: (message: string) => void + stagingDir?: string + env?: NodeJS.ProcessEnv +} + +export type InstalledWindowsMenubar = { version: string; exePath: string } + +/// Windows' `CreateProcess` searches the current directory before `PATH`, so spawning `msiexec` +/// or `reg` by bare name lets anything dropped next to the CLI impersonate a system tool. Same +/// rule the tray app follows (windows/src-tauri/src/cli.rs: system32_path). +export function resolveSystem32Path(exe: string, env: NodeJS.ProcessEnv = process.env): string { + const root = env.SystemRoot + const base = root && /^[a-zA-Z]:[\\/]/.test(root) ? root.replace(/[\\/]+$/, '') : 'C:\\Windows' + return `${base}\\System32\\${exe}` +} + +/// Reads `reg query ... /s` output, which prints one blank-line separated block per subkey. +export function parseInstalledWindowsMenubar(regOutput: string): InstalledWindowsMenubar | undefined { + for (const block of regOutput.split(/\r?\n\s*\r?\n/)) { + const values = new Map() + for (const line of block.split(/\r?\n/)) { + const match = /^\s+(.+?)\s{4}REG_\w+\s{4}(.*)$/.exec(line) + if (match) values.set(match[1]!.trim(), match[2]!.trim()) + } + if (values.get('DisplayName') !== WINDOWS_PRODUCT_NAME) continue + const location = values.get('InstallLocation') + // DisplayIcon is `[,]` and points at the installed binary when there is no + // InstallLocation to join onto. + const icon = values.get('DisplayIcon')?.split(',')[0]?.trim() + const exePath = location + ? `${location.replace(/[\\/]+$/, '')}\\${WINDOWS_PRODUCT_NAME}.exe` + : icon + if (!exePath) continue + return { version: values.get('DisplayVersion') ?? '', exePath } + } + return undefined +} + +async function queryWindowsUninstallRegistry(env: NodeJS.ProcessEnv): Promise { + const reg = resolveSystem32Path('reg.exe', env) + // reg exits non-zero for a hive the machine does not have; an empty block is the right answer. + const outputs = await Promise.all( + WINDOWS_UNINSTALL_KEYS.map(key => captureCommand(reg, ['query', key, '/s']).catch(() => '')), + ) + return outputs.join('\n\n') +} + +async function runMsiexec(exe: string, args: string[]): Promise { + return new Promise((resolve, reject) => { + const proc = spawn(exe, args, { stdio: 'inherit' }) + proc.on('error', reject) + proc.on('close', code => resolve(code ?? 1)) + }) +} + +function launchWindowsApp(exePath: string): void { + const proc = spawn(exePath, [], { detached: true, stdio: 'ignore' }) + proc.on('error', err => console.error(`Could not launch ${exePath}: ${err.message}`)) + proc.unref() +} + +async function stageWindowsInstaller( + assets: ResolvedAssets, + stagingDir: string, + hooks: WindowsInstallHooks, + log: (message: string) => void, +): Promise { + const { zip: msi, checksum } = assets + const msiPath = join(stagingDir, msi.name) + log(`Downloading ${msi.name}...`) + await downloadToFile(msi.browser_download_url, msiPath, hooks.fetchOptions) + log('Verifying checksum...') + await verifyChecksum(msiPath, checksum.browser_download_url, hooks.fetchOptions) + return msiPath +} + +async function installWindowsMenubarApp(options: InstallOptions): Promise { + const hooks = options.windows ?? {} + const log = hooks.log ?? console.log + const env = hooks.env ?? process.env + const queryRegistry = hooks.queryRegistry ?? (() => queryWindowsUninstallRegistry(env)) + const launch = hooks.launch ?? launchWindowsApp + const cliVersion = options.cliVersion ? normalizeCliVersion(options.cliVersion) : '' + + const installed = parseInstalledWindowsMenubar(await queryRegistry()) + if (installed && !options.force && (!cliVersion || installed.version === cliVersion)) { + launch(installed.exePath) + log('Launched CodeBurn Menubar.') + return { installedPath: installed.exePath, launched: true } + } + + let assets: ResolvedAssets + if (cliVersion) { + log(`Resolving CodeBurn Menubar v${cliVersion}...`) + assets = resolveVersionedMenubarReleaseAssets(cliVersion, WINDOWS_RELEASE) + } else { + log('Looking up the latest CodeBurn Menubar release...') + assets = await fetchLatestReleaseAssets(WINDOWS_RELEASE, hooks.apiFetch) + } + + const stagingDir = hooks.stagingDir ?? await (async () => { + await mkdir(getCodeburnCacheDir(), { recursive: true }) + return mkdtemp(join(getCodeburnCacheDir(), 'menubar-')) + })() + try { + let msiPath: string + try { + msiPath = await stageWindowsInstaller(assets, stagingDir, hooks, log) + } catch (err) { + if (!cliVersion || !isMissingDirectAssetError(err)) throw err + log(`CodeBurn Menubar v${cliVersion} assets were not found. Looking up the latest CodeBurn Menubar release...`) + assets = await fetchLatestReleaseAssets(WINDOWS_RELEASE, hooks.apiFetch) + msiPath = await stageWindowsInstaller(assets, stagingDir, hooks, log) + } + + log('Installing...') + const msiexec = resolveSystem32Path('msiexec.exe', env) + const exitCode = await (hooks.runInstaller ?? runMsiexec)(msiexec, ['/i', msiPath, '/passive', '/norestart']) + if (exitCode === MSI_EXIT_USER_CANCEL) { + log('Installation was cancelled; nothing was installed.') + return { installedPath: '', launched: false } + } + if (exitCode !== 0 && exitCode !== MSI_EXIT_REBOOT_REQUIRED) { + throw new Error(`msiexec exited with ${exitCode} while installing ${assets.zip.name}.`) + } + if (exitCode === MSI_EXIT_REBOOT_REQUIRED) log('Windows wants a restart to finish the install.') + + const nowInstalled = parseInstalledWindowsMenubar(await queryRegistry()) + if (!nowInstalled) { + throw new Error('CodeBurn Menubar installed, but it was not found in the uninstall registry; start it from the Start menu.') + } + launch(nowInstalled.exePath) + log('Launched CodeBurn Menubar.') + return { installedPath: nowInstalled.exePath, launched: true } + } finally { + if (!hooks.stagingDir) await rm(stagingDir, { recursive: true, force: true }) + } +} + export async function installMenubarApp(options: InstallOptions = {}): Promise { + if ((options.platform ?? platform()) === 'win32') return installWindowsMenubarApp(options) await ensureSupportedPlatform() await persistCodeburnPath() diff --git a/src/models-report.ts b/src/models-report.ts index 720e2994..483a05cb 100644 --- a/src/models-report.ts +++ b/src/models-report.ts @@ -4,6 +4,7 @@ import stripAnsi from 'strip-ansi' import { isBehavioralCall } from './behavioral-weight.js' import { codexCredits } from './codex-credits.js' import { formatCost, formatTokens } from './format.js' +import { sanitizeModelForDisplay } from './models.js' import { getProvider } from './providers/index.js' import { CATEGORY_LABELS, type ProjectSummary, type TaskCategory } from './types.js' @@ -160,7 +161,9 @@ export async function aggregateModels(projects: ProjectSummary[], opts: Aggregat const p = await getProvider(name) const entry = { displayName: p?.displayName ?? name, - formatModel: p ? (m: string) => p.modelDisplayName(m) : (m: string) => m, + formatModel: p + ? (m: string) => sanitizeModelForDisplay(p.modelDisplayName(m)) + : sanitizeModelForDisplay, } providerCache.set(name, entry) return entry diff --git a/src/models.ts b/src/models.ts index bf4ed448..4413d084 100644 --- a/src/models.ts +++ b/src/models.ts @@ -297,6 +297,10 @@ const BUILTIN_ALIASES: Record = { 'k3-agent': 'kimi-k3', 'k2d6-agent': 'kimi-k2p6', 'mimo-v2-flash': 'xiaomi/mimo-v2-flash', + // Hermes / Xiaomi token-plan sessions store the bare id. LiteLLM's row is + // namespaced. Same class as mimo-v2-flash above — do not invent a rate. + 'mimo-v2.5-pro': 'xiaomi/mimo-v2.5-pro', + 'mimo-v2.5': 'xiaomi/mimo-v2.5', 'kat-coder-pro-v1': 'kwaipilot/kat-coder-pro', // Cursor emits dot-version tier-last names plus tier/reasoning suffixes // that LiteLLM does not index (`-high`, `-low`, `-medium`, `-thinking`, @@ -307,7 +311,7 @@ const BUILTIN_ALIASES: Record = { // reports that quote literal slugs (e.g. forum.cursor.com/t/154933). 'claude-4-sonnet': 'claude-sonnet-4', 'claude-4-sonnet-1m': 'claude-sonnet-4', - 'claude-4-sonnet-thinking': 'claude-sonnet-4-5', + 'claude-4-sonnet-thinking': 'claude-sonnet-4', 'claude-4.5-sonnet': 'claude-sonnet-4-5', 'claude-4.5-sonnet-thinking': 'claude-sonnet-4-5', 'claude-4.6-sonnet': 'claude-sonnet-4-6', @@ -791,6 +795,11 @@ function shouldWarnAboutUnknownModel(name: string): boolean { return true } +/** Render provider-supplied model IDs without terminal control characters. */ +export function sanitizeModelForDisplay(model: string): string { + return model.replace(/[\x00-\x1F\x7F-\x9F]/g, '?').slice(0, 200) +} + export function calculateCost( model: string, inputTokens: number, @@ -808,7 +817,7 @@ export function calculateCost( // Strip control characters and cap length: model names come from JSONL // payloads written by external tools, so a hostile or corrupt file // could embed terminal escape sequences here. - const safeName = model.replace(/[\x00-\x1F\x7F-\x9F]/g, '?').slice(0, 200) + const safeName = sanitizeModelForDisplay(model) const aliasHint = `Map it with: codeburn model-alias "${safeName}" , or track local-model savings with: codeburn model-savings "${safeName}" ` process.stderr.write( `codeburn: no pricing data for model "${safeName}" — costs for this model will show $0. ` + @@ -942,11 +951,17 @@ const SHORT_NAMES: Record = { // The Grok Build harness reports the model it runs (`grok-4.5`), so this is // the model's own name; `grok-build*` ids still resolve to "Grok Build". 'grok-4.5': 'Grok 4.5', + // The harness also reports a `-build` variant of that model. It is a distinct + // id and reports bucket by id, so without its own entry the prefix match gave + // it the same name as `grok-4.5` and the report showed two identical rows. + 'grok-4.5-build': 'Grok 4.5 (build)', // ClinePass routes models as `cline-pass/`; getShortModelName's path // fallback strips the prefix and re-resolves the bare slug through this // table, the same way it handles `accounts/fireworks/models/`. 'qwen3.7-max': 'Qwen 3.7 Max', 'mimo-v2.5-pro': 'MiMo v2.5 Pro', + 'mimo-v2.5': 'MiMo v2.5', + 'mimo-v2-flash': 'MiMo v2 Flash', // Both spellings occur in the wild: OpenRouter gap-filled keys are lowercase // slugs while sessions report the capitalized name (see the case-insensitive // pricing index above). SHORT_NAMES matching is case-sensitive, so map both. @@ -972,28 +987,57 @@ function deriveClaudeShortName(canonical: string): string | undefined { return `${CLAUDE_FAMILY[family]} ${major}${minor ? `.${minor}` : ''}` } -export function getShortModelName(model: string): string { - if (autoModelNames[model]) return autoModelNames[model] - const canonical = resolveAlias(getCanonicalName(model)) - const claude = deriveClaudeShortName(canonical) +function lookupShortName(id: string): string | undefined { + const claude = deriveClaudeShortName(id) if (claude) return claude for (const [key, name] of SORTED_SHORT_NAMES) { - // Match on a version boundary, not a bare prefix: an unlisted future minor - // (e.g. gpt-5.6) must NOT collapse into the base "gpt-5" entry — it should - // fall through to its raw id rather than show a wrong name/tier. - if (canonical === key || canonical.startsWith(key + '-')) return name + if (id === key || id.startsWith(key + '-')) return name } - // getCanonicalName only strips the leading provider prefix, so a raw - // path-style id (e.g. accounts/fireworks/models/glm-5p2) still has slashes - // here. Take the last path segment and re-resolve it: the segment may itself - // be a known model slug (Fireworks fleet ids), earning a friendly name; a - // genuinely unmapped slug resolves to itself, preserving the raw-segment - // fallback for everything else. + return undefined +} + +// Public API stays unary so Array.map/forEach cannot feed index as cycle state. +export function getShortModelName(model: string): string { + return shortModelName(model, new Set()) +} + +function shortModelName(model: string, seen: Set): string { + if (autoModelNames[model]) return autoModelNames[model] + if (seen.has(model)) { + const leaf = model.includes('/') ? model.slice(model.lastIndexOf('/') + 1) : model + return lookupShortName(leaf) ?? leaf + } + seen.add(model) + + // User aliases win over built-in display names. A remap of gpt-4o must + // show the target, not "GPT-4o". + if (Object.hasOwn(userAliases, model)) { + return shortModelName(userAliases[model]!, seen) + } + + const stripped = getCanonicalName(model) + if (stripped !== model) { + if (Object.hasOwn(userAliases, stripped)) { + return shortModelName(userAliases[stripped]!, seen) + } + const knownStripped = lookupShortName(stripped) + if (knownStripped && !Object.hasOwn(BUILTIN_ALIASES, stripped) && !Object.hasOwn(BUILTIN_ALIASES, stripped.toLowerCase())) { + return knownStripped + } + } + + const canonical = resolveAlias(stripped) + const known = lookupShortName(canonical) + if (known) return known + if (canonical.includes('/')) { const segment = canonical.slice(canonical.lastIndexOf('/') + 1) - return segment ? getShortModelName(segment) : canonical + if (!segment || seen.has(segment) || segment === stripped) { + return lookupShortName(segment) ?? segment + } + return shortModelName(segment, seen) } - return canonical + return lookupShortName(canonical) ?? canonical } // Pricing is process-global state assembled at CLI startup from the cached diff --git a/src/optimize.ts b/src/optimize.ts index 63d49330..2ecd348b 100644 --- a/src/optimize.ts +++ b/src/optimize.ts @@ -1,10 +1,12 @@ import chalk from 'chalk' -import { isReadShapedBashCommand } from './bash-utils.js' +import stripAnsi from 'strip-ansi' +import { createHash } from 'crypto' import { readdir, stat } from 'fs/promises' import { existsSync, statSync } from 'fs' import { basename, join } from 'path' import { homedir } from 'os' +import { isReadShapedBashCommand } from './bash-utils.js' import { readSessionLines, readSessionFileSync } from './fs-utils.js' import { discoverAllSessions } from './providers/index.js' import { parseJsonlLine, shouldSkipLine } from './parser.js' @@ -12,6 +14,8 @@ import type { DateRange, ProjectSummary, SessionSummary } from './types.js' import { formatCost } from './currency.js' import { formatTokens } from './format.js' import { recommendModelDefault, type ModelDefaultRecommendation } from './act/model-defaults.js' +import { appliedFixGlyph, formatAppliedFix, type AppliedFix } from './act/types.js' +import { isUserStartedSession, userStartedProjects } from './session-population.js' import { aggregateFileChurn, buildCoachingNotes, scanUserCorrections, medianTimeToFirstEditMs, worstOneShotCategory, type ReworkedFile } from './workflow-insights.js' // ============================================================================ @@ -168,6 +172,17 @@ const DEFER_THRESHOLD_DEFAULT_PERCENT = 10 const DEFER_THRESHOLD_MAX_PERCENT = 100 const DEFER_THRESHOLD_MIN_TOKENS_PER_SESSION = 5_000 const DEFER_THRESHOLD_MEDIUM_IMPACT_TOKENS = 200_000 +// "recurring-context": the same block opening session after session. 1.5 KB +// is roughly 400 tokens at BASH_TOKENS_PER_CHAR — below that a repeated +// opener costs too little to be worth a habit change, and five sessions is +// where "I keep pasting this" stops looking like coincidence. +const RECURRING_CONTEXT_MIN_CHARS = 1_500 +const RECURRING_CONTEXT_MIN_SESSIONS = 5 +const RECURRING_CONTEXT_NORMALIZE_SLACK = 4 +const RECURRING_CONTEXT_PREVIEW = 3 +const RECURRING_CONTEXT_PREVIEW_CHARS = 80 +const RECURRING_CONTEXT_MEDIUM_IMPACT_TOKENS = 50_000 +const RECURRING_CONTEXT_HIGH_IMPACT_TOKENS = 200_000 // ============================================================================ // Scoring constants @@ -232,6 +247,7 @@ export type PasteDestination = | 'session-opener' // one-time paste at the start of a NEW session | 'prompt' // one-time ask in the current Claude conversation | 'shell-config' // append to ~/.zshrc / ~/.bashrc + | 'manual' // instructions the user carries out directly export type WasteAction = | { type: 'paste'; label: string; text: string; destination?: PasteDestination } @@ -263,6 +279,154 @@ export type FindingId = | 'unused-agents' | 'unused-skills' | 'unused-commands' + | 'recurring-context' + +/// How a finding is meant to be acted on: +/// - `fix` CodeBurn can write the change itself (`codeburn optimize --apply`) +/// - `nudge` behavioural, the user changes a habit +/// - `keep` informational; the cost may well be justified +export type FindingClass = 'fix' | 'nudge' | 'keep' + +/// Where a finding's `tokensSaved` number comes from: +/// - `measured` summed from provider-counted usage on the parsed calls +/// - `estimated` a schema/heuristic model (per-tool sizes, recovery fractions) +/// A detector that mixes the two counts as `estimated`. +export type FindingBasis = 'measured' | 'estimated' + +/// Static class per finding id. `fix` entries are exactly the ids `buildPlan` +/// (src/act/plans.ts) routes to a plan builder; tests assert the two lists +/// stay equal. Instances that lack the payload their builder needs fall back +/// to `nudge` via `findingClass`. +export const FINDING_CLASS: Record = { + 'read-edit-ratio': 'fix', // CLAUDE.md rule block + 'build-folder-reads': 'fix', // CLAUDE.md rule block + 'redundant-rereads': 'nudge', + 'warmup-heavy': 'nudge', + 'unused-mcp': 'fix', + 'mcp-low-coverage': 'fix', + 'mcp-project-scope': 'fix', + 'mcp-deferral-off': 'fix', + 'mcp-alwaysload-hygiene': 'fix', + 'mcp-defer-threshold': 'fix', + 'retry-heavy-capabilities': 'nudge', + 'low-worth-sessions': 'nudge', + 'context-heavy-sessions': 'keep', // context-heavy work is often load-bearing + 'cost-outliers': 'nudge', + 'claude-md-too-long': 'nudge', // trimming is a judgement call, not a rule block + 'bash-output-cap': 'fix', + 'unused-agents': 'fix', + 'unused-skills': 'fix', + 'unused-commands': 'fix', + 'recurring-context': 'nudge', +} + +/// Ids whose plan is built from the `apply` payload: without it the plan +/// builder returns null, so the finding is only a nudge. +const CLASS_NEEDS_APPLY: ReadonlySet = new Set([ + 'unused-mcp', + 'mcp-low-coverage', + 'mcp-project-scope', + 'mcp-deferral-off', + 'mcp-alwaysload-hygiene', + 'mcp-defer-threshold', + 'unused-agents', + 'unused-skills', + 'unused-commands', +]) + +/// Static basis per finding id. Only the two session-level detectors sum +/// provider-counted tokens end to end; everything else multiplies a modelled +/// per-unit size or a recovery fraction. +export const FINDING_BASIS: Record = { + 'read-edit-ratio': 'estimated', // reads x AVG_TOKENS_PER_READ + 'build-folder-reads': 'estimated', // reads x AVG_TOKENS_PER_READ + 'redundant-rereads': 'estimated', // reads x AVG_TOKENS_PER_READ + 'warmup-heavy': 'estimated', // observed median minus a modelled baseline + 'unused-mcp': 'estimated', // tools x TOKENS_PER_MCP_TOOL x sessions + 'mcp-low-coverage': 'estimated', // schema-size model, only capped by observed cache tokens + 'mcp-project-scope': 'estimated', // same schema-size model + 'mcp-deferral-off': 'estimated', // schema-size model x affected sessions + 'mcp-alwaysload-hygiene': 'estimated', // tools x TOKENS_PER_MCP_TOOL x loaded sessions + 'mcp-defer-threshold': 'estimated', // definition-size model x sessions + 'retry-heavy-capabilities': 'estimated', // real turn tokens x recovery fraction + 'low-worth-sessions': 'estimated', // real session tokens x recovery fraction + 'context-heavy-sessions': 'measured', // counted input/cache tokens above the target ratio + 'cost-outliers': 'measured', // counted session tokens above the peer average + 'claude-md-too-long': 'estimated', // lines x CLAUDEMD_TOKENS_PER_LINE + 'bash-output-cap': 'estimated', // chars x BASH_TOKENS_PER_CHAR + 'unused-agents': 'estimated', // count x TOKENS_PER_AGENT_DEF + 'unused-skills': 'estimated', // count x TOKENS_PER_SKILL_DEF + 'unused-commands': 'estimated', // count x TOKENS_PER_COMMAND_DEF + // Provider usage is per API call: the first turn's input tokens mix the + // system prompt, tool schemas and CLAUDE.md in with the pasted block, so + // nothing counted isolates the block. Its size is modelled from its bytes. + 'recurring-context': 'estimated', // block chars x BASH_TOKENS_PER_CHAR x repeats +} + +/// Scope label for a setting that lives in ~/.zshrc / ~/.bashrc. The MCP +/// deferral plans (defer-enable, defer-threshold) refuse to rewrite an +/// override found there and report it instead; bash-output-cap does append +/// its own marker block to the shell rc. +export const SHELL_PROFILE_SCOPE = 'shell profile' + +export function findingClass(f: WasteFinding): FindingClass { + const base = FINDING_CLASS[f.id] + if (base !== 'fix') return base + if (CLASS_NEEDS_APPLY.has(f.id) && !f.apply) return 'nudge' + const apply = f.apply + if ((apply?.kind === 'defer-enable' || apply?.kind === 'defer-threshold') && apply.settingScope === SHELL_PROFILE_SCOPE) { + return 'nudge' + } + // Of the deferral causes only these two have a plan; the rest are manual + // advice (Vertex policy, an outdated Claude Code, an unverified proxy). + if (apply?.kind === 'defer-enable' && apply.cause !== 'env-false' && apply.cause !== 'proxy-verified') return 'nudge' + return 'fix' +} + +export function findingBasis(f: WasteFinding): FindingBasis { + return f.basis ?? FINDING_BASIS[f.id] +} + +const CLASS_ORDER: Record = { fix: 0, nudge: 1, keep: 2 } + +export const CLASS_HEADERS: Record = { + fix: 'Fix now (apply-able)', + nudge: 'Habits', + keep: 'FYI', +} + +export type ClassTotals = { tokensSaved: number; savingsUSD: number; count: number } + +export function classTotals(findings: WasteFinding[], costRate: number): Record { + const totals: Record = { + fix: { tokensSaved: 0, savingsUSD: 0, count: 0 }, + nudge: { tokensSaved: 0, savingsUSD: 0, count: 0 }, + keep: { tokensSaved: 0, savingsUSD: 0, count: 0 }, + } + for (const f of findings) { + const cls = findingClass(f) + // A `fix` whose plan owns only part of its estimate (a mixed local + + // claude.ai connector MCP finding) contributes only the apply-able + // subset, so this subtotal and the "apply-able" headline never promise + // what `--apply` cannot recover. The finding keeps the whole + // opportunity in its own `tokensSaved`, so the fix subtotal can be + // smaller than the findings listed under it. + const tokens = cls === 'fix' ? f.applyTokensSaved ?? f.tokensSaved : f.tokensSaved + const t = totals[cls] + t.tokensSaved += tokens + t.savingsUSD += tokens * costRate + t.count++ + } + return totals +} + +/// Group header with its own subtotal, shared by the CLI and the TUI so the +/// two never drift apart. +export function classHeaderLine(cls: FindingClass, totals: ClassTotals, costRate: number): string { + const cost = costRate > 0 ? ` (~${formatCost(totals.savingsUSD)})` : '' + const suffix = cls === 'fix' ? ' — codeburn optimize --apply' : '' + return `${CLASS_HEADERS[cls]} · ~${formatTokens(totals.tokensSaved)} tokens${cost} · ${totals.count} finding${totals.count === 1 ? '' : 's'}${suffix}` +} // Cause taxonomy for defer-enable plans (mcp-deferral-off findings). // 'proxy-verified' is never produced by the detector today: it is reserved @@ -300,9 +464,24 @@ export type WasteFinding = { explanation: string impact: Impact tokensSaved: number + /// Savings attributable to the automatic mutation when it covers only a + /// subset of the finding. Omitted when `tokensSaved` already describes the + /// whole apply action (or when the finding is manual-only). + applyTokensSaved?: number + /// Per-server shares from the same capped cost pass as `tokensSaved`. + /// Internal apply/report consumers use this to price only targets that a + /// concrete mutation plan can actually edit; JSON output remains stable. + applyTokensSavedByServer?: Record + /// Additional by-hand action retained when `fix` is an executable local + /// command (for example, connector guidance beside a local MCP removal). + /// Internal apply UI metadata; the stable optimize JSON mapper omits it. + manualFollowUp?: { label: string; text: string } fix: WasteAction trend?: Trend apply?: FindingApply + /// Set only when a detector's basis varies per run (see detectSessionOutliers); + /// otherwise `FINDING_BASIS[id]` applies. Read through `findingBasis`. + basis?: FindingBasis } export type OptimizeResult = { @@ -330,6 +509,12 @@ export type OptimizeJsonReport = { potentialSavingsCostUSD: number potentialSavingsPercent: number | null costRateUSD: number + /// Portion of `potentialSavingsCostUSD` coming from `measured`-basis + /// findings. The total keeps its old meaning: measured plus estimated. + measuredSavingsUSD: number + /// Per-class subtotals; the three counts and token sums add up to + /// `findingCount` and `potentialSavingsTokens`. + byClass: Record } findings: Array<{ id: FindingId @@ -339,6 +524,8 @@ export type OptimizeJsonReport = { trend: Trend | null tokensSaved: number estimatedSavingsUSD: number + class: FindingClass + basis: FindingBasis fix: WasteAction }> /// Files most reworked by edit-family calls, relative to project root (top 15). @@ -346,6 +533,8 @@ export type OptimizeJsonReport = { /// 1-3 templated one-liners keyed on the strongest workflow signals. coachingNotes: string[] modelRecommendations?: Array + /// One entry per still-applied fix, re-measured on every run (see act/report.ts). + appliedFixes: Array> } export type ToolCall = { @@ -354,6 +543,7 @@ export type ToolCall = { sessionId: string project: string recent?: boolean + isSidechain?: boolean } export type ApiCallMeta = { @@ -362,11 +552,22 @@ export type ApiCallMeta = { recent?: boolean } +/// One session's opening paste. `hash` groups sessions that open with the +/// same block; `chars` is the block's length, a floor for a block long +/// enough that the parser capped its text. +export type SessionOpener = { + hash: string + chars: number + project: string + preview: string +} + type ScanData = { toolCalls: ToolCall[] projectCwds: Set apiCalls: ApiCallMeta[] userMessages: string[] + openers: SessionOpener[] } // ============================================================================ @@ -453,6 +654,43 @@ type ScanFileResult = { cwds: string[] apiCalls: ApiCallMeta[] userMessages: string[] + openers: SessionOpener[] +} + +/// Whitespace-insensitive so the same block reflowed by a different paste +/// still groups, and ANSI-free so terminal output pasted twice matches. +function normalizeOpener(text: string): string { + return stripAnsi(text).replace(/\s+/g, ' ').trim() +} + +/// True when a program wrote this prompt rather than a person pasting it: an +/// SDK caller, or a parent agent writing a subagent's task. Either repeats by +/// design and has no home in CLAUDE.md. Both flags survive the parser's +/// large-line path, which is where generated prompts routinely land. +function isMachineWrittenPrompt(entry: Record): boolean { + return entry['promptSource'] === 'sdk' || entry['isSidechain'] === true +} + +/// A session's opening block, or null when it is too small to matter or is +/// not a paste at all: system reminders carry CLAUDE.md and hook output, +/// slash command wrappers refer to a file that already exists. `chars` is a +/// floor: the parser caps the text of a very large user entry, so a huge +/// block is sized at that cap rather than its true length. +function toSessionOpener(text: string, project: string): SessionOpener | null { + if (text.length < RECURRING_CONTEXT_MIN_CHARS) return null + const head = text.trimStart() + if (head.startsWith('') || head.startsWith('') || head.startsWith('')) return null + // Normalizing before the cap is what lets a re-flowed paste hash the same; + // the pre-slice keeps the work per session bounded however long the block + // is, with slack for whitespace that expands under re-flow. + const normalized = normalizeOpener(text.slice(0, OPTIMIZE_TEXT_CAP * RECURRING_CONTEXT_NORMALIZE_SLACK)) + .slice(0, OPTIMIZE_TEXT_CAP) + return { + hash: createHash('sha1').update(normalized).digest('hex'), + chars: text.length, + project, + preview: normalized.slice(0, RECURRING_CONTEXT_PREVIEW_CHARS), + } } function inRange(timestamp: string | undefined, range: DateRange | undefined): boolean { @@ -477,8 +715,13 @@ export async function scanJsonlFile( const cwds: string[] = [] const apiCalls: ApiCallMeta[] = [] const userMessages: string[] = [] + const openers: SessionOpener[] = [] const sessionId = basename(filePath, '.jsonl') let lastVersion = '' + let fileIsSidechain = false + // The opening block is the first user message carrying text; anything + // later in the session is not what the user opens with. + let sawUserText = false const skipThreshold = dateRange ? new Date(dateRange.start.getTime() - 86_400_000).toISOString() @@ -494,6 +737,11 @@ export async function scanJsonlFile( if (!parsed) continue const entry = parsed as Record + if (entry.isSidechain === true && !fileIsSidechain) { + fileIsSidechain = true + for (const call of calls) call.isSidechain = true + } + if (entry.version && typeof entry.version === 'string') lastVersion = entry.version const ts = typeof entry.timestamp === 'string' ? entry.timestamp : undefined @@ -508,6 +756,11 @@ export async function scanJsonlFile( const msgContent = msg?.content if (typeof msgContent === 'string') { userMessages.push(msgContent.slice(0, OPTIMIZE_TEXT_CAP)) + if (!sawUserText) { + sawUserText = true + const opener = isMachineWrittenPrompt(entry) ? null : toSessionOpener(msgContent, project) + if (opener) openers.push(opener) + } } else if (Array.isArray(msgContent)) { let remaining = OPTIMIZE_TEXT_CAP for (const block of msgContent) { @@ -516,6 +769,11 @@ export async function scanJsonlFile( const text = block.text.slice(0, remaining) userMessages.push(text) remaining -= text.length + if (!sawUserText) { + sawUserText = true + const opener = isMachineWrittenPrompt(entry) ? null : toSessionOpener(block.text, project) + if (opener) openers.push(opener) + } } } } @@ -544,19 +802,32 @@ export async function scanJsonlFile( sessionId, project, recent, + isSidechain: fileIsSidechain, }) } } - return { calls, cwds, apiCalls, userMessages } + return { calls, cwds, apiCalls, userMessages, openers } } -async function scanSessions(dateRange?: DateRange): Promise { +// The session scan reads Claude Code transcripts only, so a `--provider` that +// excludes Claude leaves nothing for it to do. Callers must also skip the +// detectors it feeds (see `claudeOnly` in scanAndDetect) — the empty scan +// returned here is an absence of measurement, not a measurement of absence. +export function providerCoversClaude(provider?: string): boolean { + return !provider || provider === 'all' || provider === 'claude' +} + +async function scanSessions(dateRange?: DateRange, provider?: string): Promise { + if (!providerCoversClaude(provider)) { + return { toolCalls: [], projectCwds: new Set(), apiCalls: [], userMessages: [], openers: [] } + } const sources = await discoverAllSessions('claude') const allCalls: ToolCall[] = [] const allCwds = new Set() const allApiCalls: ApiCallMeta[] = [] const allUserMessages: string[] = [] + const allOpeners: SessionOpener[] = [] const tasks: Array<{ file: string; project: string }> = [] for (const source of sources) { @@ -568,14 +839,15 @@ async function scanSessions(dateRange?: DateRange): Promise { } await runWithConcurrency(tasks, FILE_READ_CONCURRENCY, async ({ file, project }) => { - const { calls, cwds, apiCalls, userMessages } = await scanJsonlFile(file, project, dateRange) + const { calls, cwds, apiCalls, userMessages, openers } = await scanJsonlFile(file, project, dateRange) allCalls.push(...calls) for (const cwd of cwds) allCwds.add(cwd) allApiCalls.push(...apiCalls) allUserMessages.push(...userMessages) + allOpeners.push(...openers) }) - return { toolCalls: allCalls, projectCwds: allCwds, apiCalls: allApiCalls, userMessages: allUserMessages } + return { toolCalls: allCalls, projectCwds: allCwds, apiCalls: allApiCalls, userMessages: allUserMessages, openers: allOpeners } } // ============================================================================ @@ -650,6 +922,27 @@ export function loadMcpConfigs(projectCwds: Iterable, homeDir = homedir( return servers } +/// Server names owned by readable local MCP config, normalized the way +/// transcript namespaces are (":" -> "_"). `loadMcpConfigs` covers +/// settings.json and .mcp.json; `~/.claude.json` adds the top-level and +/// per-project `mcpServers` containers the remove plan also edits. +/// +/// A `claude_ai_*` namespace listed here is a local server that happens to +/// carry the connector prefix, not a claude.ai connector. Config we cannot +/// read simply contributes no names, which leaves those namespaces on the +/// conservative connector path. +export function localMcpServerNames(projectCwds: Iterable, homeDir = homedir()): Set { + const names = new Set(loadMcpConfigs(projectCwds, homeDir).keys()) + const userJson = readJsonFile(join(homeDir, '.claude.json')) + const projects = (userJson?.['projects'] ?? {}) as Record + const containers = [userJson?.['mcpServers'], ...Object.values(projects).map(entry => entry?.mcpServers)] + for (const container of containers) { + if (!container || typeof container !== 'object') continue + for (const name of Object.keys(container)) names.add(name.replace(/:/g, '_')) + } + return names +} + // ============================================================================ // Detectors // ============================================================================ @@ -705,6 +998,11 @@ export function detectJunkReads(calls: ToolCall[], dateRange?: DateRange): Waste } export function detectDuplicateReads(calls: ToolCall[], dateRange?: DateRange): WasteFinding | null { + // A sidechain re-reading what its parent read is not a repeat: a subagent + // starts on a fresh context and has to read it. Junk reads and the + // read:edit ratio keep the full call population - that waste is waste + // whoever does it, and the CLAUDE.md rule they suggest binds subagents too. + calls = calls.filter(call => call.isSidechain !== true) const sessionFiles = new Map>() for (const call of calls) { @@ -789,6 +1087,12 @@ type McpSchemaCostEstimate = { effectiveInputTokens: number } +type McpSchemaCostAttribution = McpSchemaCostEstimate & { + byServer: Record +} + +type McpUnusedToolsByServer = Record + /** * Aggregate MCP inventory and invocations across the projects in scope. * @@ -964,49 +1268,86 @@ export function estimateMcpSchemaCost( counts = unusedToolCounts } - const totalUnusedSchemaTokens = servers.reduce( - (s, srv) => s + (counts[srv] ?? 0) * TOKENS_PER_MCP_TOOL, - 0, - ) - if (totalUnusedSchemaTokens === 0) { - return { cacheWriteTokens: 0, cacheReadTokens: 0, effectiveInputTokens: 0 } + const attributed = estimateMcpSchemaCostAttributed(counts, projects, servers) + return { + cacheWriteTokens: attributed.cacheWriteTokens, + cacheReadTokens: attributed.cacheReadTokens, + effectiveInputTokens: attributed.effectiveInputTokens, + } +} + +function estimateMcpSchemaCostAttributed( + unusedToolsByServer: McpUnusedToolsByServer, + projects: ProjectSummary[], + servers: string[], +): McpSchemaCostAttribution { + servers = [...new Set(servers)] + const byServer: Record = {} + for (const server of servers) { + byServer[server] = { cacheWriteTokens: 0, cacheReadTokens: 0, effectiveInputTokens: 0 } } - const serverSet = new Set(servers) - let cacheWriteTokens = 0 - let cacheReadTokens = 0 + const addBucket = ( + loaded: Array<{ server: string; schemaTokens: number }>, + bucket: number, + key: 'cacheWriteTokens' | 'cacheReadTokens', + ): void => { + if (bucket <= 0) return + const totalSchemaTokens = loaded.reduce((sum, entry) => sum + entry.schemaTokens, 0) + if (totalSchemaTokens <= 0) return + const charged = Math.min(totalSchemaTokens, bucket) + for (const entry of loaded) { + byServer[entry.server]![key] += charged * (entry.schemaTokens / totalSchemaTokens) + } + } for (const project of projects) { for (const session of project.sessions) { - // A session counts only if its observed inventory included at least - // one of the flagged servers — same invariant `aggregateMcpCoverage` - // uses for `loadedSessions`. - let loaded = false - for (const fqn of session.mcpInventory ?? []) { - const seg = fqn.split('__')[1] - if (seg && serverSet.has(seg)) { loaded = true; break } + const inventory = new Set(session.mcpInventory ?? []) + const inventoryCounts = new Map() + for (const fqn of inventory) { + const parts = fqn.split('__') + if (parts[0] !== 'mcp' || !parts[1] || parts.length < 3) continue + inventoryCounts.set(parts[1], (inventoryCounts.get(parts[1]) ?? 0) + 1) } - if (!loaded) continue + + const loaded: Array<{ server: string; schemaTokens: number }> = [] + for (const server of servers) { + const unused = unusedToolsByServer[server] + const toolCount = typeof unused === 'number' + ? Math.min(unused, inventoryCounts.get(server) ?? 0) + : [...new Set(unused ?? [])].reduce((count, fqn) => count + (inventory.has(fqn) ? 1 : 0), 0) + if (toolCount > 0) loaded.push({ server, schemaTokens: toolCount * TOKENS_PER_MCP_TOOL }) + } + if (loaded.length === 0) continue for (const turn of session.turns) { for (const call of turn.assistantCalls) { - // Both buckets can be non-zero on the same call (cache rebuild - // alongside a partial read), so account for them independently. - // The cap is applied to the combined unused-schema budget so - // multiple flagged servers cannot all claim the same call. - if (call.usage.cacheCreationInputTokens > 0) { - cacheWriteTokens += Math.min(totalUnusedSchemaTokens, call.usage.cacheCreationInputTokens) - } - if (call.usage.cacheReadInputTokens > 0) { - cacheReadTokens += Math.min(totalUnusedSchemaTokens, call.usage.cacheReadInputTokens) - } + // A cache bucket is shared by every flagged schema loaded on this + // call. Charge it once, then attribute the capped amount in + // proportion to each server's unused schema. This conserves the + // combined total and makes any local-only subset additive. + addBucket(loaded, call.usage.cacheCreationInputTokens, 'cacheWriteTokens') + addBucket(loaded, call.usage.cacheReadInputTokens, 'cacheReadTokens') } } } } - const effectiveInputTokens = cacheWriteTokens * CACHE_WRITE_MULTIPLIER + cacheReadTokens * CACHE_READ_DISCOUNT - return { cacheWriteTokens, cacheReadTokens, effectiveInputTokens } + let cacheWriteTokens = 0 + let cacheReadTokens = 0 + for (const estimate of Object.values(byServer)) { + estimate.effectiveInputTokens = estimate.cacheWriteTokens * CACHE_WRITE_MULTIPLIER + + estimate.cacheReadTokens * CACHE_READ_DISCOUNT + cacheWriteTokens += estimate.cacheWriteTokens + cacheReadTokens += estimate.cacheReadTokens + } + return { + cacheWriteTokens, + cacheReadTokens, + effectiveInputTokens: cacheWriteTokens * CACHE_WRITE_MULTIPLIER + cacheReadTokens * CACHE_READ_DISCOUNT, + byServer, + } } /** @@ -1026,6 +1367,7 @@ export function estimateMcpSchemaCost( export function detectMcpToolCoverage( projects: ProjectSummary[], coverage = aggregateMcpCoverage(projects), + localServerNames: ReadonlySet = new Set(), ): WasteFinding | null { if (coverage.length === 0) return null @@ -1040,30 +1382,102 @@ export function detectMcpToolCoverage( const lines: string[] = [] const removeCommands: string[] = [] - const unusedCountsByServer: Record = {} + const unusedToolsByServer: Record = {} const flaggedServers: string[] = [] + const localServers: string[] = [] + const connectorServers: string[] = [] + // Local, but named like a connector: the transcript cannot tell the two + // apart, so the removal targets the config entry and the guidance warns + // about a possible same-name connector instead of asserting one. + const ambiguousServers: string[] = [] for (const c of flagged) { - unusedCountsByServer[c.server] = c.toolsAvailable - c.toolsInvoked + unusedToolsByServer[c.server] = c.unusedTools flaggedServers.push(c.server) const pct = Math.round(c.coverageRatio * 100) lines.push( `${c.server}: ${c.toolsInvoked}/${c.toolsAvailable} tools used (${pct}% coverage) across ${c.loadedSessions} session${c.loadedSessions === 1 ? '' : 's'}`, ) - removeCommands.push(`claude mcp remove '${c.server}'`) + if (c.server.startsWith('claude_ai_') && !localServerNames.has(c.server)) { + connectorServers.push(c.server) + } else { + if (c.server.startsWith('claude_ai_')) ambiguousServers.push(c.server) + localServers.push(c.server) + removeCommands.push(`claude mcp remove '${c.server}'`) + } } // Single combined cost pass: caps each call's contribution at the // total unused-schema budget across all flagged servers, so two // flagged servers cannot independently claim the same call's cache // bucket and overstate `tokensSaved`. - const cost = estimateMcpSchemaCost(unusedCountsByServer, projects, flaggedServers) + const cost = estimateMcpSchemaCostAttributed(unusedToolsByServer, projects, flaggedServers) const tokensSaved = Math.round(cost.effectiveInputTokens) + const applyTokensSavedByServer = Object.fromEntries(localServers.map(server => [ + server, + cost.byServer[server]?.effectiveInputTokens ?? 0, + ])) + const localTokensSaved = Object.values(applyTokensSavedByServer).reduce((sum, value) => sum + value, 0) + const applyTokensSaved = localServers.length > 0 && connectorServers.length > 0 + ? Math.round(localTokensSaved) + : undefined const impact: Impact = tokensSaved >= MCP_COVERAGE_HIGH_IMPACT_TOKENS ? 'high' : flagged.length >= UNUSED_MCP_HIGH_THRESHOLD ? 'high' : 'medium' + // `claude_ai_*` is Claude Code's transcript namespace for server-side + // claude.ai connectors, which are not local mcpServers entries, so + // `claude mcp remove` and the file-editing apply plan cannot own them -- + // unless readable local config claims the exact name (`ambiguousServers`). + // Coverage is aggregate here; project-level config attribution is deliberately + // out of scope, hence the instruction to inspect /mcp per affected project. + const one = connectorServers.length === 1 + const connectorLabels = connectorServers.map(server => + `claude.ai ${server.slice('claude_ai_'.length).replaceAll('_', ' ')}`, + ) + const connectorEvidence = connectorServers.map((server, index) => + `${connectorLabels[index]} (${server})`, + ) + const connectorGuidance = connectorServers.length > 0 + ? ` ${connectorEvidence.join(', ')} ${one ? 'is a claude.ai connector namespace' : 'are claude.ai connector namespaces'}, separate from any similarly named local MCP server. Transcript inventory is aggregated across the selected projects; use /mcp in each project where ${one ? 'it loads' : 'they load'}, or manage ${one ? 'it' : 'them'} in claude.ai Settings > Connectors.` + : '' + const oneAmbiguous = ambiguousServers.length === 1 + const ambiguousNote = ambiguousServers.length > 0 + ? `If you also use ${oneAmbiguous ? 'a claude.ai connector' : 'claude.ai connectors'} named ${ambiguousServers.join(', ')}, manage ${oneAmbiguous ? 'it' : 'them'} with /mcp or in claude.ai Settings > Connectors.` + : '' + const ambiguousGuidance = ambiguousServers.length > 0 + ? ` ${ambiguousServers.join(', ')} ${oneAmbiguous ? 'is a local MCP config entry whose name matches' : 'are local MCP config entries whose names match'} the claude.ai connector namespace, so the removal below edits local config only. ${ambiguousNote}` + : '' + const connectorText = [ + connectorServers.length > 0 + ? `Open /mcp in each affected project and disable ${connectorLabels.join(', ')}, or manage ${one ? 'it' : 'them'} in claude.ai Settings > Connectors.` + : '', + ambiguousNote, + ].filter(Boolean).join(' ') + const connectorAction = connectorText + ? { + label: connectorServers.length === 0 + ? 'Check for a same-name claude.ai connector:' + : one ? 'Manage the underused claude.ai connector where it loads:' + : 'Manage the underused claude.ai connectors where they load:', + text: connectorText, + } + : undefined + const fix: WasteAction = localServers.length > 0 + ? { + type: 'command', + label: localServers.length === 1 + ? 'Remove the underused local server, or trim its tools in your MCP config:' + : 'Remove underused local servers, or trim their tools in your MCP config:', + text: removeCommands.join('\n'), + } + : { + type: 'paste', + destination: 'manual', + label: connectorAction!.label, + text: connectorAction!.text, + } return { id: 'mcp-low-coverage', @@ -1071,17 +1485,16 @@ export function detectMcpToolCoverage( explanation: `Schema for unused tools is loaded into the system prompt every session and ` + `carried in the cached prefix on every turn. ` + - `${lines.join('; ')}.`, + `${lines.join('; ')}.${connectorGuidance}${ambiguousGuidance}`, impact, tokensSaved, - fix: { - type: 'command', - label: flagged.length === 1 - ? 'Remove the underused server, or trim its tools in your MCP config:' - : 'Remove underused servers, or trim their tools in your MCP config:', - text: removeCommands.join('\n'), - }, - apply: { kind: 'mcp-remove', servers: flaggedServers }, + ...(applyTokensSaved !== undefined ? { applyTokensSaved } : {}), + ...(localServers.length > 0 ? { applyTokensSavedByServer } : {}), + ...(localServers.length > 0 && connectorAction ? { manualFollowUp: connectorAction } : {}), + fix, + ...(localServers.length > 0 + ? { apply: { kind: 'mcp-remove' as const, servers: localServers } } + : {}), } } @@ -1514,6 +1927,7 @@ function findCapabilityReliabilityCandidates(projects: ProjectSummary[]): Capabi } export function detectCapabilityReliability(projects: ProjectSummary[]): WasteFinding | null { + projects = userStartedProjects(projects) const candidates = findCapabilityReliabilityCandidates(projects) if (candidates.length === 0) return null @@ -1705,7 +2119,7 @@ export function findDeferralEnvSetting( const content = readSessionFileSync(path) if (content === null) continue const match = content.match(linePattern) - if (match) return { value: match[1]!, scope: 'shell profile', path } + if (match) return { value: match[1]!, scope: SHELL_PROFILE_SCOPE, path } } return null } @@ -2477,6 +2891,60 @@ export function detectBashBloat(): WasteFinding | null { } } +/// The same long block opening many sessions: a spec, a repo dump, a standing +/// brief. Every repeat is input tokens for context that could live in +/// CLAUDE.md or in a file read on demand. The first paste is the honest cost +/// of saying it once, so only the repeats count as savings. +export function detectRecurringContext(openers: SessionOpener[]): WasteFinding | null { + type Group = { sessions: number; chars: number; preview: string; projects: Set } + const groups = new Map() + for (const o of openers) { + const g = groups.get(o.hash) + if (!g) { + groups.set(o.hash, { sessions: 1, chars: o.chars, preview: o.preview, projects: new Set([o.project]) }) + continue + } + g.sessions++ + // Only the hashed prefix is known to match, so size the block by the + // smallest occurrence rather than claiming the longest. + g.chars = Math.min(g.chars, o.chars) + g.projects.add(o.project) + } + + const repeated = [...groups.values()] + .filter(g => g.sessions >= RECURRING_CONTEXT_MIN_SESSIONS) + .map(g => ({ ...g, tokens: Math.round((g.sessions - 1) * g.chars * BASH_TOKENS_PER_CHAR) })) + .sort((a, b) => b.tokens - a.tokens) + if (repeated.length === 0) return null + + const tokensSaved = repeated.reduce((sum, g) => sum + g.tokens, 0) + const top = repeated[0] + const preview = repeated.slice(0, RECURRING_CONTEXT_PREVIEW) + const list = preview + .map(g => { + const where = g.projects.size === 1 + ? [...g.projects][0].split('-').filter(Boolean).pop() ?? [...g.projects][0] + : `${g.projects.size} projects` + return `"${g.preview}..." — ${g.sessions} sessions in ${where}, ~${formatTokens(g.tokens)} tokens` + }) + .join('; ') + const extra = repeated.length > preview.length ? `; +${repeated.length - preview.length} more` : '' + + return { + id: 'recurring-context', + title: `Same ${(top.chars / 1024).toFixed(1)} KB block pasted at the start of ${top.sessions} sessions`, + explanation: `These sessions open with a block you have pasted before, so you pay input tokens for the same context every time: ${list}${extra}. Standing rules belong in CLAUDE.md; reference material belongs in a file Claude reads on demand. Only the repeats are counted, not the first paste.`, + impact: tokensSaved >= RECURRING_CONTEXT_HIGH_IMPACT_TOKENS ? 'high' : tokensSaved >= RECURRING_CONTEXT_MEDIUM_IMPACT_TOKENS ? 'medium' : 'low', + tokensSaved, + fix: { + type: 'paste', + destination: 'prompt', + label: 'Ask Claude to give this block a permanent home:', + text: `I open many sessions by pasting this block:\n"${top.preview}..."\nMove it into CLAUDE.md if it is a standing rule, or into a file you read on demand if it is reference material, then tell me the one-line pointer to start sessions with instead.`, + }, + } +} + function sessionTokenTotal(session: ProjectSummary['sessions'][number]): number { return session.totalInputTokens + session.totalOutputTokens @@ -2484,6 +2952,22 @@ function sessionTokenTotal(session: ProjectSummary['sessions'][number]): number + session.totalCacheWriteTokens } +// Sidechain transcripts are real usage, so they stay in project totals and in +// token/cost calibration. They are not user-started sessions, however, and +// should never enter optimize heuristics whose unit is a human work session. +// Keep that distinction local to optimize instead of deleting sidechains from +// ProjectSummary, which would under-report the work delegated to subagents. +function isOptimizeSession(session: ProjectSummary['sessions'][number]): boolean { + return isUserStartedSession(session) +} + +function optimizeSessionCount(projects: ProjectSummary[]): number { + return projects.reduce( + (total, project) => total + project.sessions.filter(isOptimizeSession).length, + 0, + ) +} + function sessionEffectiveContextTokens(session: ProjectSummary['sessions'][number]): number { return session.totalInputTokens + session.totalCacheReadTokens * CACHE_READ_DISCOUNT @@ -2592,6 +3076,7 @@ export function findLowWorthCandidates(projects: ProjectSummary[]): LowWorthCand for (const project of projects) { for (const session of project.sessions) { + if (!isOptimizeSession(session)) continue if (session.totalCostUSD < WORTH_IT_MIN_COST_USD) continue if (sessionDeliveryCommand(session)) continue @@ -2692,7 +3177,7 @@ export function findContextBloatCandidates(projects: ProjectSummary[]): ContextB const candidates: ContextBloatCandidate[] = [] for (const project of projects) { - const sessions = [...project.sessions].sort((a, b) => + const sessions = project.sessions.filter(isOptimizeSession).sort((a, b) => new Date(a.firstTimestamp).getTime() - new Date(b.firstTimestamp).getTime() ) let previousInputTokens: number | null = null @@ -2700,7 +3185,9 @@ export function findContextBloatCandidates(projects: ProjectSummary[]): ContextB for (const session of sessions) { const inputTokens = sessionEffectiveContextTokens(session) - const outputTokens = session.totalOutputTokens + // Reasoning is stored separately from ordinary output, but both are + // generated tokens for this detector. Reports already use their sum. + const outputTokens = session.totalOutputTokens + session.totalReasoningTokens const ratio = inputTokens / Math.max(outputTokens, 1) const currentMs = new Date(session.firstTimestamp).getTime() const gapMs = previousTimestampMs !== null ? currentMs - previousTimestampMs : null @@ -2803,9 +3290,17 @@ export function detectSessionOutliers(projects: ProjectSummary[], excludedSessio } const outliers: Outlier[] = [] + // Modelled costs (Kiro, Cursor, some Cline sessions) are not comparable + // against provider-reported ones, so they leave the peer math. Providers + // that only ever estimate would lose the finding entirely, so those fall + // back to the full set and the finding reports itself as estimated. + let usedEstimatedCosts = false for (const project of projects) { - const sessions = project.sessions.filter(s => s.totalCostUSD > 0) + const costed = project.sessions.filter(s => isOptimizeSession(s) && s.totalCostUSD > 0) + const exact = costed.filter(s => (s.totalEstimatedCostUSD ?? 0) === 0) + const sessions = exact.length >= MIN_SESSIONS_FOR_OUTLIER ? exact : costed + const fellBack = sessions.length > exact.length if (sessions.length < MIN_SESSIONS_FOR_OUTLIER) continue const totalCost = sessions.reduce((sum, s) => sum + s.totalCostUSD, 0) @@ -2824,6 +3319,7 @@ export function detectSessionOutliers(projects: ProjectSummary[], excludedSessio // "tighter constraint" advice here. if (excludedSessionIds?.has(session.sessionId)) continue + if (fellBack) usedEstimatedCosts = true outliers.push({ project: project.project, sessionId: session.sessionId, @@ -2853,6 +3349,7 @@ export function detectSessionOutliers(projects: ProjectSummary[], excludedSessio explanation: `Sessions costing more than ${SESSION_OUTLIER_MULTIPLIER}x their peer-session average in the same project: ${list}${extra}. These usually come from broad prompts, runaway loops, or context-heavy work that should be split into smaller sessions.`, impact: outliers.length >= 3 || totalExcessCost >= 10 ? 'high' : 'medium', tokensSaved, + ...(usedEstimatedCosts ? { basis: 'estimated' as const } : {}), fix: { type: 'paste', destination: 'session-opener', @@ -2866,7 +3363,7 @@ function findYoungProjectFirstSessionIds(projects: ProjectSummary[]): Set() for (const project of projects) { - const costed = project.sessions.filter(s => s.totalCostUSD > 0) + const costed = project.sessions.filter(s => isOptimizeSession(s) && s.totalCostUSD > 0) if (costed.length >= YOUNG_PROJECT_SESSION_LIMIT) continue let firstSession: ProjectSummary['sessions'][number] | null = null @@ -2977,7 +3474,7 @@ export function computeInputCostRate(projects: ProjectSummary[]): number { type CacheEntry = { data: OptimizeResult; ts: number } const resultCache = new Map() -export function cacheKey(projects: ProjectSummary[], dateRange: DateRange | undefined): string { +export function cacheKey(projects: ProjectSummary[], dateRange: DateRange | undefined, provider?: string): string { const dr = dateRange ? `${dateRange.start.getTime()}-${dateRange.end.getTime()}` : 'all' // Fingerprint enough of the dataset that two materially different inputs // cannot collide onto one cached OptimizeResult. Project count + api-call @@ -2985,82 +3482,110 @@ export function cacheKey(projects: ProjectSummary[], dateRange: DateRange | unde // stale findings when cost/tokens moved (e.g. a re-price) while call count // held - reachable in the long-lived menubar process within the 60s TTL. // Cost is scaled to whole micro-dollars so float jitter cannot thrash the key. - let calls = 0, cost = 0, savings = 0, proxied = 0 + let calls = 0, cost = 0, savings = 0, proxied = 0, sessions = 0, sidechains = 0 + const sidechainIdentities: string[] = [] for (const p of projects) { calls += p.totalApiCalls cost += p.totalCostUSD savings += p.totalSavingsUSD proxied += p.totalProxiedCostUSD + sessions += p.sessions.length + for (const session of p.sessions) { + if (session.isSidechain !== true) continue + sidechains++ + sidechainIdentities.push(`${p.projectPath}\0${session.sessionId}`) + } } + const sidechainDigest = createHash('sha256') + .update(sidechainIdentities.sort().join('\0')) + .digest('base64url') // Costs scaled to whole micro-dollars so float jitter cannot thrash the key. - const fingerprint = `${projects.length}:${calls}:${Math.round(cost * 1e6)}:${Math.round(savings * 1e6)}:${Math.round(proxied * 1e6)}` - return `${dr}:${fingerprint}` + const fingerprint = `${projects.length}:${sessions}:${sidechains}:${sidechainDigest}:${calls}:${Math.round(cost * 1e6)}:${Math.round(savings * 1e6)}:${Math.round(proxied * 1e6)}` + // The provider decides whether the Claude session scan runs at all, so two + // filters that happen to share a project fingerprint must not share a result. + return `${provider ?? 'all'}:${dr}:${fingerprint}` } export async function scanAndDetect( projects: ProjectSummary[], dateRange?: DateRange, + provider?: string, ): Promise { if (projects.length === 0) { return { findings: [], costRate: 0, healthScore: 100, healthGrade: 'A', modelRecommendations: [] } } - const key = cacheKey(projects, dateRange) + const key = cacheKey(projects, dateRange, provider) const cached = resultCache.get(key) if (cached && Date.now() - cached.ts < RESULT_CACHE_TTL_MS) return cached.data const costRate = computeInputCostRate(projects) - const { toolCalls, projectCwds, apiCalls, userMessages } = await scanSessions(dateRange) + const behavioralProjects = userStartedProjects(projects) + const scanCoversClaude = providerCoversClaude(provider) + const { toolCalls, projectCwds, apiCalls, userMessages, openers } = await scanSessions(dateRange, provider) const mcpCoverage = aggregateMcpCoverage(projects) const findings: WasteFinding[] = [] // Priority order for the per-session findings: low-worth → context-bloat → // outliers. Each later detector excludes sessions already named by an // earlier one so a single session is not listed in three findings. - const lowWorthSessionIds = new Set(findLowWorthCandidates(projects).map(c => c.sessionId)) + const lowWorthSessionIds = new Set(findLowWorthCandidates(behavioralProjects).map(c => c.sessionId)) const contextBloatVisibleIds = new Set( - findContextBloatCandidates(projects) + findContextBloatCandidates(behavioralProjects) .filter(c => !lowWorthSessionIds.has(c.sessionId)) .map(c => c.sessionId), ) - const firstSessionIds = findYoungProjectFirstSessionIds(projects) + const firstSessionIds = findYoungProjectFirstSessionIds(behavioralProjects) const outlierExclusions = new Set([...lowWorthSessionIds, ...contextBloatVisibleIds, ...firstSessionIds]) + // Detectors fed by the session scan or by `~/.claude` config only mean + // anything when the run covers Claude. Under a different `--provider` they + // must be skipped rather than handed an empty scan: emptiness reads as + // "never invoked", so every skill, agent and command would be reported as + // unused when it was simply not measured. + const claudeOnly = (detect: () => WasteFinding | null): (() => WasteFinding | null) => + scanCoversClaude ? detect : () => null const syncDetectors: Array<() => WasteFinding | null> = [ - () => detectCacheBloat(apiCalls, projects, dateRange), - () => detectLowReadEditRatio(toolCalls), - () => detectJunkReads(toolCalls, dateRange), - () => detectDuplicateReads(toolCalls, dateRange), - () => detectUnusedMcp(toolCalls, projects, projectCwds, mcpCoverage), - () => detectMcpToolCoverage(projects, mcpCoverage), + claudeOnly(() => detectCacheBloat(apiCalls, projects, dateRange)), + claudeOnly(() => detectLowReadEditRatio(toolCalls)), + claudeOnly(() => detectJunkReads(toolCalls, dateRange)), + claudeOnly(() => detectDuplicateReads(toolCalls, dateRange)), + claudeOnly(() => detectUnusedMcp(toolCalls, projects, projectCwds, mcpCoverage)), + () => detectMcpToolCoverage(projects, mcpCoverage, localMcpServerNames(projectCwds)), () => detectMcpProfileAdvisor(projects, mcpCoverage), // mcp-deferral-gaps family (#614): detection only, no apply plans yet. - () => detectMcpDeferralOff(toolCalls, projects, projectCwds, apiCalls), - () => detectMcpAlwaysLoadHygiene(projects, projectCwds, apiCalls, mcpCoverage), - () => detectMcpDeferThreshold(projects, projectCwds), - () => detectCapabilityReliability(projects), - () => detectLowWorthSessions(projects), - () => detectContextBloat(projects, lowWorthSessionIds), - () => detectSessionOutliers(projects, outlierExclusions), - () => detectBloatedClaudeMd(projectCwds), - () => detectBashBloat(), + claudeOnly(() => detectMcpDeferralOff(toolCalls, projects, projectCwds, apiCalls)), + claudeOnly(() => detectMcpAlwaysLoadHygiene(projects, projectCwds, apiCalls, mcpCoverage)), + claudeOnly(() => detectMcpDeferThreshold(projects, projectCwds)), + () => detectCapabilityReliability(behavioralProjects), + () => detectLowWorthSessions(behavioralProjects), + () => detectContextBloat(behavioralProjects, lowWorthSessionIds), + () => detectSessionOutliers(behavioralProjects, outlierExclusions), + claudeOnly(() => detectBloatedClaudeMd(projectCwds)), + claudeOnly(() => detectBashBloat()), + claudeOnly(() => detectRecurringContext(openers)), ] for (const detect of syncDetectors) { const finding = detect() if (finding) findings.push(finding) } - const ghostResults = await Promise.all([ - detectGhostAgents(toolCalls), - detectGhostSkills(toolCalls), - detectGhostCommands(userMessages), - ]) + const ghostResults = scanCoversClaude + ? await Promise.all([ + detectGhostAgents(toolCalls), + detectGhostSkills(toolCalls), + detectGhostCommands(userMessages), + ]) + : [] for (const f of ghostResults) if (f) findings.push(f) + // Urgency first, then class: every surface lists the apply-able fixes + // before the habit nudges, and orders by urgency inside each group. findings.sort((a, b) => urgencyScore(b) - urgencyScore(a)) + findings.sort((a, b) => CLASS_ORDER[findingClass(a)] - CLASS_ORDER[findingClass(b)]) const { score, grade } = computeHealth(findings) const modelRecommendations: ModelDefaultRecommendation[] = [] - for (const project of projects) { + for (const project of behavioralProjects) { const rec = recommendModelDefault(project, { now: dateRange?.end }) if (rec) modelRecommendations.push(rec) } @@ -3117,6 +3642,7 @@ function renderActionHeader(action: WasteAction): string { case 'session-opener': return fillTo('One-time session opener (do NOT add to CLAUDE.md)') case 'prompt': return fillTo('Ask Claude in the current session') case 'shell-config': return fillTo('Add to your shell config') + case 'manual': return fillTo('Manual action') default: return fillTo('Suggested action') } } @@ -3140,7 +3666,7 @@ function renderFinding(n: number, f: WasteFinding, costRate: number): string[] { lines.push('') lines.push(wrap(f.explanation, PANEL_WIDTH - 4, ' ')) lines.push('') - lines.push(chalk.hex(GOLD)(` Potential savings: ${savings}`)) + lines.push(chalk.hex(GOLD)(` Potential savings: ${savings}`) + chalk.dim(` ${findingBasis(f)}`)) lines.push('') // Destination header — issue #277. Tells the user where each suggestion @@ -3183,7 +3709,26 @@ function renderWorkflowSection(reworkedFiles: ReworkedFile[], coachingNotes: str return lines } -function renderOptimize( +const APPLIED_FIX_COLORS: Record = { + worked: GREEN, + partial: GOLD, + 'no-effect': RED, + pending: DIM, +} + +// Closes the loop after --apply: every still-applied fix gets its measured +// verdict back here, on every run. +function renderAppliedFixes(appliedFixes: AppliedFix[]): string[] { + if (appliedFixes.length === 0) return [] + const lines = [chalk.bold.hex(ORANGE)(' Applied fixes'), ''] + for (const fix of appliedFixes) { + lines.push(chalk.hex(APPLIED_FIX_COLORS[fix.verdict])(` ${appliedFixGlyph(fix)} ${formatAppliedFix(fix)}`)) + } + lines.push('') + return lines +} + +export function renderOptimize( findings: WasteFinding[], costRate: number, periodLabel: string, @@ -3197,6 +3742,7 @@ function renderOptimize( appliedHeader?: string, previouslyApplied?: Record, modelRecommendations?: ModelDefaultRecommendation[], + appliedFixes: AppliedFix[] = [], ): string { const lines: string[] = [] lines.push('') @@ -3204,12 +3750,16 @@ function renderOptimize( lines.push(chalk.hex(DIM)(' ' + SEP.repeat(PANEL_WIDTH))) const issueSuffix = findings.length > 0 ? `, ${findings.length} issue${findings.length > 1 ? 's' : ''}` : '' + const measured = findings.filter(f => findingBasis(f) === 'measured').length lines.push(' ' + [ - `${sessionCount} sessions`, + `${sessionCount} session${sessionCount === 1 ? '' : 's'}`, `${callCount.toLocaleString()} calls`, chalk.hex(GOLD)(formatCost(periodCost)), `Health: ${chalk.bold.hex(GRADE_COLORS[healthGrade])(healthGrade)}${chalk.dim(` (${healthScore}/100${issueSuffix})`)}`, ].join(chalk.hex(DIM)(' '))) + if (findings.length > 0) { + lines.push(chalk.dim(` ${measured} measured · ${findings.length - measured} estimated`)) + } if (appliedHeader) lines.push(' ' + chalk.hex(GREEN)(appliedHeader)) lines.push('') @@ -3220,6 +3770,7 @@ function renderOptimize( lines.push(chalk.dim(' token waste: junk directory reads, duplicate file reads, unused')) lines.push(chalk.dim(' agents/skills/MCP servers, bloated CLAUDE.md, and more.')) lines.push('') + lines.push(...renderAppliedFixes(appliedFixes)) lines.push(...renderWorkflowSection(reworkedFiles, coachingNotes)) return lines.join('\n') } @@ -3229,21 +3780,33 @@ function renderOptimize( const pctRaw = periodCost > 0 ? (totalCost / periodCost) * 100 : 0 const pct = pctRaw >= 1 ? pctRaw.toFixed(0) : pctRaw.toFixed(1) + const totals = classTotals(findings, costRate) const costText = costRate > 0 ? ` (~${formatCost(totalCost)}, ~${pct}% of spend)` : '' - lines.push(chalk.hex(GREEN)(` Potential savings: ~${formatTokens(totalTokens)} tokens${costText}`)) + // The headline is the whole board; name the apply-able slice separately so + // it never reads as "what CodeBurn can fix for you". + const applyable = costRate > 0 && totals.fix.count > 0 ? ` — apply-able: ~${formatCost(totals.fix.savingsUSD)}` : '' + lines.push(chalk.hex(GREEN)(` Potential savings: ~${formatTokens(totalTokens)} tokens${costText}${applyable}`)) lines.push('') - for (let i = 0; i < findings.length; i++) { - const f = findings[i]! - const appliedOn = previouslyApplied?.[f.id] - const shown = appliedOn ? { ...f, title: `${f.title} (previously applied ${appliedOn}, re-flagged)` } : f - lines.push(...renderFinding(i + 1, shown, costRate)) + // One block per class, in fix -> nudge -> keep order; numbering runs + // continuously across the blocks so `--only` picks stay unambiguous. + let n = 0 + for (const cls of ['fix', 'nudge', 'keep'] as const) { + const group = findings.filter(f => findingClass(f) === cls) + if (group.length === 0) continue + lines.push(chalk.bold.hex(ORANGE)(` ${classHeaderLine(cls, totals[cls], costRate)}`)) + lines.push('') + for (const f of group) { + const appliedOn = previouslyApplied?.[f.id] + const shown = appliedOn ? { ...f, title: `${f.title} (previously applied ${appliedOn}, re-flagged)` } : f + lines.push(...renderFinding(++n, shown, costRate)) + } } lines.push(chalk.hex(DIM)(' ' + SEP.repeat(PANEL_WIDTH))) - lines.push(chalk.dim(' Estimates only.')) lines.push('') + lines.push(...renderAppliedFixes(appliedFixes)) lines.push(...renderWorkflowSection(reworkedFiles, coachingNotes)) if (modelRecommendations && modelRecommendations.length > 0) { @@ -3281,7 +3844,7 @@ export async function runOptimize( projects: ProjectSummary[], periodLabel: string, dateRange?: DateRange, - opts: { format?: 'text' | 'json'; appliedHeader?: string; previouslyApplied?: Record } = {}, + opts: { format?: 'text' | 'json'; appliedHeader?: string; previouslyApplied?: Record; appliedFixes?: AppliedFix[]; provider?: string } = {}, ): Promise { const format = opts.format ?? 'text' if (projects.length === 0 && format === 'text') { @@ -3293,19 +3856,19 @@ export async function runOptimize( process.stderr.write(chalk.dim(' Analyzing your sessions...\n')) } - const result = await scanAndDetect(projects, dateRange) + const result = await scanAndDetect(projects, dateRange, opts.provider) const { findings, costRate, healthScore, healthGrade } = result - const sessions = projects.flatMap(p => p.sessions) + const sessionCount = optimizeSessionCount(projects) const periodCost = projects.reduce((s, p) => s + p.totalCostUSD, 0) const callCount = projects.reduce((s, p) => s + p.totalApiCalls, 0) if (format === 'json') { - console.log(JSON.stringify(buildOptimizeJsonReport(projects, periodLabel, result, dateRange), null, 2)) + console.log(JSON.stringify(buildOptimizeJsonReport(projects, periodLabel, result, dateRange, opts.appliedFixes), null, 2)) return } const { topReworkedFiles, coachingNotes } = buildWorkflowReport(projects) - const output = renderOptimize(findings, costRate, periodLabel, periodCost, sessions.length, callCount, healthScore, healthGrade, topReworkedFiles, coachingNotes, opts.appliedHeader, opts.previouslyApplied, result.modelRecommendations) + const output = renderOptimize(findings, costRate, periodLabel, periodCost, sessionCount, callCount, healthScore, healthGrade, topReworkedFiles, coachingNotes, opts.appliedHeader, opts.previouslyApplied, result.modelRecommendations, opts.appliedFixes) console.log(output) } @@ -3314,8 +3877,8 @@ export function buildOptimizeJsonReport( periodLabel: string, result: OptimizeResult, dateRange?: DateRange, + appliedFixes: AppliedFix[] = [], ): OptimizeJsonReport { - const sessions = projects.flatMap(p => p.sessions) const periodCostUSD = projects.reduce((s, p) => s + p.totalCostUSD, 0) const calls = projects.reduce((s, p) => s + p.totalApiCalls, 0) const potentialSavingsTokens = result.findings.reduce((s, f) => s + f.tokensSaved, 0) @@ -3335,12 +3898,16 @@ export function buildOptimizeJsonReport( healthGrade: result.healthGrade, findingCount: result.findings.length, periodCostUSD, - sessions: sessions.length, + sessions: optimizeSessionCount(projects), calls, potentialSavingsTokens, potentialSavingsCostUSD, potentialSavingsPercent, costRateUSD: result.costRate, + measuredSavingsUSD: result.findings + .filter(f => findingBasis(f) === 'measured') + .reduce((s, f) => s + f.tokensSaved * result.costRate, 0), + byClass: classTotals(result.findings, result.costRate), }, findings: result.findings.map(f => ({ id: f.id, @@ -3350,9 +3917,21 @@ export function buildOptimizeJsonReport( trend: f.trend ?? null, tokensSaved: f.tokensSaved, estimatedSavingsUSD: f.tokensSaved * result.costRate, + class: findingClass(f), + basis: findingBasis(f), fix: f.fix, })), ...buildWorkflowReport(projects), modelRecommendations: result.modelRecommendations, + appliedFixes: appliedFixes.map(f => ({ + id: f.id, + kind: f.kind, + findingId: f.findingId, + appliedAt: f.appliedAt, + verdict: f.verdict, + estimatedTokens: f.estimatedTokens, + realizedTokens: f.realizedTokens, + undoCommand: f.undoCommand, + })), } } diff --git a/src/parser.ts b/src/parser.ts index 65ec4987..582e9a71 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -559,7 +559,7 @@ function extractObjectFields( return captured } -const LARGE_ROOT_FIELDS = ['type', 'timestamp', 'sessionId', 'cwd', 'gitBranch', 'attachment', 'message'] as const +const LARGE_ROOT_FIELDS = ['type', 'timestamp', 'sessionId', 'cwd', 'gitBranch', 'attachment', 'message', 'isSidechain', 'promptSource'] as const const LARGE_ASSISTANT_MESSAGE_FIELDS = ['model', 'usage', 'id', 'content'] as const function parseLargeJsonl(line: string | Buffer): JournalEntry | null { @@ -573,14 +573,19 @@ function parseLargeJsonl(line: string | Buffer): JournalEntry | null { if (!type) return null const entry: JournalEntry = { type } + if (root['isSidechain']?.kind === 'scalar' && source.slice(root['isSidechain'].start, root['isSidechain'].end) === 'true') { + entry.isSidechain = true + } const timestamp = readJsonString(source, root['timestamp']) const sessionId = readJsonString(source, root['sessionId']) const cwd = readJsonString(source, root['cwd']) const gitBranch = readJsonString(source, root['gitBranch']) + const promptSource = readJsonString(source, root['promptSource']) if (timestamp !== undefined) entry.timestamp = timestamp if (sessionId !== undefined) entry.sessionId = sessionId if (cwd !== undefined) entry.cwd = cwd if (gitBranch !== undefined) entry.gitBranch = gitBranch + if (promptSource !== undefined) entry.promptSource = promptSource const addedNames = extractLargeAddedNames(source, root['attachment']) if (addedNames.length > 0) { ;(entry as Record)['attachment'] = { type: 'deferred_tools_delta', addedNames } @@ -2361,6 +2366,7 @@ async function scanProjectDirs( // on a resumed session) and derive the agent id from the `agent-` // filename. A sidechain whose parent id was never captured stays standalone. if (cachedFile.isSidechain) { + session.isSidechain = true if (cachedFile.parentSessionId) session.parentSessionId = cachedFile.parentSessionId session.agentId = sessionId.startsWith('agent-') ? sessionId.slice('agent-'.length) : sessionId } @@ -3429,13 +3435,12 @@ async function parseProviderSources( } } - // 90-day age-out for durable providers: remove entries whose newest call is - // older than 90 days so the cache doesn't grow unboundedly. One scoped - // exemption: a source that declared retainWhilePresent and is still - // discovered IS the durable record itself (copilot's session-store.db) — - // pruning it would drop crash-only rows the file still holds and force a - // full re-read on the next refresh. Everything else — orphans, and ordinary - // still-present journal files — ages out on the pre-existing schedule. + // 90-day age-out for durable providers: prune only orphaned entries whose + // newest call is older than 90 days. Still-discovered sources remain live + // regardless of age and keep their persisted fingerprint for reuse (#992). + // retainWhilePresent (copilot's session-store.db, the durable record itself) + // states the same intent explicitly for a still-discovered source; under the + // orphan-only rule it is currently redundant rather than load-bearing. if (!readOnly && provider.durableSources) { const retainPaths = new Set(sources.filter(s => s.retainWhilePresent).map(s => s.path)) const cutoffMs = Date.now() - 90 * 24 * 60 * 60 * 1000 @@ -3446,7 +3451,7 @@ async function parseProviderSources( .map(c => new Date(c.timestamp).getTime()) .filter(ts => !isNaN(ts)) .reduce((max, ts) => Math.max(max, ts), 0) - if (newestTs > 0 && newestTs < cutoffMs) { + if (!allDiscoveredFiles.has(cachedPath) && newestTs > 0 && newestTs < cutoffMs) { delete section.files[cachedPath] markCacheDirty(diskCache, providerName, cachedPath) } @@ -4091,6 +4096,7 @@ function carryLinkageFields(rebuilt: SessionSummary, original: SessionSummary): if (original.prLinks?.length) rebuilt.prLinks = original.prLinks if (original.prAttributionSource) rebuilt.prAttributionSource = original.prAttributionSource if (original.workingDirectory) rebuilt.workingDirectory = original.workingDirectory + if (original.isSidechain) rebuilt.isSidechain = true // prRefsAtRangeStart is NOT copied here: a narrower slice needs it recomputed at // the new boundary (see recomputeRangeStartPrRefs), not the wide range's value. if (original.parentSessionId) rebuilt.parentSessionId = original.parentSessionId diff --git a/src/providers/cursor.ts b/src/providers/cursor.ts index 290f615a..b38aee54 100644 --- a/src/providers/cursor.ts +++ b/src/providers/cursor.ts @@ -5,7 +5,16 @@ import { homedir } from 'os' import { calculateCost } from '../models.js' import { extractBashCommands } from '../bash-utils.js' import { readCachedResults, writeCachedResults } from '../cursor-cache.js' -import { isSqliteAvailable, isSqliteBusyError, getSqliteLoadError, openDatabase, blobToText, type SqliteDatabase } from '../sqlite.js' +import { + isSqliteAvailable, + isSqliteBusyError, + getSqliteLoadError, + openDatabase, + blobToText, + isSqliteReadonlyError, + warnSqliteReadonlyOnce, + type SqliteDatabase, +} from '../sqlite.js' import { estimateTokensFromChars } from '../token-estimate.js' import type { DateRange } from '../types.js' import type { ProbeRoot, Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js' @@ -188,7 +197,8 @@ function loadWorkspaceMap(workspaceStorageDir: string): WorkspaceMapping { let db: SqliteDatabase try { db = openDatabase(wsDbPath) - } catch { + } catch (err) { + if (isSqliteReadonlyError(err)) warnSqliteReadonlyOnce(wsDbPath) continue } try { diff --git a/src/providers/dsh.ts b/src/providers/dsh.ts new file mode 100644 index 00000000..d82664db --- /dev/null +++ b/src/providers/dsh.ts @@ -0,0 +1,591 @@ +import { open, readdir, readFile, stat } from 'fs/promises' +import { join } from 'path' +import { homedir } from 'os' +import zlib from 'zlib' + +import { MAX_SESSION_FILE_BYTES, readSessionFile } from '../fs-utils.js' +import { calculateCost, getShortModelName } from '../models.js' +import { extractBashCommands } from '../bash-utils.js' +import type { ProbeRoot, Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js' + +// DeepSeek Harness (dsh) stores one session per directory: +// /sessions//session-/session.jsonl.zstd +// (or an uncompressed session.jsonl when compression=none). The .zstd file is +// a concatenation of INDEPENDENT zstd frames — one per appended event batch — +// so node:zlib's one-shot zstdDecompressSync (which decodes a single frame) +// must be driven frame-by-frame behind a structural frame-boundary scan. The +// scan below is a port of scanZstdFrames from the official +// @deepseek-ai/dsh-session-persistence-jsonl package, which is third-party code +// under its own license - see THIRD_PARTY_NOTICES.md. + +// zstd landed in node:zlib in 22.15 / 23.8; the package floor is lower, so the +// provider degrades with a notice instead of assuming the export exists. +const zstdDecompress = (zlib as { zstdDecompressSync?: (buf: Buffer, opts?: { maxOutputLength?: number }) => Buffer }).zstdDecompressSync + +const ZSTD_MAGIC = 0xfd2fb528 + +// SESSION_FORMAT_VERSION in @deepseek-ai/dsh-session. DSH refuses to load a log +// stamped with any other version, and a bump means an event's meaning changed, +// so a foreign version is skipped rather than read with today's assumptions. +// A zstd frame's declared content size is attacker-controlled, so a few KB of +// crafted input can expand to gigabytes. Every decode is capped: no single +// frame may exceed this, and no file may decode to more than it would have been +// allowed to occupy uncompressed (MAX_SESSION_FILE_BYTES). Overflow throws, and +// the caller skips the WHOLE file rather than counting the frames it got to. +const MAX_FRAME_DECODED_BYTES = 64 * 1024 * 1024 + +const SESSION_FORMAT_VERSION = 0 + +const MIN_REASONABLE_TIMESTAMP_MS = 1_000_000_000_000 + +// Discovery walks every session, so a per-file notice would repeat once per +// log; each distinct message is worth saying exactly once. +const noticed = new Set() + +function notice(message: string): void { + if (noticed.has(message)) return + noticed.add(message) + process.stderr.write(message) +} + +type ZstdFrame = { start: number; end: number } + +// Locate complete frames without decompressing their blocks. An EOF inside the +// final frame (a torn append from a crashed writer) returns its start so the +// caller can ignore the tail; invalid complete structure rejects. +function scanZstdFrames(buffer: Buffer, maxFrames = Number.POSITIVE_INFINITY): { frames: ZstdFrame[]; tornStart?: number } { + const frames: ZstdFrame[] = [] + let offset = 0 + while (offset < buffer.length) { + const start = offset + if (buffer.length - offset < 4) return { frames, tornStart: start } + if (buffer.readUInt32LE(offset) !== ZSTD_MAGIC) { + throw new Error(`invalid zstd frame magic at byte ${offset}`) + } + offset += 4 + if (offset === buffer.length) return { frames, tornStart: start } + const descriptor = buffer.readUInt8(offset)! + offset += 1 + if ((descriptor & 24) !== 0) throw new Error(`reserved frame-header bit at byte ${offset - 1}`) + const contentSizeFlag = descriptor >>> 6 + const singleSegment = (descriptor & 32) !== 0 + const checksum = (descriptor & 4) !== 0 + const dictionaryFlag = descriptor & 3 + const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag + const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag + const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes + if (buffer.length - offset < remainingHeaderBytes) return { frames, tornStart: start } + offset += remainingHeaderBytes + for (;;) { + if (buffer.length - offset < 3) return { frames, tornStart: start } + const blockHeader = buffer.readUIntLE(offset, 3) + offset += 3 + const lastBlock = (blockHeader & 1) !== 0 + const blockType = (blockHeader >>> 1) & 3 + const blockSize = blockHeader >>> 3 + if (blockType === 3) throw new Error(`reserved block type at byte ${offset - 3}`) + const payloadBytes = blockType === 1 ? 1 : blockSize + if (buffer.length - offset < payloadBytes) return { frames, tornStart: start } + offset += payloadBytes + if (lastBlock) break + } + if (checksum) { + if (buffer.length - offset < 4) return { frames, tornStart: start } + offset += 4 + } + frames.push({ start, end: offset }) + if (frames.length === maxFrames) return { frames } + } + return { frames } +} + +type DshUsage = { + inputTokens?: number + outputTokens?: number + cacheReadTokens?: number + cacheWriteTokens?: number + reasoningTokens?: number +} + +type DshEvent = { + type?: string + seq?: number + time?: number + // Session header fields live at the top level of the first event. + version?: number + id?: string + cwd?: string + createdAt?: number + parentSession?: string + seedLength?: number + data?: { + turn?: number + step?: number + content?: Array<{ type?: string; text?: string }> + // `user/message` carries the message author: a real prompt is + // `{ kind: 'user' }`, agent-injected context is `{ kind: 'plugin' }`. + source?: { kind?: string } + header?: { config?: { model?: string; provider?: string } } + message?: { source?: { kind?: string; model?: string; provider?: string } } + chunk?: { type?: string; usage?: DshUsage } + usage?: DshUsage + name?: string + arguments?: string + } +} + +type StepBucket = { + usage: DshUsage + // A usage report from assistant/message is the final value for its + // (turn, step) and replaces an earlier assistant/chunk sample (the two are + // adjacent reports of the same API call, per dsh-token-meter's usage + // projection). Time follows the winning report. + final: boolean + time?: number + // Model that produced this step: the reporting assistant/message's own + // `message.source` when it names one, else the most recent request/header + // config (a header can change the model mid-turn between steps). + model: string + tools: string[] + skills: string[] + bashCommands: string[] +} + +const toolNameMap: Record = { + bash: 'Bash', + pwsh: 'Bash', + read: 'Read', + write: 'Write', + edit: 'Edit', + str_replace_editor: 'Edit', + glob: 'Glob', + grep: 'Grep', + todo_write: 'TodoWrite', + todo: 'TodoWrite', + web_search: 'WebSearch', + skill: 'Skill', + agent: 'Agent', + ask_user_question: 'AskUserQuestion', +} + +function mapToolName(raw: string): string { + return toolNameMap[raw] ?? raw +} + +// Usage fields are whatever the JSON held. A string or array would flow +// straight into the global token totals and the persisted cache, where +// `0 + [1, 2]` silently becomes "01,2". Same semantics as copilot.ts. +function numberOrZero(raw: unknown): number { + return typeof raw === 'number' && Number.isFinite(raw) && raw > 0 ? raw : 0 +} + +// A log stamped with a version this parser was not written against is skipped +// whole: a bump means an event's meaning changed, so reading it with today's +// assumptions would report confident wrong numbers. +function isReadableVersion(header: DshEvent): boolean { + if (header.version === SESSION_FORMAT_VERSION) return true + // Keyed on the version, not the path: a DSH upgrade makes EVERY session + // unreadable at once, and one line per session log is noise, not a report. + notice(`codeburn: skipping DSH sessions written in session format version ${String(header.version)}; upgrade codeburn.\n`) + return false +} + +// DSH writes epoch milliseconds; promote a seconds-resolution value and reject +// what stays implausible, matching the guard cline-cli.ts uses on the hazard. +function isoTimestamp(value: number | undefined, fallback: string): string { + if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return fallback + const ms = value < MIN_REASONABLE_TIMESTAMP_MS ? value * 1000 : value + const date = new Date(ms) + if (Number.isNaN(date.getTime()) || date.getTime() < MIN_REASONABLE_TIMESTAMP_MS) return fallback + return date.toISOString() +} + +function getDshHome(override?: string): string { + // An empty-string DSH_HOME is treated as unset. + return override ?? (process.env['DSH_HOME'] || undefined) ?? join(homedir(), '.dsh') +} + +// DSH writes native-platform paths into the header (backslashes on Windows); +// split on both separators so discovery is correct on any host. +function projectFromCwd(cwd: string, fallback: string): string { + const segments = cwd.split(/[\\/]/).filter(Boolean) + return segments[segments.length - 1] ?? fallback +} + +// Decode every complete frame and yield its JSONL lines. A torn final frame is +// ignored; a structurally corrupt file, or one that decodes past `budget`, +// throws for the caller to report. Exported for the decode-budget test. +export function* readZstdLines( + buffer: Buffer, + maxFrames = Number.POSITIVE_INFINITY, + budget = MAX_SESSION_FILE_BYTES, +): Generator { + const { frames } = scanZstdFrames(buffer, maxFrames) + let remaining = budget + for (const frame of frames) { + if (remaining <= 0) throw new Error(`decodes past the ${budget}-byte cap`) + // node throws ERR_BUFFER_TOO_LARGE without allocating past the cap, so the + // per-frame limit doubles as the running budget for the frames after it. + const decoded = zstdDecompress!(buffer.subarray(frame.start, frame.end), { + maxOutputLength: Math.min(remaining, MAX_FRAME_DECODED_BYTES), + }) + remaining -= decoded.length + for (const line of decoded.toString('utf-8').split('\n')) { + if (line.trim()) yield line + } + } +} + +async function readEventLines(filePath: string): Promise { + if (filePath.endsWith('.zstd')) { + if (!zstdDecompress) { + notice('codeburn: DSH sessions need Node >= 22.15 (zstd support); skipping DSH usage.\n') + return null + } + let buffer: Buffer + try { + // The whole log is buffered to scan its frames, so it needs the same + // oversize guard readSessionFile applies to the uncompressed variant. + const size = (await stat(filePath)).size + if (size > MAX_SESSION_FILE_BYTES) { + notice(`codeburn: skipped oversize DSH session log ${filePath} (${size} bytes)\n`) + return null + } + buffer = await readFile(filePath) + } catch { + return null + } + try { + return [...readZstdLines(buffer)] + } catch (err) { + notice(`codeburn: skipped corrupt DSH session log ${filePath}: ${err instanceof Error ? err.message : err}\n`) + return null + } + } + const content = await readSessionFile(filePath) + if (content === null) return null + return content.split('\n').filter(l => l.trim()) +} + +// Cheap discovery probe: decompress ONLY the first frame (the session header +// batch) instead of the whole log. The header frame is tiny, so a bounded head +// read almost always contains it; fall back to a full read when it does not. +async function readSessionHeader(filePath: string): Promise { + const firstLine = async (): Promise => { + if (filePath.endsWith('.zstd')) { + if (!zstdDecompress) return null + let head: Buffer + try { + const handle = await open(filePath, 'r') + try { + const size = (await handle.stat()).size + const length = Math.min(size, 256 * 1024) + head = Buffer.alloc(length) + await handle.read(head, 0, length, 0) + } finally { + await handle.close() + } + } catch { + return null + } + let { frames } = scanZstdFrames(head, 1) + if (frames.length === 0) { + // Head read did not cover one full frame; take the whole file. A fork's + // first batch carries the whole inherited seed, so this is reachable on + // a real log and needs the same oversize guard as the parse read. + try { + if ((await stat(filePath)).size > MAX_SESSION_FILE_BYTES) return null + const full = await readFile(filePath) + frames = scanZstdFrames(full, 1).frames + if (frames.length === 0) return null + head = full + } catch { + return null + } + } + const text = zstdDecompress(head.subarray(frames[0]!.start, frames[0]!.end), { + maxOutputLength: MAX_FRAME_DECODED_BYTES, + }).toString('utf-8') + return text.split('\n').find(l => l.trim()) ?? null + } + const content = await readSessionFile(filePath) + return content?.split('\n').find(l => l.trim()) ?? null + } + + try { + const line = await firstLine() + if (!line) return null + const event = JSON.parse(line) as DshEvent + if (event.type !== 'session') return null + return isReadableVersion(event) ? event : null + } catch { + return null + } +} + +async function discoverSessionsInDir(sessionsDir: string): Promise { + const sources: SessionSource[] = [] + + let projectDirs: string[] + try { + projectDirs = await readdir(sessionsDir) + } catch { + return sources + } + + for (const dirName of projectDirs) { + const dirPath = join(sessionsDir, dirName) + const dirStat = await stat(dirPath).catch(() => null) + if (!dirStat?.isDirectory()) continue + + let sessionDirs: string[] + try { + sessionDirs = await readdir(dirPath) + } catch { + continue + } + + for (const sessionDir of sessionDirs) { + const sessionPath = join(dirPath, sessionDir) + const sessionStat = await stat(sessionPath).catch(() => null) + if (!sessionStat?.isDirectory()) continue + + // Compressed log first; the uncompressed variant exists when + // compression=none. Never both for the same session. + let filePath: string | null = null + for (const name of ['session.jsonl.zstd', 'session.jsonl']) { + const candidate = join(sessionPath, name) + const fileStat = await stat(candidate).catch(() => null) + if (fileStat?.isFile()) { + filePath = candidate + break + } + } + if (!filePath) continue + + const header = await readSessionHeader(filePath) + if (!header) continue + + const cwd = typeof header.cwd === 'string' && header.cwd.trim() ? header.cwd : dirName + sources.push({ path: filePath, project: projectFromCwd(cwd, dirName), provider: 'dsh' }) + } + } + + return sources +} + +function parseToolArguments(raw: string | undefined): Record | null { + if (!raw) return null + try { + const parsed = JSON.parse(raw) as unknown + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record : null + } catch { + return null + } +} + +function createParser(source: SessionSource, seenKeys: Set): SessionParser { + return { + async *parse(): AsyncGenerator { + const lines = await readEventLines(source.path) + if (!lines) return + + let sessionId = '' + let cwd = '' + let model = 'unknown' + let currentTurn = 0 + let sessionStart = '' + // Events a forked session inherited from its parent. They are a verbatim + // copy of the parent's log, which codeburn parses as its own session, so + // counting them here would bill the same calls twice. + let seedLength = 0 + const userMessageByTurn = new Map() + const buckets = new Map() + + for (const line of lines) { + let event: DshEvent + try { + event = JSON.parse(line) as DshEvent + } catch { + continue + } + + if (event.type === 'session') { + if (!isReadableVersion(event)) return + sessionId = event.id ?? sessionId + cwd = event.cwd ?? cwd + sessionStart = isoTimestamp(event.createdAt, sessionStart) + if (typeof event.parentSession === 'string' && event.parentSession && typeof event.seedLength === 'number') { + seedLength = event.seedLength + } + continue + } + + if (typeof event.seq === 'number' && event.seq < seedLength) continue + + if (event.type === 'turn/start') { + currentTurn = event.data?.turn ?? currentTurn + continue + } + + if (event.type === 'request/header') { + // Emitted at most once per request; steps after the last header + // inherit its config as their model. + const headerModel = event.data?.header?.config?.model + if (typeof headerModel === 'string' && headerModel) model = headerModel + continue + } + + if (event.type === 'user/message') { + // Plugin-injected context (runtime snapshots, skill bodies, file-change + // notices) rides the same event type as a typed prompt; only the latter + // is a useful preview. + if (event.data?.source?.kind !== 'user') continue + if (userMessageByTurn.has(currentTurn)) continue + const texts = (event.data?.content ?? []) + .filter(c => c.type === 'text' && typeof c.text === 'string' && c.text) + .map(c => c.text!) + if (texts.length > 0) userMessageByTurn.set(currentTurn, texts.join(' ').slice(0, 500)) + continue + } + + if (event.type === 'tool/call') { + const turn = event.data?.turn ?? currentTurn + const step = event.data?.step ?? 0 + const rawName = event.data?.name + if (!rawName) continue + const key = `${turn}:${step}` + let bucket = buckets.get(key) + if (!bucket) { + bucket = { usage: {}, final: false, model, tools: [], skills: [], bashCommands: [] } + buckets.set(key, bucket) + } + bucket.tools.push(mapToolName(rawName)) + const args = parseToolArguments(event.data?.arguments) + if ((rawName === 'bash' || rawName === 'pwsh') && typeof args?.['command'] === 'string') { + bucket.bashCommands.push(...extractBashCommands(args['command'])) + } + if (rawName === 'skill' && typeof args?.['name'] === 'string') { + bucket.skills.push(args['name']) + } + continue + } + + let usage: DshUsage | undefined + let isFinal = false + // The model that actually served the call, when the message records it. + // request/header only describes the request codeburn is about to see. + let reportedModel = model + if (event.type === 'assistant/chunk' && event.data?.chunk?.type === 'usage') { + usage = event.data.chunk.usage + } else if (event.type === 'assistant/message' && event.data?.usage) { + usage = event.data.usage + isFinal = true + const messageModel = event.data.message?.source?.model + if (typeof messageModel === 'string' && messageModel) reportedModel = messageModel + } else { + continue + } + if (!usage) continue + + const turn = event.data?.turn ?? currentTurn + const step = event.data?.step ?? 0 + const key = `${turn}:${step}` + let bucket = buckets.get(key) + if (!bucket) { + bucket = { usage: {}, final: false, model, tools: [], skills: [], bashCommands: [] } + buckets.set(key, bucket) + } + // A final report replaces an earlier sample; a late sample never + // overwrites a final one. The model snapshot follows the winning + // report (a header can change the model mid-turn between steps). + if (isFinal || !bucket.final) { + bucket.usage = usage + bucket.final = isFinal + bucket.time = event.time + bucket.model = reportedModel + } + } + + const sortedKeys = [...buckets.keys()].sort((a, b) => { + const [ta, sa] = a.split(':').map(Number) + const [tb, sb] = b.split(':').map(Number) + return ta! - tb! || sa! - sb! + }) + + for (const key of sortedKeys) { + const bucket = buckets.get(key)! + const input = numberOrZero(bucket.usage.inputTokens) + const output = numberOrZero(bucket.usage.outputTokens) + const cacheRead = numberOrZero(bucket.usage.cacheReadTokens) + const cacheWrite = numberOrZero(bucket.usage.cacheWriteTokens) + const reasoning = numberOrZero(bucket.usage.reasoningTokens) + if (input + output + cacheRead + cacheWrite + reasoning === 0) continue + + const dedupKey = `dsh:${sessionId || source.path}:${key}` + if (seenKeys.has(dedupKey)) continue + seenKeys.add(dedupKey) + + // DSH bills reasoning tokens at the output rate (same as Gemini). + const costUSD = calculateCost(bucket.model, input, output + reasoning, cacheWrite, cacheRead, 0) + const [turn] = key.split(':').map(Number) + + yield { + provider: 'dsh', + model: bucket.model, + inputTokens: input, + outputTokens: output, + cacheCreationInputTokens: cacheWrite, + cacheReadInputTokens: cacheRead, + cachedInputTokens: cacheRead, + reasoningTokens: reasoning, + webSearchRequests: 0, + costUSD, + tools: [...new Set(bucket.tools)], + bashCommands: bucket.bashCommands, + skills: bucket.skills.length > 0 ? [...new Set(bucket.skills)] : undefined, + timestamp: isoTimestamp(bucket.time, sessionStart), + speed: 'standard', + deduplicationKey: dedupKey, + userMessage: userMessageByTurn.get(turn!) ?? '', + sessionId: sessionId || source.path, + project: cwd ? projectFromCwd(cwd, source.project) : source.project, + projectPath: cwd || undefined, + workingDirectory: cwd || undefined, + } + } + }, + } +} + +export function createDshProvider(dshHomeOverride?: string): Provider { + const dshHome = getDshHome(dshHomeOverride) + const sessionsDir = join(dshHome, 'sessions') + + return { + name: 'dsh', + displayName: 'DeepSeek Harness', + + modelDisplayName(model: string): string { + return getShortModelName(model) + }, + + toolDisplayName(rawTool: string): string { + return mapToolName(rawTool) + }, + + async probeRoots(): Promise { + return [{ path: sessionsDir, label: 'sessions' }] + }, + + async discoverSessions(): Promise { + return discoverSessionsInDir(sessionsDir) + }, + + createSessionParser(source: SessionSource, seenKeys: Set): SessionParser { + return createParser(source, seenKeys) + }, + } +} + +export const dsh = createDshProvider() diff --git a/src/providers/grok.ts b/src/providers/grok.ts index 1c292441..4724a8af 100644 --- a/src/providers/grok.ts +++ b/src/providers/grok.ts @@ -3,7 +3,7 @@ import { basename, dirname, join } from 'path' import { homedir } from 'os' import { readSessionFile } from '../fs-utils.js' -import { calculateCost, getShortModelName } from '../models.js' +import { calculateCost, getModelCosts, getShortModelName } from '../models.js' import { extractBashCommands } from '../bash-utils.js' import type { ProbeRoot, Provider, SessionSource, SessionParser, ParsedProviderCall } from './types.js' @@ -12,14 +12,15 @@ import type { ProbeRoot, Provider, SessionSource, SessionParser, ParsedProviderC // or ~/.grok. Each session dir holds summary.json, signals.json, and the ACP // log updates.jsonl. // -// Grok does NOT record billable input/output tokens. signals.json carries -// `contextTokensUsed` (current context fill) and updates.jsonl carries a running -// `_meta.totalTokens` per streamed chunk; there is no per-call input/output -// split. We reconstruct an ESTIMATE from the per-turn totalTokens curve. Agentic -// turns re-send the growing context every call, and that re-sent context is -// cached server-side, so we bill the unique context (summed per compaction segment) as fresh input, -// the re-sent remainder as cache reads, and the per-turn growth as output. Cost -// is flagged estimated; grok-build is priced via its grok-build-0.1 alias. +// Newer Grok CLI versions append a `turn_completed` update with provider-recorded +// input/output/cache/reasoning usage. That record is authoritative: cached reads +// are part of input, and reasoning is a subset of output. Cache creation is +// treated as another input subset by analogy because the record exposes no +// separate fresh-input field; any per-record violation is clamped before pricing. +// Older sessions only carry +// `signals.json.contextTokensUsed` and the running `_meta.totalTokens` curve; for +// those we retain the old compaction-aware estimate and mark its cost estimated. +// `costUsdTicks` is deliberately ignored because its scale is not documented. const toolNameMap: Record = { bash: 'Bash', @@ -80,28 +81,136 @@ function safeDecode(name: string): string { } } -// updates.jsonl is one ACP JSON-RPC notification per line; streamed chunks carry -// params._meta.{totalTokens, promptId}. totalTokens is the running context size, -// so grouping by promptId (one per turn) gives each turn's first/last value. +// updates.jsonl is one ACP JSON-RPC notification per line. Streamed chunks carry +// params._meta.{totalTokens, promptId}; completed turns carry snake_case +// params.update.{prompt_id, usage}. type GrokUpdate = { params?: { - _meta?: { totalTokens?: number; promptId?: string } - update?: { sessionUpdate?: string; title?: string; rawInput?: { command?: unknown; subagent_type?: unknown } } + _meta?: { totalTokens?: unknown; promptId?: unknown } + update?: { + sessionUpdate?: unknown + prompt_id?: unknown + usage?: unknown + title?: unknown + rawInput?: { command?: unknown; subagent_type?: unknown } + } } } -// Single pass over updates.jsonl: per-turn totalTokens for the cost estimate, -// plus the real tool calls (each tool_call's title -> a tool, and -// run_terminal_command's rawInput.command -> shell commands). -function parseUpdates(updates: string): { +type GrokUsageValues = { + inputTokens: number + outputTokens: number + cacheReadTokens: number + cacheCreationTokens: number + reasoningTokens: number +} + +type GrokAuthoritativeUsage = GrokUsageValues & { + modelUsage: Map +} + +type GrokTokenTotals = { input: number cacheRead: number output: number + cacheCreation: number + reasoning: number +} + +function emptyTokenTotals(): GrokTokenTotals { + return { input: 0, cacheRead: 0, output: 0, cacheCreation: 0, reasoning: 0 } +} + +const authoritativeTokenFields = [ + 'inputTokens', + 'outputTokens', + 'cachedReadTokens', + 'cacheCreationTokens', + 'reasoningTokens', +] as const + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +// JSONL is third-party input. Keep the check local to this provider so bad +// usage fields become absent rather than leaking NaN, negative tokens, or a +// throwing arithmetic operation into the session aggregate. +function finiteNonNegative(value: unknown): number | undefined { + if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return undefined + // Token counts this large are not meaningful in a session and can overflow + // when summed or priced. Capping preserves the non-negative finite invariant. + return Math.min(value, Number.MAX_SAFE_INTEGER) +} + +function addTokenCounts(left: number, right: number): number { + return Math.min(Number.MAX_SAFE_INTEGER, left + right) +} + +function readUsageNumber(usage: Record, field: string): number | undefined { + return finiteNonNegative(usage[field]) +} + +function readModelUsage(usage: Record): Map { + const modelUsage = usage['modelUsage'] + const result = new Map() + if (!isRecord(modelUsage)) return result + + for (const [modelId, rawModelUsage] of Object.entries(modelUsage)) { + if (!modelId || !isRecord(rawModelUsage)) continue + const values = authoritativeTokenFields.map((field) => finiteNonNegative(rawModelUsage[field])) + if (!values.some((value) => value !== undefined)) continue + result.set(modelId, { + inputTokens: values[0] ?? 0, + outputTokens: values[1] ?? 0, + cacheReadTokens: values[2] ?? 0, + cacheCreationTokens: values[3] ?? 0, + reasoningTokens: values[4] ?? 0, + }) + } + return result +} + +function parseAuthoritativeUsage(raw: unknown): GrokAuthoritativeUsage | null { + if (!isRecord(raw)) return null + + const values = authoritativeTokenFields.map((field) => readUsageNumber(raw, field)) + const modelUsage = readModelUsage(raw) + return { + inputTokens: values[0] ?? 0, + outputTokens: values[1] ?? 0, + cacheReadTokens: values[2] ?? 0, + cacheCreationTokens: values[3] ?? 0, + reasoningTokens: values[4] ?? 0, + modelUsage, + } +} + +function chooseAuthoritativeModel(modelIds: string[], existingModel: string): string { + // modelUsage is the best attribution signal, but it may contain a newer + // provider id that this checkout cannot price yet (for example + // `grok-4.6-build`). Prefer an actual model id when it prices; otherwise keep + // the existing summary/signals id when that one prices, avoiding a truthful + // but $0 row. If neither prices, retain the actual model id for attribution. + const pricedActualModel = modelIds.find((modelId) => getModelCosts(modelId) !== null) + if (pricedActualModel) return pricedActualModel + if (getModelCosts(existingModel) !== null) return existingModel + return modelIds[0] ?? existingModel +} + +// Single pass over updates.jsonl: retain the old per-turn totalTokens estimate, +// the deduplicated authoritative turn records, and the real tool calls. +function parseUpdates(updates: string): { + usage: GrokTokenTotals + modelIds: string[] + authoritative: boolean + hasUncompletedTurn: boolean tools: string[] bashCommands: string[] subagentTypes: string[] } { const turns = new Map() + const completedUsages = new Map() const tools: string[] = [] const bashCommands: string[] = [] const subagentTypes: string[] = [] @@ -111,6 +220,7 @@ function parseUpdates(updates: string): { let prevTotal = -1 let segmentPeak = 0 let inputFresh = 0 + let completedWithoutPromptId = 0 for (const line of updates.split('\n')) { if (!line.trim()) continue @@ -122,16 +232,16 @@ function parseUpdates(updates: string): { } if (!params) continue - const total = params._meta?.totalTokens - if (typeof total === 'number') { + const total = finiteNonNegative(params._meta?.totalTokens) + if (total !== undefined) { if (prevTotal >= 0 && total < prevTotal * 0.5) { - inputFresh += segmentPeak // close the segment a compaction just ended + inputFresh = addTokenCounts(inputFresh, segmentPeak) // close the segment a compaction just ended segmentPeak = 0 } if (total > segmentPeak) segmentPeak = total prevTotal = total - const promptId = params._meta?.promptId + const promptId = typeof params._meta?.promptId === 'string' ? params._meta.promptId : undefined if (promptId) { const turn = turns.get(promptId) if (!turn) turns.set(promptId, { first: total, last: total }) @@ -140,6 +250,18 @@ function parseUpdates(updates: string): { } const update = params.update + if (update?.sessionUpdate === 'turn_completed') { + const usage = parseAuthoritativeUsage(update.usage) + if (usage) { + const promptId = typeof update.prompt_id === 'string' && update.prompt_id.length > 0 + ? update.prompt_id + : `turn_completed:${completedWithoutPromptId++}` + // Re-emitted turn_completed notifications are cumulative updates for + // the same turn. Last write wins so they cannot double count. + completedUsages.set(promptId, usage) + } + } + if (update?.sessionUpdate === 'tool_call' && typeof update.title === 'string') { tools.push(toolNameMap[update.title] ?? update.title) if (update.title === 'run_terminal_command' && typeof update.rawInput?.command === 'string') { @@ -151,17 +273,101 @@ function parseUpdates(updates: string): { } } - inputFresh += segmentPeak // close the final segment + inputFresh = addTokenCounts(inputFresh, segmentPeak) // close the final segment let sumFirst = 0 let output = 0 for (const { first, last } of turns.values()) { - sumFirst += first - output += Math.max(0, last - first) + sumFirst = addTokenCounts(sumFirst, first) + output = addTokenCounts(output, Math.max(0, last - first)) } // Fresh input (summed segment peaks) is billed once; the rest of the per-turn // re-sends are cache reads (Grok caches them, even though it reports nothing). - const cacheRead = Math.max(0, sumFirst - inputFresh) - return { input: inputFresh, cacheRead, output, tools, bashCommands, subagentTypes } + const estimated = { + input: inputFresh, + cacheRead: Math.max(0, sumFirst - inputFresh), + output, + } + + const usageTotals = emptyTokenTotals() + const modelIds: string[] = [] + const seenModelIds = new Set() + for (const usage of completedUsages.values()) { + addUsageToTotals(usageTotals, usage) + for (const modelId of usage.modelUsage.keys()) { + if (seenModelIds.has(modelId)) continue + seenModelIds.add(modelId) + modelIds.push(modelId) + } + } + + // Decide from the final, prompt-deduplicated records. A positive modelUsage + // entry is attribution metadata only; it is not a substitute for the + // top-level accounting fields. This also prevents a superseded positive + // record from suppressing the streaming fallback. + const hasPositiveCompletedUsage = [...completedUsages.values()].some(hasPositiveTopLevelUsage) + if (!hasPositiveCompletedUsage || !hasPositiveTotals(usageTotals)) { + // Older Grok CLI versions have no completed usage record. Keep the + // heuristic only here; blending it into a real record would reintroduce the + // large over-count this parser is fixing. A record that only has modelUsage, + // or whose final deduplicated values are empty, is treated the same way. + return { + usage: { input: estimated.input, cacheRead: estimated.cacheRead, output: estimated.output, cacheCreation: 0, reasoning: 0 }, + modelIds: [], + authoritative: false, + hasUncompletedTurn: false, + tools, + bashCommands, + subagentTypes, + } + } + + const hasUncompletedTurn = [...turns.keys()].some(promptId => !completedUsages.has(promptId)) + + // calculateCost follows the cache-exclusive input convention used by the + // other real-usage providers. Each record is decomposed before its totals + // are added, so an inconsistent record cannot consume another record's fresh + // input budget. + return { + usage: usageTotals, + modelIds, + authoritative: true, + hasUncompletedTurn, + tools, + bashCommands, + subagentTypes, + } +} + +function hasPositiveTopLevelUsage(usage: GrokAuthoritativeUsage): boolean { + return usage.inputTokens > 0 + || usage.outputTokens > 0 + || usage.cacheReadTokens > 0 + || usage.cacheCreationTokens > 0 + || usage.reasoningTokens > 0 +} + +function addUsageToTotals(totals: GrokTokenTotals, usage: GrokUsageValues): void { + // `cacheCreationTokens` is treated as an input subset by analogy. Clamp the + // exclusive portion per record before summing the session. Reasoning is + // reported inside outputTokens by Grok, so clamp it to that same record's + // output before the session totals are accumulated. + const reasoningTokens = Math.min(usage.reasoningTokens, usage.outputTokens) + totals.input = addTokenCounts( + totals.input, + Math.max(0, usage.inputTokens - usage.cacheReadTokens - usage.cacheCreationTokens), + ) + totals.cacheRead = addTokenCounts(totals.cacheRead, usage.cacheReadTokens) + totals.output = addTokenCounts(totals.output, usage.outputTokens) + totals.cacheCreation = addTokenCounts(totals.cacheCreation, usage.cacheCreationTokens) + totals.reasoning = addTokenCounts(totals.reasoning, reasoningTokens) +} + +function hasPositiveTotals(totals: GrokTokenTotals): boolean { + return totals.input > 0 + || totals.cacheRead > 0 + || totals.output > 0 + || totals.cacheCreation > 0 + || totals.reasoning > 0 } function createParser(source: SessionSource, seenKeys: Set): SessionParser { @@ -172,37 +378,64 @@ function createParser(source: SessionSource, seenKeys: Set): SessionPars const updates = await readSessionFile(source.path) if (!summary || updates === null) return - const { input, cacheRead, output, tools, bashCommands, subagentTypes } = parseUpdates(updates) - if (input === 0 && output === 0) return - const signals = await readJson(join(dir, 'signals.json')) - const model = + const existingModel = summary.current_model_id ?? signals?.primaryModelId ?? signals?.modelsUsed?.[0] ?? 'grok-build' + const parsed = parseUpdates(updates) + if (!hasPositiveTotals(parsed.usage)) return + const timestamp = summary.updated_at ?? summary.last_active_at ?? summary.created_at ?? '' const sessionId = summary.info?.id ?? basename(dir) - const dedupKey = `${source.provider}:${dir}:${timestamp}:${sessionId}` - if (seenKeys.has(dedupKey)) return - seenKeys.add(dedupKey) + // Multi-model attribution is deliberately out of scope: modelUsage may + // help choose a priced attribution id, but top-level totals remain the + // accounting source and one session uses one model's rate. + const model = parsed.authoritative ? chooseAuthoritativeModel(parsed.modelIds, existingModel) : existingModel + const baseDedupKey = `${source.provider}:${dir}:${timestamp}:${sessionId}` + if (seenKeys.has(baseDedupKey)) return + seenKeys.add(baseDedupKey) + + // `addUsageToTotals` clamps reasoning per authoritative record before + // summing, so the aggregate preserves this identity as well. + const reasoningTokens = parsed.usage.reasoning yield { provider: source.provider, model, - inputTokens: input, - outputTokens: output, - cacheCreationInputTokens: 0, - cacheReadInputTokens: cacheRead, - cachedInputTokens: cacheRead, - reasoningTokens: 0, + inputTokens: parsed.usage.input, + // Grok reports reasoning INSIDE outputTokens, but the repo contract is + // the opposite: ParsedProviderCall.reasoningTokens is exclusive of + // outputTokens, and every consumer sums the two (parser.ts's + // cachedCallToApiCall for cost, modelBreakdown for tokens, and the + // models/audit reports). tests/providers/kiro.test.ts states it + // outright. So split it here rather than special-casing grok in five + // downstream places: subtracting reasoning makes `output + reasoning` + // reconstruct exactly the number Grok reported. + outputTokens: parsed.usage.output - reasoningTokens, + cacheCreationInputTokens: parsed.usage.cacheCreation, + cacheReadInputTokens: parsed.usage.cacheRead, + cachedInputTokens: parsed.usage.cacheRead, + reasoningTokens, webSearchRequests: 0, - costUSD: calculateCost(model, input, output, 0, cacheRead, 0), - costIsEstimated: true, - tools, - bashCommands, - subagentTypes, + // Authoritative token counts are measured even though CodeBurn applies + // its own pricing table; only the legacy context-curve path is an + // estimate. The full provider output is priced once here, which is + // what the downstream `output + reasoning` recompute reproduces. + costUSD: calculateCost( + model, + parsed.usage.input, + parsed.usage.output, + parsed.usage.cacheCreation, + parsed.usage.cacheRead, + 0, + ), + costIsEstimated: !parsed.authoritative || parsed.hasUncompletedTurn, + tools: parsed.tools, + bashCommands: parsed.bashCommands, + subagentTypes: parsed.subagentTypes, timestamp, speed: 'standard', - deduplicationKey: dedupKey, + deduplicationKey: baseDedupKey, userMessage: summary.session_summary ?? summary.generated_title ?? '', sessionId, project: source.project, diff --git a/src/providers/index.ts b/src/providers/index.ts index bf035f06..70af252c 100644 --- a/src/providers/index.ts +++ b/src/providers/index.ts @@ -7,6 +7,7 @@ import { codex } from './codex.js' import { copilot } from './copilot.js' import { droid } from './droid.js' import { devin } from './devin.js' +import { dsh } from './dsh.js' import { gemini } from './gemini.js' import { hermes } from './hermes.js' import { ibmBob } from './ibm-bob.js' @@ -192,7 +193,7 @@ async function loadZed(): Promise { } } -const coreProviders: Provider[] = [claude, cline, clineCli, codewhale, codebuff, codex, copilot, devin, droid, gemini, hermes, ibmBob, kiloCode, kiro, kimi, kimicode, lingtaiTui, mistralVibe, mux, openclaw, openclaude, openDesign, pi, omp, qwen, quickdesk, rooCode, zerostack, grok] +const coreProviders: Provider[] = [claude, cline, clineCli, codewhale, codebuff, codex, copilot, devin, droid, dsh, gemini, hermes, ibmBob, kiloCode, kiro, kimi, kimicode, lingtaiTui, mistralVibe, mux, openclaw, openclaude, openDesign, pi, omp, qwen, quickdesk, rooCode, zerostack, grok] // Lazily loaded providers, listed by name so --provider validation works even // when an optional module fails to load. Must stay in sync with getAllProviders. diff --git a/src/providers/sqlite-session-parser.ts b/src/providers/sqlite-session-parser.ts index b1e962f0..925a942b 100644 --- a/src/providers/sqlite-session-parser.ts +++ b/src/providers/sqlite-session-parser.ts @@ -2,7 +2,16 @@ import { readdir } from 'fs/promises' import { join } from 'path' import { calculateCost } from '../models.js' -import { isSqliteAvailable, getSqliteLoadError, openDatabase, blobToText, isSqliteBusyError, type SqliteDatabase } from '../sqlite.js' +import { + isSqliteAvailable, + getSqliteLoadError, + openDatabase, + blobToText, + isSqliteBusyError, + isSqliteReadonlyError, + warnSqliteReadonlyOnce, + type SqliteDatabase, +} from '../sqlite.js' import { buildAssistantCall, parseTimestamp, sanitize, type MessageData, type PartData } from './session-message.js' import type { SessionSource, @@ -310,7 +319,8 @@ export async function discoverSqliteSessions( let db: SqliteDatabase try { db = openDatabase(dbPath) - } catch { + } catch (err) { + if (isSqliteReadonlyError(err)) warnSqliteReadonlyOnce(dbPath) continue } diff --git a/src/session-cache.ts b/src/session-cache.ts index 50d1f86c..87ea1262 100644 --- a/src/session-cache.ts +++ b/src/session-cache.ts @@ -105,7 +105,7 @@ export type CachedFile = { // is re-parsed only when the file changes (fingerprint differs). Carries no // turns, so it contributes no usage. (issue #441 follow-up) failed?: boolean - // Rich-session-capture, Claude session-level (capture-only; no report yet). + // Rich-session-capture, Claude session-level. // `title` is the LAST `ai-title` entry's text; `prLinks` accumulates every // `pr-link` entry's URL. `isSidechain` is true when any entry is a sidechain: // parentUuid references an intra-file entry uuid, not another session id, so it @@ -230,6 +230,7 @@ export const PROVIDER_ENV_VARS: Record = { hermes: ['HERMES_HOME'], 'lingtai-tui': ['LINGTAI_HOME', 'LINGTAI_TUI_HOME', 'LINGTAI_TUI_GLOBAL_DIR'], droid: ['FACTORY_DIR'], + dsh: ['DSH_HOME'], cursor: ['CODEBURN_CURSOR_MAX_BUBBLES'], // XDG_DATA_HOME is stale here (cursor-agent never reads it) but deliberately // kept: removing it would force a re-parse to fix nothing. @@ -304,7 +305,14 @@ export const PROVIDER_PARSE_VERSIONS: Record = { // they still contribute. v2 (over the never-released v1): store dedup keys // grew a content discriminator so a same-path DB reset cannot alias rows. copilot: 'cli-shutdown-cost-v1-skills-source-provenance-v1-session-store-v2', - grok: 'estimated-cost-v1', + // authoritative-usage-v4: persist one Grok session call from top-level + // authoritative totals, use modelUsage only for priced attribution, clamp + // reasoning per record, and label mixed sessions estimated. + grok: 'authoritative-usage-v4', + // seed-aware-v1: the parser now skips the parent events a forked session + // replays (double-counted before), takes the model from the reporting + // assistant/message, and keeps agent-injected context out of the preview. + dsh: 'seed-aware-v1', hermes: 'reasoning-output-accounting-v1-est-cost', 'lingtai-tui': 'token-ledger-registry-activity-v3', 'ibm-bob': 'worktree-project-grouping-v1', @@ -807,8 +815,15 @@ async function loadShard(path: string): Promise | nul * full: the first because its cache is the only surviving record of pruned * usage, the second because a fingerprint change discards the whole section and * must see every entry it is discarding. + * + * `CODEBURN_CACHE_SCOPE=all` is the escape hatch: it drops the scope here, at + * the one place every caller routes through, so a suspect scoped read can be + * compared against a full one without a rebuild. It is a READ policy and + * deliberately not part of any env fingerprint (PROVIDER_ENV_VARS) — setting or + * unsetting it must never invalidate a cache, only change how much of it is read. */ export async function loadCache(scope?: CacheLoadScope): Promise { + if (process.env['CODEBURN_CACHE_SCOPE'] === 'all') scope = undefined const dir = sessionCacheDir() const envelope = await readEnvelope(dir) if (!envelope) return afterMissingShardCache() @@ -1056,6 +1071,15 @@ export async function saveCache(cache: SessionCache, verifyStillOwner?: () => Pr const files = plan.groups.get(bucket)! const onDisk = from ? await loadShard(join(dir, from)) : null if (!onDisk) return writeShard(provider, bucket, files) + // A file whose month this run never loaded has no visible cache entry, so it + // looks uncached and is re-parsed into the same bucket — re-deriving the + // entry the shard already holds. Republishing then churns the shard's nonce + // name on every run for content that never changed (#1032), so a merge that + // neither adds, changes nor removes an entry keeps the published shard. + const adds = Object.entries(files).some(([path, file]) => + onDisk[path] === undefined || JSON.stringify(onDisk[path]) !== JSON.stringify(file)) + const removes = [...plan.moved].some(path => onDisk[path] !== undefined && files[path] === undefined) + if (!adds && !removes) return { name: from!, until: untilMonth(onDisk) } for (const path of plan.moved) delete onDisk[path] return writeShard(provider, bucket, { ...onDisk, ...files }) } diff --git a/src/session-population.ts b/src/session-population.ts new file mode 100644 index 00000000..965f3591 --- /dev/null +++ b/src/session-population.ts @@ -0,0 +1,34 @@ +import type { ProjectSummary, SessionSummary } from './types.js' + +/** + * Sidechains are real usage, but they are not user-started work sessions. + * Behavioral consumers should use this predicate or the projected project + * view below; accounting and configuration consumers should use the originals. + */ +export function isUserStartedSession(session: SessionSummary): boolean { + return session.isSidechain !== true +} + +export function withUserStartedSessions(project: ProjectSummary): ProjectSummary { + const sessions = project.sessions.filter(isUserStartedSession) + if (sessions.length === project.sessions.length) return project + + const totalCostUSD = sessions.reduce((sum, session) => sum + session.totalCostUSD, 0) + return { + ...project, + sessions, + totalCostUSD, + totalSavingsUSD: sessions.reduce((sum, session) => sum + session.totalSavingsUSD, 0), + totalEstimatedCostUSD: project.totalEstimatedCostUSD === undefined + ? undefined + : sessions.reduce((sum, session) => sum + (session.totalEstimatedCostUSD ?? 0), 0), + totalApiCalls: sessions.reduce((sum, session) => sum + session.apiCalls, 0), + // Proxy coverage is project-scoped and applies to every retained session + // whenever it applies to the source project. + totalProxiedCostUSD: project.totalProxiedCostUSD > 0 ? totalCostUSD : 0, + } +} + +export function userStartedProjects(projects: ProjectSummary[]): ProjectSummary[] { + return projects.map(withUserStartedSessions) +} diff --git a/src/sqlite.ts b/src/sqlite.ts index 3fb3c6a8..7c107c0d 100644 --- a/src/sqlite.ts +++ b/src/sqlite.ts @@ -1,4 +1,10 @@ import { createRequire } from 'node:module' +import { copyFileSync, existsSync, mkdirSync, readdirSync, renameSync, statSync, unlinkSync, utimesSync } from 'node:fs' +import { createHash, randomBytes } from 'node:crypto' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' + +import { getCodeburnCacheDir } from './cache-dir.js' /// Thin SQLite read-only wrapper over Node's built-in `node:sqlite` module (stable in /// Node 24, experimental in Node 22 / 23). Replaces the earlier `better-sqlite3` binding @@ -14,12 +20,14 @@ export type SqliteDatabase = { close(): void } -type DatabaseSyncCtor = new (path: string, options?: { readOnly?: boolean }) => { +type DatabaseSyncInstance = { prepare(sql: string): { all(...params: unknown[]): Row[] } exec?(sql: string): void close(): void } +type DatabaseSyncCtor = new (path: string, options?: { readOnly?: boolean }) => DatabaseSyncInstance + let DatabaseSync: DatabaseSyncCtor | null = null let loadAttempted = false let loadError: string | null = null @@ -116,12 +124,304 @@ export function isSqliteBusyError(err: unknown): boolean { ) } +/// SQLite reports SQLITE_READONLY_DIRECTORY as ERR_SQLITE_ERROR with an extended +/// result code on the Node 22 builds CodeBurn supports. Keep the base-code check +/// so this also covers SQLITE_READONLY and its other extended variants, while +/// leaving ENOENT/SQLITE_CANTOPEN distinguishable to callers. +export function isSqliteReadonlyError(err: unknown): boolean { + const e = err as { code?: unknown; errcode?: unknown; errstr?: unknown; message?: unknown } | null + const code = typeof e?.code === 'string' ? e.code : '' + const errcode = typeof e?.errcode === 'number' ? e.errcode : null + const message = [ + typeof e?.message === 'string' ? e.message : '', + typeof e?.errstr === 'string' ? e.errstr : '', + ].join(' ') + + return ( + (errcode !== null && (errcode & 0xff) === 8) || + /SQLITE_READONLY|attempt to write a readonly database|readonly database|read-only database/i.test(`${code} ${message}`) + ) +} + +/// A read-only parent reports SQLITE_READONLY_DIRECTORY when it must create the +/// sidecars from scratch, but SQLITE_CANTOPEN when a `-wal` is present and the +/// `-shm` it needs to index it is not. openReadonlyCache re-throws the original +/// error when the database itself is missing, which is the other CANTOPEN. +function isSqliteSidecarError(err: unknown): boolean { + if (isSqliteReadonlyError(err)) return true + const errcode = (err as { errcode?: unknown } | null)?.errcode + return typeof errcode === 'number' && (errcode & 0xff) === 14 +} + +let uriFilenamesSupported: boolean | null = null + +/// node:sqlite only enables SQLITE_OPEN_URI from Node 22.15 on (measured: 22.13 +/// and 22.14 fail, 22.15 and later work). Below that a `file:...` location is +/// taken literally and fails as CANTOPEN, so the immutable open is not attempted +/// there. The probe is an in-memory URI rather than a version comparison: it +/// answers the question directly and touches no filesystem either way. +export function sqliteSupportsUriFilenames(): boolean { + if (uriFilenamesSupported !== null) return uriFilenamesSupported + uriFilenamesSupported = false + const Driver = loadDriver() ? DatabaseSync : null + if (Driver !== null) { + try { + new Driver('file:codeburn-uri-probe?mode=memory', { readOnly: true }).close() + uriFilenamesSupported = true + } catch { + // An older build: locations are plain paths, and the copy fallback covers + // exactly the case the immutable open would have. + } + } + return uriFilenamesSupported +} + +type DatabaseFingerprint = { + dev: number + ino: number + mtimeMs: number + sizeBytes: number + walBytes: number +} + +/// A superseded copy is dropped once it has gone this long without being used. +/// The delay is what keeps a concurrent reader of the previous copy from having +/// its file yanked out from under it. +const CACHE_ENTRY_MAX_AGE_MS = 24 * 60 * 60 * 1000 +const warnedDatabases = new Set() + +/// One notice per source path per run: a provider may discover many sessions +/// from the same database, and the first notice already says what happened. +function warnSqliteOnce(path: string, message: string): void { + if (warnedDatabases.has(path)) return + warnedDatabases.add(path) + process.stderr.write(message) +} + +/// A read-only SQLite connection can still need sidecar files. +export function warnSqliteReadonlyOnce(path: string): void { + warnSqliteOnce( + path, + `codeburn: SQLite database ${path} is in a read-only directory and needs sidecar files; using a cache copy when necessary. ` + + 'The original database is not modified.\n', + ) +} + +function errorCode(err: unknown): string | undefined { + if (typeof err !== 'object' || err === null || !('code' in err)) return undefined + const code = err.code + return typeof code === 'string' ? code : undefined +} + +function describeError(err: unknown): string { + return err instanceof Error ? err.message : String(err) +} + +/// This deliberately mirrors fingerprintSqliteFile/fingerprintFile in +/// session-cache.ts. openDatabase is synchronous, so the fallback uses the +/// synchronous fs APIs only after the direct open has already failed; the +/// ordinary successful open remains probe-free. +function fingerprintDatabase(path: string): DatabaseFingerprint { + const main = statSync(path) + let wal: ReturnType | null = null + try { + wal = statSync(path + '-wal') + } catch (err) { + if (errorCode(err) !== 'ENOENT') throw err + } + return { + dev: main.dev, + ino: main.ino, + mtimeMs: wal ? Math.max(main.mtimeMs, wal.mtimeMs) : main.mtimeMs, + sizeBytes: main.size + (wal?.size ?? 0), + walBytes: wal?.size ?? 0, + } +} + +function sameFingerprint(a: DatabaseFingerprint, b: DatabaseFingerprint): boolean { + return ( + a.dev === b.dev && + a.ino === b.ino && + a.mtimeMs === b.mtimeMs && + a.sizeBytes === b.sizeBytes && + a.walBytes === b.walBytes + ) +} + +function unlinkQuietly(path: string): void { + try { + unlinkSync(path) + } catch { + // Already gone, or still held open by another CodeBurn on Windows. Either + // way the next run's eviction pass gets another chance at it. + } +} + +function copyOptionalFile(sourcePath: string, destinationPath: string): boolean { + try { + copyFileSync(sourcePath, destinationPath) + return true + } catch (err) { + if (errorCode(err) === 'ENOENT') return false + throw err + } +} + +function sourceKeyOf(sourcePath: string): string { + return createHash('sha256').update(sourcePath, 'utf8').digest('hex').slice(0, 32) +} + +/// The copy is named after the source it came from AND the fingerprint it was +/// taken at, so a refresh publishes a new file rather than overwriting one that +/// another process may still have open. +function cacheEntryName(sourceKey: string, fingerprint: DatabaseFingerprint): string { + const parts = `${fingerprint.dev}:${fingerprint.ino}:${fingerprint.mtimeMs}:${fingerprint.sizeBytes}:${fingerprint.walBytes}` + return `${sourceKey}.${createHash('sha256').update(parts).digest('hex').slice(0, 16)}.db` +} + +function dropCopy(cacheDir: string, name: string): void { + unlinkQuietly(join(cacheDir, name)) + unlinkQuietly(join(cacheDir, name + '-wal')) + unlinkQuietly(join(cacheDir, name + '-shm')) +} + +/// Superseded copies are cleaned up here rather than by overwriting them: keep +/// the one in use plus at most one predecessor, and drop anything untouched for +/// a day, which is also what a source path that no longer exists looks like. +/// Reuse touches the copy, so its mtime is last-use rather than copy time. +function evictSupersededCopies(cacheDir: string, sourceKey: string, keepName: string): void { + let names: string[] + try { + names = readdirSync(cacheDir) + } catch { + return + } + const now = Date.now() + const superseded: { name: string, mtimeMs: number }[] = [] + for (const name of names) { + if (!name.endsWith('.db') || name === keepName) continue + let mtimeMs: number + try { + mtimeMs = statSync(join(cacheDir, name)).mtimeMs + } catch { + continue + } + if (name.startsWith(`${sourceKey}.`)) superseded.push({ name, mtimeMs }) + else if (now - mtimeMs > CACHE_ENTRY_MAX_AGE_MS) dropCopy(cacheDir, name) + } + superseded.sort((a, b) => b.mtimeMs - a.mtimeMs) + for (const [index, entry] of superseded.entries()) { + if (index > 0 || now - entry.mtimeMs > CACHE_ENTRY_MAX_AGE_MS) dropCopy(cacheDir, entry.name) + } +} + +/// A concurrent CodeBurn may have published the same copy first. The name is +/// the fingerprint, so the content is identical by construction and losing that +/// race is not an error. +function publish(tempPath: string, finalPath: string): void { + try { + renameSync(tempPath, finalPath) + } catch (err) { + if (!existsSync(finalPath)) throw err + } +} + +function readOnlyCachePath(sourcePath: string, fingerprint: DatabaseFingerprint): string { + const cacheDir = join(getCodeburnCacheDir(), 'sqlite-ro') + mkdirSync(cacheDir, { recursive: true, mode: 0o700 }) + + const sourceKey = sourceKeyOf(sourcePath) + const name = cacheEntryName(sourceKey, fingerprint) + const cachePath = join(cacheDir, name) + if (existsSync(cachePath)) { + const now = new Date() + try { + utimesSync(cachePath, now, now) + } catch { + // mtime is only the eviction clock; a copy we cannot touch still reads. + } + evictSupersededCopies(cacheDir, sourceKey, name) + return cachePath + } + + const tempBase = `${cachePath}.tmp-${process.pid}-${randomBytes(8).toString('hex')}` + const tempWal = tempBase + '-wal' + try { + copyFileSync(sourcePath, tempBase) + const copiedWal = copyOptionalFile(sourcePath + '-wal', tempWal) + + // Do not publish a cache made from a moving database. A live WAL writer will + // normally make the direct open succeed once its sidecars exist; this check + // covers the narrow race where the source changes during the copy fallback. + if (!sameFingerprint(fingerprintDatabase(sourcePath), fingerprint)) { + throw new Error('SQLite database changed while preparing its read-only cache copy') + } + + // The -wal goes first: a reader that can see the database must never find it + // without the sidecar holding its most recent rows. + if (copiedWal) publish(tempWal, cachePath + '-wal') + publish(tempBase, cachePath) + evictSupersededCopies(cacheDir, sourceKey, name) + return cachePath + } finally { + unlinkQuietly(tempBase) + unlinkQuietly(tempWal) + } +} + +function openReadonlyCache(path: string, originalError: unknown): DatabaseSyncInstance { + const Driver = DatabaseSync + if (Driver === null) throw new Error(getSqliteLoadError()) + + let fingerprint: DatabaseFingerprint + try { + fingerprint = fingerprintDatabase(path) + } catch { + // Preserve the original SQLite error when the source disappeared or became + // inaccessible between the failed query and the fallback probe. + throw originalError + } + + // An absent or empty -wal holds no frames, so there is nothing to go stale and + // nothing worth copying: immutable lets SQLite skip the -shm it cannot create + // and read the source in place. + if (fingerprint.walBytes === 0 && sqliteSupportsUriFilenames()) { + try { + return new Driver(`${pathToFileURL(path).href}?immutable=1`, { readOnly: true }) + } catch { + // Understood but refused: the copy covers it. + } + } + + let cachedPath: string + try { + cachedPath = readOnlyCachePath(path, fingerprint) + } catch (err) { + warnSqliteOnce( + path, + `codeburn: SQLite database ${path} is in a read-only directory and its cache copy could not be written ` + + `(${describeError(err)}); skipping this database.\n`, + ) + throw originalError + } + return new Driver(cachedPath, { readOnly: true }) +} + export function openDatabase(path: string): SqliteDatabase { if (!loadDriver() || DatabaseSync === null) { throw new Error(getSqliteLoadError()) } - const db = new DatabaseSync(path, { readOnly: true }) + let db: DatabaseSyncInstance + let fallbackUsed = false + try { + db = new DatabaseSync(path, { readOnly: true }) + } catch (err) { + if (!isSqliteSidecarError(err)) throw err + fallbackUsed = true + db = openReadonlyCache(path, err) + warnSqliteReadonlyOnce(path) + } try { db.exec?.('PRAGMA busy_timeout = 1000') } catch { @@ -130,7 +430,26 @@ export function openDatabase(path: string): SqliteDatabase { return { query(sql: string, params: unknown[] = []): T[] { - return db.prepare(sql).all(...params) as T[] + try { + return db.prepare(sql).all(...params) as T[] + } catch (err) { + if (!isSqliteSidecarError(err)) throw err + if (fallbackUsed) throw err + fallbackUsed = true + try { + db.close() + } catch { + // The failed connection may already have been closed by node:sqlite. + } + db = openReadonlyCache(path, err) + warnSqliteReadonlyOnce(path) + try { + db.exec?.('PRAGMA busy_timeout = 1000') + } catch { + // Best effort, matching the direct-open path above. + } + return db.prepare(sql).all(...params) as T[] + } }, close() { db.close() diff --git a/src/types.ts b/src/types.ts index a4fcb883..34451ac1 100644 --- a/src/types.ts +++ b/src/types.ts @@ -211,6 +211,11 @@ export type SessionSummary = { /// correlations performed after all saved sessions have been parsed. prAttributionSource?: 'transcript' | 'explicit-reference' | 'working-directory' | 'launcher-prompt' source?: SessionSourceMetadata + /// Claude Code only: true when this record is a subagent (sidechain) + /// transcript rather than a user-started parent session. Sidechain spend is + /// real and remains in every cost/token/call aggregate; consumers that reason + /// about human session populations may exclude it explicitly. + isSidechain?: boolean // Claude Code only: agent type of a subagent transcript session // (`workflow-subagent`, `Explore`, `general-purpose`, …); undefined for // ordinary sessions. Drives the Claude-scoped agent-type breakdown. diff --git a/src/usage-aggregator.ts b/src/usage-aggregator.ts index 53cbdd2c..081e3f69 100644 --- a/src/usage-aggregator.ts +++ b/src/usage-aggregator.ts @@ -941,7 +941,7 @@ export async function buildMenubarPayloadForRange(periodInfo: PeriodInfo, opts: } })() - const optimize = opts.optimize === false ? null : await scanAndDetect(scanProjects, scanRange) + const optimize = opts.optimize === false ? null : await scanAndDetect(scanProjects, scanRange, opts.provider) const granularRange = opts.daysSelection?.range ?? scanRange const granularHistory = opts.timeline === false ? undefined : buildGranularHistory(scanProjects, granularRange) return buildMenubarPayload(currentData, providers, optimize, dailyHistory, retryTax, routingWaste, breakdowns, claudeConfigs, granularHistory) diff --git a/src/web-dashboard.ts b/src/web-dashboard.ts index fec1f9eb..39416d7b 100644 --- a/src/web-dashboard.ts +++ b/src/web-dashboard.ts @@ -90,6 +90,15 @@ function openBrowser(url: string): void { } } +export function injectDashboardBootstrap(html: string, payload: unknown): string { + const json = JSON.stringify(payload) + if (json === undefined) throw new TypeError('dashboard bootstrap payload is not serializable') + // Keep the JSON safe at the boundary where it enters an HTML script. This is + // deliberately inside the helper so callers cannot forget the escape. + const safeJson = json.replace(/ `\n \n ' + + const injected = injectDashboardBootstrap(html, payload) + + expect(injected).toContain(`window.__CODEBURN_BOOTSTRAP__=${JSON.stringify(payload)}`) + expect(injected).toContain(`"name":"${payloadValue}"`) + }) + + it('escapes script-closing payload values and preserves the served bootstrap payload', () => { + const hostileName = '' + const payload = { + devices: [{ + id: 'local', + name: hostileName, + payload: { current: { topProjects: [{ name: hostileName }] } }, + }], + } + const html = '' + + const servedHtml = injectDashboardBootstrap(html, payload) + const marker = 'window.__CODEBURN_BOOTSTRAP__=' + const start = servedHtml.indexOf(marker) + marker.length + const end = servedHtml.indexOf('', start) + const serialized = servedHtml.slice(start, end) + + expect(serialized).not.toContain('') + expect(JSON.parse(serialized)).toEqual(payload) + }) +}) // Regression guard for the original bug: a bad `period` query used to hit // process.exit(1) and kill the long-running dashboard server. The handlers must diff --git a/tests/workflow-insights.test.ts b/tests/workflow-insights.test.ts index 2e44687e..bb18d759 100644 --- a/tests/workflow-insights.test.ts +++ b/tests/workflow-insights.test.ts @@ -353,4 +353,25 @@ describe('review-findings regressions', () => { // 95 local calls + 5 unpriced cloud calls: coverage must be 0, not 0.95. expect(computePricingCoverage(5, 5)).toBe(0) }) + + it('excludes sidechain-only work from every human workflow signal', () => { + const editCall = call({ + tools: ['Edit'], + timestamp: '2026-06-01T10:06:00Z', + toolSequence: [[{ tool: 'Edit', file: '/home/u/app/src/a.ts' }]], + }) + const sidechain = session('agent-reviewer', [ + turn({ userMessage: 'review the change', timestamp: '2026-06-01T10:00:00Z' }), + turn({ userMessage: 'you missed the edge case', calls: [editCall], timestamp: '2026-06-01T10:06:00Z' }), + turn({ userMessage: 'that is still wrong', timestamp: '2026-06-01T10:07:00Z' }), + turn({ userMessage: 'revert that change', timestamp: '2026-06-01T10:08:00Z' }), + ], { feature: cat(10, 0) } as SessionSummary['categoryBreakdown']) + sidechain.isSidechain = true + const projects = [project([sidechain])] + + expect(scanUserCorrections(projects)).toEqual({ corrections: 0, userTurns: 0, correctionRate: null }) + expect(medianTimeToFirstEditMs(projects)).toBeNull() + expect(aggregateFileChurn(projects)).toEqual([]) + expect(worstOneShotCategory(projects)).toBeNull() + }) }) diff --git a/vitest.config.ts b/vitest.config.ts index b56c0158..0fa9f58b 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -6,5 +6,8 @@ export default defineConfig({ // session-discovery env vars (CLAUDE_CONFIG_DIRS, HOME, XDG_*, every // provider-specific *_HOME) don't bleed real local data into fixtures. setupFiles: ['./tests/setup/env-isolation.ts'], + // Real-I/O tests (session parses, sqlite fixtures, worker pools) exceed the + // 5s default under CI runner load; a hung test still fails at 30s. + testTimeout: 30_000, }, }) diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 00000000..2e4d499b --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,10 @@ +node_modules/ +# dist/ is a Vite build output; we gitignore its contents but keep a tracked placeholder +# index.html so Tauri's compile-time `frontendDist` validation passes on fresh clones before +# anyone has run `npm run build`. Real build output replaces the placeholder locally. +dist/* +!dist/index.html +src-tauri/target/ +src-tauri/gen/ +.DS_Store +*.log diff --git a/windows/DEVELOPMENT.md b/windows/DEVELOPMENT.md new file mode 100644 index 00000000..e59a7392 --- /dev/null +++ b/windows/DEVELOPMENT.md @@ -0,0 +1,188 @@ +# CodeBurn Menubar (Windows) + +Tauri 2.x tray app that surfaces CodeBurn in the Windows notification area. It is the Windows +mirror of the native macOS menubar in `../mac/`, which stays the authoritative look and feel; +this project mirrors its layout, colors, and data via the shared `tokens.json`. + +Linux (ksni / AppIndicator) support is compiled and kept working for dev, but it is +**experimental and unreleased** - Linux users should use the GNOME extension in `../gnome/`. +The releases this repo cuts from here are Windows only. + +Not everything crosses over: the spend badge is a second tray icon carrying the number as its +bitmap, which only the Windows notification area provides. `tray_badge` is compiled out on +Linux, the `set_tray_badge` command reports it as unsupported there, and the frontend hides +the control behind `TRAY_BADGE_SUPPORTED` in `src/lib/platform.ts`. Anything else that is +Windows-only must be cfg-gated the same way, or the ubuntu leg of CI fails on dead code. + +## Architecture + +``` +windows/ +├── src/ React + TypeScript popover UI (runs inside the Tauri webview) +├── src-tauri/ +│ ├── src/ +│ │ ├── main.rs binary entry +│ │ ├── lib.rs tray, window lifecycle, state wiring +│ │ ├── cli.rs argv-validated spawn of the codeburn CLI +│ │ ├── config.rs ~/.config/codeburn/config.json read/write under a lock +│ │ ├── plan.rs Claude OAuth quota (port of mac/.../ClaudeSubscriptionService.swift) +│ │ └── fx.rs Frankfurter fetch + 24h disk cache + [0.0001, 1e6] clamp +│ ├── capabilities/ Tauri v2 permission manifests +│ └── icons/ tray + bundle icons +└── tokens.json shared design tokens (also consumed by mac/ at build time) +``` + +## Prerequisites (Windows) + +```powershell +# Rust +winget install Rustlang.Rustup +rustup target add x86_64-pc-windows-msvc + +# WebView2 Runtime +winget install Microsoft.EdgeWebView2Runtime + +# Microsoft C++ Build Tools (ships with Visual Studio Installer; pick "Desktop development with C++") +``` + +## Prerequisites (macOS / Linux, dev only) + +Tauri builds on macOS and Linux for inner-loop UI iteration. The shipping macOS product is the +Swift app in `../mac/`, so we don't cut a Tauri Mac release. + +```bash +# macOS +brew install rust node + +# Ubuntu / Debian +sudo apt update +sudo apt install -y \ + build-essential curl wget file \ + libwebkit2gtk-4.1-dev \ + libayatana-appindicator3-dev \ + librsvg2-dev \ + libssl-dev \ + libxdo-dev \ + libgtk-3-dev +``` + +## Run the dev server + +```bash +cd windows +npm install +npm run tauri dev +``` + +Under the hood this starts Vite on `localhost:1420`, builds `src-tauri/target/debug/codeburn-menubar`, +and opens a window wired to the dev server with hot reload for the React code. The tray icon +appears at the same time. + +If the codeburn CLI isn't on PATH (dev builds from this monorepo), point the app at your local build: + +```bash +npm --prefix .. run build +CODEBURN_BIN="node $(pwd)/../dist/cli.js" npm run tauri dev +``` + +`CODEBURN_BIN` is validated against a strict allowlist (alphanumerics plus `._/-` and space; +`\ : ( )` also allowed on Windows) before use; anything else falls back to auto-resolution. + +Without `CODEBURN_BIN` the app looks for `codeburn` (`codeburn.cmd` / `codeburn.exe` on Windows) +on the inherited `PATH`, then in the usual npm and node prefixes (`%APPDATA%\npm`, +`%LOCALAPPDATA%\Programs\nodejs`, pnpm, Volta, scoop, `/opt/homebrew/bin`, `~/.npm-global/bin`), +and finally on Windows in the live user and machine `PATH` read from the registry, so a CLI +installed after the tray app was launched is still found. Only absolute directory entries are +considered - empty or relative `PATH` entries are skipped so nothing is ever resolved out of the +current working directory. + +If nothing is found, or `codeburn --version` is older than `MIN_CLI_VERSION` +(`src-tauri/src/cli.rs`), the popover shows a setup screen with the install command and a +"Check again" button. That gate is probed once on mount, before the first payload fetch. + +`MIN_CLI_VERSION` is **0.9.9**: the first release whose `codeburn status --format menubar-json` +accepts `--no-optimize`, which the app's quiet background refreshes always pass. Every payload +field the popover reads (`current.providers`, `current.cacheHitPercent`, `history.daily[].topModels`) +also exists at that version. + +## Refresh policy + +Mirrors `mac/Sources/CodeBurnMenubar/RefreshCadence.swift`: each CLI fetch is a full Node +process, so the cadence follows popover visibility. + +- popover visible: 60 s tick, full fetch (optimize findings included) +- popover hidden: 120 s tick, `today`/`all` only, `--no-optimize` +- on show: immediate refresh when the visible key is older than 60 s + +## Plan / quota + +The Plan pill (visible on the Claude tab, or when Claude is the only detected provider) reads +Claude Code's OAuth credentials from `~/.claude/.credentials.json`, calls +`https://api.anthropic.com/api/oauth/usage`, and stores one snapshot per window under +`~/.cache/codeburn/subscription-snapshots.json` (`CODEBURN_CACHE_DIR` override) so a freshly +reset window can still show last cycle's final. This is the same file format the macOS app +writes. Nothing is logged: the credential blob never leaves the Rust side. + +On a 401 we do **not** call the token refresh endpoint. Claude's refresh token is single-use +and rotates, so spending it would invalidate the token Claude Code itself is holding and break +the user's login. Like `ClaudeCredentialStore.refreshAfter401` on macOS, we re-read Claude's +own credential file for a token it has already rotated, and report a transient failure when +there isn't one yet. + +## Build a production package + +```bash +# Windows (.msi): run from a Windows host +npm run tauri build + +# Linux (experimental): produces .deb, .rpm, .AppImage under src-tauri/target/release/bundle/ +npm run tauri build +``` + +## Security model + +- **Process spawn**: every call into the codeburn CLI goes through `CodeburnCli::fetch_menubar_payload`, + which builds argv explicitly and runs the binary directly (no `sh -c`). `CODEBURN_BIN` is + allowlisted before use. Windows system tools (`reg.exe`, `cmd.exe`) are invoked by absolute + path under `%SystemRoot%\System32` so `CreateProcess`'s current-directory search can never + pick up a planted binary; `claude` is resolved from absolute `PATH` directories the same way. +- **Pipes**: stdout is capped at 20 MB, stderr at 256 KB, total wall time at 60 s. A hung CLI + cannot pin file descriptors or memory. +- **Config writes**: `~/.config/codeburn/config.json` writes run under a POSIX `flock` on + `~/.config/codeburn/.config.lock`. On Windows the same path uses a create-new lock file. Note + that this lock is advisory *between instances of this app only* - the codeburn CLI does not + take it - so it narrows, but does not eliminate, a concurrent-write race. A live holder keeps + its file handle open and Windows will not unlink an open file, so the staleness sweep can only + ever reclaim a lock whose owner is gone (after 30 s). +- **Snapshot writes**: `subscription-snapshots.json` refuses a symlinked target and is written + 0600 on unix, mirroring `mac/Sources/CodeBurnMenubar/Security/SafeFile.swift`. +- **Credentials**: the Plan view reads `~/.claude/.credentials.json` with a 64 KB cap and refuses + symlinks; the access token is only ever sent to the Anthropic usage endpoint over TLS, and the + refresh token is never read or sent at all. +- **FX fetches**: Frankfurter response is parsed as JSON and the rate is clamped to + `[0.0001, 1_000_000]` before it touches displayed numbers. Stale cache preferred over poisoned + fresh data. +- **CSP**: `connect-src` restricted to `self`, `ipc:`, and `https://api.frankfurter.app`. No + inline scripts. + +## CI and release tags + +- `.github/workflows/windows-menubar-ci.yml` runs on any `windows/**` change: `tsc --noEmit`, + `cargo clippy -D warnings` and `cargo test` on windows-latest + ubuntu-latest, plus a release + build smoke on Windows. +- `windows-v*` tag (e.g. `windows-v0.9.20`) triggers + `.github/workflows/release-menubar-windows.yml`; publishes the `.msi` (plus its sha256) to + a "Windows Menubar vX" release. Unsigned for now, so Windows SmartScreen prompts on first run + until a signing cert is in place. +- `codeburn menubar` installs from those assets (`src/menubar-installer.ts`): it pins the tag to + the CLI's own version (`windows-v`), falls back to a scan of the newest `windows-v*` + release carrying both assets, verifies the sha256 before anything executes the file, then runs + `%SystemRoot%\System32\msiexec.exe /i /passive /norestart` and launches the exe named by + the product's Uninstall registry key. Renaming the bundle or the MSI asset breaks that lookup — + `WINDOWS_RELEASE` and `WINDOWS_PRODUCT_NAME` in the installer have to move with it. + +## Pending work + +1. Code signing for the Windows `.msi` to remove the SmartScreen warning. +2. Linux: decide whether to ship at all (the GNOME extension in `../gnome/` covers that + surface today) or promote the ksni tray out of experimental. diff --git a/windows/Scripts/autoinstall/README.md b/windows/Scripts/autoinstall/README.md new file mode 100644 index 00000000..5e81424a --- /dev/null +++ b/windows/Scripts/autoinstall/README.md @@ -0,0 +1,38 @@ +# Unattended Ubuntu install for the CodeBurn dev VM + +This directory contains a cloud-init `user-data` + `meta-data` pair that tells the Ubuntu 24.04 Server installer to configure itself without any user prompts. After it finishes, you reboot into GNOME and run the one-line provisioner. + +Default credentials in `user-data`: **`codeburn` / `codeburn`**. Change them before using anywhere that matters. + +## Build the CIDATA ISO (on your Mac) + +```bash +cd windows/Scripts/autoinstall +hdiutil makehybrid -o codeburn-cidata.iso \ + -hfs -joliet -iso -default-volume-name CIDATA . +``` + +That produces `codeburn-cidata.iso` (around 2 KB) with the two YAML files at the root, labelled `CIDATA`. + +## Hook it into UTM + +1. Create the VM as usual (Virtualize → Linux → Ubuntu Server arm64 ISO). +2. Before first boot, open the VM's Settings → **Drives** → **New Drive** → pick **Removable** → **Import**, and select `codeburn-cidata.iso`. +3. Boot. The Ubuntu installer auto-detects the CIDATA volume, reads the autoinstall config, and runs the install without prompts. Takes 15-20 minutes depending on disk speed. +4. Reboot into the installed system, log in as `codeburn`, then: + + ```bash + bash ~/provision.sh + ``` + + (The autoinstall drops the script to `~/provision.sh`. It installs Rust + Node + the codeburn CLI, clones the repo, and sets up the windows/ npm deps.) + +5. `cd ~/codeburn/windows && npm run tauri dev`. + +## Why not automate the provisioner run too + +cloud-init's `late-commands` runs in the installer environment, which doesn't have a GNOME session for the tray icon to land in. We deliberately stop short of running `npm run tauri dev` from within autoinstall so the tray shows up on your first real login instead of a detached systemd unit. + +## Skipping autoinstall + +If you'd rather click through the Ubuntu installer normally, ignore this directory entirely. The `provision-linux.sh` script in the parent directory works the same way whether the OS was installed unattended or by hand. diff --git a/windows/Scripts/autoinstall/meta-data b/windows/Scripts/autoinstall/meta-data new file mode 100644 index 00000000..576f5acd --- /dev/null +++ b/windows/Scripts/autoinstall/meta-data @@ -0,0 +1,2 @@ +instance-id: codeburn-linux-01 +local-hostname: codeburn-linux diff --git a/windows/Scripts/autoinstall/user-data b/windows/Scripts/autoinstall/user-data new file mode 100644 index 00000000..f4050494 --- /dev/null +++ b/windows/Scripts/autoinstall/user-data @@ -0,0 +1,57 @@ +#cloud-config +# Ubuntu 24.04 LTS Server autoinstall configuration for a CodeBurn desktop dev VM. Mount this +# file as a second virtual disk (CIDATA volume) alongside the Ubuntu Server ISO in UTM and +# the installer runs unattended end to end. Default login: codeburn / codeburn. Change the +# identity block before running in any environment that matters. +autoinstall: + version: 1 + + # Accept the EULA-style prompts without user input. + refresh-installer: + update: yes + + locale: en_US.UTF-8 + keyboard: + layout: us + + # Wire up a default user. Password is `codeburn`; hash generated with `openssl passwd -6`. + # Regenerate the hash if you care about the credentials outside of a throwaway VM. + identity: + hostname: codeburn-linux + username: codeburn + password: "$6$rounds=4096$JrKVZcJ2$F93p8IWyTlZR5p1Trmno/qCnhYI1BnbUUYdf6HsiD.XW4T0I3JtvzH40nWNy9Z1CcJ2X5C6RuzK0bj9WM3x/n." + + ssh: + install-server: yes + allow-pw: yes + + # Install GNOME + the build dependencies Tauri needs so the first login is already ready + # to run `npm run tauri dev` without another apt round trip. + packages: + - ubuntu-desktop-minimal + - build-essential + - curl + - wget + - file + - git + - libwebkit2gtk-4.1-dev + - libayatana-appindicator3-dev + - librsvg2-dev + - libssl-dev + - libxdo-dev + - libgtk-3-dev + - pkg-config + + # Run the provisioner as the new user on first boot. It installs Node + Rust, pulls the + # repo, and runs `npm install` for the desktop app. After the script finishes, logging in + # to GNOME and running `cd ~/codeburn/windows && npm run tauri dev` brings the tray up. + late-commands: + - curtin in-target --target=/target -- bash -lc ' + sudo -iu codeburn bash -lc " + curl -fsSL https://raw.githubusercontent.com/getagentseal/codeburn/main/windows/Scripts/provision-linux.sh \ + -o /home/codeburn/provision.sh + chmod +x /home/codeburn/provision.sh + " + ' + + shutdown: reboot diff --git a/windows/Scripts/provision-linux.sh b/windows/Scripts/provision-linux.sh new file mode 100755 index 00000000..23ba9991 --- /dev/null +++ b/windows/Scripts/provision-linux.sh @@ -0,0 +1,89 @@ +#!/usr/bin/env bash +# One-shot Ubuntu provisioning for the CodeBurn desktop (Tauri) dev environment. +# +# Usage inside a fresh Ubuntu 24.04 LTS Server VM (after `sudo apt install +# ubuntu-desktop-minimal && sudo reboot`, and logging into GNOME): +# +# curl -fsSL https://raw.githubusercontent.com/getagentseal/codeburn/main/windows/Scripts/provision-linux.sh | bash +# +# Or if you cloned the repo manually: `bash windows/Scripts/provision-linux.sh`. +# +# Installs: build toolchain, webkit + appindicator headers, Node 20 LTS, Rust stable, +# the codeburn npm CLI, and this repo. Leaves you one command away from `npm run tauri dev`. + +set -euo pipefail + +REPO_URL="https://github.com/getagentseal/codeburn.git" +BRANCH="feat/tauri-menubar-win-linux" +CHECKOUT="${HOME}/codeburn" + +log() { printf '\033[1;34m▸\033[0m %s\n' "$*"; } +fail() { printf '\033[1;31m✗\033[0m %s\n' "$*" >&2; exit 1; } + +# 1. Platform sanity +[[ "$(uname -s)" == "Linux" ]] || fail "Run me on Linux (detected: $(uname -s))." +if ! command -v apt-get >/dev/null; then + fail "Only apt-based distros supported by this provisioner (Ubuntu, Debian)." +fi + +log "apt update + system build deps" +sudo apt-get update -qq +sudo apt-get install -y \ + build-essential curl wget file git \ + libwebkit2gtk-4.1-dev \ + libayatana-appindicator3-dev \ + librsvg2-dev \ + libssl-dev \ + libxdo-dev \ + libgtk-3-dev \ + pkg-config + +# 2. Node 20 LTS via NodeSource if the distro version is too old. Tauri CLI needs >= 18. +if ! command -v node >/dev/null || [[ "$(node -v | sed 's/v\([0-9]*\).*/\1/')" -lt 18 ]]; then + log "installing Node 20 LTS" + curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - + sudo apt-get install -y nodejs +fi + +# 3. Rust via rustup if not present +if ! command -v cargo >/dev/null; then + log "installing Rust via rustup" + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal + # shellcheck disable=SC1091 + source "$HOME/.cargo/env" +fi + +# 4. codeburn CLI (the Tauri app shells out to this for data) +if ! command -v codeburn >/dev/null; then + log "installing codeburn CLI from npm" + sudo npm install -g codeburn +fi + +# 5. Repo +if [[ -d "${CHECKOUT}/.git" ]]; then + log "updating existing checkout at ${CHECKOUT}" + git -C "${CHECKOUT}" fetch origin + git -C "${CHECKOUT}" checkout "${BRANCH}" + git -C "${CHECKOUT}" pull --ff-only origin "${BRANCH}" +else + log "cloning ${REPO_URL} into ${CHECKOUT}" + git clone --branch "${BRANCH}" "${REPO_URL}" "${CHECKOUT}" +fi + +# 6. npm deps for the desktop app +log "npm install for windows/" +(cd "${CHECKOUT}/windows" && npm install --no-audit --no-fund) + +# 7. Summary + next step +cat <CodeBurn + +

Run npm install && npm run tauri dev from windows/.

+ diff --git a/windows/index.html b/windows/index.html new file mode 100644 index 00000000..44d28a31 --- /dev/null +++ b/windows/index.html @@ -0,0 +1,12 @@ + + + + + + CodeBurn + + +
+ + + diff --git a/windows/package-lock.json b/windows/package-lock.json new file mode 100644 index 00000000..9694bd7c --- /dev/null +++ b/windows/package-lock.json @@ -0,0 +1,2069 @@ +{ + "name": "codeburn-menubar", + "version": "0.9.20", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "codeburn-menubar", + "version": "0.9.20", + "dependencies": { + "@tauri-apps/api": "^2.0.0", + "@tauri-apps/plugin-opener": "^2.0.0", + "@tauri-apps/plugin-shell": "^2.0.0", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@tauri-apps/cli": "^2.0.0", + "@types/react": "^19.0.0", + "@types/react-dom": "^19.0.0", + "@vitejs/plugin-react": "^4.3.0", + "typescript": "^5.6.0", + "vite": "^6.0.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", + "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.28.5", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.0.tgz", + "integrity": "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz", + "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", + "@babel/helper-compilation-targets": "^7.28.6", + "@babel/helper-module-transforms": "^7.28.6", + "@babel/helpers": "^7.28.6", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/traverse": "^7.29.0", + "@babel/types": "^7.29.0", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.1", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz", + "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.0", + "@babel/types": "^7.29.0", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz", + "integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.28.6", + "@babel/helper-validator-option": "^7.27.1", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz", + "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz", + "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.28.6", + "@babel/types": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz", + "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.28.6", + "@babel/helper-validator-identifier": "^7.28.5", + "@babel/traverse": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.28.6.tgz", + "integrity": "sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz", + "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.2.tgz", + "integrity": "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.28.6", + "@babel/types": "^7.29.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz", + "integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.0" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.27.1.tgz", + "integrity": "sha512-6UzkCs+ejGdZ5mFFC/OCUrv028ab2fp1znZmCZjAOBKiBK2jXD1O+BPSfX8X2qjJ75fZBMSnQn3Rq2mrBJK2mw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.27.1.tgz", + "integrity": "sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz", + "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.28.6", + "@babel/parser": "^7.28.6", + "@babel/types": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz", + "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", + "@babel/helper-globals": "^7.28.0", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/types": "^7.29.0", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz", + "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "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/@rolldown/pluginutils": { + "version": "1.0.0-beta.27", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz", + "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.1.tgz", + "integrity": "sha512-d6FinEBLdIiK+1uACUttJKfgZREXrF0Qc2SmLII7W2AD8FfiZ9Wjd+rD/iRuf5s5dWrr1GgwXCvPqOuDquOowA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.60.1.tgz", + "integrity": "sha512-YjG/EwIDvvYI1YvYbHvDz/BYHtkY4ygUIXHnTdLhG+hKIQFBiosfWiACWortsKPKU/+dUwQQCKQM3qrDe8c9BA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.60.1.tgz", + "integrity": "sha512-mjCpF7GmkRtSJwon+Rq1N8+pI+8l7w5g9Z3vWj4T7abguC4Czwi3Yu/pFaLvA3TTeMVjnu3ctigusqWUfjZzvw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.60.1.tgz", + "integrity": "sha512-haZ7hJ1JT4e9hqkoT9R/19XW2QKqjfJVv+i5AGg57S+nLk9lQnJ1F/eZloRO3o9Scy9CM3wQ9l+dkXtcBgN5Ew==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.60.1.tgz", + "integrity": "sha512-czw90wpQq3ZsAVBlinZjAYTKduOjTywlG7fEeWKUA7oCmpA8xdTkxZZlwNJKWqILlq0wehoZcJYfBvOyhPTQ6w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.60.1.tgz", + "integrity": "sha512-KVB2rqsxTHuBtfOeySEyzEOB7ltlB/ux38iu2rBQzkjbwRVlkhAGIEDiiYnO2kFOkJp+Z7pUXKyrRRFuFUKt+g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.60.1.tgz", + "integrity": "sha512-L+34Qqil+v5uC0zEubW7uByo78WOCIrBvci69E7sFASRl0X7b/MB6Cqd1lky/CtcSVTydWa2WZwFuWexjS5o6g==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.60.1.tgz", + "integrity": "sha512-n83O8rt4v34hgFzlkb1ycniJh7IR5RCIqt6mz1VRJD6pmhRi0CXdmfnLu9dIUS6buzh60IvACM842Ffb3xd6Gg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.60.1.tgz", + "integrity": "sha512-Nql7sTeAzhTAja3QXeAI48+/+GjBJ+QmAH13snn0AJSNL50JsDqotyudHyMbO2RbJkskbMbFJfIJKWA6R1LCJQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.60.1.tgz", + "integrity": "sha512-+pUymDhd0ys9GcKZPPWlFiZ67sTWV5UU6zOJat02M1+PiuSGDziyRuI/pPue3hoUwm2uGfxdL+trT6Z9rxnlMA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.60.1.tgz", + "integrity": "sha512-VSvgvQeIcsEvY4bKDHEDWcpW4Yw7BtlKG1GUT4FzBUlEKQK0rWHYBqQt6Fm2taXS+1bXvJT6kICu5ZwqKCnvlQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.60.1.tgz", + "integrity": "sha512-4LqhUomJqwe641gsPp6xLfhqWMbQV04KtPp7/dIp0nzPxAkNY1AbwL5W0MQpcalLYk07vaW9Kp1PBhdpZYYcEw==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.60.1.tgz", + "integrity": "sha512-tLQQ9aPvkBxOc/EUT6j3pyeMD6Hb8QF2BTBnCQWP/uu1lhc9AIrIjKnLYMEroIz/JvtGYgI9dF3AxHZNaEH0rw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.60.1.tgz", + "integrity": "sha512-RMxFhJwc9fSXP6PqmAz4cbv3kAyvD1etJFjTx4ONqFP9DkTkXsAMU4v3Vyc5BgzC+anz7nS/9tp4obsKfqkDHg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.60.1.tgz", + "integrity": "sha512-QKgFl+Yc1eEk6MmOBfRHYF6lTxiiiV3/z/BRrbSiW2I7AFTXoBFvdMEyglohPj//2mZS4hDOqeB0H1ACh3sBbg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.60.1.tgz", + "integrity": "sha512-RAjXjP/8c6ZtzatZcA1RaQr6O1TRhzC+adn8YZDnChliZHviqIjmvFwHcxi4JKPSDAt6Uhf/7vqcBzQJy0PDJg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.60.1.tgz", + "integrity": "sha512-wcuocpaOlaL1COBYiA89O6yfjlp3RwKDeTIA0hM7OpmhR1Bjo9j31G1uQVpDlTvwxGn2nQs65fBFL5UFd76FcQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.60.1.tgz", + "integrity": "sha512-77PpsFQUCOiZR9+LQEFg9GClyfkNXj1MP6wRnzYs0EeWbPcHs02AXu4xuUbM1zhwn3wqaizle3AEYg5aeoohhg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.60.1.tgz", + "integrity": "sha512-5cIATbk5vynAjqqmyBjlciMJl1+R/CwX9oLk/EyiFXDWd95KpHdrOJT//rnUl4cUcskrd0jCCw3wpZnhIHdD9w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.60.1.tgz", + "integrity": "sha512-cl0w09WsCi17mcmWqqglez9Gk8isgeWvoUZ3WiJFYSR3zjBQc2J5/ihSjpl+VLjPqjQ/1hJRcqBfLjssREQILw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.60.1.tgz", + "integrity": "sha512-4Cv23ZrONRbNtbZa37mLSueXUCtN7MXccChtKpUnQNgF010rjrjfHx3QxkS2PI7LqGT5xXyYs1a7LbzAwT0iCA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.60.1.tgz", + "integrity": "sha512-i1okWYkA4FJICtr7KpYzFpRTHgy5jdDbZiWfvny21iIKky5YExiDXP+zbXzm3dUcFpkEeYNHgQ5fuG236JPq0g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.60.1.tgz", + "integrity": "sha512-u09m3CuwLzShA0EYKMNiFgcjjzwqtUMLmuCJLeZWjjOYA3IT2Di09KaxGBTP9xVztWyIWjVdsB2E9goMjZvTQg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.60.1.tgz", + "integrity": "sha512-k+600V9Zl1CM7eZxJgMyTUzmrmhB/0XZnF4pRypKAlAgxmedUA+1v9R+XOFv56W4SlHEzfeMtzujLJD22Uz5zg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.60.1.tgz", + "integrity": "sha512-lWMnixq/QzxyhTV6NjQJ4SFo1J6PvOX8vUx5Wb4bBPsEb+8xZ89Bz6kOXpfXj9ak9AHTQVQzlgzBEc1SyM27xQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@tauri-apps/api": { + "version": "2.10.1", + "resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.10.1.tgz", + "integrity": "sha512-hKL/jWf293UDSUN09rR69hrToyIXBb8CjGaWC7gfinvnQrBVvnLr08FeFi38gxtugAVyVcTa5/FD/Xnkb1siBw==", + "license": "Apache-2.0 OR MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/tauri" + } + }, + "node_modules/@tauri-apps/cli": { + "version": "2.10.1", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.10.1.tgz", + "integrity": "sha512-jQNGF/5quwORdZSSLtTluyKQ+o6SMa/AUICfhf4egCGFdMHqWssApVgYSbg+jmrZoc8e1DscNvjTnXtlHLS11g==", + "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.10.1", + "@tauri-apps/cli-darwin-x64": "2.10.1", + "@tauri-apps/cli-linux-arm-gnueabihf": "2.10.1", + "@tauri-apps/cli-linux-arm64-gnu": "2.10.1", + "@tauri-apps/cli-linux-arm64-musl": "2.10.1", + "@tauri-apps/cli-linux-riscv64-gnu": "2.10.1", + "@tauri-apps/cli-linux-x64-gnu": "2.10.1", + "@tauri-apps/cli-linux-x64-musl": "2.10.1", + "@tauri-apps/cli-win32-arm64-msvc": "2.10.1", + "@tauri-apps/cli-win32-ia32-msvc": "2.10.1", + "@tauri-apps/cli-win32-x64-msvc": "2.10.1" + } + }, + "node_modules/@tauri-apps/cli-darwin-arm64": { + "version": "2.10.1", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.10.1.tgz", + "integrity": "sha512-Z2OjCXiZ+fbYZy7PmP3WRnOpM9+Fy+oonKDEmUE6MwN4IGaYqgceTjwHucc/kEEYZos5GICve35f7ZiizgqEnQ==", + "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.10.1", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.10.1.tgz", + "integrity": "sha512-V/irQVvjPMGOTQqNj55PnQPVuH4VJP8vZCN7ajnj+ZS8Kom1tEM2hR3qbbIRoS3dBKs5mbG8yg1WC+97dq17Pw==", + "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.10.1", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.10.1.tgz", + "integrity": "sha512-Hyzwsb4VnCWKGfTw+wSt15Z2pLw2f0JdFBfq2vHBOBhvg7oi6uhKiF87hmbXOBXUZaGkyRDkCHsdzJcIfoJC2w==", + "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.10.1", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.10.1.tgz", + "integrity": "sha512-OyOYs2t5GkBIvyWjA1+h4CZxTcdz1OZPCWAPz5DYEfB0cnWHERTnQ/SLayQzncrT0kwRoSfSz9KxenkyJoTelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-arm64-musl": { + "version": "2.10.1", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.10.1.tgz", + "integrity": "sha512-MIj78PDDGjkg3NqGptDOGgfXks7SYJwhiMh8SBoZS+vfdz7yP5jN18bNaLnDhsVIPARcAhE1TlsZe/8Yxo2zqg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-riscv64-gnu": { + "version": "2.10.1", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.10.1.tgz", + "integrity": "sha512-X0lvOVUg8PCVaoEtEAnpxmnkwlE1gcMDTqfhbefICKDnOTJ5Est3qL0SrWxizDackIOKBcvtpejrSiVpuJI1kw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-x64-gnu": { + "version": "2.10.1", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.10.1.tgz", + "integrity": "sha512-2/12bEzsJS9fAKybxgicCDFxYD1WEI9kO+tlDwX5znWG2GwMBaiWcmhGlZ8fi+DMe9CXlcVarMTYc0L3REIRxw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-x64-musl": { + "version": "2.10.1", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.10.1.tgz", + "integrity": "sha512-Y8J0ZzswPz50UcGOFuXGEMrxbjwKSPgXftx5qnkuMs2rmwQB5ssvLb6tn54wDSYxe7S6vlLob9vt0VKuNOaCIQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-win32-arm64-msvc": { + "version": "2.10.1", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.10.1.tgz", + "integrity": "sha512-iSt5B86jHYAPJa/IlYw++SXtFPGnWtFJriHn7X0NFBVunF6zu9+/zOn8OgqIWSl8RgzhLGXQEEtGBdR4wzpVgg==", + "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.10.1", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.10.1.tgz", + "integrity": "sha512-gXyxgEzsFegmnWywYU5pEBURkcFN/Oo45EAwvZrHMh+zUSEAvO5E8TXsgPADYm31d1u7OQU3O3HsYfVBf2moHw==", + "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.10.1", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.10.1.tgz", + "integrity": "sha512-6Cn7YpPFwzChy0ERz6djKEmUehWrYlM+xTaNzGPgZocw3BD7OfwfWHKVWxXzdjEW2KfKkHddfdxK1XXTYqBRLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/plugin-opener": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-opener/-/plugin-opener-2.5.3.tgz", + "integrity": "sha512-CCcUltXMOfUEArbf3db3kCE7Ggy1ExBEBl51Ko2ODJ6GDYHRp1nSNlQm5uNCFY5k7/ufaK5Ib3Du/Zir19IYQQ==", + "license": "MIT OR Apache-2.0", + "dependencies": { + "@tauri-apps/api": "^2.8.0" + } + }, + "node_modules/@tauri-apps/plugin-shell": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-shell/-/plugin-shell-2.3.5.tgz", + "integrity": "sha512-jewtULhiQ7lI7+owCKAjc8tYLJr92U16bPOeAa472LHJdgaibLP83NcfAF2e+wkEcA53FxKQAZ7byDzs2eeizg==", + "license": "MIT OR Apache-2.0", + "dependencies": { + "@tauri-apps/api": "^2.10.1" + } + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "19.2.14", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz", + "integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.2.3", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz", + "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.2.0" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz", + "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.28.0", + "@babel/plugin-transform-react-jsx-self": "^7.27.1", + "@babel/plugin-transform-react-jsx-source": "^7.27.1", + "@rolldown/pluginutils": "1.0.0-beta.27", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.17.0" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.10.19", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.19.tgz", + "integrity": "sha512-qCkNLi2sfBOn8XhZQ0FXsT1Ki/Yo5P90hrkRamVFRS7/KV9hpfA4HkoWNU152+8w0zPjnxo5psx5NL3PSGgv5g==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.28.2", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz", + "integrity": "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.10.12", + "caniuse-lite": "^1.0.30001782", + "electron-to-chromium": "^1.5.328", + "node-releases": "^2.0.36", + "update-browserslist-db": "^1.2.3" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001788", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001788.tgz", + "integrity": "sha512-6q8HFp+lOQtcf7wBK+uEenxymVWkGKkjFpCvw5W25cmMwEDU45p1xQFBQv8JDlMMry7eNxyBaR+qxgmTUZkIRQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.340", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.340.tgz", + "integrity": "sha512-908qahOGocRMinT2nM3ajCEM99H4iPdv84eagPP3FfZy/1ZGeOy2CZYzjhms81ckOPCXPlW7LkY4XpxD8r1DrA==", + "dev": true, + "license": "ISC" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "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/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "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/node-releases": { + "version": "2.0.37", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.37.tgz", + "integrity": "sha512-1h5gKZCF+pO/o3Iqt5Jp7wc9rH3eJJ0+nh/CIoiRwjRxde/hAHyLPXYN4V3CqKAbiZPSeJFSWHmJsbkicta0Eg==", + "dev": true, + "license": "MIT" + }, + "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.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.10", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.10.tgz", + "integrity": "sha512-pMMHxBOZKFU6HgAZ4eyGnwXF/EvPGGqUr0MnZ5+99485wwW41kW91A4LOGxSHhgugZmSChL5AlElNdwlNgcnLQ==", + "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.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "19.2.5", + "resolved": "https://registry.npmjs.org/react/-/react-19.2.5.tgz", + "integrity": "sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.2.5", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.5.tgz", + "integrity": "sha512-J5bAZz+DXMMwW/wV3xzKke59Af6CHY7G4uYLN1OvBcKEsWOs4pQExj86BBKamxl/Ik5bx9whOrvBlSDfWzgSag==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.27.0" + }, + "peerDependencies": { + "react": "^19.2.5" + } + }, + "node_modules/react-refresh": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz", + "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rollup": { + "version": "4.60.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.1.tgz", + "integrity": "sha512-VmtB2rFU/GroZ4oL8+ZqXgSA38O6GR8KSIvWmEFv63pQ0G6KaBH9s07PO8XTXP4vI+3UJUEypOfjkGfmSBBR0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.60.1", + "@rollup/rollup-android-arm64": "4.60.1", + "@rollup/rollup-darwin-arm64": "4.60.1", + "@rollup/rollup-darwin-x64": "4.60.1", + "@rollup/rollup-freebsd-arm64": "4.60.1", + "@rollup/rollup-freebsd-x64": "4.60.1", + "@rollup/rollup-linux-arm-gnueabihf": "4.60.1", + "@rollup/rollup-linux-arm-musleabihf": "4.60.1", + "@rollup/rollup-linux-arm64-gnu": "4.60.1", + "@rollup/rollup-linux-arm64-musl": "4.60.1", + "@rollup/rollup-linux-loong64-gnu": "4.60.1", + "@rollup/rollup-linux-loong64-musl": "4.60.1", + "@rollup/rollup-linux-ppc64-gnu": "4.60.1", + "@rollup/rollup-linux-ppc64-musl": "4.60.1", + "@rollup/rollup-linux-riscv64-gnu": "4.60.1", + "@rollup/rollup-linux-riscv64-musl": "4.60.1", + "@rollup/rollup-linux-s390x-gnu": "4.60.1", + "@rollup/rollup-linux-x64-gnu": "4.60.1", + "@rollup/rollup-linux-x64-musl": "4.60.1", + "@rollup/rollup-openbsd-x64": "4.60.1", + "@rollup/rollup-openharmony-arm64": "4.60.1", + "@rollup/rollup-win32-arm64-msvc": "4.60.1", + "@rollup/rollup-win32-ia32-msvc": "4.60.1", + "@rollup/rollup-win32-x64-gnu": "4.60.1", + "@rollup/rollup-win32-x64-msvc": "4.60.1", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", + "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.16", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz", + "integrity": "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==", + "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/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/vite": { + "version": "6.4.2", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.2.tgz", + "integrity": "sha512-2N/55r4JDJ4gdrCvGgINMy+HH3iRpNIz8K6SFwVsA+JbQScLiC+clmAxBgwiSPgcG9U15QmvqCGWzMbqda5zGQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "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/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + } + } +} diff --git a/windows/package.json b/windows/package.json new file mode 100644 index 00000000..bbf2b50d --- /dev/null +++ b/windows/package.json @@ -0,0 +1,28 @@ +{ + "name": "codeburn-menubar", + "private": true, + "version": "0.9.20", + "description": "CodeBurn menubar (tray) app for Windows, with experimental Linux support. Shares design tokens with the native macOS app under mac/.", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc --noEmit && vite build", + "preview": "vite preview", + "tauri": "tauri" + }, + "dependencies": { + "@tauri-apps/api": "^2.0.0", + "@tauri-apps/plugin-opener": "^2.0.0", + "@tauri-apps/plugin-shell": "^2.0.0", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@tauri-apps/cli": "^2.0.0", + "@types/react": "^19.0.0", + "@types/react-dom": "^19.0.0", + "@vitejs/plugin-react": "^4.3.0", + "typescript": "^5.6.0", + "vite": "^6.0.0" + } +} diff --git a/windows/src-tauri/Cargo.lock b/windows/src-tauri/Cargo.lock new file mode 100644 index 00000000..18765ad9 --- /dev/null +++ b/windows/src-tauri/Cargo.lock @@ -0,0 +1,6066 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix", +] + +[[package]] +name = "async-recursion" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" +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 = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2", +] + +[[package]] +name = "blocking" +version = "1.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "brotli" +version = "8.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[package]] +name = "bytemuck" +version = "1.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +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.11.1", + "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.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e629a66d692cb9ff1a1c664e41771b3dcaf961985a9774c0eb0bd1b51cf60a48" +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.18", +] + +[[package]] +name = "cargo_toml" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "374b7c592d9c00c1f4972ea58390ac6b18cbb6ab79011f3bdc90a0b82ca06b77" +dependencies = [ + "serde", + "toml 0.9.12+spec-1.1.0", +] + +[[package]] +name = "cc" +version = "1.2.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43c5703da9466b66a946814e1adf53ea2c90f10063b86290cc9eb67ce3478a20" +dependencies = [ + "find-msvc-tools", + "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.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f" +dependencies = [ + "byteorder", + "fnv", + "uuid", +] + +[[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.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "chrono" +version = "0.4.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" +dependencies = [ + "iana-time-zone", + "num-traits", + "serde", + "windows-link 0.2.1", +] + +[[package]] +name = "codeburn-menubar" +version = "0.9.20" +dependencies = [ + "anyhow", + "dirs 5.0.1", + "fontdue", + "ksni", + "png 0.17.16", + "reqwest 0.12.28", + "serde", + "serde_json", + "tauri", + "tauri-build", + "tauri-plugin-opener", + "tauri-plugin-shell", + "thiserror 1.0.69", + "tokio", + "windows-sys 0.59.0", +] + +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + +[[package]] +name = "cookie" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" +dependencies = [ + "time", + "version_check", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +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.11.1", + "core-foundation", + "core-graphics-types", + "foreign-types", + "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.11.1", + "core-foundation", + "libc", +] + +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "cssparser" +version = "0.29.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f93d03419cb5950ccfd3daf3ff1c7a36ace64609a1a8746d493df1ca0afde0fa" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "matches", + "phf 0.10.1", + "proc-macro2", + "quote", + "smallvec", + "syn 1.0.109", +] + +[[package]] +name = "cssparser" +version = "0.36.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dae61cf9c0abb83bd659dab65b7e4e38d8236824c85f0f804f173567bda257d2" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "phf 0.13.1", + "smallvec", +] + +[[package]] +name = "cssparser-macros" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331" +dependencies = [ + "quote", + "syn 2.0.117", +] + +[[package]] +name = "ctor" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a2785755761f3ddc1492979ce1e48d2c00d09311c39e4466429188f3dd6501" +dependencies = [ + "quote", + "syn 2.0.117", +] + +[[package]] +name = "darling" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.117", +] + +[[package]] +name = "darling_macro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "powerfmt", + "serde_core", +] + +[[package]] +name = "derive_more" +version = "0.99.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6edb4b64a43d977b8e99788fe3a04d483834fba1215a7e02caa415b626497f7f" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.117", +] + +[[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.117", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys 0.4.1", +] + +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys 0.5.0", +] + +[[package]] +name = "dirs-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users 0.4.6", + "windows-sys 0.48.0", +] + +[[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 0.5.2", + "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.11.1", + "block2", + "libc", + "objc2", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[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.117", +] + +[[package]] +name = "dom_query" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521e380c0c8afb8d9a1e83a1822ee03556fc3e3e7dbc1fd30be14e37f9cb3f89" +dependencies = [ + "bit-set", + "cssparser 0.36.0", + "foldhash 0.2.0", + "html5ever 0.38.0", + "precomputed-hash", + "selectors 0.36.1", + "tendril 0.5.0", +] + +[[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.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63a1d0de4f2249aa0ff5884d7080814f446bb241a559af6c170a41e878ed2d45" +dependencies = [ + "cc", + "memchr", + "rustc_version", + "toml 0.9.12+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 = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[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.117", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "erased-serde" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "event-listener" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +dependencies = [ + "concurrent-queue", + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "flate2" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "fontdue" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7894823fa221401399e2598f8b63f81ac77ff5c63248b7656779bff1632d7d3d" +dependencies = [ + "hashbrown 0.15.5", + "ttf-parser", +] + +[[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", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843" +dependencies = [ + "mac", + "new_debug_unreachable", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-executor" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "fxhash" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" +dependencies = [ + "byteorder", +] + +[[package]] +name = "gdk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691" +dependencies = [ + "cairo-rs", + "gdk-pixbuf", + "gdk-sys", + "gio", + "glib", + "libc", + "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.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.9.0+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "wasip2", + "wasip3", +] + +[[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.11.1", + "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.117", +] + +[[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.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" + +[[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.117", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "html5ever" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b7410cae13cbc75623c98ac4cbfd1f0bedddf3227afc24f370cf0f50a44a11c" +dependencies = [ + "log", + "mac", + "markup5ever 0.14.1", + "match_token", +] + +[[package]] +name = "html5ever" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1054432bae2f14e0061e33d23402fbaa67a921d319d56adc6bcf887ddad1cbc2" +dependencies = [ + "log", + "markup5ever 0.38.0", +] + +[[package]] +name = "http" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "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 0.62.2", +] + +[[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.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e795dff5605e0f04bff85ca41b51a96b83e80b281e96231bcaaf1ac35103371" +dependencies = [ + "byteorder", + "png 0.17.16", +] + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png 0.18.1", +] + +[[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.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.0", + "serde", + "serde_core", +] + +[[package]] +name = "infer" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a588916bfdfd92e71cacef98a63d9b1f0d74d6599980d11894290e7ddefffcf7" +dependencies = [ + "cfb", +] + +[[package]] +name = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + +[[package]] +name = "iri-string" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25e659a4bb38e810ebc252e53b5814ff908a8c58c2a9ce2fae1bbec24cbf4e20" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "is-docker" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" +dependencies = [ + "once_cell", +] + +[[package]] +name = "is-wsl" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" +dependencies = [ + "is-docker", + "once_cell", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "javascriptcore-rs" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc" +dependencies = [ + "bitflags 1.3.2", + "glib", + "javascriptcore-rs-sys", +] + +[[package]] +name = "javascriptcore-rs-sys" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys 0.3.1", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "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.117", +] + +[[package]] +name = "js-sys" +version = "0.3.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca" +dependencies = [ + "cfg-if", + "futures-util", + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "json-patch" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863726d7afb6bc2590eeff7135d923545e5e964f004c2ccf8716c25e70a86f08" +dependencies = [ + "jsonptr", + "serde", + "serde_json", + "thiserror 1.0.69", +] + +[[package]] +name = "jsonptr" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dea2b27dd239b2556ed7a25ba842fe47fd602e7fc7433c2a8d6106d4d9edd70" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "keyboard-types" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a" +dependencies = [ + "bitflags 2.11.1", + "serde", + "unicode-segmentation", +] + +[[package]] +name = "ksni" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7ca513d0be42df5edb485af9f44a12b2cb85af773d91c27dc796d1c58b78edc" +dependencies = [ + "futures-util", + "pastey", + "serde", + "tokio", + "zbus", +] + +[[package]] +name = "kuchikiki" +version = "0.8.8-speedreader" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02cb977175687f33fa4afa0c95c112b987ea1443e5a51c8f8ff27dc618270cc2" +dependencies = [ + "cssparser 0.29.6", + "html5ever 0.29.1", + "indexmap 2.14.0", + "selectors 0.24.0", +] + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libappindicator" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a" +dependencies = [ + "glib", + "gtk", + "gtk-sys", + "libappindicator-sys", + "log", +] + +[[package]] +name = "libappindicator-sys" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf" +dependencies = [ + "gtk-sys", + "libloading", + "once_cell", +] + +[[package]] +name = "libc" +version = "0.2.185" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f" + +[[package]] +name = "libloading" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +dependencies = [ + "cfg-if", + "winapi", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e02f3bb43d335493c96bf3fd3a321600bf6bd07ed34bc64118e9293bdffea46c" +dependencies = [ + "libc", +] + +[[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.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[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.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "mac" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" + +[[package]] +name = "markup5ever" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7a7213d12e1864c0f002f52c2923d4556935a43dec5e71355c2760e0f6e7a18" +dependencies = [ + "log", + "phf 0.11.3", + "phf_codegen 0.11.3", + "string_cache 0.8.9", + "string_cache_codegen 0.5.4", + "tendril 0.4.3", +] + +[[package]] +name = "markup5ever" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8983d30f2915feeaaab2d6babdd6bc7e9ed1a00b66b5e6d74df19aa9c0e91862" +dependencies = [ + "log", + "tendril 0.5.0", + "web_atoms", +] + +[[package]] +name = "match_token" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88a9689d8d44bf9964484516275f5cd4c9b59457a6940c1d5d0ecbb94510a36b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "matches" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5" + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[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.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[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 = "mio" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" +dependencies = [ + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", + "windows-sys 0.61.2", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "muda" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c9fec5a4e89860383d778d10563a605838f8f0b2f9303868937e5ff32e86177" +dependencies = [ + "crossbeam-channel", + "dpi", + "gtk", + "keyboard-types", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "once_cell", + "png 0.17.16", + "serde", + "thiserror 2.0.18", + "windows-sys 0.60.2", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.11.1", + "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 = "nodrop" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb" + +[[package]] +name = "num-conv" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "objc2" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f" +dependencies = [ + "objc2-encode", + "objc2-exception-helper", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.11.1", + "block2", + "objc2", + "objc2-core-foundation", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.11.1", + "dispatch2", + "objc2", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.11.1", + "dispatch2", + "objc2", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[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.11.1", + "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.11.1", + "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.11.1", + "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.11.1", + "objc2", + "objc2-core-foundation", + "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.11.1", + "block2", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "open" +version = "5.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43bb73a7fa3799b198970490a51174027ba0d4ec504b03cd08caf513d40024bc" +dependencies = [ + "dunce", + "is-wsl", + "libc", + "pathdiff", +] + +[[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" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "os_pipe" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[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 0.2.1", +] + +[[package]] +name = "pastey" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b867cad97c0791bbd3aaa6472142568c6c9e8f71937e98379f584cfb0cf35bec" + +[[package]] +name = "pathdiff" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3" + +[[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.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3dfb61232e34fcb633f43d12c58f83c1df82962dcdfa565a4e866ffc17dafe12" +dependencies = [ + "phf_shared 0.8.0", +] + +[[package]] +name = "phf" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259" +dependencies = [ + "phf_macros 0.10.0", + "phf_shared 0.10.0", + "proc-macro-hack", +] + +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros 0.11.3", + "phf_shared 0.11.3", +] + +[[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_codegen" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbffee61585b0411840d3ece935cce9cb6321f01c45477d30066498cd5e1a815" +dependencies = [ + "phf_generator 0.8.0", + "phf_shared 0.8.0", +] + +[[package]] +name = "phf_codegen" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", +] + +[[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_generator" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17367f0cc86f2d25802b2c26ee58a7b23faeccf78a396094c13dced0d0182526" +dependencies = [ + "phf_shared 0.8.0", + "rand 0.7.3", +] + +[[package]] +name = "phf_generator" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6" +dependencies = [ + "phf_shared 0.10.0", + "rand 0.8.6", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared 0.11.3", + "rand 0.8.6", +] + +[[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_macros" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58fdf3184dd560f160dd73922bea2d5cd6e8f064bf4b13110abd81b03697b4e0" +dependencies = [ + "phf_generator 0.10.0", + "phf_shared 0.10.0", + "proc-macro-hack", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[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.117", +] + +[[package]] +name = "phf_shared" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c00cf8b9eafe68dde5e9eaa2cef8ee84a9336a47d566ec55ca16589633b65af7" +dependencies = [ + "siphasher 0.3.11", +] + +[[package]] +name = "phf_shared" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096" +dependencies = [ + "siphasher 0.3.11", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher 1.0.2", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher 1.0.2", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + +[[package]] +name = "pkg-config" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + +[[package]] +name = "plist" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "740ebea15c5d1428f910cd1a5f52cebf8d25006245ed8ade92702f4943d91e07" +dependencies = [ + "base64 0.22.1", + "indexmap 2.14.0", + "quick-xml", + "serde", + "time", +] + +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide", +] + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.11.1", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.117", +] + +[[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.11+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-macro-hack" +version = "0.5.20+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-xml" +version = "0.38.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c" +dependencies = [ + "memchr", +] + +[[package]] +name = "quinn" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror 2.0.18", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" +dependencies = [ + "bytes", + "getrandom 0.3.4", + "lru-slab", + "rand 0.9.4", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.18", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.60.2", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +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 = "rand" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" +dependencies = [ + "getrandom 0.1.16", + "libc", + "rand_chacha 0.2.2", + "rand_core 0.5.1", + "rand_hc", + "rand_pcg", +] + +[[package]] +name = "rand" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" +dependencies = [ + "ppv-lite86", + "rand_core 0.5.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" +dependencies = [ + "getrandom 0.1.16", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_hc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" +dependencies = [ + "rand_core 0.5.1", +] + +[[package]] +name = "rand_pcg" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16abd0c1b639e9eb4d7c50c0b8100b0d0f849be2349829c740fe8e6eb4816429" +dependencies = [ + "rand_core 0.5.1", +] + +[[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.11.1", +] + +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom 0.2.17", + "libredox", + "thiserror 1.0.69", +] + +[[package]] +name = "redox_users" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" +dependencies = [ + "getrandom 0.2.17", + "libredox", + "thiserror 2.0.18", +] + +[[package]] +name = "ref-cast" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "regex" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "reqwest" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab3f43e3283ab1488b624b44b0e988d0acea0b3214e694730a055cb6b2efa801" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" + +[[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.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags 2.11.1", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69f9466fb2c14ea04357e91413efb882e2a6d4a406e625449bc0a5d360d53a21" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8279bb85272c9f10811ae6a6c547ff594d6a7f3c6c6b02ee9726d1d0dcfcdd06" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[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 = "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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc" +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.117", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "selectors" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c37578180969d00692904465fb7f6b3d50b9a2b952b87c23d0e2e5cb5013416" +dependencies = [ + "bitflags 1.3.2", + "cssparser 0.29.6", + "derive_more 0.99.20", + "fxhash", + "log", + "phf 0.8.0", + "phf_codegen 0.8.0", + "precomputed-hash", + "servo_arc 0.2.0", + "smallvec", +] + +[[package]] +name = "selectors" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5d9c0c92a92d33f08817311cf3f2c29a3538a8240e94a6a3c622ce652d7e00c" +dependencies = [ + "bitflags 2.11.1", + "cssparser 0.36.0", + "derive_more 2.1.1", + "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 = "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.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +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.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[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.117", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_repr" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_with" +version = "3.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd5414fad8e6907dbdd5bc441a50ae8d6e26151a03b1de04d89a5576de61d01f" +dependencies = [ + "base64 0.22.1", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.14.0", + "schemars 0.9.0", + "schemars 1.2.1", + "serde_core", + "serde_json", + "serde_with_macros", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "3.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3db8978e608f1fe7357e211969fd9abdcae80bac1ba7a3369bb7eb6b404eb65" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[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.117", +] + +[[package]] +name = "servo_arc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d52aa42f8fdf0fed91e5ce7f23d8138441002fa31dca008acf47e6fd4721f741" +dependencies = [ + "nodrop", + "stable_deref_trait", +] + +[[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 = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shared_child" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e362d9935bc50f019969e2f9ecd66786612daae13e8f277be7bfb66e8bed3f7" +dependencies = [ + "libc", + "sigchld", + "windows-sys 0.60.2", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "sigchld" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47106eded3c154e70176fc83df9737335c94ce22f821c32d17ed1db1f83badb1" +dependencies = [ + "libc", + "os_pipe", + "signal-hook", +] + +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" + +[[package]] +name = "siphasher" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" + +[[package]] +name = "siphasher" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2aa850e253778c88a04c3d7323b043aeda9d3e30d5971937c1855769763678e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "socket2" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" +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 = "string_cache" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared 0.11.3", + "precomputed-hash", + "serde", +] + +[[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_codegen" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c711928715f1fe0fe509c53b43e993a9a557babc2d0a3567d0a3006f1ac931a0" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", + "proc-macro2", + "quote", +] + +[[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 = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "swift-rs" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4057c98e2e852d51fdcfca832aac7b571f6b351ad159f9eda5db1655f8d0c4d7" +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", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +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.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[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.34.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9103edf55f2da3c82aea4c7fab7c4241032bfeea0e71fa557d98e00e7ce7cc20" +dependencies = [ + "bitflags 2.11.1", + "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", + "once_cell", + "parking_lot", + "raw-window-handle", + "tao-macros", + "unicode-segmentation", + "url", + "windows", + "windows-core 0.61.2", + "windows-version", + "x11-dl", +] + +[[package]] +name = "tao-macros" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4e16beb8b2ac17db28eab8bca40e62dbfbb34c0fcdc6d9826b11b7b5d047dfd" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[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.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da77cc00fb9028caf5b5d4650f75e31f1ef3693459dfca7f7e506d1ecef0ba2d" +dependencies = [ + "anyhow", + "bytes", + "cookie", + "dirs 6.0.0", + "dunce", + "embed_plist", + "getrandom 0.3.4", + "glob", + "gtk", + "heck 0.5.0", + "http", + "image", + "jni", + "libc", + "log", + "mime", + "muda", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "objc2-ui-kit", + "objc2-web-kit", + "percent-encoding", + "plist", + "raw-window-handle", + "reqwest 0.13.2", + "serde", + "serde_json", + "serde_repr", + "serialize-to-javascript", + "swift-rs", + "tauri-build", + "tauri-macros", + "tauri-runtime", + "tauri-runtime-wry", + "tauri-utils", + "thiserror 2.0.18", + "tokio", + "tray-icon", + "url", + "webkit2gtk", + "webview2-com", + "window-vibrancy", + "windows", +] + +[[package]] +name = "tauri-build" +version = "2.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bbc990d1dbf57a8e1c7fa2327f2a614d8b757805603c1b9ba5c81bade09fd4d" +dependencies = [ + "anyhow", + "cargo_toml", + "dirs 6.0.0", + "glob", + "heck 0.5.0", + "json-patch", + "schemars 0.8.22", + "semver", + "serde", + "serde_json", + "tauri-utils", + "tauri-winres", + "toml 0.9.12+spec-1.1.0", + "walkdir", +] + +[[package]] +name = "tauri-codegen" +version = "2.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a24476afd977c5d5d169f72425868613d82747916dd29e0a357c84c4bd6d29" +dependencies = [ + "base64 0.22.1", + "brotli", + "ico", + "json-patch", + "plist", + "png 0.17.16", + "proc-macro2", + "quote", + "semver", + "serde", + "serde_json", + "sha2", + "syn 2.0.117", + "tauri-utils", + "thiserror 2.0.18", + "time", + "url", + "uuid", + "walkdir", +] + +[[package]] +name = "tauri-macros" +version = "2.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d39b349a98dadaffebb73f0a40dcd1f23c999211e5a2e744403db384d0c33de7" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.117", + "tauri-codegen", + "tauri-utils", +] + +[[package]] +name = "tauri-plugin" +version = "2.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddde7d51c907b940fb573006cdda9a642d6a7c8153657e88f8a5c3c9290cd4aa" +dependencies = [ + "anyhow", + "glob", + "plist", + "schemars 0.8.22", + "serde", + "serde_json", + "tauri-utils", + "toml 0.9.12+spec-1.1.0", + "walkdir", +] + +[[package]] +name = "tauri-plugin-opener" +version = "2.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc624469b06f59f5a29f874bbc61a2ed737c0f9c23ef09855a292c389c42e83f" +dependencies = [ + "dunce", + "glob", + "objc2-app-kit", + "objc2-foundation", + "open", + "schemars 0.8.22", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "thiserror 2.0.18", + "url", + "windows", + "zbus", +] + +[[package]] +name = "tauri-plugin-shell" +version = "2.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8457dbf9e2bab1edd8df22bb2c20857a59a9868e79cb3eac5ed639eec4d0c73b" +dependencies = [ + "encoding_rs", + "log", + "open", + "os_pipe", + "regex", + "schemars 0.8.22", + "serde", + "serde_json", + "shared_child", + "tauri", + "tauri-plugin", + "thiserror 2.0.18", + "tokio", +] + +[[package]] +name = "tauri-runtime" +version = "2.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2826d79a3297ed08cd6ea7f412644ef58e32969504bc4fbd8d7dbeabc4445ea2" +dependencies = [ + "cookie", + "dpi", + "gtk", + "http", + "jni", + "objc2", + "objc2-ui-kit", + "objc2-web-kit", + "raw-window-handle", + "serde", + "serde_json", + "tauri-utils", + "thiserror 2.0.18", + "url", + "webkit2gtk", + "webview2-com", + "windows", +] + +[[package]] +name = "tauri-runtime-wry" +version = "2.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11ea2e6f801d275fdd890d6c9603736012742a1c33b96d0db788c9cdebf7f9e" +dependencies = [ + "gtk", + "http", + "jni", + "log", + "objc2", + "objc2-app-kit", + "once_cell", + "percent-encoding", + "raw-window-handle", + "softbuffer", + "tao", + "tauri-runtime", + "tauri-utils", + "url", + "webkit2gtk", + "webview2-com", + "windows", + "wry", +] + +[[package]] +name = "tauri-utils" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "219a1f983a2af3653f75b5747f76733b0da7ff03069c7a41901a5eb3ace4557d" +dependencies = [ + "anyhow", + "brotli", + "cargo_metadata", + "ctor", + "dunce", + "glob", + "html5ever 0.29.1", + "http", + "infer", + "json-patch", + "kuchikiki", + "log", + "memchr", + "phf 0.11.3", + "proc-macro2", + "quote", + "regex", + "schemars 0.8.22", + "semver", + "serde", + "serde-untagged", + "serde_json", + "serde_with", + "swift-rs", + "thiserror 2.0.18", + "toml 0.9.12+spec-1.1.0", + "url", + "urlpattern", + "uuid", + "walkdir", +] + +[[package]] +name = "tauri-winres" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1087b111fe2b005e42dbdc1990fc18593234238d47453b0c99b7de1c9ab2c1e0" +dependencies = [ + "dunce", + "embed-resource", + "toml 0.9.12+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.2", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "tendril" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0" +dependencies = [ + "futf", + "mac", + "utf-8", +] + +[[package]] +name = "tendril" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4790fc369d5a530f4b544b094e31388b9b3a37c0f4652ade4505945f5660d24" +dependencies = [ + "new_debug_unreachable", + "utf-8", +] + +[[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.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl 2.0.18", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "time" +version = "0.3.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" + +[[package]] +name = "time-macros" +version = "0.2.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.52.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67dee974fe86fd92cc45b7a95fdd2f99a36a6d7b0d431a231178d3d670bbcc6" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d" +dependencies = [ + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.3", + "toml_edit 0.20.2", +] + +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "indexmap 2.14.0", + "serde_core", + "serde_spanned 1.1.1", + "toml_datetime 0.7.5+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + +[[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 = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +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.0", + "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.0", + "serde", + "serde_spanned 0.6.9", + "toml_datetime 0.6.3", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.25.11+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b59c4d22ed448339746c59b905d24568fcbb3ab65a500494f7b8c3e97739f2b" +dependencies = [ + "indexmap 2.14.0", + "toml_datetime 1.1.1+spec-1.1.0", + "toml_parser", + "winnow 1.0.1", +] + +[[package]] +name = "toml_parser" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" +dependencies = [ + "winnow 1.0.1", +] + +[[package]] +name = "toml_writer" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db" + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" +dependencies = [ + "bitflags 2.11.1", + "bytes", + "futures-util", + "http", + "http-body", + "iri-string", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +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.117", +] + +[[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 = "tray-icon" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e85aa143ceb072062fc4d6356c1b520a51d636e7bc8e77ec94be3608e5e80c" +dependencies = [ + "crossbeam-channel", + "dirs 6.0.0", + "libappindicator", + "muda", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "once_cell", + "png 0.17.16", + "serde", + "thiserror 2.0.18", + "windows-sys 0.60.2", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +dependencies = [ + "core_maths", +] + +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[package]] +name = "typenum" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" + +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "unic-char-property" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" +dependencies = [ + "unic-char-range", +] + +[[package]] +name = "unic-char-range" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" + +[[package]] +name = "unic-common" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" + +[[package]] +name = "unic-ucd-ident" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e230a37c0381caa9219d67cf063aa3a375ffed5bf541a452db16e744bdab6987" +dependencies = [ + "unic-char-property", + "unic-char-range", + "unic-ucd-version", +] + +[[package]] +name = "unic-ucd-version" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" +dependencies = [ + "unic-common", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-segmentation" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", + "serde_derive", +] + +[[package]] +name = "urlpattern" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70acd30e3aa1450bc2eece896ce2ad0d178e9c079493819301573dae3c37ba6d" +dependencies = [ + "regex", + "serde", + "unic-ucd-ident", + "url", +] + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd74a9687298c6858e9b88ec8935ec45d22e8fd5e6394fa1bd4e99a87789c76" +dependencies = [ + "getrandom 0.4.2", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vswhom" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b" +dependencies = [ + "libc", + "vswhom-sys", +] + +[[package]] +name = "vswhom-sys" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.9.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.3+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" +dependencies = [ + "wit-bindgen 0.57.1", +] + +[[package]] +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +dependencies = [ + "wit-bindgen 0.51.0", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf938a0bacb0469e83c1e148908bd7d5a6010354cf4fb73279b7447422e3a89" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f371d383f2fb139252e0bfac3b81b265689bf45b6874af544ffa4c975ac1ebf8" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeff24f84126c0ec2db7a449f0c2ec963c6a49efe0698c4242929da037ca28ed" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d08065faf983b2b80a79fd87d8254c409281cf7de75fc4b773019824196c904" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.117", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd04d9e306f1907bd13c6361b5c6bfc7b3b3c095ed3f8a9246390f8dbdee129" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap 2.14.0", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags 2.11.1", + "hashbrown 0.15.5", + "indexmap 2.14.0", + "semver", +] + +[[package]] +name = "web-sys" +version = "0.3.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f2dfbb17949fa2088e5d39408c48368947b86f7834484e87b73de55bc14d97d" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web_atoms" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57a9779e9f04d2ac1ce317aee707aa2f6b773afba7b931222bff6983843b1576" +dependencies = [ + "phf 0.13.1", + "phf_codegen 0.13.1", + "string_cache 0.9.0", + "string_cache_codegen 0.6.1", +] + +[[package]] +name = "webkit2gtk" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793" +dependencies = [ + "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 = "webkit2gtk-sys" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5" +dependencies = [ + "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 = "webpki-roots" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webview2-com" +version = "0.38.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a" +dependencies = [ + "webview2-com-macros", + "webview2-com-sys", + "windows", + "windows-core 0.61.2", + "windows-implement", + "windows-interface", +] + +[[package]] +name = "webview2-com-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "webview2-com-sys" +version = "0.38.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c" +dependencies = [ + "thiserror 2.0.18", + "windows", + "windows-core 0.61.2", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "window-vibrancy" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9bec5a31f3f9362f2258fd0e9c9dd61a9ca432e7306cc78c444258f0dce9a9c" +dependencies = [ + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "raw-window-handle", + "windows-sys 0.59.0", + "windows-version", +] + +[[package]] +name = "windows" +version = "0.61.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" +dependencies = [ + "windows-collections", + "windows-core 0.61.2", + "windows-future", + "windows-link 0.1.3", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" +dependencies = [ + "windows-core 0.61.2", +] + +[[package]] +name = "windows-core" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link 0.1.3", + "windows-result 0.3.4", + "windows-strings 0.4.2", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-future" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", +] + +[[package]] +name = "windows-result" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-strings" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link 0.2.1", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows-threading" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-version" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "winnow" +version = "0.5.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09dac053f1cd375980747450bfc7250c264eaae0583872e845c0c7cd578872b5" +dependencies = [ + "memchr", +] + +[[package]] +name = "winreg" +version = "0.55.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97" +dependencies = [ + "cfg-if", + "windows-sys 0.59.0", +] + +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck 0.5.0", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck 0.5.0", + "indexmap 2.14.0", + "prettyplease", + "syn 2.0.117", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.117", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags 2.11.1", + "indexmap 2.14.0", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap 2.14.0", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "wry" +version = "0.54.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5a8135d8676225e5744de000d4dff5a082501bf7db6a1c1495034f8c314edbc" +dependencies = [ + "base64 0.22.1", + "block2", + "cookie", + "crossbeam-channel", + "dirs 6.0.0", + "dom_query", + "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", + "once_cell", + "percent-encoding", + "raw-window-handle", + "sha2", + "soup3", + "tao-macros", + "thiserror 2.0.18", + "url", + "webkit2gtk", + "webkit2gtk-sys", + "webview2-com", + "windows", + "windows-core 0.61.2", + "windows-version", + "x11-dl", +] + +[[package]] +name = "x11" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "yoke" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "synstructure", +] + +[[package]] +name = "zbus" +version = "5.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca82f95dbd3943a40a53cfded6c2d0a2ca26192011846a1810c4256ef92c60bc" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix", + "serde", + "serde_repr", + "tokio", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow 0.7.15", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897e79616e84aac4b2c46e9132a4f63b93105d54fe8c0e8f6bffc21fa8d49222" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.117", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffd8af6d5b78619bab301ff3c560a5bd22426150253db278f164d6cf3b72c50f" +dependencies = [ + "serde", + "winnow 0.7.15", + "zvariant", +] + +[[package]] +name = "zerocopy" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "zerofrom" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" + +[[package]] +name = "zvariant" +version = "5.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5708299b21903bbe348e94729f22c49c55d04720a004aa350f1f9c122fd2540b" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow 0.7.15", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b59b012ebe9c46656f9cc08d8da8b4c726510aef12559da3e5f1bf72780752c" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.117", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75c23a64ef8f40f13a6989991e643554d9bef1d682a281160cf0c1bc389c5e9" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 2.0.117", + "winnow 0.7.15", +] diff --git a/windows/src-tauri/Cargo.toml b/windows/src-tauri/Cargo.toml new file mode 100644 index 00000000..548afcba --- /dev/null +++ b/windows/src-tauri/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "codeburn-menubar" +version = "0.9.20" +description = "CodeBurn menubar (tray) app for Windows and Linux" +authors = ["AgentSeal"] +edition = "2021" +rust-version = "1.80" + +[lib] +name = "codeburn_menubar_lib" +crate-type = ["staticlib", "cdylib", "rlib"] + +[build-dependencies] +tauri-build = { version = "2", features = [] } + +[dependencies] +tauri = { version = "2", features = ["tray-icon", "image-png"] } +tauri-plugin-opener = "2" +tauri-plugin-shell = "2" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tokio = { version = "1", features = ["process", "io-util", "rt-multi-thread", "macros", "time", "sync"] } +thiserror = "1" +anyhow = "1" +dirs = "5" +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } +fontdue = "0.9" + +[target.'cfg(target_os = "windows")'.dependencies] +windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Graphics_Dwm", "Win32_UI_WindowsAndMessaging"] } + +[target.'cfg(target_os = "linux")'.dependencies] +ksni = "0.3" +png = "0.17" + +[features] +default = ["custom-protocol"] +# This feature is used for production builds or when a dev server is not specified. Don't +# change it unless you know what you're doing. +custom-protocol = ["tauri/custom-protocol"] diff --git a/windows/src-tauri/build.rs b/windows/src-tauri/build.rs new file mode 100644 index 00000000..d860e1e6 --- /dev/null +++ b/windows/src-tauri/build.rs @@ -0,0 +1,3 @@ +fn main() { + tauri_build::build() +} diff --git a/windows/src-tauri/capabilities/default.json b/windows/src-tauri/capabilities/default.json new file mode 100644 index 00000000..e227dc18 --- /dev/null +++ b/windows/src-tauri/capabilities/default.json @@ -0,0 +1,20 @@ +{ + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "default", + "description": "Default permissions for the CodeBurn tray app window", + "windows": ["popover"], + "permissions": [ + "core:default", + "core:window:allow-close", + "core:window:allow-hide", + "core:window:allow-show", + "core:window:allow-set-focus", + "core:window:allow-set-position", + "core:window:allow-set-size", + "core:tray:default", + "core:event:allow-listen", + "core:event:allow-emit", + "opener:default", + "shell:default" + ] +} diff --git a/windows/src-tauri/icons/128x128.png b/windows/src-tauri/icons/128x128.png new file mode 100644 index 00000000..2682d606 Binary files /dev/null and b/windows/src-tauri/icons/128x128.png differ diff --git a/windows/src-tauri/icons/128x128@2x.png b/windows/src-tauri/icons/128x128@2x.png new file mode 100644 index 00000000..4942be53 Binary files /dev/null and b/windows/src-tauri/icons/128x128@2x.png differ diff --git a/windows/src-tauri/icons/32x32.png b/windows/src-tauri/icons/32x32.png new file mode 100644 index 00000000..b90f1af5 Binary files /dev/null and b/windows/src-tauri/icons/32x32.png differ diff --git a/windows/src-tauri/icons/icon.ico b/windows/src-tauri/icons/icon.ico new file mode 100644 index 00000000..826504af Binary files /dev/null and b/windows/src-tauri/icons/icon.ico differ diff --git a/windows/src-tauri/icons/icon.png b/windows/src-tauri/icons/icon.png new file mode 100644 index 00000000..aace9aa7 Binary files /dev/null and b/windows/src-tauri/icons/icon.png differ diff --git a/windows/src-tauri/icons/tray.png b/windows/src-tauri/icons/tray.png new file mode 100644 index 00000000..1bbc27e5 Binary files /dev/null and b/windows/src-tauri/icons/tray.png differ diff --git a/windows/src-tauri/src/autostart.rs b/windows/src-tauri/src/autostart.rs new file mode 100644 index 00000000..f563d429 --- /dev/null +++ b/windows/src-tauri/src/autostart.rs @@ -0,0 +1,89 @@ +//! Launch at login. Windows: a value under HKCU\...\CurrentVersion\Run pointing at this +//! executable. Linux: an XDG autostart .desktop file. No extra crates; both are a few +//! lines of `reg` / plain file IO. + +use anyhow::{anyhow, Result}; +#[cfg(any(target_os = "windows", target_os = "linux"))] +use anyhow::Context; + +#[cfg(any(target_os = "windows", target_os = "linux"))] +const APP_NAME: &str = "CodeBurn"; + +#[cfg(target_os = "windows")] +const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run"; + +/// Absolute `reg.exe` out of System32 -- see `cli::system_command`. +#[cfg(target_os = "windows")] +fn reg(args: &[&str]) -> Result { + crate::cli::system_command("reg.exe") + .args(args) + .output() + .with_context(|| "failed to run reg.exe") +} + +#[cfg(target_os = "windows")] +pub fn is_enabled() -> bool { + reg(&["query", RUN_KEY, "/v", APP_NAME]) + .map(|out| out.status.success()) + .unwrap_or(false) +} + +#[cfg(target_os = "windows")] +pub fn set_enabled(enabled: bool) -> Result<()> { + if enabled { + let exe = std::env::current_exe().with_context(|| "cannot resolve current exe")?; + let value = format!("\"{}\"", exe.display()); + let out = reg(&["add", RUN_KEY, "/v", APP_NAME, "/t", "REG_SZ", "/d", &value, "/f"])?; + if !out.status.success() { + return Err(anyhow!(String::from_utf8_lossy(&out.stderr).trim().to_string())); + } + } else { + let out = reg(&["delete", RUN_KEY, "/v", APP_NAME, "/f"])?; + // Deleting a value that does not exist is the state we want anyway. + if !out.status.success() && is_enabled() { + return Err(anyhow!(String::from_utf8_lossy(&out.stderr).trim().to_string())); + } + } + Ok(()) +} + +#[cfg(target_os = "linux")] +fn desktop_file() -> Option { + dirs::config_dir().map(|d| d.join("autostart").join("codeburn-menubar.desktop")) +} + +#[cfg(target_os = "linux")] +pub fn is_enabled() -> bool { + desktop_file().map(|p| p.is_file()).unwrap_or(false) +} + +#[cfg(target_os = "linux")] +pub fn set_enabled(enabled: bool) -> Result<()> { + let path = desktop_file().ok_or_else(|| anyhow!("no config dir"))?; + if enabled { + let exe = std::env::current_exe().with_context(|| "cannot resolve current exe")?; + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write( + &path, + format!( + "[Desktop Entry]\nType=Application\nName={APP_NAME}\nExec=\"{}\"\nX-GNOME-Autostart-enabled=true\n", + exe.display() + ), + )?; + } else if path.exists() { + std::fs::remove_file(&path)?; + } + Ok(()) +} + +#[cfg(target_os = "macos")] +pub fn is_enabled() -> bool { + false +} + +#[cfg(target_os = "macos")] +pub fn set_enabled(_enabled: bool) -> Result<()> { + Err(anyhow!("launch at login is handled by the native macOS app")) +} diff --git a/windows/src-tauri/src/cli.rs b/windows/src-tauri/src/cli.rs new file mode 100644 index 00000000..53435547 --- /dev/null +++ b/windows/src-tauri/src/cli.rs @@ -0,0 +1,601 @@ +use std::env; +use std::path::PathBuf; +use std::process::Stdio; + +use anyhow::{anyhow, bail, Context, Result}; +use serde::Serialize; +use serde_json::Value; +use tauri::AppHandle; +use tokio::io::AsyncReadExt; +use tokio::process::Command; +use tokio::time::{timeout, Duration}; + +/// Hard bounds mirror the macOS CodeburnCLI / DataClient design. A malicious or stuck CLI +/// cannot pin the Tauri process: stdout is capped, stderr is bounded, total wall time is +/// 60s. A hostile CODEBURN_BIN is rejected before any shell-resembling path is taken. +const MAX_PAYLOAD_BYTES: usize = 20 * 1024 * 1024; +const MAX_STDERR_BYTES: usize = 256 * 1024; +const FETCH_TIMEOUT_SECS: u64 = 60; +const VERSION_TIMEOUT_SECS: u64 = 20; + +/// Oldest CLI this app can talk to. 0.9.9 is the first release whose +/// `status --format menubar-json` accepts `--no-optimize`, which every quiet background +/// refresh passes; it also emits all the payload fields the popover reads +/// (`current.providers`, `current.cacheHitPercent`, `history.daily[].topModels`). Older CLIs +/// get the setup screen instead of a half-rendered popover or a stream of spawn failures. +pub const MIN_CLI_VERSION: (u32, u32, u32) = (0, 9, 9); + +#[cfg(windows)] +const WINDOWS_CLI_NAMES: [&str; 2] = ["codeburn.cmd", "codeburn.exe"]; + +#[cfg(windows)] +const CLAUDE_NAMES: [&str; 2] = ["claude.cmd", "claude.exe"]; +#[cfg(not(windows))] +const CLAUDE_NAMES: [&str; 1] = ["claude"]; + +/// Alphanumerics plus `._/-` and space, with `\`, `:`, `(`, `)` also allowed on Windows +/// so a user-supplied `CODEBURN_BIN` path like `C:\Users\...\codeburn.cmd` is accepted. +/// None of these are shell metacharacters in a direct-argv spawn (we never invoke `sh -c`). +fn is_safe_arg(value: &str) -> bool { + !value.is_empty() + && value.chars().all(|c| { + c.is_ascii_alphanumeric() + || matches!(c, '.' | '_' | '/' | '-' | ' ') + || (cfg!(windows) && matches!(c, '\\' | ':' | '(' | ')')) + }) +} + +#[derive(Clone, Debug)] +pub struct CodeburnCli { + program: String, + extra_args: Vec, +} + +/// What the setup screen needs to know about the CLI on this machine. +#[derive(Clone, Debug, Serialize)] +pub struct CliStatus { + pub found: bool, + pub program: String, + pub version: Option, + pub min_version: String, + pub compatible: bool, + pub error: Option, +} + +impl CodeburnCli { + /// Honours `CODEBURN_BIN` only when every whitespace-delimited token passes the + /// allowlist. Otherwise resolves `codeburn` from PATH and the usual npm locations. + pub fn resolve() -> Self { + let raw = env::var("CODEBURN_BIN").unwrap_or_default(); + if raw.is_empty() { + return Self::default_program(); + } + // A bare path (which may contain spaces, e.g. under Program Files) is used whole; + // only otherwise is the value split into program + leading arguments. + if is_safe_arg(&raw) && std::path::Path::new(&raw).is_file() { + return CodeburnCli { + program: raw, + extra_args: vec![], + }; + } + let parts: Vec = raw.split_whitespace().map(String::from).collect(); + if parts.iter().all(|p| is_safe_arg(p)) { + if let Some((first, rest)) = parts.split_first() { + return CodeburnCli { + program: first.clone(), + extra_args: rest.to_vec(), + }; + } + } + eprintln!("codeburn-menubar: refusing unsafe CODEBURN_BIN; falling back to `codeburn`"); + Self::default_program() + } + + fn default_program() -> Self { + CodeburnCli { + program: locate_cli().unwrap_or_else(default_program_name), + extra_args: vec![], + } + } + + pub fn program(&self) -> &str { + &self.program + } + + /// Runs `codeburn --version` and reports whether the CLI is present and new enough. + pub async fn status(&self) -> CliStatus { + let min_version = format!( + "{}.{}.{}", + MIN_CLI_VERSION.0, MIN_CLI_VERSION.1, MIN_CLI_VERSION.2 + ); + let mut status = CliStatus { + found: false, + program: self.program.clone(), + version: None, + min_version, + compatible: false, + error: None, + }; + match self.run_capture(&["--version"], VERSION_TIMEOUT_SECS).await { + Ok(out) => { + let version = out.trim().to_string(); + status.found = true; + status.compatible = parse_version(&version) + .map(|v| v >= MIN_CLI_VERSION) + .unwrap_or(false); + status.version = Some(version); + } + Err(err) => { + status.error = Some(err.to_string()); + } + } + status + } + + /// Spawns `codeburn status --format menubar-json --period X --provider Y` and decodes the + /// output. Pipes are drained concurrently so a chatty stderr cannot deadlock stdout. + pub async fn fetch_menubar_payload( + &self, + period: &str, + provider: &str, + include_optimize: bool, + ) -> Result { + if !is_safe_arg(period) || !is_safe_arg(provider) { + bail!("invalid period/provider argument"); + } + + let mut args = vec![ + "status", + "--format", + "menubar-json", + "--period", + period, + "--provider", + provider, + ]; + if !include_optimize { + args.push("--no-optimize"); + } + + let stdout = self.run_capture(&args, FETCH_TIMEOUT_SECS).await?; + let payload: Value = + serde_json::from_str(&stdout).with_context(|| "CLI returned invalid JSON")?; + Ok(payload) + } + + async fn run_capture(&self, args: &[&str], timeout_secs: u64) -> Result { + let mut full_args = self.extra_args.clone(); + full_args.extend(args.iter().map(|s| s.to_string())); + + let mut cmd = Command::new(&self.program); + cmd.args(&full_args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true); + #[cfg(windows)] + { + const CREATE_NO_WINDOW: u32 = 0x08000000; + cmd.creation_flags(CREATE_NO_WINDOW); + } + let mut child = cmd.spawn().map_err(|err| { + anyhow!( + "CodeBurn CLI not found ({}). Install it with `npm install -g codeburn`.", + spawn_error_summary(&self.program, &err) + ) + })?; + + let mut stdout = child.stdout.take().ok_or_else(|| anyhow!("no stdout"))?; + let mut stderr = child.stderr.take().ok_or_else(|| anyhow!("no stderr"))?; + + let stdout_task = tokio::spawn(async move { + let mut buf = Vec::with_capacity(64 * 1024); + let mut limited = (&mut stdout).take(MAX_PAYLOAD_BYTES as u64); + limited.read_to_end(&mut buf).await.ok(); + buf + }); + let stderr_task = tokio::spawn(async move { + let mut buf = Vec::with_capacity(4 * 1024); + let mut limited = (&mut stderr).take(MAX_STDERR_BYTES as u64); + limited.read_to_end(&mut buf).await.ok(); + buf + }); + + let status = timeout(Duration::from_secs(timeout_secs), child.wait()) + .await + .map_err(|_| anyhow!("codeburn CLI timed out after {}s", timeout_secs))??; + + let stdout_bytes = stdout_task.await.unwrap_or_default(); + let stderr_bytes = stderr_task.await.unwrap_or_default(); + + if !status.success() { + let msg = String::from_utf8_lossy(&stderr_bytes); + bail!("codeburn CLI exited {}: {}", status, msg.trim()); + } + Ok(String::from_utf8_lossy(&stdout_bytes).into_owned()) + } +} + +fn spawn_error_summary(program: &str, err: &std::io::Error) -> String { + match err.kind() { + std::io::ErrorKind::NotFound => format!("{} is not on PATH", program), + _ => format!("{}: {}", program, err), + } +} + +fn default_program_name() -> String { + #[cfg(windows)] + { + "codeburn.cmd".to_string() + } + #[cfg(not(windows))] + { + "codeburn".to_string() + } +} + +/// Parses "0.7.3" or "codeburn 0.7.3" into a comparable tuple. +pub fn parse_version(text: &str) -> Option<(u32, u32, u32)> { + let token = text + .split_whitespace() + .find(|t| t.chars().next().map(|c| c.is_ascii_digit()).unwrap_or(false))?; + let mut parts = token.split('.').map(|p| { + p.chars() + .take_while(|c| c.is_ascii_digit()) + .collect::() + .parse::() + .ok() + }); + Some((parts.next()??, parts.next()??, parts.next().flatten().unwrap_or(0))) +} + +/// Locates the CLI without relying on the inherited PATH being fresh. A tray app is often +/// launched from Explorer or at login, before (or long after) `npm install -g codeburn` +/// changed the user's PATH, so we also read the live PATH from the registry on Windows and +/// probe the standard npm / node install prefixes. +fn locate_cli() -> Option { + find_in_search_dirs(&candidate_names()) +} + +/// Same search for Claude Code's own binary, so "Connect Claude" spawns an absolute path +/// instead of letting the console shell resolve a bare `claude`. +fn locate_claude() -> Option { + find_in_search_dirs(&CLAUDE_NAMES) +} + +fn find_in_search_dirs(names: &[&str]) -> Option { + let mut dirs: Vec = Vec::new(); + if let Some(path) = env::var_os("PATH") { + dirs.extend(env::split_paths(&path)); + } + dirs.extend(extra_search_dirs()); + find_in_dirs(&dirs, names) +} + +/// The absolute-only filter is the security boundary, so it lives here where every search +/// goes through it. `env::split_paths` yields an empty `PathBuf` for `;;` or a trailing `;`, +/// and the registry PATH can hold relative entries too; `PathBuf::from("").join("codeburn.cmd")` +/// resolves against the current directory, which for a tray app launched at login is +/// whatever Explorer handed it. A binary planted there must never win. +fn find_in_dirs(dirs: &[PathBuf], names: &[&str]) -> Option { + for dir in dirs.iter().filter(|d| d.is_absolute()) { + for name in names { + let candidate = dir.join(name); + if candidate.is_file() { + return Some(candidate.to_string_lossy().into_owned()); + } + } + } + None +} + +fn candidate_names() -> Vec<&'static str> { + #[cfg(windows)] + { + WINDOWS_CLI_NAMES.to_vec() + } + #[cfg(not(windows))] + { + vec!["codeburn"] + } +} + +#[cfg(windows)] +fn extra_search_dirs() -> Vec { + let mut out = Vec::new(); + for var in ["APPDATA", "LOCALAPPDATA", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = env::var_os(var).map(PathBuf::from) { + match var { + "APPDATA" => out.push(base.join("npm")), + "LOCALAPPDATA" => { + out.push(base.join("Programs").join("nodejs")); + out.push(base.join("pnpm")); + out.push(base.join("Volta").join("bin")); + out.push(base.join("fnm_multishells")); + } + _ => out.push(base.join("nodejs")), + } + } + } + if let Some(home) = dirs::home_dir() { + out.push(home.join("scoop").join("shims")); + out.push(home.join(".bun").join("bin")); + } + out.extend(registry_path_dirs()); + out +} + +#[cfg(not(windows))] +fn extra_search_dirs() -> Vec { + let mut out = vec![ + PathBuf::from("/opt/homebrew/bin"), + PathBuf::from("/usr/local/bin"), + ]; + if let Some(home) = dirs::home_dir() { + out.push(home.join(".npm-global").join("bin")); + out.push(home.join(".local").join("bin")); + } + out +} + +/// Windows' `CreateProcess` searches the current directory before `PATH`, so spawning +/// `reg` or `cmd` by bare name lets anything dropped next to the app impersonate a system +/// tool -- and the tray badge re-runs `reg query` every refresh. Always spawn the real one +/// out of `%SystemRoot%\System32`, falling back to the documented default when the +/// environment variable is missing or relative. +#[cfg(windows)] +pub fn system32_path(exe: &str) -> PathBuf { + let root = env::var_os("SystemRoot") + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + .unwrap_or_else(|| PathBuf::from(r"C:\Windows")); + root.join("System32").join(exe) +} + +/// `system32_path` plus the CREATE_NO_WINDOW flag every one of these callers wants. +#[cfg(windows)] +pub fn system_command(exe: &str) -> std::process::Command { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x08000000; + let mut cmd = std::process::Command::new(system32_path(exe)); + cmd.creation_flags(CREATE_NO_WINDOW); + cmd +} + +/// Reads the user and machine PATH values from the registry via `reg.exe` so a PATH edit +/// made after this process started (npm install adds `%APPDATA%\npm`) is still honoured. +#[cfg(windows)] +fn registry_path_dirs() -> Vec { + let mut out = Vec::new(); + let keys = [ + r"HKCU\Environment", + r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment", + ]; + for key in keys { + let output = system_command("reg.exe") + .args(["query", key, "/v", "Path"]) + .output(); + let Ok(output) = output else { continue }; + let text = String::from_utf8_lossy(&output.stdout); + for line in text.lines() { + let trimmed = line.trim(); + if !trimmed.starts_with("Path") { + continue; + } + let Some(idx) = trimmed.find("REG_") else { continue }; + let rest = &trimmed[idx..]; + let Some(space) = rest.find(char::is_whitespace) else { continue }; + let value = rest[space..].trim(); + for part in value.split(';') { + let expanded = expand_env(part.trim()); + if !expanded.is_empty() { + out.push(PathBuf::from(expanded)); + } + } + } + } + out +} + +#[cfg(windows)] +fn expand_env(value: &str) -> String { + let mut result = String::with_capacity(value.len()); + let mut rest = value; + while let Some(start) = rest.find('%') { + result.push_str(&rest[..start]); + let after = &rest[start + 1..]; + match after.find('%') { + Some(end) => { + let name = &after[..end]; + match env::var(name) { + Ok(v) => result.push_str(&v), + Err(_) => { + result.push('%'); + result.push_str(name); + result.push('%'); + } + } + rest = &after[end + 1..]; + } + None => { + result.push_str(&rest[start..]); + rest = ""; + } + } + } + result.push_str(rest); + result +} + +/// Runs a codeburn subcommand in the user's terminal emulator so they can see the output. +/// Linux: tries `x-terminal-emulator`, `gnome-terminal`, `konsole`, then falls back to a +/// detached headless spawn. Windows: opens a console via `cmd /C start`. Never +/// interpolates through a shell -- argv throughout. +pub fn spawn_in_terminal(app: &AppHandle, subcommand: &[&str]) -> Result<()> { + let cli = CodeburnCli::resolve(); + spawn_program_in_terminal(app, &cli, subcommand) +} + +/// The Plan view's "Connect Claude" runs Claude Code's own login flow, not codeburn. The +/// binary is located up front rather than handed to the console shell as a bare name, so +/// the same absolute-directory rule that protects the codeburn lookup applies here too. +pub fn spawn_claude_login(app: &AppHandle) -> Result<()> { + let program = locate_claude().ok_or_else(|| { + anyhow!("Claude Code was not found on this machine. Install it, then try again.") + })?; + let cli = CodeburnCli { + program, + extra_args: vec![], + }; + spawn_program_in_terminal(app, &cli, &["login"]) +} + +fn spawn_program_in_terminal(_app: &AppHandle, cli: &CodeburnCli, subcommand: &[&str]) -> Result<()> { + if !subcommand.iter().all(|s| is_safe_arg(s)) { + bail!("unsafe subcommand argument"); + } + + #[cfg(target_os = "linux")] + { + let mut command_parts: Vec = vec![cli.program.clone()]; + command_parts.extend(cli.extra_args.clone()); + command_parts.extend(subcommand.iter().map(|s| s.to_string())); + // Terminal emulators take the command as one string that a shell then parses + // (gnome-terminal explicitly hands it to `bash -lc`). `cli.program` reaches here + // from PATH resolution, not only from the allowlisted CODEBURN_BIN, so re-check + // every part before joining; anything a shell could reinterpret skips the terminal + // and goes through the argv-only detached spawn below. + if command_parts.iter().all(|p| is_safe_arg(p)) { + let composite = command_parts.join(" "); + let terminals: [&[&str]; 4] = [ + &["x-terminal-emulator", "-e"], + &["gnome-terminal", "--", "bash", "-lc"], + &["konsole", "-e"], + &["xterm", "-e"], + ]; + for term in &terminals { + let program = term[0]; + let extras = &term[1..]; + if which::which(program).is_ok() { + let mut cmd = std::process::Command::new(program); + cmd.args(extras); + cmd.arg(&composite); + cmd.spawn().with_context(|| format!("failed to launch {}", program))?; + return Ok(()); + } + } + } + // Fallback: run detached, output lost -- better than silently doing nothing. + std::process::Command::new(&cli.program) + .args(&cli.extra_args) + .args(subcommand) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .with_context(|| "no terminal emulator found, detached spawn also failed")?; + } + + #[cfg(target_os = "windows")] + { + // `start` treats the first quoted argument as the window title, so we pass an + // explicit empty title. `/K` keeps the console open for non-interactive commands + // (export) so the user can read where the file went; the TUI (report/optimize) + // owns the window until the user quits it either way. + // Only the unresolved default name is worth a second lookup; anything else is + // either already absolute or a CODEBURN_BIN the user chose. + let program = if cli.program == default_program_name() { + locate_cli().unwrap_or_else(|| cli.program.clone()) + } else { + cli.program.clone() + }; + let cmd_exe = system32_path("cmd.exe"); + let mut cmd = system_command("cmd.exe"); + cmd.arg("/C").arg("start").arg("").arg(&cmd_exe).arg("/K").arg(&program); + for a in &cli.extra_args { + cmd.arg(a); + } + for a in subcommand { + cmd.arg(a); + } + cmd.spawn().with_context(|| "failed to open cmd.exe")?; + } + + #[cfg(target_os = "macos")] + { + // macOS isn't our target for this app (Swift handles Mac), but keep dev-on-Mac working. + std::process::Command::new(&cli.program) + .args(&cli.extra_args) + .args(subcommand) + .spawn() + .with_context(|| format!("failed to spawn {}", cli.program))?; + } + + Ok(()) +} + +/// Minimal dependency: we only use `which` inside spawn_in_terminal on Linux. Vendored here +/// so the crate graph stays tiny. Gated so the unused-function warning doesn't fire on Mac +/// or Windows builds. +#[cfg(target_os = "linux")] +mod which { + use std::env; + use std::path::PathBuf; + + pub fn which(program: &str) -> Result { + let path = env::var_os("PATH").ok_or(())?; + let dirs: Vec = env::split_paths(&path).collect(); + super::find_in_dirs(&dirs, &[program]).map(PathBuf::from).ok_or(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The `;;` / trailing-`;` case: an empty PATH entry must not turn into a + /// current-directory lookup, which is how a planted binary would win at login. + #[test] + fn find_in_dirs_skips_empty_and_relative_entries() { + let dir = std::env::temp_dir(); + let name = "codeburn-menubar-locate-probe"; + let planted = dir.join(name); + std::fs::write(&planted, b"probe").unwrap(); + + // Empty and relative entries are ignored even though the file is reachable + // through them once the process CWD is the temp dir. + let unsafe_dirs = vec![PathBuf::from(""), PathBuf::from("."), PathBuf::from("..")]; + assert_eq!(find_in_dirs(&unsafe_dirs, &[name]), None); + + // The same name behind an absolute entry is found. + let found = find_in_dirs(std::slice::from_ref(&dir), &[name]).expect("absolute entry should match"); + assert!(PathBuf::from(&found).is_absolute()); + assert!(found.ends_with(name)); + + // An unsafe entry ahead of a good one cannot shadow it. + let mixed = vec![PathBuf::from(""), dir.clone()]; + assert_eq!(find_in_dirs(&mixed, &[name]), Some(found)); + + std::fs::remove_file(&planted).ok(); + } + + #[test] + fn parse_version_reads_bare_and_prefixed_output() { + assert_eq!(parse_version("0.9.9"), Some((0, 9, 9))); + assert_eq!(parse_version("codeburn 0.9.20\n"), Some((0, 9, 20))); + assert_eq!(parse_version("1.0"), Some((1, 0, 0))); + assert_eq!(parse_version("0.10.0-beta.1"), Some((0, 10, 0))); + assert_eq!(parse_version("no version here"), None); + } + + /// The gate is a plain tuple compare, so the only thing worth pinning is that the + /// versions on either side of MIN_CLI_VERSION land on the right side of it. + #[test] + fn version_gate_rejects_only_older_clis() { + assert_eq!(MIN_CLI_VERSION, (0, 9, 9)); + assert!(parse_version("0.9.8").unwrap() < MIN_CLI_VERSION); + assert!(parse_version("0.9.9").unwrap() >= MIN_CLI_VERSION); + assert!(parse_version("0.9.20").unwrap() >= MIN_CLI_VERSION); + assert!(parse_version("0.10.0").unwrap() >= MIN_CLI_VERSION); + } +} diff --git a/windows/src-tauri/src/config.rs b/windows/src-tauri/src/config.rs new file mode 100644 index 00000000..3ec8c0ab --- /dev/null +++ b/windows/src-tauri/src/config.rs @@ -0,0 +1,183 @@ +use std::fs; +use std::io::Write; +use std::path::PathBuf; + +use anyhow::{Context, Result}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Default, Clone, Serialize, Deserialize)] +pub struct CurrencyConfig { + #[serde(default, flatten)] + extra: serde_json::Map, +} + +fn codeburn_config_dir() -> PathBuf { + dirs::home_dir() + .map(|h| h.join(".config/codeburn")) + .unwrap_or_else(|| PathBuf::from(".codeburn")) +} + +fn config_path() -> PathBuf { + codeburn_config_dir().join("config.json") +} + +fn lock_path() -> PathBuf { + codeburn_config_dir().join(".config.lock") +} + +impl CurrencyConfig { + pub fn load_or_default() -> Self { + match fs::read(config_path()) { + Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(), + Err(_) => Self::default(), + } + } + + pub fn set_currency(&mut self, code: &str, symbol: &str) -> Result<()> { + fs::create_dir_all(codeburn_config_dir()) + .with_context(|| "failed to create ~/.config/codeburn")?; + + #[cfg(unix)] + let _lock = unix_lock::acquire()?; + #[cfg(windows)] + let _lock = windows_lock::acquire()?; + + let mut disk: serde_json::Value = match fs::read(config_path()) { + Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|_| serde_json::json!({})), + Err(_) => serde_json::json!({}), + }; + + if code == "USD" { + if let Some(obj) = disk.as_object_mut() { + obj.remove("currency"); + } + } else if let Some(obj) = disk.as_object_mut() { + obj.insert( + "currency".into(), + serde_json::json!({ "code": code, "symbol": symbol }), + ); + } + + let serialized = serde_json::to_vec_pretty(&disk)?; + let tmp = config_path().with_extension("tmp"); + { + let mut file = fs::OpenOptions::new() + .create(true) + .write(true) + .truncate(true) + .open(&tmp)?; + file.write_all(&serialized)?; + file.flush()?; + } + fs::rename(&tmp, config_path())?; + + *self = serde_json::from_value(disk).unwrap_or_default(); + Ok(()) + } +} + +#[cfg(unix)] +mod unix_lock { + use std::fs; + use std::os::fd::AsRawFd; + use anyhow::{anyhow, Context, Result}; + + pub struct Guard { + _file: fs::File, + } + + pub fn acquire() -> Result { + let file = fs::OpenOptions::new() + .create(true) + .read(true) + .write(true) + // A lock file only ever needs to exist; its contents are irrelevant. + .truncate(false) + .open(super::lock_path()) + .with_context(|| "failed to open config lock")?; + + let fd = file.as_raw_fd(); + let ret = unsafe { flock(fd, 2) }; + if ret != 0 { + return Err(anyhow!("flock failed: {}", std::io::Error::last_os_error())); + } + Ok(Guard { _file: file }) + } + + extern "C" { + fn flock(fd: i32, operation: i32) -> i32; + } +} + +/// Windows has no flock; a create-new lock file is the closest equivalent. +/// +/// What this actually buys: mutual exclusion between writers that take this lock, which +/// today means only other instances of this app. The codeburn CLI writes `config.json` +/// without taking it, so a concurrent CLI write still races us -- the rename below keeps the +/// file from ever being torn, but a simultaneous CLI edit can still be the one that wins. +/// +/// A lock file left behind by a crash is treated as abandoned once it is older than +/// STALE_LOCK_SECS (three orders of magnitude longer than the read-modify-rename it guards), +/// so one crash cannot wedge currency changes forever. Upgrading to `LockFileEx`, which the +/// OS releases on process death and needs no staleness heuristic, only becomes worth it if +/// the CLI ever starts taking the lock too. +#[cfg(windows)] +mod windows_lock { + use std::fs; + use std::path::PathBuf; + use std::thread::sleep; + use std::time::{Duration, SystemTime}; + use anyhow::{anyhow, Result}; + + const RETRY_INTERVAL: Duration = Duration::from_millis(40); + const MAX_RETRIES: u32 = 50; + const STALE_LOCK_SECS: u64 = 30; + + pub struct Guard { + path: PathBuf, + /// Kept open for the lifetime of the guard: Windows will not unlink a file that is + /// still open, so holding the handle is what stops the stale sweep below from ever + /// deleting a lock whose owner is alive. + file: Option, + } + + impl Drop for Guard { + fn drop(&mut self) { + self.file.take(); + let _ = fs::remove_file(&self.path); + } + } + + pub fn acquire() -> Result { + let path = super::lock_path(); + for _ in 0..MAX_RETRIES { + match fs::OpenOptions::new().write(true).create_new(true).open(&path) { + Ok(file) => { + return Ok(Guard { + path, + file: Some(file), + }) + } + Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => { + // Only proceed on a successful unlink: a live holder still has the file + // open, so this fails for anything but an abandoned lock. + if is_stale(&path) && fs::remove_file(&path).is_ok() { + continue; + } + sleep(RETRY_INTERVAL); + } + Err(err) => return Err(anyhow!("failed to open config lock: {err}")), + } + } + Err(anyhow!("config lock is held by another process")) + } + + fn is_stale(path: &PathBuf) -> bool { + fs::metadata(path) + .and_then(|m| m.modified()) + .ok() + .and_then(|t| SystemTime::now().duration_since(t).ok()) + .map(|age| age.as_secs() > STALE_LOCK_SECS) + .unwrap_or(false) + } +} diff --git a/windows/src-tauri/src/fx.rs b/windows/src-tauri/src/fx.rs new file mode 100644 index 00000000..5eb63be1 --- /dev/null +++ b/windows/src-tauri/src/fx.rs @@ -0,0 +1,152 @@ +use std::collections::HashMap; +use std::fs; +use std::path::PathBuf; +use std::sync::Mutex; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; + +const FRANKFURTER_URL: &str = "https://api.frankfurter.app/latest?from=USD&to="; +const CACHE_TTL_SECS: u64 = 24 * 3600; +const FETCH_TIMEOUT: Duration = Duration::from_secs(10); +/// Defensive bounds on any fetched FX rate. Outside [0.0001, 1_000_000] the rate is either +/// a parser bug or a tampered response; we refuse it so the UI never multiplies a NaN or +/// wild value into displayed costs. +const MIN_VALID_FX_RATE: f64 = 0.0001; +const MAX_VALID_FX_RATE: f64 = 1_000_000.0; + +/// Currency metadata the frontend renders against. `rate` is USD -> target; the UI +/// multiplies each raw USD number by `rate` and prefixes `symbol` for display. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CurrencyApplied { + pub code: String, + pub symbol: String, + pub rate: f64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct Entry { + rate: f64, + saved_at: u64, +} + +pub struct FxCache { + entries: Mutex>, +} + +impl FxCache { + pub fn new() -> Self { + let entries = load_from_disk().unwrap_or_default(); + FxCache { + entries: Mutex::new(entries), + } + } + + /// Returns a cached-or-fresh rate. Tries cache first, then Frankfurter if stale. Any + /// response that fails the sanity bounds is dropped and the cached (possibly stale) + /// value is returned instead. + pub async fn rate_for(&self, code: &str) -> Option { + if code == "USD" { + return Some(1.0); + } + + { + let guard = self.entries.lock().ok()?; + if let Some(entry) = guard.get(code) { + if now_secs().saturating_sub(entry.saved_at) < CACHE_TTL_SECS { + return Some(entry.rate); + } + } + } + + match fetch_rate(code).await { + Some(fresh) if is_valid(fresh) => { + if let Ok(mut guard) = self.entries.lock() { + guard.insert( + code.to_string(), + Entry { + rate: fresh, + saved_at: now_secs(), + }, + ); + let _ = save_to_disk(&guard); + } + Some(fresh) + } + _ => { + // Fetch failed or out-of-band; serve stale cached value if any. + let guard = self.entries.lock().ok()?; + guard.get(code).map(|e| e.rate) + } + } + } +} + +fn is_valid(rate: f64) -> bool { + rate.is_finite() && (MIN_VALID_FX_RATE..=MAX_VALID_FX_RATE).contains(&rate) +} + +fn now_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +fn cache_path() -> PathBuf { + dirs::cache_dir() + .unwrap_or_else(|| PathBuf::from(".")) + .join("codeburn-menubar") + .join("fx-rates.json") +} + +fn load_from_disk() -> Option> { + let bytes = fs::read(cache_path()).ok()?; + let parsed: HashMap = serde_json::from_slice(&bytes).ok()?; + Some(parsed.into_iter().filter(|(_, e)| is_valid(e.rate)).collect()) +} + +fn save_to_disk(entries: &HashMap) -> Option<()> { + let path = cache_path(); + let parent = path.parent()?; + fs::create_dir_all(parent).ok()?; + let serialized = serde_json::to_vec(entries).ok()?; + let tmp = path.with_extension("tmp"); + fs::write(&tmp, serialized).ok()?; + fs::rename(&tmp, path).ok()?; + Some(()) +} + +async fn fetch_rate(code: &str) -> Option { + let client = reqwest::Client::builder() + .timeout(FETCH_TIMEOUT) + .https_only(true) + .build() + .ok()?; + let url = format!("{}{}", FRANKFURTER_URL, code); + let response = client.get(&url).send().await.ok()?; + if !response.status().is_success() { + return None; + } + let body: serde_json::Value = response.json().await.ok()?; + body.get("rates")?.get(code)?.as_f64() +} + +/// Prefers a handwritten glyph over whatever Intl returns for a given code, since some +/// locales produce "US$" / "CA$" which reads as noise. Mirrors the Swift symbol override +/// table so both apps display identical strings for the same code. +pub fn symbol_for(code: &str) -> String { + match code { + "USD" | "CAD" | "AUD" | "NZD" | "HKD" | "SGD" | "MXN" => "$".into(), + "EUR" => "\u{20AC}".into(), + "GBP" => "\u{00A3}".into(), + "JPY" | "CNY" => "\u{00A5}".into(), + "KRW" => "\u{20A9}".into(), + "INR" => "\u{20B9}".into(), + "BRL" => "R$".into(), + "CHF" => "CHF".into(), + "SEK" | "DKK" => "kr".into(), + "ZAR" => "R".into(), + _ => code.into(), + } +} diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rs new file mode 100644 index 00000000..64e67111 --- /dev/null +++ b/windows/src-tauri/src/lib.rs @@ -0,0 +1,520 @@ +mod autostart; +mod cli; +mod config; +mod fx; +mod plan; +/// The spend-in-the-tray badge is a second tray icon, which only the Tauri tray backend +/// provides; Linux runs its own SNI tray (`tray_linux`) and has no equivalent, so the +/// whole module is compiled out there rather than sitting unused. +#[cfg(not(target_os = "linux"))] +mod tray_badge; +#[cfg(target_os = "linux")] +mod tray_linux; + +use std::sync::Mutex; +use std::sync::atomic::{AtomicI64, Ordering}; + +static LAST_HIDDEN_MS: AtomicI64 = AtomicI64::new(0); + +use tauri::{AppHandle, Emitter, Manager, WindowEvent}; +#[cfg(target_os = "linux")] +use tauri::Listener; + +#[cfg(not(target_os = "linux"))] +use tauri::{ + menu::{Menu, MenuItem, PredefinedMenuItem}, + tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}, +}; + +use crate::cli::CodeburnCli; +use crate::config::CurrencyConfig; +use crate::fx::FxCache; + +#[cfg(not(target_os = "linux"))] +const TRAY_ID: &str = "codeburn-tray"; +/// Second tray icon that carries today's spend as text, sitting next to the logo. The +/// closest the Windows notification area gets to the macOS menubar title. +#[cfg(not(target_os = "linux"))] +const BADGE_TRAY_ID: &str = "codeburn-badge"; +const POPOVER_LABEL: &str = "popover"; + +/// Shared application state. Wraps the CLI handle + currency config + FX cache so every +/// Tauri command sees the same instances. Interior Mutex keeps things simple; the state is +/// touched from the main thread (UI) and the Tokio runtime (CLI spawn, HTTP), both of +/// which go through `#[tauri::command]` async functions that acquire the lock briefly. +pub struct AppState { + pub cli: Mutex, + pub config: Mutex, + pub fx: FxCache, + pub plan: plan::PlanClient, +} + +#[cfg_attr(mobile, tauri::mobile_entry_point)] +pub fn run() { + tauri::Builder::default() + .plugin(tauri_plugin_shell::init()) + .plugin(tauri_plugin_opener::init()) + .setup(|app| { + app.manage(AppState { + cli: Mutex::new(CodeburnCli::resolve()), + config: Mutex::new(CurrencyConfig::load_or_default()), + fx: FxCache::new(), + plan: plan::PlanClient::new(), + }); + + #[cfg(not(target_os = "linux"))] + build_tray_tauri(app.handle())?; + + #[cfg(target_os = "linux")] + init_tray_linux(app.handle().clone(), tray_linux::LinuxTrayHandle::empty()); + + if let Some(window) = app.get_webview_window(POPOVER_LABEL) { + let _ = window.hide(); + #[cfg(target_os = "windows")] + round_window_corners(&window); + } + + Ok(()) + }) + .on_window_event(|window, event| { + match event { + WindowEvent::CloseRequested { api, .. } => { + api.prevent_close(); + let _ = window.hide(); + mark_hidden(window.app_handle()); + } + WindowEvent::Focused(false) => { + let _ = window.hide(); + mark_hidden(window.app_handle()); + } + _ => {} + } + }) + .invoke_handler(tauri::generate_handler![ + commands::fetch_payload, + commands::cli_status, + commands::set_currency, + commands::open_terminal_command, + commands::open_claude_login, + commands::quit_app, + commands::hide_popover, + commands::set_tray_tooltip, + commands::set_tray_badge, + commands::app_version, + commands::plan_usage, + commands::launch_at_login, + commands::set_launch_at_login, + ]) + .build(tauri::generate_context!()) + .expect("error while running tauri application") + .run(|_app, event| { + if let tauri::RunEvent::ExitRequested { api, .. } = event { + api.prevent_exit(); + } + }); +} + +#[cfg(not(target_os = "linux"))] +fn build_tray_tauri(app: &AppHandle) -> tauri::Result<()> { + let Some(tray) = app.tray_by_id(TRAY_ID) else { + return Ok(()); + }; + + let open = MenuItem::with_id(app, "open", "Open CodeBurn", true, None::<&str>)?; + let refresh = MenuItem::with_id(app, "refresh", "Refresh", true, None::<&str>)?; + let theme = MenuItem::with_id(app, "toggle_theme", "Toggle Dark/Light", true, None::<&str>)?; + let report = MenuItem::with_id(app, "report", "Open Full Report", true, None::<&str>)?; + let quit = MenuItem::with_id(app, "quit", "Quit CodeBurn", true, None::<&str>)?; + let menu = Menu::with_items( + app, + &[ + &open, + &refresh, + &theme, + &report, + &PredefinedMenuItem::separator(app)?, + &quit, + ], + )?; + + tray.set_menu(Some(menu.clone()))?; + tray.set_show_menu_on_left_click(false)?; + let _ = tray.set_tooltip(Some("CodeBurn")); + tray.on_menu_event(on_tray_menu_event); + tray.on_tray_icon_event(on_tray_icon_event); + + // The badge icon starts fully transparent and hidden; the frontend shows it once it has + // today's spend. Registering it right after the logo puts it beside the logo in the tray. + let blank = tauri::image::Image::new_owned( + vec![0u8; (BLANK_ICON_SIZE * BLANK_ICON_SIZE * 4) as usize], + BLANK_ICON_SIZE, + BLANK_ICON_SIZE, + ); + TrayIconBuilder::with_id(BADGE_TRAY_ID) + .icon(blank) + .tooltip("CodeBurn") + .menu(&menu) + .show_menu_on_left_click(false) + .on_menu_event(on_tray_menu_event) + .on_tray_icon_event(on_tray_icon_event) + .build(app)? + .set_visible(false)?; + + Ok(()) +} + +#[cfg(not(target_os = "linux"))] +const BLANK_ICON_SIZE: u32 = 16; + +#[cfg(not(target_os = "linux"))] +fn on_tray_menu_event(app: &AppHandle, event: tauri::menu::MenuEvent) { + match event.id.as_ref() { + "quit" => app.exit(0), + "open" => show_popover(app, None), + "refresh" => { + if let Some(window) = app.get_webview_window(POPOVER_LABEL) { + let _ = window.emit("codeburn://refresh", ()); + } + } + "toggle_theme" => { + if let Some(window) = app.get_webview_window(POPOVER_LABEL) { + let _ = window.emit("codeburn://toggle-theme", ()); + } + } + "report" => { + let _ = cli::spawn_in_terminal(app, &["report"]); + } + _ => {} + } +} + +#[cfg(not(target_os = "linux"))] +fn on_tray_icon_event(tray: &tauri::tray::TrayIcon, event: TrayIconEvent) { + match event { + TrayIconEvent::Click { + button: MouseButton::Left, + button_state: MouseButtonState::Up, + position, + .. + } + | TrayIconEvent::DoubleClick { + button: MouseButton::Left, + position, + .. + } => { + toggle_popover(tray.app_handle(), Some((position.x as i32, position.y as i32))); + } + _ => {} + } +} + +#[cfg(target_os = "linux")] +fn init_tray_linux(app: AppHandle, handle: tray_linux::LinuxTrayHandle) { + // Spawn the SNI tray on the Tokio runtime that Tauri already owns. + let spawn_app = app.clone(); + let spawn_handle = handle.clone(); + tauri::async_runtime::spawn(async move { + if let Err(err) = tray_linux::spawn(spawn_app, spawn_handle).await { + eprintln!("codeburn: failed to spawn Linux tray: {err}"); + } + }); + + // Left-click on the tray: show popover anchored to the click coordinates. + let activate_app = app.clone(); + app.listen_any("codeburn://tray-activate", move |event| { + let anchor = parse_click(event.payload()); + toggle_popover(&activate_app, anchor); + }); + + // Right-click / middle-click: same as left for now. Quit lives in the popover footer. + let secondary_app = app.clone(); + app.listen_any("codeburn://tray-secondary", move |event| { + let anchor = parse_click(event.payload()); + toggle_popover(&secondary_app, anchor); + }); +} + +#[cfg(target_os = "linux")] +fn parse_click(payload: &str) -> Option<(i32, i32)> { + let value: serde_json::Value = serde_json::from_str(payload).ok()?; + let x = value.get("x")?.as_i64()? as i32; + let y = value.get("y")?.as_i64()? as i32; + Some((x, y)) +} + +/// Undecorated windows are square by default; ask DWM for the Windows 11 rounded corner so +/// the acrylic backdrop is clipped to the same shape as the popover card. Silently ignored +/// on Windows 10, where the corners stay square. +#[cfg(target_os = "windows")] +fn round_window_corners(window: &tauri::WebviewWindow) { + use windows_sys::Win32::Graphics::Dwm::{ + DwmSetWindowAttribute, DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_ROUND, + }; + let Ok(hwnd) = window.hwnd() else { return }; + let preference: u32 = DWMWCP_ROUND as u32; + unsafe { + DwmSetWindowAttribute( + hwnd.0 as _, + DWMWA_WINDOW_CORNER_PREFERENCE as u32, + &preference as *const u32 as *const std::ffi::c_void, + std::mem::size_of::() as u32, + ); + } +} + +/// A blur immediately followed by the tray click that caused it would re-open the popover; +/// ignore show requests inside this window after a hide. +const TOGGLE_DEBOUNCE_MS: i64 = 300; + +fn now_ms() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as i64 +} + +/// Every path that hides the popover goes through here, so the debounce stamp and the +/// frontend's visibility signal can never drift apart. The frontend drops to its idle +/// refresh cadence on `codeburn://hidden` and comes back on `codeburn://shown`. +fn mark_hidden(app: &AppHandle) { + LAST_HIDDEN_MS.store(now_ms(), Ordering::Relaxed); + let _ = app.emit("codeburn://hidden", ()); +} + +fn toggle_popover(app: &AppHandle, anchor: Option<(i32, i32)>) { + let Some(window) = app.get_webview_window(POPOVER_LABEL) else { + return; + }; + if window.is_visible().unwrap_or(false) { + let _ = window.hide(); + mark_hidden(app); + return; + } + let last = LAST_HIDDEN_MS.load(Ordering::Relaxed); + if now_ms() - last < TOGGLE_DEBOUNCE_MS { + return; + } + show_popover(app, anchor); +} + +fn show_popover(app: &AppHandle, anchor: Option<(i32, i32)>) { + let Some(window) = app.get_webview_window(POPOVER_LABEL) else { + return; + }; + // Position before showing so the first frame is already in place (no jump). + position_popover(&window, anchor); + let _ = window.show(); + let _ = window.unminimize(); + position_popover(&window, anchor); + let _ = window.set_focus(); + let _ = window.emit("codeburn://shown", ()); +} + +/// Places the popover against the taskbar / panel edge of the monitor that owns the click +/// (or the cursor, when the request came from a menu). The work area already excludes the +/// taskbar on Windows and panels on Linux, so we never need to guess their heights: the +/// popover sits `MARGIN` inside the work area, horizontally centred on the anchor and +/// clamped to the screen. +fn position_popover(window: &tauri::WebviewWindow, anchor: Option<(i32, i32)>) { + const POPOVER_WIDTH_LOGICAL: f64 = 360.0; + const POPOVER_HEIGHT_LOGICAL: f64 = 660.0; + const MARGIN_LOGICAL: f64 = 8.0; + + let point = anchor + .filter(|(x, y)| *x > 0 || *y > 0) + .map(|(x, y)| (x as f64, y as f64)) + .or_else(|| window.cursor_position().ok().map(|p| (p.x, p.y))); + + let monitor = point + .and_then(|(x, y)| window.monitor_from_point(x, y).ok().flatten()) + .or_else(|| window.primary_monitor().ok().flatten()); + let Some(monitor) = monitor else { + return; + }; + + let scale = monitor.scale_factor(); + let pop_w = (POPOVER_WIDTH_LOGICAL * scale).round() as i32; + let pop_h = (POPOVER_HEIGHT_LOGICAL * scale).round() as i32; + let margin = (MARGIN_LOGICAL * scale).round() as i32; + + let area = monitor.work_area(); + let area_x = area.position.x; + let area_y = area.position.y; + let area_w = area.size.width as i32; + let area_h = area.size.height as i32; + let screen = monitor.size(); + let screen_pos = monitor.position(); + + let (anchor_x, anchor_y) = point + .map(|(x, y)| (x as i32, y as i32)) + .unwrap_or((area_x + area_w - pop_w / 2 - margin, area_y + area_h)); + + let min_x = area_x + margin; + let max_x = (area_x + area_w - pop_w - margin).max(min_x); + let x = (anchor_x - pop_w / 2).clamp(min_x, max_x); + + // Which edge holds the taskbar? Whichever side the work area was trimmed on. If the + // taskbar is at the top (or the anchor is in the top half with no bottom taskbar) the + // popover drops down from the top edge; otherwise it rises from the bottom edge. + let trimmed_top = area_y > screen_pos.y; + let trimmed_bottom = (area_y + area_h) < (screen_pos.y + screen.height as i32); + let anchor_in_top_half = anchor_y < screen_pos.y + (screen.height as i32) / 2; + let open_downward = trimmed_top || (!trimmed_bottom && anchor_in_top_half); + + let y = if open_downward { + area_y + margin + } else { + (area_y + area_h - pop_h - margin).max(area_y + margin) + }; + + let _ = window.set_position(tauri::PhysicalPosition::new(x, y)); +} + +mod commands { + use super::{AppState, POPOVER_LABEL}; + use serde_json::Value; + use tauri::{AppHandle, Manager, State}; + + #[tauri::command] + pub async fn fetch_payload( + period: String, + provider: String, + include_optimize: bool, + state: State<'_, AppState>, + ) -> Result { + let cli = state.cli.lock().map_err(|e| e.to_string())?.clone(); + cli.fetch_menubar_payload(&period, &provider, include_optimize) + .await + .map_err(|e| e.to_string()) + } + + /// Re-resolves the CLI each call so a freshly installed `codeburn` is picked up + /// without restarting the tray app. + #[tauri::command] + pub async fn cli_status(state: State<'_, AppState>) -> Result { + let fresh = crate::cli::CodeburnCli::resolve(); + let status = fresh.status().await; + if status.found { + if let Ok(mut guard) = state.cli.lock() { + *guard = fresh; + } + } + Ok(status) + } + + #[tauri::command] + pub async fn set_currency( + code: String, + state: State<'_, AppState>, + ) -> Result { + let symbol = crate::fx::symbol_for(&code); + let rate = state + .fx + .rate_for(&code) + .await + .ok_or_else(|| format!("Exchange rate for {code} is unavailable right now"))?; + state + .config + .lock() + .map_err(|e| e.to_string())? + .set_currency(&code, &symbol) + .map_err(|e| e.to_string())?; + Ok(crate::fx::CurrencyApplied { code, symbol, rate }) + } + + #[tauri::command] + pub fn open_terminal_command(app: AppHandle, args: Vec) -> Result<(), String> { + let args: Vec<&str> = args.iter().map(String::as_str).collect(); + crate::cli::spawn_in_terminal(&app, &args).map_err(|e| e.to_string()) + } + + #[tauri::command] + pub fn open_claude_login(app: AppHandle) -> Result<(), String> { + crate::cli::spawn_claude_login(&app).map_err(|e| e.to_string()) + } + + #[tauri::command] + pub fn quit_app(app: AppHandle) { + app.exit(0); + } + + #[tauri::command] + pub fn hide_popover(app: AppHandle) { + if let Some(window) = app.get_webview_window(POPOVER_LABEL) { + let _ = window.hide(); + super::mark_hidden(&app); + } + } + + /// The tray cannot render text on Windows, so today's spend lives in the tooltip. + #[tauri::command] + pub fn set_tray_tooltip(app: AppHandle, text: String) { + #[cfg(not(target_os = "linux"))] + for id in [super::TRAY_ID, super::BADGE_TRAY_ID] { + if let Some(tray) = app.tray_by_id(id) { + let _ = tray.set_tooltip(Some(text.as_str())); + } + } + #[cfg(target_os = "linux")] + { + let _ = (app, text); + } + } + + /// `text` is a short spend string ("$87", "142", "1.2K"); `None` hides the badge icon. + #[tauri::command] + pub fn set_tray_badge(app: AppHandle, text: Option) -> Result<(), String> { + #[cfg(target_os = "linux")] + { + // Unreachable from the UI: the frontend hides the control wherever the badge is + // unsupported (lib/platform.ts). Saying so beats reporting a success that never + // happened. + let _ = (app, text); + Err("the tray spend badge needs a second tray icon, which the Linux SNI tray does not provide".to_string()) + } + #[cfg(not(target_os = "linux"))] + { + let Some(badge) = app.tray_by_id(super::BADGE_TRAY_ID) else { + return Ok(()); + }; + match text.as_deref().map(str::trim).filter(|t| !t.is_empty()) { + Some(t) => { + let icon = crate::tray_badge::render( + t, + crate::tray_badge::small_icon_size(), + crate::tray_badge::taskbar_is_dark(), + ); + // Windows can only modify an icon that is currently shown, so show + // first (re-adds the previous bitmap) and then swap the bitmap. + badge.set_visible(true).map_err(|e| e.to_string())?; + badge.set_icon(Some(icon)).map_err(|e| e.to_string())?; + } + None => { + badge.set_visible(false).map_err(|e| e.to_string())?; + } + } + Ok(()) + } + } + + #[tauri::command] + pub fn app_version(app: AppHandle) -> String { + app.package_info().version.to_string() + } + + #[tauri::command] + pub fn launch_at_login() -> bool { + crate::autostart::is_enabled() + } + + #[tauri::command] + pub fn set_launch_at_login(enabled: bool) -> Result { + crate::autostart::set_enabled(enabled).map_err(|e| e.to_string())?; + Ok(crate::autostart::is_enabled()) + } + + #[tauri::command] + pub async fn plan_usage(state: State<'_, AppState>) -> Result { + state.plan.fetch().await.map_err(|e| e.to_string()) + } +} diff --git a/windows/src-tauri/src/main.rs b/windows/src-tauri/src/main.rs new file mode 100644 index 00000000..b79df4b0 --- /dev/null +++ b/windows/src-tauri/src/main.rs @@ -0,0 +1,6 @@ +// Stops an extra console window appearing on Windows in release builds. +#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] + +fn main() { + codeburn_menubar_lib::run() +} diff --git a/windows/src-tauri/src/plan.rs b/windows/src-tauri/src/plan.rs new file mode 100644 index 00000000..98fbbff2 --- /dev/null +++ b/windows/src-tauri/src/plan.rs @@ -0,0 +1,479 @@ +//! Claude subscription usage (the "Plan" insight). Mirrors the macOS SubscriptionClient: +//! read Claude Code's OAuth credentials, call the usage endpoint, adopt a token Claude Code +//! has already rotated on 401 (never spending the shared refresh token), and keep a rolling +//! snapshot file so a freshly reset window can still show last cycle's final. + +use std::fs; +use std::path::PathBuf; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use anyhow::{bail, Context, Result}; +use serde::{Deserialize, Serialize}; +use tokio::sync::Mutex; + +const CREDENTIALS_RELATIVE_PATH: &str = ".claude/.credentials.json"; +const USAGE_URL: &str = "https://api.anthropic.com/api/oauth/usage"; +const BETA_HEADER: &str = "oauth-2025-04-20"; +const USER_AGENT: &str = "claude-code/2.1.0"; +const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); +const MAX_CREDENTIAL_BYTES: u64 = 64 * 1024; +const SNAPSHOT_FILENAME: &str = "subscription-snapshots.json"; +const SNAPSHOT_RETENTION: Duration = Duration::from_secs(30 * 24 * 3600); +const WINDOW_KEYS: [(&str, &str); 4] = [ + ("five_hour", "5-hour window"), + ("seven_day", "7-day total"), + ("seven_day_opus", "7-day Opus"), + ("seven_day_sonnet", "7-day Sonnet"), +]; + +#[derive(Debug, Clone, Serialize)] +pub struct PlanWindow { + pub key: String, + pub label: String, + /// 0..100 + pub percent: f64, + /// RFC 3339 timestamp of the next reset, when the API supplied one. + pub resets_at: Option, + /// Final percent reached in the immediately prior cycle, from the snapshot store. + pub previous_final: Option, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(tag = "state", rename_all = "snake_case")] +pub enum PlanUsage { + Ok { + tier: String, + raw_tier: Option, + windows: Vec, + fetched_at: String, + }, + NoCredentials, + Failed { + message: String, + }, +} + +pub struct PlanClient { + snapshot_lock: Mutex<()>, +} + +impl PlanClient { + pub fn new() -> Self { + PlanClient { + snapshot_lock: Mutex::new(()), + } + } + + pub async fn fetch(&self) -> Result { + let creds = match load_credentials() { + Ok(Some(c)) => c, + Ok(None) => return Ok(PlanUsage::NoCredentials), + Err(err) => { + return Ok(PlanUsage::Failed { + message: err.to_string(), + }) + } + }; + + let response = match fetch_usage(&creds.access_token).await { + Ok(r) => r, + // Parity with mac/Sources/CodeBurnMenubar/Data/ClaudeCredentialStore.swift + // (`refreshAfter401`): Claude's refresh token is single-use and rotates, so + // spending it here would invalidate the token Claude Code itself is holding and + // break the user's `claude` login. Instead re-read Claude's own store for a + // token it has already rotated; if there is nothing fresher yet, report a + // transient failure and let the next refresh pick it up. + Err(FetchError::Unauthorized) => { + let rotated = load_credentials() + .ok() + .flatten() + .map(|c| c.access_token) + .filter(|t| *t != creds.access_token); + let Some(token) = rotated else { + return Ok(PlanUsage::Failed { + message: "Claude is refreshing its session. This clears itself once Claude Code renews the token; run `claude login` if it persists.".into(), + }); + }; + match fetch_usage(&token).await { + Ok(r) => r, + Err(err) => { + return Ok(PlanUsage::Failed { + message: err.to_string(), + }) + } + } + } + Err(err) => { + return Ok(PlanUsage::Failed { + message: err.to_string(), + }) + } + }; + + let now = SystemTime::now(); + let mut windows = Vec::new(); + for (key, label) in WINDOW_KEYS { + let Some(window) = response.window(key) else { continue }; + let Some(percent) = window.utilization else { continue }; + let resets_at = window.resets_at.clone().filter(|s| !s.is_empty()); + let previous_final = { + let _guard = self.snapshot_lock.lock().await; + if let Some(reset) = resets_at.as_deref() { + record_snapshot(key, percent, reset, now); + previous_window_final(key, reset) + } else { + None + } + }; + windows.push(PlanWindow { + key: key.to_string(), + label: label.to_string(), + percent: percent.clamp(0.0, 100.0), + resets_at, + previous_final, + }); + } + + Ok(PlanUsage::Ok { + tier: tier_display(creds.rate_limit_tier.as_deref()), + raw_tier: creds.rate_limit_tier, + windows, + fetched_at: to_rfc3339(now), + }) + } +} + +// ---- credentials ----------------------------------------------------------------------- + +struct StoredCredentials { + access_token: String, + rate_limit_tier: Option, +} + +#[derive(Deserialize)] +struct CredentialsRoot { + #[serde(rename = "claudeAiOauth")] + claude_ai_oauth: Option, +} + +#[derive(Deserialize)] +struct OAuthBlock { + #[serde(rename = "accessToken")] + access_token: Option, + #[serde(rename = "rateLimitTier")] + rate_limit_tier: Option, +} + +fn credentials_path() -> Option { + dirs::home_dir().map(|h| h.join(CREDENTIALS_RELATIVE_PATH)) +} + +/// Ok(None) when the file does not exist (user never logged in); Err for malformed data. +fn load_credentials() -> Result> { + let Some(path) = credentials_path() else { + return Ok(None); + }; + let meta = match fs::symlink_metadata(&path) { + Ok(m) => m, + Err(_) => return Ok(None), + }; + if meta.file_type().is_symlink() { + bail!("credentials file is a symlink; refusing to read it"); + } + if meta.len() > MAX_CREDENTIAL_BYTES { + bail!("credentials file is unexpectedly large"); + } + let bytes = fs::read(&path).with_context(|| "failed to read Claude credentials")?; + let root: CredentialsRoot = + serde_json::from_slice(&bytes).with_context(|| "Claude credentials are malformed")?; + let Some(oauth) = root.claude_ai_oauth else { + return Ok(None); + }; + let token = oauth.access_token.unwrap_or_default().trim().to_string(); + if token.is_empty() { + return Ok(None); + } + Ok(Some(StoredCredentials { + access_token: token, + rate_limit_tier: oauth.rate_limit_tier, + })) +} + +fn tier_display(raw: Option<&str>) -> String { + let Some(raw) = raw.map(|r| r.to_lowercase()) else { + return "Subscription".into(); + }; + if raw.contains("max_20x") || raw.contains("max20x") || raw.contains("max-20x") { + return "Max 20x".into(); + } + if raw.contains("max_5x") || raw.contains("max5x") || raw.contains("max-5x") { + return "Max 5x".into(); + } + if raw.contains("max") { + return "Max 5x".into(); + } + if raw.contains("pro") { + return "Pro".into(); + } + if raw.contains("team") { + return "Team".into(); + } + if raw.contains("enterprise") { + return "Enterprise".into(); + } + "Subscription".into() +} + +// ---- HTTP ------------------------------------------------------------------------------ + +#[derive(Debug, Deserialize)] +struct UsageResponse { + five_hour: Option, + seven_day: Option, + seven_day_opus: Option, + seven_day_sonnet: Option, +} + +impl UsageResponse { + fn window(&self, key: &str) -> Option<&Window> { + match key { + "five_hour" => self.five_hour.as_ref(), + "seven_day" => self.seven_day.as_ref(), + "seven_day_opus" => self.seven_day_opus.as_ref(), + "seven_day_sonnet" => self.seven_day_sonnet.as_ref(), + _ => None, + } + } +} + +#[derive(Debug, Deserialize)] +struct Window { + utilization: Option, + resets_at: Option, +} + +#[derive(Debug, thiserror::Error)] +enum FetchError { + #[error("Claude session is no longer authorized")] + Unauthorized, + #[error("Usage fetch failed ({0}){1}")] + Http(u16, String), + #[error("{0}")] + Other(String), +} + +fn client() -> Result { + reqwest::Client::builder() + .timeout(REQUEST_TIMEOUT) + .https_only(true) + .build() + .map_err(|e| FetchError::Other(e.to_string())) +} + +async fn fetch_usage(token: &str) -> Result { + let response = client()? + .get(USAGE_URL) + .bearer_auth(token) + .header("Accept", "application/json") + .header("anthropic-beta", BETA_HEADER) + .header("User-Agent", USER_AGENT) + .send() + .await + .map_err(|e| FetchError::Other(e.to_string()))?; + let status = response.status(); + if status.as_u16() == 401 { + return Err(FetchError::Unauthorized); + } + if !status.is_success() { + let body = response.text().await.unwrap_or_default(); + let detail = if body.is_empty() { String::new() } else { format!(": {}", truncate(&body, 200)) }; + return Err(FetchError::Http(status.as_u16(), detail)); + } + response + .json::() + .await + .map_err(|e| FetchError::Other(format!("Decode failed: {e}"))) +} + +fn truncate(text: &str, max: usize) -> String { + let mut out: String = text.chars().take(max).collect(); + if text.chars().count() > max { + out.push_str("..."); + } + out +} + +// ---- snapshots ------------------------------------------------------------------------- + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct Snapshot { + #[serde(rename = "windowKey")] + window_key: String, + percent: f64, + #[serde(rename = "resetsAt")] + resets_at: String, + #[serde(rename = "capturedAt")] + captured_at: String, + #[serde(rename = "effectiveTokens")] + effective_tokens: Option, +} + +/// None when there is no cache dir and no home dir: writing the snapshot store into the +/// process's current directory would scatter a file wherever the tray happened to be +/// launched from, so we simply skip snapshots instead. +fn snapshots_path() -> Option { + std::env::var_os("CODEBURN_CACHE_DIR") + .map(PathBuf::from) + .or_else(|| dirs::home_dir().map(|h| h.join(".cache").join("codeburn"))) + .map(|dir| dir.join(SNAPSHOT_FILENAME)) +} + +fn load_snapshots() -> Vec { + snapshots_path() + .and_then(|p| fs::read(p).ok()) + .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + .unwrap_or_default() +} + +/// Mirrors `mac/Sources/CodeBurnMenubar/Security/SafeFile.swift`: write to a temp file with +/// owner-only permissions and rename over the target, and refuse a target that has been +/// replaced by a symlink pointing somewhere else. +fn save_snapshots(all: &[Snapshot]) { + let Some(path) = snapshots_path() else { return }; + if let Ok(meta) = fs::symlink_metadata(&path) { + if meta.file_type().is_symlink() { + return; + } + } + if let Some(parent) = path.parent() { + let _ = fs::create_dir_all(parent); + } + let Ok(bytes) = serde_json::to_vec_pretty(all) else { return }; + let tmp = path.with_extension("tmp"); + let mut options = fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let Ok(mut file) = options.open(&tmp) else { return }; + use std::io::Write; + if file.write_all(&bytes).is_ok() && file.flush().is_ok() { + drop(file); + let _ = fs::rename(&tmp, &path); + } else { + drop(file); + let _ = fs::remove_file(&tmp); + } +} + +fn record_snapshot(window_key: &str, percent: f64, resets_at: &str, now: SystemTime) { + let mut all = load_snapshots(); + match all + .iter_mut() + .find(|s| s.window_key == window_key && s.resets_at == resets_at) + { + Some(existing) => { + if percent > existing.percent { + existing.percent = percent; + existing.captured_at = to_rfc3339(now); + } + } + None => all.push(Snapshot { + window_key: window_key.to_string(), + percent, + resets_at: resets_at.to_string(), + captured_at: to_rfc3339(now), + effective_tokens: None, + }), + } + let cutoff = now.checked_sub(SNAPSHOT_RETENTION).unwrap_or(UNIX_EPOCH); + all.retain(|s| parse_rfc3339(&s.captured_at).map(|t| t >= cutoff).unwrap_or(true)); + save_snapshots(&all); +} + +fn previous_window_final(window_key: &str, current_resets_at: &str) -> Option { + let current = parse_rfc3339(current_resets_at)?; + let all = load_snapshots(); + let priors: Vec<(SystemTime, f64)> = all + .iter() + .filter(|s| s.window_key == window_key) + .filter_map(|s| parse_rfc3339(&s.resets_at).map(|t| (t, s.percent))) + .filter(|(t, _)| *t < current) + .collect(); + let latest = priors.iter().map(|(t, _)| *t).max()?; + priors + .iter() + .filter(|(t, _)| *t == latest) + .map(|(_, p)| *p) + .fold(None, |acc: Option, p| Some(acc.map_or(p, |a| a.max(p)))) +} + +// ---- time helpers (RFC 3339 without pulling in chrono) -------------------------------- + +fn to_rfc3339(t: SystemTime) -> String { + let secs = t.duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) as i64; + let (y, m, d, hh, mm, ss) = civil_from_unix(secs); + format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z") +} + +/// Accepts `2026-08-18T10:00:00Z`, with optional fractional seconds and `+hh:mm` offsets. +fn parse_rfc3339(text: &str) -> Option { + let bytes = text.as_bytes(); + if bytes.len() < 19 { + return None; + } + let num = |a: usize, b: usize| text.get(a..b)?.parse::().ok(); + let (y, mo, d) = (num(0, 4)?, num(5, 7)?, num(8, 10)?); + let (h, mi, s) = (num(11, 13)?, num(14, 16)?, num(17, 19)?); + let mut rest = &text[19..]; + if rest.starts_with('.') { + let end = rest[1..] + .find(|c: char| !c.is_ascii_digit()) + .map(|i| i + 1) + .unwrap_or(rest.len()); + rest = &rest[end..]; + } + let offset_secs = match rest { + "" | "Z" | "z" => 0, + _ => { + let sign = if rest.starts_with('-') { -1 } else { 1 }; + let oh = rest.get(1..3)?.parse::().ok()?; + let om = rest.get(4..6)?.parse::().ok()?; + sign * (oh * 3600 + om * 60) + } + }; + let unix = unix_from_civil(y, mo, d) + h * 3600 + mi * 60 + s - offset_secs; + if unix < 0 { + return None; + } + Some(UNIX_EPOCH + Duration::from_secs(unix as u64)) +} + +fn unix_from_civil(y: i64, m: i64, d: i64) -> i64 { + // Howard Hinnant's days_from_civil. + let y = if m <= 2 { y - 1 } else { y }; + let era = if y >= 0 { y } else { y - 399 } / 400; + let yoe = y - era * 400; + let mp = (m + 9) % 12; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + (era * 146_097 + doe - 719_468) * 86_400 +} + +fn civil_from_unix(secs: i64) -> (i64, i64, i64, i64, i64, i64) { + let days = secs.div_euclid(86_400); + let rem = secs.rem_euclid(86_400); + let z = days + 719_468; + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = if m <= 2 { y + 1 } else { y }; + (y, m, d, rem / 3600, (rem % 3600) / 60, rem % 60) +} diff --git a/windows/src-tauri/src/tray_badge.rs b/windows/src-tauri/src/tray_badge.rs new file mode 100644 index 00000000..5411d59f --- /dev/null +++ b/windows/src-tauri/src/tray_badge.rs @@ -0,0 +1,252 @@ +//! Renders today's spend into the tray icon. Windows and most Linux panels cannot place a +//! title next to a tray icon the way the macOS menubar does, so the number becomes the icon: +//! a 4x7 pixel font drawn at the panel's native small-icon size, so it stays crisp instead +//! of being a scaled-down bitmap. + +use tauri::image::Image; + +const GLYPH_HEIGHT: usize = 7; +const BASE_ICON_SIZE: u32 = 16; +const GLYPH_GAP: usize = 1; +/// Brand accent on a light taskbar, the lighter ember on a dark one. +const ACCENT_LIGHT_TASKBAR: [u8; 3] = [0xC9, 0x52, 0x1D]; +const ACCENT_DARK_TASKBAR: [u8; 3] = [0xF0, 0x8A, 0x55]; + +struct Glyph { + width: usize, + rows: [&'static str; GLYPH_HEIGHT], +} + +fn glyph(c: char) -> Option { + let g = |width: usize, rows: [&'static str; GLYPH_HEIGHT]| Some(Glyph { width, rows }); + match c { + '0' => g(4, [".##.", "#..#", "#..#", "#..#", "#..#", "#..#", ".##."]), + '1' => g(3, [".#.", "##.", ".#.", ".#.", ".#.", ".#.", "###"]), + '2' => g(4, [".##.", "#..#", "...#", "..#.", ".#..", "#...", "####"]), + '3' => g(4, ["###.", "...#", "...#", ".##.", "...#", "...#", "###."]), + '4' => g(4, ["#..#", "#..#", "#..#", "####", "...#", "...#", "...#"]), + '5' => g(4, ["####", "#...", "#...", "###.", "...#", "...#", "###."]), + '6' => g(4, [".##.", "#...", "#...", "###.", "#..#", "#..#", ".##."]), + '7' => g(4, ["####", "...#", "..#.", "..#.", ".#..", ".#..", ".#.."]), + '8' => g(4, [".##.", "#..#", "#..#", ".##.", "#..#", "#..#", ".##."]), + '9' => g(4, [".##.", "#..#", "#..#", ".###", "...#", "...#", ".##."]), + '$' => g(4, ["..#.", ".###", "#.#.", ".##.", ".#.#", "###.", "..#."]), + 'K' => g(4, ["#..#", "#.#.", "##..", "#...", "##..", "#.#.", "#..#"]), + 'M' => g(4, ["#..#", "####", "####", "#..#", "#..#", "#..#", "#..#"]), + '.' => g(1, [".", ".", ".", ".", ".", ".", "#"]), + _ => None, + } +} + +fn text_width(text: &str) -> usize { + let glyphs: Vec = text.chars().filter_map(glyph).collect(); + if glyphs.is_empty() { + return 0; + } + glyphs.iter().map(|g| g.width).sum::() + GLYPH_GAP * (glyphs.len() - 1) +} + +/// Draws `text` centred in a `size` x `size` RGBA icon. Prefers anti-aliased bold system +/// text (far more legible at 16px than 1px pixel strokes); falls back to the pixel font +/// when no usable font file is present. +pub fn render(text: &str, size: u32, dark_taskbar: bool) -> Image<'static> { + let color = if dark_taskbar { ACCENT_DARK_TASKBAR } else { ACCENT_LIGHT_TASKBAR }; + if let Some(image) = render_with_font(text, size, color) { + return image; + } + // The pixel font cannot shrink, so trim from the right until the string fits. + let mut trimmed: String = text.to_string(); + while !fits(&trimmed) && trimmed.pop().is_some() {} + render_pixel_font(&trimmed, size, dark_taskbar) +} + +/// Bold sans faces shipped with Windows, best first. Bahnschrift's condensed numerals fit +/// four glyphs into 16px at a larger size than Segoe UI Bold does. +#[cfg(target_os = "windows")] +const FONT_CANDIDATES: [&str; 3] = [ + r"C:\Windows\Fonts\bahnschrift.ttf", + r"C:\Windows\Fonts\segoeuib.ttf", + r"C:\Windows\Fonts\arialbd.ttf", +]; +#[cfg(not(target_os = "windows"))] +const FONT_CANDIDATES: [&str; 3] = [ + "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", + "/usr/share/fonts/TTF/DejaVuSans-Bold.ttf", + "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", +]; + +/// Largest and smallest text sizes tried, as a fraction of the icon size. +const FONT_MAX_FRACTION: f32 = 0.95; +const FONT_MIN_FRACTION: f32 = 0.5; +const FONT_STEP_PX: f32 = 0.5; + +/// Read and parsed once: the badge re-renders on every refresh and the font file does not +/// change under a running session. +fn font() -> Option<&'static fontdue::Font> { + static FONT: std::sync::OnceLock> = std::sync::OnceLock::new(); + FONT.get_or_init(load_font).as_ref() +} + +fn load_font() -> Option { + for path in FONT_CANDIDATES { + if let Ok(bytes) = std::fs::read(path) { + if let Ok(font) = fontdue::Font::from_bytes(bytes, fontdue::FontSettings::default()) { + return Some(font); + } + } + } + None +} + +struct Raster { + metrics: fontdue::Metrics, + bitmap: Vec, +} + +fn layout(font: &fontdue::Font, text: &str, px: f32) -> (Vec, f32, i32, i32) { + let glyphs: Vec = text + .chars() + .map(|c| { + let (metrics, bitmap) = font.rasterize(c, px); + Raster { metrics, bitmap } + }) + .collect(); + let width: f32 = glyphs.iter().map(|g| g.metrics.advance_width).sum(); + let top = glyphs.iter().map(|g| g.metrics.height as i32 + g.metrics.ymin).max().unwrap_or(0); + let bottom = glyphs.iter().map(|g| g.metrics.ymin).min().unwrap_or(0); + (glyphs, width, top, bottom) +} + +fn render_with_font(text: &str, size: u32, color: [u8; 3]) -> Option> { + let font = font()?; + let limit = size as f32; + let mut px = limit * FONT_MAX_FRACTION; + let mut chosen = None; + while px >= limit * FONT_MIN_FRACTION { + let (glyphs, width, top, bottom) = layout(font, text, px); + let height = (top - bottom) as f32; + if width <= limit && height <= limit { + chosen = Some((glyphs, width, top, bottom)); + break; + } + px -= FONT_STEP_PX; + } + let (glyphs, width, top, bottom) = chosen?; + + let mut rgba = vec![0u8; (size * size * 4) as usize]; + let height = top - bottom; + let x0 = ((limit - width) / 2.0).round(); + let baseline = ((size as i32 - height) / 2) + top; + let mut pen = x0; + for g in &glyphs { + let gx = pen.round() as i32 + g.metrics.xmin; + let gy = baseline - g.metrics.height as i32 - g.metrics.ymin; + for row in 0..g.metrics.height { + for col in 0..g.metrics.width { + let alpha = g.bitmap[row * g.metrics.width + col]; + if alpha == 0 { + continue; + } + let px_x = gx + col as i32; + let px_y = gy + row as i32; + if px_x < 0 || px_y < 0 || px_x >= size as i32 || px_y >= size as i32 { + continue; + } + let i = ((px_y as u32 * size + px_x as u32) * 4) as usize; + let existing = rgba[i + 3]; + let merged = existing.max(alpha); + rgba[i] = color[0]; + rgba[i + 1] = color[1]; + rgba[i + 2] = color[2]; + rgba[i + 3] = merged; + } + } + pen += g.metrics.advance_width; + } + Some(Image::new_owned(rgba, size, size)) +} + +fn render_pixel_font(text: &str, size: u32, dark_taskbar: bool) -> Image<'static> { + let size = size.max(BASE_ICON_SIZE); + let scale = (size / BASE_ICON_SIZE).max(1) as usize; + let mut rgba = vec![0u8; (size * size * 4) as usize]; + let color = if dark_taskbar { ACCENT_DARK_TASKBAR } else { ACCENT_LIGHT_TASKBAR }; + + let width = text_width(text) * scale; + let height = GLYPH_HEIGHT * scale; + let mut x = (size as usize).saturating_sub(width) / 2; + let y0 = (size as usize).saturating_sub(height) / 2; + + for g in text.chars().filter_map(glyph) { + for (row, bits) in g.rows.iter().enumerate() { + for (col, ch) in bits.chars().enumerate() { + if ch != '#' { + continue; + } + for dy in 0..scale { + for dx in 0..scale { + let px = x + col * scale + dx; + let py = y0 + row * scale + dy; + if px < size as usize && py < size as usize { + let i = (py * size as usize + px) * 4; + rgba[i] = color[0]; + rgba[i + 1] = color[1]; + rgba[i + 2] = color[2]; + rgba[i + 3] = 0xFF; + } + } + } + } + } + x += (g.width + GLYPH_GAP) * scale; + } + + Image::new_owned(rgba, size, size) +} + +/// Whether the text fits the 16px pixel-font grid (the font path scales itself to fit). +fn fits(text: &str) -> bool { + text_width(text) <= BASE_ICON_SIZE as usize +} + +/// The panel's small-icon size in physical pixels (16 at 100%, 20 at 125%, 24 at 150%). +#[cfg(target_os = "windows")] +pub fn small_icon_size() -> u32 { + use windows_sys::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_CXSMICON}; + let px = unsafe { GetSystemMetrics(SM_CXSMICON) }; + if px > 0 { px as u32 } else { BASE_ICON_SIZE } +} + +#[cfg(not(target_os = "windows"))] +pub fn small_icon_size() -> u32 { + 22 +} + +/// Windows keeps the taskbar theme separate from the app theme; the number must contrast +/// with the taskbar, not the popover. +#[cfg(target_os = "windows")] +pub fn taskbar_is_dark() -> bool { + // Absolute `reg.exe` out of System32 -- this runs on every badge refresh, so a bare + // name here would be the single most reliably triggered planted-binary path. + let output = crate::cli::system_command("reg.exe") + .args([ + "query", + r"HKCU\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", + "/v", + "SystemUsesLightTheme", + ]) + .output(); + match output { + Ok(out) => { + let text = String::from_utf8_lossy(&out.stdout); + // "0x0" means the system (taskbar) uses the dark theme. + text.lines().any(|l| l.contains("SystemUsesLightTheme") && l.trim_end().ends_with("0x0")) + } + Err(_) => true, + } +} + +#[cfg(not(target_os = "windows"))] +pub fn taskbar_is_dark() -> bool { + true +} diff --git a/windows/src-tauri/src/tray_linux.rs b/windows/src-tauri/src/tray_linux.rs new file mode 100644 index 00000000..c57cb5c2 --- /dev/null +++ b/windows/src-tauri/src/tray_linux.rs @@ -0,0 +1,139 @@ +use std::sync::{Arc, Mutex}; + +use ksni::{Category, Icon, Status, ToolTip, Tray, TrayMethods}; +use tauri::{AppHandle, Emitter}; + +/// StatusNotifierItem-backed tray for Linux. Bypasses libappindicator so left-click +/// fires `activate(x, y)` with real screen coordinates, which is what Tauri's Linux +/// tray path cannot deliver. See tauri-apps/tauri#7283 for the upstream gap. +/// +/// No menu() is exported. Exporting a menu causes most SNI hosts (notably +/// gnome-shell-extension-appindicator) to swallow left-click as a menu-open and +/// never fire Activate. Quit/Refresh/Open Full Report live in the popover footer. +pub struct CodeburnTray { + app: AppHandle, + title: String, + icon: Vec, +} + +impl CodeburnTray { + fn new(app: AppHandle, icon: Vec) -> Self { + Self { + app, + title: "CodeBurn".to_string(), + icon, + } + } +} + +impl Tray for CodeburnTray { + fn id(&self) -> String { + "org.agentseal.codeburn".to_string() + } + + fn title(&self) -> String { + self.title.clone() + } + + fn category(&self) -> Category { + Category::ApplicationStatus + } + + fn status(&self) -> Status { + Status::Active + } + + fn icon_pixmap(&self) -> Vec { + self.icon.clone() + } + + fn tool_tip(&self) -> ToolTip { + ToolTip { + icon_name: String::new(), + icon_pixmap: Vec::new(), + title: "CodeBurn".to_string(), + description: self.title.clone(), + } + } + + fn activate(&mut self, x: i32, y: i32) { + let _ = self + .app + .emit("codeburn://tray-activate", TrayClick { x, y }); + } + + fn secondary_activate(&mut self, x: i32, y: i32) { + let _ = self + .app + .emit("codeburn://tray-secondary", TrayClick { x, y }); + } +} + +#[derive(Clone, serde::Serialize)] +struct TrayClick { + x: i32, + y: i32, +} + +/// Type-erased handle for the Linux tray so callers can push title updates without +/// naming the `ksni::Handle` generic parameter across module boundaries. +#[derive(Clone)] +pub struct LinuxTrayHandle { + inner: Arc>>>, +} + +impl LinuxTrayHandle { + pub fn empty() -> Self { + Self { + inner: Arc::new(Mutex::new(None)), + } + } + + fn set(&self, handle: ksni::Handle) { + if let Ok(mut guard) = self.inner.lock() { + *guard = Some(handle); + } + } + +} + +/// Decode the bundled tray.png into ARGB32 pixels that the SNI spec expects. +/// Falls back to an empty icon list (host shows a broken-icon placeholder) if the +/// asset can't be decoded. We'd rather render a blank icon than crash the tray. +fn load_icon() -> Vec { + // Embedded at build time so the binary is self-contained. + let bytes = include_bytes!("../icons/tray.png"); + let Ok(decoder) = png::Decoder::new(bytes.as_slice()).read_info().map_err(|_| ()) else { + return Vec::new(); + }; + decode_png(decoder) +} + +fn decode_png(mut reader: png::Reader<&[u8]>) -> Vec { + let info = reader.info().clone(); + let width = info.width as i32; + let height = info.height as i32; + let mut buf = vec![0u8; reader.output_buffer_size()]; + if reader.next_frame(&mut buf).is_err() { + return Vec::new(); + } + // SNI expects ARGB32 in network byte order. PNG decoder gives RGBA8. + let pixel_count = (width as usize) * (height as usize); + let mut argb = Vec::with_capacity(pixel_count * 4); + for chunk in buf.chunks_exact(4) { + let (r, g, b, a) = (chunk[0], chunk[1], chunk[2], chunk[3]); + argb.extend_from_slice(&[a, r, g, b]); + } + vec![Icon { + width, + height, + data: argb, + }] +} + +pub async fn spawn(app: AppHandle, handle_out: LinuxTrayHandle) -> anyhow::Result<()> { + let tray = CodeburnTray::new(app, load_icon()); + let handle = tray.spawn().await?; + handle_out.set(handle); + Ok(()) +} diff --git a/windows/src-tauri/tauri.conf.json b/windows/src-tauri/tauri.conf.json new file mode 100644 index 00000000..a063413f --- /dev/null +++ b/windows/src-tauri/tauri.conf.json @@ -0,0 +1,64 @@ +{ + "$schema": "https://schema.tauri.app/config/2", + "productName": "CodeBurn Menubar", + "version": "0.9.20", + "identifier": "org.agentseal.codeburn-menubar", + "build": { + "beforeDevCommand": "npm run dev", + "devUrl": "http://localhost:1420", + "beforeBuildCommand": "npm run build", + "frontendDist": "../dist" + }, + "app": { + "windows": [ + { + "label": "popover", + "title": "CodeBurn", + "width": 360, + "height": 660, + "decorations": false, + "transparent": true, + "resizable": false, + "alwaysOnTop": true, + "skipTaskbar": true, + "visible": false, + "focus": false, + "shadow": true, + "windowEffects": { + "effects": ["acrylic"], + "state": "active" + } + } + ], + "security": { + "csp": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; connect-src 'self' ipc: https://api.frankfurter.app" + }, + "trayIcon": { + "id": "codeburn-tray", + "iconPath": "icons/tray.png", + "iconAsTemplate": false, + "tooltip": "CodeBurn" + } + }, + "bundle": { + "active": true, + "category": "Utility", + "shortDescription": "AI coding cost tracker", + "longDescription": "Shows today's AI coding spend in your system tray. Popover breaks down cost by activity, model, and provider across Claude Code, Cursor, Codex, and more.", + "publisher": "AgentSeal", + "homepage": "https://github.com/getagentseal/codeburn", + "targets": ["deb", "rpm", "appimage", "msi"], + "icon": [ + "icons/32x32.png", + "icons/128x128.png", + "icons/128x128@2x.png", + "icons/icon.png", + "icons/icon.ico" + ], + "linux": { + "deb": { + "depends": ["libwebkit2gtk-4.1-0", "libayatana-appindicator3-1"] + } + } + } +} diff --git a/windows/src/App.tsx b/windows/src/App.tsx new file mode 100644 index 00000000..77281597 --- /dev/null +++ b/windows/src/App.tsx @@ -0,0 +1,377 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { invoke } from '@tauri-apps/api/core' +import { listen } from '@tauri-apps/api/event' + +import type { MenubarPayload } from './lib/payload' +import type { CurrencyState } from './lib/currency' +import { USD, formatCurrency, trayBadgeText } from './lib/currency' +import { PayloadCache } from './lib/cache' +import { relativePast } from './lib/dates' +import { applyTheme, currentTheme, readSetting, writeSetting } from './lib/settings' +import { TRAY_BADGE_SUPPORTED } from './lib/platform' +import { AgentTabStrip, detectedProviders } from './components/AgentTabStrip' +import type { Provider } from './components/AgentTabStrip' +import { ModelsSection } from './components/ModelsSection' +import { InsightPills, INSIGHT_ORDER, isInsightMode, type InsightMode } from './components/InsightPills' +import { TrendInsight } from './components/TrendInsight' +import { ForecastInsight } from './components/ForecastInsight' +import { PulseInsight } from './components/PulseInsight' +import { StatsInsight } from './components/StatsInsight' +import { PlanInsight } from './components/PlanInsight' +import { FindingsSection } from './components/FindingsSection' +import { ActivitySection } from './components/ActivitySection' +import { LoadingOverlay } from './components/LoadingOverlay' +import { EmptyProviderState } from './components/EmptyProviderState' +import { NoDataState } from './components/NoDataState' +import { SetupState, type CliStatus } from './components/SetupState' +import { StarBanner } from './components/StarBanner' +import { HeroSection } from './components/HeroSection' +import { PeriodTabs, PERIOD_LABELS } from './components/PeriodTabs' +import type { Period } from './components/PeriodTabs' +import { FooterBar } from './components/FooterBar' +import { ErrorToast } from './components/ErrorToast' +import { SettingsPanel, type ThemeChoice } from './components/SettingsPanel' + +const payloadCache = new PayloadCache() + +/// Background cadence, mirroring mac/Sources/CodeBurnMenubar/RefreshCadence.swift: every +/// fetch is a full Node process, so the popover being closed has to cost less than it being +/// open. Visible, a tick refreshes today/all plus the selected period/provider with optimize +/// findings; hidden, a slower tick refreshes only today/all and skips optimize, since the +/// tray badge and tooltip are the only things anyone can see. Entries younger than STALE_MS +/// are left alone when the popover is re-opened. +const REFRESH_ACTIVE_MS = 60_000 +const REFRESH_IDLE_MS = 120_000 +const STALE_MS = 60_000 + +type FetchOptions = { + includeOptimize: boolean + showOverlay: boolean +} + +export function App() { + const [period, setPeriod] = useState('today') + const [provider, setProvider] = useState('all') + const [payload, setPayload] = useState(null) + const [todayPayload, setTodayPayload] = useState(null) + const [currency, setCurrency] = useState(USD) + const [overlay, setOverlay] = useState(false) + const [error, setError] = useState(null) + const [insight, setInsight] = useState(() => { + const saved = readSetting('insight') + return isInsightMode(saved) ? saved : 'trend' + }) + const [cliStatus, setCliStatus] = useState(null) + const [cliChecking, setCliChecking] = useState(false) + const [version, setVersion] = useState('') + const [lastUpdated, setLastUpdated] = useState(null) + const [theme, setTheme] = useState(() => currentTheme()) + const [trayBadge, setTrayBadge] = useState(() => TRAY_BADGE_SUPPORTED && readSetting('trayBadge') !== 'off') + const [showSettings, setShowSettings] = useState(false) + // The window starts hidden and is shown by a tray click, which emits `codeburn://shown`. + const [popoverVisible, setPopoverVisible] = useState(false) + const [themeChoice, setThemeChoice] = useState(() => { + const saved = readSetting('theme') + return saved === 'dark' || saved === 'light' ? saved : 'system' + }) + + const selection = useRef({ period, provider }) + selection.current = { period, provider } + + const fetchKey = useCallback(async (p: Period, prov: Provider, opts: FetchOptions) => { + if (payloadCache.isInFlight(p, prov)) return + payloadCache.markInFlight(p, prov) + const isSelected = () => selection.current.period === p && selection.current.provider === prov + if (opts.showOverlay && isSelected()) setOverlay(true) + try { + const json = await invoke('fetch_payload', { + period: p, + provider: prov, + includeOptimize: opts.includeOptimize, + }) + // A quiet (no-optimize) refresh must not wipe findings a previous full fetch had. + if (!opts.includeOptimize) { + const previous = payloadCache.get(p, prov) + if (previous) json.optimize = previous.optimize + } + payloadCache.set(p, prov, json) + if (isSelected()) { + setPayload(json) + // "updated Xs ago" describes what the user is looking at, so only a fetch of the + // visible key may stamp it - a background today/all tick must not. + setLastUpdated(new Date()) + } + if (p === 'today' && prov === 'all') setTodayPayload(json) + } catch (err) { + const message = err instanceof Error ? err.message : String(err) + if (message.includes('CLI not found')) { + const status = await invoke('cli_status').catch(() => null) + if (status) setCliStatus(status) + } else if (isSelected()) { + setError(message) + } + } finally { + payloadCache.clearInFlight(p, prov) + if (isSelected()) setOverlay(false) + } + }, []) + + const refreshAll = useCallback(async (opts: FetchOptions) => { + const { period: p, provider: prov } = selection.current + if (!(p === 'today' && prov === 'all')) { + fetchKey('today', 'all', { includeOptimize: false, showOverlay: false }) + } + await fetchKey(p, prov, opts) + }, [fetchKey]) + + /// The single source of truth for the CLI gate. Nothing else writes a "compatible" + /// verdict: a payload that happens to parse does not prove the CLI is new enough, and a + /// probe from the settings panel must not be able to invent one either. + const checkCli = useCallback(async () => { + setCliChecking(true) + try { + const status = await invoke('cli_status') + setCliStatus(status) + if (status.found && status.compatible) { + refreshAll({ includeOptimize: true, showOverlay: true }) + } + } catch (err) { + setError(err instanceof Error ? err.message : String(err)) + } finally { + setCliChecking(false) + } + }, [refreshAll]) + + const cliReady = cliStatus !== null && cliStatus.found && cliStatus.compatible + + // Probe the gate before the first fetch: an old CLI emits a payload missing fields the + // popover reads, which used to blank the whole window instead of showing the setup screen. + useEffect(() => { + invoke('app_version').then(setVersion).catch(() => {}) + checkCli() + // Startup only; checkCli is re-run from the setup screen and settings on demand. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []) + + useEffect(() => { + if (!cliReady) return + const tick = popoverVisible + ? () => refreshAll({ includeOptimize: true, showOverlay: false }) + : () => fetchKey('today', 'all', { includeOptimize: false, showOverlay: false }) + const id = setInterval(tick, popoverVisible ? REFRESH_ACTIVE_MS : REFRESH_IDLE_MS) + return () => clearInterval(id) + }, [cliReady, popoverVisible, refreshAll, fetchKey]) + + useEffect(() => { + const cached = payloadCache.get(period, provider) + setPayload(cached) + if (!cliReady) return + if (!cached) { + fetchKey(period, provider, { includeOptimize: true, showOverlay: true }) + } else if (payloadCache.age(period, provider) > STALE_MS) { + fetchKey(period, provider, { includeOptimize: true, showOverlay: false }) + } + }, [period, provider, cliReady, fetchKey]) + + useEffect(() => { + const unlistenRefresh = listen('codeburn://refresh', () => refreshAll({ includeOptimize: true, showOverlay: true })) + const unlistenShown = listen('codeburn://shown', () => { + setPopoverVisible(true) + const { period: p, provider: prov } = selection.current + if (payloadCache.age(p, prov) > STALE_MS) refreshAll({ includeOptimize: true, showOverlay: false }) + }) + const unlistenHidden = listen('codeburn://hidden', () => setPopoverVisible(false)) + const unlistenTheme = listen('codeburn://toggle-theme', () => toggleTheme()) + return () => { + unlistenRefresh.then(fn => fn()) + unlistenShown.then(fn => fn()) + unlistenHidden.then(fn => fn()) + unlistenTheme.then(fn => fn()) + } + }, [refreshAll]) + + useEffect(() => { + const saved = readSetting('theme') + if (saved === 'dark' || saved === 'light') applyTheme(saved) + setTheme(currentTheme()) + const media = window.matchMedia('(prefers-color-scheme: dark)') + const onChange = () => setTheme(currentTheme()) + media.addEventListener('change', onChange) + return () => media.removeEventListener('change', onChange) + }, []) + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Escape') invoke('hide_popover').catch(() => {}) + } + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, []) + + const todayCost = todayPayload?.current?.cost ?? null + + useEffect(() => { + if (todayCost === null) return + const text = `CodeBurn · ${formatCurrency(todayCost, currency)} today` + invoke('set_tray_tooltip', { text }).catch(() => {}) + }, [todayCost, currency]) + + useEffect(() => { + if (!TRAY_BADGE_SUPPORTED) return + const text = trayBadge && todayCost !== null ? trayBadgeText(todayCost, currency) : null + invoke('set_tray_badge', { text }).catch(err => setError(`Tray badge: ${String(err)}`)) + }, [todayCost, currency, trayBadge]) + + + const chooseTheme = (choice: ThemeChoice) => { + applyTheme(choice === 'system' ? null : choice) + setThemeChoice(choice) + setTheme(currentTheme()) + } + + const toggleTheme = () => { + chooseTheme(currentTheme() === 'dark' ? 'light' : 'dark') + } + + const setTrayBadgePref = (on: boolean) => { + setTrayBadge(on) + writeSetting('trayBadge', on ? 'on' : 'off') + } + + const applyCurrency = async (code: string) => { + try { + setCurrency(await invoke('set_currency', { code })) + } catch (err) { + setError(err instanceof Error ? err.message : String(err)) + } + } + + const openTerminal = (args: string[]) => { + invoke('open_terminal_command', { args }).catch(err => setError(String(err))) + } + const connectClaude = () => { + invoke('open_claude_login').catch(err => setError(String(err))) + } + + const selectInsight = (mode: InsightMode) => { + setInsight(mode) + writeSetting('insight', mode) + } + + const providers = detectedProviders(todayPayload) + const planVisible = provider === 'claude' || (provider === 'all' && providers.length === 1 && providers[0] === 'claude') + const visibleModes = useMemo( + () => INSIGHT_ORDER.filter(m => m !== 'plan' || planVisible), + [planVisible], + ) + const activeInsight = visibleModes.includes(insight) ? insight : 'trend' + + const cliBlocked = cliStatus !== null && (!cliStatus.found || !cliStatus.compatible) + // The version gate above is what keeps these fields present; the optional reads are the + // backstop that turns a surprising payload into an empty state rather than a blank window. + const isFilteredEmpty = payload !== null && provider !== 'all' + && (payload.current?.cost ?? 0) <= 0 && (payload.current?.calls ?? 0) === 0 + const neverAnyData = payload !== null && provider === 'all' + && (payload.current?.calls ?? 0) === 0 && (payload.current?.sessions ?? 0) === 0 + && (payload.history?.daily?.length ?? 0) === 0 + + const footnote = [version ? `CodeBurn v${version}` : 'CodeBurn', lastUpdated ? `updated ${relativePast(lastUpdated)}` : null] + .filter(Boolean) + .join(' · ') + + return ( +
+
+
+ Code + Burn +
+
AI Coding Cost Tracker
+
+ + {!cliBlocked && !showSettings && ( + + )} + +
+ {showSettings ? ( + setShowSettings(false)} + version={version} + currency={currency} + onCurrency={applyCurrency} + themeChoice={themeChoice} + onThemeChoice={chooseTheme} + trayBadge={trayBadge} + onTrayBadge={setTrayBadgePref} + cliStatus={cliStatus} + onCheckCli={checkCli} + cliChecking={cliChecking} + onQuit={() => invoke('quit_app').catch(() => {})} + /> + ) : cliBlocked && cliStatus ? ( + + ) : ( + <> + + + + {isFilteredEmpty ? ( + + ) : neverAnyData ? ( + refreshAll({ includeOptimize: true, showOverlay: true })} /> + ) : ( + <> +
+ + {activeInsight === 'plan' && ( + + )} + {activeInsight === 'trend' && } + {activeInsight === 'forecast' && } + {activeInsight === 'pulse' && payload && } + {activeInsight === 'stats' && payload && } +
+ {payload?.current && ( + <> + + + + + )} + + )} + {overlay && } + + )} +
+ + refreshAll({ includeOptimize: true, showOverlay: true })} + onExport={format => openTerminal(['export', '-f', format])} + onOpenReport={() => openTerminal(['report'])} + onToggleTheme={toggleTheme} + onQuit={() => invoke('quit_app').catch(() => {})} + themeLabel={theme === 'dark' ? 'Switch to light theme' : 'Switch to dark theme'} + trayBadge={trayBadge} + onToggleTrayBadge={() => setTrayBadgePref(!trayBadge)} + onOpenSettings={() => setShowSettings(s => !s)} + settingsOpen={showSettings} + footnote={footnote} + /> + + + + {error && setError(null)} />} +
+ ) +} diff --git a/windows/src/components/ActivitySection.tsx b/windows/src/components/ActivitySection.tsx new file mode 100644 index 00000000..f7becd1b --- /dev/null +++ b/windows/src/components/ActivitySection.tsx @@ -0,0 +1,52 @@ +import type { MenubarPayload } from '../lib/payload' +import type { CurrencyState } from '../lib/currency' +import { formatCompactCurrency } from '../lib/currency' +import { CollapsibleSection } from './CollapsibleSection' + +/// Column widths shared with the header captions (mac: Cost 54 / Turns 52 / 1-shot 44). +export const COL_COST = 54 +export const COL_COUNT = 52 +export const COL_ONESHOT = 44 + +type Props = { + payload: MenubarPayload + currency: CurrencyState +} + +export function ActivitySection({ payload, currency }: Props) { + const activities = payload.current.topActivities + if (activities.length === 0) return null + const maxCost = Math.max(...activities.map(a => a.cost), 0.01) + + return ( + + {activities.map(a => ( +
+ + {a.name} + {formatCompactCurrency(a.cost, currency)} + {a.turns} + + {a.oneShotRate == null ? '-' : `${Math.round(a.oneShotRate * 100)}%`} + +
+ ))} +
+ ) +} + +export function FixedBar({ fraction }: { fraction: number }) { + const pct = Math.min(Math.max(fraction, 0), 1) * 100 + return ( +