diff --git a/.agents/skills/verify-quota-bar/SKILL.md b/.agents/skills/verify-quota-bar/SKILL.md index b03076d..7292a4a 100644 --- a/.agents/skills/verify-quota-bar/SKILL.md +++ b/.agents/skills/verify-quota-bar/SKILL.md @@ -191,5 +191,4 @@ standard library. Invoke it through `uv run --no-project python`, as shown in Launch and Doctor. `--help` lists its two commands. It deliberately wraps the repository's native verifier rather than recreating its assertions. -Keep the feature map current with `/maintain-verification-skill` when app paths or -verification preconditions change. +Update the feature map when app paths or verification preconditions change. diff --git a/.agents/skills/verify-quota-bar/features/saved-usage-and-sources.md b/.agents/skills/verify-quota-bar/features/saved-usage-and-sources.md index decb9b1..e7a7000 100644 --- a/.agents/skills/verify-quota-bar/features/saved-usage-and-sources.md +++ b/.agents/skills/verify-quota-bar/features/saved-usage-and-sources.md @@ -27,7 +27,7 @@ Preconditions: - **Import.** Choose `Import…`; confirm the file panel is `Import Usage Backup`, select the synthetic backup, and choose `Import`. Capture the result and changed saved-record count. Repeat import and verify no duplicate records are added. - **Export.** With saved records present, choose `Export…` and save inside the evidence directory. Its suggested name is `QuotaBar-Backup-YYYY-MM-DD.sqlite`. Verify the file exists, is readable SQLite, passes a read-only integrity check, and contains the expected records; retain the file after cleanup. - **Add/cancel.** Choose `Add host`, resolve field `SSH host or alias` (placeholder `Search hosts or type devbox`), type the isolated host, then choose `Cancel`; no host row should be added. -- **Add/sync.** Repeat and choose `Add`. Capture syncing followed by the host's recorded/new counts and copied bytes. Independently confirm the expected synthetic records reached the scratch database and mirrored logs stay under the owned scratch directory. +- **Add/sync.** Repeat and choose `Add`. Capture syncing followed by the host's record count, unique contribution, and remaining cache size. Confirm the expected synthetic records reached the scratch database and any retained logs are under the owned scratch directory. - **Other sync entries.** Exercise `Sync now`, `Actions for ` → `Sync this host`, and `Retry` on a deliberately failed host separately. Each must complete or display an actionable failure. - **Remove.** Choose `Actions for ` → `Stop syncing`; its source row disappears while saved records remain. diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml index 38f5e62..365b5a7 100644 --- a/.github/actionlint.yaml +++ b/.github/actionlint.yaml @@ -1,4 +1,4 @@ -# The repository's macOS 27 SDK runner is a custom runner label. +# GitHub hosts xcode-27, but actionlint does not yet recognize its label. self-hosted-runner: labels: - xcode-27 diff --git a/.github/dependabot.yml b/.github/dependabot.yml index f59c2b8..4047f55 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -21,3 +21,9 @@ updates: - "*" commit-message: prefix: build + - package-ecosystem: npm + directory: / + schedule: + interval: monthly + commit-message: + prefix: build diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2f65ee9..09c11ed 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -84,6 +84,22 @@ jobs: if: ${{ needs.changes.outputs.build == 'true' }} run: make test + - name: Verify the offline usage report + if: ${{ needs.changes.outputs.build == 'true' && matrix.os == 'macos-15' }} + env: + CHROMIUM_PATH: /Applications/Google Chrome.app/Contents/MacOS/Google Chrome + HOMEBREW_NO_AUTO_UPDATE: "1" + run: | + set -euo pipefail + command -v fnm >/dev/null || brew install fnm + eval "$(fnm env --shell bash)" + fnm install + fnm use + corepack pnpm install --frozen-lockfile + make build + .build/debug/QuotaBar --dump-usage-report "$RUNNER_TEMP/report" + corepack pnpm run report:verify --file "$RUNNER_TEMP/report/usage-report.html" --output "$RUNNER_TEMP/report/checks" + # Release tags are permanent, so a broken packaging script must fail here, not on a tag. - name: Package app if: ${{ needs.changes.outputs.build == 'true' && matrix.os == 'xcode-27' }} diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 503376e..feefaf9 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -28,7 +28,8 @@ jobs: matrix: include: - language: swift - os: xcode-27 + # Traced Swift extraction requires macOS and Xcode 26 or earlier. + os: macos-15 build-mode: manual - language: javascript-typescript os: ubuntu-24.04 @@ -48,9 +49,11 @@ jobs: with: persist-credentials: false - - name: Install pinned Rust toolchain for Swift linking + - name: Select the Swift analysis toolchain if: ${{ matrix.language == 'swift' }} - run: bash Scripts/setup_rust_ci.sh + run: | + echo "DEVELOPER_DIR=/Applications/Xcode_16.4.app/Contents/Developer" >> "$GITHUB_ENV" + bash Scripts/setup_rust_ci.sh - name: Initialize CodeQL uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 @@ -61,7 +64,7 @@ jobs: - name: Build Swift targets if: ${{ matrix.language == 'swift' }} # A fresh build lets CodeQL observe every target without running app tests. - run: Scripts/swift.sh build -c debug --scratch-path "$RUNNER_TEMP/codeql-build" + run: Scripts/swift.sh build -c debug --arch arm64 --scratch-path "$RUNNER_TEMP/codeql-build" - name: Perform CodeQL analysis uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4 diff --git a/.gitignore b/.gitignore index a1ccd3f..e9c6df5 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,7 @@ Rust/**/target/ # Build output build/ *.app - +node_modules/ # macOS .DS_Store diff --git a/.node-version b/.node-version new file mode 100644 index 0000000..a43a5b9 --- /dev/null +++ b/.node-version @@ -0,0 +1 @@ +24.22.0 diff --git a/Package.swift b/Package.swift index 55f7585..f7a0d58 100644 --- a/Package.swift +++ b/Package.swift @@ -16,32 +16,28 @@ let package = Package( .target( name: "QuotaBarCore", dependencies: ["CQuotaBarRust"], - resources: [.copy("Resources/UsageReport"), .copy("Resources/Pricing")], - swiftSettings: [.swiftLanguageMode(.v5)] + resources: [.copy("Resources/UsageReport"), .copy("Resources/Pricing")] ), // Menu bar UI, as a library so the test runner can drive it. .target( name: "QuotaBarApp", - dependencies: ["QuotaBarCore"], - swiftSettings: [.swiftLanguageMode(.v5)] + dependencies: ["QuotaBarCore"] ), // The app's entry point, and nothing else. .executableTarget( name: "QuotaBar", - dependencies: ["QuotaBarApp"], - swiftSettings: [.swiftLanguageMode(.v5)] + dependencies: ["QuotaBarApp"] ), // Headless probe: prints what the providers return. Debugging aid, not shipped. .executableTarget( name: "QuotaBarProbe", - dependencies: ["QuotaBarCore"], - swiftSettings: [.swiftLanguageMode(.v5)] + dependencies: ["QuotaBarCore"] ), // Core and app regression checks use a plain assertion executable. .executableTarget( name: "QuotaBarTests", - dependencies: ["QuotaBarCore", "QuotaBarApp"], - swiftSettings: [.swiftLanguageMode(.v5)] + dependencies: ["QuotaBarCore", "QuotaBarApp"] ), - ] + ], + swiftLanguageModes: [.v5] ) diff --git a/README.md b/README.md index eac610a..273c39e 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ claude Open QuotaBar, click its menu bar icon, and select Claude, Codex, or Pi. Open [Settings](docs/images/settings-general.png) to pick the quota provider the menu bar shows from cards with each one's live quota, choose the refresh interval or **Manual**, to [see model prices and turn models.dev pricing on or off](#model-prices), or to [back up saved usage](#backing-up-saved-usage). -If a provider is not signed in, choose **Copy command**, run it in Terminal, then return and choose **Check sign-in**. +If a provider is not signed in, choose **Copy**, run the command in Terminal, then return and choose **Check sign-in**. QuotaBar reads Codex credentials from `$CODEX_HOME/auth.json`, or `~/.codex/auth.json` by default. It reads Claude credentials from the `Claude Code-credentials` entry in macOS Keychain. @@ -111,7 +111,7 @@ After QuotaBar detects a reset, opening the card plays a brief bar animation whi Choose manual refresh or an interval of 1, 2, 5, 15, or 30 minutes in Settings. The default is 5 minutes. -- Polling, opening the card, and clicking **Refresh** update only the selected provider. Switching tabs requests an update for the newly selected provider. +- Polling and opening the card request a refresh for the menu bar's quota provider. Selecting Claude or Codex changes that provider. Selecting Pi or reopening its card requests a local Pi scan and keeps the same menu bar gauge. - Each quota provider has a one-minute refresh cooldown. A server rate limit can extend the wait. Pi refreshes only its local sessions and has no quota cooldown. - An explicit Claude credential-recovery action can bypass the local cooldown, but still respects the server limit. @@ -157,7 +157,7 @@ QuotaBar counts tokens in local session logs and estimates what that usage would Choose **Tokens** or **Cost** above the chart. The chart shows the last 10 calendar days; the summary shows the selected day and the last 30 days, each with its value in the other unit underneath. -Hover to preview a day, click to pin it, or use the Left and Right Arrow keys when a date is focused. The summary's first figure follows the selection and reads **Today** until another day is chosen. Under that row, **Cache hit** gives the share of the day's input served from the prompt cache, over a bar of its cache reads, cache writes, fresh input, and output. Click the row under the chart to list that day's models and keep the date fixed. Each model shows the mark of the tool that used it, a bolt for Fast usage, and a bar of its share of the day in the chosen unit. Click the pinned day again, or reopen the card, to resume hover previews. Switching units keeps the selected date. +Hover to preview a day, click to pin it, or use the Left and Right Arrow keys when a date is focused. The summary's first figure follows the selection and reads **Today** until another day is chosen. Click the date row below the chart to list that day's models and keep the date fixed. **Cache hit** divides the day's input into **Cache read** and **Uncached**. Its tooltip also lists cache writes, fresh input, and output. Each model shows its share of the day in the chosen unit, with a bolt for Fast usage. Pi rows name the upstream provider when known. On days with multiple tools, other rows name their tool. Click the pinned day again, or reopen the card, to resume hover previews. Switching units keeps the selected date. The chart distinguishes zero usage from missing data: @@ -168,7 +168,7 @@ The chart distinguishes zero usage from missing data: | **—** in Cost view | Usage is recorded, but no rate applies. The chart shows a dashed stub. | | **No price** in a day's model list | The model has no rate on that day. Cost totals include priced usage only, so they leave its tokens out. | -**Settings → Pricing** lists every model with its rates and where they come from. Unpriced models are local or free models, new Claude or OpenAI models the price book does not list yet, and Fast usage of models without a Fast multiplier. +**Settings → Pricing** lists the rates available for each model and their source. A model outside the bundled price book can still have a models.dev rate. Fast usage needs a Fast multiplier. ### Data sources @@ -181,7 +181,7 @@ The chart distinguishes zero usage from missing data: For OpenCode `openai` usage, QuotaBar checks OpenCode's current OAuth credentials against the Codex account. Matching usage counts toward Codex totals. Other providers, API-key credentials, and account mismatches are excluded. These totals do not affect quota bars. -Pi Agent usage has its own **Pi** tab. Every request counts, whichever upstream provider served it and whether a subscription or an API key paid for it, and is priced at the model's API rate. The tab has no quota bars. A model with no known rate uses the cost Pi logged for it. See [Limitations](#limitations) for historical OpenCode authentication changes. +Pi Agent usage has its own **Pi** tab. Every request counts, whichever upstream provider served it and whether a subscription or an API key paid for it, and is priced at the model's API rate. The tab has no quota bars. When no rate applies, QuotaBar uses a positive cost logged by Pi if available. See [Limitations](#limitations) for historical OpenCode authentication changes.

Pi usage card with upstream provider shares and local usage rendered with sample data @@ -189,7 +189,7 @@ Pi Agent usage has its own **Pi** tab. Every request counts, whichever upstream ### Remote machines -To count Claude Code and Codex sessions from another machine, open **Settings → Usage**, press **Add host**, and type its SSH host or pick one from your SSH config. QuotaBar copies the machine's `.jsonl` logs with `rsync` over `ssh` when the host is added, when the app starts, every 15 minutes, and when you press **Sync now**. With **Sync automatically** off, only adding a host and **Sync now** connect. Each row shows when the host last synced or why it failed, how many usage records its logs hold, how many of those are new, and how much was copied. Press **Retry** on a failed host, or use its **···** menu to sync that host alone or stop syncing it. New records are the ones no other log recorded first, so a host whose sessions are already here can sync successfully with few or none. A machine that is off only delays its own sync. +To count Claude Code and Codex sessions from another machine, open **Settings → Usage**, press **Add host**, and type its SSH host or pick one from your SSH config. QuotaBar copies the machine's `.jsonl` logs with `rsync` over `ssh` when the host is added, when the app starts, every 15 minutes, and when you press **Sync now**. Turning off **Sync automatically** disables startup and scheduled syncs. Each row shows the sync status and how many usage records belong to that host. The `unique` count identifies records first seen on that host, and `cached` shows how much space its log copies currently occupy on this Mac. Press **Retry** on a failed host, or use its **···** menu to sync that host alone or stop syncing it. A machine that is off only delays its own sync. The host needs key-based SSH sign-in that works without a prompt, and `rsync` installed. QuotaBar reads `~/.claude/projects`, `~/.config/claude/projects`, `~/.codex/sessions`, and `~/.codex/archived_sessions` on the machine, not custom `CLAUDE_CONFIG_DIR` or `CODEX_HOME` locations. OpenCode and Pi Agent are local only. @@ -197,9 +197,6 @@ Remote usage adds to the same totals as this Mac's; the menu and the usage repor After a successful sync and scan, QuotaBar automatically removes eligible local log copies that have been unchanged for at least 24 hours. Recorded usage and scan positions stay in SQLite. Each later sync validates an evicted file's remote contents before skipping its download. If the session grows, QuotaBar downloads that file again and resumes after the recorded portion. Incomplete or failed scans keep their files, and a rewritten historical portion preserves the existing usage and reports a scan failure. Remote originals are never deleted. See [Remote log cache](docs/remote-log-cache.md) for the cleanup guarantees. -The host row labels the contribution as `unique` and the remaining local log size -as `cached`; neither is the number of records or bytes transferred by the last sync. - ### Saved history The first scan of a large history may take time. QuotaBar saves token counts, dates, models, sources, and pricing tiers in SQLite, along with record IDs and scan positions. It calculates costs when reading that usage. @@ -226,11 +223,11 @@ A backup holds token counts, dates, models, pricing tiers, record IDs, scan posi ### Pricing rules -- Every cost is an estimate at API list prices. +- Estimates use API list prices when available. A Pi request can also carry a cost reported by its provider or estimated by Pi. - Claude and OpenAI models on their makers' current price lists use the bundled [price book](Sources/QuotaBarCore/Resources/Pricing/price-book.json), which stores rates in dated periods. Each day's usage uses that day's rates. - Other models, including retired Claude and OpenAI models, use rates from [models.dev](https://models.dev): the model maker's own price when it lists one, otherwise the middle price across providers. QuotaBar keeps them in a local cache and refreshes it at most once a day. When a price changes, earlier days keep the old rates. Models listed only for free stay unpriced. Turn this off with the **models.dev** switch in **Settings → Pricing**. - Fast usage (Codex priority tier and Claude Fast mode) multiplies the price book's rates by that period's Fast multiplier, including cache rates. Without a Fast multiplier, and for models priced from models.dev, Fast usage stays unpriced. Claude usage scanned before QuotaBar recorded Fast mode stays Standard. -- Long-context rates apply when a request's input and cache tokens exceed its threshold. QuotaBar records that classification during scanning; later threshold changes do not reclassify saved usage. +- Long-context rates apply when a request's input and cache tokens exceed its threshold. For Claude, OpenCode, and Pi requests with a saved context size, QuotaBar applies the model's threshold for the recorded day when reading usage. Codex aggregates and older requests without a saved context size keep their scan-time tier. Provider billing rules, cache accounting, and price changes can make estimates differ from an invoice. See [Maintaining the price book](docs/pricing.md) to update bundled rates and for how models.dev rates are chosen. @@ -312,7 +309,7 @@ make app | `make run` | Build and run in the foreground. | | `make preview` | Open the isolated sample interface without stopping the installed app. | | `make card-snapshot` | Render offscreen card images to `.build/screenshots/card`. | -| `make test` | Run core assertions and UI/policy verifiers. | +| `make test` | Check Rust formatting, run Rust tests and Clippy, then run the Swift core and app assertions. | | `make probe` | Check both provider integrations. | | `make probe-cost` | Rescan local logs and print cost totals. | | `make benchmark-startup` | Measure status-item construction offline in a debug build. | @@ -335,13 +332,13 @@ To preview interactions with sample quota and cost data, run: make preview ``` -Set `PREVIEW_STATE=signed-out`, `stale`, or `motion` to inspect those states; the default is `loaded`. Preview uses isolated preferences and temporary history. It does not read credentials, contact providers, or scan real logs. Choose **Quit** in the preview to clear its temporary data. Running it alongside the installed app adds a second menu bar icon. +Set `PREVIEW_STATE=signed-out`, `stale`, or `motion` to inspect those states; the default is `loaded`. The quota card and usage report show sample data. Preview keeps its own preferences and temporary usage database. **Add host** starts a real SSH sync, and **Open at login** changes the macOS login item. Choose **Quit** in the preview to clear its temporary data. Running it alongside the installed app adds a second menu bar icon. `make card-snapshot` writes offscreen card images to `.build/screenshots/card`. Set `SNAPSHOT_DIR` to write somewhere else. `make readme-assets` renders both READMEs' shared images from the current views with sample data, including the light and dark card, sign-in, and refresh-failure states. Regenerate them after changing the UI. -Image generation requires ffmpeg. The report screenshot also needs Node.js and Playwright from `playwright-cli` or `PLAYWRIGHT_MODULE`. It uses Brave by default, or the browser at `CHROMIUM_PATH`. See [report development checks](docs/usage-report.md#verification) and [rendering notes](docs/design-implementation.md). +Image generation requires ffmpeg. For the report screenshot, run `fnm install`, `fnm use`, and `pnpm install --frozen-lockfile` in the repository root. It uses Brave by default, or the browser at `CHROMIUM_PATH`. See the [report development checks](docs/usage-report.md#verification) and [rendering notes](docs/design-implementation.md). @@ -363,9 +360,9 @@ The workflow packages an `arm64` ZIP and verifies its signature, version, archit | Provider is not signed in | Copy the command in the card, complete the CLI login, then choose **Check sign-in**. Use `make probe` for the raw error. | | Data is stale or refresh returns HTTP 429 | Read the warning above the saved quota. Wait for the retry countdown, then retry; a server limit may last longer than one minute. | | Local scan failed | Read the local usage error and choose **Retry local scan**. Confirm the CLI writes session logs to the paths above. | -| Cost shows — or a model shows No price | Check the model in **Settings → Pricing**. Local, free, and Fast usage of models outside the price book stays unpriced. For other models, confirm the **models.dev** switch in **Settings → Pricing** is on and that models.dev lists the model. | +| Cost shows — or a model shows No price | Check the model in **Settings → Pricing**. For Standard usage outside the price book, confirm **models.dev** is on and lists a paid rate. Fast usage needs a Fast multiplier. Pi can also use a positive cost from its session log. | | A date shows Not scanned yet | Wait for the local scan to finish. This means the date is not covered yet, rather than zero usage. | -| OpenCode usage is missing | Confirm OpenCode uses `openai` OAuth with the same account as Codex. Check **Settings → Pricing** for database or authentication errors. | +| OpenCode usage is missing | Confirm OpenCode uses `openai` OAuth with the same account as Codex. Recording pauses while either account cannot be read. **Settings → Pricing** shows account mismatches, API-key exclusions, and database errors. | | Pi Agent usage is missing | Open the **Pi** tab and choose Refresh. Confirm the sessions are in one of the Pi Agent locations above. | ## Limitations diff --git a/README.zh-CN.md b/README.zh-CN.md index 5f9f25f..ef97de9 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -87,7 +87,7 @@ claude 打开 QuotaBar,点击菜单栏图标,选择 Claude、Codex 或 Pi。在 [Settings](docs/images/settings-general.png) 中,可以从带实时额度的供应商卡片里选择菜单栏显示哪一个,选择刷新间隔或 **Manual**,[查看模型费率并开关 models.dev 计价](#模型费率),或[备份已保存用量](#备份已保存用量)。 -未登录时,点击 **Copy command**,在终端中执行命令,登录后返回并点击 **Check sign-in**。 +未登录时,点击 **Copy** 复制命令,在终端中执行,登录后返回并点击 **Check sign-in**。 QuotaBar 从 `$CODEX_HOME/auth.json` 读取 Codex 凭据,默认路径为 `~/.codex/auth.json`。Claude 凭据来自 macOS 钥匙串中的 `Claude Code-credentials` 条目。 @@ -103,7 +103,7 @@ QuotaBar 从 `$CODEX_HOME/auth.json` 读取 Codex 凭据,默认路径为 `~/.c 每个额度窗口显示剩余百分比和重置时间。点击重置时间并选择 **Show reset date** 或 **Show countdown**,可同时切换两个窗口的重置时间显示方式。无限额会话显示 **No limit**,额度用尽时显示 **Limit reached**。 -每条额度条上有一个节奏标记,表示按均匀速度此刻应剩下的位置。QuotaBar 会比较用量与已过时间。采样满几天后,周窗口会按你平时活跃的时段计时,而不是按钟点平均。会话停下来时,显示按之前速度还能用多久,而不是耗尽时刻。积累至少三个可比较的周窗口后,也会用这些历史记录估算每周节奏。额度采样保留 56 天。 +每条额度条都有一个 **Expected remaining** 标记,表示按均匀速度此刻应剩下的位置。如果预计额度会提前耗尽,对应窗口下方会显示提醒。QuotaBar 会比较用量与已过时间。采样满几天后,周窗口会按你平时活跃的时段计时,而不是按钟点平均。会话停下来时,显示按之前速度还能用多久,而不是耗尽时刻。积累至少三个可比较的周窗口后,也会用这些历史记录估算每周节奏。额度采样保留 56 天。 检测到额度重置后,打开卡片时会播放简短的额度条动画,标题显示新读数。应用遵循 macOS 的减弱动态效果设置。 @@ -111,7 +111,7 @@ QuotaBar 从 `$CODEX_HOME/auth.json` 读取 Codex 凭据,默认路径为 `~/.c 在设置中选择手动刷新,或每 1、2、5、15、30 分钟刷新一次,默认 5 分钟。 -- 定时刷新、打开卡片和点击 **Refresh** 都只更新当前供应商。切换标签页时,会请求更新新选中的供应商。 +- 定时刷新和打开卡片都会请求刷新菜单栏当前显示的额度供应商。选择 Claude 或 Codex 会切换该供应商。选择 Pi 或重新打开 Pi 卡片时,应用会扫描本地 Pi 会话,菜单栏仍显示原来的额度供应商。 - 每家额度供应商有独立的一分钟刷新冷却,服务端限流可能延长等待时间。Pi 只重新扫描本地会话,没有额度刷新冷却。 - 手动触发 Claude 凭据恢复时可以跳过本地冷却,但仍受服务端限制。 @@ -157,7 +157,7 @@ QuotaBar 统计本地会话日志中的 token,估算这些用量按 API 费率 在图表上方选择 **Tokens** 或 **Cost**。图表显示最近 10 个日历日,摘要显示所选日期和最近 30 天的总计,下方小字是另一种单位的数值。 -悬停可预览某天,点击可固定日期,日期获得焦点后也可用左右方向键切换。摘要的第一个数值跟随所选日期,未选其他日期时显示 **Today**。那一行下方的 **Cache hit** 显示当天输入中由提示缓存提供的比例,下面的条把当天 tokens 分为缓存读取、缓存写入、新输入和输出。点击图表下方那一行可展开当天的模型明细,并固定日期。每个模型前显示所用工具的图标,Fast 用量带闪电标记,下方的条表示它在当天所选单位中的占比。再次点击已固定的日期或重新打开卡片,可恢复悬停预览;切换单位会保留选中日期。 +悬停可预览某天,点击可固定日期,日期获得焦点后也可用左右方向键切换。摘要的第一个数值跟随所选日期,未选其他日期时显示 **Today**。点击图表下方的日期行可展开当天的模型明细,并固定日期。**Cache hit** 将当天的输入分为 **Cache read**(缓存命中)和 **Uncached**(未命中),悬停可查看缓存写入、新输入和输出的数量。每个模型下方的条表示它在当天所选单位中的占比,Fast 用量带闪电标记。Pi 的模型行会显示已知的上游供应商;其他来源在当天混用多种工具时显示工具名。再次点击已固定的日期或重新打开卡片,可恢复悬停预览;切换单位会保留选中日期。 图表区分零用量和缺失数据: @@ -168,7 +168,7 @@ QuotaBar 统计本地会话日志中的 token,估算这些用量按 API 费率 | Cost 视图中的 **—** | 已记录用量,但没有适用的费率。图表显示虚线短条。 | | 模型明细中的 **No price** | 该模型在当天没有费率。成本合计只包含有费率的用量,不计入它的 token。 | -**Settings → Pricing** 列出每个模型的费率及其来源。未计价的通常是本地或免费模型、价格表尚未收录的新 Claude 或 OpenAI 模型,以及没有 Fast 倍率的 Fast 用量。 +**Settings → Pricing** 列出各模型可用的费率及其来源。内置价格表之外的模型也可能从 models.dev 获取费率。按费率估算 Fast 用量需要相应的 Fast 倍率。 ### 数据来源 @@ -181,7 +181,7 @@ QuotaBar 统计本地会话日志中的 token,估算这些用量按 API 费率 对于 OpenCode 的 `openai` 用量,QuotaBar 会将 OpenCode 当前的 OAuth 凭据与 Codex 账号匹配,匹配成功后计入 Codex 总计。其他供应商、API key 凭据和账号不匹配的数据不计入。这些总计不会改变额度条。 -Pi Agent 的用量显示在独立的 **Pi** 标签页。无论由哪个上游供应商提供、由订阅还是 API key 付费,每个请求都计入,并按模型的 API 价格计费。该标签页没有额度条。没有已知价格的模型使用 Pi 记录的费用。OpenCode 历史认证方式变更的处理限制见[已知限制](#已知限制)。 +Pi Agent 的用量显示在独立的 **Pi** 标签页。无论由哪个上游供应商提供、由订阅还是 API key 付费,每个请求都计入,并按模型的 API 价格计费。该标签页没有额度条。没有适用费率时,如果 Pi 记录了大于零的费用,QuotaBar 会采用该金额。OpenCode 历史认证方式变更的处理限制见[已知限制](#已知限制)。

使用示例数据渲染的 Pi 用量卡片,展示上游供应商占比和本地用量 @@ -189,19 +189,13 @@ Pi Agent 的用量显示在独立的 **Pi** 标签页。无论由哪个上游供 ### 远程机器 -如需统计其他机器上的 Claude Code 和 Codex 会话,打开 **Settings → Usage**,点击 **Add host**,输入它的 SSH 主机或从 SSH 配置中选择。QuotaBar 会在添加主机时、应用启动时、每 15 分钟以及点击 **Sync now** 时,通过 `ssh` 用 `rsync` 复制这台机器的 `.jsonl` 日志。关闭 **Sync automatically** 后,只有添加主机和 **Sync now** 会发起连接。每一行都会显示上次同步时间或失败原因、日志中的用量记录数、其中新增的数量,以及复制的数据量。同步失败时可点击 **Retry**,也可以通过 **···** 菜单单独同步这台主机或停止同步。新增记录是指其他日志尚未记录过的部分,因此会话已在本机的主机即使同步成功,新增也可能很少甚至为零。机器关机只会推迟它自己的同步。 +如需统计其他机器上的 Claude Code 和 Codex 会话,打开 **Settings → Usage**,点击 **Add host**,输入它的 SSH 主机或从 SSH 配置中选择。QuotaBar 会在添加主机时、应用启动时、每 15 分钟以及点击 **Sync now** 时,通过 `ssh` 用 `rsync` 复制这台机器的 `.jsonl` 日志。关闭 **Sync automatically** 会停用启动时同步和定时同步。每一行显示同步状态和该主机关联的用量记录数。`unique` 表示首次从这台主机记录的条数,`cached` 表示日志副本目前在本机占用的空间。同步失败时可点击 **Retry**,也可以通过 **···** 菜单单独同步这台主机或停止同步。机器关机只会推迟它自己的同步。 主机需要支持免交互的 SSH 密钥登录,并已安装 `rsync`。QuotaBar 读取这台机器上的 `~/.claude/projects`、`~/.config/claude/projects`、`~/.codex/sessions` 和 `~/.codex/archived_sessions`,不读取自定义的 `CLAUDE_CONFIG_DIR` 或 `CODEX_HOME` 路径。OpenCode 和 Pi Agent 仅统计本机数据。 远程用量与本机用量合并到同一总计中,菜单和用量报告不按机器拆分。两边都有的会话只计一次。移除主机后不再同步,已记录的用量会保留。 -Remote log cache update: after a successful sync and scan, eligible local copies -are removed once their recorded version has remained unchanged for 24 hours. -`unique` describes this host's contribution; `cached` is the remaining local log -size. Recorded usage stays in SQLite. Later syncs revalidate remote contents, -skip unchanged evicted files, and resume growing sessions after their recorded -portion. Incomplete, malformed, or unverifiable files remain cached. Remote -originals are never deleted. See [Remote log cache](docs/remote-log-cache.md). +成功同步并扫描后,已完整记录且至少 24 小时未变化的本地日志副本可自动清理。用量和扫描位置保存在 SQLite 中。后续同步会校验远端内容,跳过已清理且未变化的文件;会话增长时会重新下载文件,并从上次记录处继续扫描。未完成或扫描失败的文件会保留。历史内容被改写时,扫描会报错,已记录的用量会保留。清理只涉及本地副本,详见[远程日志缓存](docs/remote-log-cache.md)。 ### 历史记录 @@ -229,11 +223,11 @@ Codex 和 Claude 从上次读到的字节继续扫描,OpenCode 和 Pi Agent ### 计价规则 -- 所有成本都是按 API 公开价格的估算。 +- 有适用费率时,成本按 API 公开价格估算。Pi 请求还可能附带供应商报告或 Pi 自行估算的费用。 - 官方当前价目表上的 Claude 和 OpenAI 模型使用内置[价格表](Sources/QuotaBarCore/Resources/Pricing/price-book.json)。价格表按生效日期分段记录费率,每天的用量使用当天的费率。 - 其他模型(包括已退役的 Claude 和 OpenAI 模型)使用 [models.dev](https://models.dev) 的费率:模型厂商自己有报价时用厂商价,否则取各家供应商报价的中间值。QuotaBar 把这些费率缓存在本地,每天最多更新一次;价格变化后,之前的日期仍按旧费率计算。只有免费报价的模型保持未计价。可用 **Settings → Pricing** 中的 **models.dev** 开关关闭。 - Fast 用量(Codex priority 层级和 Claude Fast mode)使用价格表中的费率乘以该时段的 Fast 倍率,缓存费率同样适用。没有 Fast 倍率的模型,以及使用 models.dev 计价的模型,其 Fast 用量保持未计价状态。QuotaBar 开始记录 Fast mode 之前扫描的 Claude 用量仍按 Standard 计价。 -- 单次请求的输入和缓存 token 总数超过阈值时,使用长上下文费率。QuotaBar 在扫描时记录这一归类,之后修改阈值不会重新归类已保存的用量。 +- 单次请求的输入和缓存 token 总数超过阈值时,使用长上下文费率。对于保存了请求上下文大小的 Claude、OpenCode 和 Pi 记录,QuotaBar 在读取用量时使用该模型在记录当日适用的阈值重新分档。Codex 汇总记录和缺少请求上下文大小的旧记录保留扫描时的档位。 供应商计费规则、缓存计算方式和价格变化,都可能让估算结果与账单不同。更新内置费率的方法以及 models.dev 费率的选取方式见[维护价格表](docs/pricing.md)。 @@ -265,13 +259,7 @@ QuotaBar 会读取 CLI 凭据和本地会话记录,不会写入 CLI 的凭据 统计会使用时间、模型、token 数量、记录 ID,以及匹配 OAuth 会话所需的账号 ID。QuotaBar 不会将提示词、回复和推理文本写入用量历史或上传。 -[Remote machines](#远程机器) connect over SSH and copy complete session logs, -including possible prompts and responses, into a directory only this user can -read. QuotaBar sends sync commands and content-validation requests, without -uploading conversation contents. Eligible old local copies are cleaned up after -recording; recent or unverified copies may remain after removing a host. Delete -`cost-usage/remote-logs` to remove remaining copies; recorded usage stays. The -Usage database size excludes these cached JSONL files. +添加[远程机器](#远程机器)后,QuotaBar 会通过 SSH 将完整会话日志复制到仅当前用户可读的目录。日志中可能包含提示词和回复。QuotaBar 向主机发送同步命令和内容校验请求,不会上传对话内容。记录用量后,符合条件的旧副本会自动清理;移除主机后,新近或尚未校验的副本可能保留。删除 `cost-usage/remote-logs` 可清除剩余副本,已记录的用量仍在数据库中。用量数据库显示的大小不包含这些 JSONL 缓存。

本地存储路径 @@ -294,7 +282,7 @@ Codex 额度请求会使用 `$CODEX_HOME/config.toml` 中的 `chatgpt_base_url` 构建需要完整的 Xcode 及 Swift 6 工具链。项目使用 Swift Package Manager。`Scripts/swift.sh` 默认使用 `/Applications/Xcode.app/Contents/Developer`,不会修改全局 `xcode-select` 设置。 -Rust kernels also require `rustup` and the toolchain pinned in `rust-toolchain.toml`. Install rustup with `brew install rustup` and add its `bin` directory to PATH as Homebrew instructs. Use `make` or `Scripts/swift.sh` for builds: the wrapper builds the matching Cargo profile, links the static library, and invalidates SwiftPM's cache when Rust changes. Bare `swift build` and opening the package directly in Xcode do not run this integration. Prebuilt app users do not need Rust. See [Rust core boundaries and validation](docs/rust-migration.md). +从源码构建还需要 `rustup` 和 `rust-toolchain.toml` 指定的工具链。运行 `brew install rustup`,再按 Homebrew 提示将其 `bin` 目录加入 `PATH`。使用 `make` 或 `Scripts/swift.sh` 构建,脚本会按对应的 Cargo 配置编译并链接 Rust 静态库,Rust 代码变化时也会刷新 SwiftPM 缓存。直接运行 `swift build` 或在 Xcode 中打开包会跳过这些步骤。使用预编译应用无需安装 Rust。详见 [Rust 核心模块与验证](docs/rust-migration.md)。 发布工作流要求 macOS 27 SDK,以支持 macOS 27 的原生菜单栏会话。使用较旧 SDK 的本地构建会采用旧版菜单栏处理方式。最低运行系统仍为 macOS 14。 @@ -321,7 +309,7 @@ make app | `make run` | 构建并在前台运行。 | | `make preview` | 打开隔离的示例界面,不会停止已安装的应用。 | | `make card-snapshot` | 将离屏卡片图生成到 `.build/screenshots/card`。 | -| `make test` | 运行核心断言和界面、行为规则验证。 | +| `make test` | 检查 Rust 格式,运行 Rust 测试和 Clippy,再运行 Swift 核心与应用断言。 | | `make probe` | 检查两家供应商的集成。 | | `make probe-cost` | 重新扫描本地日志并输出成本总计。 | | `make benchmark-startup` | 使用调试版本,离线测量菜单栏项目的创建耗时。 | @@ -344,13 +332,13 @@ make app make preview ``` -设置 `PREVIEW_STATE=signed-out`、`stale` 或 `motion` 可以查看对应状态;默认是 `loaded`。预览使用隔离的偏好设置和临时历史记录,不读取凭据、不请求供应商接口,也不扫描真实日志。通过预览中的 **Quit** 清理临时数据。与已安装的应用同时运行时,菜单栏会多出一个图标。 +设置 `PREVIEW_STATE=signed-out`、`stale` 或 `motion` 可以查看对应状态;默认是 `loaded`。额度卡片和用量报告使用示例数据。预览有独立的偏好设置和临时用量数据库。**Add host** 会启动真实的 SSH 同步,**Open at login** 会修改 macOS 登录项。通过预览中的 **Quit** 清理临时数据。与已安装的应用同时运行时,菜单栏会多出一个图标。 `make card-snapshot` 会将离屏卡片图写到 `.build/screenshots/card`;设置 `SNAPSHOT_DIR` 可以改写到其他位置。 `make readme-assets` 使用当前视图和示例数据,重新生成两版 README 共用的图片,包括深浅色卡片、登录和刷新失败状态。修改界面后应同步生成图片。 -生成图片需要 ffmpeg。报告截图还需要 Node.js,以及通过 `playwright-cli` 或 `PLAYWRIGHT_MODULE` 提供的 Playwright。默认使用 Brave,也可通过 `CHROMIUM_PATH` 指定浏览器。详见[报告开发验证](docs/usage-report.md#verification)和[渲染说明](docs/design-implementation.md)。 +生成图片需要 ffmpeg。生成报告截图前,在仓库根目录依次运行 `fnm install`、`fnm use` 和 `pnpm install --frozen-lockfile`。默认使用 Brave,也可通过 `CHROMIUM_PATH` 指定浏览器。详见[报告开发验证](docs/usage-report.md#verification)和[渲染说明](docs/design-implementation.md)。
@@ -372,9 +360,9 @@ make preview | 供应商显示未登录 | 复制卡片中的命令,完成 CLI 登录后点击 **Check sign-in**。使用 `make probe` 查看原始错误。 | | 数据过期或刷新返回 HTTP 429 | 查看已保存额度上方的警告,等待倒计时结束后重试。服务端限制可能超过一分钟。 | | 本地扫描失败 | 查看本地用量区域的错误,点击 **Retry local scan**。确认 CLI 正在向上面的路径写入会话日志。 | -| 成本显示 — 或模型显示 No price | 在 **Settings → Pricing** 中查看该模型。本地模型、免费模型,以及价格表之外模型的 Fast 用量,都保持未计价。其他模型请确认 **Settings → Pricing** 中的 **models.dev** 开关已开启,且 models.dev 收录了该模型。 | +| 成本显示 — 或模型显示 No price | 在 **Settings → Pricing** 中查看该模型。内置价格表之外的 Standard 用量需要开启 **models.dev**,且其中有该模型的付费费率。按费率估算 Fast 用量需要 Fast 倍率。Pi 也可以采用其会话日志中大于零的费用。 | | 日期显示 Not scanned yet | 等待本地扫描完成。这表示该日期尚未被扫描覆盖,不代表零用量。 | -| 缺少 OpenCode 用量 | 确认 OpenCode 使用 `openai` OAuth,且账号与 Codex 相同。在 **Settings → Pricing** 查看数据库或认证错误。 | +| 缺少 OpenCode 用量 | 确认 OpenCode 使用 `openai` OAuth,且账号与 Codex 相同。任一账号信息无法读取时会暂停记录。**Settings → Pricing** 会显示账号不匹配、使用 API key 而被排除以及数据库错误。 | | 缺少 Pi Agent 用量 | 打开 **Pi** 标签页并选择 Refresh。确认会话位于上面列出的 Pi Agent 路径之一。 | ## 已知限制 diff --git a/Rust/QuotaBarCore/Cargo.toml b/Rust/QuotaBarCore/Cargo.toml index fc30231..683a391 100644 --- a/Rust/QuotaBarCore/Cargo.toml +++ b/Rust/QuotaBarCore/Cargo.toml @@ -7,7 +7,7 @@ publish = false license = "AGPL-3.0-only" [lib] -crate-type = ["staticlib", "rlib"] +crate-type = ["staticlib"] [dependencies] serde = { version = "=1.0.229", features = ["derive"] } diff --git a/Rust/QuotaBarCore/src/aggregation.rs b/Rust/QuotaBarCore/src/aggregation.rs index 57975e4..9116ea8 100644 --- a/Rust/QuotaBarCore/src/aggregation.rs +++ b/Rust/QuotaBarCore/src/aggregation.rs @@ -325,10 +325,18 @@ mod tests { let mut unpriced = row(); unpriced.priced = 0; unpriced.cost = f64::NAN; - assert_eq!(run(&[unpriced]), Ok(1)); let mut zero = row(); zero.cost = 0.0; - assert_eq!(run(&[zero]), Ok(1)); + for row in [unpriced, zero] { + let priced = row.priced; + let mut groups = [QBAggregateGroup::default()]; + let mut days = [QBAggregateDay::default()]; + let mut models = [QBAggregateModel::default()]; + assert_eq!(fold(&[row], &mut groups, &mut days, &mut models), Ok(1)); + assert_eq!((groups[0].priced, groups[0].cost), (priced, 0.0)); + assert_eq!((days[0].priced, days[0].cost), (priced, 0.0)); + assert_eq!((models[0].priced, models[0].cost), (priced, 0.0)); + } } #[test] diff --git a/Rust/QuotaBarCore/src/classifier.rs b/Rust/QuotaBarCore/src/classifier.rs index 721ce8e..a68adbe 100644 --- a/Rust/QuotaBarCore/src/classifier.rs +++ b/Rust/QuotaBarCore/src/classifier.rs @@ -2,28 +2,9 @@ //! This is not a JSON validator: escaped keys/target values remain indeterminate, and //! classification stops at the first matching key without validating trailing input. -use std::ffi::{c_int, c_void}; +use crate::find_byte; use std::ops::Range; -unsafe extern "C" { - #[link_name = "memchr"] - fn c_memchr(data: *const c_void, byte: c_int, len: usize) -> *const c_void; -} - -/// Uses the same bounded libc search as the previous Swift implementation. -fn find_byte(bytes: &[u8], byte: u8) -> Option { - // SAFETY: The slice is readable for exactly its length. memchr returns either null - // or a pointer within this slice, so the offset stays within the same allocation. - unsafe { - let found = c_memchr(bytes.as_ptr().cast(), byte.into(), bytes.len()); - if found.is_null() { - None - } else { - Some(found.cast::().offset_from(bytes.as_ptr()) as usize) - } - } -} - const MISSING: i32 = 0; const INDETERMINATE: i32 = 1; const OTHER: i32 = 2; diff --git a/Rust/QuotaBarCore/src/claude.rs b/Rust/QuotaBarCore/src/claude.rs index 00e0e67..7593bbc 100644 --- a/Rust/QuotaBarCore/src/claude.rs +++ b/Rust/QuotaBarCore/src/claude.rs @@ -144,10 +144,6 @@ fn scalar(value: &Value) -> Result { // exponent spellings. Delegate all floating encodings, not only values >2^53. return Err(()); } - if value.is_u64() { - // An unsigned value outside Int64 is also outside LooseScalar's Double bound. - return Ok(0); - } if let Some(boolean) = value.as_bool() { return Ok(i64::from(boolean)); } diff --git a/Rust/QuotaBarCore/src/lib.rs b/Rust/QuotaBarCore/src/lib.rs index 66ed6d6..71fa4a4 100644 --- a/Rust/QuotaBarCore/src/lib.rs +++ b/Rust/QuotaBarCore/src/lib.rs @@ -7,3 +7,18 @@ mod classifier; mod claude; mod pricing; mod scanner; + +use std::ffi::{c_int, c_void}; + +unsafe extern "C" { + fn memchr(bytes: *const c_void, value: c_int, length: usize) -> *const c_void; +} + +/// Bounded libc search shared by the JSON classifier and line reader. +fn find_byte(bytes: &[u8], byte: u8) -> Option { + // SAFETY: memchr reads at most this slice's length and returns null or a pointer into it. + unsafe { + let found = memchr(bytes.as_ptr().cast(), byte.into(), bytes.len()); + (!found.is_null()).then(|| found.cast::().offset_from(bytes.as_ptr()) as usize) + } +} diff --git a/Rust/QuotaBarCore/src/scanner.rs b/Rust/QuotaBarCore/src/scanner.rs index f576f46..063b067 100644 --- a/Rust/QuotaBarCore/src/scanner.rs +++ b/Rust/QuotaBarCore/src/scanner.rs @@ -1,4 +1,5 @@ //! Bounded JSONL streaming. Swift owns scan plans, transactions and callback lifetimes. +use crate::find_byte; use std::ffi::{CStr, c_char, c_int, c_void}; use std::panic::{AssertUnwindSafe, catch_unwind}; @@ -15,7 +16,6 @@ unsafe extern "C" { fn read(fd: c_int, buffer: *mut c_void, count: usize) -> isize; fn close(fd: c_int) -> c_int; fn lseek(fd: c_int, offset: i64, whence: c_int) -> i64; - fn memchr(bytes: *const c_void, value: c_int, length: usize) -> *const c_void; } struct Descriptor(c_int); @@ -76,13 +76,10 @@ fn read_lines( let mut start = 0; while start < count { - // SAFETY: both the pointer and search length remain inside the initialized read. - let found = unsafe { memchr(buffer.as_ptr().add(start).cast(), 10, count - start) }; - if found.is_null() { + let Some(distance) = find_byte(&buffer[start..count], b'\n') else { break; - } - // SAFETY: memchr returned a pointer into this buffer. - let newline = unsafe { found.cast::().offset_from(buffer.as_ptr()) as usize }; + }; + let newline = start + distance; if skipping { skipping = false; } else if carry.is_empty() { @@ -133,11 +130,12 @@ pub unsafe extern "C" fn qb_read_lines( context: *mut c_void, consumed: *mut i64, ) -> i32 { - if path.is_null() || consumed.is_null() || wanted.is_none() || handle.is_none() { + if path.is_null() || consumed.is_null() { return EINVAL; } - let wanted = wanted.unwrap(); - let handle = handle.unwrap(); + let (Some(wanted), Some(handle)) = (wanted, handle) else { + return EINVAL; + }; let result = catch_unwind(AssertUnwindSafe(|| { // SAFETY: the ABI caller supplies a valid terminated path. let path = unsafe { CStr::from_ptr(path) }; diff --git a/Scripts/benchmark_classifier.py b/Scripts/benchmark_classifier.py index bc7c4ac..0f8d7c1 100644 --- a/Scripts/benchmark_classifier.py +++ b/Scripts/benchmark_classifier.py @@ -2,6 +2,7 @@ """Compare two release probes on a deterministic long-string transcript workload.""" import argparse +from datetime import datetime, timezone import json import os from pathlib import Path @@ -29,6 +30,8 @@ def main() -> None: ) binaries = {"before": args.before.resolve(), "after": args.after.resolve()} results: dict[str, list[float]] = {label: [] for label in binaries} + # Keep all records inside the rolling cost window for both executables. + timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z") with tempfile.TemporaryDirectory(prefix="quotabar-classifier-") as directory: root = Path(directory) projects = root / "claude/projects/app" @@ -40,7 +43,7 @@ def main() -> None: row = { "padding": padding, "type": "user" if line_index % 2 else "assistant", - "timestamp": "2026-11-07T02:00:00.000Z", + "timestamp": timestamp, "requestId": identifier, "message": { "id": identifier, @@ -52,7 +55,8 @@ def main() -> None: environment = dict(os.environ) for key, child in { "CLAUDE_CONFIG_DIR": "claude", "CODEX_HOME": "codex", - "PI_CODING_AGENT_DIR": "pi", "OPENCODE_DATA_HOME": "opencode", + "PI_CODING_AGENT_DIR": "pi", "PI_CODING_AGENT_SESSION_DIR": "pi/sessions", + "OPENCODE_DATA_HOME": "opencode", }.items(): environment[key] = str(root / child) for iteration in range(args.iterations): diff --git a/Scripts/ci_requires_build.sh b/Scripts/ci_requires_build.sh index 954cce2..dce843e 100644 --- a/Scripts/ci_requires_build.sh +++ b/Scripts/ci_requires_build.sh @@ -9,7 +9,7 @@ git diff --name-only --no-renames -z "${1:?base revision required}" "${2:?head r while IFS= read -r -d '' path; do case "$path" in - README.md|README.zh-CN.md|AGENTS.md|docs/*.md|docs/images/*.png|docs/images/*.jpg|docs/images/*.jpeg|docs/images/*.gif|docs/images/*.webp|docs/images/*.svg) + README.md|README.zh-CN.md|AGENTS.md|SECURITY.md|THIRD_PARTY_NOTICES.md|.agents/skills/*.md|docs/*.md|docs/images/*.png|docs/images/*.jpg|docs/images/*.jpeg|docs/images/*.gif|docs/images/*.webp|docs/images/*.svg) ;; *) echo true diff --git a/Scripts/readme_assets.sh b/Scripts/readme_assets.sh index 1cc5eb5..62a8971 100755 --- a/Scripts/readme_assets.sh +++ b/Scripts/readme_assets.sh @@ -23,7 +23,7 @@ echo "==> rendering frames" "$BIN" --dump-icons "$WORK/icons" >/dev/null "$BIN" --dump-settings "$WORK/settings" >/dev/null "$BIN" --dump-usage-report "$WORK/report" >/dev/null -node Scripts/report_image.mjs "$WORK/report/usage-report.html" "$OUT/usage-report.png" +pnpm run report:image "$WORK/report/usage-report.html" "$OUT/usage-report.png" # AppKit captures can carry wide-gamut profiles. Convert their pixels before ffmpeg, which does # not preserve those PNG profiles through overlays. diff --git a/Scripts/report_browser.mjs b/Scripts/report_browser.mjs new file mode 100644 index 0000000..50190fc --- /dev/null +++ b/Scripts/report_browser.mjs @@ -0,0 +1,27 @@ +import {createRequire} from 'node:module'; + +// PLAYWRIGHT_MODULE points to the entry file of an existing Playwright-backed CLI. +export async function launchReportBrowser() { + const {chromium} = process.env.PLAYWRIGHT_MODULE + ? createRequire(process.env.PLAYWRIGHT_MODULE)('playwright') + : await import('playwright-core'); + return chromium.launch({ + headless: true, + executablePath: process.env.CHROMIUM_PATH || '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser', + }); +} + +export async function captureReport(page) { + const viewport = page.viewportSize(); + const height = await page.evaluate(() => document.documentElement.scrollHeight); + if (height <= viewport.height) return page.screenshot({animations: 'disabled'}); + + // Fit the report in one frame. Chromium can repeat the first viewport when stitching a tall page. + await page.setViewportSize({...viewport, height}); + try { + await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))); + return await page.screenshot({animations: 'disabled'}); + } finally { + await page.setViewportSize(viewport); + } +} diff --git a/Scripts/report_image.mjs b/Scripts/report_image.mjs index 64365f2..276d1a5 100644 --- a/Scripts/report_image.mjs +++ b/Scripts/report_image.mjs @@ -1,25 +1,22 @@ // Renders a synthetic native HTML report for the README. Takes input HTML and output PNG paths. -import {realpathSync,mkdirSync} from 'node:fs'; +import {mkdirSync,writeFileSync} from 'node:fs'; import {dirname,resolve} from 'node:path'; import {pathToFileURL} from 'node:url'; -import {createRequire} from 'node:module'; -import {execFileSync} from 'node:child_process'; +import {captureReport,launchReportBrowser} from './report_browser.mjs'; const [input,output]=process.argv.slice(2); if(!input||!output)throw new Error('Usage: node Scripts/report_image.mjs INPUT.html OUTPUT.png'); -const modulePath=process.env.PLAYWRIGHT_MODULE||realpathSync(execFileSync('which',['playwright-cli'],{encoding:'utf8'}).trim()); -const {chromium}=createRequire(modulePath)('playwright'); -const browser=await chromium.launch({headless:true,executablePath:process.env.CHROMIUM_PATH||'/Applications/Brave Browser.app/Contents/MacOS/Brave Browser'}); +const browser=await launchReportBrowser(); try{ const context=await browser.newContext({viewport:{width:1040,height:1000},reducedMotion:'reduce',colorScheme:'dark'}); const errors=[]; await context.route(/^https?:/,route=>{errors.push('Unexpected external resource: '+route.request().url());return route.abort();}); const page=await context.newPage();page.on('pageerror',error=>errors.push(error.message)); await page.goto(pathToFileURL(resolve(input)).href+'?lang=en'); - await page.waitForFunction(()=>typeof window.setReportLanguage==='function'); - await page.locator('[data-language=en]').click(); + await page.locator('.hero-value').waitFor(); + const image=await captureReport(page); if(errors.length)throw new Error(errors.join('\n')); mkdirSync(dirname(resolve(output)),{recursive:true}); - await page.screenshot({path:resolve(output),fullPage:true}); + writeFileSync(output,image); console.log('Rendered sample report: '+output); }finally{await browser.close();} diff --git a/Scripts/verify_usage_report.mjs b/Scripts/verify_usage_report.mjs index 90cff69..44a46fc 100644 --- a/Scripts/verify_usage_report.mjs +++ b/Scripts/verify_usage_report.mjs @@ -1,10 +1,10 @@ // Browser regression checks for the native usage report page. import assert from 'node:assert/strict'; -import {readFileSync,realpathSync,mkdirSync,writeFileSync,rmSync} from 'node:fs'; +import {readFileSync,mkdirSync,mkdtempSync,writeFileSync,rmSync} from 'node:fs'; import {join,resolve} from 'node:path'; import {pathToFileURL} from 'node:url'; -import {createRequire} from 'node:module'; import {execFileSync} from 'node:child_process'; +import {captureReport,launchReportBrowser} from './report_browser.mjs'; const args=process.argv.slice(2); const option=(key,fallback)=>args.includes(key)?args[args.indexOf(key)+1]:fallback; @@ -17,20 +17,22 @@ assert(match,'Expected the native report output'); const snapshot=JSON.parse(match[1]); for(const script of source.matchAll(/]*>([\s\S]*?)<\/script>/g))execFileSync(process.execPath,['--check','-'],{input:script[1],stdio:['pipe','pipe','pipe']}); assert(!/<(?:script|link|img)[^>]+(?:src|href)=["']https?:/i.test(source)); -const modulePath=process.env.PLAYWRIGHT_MODULE||realpathSync(execFileSync('which',['playwright-cli'],{encoding:'utf8'}).trim()); -const {chromium}=createRequire(modulePath)('playwright'); -const browser=await chromium.launch({headless:true,executablePath:process.env.CHROMIUM_PATH||'/Applications/Brave Browser.app/Contents/MacOS/Brave Browser'}); +const browser=await launchReportBrowser(); const context=await browser.newContext({viewport:{width:1280,height:960},reducedMotion:'reduce'}); let external=0;await context.route(/^https?:/,route=>{external++;return route.abort();}); const errors=[],results=[]; const page=await context.newPage();page.on('pageerror',e=>errors.push(e.message)); -const reportFile=join(output,'case.html'); +const fixtureDirectory=mkdtempSync(join(output,'case-')); +const reportFile=join(fixtureDirectory,'usage-report.html'); const safeJSON=data=>JSON.stringify(data).replace(/`const REPORT=${safeJSON(data)};\n/* Report runtime */`)); - await page.evaluate(()=>{try{localStorage.clear();}catch{}}).catch(()=>{}); + if(page.url()!=='about:blank')await page.evaluate(()=>localStorage.clear()); await page.goto(pathToFileURL(reportFile).href+'?'+query); - await page.waitForFunction(()=>typeof window.setReportLanguage==='function'); + await page.locator('.hero-value').waitFor(); +} +async function screenshot(name){ + writeFileSync(join(output,name),await captureReport(page)); } const hero=()=>page.locator('.hero-value').textContent(); async function layout(){ @@ -46,6 +48,8 @@ async function checkLanguage(language){ const cjk=await page.evaluate(()=>[...document.querySelectorAll('.topbar :not([data-language]),.page *')] .filter(n=>!n.children.length&&/[㐀-鿿]/.test(n.textContent)).map(n=>n.textContent)); assert.deepEqual(cjk,[],'English view shows no Chinese copy'); + }else{ + assert.match(await page.getByRole('heading',{level:1}).innerText(),/[㐀-鿿]/,'The report title switches to Chinese'); } } @@ -66,26 +70,31 @@ const usd=v=>'$'+v.toLocaleString('en-US',{minimumFractionDigits:2,maximumFracti try{ await load(); + const defaultDays=snapshot.days.length===7?7:30; + const recentDays=snapshot.history.slice(-defaultDays); + const expectedSegments=Array(defaultDays-recentDays.length).fill(0) + .concat(recentDays.map(day=>day.sources.filter(row=>row.cost>0).length)); for(const language of ['zh','en']){ await checkLanguage(language); const metrics=await layout(); assert(metrics.scrollWidth<=metrics.width+2,'Desktop overflow'); assert.equal(metrics.escaped,0,'Content escapes the page'); - assert.equal(await page.locator('[data-chart=daily] svg rect:not([visibility])').count()>0||snapshot.days.every(day=>day.total===0),true,'Daily chart draws its nonzero columns'); - await page.screenshot({path:join(output,'native-'+language+'.png'),fullPage:true}); + const segments=await page.locator('.column').evaluateAll(columns=>columns.map(column=>column.querySelectorAll('rect').length)); + assert.deepEqual(segments,expectedSegments,'Each day draws one cost segment for each source with a positive estimate'); + await screenshot('native-'+language+'.png'); results.push({case:'native-'+language,...metrics}); } await page.locator('[data-metric=tokens]').click(); assert.equal(await page.locator('[data-metric=tokens]').getAttribute('aria-pressed'),'true'); await page.locator('[data-breakdown=day]').click(); - assert.equal(await page.locator('.days tbody tr').count(),snapshot.days.length,'Day breakdown lists every day in the default period'); + assert.equal(await page.locator('.days tbody tr').count(),defaultDays,'Day breakdown lists every day in the default period'); await page.locator('[data-language=zh]').click();await page.goto(pathToFileURL(reportFile).href); assert.equal(await page.locator('html').getAttribute('lang'),'zh-Hans','Language choice persists for the exported file'); assert.equal(await page.locator('[data-metric=tokens]').getAttribute('aria-pressed'),'true','Metric choice persists for the exported file'); for(const width of [640,390]){ await page.setViewportSize({width,height:700}); assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),'Narrow report body must reflow'); - await page.screenshot({path:join(output,'native-'+width+'.png'),fullPage:true}); + await screenshot('native-'+width+'.png'); } await page.setViewportSize({width:1280,height:960}); @@ -114,7 +123,7 @@ try{ assert.equal(await page.locator('[data-range-to]').inputValue(),'2026-09-09'); await page.goto(pathToFileURL(reportFile).href+'?lang=en&from=2026-08-10&to=2026-08-01'); assert.equal(await hero(),usd(sumCost(0,10)),'A reversed custom period is read in date order'); - await page.screenshot({path:join(output,'custom-period.png'),fullPage:true}); + await screenshot('custom-period.png'); results.push({case:'periods',passed:true}); await load(fixture(Array(7).fill(0))); @@ -134,7 +143,7 @@ try{ day.sources[0]={...day.sources[0],name:'Pi Agent',source:'piAgent'}; day.models=['anthropic','openrouter'].map(upstreamProvider=>({ ...day.models[0],name:'claude-sonnet-5',source:'piAgent',upstreamProvider, - ...Object.fromEntries(Object.entries(totals(50))), + ...totals(50), })); } await load(routed); @@ -143,7 +152,7 @@ try{ assert(routedLabels.some(label=>label.includes('anthropic'))&&routedLabels.some(label=>label.includes('openrouter')), 'Pi model rows identify their upstream providers'); assert.equal((await layout()).escaped,0,'Upstream labels stay inside the model column'); - await page.screenshot({path:join(output,'pi-upstreams.png'),fullPage:true}); + await screenshot('pi-upstreams.png'); results.push({case:'pi-upstreams',passed:true}); await load(fixture(Array(7).fill(100),{unpriced:true})); assert.equal(await hero(),'Unpriced'); @@ -152,7 +161,7 @@ try{ await load(fixture(Array(7).fill(100),{long:true})); assert((await page.locator('.model-name').first().textContent()).length>100); assert.equal((await layout()).escaped,0,'A long model name wraps inside the page'); - await page.screenshot({path:join(output,'long-model.png'),fullPage:true}); + await screenshot('long-model.png'); results.push({case:'long-model',passed:true}); await load(fixture(Array(7).fill(1e12))); await page.locator('[data-metric=tokens]').click(); @@ -161,4 +170,4 @@ try{ assert.deepEqual(errors,[]);assert.equal(external,0); writeFileSync(join(output,'verification.json'),JSON.stringify({results,errors,external},null,2)+'\n'); console.log('Passed native report: bilingual copy, persistence, 7/30/custom periods, missing/zero dates, pricing states, offline, narrow windows, and long model IDs.'); -}finally{rmSync(reportFile,{force:true});await browser.close();} +}finally{rmSync(fixtureDirectory,{recursive:true,force:true});await browser.close();} diff --git a/Sources/QuotaBarApp/App.swift b/Sources/QuotaBarApp/App.swift index 11aa433..39c536f 100644 --- a/Sources/QuotaBarApp/App.swift +++ b/Sources/QuotaBarApp/App.swift @@ -40,14 +40,9 @@ public enum QuotaBarLaunch { #if DEBUG let arguments = CommandLine.arguments - /// `--flag ...`: the `count` arguments after `flag`, when the caller passed that - /// many. Nil for a flag that is absent or short of its arguments, which leaves the app to - /// launch normally rather than acting on half a request. - func values(after flag: String, count: Int) -> [String]? { - guard let index = arguments.firstIndex(of: flag), index + count < arguments.count else { - return nil - } - return Array(arguments[(index + 1)...(index + count)]) + func value(after flag: String) -> String? { + guard let index = arguments.firstIndex(of: flag) else { return nil } + return arguments.dropFirst(index + 1).first } // Manual checks that need the real menu bar, and the README asset dumps, are launch @@ -66,11 +61,11 @@ public enum QuotaBarLaunch { UsageReportDumps.previewLiveWindow() } - if let state = values(after: "--preview-interface", count: 1)?.first { + if let state = value(after: "--preview-interface") { InterfacePreview.run(state: state) } - // `Scripts/readme_assets.sh` drives these. Each writes its frames and exits. + // Documentation and development captures each accept one output directory. let dumps: [(flag: String, run: @MainActor (String) -> Void)] = [ ("--dump-interaction-states", CardDump.dumpInteractionStates), ("--dump-icons", IconDump.run), @@ -80,7 +75,7 @@ public enum QuotaBarLaunch { ("--dump-usage-window", UsageReportDumps.dumpUsageWindow), ] for dump in dumps { - if let directory = values(after: dump.flag, count: 1)?[0] { + if let directory = value(after: dump.flag) { dump.run(directory) return } diff --git a/Sources/QuotaBarApp/CardDump.swift b/Sources/QuotaBarApp/CardDump.swift index 28eca14..9f64579 100644 --- a/Sources/QuotaBarApp/CardDump.swift +++ b/Sources/QuotaBarApp/CardDump.swift @@ -208,7 +208,8 @@ enum CardDump { case let .written(url): print("wrote \(url.path) (\(Int(hosting.frame.width))x\(Int(hosting.frame.height)))") case let .failed(reason): - print(reason) + fputs("\(reason)\n", stderr) + exit(1) } } diff --git a/Sources/QuotaBarApp/CostSectionView.swift b/Sources/QuotaBarApp/CostSectionView.swift index 70a4296..9c0eec8 100644 --- a/Sources/QuotaBarApp/CostSectionView.swift +++ b/Sources/QuotaBarApp/CostSectionView.swift @@ -201,7 +201,7 @@ struct CostSectionView: View { let scale = max(self.displayScale, 1) // Align the one-point stroke's edges to pixels so it stays crisp at 1× too. let y = ((rawY - 0.5) * scale).rounded() / scale + 0.5 - let tops = self.barTops(slotWidth: slotWidth) + let tops = self.barTops() // One continuous rule, with a 2pt clearance cut around every bar, so a // bar ending just under it never looks outlined by it. Canvas { context, _ in @@ -369,7 +369,7 @@ struct CostSectionView: View { } /// Each day's bar top in the chart's space, or nil for a day drawn as a stub. - private func barTops(slotWidth: CGFloat) -> [CGFloat?] { + private func barTops() -> [CGFloat?] { let maxValue = CostChartHighlightPolicy.maxValue(for: self.bars, mode: self.selectedLabelMode) return self.bars.map { day in let value = CostChartHighlightPolicy.value(for: day, mode: self.selectedLabelMode) @@ -709,8 +709,8 @@ struct CostSectionView: View { return "\(percent)%" } - /// The model's name over a bar of its share of the day, in the chosen unit. When the day mixes - /// tools, each row also names the tool it came from, in words and by its mark. + /// The model's share of the day in the selected unit. Pi rows name their upstream provider; + /// rows from mixed tools name their source. private func breakdownRow( _ entry: (key: ModelUsageKey, model: String, usage: ModelDayUsage), showsSource: Bool, diff --git a/Sources/QuotaBarApp/IconDump.swift b/Sources/QuotaBarApp/IconDump.swift index 62e125e..2288474 100644 --- a/Sources/QuotaBarApp/IconDump.swift +++ b/Sources/QuotaBarApp/IconDump.swift @@ -21,8 +21,8 @@ enum IconDump { ) let url = root.appendingPathComponent("\(entry.name).png") guard Self.writePNG(image, to: url) else { - print("failed to write \(url.path)") - continue + fputs("failed to write \(url.path)\n", stderr) + exit(1) } print("wrote \(url.path)") } diff --git a/Sources/QuotaBarApp/MenuCardView.swift b/Sources/QuotaBarApp/MenuCardView.swift index 5423c3e..82d4962 100644 --- a/Sources/QuotaBarApp/MenuCardView.swift +++ b/Sources/QuotaBarApp/MenuCardView.swift @@ -398,10 +398,7 @@ struct MenuCardView: View { } else if snapshot.sessionIsUnlimited { // Held in the session slot rather than dropped, so a plan without the // five-hour cap lines up with one that has it. - UnlimitedWindowRow( - title: QuotaWindowKind.session.title, - tint: Theme.accent(for: self.provider) - ) + UnlimitedWindowRow(title: QuotaWindowKind.session.title) } if let weekly = snapshot.weekly { self.window(window: weekly, kind: .weekly) @@ -516,7 +513,6 @@ private struct QuotaWindowRow: View { // A saved reading loses its hue rather than going muddy: grey at the same weight. tint: self.isStale ? Color.primary.opacity(0.42) : Theme.accent(for: self.provider), pacePercent: self.pacePercent, - paceIsDeficit: self.paceIsDeficit, isExhausted: self.isExhausted, isStale: self.isStale, animatesFill: self.animatesFill, @@ -600,12 +596,9 @@ private struct QuotaWindowRow: View { } } -/// A window the plan does not cap: the same headline, bar and trailing label as a metered row, so -/// the card keeps its shape, but nothing on it counts down. The bar sits full and faded, since -/// there is no balance for it to spend and a full-strength fill would read as a fresh reset. +/// An uncapped window keeps the metered row's layout and uses a neutral dashed rule. private struct UnlimitedWindowRow: View { let title: String - let tint: Color var body: some View { VStack(alignment: .leading, spacing: 8) { diff --git a/Sources/QuotaBarApp/OffscreenCapture.swift b/Sources/QuotaBarApp/OffscreenCapture.swift index 10b128b..21774a2 100644 --- a/Sources/QuotaBarApp/OffscreenCapture.swift +++ b/Sources/QuotaBarApp/OffscreenCapture.swift @@ -6,9 +6,7 @@ import AppKit /// to build its view and name its file. @MainActor enum OffscreenCapture { - /// The real card sits on the menu's vibrant material, so the dumps are forced dark. But - /// `cacheDisplay` paints no window background, so the render also needs an opaque ground of its - /// own — without one the dark-mode text comes out white on white. + /// Opaque ground for dark captures. `cacheDisplay` omits the window background. private static let ground = NSColor(white: 0.13, alpha: 1) enum Outcome { @@ -92,7 +90,12 @@ enum OffscreenCapture { /// `` as the dumps take it: tilde-expanded and created if it is not there yet. nonisolated static func directory(_ path: String) -> URL { let root = URL(fileURLWithPath: (path as NSString).expandingTildeInPath) - try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + do { + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } catch { + fputs("Could not create capture directory \(root.path): \(error.localizedDescription)\n", stderr) + exit(1) + } return root } } diff --git a/Sources/QuotaBarApp/ProviderDisplay.swift b/Sources/QuotaBarApp/ProviderDisplay.swift index 56cdc0a..15e4558 100644 --- a/Sources/QuotaBarApp/ProviderDisplay.swift +++ b/Sources/QuotaBarApp/ProviderDisplay.swift @@ -1,8 +1,7 @@ import QuotaBarCore import Foundation -/// A quota refresh problem, separate from a missing login and from the local usage scan. -/// Local usage collection runs independently of the provider's quota request. +/// Progress of the local usage scan, which runs independently of the quota request. enum LocalScanStatus: Equatable { case idle case scanning diff --git a/Sources/QuotaBarApp/ProviderTabBar.swift b/Sources/QuotaBarApp/ProviderTabBar.swift index aa029f2..d7216ac 100644 --- a/Sources/QuotaBarApp/ProviderTabBar.swift +++ b/Sources/QuotaBarApp/ProviderTabBar.swift @@ -24,16 +24,9 @@ struct ProviderTabBar: View { options: Self.providers, selection: self.selection, style: Self.style, - emphasisAnimation: { - CostChartHoverMotion.systemReduceMotion ? nil : .easeOut(duration: 0.12) - }, - edgeCurves: { - TabSwitchMotion.edgeCurves(movingRight: $0, reduceMotion: CostChartHoverMotion.systemReduceMotion) - }, keyboardSelection: .cutAllAnimations, shortcut: { KeyboardShortcut(Self.shortcutKey(for: $0), modifiers: .command) }, accessibilityLabel: { $0.displayName }, - selectedTraits: .isSelected, onSelect: self.onSelect ) { provider, isSelected, isEmphasized, emphasisAnimation in self.label(provider, isSelected: isSelected, isEmphasized: isEmphasized, diff --git a/Sources/QuotaBarApp/SegmentedSwitch.swift b/Sources/QuotaBarApp/SegmentedSwitch.swift index cfea54d..b008cde 100644 --- a/Sources/QuotaBarApp/SegmentedSwitch.swift +++ b/Sources/QuotaBarApp/SegmentedSwitch.swift @@ -16,7 +16,7 @@ struct SegmentedSwitchStyle { } /// Equal-width custom segments with shared focus, hover, press, and selection feedback. -/// Labels and motion policies remain with the caller so the two switches keep their own behavior. +/// Callers supply their labels, shortcuts and keyboard selection behavior. struct SegmentedSwitch: View { enum KeyboardSelection { case cutAllAnimations @@ -26,12 +26,9 @@ struct SegmentedSwitch: View { let options: [Option] let selection: Option let style: SegmentedSwitchStyle - let emphasisAnimation: () -> Animation? - let edgeCurves: (Bool) -> (minX: Animation?, maxX: Animation?) let keyboardSelection: KeyboardSelection let shortcut: (Option) -> KeyboardShortcut? let accessibilityLabel: (Option) -> String - let selectedTraits: AccessibilityTraits let onSelect: (Option) -> Void let label: (Option, Bool, Bool, Animation?) -> Label @@ -47,24 +44,18 @@ struct SegmentedSwitch: View { options: [Option], selection: Option, style: SegmentedSwitchStyle, - emphasisAnimation: @escaping () -> Animation?, - edgeCurves: @escaping (Bool) -> (minX: Animation?, maxX: Animation?), keyboardSelection: KeyboardSelection, shortcut: @escaping (Option) -> KeyboardShortcut?, accessibilityLabel: @escaping (Option) -> String, - selectedTraits: AccessibilityTraits, onSelect: @escaping (Option) -> Void, @ViewBuilder label: @escaping (Option, Bool, Bool, Animation?) -> Label ) { self.options = options self.selection = selection self.style = style - self.emphasisAnimation = emphasisAnimation - self.edgeCurves = edgeCurves self.keyboardSelection = keyboardSelection self.shortcut = shortcut self.accessibilityLabel = accessibilityLabel - self.selectedTraits = selectedTraits self.onSelect = onSelect self.label = label let span = Self.span(of: selection, in: options) @@ -87,7 +78,7 @@ struct SegmentedSwitch: View { } .onHover { hovered in self.hovered = hovered ? option : nil } .accessibilityLabel(self.accessibilityLabel(option)) - .accessibilityAddTraits(option == self.selection ? self.selectedTraits : []) + .accessibilityAddTraits(option == self.selection ? .isSelected : []) } } .frame(height: self.style.segmentHeight) @@ -103,7 +94,10 @@ struct SegmentedSwitch: View { } .onChange(of: self.selection) { _, newValue in let span = Self.span(of: newValue, in: self.options) - let curves = self.edgeCurves(span.minX >= self.pillMinX) + let curves = TabSwitchMotion.edgeCurves( + movingRight: span.minX >= self.pillMinX, + reduceMotion: CostChartHoverMotion.systemReduceMotion + ) let animates = self.clickedOption == newValue self.clickedOption = nil // Two transactions keep the leading and trailing edges on their own clocks. @@ -116,7 +110,7 @@ struct SegmentedSwitch: View { private func segment(_ option: Option) -> some View { let isSelected = option == self.selection // Re-read Reduce Motion on local hover updates as well as parent selection updates. - let emphasisAnimation = self.emphasisAnimation() + let emphasisAnimation: Animation? = CostChartHoverMotion.systemReduceMotion ? nil : .easeOut(duration: 0.12) return self.label(option, isSelected, isSelected || self.hovered == option, emphasisAnimation) .frame(maxWidth: .infinity, maxHeight: .infinity) .background { diff --git a/Sources/QuotaBarApp/SourceMark.swift b/Sources/QuotaBarApp/SourceMark.swift deleted file mode 100644 index 7bd5db0..0000000 --- a/Sources/QuotaBarApp/SourceMark.swift +++ /dev/null @@ -1,293 +0,0 @@ -import QuotaBarCore -import SwiftUI - -/// The mark of the local tool a row of usage came from: the same OpenAI, Claude, OpenCode, and Pi -/// marks the usage report draws, so a model reads the same in the menu and in the report. -struct SourceMark: View { - let source: CostUsageSource - var size: CGFloat = 12 - - var body: some View { - let art = SourceMarkArt.art(for: self.source) - ZStack { - ForEach(Array(art.layers.enumerated()), id: \.offset) { _, layer in - SVGPathShape(path: layer.path, viewBox: art.viewBox) - .fill(layer.tone.color, style: FillStyle(eoFill: layer.evenOdd)) - } - } - .frame(width: self.size, height: self.size) - .accessibilityHidden(true) - } -} - -/// One mark as the report's SVG has it: a view box and the filled paths drawn in it. -struct SourceMarkArt { - enum Tone { - /// The monochrome marks follow the text color, as the report's do in each theme. - case ink - case faint - case claude - - var color: Color { - switch self { - case .ink: Color(nsColor: .labelColor) - case .faint: Color(nsColor: .tertiaryLabelColor) - case .claude: Color(red: 0xD9 / 255, green: 0x77 / 255, blue: 0x57 / 255) - } - } - } - - struct Layer { - let tone: Tone - let evenOdd: Bool - let path: Path - - init(tone: Tone, evenOdd: Bool, data: String) { - self.tone = tone - self.evenOdd = evenOdd - self.path = Path(SVGPathParser.path(from: data)) - } - } - - let viewBox: CGRect - let layers: [Layer] - - static func art(for source: CostUsageSource) -> SourceMarkArt { - switch source { - case .codex: Self.codex - case .claude: Self.claude - case .openCode: Self.openCode - case .piAgent: Self.piAgent - } - } - - // Path data copied from the usage report's ICONS table in report.js. - - static let codex = SourceMarkArt( - viewBox: CGRect(x: 100, y: 100, width: 411, height: 411), - layers: [ - Layer(tone: .ink, evenOdd: true, data: - """ - M252.794 108.802C289.191 99.0484 326.265 110.305 351.148 135.135C385.113 126.072 422.85 134.862 \ - 449.492 161.505C476.136 188.149 484.925 225.888 475.862 259.85V259.854C500.696 284.735 511.95 32\ - 1.81 502.198 358.207C492.447 394.602 464.161 421.084 430.215 430.217C421.083 464.162 394.603 492\ - .448 358.206 502.199C321.812 511.951 284.734 500.693 259.852 475.864C225.887 484.927 188.15 476.\ - 137 161.507 449.495C134.864 422.851 126.073 385.111 135.136 351.149C110.304 326.266 99.0496 289.\ - 192 108.801 252.795C118.552 216.4 146.84 189.918 180.784 180.785C189.917 146.841 216.396 118.553\ - 252.794 108.802ZM374.292 407.145C374.292 411.271 372.092 415.086 368.517 417.148L283.723 466.10\ - 2C302.487 480.585 327.555 486.459 352.217 479.852C386.997 470.532 410.068 439.312 410.555 405.00\ - 6V317.717C410.555 315.08 409.125 312.621 406.843 311.303L374.292 292.509V407.145ZM251.868 415.89\ - 7C248.296 417.959 243.893 417.959 240.317 415.897L155.526 366.942C152.366 390.436 159.811 415.08\ - 177.866 433.136H177.863C203.325 458.594 241.896 462.962 271.85 446.232L347.449 402.586C349.735 \ - 401.268 351.148 398.8 351.148 396.163V358.579L251.868 415.897ZM368.602 220.628C366.319 219.309 3\ - 63.474 219.318 361.191 220.637L328.641 239.431L427.921 296.749C431.496 298.811 433.697 302.627 4\ - 33.697 306.752V404.661C455.622 395.654 473.244 376.881 479.851 352.218C489.169 317.442 473.668 2\ - 81.85 444.201 264.274L368.602 220.628ZM177.303 206.34C155.377 215.348 137.756 234.122 131.148 25\ - 8.783C121.832 293.561 137.331 329.153 166.799 346.727L242.398 390.373C244.68 391.692 247.525 391\ - .684 249.807 390.366L282.357 371.572L183.078 314.253C179.504 312.189 177.303 308.375 177.303 304\ - .251V206.34ZM259.849 279.145V331.858L305.5 358.213L351.15 331.858V279.145L305.5 252.789L259.849 \ - 279.145ZM327.276 144.9C308.512 130.418 283.445 124.543 258.782 131.15C224.002 140.471 200.931 17\ - 1.691 200.445 205.995V293.286C200.445 295.923 201.875 298.381 204.158 299.7L236.707 318.493V203.\ - 856C236.707 199.731 238.909 195.916 242.483 193.853L327.276 144.9ZM433.137 177.867C407.675 152.4\ - 07 369.103 148.038 339.149 164.769L263.55 208.415C261.265 209.734 259.852 212.202 259.852 214.83\ - 8V252.423L359.132 195.105C362.703 193.041 367.108 193.041 370.682 195.105L455.473 244.06C458.635\ - 220.567 451.189 195.922 433.135 177.867H433.137Z - """ - ), - ] - ) - - static let claude = SourceMarkArt( - viewBox: CGRect(x: 0, y: 0, width: 256, height: 257), - layers: [ - Layer(tone: .claude, evenOdd: false, data: - """ - m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-2\ - 4.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.6\ - 29 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258\ - -10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L9\ - 4.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.\ - 814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0 82.05 1.426l4.472 3.888 6.61 1\ - 5.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.52\ - 8-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.76\ - 8-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657\ - 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518\ - .778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5\ - .184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 \ - 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11\ - .406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.54\ - 5-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.6\ - 47-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.43\ - 6-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 2\ - 0.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.3\ - 6-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.59\ - 3 20.35-13.999-.064.065Z - """ - ), - ] - ) - - static let openCode = SourceMarkArt( - viewBox: CGRect(x: 0, y: 0, width: 32, height: 40), - layers: [ - Layer(tone: .faint, evenOdd: false, data: - "M24 32H8V16H24V32Z" - ), - Layer(tone: .ink, evenOdd: false, data: - "M24 8H8V32H24V8ZM32 40H0V0H32V40Z" - ), - ] - ) - - static let piAgent = SourceMarkArt( - viewBox: CGRect(x: 165.29, y: 165.29, width: 469.43, height: 469.43), - layers: [ - Layer(tone: .ink, evenOdd: true, data: - "M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z" - ), - Layer(tone: .ink, evenOdd: false, data: - "M517.36 400H634.72V634.72H517.36Z" - ), - ] - ) -} - -/// Scales a path drawn in `viewBox` to fit the frame, centered, the way SVG's default -/// `xMidYMid meet` does. -private struct SVGPathShape: Shape { - let path: Path - let viewBox: CGRect - - func path(in rect: CGRect) -> Path { - let scale = min(rect.width / self.viewBox.width, rect.height / self.viewBox.height) - let x = rect.midX - self.viewBox.midX * scale - let y = rect.midY - self.viewBox.midY * scale - let transform = CGAffineTransform(a: scale, b: 0, c: 0, d: scale, tx: x, ty: y) - return self.path.applying(transform) - } -} - -/// Reads the subset of SVG path syntax the marks use: move, line, horizontal, vertical, cubic -/// curve, and close, in absolute and relative form. -enum SVGPathParser { - static func path(from data: String) -> CGPath { - let path = CGMutablePath() - var tokens = Tokens(data) - var current = CGPoint.zero - var start = CGPoint.zero - var command: Character = "M" - - while let next = tokens.next() { - if case let .command(c) = next { - command = c - if c == "Z" || c == "z" { - path.closeSubpath() - current = start - continue - } - } else { - tokens.pushBack(next) - } - let relative = command.isLowercase - let origin = relative ? current : .zero - switch command.uppercased() { - case "M": - guard let point = tokens.point(offset: origin) else { return path } - path.move(to: point) - current = point - start = point - // Pairs after a move are implicit lines. - command = relative ? "l" : "L" - case "L": - guard let point = tokens.point(offset: origin) else { return path } - path.addLine(to: point) - current = point - case "H": - guard let x = tokens.number() else { return path } - current = CGPoint(x: x + origin.x, y: current.y) - path.addLine(to: current) - case "V": - guard let y = tokens.number() else { return path } - current = CGPoint(x: current.x, y: y + origin.y) - path.addLine(to: current) - case "C": - guard let c1 = tokens.point(offset: origin), - let c2 = tokens.point(offset: origin), - let end = tokens.point(offset: origin) else { return path } - path.addCurve(to: end, control1: c1, control2: c2) - current = end - default: - return path - } - } - return path - } - - private enum Token { - case command(Character) - case number(CGFloat) - } - - private struct Tokens { - private let scalars: [Character] - private var index = 0 - private var pending: Token? - - init(_ data: String) { - self.scalars = Array(data) - } - - mutating func pushBack(_ token: Token) { - self.pending = token - } - - mutating func number() -> CGFloat? { - guard case let .number(value)? = self.next() else { return nil } - return value - } - - mutating func point(offset: CGPoint) -> CGPoint? { - guard let x = self.number(), let y = self.number() else { return nil } - return CGPoint(x: x + offset.x, y: y + offset.y) - } - - mutating func next() -> Token? { - if let pending = self.pending { - self.pending = nil - return pending - } - while self.index < self.scalars.count, - self.scalars[self.index] == " " || self.scalars[self.index] == "," { - self.index += 1 - } - guard self.index < self.scalars.count else { return nil } - let first = self.scalars[self.index] - if first.isLetter, first != "e", first != "E" { - self.index += 1 - return .command(first) - } - // A number ends at a second sign, a second decimal point, or anything else. - var text = "" - var seenDot = false - var seenExponent = false - while self.index < self.scalars.count { - let c = self.scalars[self.index] - if c == "-" || c == "+" { - guard text.isEmpty || text.last == "e" || text.last == "E" else { break } - } else if c == "." { - guard !seenDot, !seenExponent else { break } - seenDot = true - } else if c == "e" || c == "E" { - guard !seenExponent else { break } - seenExponent = true - } else if !c.isNumber { - break - } - text.append(c) - self.index += 1 - } - guard let value = Double(text) else { return nil } - return .number(CGFloat(value)) - } - } -} diff --git a/Sources/QuotaBarApp/UsageProgressBar.swift b/Sources/QuotaBarApp/UsageProgressBar.swift index a60c8cc..7711828 100644 --- a/Sources/QuotaBarApp/UsageProgressBar.swift +++ b/Sources/QuotaBarApp/UsageProgressBar.swift @@ -15,8 +15,6 @@ struct UsageProgressBar: View { let tint: Color /// Where the fill would sit if the budget were being spent evenly, in remaining percent. let pacePercent: Double? - /// Burning faster than the clock. The marker stays neutral; the outcome line carries the color. - let paceIsDeficit: Bool /// The window is spent: the track takes a red tint so an empty bar never reads as a blank one. let isExhausted: Bool /// A saved reading: the pace tick steps back with the grey fill. @@ -64,7 +62,6 @@ struct UsageProgressBar: View { percent: Double, tint: Color, pacePercent: Double? = nil, - paceIsDeficit: Bool = false, isExhausted: Bool = false, isStale: Bool = false, animatesFill: Bool = true, @@ -77,7 +74,6 @@ struct UsageProgressBar: View { self.percent = percent self.tint = tint self.pacePercent = pacePercent - self.paceIsDeficit = paceIsDeficit self.isExhausted = isExhausted self.isStale = isStale self.animatesFill = animatesFill diff --git a/Sources/QuotaBarApp/UsageReportWindowController.swift b/Sources/QuotaBarApp/UsageReportWindowController.swift index 33283dc..9b82b38 100644 --- a/Sources/QuotaBarApp/UsageReportWindowController.swift +++ b/Sources/QuotaBarApp/UsageReportWindowController.swift @@ -76,8 +76,7 @@ final class UsageReportWindowController: NSObject, NSWindowDelegate, WKNavigatio } } - /// How often an open window rescans local logs. Scans are incremental, so after the first - /// pass each one only reads what the sources appended since. + /// How often an open window requests fresh local usage. static let rescanInterval: TimeInterval = 60 private let operations: Operations diff --git a/Sources/QuotaBarApp/UsageStore.swift b/Sources/QuotaBarApp/UsageStore.swift index ebd90e3..28270d2 100644 --- a/Sources/QuotaBarApp/UsageStore.swift +++ b/Sources/QuotaBarApp/UsageStore.swift @@ -37,10 +37,8 @@ final class UsageStore: ObservableObject { private var timer: Timer? private var refreshTasks: [Provider: Task] = [:] - private var costTasks: [Provider: Task] = [:] - private var pendingCostRefreshes: Set = [] - private var piCostTask: Task? - private var piCostRefreshPending = false + private var costTasks: [UsageTab: Task] = [:] + private var pendingCostRefreshes: Set = [] private let fetchPiCost: () async -> CostSnapshot? private let historyStore: UsageHistoryStore private let recovery: QuotaRecoveryTracker @@ -48,6 +46,7 @@ final class UsageStore: ObservableObject { private var settingsObserver: AnyCancellable? private var providerObserver: AnyCancellable? private var modelsDevObserver: AnyCancellable? + private var pricingChangeTask: Task? /// The models.dev download in flight, so cost refreshes started meanwhile do not queue more. private var thirdPartyRatesTask: Task? /// Whether each provider may be refreshed now, claimed by whichever path asked. @@ -58,7 +57,6 @@ final class UsageStore: ObservableObject { private let fetchCost: (Provider) async -> CostSnapshot? /// Downloads models.dev when it is due; true when the rates changed. private let updateThirdPartyRates: () async -> Bool - private let invalidatePricing: () async -> Void private let remoteLogMirror: RemoteLogMirror /// The cost service every local scan goes through. let costService: CostService @@ -87,7 +85,6 @@ final class UsageStore: ObservableObject { // Pi reads nothing there unless it is supplied too. self.fetchPiCost = fetchPiCost ?? (fetchCost == nil ? { await costService.refresh(.pi) } : { nil }) self.updateThirdPartyRates = updateThirdPartyRates ?? { await costService.updateThirdPartyRates() } - self.invalidatePricing = { await costService.invalidatePricing() } self.remoteLogMirror = RemoteLogMirror(root: costService.remoteLogsURL) } @@ -124,9 +121,12 @@ final class UsageStore: ObservableObject { self.thirdPartyRatesTask?.cancel() self.thirdPartyRatesTask = nil } - Task { @MainActor in - await self.invalidatePricing() + self.pricingChangeTask?.cancel() + self.pricingChangeTask = Task { [weak self, costService = self.costService] in + await costService.invalidatePricing() + guard let self, !Task.isCancelled else { return } self.refreshCostsAfterPricingChange() + self.pricingChangeTask = nil } } } @@ -154,11 +154,17 @@ final class UsageStore: ObservableObject { self.timer = nil for task in self.refreshTasks.values { task.cancel() } self.refreshTasks = [:] - for task in self.costTasks.values { task.cancel() } + self.refreshingProviders = [] + for (tab, task) in self.costTasks { + task.cancel() + self[tab].localScanStatus = .idle + } self.costTasks = [:] self.pendingCostRefreshes = [] self.thirdPartyRatesTask?.cancel() self.thirdPartyRatesTask = nil + self.pricingChangeTask?.cancel() + self.pricingChangeTask = nil self.settingsObserver = nil self.providerObserver = nil self.modelsDevObserver = nil @@ -190,7 +196,9 @@ final class UsageStore: ObservableObject { self.refreshingProviders.insert(provider) self.refreshTasks[provider] = Task { [weak self, historyStore, fetchState] in + guard !Task.isCancelled else { return } let state = await fetchState(provider, interaction) + guard !Task.isCancelled else { return } // Sampling the weekly window builds the history the pace model regresses over. // CodexBar records only Codex here; the model is provider-agnostic, so both are. @@ -199,16 +207,14 @@ final class UsageStore: ObservableObject { history = await historyStore.record(provider: provider, window: weekly) } - await MainActor.run { - guard let self else { return } - self.apply(state: state, to: provider, history: history) - Self.log(provider: provider, state: state) - self.refreshingProviders.remove(provider) - self.refreshTasks[provider] = nil - } + guard let self, !Task.isCancelled else { return } + self.apply(state: state, to: provider, history: history) + Self.log(provider: provider, state: state) + self.refreshingProviders.remove(provider) + self.refreshTasks[provider] = nil } - self.refreshCosts(for: provider) + self.refreshCosts(for: UsageTab(provider: provider)) } private static func fetch( @@ -221,86 +227,74 @@ final class UsageStore: ObservableObject { } } - /// Log scanning runs on its own task: the first pass reads hundreds of megabytes and must not - /// hold up the quota numbers, which are what the menu bar icon needs. Utility priority lets - /// that multi-second pass yield the performance cores to whatever the user is doing. - private func refreshCosts(for provider: Provider, repeatingRunningScan: Bool = false) { - self.updateThirdPartyRatesIfDue() - guard self.costTasks[provider] == nil else { - if repeatingRunningScan { self.pendingCostRefreshes.insert(provider) } - return + private subscript(tab: UsageTab) -> ProviderDisplay { + get { + guard let provider = tab.quotaProvider else { return self.piDisplay } + return self.displays[provider] ?? ProviderDisplay() } - - self.displays[provider, default: ProviderDisplay()].localScanStatus = .scanning - self.costTasks[provider] = Task(priority: .utility) { [weak self, fetchCost, costService] in - let scanned = await fetchCost(provider) - let scanFailed = await costService.currentScanStatuses().contains { entry in - guard entry.source.tab == UsageTab(provider: provider) else { return false } - if case .error = entry.status { return true } - return false - } - await MainActor.run { - guard let self else { return } - var display = self.displays[provider] ?? ProviderDisplay() - if let scanned { - display.cost = scanned - display.localScanStatus = - scanFailed - ? .failed("Some local usage could not be scanned. Available usage is shown; retry the scan.") - : .completed(self.dateClock()) - } else { - display.localScanStatus = - .failed("Local usage scan failed. Previous usage remains available.") - } - self.displays[provider] = display - self.costTasks[provider] = nil - self.finishedLocalScans += 1 - if self.pendingCostRefreshes.remove(provider) != nil { - self.refreshCosts(for: provider) - } + set { + if let provider = tab.quotaProvider { + self.displays[provider] = newValue + } else { + self.piDisplay = newValue } } } - /// Scans Pi's sessions. It shares nothing with a quota refresh, so it has no cooldown; calls - /// during a scan coalesce, and one that must see newer data queues a single follow-up. - func refreshPiUsage(repeatingRunningScan: Bool = false) { + /// Local scans run independently of quota. Each tab coalesces overlapping requests and + /// queues one follow-up when changed pricing or new logs need a fresh scan. + private func refreshCosts(for tab: UsageTab, repeatingRunningScan: Bool = false) { self.updateThirdPartyRatesIfDue() - guard self.piCostTask == nil else { - if repeatingRunningScan { self.piCostRefreshPending = true } + guard self.costTasks[tab] == nil else { + if repeatingRunningScan { self.pendingCostRefreshes.insert(tab) } return } - self.piDisplay.localScanStatus = .scanning - self.piCostTask = Task(priority: .utility) { [weak self, fetchPiCost, costService] in - let scanned = await fetchPiCost() + + self[tab].localScanStatus = .scanning + self.costTasks[tab] = Task(priority: .utility) { [weak self, fetchCost, fetchPiCost, costService] in + guard !Task.isCancelled else { return } + let scanned: CostSnapshot? + if let provider = tab.quotaProvider { + scanned = await fetchCost(provider) + } else { + scanned = await fetchPiCost() + } + guard !Task.isCancelled else { return } let scanFailed = await costService.currentScanStatuses().contains { entry in - guard entry.source.tab == .pi else { return false } + guard entry.source.tab == tab else { return false } if case .error = entry.status { return true } return false } - await MainActor.run { - guard let self else { return } - if let scanned { - self.piDisplay.cost = scanned - self.piDisplay.localScanStatus = - scanFailed - ? .failed("Some Pi sessions could not be scanned. Available usage is shown; retry the scan.") - : .completed(self.dateClock()) + // stop() may have cancelled this task and a new scan may now own the tab. + guard let self, !Task.isCancelled else { return } + var display = self[tab] + if let scanned { + display.cost = scanned + if scanFailed { + let message = tab == .pi + ? "Some Pi sessions could not be scanned. Available usage is shown; retry the scan." + : "Some local usage could not be scanned. Available usage is shown; retry the scan." + display.localScanStatus = .failed(message) } else { - self.piDisplay.localScanStatus = - .failed("Local usage scan failed. Previous usage remains available.") - } - self.piCostTask = nil - self.finishedLocalScans += 1 - if self.piCostRefreshPending { - self.piCostRefreshPending = false - self.refreshPiUsage() + display.localScanStatus = .completed(self.dateClock()) } + } else { + display.localScanStatus = .failed("Local usage scan failed. Previous usage remains available.") + } + self[tab] = display + self.costTasks[tab] = nil + self.finishedLocalScans += 1 + if self.pendingCostRefreshes.remove(tab) != nil { + self.refreshCosts(for: tab) } } } - var isScanningPi: Bool { self.piCostTask != nil } + func refreshPiUsage(repeatingRunningScan: Bool = false) { + self.refreshCosts(for: .pi, repeatingRunningScan: repeatingRunningScan) + } + + var isScanningPi: Bool { self.costTasks[.pi] != nil } #if DEBUG func debugSetPiDisplay(_ display: ProviderDisplay) { self.piDisplay = display } @@ -315,8 +309,7 @@ final class UsageStore: ObservableObject { /// Newly mirrored logs and imported usage need a scan that starts after them, so a scan /// already running does not stand in for this one. func refreshAllLocalUsageAfterChange() { - for provider in Provider.allCases { self.refreshCosts(for: provider, repeatingRunningScan: true) } - self.refreshPiUsage(repeatingRunningScan: true) + for tab in UsageTab.allCases { self.refreshCosts(for: tab, repeatingRunningScan: true) } } /// Checks models.dev alongside a cost refresh without holding the scan up. The service @@ -324,26 +317,24 @@ final class UsageStore: ObservableObject { private func updateThirdPartyRatesIfDue() { guard self.thirdPartyRatesTask == nil else { return } self.thirdPartyRatesTask = Task(priority: .utility) { [weak self, updateThirdPartyRates] in + guard !Task.isCancelled else { return } let changed = await updateThirdPartyRates() - await MainActor.run { - guard let self else { return } - self.thirdPartyRatesTask = nil - if changed { self.refreshCostsAfterPricingChange() } - } + guard let self, !Task.isCancelled else { return } + self.thirdPartyRatesTask = nil + if changed { self.refreshCostsAfterPricingChange() } } } /// Retries only the selected provider's local usage scan. This has no quota cooldown and /// shares the scan task with automatic and pricing-triggered work, so repeated clicks coalesce. func retryLocalUsage() { - self.refreshCosts(for: self.settings.menuBarProvider) + self.refreshCosts(for: UsageTab(provider: self.settings.menuBarProvider)) } /// Scans every provider's local usage, for the usage window, which reports all sources at /// once. Each scan shares its provider's task with every other path, so calls coalesce. func refreshAllLocalUsage() { - for provider in Provider.allCases { self.refreshCosts(for: provider) } - self.refreshPiUsage() + for tab in UsageTab.allCases { self.refreshCosts(for: tab) } } /// Whether a user click on the Refresh row would start a refresh now. diff --git a/Sources/QuotaBarApp/UsageUnitSwitch.swift b/Sources/QuotaBarApp/UsageUnitSwitch.swift index 07a5242..ee9aeba 100644 --- a/Sources/QuotaBarApp/UsageUnitSwitch.swift +++ b/Sources/QuotaBarApp/UsageUnitSwitch.swift @@ -19,16 +19,9 @@ struct UsageUnitSwitch: View { options: Self.modes, selection: self.selection, style: Self.style, - emphasisAnimation: { - CostChartHoverMotion.systemReduceMotion ? nil : .easeOut(duration: 0.12) - }, - edgeCurves: { - TabSwitchMotion.edgeCurves(movingRight: $0, reduceMotion: CostChartHoverMotion.systemReduceMotion) - }, keyboardSelection: .inheritTransaction, shortcut: { _ in nil }, accessibilityLabel: Self.title, - selectedTraits: .isSelected, onSelect: self.onSelect ) { mode, isSelected, isEmphasized, emphasisAnimation in Text(Self.title(of: mode)) diff --git a/Sources/QuotaBarCore/Claude/ClaudeProvider.swift b/Sources/QuotaBarCore/Claude/ClaudeProvider.swift index 430bc5c..d6b1665 100644 --- a/Sources/QuotaBarCore/Claude/ClaudeProvider.swift +++ b/Sources/QuotaBarCore/Claude/ClaudeProvider.swift @@ -56,24 +56,8 @@ public enum ClaudeProvider { } do { - let response = try await ClaudeUsageFetcher.fetchUsage( - accessToken: credentials.accessToken, - transport: transport - ) - await gate.recordSuccess(.claude) - return .loaded(Self.snapshot(from: response, credentials: credentials)) - } catch let error as ClaudeFetchError { - if case let .rateLimited(retryAfter) = error { - await gate.recordRateLimit(.claude, retryAfter: retryAfter) - let until = await gate.blocked(.claude) ?? Date().addingTimeInterval(5 * 60) - return .rateLimited( - reason: ClaudeFetchError.rateLimited(until).localizedDescription, - retryAfter: until - ) - } - guard case .unauthorized = error else { - return .failed(error.localizedDescription) - } + return try await Self.fetchUsage(credentials: credentials, transport: transport, gate: gate) + } catch ClaudeFetchError.unauthorized { return await Self.recoverAfterUnauthorized( originalCredentials: credentials, interaction: interaction, @@ -157,12 +141,11 @@ public enum ClaudeProvider { ) } - private static func retryUsage( + private static func fetchUsage( credentials: ClaudeCredentials, transport: any HTTPTransport, gate: UsageRateLimitGate - ) async -> ProviderState { - // This is the one and only retry. + ) async throws -> ProviderState { do { let response = try await ClaudeUsageFetcher.fetchUsage( accessToken: credentials.accessToken, @@ -170,20 +153,23 @@ public enum ClaudeProvider { ) await gate.recordSuccess(.claude) return .loaded(Self.snapshot(from: response, credentials: credentials)) - } catch let error as ClaudeFetchError { - if case let .rateLimited(retryAfter) = error { - await gate.recordRateLimit(.claude, retryAfter: retryAfter) - let until = await gate.blocked(.claude) ?? Date().addingTimeInterval(5 * 60) - return .rateLimited( - reason: ClaudeFetchError.rateLimited(until).localizedDescription, - retryAfter: until - ) - } - if case .unauthorized = error { - await gate.recordRejected(.claude, token: credentials.accessToken) - return .failed("Claude credential recovery produced a token the usage API rejected.") - } - return .failed(error.localizedDescription) + } catch let ClaudeFetchError.rateLimited(retryAfter) { + let deadline = await gate.applyRateLimit(.claude, retryAfter: retryAfter) + return .rateLimited(reason: ClaudeFetchError.rateLimited(deadline).localizedDescription, retryAfter: deadline) + } + } + + private static func retryUsage( + credentials: ClaudeCredentials, + transport: any HTTPTransport, + gate: UsageRateLimitGate + ) async -> ProviderState { + // This is the one and only retry. + do { + return try await Self.fetchUsage(credentials: credentials, transport: transport, gate: gate) + } catch ClaudeFetchError.unauthorized { + await gate.recordRejected(.claude, token: credentials.accessToken) + return .failed("Claude credential recovery produced a token the usage API rejected.") } catch { return .failed(error.localizedDescription) } diff --git a/Sources/QuotaBarCore/Codex/CodexProvider.swift b/Sources/QuotaBarCore/Codex/CodexProvider.swift index 1a6c37d..1a0680e 100644 --- a/Sources/QuotaBarCore/Codex/CodexProvider.swift +++ b/Sources/QuotaBarCore/Codex/CodexProvider.swift @@ -13,11 +13,7 @@ public enum CodexProvider { credentialLoader: CodexCredentialLoader? = nil ) async -> ProviderState { if let until = await gate.blocked(.codex) { - return .rateLimited( - reason: "Codex usage API rate-limited. Try again after " - + until.formatted(date: .omitted, time: .shortened) + ".", - retryAfter: until - ) + return Self.rateLimited(until: until) } let session: CodexCredentialSession @@ -46,51 +42,42 @@ public enum CodexProvider { } } - do { - let response = try await CodexUsageFetcher.fetchUsage( + func fetchUsage(_ credentials: CodexCredentials) async throws -> CodexUsageResponse { + try await CodexUsageFetcher.fetchUsage( accessToken: credentials.accessToken, accountId: credentials.accountId, env: env, transport: transport ) - await gate.recordSuccess(.codex) - return .loaded(Self.snapshot(from: response)) - } catch let CodexFetchError.rateLimited(retryAfter) { - await gate.recordRateLimit(.codex, retryAfter: retryAfter) - let until = await gate.blocked(.codex) ?? Date().addingTimeInterval(5 * 60) - return .rateLimited( - reason: "Codex usage API rate-limited. Try again after " - + until.formatted(date: .omitted, time: .shortened) + ".", - retryAfter: until - ) - } catch CodexFetchError.unauthorized where !credentials.refreshToken.isEmpty { - // The stored token was stale after all — refresh once, then retry. + } + + do { + let response: CodexUsageResponse do { + response = try await fetchUsage(credentials) + } catch CodexFetchError.unauthorized where !credentials.refreshToken.isEmpty { + // Retry once with the refreshed token. Both attempts use the same 429 policy. let refreshed = try await session.refresh(credentials, transport: transport) - let response = try await CodexUsageFetcher.fetchUsage( - accessToken: refreshed.accessToken, - accountId: refreshed.accountId, - env: env, - transport: transport - ) - await gate.recordSuccess(.codex) - return .loaded(Self.snapshot(from: response)) - } catch let CodexFetchError.rateLimited(retryAfter) { - await gate.recordRateLimit(.codex, retryAfter: retryAfter) - let until = await gate.blocked(.codex) ?? Date().addingTimeInterval(5 * 60) - return .rateLimited( - reason: "Codex usage API rate-limited. Try again after " - + until.formatted(date: .omitted, time: .shortened) + ".", - retryAfter: until - ) - } catch { - return .failed(error.localizedDescription) + response = try await fetchUsage(refreshed) } + await gate.recordSuccess(.codex) + return .loaded(Self.snapshot(from: response)) + } catch let CodexFetchError.rateLimited(retryAfter) { + let deadline = await gate.applyRateLimit(.codex, retryAfter: retryAfter) + return Self.rateLimited(until: deadline) } catch { return .failed(error.localizedDescription) } } + private static func rateLimited(until: Date) -> ProviderState { + .rateLimited( + reason: "Codex usage API rate-limited. Try again after " + + until.formatted(date: .omitted, time: .shortened) + ".", + retryAfter: until + ) + } + public static func snapshot(from response: CodexUsageResponse, now: Date = Date()) -> UsageSnapshot { let primary = response.rateLimit?.primaryWindow?.window let secondary = response.rateLimit?.secondaryWindow?.window diff --git a/Sources/QuotaBarCore/Codex/CodexUsageFetcher.swift b/Sources/QuotaBarCore/Codex/CodexUsageFetcher.swift index 7831fdb..2e6425c 100644 --- a/Sources/QuotaBarCore/Codex/CodexUsageFetcher.swift +++ b/Sources/QuotaBarCore/Codex/CodexUsageFetcher.swift @@ -168,8 +168,6 @@ public enum CodexUsageFetcher { throw CodexFetchError.unauthorized case 429: throw CodexFetchError.rateLimited(HTTPRetryAfter.date(from: response)) - case 403: - throw CodexFetchError.serverError(403, String(data: data, encoding: .utf8)) default: throw CodexFetchError.serverError(response.statusCode, String(data: data, encoding: .utf8)) } @@ -204,10 +202,8 @@ public enum CodexUsageFetcher { private static func parseBaseURL(from contents: String) -> String? { for rawLine in contents.split(whereSeparator: \.isNewline) { - let line = rawLine.split(separator: "#", maxSplits: 1, omittingEmptySubsequences: true).first - let trimmed = line?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - guard !trimmed.isEmpty else { continue } - let parts = trimmed.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: true) + let line = rawLine.prefix { $0 != "#" } + let parts = line.split(separator: "=", maxSplits: 1) guard parts.count == 2, parts[0].trimmingCharacters(in: .whitespacesAndNewlines) == "chatgpt_base_url" else { continue } var value = parts[1].trimmingCharacters(in: .whitespacesAndNewlines) diff --git a/Sources/QuotaBarCore/Cost/CostCache.swift b/Sources/QuotaBarCore/Cost/CostCache.swift index d5ca4c2..357ea7b 100644 --- a/Sources/QuotaBarCore/Cost/CostCache.swift +++ b/Sources/QuotaBarCore/Cost/CostCache.swift @@ -544,11 +544,10 @@ final class CostCache { day: String, model: String, longContext: Bool, - totals: TokenTotals, contextInput: Int?, - request: ObservedRequest? = nil + request: ObservedRequest ) throws { - if let request, let entryID = request.entryID, request.upstreamProvider == "openai-codex" { + if let entryID = request.entryID, request.upstreamProvider == "openai-codex" { // A legacy row has no timestamp/raw model. Adopt it once, on the first compatible // replay, retaining its historical day. Later short-ID collisions get their own keys. let promote = try self.reusable(""" @@ -600,13 +599,13 @@ final class CostCache { sqlite3_bind_text(stmt, 3, day, -1, sqliteTransient) sqlite3_bind_text(stmt, 4, model, -1, sqliteTransient) sqlite3_bind_int64(stmt, 5, longContext ? 1 : 0) - self.bindUsage(stmt, from: 6, totals: totals) + self.bindUsage(stmt, from: 6, totals: request.tokens) if let contextInput { sqlite3_bind_int64(stmt, 11, Int64(contextInput)) } - if let value = request?.upstreamProvider { sqlite3_bind_text(stmt, 12, value, -1, sqliteTransient) } - if let value = request?.model { sqlite3_bind_text(stmt, 13, value, -1, sqliteTransient) } - if let value = request?.loggedCostUSD { sqlite3_bind_double(stmt, 14, value) } - if let value = request?.totalFromProvider { sqlite3_bind_int(stmt, 15, value ? 1 : 0) } - if let value = request?.entryID { sqlite3_bind_text(stmt, 16, value, -1, sqliteTransient) } + if let value = request.upstreamProvider { sqlite3_bind_text(stmt, 12, value, -1, sqliteTransient) } + if let value = request.model { sqlite3_bind_text(stmt, 13, value, -1, sqliteTransient) } + if let value = request.loggedCostUSD { sqlite3_bind_double(stmt, 14, value) } + if let value = request.totalFromProvider { sqlite3_bind_int(stmt, 15, value ? 1 : 0) } + if let value = request.entryID { sqlite3_bind_text(stmt, 16, value, -1, sqliteTransient) } try self.step(stmt) } diff --git a/Sources/QuotaBarCore/Cost/ExternalAgentScan.swift b/Sources/QuotaBarCore/Cost/ExternalAgentScan.swift index 7e36c43..8fd4248 100644 --- a/Sources/QuotaBarCore/Cost/ExternalAgentScan.swift +++ b/Sources/QuotaBarCore/Cost/ExternalAgentScan.swift @@ -1,9 +1,8 @@ import Darwin import Foundation -/// The outcome of scanning one Usage source. Any source can fail; OpenCode and Pi Agent also ride -/// on the user's OpenAI account, so they can be left out for an account that is not Codex's. Only -/// the name in the sentence differs between sources. +/// The outcome of scanning one usage source. OpenCode additionally checks that its +/// OpenAI OAuth account matches Codex before including newly observed requests. public enum ExternalAgentScanStatus: Sendable, Equatable { case idle case accountMismatch @@ -20,111 +19,6 @@ public enum ExternalAgentScanStatus: Sendable, Equatable { } } -/// Whether one agent's usage counts toward the Codex total. -enum ExternalAgentEligibility { - case eligible - case ineligible(ExternalAgentScanStatus) - case indeterminate - - /// An agent is included only when it is signed in with OAuth to the same OpenAI account Codex - /// uses. An account either side cannot name is indeterminate rather than a mismatch, so a - /// half-configured install neither drops usage silently nor accuses the user of a mismatch. - static func matchingCodexAccount( - type: String?, - accountId: String?, - codexAccountId: String? - ) -> Self { - guard type?.lowercased() == "oauth" else { return .ineligible(.nonOAuth) } - guard let left = accountId?.trimmingCharacters(in: .whitespacesAndNewlines), !left.isEmpty, - let right = codexAccountId, !right.isEmpty else { - return .indeterminate - } - return left == right ? .eligible : .ineligible(.accountMismatch) - } - - /// Reads the sign-in stored under `entry` in an agent's `auth.json` (an object with `type` - /// and `accountId`) and checks it against the Codex account. A file either side cannot read - /// or decode is indeterminate. - static func signIn(authFile: URL, entry: String, env: [String: String]) -> Self { - do { - let data = try Data(contentsOf: authFile) - let codexAccountId = try CodexCredentialsStore.accountId(env: env) - let decoder = JSONDecoder() - decoder.userInfo[AgentAuthFile.entryKey] = entry - guard let signIn = try decoder.decode(AgentAuthFile.self, from: data).signIn else { return .indeterminate } - return .matchingCodexAccount( - type: signIn.type, - accountId: signIn.accountId, - codexAccountId: codexAccountId - ) - } catch { - return .indeterminate - } - } - - /// How an agent riding on the Codex account is surveyed: absent until `marker` exists, failed - /// while its sign-in cannot be checked, otherwise present with the batch's `included` flag and - /// status. The sign-in is checked before `stamp` examines the agent's files, and a - /// `SnapshotReadError` thrown there fails the survey for its reason. - static func survey( - installedAt marker: URL, - authFile: URL, - entry: String, - env: [String: String], - stamp: () throws -> Stamp? - ) -> SnapshotSurvey { - guard FileManager.default.fileExists(atPath: marker.path) else { return .absent } - guard let (included, status) = Self.signIn(authFile: authFile, entry: entry, env: env).resolved else { - return .failed(.auth) - } - do { - return .present(stamp: try stamp(), included: included, status: status) - } catch { - return .failed((error as? SnapshotReadError)?.failure ?? .sessions) - } - } - - /// Whether this agent's rows count, and what the settings pane should say about it. An - /// indeterminate account answers neither question, so it returns nil and the caller reports - /// the scan as failed rather than silently dropping or silently counting the usage. - var resolved: (included: Bool, status: ExternalAgentScanStatus)? { - switch self { - case .eligible: (included: true, status: .idle) - case let .ineligible(reason): (included: false, status: reason) - case .indeterminate: nil - } - } -} - -/// An agent's `auth.json`, of which only the one entry naming its OpenAI sign-in is decoded, so -/// other providers' entries in any shape cannot fail the check. -private struct AgentAuthFile: Decodable { - static let entryKey = CodingUserInfoKey(rawValue: "entry")! - - struct SignIn: Decodable { - let type: String? - let accountId: String? - } - - let signIn: SignIn? - - init(from decoder: Decoder) throws { - guard let entry = decoder.userInfo[Self.entryKey] as? String, - let key = EntryKey(stringValue: entry) else { - self.signIn = nil - return - } - self.signIn = try decoder.container(keyedBy: EntryKey.self).decodeIfPresent(SignIn.self, forKey: key) - } - - private struct EntryKey: CodingKey { - let stringValue: String - var intValue: Int? { nil } - init?(stringValue: String) { self.stringValue = stringValue } - init?(intValue: Int) { nil } - } -} - /// Identity of one file at the moment it was examined: which file it is and when it last /// changed. A snapshot source whose files keep their stamps is not read again. struct FileStamp: Hashable { diff --git a/Sources/QuotaBarCore/Cost/LogFileScanner.swift b/Sources/QuotaBarCore/Cost/LogFileScanner.swift index d525383..4f08b70 100644 --- a/Sources/QuotaBarCore/Cost/LogFileScanner.swift +++ b/Sources/QuotaBarCore/Cost/LogFileScanner.swift @@ -82,8 +82,8 @@ package enum LogFileScanner { /// absolute byte offset and is never read past, even when it lands inside a line. The buffer /// passed to `handle` is valid only for that call and must not escape it. /// - /// Only lines `isWanted` accepts reach `handle`. A line longer than 64KB is first judged by - /// that prefix alone, and skipped to its newline unbuffered if rejected, so `isWanted` may + /// Only lines `isWanted` accepts reach `handle`. When an incomplete line spans reads and its + /// prefix reaches 64KB, a rejected prefix lets the scanner skip to its newline. `isWanted` may /// reject a prefix only when it would reject every line starting with it. Some logs carry /// irrelevant lines of tens of megabytes. package static func readLines( diff --git a/Sources/QuotaBarCore/Cost/OpenCodeAdapter.swift b/Sources/QuotaBarCore/Cost/OpenCodeAdapter.swift index fc15436..0af9776 100644 --- a/Sources/QuotaBarCore/Cost/OpenCodeAdapter.swift +++ b/Sources/QuotaBarCore/Cost/OpenCodeAdapter.swift @@ -28,17 +28,33 @@ package struct OpenCodeAdapter: SnapshotAdapter { private var databaseURL: URL { self.dataDirectory.appendingPathComponent("opencode.db") } package func survey() -> SnapshotSurvey { - let survey = ExternalAgentEligibility.survey( - installedAt: self.databaseURL, - authFile: self.dataDirectory.appendingPathComponent("auth.json"), - entry: "openai", - env: self.env, - stamp: self.stamp - ) - // OpenCode can remain installed after sign-out. Keep recorded history quietly and - // recheck its sign-in on the next refresh so recording resumes automatically. - if case .failed(.auth) = survey { return .skipped } - return survey + guard FileManager.default.fileExists(atPath: self.databaseURL.path) else { return .absent } + guard let status = self.accountStatus() else { return .skipped } + return .present(stamp: self.stamp(), included: status == .idle, status: status) + } + + private struct AuthFile: Decodable { + struct SignIn: Decodable { + let type: String? + let accountId: String? + } + + let openai: SignIn? + } + + /// A missing or unreadable sign-in pauses recording until it can be checked again. + private func accountStatus() -> ExternalAgentScanStatus? { + do { + let data = try Data(contentsOf: self.dataDirectory.appendingPathComponent("auth.json")) + let codexAccount = try CodexCredentialsStore.accountId(env: self.env) + guard let signIn = try JSONDecoder().decode(AuthFile.self, from: data).openai else { return nil } + guard signIn.type?.lowercased() == "oauth" else { return .nonOAuth } + guard let account = signIn.accountId?.trimmingCharacters(in: .whitespacesAndNewlines), + !account.isEmpty, let codexAccount, !codexAccount.isEmpty else { return nil } + return account == codexAccount ? .idle : .accountMismatch + } catch { + return nil + } } package func requests() throws -> [ObservedRequest] { diff --git a/Sources/QuotaBarCore/Cost/PricedUsage.swift b/Sources/QuotaBarCore/Cost/PricedUsage.swift index 443a8a3..09c4416 100644 --- a/Sources/QuotaBarCore/Cost/PricedUsage.swift +++ b/Sources/QuotaBarCore/Cost/PricedUsage.swift @@ -44,14 +44,19 @@ package struct PricedUsage: Equatable { upstreamProvider: row.tier.upstreamProvider, pricingProvider: provider ) - let hasRate = rateCard.rates(for: key.model, provider: provider, day: key.day, fast: key.isFast) != nil - let fallback = row.tokens.total > 0 && !hasRate && key.source == .piAgent + let rates = rateCard.rates(for: key.model, provider: provider, day: key.day, fast: key.isFast) + let total = row.tokens.total + let fallback = total > 0 && rates == nil && key.source == .piAgent && (row.loggedCostUSD.map { $0.isFinite && $0 > 0 } ?? false) - let cost = hasRate && row.tokens.total > 0 - ? rateCard.cost(of: row.tokens, model: key.model, provider: provider, day: key.day, - fast: key.isFast, longContext: key.longContext) - : (fallback ? row.loggedCostUSD : nil) - let unpriced = cost == nil ? row.tokens.total : (fallback ? row.tokens.total - row.loggedCostTokens : 0) + let cost: Double? + if total == 0 { + cost = nil + } else if fallback { + cost = row.loggedCostUSD + } else { + cost = rates?.cost(for: row.tokens, longContext: key.longContext) + } + let unpriced = cost == nil ? total : (fallback ? total - row.loggedCostTokens : 0) let previous = grouped[key] let combinedCost: Double? = cost == nil && previous?.cost == nil ? nil : (cost ?? 0) + (previous?.cost ?? 0) guard combinedCost?.isFinite ?? true else { diff --git a/Sources/QuotaBarCore/Cost/UsageRecorder.swift b/Sources/QuotaBarCore/Cost/UsageRecorder.swift index dc6d0a3..48389a5 100644 --- a/Sources/QuotaBarCore/Cost/UsageRecorder.swift +++ b/Sources/QuotaBarCore/Cost/UsageRecorder.swift @@ -34,8 +34,6 @@ package struct ObservedRequest: Equatable { /// Why a Usage source could not be recorded this pass. Its raw value is the reason its scan /// status reports. package enum ScanFailure: String { - /// The source's sign-in could not be checked against the Codex account. - case auth /// The source's session files could not be listed or read. case sessions /// A database could not be opened or written. @@ -222,7 +220,6 @@ private struct RecordedRow { let longContext: Bool let isFast: Bool let tokens: TokenTotals - var piRequest: ObservedRequest? = nil // The one-hour cache-write count is already part of cacheWrite; output never sets the tier. var contextInput: Int? { @@ -289,7 +286,9 @@ extension UsageRecorder { } /// Merges a request from a snapshot. `included` is written only when the row is first seen. - private func merge(_ row: RecordedRow, from source: SnapshotSource, included: Bool) throws { + private func merge(_ request: ObservedRequest, from source: SnapshotSource, included: Bool, rateCard: RateCard) throws { + let provider = source.usageSource.pricingProvider(model: request.model ?? "", upstreamProvider: request.upstreamProvider) + let row = Self.row(for: request, provider: provider, rateCard: rateCard) switch source { case .openCode: // One row per part, rewritten only when its content changes. `included` is written @@ -312,9 +311,8 @@ extension UsageRecorder { day: row.day, model: row.model, longContext: row.longContext, - totals: row.tokens, contextInput: row.contextInput, - request: row.piRequest + request: request ) } } @@ -372,8 +370,8 @@ package protocol AppendedLogAdapter { var source: AppendedLogSource { get } /// Every log file to consider this pass. func logFiles(onError: @escaping (Error) -> Void) -> [URL] - /// A byte-level prefilter run before a line is parsed. It sees at most a long line's first - /// 64KB, so it may reject a prefix only when it would reject every line starting with it. + /// A byte-level prefilter run before a line is parsed. It can see an incomplete prefix of + /// a long line, so it may reject a prefix only when it would reject every line starting with it. func isWanted(_ line: UnsafeRawBufferPointer) -> Bool /// A parser positioned at `offset` of `file`. `savedState` is what a parser's `savedState` /// returned when the cursor was last saved at that offset; it is nil when the file is read from @@ -426,8 +424,9 @@ extension UsageRecorder { let versions = Dictionary(uniqueKeysWithValues: try self.cache.remoteVersions().map { ($0.path, $0) }) var touched = 0 for url in files { - if let host = RemoteLogMirror.host(ofLog: url.path), self.busyRemoteHosts.contains(host) { continue } let filePath = url.path + let mirrorHost = RemoteLogMirror.host(ofLog: filePath) + if let mirrorHost, self.busyRemoteHosts.contains(mirrorHost) { continue } let sessionID = adapter.sessionID(path: filePath) // Rows and cursor stay under the path a session was first stored at, so a moved or // copied log continues that session instead of counting it again. @@ -435,7 +434,8 @@ extension UsageRecorder { if let host = RemoteLogMirror.host(ofLog: path), self.busyRemoteHosts.contains(host) { continue } let previous = self.cache.cursor(forPath: path) let version = versions[path] - let isRemote = RemoteLogMirror.host(ofLog: filePath) != nil + let isRemote = mirrorHost != nil + let verifyMirror = isRemote || version != nil if path != filePath, sessionID != nil, let previous, let size = try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize, Int64(size) < previous.size { continue } @@ -477,11 +477,9 @@ extension UsageRecorder { } continue } - let mirrorHost = RemoteLogMirror.host(ofLog: filePath) - try self.cache.beginTransaction() do { - let beforeDigest = isRemote || version != nil + let beforeDigest = verifyMirror ? try LogFileScanner.prefixDigest(of: url, byteCount: plan.cursor.size) : nil if plan.requiresFullReparse, source.dropsRowsOnRewrite { try self.cache.forget(path: path) @@ -497,12 +495,13 @@ extension UsageRecorder { of: url, from: plan.cursor.offset, upTo: plan.cursor.size, - where: { isRemote || version != nil || adapter.isWanted($0) } + where: { verifyMirror || adapter.isWanted($0) } ) { line in guard failure == nil else { return } - if isRemote || version != nil, - (try? JSONSerialization.jsonObject(with: Data(line))) == nil { validJSON = false } - guard adapter.isWanted(line) else { return } + if verifyMirror { + if (try? JSONSerialization.jsonObject(with: Data(line))) == nil { validJSON = false } + guard adapter.isWanted(line) else { return } + } do { guard let request = try parser.request(in: line) else { return } try self.merge( @@ -722,10 +721,7 @@ extension UsageRecorder { try self.cache.beginTransaction() do { for request in requests { - let provider = source.usageSource.pricingProvider(model: request.model ?? "", upstreamProvider: request.upstreamProvider) - var row = Self.row(for: request, provider: provider, rateCard: rateCard) - if source == .piAgent { row.piRequest = request } - try self.merge(row, from: source, included: included) + try self.merge(request, from: source, included: included, rateCard: rateCard) } try self.cache.commit() } catch { diff --git a/Sources/QuotaBarCore/DailyUsageRhythm.swift b/Sources/QuotaBarCore/DailyUsageRhythm.swift index 4bea174..21f2506 100644 --- a/Sources/QuotaBarCore/DailyUsageRhythm.swift +++ b/Sources/QuotaBarCore/DailyUsageRhythm.swift @@ -44,24 +44,22 @@ public struct DailyUsageRhythm: Sendable, Equatable { from records: [UsageHistoryRecord], timeZone: TimeZone = .current ) -> DailyUsageRhythm? { + let windows = Dictionary(grouping: records, by: \.windowKey) + return Self.learn(windows: windows.values, timeZone: timeZone) + } + + static func learn(windows: some Sequence<[UsageHistoryRecord]>, timeZone: TimeZone) -> DailyUsageRhythm? { var usage = Array(repeating: 0.0, count: 24) var exposure = Array(repeating: 0.0, count: 24) - struct WindowKey: Hashable { - let resetsAt: Date - let windowMinutes: Int - } - let windows = Dictionary(grouping: records) { - WindowKey(resetsAt: $0.resetsAt, windowMinutes: $0.windowMinutes) - } - for samples in windows.values { + for samples in windows { let ordered = samples.sorted { $0.sampledAt < $1.sampledAt } for (earlier, later) in zip(ordered, ordered.dropFirst()) { let gap = later.sampledAt.timeIntervalSince(earlier.sampledAt) guard gap > 0 else { continue } let rise = max(0, later.usedPercent - earlier.usedPercent) if rise > 0, gap > Self.maximumRisingGap { continue } - Self.forEachHour(from: earlier.sampledAt, to: later.sampledAt, timeZone: timeZone) { hour, seconds in + Self.forEachHourSegment(from: earlier.sampledAt, to: later.sampledAt, timeZone: timeZone) { hour, seconds, _ in exposure[hour] += seconds // Spread evenly: the samples cannot say when within the gap it was used. usage[hour] += rise * seconds / gap @@ -88,9 +86,8 @@ public struct DailyUsageRhythm: Sendable, Equatable { /// Clock time between two dates, weighted by how active each hour usually is. public func activeSeconds(from start: Date, to end: Date) -> TimeInterval { - guard end > start else { return 0 } var total = 0.0 - Self.forEachHour(from: start, to: end, timeZone: self.timeZone) { hour, seconds in + Self.forEachHourSegment(from: start, to: end, timeZone: self.timeZone) { hour, seconds, _ in total += self.hourlyWeights[hour] * seconds } return total @@ -117,17 +114,6 @@ public struct DailyUsageRhythm: Sendable, Equatable { // MARK: - Hour segments - private static func forEachHour( - from start: Date, - to end: Date, - timeZone: TimeZone, - _ body: (_ hour: Int, _ seconds: TimeInterval) -> Void - ) { - Self.forEachHourSegment(from: start, to: end, timeZone: timeZone) { hour, seconds, _ in - body(hour, seconds) - } - } - /// Splits [start, end) at local hour boundaries and reports each piece's hour of day. private static func forEachHourSegment( from start: Date, diff --git a/Sources/QuotaBarCore/RateLimitGate.swift b/Sources/QuotaBarCore/RateLimitGate.swift index aa0be35..749cb60 100644 --- a/Sources/QuotaBarCore/RateLimitGate.swift +++ b/Sources/QuotaBarCore/RateLimitGate.swift @@ -32,9 +32,16 @@ public actor UsageRateLimitGate { } public func recordRateLimit(_ provider: Provider, retryAfter: Date?, now: Date = Date()) { + _ = self.applyRateLimit(provider, retryAfter: retryAfter, now: now) + } + + /// Return the deadline from the same actor turn that installs it. + func applyRateLimit(_ provider: Provider, retryAfter: Date?, now: Date = Date()) -> Date { let requested = retryAfter?.timeIntervalSince(now) ?? Self.defaultBackoff let clamped = min(Self.maxBackoff, max(Self.defaultBackoff, requested)) - self.blockedUntil[provider] = now.addingTimeInterval(clamped) + let deadline = now.addingTimeInterval(clamped) + self.blockedUntil[provider] = deadline + return deadline } public func recordSuccess(_ provider: Provider) { diff --git a/Sources/QuotaBarCore/Resources/UsageReport/report.css b/Sources/QuotaBarCore/Resources/UsageReport/report.css index bf39f59..38dcc7c 100644 --- a/Sources/QuotaBarCore/Resources/UsageReport/report.css +++ b/Sources/QuotaBarCore/Resources/UsageReport/report.css @@ -3,11 +3,9 @@ /* Matches the settings window and menu card: the system window color, label tiers, and the provider hues the app uses everywhere else. */ --background:#f6f6f6;--foreground:#1d1d1f;--muted:rgb(0 0 0/4%);--muted-foreground:#6e6e73; - --border:rgb(0 0 0/10%);--input:rgb(0 0 0/8%);--icon-muted:#8e8e93;--warning:#b45309; - --surface:#fff;--surface-border:rgb(0 0 0/7%); + --border:rgb(0 0 0/10%);--input:rgb(0 0 0/8%); --glass:color-mix(in srgb,var(--background) 85%,transparent); --shadow-lg:0 8px 24px -6px rgb(0 0 0/18%),0 0 0 .5px rgb(0 0 0/8%); - --radius:8px; --codex:#3f97a4;--claude:#c4724f; /* Token categories use distinct, quiet hues; speed remains a neutral comparison. */ --type-1:#3b4654;--type-2:#9aa7b4;--type-3:#b08a2e;--type-4:#5c6fb5; @@ -17,10 +15,9 @@ color-scheme:light; } @media (prefers-color-scheme:dark){ - :root:not([data-theme=light]){ + :root{ --background:#1e1e1e;--foreground:#f2f2f2;--muted:rgb(255 255 255/5%);--muted-foreground:#9a9a9f; - --border:rgb(255 255 255/10%);--input:rgb(255 255 255/9%);--icon-muted:#8a8a8e;--warning:#f59e0b; - --surface:rgb(255 255 255/4%);--surface-border:rgb(255 255 255/7%); + --border:rgb(255 255 255/10%);--input:rgb(255 255 255/9%); --shadow-lg:0 8px 24px -6px rgb(0 0 0/50%),0 0 0 .5px rgb(255 255 255/10%); --codex:#49a3b0;--claude:#cc7c5e; --type-1:#cfd6de;--type-2:#6f7b88;--type-3:#cfae5a;--type-4:#8fa0e0; @@ -29,17 +26,6 @@ --mark-codex:#f2f2f2;--mark-opencode:#f1ecec;--mark-opencode-inner:#4b4646;--mark-pi:#f5f5f5; } } -:root[data-theme=dark]{ - --background:#1e1e1e;--foreground:#f2f2f2;--muted:rgb(255 255 255/5%);--muted-foreground:#9a9a9f; - --border:rgb(255 255 255/10%);--input:rgb(255 255 255/9%);--icon-muted:#8a8a8e;--warning:#f59e0b; - --surface:rgb(255 255 255/4%);--surface-border:rgb(255 255 255/7%); - --shadow-lg:0 8px 24px -6px rgb(0 0 0/50%),0 0 0 .5px rgb(255 255 255/10%); - --codex:#49a3b0;--claude:#cc7c5e; - --type-1:#cfd6de;--type-2:#6f7b88;--type-3:#cfae5a;--type-4:#8fa0e0; - --speed-standard:#a2adb8;--speed-fast:#71808d; - color-scheme:dark; - --mark-codex:#f2f2f2;--mark-opencode:#f1ecec;--mark-opencode-inner:#4b4646;--mark-pi:#f5f5f5; -} *{box-sizing:border-box;margin:0;padding:0} html{background:var(--background)} body{background:var(--background);color:var(--foreground);font-family:var(--font-sans);font-size:13px;line-height:18px; @@ -70,16 +56,14 @@ button:focus-visible,[tabindex]:focus-visible{outline:2px solid var(--foreground .language-toggle button[aria-pressed=true]{color:var(--foreground);font-weight:500} .segmented button:hover:not([aria-pressed=true]){background:color-mix(in srgb,var(--foreground) 5%,transparent)} .segmented button[aria-pressed=true]{background:#fff;font-weight:500;box-shadow:0 .5px 1.5px rgb(0 0 0/22%),0 0 0 .5px rgb(0 0 0/6%)} -@media (prefers-color-scheme:dark){:root:not([data-theme=light]) .segmented button[aria-pressed=true]{background:rgb(255 255 255/22%);box-shadow:0 .5px 1px rgb(0 0 0/30%)}} -:root[data-theme=dark] .segmented button[aria-pressed=true]{background:rgb(255 255 255/22%);box-shadow:0 .5px 1px rgb(0 0 0/30%)} +@media (prefers-color-scheme:dark){.segmented button[aria-pressed=true]{background:rgb(255 255 255/22%);box-shadow:0 .5px 1px rgb(0 0 0/30%)}} .range-inputs{display:flex;align-items:center;gap:6px} .range-inputs input{height:28px;padding:0 8px;border:1px solid var(--input);border-radius:8px;background:var(--background); color:var(--foreground);font:inherit;font-size:12px;line-height:16px;font-variant-numeric:tabular-nums} .range-inputs input:focus-visible{outline:2px solid var(--foreground);outline-offset:1px} .range-dash{color:var(--muted-foreground);font-size:12px} -@media (prefers-color-scheme:dark){:root:not([data-theme=light]) .range-inputs input{background:rgb(255 255 255/4%)}} -:root[data-theme=dark] .range-inputs input{background:rgb(255 255 255/4%)} +@media (prefers-color-scheme:dark){.range-inputs input{background:rgb(255 255 255/4%)}} /* Page */ .page{max-width:64rem;margin:0 auto;padding:28px 28px 48px;display:flex;flex-direction:column;gap:32px} @@ -108,7 +92,6 @@ button:focus-visible,[tabindex]:focus-visible{outline:2px solid var(--foreground .mark svg{width:100%;height:100%;display:block} .provider-label{display:flex;align-items:baseline;gap:6px;min-width:0} .provider-label .label{flex:none;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} -.provider-label .count{flex:0 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px;line-height:16px;color:var(--muted-foreground);font-variant-numeric:tabular-nums} .provider-value{flex:none;font-size:13px;font-weight:600;color:var(--foreground);font-variant-numeric:tabular-nums} .provider-sub{display:flex;justify-content:space-between;gap:12px;font-size:12px;line-height:16px;color:var(--muted-foreground)} .trend{display:flex;flex-direction:column;gap:12px;min-width:0} @@ -169,7 +152,6 @@ button:focus-visible,[tabindex]:focus-visible{outline:2px solid var(--foreground .share-legend i{width:8px;height:8px;border-radius:999px;flex:none} /* Breakdown */ -.breakdown{gap:12px} .breakdown-head{display:flex;align-items:center;justify-content:space-between;gap:12px} .table-scroll{overflow-x:auto} table{width:100%;border-collapse:collapse;font-size:13px;line-height:18px} diff --git a/Sources/QuotaBarCore/Resources/UsageReport/report.html b/Sources/QuotaBarCore/Resources/UsageReport/report.html index 90fadfe..541922c 100644 --- a/Sources/QuotaBarCore/Resources/UsageReport/report.html +++ b/Sources/QuotaBarCore/Resources/UsageReport/report.html @@ -44,7 +44,7 @@

Usage

-
+
diff --git a/Sources/QuotaBarCore/Resources/UsageReport/report.js b/Sources/QuotaBarCore/Resources/UsageReport/report.js index 6a70509..cb0f7ce 100644 --- a/Sources/QuotaBarCore/Resources/UsageReport/report.js +++ b/Sources/QuotaBarCore/Resources/UsageReport/report.js @@ -9,7 +9,7 @@ unpricedInfo:p=>`API estimate excludes ${p} of tokens, which are unpriced.`, ofCost:p=>`${p} of cost`,ofTokens:p=>`${p} of tokens`,tokenCount:v=>`${v} tokens`, dailyCost:'Daily cost',average:'avg',dailyAverage:'Daily average',peakDay:'Peak',dailyTokens:'Daily processed tokens', - processedTokens:'Processed tokens',cachedInput:'Cached input',uncachedInput:'Uncached input',output:'Output',cacheSavings:'Cache savings', + output:'Output',cacheSavings:'Cache savings', costByType:'Cost by type',tokensByType:'Tokens by type',costBySpeed:'Cost by speed', input:'Input',cacheRead:'Cache read',cacheWrite:'Cache write',standard:'Standard',fast:'Fast',premium:'Extra for Fast', savingsDetail:'vs. uncached input rate',weekdays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'], @@ -24,7 +24,7 @@ unpricedInfo:p=>`API 估算未计入 ${p} 的未定价 tokens。`, ofCost:p=>`占费用 ${p}`,ofTokens:p=>`占 tokens ${p}`,tokenCount:v=>`${v} tokens`, dailyCost:'每日费用',average:'日均',dailyAverage:'日均',peakDay:'峰值',dailyTokens:'每日处理的 Tokens', - processedTokens:'处理的 Tokens',cachedInput:'缓存输入',uncachedInput:'未缓存输入',output:'输出',cacheSavings:'缓存节省', + output:'输出',cacheSavings:'缓存节省', costByType:'按类型的费用',tokensByType:'按类型的 tokens',costBySpeed:'按速度的费用', input:'输入',cacheRead:'缓存读取',cacheWrite:'缓存写入',standard:'标准',fast:'快速',premium:'快速额外支出', savingsDetail:'相比未缓存输入价',weekdays:['周日','周一','周二','周三','周四','周五','周六'], @@ -83,15 +83,13 @@ // Saved history, one entry per calendar day. Every figure on the page is summed from the days // inside the selected period, so changing the period needs no new snapshot. - const FIELDS=['input','output','cacheRead','cacheWrite','cacheWrite1h','cost','unpricedTokens','total']; + const FIELDS=['input','output','cacheRead','cacheWrite','cost','unpricedTokens','total']; const COST_FIELDS=['input','output','cacheRead','cacheWrite','cacheSavings','fast','fastPremium']; // The app's live view replaces the snapshot in place, so everything read from it is reassignable. - let report,BY_DAY,FIRST_DAY,LAST_DAY,DEFAULT_PERIOD; - function load(next){ - report=next; + let BY_DAY,FIRST_DAY,LAST_DAY; + function load(report){ BY_DAY=new Map(report.history.map(d=>[d.day,d])); FIRST_DAY=report.history[0]?.day??'';LAST_DAY=report.history.at(-1)?.day??''; - DEFAULT_PERIOD=String(report.days.length)==='7'?'7':'30'; } load(REPORT); const toTime=day=>Date.parse(day+'T00:00:00Z'); @@ -101,7 +99,7 @@ const addInto=(target,row,keys)=>{for(const k of keys)target[k]+=row?.[k]??0;return target;}; function periodRange(){ if(period==='custom'&&range.from&&range.to)return range.from<=range.to?range:{from:range.to,to:range.from}; - return {from:shiftDay(LAST_DAY,1-Number(period==='7'?7:30)),to:LAST_DAY}; + return {from:shiftDay(LAST_DAY,1-(period==='7'?7:30)),to:LAST_DAY}; } let days=[],daySources=[],totals,breakdownCost,recordedDays=0,sourceRows=new Map(),providers=[],models=[]; @@ -117,7 +115,10 @@ breakdownCost=days.reduce((sum,day)=>addInto(sum,day.costBreakdown,COST_FIELDS),zero(COST_FIELDS)); recordedDays=days.filter(d=>d.recorded).length; sourceRows=new Map(); - daySources.forEach(m=>m.forEach((row,id)=>{if(!sourceRows.has(id))sourceRows.set(id,{name:row.name,source:id,...zero(FIELDS)});addInto(sourceRows.get(id),row,FIELDS);})); + daySources.forEach(m=>m.forEach((row,id)=>{ + if(!sourceRows.has(id))sourceRows.set(id,zero(FIELDS)); + addInto(sourceRows.get(id),row,FIELDS); + })); providers=[...sourceRows.keys()].filter(id=>{const r=sourceRows.get(id);return r.total>0||r.cost>0;}) .sort((a,b)=>(ORDER.indexOf(a)+1||99)-(ORDER.indexOf(b)+1||99)); // Keep routing providers separate even when they sell the same model. @@ -319,7 +320,7 @@ const root=document.getElementById('shares');root.replaceChildren(); if(totals.total<=0)return; const c=breakdownCost,label=t(metric==='tokens'?'tokensByType':'costByType'); - const types=['input','cacheRead','cacheWrite','output'].map(key=>({key,label:t(key),color:TYPE_COLORS[key], + const types=Object.keys(TYPE_COLORS).map(key=>({label:t(key),color:TYPE_COLORS[key], value:metric==='tokens'?totals[key]:c[key],other:metric==='tokens'?usd(c[key]):t('tokenCount')(tokens(totals[key]))})).filter(x=>x.value>0); const total=types.reduce((sum,x)=>sum+x.value,0),savings=c.cacheSavings>0; const cells=h('div',{class:'type-cells'+(savings?' with-savings':'')},types.map((x,i)=>h('div',{class:'type-cell','data-cell':i}, @@ -328,7 +329,7 @@ h('span',{class:'type-detail'},`${percent(x.value/total)} · ${x.other}`)))); if(savings)cells.append(h('div',{class:'type-cell cache-savings'},h('span',{class:'type-label'},t('cacheSavings')), h('span',{class:'type-value'},usd(c.cacheSavings)),h('span',{class:'type-detail'},t('savingsDetail')))); - if(types.length||savings)root.append(h('div',{class:'share composition'},h('h2',{class:'heading'},label), + if(types.length||savings)root.append(h('div',{class:'share'},h('h2',{class:'heading'},label), h('div',{class:'share-bar',role:'img','aria-label':`${label}: ${types.map(x=>`${x.label} ${format(x.value)}`).join(', ')}`}, types.map((x,i)=>h('div',{style:`flex:${x.value} 1 0;background:${x.color}`,'data-seg':i,'data-tip':`${x.label} · ${format(x.value)} · ${percent(x.value/total)}`}))),cells)); if(metric==='cost'&&c.fast>0){ @@ -341,11 +342,10 @@ function modelTable(){ const rows=[...models].sort(metric==='tokens'?(a,b)=>b.total-a.total||b.cost-a.cost:(a,b)=>b.cost-a.cost||b.total-a.total); - const peak=Math.max(0,...rows.map(value)); const body=h('tbody'); if(!rows.length)body.append(h('tr',{class:'empty-row'},h('td',{colspan:4},t('noActivity')))); rows.forEach(m=>{ - const id=m.source??providers[0],v=value(m),bar=v>0&&peak>0; + const id=m.source??providers[0]; const share=metric==='tokens'?(totals.total>0?m.total/totals.total:null):(unknownCost(m)||!(totals.cost>0)?null:m.cost/totals.cost); // Rows are already ranked, so the share bar does the work a rank column would. body.append(h('tr',{}, @@ -353,7 +353,7 @@ modelName(m.name),m.upstreamProvider?h('span',{class:'model-upstream'},' · '+m.upstreamProvider):null))), h('td',{class:'share-col'},h('span',{class:'share-cell'}, // The track is the whole window, so the bar's length is the share printed beside it. - h('span',{class:'model-bar','aria-hidden':'true'},bar&&share!=null?h('span',{style:`width:${Math.max(1,share*100)}%;background:${presentation(id).color}`}):null), + h('span',{class:'model-bar','aria-hidden':'true'},share>0?h('span',{style:`width:${Math.max(1,share*100)}%;background:${presentation(id).color}`}):null), h('span',{class:'share-value'},share==null?'':percent(share)))), h('td',{class:'cost'+(metric==='cost'?' active-metric':''),title:usd(m.cost)},unknownCost(m)?t('unpriced'):usd(m.cost)), h('td',{class:metric==='tokens'?'active-metric':null,title:count(m.total)},tokens(m.total)))); @@ -455,6 +455,6 @@ const requested=params.get('period')??stored.period; if(isDay(params.get('from'))&&isDay(params.get('to'))){period='custom';range={from:params.get('from'),to:clampDay(params.get('to'))};} else if(requested==='custom'&&storedRange){period='custom';range=storedRange;} - else period=requested==='7'||requested==='30'?requested:DEFAULT_PERIOD; + else period=requested==='7'||requested==='30'?requested:(REPORT.days.length===7?'7':'30'); render(); })(); diff --git a/Sources/QuotaBarCore/UsageHistoryStore.swift b/Sources/QuotaBarCore/UsageHistoryStore.swift index 22beb6a..bdcb411 100644 --- a/Sources/QuotaBarCore/UsageHistoryStore.swift +++ b/Sources/QuotaBarCore/UsageHistoryStore.swift @@ -13,6 +13,15 @@ public struct UsageHistoryRecord: Codable, Sendable { public let resetsAt: Date public let windowMinutes: Int + struct WindowKey: Hashable { + let resetsAt: Date + let windowMinutes: Int + } + + var windowKey: WindowKey { + WindowKey(resetsAt: self.resetsAt, windowMinutes: self.windowMinutes) + } + public init( provider: Provider, sampledAt: Date, @@ -143,14 +152,7 @@ public actor UsageHistoryStore { ) -> UsageHistoryDataset? { guard !records.isEmpty else { return nil } - struct WeekKey: Hashable { - let resetsAt: Date - let windowMinutes: Int - } - - let grouped = Dictionary(grouping: records) { - WeekKey(resetsAt: $0.resetsAt, windowMinutes: $0.windowMinutes) - } + let grouped = Dictionary(grouping: records, by: \.windowKey) var weeks: [UsageWeekProfile] = [] for (key, samples) in grouped { @@ -171,7 +173,7 @@ public actor UsageHistoryStore { )) } - let rhythm = DailyUsageRhythm.learn(from: records, timeZone: timeZone) + let rhythm = DailyUsageRhythm.learn(windows: grouped.values, timeZone: timeZone) guard !weeks.isEmpty || rhythm != nil else { return nil } weeks.sort { $0.resetsAt < $1.resetsAt } return UsageHistoryDataset(weeks: weeks, rhythm: rhythm) @@ -211,17 +213,16 @@ public actor UsageHistoryStore { points.sort { $0.u == $1.u ? $0.value < $1.value : $0.u < $1.u } // Cumulative usage never decreases; a dip means a stale or reordered reading. - var monotone = points var runningMax = 0.0 - for index in monotone.indices { - runningMax = max(runningMax, monotone[index].value) - monotone[index].value = runningMax + for index in points.indices { + runningMax = max(runningMax, points[index].value) + points[index].value = runningMax } var curve = Array(repeating: 0.0, count: gridPointCount) let denominator = Double(gridPointCount - 1) - let first = monotone[0] - let last = monotone[monotone.count - 1] + let first = points[0] + let last = points[points.count - 1] var upperIndex = 1 for index in 0..= last.u { curve[index] = last.value; continue } - while upperIndex < monotone.count, monotone[upperIndex].u < u { upperIndex += 1 } - let high = monotone[min(upperIndex, monotone.count - 1)] - let low = monotone[max(0, upperIndex - 1)] + while upperIndex < points.count, points[upperIndex].u < u { upperIndex += 1 } + let high = points[min(upperIndex, points.count - 1)] + let low = points[upperIndex - 1] if high.u <= low.u { curve[index] = max(low.value, high.value) continue @@ -244,7 +245,6 @@ public actor UsageHistoryStore { public static func normalizeReset(_ value: Date) -> Date { let bucket = Self.resetBucket - guard bucket > 0 else { return value } let rounded = (value.timeIntervalSinceReferenceDate / bucket).rounded() * bucket return Date(timeIntervalSinceReferenceDate: rounded) } diff --git a/Sources/QuotaBarProbe/main.swift b/Sources/QuotaBarProbe/main.swift index 1a5f0d5..c4c0b8f 100644 --- a/Sources/QuotaBarProbe/main.swift +++ b/Sources/QuotaBarProbe/main.swift @@ -73,12 +73,7 @@ func median(_ values: [Double]) -> Double { values.sorted()[values.count / 2] } -func benchmarkCost(arguments: [String]) async { - func fail(_ message: String) -> Never { - FileHandle.standardError.write(Data("error: \(message)\n".utf8)) - exit(2) - } - +func benchmarkCost(arguments: [String]) async -> String? { var provider: Provider? var iterations = 3 var index = 0 @@ -86,29 +81,29 @@ func benchmarkCost(arguments: [String]) async { switch arguments[index] { case "--provider": guard index + 1 < arguments.count, let value = Provider(rawValue: arguments[index + 1]) else { - fail("--provider requires codex or claude") + return "--provider requires codex or claude" } provider = value index += 2 case "--iterations": guard index + 1 < arguments.count, let value = Int(arguments[index + 1]), value > 0, value % 2 == 1 else { - fail("--iterations requires a positive odd integer") + return "--iterations requires a positive odd integer" } iterations = value index += 2 default: - fail("unknown benchmark argument \(arguments[index])") + return "unknown benchmark argument \(arguments[index])" } } - guard let provider else { fail("--provider is required") } + guard let provider else { return "--provider is required" } let root = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingPathComponent("quotabar-benchmark-\(UUID().uuidString)", isDirectory: true) do { try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) } catch { - fail("could not create the benchmark directory") + return "could not create the benchmark directory" } defer { try? FileManager.default.removeItem(at: root) } @@ -121,9 +116,9 @@ func benchmarkCost(arguments: [String]) async { rateCard: RateCard() ) let (cold, coldTime) = await milliseconds { await service.refresh(UsageTab(provider: provider)) } - guard let cold else { fail("cold scan failed") } + guard let cold else { return "cold scan failed" } let (incremental, incrementalTime) = await milliseconds { await service.refresh(UsageTab(provider: provider)) } - guard let incremental else { fail("incremental scan failed") } + guard let incremental else { return "incremental scan failed" } stable = stable && equivalentCost(cold, incremental) coldTimes.append(coldTime) incrementalTimes.append(incrementalTime) @@ -140,14 +135,17 @@ func benchmarkCost(arguments: [String]) async { format: "incremental_ms median=%.1f min=%.1f max=%.1f", median(incrementalTimes), incrementalTimes.min() ?? 0, incrementalTimes.max() ?? 0 )) + return nil } let arguments = Array(CommandLine.arguments.dropFirst()) if let benchmarkIndex = arguments.firstIndex(of: "--benchmark-cost") { var benchmarkArguments = arguments benchmarkArguments.remove(at: benchmarkIndex) - // Returning first lets the benchmark's `defer` remove its temporary databases. - await benchmarkCost(arguments: benchmarkArguments) + if let message = await benchmarkCost(arguments: benchmarkArguments) { + FileHandle.standardError.write(Data("error: \(message)\n".utf8)) + exit(2) + } exit(0) } diff --git a/Sources/QuotaBarTests/AppCheck.swift b/Sources/QuotaBarTests/AppCheck.swift index aced6ef..e0a8ac6 100644 --- a/Sources/QuotaBarTests/AppCheck.swift +++ b/Sources/QuotaBarTests/AppCheck.swift @@ -1,4 +1,5 @@ import Foundation +@testable import QuotaBarApp /// The failure that stopped an app check. struct CheckFailure: Error, CustomStringConvertible { @@ -22,7 +23,7 @@ enum AppCheck { static func waitDuringMenuTracking(until ready: () -> Bool, timeout: TimeInterval = 5) async -> Bool { let deadline = Date().addingTimeInterval(timeout) while !ready(), Date() < deadline { - _ = RunLoop.main.run(mode: .eventTracking, before: Date().addingTimeInterval(0.01)) + RunLoopDrain.run(for: 0.01, mode: .eventTracking) try? await Task.sleep(for: .milliseconds(1)) } return ready() diff --git a/Sources/QuotaBarTests/CodexRecordingTests.swift b/Sources/QuotaBarTests/CodexRecordingTests.swift index 9e5d39b..7429875 100644 --- a/Sources/QuotaBarTests/CodexRecordingTests.swift +++ b/Sources/QuotaBarTests/CodexRecordingTests.swift @@ -191,18 +191,10 @@ extension RecorderFixture { } func writeCodexRollout(_ relativePath: String, lines: [String]) { - let file = self.codexRollout(relativePath) - try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) - try? (lines.joined(separator: "\n") + "\n").write(to: file, atomically: true, encoding: .utf8) + self.writeLog(at: self.codexRollout(relativePath), lines: lines) } func appendCodexRollout(_ relativePath: String, lines: [String]) { - guard let handle = try? FileHandle(forWritingTo: self.codexRollout(relativePath)) else { - Harness.expect(false, "could not append to \(relativePath)") - return - } - defer { try? handle.close() } - _ = try? handle.seekToEnd() - try? handle.write(contentsOf: Data((lines.joined(separator: "\n") + "\n").utf8)) + self.appendLog(at: self.codexRollout(relativePath), lines: lines) } } diff --git a/Sources/QuotaBarTests/Harness.swift b/Sources/QuotaBarTests/Harness.swift index 23c0d51..bae26fb 100644 --- a/Sources/QuotaBarTests/Harness.swift +++ b/Sources/QuotaBarTests/Harness.swift @@ -1,7 +1,6 @@ import Foundation -/// Command Line Tools ship neither XCTest nor swift-testing, so the suite is a plain -/// executable with a few assertions. `make test` runs it; a failure exits non-zero. +/// Shared assertions for the executable run by `make test`. A failure exits nonzero. enum Harness { nonisolated(unsafe) private static var failures: [String] = [] nonisolated(unsafe) private static var checks = 0 diff --git a/Sources/QuotaBarTests/OpenCodeAdapterTests.swift b/Sources/QuotaBarTests/OpenCodeAdapterTests.swift index 6f051ae..666d4e6 100644 --- a/Sources/QuotaBarTests/OpenCodeAdapterTests.swift +++ b/Sources/QuotaBarTests/OpenCodeAdapterTests.swift @@ -157,17 +157,17 @@ final class OpenCodeFixtureDatabase { init?(at root: URL, partColumns: String = "id TEXT PRIMARY KEY, message_id TEXT NOT NULL, data TEXT NOT NULL", hasSessionColumn: Bool = true) { self.hasSessionColumn = hasSessionColumn let directory = root.appendingPathComponent("opencode") - try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) self.url = directory.appendingPathComponent("opencode.db") do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) self.db = try TestDatabase(self.url) + let session = hasSessionColumn ? ", session_id TEXT" : "" + try self.db.exec("CREATE TABLE IF NOT EXISTS message (id TEXT PRIMARY KEY, data TEXT NOT NULL\(session))") + try self.db.exec("CREATE TABLE IF NOT EXISTS part (\(partColumns))") } catch { - Harness.expect(false, "OpenCode fixture database opens") + Harness.expect(false, "could not prepare the OpenCode fixture database: \(error)") return nil } - self.execute("CREATE TABLE message (id TEXT PRIMARY KEY, data TEXT NOT NULL)") - if hasSessionColumn { self.execute("ALTER TABLE message ADD COLUMN session_id TEXT") } - self.execute("CREATE TABLE part (\(partColumns))") } func close() { @@ -220,20 +220,44 @@ final class OpenCodeFixtureDatabase { ) } - func execute(_ sql: String) { - try? self.db.exec(sql) + func execute(_ sql: String, _ bindings: String?...) { + do { + try self.db.exec(sql, bindings: bindings) + } catch { + Harness.expect(false, "writing the OpenCode fixture failed: \(error)") + } } private func setSession(_ sessionID: String?, messageID: String) { guard self.hasSessionColumn, let sessionID else { return } - try? self.db.exec("UPDATE message SET session_id = ? WHERE id = ?", sessionID, messageID) + self.execute("UPDATE message SET session_id = ? WHERE id = ?", sessionID, messageID) } private func insert(_ table: String, id: String, messageID: String? = nil, data: String) { if let messageID { - try? self.db.exec("INSERT INTO \(table) (id, message_id, data) VALUES (?, ?, ?)", id, messageID, data) + self.execute("INSERT INTO \(table) (id, message_id, data) VALUES (?, ?, ?)", id, messageID, data) } else { - try? self.db.exec("INSERT INTO \(table) (id, data) VALUES (?, ?)", id, data) + self.execute("INSERT INTO \(table) (id, data) VALUES (?, ?)", id, data) + } + } +} + +extension RecorderFixture { + func writeOpenCodeUsage(openCodeAccount: String, created: Int64 = 1_788_264_000_000) { + let codex = self.root.appendingPathComponent("codex") + guard let db = OpenCodeFixtureDatabase(at: self.root) else { return } + db.stepFinish("part-1", created: created, model: "gpt-5.6-luna", input: 10) + db.close() + do { + try FileManager.default.createDirectory(at: codex, withIntermediateDirectories: true) + try #"{"tokens":{"account_id":"account-a"}}"#.write( + to: codex.appendingPathComponent("auth.json"), atomically: true, encoding: .utf8 + ) + try #"{"openai":{"type":"oauth","accountId":"\#(openCodeAccount)"}}"#.write( + to: db.url.deletingLastPathComponent().appendingPathComponent("auth.json"), atomically: true, encoding: .utf8 + ) + } catch { + Harness.expect(false, "could not prepare OpenCode account fixtures: \(error)") } } } diff --git a/Sources/QuotaBarTests/PiAgentAdapterTests.swift b/Sources/QuotaBarTests/PiAgentAdapterTests.swift index ab629df..877893f 100644 --- a/Sources/QuotaBarTests/PiAgentAdapterTests.swift +++ b/Sources/QuotaBarTests/PiAgentAdapterTests.swift @@ -75,20 +75,6 @@ enum PiSessionFile { try? (lines.joined(separator: "\n") + "\n").write(to: file, atomically: true, encoding: .utf8) } - /// Pi Agent's sign-in to OpenAI, and Codex's, so eligibility can be decided. - static func signIn(root: URL, piAccount: String, codexAccount: String = "account-a") { - let codex = root.appendingPathComponent("codex") - let pi = root.appendingPathComponent("pi") - try? FileManager.default.createDirectory(at: codex, withIntermediateDirectories: true) - try? FileManager.default.createDirectory(at: pi, withIntermediateDirectories: true) - try? #"{"tokens":{"account_id":"\#(codexAccount)"}}"#.write( - to: codex.appendingPathComponent("auth.json"), atomically: true, encoding: .utf8 - ) - try? #"{"openai-codex":{"type":"oauth","accountId":"\#(piAccount)"}}"#.write( - to: pi.appendingPathComponent("auth.json"), atomically: true, encoding: .utf8 - ) - } - static func message( _ id: String, role: String = "assistant", diff --git a/Sources/QuotaBarTests/PricingRefreshTests.swift b/Sources/QuotaBarTests/PricingRefreshTests.swift index 1bc0ce9..758df1e 100644 --- a/Sources/QuotaBarTests/PricingRefreshTests.swift +++ b/Sources/QuotaBarTests/PricingRefreshTests.swift @@ -42,6 +42,7 @@ enum PricingRefreshTests { } static func run() async { + await Self.stoppingDiscardsQueuedPiScans() await AppCheck.run("rate changes refresh costs without extra quota requests") { let defaults = EphemeralDefaults.make(Self.suite) defer { EphemeralDefaults.clear(Self.suite) } @@ -96,4 +97,51 @@ enum PricingRefreshTests { await Task.yield() } } + + private static func stoppingDiscardsQueuedPiScans() async { + await AppCheck.run("stopping cancels the current and queued Pi scans") { + let suite = "QuotaBarPiScanCancellationTests.\(UUID().uuidString)" + let defaults = EphemeralDefaults.make(suite) + defer { EphemeralDefaults.clear(suite) } + var calls = 0 + var oldScan: CheckedContinuation? + var wasCancelled: Bool? + let replacement = CostSnapshot( + tab: .pi, days: [], todayCostUSD: 0, windowCostUSD: 0, latestTokens: 0, windowTokens: 0, + topModel: nil, hasUnpricedTokens: false, scannedAt: Date() + ) + let store = UsageStore( + settings: SettingsStore(defaults: defaults), costService: CostService(rateCard: RateCard()), + fetchPiCost: { + calls += 1 + if calls == 1 { + await withCheckedContinuation { oldScan = $0 } + wasCancelled = Task.isCancelled + return nil + } + return replacement + }, + updateThirdPartyRates: { false }, recoveryDefaults: defaults + ) + defer { + oldScan?.resume() + store.stop() + } + store.refreshPiUsage() + try AppCheck.require(await AsyncWait.wait { oldScan != nil }, "the first Pi scan did not start") + store.refreshPiUsage(repeatingRunningScan: true) + store.stop() + try AppCheck.require(!store.isScanningPi, "stopping left the old Pi scan registered") + + store.refreshPiUsage() + try AppCheck.require(await AsyncWait.wait { !store.isScanningPi && store.finishedLocalScans == 1 }, + "the replacement scan could not finish while the old scan was suspended") + oldScan?.resume() + oldScan = nil + try AppCheck.require(await AsyncWait.wait { wasCancelled != nil }, "the old scan did not return") + try AppCheck.require(wasCancelled == true && calls == 2 && store.finishedLocalScans == 1 + && store.piDisplay.cost == replacement, + "stopped work was published or started another Pi scan") + } + } } diff --git a/Sources/QuotaBarTests/RemoteLogMirrorTests.swift b/Sources/QuotaBarTests/RemoteLogMirrorTests.swift index 4dc9737..461ab65 100644 --- a/Sources/QuotaBarTests/RemoteLogMirrorTests.swift +++ b/Sources/QuotaBarTests/RemoteLogMirrorTests.swift @@ -237,7 +237,7 @@ enum RemoteLogMirrorTests { let commands = SuspendedRemoteCommand(suspended: 2) let mirror = RemoteLogMirror(root: fixture.remoteLogs, run: commands.run) let task = Task { try await service.syncRemote(host: "host", mirror: mirror) } - Harness.expect(await Self.eventually { commands.isSuspended }, "service holds host during copy") + Harness.expect(await AsyncWait.wait { commands.isSuspended }, "service holds host during copy") _ = await service.refresh(.codex) Harness.expectEqual(fixture.remoteUsage("host")?.records, 0, "background scans cannot see in-flight copies") do { @@ -312,7 +312,9 @@ enum RemoteLogMirrorTests { /// Hosts used to follow the refresh cadence, so someone on Manual must not start connecting. @MainActor private static func manualRefreshKeepsHostsManualUntilChanged() { - let defaults = EphemeralDefaults.make("QuotaBarRemoteAutoSyncTests") + let suite = "QuotaBarRemoteAutoSyncTests" + let defaults = EphemeralDefaults.make(suite) + defer { EphemeralDefaults.clear(suite) } Harness.expect(SettingsStore(defaults: defaults).remoteAutoSync, "hosts sync on their own by default") defaults.set(RefreshFrequency.manual.rawValue, forKey: "refreshFrequency") @@ -409,7 +411,7 @@ enum RemoteLogMirrorTests { let root = fixture.root.appendingPathComponent("mirror") let mirror = RemoteLogMirror(root: root, run: commands.run) let task = Task { try await mirror.sync(host: "host") } - let reached = await Self.eventually { commands.isSuspended } + let reached = await AsyncWait.wait { commands.isSuspended } Harness.expect(reached, "the dummy command reaches its suspension") task.cancel() commands.release() @@ -433,7 +435,9 @@ enum RemoteLogMirrorTests { for suspended in [1, 2] { let fixture = RecorderFixture(name: "remote-readd-\(suspended)") defer { fixture.remove() } - let settings = SettingsStore(defaults: EphemeralDefaults.make("RemoteReadd-\(suspended)")) + let suite = "RemoteReadd-\(suspended)" + let settings = SettingsStore(defaults: EphemeralDefaults.make(suite)) + defer { EphemeralDefaults.clear(suite) } let commands = SuspendedRemoteCommand(suspended: suspended) var successes = 0 let model = RemoteSyncModel( @@ -445,7 +449,7 @@ enum RemoteLogMirrorTests { try? FileManager.default.createDirectory(at: retained.deletingLastPathComponent(), withIntermediateDirectories: true) try? Data("existing transcript".utf8).write(to: retained) model.add("host") - let reached = await Self.eventually { commands.isSuspended } + let reached = await AsyncWait.wait { commands.isSuspended } Harness.expect(reached, "model reaches suspended command") model.remove("host") Harness.expect(FileManager.default.fileExists(atPath: retained.path), "removing a host preserves old mirror data") @@ -454,7 +458,7 @@ enum RemoteLogMirrorTests { for _ in 0..<100 { await Task.yield() } Harness.expectEqual(commands.count, suspended, "replacement waits for previous command to finish") commands.release() - let finished = await Self.eventually { !model.isSyncing } + let finished = await AsyncWait.wait { !model.isSyncing } Harness.expect(finished, "replacement finishes within the test deadline") Harness.expectEqual(successes, 1, "only replacement requests a scan") Harness.expectEqual(commands.count, suspended + 3, "replacement runs exactly one probe and two copies") @@ -485,14 +489,14 @@ enum RemoteLogMirrorTests { withExtendedLifetime(observer) {} } model.sync("host") - let started = await Self.eventually { commands.isSuspended } + let started = await AsyncWait.wait { commands.isSuspended } Harness.expect(started, "removed-host fixture reaches suspended command") model.remove("host") Harness.expect(model.isSyncing, "removing a host keeps its winding-down write tracked") Harness.expectEqual(model.state(of: "idle-host"), .idle, "other host stays idle") let beforeCompletion = publications commands.release() - let finished = await Self.eventually { !model.isSyncing } + let finished = await AsyncWait.wait { !model.isSyncing } Harness.expect(finished, "cancelled host finishes within the test deadline") Harness.expect(publications > beforeCompletion, "task completion must invalidate Sync now's disabled state") } @@ -506,8 +510,13 @@ enum RemoteLogMirrorTests { "/bin/sh", ["-c", "echo $$ > \"$1\"; exec /bin/sleep 30", "test", marker.path], 2 ) } - let reached = await Self.eventually { FileManager.default.fileExists(atPath: marker.path) } - Harness.expect(reached, "local dummy process starts without network access") + var childPID: Int32? + let started = await AsyncWait.wait { + guard let raw = try? String(contentsOf: marker, encoding: .utf8) else { return false } + childPID = Int32(raw.trimmingCharacters(in: .whitespacesAndNewlines)) + return childPID != nil + } + Harness.expect(started, "local dummy process publishes its PID before cancellation") let start = Date() task.cancel() do { @@ -517,18 +526,11 @@ enum RemoteLogMirrorTests { Harness.expect(error is CancellationError, "native command reports cancellation") } Harness.expect(Date().timeIntervalSince(start) < 1, "cancellation does not wait for timeout") - if let raw = try? String(contentsOf: marker, encoding: .utf8), let pid = Int32(raw.trimmingCharacters(in: .whitespacesAndNewlines)) { - Harness.expect(kill(pid, 0) == -1, "cancelled child has exited before completion") + if let pid = childPID { + Harness.expect(kill(pid, 0) == -1 && errno == ESRCH, "cancelled child has exited before completion") } } - @MainActor - private static func eventually(_ predicate: () -> Bool) async -> Bool { - let deadline = Date().addingTimeInterval(3) - while !predicate(), Date() < deadline { try? await Task.sleep(for: .milliseconds(5)) } - return predicate() - } - private static func expectFailure( of mirror: RemoteLogMirror, equals expected: RemoteSyncError, @@ -729,19 +731,11 @@ private extension RecorderFixture { } func writeMirrored(_ relativePath: String, lines: [String]) { - let file = self.remoteLogs.appendingPathComponent(relativePath) - try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) - try? (lines.joined(separator: "\n") + "\n").write(to: file, atomically: true, encoding: .utf8) + self.writeLog(at: self.remoteLogs.appendingPathComponent(relativePath), lines: lines) } func appendMirrored(_ relativePath: String, lines: [String]) { - guard let handle = try? FileHandle(forWritingTo: self.remoteLogs.appendingPathComponent(relativePath)) else { - Harness.expect(false, "could not append to \(relativePath)") - return - } - defer { try? handle.close() } - _ = try? handle.seekToEnd() - try? handle.write(contentsOf: Data((lines.joined(separator: "\n") + "\n").utf8)) + self.appendLog(at: self.remoteLogs.appendingPathComponent(relativePath), lines: lines) } } diff --git a/Sources/QuotaBarTests/SnapshotRecordingTests.swift b/Sources/QuotaBarTests/SnapshotRecordingTests.swift index 54dd7f5..90b45df 100644 --- a/Sources/QuotaBarTests/SnapshotRecordingTests.swift +++ b/Sources/QuotaBarTests/SnapshotRecordingTests.swift @@ -11,12 +11,12 @@ enum SnapshotRecordingTests { Self.fastRequestsAreRecordedAsFast() Self.ineligibleAccountIsRecordedButNotIncluded() Self.piSessionChangesAreDetected() - Self.codexProviderRecordsExternalAgents() + Self.codexRecordsOpenCodeAndLeavesPiForItsOwnScan() Self.rowsMissingFromALaterSnapshotAreKept() Self.nonOAuthSignInIsNotIncluded() Self.uncheckableSignInRecordsNothingUntilItRecovers() Self.openCodeSignOutKeepsHistoryAndResumesAutomatically() - Self.piSignOutKeepsHistoryAndResumesAutomatically() + Self.piRecordsWithoutSignInAndKeepsHistoryOnFailure() Self.excludedRowsStayExcluded() Self.unreadableSourceKeepsRecordedUsage() Self.removedSourceIsIdleAndKeepsRecordedUsage() @@ -40,8 +40,7 @@ enum SnapshotRecordingTests { NSTimeZone.default = previousZone } setZone("UTC") - Self.writeOpenCodeUsage(fixture, openCodeAccount: "account-a") - PiSessionFile.signIn(root: fixture.root, piAccount: "account-a") + fixture.writeOpenCodeUsage(openCodeAccount: "account-a") PiSessionFile.write(root: fixture.root, "project/session.jsonl", lines: [PiSessionFile.message("old", input: 10)]) fixture.writeClaudeTranscript("app/session.jsonl", lines: [ ClaudeLine.assistant(id: "old", model: "claude-opus-5", input: 10, output: 1), @@ -124,7 +123,7 @@ enum SnapshotRecordingTests { private static func nonOAuthSignInIsNotIncluded() { let fixture = RecorderFixture(name: "snapshot-non-oauth") defer { fixture.remove() } - Self.writeOpenCodeUsage(fixture, openCodeAccount: "account-a") + fixture.writeOpenCodeUsage(openCodeAccount: "account-a") Self.signInOpenCode(fixture, #"{"openai":{"type":"api","accountId":"account-a"}}"#) fixture.recorder?.record(OpenCodeAdapter(env: fixture.env), rateCard: RateCard()) @@ -138,7 +137,7 @@ enum SnapshotRecordingTests { private static func uncheckableSignInRecordsNothingUntilItRecovers() { let fixture = RecorderFixture(name: "snapshot-uncheckable") defer { fixture.remove() } - Self.writeOpenCodeUsage(fixture, openCodeAccount: "account-a") + fixture.writeOpenCodeUsage(openCodeAccount: "account-a") Self.signInOpenCode(fixture, #"{"openai":null}"#) fixture.recorder?.record(OpenCodeAdapter(env: fixture.env), rateCard: RateCard()) @@ -158,7 +157,7 @@ enum SnapshotRecordingTests { private static func openCodeSignOutKeepsHistoryAndResumesAutomatically() { let fixture = RecorderFixture(name: "snapshot-opencode-sign-out") defer { fixture.remove() } - Self.writeOpenCodeUsage(fixture, openCodeAccount: "account-a") + fixture.writeOpenCodeUsage(openCodeAccount: "account-a") fixture.record(.codex) Harness.expectEqual(fixture.recorded(.codex)[Self.standard]?.input, 10, "OpenCode history is initially recorded") @@ -189,8 +188,8 @@ enum SnapshotRecordingTests { } /// Pi usage depends on readable sessions, with no sign-in dependency. - private static func piSignOutKeepsHistoryAndResumesAutomatically() { - let fixture = RecorderFixture(name: "snapshot-pi-sign-out") + private static func piRecordsWithoutSignInAndKeepsHistoryOnFailure() { + let fixture = RecorderFixture(name: "snapshot-pi-without-auth") defer { fixture.remove() } PiSessionFile.write(root: fixture.root, "project/session.jsonl", lines: [PiSessionFile.message("one", input: 10)]) fixture.record(.pi) @@ -217,7 +216,7 @@ enum SnapshotRecordingTests { private static func excludedRowsStayExcluded() { let fixture = RecorderFixture(name: "snapshot-stay-excluded") defer { fixture.remove() } - Self.writeOpenCodeUsage(fixture, openCodeAccount: "account-b") + fixture.writeOpenCodeUsage(openCodeAccount: "account-b") fixture.recorder?.record(OpenCodeAdapter(env: fixture.env), rateCard: RateCard()) Self.signInOpenCode(fixture, #"{"openai":{"type":"oauth","accountId":"account-a"}}"#) @@ -237,7 +236,7 @@ enum SnapshotRecordingTests { private static func unreadableSourceKeepsRecordedUsage() { let fixture = RecorderFixture(name: "snapshot-unreadable") defer { fixture.remove() } - Self.writeOpenCodeUsage(fixture, openCodeAccount: "account-a") + fixture.writeOpenCodeUsage(openCodeAccount: "account-a") fixture.recorder?.record(OpenCodeAdapter(env: fixture.env), rateCard: RateCard()) guard let db = OpenCodeFixtureDatabase(at: fixture.root) else { return } @@ -253,7 +252,6 @@ enum SnapshotRecordingTests { private static func removedSourceIsIdleAndKeepsRecordedUsage() { let fixture = RecorderFixture(name: "snapshot-removed") defer { fixture.remove() } - PiSessionFile.signIn(root: fixture.root, piAccount: "account-a") PiSessionFile.write(root: fixture.root, "project/session.jsonl", lines: [PiSessionFile.message("one", input: 10)]) fixture.recorder?.record(PiAgentAdapter(env: fixture.env), rateCard: RateCard()) @@ -335,7 +333,7 @@ enum SnapshotRecordingTests { private static func ineligibleAccountIsRecordedButNotIncluded() { let fixture = RecorderFixture(name: "snapshot-ineligible") defer { fixture.remove() } - Self.writeOpenCodeUsage(fixture, openCodeAccount: "account-b") + fixture.writeOpenCodeUsage(openCodeAccount: "account-b") fixture.recorder?.record(OpenCodeAdapter(env: fixture.env), rateCard: RateCard()) @@ -352,7 +350,6 @@ enum SnapshotRecordingTests { private static func piSessionChangesAreDetected() { let fixture = RecorderFixture(name: "snapshot-pi-change") defer { fixture.remove() } - PiSessionFile.signIn(root: fixture.root, piAccount: "account-a") PiSessionFile.write(root: fixture.root, "project/session.jsonl", lines: [PiSessionFile.message("one", input: 10)]) let first = fixture.recorder?.record(PiAgentAdapter(env: fixture.env), rateCard: RateCard()) @@ -374,11 +371,10 @@ enum SnapshotRecordingTests { } /// Codex records OpenCode; Pi is scanned independently of Codex accounts. - private static func codexProviderRecordsExternalAgents() { + private static func codexRecordsOpenCodeAndLeavesPiForItsOwnScan() { let fixture = RecorderFixture(name: "snapshot-codex-provider") defer { fixture.remove() } - Self.writeOpenCodeUsage(fixture, openCodeAccount: "account-a") - PiSessionFile.signIn(root: fixture.root, piAccount: "account-b") + fixture.writeOpenCodeUsage(openCodeAccount: "account-a") PiSessionFile.write(root: fixture.root, "project/session.jsonl", lines: [PiSessionFile.message("one", input: 5)]) fixture.record(.codex) @@ -386,28 +382,12 @@ enum SnapshotRecordingTests { Harness.expectEqual( fixture.recorded(.codex)[Self.standard]?.input, 10, - "recording Codex records OpenCode usage, and Pi Agent usage of another account is left out" + "the Codex tab includes OpenCode usage" ) + Harness.expect(fixture.recorded(.pi).isEmpty, "a Codex scan leaves Pi sessions unrecorded") Harness.expectEqual(fixture.recorder?.scanStatus(of: .openCode), .idle, "OpenCode status after recording Codex") - Harness.expectEqual( - fixture.recorder?.scanStatus(of: .piAgent), - .idle, - "recording Codex leaves Pi status untouched" - ) - } - - private static func writeOpenCodeUsage(_ fixture: RecorderFixture, openCodeAccount: String) { - let codex = fixture.root.appendingPathComponent("codex") - try? FileManager.default.createDirectory(at: codex, withIntermediateDirectories: true) - try? #"{"tokens":{"account_id":"account-a"}}"#.write( - to: codex.appendingPathComponent("auth.json"), atomically: true, encoding: .utf8 - ) - guard let db = OpenCodeFixtureDatabase(at: fixture.root) else { return } - db.stepFinish("part-1", created: 1_788_264_000_000, model: "gpt-5.6-luna", input: 10) - db.close() - try? #"{"openai":{"type":"oauth","accountId":"\#(openCodeAccount)"}}"#.write( - to: db.url.deletingLastPathComponent().appendingPathComponent("auth.json"), atomically: true, encoding: .utf8 - ) + fixture.record(.pi) + Harness.expectEqual(fixture.recorded(.pi)[Self.standard]?.input, 5, "the Pi scan records the separate session") } } diff --git a/Sources/QuotaBarTests/SourceFailureTests.swift b/Sources/QuotaBarTests/SourceFailureTests.swift index 2cec63b..5d3cf1e 100644 --- a/Sources/QuotaBarTests/SourceFailureTests.swift +++ b/Sources/QuotaBarTests/SourceFailureTests.swift @@ -13,7 +13,7 @@ enum SourceFailureTests { private static let rollout = "2026/09/01/rollout-2026-09-01T12-00-00-0199a000-0000-7000-8000-000000000103.jsonl" /// The Codex refresh still returns a cost snapshot when the Codex scan fails, and it shows - /// OpenCode, Pi Agent, and the Codex usage recorded before. + /// OpenCode and previously recorded Codex usage. Pi remains available through its own scan. private static func failedCodexScanStillYieldsASnapshot() async { let fixture = RecorderFixture(name: "failure-codex-refresh") defer { fixture.remove() } @@ -123,19 +123,13 @@ enum SourceFailureTests { } } - /// OpenCode usage of 10 input tokens and Pi Agent usage of 5, both of the Codex account. + /// OpenCode usage from the Codex account and an independent Pi session. private static func writeExternalAgentUsage(_ fixture: RecorderFixture) { let milliseconds = Int64(Date().timeIntervalSince1970 * 1_000) - PiSessionFile.signIn(root: fixture.root, piAccount: "account-a") + fixture.writeOpenCodeUsage(openCodeAccount: "account-a", created: milliseconds) PiSessionFile.write(root: fixture.root, "project/session.jsonl", lines: [ PiSessionFile.message("one", model: "gpt-5.6-terra", milliseconds: milliseconds, input: 5), ]) - guard let db = OpenCodeFixtureDatabase(at: fixture.root) else { return } - db.stepFinish("part-1", created: milliseconds, model: "gpt-5.6-luna", input: 10) - db.close() - try? #"{"openai":{"type":"oauth","accountId":"account-a"}}"#.write( - to: db.url.deletingLastPathComponent().appendingPathComponent("auth.json"), atomically: true, encoding: .utf8 - ) } private static var now: String { ISO8601DateFormatter().string(from: Date()) } diff --git a/Sources/QuotaBarTests/TestDatabase.swift b/Sources/QuotaBarTests/TestDatabase.swift index 9b373f3..d58d7a0 100644 --- a/Sources/QuotaBarTests/TestDatabase.swift +++ b/Sources/QuotaBarTests/TestDatabase.swift @@ -27,6 +27,10 @@ final class TestDatabase { /// Runs `sql`, which may hold several statements. With bindings it must be one statement, /// and each `?` takes the next value, `nil` binding NULL. func exec(_ sql: String, _ bindings: String?...) throws { + try self.exec(sql, bindings: bindings) + } + + func exec(_ sql: String, bindings: [String?]) throws { guard !bindings.isEmpty else { var message: UnsafeMutablePointer? guard sqlite3_exec(self.db, sql, nil, nil, &message) == SQLITE_OK else { diff --git a/Sources/QuotaBarTests/UsageBackupTests.swift b/Sources/QuotaBarTests/UsageBackupTests.swift index eddd610..f95c640 100644 --- a/Sources/QuotaBarTests/UsageBackupTests.swift +++ b/Sources/QuotaBarTests/UsageBackupTests.swift @@ -222,9 +222,8 @@ enum UsageBackupTests { /// A restored disk gives the rollout a new inode. Whatever it reappears as, what it appended /// counts and nothing counts twice. private static func restoredCodexRolloutResumes() async { - let original = BackupFixture(name: "resume-original") let restored = BackupFixture(name: "resume-new") - defer { original.remove(); restored.remove() } + defer { restored.remove() } let lines = [ CodexLine.turnContext(model: "gpt-5.6-sol"), CodexLine.tokenCount(input: 100, output: 10, total: 110), @@ -238,9 +237,10 @@ enum UsageBackupTests { try? FileManager.default.removeItem(atPath: restored.logs.databaseURL.path + suffix) } restored.logs.writeCodexRollout(Self.rollout, lines: lines) - let fresh = BackupFixture(name: "resume-new", keeping: restored.logs) + let fresh = BackupFixture(keeping: restored.logs) - _ = await Self.importBackup(restored.backup, into: fresh) + let imported = await Self.importBackup(restored.backup, into: fresh) + Harness.expectEqual(imported?.added, 1, "the restored database starts empty and imports the saved rollout") await fresh.scan() Harness.expectEqual(fresh.logs.recorded(.codex)[Self.codexTier]?.input, 100, "the restored rollout is not doubled") @@ -347,18 +347,24 @@ enum UsageBackupTests { await fixture.scan() let text = fixture.logs.root.appendingPathComponent("notes.sqlite") - try? Data(String(repeating: "not a database\n", count: 200).utf8).write(to: text) let foreign = fixture.logs.root.appendingPathComponent("foreign.sqlite") - try? TestDatabase(foreign).exec("CREATE TABLE notes (body TEXT)") let newer = fixture.logs.root.appendingPathComponent("newer.sqlite") await Self.export(fixture, to: newer) - try? TestDatabase(newer).exec("ALTER TABLE claude_message ADD COLUMN from_the_future INTEGER") + do { + try Data(String(repeating: "not a database\n", count: 200).utf8).write(to: text) + try TestDatabase(foreign).exec("CREATE TABLE notes (body TEXT)") + try TestDatabase(newer).exec("ALTER TABLE claude_message ADD COLUMN from_the_future INTEGER") + } catch { + Harness.expect(false, "could not create unusable backup fixtures: \(error)") + return + } await Self.expectRefused(text, by: fixture, "a file that is not a database") await Self.expectRefused(foreign, by: fixture, "another app's database") - await Self.expectRefused(newer, by: fixture, "a backup from a newer version") + await Self.expectRefused(newer, by: fixture, "a backup from a newer version", expected: UsageBackupError.newerVersion) await Self.expectRefused( - fixture.logs.root.appendingPathComponent("missing.sqlite"), by: fixture, "a file that is gone" + fixture.logs.root.appendingPathComponent("missing.sqlite"), by: fixture, "a file that is gone", + expected: CocoaError(.fileReadNoSuchFile) ) Harness.expectEqual(fixture.logs.recorded(.claude)[Self.claudeTier]?.input, 7, "the saved usage is untouched") @@ -399,7 +405,7 @@ enum UsageBackupTests { } await Self.export(original) _ = await Self.importBackup(original.backup, into: local) - let reopened = BackupFixture(name: "reopened", keeping: local.logs) + let reopened = BackupFixture(keeping: local.logs) await reopened.scan() Harness.expectEqual(reopened.logs.recorded(.claude)[Self.claudeTier]?.input, 26, "valid backup remains readable after reopening and scanning") @@ -433,7 +439,7 @@ enum UsageBackupTests { } await Self.export(source) _ = await Self.importBackup(source.backup, into: target) - let reopened = BackupFixture(name: "reopened-valid-tokens", keeping: target.logs) + let reopened = BackupFixture(keeping: target.logs) await reopened.scan() Harness.expectEqual(reopened.logs.recorded(.claude)[Self.claudeTier]?.input, 26, "valid token import survives reopening") @@ -452,7 +458,7 @@ enum UsageBackupTests { fixture.logs.appendClaudeTranscript("app/session.jsonl", lines: [ ClaudeLine.assistant(id: "second", model: "claude-opus-5", input: 11, output: 3), ]) - let reopened = BackupFixture(name: "reopened-corrupt", keeping: fixture.logs) + let reopened = BackupFixture(keeping: fixture.logs) await reopened.scan() Harness.expectEqual(reopened.logs.recorded(.claude)[Self.claudeTier]?.input, 18, "an invalid existing cursor triggers a safe reparse after reopening") @@ -465,23 +471,21 @@ enum UsageBackupTests { let fixture = BackupFixture(name: "pane") defer { fixture.remove() } let suite = "QuotaBarBackupTests.\(UUID().uuidString)" - guard let defaults = UserDefaults(suiteName: suite) else { return } - defer { defaults.removePersistentDomain(forName: suite) } + let defaults = EphemeralDefaults.make(suite) + defer { EphemeralDefaults.clear(suite) } fixture.logs.writeClaudeTranscript("app/session.jsonl", lines: [ ClaudeLine.assistant(id: "msg", model: "claude-opus-5", input: 7, output: 3), ]) await fixture.scan() - var scans = 0 + var scannedTabs: Set = [] let settings = SettingsStore(defaults: defaults) let store = UsageStore( settings: settings, costService: fixture.service, fetchState: { _, _ in .signedOut("") }, - fetchCost: { _ in - scans += 1 - return nil - }, + fetchCost: { scannedTabs.insert(UsageTab(provider: $0)); return nil }, + fetchPiCost: { scannedTabs.insert(.pi); return nil }, updateThirdPartyRates: { false }, historyStore: UsageHistoryStore(fileURL: fixture.logs.root.appendingPathComponent("history.json")), recoveryDefaults: defaults @@ -502,7 +506,7 @@ enum UsageBackupTests { .failed(UsageBackupError.unreadable.localizedDescription), "the pane says why a file was refused" ) - Harness.expectEqual(scans, 0, "a refused file starts no scan") + Harness.expect(scannedTabs.isEmpty, "a refused file starts no scan") await model.importBackup(from: fixture.backup) Harness.expectEqual( @@ -510,11 +514,8 @@ enum UsageBackupTests { .imported(UsageImportResult(added: 0, updated: 0)), "the pane reports what the import changed" ) - let deadline = Date().addingTimeInterval(5) - while scans < Provider.allCases.count, Date() < deadline { - try? await Task.sleep(for: .milliseconds(5)) - } - Harness.expectEqual(scans, Provider.allCases.count, "an import scans every provider") + Harness.expect(await AsyncWait.wait { scannedTabs == Set(UsageTab.allCases) }, + "an import rescans every usage tab") } @MainActor @@ -549,12 +550,17 @@ enum UsageBackupTests { Harness.expectEqual(model.summary, lastGood, "a later read failure preserves the last good summary") } - private static func expectRefused(_ file: URL, by fixture: BackupFixture, _ label: String) async { + private static func expectRefused( + _ file: URL, by fixture: BackupFixture, _ label: String, expected: Error = UsageBackupError.unreadable + ) async { do { _ = try await fixture.service.importBackup(from: file) Harness.expect(false, "\(label) was imported") } catch { - Harness.expect(true, "\(label) was refused") + let actual = error as NSError + let wanted = expected as NSError + Harness.expect(actual.domain == wanted.domain && actual.code == wanted.code, + "\(label): expected \(wanted), got \(actual)") } } @@ -582,11 +588,11 @@ private struct BackupFixture { let service: CostService init(name: String) { - self.init(name: "backup-\(name)", keeping: RecorderFixture(name: "backup-\(name)")) + self.init(keeping: RecorderFixture(name: "backup-\(name)")) } /// A service starting over on the logs of an earlier fixture. - init(name _: String, keeping logs: RecorderFixture) { + init(keeping logs: RecorderFixture) { self.logs = logs self.service = CostService(databaseURL: logs.databaseURL, env: logs.env, rateCard: RateCard()) } diff --git a/Sources/QuotaBarTests/UsageRecorderTests.swift b/Sources/QuotaBarTests/UsageRecorderTests.swift index 7d43c2b..442a44e 100644 --- a/Sources/QuotaBarTests/UsageRecorderTests.swift +++ b/Sources/QuotaBarTests/UsageRecorderTests.swift @@ -319,19 +319,31 @@ struct RecorderFixture { } func writeClaudeTranscript(_ relativePath: String, lines: [String]) { - let file = self.claudeTranscript(relativePath) - try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) - try? (lines.joined(separator: "\n") + "\n").write(to: file, atomically: true, encoding: .utf8) + self.writeLog(at: self.claudeTranscript(relativePath), lines: lines) } func appendClaudeTranscript(_ relativePath: String, lines: [String]) { - guard let handle = try? FileHandle(forWritingTo: self.claudeTranscript(relativePath)) else { - Harness.expect(false, "could not append to \(relativePath)") - return + self.appendLog(at: self.claudeTranscript(relativePath), lines: lines) + } + + func writeLog(at file: URL, lines: [String]) { + do { + try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try (lines.joined(separator: "\n") + "\n").write(to: file, atomically: true, encoding: .utf8) + } catch { + Harness.expect(false, "could not write \(file.path): \(error)") + } + } + + func appendLog(at file: URL, lines: [String]) { + do { + let handle = try FileHandle(forWritingTo: file) + defer { try? handle.close() } + try handle.seekToEnd() + try handle.write(contentsOf: Data((lines.joined(separator: "\n") + "\n").utf8)) + } catch { + Harness.expect(false, "could not append to \(file.path): \(error)") } - defer { try? handle.close() } - _ = try? handle.seekToEnd() - try? handle.write(contentsOf: Data((lines.joined(separator: "\n") + "\n").utf8)) } func record(_ tab: UsageTab, rateCard: RateCard = RateCard()) { diff --git a/Sources/QuotaBarTests/UsageReportRendererTests.swift b/Sources/QuotaBarTests/UsageReportRendererTests.swift index be2a20a..27e8c22 100644 --- a/Sources/QuotaBarTests/UsageReportRendererTests.swift +++ b/Sources/QuotaBarTests/UsageReportRendererTests.swift @@ -11,7 +11,6 @@ func runUsageReportRendererTests() { Harness.expectEqual(html.components(separatedBy: "const REPORT=").count - 1, 1, "placeholder-shaped model text cannot insert another script") Harness.expect(!html.contains("src=\"http"), "report does not load external scripts") Harness.expect(!html.contains("href=\"http"), "report does not load remote fonts") - Harness.expect(!html.contains("sourceMappingURL="), "embedded chart library has no external source map") guard let start = html.range(of: "const REPORT=")?.upperBound, let end = html.range(of: ";\n/* Report runtime */", range: start.. --json state --jq .state` prints `MERGED`. -When a PR introduces the custom CodeQL workflow, also complete the one-time -[CodeQL activation](../ci.md#activate-the-codeql-workflow) after merging. ## Publish a release diff --git a/docs/ci.md b/docs/ci.md index 083a253..ab7dd4a 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -6,10 +6,19 @@ in `Scripts/ci_requires_build.sh` lets both checks finish on Linux without a macOS build. Any other path runs the existing tests and release packaging. Classification errors fail the required checks. +The `macos-15` check also renders the offline usage report with synthetic data +and runs the browser assertions against the runner's Chrome installation. The +report tools use the Node version in `.node-version` and the pnpm lockfile. + CodeQL scans Swift, Rust, Python, JavaScript/TypeScript, and Actions after pushes to `main`, weekly, and on manual dispatch. It is independent of PR merging. Review scan failures and security alerts separately from the required PR checks. +Swift analysis traces a manual build on `macos-15` with Xcode 16.4. GitHub +supports Swift build tracing through Xcode 26. The macOS 27 SDK branches are +compiled by the required `xcode-27` PR check and the release build. +See [GitHub's Swift tracing support](https://github.blog/changelog/2026-10-19-codeql-changes-for-macos-27-xcode-27-and-swift-6-4/). + Every Swift build job (PR checks, release packaging and CodeQL's manual Swift build) installs the toolchain pinned in `rust-toolchain.toml` before invoking `Scripts/swift.sh`. `make test` checks Rust formatting, unit tests and Clippy @@ -21,29 +30,10 @@ they are outside the documentation allowlist. The Rust CodeQL job uses `build-mode: none` on Linux, as supported by [CodeQL's Rust analysis](https://github.blog/changelog/2025-10-14-codeql-scanning-rust-and-c-c-without-builds-is-now-generally-available/). It does not execute the Darwin-specific native kernels. Dependabot checks the -Cargo manifest and lockfile in `Rust/QuotaBarCore` monthly, alongside the existing -GitHub Actions updates. Compiler updates remain explicit changes to the pinned -toolchain and must pass both macOS checks. - -## Activate the CodeQL workflow - -This is a one-time migration from GitHub default setup. Complete it after -`.github/workflows/codeql.yml` has merged into `main`: default setup blocks -analysis uploads from custom workflows, so adding the YAML alone is not enough. - -1. Confirm the workflow is present on `main`: - `gh api 'repos/softmaxe/quota-bar/contents/.github/workflows/codeql.yml?ref=main' --jq .path`. -2. Disable default setup: - `gh api --method PATCH repos/softmaxe/quota-bar/code-scanning/default-setup -f state=not-configured`. -3. Enable the custom workflow and dispatch its first scan: - `gh workflow enable codeql.yml`, then - `gh workflow run codeql.yml --ref main`. -4. Inspect the resulting run using `gh run list --workflow codeql.yml` and - `gh run view `. Migration is complete when all configured language jobs - succeed, including analysis upload. Fix and rerun failures before considering - the migration complete. +Cargo dependencies, report tooling dependencies, and GitHub Actions monthly. +Rust compiler updates are explicit changes to the pinned toolchain and must +pass both macOS checks. -Keep CodeQL outside the required status checks. If migration cannot be completed, -restore default setup with -`gh api --method PATCH repos/softmaxe/quota-bar/code-scanning/default-setup -f state=configured` -until the custom workflow is fixed. +The repository uses the custom CodeQL workflow with GitHub default setup +disabled. Inspect individual language jobs with `gh run list --workflow codeql.yml` +and `gh run view `. diff --git a/docs/design-implementation.md b/docs/design-implementation.md index 3a676c2..fac2be8 100644 --- a/docs/design-implementation.md +++ b/docs/design-implementation.md @@ -12,8 +12,8 @@ How the menu bar card, its controls, and its motion behave, and how to check the - Settings first opens centered in the usable area of the pointer's screen on the active Space. Moving it saves its position, including across app relaunches. Reopening preserves that position; a disconnected display causes centering on the current screen, and clipped positions are fitted into the available area. Preview positions stay in the isolated preference suite. - Settings has three panes behind a 148 pt sidebar. Each pane is a stack of titled sections: a section's actions sit beside its heading, and hairlines inside a card run edge to edge. General holds the menu bar provider and the refresh interval. - Pricing is a read-only list of the rates every estimate uses, plus the models.dev switch. Built-in, models.dev, and Unpriced models each have their own titled card, and each card groups its models by vendor under a header that folds them away. The models.dev heading stays when it has nothing to list, because it holds the switch. Every vendor is folded each time the pane opens, an open vendor names the rate columns above its rows, and a search opens every vendor. -- Usage shows how much usage is saved, where it comes from, and how to back it up. Export writes a consistent copy of the database to a chosen file. Import merges a copy of the chosen file, so it only adds, and reports what it changed; it needs no confirmation. -- Sources lists this Mac and each SSH host. Adding a host is a sheet whose one field filters the SSH config and accepts a typed name. A host's row shows the usage records its mirrored logs hold, how many of them are new, and the bytes copied; the file count is in its tooltip, and a failed host offers Retry. Claude messages are counted by key and Codex rollouts by session, so usage another log recorded first still counts as held but not as new. Records and new records are read from Recorded usage rather than from the sync, so a host whose logs hold no usage warns even though its sync succeeded. +- Usage shows how much usage is saved, where it comes from, and how to back it up. Export writes a consistent copy of the database to a chosen file. Import merges a copy of the chosen file and reports how many records it added or updated. +- Sources lists this Mac and each SSH host. Adding a host is a sheet whose one field filters the SSH config and accepts a typed name. Each host row shows its sync status, associated record count, records first seen on that host (`unique`), and the disk space occupied by its cached logs (`cached`). Claude messages are counted by key and Codex rollouts by session. The tooltip shows the cached file count or the sync error. A failed host offers Retry. - Local usage has a visible Tokens / Cost selector and ten calendar date columns. A compact, left-aligned summary below the date axis groups the daily average (`avg`) and daily maximum (`max`) for the visible dates. A dashed swatch beside `avg` keys the dashed average line in the chart. Dates support whole-column pointer targets and keyboard selection. Model details are collapsed as a group; complete labels remain available to accessibility. Unit changes and refreshes preserve a still-valid date selection. Unpriced and partially priced usage have distinct labels; dates not covered by the last completed scan do not claim zero usage. - Quota headlines display authoritative values; a changed reading rolls in over 120 ms. Reset feedback lasts about 0.82 seconds and respects Reduce Motion. Neutral pace markers share an Expected remaining key, with a warning below a window when its pace runs short. Credits sit with the quota windows. Stale quota fills lose their hue while reset times remain legible; local usage keeps its own colors and chart scale. @@ -67,7 +67,7 @@ images to `.build/screenshots/card`; set `SNAPSHOT_DIR` to write somewhere else. The underlying flags are `--preview-interface ` and `--dump-card `. -The `motion` state slows fetches and the first local scan, starts Claude signed out until Check sign-in, and shortens the refresh cooldown, so each animation can be watched again. Preview uses sample providers, a separate preference suite, temporary history, and no-op pricing writes. Use its Quit command for cleanup. It does not use CLI credentials or scan real session files. Normal app launch retains the real integrations. +The `motion` state slows fetches and the first local scan, starts Claude signed out until Check sign-in, and shortens the refresh cooldown, so each animation can be watched again. The preview card, pricing table, and usage report use fixtures. Settings use a separate preference suite, and recorded usage goes into a temporary database. Adding an SSH host starts a real sync and can scan local sessions. Open at login uses the macOS login-item service. Choose Quit in the preview to clean up its temporary data. `make readme-assets` regenerates the documentation images and all four interaction state screenshots. `--dump-interaction-states` can also render just those state screenshots. The generated `.build` directory is ordinary local build output. diff --git a/docs/images/settings-pricing.png b/docs/images/settings-pricing.png index 7e697e3..34423a8 100644 Binary files a/docs/images/settings-pricing.png and b/docs/images/settings-pricing.png differ diff --git a/docs/performance.md b/docs/performance.md index 832d668..299edcf 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -55,7 +55,7 @@ real-world speedup percentage. No such percentage or memory reduction is claimed ## Regression coverage -Run `make test`. After integration with `main`, the 1176 checks include escaped classifier keys and values, decoy markers, +Run `make test`. The regression suite covers escaped classifier keys and values, decoy markers, long preceding values, even and odd backslash runs, unterminated strings, resuming scans, rewrite detection, replay deduplication, source failure, pricing changes, and WAL-visible reports. The report-update regression holds one provider's scan open while another has completed, checks @@ -68,12 +68,11 @@ redundant read; restoring the former two display writes makes it fail on an inte ## Remaining candidates -Claude decoding still accounts for substantial initial-import work. Replacing Foundation's -JSON decoder or batching file transactions would require evidence and additional failure-boundary -validation. Pi and OpenCode reread snapshots when their file stamps change; caching individual -Pi files would require preserving fork deduplication, deletion, and failed-read -recovery. These remain candidates for representative active-session benchmarks, not proven -improvements. Absolute optimality cannot be established by these measurements. +Subsequent work moved ordinary Claude record decoding into Rust and retained Foundation for +compatibility. See the [Rust core boundaries](rust-migration.md) for the current implementation. +Batching file transactions would require benchmarks and validation of failure handling. +Pi and OpenCode reread snapshots when their file stamps change. A per-file Pi cache would +need to preserve fork deduplication, deletion handling, and recovery from failed reads. ## Read-time context tiers diff --git a/docs/pricing.md b/docs/pricing.md index eda941f..c617126 100644 --- a/docs/pricing.md +++ b/docs/pricing.md @@ -1,6 +1,6 @@ # Maintaining the price book -Claude and OpenAI models that are on their makers' current price lists and still supported are priced from [`price-book.json`](../Sources/QuotaBarCore/Resources/Pricing/price-book.json), kept by hand. Every other model, retired Claude and OpenAI models included, is priced from models.dev through a local cache (see [Models outside the book](#models-outside-the-book)). Cost is computed from stored tokens each time it is read, so editing the book reprices recorded usage as soon as the new build runs. Rates, aliases, and supported per-request long-context tiers are resolved again; rows without a saved request context retain their stored tier. See [Historical thresholds](#historical-thresholds). +Claude and OpenAI models that are on their makers' current price lists and still supported are priced from [`price-book.json`](../Sources/QuotaBarCore/Resources/Pricing/price-book.json), kept by hand. For other models, including retired Claude and OpenAI models, QuotaBar looks up rates in its local [models.dev cache](#models-outside-the-book). Pi can also supply a [logged cost](#pi-logged-cost-fallback) when no rate applies. Cost is computed from stored tokens each time it is read, so editing the book reprices recorded usage as soon as the new build runs. Rates, aliases, and supported per-request long-context tiers are resolved again; rows without a saved request context retain their stored tier. See [Historical thresholds](#historical-thresholds). ## Layout @@ -57,7 +57,7 @@ A period has these keys: **Wrong rate.** Fix it in place. Every recorded day it covered is repriced. -**Model is retired.** Delete its entry. All of its recorded usage is then priced from models.dev, whose rates cover no Fast tier, and stays unpriced if models.dev does not list it. +**Model is retired.** Delete its entry. Recorded Standard usage can then use models.dev rates. If no rate applies, only Pi requests with a usable logged cost contribute to the cost total. After any edit, update `checkedAt` for the provider or model you compared, then run: @@ -78,7 +78,7 @@ Models the book does not list, such as DeepSeek, GLM, or Kimi used through Codex - `context_over_200k` becomes a 200K long-context tier. Requests for models outside the book use the 200K threshold even before their rates are downloaded. Keyed rows with saved request context are classified again when read; aggregate-only rows keep their scan-time tier. There is no Fast tier. - A model whose rates changed since the last fetch gets a new period starting that day, so earlier days keep their rates. - A new Claude or OpenAI model is priced from models.dev until the book lists it. The book's rates replace models.dev for all of its usage from then on. -- The **models.dev** switch in **Settings → Pricing** turns this off. Usage of models outside the book is then unpriced and nothing is downloaded. +- The **models.dev** switch in **Settings → Pricing** turns this off. This disables downloads and pricing from cached models.dev rates. Pi requests can still use their logged costs. `ThirdPartyRatesTests` covers the parsing, the choice between listings, and the dated cache. diff --git a/docs/rust-migration.md b/docs/rust-migration.md index 1264076..9a117db 100644 --- a/docs/rust-migration.md +++ b/docs/rust-migration.md @@ -13,10 +13,10 @@ streaming accepted for product-chain parity under the user's language preference | Boundary | Implementation and code evidence | Rationale and retained ownership | | --- | --- | --- | -| Claude record decoding | `ClaudeCodeAdapter.swift:54` calls `Rust/QuotaBarCore/src/claude.rs` through a fixed C result | Rust decodes ordinary records. Foundation still handles dates, Unicode trimming/lowercasing and ID-less canonical hashing. Unsupported or ambiguous encodings fall back to the original parser before recording. | -| JSON prefix classification | `JSONLogClassifier.swift:4`, `Rust/QuotaBarCore/src/classifier.rs` | Preserve the loose classifier contract, including truncated prefixes. Bounded libc searches retain the existing long-string optimization; a pure scalar Rust version was rejected experimentally. | -| Numeric model pricing | `CostPricing.swift:93`, `Rust/QuotaBarCore/src/pricing.rs` | One call validates and prices a complete token bucket, preserving operation order, optional-rate fallback, long-context pricing and checked overflow. RateCard model lookup, aliases, dated price books, unknown-price policy and public validation diagnostics remain Swift. | -| Bounded line streaming | `LogFileScanner.swift:89`, `Rust/QuotaBarCore/src/scanner.rs` | The synchronous reader owns a descriptor and byte buffers. File discovery, stat/digest resume planning, parser state, cursor commits and transactions remain Swift. See the separate validation report for the callback cost and final acceptance evidence. | +| Claude record decoding | `ClaudeCodeAdapter.swift` calls `Rust/QuotaBarCore/src/claude.rs` through a fixed C result | Rust decodes ordinary records. Foundation still handles dates, Unicode trimming/lowercasing and ID-less canonical hashing. Unsupported or ambiguous encodings fall back to the original parser before recording. | +| JSON prefix classification | `JSONLogClassifier.swift`, `Rust/QuotaBarCore/src/classifier.rs` | Preserve the loose classifier contract, including truncated prefixes. Bounded libc searches retain the existing long-string optimization; a pure scalar Rust version was rejected experimentally. | +| Numeric model pricing | `CostPricing.swift`, `Rust/QuotaBarCore/src/pricing.rs` | One call validates and prices a complete token bucket, preserving operation order, optional-rate fallback, long-context pricing and checked overflow. RateCard model lookup, aliases, dated price books, unknown-price policy and public validation diagnostics remain Swift. | +| Bounded line streaming | `LogFileScanner.swift`, `Rust/QuotaBarCore/src/scanner.rs` | The synchronous reader owns a descriptor and byte buffers. File discovery, stat/digest resume planning, parser state, cursor commits and transactions remain Swift. See the separate validation report for the callback cost and final acceptance evidence. | | Priced-row aggregation | `CostAggregator.swift`, `Rust/QuotaBarCore/src/aggregation.rs` | Rust folds already-priced rows into per-key/day/model totals. Swift supplies day/key identities and reconstructs existing presentation models; Calendar, SQL, pricing policy and top-model tie policy remain Swift. | The C header is [QuotaBarRust.h](../Sources/CQuotaBarRust/include/QuotaBarRust.h). @@ -86,12 +86,12 @@ are excluded from this migration; they are not pending implementation work. | Module | Evidence and reason | Future experiment or alternative | | --- | --- | --- | -| `RateCard` / `PriceBook` / `PricedUsage` | `RateCard.swift:38,72,120` and `PricedUsage.swift:34`: dated aliases, context thresholds, Fast availability, unknown prices and Pi logged-cost fallback | Numeric pricing is extracted. Cache repeated resolved lookups within a pinned refresh before adding strings and price-book ownership to FFI. | -| Codex adapter | `CodexAdapter.swift:86,162`: running totals, replay suppression and persisted parser state | Current full-chain Codex comparison exercises migrated shared kernels. A separate decoder port must compare saved state after every record, not just final totals. | -| Pi / OpenCode adapters | `PiAgentAdapter.swift:102`, `OpenCodeAdapter.swift:44`: fork identity, logged costs and coherent SQLite snapshots | Profile changed-file rescans; Swift per-file caching may eliminate more work than replacing parsing. No Rust decoder performance claim is made. | -| `UsageRecorder`, `CostCache`, backups | `UsageRecorder.swift:482`, `CostCache.swift:85,615,623`: one writer, WAL/FULL durability, per-file row/cursor/state/manifest commits and history-preserving merges | SQLite remains the same native engine. Do not split transaction ownership merely to move wrappers. Existing backup, rollback, rewrite and deduplication tests remain mandatory. | -| `CostService`, `UsageStore`, report updates | `CostService.swift:65,75,94`; `UsageStore.swift:227,257`: remote-host lease across suspension, synchronous record/read, atomic cost/status publication then completion event | Preserve actors and MainActor ownership. Existing concurrent refresh/report tests verify event ordering and coalescing. | -| HTTP, credentials, Keychain, PTY, remote sync | `ClaudeCredentials.swift:5`, `ClaudePTYRunner.swift:213`, `CodexCredentialCache.swift:42`, `RemoteLogMirror.swift:197`: Apple-signed requester identity, process cancellation, refresh generations and rsync-in-place guards | Keep platform adapters. Moving these without changing platform calls has no demonstrated CPU benefit and increases cancellation/authorization risk. Tests use fake transports and processes; real credentials were not exercised. | +| `RateCard` / `PriceBook` / `PricedUsage` | `RateCard.swift` and `PricedUsage.swift`: dated aliases, context thresholds, Fast availability, unknown prices and Pi logged-cost fallback | Numeric pricing is extracted. Cache repeated resolved lookups within a pinned refresh before adding strings and price-book ownership to FFI. | +| Codex adapter | `CodexAdapter.swift`: running totals, replay suppression and persisted parser state | Current full-chain Codex comparison exercises migrated shared kernels. A separate decoder port must compare saved state after every record, not just final totals. | +| Pi / OpenCode adapters | `PiAgentAdapter.swift`, `OpenCodeAdapter.swift`: fork identity, logged costs and coherent SQLite snapshots | Profile changed-file rescans; Swift per-file caching may eliminate more work than replacing parsing. No Rust decoder performance claim is made. | +| `UsageRecorder`, `CostCache`, backups | `UsageRecorder.swift`, `CostCache.swift`: one writer, WAL/FULL durability, per-file row/cursor/state/manifest commits and history-preserving merges | SQLite remains the same native engine. Do not split transaction ownership merely to move wrappers. Existing backup, rollback, rewrite and deduplication tests remain mandatory. | +| `CostService`, `UsageStore`, report updates | `CostService.swift`; `UsageStore.swift`: remote-host lease across suspension, synchronous record/read, atomic cost/status publication then completion event | Preserve actors and MainActor ownership. Existing concurrent refresh/report tests verify event ordering and coalescing. | +| HTTP, credentials, Keychain, PTY, remote sync | `ClaudeCredentials.swift`, `ClaudePTYRunner.swift`, `CodexCredentialCache.swift`, `RemoteLogMirror.swift`: Apple-signed requester identity, process cancellation, refresh generations and rsync-in-place guards | Keep platform adapters. Moving these without changing platform calls has no demonstrated CPU benefit and increases cancellation/authorization risk. Tests use fake transports and processes; real credentials were not exercised. | | SwiftUI / AppKit / WebKit / settings | `UsageStore.swift`, `SettingsStore.swift`, `UsageReportWindowController.swift` | Preserve the required product surface and platform ownership. No Rust UI rewrite is proposed. | ## Build and maintenance @@ -113,100 +113,20 @@ app users do not install Rust or receive a separate Rust dylib. Both toolchains macOS 14. The current package/release path is a native arm64 build. Cross-architecture and universal builds are not implemented by this wrapper. -The link-cache behavior was also tested in a minimal isolated package using byte-for-byte -copies of the actual wrappers: changing only a Rust function from returning `1` to `2` -changed both archive/executable hashes and the program's output, without cleaning or -changing Swift/C sources. Raw evidence is in `build/rust-validation/relink-test.md`. - -The local release app was assembled with `make app`; its existing ad-hoc signature -passes `codesign --verify --deep --strict`. The executable is arm64, reports minimum -macOS 14.0, and has no Rust dylib dependency. Its size is 7,551,312 bytes; the complete -app is approximately 8.5 MiB and the local ZIP approximately 3.1 MiB. The local bundle -retains version `0.0.34` from the repository's release tag; this is an uncommitted -development build, not a newly published release. No installed app was replaced or -launched against personal data. The ZIP is `build/QuotaBar-rust-local-arm64.zip`, with -a matching SHA-256 file. Hosted CI and release publication have not been run. -With the identical validation hook, the original and final release probes are -2,774,256 and 3,297,824 bytes respectively (+523,568 bytes). That is a like-for-like -probe binary comparison, not a measured app-bundle size delta. The delivery manifest -binds the packaged executable and ZIP to the 186 source-input hashes used for the -final benchmark; none of the UI or resource source files changed. - -Use the wrapper or Make targets. Bare `swift build`, opening the package directly in -Xcode, or consuming `QuotaBarCore` as an external Swift package does not automatically -build/link Rust. A future distributed SDK should package an XCFramework or supply a -separately validated build integration. The CI workflows now install the pinned toolchain -before their existing test/package steps; the older SDK runner and hosted release workflow -still require execution on GitHub before claiming those environments passed. - -Rust adds a pinned compiler and dependency graph, native boundary debugging, archive -cache invalidation and a second set of tests. An early pricing diagnostic placed the -Swift oracle outside the Core module and did not enable whole-module optimization. -Its apparent 79.363/0.109 ms result is therefore withdrawn as comparative performance -evidence. The implementation removes per-bucket dictionary construction/sorting, which -Swift could also optimize, but only the final production-chain measurements support the -performance conclusion. No general Rust-versus-Swift language speed ratio is claimed. - -The line reader was accepted only after an ablation held the other Rust kernels fixed. -With Rust versus Swift streaming, five-run initial-scan medians were 15.308/15.733 ms -(short), 43.179/42.941 ms (plain long strings), 275.545/275.911 ms (dense escapes), and -22.851/23.061 ms (Codex). Appended scans were likewise close. This supports parity in -the exercised product chain, not a streaming speedup. A minimal million-short-line -counter still regresses from 18.37 to 33.72 ms because of the two Swift callbacks; -that limitation is retained in the report rather than hidden behind other improvements. - -Aggregation is also a preference-based tradeoff at small row counts. The final isolated -same-Core/WMO benchmark (including input/output conversion) improves 120/840/4,800-row -folds from 0.175/1.293/7.269 ms to 0.087/0.598/3.398 ms. However, an independent -short-record full-chain confirmation with only aggregation switched measures -16.256 ms with Swift versus 16.647 ms with Rust (+0.391 ms, +2.4%), and appended -scans 2.186 versus 2.284 ms (+0.098 ms, +4.5%). Initial-scan ranges overlap. -This small overhead is accepted under the user's near-parity preference; the module -is not claimed to accelerate every refresh. The first five-run ablation and the -targeted seven-run confirmation are both retained, rather than selecting only the -faster-looking trial. Details are in `build/rust-validation/aggregation-experiment.md` -and the validation report. - -For the complete final migration against the original Swift revision, seven-run -initial-scan medians are 21.861/15.353 ms (short Claude), 83.578/44.452 ms (plain -long Claude), 401.844/277.387 ms (dense-escape Claude) and 23.317/23.089 ms (Codex). -Unchanged refreshes remain approximately equal. These include actual file scanning, -SQLite recording, pricing and snapshot construction through `CostService`, with -cross-language costs included. They do not measure network refreshes or imply an -equivalent percentage improvement in the whole application. - ## Validation and rollback -The final integrated `make test` run passed 1,861 Swift harness assertions and 20 -Rust unit tests, plus `cargo fmt --check` and Clippy with warnings denied. The Swift -harness includes grouped differential corpora rather than counting every generated -input as a separate assertion: over 20,000 classifier cases, more than 2,000 parser -mutations/boundaries, 6,454 pricing cases, 230 aggregation cases and the scanner -boundary suite. The existing backup, authentication mocks, remote synchronization, -report publication and UI policy checks also ran. Execution used a sandbox denying -real provider credentials/data and network access; compilation ran outside that -sandbox because SwiftPM uses its own manifest sandbox. The pre-existing Swift 6-mode -warning in `AppCheck.swift` remains; the package's Swift 5 language mode is unchanged. - -See [validation methods and results](rust-validation.md) for the final repeated workload -measurements, differential database checks and UI snapshot comparison. Synthetic inputs -are intentional: the evaluation does not read personal logs, databases or credentials. -The unchanged UI source and fixture snapshots support interface compatibility, while -the complete test suite covers behavior. They cannot prove every possible real-world -log, OS release, Keychain prompt, live network race or assistive-technology interaction. - -All 32 paired offscreen PNGs (26 cards and six interaction states) are byte-identical. -The original earlier baseline is retained: 27 of its images already matched, while -five reset-clock views displayed the naturally different current minute. Rerendering -the unchanged baseline binary and final debug binary in the same minute produced the -32 identical pairs without editing any pixels or production code. No UI animation -logic changed, so no new motion implementation or animation recording is claimed. - -Seven fresh-process debug menu-construction measurements are 20.067 ms before and -19.975 ms after. Whole-process wall time, including the sandbox launcher, is -87.769/88.038 ms. All runs reported `menu_created=no`. These isolated startup checks -are effectively equal; they do not measure a cold disk, real account/network startup, -or the release app's complete interactive launch. +Run `make test` for the current regression suite. It checks Rust formatting, unit tests +and Clippy, then runs the Swift harness against the linked archive. The harness compares +classifier, Claude parser, pricing, scanner and aggregation results with their Swift +reference implementations. It also covers recording, backup, authentication mocks, +report publication and UI policy. + +The [migration validation report](rust-validation.md) records the original performance +measurements, database comparisons, startup timings and offscreen image comparisons. +It includes the command for comparing another working tree with the Swift baseline. +The migration accepted the line reader and aggregator at comparable end-to-end +performance. The short-line callback benchmark and small-row aggregation measurements +in the report qualify that result. The migration has no data-format or settings upgrade. Rollback is a code/build rollback: restore the affected adapters/kernels and remove Rust build integration, then rebuild the diff --git a/docs/rust-validation.md b/docs/rust-validation.md index 309d914..ba0d0f3 100644 --- a/docs/rust-validation.md +++ b/docs/rust-validation.md @@ -2,8 +2,9 @@ ## Scope and baseline -The reference is commit `f8df98b129c9138ccb9e6290d6c801e805fed1be`. The final candidate -contains Rust kernels for Claude decoding, structural JSON classification, bounded +The measurements were taken during the migration included in `96fc2af`, using Swift +commit `f8df98b129c9138ccb9e6290d6c801e805fed1be` as the reference. The candidate +contained Rust kernels for Claude decoding, structural JSON classification, bounded JSONL streaming, token-rate arithmetic and usage aggregation. See [Migration boundaries](rust-migration.md) for their architecture. The migration keeps Swift's file planning, inode/size checks, CryptoKit prefix digests and memoization, @@ -74,10 +75,8 @@ and crossed FFI only for the handler. It measured 18.45/10.06 ms on short lines, but omitted the final filter boundary and therefore does not describe production performance. The final table above supersedes those timings. -Raw seven-run arrays, the standalone build harness and frozen baseline inputs are -retained in `/tmp/quota-rust-scanner-experiment/production` on the validation Mac. -The correctness checks are added to the source tree; the microbenchmark harness is a temporary -experiment and is not part of the product or standard test command. +The standalone scanner microbenchmark was a local experiment. The repository preserves +its correctness corpus in `RustLogFileScannerTests` and the Rust scanner unit tests. ## Scanner ablation in the complete pipeline @@ -98,9 +97,7 @@ cursor contents matched. The complete-pipeline scanner comparison is effectively equal. It supports retaining the Rust reader under the chosen preference for migration at comparable performance, while preserving the short-line microbenchmark caveat above. It -does not attribute the other kernels' gains to the scanner. Raw results are in -`build/rust-validation/scanner-ablation`; `before` means the Rust scanner and -`after` means the restored Swift scanner in that run. +does not attribute the other kernels' gains to the scanner. ## Final complete-pipeline results @@ -123,18 +120,15 @@ Codex and unchanged scans are effectively equal. The three Claude fixtures show lower initial-import elapsed time, but are synthetic workloads rather than a claim about every history or the app's startup time. -`build/rust-validation/final-pipeline-unicode/benchmark-summary.json` retains all -runs and ranges. Its metadata binds every input source file and the fixture hook -to the executable hashes. The equally instrumented release probes are 2,774,256 -bytes before and 3,297,824 bytes after, an increase of 523,568 bytes (about 0.50 MiB). -Intermediate four-kernel and pre-Unicode-fix runs remain separately labeled and -are not the final artifact's results. In particular, the earlier `pipeline-final` -and `final-pipeline` directory names do not designate the corrected final build; -`final-pipeline-unicode` does. Its metadata also names the preserved final binary -used before the ablation copy was rebuilt. +The equally instrumented release probes were 2,774,256 bytes before and +3,297,824 bytes after, an increase of 523,568 bytes (about 0.50 MiB). ## Aggregation ablation and its tradeoff +In the isolated same-module, whole-module-optimized benchmark, the original Swift +aggregator folded 120, 840 and 4,800 rows in 0.175, 1.293 and 7.269 ms respectively. +The Rust aggregator took 0.087, 0.598 and 3.398 ms including input/output conversion. + The corrected final candidate was compared with a temporary copy restoring only `CostAggregator.swift` from the original revision. Every other Rust kernel stayed the same. Five alternating rounds passed the same lifecycle and per-run database @@ -156,11 +150,6 @@ work has a modest cost even though larger isolated aggregation workloads improve This is not evidence that aggregation accelerates every complete scan. No further runs were added after that confirmation. -Raw corrected ablation data is in `build/rust-validation/aggregator-ablation-unicode` -and `aggregator-short-confirmation`; in both, `before` means Rust aggregation and -`after` means the original Swift aggregation. The pre-correction -`aggregator-ablation` results remain intermediate evidence only. - ## Reproducing full pipeline validation ```sh @@ -214,16 +203,12 @@ The output is ignored build data. Neither command reads CLI credentials, scans personal sessions or starts the normal application integrations. The same commands on the final candidate initially produced 27 byte-identical PNGs. The five `*-reset-clock.png` files differed because the sample factory uses the current -minute for its absolute reset labels. The original before and after images remain -under `build/rust-validation/before` and `after`. +minute for its absolute reset labels. The untouched baseline binary and final binary were then rendered consecutively within the same minute, without editing any pixels or source. All 32 resulting PNGs are byte-identical: 26 card variants and six interaction states, including -light/dark, sign-in and refresh failure. They are in `paired-before` and -`paired-after`; `screenshot-comparison-paired.json` records every hash, and -`paired-render-metadata.json` records commands and wall times. UI source and motion -behavior are unchanged, so no animation comparison is claimed or needed. +light/dark, sign-in and refresh failure. The comparison covered static rendering. ## Menu construction and process startup @@ -236,8 +221,7 @@ startup improvement is claimed. The flag does not start provider integrations or scan logs. Both binaries ran with the same runtime sandbox; process-wall time includes its launcher and normal process loading/exit. These are fresh-process, warm-filesystem observations, not -cold-disk application-launch measurements. All 14 stdout/stderr records and timing -arrays are retained under `build/rust-validation/startup`. +cold-disk application-launch measurements. ## Boundaries retained in Swift diff --git a/docs/usage-report.md b/docs/usage-report.md index ba3d2b6..43f0943 100644 --- a/docs/usage-report.md +++ b/docs/usage-report.md @@ -6,7 +6,7 @@ QuotaBar shows all saved usage in one bilingual page inside the app. The page ca Choose **Usage…** in the menu card, or press ⌘U while the card is open or a QuotaBar window is active. With no saved usage, the window shows **No saved usage yet** instead of the page. -While the window is open, QuotaBar keeps it current. Opening it shows what is saved, then scans the local logs of every provider, not only the one in the menu bar. It scans again every minute and rereads the database whenever any scan finishes, whichever path started it. Scans are incremental, so after the first pass each one reads only what the sources appended. A newer snapshot reaches the page through `window.updateReport`, which redraws in place and keeps the chosen period, metric, breakdown, language, and scroll position. A custom end date past the new last day is clamped. Closing the window stops the timer and keeps the page loaded for the next open. +Opening the window reads saved usage and starts a local scan for every provider. While the window is open, it requests scans every minute and rereads the database whenever a scan finishes. Unchanged sources can reuse cached results. Appended logs resume from saved cursors where supported, and rewritten logs can require a full reread. A newer snapshot reaches the page through `window.updateReport`, which redraws in place and keeps the chosen period, metric, breakdown, language, and scroll position. A custom end date past the new last day is clamped. Closing the window stops the timer and keeps the page loaded for the next open. ## What the page shows @@ -93,9 +93,10 @@ The default installation is `/Applications/Xcode.app`. Set `DEVELOPER_DIR` to an The Swift checks cover the calendar windows, the snapshot history and its per-day source and model splits, supported sources, WAL-visible records, missing and zero dates, dated and unpriced costs, numeric bounds, safe JSON insertion, live-update encoding, and resource bundling. JavaScriptCore checks the report's startup language precedence without a browser dependency. -A debug build can open the usage window on 29 sample days, hand it the thirtieth as a live update, check that the page took it, and write what it shows to `/usage-window.png`: +Build the debug app to use its report commands. The window dump starts with 29 sample days, delivers the thirtieth as a live update, checks that the page received it, and saves `/usage-window.png`. ```sh +make build .build/debug/QuotaBar --dump-usage-window build/usage-window ``` @@ -110,20 +111,23 @@ It can also open only the usage window on the saved usage, beside an installed Q .build/debug/QuotaBar --preview-usage-window ``` -The optional browser verifier checks a rendered page in both languages, the 7-day, 30-day, and custom periods and their stored choice, narrow layouts, missing and zero dates, unpriced data, long model names, script syntax, and the absence of remote requests. Render the sample page first: +The optional browser verifier checks both languages, daily chart segments against source costs, 7-day and 30-day periods, custom ranges, saved choices, narrow layouts, missing and zero dates, unpriced data, long model names, script syntax, and offline operation. Install the pinned report tools from the repository root and run the verifier against the rendered sample page. ```sh +fnm install +fnm use +pnpm install --frozen-lockfile .build/debug/QuotaBar --dump-usage-report build -node Scripts/verify_usage_report.mjs --file build/usage-report.html +pnpm run report:verify --file build/usage-report.html ``` -It requires Node.js, a Playwright installation discoverable through `playwright-cli`, and a Chromium executable. The default executable is Brave at `/Applications/Brave Browser.app/Contents/MacOS/Brave Browser`. Set `PLAYWRIGHT_MODULE` to an absolute Playwright-backed CLI entry path or `CHROMIUM_PATH` to another Chromium executable when those defaults do not match the machine. +The report tools use the project's `playwright-core` and launch Brave at `/Applications/Brave Browser.app/Contents/MacOS/Brave Browser`. Set `CHROMIUM_PATH` to use another local Chromium executable. To use an existing Playwright installation, set `PLAYWRIGHT_MODULE` to the absolute entry file of a CLI that depends on `playwright`. Both scripts also accept direct invocation with `node`. To regenerate the public image with synthetic data: ```sh .build/debug/QuotaBar --dump-usage-report build/sample-report -node Scripts/report_image.mjs build/sample-report/usage-report.html docs/images/usage-report.png +pnpm run report:image build/sample-report/usage-report.html docs/images/usage-report.png ``` The sample generator uses the native renderer and never reads the local database. The same image diff --git a/package.json b/package.json new file mode 100644 index 0000000..7d065e5 --- /dev/null +++ b/package.json @@ -0,0 +1,12 @@ +{ + "name": "quotabar-report-tools", + "private": true, + "packageManager": "pnpm@12.21.0", + "scripts": { + "report:image": "node Scripts/report_image.mjs", + "report:verify": "node Scripts/verify_usage_report.mjs" + }, + "devDependencies": { + "playwright-core": "1.65.1" + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..93a59ed --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,191 @@ +--- +lockfileVersion: '9.0' + +importers: + + .: + configDependencies: {} + packageManagerDependencies: + pnpm: + specifier: 12.21.0 + version: 12.21.0 + +packages: + + '@pnpm/exe.android-arm64@12.21.0': + resolution: {integrity: sha512-iaWidxR5B9NUBpwMznCQu1yUpKB6BjTY5BYX2lORj76VsfINdj8Z8XWSzSNrGI8qlxa28Jzdp5fiaspzOaJZlA==} + cpu: [arm64] + os: [android] + + '@pnpm/exe.android-x64@12.21.0': + resolution: {integrity: sha512-35e5v3wlwjIYxDywq+R6/z8CE4gLOEgRxt18yqz1tMRLmx2mnW+CFJI2Q8+srTNjn7gykXUC0x1k195JNikC5A==} + cpu: [x64] + os: [android] + + '@pnpm/exe.darwin-arm64@12.21.0': + resolution: {integrity: sha512-F5OyMX/6zLSowpTZEQRojbCmPS1Pq+fyRaIinslsIe6Glh3qbyQ52u+Fe0eEzSaRuIbWZkXmAAXSWh6Q5Wrlgg==} + cpu: [arm64] + os: [darwin] + + '@pnpm/exe.darwin-x64@12.21.0': + resolution: {integrity: sha512-EzpvcsaE6hrrgYeEiAFYd2rSgFybYyxXhkAY7K3y6Hg3loVfcyJ81hHczpFzi8lW5RXtUlFECRPZ8ZAMRFQYYg==} + cpu: [x64] + os: [darwin] + + '@pnpm/exe.freebsd-x64@12.21.0': + resolution: {integrity: sha512-wNjuEnmdLks4aayPu/QZWQ5tQM9Jn+odUp/vwQM8BXRYoulkTZhtZTHoD60N6mUdLWef1hgUeUh8llNGEUsimw==} + cpu: [x64] + os: [freebsd] + + '@pnpm/exe.linux-arm64-musl@12.21.0': + resolution: {integrity: sha512-Ceit9zn4g5ZqCJtx1fV8eJE7p8aeXMrGZ+Dc01vRqZLIUNgNeI+Ur0ruyqxtsnJx6rGADyXzohumxPLHjaJ5AQ==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@pnpm/exe.linux-arm64@12.21.0': + resolution: {integrity: sha512-4Oj/iF2TDCe2lcH0n4TupPR5sSdrNLclJB6xBElLMPCUOAvBhdf2rRlSaO5M4erJ6g4Fyy7YTXTpcmfFsKyxEA==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-ppc64@12.21.0': + resolution: {integrity: sha512-s2o7rdSDeUTBFsNqxptpZXlTgT6cojmMVUOvTQvFNSv6Easian02ha4tR32fwwD97Au4YzIIjMCwywCF4D82Sw==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-riscv64@12.21.0': + resolution: {integrity: sha512-EYv3GzxeBTITCuM3yGHHbpRFpUvyulkXpQ6LsjKAQNL3iaba1E6h9iDmlouLb3Io4AMMsfdk0/uG6poQ41uewA==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-s390x@12.21.0': + resolution: {integrity: sha512-8VXGNGVNEfs7pL9GTZOzFxjFEnMt4WL3rLOADR5/kPQ7ROTV9GfpVI2DPO/zArXFSkvfc9Zad/WypHLbvzoaTQ==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-x64-musl@12.21.0': + resolution: {integrity: sha512-MnC5vpIXYubhDZCgCwlfJMg7Cg6HupN2IuouT9gD/tUmOfVdQYqeyYccWbthyo/Jeto8de1oQlxeRN1+1Hl2DQ==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@pnpm/exe.linux-x64@12.21.0': + resolution: {integrity: sha512-8eufCjHXspKbNS/kh8q4Q0gqJoOuvC4Q5pgos6XS8By/nAMtP+jf8F1Cw9er840kfAX+PJ/ts+A9qnLE91rvXQ==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.netbsd-x64@12.21.0': + resolution: {integrity: sha512-eyh1M8hQZCkLWxuva7S/fc1SbFbgqg0/5di0dgWmyiuc2Io3dbWVihDun8X+XM8zsR5uhIDvvZpbS9aZQbCovg==} + cpu: [x64] + os: [netbsd] + + '@pnpm/exe.win32-arm64@12.21.0': + resolution: {integrity: sha512-7xTxxUXo/grRLivSeIl6B21gnsz7ooe5EMPcJmQqwxc8WLJVReN8MzrlHru8bqXfVr4X3+6ZGZscntKenlCBqQ==} + cpu: [arm64] + os: [win32] + + '@pnpm/exe.win32-x64@12.21.0': + resolution: {integrity: sha512-9TpkJemVApxJ1Z1w0ZFGN+AuSx4nJOqXSJUqMqDvaXTYwGOzvBiiWdFP9GN0ketiWCQS1Q0/pza2E7I3pP0OBQ==} + cpu: [x64] + os: [win32] + + pnpm@12.21.0: + resolution: {integrity: sha512-Zv2CeO4ok1zpUXktNDZ/869cQyonVkRYIwKVM4NbjaUpu+C+UTCv1W7QcT+4eJ5Hutgtk71a4v5UsVVi1idu8A==} + engines: {node: '>=18'} + hasBin: true + +snapshots: + + '@pnpm/exe.android-arm64@12.21.0': + optional: true + + '@pnpm/exe.android-x64@12.21.0': + optional: true + + '@pnpm/exe.darwin-arm64@12.21.0': + optional: true + + '@pnpm/exe.darwin-x64@12.21.0': + optional: true + + '@pnpm/exe.freebsd-x64@12.21.0': + optional: true + + '@pnpm/exe.linux-arm64-musl@12.21.0': + optional: true + + '@pnpm/exe.linux-arm64@12.21.0': + optional: true + + '@pnpm/exe.linux-ppc64@12.21.0': + optional: true + + '@pnpm/exe.linux-riscv64@12.21.0': + optional: true + + '@pnpm/exe.linux-s390x@12.21.0': + optional: true + + '@pnpm/exe.linux-x64-musl@12.21.0': + optional: true + + '@pnpm/exe.linux-x64@12.21.0': + optional: true + + '@pnpm/exe.netbsd-x64@12.21.0': + optional: true + + '@pnpm/exe.win32-arm64@12.21.0': + optional: true + + '@pnpm/exe.win32-x64@12.21.0': + optional: true + + pnpm@12.21.0: + optionalDependencies: + '@pnpm/exe.android-arm64': 12.21.0 + '@pnpm/exe.android-x64': 12.21.0 + '@pnpm/exe.darwin-arm64': 12.21.0 + '@pnpm/exe.darwin-x64': 12.21.0 + '@pnpm/exe.freebsd-x64': 12.21.0 + '@pnpm/exe.linux-arm64': 12.21.0 + '@pnpm/exe.linux-arm64-musl': 12.21.0 + '@pnpm/exe.linux-ppc64': 12.21.0 + '@pnpm/exe.linux-riscv64': 12.21.0 + '@pnpm/exe.linux-s390x': 12.21.0 + '@pnpm/exe.linux-x64': 12.21.0 + '@pnpm/exe.linux-x64-musl': 12.21.0 + '@pnpm/exe.netbsd-x64': 12.21.0 + '@pnpm/exe.win32-arm64': 12.21.0 + '@pnpm/exe.win32-x64': 12.21.0 + +--- +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + devDependencies: + playwright-core: + specifier: 1.65.1 + version: 1.65.1 + +packages: + + playwright-core@1.65.1: + resolution: {integrity: sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==} + engines: {node: '>=20'} + hasBin: true + +snapshots: + + playwright-core@1.65.1: {}